@relo-ui/web 0.0.0-stage → 0.1.0-rc.1

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.
Files changed (127) hide show
  1. package/README.md +27 -2
  2. package/dist/LICENSE +202 -0
  3. package/dist/NOTICE +5 -0
  4. package/dist/core/contracts.d.ts +72 -0
  5. package/dist/core/contracts.js +76 -0
  6. package/dist/core/document.d.ts +16 -0
  7. package/dist/core/document.js +21 -0
  8. package/dist/core/engine.d.ts +8 -0
  9. package/dist/core/engine.js +28 -0
  10. package/dist/core/index.d.ts +7 -0
  11. package/dist/core/index.js +7 -0
  12. package/dist/core/runtime.d.ts +23 -0
  13. package/dist/core/runtime.js +46 -0
  14. package/dist/core/schema.d.ts +56 -0
  15. package/dist/core/schema.js +72 -0
  16. package/dist/core/session.d.ts +88 -0
  17. package/dist/core/session.js +520 -0
  18. package/dist/core/value.d.ts +18 -0
  19. package/dist/core/value.js +118 -0
  20. package/dist/dom/accessibility.d.ts +2 -0
  21. package/dist/dom/accessibility.js +69 -0
  22. package/dist/dom/icons.d.ts +1 -0
  23. package/dist/dom/icons.js +21 -0
  24. package/dist/dom/images.d.ts +59 -0
  25. package/dist/dom/images.js +406 -0
  26. package/dist/dom/index.d.ts +3 -0
  27. package/dist/dom/index.js +2 -0
  28. package/dist/dom/inputs.d.ts +5 -0
  29. package/dist/dom/inputs.js +85 -0
  30. package/dist/dom/lists.d.ts +7 -0
  31. package/dist/dom/lists.js +48 -0
  32. package/dist/dom/measurement.d.ts +16 -0
  33. package/dist/dom/measurement.js +67 -0
  34. package/dist/dom/motion-lifecycle.d.ts +17 -0
  35. package/dist/dom/motion-lifecycle.js +28 -0
  36. package/dist/dom/motion-plan.d.ts +44 -0
  37. package/dist/dom/motion-plan.js +31 -0
  38. package/dist/dom/motion.d.ts +73 -0
  39. package/dist/dom/motion.js +817 -0
  40. package/dist/dom/mount-plan.d.ts +15 -0
  41. package/dist/dom/mount-plan.js +58 -0
  42. package/dist/dom/presentation.d.ts +11 -0
  43. package/dist/dom/presentation.js +331 -0
  44. package/dist/dom/primitives.d.ts +16 -0
  45. package/dist/dom/primitives.js +378 -0
  46. package/dist/dom/range.d.ts +9 -0
  47. package/dist/dom/range.js +120 -0
  48. package/dist/dom/renderer.d.ts +99 -0
  49. package/dist/dom/renderer.js +1041 -0
  50. package/dist/dom/scroll.d.ts +7 -0
  51. package/dist/dom/scroll.js +167 -0
  52. package/dist/dom/shared-layout.d.ts +40 -0
  53. package/dist/dom/shared-layout.js +440 -0
  54. package/dist/dom/style.d.ts +35 -0
  55. package/dist/dom/style.js +337 -0
  56. package/dist/dom/text-motion.d.ts +17 -0
  57. package/dist/dom/text-motion.js +185 -0
  58. package/dist/dom/theme.d.ts +13 -0
  59. package/dist/dom/theme.js +65 -0
  60. package/dist/index.d.ts +10 -0
  61. package/dist/index.js +18 -0
  62. package/dist/licenses/Rust-COPYRIGHT-library.html +29357 -0
  63. package/dist/licenses/archery-1.2.3/LICENSE.md +21 -0
  64. package/dist/licenses/bytemuck-1.25.2/LICENSE-APACHE +61 -0
  65. package/dist/licenses/bytemuck-1.25.2/LICENSE-MIT +9 -0
  66. package/dist/licenses/bytemuck-1.25.2/LICENSE-ZLIB +11 -0
  67. package/dist/licenses/cargo.json +340 -0
  68. package/dist/licenses/cfg-if-1.0.5/LICENSE-APACHE +201 -0
  69. package/dist/licenses/cfg-if-1.0.5/LICENSE-MIT +25 -0
  70. package/dist/licenses/equivalent-1.0.2/LICENSE-APACHE +201 -0
  71. package/dist/licenses/equivalent-1.0.2/LICENSE-MIT +25 -0
  72. package/dist/licenses/futures-core-0.3.34/LICENSE-APACHE +202 -0
  73. package/dist/licenses/futures-core-0.3.34/LICENSE-MIT +26 -0
  74. package/dist/licenses/futures-task-0.3.34/LICENSE-APACHE +202 -0
  75. package/dist/licenses/futures-task-0.3.34/LICENSE-MIT +26 -0
  76. package/dist/licenses/futures-util-0.3.34/LICENSE-APACHE +202 -0
  77. package/dist/licenses/futures-util-0.3.34/LICENSE-MIT +26 -0
  78. package/dist/licenses/imbl-7.0.2/LICENCE.md +355 -0
  79. package/dist/licenses/imbl-sized-chunks-0.2.0/LICENCE.md +355 -0
  80. package/dist/licenses/itoa-1.0.18/LICENSE-APACHE +176 -0
  81. package/dist/licenses/itoa-1.0.18/LICENSE-MIT +23 -0
  82. package/dist/licenses/js-sys-0.3.106/LICENSE-APACHE +201 -0
  83. package/dist/licenses/js-sys-0.3.106/LICENSE-MIT +25 -0
  84. package/dist/licenses/memchr-2.8.3/COPYING +3 -0
  85. package/dist/licenses/memchr-2.8.3/LICENSE-MIT +21 -0
  86. package/dist/licenses/once_cell-1.21.4/LICENSE-APACHE +201 -0
  87. package/dist/licenses/once_cell-1.21.4/LICENSE-MIT +23 -0
  88. package/dist/licenses/pin-project-lite-0.2.17/LICENSE-APACHE +177 -0
  89. package/dist/licenses/pin-project-lite-0.2.17/LICENSE-MIT +23 -0
  90. package/dist/licenses/rand_core-0.9.5/COPYRIGHT +12 -0
  91. package/dist/licenses/rand_core-0.9.5/LICENSE-APACHE +187 -0
  92. package/dist/licenses/rand_core-0.9.5/LICENSE-MIT +26 -0
  93. package/dist/licenses/rand_xoshiro-0.7.0/COPYRIGHT +12 -0
  94. package/dist/licenses/rand_xoshiro-0.7.0/LICENSE-APACHE +176 -0
  95. package/dist/licenses/rand_xoshiro-0.7.0/LICENSE-MIT +25 -0
  96. package/dist/licenses/roxmltree-0.21.1/LICENSE-APACHE +201 -0
  97. package/dist/licenses/roxmltree-0.21.1/LICENSE-MIT +21 -0
  98. package/dist/licenses/safe_arch-0.7.4/LICENSE-APACHE.md +61 -0
  99. package/dist/licenses/safe_arch-0.7.4/LICENSE-MIT.md +9 -0
  100. package/dist/licenses/safe_arch-0.7.4/LICENSE-ZLIB.md +11 -0
  101. package/dist/licenses/serde-1.0.229/LICENSE-APACHE +176 -0
  102. package/dist/licenses/serde-1.0.229/LICENSE-MIT +23 -0
  103. package/dist/licenses/serde_core-1.0.229/LICENSE-APACHE +176 -0
  104. package/dist/licenses/serde_core-1.0.229/LICENSE-MIT +23 -0
  105. package/dist/licenses/serde_json-1.0.151/LICENSE-APACHE +176 -0
  106. package/dist/licenses/serde_json-1.0.151/LICENSE-MIT +23 -0
  107. package/dist/licenses/slab-0.4.12/LICENSE +25 -0
  108. package/dist/licenses/slotmap-1.1.1/LICENSE +19 -0
  109. package/dist/licenses/smallvec-1.16.3/LICENSE-APACHE +201 -0
  110. package/dist/licenses/smallvec-1.16.3/LICENSE-MIT +25 -0
  111. package/dist/licenses/taffy-0.15.0/taffy-0.15.0-LICENSE +22 -0
  112. package/dist/licenses/unicode-ident-1.0.26/LICENSE-APACHE +176 -0
  113. package/dist/licenses/unicode-ident-1.0.26/LICENSE-MIT +23 -0
  114. package/dist/licenses/unicode-ident-1.0.26/LICENSE-UNICODE +39 -0
  115. package/dist/licenses/wasm-bindgen-0.2.129/LICENSE-APACHE +201 -0
  116. package/dist/licenses/wasm-bindgen-0.2.129/LICENSE-MIT +25 -0
  117. package/dist/licenses/wasm-bindgen-shared-0.2.129/LICENSE-APACHE +201 -0
  118. package/dist/licenses/wasm-bindgen-shared-0.2.129/LICENSE-MIT +25 -0
  119. package/dist/licenses/web-time-1.1.0/LICENSE-APACHE +201 -0
  120. package/dist/licenses/web-time-1.1.0/LICENSE-MIT +21 -0
  121. package/dist/licenses/wide-0.7.33/LICENSE-ZLIB.md +11 -0
  122. package/dist/licenses/zmij-1.0.23/LICENSE-MIT +23 -0
  123. package/dist/wasm/relo_wasm.d.ts +179 -0
  124. package/dist/wasm/relo_wasm.js +1228 -0
  125. package/dist/wasm/relo_wasm_bg.wasm +0 -0
  126. package/dist/wasm/relo_wasm_bg.wasm.d.ts +65 -0
  127. package/package.json +25 -4
