observable-membrane
A Javascript Membrane implementation using Proxies to observe mutation on an object graph
Last updated 4 months ago by caridy .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install observable-membrane 
SYNC missed versions from official npm registry.

Observable Membrane

Creating robust JavaScript code becomes increasingly important as web applications become more sophisticated. The dynamic nature of JavaScript code at runtime has always presented challenges for developers.

This package implements an observable membrane in JavaScript using Proxies.

A membrane can be created to observe access to a module graph, observe what the other part is attempting to do with certain objects, and even distort the way they see the module graph.

What is a Membrane

Use Cases

One of the prime use-cases for observable membranes is the popular @observed or @tracked decorator used in components to detect mutations on the state of the component to re-render the component when needed. In this case, any object value set into a decorated field can be wrapped into an observable membrane to monitor if the object is accessed during the rendering phase, and if so, the component must be re-rendered when mutations on the object value are detected. And this process is applied not only at the object value level, but at any level in the object graph accessible via the observed object value.

Additionally, it supports distorting objects within an object graph, which could be used for:

  • Avoid leaking certain references.
  • Values observed through the membrane can be different representations of the original values.

Usage

The following example illustrates how to create an observable membrane, and proxies:

import ObservableMembrane from 'observable-membrane';

const membrane = new ObservableMembrane();

const o = {
    x: 2,
    y: {
        z: 1
    },
};

const p = membrane.getProxy(o);

p.x;
// yields 2

p.y.z;
// yields 1

Note: If the value that you're accessing via the membrane is an object that can be observed, then the membrane will return a proxy around it. In the example above, o.y !== p.y because it is a proxy that applies the exact same mechanism. In other words, the membrane is applicable to an entire object graph.

Observing Access and Mutations

The most basic operation in an observable membrane is to observe property member access and mutations. For that, the constructor accepts an optional arguments options that accepts two callbacks, valueObserved and valueMutated:

import ObservableMembrane from 'observable-membrane';

const membrane = new ObservableMembrane({
    valueObserved(target, key) {
        // where target is the object that was accessed
        // and key is the key that was read
        console.log('accessed ', key);
    },
    valueMutated(target, key) {
        // where target is the object that was mutated
        // and key is the key that was mutated
        console.log('mutated ', key);
    },
});

const o = {
    x: 2,
    y: {
        z: 1
    },
};

const p = membrane.getProxy(o);

p.x;
// console output -> 'accessed x'
// yields 2

p.y.z;
// console output -> 'accessed z'
// yields 1

p.y.z = 3;
// console output -> 'mutated z'
// yields 3

Read Only Proxies

Another use-case for observable membranes is to prevent mutations in the object graph. For that, ObservableMembrane provides an additional method that gets a read-only version of any object value. One of the prime use-cases for read-only membranes is to hand over an object to another actor, observe how the actor uses that object reference, but prevent the actor from mutating the object. E.g.: passing an object property down to a child component that can consume the object value but not mutate it.

This is also a very cheap way of doing deep-freeze, although it is not exactly the same, but can cover a lot of ground without having to actually freeze the original object, or a copy of it:

import ObservableMembrane from 'observable-membrane';

const membrane = new ObservableMembrane({
    valueObserved(target, key) {
        // where target is the object that was accessed
        // and key is the key that was read
        console.log('accessed ', key);
    },
});

const o = {
    x: 2,
    y: {
        z: 1
    },
};

const r = membrane.getReadOnlyProxy(o);

r.x;
// yields 2

r.y.z;
// yields 1

r.y.z = 2;
// throws Error in dev-mode, and does nothing in production mode

Distortion

As described above, you can use distortions to avoid leaking non-observable objects and distorting values observed through the membrane:

import ObservableMembrane from 'observable-membrane';

const membrane = new ObservableMembrane({
    valueDistortion(value) {
        if (value instanceof Node) {
            throw new ReferenceError(`Invalid access to a non-observable Node`);
        }
        console.log('distorting ', value);
        if (value === 1) {
            return 10;
        }
        return value;
    },
});

const o = {
    x: 2,
    y: {
        z: 1,
        node: document.createElement('p'),
    },
};

const p = membrane.getProxy(o);

p.x;
// console output -> 'distorting 2'
// yields 2

p.y.z;
// console output -> 'distorting 1'
// yields 10

p.y.node;
// throws ReferenceError

Note: You could use a WeakMap to remap symbols to avoid leaking the original symbols and other non-observable objects through the distortion mechanism.

Unwrapping Proxies

For advanced usages, the observable membrane instance offers the ability to unwrap any proxy generated by the membrane. This can be used to detect membrane presence and other detections that may be useful to framework authors. E.g.:

import ObservableMembrane from 'observable-membrane';

const membrane = new ObservableMembrane();

const o = {
    x: 2,
    y: {
        z: 1,
    },
};

const p = membrane.getProxy(o);

o.y !== p.x;
// yields true because `p` is a proxy of `o`

o.y === membrane.unwrapProxy(p.y);
// yields true because `membrane.unwrapProxy(p.y)` returns the original target `o.y`

Observable Objects

