@expressive/mvc 0.86.0 → 0.87.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_virtual/_rolldown/runtime.js +18 -0
- package/dist/component.d.ts +3 -1
- package/dist/component.js +18 -10
- package/dist/component.js.map +1 -1
- package/dist/field/def.js +1 -0
- package/dist/field/def.js.map +1 -1
- package/dist/hot.d.ts +32 -0
- package/dist/hot.js +113 -0
- package/dist/hot.js.map +1 -0
- package/dist/observable.js +3 -1
- package/dist/observable.js.map +1 -1
- package/dist/runtime.d.ts +2 -1
- package/dist/runtime.js +3 -1
- package/dist/runtime.js.map +1 -1
- package/dist/state.d.ts +21 -3
- package/dist/state.js +179 -34
- package/dist/state.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __exportAll = (all, no_symbols) => {
|
|
4
|
+
let target = {};
|
|
5
|
+
for (var name in all) {
|
|
6
|
+
__defProp(target, name, {
|
|
7
|
+
get: all[name],
|
|
8
|
+
enumerable: true
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
if (!no_symbols) {
|
|
12
|
+
__defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
13
|
+
}
|
|
14
|
+
return target;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
//#endregion
|
|
18
|
+
export { __exportAll };
|
package/dist/component.d.ts
CHANGED
|
@@ -87,6 +87,8 @@ declare class Component extends State {
|
|
|
87
87
|
*/
|
|
88
88
|
catch?(error: Error): Promise<void> | void;
|
|
89
89
|
}
|
|
90
|
+
/** Drop composed renders, so each is rebuilt from current prototypes. */
|
|
91
|
+
declare function rechain(): void;
|
|
90
92
|
//#endregion
|
|
91
|
-
export { Component };
|
|
93
|
+
export { Component, rechain };
|
|
92
94
|
//# sourceMappingURL=component.d.ts.map
|
package/dist/component.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { State, unbind } from "./state.js";
|
|
1
|
+
import { State, trailing, unbind } from "./state.js";
|
|
2
2
|
import { Context } from "./context.js";
|
|
3
3
|
import { set } from "./field/set.js";
|
|
4
4
|
|
|
5
5
|
//#region src/component.ts
|
|
6
6
|
const PENDING = /* @__PURE__ */ new WeakMap();
|
|
7
7
|
/** Per-class composed content render. */
|
|
8
|
-
|
|
8
|
+
let CHAIN = /* @__PURE__ */ new WeakMap();
|
|
9
9
|
var Component = class extends State {
|
|
10
10
|
/**
|
|
11
11
|
* Content to display while this component or its children are suspended.
|
|
@@ -20,7 +20,7 @@ var Component = class extends State {
|
|
|
20
20
|
constructor(props, ...rest) {
|
|
21
21
|
if (props == null) props = {};
|
|
22
22
|
const seen = {};
|
|
23
|
-
const
|
|
23
|
+
const twin = PENDING.get(props);
|
|
24
24
|
if (typeof props == "object") merge(props);
|
|
25
25
|
function merge(props) {
|
|
26
26
|
for (const k in props) seen[k] = void 0;
|
|
@@ -29,28 +29,32 @@ var Component = class extends State {
|
|
|
29
29
|
...props
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
|
-
super(
|
|
32
|
+
super([
|
|
33
33
|
props,
|
|
34
34
|
rest.filter((x) => !(x instanceof Context)),
|
|
35
35
|
() => {
|
|
36
|
+
const other = twin || PENDING.get(props);
|
|
37
|
+
if (other !== this) {
|
|
38
|
+
trailing(other).forEach((orphan) => orphan.set(null));
|
|
39
|
+
other.set(null);
|
|
40
|
+
}
|
|
36
41
|
props.is?.(this);
|
|
37
42
|
Object.defineProperty(this, "props", { enumerable: false });
|
|
38
43
|
PENDING.delete(props);
|
|
39
44
|
}
|
|
40
45
|
]);
|
|
41
|
-
if (copy) {
|
|
42
|
-
this.set(null);
|
|
43
|
-
return copy;
|
|
44
|
-
}
|
|
45
46
|
PENDING.set(props, this);
|
|
46
47
|
this.props = props;
|
|
47
48
|
this.set("props", () => {
|
|
48
49
|
this.set(merge(this.props));
|
|
49
50
|
});
|
|
51
|
+
const self = this;
|
|
50
52
|
Object.defineProperty(this, "render", {
|
|
51
53
|
writable: true,
|
|
52
54
|
configurable: true,
|
|
53
|
-
value
|
|
55
|
+
value(props) {
|
|
56
|
+
return render(self).call(this, props);
|
|
57
|
+
}
|
|
54
58
|
});
|
|
55
59
|
}
|
|
56
60
|
/**
|
|
@@ -137,7 +141,11 @@ function compose(outer, inner) {
|
|
|
137
141
|
});
|
|
138
142
|
};
|
|
139
143
|
}
|
|
144
|
+
/** Drop composed renders, so each is rebuilt from current prototypes. */
|
|
145
|
+
function rechain() {
|
|
146
|
+
CHAIN = /* @__PURE__ */ new WeakMap();
|
|
147
|
+
}
|
|
140
148
|
|
|
141
149
|
//#endregion
|
|
142
|
-
export { Component };
|
|
150
|
+
export { Component, rechain };
|
|
143
151
|
//# sourceMappingURL=component.js.map
|
package/dist/component.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component.js","names":[],"sources":["../src/component.ts"],"sourcesContent":["import { Context } from './context';\nimport { set } from './field/set';\nimport { State, unbind } from './state';\n\nimport type { Host } from './runtime';\n\nconst PENDING = new WeakMap<object, Component>();\n\n/** Per-class composed content render. */\nconst CHAIN = new WeakMap<Function, Function>();\n\ntype IfEquals<X, Y, A, B> =\n (<T>() => T extends X ? 1 : 2) extends\n (<T>() => T extends Y ? 1 : 2) ? A : B;\n\n/** Keys of T which are settable (excludes get-only accessors and `readonly`). */\ntype Acceptable<T> = {\n [P in keyof T]-?: IfEquals<\n { [Q in P]: T[P] },\n { -readonly [Q in P]: T[P] },\n P, never\n >;\n}[keyof T];\n\ndeclare namespace Component {\n /**\n * Host element type produced by `Component.render`. Delegates to the\n * {@link Host} manifest on the jsx-runtime entry; falls back to `any`\n * until an adapter augments it with `node`. `any` (not `unknown`) so an\n * un-annotated `render` override in a host-agnostic package still emits a\n * JSX-valid return - `any` is assignable to every host's node type, where\n * `unknown` is assignable to none.\n */\n type Node = Host extends { node: infer T } ? T : any;\n\n interface BaseProps<T extends Component> {\n /**\n * Callback for newly created instance. Only called once.\n *\n * Runs after props apply but **before** the `new()` lifecycle hook - so it\n * may configure state that `new()` then observes. To react to a fully\n * initialized instance instead, use `watch` or an effect.\n */\n is?: (instance: T) => void;\n\n /**\n * Fallback to show when suspended or in error recovery.\n * Pass `false` to opt out of the component's own suspense boundary,\n * letting suspension bubble to an ancestor.\n */\n fallback?: Component.Node;\n }\n\n type StateProps<T extends State> = {\n [K in Exclude<keyof T, keyof Component> & Acceptable<T>]?: T[K];\n };\n\n type RenderProps<T> = [T] extends [(props: infer P) => any]\n ? [keyof NonNullable<P>] extends [never]\n ? { children?: Component.Node }\n : NonNullable<P>\n : { children?: Component.Node };\n\n type Props<T extends Component> =\n & StateProps<T>\n & BaseProps<T>\n & RenderProps<T['render']>;\n}\n\nclass Component extends State {\n /**\n * All JSX attributes passed to this component.\n * Includes state-derived props, render props, and built-in props like `is` and `fallback`.\n *\n * Will incorperate extra props you declare as props parameter in `render` method.\n */\n declare readonly props: Component.Props<this>;\n\n /** Stable identity used when this instance is rendered in a collection. */\n declare readonly key: string;\n\n /**\n * Content to display while this component or its children are suspended.\n * Will cover suspense by pending properties in `this.render` as well.\n * Can be set as a class property or overridden via the `fallback` JSX prop.\n *\n * Defaults to null - nothing will be rendered.\n * Set `false` to opt out of having a boundary at all - suspension then\n * bubbles to the nearest ancestor boundary.\n */\n fallback: Component.Node = set(null);\n\n constructor(props?: any, ...rest: any[]) {\n if (props == null) props = {};\n\n const seen = {} as Record<string, undefined>;\n const copy = PENDING.get(props);\n\n if (typeof props == 'object') merge(props);\n\n function merge(props: {}) {\n for (const k in props) seen[k] = undefined;\n return { ...seen, ...props };\n }\n\n super(copy ? [] : [\n props,\n rest.filter((x) => !(x instanceof Context)),\n () => {\n props.is?.(this);\n Object.defineProperty(this, 'props', { enumerable: false });\n PENDING.delete(props);\n }\n ]);\n\n if (copy) {\n this.set(null);\n return copy;\n }\n\n PENDING.set(props, this);\n\n this.props = props;\n this.set('props', () => {\n this.set(merge(this.props));\n });\n\n Object.defineProperty(this, 'render', {\n writable: true,\n configurable: true,\n value: render(this)\n });\n }\n\n /**\n * Output for this component. Override to define custom JSX.\n *\n * Properties accessed via `this` are reactive and trigger a render when they\n * change, in addition to props. Accepts an optional parameter to receive extra\n * props from JSX, beyond those merged to state properties; declare its shape\n * via `props = {} as { ... }`. Without a parameter (the default below),\n * children pass through.\n *\n * The constructor installs a composed `render` per instance; the bootstrap\n * `type` pass seals this and any override non-configurable, keeping it the\n * content-render seam the chain reads.\n */\n render(props?: {}): Component.Node {\n const { children } = (props || this.props) as { children?: Component.Node };\n return children || null;\n }\n\n /**\n * Called when a child component throws during render.\n * While this is pending, `fallback` is displayed.\n * When resolved, the error boundary resets and `render` is called again.\n *\n * Override to handle errors - set `this.fallback` for error-specific UI,\n * await async recovery, or await user interaction before retrying. If you\n * assign a fallback within catch, it will be reverted after resolved.\n */\n catch?(error: Error): Promise<void> | void;\n}\n\n/**\n * Default `key` accessor. The get/set pair keeps it off observed state.\n */\nObject.defineProperty(Component.prototype, 'key', {\n configurable: true,\n get() {\n return String(this);\n },\n set(value) {\n Object.defineProperty(this, 'key', { value });\n }\n});\n\n/**\n * Seal each class's own `render` non-configurable at bootstrap so member\n * classification leaves it unbound - it stays the content-render seam the chain\n * reads (and which adapters like preact detect as the class-component marker).\n */\nComponent.on({\n before(self) {\n const key = Object.getOwnPropertyDescriptor(self, 'key');\n\n if (key?.configurable)\n Object.defineProperty(self, 'key', {\n enumerable: false,\n writable: false\n });\n },\n type(type) {\n const desc = Object.getOwnPropertyDescriptor(type.prototype, 'render');\n\n if (desc && typeof desc.value == 'function')\n Object.defineProperty(type.prototype, 'render', {\n ...desc,\n configurable: false\n });\n }\n});\n\n/**\n * Build (or fetch the cached) composed content render for an instance's class.\n * Walks the prototype chain for content renders strictly below Component - the\n * default render on Component.prototype is excluded and serves as the fallback\n * when a class authors none.\n */\nfunction render(target: Component) {\n const cached = CHAIN.get(target.constructor);\n\n if (cached) return cached;\n\n let render: Function | undefined;\n let proto = target;\n\n while ((proto = Object.getPrototypeOf(proto)) !== Component.prototype) {\n const desc = Object.getOwnPropertyDescriptor(proto, 'render');\n\n if (desc) {\n const layer = unbind(desc.get || desc.value);\n render = render ? compose(layer, render) : layer;\n }\n }\n\n if (!render)\n render = Component.prototype.render;\n\n CHAIN.set(target.constructor, render);\n\n return render;\n}\n\n/** Wrap an outer render so it receives `inner` as a lazy `children` getter. */\nfunction compose(outer: Function, inner: Function): Function {\n return function (this: Component, props?: {}) {\n const self = this;\n return outer.call(self, {\n ...props,\n get children() {\n return inner.call(self, props);\n }\n });\n };\n}\n\nexport { Component };\n"],"mappings":";;;;;AAMA,MAAM,0BAAU,IAAI,SAA4B;;AAGhD,MAAM,wBAAQ,IAAI,SAA6B;AA4D/C,IAAM,YAAN,cAAwB,MAAM;;;;;;;;;;CAqB5B,WAA2B,IAAI,KAAK;CAEpC,YAAY,OAAa,GAAG,MAAa;AACvC,MAAI,SAAS,KAAM,SAAQ,EAAE;EAE7B,MAAM,OAAO,EAAE;EACf,MAAM,OAAO,QAAQ,IAAI,MAAM;AAE/B,MAAI,OAAO,SAAS,SAAU,OAAM,MAAM;EAE1C,SAAS,MAAM,OAAW;AACxB,QAAK,MAAM,KAAK,MAAO,MAAK,KAAK;AACjC,UAAO;IAAE,GAAG;IAAM,GAAG;IAAO;;AAG9B,QAAM,OAAO,EAAE,GAAG;GAChB;GACA,KAAK,QAAQ,MAAM,EAAE,aAAa,SAAS;SACrC;AACJ,UAAM,KAAK,KAAK;AAChB,WAAO,eAAe,MAAM,SAAS,EAAE,YAAY,OAAO,CAAC;AAC3D,YAAQ,OAAO,MAAM;;GAExB,CAAC;AAEF,MAAI,MAAM;AACR,QAAK,IAAI,KAAK;AACd,UAAO;;AAGT,UAAQ,IAAI,OAAO,KAAK;AAExB,OAAK,QAAQ;AACb,OAAK,IAAI,eAAe;AACtB,QAAK,IAAI,MAAM,KAAK,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OAAO;AACb,SAAO,MAAM,KAAK,MAAM;GACtB,GAAG;GACH,IAAI,WAAW;AACb,WAAO,MAAM,KAAK,MAAM,MAAM;;GAEjC,CAAC"}
|
|
1
|
+
{"version":3,"file":"component.js","names":[],"sources":["../src/component.ts"],"sourcesContent":["import { Context } from './context';\nimport { set } from './field/set';\nimport { State, trailing, unbind } from './state';\n\nimport type { Host } from './runtime';\n\nconst PENDING = new WeakMap<object, Component>();\n\n/** Per-class composed content render. */\nlet CHAIN = new WeakMap<Function, Function>();\n\ntype IfEquals<X, Y, A, B> =\n (<T>() => T extends X ? 1 : 2) extends\n (<T>() => T extends Y ? 1 : 2) ? A : B;\n\n/** Keys of T which are settable (excludes get-only accessors and `readonly`). */\ntype Acceptable<T> = {\n [P in keyof T]-?: IfEquals<\n { [Q in P]: T[P] },\n { -readonly [Q in P]: T[P] },\n P, never\n >;\n}[keyof T];\n\ndeclare namespace Component {\n /**\n * Host element type produced by `Component.render`. Delegates to the\n * {@link Host} manifest on the jsx-runtime entry; falls back to `any`\n * until an adapter augments it with `node`. `any` (not `unknown`) so an\n * un-annotated `render` override in a host-agnostic package still emits a\n * JSX-valid return - `any` is assignable to every host's node type, where\n * `unknown` is assignable to none.\n */\n type Node = Host extends { node: infer T } ? T : any;\n\n interface BaseProps<T extends Component> {\n /**\n * Callback for newly created instance. Only called once.\n *\n * Runs after props apply but **before** the `new()` lifecycle hook - so it\n * may configure state that `new()` then observes. To react to a fully\n * initialized instance instead, use `watch` or an effect.\n */\n is?: (instance: T) => void;\n\n /**\n * Fallback to show when suspended or in error recovery.\n * Pass `false` to opt out of the component's own suspense boundary,\n * letting suspension bubble to an ancestor.\n */\n fallback?: Component.Node;\n }\n\n type StateProps<T extends State> = {\n [K in Exclude<keyof T, keyof Component> & Acceptable<T>]?: T[K];\n };\n\n type RenderProps<T> = [T] extends [(props: infer P) => any]\n ? [keyof NonNullable<P>] extends [never]\n ? { children?: Component.Node }\n : NonNullable<P>\n : { children?: Component.Node };\n\n type Props<T extends Component> =\n & StateProps<T>\n & BaseProps<T>\n & RenderProps<T['render']>;\n}\n\nclass Component extends State {\n /**\n * All JSX attributes passed to this component.\n * Includes state-derived props, render props, and built-in props like `is` and `fallback`.\n *\n * Will incorperate extra props you declare as props parameter in `render` method.\n */\n declare readonly props: Component.Props<this>;\n\n /** Stable identity used when this instance is rendered in a collection. */\n declare readonly key: string;\n\n /**\n * Content to display while this component or its children are suspended.\n * Will cover suspense by pending properties in `this.render` as well.\n * Can be set as a class property or overridden via the `fallback` JSX prop.\n *\n * Defaults to null - nothing will be rendered.\n * Set `false` to opt out of having a boundary at all - suspension then\n * bubbles to the nearest ancestor boundary.\n */\n fallback: Component.Node = set(null);\n\n constructor(props?: any, ...rest: any[]) {\n if (props == null) props = {};\n\n const seen = {} as Record<string, undefined>;\n const twin = PENDING.get(props);\n\n if (typeof props == 'object') merge(props);\n\n function merge(props: {}) {\n for (const k in props) seen[k] = undefined;\n return { ...seen, ...props };\n }\n\n super([\n props,\n rest.filter((x) => !(x instanceof Context)),\n () => {\n const other = twin || PENDING.get(props)!;\n\n if (other !== this) {\n trailing(other).forEach((orphan) => orphan.set(null));\n other.set(null);\n }\n\n props.is?.(this);\n Object.defineProperty(this, 'props', { enumerable: false });\n PENDING.delete(props);\n }\n ]);\n\n PENDING.set(props, this);\n\n this.props = props;\n this.set('props', () => {\n this.set(merge(this.props));\n });\n\n const self = this;\n\n Object.defineProperty(this, 'render', {\n writable: true,\n configurable: true,\n value(this: Component, props?: {}) {\n return render(self).call(this, props);\n }\n });\n }\n\n /**\n * Output for this component. Override to define custom JSX.\n *\n * Properties accessed via `this` are reactive and trigger a render when they\n * change, in addition to props. Accepts an optional parameter to receive extra\n * props from JSX, beyond those merged to state properties; declare its shape\n * via `props = {} as { ... }`. Without a parameter (the default below),\n * children pass through.\n *\n * The constructor installs a composed `render` per instance; the bootstrap\n * `type` pass seals this and any override non-configurable, keeping it the\n * content-render seam the chain reads.\n */\n render(props?: {}): Component.Node {\n const { children } = (props || this.props) as { children?: Component.Node };\n return children || null;\n }\n\n /**\n * Called when a child component throws during render.\n * While this is pending, `fallback` is displayed.\n * When resolved, the error boundary resets and `render` is called again.\n *\n * Override to handle errors - set `this.fallback` for error-specific UI,\n * await async recovery, or await user interaction before retrying. If you\n * assign a fallback within catch, it will be reverted after resolved.\n */\n catch?(error: Error): Promise<void> | void;\n}\n\n/**\n * Default `key` accessor. The get/set pair keeps it off observed state.\n */\nObject.defineProperty(Component.prototype, 'key', {\n configurable: true,\n get() {\n return String(this);\n },\n set(value) {\n Object.defineProperty(this, 'key', { value });\n }\n});\n\n/**\n * Seal each class's own `render` non-configurable at bootstrap so member\n * classification leaves it unbound - it stays the content-render seam the chain\n * reads (and which adapters like preact detect as the class-component marker).\n */\nComponent.on({\n before(self) {\n const key = Object.getOwnPropertyDescriptor(self, 'key');\n\n if (key?.configurable)\n Object.defineProperty(self, 'key', {\n enumerable: false,\n writable: false\n });\n },\n type(type) {\n const desc = Object.getOwnPropertyDescriptor(type.prototype, 'render');\n\n if (desc && typeof desc.value == 'function')\n Object.defineProperty(type.prototype, 'render', {\n ...desc,\n configurable: false\n });\n }\n});\n\n/**\n * Build (or fetch the cached) composed content render for an instance's class.\n * Walks the prototype chain for content renders strictly below Component - the\n * default render on Component.prototype is excluded and serves as the fallback\n * when a class authors none.\n */\nfunction render(target: Component) {\n const cached = CHAIN.get(target.constructor);\n\n if (cached) return cached;\n\n let render: Function | undefined;\n let proto = target;\n\n while ((proto = Object.getPrototypeOf(proto)) !== Component.prototype) {\n const desc = Object.getOwnPropertyDescriptor(proto, 'render');\n\n if (desc) {\n const layer = unbind(desc.get || desc.value);\n render = render ? compose(layer, render) : layer;\n }\n }\n\n if (!render)\n render = Component.prototype.render;\n\n CHAIN.set(target.constructor, render);\n\n return render;\n}\n\n/** Wrap an outer render so it receives `inner` as a lazy `children` getter. */\nfunction compose(outer: Function, inner: Function): Function {\n return function (this: Component, props?: {}) {\n const self = this;\n return outer.call(self, {\n ...props,\n get children() {\n return inner.call(self, props);\n }\n });\n };\n}\n\n/** Drop composed renders, so each is rebuilt from current prototypes. */\nfunction rechain() {\n CHAIN = new WeakMap();\n}\n\nexport { Component, rechain };\n"],"mappings":";;;;;AAMA,MAAM,0BAAU,IAAI,SAA4B;;AAGhD,IAAI,wBAAQ,IAAI,SAA6B;AA4D7C,IAAM,YAAN,cAAwB,MAAM;;;;;;;;;;CAqB5B,WAA2B,IAAI,KAAK;CAEpC,YAAY,OAAa,GAAG,MAAa;AACvC,MAAI,SAAS,KAAM,SAAQ,EAAE;EAE7B,MAAM,OAAO,EAAE;EACf,MAAM,OAAO,QAAQ,IAAI,MAAM;AAE/B,MAAI,OAAO,SAAS,SAAU,OAAM,MAAM;EAE1C,SAAS,MAAM,OAAW;AACxB,QAAK,MAAM,KAAK,MAAO,MAAK,KAAK;AACjC,UAAO;IAAE,GAAG;IAAM,GAAG;IAAO;;AAG9B,QAAM;GACJ;GACA,KAAK,QAAQ,MAAM,EAAE,aAAa,SAAS;SACrC;IACJ,MAAM,QAAQ,QAAQ,QAAQ,IAAI,MAAM;AAExC,QAAI,UAAU,MAAM;AAClB,cAAS,MAAM,CAAC,SAAS,WAAW,OAAO,IAAI,KAAK,CAAC;AACrD,WAAM,IAAI,KAAK;;AAGjB,UAAM,KAAK,KAAK;AAChB,WAAO,eAAe,MAAM,SAAS,EAAE,YAAY,OAAO,CAAC;AAC3D,YAAQ,OAAO,MAAM;;GAExB,CAAC;AAEF,UAAQ,IAAI,OAAO,KAAK;AAExB,OAAK,QAAQ;AACb,OAAK,IAAI,eAAe;AACtB,QAAK,IAAI,MAAM,KAAK,MAAM,CAAC;IAC3B;EAEF,MAAM,OAAO;AAEb,SAAO,eAAe,MAAM,UAAU;GACpC,UAAU;GACV,cAAc;GACd,MAAuB,OAAY;AACjC,WAAO,OAAO,KAAK,CAAC,KAAK,MAAM,MAAM;;GAExC,CAAC;;;;;;;;;;;;;;;CAgBJ,OAAO,OAA4B;EACjC,MA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,SAAS"}
|
package/dist/field/def.js
CHANGED
|
@@ -18,6 +18,7 @@ State.on((self) => {
|
|
|
18
18
|
const entry = APPLY.get(property.value);
|
|
19
19
|
if (entry === null) throw new Error(`${self}.${key} has an instruction applied to another State.`);
|
|
20
20
|
if (!entry) continue;
|
|
21
|
+
if (key[0] == "_") throw new Error(`${self}.${key} is unmanaged - instructions cannot apply to _ keys.`);
|
|
21
22
|
const [instruction, pending] = entry;
|
|
22
23
|
APPLY.set(property.value, null);
|
|
23
24
|
discard(self, pending);
|
package/dist/field/def.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"def.js","names":[],"sources":["../../src/field/def.ts"],"sourcesContent":["import { listener } from '../observable';\nimport { PENDING, State, STORE, uid, apply } from '../state';\n\ndeclare namespace def {\n /**\n * Property initializer, will run upon instance creation.\n * Optional returned callback will run when once upon first access.\n */\n type Factory<T = any, M extends State = any> = (\n this: M,\n key: Extract<State.Field<M>, string>,\n thisArg: M,\n state: State.Values<M>\n ) => def.Config<T> | (() => void) | void;\n\n interface Config<T = any> extends State.Apply<T> {\n destroy?: () => void;\n }\n}\n\nconst APPLY = new Map<symbol, [def.Factory, State[]] | null>();\nconst RESET = () => APPLY.clear();\n\nfunction def<T>(arg1: def.Factory<T>) {\n if (!PENDING.size || (PENDING.size == 1 && PENDING.has(RESET)))\n throw new Error(\n 'Instruction created with no State under construction.'\n );\n\n PENDING.add(RESET);\n\n const token = Symbol('field-' + uid());\n\n APPLY.set(token, [arg1, [...PENDING].filter((x) => x instanceof State) as State[]]);\n\n return token as T extends void ? unknown : T;\n}\n\nState.on((self) => {\n const store = STORE.get(self)!;\n\n for (const key in self) {\n const property: PropertyDescriptor = Object.getOwnPropertyDescriptor(self, key) || {};\n const entry = APPLY.get(property.value);\n\n if (entry === null)\n throw new Error(\n `${self}.${key} has an instruction applied to another State.`\n );\n\n if (!entry) continue;\n\n const [instruction, pending] = entry;\n\n APPLY.set(property.value, null);\n discard(self, pending);\n delete (self as any)[key];\n\n const output = instruction.call(self, key, self, store);\n\n if (!output) continue;\n\n const desc = typeof output == 'function' ? { destroy: output } : output;\n\n if (desc.destroy) listener(self, desc.destroy, null);\n\n apply(self, key, desc, true);\n }\n});\n\n/**\n * Drop pending States constructed after `self` and before the instruction -\n * products of its own initializers, discarded when this token replaced them.\n */\nfunction discard(self: State, pending: State[]) {\n let seen = false;\n\n for (const item of pending)\n if (!seen) seen = item === self;\n else PENDING.delete(item);\n}\n\nexport { def };\n"],"mappings":";;;;AAoBA,MAAM,wBAAQ,IAAI,KAA4C;AAC9D,MAAM,cAAc,MAAM,OAAO;AAEjC,SAAS,IAAO,MAAsB;AACpC,KAAI,CAAC,QAAQ,QAAS,QAAQ,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAC3D,OAAM,IAAI,MACR,wDACD;AAEH,SAAQ,IAAI,MAAM;CAElB,MAAM,QAAQ,OAAO,WAAW,KAAK,CAAC;AAEtC,OAAM,IAAI,OAAO,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC,QAAQ,MAAM,aAAa,MAAM,CAAY,CAAC;AAEnF,QAAO;;AAGT,MAAM,IAAI,SAAS;CACjB,MAAM,QAAQ,MAAM,IAAI,KAAK;AAE7B,MAAK,MAAM,OAAO,MAAM;EACtB,MAAM,WAA+B,OAAO,yBAAyB,MAAM,IAAI,IAAI,EAAE;EACrF,MAAM,QAAQ,MAAM,IAAI,SAAS,MAAM;AAEvC,MAAI,UAAU,KACZ,OAAM,IAAI,MACR,GAAG,KAAK,GAAG,IAAI,+CAChB;AAEH,MAAI,CAAC,MAAO;
|
|
1
|
+
{"version":3,"file":"def.js","names":[],"sources":["../../src/field/def.ts"],"sourcesContent":["import { listener } from '../observable';\nimport { PENDING, State, STORE, uid, apply } from '../state';\n\ndeclare namespace def {\n /**\n * Property initializer, will run upon instance creation.\n * Optional returned callback will run when once upon first access.\n */\n type Factory<T = any, M extends State = any> = (\n this: M,\n key: Extract<State.Field<M>, string>,\n thisArg: M,\n state: State.Values<M>\n ) => def.Config<T> | (() => void) | void;\n\n interface Config<T = any> extends State.Apply<T> {\n destroy?: () => void;\n }\n}\n\nconst APPLY = new Map<symbol, [def.Factory, State[]] | null>();\nconst RESET = () => APPLY.clear();\n\nfunction def<T>(arg1: def.Factory<T>) {\n if (!PENDING.size || (PENDING.size == 1 && PENDING.has(RESET)))\n throw new Error(\n 'Instruction created with no State under construction.'\n );\n\n PENDING.add(RESET);\n\n const token = Symbol('field-' + uid());\n\n APPLY.set(token, [arg1, [...PENDING].filter((x) => x instanceof State) as State[]]);\n\n return token as T extends void ? unknown : T;\n}\n\nState.on((self) => {\n const store = STORE.get(self)!;\n\n for (const key in self) {\n const property: PropertyDescriptor = Object.getOwnPropertyDescriptor(self, key) || {};\n const entry = APPLY.get(property.value);\n\n if (entry === null)\n throw new Error(\n `${self}.${key} has an instruction applied to another State.`\n );\n\n if (!entry) continue;\n\n if (key[0] == '_')\n throw new Error(`${self}.${key} is unmanaged - instructions cannot apply to _ keys.`);\n\n const [instruction, pending] = entry;\n\n APPLY.set(property.value, null);\n discard(self, pending);\n delete (self as any)[key];\n\n const output = instruction.call(self, key, self, store);\n\n if (!output) continue;\n\n const desc = typeof output == 'function' ? { destroy: output } : output;\n\n if (desc.destroy) listener(self, desc.destroy, null);\n\n apply(self, key, desc, true);\n }\n});\n\n/**\n * Drop pending States constructed after `self` and before the instruction -\n * products of its own initializers, discarded when this token replaced them.\n */\nfunction discard(self: State, pending: State[]) {\n let seen = false;\n\n for (const item of pending)\n if (!seen) seen = item === self;\n else PENDING.delete(item);\n}\n\nexport { def };\n"],"mappings":";;;;AAoBA,MAAM,wBAAQ,IAAI,KAA4C;AAC9D,MAAM,cAAc,MAAM,OAAO;AAEjC,SAAS,IAAO,MAAsB;AACpC,KAAI,CAAC,QAAQ,QAAS,QAAQ,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAC3D,OAAM,IAAI,MACR,wDACD;AAEH,SAAQ,IAAI,MAAM;CAElB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Replaced {
|
|
8
|
+
/** Module id the class was accepted under. */
|
|
9
|
+
id: string;
|
|
10
|
+
/** Local declaration name of the class. */
|
|
11
|
+
name: string;
|
|
12
|
+
/** Class live instances belong to. */
|
|
13
|
+
prev: State.Extends;
|
|
14
|
+
/** Class that took its place. */
|
|
15
|
+
next: State.Extends;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Keep a module's State classes stable across runs. A class seen before is
|
|
19
|
+
* patched with its replacement and returned in its place, refreshing live
|
|
20
|
+
* instances; one whose shape or parent changed is returned as-is, and
|
|
21
|
+
* reported to `replaced` listeners before `accept` returns.
|
|
22
|
+
*/
|
|
23
|
+
declare function accept<T extends Record<string, unknown>>(id: string, classes: T): T;
|
|
24
|
+
/**
|
|
25
|
+
* Observe classes `accept` replaced instead of patching. Fires synchronously
|
|
26
|
+
* inside `accept`, while the module re-runs, so a host can retire instances of
|
|
27
|
+
* `prev` before anything resolves the module again.
|
|
28
|
+
*/
|
|
29
|
+
declare function replaced(listener: (event: Replaced) => void): () => void;
|
|
30
|
+
//#endregion
|
|
31
|
+
export { type Replaced, accept, hot_d_exports, replaced };
|
|
32
|
+
//# sourceMappingURL=hot.d.ts.map
|
package/dist/hot.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { __exportAll } from "./_virtual/_rolldown/runtime.js";
|
|
2
|
+
import { State, handlers, patch, track } from "./state.js";
|
|
3
|
+
import { event, observer } from "./observable.js";
|
|
4
|
+
import { rechain } from "./component.js";
|
|
5
|
+
|
|
6
|
+
//#region src/hot.ts
|
|
7
|
+
var hot_exports = /* @__PURE__ */ __exportAll({
|
|
8
|
+
accept: () => accept,
|
|
9
|
+
replaced: () => replaced
|
|
10
|
+
});
|
|
11
|
+
const MODULES = /* @__PURE__ */ new Map();
|
|
12
|
+
const LISTENERS = /* @__PURE__ */ new Set();
|
|
13
|
+
const REFRESH = Symbol.for("@expressive/mvc.refresh");
|
|
14
|
+
const PRIVATE = /(?:^|[\s;{}*])#[\w$]+(?=[\s=;(}])/;
|
|
15
|
+
function isState(value) {
|
|
16
|
+
return typeof value == "function" && value.prototype instanceof State;
|
|
17
|
+
}
|
|
18
|
+
/** What a patch cannot carry: class source less its members, and member kinds. */
|
|
19
|
+
function describe(type) {
|
|
20
|
+
const text = Function.prototype.toString;
|
|
21
|
+
const kinds = {};
|
|
22
|
+
let shape = text.call(type);
|
|
23
|
+
for (const target of [type.prototype, type]) for (const [key, desc] of Object.entries(Object.getOwnPropertyDescriptors(target))) for (const fn of [
|
|
24
|
+
desc.value,
|
|
25
|
+
desc.get,
|
|
26
|
+
desc.set
|
|
27
|
+
]) if (typeof fn == "function" && fn !== type) {
|
|
28
|
+
shape = shape.replace(text.call(fn), "");
|
|
29
|
+
if (target !== type) kinds[key] = desc.set ? "accessor" : desc.get ? "get" : "fn";
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
type,
|
|
33
|
+
shape: shape.replace(/\s+/g, " "),
|
|
34
|
+
kinds,
|
|
35
|
+
own: handlers(type)
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function compatible(prev, next) {
|
|
39
|
+
if (prev.shape !== next.shape || PRIVATE.test(next.shape)) return false;
|
|
40
|
+
if (Object.getPrototypeOf(prev.type) !== Object.getPrototypeOf(next.type)) return false;
|
|
41
|
+
for (const key in next.kinds) if (key in prev.kinds && prev.kinds[key] !== next.kinds[key]) return false;
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Keep a module's State classes stable across runs. A class seen before is
|
|
46
|
+
* patched with its replacement and returned in its place, refreshing live
|
|
47
|
+
* instances; one whose shape or parent changed is returned as-is, and
|
|
48
|
+
* reported to `replaced` listeners before `accept` returns.
|
|
49
|
+
*/
|
|
50
|
+
function accept(id, classes) {
|
|
51
|
+
let known = MODULES.get(id);
|
|
52
|
+
if (!known) MODULES.set(id, known = {});
|
|
53
|
+
const output = { ...classes };
|
|
54
|
+
const refresh = /* @__PURE__ */ new Set();
|
|
55
|
+
const replace = [];
|
|
56
|
+
let patched = false;
|
|
57
|
+
track();
|
|
58
|
+
for (const [name, type] of Object.entries(classes)) {
|
|
59
|
+
if (!isState(type)) continue;
|
|
60
|
+
const prev = known[name];
|
|
61
|
+
if (prev?.type === type) continue;
|
|
62
|
+
const next = describe(type);
|
|
63
|
+
if (!prev || !compatible(prev, next)) {
|
|
64
|
+
if (prev) replace.push({
|
|
65
|
+
id,
|
|
66
|
+
name,
|
|
67
|
+
prev: prev.type,
|
|
68
|
+
next: type
|
|
69
|
+
});
|
|
70
|
+
known[name] = next;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
for (const state of patch(prev.type, type, prev.own)) refresh.add(state);
|
|
75
|
+
patched = true;
|
|
76
|
+
known[name] = {
|
|
77
|
+
...next,
|
|
78
|
+
type: prev.type
|
|
79
|
+
};
|
|
80
|
+
output[name] = prev.type;
|
|
81
|
+
} catch (error) {
|
|
82
|
+
console.error(error);
|
|
83
|
+
replace.push({
|
|
84
|
+
id,
|
|
85
|
+
name,
|
|
86
|
+
prev: prev.type,
|
|
87
|
+
next: type
|
|
88
|
+
});
|
|
89
|
+
known[name] = next;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (patched) rechain();
|
|
93
|
+
for (const state of refresh) if (observer(state)?.ready) event(state, REFRESH);
|
|
94
|
+
for (const event of replace) for (const listener of LISTENERS) try {
|
|
95
|
+
listener(event);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
console.error(error);
|
|
98
|
+
}
|
|
99
|
+
return output;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Observe classes `accept` replaced instead of patching. Fires synchronously
|
|
103
|
+
* inside `accept`, while the module re-runs, so a host can retire instances of
|
|
104
|
+
* `prev` before anything resolves the module again.
|
|
105
|
+
*/
|
|
106
|
+
function replaced(listener) {
|
|
107
|
+
LISTENERS.add(listener);
|
|
108
|
+
return () => void LISTENERS.delete(listener);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
//#endregion
|
|
112
|
+
export { accept, hot_exports, replaced };
|
|
113
|
+
//# sourceMappingURL=hot.js.map
|
package/dist/hot.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hot.js","names":[],"sources":["../src/hot.ts"],"sourcesContent":["import { rechain } from './component';\nimport { event, observer } from './observable';\nimport { State, handlers, patch, track } from './state';\n\ninterface Entry {\n type: Function;\n shape: string;\n kinds: Record<string, 'get' | 'accessor' | 'fn'>;\n own: ReturnType<typeof handlers>;\n}\n\ninterface Replaced {\n /** Module id the class was accepted under. */\n id: string;\n /** Local declaration name of the class. */\n name: string;\n /** Class live instances belong to. */\n prev: State.Extends;\n /** Class that took its place. */\n next: State.Extends;\n}\n\nconst MODULES = new Map<string, Record<string, Entry>>();\nconst LISTENERS = new Set<(event: Replaced) => void>();\nconst REFRESH = Symbol.for('@expressive/mvc.refresh');\nconst PRIVATE = /(?:^|[\\s;{}*])#[\\w$]+(?=[\\s=;(}])/;\n\nfunction isState(value: unknown): value is State.Extends {\n return typeof value == 'function' && value.prototype instanceof State;\n}\n\n/** What a patch cannot carry: class source less its members, and member kinds. */\nfunction describe(type: Function): Entry {\n const text = Function.prototype.toString;\n const kinds: Entry['kinds'] = {};\n let shape = text.call(type);\n\n for (const target of [type.prototype, type])\n for (const [key, desc] of Object.entries(Object.getOwnPropertyDescriptors(target)))\n for (const fn of [desc.value, desc.get, desc.set])\n if (typeof fn == 'function' && fn !== type) {\n shape = shape.replace(text.call(fn), '');\n if (target !== type) kinds[key] = desc.set ? 'accessor' : desc.get ? 'get' : 'fn';\n }\n\n return { type, shape: shape.replace(/\\s+/g, ' '), kinds, own: handlers(type as State.Extends) };\n}\n\nfunction compatible(prev: Entry, next: Entry) {\n if (prev.shape !== next.shape || PRIVATE.test(next.shape)) return false;\n if (Object.getPrototypeOf(prev.type) !== Object.getPrototypeOf(next.type)) return false;\n\n for (const key in next.kinds)\n if (key in prev.kinds && prev.kinds[key] !== next.kinds[key]) return false;\n\n return true;\n}\n\n/**\n * Keep a module's State classes stable across runs. A class seen before is\n * patched with its replacement and returned in its place, refreshing live\n * instances; one whose shape or parent changed is returned as-is, and\n * reported to `replaced` listeners before `accept` returns.\n */\nfunction accept<T extends Record<string, unknown>>(id: string, classes: T): T {\n let known = MODULES.get(id);\n\n if (!known) MODULES.set(id, (known = {}));\n\n const output: Record<string, unknown> = { ...classes };\n const refresh = new Set<State>();\n const replace: Replaced[] = [];\n let patched = false;\n\n track();\n\n for (const [name, type] of Object.entries(classes)) {\n if (!isState(type)) continue;\n\n const prev = known[name];\n\n if (prev?.type === type) continue;\n\n const next = describe(type);\n\n if (!prev || !compatible(prev, next)) {\n if (prev) replace.push({ id, name, prev: prev.type as State.Extends, next: type });\n known[name] = next;\n continue;\n }\n\n try {\n for (const state of patch(prev.type as State.Extends, type, prev.own)) refresh.add(state);\n patched = true;\n known[name] = { ...next, type: prev.type };\n output[name] = prev.type;\n } catch (error) {\n console.error(error);\n replace.push({ id, name, prev: prev.type as State.Extends, next: type });\n known[name] = next;\n }\n }\n\n if (patched) rechain();\n\n for (const state of refresh) if (observer(state)?.ready) event(state, REFRESH);\n\n for (const event of replace)\n for (const listener of LISTENERS)\n try {\n listener(event);\n } catch (error) {\n console.error(error);\n }\n\n return output as T;\n}\n\n/**\n * Observe classes `accept` replaced instead of patching. Fires synchronously\n * inside `accept`, while the module re-runs, so a host can retire instances of\n * `prev` before anything resolves the module again.\n */\nfunction replaced(listener: (event: Replaced) => void): () => void {\n LISTENERS.add(listener);\n return () => void LISTENERS.delete(listener);\n}\n\nexport { accept, replaced };\nexport type { Replaced };\n"],"mappings":";;;;;;;;;;AAsBA,MAAM,0BAAU,IAAI,KAAoC;AACxD,MAAM,4BAAY,IAAI,KAAgC;AACtD,MAAM,UAAU,OAAO,IAAI,0BAA0B;AACrD,MAAM,UAAU;AAEhB,SAAS,QAAQ,OAAwC;AACvD,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,QAAQ,QAAQ,EAAE;AAClD,MAAI,CAAC,QAAQ,KAAK,CAAE;EAEpB,MAAM,OAAO,MAAM;AAEnB,MAAI,MAAM,SAAS,KAAM;EAEzB,MAAM,OAAO,SAAS,KAAK;AAE3B,MAAI,CAAC,QAAQ,CAAC,WAAW,MAAM,KAAK,EAAE;AACpC,OAAI,KAAM,SAAQ,KAAK;IAAE;IAAI;IAAM,MAAM,KAAK;IAAuB,MAAM;IAAM,CAAC;AAClF,SAAM,QAAQ;AACd;;AAGF,MAAI;AACF,QAAK,MAAM,SAAS,MAAM,KAAK,MAAuB,MAAM,KAAK,IAAI,CAAE,SAAQ,IAAI,MAAM;AACzF,aAAU;AACV,SAAM,QAAQ;IAAE,GAAG;IAAM,MAAM,KAAK;IAAM;AAC1C,UAAO,QAAQ,KAAK;WACb,OAAO;AACd,WAAQ,MAAM,MAAM;AACpB,WAAQ,KAAK;IAAE;IAAI;IAAM,MAAM,KAAK;IAAuB,MAAM;IAAM,CAAC;AACxE,SAAM,QAAQ;;;AAIlB,KAAI,QAAS,UAAS;AAEtB,MAAK,MAAM,SAAS,QAAS,KAAI,SAAS,MAAM,EAAE,MAAO,OAAM,OAAO,QAAQ;AAE9E,MAAK,MAAM,SAAS,QAClB,MAAK,MAAM,YAAY,UACrB,KAAI;AACF,WAAS,MAAM;UACR,OAAO;AACd,UAAQ,MAAM,MAAM;;AAG1B,QAAO;;;;;;;AAQT,SAAS,SAAS,UAAiD;AACjE,WAAU,IAAI,SAAS;AACvB,cAAa,KAAK,UAAU,OAAO,SAAS"}
|
package/dist/observable.js
CHANGED
|
@@ -3,6 +3,8 @@ import { enqueue, hold } from "./dispatch.js";
|
|
|
3
3
|
//#region src/observable.ts
|
|
4
4
|
const Observer = Symbol("Observer");
|
|
5
5
|
const Observing = Symbol("Observing");
|
|
6
|
+
/** Event every observer treats as watched, to force a refresh. */
|
|
7
|
+
const REFRESH = Symbol.for("@expressive/mvc.refresh");
|
|
6
8
|
function observer(state, create) {
|
|
7
9
|
const o = state[Observer];
|
|
8
10
|
if (!o && create) {
|
|
@@ -29,7 +31,7 @@ function observe(object, callback, required, cleanup = []) {
|
|
|
29
31
|
release: cleanup
|
|
30
32
|
};
|
|
31
33
|
const release = listener(object, (key) => {
|
|
32
|
-
if (watching.has(key)) return observing.callback();
|
|
34
|
+
if (watching.has(key) || key === REFRESH) return observing.callback();
|
|
33
35
|
});
|
|
34
36
|
cleanup.push(release);
|
|
35
37
|
if (EffectContext) EffectContext.add((update) => {
|
package/dist/observable.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"observable.js","names":[],"sources":["../src/observable.ts"],"sourcesContent":["import { enqueue, hold } from './dispatch';\n\ndeclare namespace Observer {\n /**\n * Update callback function.\n *\n * @param key -\n * - `string` - property which has updated.\n * - `false` - a normal update has completed.\n * - `true` - initial event; instance is ready.\n * - `null` - terminal event; instance is expired.\n */\n type Notify = (key: Signal) => (() => void) | null | void;\n\n type EffectCleanup = (update: boolean | null) => void;\n\n type Effect<T extends object> = (\n this: T,\n proxy: T,\n changed: readonly Event[]\n ) => EffectCleanup | Promise<void> | null | void;\n\n type Event = number | string | symbol;\n\n type Signal = Event | true | false | null;\n\n type Callback = () => void | null;\n}\n\ninterface Observer {\n /** Becomes `true` once the subject has emitted its initial event. */\n ready?: true;\n listeners: Map<Observer.Notify, Set<Observer.Signal> | undefined>;\n /** Recursion guard for an in-progress emit pass. */\n pending: Set<Observer.Signal>;\n /** Accumulator drained by the next microtask. */\n events: Set<Observer.Event>;\n}\n\ninterface Observing {\n callback: Observer.Callback;\n watching: Set<Observer.Signal>;\n required?: boolean;\n release: (() => void)[];\n}\n\nconst Observer: unique symbol = Symbol('Observer');\nconst Observing: unique symbol = Symbol('Observing');\n\ninterface Observable { [Observer]?: Observer | null }\ninterface Observed { [Observing]?: Observing }\n\n/**\n * Fetch the dispatch bundle attached to an object.\n * - returns the bundle if active\n * - returns `null` if the subject has been terminated\n * - returns `undefined` if the subject was never observable\n *\n * With `create: true`, attaches a fresh bundle iff the slot is undefined.\n * A terminated (null) slot is not resurrected.\n */\nfunction observer(state: object, create: true): Observer;\nfunction observer(state: object, create?: boolean): Observer | undefined | null;\nfunction observer(state: object, create?: boolean) {\n const o = (state as Observable)[Observer];\n\n if (!o && create) {\n if (o === null)\n throw new Error(\n `${state} was destroyed - cannot be rendered, watched or updated.`\n );\n\n const value: Observer = {\n listeners: new Map(),\n pending: new Set(),\n events: new Set()\n };\n Object.defineProperty(state, Observer, { value, writable: true });\n return value;\n }\n\n return o;\n}\n\nfunction observe<T extends object>(\n object: T,\n callback: Observer.Callback,\n required?: boolean,\n cleanup: (() => void)[] = []\n): T {\n const watching = new Set<Observer.Signal>();\n const observing: Observing = { callback, watching, required, release: cleanup };\n\n const release = listener(object, (key) => {\n if (watching.has(key)) return observing.callback();\n });\n\n cleanup.push(release);\n\n if (EffectContext)\n EffectContext.add((update) => {\n if (update !== true) release();\n });\n\n const proxy = Object.create(object) as T;\n\n if ('is' in object)\n Object.defineProperty(proxy, 'is', {\n value: (object as { is?: unknown }).is,\n writable: true\n });\n\n return Object.defineProperty(proxy, Observing, { value: observing });\n}\n\nfunction touch(from: object, key: any): void;\nfunction touch<T>(from: object, key: any, value?: T): T;\nfunction touch(from: object, key: any, value?: any) {\n const active = (from as Observed)[Observing];\n\n if (active) {\n if (value === undefined && arguments.length === 3 && active.required)\n throw new Error(\n `${Object.getPrototypeOf(from)}.${String(key)} is required in this context.`\n );\n\n active.watching.add(key);\n\n if (value instanceof Object && observer(value))\n return observe(\n value,\n () => active.callback(),\n active.required,\n active.release\n );\n }\n\n return value;\n}\n\nfunction unobserve(observing: Observing) {\n for (const release of observing.release) release();\n}\n\nfunction listener<T extends object>(\n subject: T,\n callback: Observer.Notify,\n select?: Observer.Signal | Set<Observer.Signal>\n) {\n const o = observer(subject, true);\n\n if (select !== undefined && !(select instanceof Set))\n select = new Set([select]);\n\n if (o.ready && !select) callback(true);\n\n o.listeners.set(callback, select);\n\n return () => o.listeners.delete(callback);\n}\n\nconst EMPTY = Object.assign([], {\n then: Promise.prototype.then.bind(Promise.resolve([]))\n} as PromiseLike<never[]>);\n\nfunction queued<K extends Observer.Event>(\n state: object\n): K[] & PromiseLike<K[]> {\n const o = observer(state);\n if (!o?.events.size) return EMPTY;\n\n const current = o.events as Set<K>;\n const promise = new Promise<K[]>((res) => {\n const callback: Observer.Notify = () => {\n o.listeners.delete(callback);\n return () => res([...current]);\n };\n o.listeners.set(callback, undefined);\n });\n\n return Object.assign([...current], {\n then: promise.then.bind(promise)\n });\n}\n\nfunction event(state: object, key?: Observer.Event | null, silent?: boolean) {\n const o = observer(state, key === undefined);\n\n if (!o) return;\n\n if (key === null) {\n if (!Object.getOwnPropertyDescriptor(state, Observer)) return;\n\n (state as Observable)[Observer] = null;\n return emit(o, key, state);\n }\n\n if (key === undefined) return emit(o, true, state);\n\n if (!o.events.size && !silent)\n enqueue(() => {\n emit(o, false, state);\n o.events = new Set();\n }, undefined, state);\n\n o.events.add(key);\n\n if (!silent) emit(o, key, state);\n}\n\nfunction emit(o: Observer, key: Observer.Signal, subject: object): void {\n const { listeners, pending, ready } = o;\n\n if (key === ready) return;\n\n if (pending.size) {\n pending.add(key);\n return;\n }\n\n if (!ready && key !== null) pending.add(true);\n\n pending.add(key);\n\n for (const k of pending)\n for (const [callback, filter] of listeners)\n if (!filter || filter.has(k)) {\n const after = callback(k);\n if (after === null) listeners.delete(callback);\n else if (typeof after == 'function') enqueue(after, undefined, subject);\n }\n\n if (key === null) listeners.clear();\n else if (key === true) o.ready = true;\n\n pending.clear();\n}\n\n/**\n * Create a side-effect which will update whenever values accessed change.\n * Callback is called immediately and whenever values are stale.\n *\n * @param target - Instance of State to observe.\n * @param callback - Function to invoke when values change.\n * @param requireValues - If `true` will throw if accessing a value which is `undefined`.\n */\nfunction watch<T extends object>(\n target: T,\n callback: Observer.Effect<Required<T>>,\n requireValues: true,\n transition?: (work: () => void) => void\n): () => void;\n\nfunction watch<T extends object>(\n target: T,\n callback: Observer.Effect<T>,\n recursive?: boolean,\n transition?: (work: () => void) => void\n): () => void;\n\nfunction watch<T extends object>(\n target: T,\n callback: Observer.Effect<T>,\n argument?: boolean,\n transition?: (work: () => void) => void\n) {\n const o = observer(target, true);\n let events: readonly Observer.Event[] = [];\n let unset: ((update: boolean | null) => void) | undefined;\n let reset: (() => void) | null | undefined;\n let previous: Observing | undefined;\n let latest: Observing | undefined;\n let queued = false;\n let suspense: ReturnType<typeof hold>;\n\n function resume() {\n suspense?.();\n suspense = undefined;\n }\n\n function invoke() {\n if (reset === null || observer(target) === null) return;\n\n queued = false;\n let ignore: boolean = true;\n\n function onUpdate() {\n events = [...o.events];\n\n if (reset === null) return null;\n if (ignore) {\n if (queued) enqueue(invoke, transition, target);\n return;\n }\n\n ignore = true;\n queued = true;\n\n unset!(true);\n unset = undefined;\n\n enqueue(invoke, transition, target);\n }\n\n function run(release?: (update?: boolean | null) => void) {\n if (previous !== latest) unobserve(latest!);\n\n const proxy = observe(target, onUpdate, argument === true);\n const current = latest = (proxy as Observed)[Observing]!;\n const output = callback.call(proxy, proxy, events);\n\n if (observer(target) === null) {\n if (typeof output == 'function') output(null);\n if (release) release(null);\n return;\n }\n\n if (previous && argument === false && !current.watching.size)\n previous.callback = onUpdate;\n else {\n if (previous) unobserve(previous);\n previous = current;\n }\n\n ignore = false;\n reset = output === null ? null : invoke;\n unset = (key) => {\n if (typeof output == 'function') output(key);\n if (release) release(key);\n };\n\n events = [];\n }\n\n try {\n if (argument !== false) capture(run);\n else run();\n } catch (err) {\n if (err instanceof Promise) {\n reset = undefined;\n const suspended = suspense = hold(true, transition)!;\n const replay = () => {\n if (suspense !== suspended) return;\n suspense = undefined;\n suspended(invoke);\n };\n err.then(replay, replay);\n } else {\n throw err;\n }\n }\n }\n\n const unlisten = listener(target, (key) => {\n if (key === true) invoke();\n else if (key === null) {\n if (unset) unset(null);\n resume();\n reset = null;\n } else if (!reset) {\n suspense?.(false);\n return reset;\n }\n });\n\n function cleanup() {\n if (unset) unset(false);\n\n resume();\n reset = null;\n unlisten();\n }\n\n if (EffectContext && argument !== false) EffectContext.add(cleanup);\n\n return cleanup;\n}\n\nlet EffectContext: Set<(update?: boolean | null) => void> | undefined;\n\nfunction capture(scope: (release: (update?: boolean | null) => void) => void) {\n const parent = EffectContext;\n const context = (EffectContext = new Set());\n\n try {\n scope((update) => context.forEach((fn) => fn(update)));\n } finally {\n EffectContext = parent;\n }\n}\n\nexport {\n listener,\n event,\n Observer,\n touch,\n queued,\n observer,\n watch,\n capture\n};\n"],"mappings":";;;AA8CA,MAAM,WAA0B,OAAO,WAAW;AAClD,MAAM,YAA2B,OAAO,YAAY;AAgBpD,SAAS,SAAS,OAAe,QAAkB;CACjD,MAAM,IAAK,MAAqB;AAEhC,KAAI,CAAC,KAAK,QAAQ;AAChB,MAAI,MAAM,KACR,OAAM,IAAI,MACR,GAAG,MAAM,0DACV;EAEH,MAAM,QAAkB;GACtB,2BAAW,IAAI,KAAK;GACpB,yBAAS,IAAI,KAAK;GAClB,wBAAQ,IAAI,KAAK;GAClB;AACD,SAAO,eAAe,OAAO,UAAU;GAAE;GAAO,UAAU;GAAM,CAAC;AACjE,SAAO;;AAGT,QAAO;;AAGT,SAAS,QACP,QACA,UACA,UACA,UAA0B,EAAE,EACzB;CACH,MAAM,2BAAW,IAAI,KAAsB;CAC3C,MAAM,YAAuB;EAAE;EAAU;EAAU;EAAU,SAAS;EAAS;CAE/E,MAAM,UAAU,SAAS,SAAS,QAAQ;AACxC,MAAI,SAAS,IAAI,IAAI,CAAE,QAAO,UAAU,UAAU;GAClD;AAEF,SAAQ,KAAK,QAAQ;AAErB,KAAI,cACF,eAAc,KAAK,WAAW;AAC5B,MAAI,WAAW,KAAM,UAAS;GAC9B;CAEJ,MAAM,QAAQ,OAAO,OAAO,OAAO;AAEnC,KAAI,QAAQ,OACV,QAAO,eAAe,OAAO,MAAM;EACjC,OAAQ,OAA4B;EACpC,UAAU;EACX,CAA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AAM,WAAW;IACnD,MAAM,eAAe;AACnB,SAAI,aAAa,UAAW;AAC5B,gBAAW;AACX,eAAU,OAAO;;AAEnB,QAAI,KAAK,QAAQ,OAAO;SAExB,OAAM;;;CAKZ,MAAM,WAAW,SAAS,SAAS,QAAQ;AACzC,MAAI,QAAQ,KAAM,SAAQ;WACjB,QAAQ,MAAM;AACrB,OAAI,MAAO,OAAM,KAAK;AACtB,WAAQ;AACR,WAAQ;aACC,CAAC,OAAO;AACjB,cAAW,MAAM;AACjB,UAAO;;GAET;CAEF,SAAS,UAAU;AACjB,MAAI,MAAO,OAAM,MAAM;AAEvB,UAAQ;AACR,UAAQ;AACR,YAAU;;AAGZ,KAAI,iBAAiB,aAAa,MAAO,eAAc,IAAI,QAAQ;AAEnE,QAAO;;AAGT,IAAI;AAEJ,SAAS,QAAQ,OAA6D;CAC5E,MAAM,SAAS;CACf,MAAM,UAAW,gCAAgB,IAAI,KAAK;AAE1C,KAAI;AACF,SAAO,WAAW,QAAQ,SAAS,OAAO,GAAG,OAAO,CAAC,CAAC;WAC9C;AACR,kBAAgB"}
|
|
1
|
+
{"version":3,"file":"observable.js","names":[],"sources":["../src/observable.ts"],"sourcesContent":["import { enqueue, hold } from './dispatch';\n\ndeclare namespace Observer {\n /**\n * Update callback function.\n *\n * @param key -\n * - `string` - property which has updated.\n * - `false` - a normal update has completed.\n * - `true` - initial event; instance is ready.\n * - `null` - terminal event; instance is expired.\n */\n type Notify = (key: Signal) => (() => void) | null | void;\n\n type EffectCleanup = (update: boolean | null) => void;\n\n type Effect<T extends object> = (\n this: T,\n proxy: T,\n changed: readonly Event[]\n ) => EffectCleanup | Promise<void> | null | void;\n\n type Event = number | string | symbol;\n\n type Signal = Event | true | false | null;\n\n type Callback = () => void | null;\n}\n\ninterface Observer {\n /** Becomes `true` once the subject has emitted its initial event. */\n ready?: true;\n listeners: Map<Observer.Notify, Set<Observer.Signal> | undefined>;\n /** Recursion guard for an in-progress emit pass. */\n pending: Set<Observer.Signal>;\n /** Accumulator drained by the next microtask. */\n events: Set<Observer.Event>;\n}\n\ninterface Observing {\n callback: Observer.Callback;\n watching: Set<Observer.Signal>;\n required?: boolean;\n release: (() => void)[];\n}\n\nconst Observer: unique symbol = Symbol('Observer');\nconst Observing: unique symbol = Symbol('Observing');\n\n/** Event every observer treats as watched, to force a refresh. */\nconst REFRESH = Symbol.for('@expressive/mvc.refresh');\n\ninterface Observable { [Observer]?: Observer | null }\ninterface Observed { [Observing]?: Observing }\n\n/**\n * Fetch the dispatch bundle attached to an object.\n * - returns the bundle if active\n * - returns `null` if the subject has been terminated\n * - returns `undefined` if the subject was never observable\n *\n * With `create: true`, attaches a fresh bundle iff the slot is undefined.\n * A terminated (null) slot is not resurrected.\n */\nfunction observer(state: object, create: true): Observer;\nfunction observer(state: object, create?: boolean): Observer | undefined | null;\nfunction observer(state: object, create?: boolean) {\n const o = (state as Observable)[Observer];\n\n if (!o && create) {\n if (o === null)\n throw new Error(\n `${state} was destroyed - cannot be rendered, watched or updated.`\n );\n\n const value: Observer = {\n listeners: new Map(),\n pending: new Set(),\n events: new Set()\n };\n Object.defineProperty(state, Observer, { value, writable: true });\n return value;\n }\n\n return o;\n}\n\nfunction observe<T extends object>(\n object: T,\n callback: Observer.Callback,\n required?: boolean,\n cleanup: (() => void)[] = []\n): T {\n const watching = new Set<Observer.Signal>();\n const observing: Observing = { callback, watching, required, release: cleanup };\n\n const release = listener(object, (key) => {\n if (watching.has(key) || key === REFRESH) return observing.callback();\n });\n\n cleanup.push(release);\n\n if (EffectContext)\n EffectContext.add((update) => {\n if (update !== true) release();\n });\n\n const proxy = Object.create(object) as T;\n\n if ('is' in object)\n Object.defineProperty(proxy, 'is', {\n value: (object as { is?: unknown }).is,\n writable: true\n });\n\n return Object.defineProperty(proxy, Observing, { value: observing });\n}\n\nfunction touch(from: object, key: any): void;\nfunction touch<T>(from: object, key: any, value?: T): T;\nfunction touch(from: object, key: any, value?: any) {\n const active = (from as Observed)[Observing];\n\n if (active) {\n if (value === undefined && arguments.length === 3 && active.required)\n throw new Error(\n `${Object.getPrototypeOf(from)}.${String(key)} is required in this context.`\n );\n\n active.watching.add(key);\n\n if (value instanceof Object && observer(value))\n return observe(\n value,\n () => active.callback(),\n active.required,\n active.release\n );\n }\n\n return value;\n}\n\nfunction unobserve(observing: Observing) {\n for (const release of observing.release) release();\n}\n\nfunction listener<T extends object>(\n subject: T,\n callback: Observer.Notify,\n select?: Observer.Signal | Set<Observer.Signal>\n) {\n const o = observer(subject, true);\n\n if (select !== undefined && !(select instanceof Set))\n select = new Set([select]);\n\n if (o.ready && !select) callback(true);\n\n o.listeners.set(callback, select);\n\n return () => o.listeners.delete(callback);\n}\n\nconst EMPTY = Object.assign([], {\n then: Promise.prototype.then.bind(Promise.resolve([]))\n} as PromiseLike<never[]>);\n\nfunction queued<K extends Observer.Event>(\n state: object\n): K[] & PromiseLike<K[]> {\n const o = observer(state);\n if (!o?.events.size) return EMPTY;\n\n const current = o.events as Set<K>;\n const promise = new Promise<K[]>((res) => {\n const callback: Observer.Notify = () => {\n o.listeners.delete(callback);\n return () => res([...current]);\n };\n o.listeners.set(callback, undefined);\n });\n\n return Object.assign([...current], {\n then: promise.then.bind(promise)\n });\n}\n\nfunction event(state: object, key?: Observer.Event | null, silent?: boolean) {\n const o = observer(state, key === undefined);\n\n if (!o) return;\n\n if (key === null) {\n if (!Object.getOwnPropertyDescriptor(state, Observer)) return;\n\n (state as Observable)[Observer] = null;\n return emit(o, key, state);\n }\n\n if (key === undefined) return emit(o, true, state);\n\n if (!o.events.size && !silent)\n enqueue(() => {\n emit(o, false, state);\n o.events = new Set();\n }, undefined, state);\n\n o.events.add(key);\n\n if (!silent) emit(o, key, state);\n}\n\nfunction emit(o: Observer, key: Observer.Signal, subject: object): void {\n const { listeners, pending, ready } = o;\n\n if (key === ready) return;\n\n if (pending.size) {\n pending.add(key);\n return;\n }\n\n if (!ready && key !== null) pending.add(true);\n\n pending.add(key);\n\n for (const k of pending)\n for (const [callback, filter] of listeners)\n if (!filter || filter.has(k)) {\n const after = callback(k);\n if (after === null) listeners.delete(callback);\n else if (typeof after == 'function') enqueue(after, undefined, subject);\n }\n\n if (key === null) listeners.clear();\n else if (key === true) o.ready = true;\n\n pending.clear();\n}\n\n/**\n * Create a side-effect which will update whenever values accessed change.\n * Callback is called immediately and whenever values are stale.\n *\n * @param target - Instance of State to observe.\n * @param callback - Function to invoke when values change.\n * @param requireValues - If `true` will throw if accessing a value which is `undefined`.\n */\nfunction watch<T extends object>(\n target: T,\n callback: Observer.Effect<Required<T>>,\n requireValues: true,\n transition?: (work: () => void) => void\n): () => void;\n\nfunction watch<T extends object>(\n target: T,\n callback: Observer.Effect<T>,\n recursive?: boolean,\n transition?: (work: () => void) => void\n): () => void;\n\nfunction watch<T extends object>(\n target: T,\n callback: Observer.Effect<T>,\n argument?: boolean,\n transition?: (work: () => void) => void\n) {\n const o = observer(target, true);\n let events: readonly Observer.Event[] = [];\n let unset: ((update: boolean | null) => void) | undefined;\n let reset: (() => void) | null | undefined;\n let previous: Observing | undefined;\n let latest: Observing | undefined;\n let queued = false;\n let suspense: ReturnType<typeof hold>;\n\n function resume() {\n suspense?.();\n suspense = undefined;\n }\n\n function invoke() {\n if (reset === null || observer(target) === null) return;\n\n queued = false;\n let ignore: boolean = true;\n\n function onUpdate() {\n events = [...o.events];\n\n if (reset === null) return null;\n if (ignore) {\n if (queued) enqueue(invoke, transition, target);\n return;\n }\n\n ignore = true;\n queued = true;\n\n unset!(true);\n unset = undefined;\n\n enqueue(invoke, transition, target);\n }\n\n function run(release?: (update?: boolean | null) => void) {\n if (previous !== latest) unobserve(latest!);\n\n const proxy = observe(target, onUpdate, argument === true);\n const current = latest = (proxy as Observed)[Observing]!;\n const output = callback.call(proxy, proxy, events);\n\n if (observer(target) === null) {\n if (typeof output == 'function') output(null);\n if (release) release(null);\n return;\n }\n\n if (previous && argument === false && !current.watching.size)\n previous.callback = onUpdate;\n else {\n if (previous) unobserve(previous);\n previous = current;\n }\n\n ignore = false;\n reset = output === null ? null : invoke;\n unset = (key) => {\n if (typeof output == 'function') output(key);\n if (release) release(key);\n };\n\n events = [];\n }\n\n try {\n if (argument !== false) capture(run);\n else run();\n } catch (err) {\n if (err instanceof Promise) {\n reset = undefined;\n const suspended = suspense = hold(true, transition)!;\n const replay = () => {\n if (suspense !== suspended) return;\n suspense = undefined;\n suspended(invoke);\n };\n err.then(replay, replay);\n } else {\n throw err;\n }\n }\n }\n\n const unlisten = listener(target, (key) => {\n if (key === true) invoke();\n else if (key === null) {\n if (unset) unset(null);\n resume();\n reset = null;\n } else if (!reset) {\n suspense?.(false);\n return reset;\n }\n });\n\n function cleanup() {\n if (unset) unset(false);\n\n resume();\n reset = null;\n unlisten();\n }\n\n if (EffectContext && argument !== false) EffectContext.add(cleanup);\n\n return cleanup;\n}\n\nlet EffectContext: Set<(update?: boolean | null) => void> | undefined;\n\nfunction capture(scope: (release: (update?: boolean | null) => void) => void) {\n const parent = EffectContext;\n const context = (EffectContext = new Set());\n\n try {\n scope((update) => context.forEach((fn) => fn(update)));\n } finally {\n EffectContext = parent;\n }\n}\n\nexport {\n listener,\n event,\n Observer,\n touch,\n queued,\n observer,\n watch,\n capture\n};\n"],"mappings":";;;AA8CA,MAAM,WAA0B,OAAO,WAAW;AAClD,MAAM,YAA2B,OAAO,YAAY;;AAGpD,MAAM,UAAU,OAAO,IAAI,0BAA0B;AAgBrD,SAAS,SAAS,OAAe,QAAkB;CACjD,MAAM,IAAK,MAAqB;AAEhC,KAAI,CAAC,KAAK,QAAQ;AAChB,MAAI,MAAM,KACR,OAAM,IAAI,MACR,GAAG,MAAM,0DACV;EAEH,MAAM,QAAkB;GACtB,2BAAW,IAAI,KAAK;GACpB,yBAAS,IAAI,KAAK;GAClB,wBAAQ,IAAI,KAAK;GAClB;AACD,SAAO,eAAe,OAAO,UAAU;GAAE;GAAO,UAAU;GAAM,CAAC;AACjE,SAAO;;AAGT,QAAO;;AAGT,SAAS,QACP,QACA,UACA,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} from "./component.js";
|
|
2
3
|
|
|
3
4
|
//#region src/runtime.d.ts
|
|
@@ -67,5 +68,5 @@ declare function typeOf(node: unknown): unknown;
|
|
|
67
68
|
/** Props carried by element `node`. */
|
|
68
69
|
declare function propsOf(node: unknown): Record<string, unknown>;
|
|
69
70
|
//#endregion
|
|
70
|
-
export { Fragment, Host, HostRuntime, childrenOf, host, isElement, jsx, jsxDEV, jsxs, propsOf, typeOf };
|
|
71
|
+
export { Fragment, Host, HostRuntime, childrenOf, host, hot_d_exports as hot, isElement, jsx, jsxDEV, jsxs, propsOf, typeOf };
|
|
71
72
|
//# sourceMappingURL=runtime.d.ts.map
|
package/dist/runtime.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { hot_exports } from "./hot.js";
|
|
2
|
+
|
|
1
3
|
//#region src/runtime.ts
|
|
2
4
|
/**
|
|
3
5
|
* Agnostic Fragment sentinel. The runtime entries translate it to the host's
|
|
@@ -64,5 +66,5 @@ function propsOf(node) {
|
|
|
64
66
|
}
|
|
65
67
|
|
|
66
68
|
//#endregion
|
|
67
|
-
export { Fragment, childrenOf, host, isElement, jsx, jsxDEV, jsxs, propsOf, typeOf };
|
|
69
|
+
export { Fragment, childrenOf, host, hot_exports as hot, isElement, jsx, jsxDEV, jsxs, propsOf, typeOf };
|
|
68
70
|
//# sourceMappingURL=runtime.js.map
|
package/dist/runtime.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","names":[],"sources":["../src/runtime.ts"],"sourcesContent":["import type { Component } from './component';\n\n/**\n * Per-adapter interpretation manifest. Each adapter augments this interface to\n * declare how it renders; the first member is `node` - the element type produced\n * by `Component.render` (surfaced as `Component.Node`) - alongside `intrinsics`,\n * the host's tag map (surfaced as `JSX.IntrinsicElements`).\n *\n * ```ts\n * declare module '@expressive/mvc/runtime' {\n * interface Host {\n * node: React.ReactNode;\n * intrinsics: React.JSX.IntrinsicElements;\n * }\n * }\n * ```\n *\n * Only one adapter is expected per compilation; two augmenting the same member\n * with different types in the same build would conflict - by design.\n */\nexport interface Host { }\n\n/**\n * Host runtime, registered by an adapter (e.g. `@expressive/react`) as an\n * import side effect. One host per build - a second registration with a\n * different runtime throws.\n *\n * Members are ambient host capabilities: plain functions the host uniquely\n * owns, callable outside render - element mechanics always, plus optional\n * extras that fall back sanely when absent. Hook-shaped (render-resident)\n * capabilities do not belong here; those live with the adapter.\n */\nexport interface HostRuntime {\n childrenOf(children: unknown): Component.Node[];\n isElement(node: unknown): boolean;\n jsx(type: unknown, props: object, key?: unknown): Component.Node;\n jsxDEV?(type: unknown, props: object, key?: unknown, isStatic?: boolean, source?: object, self?: unknown): Component.Node;\n jsxs(type: unknown, props: object, key?: unknown): Component.Node;\n propsOf(node: unknown): Record<string, unknown>;\n typeOf(node: unknown): unknown;\n Fragment: unknown;\n}\n\n/**\n * Agnostic Fragment sentinel. The runtime entries translate it to the host's\n * Fragment on element creation; `typeOf` translates back, so identity checks\n * against this value hold for fragments from either pragma.\n */\nexport const Fragment = Symbol.for('@expressive/mvc.Fragment');\n\n/** Default for seams only a registered host can provide. */\nfunction absent(): never {\n throw new Error(\n 'No JSX host is registered for @expressive/mvc. ' +\n \"Import a host adapter (e.g. '@expressive/react') before anything renders - \" +\n 'typically as the first import of your application entry module.'\n );\n}\n\nconst HOST: HostRuntime = {\n childrenOf: absent,\n isElement: absent,\n jsx: absent,\n jsxs: absent,\n propsOf: absent,\n typeOf: absent,\n Fragment\n};\n\nlet registered: HostRuntime | undefined;\n\n/**\n * Register the host runtime. Idempotent for the same runtime - re-registering\n * picks up members added since (e.g. an optional dev seam). Element mechanics\n * the host leaves unset keep defaults that throw a setup-pointing error;\n * `jsxDEV` is routed around at the call site instead.\n */\nexport function host(runtime: HostRuntime) {\n if (registered && registered !== runtime)\n throw new Error(\n 'A different JSX host is already registered for @expressive/mvc. ' +\n 'Only one host adapter may be active per build.'\n );\n\n registered = runtime;\n Object.assign(HOST, runtime);\n}\n\n/** Translate the agnostic Fragment sentinel to the host's Fragment. */\nfunction hostType(type: unknown): unknown {\n return type === Fragment ? HOST.Fragment : type;\n}\n\nexport function jsx(type: unknown, props: object, key?: unknown): Component.Node {\n return HOST.jsx(hostType(type), props, key);\n}\n\nexport function jsxs(type: unknown, props: object, key?: unknown): Component.Node {\n return HOST.jsxs(hostType(type), props, key);\n}\n\n/** Dev-transpiled element creation. Hosts without a `jsxDEV` of their own fall\n * back to the production entries (prod-only host under a dev build). */\nexport function jsxDEV(\n type: unknown,\n props: object,\n key?: unknown,\n isStatic?: boolean,\n source?: object,\n self?: unknown\n): Component.Node {\n return HOST.jsxDEV\n ? HOST.jsxDEV(hostType(type), props, key, isStatic, source, self)\n : isStatic\n ? jsxs(type, props, key)\n : jsx(type, props, key);\n}\n\n/** Flatten `children` to an array of nodes, per the host's semantics. */\nexport function childrenOf(children: unknown): Component.Node[] {\n return HOST.childrenOf(children);\n}\n\n/** Is `node` a host element? */\nexport function isElement(node: unknown): boolean {\n return HOST.isElement(node);\n}\n\n/** Element type of `node`; host Fragments surface as the agnostic `Fragment`. */\nexport function typeOf(node: unknown): unknown {\n const type = HOST.typeOf(node);\n return type === HOST.Fragment ? Fragment : type;\n}\n\n/** Props carried by element `node`. */\nexport function propsOf(node: unknown): Record<string, unknown> {\n return HOST.propsOf(node);\n}\n\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../src/runtime.ts"],"sourcesContent":["import type { Component } from './component';\n\n/**\n * Per-adapter interpretation manifest. Each adapter augments this interface to\n * declare how it renders; the first member is `node` - the element type produced\n * by `Component.render` (surfaced as `Component.Node`) - alongside `intrinsics`,\n * the host's tag map (surfaced as `JSX.IntrinsicElements`).\n *\n * ```ts\n * declare module '@expressive/mvc/runtime' {\n * interface Host {\n * node: React.ReactNode;\n * intrinsics: React.JSX.IntrinsicElements;\n * }\n * }\n * ```\n *\n * Only one adapter is expected per compilation; two augmenting the same member\n * with different types in the same build would conflict - by design.\n */\nexport interface Host { }\n\n/**\n * Host runtime, registered by an adapter (e.g. `@expressive/react`) as an\n * import side effect. One host per build - a second registration with a\n * different runtime throws.\n *\n * Members are ambient host capabilities: plain functions the host uniquely\n * owns, callable outside render - element mechanics always, plus optional\n * extras that fall back sanely when absent. Hook-shaped (render-resident)\n * capabilities do not belong here; those live with the adapter.\n */\nexport interface HostRuntime {\n childrenOf(children: unknown): Component.Node[];\n isElement(node: unknown): boolean;\n jsx(type: unknown, props: object, key?: unknown): Component.Node;\n jsxDEV?(type: unknown, props: object, key?: unknown, isStatic?: boolean, source?: object, self?: unknown): Component.Node;\n jsxs(type: unknown, props: object, key?: unknown): Component.Node;\n propsOf(node: unknown): Record<string, unknown>;\n typeOf(node: unknown): unknown;\n Fragment: unknown;\n}\n\n/**\n * Agnostic Fragment sentinel. The runtime entries translate it to the host's\n * Fragment on element creation; `typeOf` translates back, so identity checks\n * against this value hold for fragments from either pragma.\n */\nexport const Fragment = Symbol.for('@expressive/mvc.Fragment');\n\n/** Default for seams only a registered host can provide. */\nfunction absent(): never {\n throw new Error(\n 'No JSX host is registered for @expressive/mvc. ' +\n \"Import a host adapter (e.g. '@expressive/react') before anything renders - \" +\n 'typically as the first import of your application entry module.'\n );\n}\n\nconst HOST: HostRuntime = {\n childrenOf: absent,\n isElement: absent,\n jsx: absent,\n jsxs: absent,\n propsOf: absent,\n typeOf: absent,\n Fragment\n};\n\nlet registered: HostRuntime | undefined;\n\n/**\n * Register the host runtime. Idempotent for the same runtime - re-registering\n * picks up members added since (e.g. an optional dev seam). Element mechanics\n * the host leaves unset keep defaults that throw a setup-pointing error;\n * `jsxDEV` is routed around at the call site instead.\n */\nexport function host(runtime: HostRuntime) {\n if (registered && registered !== runtime)\n throw new Error(\n 'A different JSX host is already registered for @expressive/mvc. ' +\n 'Only one host adapter may be active per build.'\n );\n\n registered = runtime;\n Object.assign(HOST, runtime);\n}\n\n/** Translate the agnostic Fragment sentinel to the host's Fragment. */\nfunction hostType(type: unknown): unknown {\n return type === Fragment ? HOST.Fragment : type;\n}\n\nexport function jsx(type: unknown, props: object, key?: unknown): Component.Node {\n return HOST.jsx(hostType(type), props, key);\n}\n\nexport function jsxs(type: unknown, props: object, key?: unknown): Component.Node {\n return HOST.jsxs(hostType(type), props, key);\n}\n\n/** Dev-transpiled element creation. Hosts without a `jsxDEV` of their own fall\n * back to the production entries (prod-only host under a dev build). */\nexport function jsxDEV(\n type: unknown,\n props: object,\n key?: unknown,\n isStatic?: boolean,\n source?: object,\n self?: unknown\n): Component.Node {\n return HOST.jsxDEV\n ? HOST.jsxDEV(hostType(type), props, key, isStatic, source, self)\n : isStatic\n ? jsxs(type, props, key)\n : jsx(type, props, key);\n}\n\n/** Flatten `children` to an array of nodes, per the host's semantics. */\nexport function childrenOf(children: unknown): Component.Node[] {\n return HOST.childrenOf(children);\n}\n\n/** Is `node` a host element? */\nexport function isElement(node: unknown): boolean {\n return HOST.isElement(node);\n}\n\n/** Element type of `node`; host Fragments surface as the agnostic `Fragment`. */\nexport function typeOf(node: unknown): unknown {\n const type = HOST.typeOf(node);\n return type === HOST.Fragment ? Fragment : type;\n}\n\n/** Props carried by element `node`. */\nexport function propsOf(node: unknown): Record<string, unknown> {\n return HOST.propsOf(node);\n}\n\nexport * as hot from './hot';\n"],"mappings":";;;;;;;;AAgDA,MAAa,WAAW,OAAO,IAAI,2BAA2B;;AAG9D,SAAS,SAAgB;AACvB,OAAM,IAAI,MACR,4LAGD;;AAGH,MAAM,OAAoB;CACxB,YAAY;CACZ,WAAW;CACX,KAAK;CACL,MAAM;CACN,SAAS;CACT,QAAQ;CACR;CACD;AAED,IAAI;;;;;;;AAQJ,SAAgB,KAAK,SAAsB;AACzC,KAAI,cAAc,eAAe,QAC/B,OAAM,IAAI,MACR,iHAED;AAEH,cAAa;AACb,QAAO,OAAO,MAAM,QAAQ;;;AAI9B,SAAS,SAAS,MAAwB;AACxC,QAAO,SAAS,WAAW,KAAK,WAAW;;AAG7C,SAAgB,IAAI,MAAe,OAAe,KAA+B;AAC/E,QAAO,KAAK,IAAI,SAAS,KAAK,EAAE,OAAO,IAAI;;AAG7C,SAAgB,KAAK,MAAe,OAAe,KAA+B;AAChF,QAAO,KAAK,KAAK,SAAS,KAAK,EAAE,OAAO,IAAI;;;;AAK9C,SAAgB,OACd,MACA,OACA,KACA,UACA,QACA,MACgB;AAChB,QAAO,KAAK,SACR,KAAK,OAAO,SAAS,KAAK,EAAE,OAAO,KAAK,UAAU,QAAQ,KAAK,GAC/D,WACE,KAAK,MAAM,OAAO,IAAI,GACtB,IAAI,MAAM,OAAO,IAAI;;;AAI7B,SAAgB,WAAW,UAAqC;AAC9D,QAAO,KAAK,WAAW,SAAS;;;AAIlC,SAAgB,UAAU,MAAwB;AAChD,QAAO,KAAK,UAAU,KAAK;;;AAI7B,SAAgB,OAAO,MAAwB;CAC7C,MAAM,OAAO,KAAK,OAAO,KAAK;AAC9B,QAAO,SAAS,KAAK,WAAW,WAAW;;;AAI7C,SAAgB,QAAQ,MAAwC;AAC9D,QAAO,KAAK,QAAQ,KAAK"}
|
package/dist/state.d.ts
CHANGED
|
@@ -8,6 +8,8 @@ declare const STORE: WeakMap<State, Record<string | number | symbol, unknown>>;
|
|
|
8
8
|
/** States under construction - added on `new`, removed when activated or released.
|
|
9
9
|
* Also carries work to run at the deadline, which `def` uses to bound its registry. */
|
|
10
10
|
declare const PENDING: Set<State | (() => void)>;
|
|
11
|
+
/** External lifecycle listeners for any given State class. */
|
|
12
|
+
type Handler = State.Init<any> | State.On<any>;
|
|
11
13
|
declare namespace State {
|
|
12
14
|
/** Any type of State, using own class constructor as its identifier. */
|
|
13
15
|
type Extends<T extends State = State> = (abstract new (...args: any[]) => T) & typeof State;
|
|
@@ -63,9 +65,11 @@ declare namespace State {
|
|
|
63
65
|
catch?(this: T, error: Caught): Caught | void;
|
|
64
66
|
}
|
|
65
67
|
/** Object overlay to override values and methods on a state. */
|
|
66
|
-
type Assign<T> = Record<string, unknown> & { [K in
|
|
68
|
+
type Assign<T> = Record<string, unknown> & { [K in Property<T>]?: T[K] extends ((...args: infer A) => infer R) ? (this: T, ...args: A) => R : T[K] };
|
|
67
69
|
/** Subset of `keyof T` not defined by base State. **/
|
|
68
|
-
type
|
|
70
|
+
type Property<T> = Exclude<keyof T, keyof State>;
|
|
71
|
+
/** Managed subset of Property<T> - excludes unmanaged `_` keys. **/
|
|
72
|
+
type Field<T> = Exclude<Property<T>, `_${string}`>;
|
|
69
73
|
/** Any valid key for state, including but not limited to Field<T>. */
|
|
70
74
|
type Event<T = State> = Field<T> | number | symbol | (string & {});
|
|
71
75
|
/** Any event signal dispatched to listeners, including lifecycle meta events. */
|
|
@@ -330,6 +334,11 @@ declare function compute(this: State, getter: (self: any) => unknown, key: strin
|
|
|
330
334
|
* @param silent - If an update does occur, listeners will not be refreshed automatically.
|
|
331
335
|
*/
|
|
332
336
|
declare function apply(state: State, key: string, config: State.Apply, silent?: boolean): void;
|
|
337
|
+
/**
|
|
338
|
+
* Pending States constructed after this one - in a parent, the products of
|
|
339
|
+
* its own initializers, until the last one it kept.
|
|
340
|
+
*/
|
|
341
|
+
declare function trailing(state: State): State[];
|
|
333
342
|
/**
|
|
334
343
|
* Report States adopted by a parent - those already held, then each one
|
|
335
344
|
* claimed later. Returns a callback to stop watching.
|
|
@@ -346,6 +355,15 @@ declare function access(state: State, property: string, required?: boolean): any
|
|
|
346
355
|
declare function update<T>(state: State, key: State.Event<T>, value: T, silent?: boolean, own?: boolean): boolean;
|
|
347
356
|
/** Error thrown by a handler replaying in dispatch, attributed to the State which queued it. */
|
|
348
357
|
declare function fault(err: unknown, owner?: object): void;
|
|
358
|
+
/** Begin tracking live instances, so a hot patch can reach them. */
|
|
359
|
+
declare function track(): void;
|
|
360
|
+
/**
|
|
361
|
+
* Move the members of `next` onto `prev`, which keeps its identity. Returns the
|
|
362
|
+
* live instances of `prev`, each needing a refresh.
|
|
363
|
+
*/
|
|
364
|
+
declare function patch(prev: State.Extends, next: State.Extends, own: Handler[]): State[];
|
|
365
|
+
/** Lifecycle handlers registered on a class itself. */
|
|
366
|
+
declare function handlers(type: State.Extends): Handler[];
|
|
349
367
|
/** Random alphanumberic of length 6; always starts with a letter. */
|
|
350
368
|
declare function uid(): string;
|
|
351
369
|
declare function unbind<T extends Function>(fn: T): T;
|
|
@@ -359,5 +377,5 @@ declare function unbind<T extends Function>(fn?: T): T | undefined;
|
|
|
359
377
|
declare function parent(child: object): State | null | undefined;
|
|
360
378
|
declare function parent(child: object, value: State | null): boolean;
|
|
361
379
|
//#endregion
|
|
362
|
-
export { PENDING, STORE, State, access, apply, children, compute, event, fault, parent, uid, unbind, update };
|
|
380
|
+
export { PENDING, STORE, State, access, apply, children, compute, event, fault, handlers, parent, patch, track, trailing, uid, unbind, update };
|
|
363
381
|
//# sourceMappingURL=state.d.ts.map
|
package/dist/state.js
CHANGED
|
@@ -11,7 +11,6 @@ const STORE = /* @__PURE__ */ new WeakMap();
|
|
|
11
11
|
/** States under construction - added on `new`, removed when activated or released.
|
|
12
12
|
* Also carries work to run at the deadline, which `def` uses to bound its registry. */
|
|
13
13
|
const PENDING = /* @__PURE__ */ new Set();
|
|
14
|
-
/** External lifecycle listeners for any given State class. */
|
|
15
14
|
const SETUP = /* @__PURE__ */ new WeakMap();
|
|
16
15
|
/** Parent-child relationships. */
|
|
17
16
|
const PARENT = /* @__PURE__ */ new WeakMap();
|
|
@@ -21,6 +20,16 @@ const UNBIND = /* @__PURE__ */ new WeakMap();
|
|
|
21
20
|
const METHODS = /* @__PURE__ */ new WeakMap();
|
|
22
21
|
/** List of reactive getters defined by a given type. */
|
|
23
22
|
const GETTERS = /* @__PURE__ */ new WeakMap();
|
|
23
|
+
/** Replacement for a getter captured by live computed properties, for hot patching. */
|
|
24
|
+
const LATEST = /* @__PURE__ */ new WeakMap();
|
|
25
|
+
/** Method implementations replaced by a hot patch. */
|
|
26
|
+
const PAST = /* @__PURE__ */ new WeakSet();
|
|
27
|
+
/** Live instances, tracked once hot patching is enabled. */
|
|
28
|
+
let LIVE;
|
|
29
|
+
/** Bootstrapped subclasses of each class, tracked once hot patching is enabled. */
|
|
30
|
+
const SUBCLASSES = /* @__PURE__ */ new WeakMap();
|
|
31
|
+
/** Event every observer treats as watched, forcing a refresh after a hot patch. */
|
|
32
|
+
const REFRESH = Symbol.for("@expressive/mvc.refresh");
|
|
24
33
|
/** Stale flags for compute closures awaiting refresh on next access. */
|
|
25
34
|
const STALE = /* @__PURE__ */ new WeakSet();
|
|
26
35
|
/** Whether the deadline which drains `PENDING` is already queued for this tick. */
|
|
@@ -60,7 +69,7 @@ var State = class State {
|
|
|
60
69
|
set(arg1, arg2) {
|
|
61
70
|
const self = this.is;
|
|
62
71
|
if (typeof arg1 == "function") return listener(self, (key) => {
|
|
63
|
-
if (typeof key == "string" || typeof key == "number" || typeof key == "symbol") return arg1.call(self, key, self);
|
|
72
|
+
if (typeof key == "string" || typeof key == "number" || typeof key == "symbol" && key !== REFRESH) return arg1.call(self, key, self);
|
|
64
73
|
});
|
|
65
74
|
if (typeof arg2 == "function") return callback(self, arg2, arg1);
|
|
66
75
|
if (arg1 && typeof arg1 == "object") assign(self, arg1, arg2 === true);
|
|
@@ -138,10 +147,13 @@ function init(state, ...args) {
|
|
|
138
147
|
const { before, after } = bootstrap(T);
|
|
139
148
|
ID.set(state, `${T}-${uid()}`);
|
|
140
149
|
STORE.set(state, {});
|
|
150
|
+
LIVE?.add(new WeakRef(state));
|
|
141
151
|
function observe() {
|
|
142
152
|
for (const key in state) {
|
|
143
153
|
const desc = Object.getOwnPropertyDescriptor(state, key) || {};
|
|
144
|
-
if ("value" in desc
|
|
154
|
+
if (!("value" in desc) || !desc.configurable) continue;
|
|
155
|
+
if (key[0] == "_") unmanaged(state, key, desc.value);
|
|
156
|
+
else apply(state, key, desc, true);
|
|
145
157
|
}
|
|
146
158
|
}
|
|
147
159
|
function register() {
|
|
@@ -191,6 +203,16 @@ function init(state, ...args) {
|
|
|
191
203
|
}
|
|
192
204
|
PENDING.add(state);
|
|
193
205
|
}
|
|
206
|
+
function unmanaged(state, key, value) {
|
|
207
|
+
define(state, key, {
|
|
208
|
+
configurable: true,
|
|
209
|
+
enumerable: false,
|
|
210
|
+
get: () => value,
|
|
211
|
+
set: (next) => {
|
|
212
|
+
value = next;
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
}
|
|
194
216
|
/**
|
|
195
217
|
* Apply instructions and inherited event listeners. Ensure class metadata is ready.
|
|
196
218
|
*
|
|
@@ -223,36 +245,15 @@ function bootstrap(T) {
|
|
|
223
245
|
continue;
|
|
224
246
|
}
|
|
225
247
|
for (const setupType of onType) setupType(type);
|
|
248
|
+
if (LIVE) {
|
|
249
|
+
const parent = Object.getPrototypeOf(type);
|
|
250
|
+
let children = SUBCLASSES.get(parent);
|
|
251
|
+
if (!children) SUBCLASSES.set(parent, children = /* @__PURE__ */ new Set());
|
|
252
|
+
children.add(type);
|
|
253
|
+
}
|
|
226
254
|
METHODS.set(type, keys = new Map(keys));
|
|
227
255
|
GETTERS.set(type, getters = new Map(getters));
|
|
228
|
-
|
|
229
|
-
if (key == "constructor" || !desc.configurable) continue;
|
|
230
|
-
if (typeof desc.get == "function") {
|
|
231
|
-
if (desc.configurable && typeof desc.set != "function") getters.set(key, desc.get);
|
|
232
|
-
continue;
|
|
233
|
-
}
|
|
234
|
-
const { value } = desc;
|
|
235
|
-
if (typeof value !== "function") continue;
|
|
236
|
-
function bind(original) {
|
|
237
|
-
const { is } = this;
|
|
238
|
-
if (is.hasOwnProperty(key) && !original) return value;
|
|
239
|
-
const fn = original || value;
|
|
240
|
-
const bound = fn.bind(is);
|
|
241
|
-
UNBIND.set(bound, fn);
|
|
242
|
-
define(is, key, {
|
|
243
|
-
value: bound,
|
|
244
|
-
writable: true,
|
|
245
|
-
configurable: true
|
|
246
|
-
});
|
|
247
|
-
return bound;
|
|
248
|
-
}
|
|
249
|
-
UNBIND.set(bind, value);
|
|
250
|
-
keys.set(key, bind);
|
|
251
|
-
define(type.prototype, key, {
|
|
252
|
-
get: bind,
|
|
253
|
-
set: bind
|
|
254
|
-
});
|
|
255
|
-
}
|
|
256
|
+
classify(type, keys, getters);
|
|
256
257
|
}
|
|
257
258
|
if (getters.size) before.add((self) => getters.forEach(compute, self));
|
|
258
259
|
return {
|
|
@@ -260,6 +261,50 @@ function bootstrap(T) {
|
|
|
260
261
|
after
|
|
261
262
|
};
|
|
262
263
|
}
|
|
264
|
+
/** Bind own configurable methods of a type and collect its reactive getters. */
|
|
265
|
+
function classify(type, keys, getters) {
|
|
266
|
+
for (const [key, desc] of Object.entries(Object.getOwnPropertyDescriptors(type.prototype))) {
|
|
267
|
+
if (key == "constructor" || !desc.configurable) continue;
|
|
268
|
+
const { get, set } = desc;
|
|
269
|
+
if (key[0] == "_" && (get || set)) {
|
|
270
|
+
define(type.prototype, key, {
|
|
271
|
+
...desc,
|
|
272
|
+
get: get && function() {
|
|
273
|
+
return get.call(this.is || this);
|
|
274
|
+
},
|
|
275
|
+
set: set && function(value) {
|
|
276
|
+
set.call(this.is || this, value);
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
if (typeof get == "function") {
|
|
282
|
+
if (typeof set != "function") getters.set(key, get);
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
const { value } = desc;
|
|
286
|
+
if (typeof value !== "function") continue;
|
|
287
|
+
function bind(original) {
|
|
288
|
+
const { is } = this;
|
|
289
|
+
if (is.hasOwnProperty(key) && !original) return value;
|
|
290
|
+
const fn = original || value;
|
|
291
|
+
const bound = fn.bind(is);
|
|
292
|
+
UNBIND.set(bound, fn);
|
|
293
|
+
define(is, key, {
|
|
294
|
+
value: bound,
|
|
295
|
+
writable: true,
|
|
296
|
+
configurable: true
|
|
297
|
+
});
|
|
298
|
+
return bound;
|
|
299
|
+
}
|
|
300
|
+
UNBIND.set(bind, value);
|
|
301
|
+
keys.set(key, bind);
|
|
302
|
+
define(type.prototype, key, {
|
|
303
|
+
get: bind,
|
|
304
|
+
set: bind
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
}
|
|
263
308
|
/**
|
|
264
309
|
* Install a reactive computed property on a state instance, derived from a prototype
|
|
265
310
|
* getter or an arity-bearing `set` factory.
|
|
@@ -288,7 +333,7 @@ function compute(getter, key) {
|
|
|
288
333
|
const run = (initial) => {
|
|
289
334
|
let next;
|
|
290
335
|
try {
|
|
291
|
-
next = getter.call(proxy, proxy);
|
|
336
|
+
next = latest(getter).call(proxy, proxy);
|
|
292
337
|
} catch (err) {
|
|
293
338
|
if (initial) {
|
|
294
339
|
console.warn(`An exception was thrown while initializing ${this}.${key}.`);
|
|
@@ -470,7 +515,7 @@ function assign(state, data, silent) {
|
|
|
470
515
|
else if (key in state && key !== "is") {
|
|
471
516
|
const set = (Object.getOwnPropertyDescriptor(state, key) || {}).set;
|
|
472
517
|
if (set) set.call(state, data[key], silent);
|
|
473
|
-
else state
|
|
518
|
+
else Reflect.set(state, key, data[key]);
|
|
474
519
|
}
|
|
475
520
|
}
|
|
476
521
|
}
|
|
@@ -548,6 +593,106 @@ function adopt(state, key, value) {
|
|
|
548
593
|
}
|
|
549
594
|
claim(value);
|
|
550
595
|
}
|
|
596
|
+
/** Resolve a getter to its latest hot-patched replacement. */
|
|
597
|
+
function latest(getter) {
|
|
598
|
+
for (let next; next = LATEST.get(getter);) getter = next;
|
|
599
|
+
return getter;
|
|
600
|
+
}
|
|
601
|
+
/** Begin tracking live instances, so a hot patch can reach them. */
|
|
602
|
+
function track() {
|
|
603
|
+
LIVE ||= /* @__PURE__ */ new Set();
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Move the members of `next` onto `prev`, which keeps its identity. Returns the
|
|
607
|
+
* live instances of `prev`, each needing a refresh.
|
|
608
|
+
*/
|
|
609
|
+
function patch(prev, next, own) {
|
|
610
|
+
const proto = prev.prototype;
|
|
611
|
+
const incoming = Object.getOwnPropertyDescriptors(next.prototype);
|
|
612
|
+
const keys = METHODS.get(prev);
|
|
613
|
+
const getters = GETTERS.get(prev);
|
|
614
|
+
const methods = /* @__PURE__ */ new Map();
|
|
615
|
+
const knownKeys = new Set(keys?.keys());
|
|
616
|
+
const knownGetters = new Set(getters?.keys());
|
|
617
|
+
let setup = SETUP.get(prev);
|
|
618
|
+
for (const handler of own) setup.delete(handler);
|
|
619
|
+
for (const handler of handlers(next)) {
|
|
620
|
+
if (!setup) SETUP.set(prev, setup = /* @__PURE__ */ new Set());
|
|
621
|
+
setup.add(handler);
|
|
622
|
+
}
|
|
623
|
+
for (const key of Reflect.ownKeys(next)) {
|
|
624
|
+
if (key == "prototype" || key == "length" || key == "name") continue;
|
|
625
|
+
if (Object.getOwnPropertyDescriptor(prev, key)?.configurable !== false) define(prev, key, Object.getOwnPropertyDescriptor(next, key));
|
|
626
|
+
}
|
|
627
|
+
const removed = /* @__PURE__ */ new Set();
|
|
628
|
+
for (const key of Object.getOwnPropertyNames(proto)) if (key != "constructor" && !(key in incoming)) {
|
|
629
|
+
const bind = keys?.get(key);
|
|
630
|
+
if (bind && Object.getOwnPropertyDescriptor(proto, key).get === bind) {
|
|
631
|
+
PAST.add(UNBIND.get(bind));
|
|
632
|
+
keys.delete(key);
|
|
633
|
+
}
|
|
634
|
+
removed.add(key);
|
|
635
|
+
Reflect.deleteProperty(proto, key);
|
|
636
|
+
getters?.delete(key);
|
|
637
|
+
}
|
|
638
|
+
for (const [key, desc] of Object.entries(incoming)) {
|
|
639
|
+
if (key == "constructor") continue;
|
|
640
|
+
const current = Object.getOwnPropertyDescriptor(proto, key);
|
|
641
|
+
if (typeof desc.value == "function") methods.set(key, desc.value);
|
|
642
|
+
if (current?.configurable === false) {
|
|
643
|
+
if (current.writable) proto[key] = desc.value;
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
if (current?.get && keys?.get(key) === current.get) PAST.add(UNBIND.get(current.get));
|
|
647
|
+
const getter = getters?.get(key);
|
|
648
|
+
if (getter) LATEST.set(getter, desc.get);
|
|
649
|
+
define(proto, key, {
|
|
650
|
+
...desc,
|
|
651
|
+
configurable: true
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
if (keys) {
|
|
655
|
+
for (let T = prev;; T = Object.getPrototypeOf(T)) {
|
|
656
|
+
for (const handler of SETUP.get(T) || []) if (typeof handler == "object" && handler.type) handler.type(prev);
|
|
657
|
+
if (T === State) break;
|
|
658
|
+
}
|
|
659
|
+
classify(prev, keys, getters);
|
|
660
|
+
}
|
|
661
|
+
const live = [];
|
|
662
|
+
for (const ref of LIVE) {
|
|
663
|
+
const state = ref.deref();
|
|
664
|
+
if (!state) LIVE.delete(ref);
|
|
665
|
+
else if (state instanceof prev) live.push(state);
|
|
666
|
+
}
|
|
667
|
+
const descendants = new Set([prev, ...live.map((state) => state.constructor)]);
|
|
668
|
+
for (const type of descendants) for (const child of SUBCLASSES.get(type) || []) descendants.add(child);
|
|
669
|
+
descendants.delete(prev);
|
|
670
|
+
for (const type of descendants) {
|
|
671
|
+
const inherit = METHODS.get(type);
|
|
672
|
+
const computed = GETTERS.get(type);
|
|
673
|
+
for (const [key, bind] of keys) if (!knownKeys.has(key) && !inherit.has(key)) inherit.set(key, bind);
|
|
674
|
+
for (const [key, get] of getters) if (!knownGetters.has(key) && !computed.has(key)) computed.set(key, get);
|
|
675
|
+
for (const key of removed) if (!(key in type.prototype)) {
|
|
676
|
+
inherit.delete(key);
|
|
677
|
+
computed.delete(key);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
for (const state of live) {
|
|
681
|
+
for (const [key, value] of methods) {
|
|
682
|
+
const desc = Object.getOwnPropertyDescriptor(state, key);
|
|
683
|
+
if (!desc) continue;
|
|
684
|
+
if (desc.set) desc.set.call(state, value);
|
|
685
|
+
else if (PAST.has(UNBIND.get(desc.value))) delete state[key];
|
|
686
|
+
}
|
|
687
|
+
for (const key of removed) if (PAST.has(UNBIND.get(Object.getOwnPropertyDescriptor(state, key)?.value))) delete state[key];
|
|
688
|
+
for (const [key, get] of GETTERS.get(state.constructor)) if (!knownGetters.has(key) && get === getters.get(key)) compute.call(state, get, key);
|
|
689
|
+
}
|
|
690
|
+
return live;
|
|
691
|
+
}
|
|
692
|
+
/** Lifecycle handlers registered on a class itself. */
|
|
693
|
+
function handlers(type) {
|
|
694
|
+
return [...SETUP.get(type) || []];
|
|
695
|
+
}
|
|
551
696
|
/** Random alphanumberic of length 6; always starts with a letter. */
|
|
552
697
|
function uid() {
|
|
553
698
|
return (.278 + Math.random() * .722).toString(36).substring(2, 8).toUpperCase();
|
|
@@ -563,5 +708,5 @@ function parent(child, value) {
|
|
|
563
708
|
}
|
|
564
709
|
|
|
565
710
|
//#endregion
|
|
566
|
-
export { PENDING, STORE, State, access, apply, children, compute, event, fault, parent, uid, unbind, update };
|
|
711
|
+
export { PENDING, STORE, State, access, apply, children, compute, event, fault, handlers, parent, patch, track, trailing, uid, unbind, update };
|
|
567
712
|
//# sourceMappingURL=state.js.map
|
package/dist/state.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.js","names":[],"sources":["../src/state.ts"],"sourcesContent":["import { Context, join } from './context';\nimport { Caught } from './caught';\nimport {\n capture,\n event,\n listener,\n Observer,\n observer,\n queued,\n touch,\n watch\n} from './observable';\n\nconst define = Object.defineProperty;\n\n/** Register for all active states via string identifiers (usually unique). */\nconst ID = new WeakMap<State, string>();\n\n/** Internal state assigned to states. */\nconst STORE = new WeakMap<State, Record<string | number | symbol, unknown>>();\n\n/** States under construction - added on `new`, removed when activated or released.\n * Also carries work to run at the deadline, which `def` uses to bound its registry. */\nconst PENDING = new Set<State | (() => void)>();\n\n/** External lifecycle listeners for any given State class. */\nconst SETUP = new WeakMap<State.Extends, Set<State.Init<any> | State.On<any>>>();\n\n/** Parent-child relationships. */\nconst PARENT = new WeakMap<object, State | null>();\n\n/** Reference bound instance methods, or their getter, to real one. */\nconst UNBIND = new WeakMap<any, any>();\n\n/** List of methods defined by a given type. */\nconst METHODS = new WeakMap<Function, Map<string, (value: any) => void>>();\n\n/** List of reactive getters defined by a given type. */\nconst GETTERS = new WeakMap<Function, Map<string, () => unknown>>();\n\n/** Stale flags for compute closures awaiting refresh on next access. */\nconst STALE = new WeakSet<() => void>();\n\n/** Whether the deadline which drains `PENDING` is already queued for this tick. */\nlet QUEUED = false;\n\n/** Global list each loaded copy of this module adds its `State` to, on first construction. */\nconst COPIES = Symbol.for('@expressive/mvc');\n\nlet ANNOUNCED = false;\n\n/** Adopters for managed properties which have held a child State. */\nconst ADOPT = new WeakMap<State, Map<unknown, (value: unknown) => void>>();\nconst CHILDREN = new WeakMap<State, Set<(child: State) => void>>();\n\ndeclare namespace State {\n /** Any type of State, using own class constructor as its identifier. */\n type Extends<T extends State = State> = (abstract new (...args: any[]) => T) &\n typeof State;\n\n /** A State constructor which may be instanciated. */\n type Type<T extends State = State> = (new (...args: State.Args<T>) => T) &\n Omit<typeof State, never>;\n\n /** State constructor arguments */\n type Args<T extends State = any> = (Args<T> | Init<T> | Assign<T> | void)[];\n\n /**\n * Value of `static global`. A boolean opts a State in or out of the\n * process-global root; a resolver decides at activation, receiving the\n * instance and returning whether it registers - use it to make the choice\n * conditional (e.g. per environment). A bare literal (`= true` / `= false`)\n * seals the choice for subclasses; widen a subclass's `static global` type to\n * `State.Global` to permit a resolver or a later override.\n */\n type Global<T extends State = any> = boolean | ((self: T) => boolean);\n\n /**\n * State constructor callback - runs during activation, in argument order,\n * before the `new()` lifecycle hook (so it may configure state `new()`\n * will observe). Returned function will run when state is destroyed.\n */\n type Init<T extends State = State> = (\n this: T,\n thisArg: T\n ) => Promise<void> | (() => void) | Args<T> | Assign<T> | void;\n\n /**\n * Lifecycle handlers for `State.on`, keyed by when they run. A bare `Init`\n * function passed to `on` is sugar for `{ before }`.\n */\n interface On<T extends State = State> {\n /**\n * Per-class setup, run once when the class is first bootstrapped - before\n * its members are classified and bound. Receives the class, so a handler\n * may inspect or reshape the prototype first. A handler registered on a\n * base class runs for each subclass too.\n */\n type?(type: State.Extends<T>): void;\n\n /**\n * Per-instance setup, run in the `prepare` phase before `observe` and the\n * `new()` hook. Equivalent to passing a bare function to `on`. May return a\n * cleanup, constructor args, or an assign overlay.\n */\n before?(this: T, thisArg: T): void | (() => void) | Promise<void> | Args<T> | Assign<T>;\n\n /**\n * Per-instance setup, run at the `new()` slot - after own values are\n * observed and constructor args applied. May return a cleanup function.\n */\n after?(this: T, self: T): void | (() => void);\n\n /**\n * Receives a `Caught` mvc reports for this State or a subclass - most-derived\n * class first, last registered first. Return it (or a replacement) to pass it\n * on; return nothing to handle it; throw to let it escape uncaught. Passed off\n * the end, a warning logs and anything else is thrown - to the writer for a\n * destroyed write, else uncaught.\n */\n catch?(this: T, error: Caught): Caught | void;\n }\n\n /** Object overlay to override values and methods on a state. */\n type Assign<T> = Record<string, unknown> & {\n [K in Field<T>]?: T[K] extends (...args: infer A) => infer R\n ? (this: T, ...args: A) => R\n : T[K];\n };\n\n /** Subset of `keyof T` not defined by base State. **/\n type Field<T> = Exclude<keyof T, keyof State>;\n\n /** Any valid key for state, including but not limited to Field<T>. */\n type Event<T = State> = Field<T> | number | symbol | (string & {});\n\n /** Any event signal dispatched to listeners, including lifecycle meta events. */\n type Signal<T = State> = Event<T> | true | false | null;\n\n /** Export/Import compatible value for a given property in a State. */\n type Export<R> = R extends State\n ? Values<R>\n : R extends { get(): infer T }\n ? T\n : R;\n\n /**\n * Values from current state of given state.\n * Differs from `Values` as values here will drill\n * into \"real\" values held by exotics like ref.Object.\n */\n type Values<T> = { [P in Field<T>]: Export<T[P]> };\n\n /** Object comperable to data found in T. */\n type Partial<T> = { [P in Field<T>]?: Export<T[P]> };\n\n /** Value for a property applied by a state. */\n type Value<T extends State, K extends State.Event<T>> = K extends keyof T\n ? Export<T[K]>\n : unknown;\n\n type Setter<T> = (value: T, previous: T) => T | void;\n\n /** Descriptor config for a managed property. */\n type Apply<T = any> = {\n value?: T;\n get?: ((source: State) => T) | boolean;\n set?: Setter<T> | boolean;\n enumerable?: boolean;\n // destroy?: () => void;\n };\n\n /** Descriptor config for set() overload - enforces type when key is a known field. */\n type Define<T, K> = K extends Field<T> ? Apply<T[K] | Export<T[K]>> : Apply;\n\n type OnEvent<T extends State> = (\n this: T,\n key: Signal<T>,\n source: T\n ) => void | (() => void) | null;\n\n /** Exotic value, where actual value is contained within. */\n type Ref<T = any> = {\n (next: T): void;\n current: T | null;\n };\n\n /**\n * A callback function which is subscribed to parent and updates when accessed properties change.\n *\n * @param current - Current state of this state. This is a proxy which detects properties which\n * where accessed, and thus depended upon to stay current.\n *\n * @param update - Set of properties which have changed, and events fired, since last update.\n *\n * @returns A callback function which will be called when this effect is stale.\n */\n type Effect<T> = (\n this: T,\n current: T,\n update: readonly State.Event<T>[] | undefined\n ) => EffectCallback | Promise<void> | null | void;\n\n /**\n * A callback function returned by effect. Will be called when effect is stale.\n *\n * @param update - `true` if update is pending, `false` effect has been cancelled, `null` if state is destroyed.\n */\n type EffectCallback = (update: boolean | null) => void;\n\n /**\n * A list of keys updated, or events fired, since last update.\n * This may be awaited to get full list (same array) when update is settled.\n */\n type Updated<T extends State> = readonly Event<T>[] &\n PromiseLike<readonly Event<T>[]>;\n}\n\nabstract class State {\n /**\n * Whether an instance activated with no enclosing context registers itself\n * to the process-global root, where `get()` can resolve it from anywhere.\n * `false` (the default) keeps a context-less instance fully functional but\n * private - not injectable, though it can still read declared globals. Opt in\n * with `static readonly global = true`; a resolver (see {@link State.Global})\n * makes the choice conditional. It must be declared per class - a subclass\n * that would inherit a global without its own declaration throws on\n * activation, so an accidental global (a forgotten `Provider`, an extended\n * global) cannot leak into the shared root.\n */\n static readonly global: State.Global = false;\n\n /**\n * Loopback to instance of this state. This is useful when in a subscribed context,\n * to keep write access to `this` after a destructure. You can use it to read variables silently as well.\n **/\n declare is: this;\n\n constructor(...args: State.Args) {\n define(this, 'is', { value: this });\n init(this, args, this.new);\n }\n\n /**\n * Optional lifecycle hook called during State initialization.\n * Can return a cleanup function to run when state is destroyed.\n *\n * It is recommended you protect this method.\n */\n protected new?(): void | (() => void);\n\n /**\n * Pull current values from state. Flattens all states and exotic values recursively.\n *\n * @returns Object with all values from this state.\n **/\n get(): State.Values<this>;\n\n /**\n * Run a function to run automatically when accessed values change.\n *\n * @param effect Function to run, and whenever accessed values change.\n * If effect returns a function, it will be called when a change occurs (syncronously),\n * effect is cancelled, or parent state is destroyed.\n * @returns Function to cancel listener.\n */\n get(effect: State.Effect<this>): () => void;\n\n /**\n * Get value of a property. Will fetch underlying value from exotic values like ref.Object.\n *\n * Any value which implements `get()` (with no arguments) will be treated as such.\n *\n * @param key - Property to get value of.\n * @param required - If true, will throw an error if property is not available.\n * @returns Value of property.\n */\n get<T extends State.Event<this>>(\n key: T,\n required?: boolean\n ): State.Value<this, T>;\n\n /**\n * Check if state is destroyed.\n *\n * @param status - `null` to check if state is destroyed.\n * @returns `true` if state is destroyed, `false` otherwise.\n */\n get(status: null): boolean;\n\n /**\n * Callback when state is to be destroyed.\n *\n * @param callback - Function to call when state is destroyed.\n * @returns Function to cancel listener.\n */\n get(status: null, callback: () => void): () => void;\n\n /** Fetch State of type from context. Throws if not found. */\n get<T extends State>(type: State.Type<T>, required?: true): T;\n\n /** Fetch a State from context. Undefined if not found. */\n get<T extends State>(type: State.Type<T>, required: boolean): T | undefined;\n\n /**\n * Subscribe to State becoming available in context.\n *\n * Will search both up and downstream by default.\n * Normally you can ignore this because State you expect is rarely both.\n *\n * Specify downstream if you only want to watch for State in children, which can be useful if you expect multiple of the same State in different branches of the tree.\n *\n * @param type - Type of State to watch for.\n * @param callback - Function to call when State is found. Will be called immediately if State is already available.\n * @param downstream - If true, will only watch for State in children, if false will only for parents.\n * @returns Function to cancel listener.\n */\n get<T extends State>(\n type: State.Type<T>,\n callback: Context.Expect<T>,\n downstream?: boolean\n ): () => void;\n\n get(\n arg1?: State.Effect<this> | State.Type | string | null,\n arg2?: boolean | Context.Expect | (() => void),\n arg3?: boolean\n ) {\n const self = this.is;\n\n if (arg1 === undefined) return values(self);\n if (State.is(arg1)) return Context.get(self).get(arg1, arg2, arg3, self);\n if (typeof arg1 == 'function') return watch(self, unbind(arg1));\n if (typeof arg2 == 'function') return callback(self, arg2, arg1);\n if (arg1 === null) return observer(self) === null;\n return access(self, arg1, arg2);\n }\n\n /**\n * Get update in progress.\n *\n * @returns Promise which resolves object with updated values, `undefined` if there no update is pending.\n **/\n set(): State.Updated<this>;\n\n /**\n * Merge argument with current state, updating one or more properties at once.\n * Properties which are not managed by this state will be ignored.\n *\n * @param assign - Object with properties to update.\n * @param silent - If true, listeners will not be notified. If state is destroyed, drops the update without reporting it.\n * @returns Array of keys updated, syncronously contains keys updated immediately and may be resolved (to itself) when all updates are settled.\n */\n set(assign?: State.Assign<this>, silent?: boolean): State.Updated<this>;\n\n /**\n * Call a function when update occurs.\n *\n * Given function is called for every assignment (which changes value) or explicit `set`.\n *\n * To run logic on final value only, callback may return a function. The same\n * function for one or more events will be called only once when update is settled.\n *\n * Return `null` from callback to stop listening.\n *\n * @param callback - Function to call when update occurs.\n * @returns Function to remove listener. Will return `true` if removed, `false` if inactive already.\n */\n set(callback: State.OnEvent<this>): () => boolean;\n\n /**\n * Push an update. This will not change the value of associated property.\n *\n * Useful where a property value internally has changed, but the object is the same.\n * For example: An array has pushed a new value, or a nested property is updated.\n *\n * You can also use this to dispatch arbitrary events.\n * Symbols are recommended as non-property events, however you can use any string.\n * If doing so, be sure to avoid collisions using property names. An easy way to do this is\n * to prefix an event with \"!\" and/or use dash-case. e.g. `set(\"!event\")` or `set(\"my-event\")`.\n *\n * @param key - Property or event to dispatch.\n * @returns Promise resolves an array of keys updated.\n */\n set(key: State.Event<this>): State.Updated<this>;\n\n /**\n * Declare an end to updates. This event is final and will freeze state.\n * This event can be watched for as well, to run cleanup logic and internally will remove all listeners.\n *\n * @param status - `null` to end updates.\n */\n set(status: null): void;\n\n /**\n * Register a callback for a specific property or event.\n *\n * Callback receives the key, current value, and source instance.\n *\n * @param event - Property or event to watch. If `null`, will callback on destroy.\n * @param callback - Function to call when event occurs.\n * @returns Function to remove listener.\n */\n set<K extends State.Event<this>>(\n event: K | null,\n callback: State.OnEvent<this>\n ): () => boolean;\n\n /**\n * Define or update a managed property using a descriptor config.\n * If the property already is managed, config will only accept value.\n * If the property does not exist, it will be created and made reactive.\n *\n * @param key - Property to define or update.\n * @param config - Descriptor config with value, get, set, enumerable, and/or destroy.\n * @returns Promise resolves an array of keys updated.\n */\n set<K extends State.Event<this>>(\n key: K,\n config: State.Define<this, K>\n ): State.Updated<this>;\n\n set(\n arg1?: State.OnEvent<this> | State.Assign<this> | State.Event<this> | null,\n arg2?: unknown\n ) {\n const self = this.is;\n\n if (typeof arg1 == 'function')\n return listener(self, (key) => {\n if (\n typeof key == 'string' ||\n typeof key == 'number' ||\n typeof key == 'symbol'\n )\n return arg1.call(self, key, self);\n });\n\n if (typeof arg2 == 'function')\n return callback(self, arg2, arg1 as State.Signal);\n\n if (arg1 && typeof arg1 == 'object') assign(self, arg1, arg2 === true);\n else if (arg2) apply(self, arg1 as string, arg2);\n else event(self, arg1);\n\n return queued(self) as State.Updated<this>;\n }\n\n /**\n * Iterate over managed properties in this instance of State.\n * Yeilds the key and current value for each property.\n */\n [Symbol.iterator](): Iterator<[string, unknown]> {\n return Object.entries(STORE.get(this.is)!)[Symbol.iterator]();\n }\n\n /**\n * Create and activate a new instance of this state.\n *\n * **Important** - Unlike `new this(...)` - this method also activates state.\n *\n * @param args - arguments sent to constructor\n */\n static new<T extends State>(this: State.Type<T>, ...args: State.Args<T>): T {\n const instance = new this(...args);\n event(instance);\n return instance;\n }\n\n /**\n * Static equivalent of `x instanceof this`.\n * Determines if provided class is a subtype of this one.\n * If so, language server will make available all static\n * methods and properties of this class.\n */\n static is<T extends State.Extends>(this: T, maybe: unknown): maybe is T {\n return (\n maybe === this ||\n (typeof maybe == 'function' && maybe.prototype instanceof this)\n );\n }\n\n /**\n * Register a lifecycle handler for this State and its subclasses.\n *\n * A bare function is per-instance setup run in the `prepare` phase (sugar for\n * `{ before }`); if it returns a function, that runs when the instance is\n * destroyed. Pass a {@link State.On} object to hook by cadence - `type`\n * (per-class, at bootstrap), `before` (per-instance, before `new()`), and\n * `after` (per-instance, at the `new()` slot).\n *\n * @returns Function to remove the handler.\n */\n static on<T extends State>(\n this: State.Extends<T>,\n handler: State.Init<T> | State.On<T>\n ) {\n let setup = SETUP.get(this);\n\n if (!setup) SETUP.set(this, (setup = new Set()));\n\n setup.add(handler);\n\n return () => setup.delete(handler);\n }\n}\n\ndefine(State.prototype, 'toString', {\n value() {\n return ID.get(this.is);\n }\n});\n\ndefine(State, 'toString', {\n value() {\n return this.name;\n }\n});\n\n/** Register a user OnEvent callback, preserving `this` and `source`. */\nfunction callback<T extends State>(\n self: T,\n cb: Function,\n select?: Observer.Signal | Set<Observer.Signal>\n) {\n return listener(self, (key) => cb.call(self, key, self), select);\n}\n\n/**\n * Apply state arguemnts, run callbacks and observe properties.\n * Accumulate and handle cleanup events.\n **/\nfunction init(state: State, ...args: State.Args) {\n const T = state.constructor as State.Extends;\n\n if (T === State) throw new Error('Cannot create base State.');\n\n if (!ANNOUNCED) {\n ANNOUNCED = true;\n ((globalThis as { [COPIES]?: unknown[] })[COPIES] ||= []).push(State);\n }\n\n const { before, after } = bootstrap(T);\n\n ID.set(state, `${T}-${uid()}`);\n STORE.set(state, {});\n\n function observe() {\n for (const key in state) {\n const desc: PropertyDescriptor = Object.getOwnPropertyDescriptor(state, key) || {};\n\n if ('value' in desc && desc.configurable) apply(state, key, desc, true);\n }\n }\n\n function register() {\n if (Context.get(state) !== Context.root) return;\n\n const type = state.constructor as typeof State;\n const g = type.global;\n\n if (!(typeof g == 'function' ? g(state) : g)) return;\n\n if (!Object.prototype.hasOwnProperty.call(type, 'global'))\n throw new Error(\n `${state} would register as a global by inheritance alone - re-declare \\`static global\\` on ${type.name} (\\`true\\` to keep it, \\`false\\` to opt out).`\n );\n\n return Context.root.add(state);\n }\n\n listener(state, (key) => {\n const rest = trailing(state);\n\n PENDING.delete(state);\n\n if (key === null) return null;\n\n parent(state, null);\n\n const queue = [...before, observe, ...args, ...after, register];\n\n capture((release) => {\n listener(state, () => release(null), null);\n\n for (let i = 0; i < queue.length; i++) {\n const arg = queue[i];\n const out = typeof arg == 'function' ? arg.call(state, state) : arg;\n\n if (out instanceof Promise)\n out.catch((err) => report(new Caught.Init(state, err)));\n else if (Array.isArray(out)) queue.splice(i + 1, 0, ...out);\n else if (typeof out == 'function') listener(state, out, null);\n else if (typeof out == 'object') assign(state, out, true);\n }\n });\n\n let end = rest.length;\n\n while (end-- > 0 && PENDING.has(rest[end]));\n\n for (let i = 0; i < end; i++) PENDING.delete(rest[i]);\n\n return null;\n });\n\n if (!QUEUED) {\n QUEUED = true;\n\n queueMicrotask(() => {\n QUEUED = false;\n\n for (const item of PENDING)\n if (typeof item == 'function') item();\n else report(new Caught.Inactive(item));\n\n PENDING.clear();\n });\n }\n\n PENDING.add(state);\n}\n\n/**\n * Apply instructions and inherited event listeners. Ensure class metadata is ready.\n *\n * @param T - State class to bootstrap.\n * @return Array of init functions to run on instance, in order of class hierarchy.\n */\nfunction bootstrap(T: State.Extends) {\n const chain = [] as State.Extends[];\n const before = new Set<State.Init>();\n const after = new Set<State.Init>();\n const onType = new Set<NonNullable<State.On['type']>>();\n let keys = new Map<string, (value: any) => void>();\n let getters = new Map<string, () => unknown>();\n\n while (true) {\n chain.unshift(T);\n if (T === State) break;\n T = Object.getPrototypeOf(T);\n }\n\n for (const type of chain) {\n for (const handler of SETUP.get(type) || [])\n if (typeof handler == 'function') before.add(handler);\n else {\n if (handler.before) before.add(handler.before);\n if (handler.after) after.add(handler.after);\n if (handler.type) onType.add(handler.type);\n }\n\n if (type === State) continue;\n\n if (METHODS.has(type)) {\n keys = METHODS.get(type)!;\n getters = GETTERS.get(type)!;\n continue;\n }\n\n for (const setupType of onType) setupType(type);\n\n METHODS.set(type, (keys = new Map(keys)));\n GETTERS.set(type, (getters = new Map(getters)));\n\n for (const [key, desc] of Object.entries(\n Object.getOwnPropertyDescriptors(type.prototype)\n )) {\n if (key == 'constructor' || !desc.configurable) continue;\n\n if (typeof desc.get == 'function') {\n if (desc.configurable && typeof desc.set != 'function')\n getters.set(key, desc.get);\n\n continue;\n }\n\n const { value } = desc;\n\n if (typeof value !== 'function') continue;\n\n function bind(this: State, original?: Function) {\n const { is } = this;\n\n if (is.hasOwnProperty(key) && !original) return value as Function;\n\n const fn = original || value;\n const bound = fn.bind(is);\n\n UNBIND.set(bound, fn);\n define(is, key, { value: bound, writable: true, configurable: true });\n\n return bound;\n }\n\n UNBIND.set(bind, value);\n\n keys.set(key, bind);\n define(type.prototype, key, { get: bind, set: bind });\n }\n }\n\n if (getters.size)\n before.add((self) => getters.forEach(compute, self));\n\n return { before, after };\n}\n\n/**\n * Install a reactive computed property on a state instance, derived from a prototype\n * getter or an arity-bearing `set` factory.\n *\n * The getter is invoked with the tracking proxy as both `this` and its first argument;\n * reads of managed properties through it create subscriptions. Result is cached and\n * emits a keyed event when stale.\n */\nfunction compute(this: State, getter: (self: any) => unknown, key: string) {\n const store = STORE.get(this)!;\n let reset: (() => void) | undefined;\n let isAsync: boolean;\n let proxy: any;\n\n const connect = () => {\n reset = watch(\n this,\n (current) => {\n proxy = current;\n\n if (!(key in store) || STALE.delete(run)) run(!reset);\n\n return (didUpdate) => {\n if (didUpdate) {\n STALE.add(run);\n event(this, key, true);\n }\n };\n },\n false\n );\n };\n\n const run = (initial?: boolean) => {\n let next: unknown;\n\n try {\n next = getter.call(proxy, proxy);\n } catch (err) {\n if (initial) {\n console.warn(`An exception was thrown while initializing ${this}.${key}.`);\n throw err;\n }\n\n if (!(err instanceof Promise)) report(new Caught.Getter(this, key, err));\n }\n\n update(this, key, next, !isAsync);\n };\n\n apply(\n this,\n key,\n {\n enumerable: true,\n set: false,\n get: () => {\n if (!proxy) {\n if (observer(this) === null) return store[key];\n\n connect();\n isAsync = true;\n }\n\n if (STALE.delete(run)) run();\n\n return access(this, key, !proxy);\n }\n },\n true\n );\n}\n\n/**\n * Define or update a managed property using a descriptor config.\n * If the property already is managed, config will only accept value.\n * If the property does not exist, it will be created and made reactive.\n *\n * @param state - State to apply property to.\n * @param key - Property to define or update.\n * @param config - Descriptor config with value, get, set, enumerable, and/or destroy.\n * @param silent - If an update does occur, listeners will not be refreshed automatically.\n */\nfunction apply(\n state: State,\n key: string,\n config: State.Apply,\n silent?: boolean\n) {\n const desc = Object.getOwnPropertyDescriptor(state, key);\n\n if (desc && 'get' in desc) {\n if (Object.keys(config).some((k) => k != 'value'))\n throw new Error(`Property ${key} on ${state} is already defined.`);\n if ('value' in config) update(state, key, config.value, silent);\n return;\n }\n\n function set(value: unknown, silent?: boolean) {\n update(state, key, value, silent, true);\n }\n\n define(state, key, {\n configurable: true,\n enumerable: config.enumerable !== false,\n get(this: State) {\n const value =\n typeof config.get == 'function'\n ? config.get(this)\n : access(state, key, config.get);\n\n return touch(this, key, value);\n },\n set(next: any, silent?: boolean) {\n if (config.set === false)\n throw new Error(`${state}.${String(key)} is read-only.`);\n\n if (typeof config.set == 'function')\n try {\n const output = config.set(next, STORE.get(state)![key]);\n if (output !== undefined) next = output;\n } catch (err: unknown) {\n if (err === false) return;\n if (err === true) {\n set(next, true);\n return;\n }\n throw err;\n }\n\n set(next, silent);\n }\n });\n\n if ('value' in config) set(config.value, silent);\n}\n\nfunction provides(ctx: Context, value: State) {\n while (ctx = ctx.parent!) {\n const entries = ctx.provide.get(value.constructor as State.Extends);\n if (entries) for (const [state] of entries) if (state === value) return true;\n }\n}\n\nfunction child(state: State) {\n let cleanup: (() => void) | undefined;\n const ctx = Context.get(state);\n\n function reset() {\n if (cleanup) cleanup();\n cleanup = undefined;\n }\n\n listener(state, reset, null);\n\n return (value: unknown) => {\n reset();\n\n if (!(value instanceof State)) return;\n\n if (parent(value, state)) {\n const remove = join(state, value);\n cleanup = () => {\n cancel();\n remove();\n event(value, null);\n };\n const cancel = listener(state, cleanup, null);\n } else if (!provides(ctx, value)) {\n cleanup = join(state, value);\n }\n\n event(value);\n\n CHILDREN.get(state)?.forEach((cb) => cb(value));\n };\n}\n\n/**\n * Pending States constructed after this one - in a parent, the products of\n * its own initializers, until the last one it kept.\n */\nfunction trailing(state: State) {\n const rest: State[] = [];\n let seen = false;\n\n for (const item of PENDING)\n if (!seen) seen = item === state;\n else if (item instanceof State) rest.push(item);\n\n return rest;\n}\n\n/**\n * Report States adopted by a parent - those already held, then each one\n * claimed later. Returns a callback to stop watching.\n */\nfunction children(state: State, callback: (child: State) => void) {\n const store = STORE.get(state)!;\n const keys = ADOPT.get(state);\n\n if (keys)\n for (const key of keys.keys()) {\n const value = store[key as string];\n if (value instanceof State) callback(value);\n }\n\n let set = CHILDREN.get(state);\n\n if (!set) CHILDREN.set(state, (set = new Set()));\n\n set.add(callback);\n\n return () => set!.delete(callback);\n}\n\n/** Currently accumulating export. Stores real values of placeholder properties such as ref() or child states. */\nlet EXPORT: Map<any, any> | undefined;\n\nfunction values<T extends State>(state: T): State.Values<T> {\n const values = {} as any;\n let notRecursive;\n\n if (!EXPORT) {\n notRecursive = true;\n EXPORT = new Map();\n }\n\n EXPORT.set(state, values);\n\n for (let [key, value] of state) {\n if (EXPORT.has(value)) value = EXPORT.get(value);\n else if (\n value &&\n typeof value == 'object' &&\n 'get' in value &&\n typeof value.get === 'function'\n )\n value = value.get();\n\n values[key] = value;\n }\n\n if (notRecursive) EXPORT = undefined;\n\n return Object.freeze(values);\n}\n\nfunction access(state: State, property: string, required?: boolean) {\n const store = STORE.get(state)!;\n\n if (property in store || required === false) {\n const value = store[property];\n\n if (value !== undefined || !required) return value;\n }\n\n if (METHODS.get(state.constructor)!.has(property))\n return unbind((state as any)[property]);\n\n if (observer(state) === null) return undefined;\n\n const error = new Error(`${state}.${property} is not yet available.`);\n const promise = new Promise<any>((resolve, reject) => {\n listener(state, (key) => {\n if (key === property) {\n resolve(store[key]);\n return null;\n }\n\n if (key === null) {\n reject(new Error(`${state} is destroyed.`));\n }\n });\n });\n\n throw Object.assign(promise, {\n toString: () => String(error),\n name: 'Suspense',\n message: error.message,\n stack: error.stack\n });\n}\n\nfunction assign(state: State, data: State.Assign<State>, silent?: boolean) {\n if (!silent && observer(state) !== null) event(state);\n\n const methods = METHODS.get(state.constructor)!;\n const getters = GETTERS.get(state.constructor);\n\n for (const key in data) {\n const bind = methods.get(key);\n\n if (bind) bind.call(state, data[key]);\n else if (getters?.has(key)) continue;\n else if (key in state && key !== 'is') {\n const desc: PropertyDescriptor = Object.getOwnPropertyDescriptor(state, key) || {};\n const set = desc.set as (value: any, silent?: boolean) => void;\n\n if (set) {\n set.call(state, data[key], silent);\n } else {\n (state as any)[key] = data[key];\n }\n }\n }\n}\n\n/**\n * Update a property on a state instance and notify listeners.\n *\n * This is used internally to update properties, but can also be used to update properties which are not managed by state, or to update values without triggering setters.\n *\n * A destroyed state reports the write - thrown to the writer unless a `catch` handler takes it - and returns `false`; `silent` skips both, and dispatch.\n */\nfunction update<T>(\n state: State,\n key: State.Event<T>,\n value: T,\n silent?: boolean,\n own?: boolean\n) {\n if (observer(state) === null) {\n if (!silent) report(new Caught.Destroyed(state, String(key)), true);\n return false;\n }\n\n const store = STORE.get(state)!;\n\n if (value instanceof State) value = value.is as T;\n\n if (key in store && value === store[key]) return false;\n\n store[key] = value;\n\n if (!silent) event(state, key);\n\n if (own) adopt(state, key, value);\n\n return true;\n}\n\n/**\n * Pass a caught error along `catch` handlers - most-derived class first, last registered\n * first - until one returns nothing. Passed off the end, a warning logs and anything\n * else is thrown - to the caller when `sync`, else uncaught. So is a handler's throw,\n * and one wrapping an error a handler already threw escapes that error unreported.\n */\nfunction report(caught: Caught, sync?: boolean) {\n const handlers = new Set<NonNullable<State.On['catch']>>();\n let error: Caught | void = caught;\n\n if (caught.cause instanceof Caught) return escape(caught.cause);\n\n for (let T = caught.state.constructor as State.Extends; ; T = Object.getPrototypeOf(T)) {\n for (const handler of [...(SETUP.get(T) || [])].reverse())\n if (typeof handler == 'object' && handler.catch) handlers.add(handler.catch);\n\n if (T === State) break;\n }\n\n try {\n for (const handler of handlers) if (!(error = handler.call(caught.state, error))) return;\n } catch (err) {\n if (sync) throw err;\n return escape(err);\n }\n\n if (error.warning) console.warn(error);\n else if (sync) throw error;\n else escape(error);\n}\n\nfunction escape(err: unknown) {\n queueMicrotask(() => {\n throw err;\n });\n}\n\n/** Error thrown by a handler replaying in dispatch, attributed to the State which queued it. */\nfunction fault(err: unknown, owner?: object) {\n const state = owner instanceof State ? owner : owner && PARENT.get(owner);\n\n if (state) report(new Caught.Effect(state, err));\n else escape(err);\n}\n\n/**\n * Hand a value stored by an owning writer to that property's adopter,\n * creating one the first time a State is stored there. A property which has\n * held a State keeps its adopter, so a later non-State value releases the\n * previous child.\n */\nfunction adopt(state: State, key: unknown, value: unknown) {\n let keys = ADOPT.get(state);\n\n if (!keys) {\n if (!(value instanceof State)) return;\n ADOPT.set(state, (keys = new Map()));\n }\n\n let claim = keys.get(key);\n\n if (!claim) {\n if (!(value instanceof State)) return;\n keys.set(key, (claim = child(state)));\n }\n\n claim(value);\n}\n\n/** Random alphanumberic of length 6; always starts with a letter. */\nfunction uid() {\n return (0.278 + Math.random() * 0.722)\n .toString(36)\n .substring(2, 8)\n .toUpperCase();\n}\n\nfunction unbind<T extends Function>(fn: T): T;\nfunction unbind<T extends Function>(fn?: T): T | undefined;\nfunction unbind(fn?: Function) {\n return UNBIND.get(fn) || fn;\n}\n\n/**\n * Read or claim a parent for a given child. In read mode (one argument) returns\n * the current parent, or `undefined` if never assigned. In write mode assigns\n * only if unclaimed and returns whether the assignment applied - `true` means\n * this call freshly claimed it, `false` means it was already parented.\n */\nfunction parent(child: object): State | null | undefined;\nfunction parent(child: object, value: State | null): boolean;\nfunction parent(child: object, value?: State | null) {\n if (arguments.length < 2) return PARENT.get(child as State);\n if (PARENT.has(child as State)) return false;\n PARENT.set(child as State, value ?? null);\n return true;\n}\n\nexport { event, unbind, State, parent, children, PENDING, STORE, uid, access, update,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,SAAS,MAAM,OAAc,KAAc,OAAgB;CACzD,IAAI,OAAO,MAAM,IAAI,MAAM;AAE3B,KAAI,CAAC,MAAM;AACT,MAAI,EAAE,iBAAiB,OAAQ;AAC/B,QAAM,IAAI,OAAQ,uBAAO,IAAI,KAAK,CAAE;;CAGtC,IAAI,QAAQ,KAAK,IAAI,IAAI;AAEzB,KAAI,CAAC,OAAO;AACV,MAAI,EAAE,iBAAiB,OAAQ;AAC/B,OAAK,IAAI,KAAM,QAAQ,MAAM,MAAM,CAAE;;AAGvC,OAAM,MAAM;;;AAId,SAAS,MAAM;AACb,SAAQ,OAAQ,KAAK,QAAQ,GAAG,MAC7B,SAAS,GAAG,CACZ,UAAU,GAAG,EAAE,CACf,aAAa;;AAKlB,SAAS,OAAO,IAAe;AAC7B,QAAO,OAAO,IAAI,GAAG,IAAI;;AAW3B,SAAS,OAAO,OAAe,OAAsB;AACnD,KAAI,UAAU,SAAS,EAAG,QAAO,OAAO,IAAI,MAAe;AAC3D,KAAI,OAAO,IAAI,MAAe,CAAE,QAAO;AACvC,QAAO,IAAI,OAAgB,SAAS,KAAK;AACzC,QAAO"}
|
|
1
|
+
{"version":3,"file":"state.js","names":[],"sources":["../src/state.ts"],"sourcesContent":["import { Context, join } from './context';\nimport { Caught } from './caught';\nimport {\n capture,\n event,\n listener,\n Observer,\n observer,\n queued,\n touch,\n watch\n} from './observable';\n\nconst define = Object.defineProperty;\n\n/** Register for all active states via string identifiers (usually unique). */\nconst ID = new WeakMap<State, string>();\n\n/** Internal state assigned to states. */\nconst STORE = new WeakMap<State, Record<string | number | symbol, unknown>>();\n\n/** States under construction - added on `new`, removed when activated or released.\n * Also carries work to run at the deadline, which `def` uses to bound its registry. */\nconst PENDING = new Set<State | (() => void)>();\n\n/** External lifecycle listeners for any given State class. */\ntype Handler = State.Init<any> | State.On<any>;\n\nconst SETUP = new WeakMap<State.Extends, Set<Handler>>();\n\n/** Parent-child relationships. */\nconst PARENT = new WeakMap<object, State | null>();\n\n/** Reference bound instance methods, or their getter, to real one. */\nconst UNBIND = new WeakMap<any, any>();\n\n/** List of methods defined by a given type. */\nconst METHODS = new WeakMap<Function, Map<string, (value: any) => void>>();\n\n/** List of reactive getters defined by a given type. */\nconst GETTERS = new WeakMap<Function, Map<string, () => unknown>>();\n\n/** Replacement for a getter captured by live computed properties, for hot patching. */\nconst LATEST = new WeakMap<Function, Function>();\n\n/** Method implementations replaced by a hot patch. */\nconst PAST = new WeakSet<Function>();\n\n/** Live instances, tracked once hot patching is enabled. */\nlet LIVE: Set<WeakRef<State>> | undefined;\n\n/** Bootstrapped subclasses of each class, tracked once hot patching is enabled. */\nconst SUBCLASSES = new WeakMap<Function, Set<State.Extends>>();\n\n/** Event every observer treats as watched, forcing a refresh after a hot patch. */\nconst REFRESH = Symbol.for('@expressive/mvc.refresh');\n\n/** Stale flags for compute closures awaiting refresh on next access. */\nconst STALE = new WeakSet<() => void>();\n\n/** Whether the deadline which drains `PENDING` is already queued for this tick. */\nlet QUEUED = false;\n\n/** Global list each loaded copy of this module adds its `State` to, on first construction. */\nconst COPIES = Symbol.for('@expressive/mvc');\n\nlet ANNOUNCED = false;\n\n/** Adopters for managed properties which have held a child State. */\nconst ADOPT = new WeakMap<State, Map<unknown, (value: unknown) => void>>();\nconst CHILDREN = new WeakMap<State, Set<(child: State) => void>>();\n\ndeclare namespace State {\n /** Any type of State, using own class constructor as its identifier. */\n type Extends<T extends State = State> = (abstract new (...args: any[]) => T) &\n typeof State;\n\n /** A State constructor which may be instanciated. */\n type Type<T extends State = State> = (new (...args: State.Args<T>) => T) &\n Omit<typeof State, never>;\n\n /** State constructor arguments */\n type Args<T extends State = any> = (Args<T> | Init<T> | Assign<T> | void)[];\n\n /**\n * Value of `static global`. A boolean opts a State in or out of the\n * process-global root; a resolver decides at activation, receiving the\n * instance and returning whether it registers - use it to make the choice\n * conditional (e.g. per environment). A bare literal (`= true` / `= false`)\n * seals the choice for subclasses; widen a subclass's `static global` type to\n * `State.Global` to permit a resolver or a later override.\n */\n type Global<T extends State = any> = boolean | ((self: T) => boolean);\n\n /**\n * State constructor callback - runs during activation, in argument order,\n * before the `new()` lifecycle hook (so it may configure state `new()`\n * will observe). Returned function will run when state is destroyed.\n */\n type Init<T extends State = State> = (\n this: T,\n thisArg: T\n ) => Promise<void> | (() => void) | Args<T> | Assign<T> | void;\n\n /**\n * Lifecycle handlers for `State.on`, keyed by when they run. A bare `Init`\n * function passed to `on` is sugar for `{ before }`.\n */\n interface On<T extends State = State> {\n /**\n * Per-class setup, run once when the class is first bootstrapped - before\n * its members are classified and bound. Receives the class, so a handler\n * may inspect or reshape the prototype first. A handler registered on a\n * base class runs for each subclass too.\n */\n type?(type: State.Extends<T>): void;\n\n /**\n * Per-instance setup, run in the `prepare` phase before `observe` and the\n * `new()` hook. Equivalent to passing a bare function to `on`. May return a\n * cleanup, constructor args, or an assign overlay.\n */\n before?(this: T, thisArg: T): void | (() => void) | Promise<void> | Args<T> | Assign<T>;\n\n /**\n * Per-instance setup, run at the `new()` slot - after own values are\n * observed and constructor args applied. May return a cleanup function.\n */\n after?(this: T, self: T): void | (() => void);\n\n /**\n * Receives a `Caught` mvc reports for this State or a subclass - most-derived\n * class first, last registered first. Return it (or a replacement) to pass it\n * on; return nothing to handle it; throw to let it escape uncaught. Passed off\n * the end, a warning logs and anything else is thrown - to the writer for a\n * destroyed write, else uncaught.\n */\n catch?(this: T, error: Caught): Caught | void;\n }\n\n /** Object overlay to override values and methods on a state. */\n type Assign<T> = Record<string, unknown> & {\n [K in Property<T>]?: T[K] extends (...args: infer A) => infer R\n ? (this: T, ...args: A) => R\n : T[K];\n };\n\n /** Subset of `keyof T` not defined by base State. **/\n type Property<T> = Exclude<keyof T, keyof State>;\n\n /** Managed subset of Property<T> - excludes unmanaged `_` keys. **/\n type Field<T> = Exclude<Property<T>, `_${string}`>;\n\n /** Any valid key for state, including but not limited to Field<T>. */\n type Event<T = State> = Field<T> | number | symbol | (string & {});\n\n /** Any event signal dispatched to listeners, including lifecycle meta events. */\n type Signal<T = State> = Event<T> | true | false | null;\n\n /** Export/Import compatible value for a given property in a State. */\n type Export<R> = R extends State\n ? Values<R>\n : R extends { get(): infer T }\n ? T\n : R;\n\n /**\n * Values from current state of given state.\n * Differs from `Values` as values here will drill\n * into \"real\" values held by exotics like ref.Object.\n */\n type Values<T> = { [P in Field<T>]: Export<T[P]> };\n\n /** Object comperable to data found in T. */\n type Partial<T> = { [P in Field<T>]?: Export<T[P]> };\n\n /** Value for a property applied by a state. */\n type Value<T extends State, K extends State.Event<T>> = K extends keyof T\n ? Export<T[K]>\n : unknown;\n\n type Setter<T> = (value: T, previous: T) => T | void;\n\n /** Descriptor config for a managed property. */\n type Apply<T = any> = {\n value?: T;\n get?: ((source: State) => T) | boolean;\n set?: Setter<T> | boolean;\n enumerable?: boolean;\n // destroy?: () => void;\n };\n\n /** Descriptor config for set() overload - enforces type when key is a known field. */\n type Define<T, K> = K extends Field<T> ? Apply<T[K] | Export<T[K]>> : Apply;\n\n type OnEvent<T extends State> = (\n this: T,\n key: Signal<T>,\n source: T\n ) => void | (() => void) | null;\n\n /** Exotic value, where actual value is contained within. */\n type Ref<T = any> = {\n (next: T): void;\n current: T | null;\n };\n\n /**\n * A callback function which is subscribed to parent and updates when accessed properties change.\n *\n * @param current - Current state of this state. This is a proxy which detects properties which\n * where accessed, and thus depended upon to stay current.\n *\n * @param update - Set of properties which have changed, and events fired, since last update.\n *\n * @returns A callback function which will be called when this effect is stale.\n */\n type Effect<T> = (\n this: T,\n current: T,\n update: readonly State.Event<T>[] | undefined\n ) => EffectCallback | Promise<void> | null | void;\n\n /**\n * A callback function returned by effect. Will be called when effect is stale.\n *\n * @param update - `true` if update is pending, `false` effect has been cancelled, `null` if state is destroyed.\n */\n type EffectCallback = (update: boolean | null) => void;\n\n /**\n * A list of keys updated, or events fired, since last update.\n * This may be awaited to get full list (same array) when update is settled.\n */\n type Updated<T extends State> = readonly Event<T>[] &\n PromiseLike<readonly Event<T>[]>;\n}\n\nabstract class State {\n /**\n * Whether an instance activated with no enclosing context registers itself\n * to the process-global root, where `get()` can resolve it from anywhere.\n * `false` (the default) keeps a context-less instance fully functional but\n * private - not injectable, though it can still read declared globals. Opt in\n * with `static readonly global = true`; a resolver (see {@link State.Global})\n * makes the choice conditional. It must be declared per class - a subclass\n * that would inherit a global without its own declaration throws on\n * activation, so an accidental global (a forgotten `Provider`, an extended\n * global) cannot leak into the shared root.\n */\n static readonly global: State.Global = false;\n\n /**\n * Loopback to instance of this state. This is useful when in a subscribed context,\n * to keep write access to `this` after a destructure. You can use it to read variables silently as well.\n **/\n declare is: this;\n\n constructor(...args: State.Args) {\n define(this, 'is', { value: this });\n init(this, args, this.new);\n }\n\n /**\n * Optional lifecycle hook called during State initialization.\n * Can return a cleanup function to run when state is destroyed.\n *\n * It is recommended you protect this method.\n */\n protected new?(): void | (() => void);\n\n /**\n * Pull current values from state. Flattens all states and exotic values recursively.\n *\n * @returns Object with all values from this state.\n **/\n get(): State.Values<this>;\n\n /**\n * Run a function to run automatically when accessed values change.\n *\n * @param effect Function to run, and whenever accessed values change.\n * If effect returns a function, it will be called when a change occurs (syncronously),\n * effect is cancelled, or parent state is destroyed.\n * @returns Function to cancel listener.\n */\n get(effect: State.Effect<this>): () => void;\n\n /**\n * Get value of a property. Will fetch underlying value from exotic values like ref.Object.\n *\n * Any value which implements `get()` (with no arguments) will be treated as such.\n *\n * @param key - Property to get value of.\n * @param required - If true, will throw an error if property is not available.\n * @returns Value of property.\n */\n get<T extends State.Event<this>>(\n key: T,\n required?: boolean\n ): State.Value<this, T>;\n\n /**\n * Check if state is destroyed.\n *\n * @param status - `null` to check if state is destroyed.\n * @returns `true` if state is destroyed, `false` otherwise.\n */\n get(status: null): boolean;\n\n /**\n * Callback when state is to be destroyed.\n *\n * @param callback - Function to call when state is destroyed.\n * @returns Function to cancel listener.\n */\n get(status: null, callback: () => void): () => void;\n\n /** Fetch State of type from context. Throws if not found. */\n get<T extends State>(type: State.Type<T>, required?: true): T;\n\n /** Fetch a State from context. Undefined if not found. */\n get<T extends State>(type: State.Type<T>, required: boolean): T | undefined;\n\n /**\n * Subscribe to State becoming available in context.\n *\n * Will search both up and downstream by default.\n * Normally you can ignore this because State you expect is rarely both.\n *\n * Specify downstream if you only want to watch for State in children, which can be useful if you expect multiple of the same State in different branches of the tree.\n *\n * @param type - Type of State to watch for.\n * @param callback - Function to call when State is found. Will be called immediately if State is already available.\n * @param downstream - If true, will only watch for State in children, if false will only for parents.\n * @returns Function to cancel listener.\n */\n get<T extends State>(\n type: State.Type<T>,\n callback: Context.Expect<T>,\n downstream?: boolean\n ): () => void;\n\n get(\n arg1?: State.Effect<this> | State.Type | string | null,\n arg2?: boolean | Context.Expect | (() => void),\n arg3?: boolean\n ) {\n const self = this.is;\n\n if (arg1 === undefined) return values(self);\n if (State.is(arg1)) return Context.get(self).get(arg1, arg2, arg3, self);\n if (typeof arg1 == 'function') return watch(self, unbind(arg1));\n if (typeof arg2 == 'function') return callback(self, arg2, arg1);\n if (arg1 === null) return observer(self) === null;\n return access(self, arg1, arg2);\n }\n\n /**\n * Get update in progress.\n *\n * @returns Promise which resolves object with updated values, `undefined` if there no update is pending.\n **/\n set(): State.Updated<this>;\n\n /**\n * Merge argument with current state, updating one or more properties at once.\n * Properties which are not managed by this state will be ignored.\n *\n * @param assign - Object with properties to update.\n * @param silent - If true, listeners will not be notified. If state is destroyed, drops the update without reporting it.\n * @returns Array of keys updated, syncronously contains keys updated immediately and may be resolved (to itself) when all updates are settled.\n */\n set(assign?: State.Assign<this>, silent?: boolean): State.Updated<this>;\n\n /**\n * Call a function when update occurs.\n *\n * Given function is called for every assignment (which changes value) or explicit `set`.\n *\n * To run logic on final value only, callback may return a function. The same\n * function for one or more events will be called only once when update is settled.\n *\n * Return `null` from callback to stop listening.\n *\n * @param callback - Function to call when update occurs.\n * @returns Function to remove listener. Will return `true` if removed, `false` if inactive already.\n */\n set(callback: State.OnEvent<this>): () => boolean;\n\n /**\n * Push an update. This will not change the value of associated property.\n *\n * Useful where a property value internally has changed, but the object is the same.\n * For example: An array has pushed a new value, or a nested property is updated.\n *\n * You can also use this to dispatch arbitrary events.\n * Symbols are recommended as non-property events, however you can use any string.\n * If doing so, be sure to avoid collisions using property names. An easy way to do this is\n * to prefix an event with \"!\" and/or use dash-case. e.g. `set(\"!event\")` or `set(\"my-event\")`.\n *\n * @param key - Property or event to dispatch.\n * @returns Promise resolves an array of keys updated.\n */\n set(key: State.Event<this>): State.Updated<this>;\n\n /**\n * Declare an end to updates. This event is final and will freeze state.\n * This event can be watched for as well, to run cleanup logic and internally will remove all listeners.\n *\n * @param status - `null` to end updates.\n */\n set(status: null): void;\n\n /**\n * Register a callback for a specific property or event.\n *\n * Callback receives the key, current value, and source instance.\n *\n * @param event - Property or event to watch. If `null`, will callback on destroy.\n * @param callback - Function to call when event occurs.\n * @returns Function to remove listener.\n */\n set<K extends State.Event<this>>(\n event: K | null,\n callback: State.OnEvent<this>\n ): () => boolean;\n\n /**\n * Define or update a managed property using a descriptor config.\n * If the property already is managed, config will only accept value.\n * If the property does not exist, it will be created and made reactive.\n *\n * @param key - Property to define or update.\n * @param config - Descriptor config with value, get, set, enumerable, and/or destroy.\n * @returns Promise resolves an array of keys updated.\n */\n set<K extends State.Event<this>>(\n key: K,\n config: State.Define<this, K>\n ): State.Updated<this>;\n\n set(\n arg1?: State.OnEvent<this> | State.Assign<this> | State.Event<this> | null,\n arg2?: unknown\n ) {\n const self = this.is;\n\n if (typeof arg1 == 'function')\n return listener(self, (key) => {\n if (\n typeof key == 'string' ||\n typeof key == 'number' ||\n typeof key == 'symbol' && key !== REFRESH\n )\n return arg1.call(self, key, self);\n });\n\n if (typeof arg2 == 'function')\n return callback(self, arg2, arg1 as State.Signal);\n\n if (arg1 && typeof arg1 == 'object') assign(self, arg1, arg2 === true);\n else if (arg2) apply(self, arg1 as string, arg2);\n else event(self, arg1);\n\n return queued(self) as State.Updated<this>;\n }\n\n /**\n * Iterate over managed properties in this instance of State.\n * Yeilds the key and current value for each property.\n */\n [Symbol.iterator](): Iterator<[string, unknown]> {\n return Object.entries(STORE.get(this.is)!)[Symbol.iterator]();\n }\n\n /**\n * Create and activate a new instance of this state.\n *\n * **Important** - Unlike `new this(...)` - this method also activates state.\n *\n * @param args - arguments sent to constructor\n */\n static new<T extends State>(this: State.Type<T>, ...args: State.Args<T>): T {\n const instance = new this(...args);\n event(instance);\n return instance;\n }\n\n /**\n * Static equivalent of `x instanceof this`.\n * Determines if provided class is a subtype of this one.\n * If so, language server will make available all static\n * methods and properties of this class.\n */\n static is<T extends State.Extends>(this: T, maybe: unknown): maybe is T {\n return (\n maybe === this ||\n (typeof maybe == 'function' && maybe.prototype instanceof this)\n );\n }\n\n /**\n * Register a lifecycle handler for this State and its subclasses.\n *\n * A bare function is per-instance setup run in the `prepare` phase (sugar for\n * `{ before }`); if it returns a function, that runs when the instance is\n * destroyed. Pass a {@link State.On} object to hook by cadence - `type`\n * (per-class, at bootstrap), `before` (per-instance, before `new()`), and\n * `after` (per-instance, at the `new()` slot).\n *\n * @returns Function to remove the handler.\n */\n static on<T extends State>(\n this: State.Extends<T>,\n handler: State.Init<T> | State.On<T>\n ) {\n let setup = SETUP.get(this);\n\n if (!setup) SETUP.set(this, (setup = new Set()));\n\n setup.add(handler);\n\n return () => setup.delete(handler);\n }\n}\n\ndefine(State.prototype, 'toString', {\n value() {\n return ID.get(this.is);\n }\n});\n\ndefine(State, 'toString', {\n value() {\n return this.name;\n }\n});\n\n/** Register a user OnEvent callback, preserving `this` and `source`. */\nfunction callback<T extends State>(\n self: T,\n cb: Function,\n select?: Observer.Signal | Set<Observer.Signal>\n) {\n return listener(self, (key) => cb.call(self, key, self), select);\n}\n\n/**\n * Apply state arguemnts, run callbacks and observe properties.\n * Accumulate and handle cleanup events.\n **/\nfunction init(state: State, ...args: State.Args) {\n const T = state.constructor as State.Extends;\n\n if (T === State) throw new Error('Cannot create base State.');\n\n if (!ANNOUNCED) {\n ANNOUNCED = true;\n ((globalThis as { [COPIES]?: unknown[] })[COPIES] ||= []).push(State);\n }\n\n const { before, after } = bootstrap(T);\n\n ID.set(state, `${T}-${uid()}`);\n STORE.set(state, {});\n LIVE?.add(new WeakRef(state));\n\n function observe() {\n for (const key in state) {\n const desc: PropertyDescriptor = Object.getOwnPropertyDescriptor(state, key) || {};\n\n if (!('value' in desc) || !desc.configurable) continue;\n\n if (key[0] == '_') unmanaged(state, key, desc.value);\n else apply(state, key, desc, true);\n }\n }\n\n function register() {\n if (Context.get(state) !== Context.root) return;\n\n const type = state.constructor as typeof State;\n const g = type.global;\n\n if (!(typeof g == 'function' ? g(state) : g)) return;\n\n if (!Object.prototype.hasOwnProperty.call(type, 'global'))\n throw new Error(\n `${state} would register as a global by inheritance alone - re-declare \\`static global\\` on ${type.name} (\\`true\\` to keep it, \\`false\\` to opt out).`\n );\n\n return Context.root.add(state);\n }\n\n listener(state, (key) => {\n const rest = trailing(state);\n\n PENDING.delete(state);\n\n if (key === null) return null;\n\n parent(state, null);\n\n const queue = [...before, observe, ...args, ...after, register];\n\n capture((release) => {\n listener(state, () => release(null), null);\n\n for (let i = 0; i < queue.length; i++) {\n const arg = queue[i];\n const out = typeof arg == 'function' ? arg.call(state, state) : arg;\n\n if (out instanceof Promise)\n out.catch((err) => report(new Caught.Init(state, err)));\n else if (Array.isArray(out)) queue.splice(i + 1, 0, ...out);\n else if (typeof out == 'function') listener(state, out, null);\n else if (typeof out == 'object') assign(state, out, true);\n }\n });\n\n let end = rest.length;\n\n while (end-- > 0 && PENDING.has(rest[end]));\n\n for (let i = 0; i < end; i++) PENDING.delete(rest[i]);\n\n return null;\n });\n\n if (!QUEUED) {\n QUEUED = true;\n\n queueMicrotask(() => {\n QUEUED = false;\n\n for (const item of PENDING)\n if (typeof item == 'function') item();\n else report(new Caught.Inactive(item));\n\n PENDING.clear();\n });\n }\n\n PENDING.add(state);\n}\n\nfunction unmanaged(state: State, key: string, value: unknown) {\n define(state, key, {\n configurable: true,\n enumerable: false,\n get: () => value,\n set: (next) => { value = next }\n });\n}\n\n/**\n * Apply instructions and inherited event listeners. Ensure class metadata is ready.\n *\n * @param T - State class to bootstrap.\n * @return Array of init functions to run on instance, in order of class hierarchy.\n */\nfunction bootstrap(T: State.Extends) {\n const chain = [] as State.Extends[];\n const before = new Set<State.Init>();\n const after = new Set<State.Init>();\n const onType = new Set<NonNullable<State.On['type']>>();\n let keys = new Map<string, (value: any) => void>();\n let getters = new Map<string, () => unknown>();\n\n while (true) {\n chain.unshift(T);\n if (T === State) break;\n T = Object.getPrototypeOf(T);\n }\n\n for (const type of chain) {\n for (const handler of SETUP.get(type) || [])\n if (typeof handler == 'function') before.add(handler);\n else {\n if (handler.before) before.add(handler.before);\n if (handler.after) after.add(handler.after);\n if (handler.type) onType.add(handler.type);\n }\n\n if (type === State) continue;\n\n if (METHODS.has(type)) {\n keys = METHODS.get(type)!;\n getters = GETTERS.get(type)!;\n continue;\n }\n\n for (const setupType of onType) setupType(type);\n\n if (LIVE) {\n const parent = Object.getPrototypeOf(type);\n let children = SUBCLASSES.get(parent);\n\n if (!children) SUBCLASSES.set(parent, (children = new Set()));\n children.add(type);\n }\n\n METHODS.set(type, (keys = new Map(keys)));\n GETTERS.set(type, (getters = new Map(getters)));\n\n classify(type, keys, getters);\n }\n\n if (getters.size)\n before.add((self) => getters.forEach(compute, self));\n\n return { before, after };\n}\n\n/** Bind own configurable methods of a type and collect its reactive getters. */\nfunction classify(\n type: State.Extends,\n keys: Map<string, (value: any) => void>,\n getters: Map<string, () => unknown>\n) {\n for (const [key, desc] of Object.entries(\n Object.getOwnPropertyDescriptors(type.prototype)\n )) {\n if (key == 'constructor' || !desc.configurable) continue;\n\n const { get, set } = desc;\n\n if (key[0] == '_' && (get || set)) {\n define(type.prototype, key, {\n ...desc,\n get: get && function (this: State) { return get.call(this.is || this) },\n set: set && function (this: State, value: unknown) { set.call(this.is || this, value) }\n });\n\n continue;\n }\n\n if (typeof get == 'function') {\n if (typeof set != 'function') getters.set(key, get);\n\n continue;\n }\n\n const { value } = desc;\n\n if (typeof value !== 'function') continue;\n\n function bind(this: State, original?: Function) {\n const { is } = this;\n\n if (is.hasOwnProperty(key) && !original) return value as Function;\n\n const fn = original || value;\n const bound = fn.bind(is);\n\n UNBIND.set(bound, fn);\n define(is, key, { value: bound, writable: true, configurable: true });\n\n return bound;\n }\n\n UNBIND.set(bind, value);\n\n keys.set(key, bind);\n define(type.prototype, key, { get: bind, set: bind });\n }\n}\n\n/**\n * Install a reactive computed property on a state instance, derived from a prototype\n * getter or an arity-bearing `set` factory.\n *\n * The getter is invoked with the tracking proxy as both `this` and its first argument;\n * reads of managed properties through it create subscriptions. Result is cached and\n * emits a keyed event when stale.\n */\nfunction compute(this: State, getter: (self: any) => unknown, key: string) {\n const store = STORE.get(this)!;\n let reset: (() => void) | undefined;\n let isAsync: boolean;\n let proxy: any;\n\n const connect = () => {\n reset = watch(\n this,\n (current) => {\n proxy = current;\n\n if (!(key in store) || STALE.delete(run)) run(!reset);\n\n return (didUpdate) => {\n if (didUpdate) {\n STALE.add(run);\n event(this, key, true);\n }\n };\n },\n false\n );\n };\n\n const run = (initial?: boolean) => {\n let next: unknown;\n\n try {\n next = latest(getter).call(proxy, proxy);\n } catch (err) {\n if (initial) {\n console.warn(`An exception was thrown while initializing ${this}.${key}.`);\n throw err;\n }\n\n if (!(err instanceof Promise)) report(new Caught.Getter(this, key, err));\n }\n\n update(this, key, next, !isAsync);\n };\n\n apply(\n this,\n key,\n {\n enumerable: true,\n set: false,\n get: () => {\n if (!proxy) {\n if (observer(this) === null) return store[key];\n\n connect();\n isAsync = true;\n }\n\n if (STALE.delete(run)) run();\n\n return access(this, key, !proxy);\n }\n },\n true\n );\n}\n\n/**\n * Define or update a managed property using a descriptor config.\n * If the property already is managed, config will only accept value.\n * If the property does not exist, it will be created and made reactive.\n *\n * @param state - State to apply property to.\n * @param key - Property to define or update.\n * @param config - Descriptor config with value, get, set, enumerable, and/or destroy.\n * @param silent - If an update does occur, listeners will not be refreshed automatically.\n */\nfunction apply(\n state: State,\n key: string,\n config: State.Apply,\n silent?: boolean\n) {\n const desc = Object.getOwnPropertyDescriptor(state, key);\n\n if (desc && 'get' in desc) {\n if (Object.keys(config).some((k) => k != 'value'))\n throw new Error(`Property ${key} on ${state} is already defined.`);\n if ('value' in config) update(state, key, config.value, silent);\n return;\n }\n\n function set(value: unknown, silent?: boolean) {\n update(state, key, value, silent, true);\n }\n\n define(state, key, {\n configurable: true,\n enumerable: config.enumerable !== false,\n get(this: State) {\n const value =\n typeof config.get == 'function'\n ? config.get(this)\n : access(state, key, config.get);\n\n return touch(this, key, value);\n },\n set(next: any, silent?: boolean) {\n if (config.set === false)\n throw new Error(`${state}.${String(key)} is read-only.`);\n\n if (typeof config.set == 'function')\n try {\n const output = config.set(next, STORE.get(state)![key]);\n if (output !== undefined) next = output;\n } catch (err: unknown) {\n if (err === false) return;\n if (err === true) {\n set(next, true);\n return;\n }\n throw err;\n }\n\n set(next, silent);\n }\n });\n\n if ('value' in config) set(config.value, silent);\n}\n\nfunction provides(ctx: Context, value: State) {\n while (ctx = ctx.parent!) {\n const entries = ctx.provide.get(value.constructor as State.Extends);\n if (entries) for (const [state] of entries) if (state === value) return true;\n }\n}\n\nfunction child(state: State) {\n let cleanup: (() => void) | undefined;\n const ctx = Context.get(state);\n\n function reset() {\n if (cleanup) cleanup();\n cleanup = undefined;\n }\n\n listener(state, reset, null);\n\n return (value: unknown) => {\n reset();\n\n if (!(value instanceof State)) return;\n\n if (parent(value, state)) {\n const remove = join(state, value);\n cleanup = () => {\n cancel();\n remove();\n event(value, null);\n };\n const cancel = listener(state, cleanup, null);\n } else if (!provides(ctx, value)) {\n cleanup = join(state, value);\n }\n\n event(value);\n\n CHILDREN.get(state)?.forEach((cb) => cb(value));\n };\n}\n\n/**\n * Pending States constructed after this one - in a parent, the products of\n * its own initializers, until the last one it kept.\n */\nfunction trailing(state: State) {\n const rest: State[] = [];\n let seen = false;\n\n for (const item of PENDING)\n if (!seen) seen = item === state;\n else if (item instanceof State) rest.push(item);\n\n return rest;\n}\n\n/**\n * Report States adopted by a parent - those already held, then each one\n * claimed later. Returns a callback to stop watching.\n */\nfunction children(state: State, callback: (child: State) => void) {\n const store = STORE.get(state)!;\n const keys = ADOPT.get(state);\n\n if (keys)\n for (const key of keys.keys()) {\n const value = store[key as string];\n if (value instanceof State) callback(value);\n }\n\n let set = CHILDREN.get(state);\n\n if (!set) CHILDREN.set(state, (set = new Set()));\n\n set.add(callback);\n\n return () => set!.delete(callback);\n}\n\n/** Currently accumulating export. Stores real values of placeholder properties such as ref() or child states. */\nlet EXPORT: Map<any, any> | undefined;\n\nfunction values<T extends State>(state: T): State.Values<T> {\n const values = {} as any;\n let notRecursive;\n\n if (!EXPORT) {\n notRecursive = true;\n EXPORT = new Map();\n }\n\n EXPORT.set(state, values);\n\n for (let [key, value] of state) {\n if (EXPORT.has(value)) value = EXPORT.get(value);\n else if (\n value &&\n typeof value == 'object' &&\n 'get' in value &&\n typeof value.get === 'function'\n )\n value = value.get();\n\n values[key] = value;\n }\n\n if (notRecursive) EXPORT = undefined;\n\n return Object.freeze(values);\n}\n\nfunction access(state: State, property: string, required?: boolean) {\n const store = STORE.get(state)!;\n\n if (property in store || required === false) {\n const value = store[property];\n\n if (value !== undefined || !required) return value;\n }\n\n if (METHODS.get(state.constructor)!.has(property))\n return unbind((state as any)[property]);\n\n if (observer(state) === null) return undefined;\n\n const error = new Error(`${state}.${property} is not yet available.`);\n const promise = new Promise<any>((resolve, reject) => {\n listener(state, (key) => {\n if (key === property) {\n resolve(store[key]);\n return null;\n }\n\n if (key === null) {\n reject(new Error(`${state} is destroyed.`));\n }\n });\n });\n\n throw Object.assign(promise, {\n toString: () => String(error),\n name: 'Suspense',\n message: error.message,\n stack: error.stack\n });\n}\n\nfunction assign(state: State, data: State.Assign<State>, silent?: boolean) {\n if (!silent && observer(state) !== null) event(state);\n\n const methods = METHODS.get(state.constructor)!;\n const getters = GETTERS.get(state.constructor);\n\n for (const key in data) {\n const bind = methods.get(key);\n\n if (bind) bind.call(state, data[key]);\n else if (getters?.has(key)) continue;\n else if (key in state && key !== 'is') {\n const desc: PropertyDescriptor = Object.getOwnPropertyDescriptor(state, key) || {};\n const set = desc.set as (value: any, silent?: boolean) => void;\n\n if (set) {\n set.call(state, data[key], silent);\n } else {\n Reflect.set(state, key, data[key]);\n }\n }\n }\n}\n\n/**\n * Update a property on a state instance and notify listeners.\n *\n * This is used internally to update properties, but can also be used to update properties which are not managed by state, or to update values without triggering setters.\n *\n * A destroyed state reports the write - thrown to the writer unless a `catch` handler takes it - and returns `false`; `silent` skips both, and dispatch.\n */\nfunction update<T>(\n state: State,\n key: State.Event<T>,\n value: T,\n silent?: boolean,\n own?: boolean\n) {\n if (observer(state) === null) {\n if (!silent) report(new Caught.Destroyed(state, String(key)), true);\n return false;\n }\n\n const store = STORE.get(state)!;\n\n if (value instanceof State) value = value.is as T;\n\n if (key in store && value === store[key]) return false;\n\n store[key] = value;\n\n if (!silent) event(state, key);\n\n if (own) adopt(state, key, value);\n\n return true;\n}\n\n/**\n * Pass a caught error along `catch` handlers - most-derived class first, last registered\n * first - until one returns nothing. Passed off the end, a warning logs and anything\n * else is thrown - to the caller when `sync`, else uncaught. So is a handler's throw,\n * and one wrapping an error a handler already threw escapes that error unreported.\n */\nfunction report(caught: Caught, sync?: boolean) {\n const handlers = new Set<NonNullable<State.On['catch']>>();\n let error: Caught | void = caught;\n\n if (caught.cause instanceof Caught) return escape(caught.cause);\n\n for (let T = caught.state.constructor as State.Extends; ; T = Object.getPrototypeOf(T)) {\n for (const handler of [...(SETUP.get(T) || [])].reverse())\n if (typeof handler == 'object' && handler.catch) handlers.add(handler.catch);\n\n if (T === State) break;\n }\n\n try {\n for (const handler of handlers) if (!(error = handler.call(caught.state, error))) return;\n } catch (err) {\n if (sync) throw err;\n return escape(err);\n }\n\n if (error.warning) console.warn(error);\n else if (sync) throw error;\n else escape(error);\n}\n\nfunction escape(err: unknown) {\n queueMicrotask(() => {\n throw err;\n });\n}\n\n/** Error thrown by a handler replaying in dispatch, attributed to the State which queued it. */\nfunction fault(err: unknown, owner?: object) {\n const state = owner instanceof State ? owner : owner && PARENT.get(owner);\n\n if (state) report(new Caught.Effect(state, err));\n else escape(err);\n}\n\n/**\n * Hand a value stored by an owning writer to that property's adopter,\n * creating one the first time a State is stored there. A property which has\n * held a State keeps its adopter, so a later non-State value releases the\n * previous child.\n */\nfunction adopt(state: State, key: unknown, value: unknown) {\n let keys = ADOPT.get(state);\n\n if (!keys) {\n if (!(value instanceof State)) return;\n ADOPT.set(state, (keys = new Map()));\n }\n\n let claim = keys.get(key);\n\n if (!claim) {\n if (!(value instanceof State)) return;\n keys.set(key, (claim = child(state)));\n }\n\n claim(value);\n}\n\n/** Resolve a getter to its latest hot-patched replacement. */\nfunction latest(getter: Function) {\n for (let next; (next = LATEST.get(getter)); ) getter = next;\n return getter;\n}\n\n/** Begin tracking live instances, so a hot patch can reach them. */\nfunction track() {\n LIVE ||= new Set();\n}\n\n/**\n * Move the members of `next` onto `prev`, which keeps its identity. Returns the\n * live instances of `prev`, each needing a refresh.\n */\nfunction patch(prev: State.Extends, next: State.Extends, own: Handler[]): State[] {\n const proto = prev.prototype;\n const incoming = Object.getOwnPropertyDescriptors(next.prototype);\n const keys = METHODS.get(prev);\n const getters = GETTERS.get(prev);\n const methods = new Map<string, Function>();\n const knownKeys = new Set(keys?.keys());\n const knownGetters = new Set(getters?.keys());\n\n let setup = SETUP.get(prev);\n\n for (const handler of own) setup!.delete(handler);\n\n for (const handler of handlers(next)) {\n if (!setup) SETUP.set(prev, (setup = new Set()));\n setup.add(handler);\n }\n\n for (const key of Reflect.ownKeys(next)) {\n if (key == 'prototype' || key == 'length' || key == 'name') continue;\n\n if (Object.getOwnPropertyDescriptor(prev, key)?.configurable !== false)\n define(prev, key, Object.getOwnPropertyDescriptor(next, key)!);\n }\n\n const removed = new Set<string>();\n\n for (const key of Object.getOwnPropertyNames(proto))\n if (key != 'constructor' && !(key in incoming)) {\n const bind = keys?.get(key);\n\n if (bind && Object.getOwnPropertyDescriptor(proto, key)!.get === bind) {\n PAST.add(UNBIND.get(bind));\n keys!.delete(key);\n }\n\n removed.add(key);\n Reflect.deleteProperty(proto, key);\n getters?.delete(key);\n }\n\n for (const [key, desc] of Object.entries(incoming)) {\n if (key == 'constructor') continue;\n\n const current = Object.getOwnPropertyDescriptor(proto, key);\n\n if (typeof desc.value == 'function') methods.set(key, desc.value);\n\n if (current?.configurable === false) {\n if (current.writable) (proto as any)[key] = desc.value;\n continue;\n }\n\n if (current?.get && keys?.get(key) === current.get) PAST.add(UNBIND.get(current.get));\n\n const getter = getters?.get(key);\n\n if (getter) LATEST.set(getter, desc.get!);\n\n define(proto, key, { ...desc, configurable: true });\n }\n\n if (keys) {\n for (let T: State.Extends = prev; ; T = Object.getPrototypeOf(T)) {\n for (const handler of SETUP.get(T) || [])\n if (typeof handler == 'object' && handler.type) handler.type(prev);\n\n if (T === State) break;\n }\n\n classify(prev, keys, getters!);\n }\n\n const live: State[] = [];\n\n for (const ref of LIVE!) {\n const state = ref.deref();\n\n if (!state) LIVE!.delete(ref);\n else if (state instanceof prev) live.push(state);\n }\n\n const descendants = new Set([prev, ...live.map((state) => state.constructor as State.Extends)]);\n\n for (const type of descendants) for (const child of SUBCLASSES.get(type) || []) descendants.add(child);\n\n descendants.delete(prev);\n\n for (const type of descendants) {\n const inherit = METHODS.get(type)!;\n const computed = GETTERS.get(type)!;\n\n for (const [key, bind] of keys!) if (!knownKeys.has(key) && !inherit.has(key)) inherit.set(key, bind);\n for (const [key, get] of getters!) if (!knownGetters.has(key) && !computed.has(key)) computed.set(key, get);\n for (const key of removed)\n if (!(key in type.prototype)) {\n inherit.delete(key);\n computed.delete(key);\n }\n }\n\n for (const state of live) {\n for (const [key, value] of methods) {\n const desc = Object.getOwnPropertyDescriptor(state, key);\n\n if (!desc) continue;\n\n if (desc.set) desc.set.call(state, value);\n else if (PAST.has(UNBIND.get(desc.value))) delete (state as any)[key];\n }\n\n for (const key of removed)\n if (PAST.has(UNBIND.get(Object.getOwnPropertyDescriptor(state, key)?.value))) delete (state as any)[key];\n\n for (const [key, get] of GETTERS.get(state.constructor)!)\n if (!knownGetters.has(key) && get === getters!.get(key)) compute.call(state, get, key);\n }\n\n return live;\n}\n\n/** Lifecycle handlers registered on a class itself. */\nfunction handlers(type: State.Extends): Handler[] {\n return [...(SETUP.get(type) || [])];\n}\n\n/** Random alphanumberic of length 6; always starts with a letter. */\nfunction uid() {\n return (0.278 + Math.random() * 0.722)\n .toString(36)\n .substring(2, 8)\n .toUpperCase();\n}\n\nfunction unbind<T extends Function>(fn: T): T;\nfunction unbind<T extends Function>(fn?: T): T | undefined;\nfunction unbind(fn?: Function) {\n return UNBIND.get(fn) || fn;\n}\n\n/**\n * Read or claim a parent for a given child. In read mode (one argument) returns\n * the current parent, or `undefined` if never assigned. In write mode assigns\n * only if unclaimed and returns whether the assignment applied - `true` means\n * this call freshly claimed it, `false` means it was already parented.\n */\nfunction parent(child: object): State | null | undefined;\nfunction parent(child: object, value: State | null): boolean;\nfunction parent(child: object, value?: State | null) {\n if (arguments.length < 2) return PARENT.get(child as State);\n if (PARENT.has(child as State)) return false;\n PARENT.set(child as State, value ?? null);\n return true;\n}\n\nexport { event, unbind, State, parent, children, trailing, PENDING, STORE, uid, access, update, apply, compute, fault, patch, track, handlers };\n"],"mappings":";;;;;AAaA,MAAM,SAAS,OAAO;;AAGtB,MAAM,qBAAK,IAAI,SAAwB;;AAGvC,MAAM,wBAAQ,IAAI,SAA2D;;;AAI7E,MAAM,0BAAU,IAAI,KAA2B;AAK/C,MAAM,wBAAQ,IAAI,SAAsC;;AAGxD,MAAM,yBAAS,IAAI,SAA+B;;AAGlD,MAAM,yBAAS,IAAI,SAAmB;;AAGtC,MAAM,0BAAU,IAAI,SAAsD;;AAG1E,MAAM,0BAAU,IAAI,SAA+C;;AAGnE,MAAM,yBAAS,IAAI,SAA6B;;AAGhD,MA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