@@ -0,0 +1,72 @@
1
+ import { ActionError, asError, fail, snapshot } from './value.js';
2
+ function checked(result) {
3
+ if (result.issues)
4
+ fail('Invalid registered input');
5
+ return result.value;
6
+ }
7
+ export async function validate(schema, input) {
8
+ return checked(await schema['~standard'].validate(input));
9
+ }
10
+ export function validateSync(schema, input) {
11
+ const result = schema['~standard'].validate(input);
12
+ if (result && 'then' in result) {
13
+ Promise.resolve(result).catch(() => { });
14
+ fail('Props and bindings require synchronous validators');
15
+ }
16
+ return checked(result);
17
+ }
18
+ export const literal = {
19
+ number(schema) {
20
+ return { literalKind: 'number', schema };
21
+ },
22
+ boolean(schema) {
23
+ return { literalKind: 'boolean', schema };
24
+ },
25
+ };
26
+ export class NativePropError extends ActionError {
27
+ prop;
28
+ constructor(prop, message) {
29
+ super('invalidArguments', message);
30
+ this.prop = prop;
31
+ }
32
+ }
33
+ export function nativeProps(fields) {
34
+ return {
35
+ decode(props) {
36
+ for (const key of Object.keys(props))
37
+ if (!Object.hasOwn(fields, key))
38
+ throw new NativePropError(key, `Unknown native prop: ${key}`);
39
+ const result = Object.create(null);
40
+ for (const [key, field] of Object.entries(fields)) {
41
+ try {
42
+ const prop = props[key];
43
+ let value = prop?.value;
44
+ const wrapped = 'literalKind' in field;
45
+ if (wrapped && prop?.literal) {
46
+ if (typeof value !== 'string')
47
+ fail(`Invalid literal prop: ${key}`);
48
+ if (field.literalKind === 'boolean') {
49
+ if (value !== 'true' && value !== 'false')
50
+ fail(`Expected literal boolean: ${key}`);
51
+ value = value === 'true';
52
+ }
53
+ else {
54
+ if (!/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(value))
55
+ fail(`Expected literal number: ${key}`);
56
+ value = Number(value);
57
+ if (!Number.isFinite(value))
58
+ fail(`Expected finite literal: ${key}`);
59
+ }
60
+ }
61
+ const decoded = validateSync(wrapped ? field.schema : field, value);
62
+ if (decoded !== undefined)
63
+ result[key] = snapshot(decoded);
64
+ }
65
+ catch (error) {
66
+ throw new NativePropError(key, asError(error).message);
67
+ }
68
+ }
69
+ return Object.freeze(result);
70
+ },
71
+ };
72
+ }
@@ -0,0 +1,88 @@
1
+ import { getEngine } from './engine.js';
2
+ import { RemoteDocument } from './document.js';
3
+ import { type ReloRuntime } from './runtime.js';
4
+ import { type ComponentRegistration } from './contracts.js';
5
+ import { ActionError, type JsonRecord, type JsonValue } from './value.js';
6
+ export interface RenderNode {
7
+ id: string;
8
+ type: string;
9
+ props: Record<string, any>;
10
+ classes: string;
11
+ shown: boolean;
12
+ children: RenderNode[];
13
+ ref: string | null;
14
+ theme: Record<string, any>;
15
+ geometry?: {
16
+ kind: string;
17
+ values: number[];
18
+ }[] | null;
19
+ presentation_anchor?: string | null;
20
+ label_target?: string | null;
21
+ observed_events?: string[];
22
+ decoded?: any;
23
+ }
24
+ export interface Attachment {
25
+ render(graph: RenderNode): void;
26
+ command(id: string, name: string, payload: JsonValue, signal: AbortSignal): unknown | Promise<unknown>;
27
+ dispose(): void;
28
+ }
29
+ export declare class RemoteSession {
30
+ document: RemoteDocument;
31
+ private readonly engine;
32
+ readonly components: ReadonlyMap<string, ComponentRegistration<any, any>>;
33
+ private readonly actions;
34
+ private readonly bindings;
35
+ private readonly navigation?;
36
+ private readonly supported?;
37
+ private readonly unsubscribers;
38
+ private readonly errors;
39
+ private readonly events;
40
+ private readonly observers;
41
+ private readonly effects;
42
+ private readonly deferred;
43
+ private processing;
44
+ private writingBinding;
45
+ private attachment?;
46
+ private readonly owner;
47
+ private nativeInputs;
48
+ private readonly themes;
49
+ private themeBytes;
50
+ graph: RenderNode;
51
+ data: JsonRecord;
52
+ isClosed: boolean;
53
+ motionEpoch: number;
54
+ private policy;
55
+ private published?;
56
+ get motionPolicy(): ReloRuntime['motionPolicy'];
57
+ set motionPolicy(value: ReloRuntime['motionPolicy']);
58
+ constructor(runtime: ReloRuntime, document: RemoteDocument);
59
+ private host;
60
+ /** @internal Renderer journal over the accepted immutable Rust graph. */
61
+ prepareMount(tree: InstanceType<ReturnType<typeof getEngine>['WasmMountTree']>, root: string, replace: boolean): number;
62
+ private open;
63
+ private readonly graphIndex;
64
+ /** Install only accepted paths; reuse references never traverse their descendants. */
65
+ private acceptGraph;
66
+ private decode;
67
+ private mutate;
68
+ private publish;
69
+ private cancel;
70
+ private accept;
71
+ private execute;
72
+ private errorValue;
73
+ private finish;
74
+ private safe;
75
+ report(error: unknown): void;
76
+ onError(listener: (error: ActionError) => void): () => void;
77
+ onEvent(listener: (name: string, payload: JsonValue) => void): () => void;
78
+ subscribe(listener: (graph: RenderNode) => void): () => void;
79
+ dispatch(id: string, event: string, payload?: JsonValue): void;
80
+ updateData(data: JsonRecord): void;
81
+ replace(document: RemoteDocument): void;
82
+ private update;
83
+ attach(attachment: Attachment): () => void;
84
+ private detach;
85
+ close(): void;
86
+ private closeNow;
87
+ /** @internal */ componentCommand(id: string, name: string, adapter: any, payload: JsonValue, signal: AbortSignal): Promise<unknown>;
88
+ }
@@ -0,0 +1,520 @@
1
+ import { getEngine } from './engine.js';
2
+ import { NativePropError, validate } from './schema.js';
3
+ import { ActionError, asError, call, fail, record, snapshot, } from './value.js';
4
+ let ownerCounter = 0;
5
+ export class RemoteSession {
6
+ document;
7
+ engine;
8
+ components;
9
+ actions;
10
+ bindings;
11
+ navigation;
12
+ supported;
13
+ unsubscribers = [];
14
+ errors = new Set();
15
+ events = new Set();
16
+ observers = new Set();
17
+ effects = new Map();
18
+ deferred = [];
19
+ processing = false;
20
+ writingBinding = false;
21
+ attachment;
22
+ owner = `web-surface-${++ownerCounter}`;
23
+ nativeInputs = {};
24
+ themes = new Map();
25
+ themeBytes = 0;
26
+ graph;
27
+ data;
28
+ isClosed = false;
29
+ motionEpoch = 0;
30
+ policy = 'system';
31
+ published;
32
+ get motionPolicy() {
33
+ return this.policy;
34
+ }
35
+ set motionPolicy(value) {
36
+ if (!['system', 'reduced', 'off'].includes(value))
37
+ fail('Invalid motion policy');
38
+ if (this.policy === value)
39
+ return;
40
+ this.policy = value;
41
+ if (this.graph)
42
+ this.mutate(() => this.publish());
43
+ }
44
+ constructor(runtime, document) {
45
+ this.document = document;
46
+ this.components = new Map([...runtime.components].map(([name, value]) => [name, value.snapshot()]));
47
+ this.actions = new Map(runtime.actions);
48
+ this.bindings = new Map(runtime.bindings);
49
+ this.navigation = runtime.navigation;
50
+ this.policy = runtime.motionPolicy;
51
+ this.supported = runtime.supportedBuiltins;
52
+ this.data = document.data;
53
+ const requirements = JSON.parse(call(() => getEngine().requirements(document.envelope)));
54
+ const registrations = {
55
+ components: Object.fromEntries([...this.components].map(([name, value]) => [
56
+ name,
57
+ {
58
+ events: [...value.events],
59
+ commands: [...value.commands.keys()],
60
+ maximum_children: value.maximumChildren,
61
+ },
62
+ ])),
63
+ actions: [...this.actions.keys()],
64
+ bindings: [...this.bindings.keys()],
65
+ navigation: !!this.navigation,
66
+ unsupported_routes: requirements.routes.filter((route) => this.navigation?.supports?.(route) === false),
67
+ };
68
+ this.engine = call(() => new (getEngine().WasmSession)(document.envelope, JSON.stringify(registrations), JSON.stringify(this.host())));
69
+ try {
70
+ const candidate = JSON.parse(this.engine.snapshot());
71
+ this.acceptGraph(this.decode(candidate));
72
+ this.nativeInputs = candidate.native_inputs;
73
+ this.published = { graph: this.graph, epoch: this.motionEpoch, policy: this.policy };
74
+ }
75
+ catch (error) {
76
+ this.engine.shutdown();
77
+ this.engine.free();
78
+ throw error;
79
+ }
80
+ for (const binding of this.bindings.values())
81
+ this.unsubscribers.push(binding.subscribe(() => {
82
+ if (!this.isClosed && !this.writingBinding)
83
+ this.mutate(() => this.accept(this.engine.update_host(JSON.stringify(this.host()))));
84
+ }));
85
+ }
86
+ host() {
87
+ return record(Object.fromEntries([...this.bindings].map(([name, value]) => [name, value.value])));
88
+ }
89
+ /** @internal Renderer journal over the accepted immutable Rust graph. */
90
+ prepareMount(tree, root, replace) {
91
+ this.open();
92
+ return call(() => this.engine.prepare_mount(tree, root, replace));
93
+ }
94
+ open() {
95
+ if (this.isClosed)
96
+ fail('Session is closed', 'closedSession');
97
+ }
98
+ graphIndex = new Map();
99
+ /** Install only accepted paths; reuse references never traverse their descendants. */
100
+ acceptGraph(next) {
101
+ const retire = (node) => {
102
+ this.graphIndex.delete(node.id);
103
+ node.children.forEach(retire);
104
+ };
105
+ const visit = (node) => {
106
+ const old = this.graphIndex.get(node.id);
107
+ if (old === node)
108
+ return;
109
+ if (old) {
110
+ const children = new Set(node.children.map((child) => child.id));
111
+ old.children.filter((child) => !children.has(child.id)).forEach(retire);
112
+ }
113
+ this.graphIndex.set(node.id, node);
114
+ node.children.forEach(visit);
115
+ };
116
+ if (this.graph && this.graph.id !== next.id)
117
+ retire(this.graph);
118
+ visit(next);
119
+ this.graph = next;
120
+ }
121
+ decode(candidate) {
122
+ const old = this.graphIndex;
123
+ const internTheme = (value) => {
124
+ const themeKey = JSON.stringify(value);
125
+ const theme = this.themes.get(themeKey);
126
+ if (theme)
127
+ return theme;
128
+ else if (themeKey.length <= 256_000) {
129
+ while (this.themes.size &&
130
+ (this.themes.size >= 16 || this.themeBytes + themeKey.length * 2 > 1_048_576)) {
131
+ const oldest = this.themes.keys().next().value;
132
+ this.themeBytes -= oldest.length * 2;
133
+ this.themes.delete(oldest);
134
+ }
135
+ this.themes.set(themeKey, value);
136
+ this.themeBytes += themeKey.length * 2;
137
+ }
138
+ return value;
139
+ };
140
+ const themes = candidate.themes?.map(internTheme);
141
+ const visit = (encoded) => {
142
+ if ('reuse' in encoded) {
143
+ const prior = old.get(encoded.reuse);
144
+ if (!prior)
145
+ fail('Unknown retained graph node');
146
+ return prior;
147
+ }
148
+ const node = { ...encoded, children: [] };
149
+ const prior = old.get(node.id);
150
+ node.theme = typeof node.theme === 'number' ? themes[node.theme] : internTheme(node.theme);
151
+ if (prior && JSON.stringify(prior.props) === JSON.stringify(node.props))
152
+ node.props = prior.props;
153
+ const registration = this.components.get(node.type);
154
+ if (registration) {
155
+ const inputs = candidate.native_inputs[node.id];
156
+ try {
157
+ node.decoded =
158
+ JSON.stringify(inputs) === JSON.stringify(this.nativeInputs[node.id]) &&
159
+ old.has(node.id)
160
+ ? old.get(node.id).decoded
161
+ : registration.definition.props.decode(inputs);
162
+ }
163
+ catch (error) {
164
+ const diagnostic = asError(error), source = candidate.native_sources?.[node.id];
165
+ const prop = error instanceof NativePropError ? error.prop : undefined;
166
+ const span = prop
167
+ ? (source?.attributes[`bind-${prop}`] ?? source?.attributes[prop])
168
+ : undefined;
169
+ const location = span
170
+ ? `line ${span.line}, column ${span.column}, attribute ${prop}, bytes ${span.start}..${span.end}`
171
+ : source?.location;
172
+ throw new ActionError(diagnostic.code, `${node.type}: ${diagnostic.message}`, location ?? diagnostic.location);
173
+ }
174
+ }
175
+ else if (this.supported && !this.supported.has(node.type))
176
+ fail(`Web renderer does not support ${node.type}`, 'unsupportedComponent');
177
+ node.children = encoded.children.map(visit);
178
+ if (prior &&
179
+ prior.type === node.type &&
180
+ prior.props === node.props &&
181
+ prior.theme === node.theme &&
182
+ prior.classes === node.classes &&
183
+ prior.shown === node.shown &&
184
+ prior.ref === node.ref &&
185
+ prior.decoded === node.decoded &&
186
+ prior.presentation_anchor === node.presentation_anchor &&
187
+ prior.label_target === node.label_target &&
188
+ JSON.stringify(prior.geometry) === JSON.stringify(node.geometry) &&
189
+ JSON.stringify(prior.observed_events) === JSON.stringify(node.observed_events) &&
190
+ prior.children.length === node.children.length &&
191
+ node.children.every((child, index) => child === prior.children[index]))
192
+ return prior;
193
+ return node;
194
+ };
195
+ return visit(candidate.graph);
196
+ }
197
+ mutate(operation) {
198
+ this.open();
199
+ if (this.processing) {
200
+ if (this.deferred.length >= 64)
201
+ fail('Deferred mutation limit', 'limitExceeded');
202
+ this.deferred.push(operation);
203
+ return;
204
+ }
205
+ this.processing = true;
206
+ try {
207
+ operation();
208
+ for (let i = 0; this.deferred.length && !this.isClosed; i++) {
209
+ if (i >= 64) {
210
+ this.deferred.length = 0;
211
+ fail('Deferred mutation limit', 'limitExceeded');
212
+ }
213
+ this.deferred.shift()();
214
+ }
215
+ }
216
+ finally {
217
+ this.processing = false;
218
+ }
219
+ }
220
+ publish() {
221
+ if (this.published?.graph === this.graph &&
222
+ this.published.epoch === this.motionEpoch &&
223
+ this.published.policy === this.policy)
224
+ return;
225
+ this.published = { graph: this.graph, epoch: this.motionEpoch, policy: this.policy };
226
+ for (const observer of [...this.observers]) {
227
+ if (this.isClosed)
228
+ break;
229
+ try {
230
+ observer(this.graph);
231
+ }
232
+ catch (error) {
233
+ this.report(error);
234
+ }
235
+ }
236
+ if (!this.isClosed && this.attachment) {
237
+ try {
238
+ this.attachment.render(this.graph);
239
+ }
240
+ catch (error) {
241
+ this.report(error);
242
+ }
243
+ }
244
+ }
245
+ cancel(id) {
246
+ const effect = this.effects.get(id);
247
+ if (effect) {
248
+ this.effects.delete(id);
249
+ clearTimeout(effect.timer);
250
+ effect.controller.abort();
251
+ }
252
+ }
253
+ accept(raw) {
254
+ let turn = JSON.parse(raw);
255
+ let pendingEffects = [];
256
+ const pendingOutputs = [];
257
+ for (let count = 0; !this.isClosed; count++) {
258
+ if (count >= 128)
259
+ fail('Graph checkpoint limit', 'limitExceeded');
260
+ // A turn may offer effects/events alongside a candidate. Keep them until
261
+ // checkpoints settle; replacing the turn with commit() must not lose them.
262
+ pendingEffects.push(...turn.effects);
263
+ pendingOutputs.push(...turn.outputs);
264
+ pendingEffects = pendingEffects.filter((effect) => !turn.cancelled.includes(effect.id));
265
+ turn.cancelled.forEach((id) => this.cancel(id));
266
+ turn.errors.forEach((error) => this.report(new ActionError(error.code, error.message, error.location)));
267
+ if (this.isClosed)
268
+ return;
269
+ if (turn.candidate) {
270
+ const candidate = turn.candidate;
271
+ let graph;
272
+ try {
273
+ graph = this.decode(candidate);
274
+ }
275
+ catch (error) {
276
+ this.report(error);
277
+ if (this.isClosed)
278
+ return;
279
+ turn = JSON.parse(this.engine.abort());
280
+ continue;
281
+ }
282
+ if (this.isClosed)
283
+ return;
284
+ turn = JSON.parse(call(() => this.engine.commit(candidate.token)));
285
+ this.acceptGraph(graph);
286
+ this.nativeInputs = candidate.native_inputs;
287
+ this.publish();
288
+ continue;
289
+ }
290
+ for (const output of pendingOutputs)
291
+ for (const listener of [...this.events]) {
292
+ if (!this.isClosed) {
293
+ try {
294
+ listener(output.name, snapshot(output.payload));
295
+ }
296
+ catch (error) {
297
+ this.report(error);
298
+ }
299
+ }
300
+ }
301
+ pendingEffects.forEach((effect) => {
302
+ if (!this.isClosed)
303
+ this.execute(effect);
304
+ });
305
+ return;
306
+ }
307
+ }
308
+ execute(effect) {
309
+ if (this.effects.has(effect.id))
310
+ return;
311
+ const controller = new AbortController();
312
+ const timer = setTimeout(() => {
313
+ if (this.isClosed || !this.effects.has(effect.id))
314
+ return;
315
+ this.cancel(effect.id);
316
+ this.safe(() => this.accept(this.engine.timeout(effect.id)));
317
+ }, effect.timeout_ms);
318
+ this.effects.set(effect.id, { controller, timer });
319
+ const context = { signal: controller.signal };
320
+ Promise.resolve()
321
+ .then(async () => {
322
+ context.signal.throwIfAborted();
323
+ switch (effect.kind) {
324
+ case 'call': {
325
+ const action = this.actions.get(effect.name);
326
+ if (!action)
327
+ fail('Action unavailable', 'unavailable');
328
+ return action(effect.payload, context);
329
+ }
330
+ case 'command': {
331
+ if (!this.attachment || !effect.target)
332
+ fail('Surface detached', 'missingRef');
333
+ return ((await this.attachment.command(effect.target, effect.name, effect.payload, context.signal)) ?? {});
334
+ }
335
+ case 'binding': {
336
+ const binding = this.bindings.get(effect.name);
337
+ if (!binding)
338
+ fail('Binding unavailable');
339
+ this.writingBinding = true;
340
+ try {
341
+ binding.write(effect.payload);
342
+ }
343
+ finally {
344
+ this.writingBinding = false;
345
+ }
346
+ return {};
347
+ }
348
+ case 'navigate':
349
+ case 'present':
350
+ if (!this.navigation || this.navigation.supports?.(effect.name) === false)
351
+ fail('Route unavailable', 'routeUnavailable');
352
+ await this.navigation.open({
353
+ route: effect.name,
354
+ payload: effect.payload,
355
+ presentation: effect.kind === 'present' ? 'modal' : 'push',
356
+ }, context);
357
+ return {};
358
+ case 'dismiss':
359
+ if (!this.navigation)
360
+ fail('Route unavailable', 'routeUnavailable');
361
+ await this.navigation.close(context);
362
+ return {};
363
+ default:
364
+ fail('Unknown effect');
365
+ }
366
+ })
367
+ .then((result) => {
368
+ try {
369
+ this.finish(effect, { result: snapshot(result) });
370
+ }
371
+ catch (error) {
372
+ this.finish(effect, { error: this.errorValue(error) });
373
+ }
374
+ }, (error) => this.finish(effect, { error: this.errorValue(error) }))
375
+ .catch((error) => this.report(error));
376
+ }
377
+ errorValue(error) {
378
+ const result = asError(error);
379
+ return { code: result.code, message: result.message, location: result.location ?? null };
380
+ }
381
+ finish(effect, completion) {
382
+ if (this.isClosed || !this.effects.has(effect.id))
383
+ return;
384
+ const pending = this.effects.get(effect.id);
385
+ clearTimeout(pending.timer);
386
+ this.effects.delete(effect.id);
387
+ this.safe(() => {
388
+ this.accept(this.engine.complete(effect.id, JSON.stringify(completion)));
389
+ if (effect.kind === 'binding' && !this.isClosed)
390
+ this.accept(this.engine.update_host(JSON.stringify(this.host())));
391
+ });
392
+ }
393
+ safe(operation) {
394
+ try {
395
+ this.mutate(operation);
396
+ }
397
+ catch (error) {
398
+ this.report(error);
399
+ }
400
+ }
401
+ report(error) {
402
+ const value = asError(error);
403
+ for (const listener of [...this.errors]) {
404
+ try {
405
+ listener(value);
406
+ }
407
+ catch {
408
+ /* Error observers cannot recursively report themselves. */
409
+ }
410
+ }
411
+ }
412
+ onError(listener) {
413
+ this.errors.add(listener);
414
+ return () => this.errors.delete(listener);
415
+ }
416
+ onEvent(listener) {
417
+ this.events.add(listener);
418
+ return () => this.events.delete(listener);
419
+ }
420
+ subscribe(listener) {
421
+ this.observers.add(listener);
422
+ return () => this.observers.delete(listener);
423
+ }
424
+ dispatch(id, event, payload = {}) {
425
+ const encoded = JSON.stringify(snapshot(payload));
426
+ this.safe(() => this.accept(call(() => this.engine.dispatch(id, event, encoded))));
427
+ }
428
+ updateData(data) {
429
+ const next = record(data);
430
+ this.mutate(() => this.update(this.engine.prepare_update(JSON.stringify(next)), () => {
431
+ this.data = next;
432
+ }));
433
+ }
434
+ replace(document) {
435
+ this.mutate(() => this.update(this.engine.prepare_replace(document.envelope), () => {
436
+ this.document = document;
437
+ this.data = document.data;
438
+ this.motionEpoch++;
439
+ }));
440
+ }
441
+ update(raw, commit) {
442
+ const candidate = JSON.parse(raw);
443
+ let graph;
444
+ try {
445
+ graph = this.decode(candidate);
446
+ }
447
+ catch (error) {
448
+ this.accept(this.engine.abort());
449
+ throw error;
450
+ }
451
+ const turn = call(() => this.engine.commit(candidate.token));
452
+ commit();
453
+ this.acceptGraph(graph);
454
+ this.nativeInputs = candidate.native_inputs;
455
+ this.publish();
456
+ this.accept(turn);
457
+ }
458
+ attach(attachment) {
459
+ this.open();
460
+ if (this.attachment)
461
+ fail('Session already attached', 'attachmentConflict');
462
+ call(() => this.engine.attach(this.owner, true));
463
+ this.attachment = attachment;
464
+ try {
465
+ attachment.render(this.graph);
466
+ }
467
+ catch (error) {
468
+ this.detach();
469
+ throw error;
470
+ }
471
+ return () => {
472
+ if (this.attachment === attachment)
473
+ this.detach();
474
+ };
475
+ }
476
+ detach() {
477
+ const attachment = this.attachment;
478
+ this.attachment = undefined;
479
+ if (!this.isClosed)
480
+ this.engine.detach(this.owner);
481
+ attachment?.dispose();
482
+ }
483
+ close() {
484
+ if (this.isClosed)
485
+ return;
486
+ if (this.processing) {
487
+ this.deferred.push(() => this.closeNow());
488
+ return;
489
+ }
490
+ this.closeNow();
491
+ }
492
+ closeNow() {
493
+ if (this.isClosed)
494
+ return;
495
+ this.isClosed = true;
496
+ this.engine.shutdown();
497
+ this.detach();
498
+ this.effects.forEach((_, id) => this.cancel(id));
499
+ this.unsubscribers.forEach((unsubscribe) => unsubscribe());
500
+ this.observers.clear();
501
+ this.events.clear();
502
+ this.errors.clear();
503
+ this.deferred.length = 0;
504
+ this.graphIndex.clear();
505
+ this.themes.clear();
506
+ this.themeBytes = 0;
507
+ this.published = undefined;
508
+ this.engine.free();
509
+ }
510
+ /** @internal */ async componentCommand(id, name, adapter, payload, signal) {
511
+ const find = (node) => node.id === id ? node : node.children.map(find).find(Boolean);
512
+ const node = find(this.graph);
513
+ const command = node && this.components.get(node.type)?.commands.get(name);
514
+ if (!command)
515
+ fail('Command unavailable', 'missingRef');
516
+ const input = await validate(command.input, payload);
517
+ signal.throwIfAborted();
518
+ return command.handler(adapter, input, { signal });
519
+ }
520
+ }
@@ -0,0 +1,18 @@
1
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
2
+ [key: string]: JsonValue;
3
+ };
4
+ export type JsonRecord = {
5
+ [key: string]: JsonValue;
6
+ };
7
+ export declare class ActionError extends Error {
8
+ readonly code: string;
9
+ readonly location?: string | undefined;
10
+ constructor(code: string, message: string, location?: string | undefined);
11
+ }
12
+ export declare function asError(error: unknown): ActionError;
13
+ export declare function fail(message: string, code?: string): never;
14
+ export declare function call<T>(operation: () => T): T;
15
+ /** Snapshot before crossing the engine boundary; never invoke getters or toJSON. */
16
+ export declare function snapshot(value: unknown): JsonValue;
17
+ export declare function record(value: unknown): JsonRecord;
18
+ export declare function equal(a: JsonValue, b: JsonValue): boolean;