This membrane implementation is tailored for what we call "observable objects", which are objects with basic functionalities that do not require identity to be preserved. Usually any object with the prototype chain set to Object.prototype or null. You can control what gets wrapped by implementing a custom callback for the valueIsObservable option:

import ObservableMembrane from 'observable-membrane';

const membrane = new ObservableMembrane({
    valueIsObservable(value) {
        // intentionally checking for null
        if (value === null) {
            return false;
        }

        // treat all non-object types, including undefined, as non-observable values
        if (typeof value !== 'object') {
            return false;
        }

        if (isArray(value)) {
            return true;
        }

        const proto = Reflect.getPrototypeOf(value);
        return (proto === Object.prototype || proto === null);
    },
});

const o = {
    x: 1
};
membrane.getProxy(o) !== o; // yields true because it was wrapped

membrane.getProxy(document) !== document; // yields false because a DOM object is not observable

Note: be very careful about customizing valueIsObservable. Any object with methods that requires identity (e.g.: objects with private fields, or methods accessing weakmaps with the this value as a key), will simply not work because those methods will be called with the this value being the actual proxy.

Example

There are runnable examples in this Git repository. You must build this package as described in the Contributing Guide before attempting to run the examples. Additionally, some of the examples might be relying on features that are not supported in all browsers (e.g.: reactivo-element example relies on Web Components APIs).

API

new ObservableMembrane([config])

Create a new membrane.

Parameters

  • config [Object] [Optional] The membrane configuration
    • valueObserved [Function] [Optional] Callback invoked when an observed property is accessed. This function receives as argument the original target and the property key.
    • valueMutated [Function] [Optional] Callback invoked when an observed property is mutated. This function receives as argument the original target and the property key.
    • valueDistortion [Function] [Optional] Callback to apply distortion to the objects present in the object graph. This function receives as argument a newly added object in the object graph.
    • valueIsObservable [Function] [Optional] Callback to determine whether or not a value qualifies as a proxy target for the membrane. The default implementation will only observe plain objects (objects with their prototype set to null or Object.prototype).
    • tagPropertyKey [PropertyKey] [Optional] A valid string or symbol that can be used to identify proxies created by the membrane. This is useful for any kind of debugging tools or object identity mechanism.

ObservableMembrane.prototype.getProxy(object)

Wrap an object in the membrane. If the object is observable it will return a proxified version of the object, otherwise it returns the original value.

Parameters

  • object [Object] The object to wrap in the membrane.

ObservableMembrane.prototype.getReadOnlyProxy(object)

Wrap an object in the read-only membrane. If the object is observable it will return a proxified version of the object, otherwise it returns the original value.

Parameters

  • object [Object] The object to wrap in the membrane.

ObservableMembrane.prototype.unwrapProxy(proxy)

Unwrap the proxified version of the object from the membrane and return it's original value.

Parameters

  • proxy [Object] Proxified object to unwrap from the membrane.

Limitations and Other Features

  • Not all objects can be wrapped by this membrane. More information about this in the examples above.
  • Distortion of Symbols and other built-in objects is possible via valueDistortion mechanism to avoid leaking internal.
  • The ability for the membrane creator to revoke all proxies within it to prevent further mutations to the underlying objects (aka, membrane shutdown switch) is not supported at the moment.
  • A value mutation that is set to a read-only proxy value is allowed, but the subtree will still be read-only, e.g.: const p = membrane.getProxy({}); p.abc = membrane.getReadOnlyProxy({}); p.abc.qwe = 1; will throw because the value assigned to abc is still read only.

Browser Compatibility

Observable membranes requires Proxy (ECMAScript 6) to be available.

Development State

This library is production ready, it has been used at Salesforce in production for over a year. It is very lightweight (~1k - minified and gzipped), that can be used with any framework or library. It is designed to be very performant.

Contribution

Please make sure to read the Contributing Guide before making a pull request.

License

MIT

Copyright (C) 2017 salesforce.com, Inc.

Current Tags

  • 0.27.0-alpha1                                ...           canary (5 months ago)
  • 1.0.1                                ...           latest (4 months ago)
  • 0.18.0                                ...           legacy (2 years ago)

14 Versions

  • 1.0.1                                ...           4 months ago
  • 1.0.0                                ...           4 months ago
  • 0.27.0-alpha1                                ...           5 months ago
  • 0.26.1                                ...           2 years ago
  • 0.26.0                                ...           2 years ago
  • 0.18.0                                ...           2 years ago
  • 0.24.14                                ...           2 years ago
  • 0.24.12                                ...           2 years ago
  • 0.19.9                                ...           2 years ago
  • 0.24.0-beta.d48d78f8                                ...           2 years ago
  • 0.24.2                                ...           2 years ago
  • 0.24.1                                ...           2 years ago
  • 0.24.0                                ...           2 years ago
  • 0.25.0                                ...           2 years ago
Downloads
Today 0
This Week 0
This Month 6
Last Day 0
Last Week 3
Last Month 15
Dependencies (0)
None
Dev Dependencies (12)
Dependents (2)

Copyright 2014 - 2016 © taobao.org |