@niscorp/nova 0.1.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/ACTION_DOCS.md +552 -0
- package/ADAPTER.md +170 -0
- package/DESIGN.md +719 -0
- package/I18N_DOCS.md +224 -0
- package/LAYOUT_DOCS.md +505 -0
- package/LICENSE +202 -0
- package/REACT_DOCS.md +562 -0
- package/README.md +379 -0
- package/SHELL_DOCS.md +615 -0
- package/TERMINAL_DOCS.md +124 -0
- package/dist/adapters/dom/components/index.cjs +473 -0
- package/dist/adapters/dom/components/index.cjs.map +1 -0
- package/dist/adapters/dom/components/index.d.cts +48 -0
- package/dist/adapters/dom/components/index.d.ts +48 -0
- package/dist/adapters/dom/components/index.js +420 -0
- package/dist/adapters/dom/components/index.js.map +1 -0
- package/dist/adapters/dom/index.cjs +171 -0
- package/dist/adapters/dom/index.cjs.map +1 -0
- package/dist/adapters/dom/index.d.cts +29 -0
- package/dist/adapters/dom/index.d.ts +29 -0
- package/dist/adapters/dom/index.js +15 -0
- package/dist/adapters/dom/index.js.map +1 -0
- package/dist/adapters/dom/server.cjs +129 -0
- package/dist/adapters/dom/server.cjs.map +1 -0
- package/dist/adapters/dom/server.d.cts +15 -0
- package/dist/adapters/dom/server.d.ts +15 -0
- package/dist/adapters/dom/server.js +37 -0
- package/dist/adapters/dom/server.js.map +1 -0
- package/dist/adapters/ink/index.d.ts +75 -0
- package/dist/adapters/ink/index.js +472 -0
- package/dist/adapters/ink/index.js.map +1 -0
- package/dist/adapters/react/components/index.cjs +552 -0
- package/dist/adapters/react/components/index.cjs.map +1 -0
- package/dist/adapters/react/components/index.d.cts +30 -0
- package/dist/adapters/react/components/index.d.ts +30 -0
- package/dist/adapters/react/components/index.js +12 -0
- package/dist/adapters/react/components/index.js.map +1 -0
- package/dist/adapters/react/index.cjs +1526 -0
- package/dist/adapters/react/index.cjs.map +1 -0
- package/dist/adapters/react/index.d.cts +149 -0
- package/dist/adapters/react/index.d.ts +149 -0
- package/dist/adapters/react/index.js +12 -0
- package/dist/adapters/react/index.js.map +1 -0
- package/dist/adapters/tty/components/index.cjs +255 -0
- package/dist/adapters/tty/components/index.cjs.map +1 -0
- package/dist/adapters/tty/components/index.d.cts +40 -0
- package/dist/adapters/tty/components/index.d.ts +40 -0
- package/dist/adapters/tty/components/index.js +187 -0
- package/dist/adapters/tty/components/index.js.map +1 -0
- package/dist/adapters/tty/index.cjs +76 -0
- package/dist/adapters/tty/index.cjs.map +1 -0
- package/dist/adapters/tty/index.d.cts +47 -0
- package/dist/adapters/tty/index.d.ts +47 -0
- package/dist/adapters/tty/index.js +76 -0
- package/dist/adapters/tty/index.js.map +1 -0
- package/dist/adapters/vue/components/index.cjs +619 -0
- package/dist/adapters/vue/components/index.cjs.map +1 -0
- package/dist/adapters/vue/components/index.d.cts +224 -0
- package/dist/adapters/vue/components/index.d.ts +224 -0
- package/dist/adapters/vue/components/index.js +12 -0
- package/dist/adapters/vue/components/index.js.map +1 -0
- package/dist/adapters/vue/index.cjs +747 -0
- package/dist/adapters/vue/index.cjs.map +1 -0
- package/dist/adapters/vue/index.d.cts +98 -0
- package/dist/adapters/vue/index.d.ts +98 -0
- package/dist/adapters/vue/index.js +127 -0
- package/dist/adapters/vue/index.js.map +1 -0
- package/dist/agent/index.cjs +178 -0
- package/dist/agent/index.cjs.map +1 -0
- package/dist/agent/index.d.cts +28 -0
- package/dist/agent/index.d.ts +28 -0
- package/dist/agent/index.js +30 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/chunk-2MNLEL45.js +47 -0
- package/dist/chunk-2MNLEL45.js.map +1 -0
- package/dist/chunk-3HGE3VWK.js +753 -0
- package/dist/chunk-3HGE3VWK.js.map +1 -0
- package/dist/chunk-4ZID7UX5.js +549 -0
- package/dist/chunk-4ZID7UX5.js.map +1 -0
- package/dist/chunk-7B3RDENH.js +1982 -0
- package/dist/chunk-7B3RDENH.js.map +1 -0
- package/dist/chunk-7S5BNPUS.js +54 -0
- package/dist/chunk-7S5BNPUS.js.map +1 -0
- package/dist/chunk-7TS3YVQR.js +114 -0
- package/dist/chunk-7TS3YVQR.js.map +1 -0
- package/dist/chunk-EG2RUXJN.js +266 -0
- package/dist/chunk-EG2RUXJN.js.map +1 -0
- package/dist/chunk-GVBBL36G.js +429 -0
- package/dist/chunk-GVBBL36G.js.map +1 -0
- package/dist/chunk-I5D2R5UA.js +753 -0
- package/dist/chunk-I5D2R5UA.js.map +1 -0
- package/dist/chunk-IGLCWXQ3.js +304 -0
- package/dist/chunk-IGLCWXQ3.js.map +1 -0
- package/dist/chunk-JI7ZRESP.js +64 -0
- package/dist/chunk-JI7ZRESP.js.map +1 -0
- package/dist/chunk-L5223LLX.js +31 -0
- package/dist/chunk-L5223LLX.js.map +1 -0
- package/dist/chunk-LA3BSEMX.js +1905 -0
- package/dist/chunk-LA3BSEMX.js.map +1 -0
- package/dist/chunk-OAMC6R6E.js +121 -0
- package/dist/chunk-OAMC6R6E.js.map +1 -0
- package/dist/chunk-OGD5CCMZ.js +62 -0
- package/dist/chunk-OGD5CCMZ.js.map +1 -0
- package/dist/chunk-PF4OJTYU.js +199 -0
- package/dist/chunk-PF4OJTYU.js.map +1 -0
- package/dist/chunk-PZ5AY32C.js +9 -0
- package/dist/chunk-PZ5AY32C.js.map +1 -0
- package/dist/chunk-RBU5PHN4.js +8 -0
- package/dist/chunk-RBU5PHN4.js.map +1 -0
- package/dist/chunk-RQB4PRPV.js +285 -0
- package/dist/chunk-RQB4PRPV.js.map +1 -0
- package/dist/chunk-V32EVEVM.js +464 -0
- package/dist/chunk-V32EVEVM.js.map +1 -0
- package/dist/chunk-ZITHBBF3.js +85 -0
- package/dist/chunk-ZITHBBF3.js.map +1 -0
- package/dist/devtools/index.cjs +1088 -0
- package/dist/devtools/index.cjs.map +1 -0
- package/dist/devtools/index.d.cts +33 -0
- package/dist/devtools/index.d.ts +33 -0
- package/dist/devtools/index.js +399 -0
- package/dist/devtools/index.js.map +1 -0
- package/dist/effects-CndX9K7D.d.cts +123 -0
- package/dist/effects-CndX9K7D.d.ts +123 -0
- package/dist/endpoints-CD-6Jl-H.d.ts +36 -0
- package/dist/endpoints-Dem-EdRx.d.cts +36 -0
- package/dist/i18n/index.cjs +299 -0
- package/dist/i18n/index.cjs.map +1 -0
- package/dist/i18n/index.d.cts +28 -0
- package/dist/i18n/index.d.ts +28 -0
- package/dist/i18n/index.js +180 -0
- package/dist/i18n/index.js.map +1 -0
- package/dist/index-CNfzSBe2.d.ts +93 -0
- package/dist/index-caZoXSwr.d.cts +93 -0
- package/dist/index.cjs +3723 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +144 -0
- package/dist/index.d.ts +144 -0
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -0
- package/dist/migrations/index.cjs +635 -0
- package/dist/migrations/index.cjs.map +1 -0
- package/dist/migrations/index.d.cts +97 -0
- package/dist/migrations/index.d.ts +97 -0
- package/dist/migrations/index.js +50 -0
- package/dist/migrations/index.js.map +1 -0
- package/dist/palette-CP0wd3bE.d.ts +15 -0
- package/dist/palette-lm0bU9i5.d.cts +15 -0
- package/dist/primitive-props-BH_EJWIe.d.cts +100 -0
- package/dist/primitive-props-BH_EJWIe.d.ts +100 -0
- package/dist/primitive-props-CGoJvmcH.d.cts +100 -0
- package/dist/primitive-props-CGoJvmcH.d.ts +100 -0
- package/dist/reflect/index.cjs +998 -0
- package/dist/reflect/index.cjs.map +1 -0
- package/dist/reflect/index.d.cts +125 -0
- package/dist/reflect/index.d.ts +125 -0
- package/dist/reflect/index.js +13 -0
- package/dist/reflect/index.js.map +1 -0
- package/dist/schemas-DPdeFlCT.d.cts +38 -0
- package/dist/schemas-DPdeFlCT.d.ts +38 -0
- package/dist/schemas-pMyyuXV7.d.cts +47 -0
- package/dist/schemas-pMyyuXV7.d.ts +47 -0
- package/dist/types-Boh9ckdG.d.ts +194 -0
- package/dist/types-Brc7v_pS.d.ts +198 -0
- package/dist/types-ByNSwtUV.d.cts +20 -0
- package/dist/types-DdltMfw7.d.ts +20 -0
- package/dist/types-De0KpxfI.d.cts +198 -0
- package/dist/types-DhHL0twe.d.ts +20 -0
- package/dist/types-Dv6JLmgo.d.cts +194 -0
- package/dist/types-Q80YtOQt.d.cts +20 -0
- package/package.json +237 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,3723 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var zod = require('zod');
|
|
4
|
+
var prism = require('@niscorp/prism');
|
|
5
|
+
var strata = require('@niscorp/strata');
|
|
6
|
+
|
|
7
|
+
// src/shared/common.ts
|
|
8
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9
|
+
var isArray = (value) => Array.isArray(value);
|
|
10
|
+
var hasKey = (obj, key) => isObject(obj) && key in obj;
|
|
11
|
+
|
|
12
|
+
// src/shared/errors.ts
|
|
13
|
+
var ErrorCodes = {
|
|
14
|
+
render: "RENDER_ERROR",
|
|
15
|
+
componentNotFound: "COMPONENT_NOT_FOUND",
|
|
16
|
+
layoutRefNotFound: "LAYOUT_REF_NOT_FOUND",
|
|
17
|
+
definitionValidation: "DEFINITION_VALIDATION_ERROR",
|
|
18
|
+
unknownAction: "UNKNOWN_ACTION",
|
|
19
|
+
unknownFragment: "UNKNOWN_FRAGMENT",
|
|
20
|
+
unknownFunction: "UNKNOWN_FUNCTION",
|
|
21
|
+
shellDisposed: "SHELL_DISPOSED",
|
|
22
|
+
lifecycle: "LIFECYCLE_ERROR",
|
|
23
|
+
mutation: "MUTATION_ERROR",
|
|
24
|
+
runaway: "RUNAWAY_CHAIN"
|
|
25
|
+
};
|
|
26
|
+
var NovaError = class extends Error {
|
|
27
|
+
code;
|
|
28
|
+
context;
|
|
29
|
+
constructor(code, message, context, options) {
|
|
30
|
+
super(message, options);
|
|
31
|
+
this.name = "NovaError";
|
|
32
|
+
this.code = code;
|
|
33
|
+
this.context = context;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
var RenderError = class extends NovaError {
|
|
37
|
+
constructor(message, context, options) {
|
|
38
|
+
super(ErrorCodes.render, message, context, options);
|
|
39
|
+
this.name = "RenderError";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
var ComponentNotFoundError = class extends NovaError {
|
|
43
|
+
constructor(message, context, options) {
|
|
44
|
+
super(ErrorCodes.componentNotFound, message, context, options);
|
|
45
|
+
this.name = "ComponentNotFoundError";
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
var LayoutRefNotFoundError = class extends NovaError {
|
|
49
|
+
constructor(message, context, options) {
|
|
50
|
+
super(ErrorCodes.layoutRefNotFound, message, context, options);
|
|
51
|
+
this.name = "LayoutRefNotFoundError";
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
var DefinitionValidationError = class extends NovaError {
|
|
55
|
+
constructor(message, context, options) {
|
|
56
|
+
super(ErrorCodes.definitionValidation, message, context, options);
|
|
57
|
+
this.name = "DefinitionValidationError";
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
var UnknownActionError = class extends NovaError {
|
|
61
|
+
constructor(message, context, options) {
|
|
62
|
+
super(ErrorCodes.unknownAction, message, context, options);
|
|
63
|
+
this.name = "UnknownActionError";
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
var UnknownFragmentError = class extends NovaError {
|
|
67
|
+
constructor(message, context, options) {
|
|
68
|
+
super(ErrorCodes.unknownFragment, message, context, options);
|
|
69
|
+
this.name = "UnknownFragmentError";
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
var ShellDisposedError = class extends NovaError {
|
|
73
|
+
constructor(message, context, options) {
|
|
74
|
+
super(ErrorCodes.shellDisposed, message, context, options);
|
|
75
|
+
this.name = "ShellDisposedError";
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
var UnknownFunctionError = class extends NovaError {
|
|
79
|
+
constructor(name, options) {
|
|
80
|
+
super(
|
|
81
|
+
ErrorCodes.unknownFunction,
|
|
82
|
+
`Unknown function: "${name}". Is it registered in shell config's \`functions\` map?`,
|
|
83
|
+
{ name },
|
|
84
|
+
options
|
|
85
|
+
);
|
|
86
|
+
this.name = "UnknownFunctionError";
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
var LifecycleError = class extends NovaError {
|
|
90
|
+
constructor(message, context, options) {
|
|
91
|
+
super(ErrorCodes.lifecycle, message, context, options);
|
|
92
|
+
this.name = "LifecycleError";
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
var MutationError = class extends NovaError {
|
|
96
|
+
constructor(message, context, options) {
|
|
97
|
+
super(ErrorCodes.mutation, message, context, options);
|
|
98
|
+
this.name = "MutationError";
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
// src/shared/ids.ts
|
|
103
|
+
var fallbackToken = () => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
104
|
+
var getCrypto = () => {
|
|
105
|
+
if (typeof globalThis === "undefined") return void 0;
|
|
106
|
+
const g = globalThis;
|
|
107
|
+
return g.crypto;
|
|
108
|
+
};
|
|
109
|
+
var createIdFactory = (prefix) => {
|
|
110
|
+
const cryptoObj = getCrypto();
|
|
111
|
+
const randomUUID = cryptoObj?.randomUUID;
|
|
112
|
+
if (typeof randomUUID === "function") {
|
|
113
|
+
return () => `${prefix}-${randomUUID.call(cryptoObj)}`;
|
|
114
|
+
}
|
|
115
|
+
return () => `${prefix}-${fallbackToken()}`;
|
|
116
|
+
};
|
|
117
|
+
zod.z.object({
|
|
118
|
+
$if: zod.z.unknown().describe("Condition \u2014 resolved recursively, then checked for truthiness."),
|
|
119
|
+
$then: zod.z.unknown().describe("Value when condition is truthy \u2014 resolved recursively."),
|
|
120
|
+
$else: zod.z.unknown().optional().describe("Value when condition is falsy \u2014 resolved recursively.")
|
|
121
|
+
}).strict().describe("Conditional value directive. Resolved at bind time.");
|
|
122
|
+
var ResolvableSchema = zod.z.unknown().describe(
|
|
123
|
+
'Any value. Strings support {{}} templates and bare $-paths. The data ROOT is "$." \u2014 a data key is ALWAYS "$.key" ("{{$.rows.length}} found", "$.loading"); "$key" without the dot is INVALID. Loop variables (a `for` directive\'s `as`) are "$<name>.field" ("{{$row.title}}"). Objects may be directives like {$if,$then,$else}. Arrays and nested objects are walked recursively. Everything else is literal.'
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
// src/shared/bindings/scope.ts
|
|
127
|
+
var createScopeChain = (data) => [data];
|
|
128
|
+
var pushScope = (chain, scope) => [scope, ...chain];
|
|
129
|
+
|
|
130
|
+
// src/shared/bindings/paths.ts
|
|
131
|
+
var splitPath = (path) => {
|
|
132
|
+
if (path.length === 0) return [];
|
|
133
|
+
return path.split(".");
|
|
134
|
+
};
|
|
135
|
+
var isIndex = (segment) => /^\d+$/.test(segment);
|
|
136
|
+
var cloneContainer = (value, nextSegment) => {
|
|
137
|
+
if (isArray(value)) return value.slice();
|
|
138
|
+
if (isObject(value)) return { ...value };
|
|
139
|
+
if (nextSegment !== void 0 && isIndex(nextSegment)) return [];
|
|
140
|
+
return {};
|
|
141
|
+
};
|
|
142
|
+
var writeSegment = (container, segment, value) => {
|
|
143
|
+
if (isArray(container)) {
|
|
144
|
+
if (isIndex(segment)) {
|
|
145
|
+
const index = Number.parseInt(segment, 10);
|
|
146
|
+
container[index] = value;
|
|
147
|
+
}
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
container[segment] = value;
|
|
151
|
+
};
|
|
152
|
+
var readSegment = (container, segment) => {
|
|
153
|
+
if (isArray(container)) {
|
|
154
|
+
if (!isIndex(segment)) return void 0;
|
|
155
|
+
const index = Number.parseInt(segment, 10);
|
|
156
|
+
return container[index];
|
|
157
|
+
}
|
|
158
|
+
return container[segment];
|
|
159
|
+
};
|
|
160
|
+
var getPath = (data, path) => {
|
|
161
|
+
const segments = splitPath(path);
|
|
162
|
+
let current = data;
|
|
163
|
+
for (const segment of segments) {
|
|
164
|
+
if (current === void 0 || current === null) return void 0;
|
|
165
|
+
if (isArray(current)) {
|
|
166
|
+
if (isIndex(segment)) {
|
|
167
|
+
const index = Number.parseInt(segment, 10);
|
|
168
|
+
current = current[index];
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
if (segment === "length") {
|
|
172
|
+
current = current.length;
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
return void 0;
|
|
176
|
+
}
|
|
177
|
+
if (isObject(current)) {
|
|
178
|
+
if (segment in current) {
|
|
179
|
+
current = current[segment];
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
return void 0;
|
|
183
|
+
}
|
|
184
|
+
return void 0;
|
|
185
|
+
}
|
|
186
|
+
return current;
|
|
187
|
+
};
|
|
188
|
+
var setPath = (data, path, value) => {
|
|
189
|
+
const segments = splitPath(path);
|
|
190
|
+
if (segments.length === 0) return value;
|
|
191
|
+
const root = cloneContainer(data, segments[0]);
|
|
192
|
+
let parent = root;
|
|
193
|
+
for (let i = 0; i < segments.length - 1; i += 1) {
|
|
194
|
+
const segment = segments[i];
|
|
195
|
+
const nextSegment = segments[i + 1];
|
|
196
|
+
if (segment === void 0) continue;
|
|
197
|
+
const existing = readSegment(parent, segment);
|
|
198
|
+
const cloned = cloneContainer(existing, nextSegment);
|
|
199
|
+
writeSegment(parent, segment, cloned);
|
|
200
|
+
parent = cloned;
|
|
201
|
+
}
|
|
202
|
+
const last = segments[segments.length - 1];
|
|
203
|
+
if (last !== void 0) writeSegment(parent, last, value);
|
|
204
|
+
return root;
|
|
205
|
+
};
|
|
206
|
+
var deletePath = (data, path) => {
|
|
207
|
+
const segments = splitPath(path);
|
|
208
|
+
if (segments.length === 0) return void 0;
|
|
209
|
+
const root = cloneContainer(data, segments[0]);
|
|
210
|
+
let parent = root;
|
|
211
|
+
for (let i = 0; i < segments.length - 1; i += 1) {
|
|
212
|
+
const segment = segments[i];
|
|
213
|
+
const nextSegment = segments[i + 1];
|
|
214
|
+
if (segment === void 0) continue;
|
|
215
|
+
const existing = readSegment(parent, segment);
|
|
216
|
+
if (existing === void 0 || existing === null) return root;
|
|
217
|
+
const cloned = cloneContainer(existing, nextSegment);
|
|
218
|
+
writeSegment(parent, segment, cloned);
|
|
219
|
+
parent = cloned;
|
|
220
|
+
}
|
|
221
|
+
const last = segments[segments.length - 1];
|
|
222
|
+
if (last === void 0) return root;
|
|
223
|
+
if (isArray(parent)) {
|
|
224
|
+
if (isIndex(last)) {
|
|
225
|
+
const index = Number.parseInt(last, 10);
|
|
226
|
+
parent.splice(index, 1);
|
|
227
|
+
}
|
|
228
|
+
} else {
|
|
229
|
+
delete parent[last];
|
|
230
|
+
}
|
|
231
|
+
return root;
|
|
232
|
+
};
|
|
233
|
+
var TEMPLATE_REGEX = /\{\{\s*([^}]+?)\s*\}\}/g;
|
|
234
|
+
var SOLE_TEMPLATE_REGEX = /^\{\{\s*([^}]+?)\s*\}\}$/;
|
|
235
|
+
var BARE_PATH_REGEX = /^\$(\.|[A-Za-z_]|$)/;
|
|
236
|
+
var matchExtra = (expression, extras) => {
|
|
237
|
+
let matched;
|
|
238
|
+
for (const key of Object.keys(extras)) {
|
|
239
|
+
if (expression === key || expression.startsWith(`${key}.`)) {
|
|
240
|
+
if (matched === void 0 || key.length > matched.length) matched = key;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return matched;
|
|
244
|
+
};
|
|
245
|
+
var resolveExtraExpression = (expression, matchedKey, extras) => {
|
|
246
|
+
const root = extras[matchedKey];
|
|
247
|
+
if (expression === matchedKey) return root;
|
|
248
|
+
const rest = expression.slice(matchedKey.length + 1);
|
|
249
|
+
if (rest.length === 0) return root;
|
|
250
|
+
return getPath(root, rest);
|
|
251
|
+
};
|
|
252
|
+
var walkFromScopeHead = (head, restSegments) => {
|
|
253
|
+
if (restSegments.length === 0) return head;
|
|
254
|
+
return getPath(head, restSegments.join("."));
|
|
255
|
+
};
|
|
256
|
+
var resolvePath = (path, chain, extras = {}) => {
|
|
257
|
+
const extraKey = matchExtra(path, extras);
|
|
258
|
+
if (extraKey !== void 0) return resolveExtraExpression(path, extraKey, extras);
|
|
259
|
+
if (!path.startsWith("$")) return void 0;
|
|
260
|
+
if (path === "$") return chain[0];
|
|
261
|
+
const afterDollar = path.slice(1);
|
|
262
|
+
if (afterDollar.startsWith(".")) {
|
|
263
|
+
const rest = afterDollar.slice(1);
|
|
264
|
+
if (rest.length === 0) return chain[0];
|
|
265
|
+
const segments2 = rest.split(".");
|
|
266
|
+
const head = segments2[0];
|
|
267
|
+
if (head === void 0) return void 0;
|
|
268
|
+
for (const scope of chain) {
|
|
269
|
+
if (hasKey(scope, head)) {
|
|
270
|
+
return walkFromScopeHead(scope[head], segments2.slice(1));
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return void 0;
|
|
274
|
+
}
|
|
275
|
+
const segments = afterDollar.split(".");
|
|
276
|
+
const varName = segments[0];
|
|
277
|
+
if (varName === void 0 || varName.length === 0) return void 0;
|
|
278
|
+
for (const scope of chain) {
|
|
279
|
+
if (hasKey(scope, varName)) {
|
|
280
|
+
return walkFromScopeHead(scope[varName], segments.slice(1));
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return void 0;
|
|
284
|
+
};
|
|
285
|
+
var stringify = (value) => {
|
|
286
|
+
if (value === null || value === void 0) return "";
|
|
287
|
+
if (typeof value === "string") return value;
|
|
288
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
289
|
+
try {
|
|
290
|
+
return JSON.stringify(value);
|
|
291
|
+
} catch {
|
|
292
|
+
return "";
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
var isTruthy = (value) => {
|
|
296
|
+
if (value === null || value === void 0) return false;
|
|
297
|
+
if (value === false) return false;
|
|
298
|
+
if (value === 0) return false;
|
|
299
|
+
if (value === "") return false;
|
|
300
|
+
if (isArray(value) && value.length === 0) return false;
|
|
301
|
+
return true;
|
|
302
|
+
};
|
|
303
|
+
var DIRECTIVES = {
|
|
304
|
+
$if: (node, chain, extras) => {
|
|
305
|
+
if (isTruthy(resolve(node.$if, chain, extras))) return resolve(node.$then, chain, extras);
|
|
306
|
+
if (hasKey(node, "$else")) return resolve(node.$else, chain, extras);
|
|
307
|
+
return void 0;
|
|
308
|
+
},
|
|
309
|
+
$eq: (node, chain, extras) => {
|
|
310
|
+
const args = isArray(node.$eq) ? node.$eq : [];
|
|
311
|
+
return resolve(args[0], chain, extras) === resolve(args[1], chain, extras);
|
|
312
|
+
},
|
|
313
|
+
// True when the operand path resolves to a present value. The structural
|
|
314
|
+
// counterpart to `$eq`: discriminate a union by which key a branch carries
|
|
315
|
+
// (`{ $exists: "$.shape.component" }`) rather than a shared tag's value.
|
|
316
|
+
$exists: (node, chain, extras) => resolve(node.$exists, chain, extras) !== void 0,
|
|
317
|
+
// Read an array element by a (dynamic) index: `{ $at: ["$.results", "$.i"] }`.
|
|
318
|
+
// An optional third arg pulls one field off the element: `["$.results", "$.i",
|
|
319
|
+
// "id"]`. Returns undefined when the array/index doesn't resolve.
|
|
320
|
+
$at: (node, chain, extras) => {
|
|
321
|
+
const args = isArray(node.$at) ? node.$at : [];
|
|
322
|
+
const arr = resolve(args[0], chain, extras);
|
|
323
|
+
const index = Number(resolve(args[1], chain, extras));
|
|
324
|
+
if (!isArray(arr) || Number.isNaN(index)) return void 0;
|
|
325
|
+
const element = arr[index];
|
|
326
|
+
const field = args[2];
|
|
327
|
+
return field !== void 0 && isObject(element) ? element[String(field)] : element;
|
|
328
|
+
},
|
|
329
|
+
// THE WHOLE TRANSFORM GRAMMAR, BEHIND ONE EXPLICIT DOOR. The directives
|
|
330
|
+
// above stay the small binding set; a value that needs a real transformation
|
|
331
|
+
// — a join, a projection, a group — says so out loud: `{ $prism: <node> }`
|
|
332
|
+
// evaluates the node with prism against the action's ROOT data. One grammar,
|
|
333
|
+
// one evaluator, nothing ambient — a prism-shaped object OUTSIDE this
|
|
334
|
+
// wrapper stays what it always was, a plain object walked for strings.
|
|
335
|
+
//
|
|
336
|
+
// The quiet failure this replaces was worse than a crash: an unrecognised
|
|
337
|
+
// op-shaped value passed through `resolve` as structure, landed in data, and
|
|
338
|
+
// rendered as garbage three screens later. Inside the wrapper, a bad node
|
|
339
|
+
// resolves to undefined — absent, not wrong.
|
|
340
|
+
$prism: (node, chain) => {
|
|
341
|
+
const result = prism.evaluateSafe(node.$prism, chain[0] ?? {});
|
|
342
|
+
return result.ok ? result.data : void 0;
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
var directiveOf = (value) => {
|
|
346
|
+
for (const key of Object.keys(value)) {
|
|
347
|
+
const directive = DIRECTIVES[key];
|
|
348
|
+
if (directive !== void 0) return directive;
|
|
349
|
+
}
|
|
350
|
+
return void 0;
|
|
351
|
+
};
|
|
352
|
+
var resolveString = (value, chain, extras) => {
|
|
353
|
+
const sole = value.match(SOLE_TEMPLATE_REGEX);
|
|
354
|
+
if (sole !== null) {
|
|
355
|
+
const expr = sole[1];
|
|
356
|
+
if (expr === void 0) return value;
|
|
357
|
+
return resolvePath(expr.trim(), chain, extras);
|
|
358
|
+
}
|
|
359
|
+
if (value.includes("{{")) {
|
|
360
|
+
return value.replace(TEMPLATE_REGEX, (_match, expression) => {
|
|
361
|
+
const resolved = resolvePath(expression.trim(), chain, extras);
|
|
362
|
+
return stringify(resolved);
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
if (BARE_PATH_REGEX.test(value)) {
|
|
366
|
+
return resolvePath(value, chain, extras);
|
|
367
|
+
}
|
|
368
|
+
if (matchExtra(value, extras) !== void 0) {
|
|
369
|
+
return resolvePath(value, chain, extras);
|
|
370
|
+
}
|
|
371
|
+
return value;
|
|
372
|
+
};
|
|
373
|
+
var resolve = (value, chain, extras = {}) => {
|
|
374
|
+
if (typeof value === "string") return resolveString(value, chain, extras);
|
|
375
|
+
if (isArray(value)) return value.map((entry) => resolve(entry, chain, extras));
|
|
376
|
+
if (isObject(value)) {
|
|
377
|
+
const directive = directiveOf(value);
|
|
378
|
+
if (directive !== void 0) return directive(value, chain, extras);
|
|
379
|
+
const out = {};
|
|
380
|
+
for (const key of Object.keys(value)) {
|
|
381
|
+
out[key] = resolve(value[key], chain, extras);
|
|
382
|
+
}
|
|
383
|
+
return out;
|
|
384
|
+
}
|
|
385
|
+
return value;
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
// src/shared/data-store/data-store.ts
|
|
389
|
+
var createDataStore = (initial) => {
|
|
390
|
+
let current = { ...initial };
|
|
391
|
+
const subscribers = [];
|
|
392
|
+
const get = () => current;
|
|
393
|
+
const update = (updater) => {
|
|
394
|
+
current = updater(current);
|
|
395
|
+
for (const handler of subscribers.slice()) {
|
|
396
|
+
try {
|
|
397
|
+
handler(current);
|
|
398
|
+
} catch {
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
const subscribe = (handler) => {
|
|
403
|
+
subscribers.push(handler);
|
|
404
|
+
return () => {
|
|
405
|
+
const idx = subscribers.indexOf(handler);
|
|
406
|
+
if (idx >= 0) subscribers.splice(idx, 1);
|
|
407
|
+
};
|
|
408
|
+
};
|
|
409
|
+
return { get, update, subscribe };
|
|
410
|
+
};
|
|
411
|
+
var uiEvent = (type, extra = {}) => zod.z.object({
|
|
412
|
+
type: zod.z.literal(type).describe("Event type discriminator."),
|
|
413
|
+
ref: zod.z.string().optional().describe("Target component ref."),
|
|
414
|
+
payload: zod.z.unknown().optional().describe("Optional event payload."),
|
|
415
|
+
origin: zod.z.string().optional().describe(
|
|
416
|
+
"Id of the action instance that dispatched this event. Stamped automatically for events dispatched from within an instance\u2019s layout; used to deliver UI events to that instance\u2019s own triggers only. Absent on programmatic (global) dispatch."
|
|
417
|
+
),
|
|
418
|
+
...extra
|
|
419
|
+
}).strict();
|
|
420
|
+
var UiClickSchema = uiEvent("ui:click").describe("A UI click event.");
|
|
421
|
+
var UiSubmitSchema = uiEvent("ui:submit").describe("A UI submit event.");
|
|
422
|
+
var UiInputSchema = uiEvent("ui:input").describe("A UI input event.");
|
|
423
|
+
var UiFocusSchema = uiEvent("ui:focus").describe("A UI focus event.");
|
|
424
|
+
var UiBlurSchema = uiEvent("ui:blur").describe("A UI blur event.");
|
|
425
|
+
var UiModelSchema = uiEvent("ui:model").describe("A two-way-bound model update event.");
|
|
426
|
+
var UiKeySchema = uiEvent("ui:key", {
|
|
427
|
+
key: zod.z.string().describe('The key pressed, e.g. "ArrowDown", "Enter", "Escape".')
|
|
428
|
+
}).describe("A keyboard key event. A trigger filters it by `key` (and optionally `ref`).");
|
|
429
|
+
var UiDropSchema = uiEvent("ui:drop").describe(
|
|
430
|
+
'A drag-and-drop "drop" event \u2014 the semantic outcome of a drag gesture, dispatched by a drop zone. The gesture mechanics stay in the component; only the drop reaches Nova.'
|
|
431
|
+
);
|
|
432
|
+
var NovaEventSchema = zod.z.discriminatedUnion("type", [
|
|
433
|
+
UiClickSchema,
|
|
434
|
+
UiSubmitSchema,
|
|
435
|
+
UiInputSchema,
|
|
436
|
+
UiFocusSchema,
|
|
437
|
+
UiBlurSchema,
|
|
438
|
+
UiModelSchema,
|
|
439
|
+
UiKeySchema,
|
|
440
|
+
UiDropSchema
|
|
441
|
+
]).describe("Discriminated union of the built-in Nova UI events.");
|
|
442
|
+
|
|
443
|
+
// src/shared/event-bus/event-bus.ts
|
|
444
|
+
var typeMatches = (matcher, type) => {
|
|
445
|
+
if (typeof matcher === "string") return matcher === type;
|
|
446
|
+
return matcher.test(type);
|
|
447
|
+
};
|
|
448
|
+
var createChildBus = (parent) => {
|
|
449
|
+
const subscriptions = [];
|
|
450
|
+
const emit = (event) => {
|
|
451
|
+
for (const sub of subscriptions.slice()) {
|
|
452
|
+
if (!typeMatches(sub.matcher, event.type)) continue;
|
|
453
|
+
try {
|
|
454
|
+
sub.handler(event);
|
|
455
|
+
} catch {
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
if (parent !== void 0) parent.emit(event);
|
|
459
|
+
};
|
|
460
|
+
const on = (matcher, handler) => {
|
|
461
|
+
const sub = { matcher, handler };
|
|
462
|
+
subscriptions.push(sub);
|
|
463
|
+
return () => {
|
|
464
|
+
const idx = subscriptions.indexOf(sub);
|
|
465
|
+
if (idx >= 0) subscriptions.splice(idx, 1);
|
|
466
|
+
};
|
|
467
|
+
};
|
|
468
|
+
const once = (matcher, handler) => {
|
|
469
|
+
const off = on(matcher, (event) => {
|
|
470
|
+
off();
|
|
471
|
+
handler(event);
|
|
472
|
+
});
|
|
473
|
+
return off;
|
|
474
|
+
};
|
|
475
|
+
const bus = {
|
|
476
|
+
emit,
|
|
477
|
+
on,
|
|
478
|
+
once,
|
|
479
|
+
scoped: () => createChildBus(bus)
|
|
480
|
+
};
|
|
481
|
+
return bus;
|
|
482
|
+
};
|
|
483
|
+
var createEventBus = () => createChildBus(void 0);
|
|
484
|
+
|
|
485
|
+
// src/shared/event-bus/scope-dispatch.ts
|
|
486
|
+
var scopeDispatch = (dispatch, origin) => {
|
|
487
|
+
return (event) => dispatch(event.origin === void 0 ? { ...event, origin } : event);
|
|
488
|
+
};
|
|
489
|
+
var MessageEnvelopeSchema = zod.z.object({
|
|
490
|
+
channel: zod.z.string().describe("Channel name the message is published on."),
|
|
491
|
+
from: zod.z.string().optional().describe("Optional sender identifier."),
|
|
492
|
+
to: zod.z.string().optional().describe("Optional direct recipient identifier."),
|
|
493
|
+
payload: zod.z.unknown().optional().describe("Optional message payload.")
|
|
494
|
+
}).strict().describe("A message envelope passed through the message bus.");
|
|
495
|
+
|
|
496
|
+
// src/shared/message-bus/message-bus.ts
|
|
497
|
+
var createMessageBus = () => {
|
|
498
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
499
|
+
const dispatch = (channel, payload, from, cause) => {
|
|
500
|
+
const list = handlers.get(channel);
|
|
501
|
+
if (list === void 0) return;
|
|
502
|
+
for (const handler of list.slice()) {
|
|
503
|
+
try {
|
|
504
|
+
handler(payload, from, cause);
|
|
505
|
+
} catch {
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
};
|
|
509
|
+
const publish = (channel, payload, cause) => {
|
|
510
|
+
dispatch(channel, payload, void 0, cause);
|
|
511
|
+
};
|
|
512
|
+
const send = (from, to, payload) => {
|
|
513
|
+
dispatch(to, payload, from);
|
|
514
|
+
};
|
|
515
|
+
const subscribe = (channel, handler) => {
|
|
516
|
+
const list = handlers.get(channel) ?? [];
|
|
517
|
+
list.push(handler);
|
|
518
|
+
handlers.set(channel, list);
|
|
519
|
+
return () => {
|
|
520
|
+
const current = handlers.get(channel);
|
|
521
|
+
if (current === void 0) return;
|
|
522
|
+
const idx = current.indexOf(handler);
|
|
523
|
+
if (idx >= 0) current.splice(idx, 1);
|
|
524
|
+
};
|
|
525
|
+
};
|
|
526
|
+
return { publish, send, subscribe };
|
|
527
|
+
};
|
|
528
|
+
var LayoutPrimitiveSchema = zod.z.union([zod.z.string(), zod.z.number(), zod.z.boolean(), zod.z.null()]).describe("A primitive layout value rendered as text.");
|
|
529
|
+
var ComponentNodeSchema = zod.z.lazy(
|
|
530
|
+
() => zod.z.object({
|
|
531
|
+
component: zod.z.string().describe("The registry name of the component to render."),
|
|
532
|
+
props: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Component props; values may be bindings to be resolved at render time."),
|
|
533
|
+
children: zod.z.union([LayoutNodeSchema, zod.z.array(LayoutNodeSchema)]).optional().describe("Child layout content (a single node or an array of nodes)."),
|
|
534
|
+
ref: zod.z.string().optional().describe("A stable identifier used to target this component from event handlers."),
|
|
535
|
+
model: zod.z.string().optional().describe('A two-way binding path, e.g. "$.name".'),
|
|
536
|
+
events: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Map of event name to event configuration handled by the action runtime.")
|
|
537
|
+
}).strict().describe("A node that instantiates a component from the registry.")
|
|
538
|
+
);
|
|
539
|
+
var ConditionalNodeSchema = zod.z.lazy(
|
|
540
|
+
() => zod.z.object({
|
|
541
|
+
if: ResolvableSchema.describe("Resolvable value evaluated for truthiness."),
|
|
542
|
+
then: LayoutNodeSchema.describe("Layout to render when condition is truthy."),
|
|
543
|
+
else: LayoutNodeSchema.optional().describe("Layout to render when condition is falsy.")
|
|
544
|
+
}).strict().describe("A node that conditionally renders one of two branches.")
|
|
545
|
+
);
|
|
546
|
+
var LoopNodeSchema = zod.z.lazy(
|
|
547
|
+
() => zod.z.object({
|
|
548
|
+
for: ResolvableSchema.describe("Resolvable value that resolves to an iterable array."),
|
|
549
|
+
as: zod.z.string().describe("Name to bind each iterated item under in the inner scope."),
|
|
550
|
+
key: zod.z.string().optional().describe("Optional key path on each item used for stable identity."),
|
|
551
|
+
do: LayoutNodeSchema.describe("Layout rendered once per iterated item.")
|
|
552
|
+
}).strict().describe("A node that iterates an array binding and renders a layout for each item.")
|
|
553
|
+
);
|
|
554
|
+
var LayoutRefNodeSchema = zod.z.object({
|
|
555
|
+
ref: zod.z.string().describe("Identifier of a layout stored in the layout store to inline at this position.")
|
|
556
|
+
}).strict().describe("A reference to a stored layout, inlined during render.");
|
|
557
|
+
var SlotNodeSchema = zod.z.object({
|
|
558
|
+
slot: zod.z.string().describe(
|
|
559
|
+
"Name of a slot placeholder. When an ActionFragment is composed with an action (a push/replace `with`), the fragment's `{ slot: \"body\" }` node is replaced by the composing action's own layout. An unfilled slot renders nothing."
|
|
560
|
+
)
|
|
561
|
+
}).strict().describe(
|
|
562
|
+
"A placeholder that a fragment-merge fills with a composing action's layout. Only meaningful inside an ActionFragment's layout."
|
|
563
|
+
);
|
|
564
|
+
var LayoutNodeSchema = zod.z.lazy(
|
|
565
|
+
() => zod.z.union([
|
|
566
|
+
ComponentNodeSchema,
|
|
567
|
+
ConditionalNodeSchema,
|
|
568
|
+
LoopNodeSchema,
|
|
569
|
+
LayoutRefNodeSchema,
|
|
570
|
+
SlotNodeSchema,
|
|
571
|
+
zod.z.array(LayoutNodeSchema),
|
|
572
|
+
LayoutPrimitiveSchema
|
|
573
|
+
]).describe("Any layout node: component, conditional, loop, layout ref, slot, array of nodes, or a primitive text value.")
|
|
574
|
+
);
|
|
575
|
+
|
|
576
|
+
// src/layout/guards.ts
|
|
577
|
+
var isLayoutPrimitive = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
578
|
+
var isComponentNode = (value) => hasKey(value, "component") && typeof value["component"] === "string";
|
|
579
|
+
var isConditionalNode = (value) => hasKey(value, "if") && hasKey(value, "then") && !hasKey(value, "for");
|
|
580
|
+
var isLoopNode = (value) => hasKey(value, "for") && hasKey(value, "as") && hasKey(value, "do");
|
|
581
|
+
var isLayoutRefNode = (value) => isObject(value) && hasKey(value, "ref") && typeof value["ref"] === "string" && !hasKey(value, "component") && Object.keys(value).length === 1;
|
|
582
|
+
var isSlotNode = (value) => isObject(value) && hasKey(value, "slot") && typeof value["slot"] === "string" && Object.keys(value).length === 1;
|
|
583
|
+
var isLayoutNode = (value) => isLayoutPrimitive(value) || Array.isArray(value) || isComponentNode(value) || isConditionalNode(value) || isLoopNode(value) || isLayoutRefNode(value) || isSlotNode(value);
|
|
584
|
+
|
|
585
|
+
// src/i18n/phrases.ts
|
|
586
|
+
var DEFAULT_PHRASE_KEYS = {
|
|
587
|
+
// A starting set, not a standard — an app with its own vocabulary passes its
|
|
588
|
+
// own. Deliberately absent: `name`, `value`, `id`, `icon`, `tone`, `variant`,
|
|
589
|
+
// `key`. Those carry data or design tokens, and translating them is how a
|
|
590
|
+
// person called "Active" gets renamed.
|
|
591
|
+
props: [
|
|
592
|
+
"label",
|
|
593
|
+
"title",
|
|
594
|
+
"subtitle",
|
|
595
|
+
"heading",
|
|
596
|
+
"eyebrow",
|
|
597
|
+
"lead",
|
|
598
|
+
"blurb",
|
|
599
|
+
"placeholder",
|
|
600
|
+
"hint",
|
|
601
|
+
"help",
|
|
602
|
+
"message",
|
|
603
|
+
"empty",
|
|
604
|
+
"emptyHint",
|
|
605
|
+
"emptyLabel",
|
|
606
|
+
"noMatch",
|
|
607
|
+
"caption",
|
|
608
|
+
"description",
|
|
609
|
+
"confirmLabel",
|
|
610
|
+
"cancelLabel",
|
|
611
|
+
"alt",
|
|
612
|
+
"tooltip"
|
|
613
|
+
],
|
|
614
|
+
text: true
|
|
615
|
+
};
|
|
616
|
+
var matcherFor = (keys) => {
|
|
617
|
+
const props = new Set(keys?.props ?? DEFAULT_PHRASE_KEYS.props);
|
|
618
|
+
const suffixes = keys?.suffixes ?? [];
|
|
619
|
+
return {
|
|
620
|
+
isProse: (key) => props.has(key) || suffixes.some((suffix) => key.endsWith(suffix)),
|
|
621
|
+
text: keys?.text ?? DEFAULT_PHRASE_KEYS.text
|
|
622
|
+
};
|
|
623
|
+
};
|
|
624
|
+
var BARE_PATH = /^\$(\.|[A-Za-z_]|$)/;
|
|
625
|
+
var EXTRA_SCOPE = /^@[A-Za-z_]/;
|
|
626
|
+
var isBinding = (value) => BARE_PATH.test(value) || EXTRA_SCOPE.test(value) || value.includes("{{");
|
|
627
|
+
var isPhrase = (value) => {
|
|
628
|
+
const trimmed = value.trim();
|
|
629
|
+
if (trimmed === "" || isBinding(trimmed)) return false;
|
|
630
|
+
return /\p{L}/u.test(trimmed);
|
|
631
|
+
};
|
|
632
|
+
|
|
633
|
+
// src/i18n/swap.ts
|
|
634
|
+
var EMPTY = {};
|
|
635
|
+
var passFor = (options) => {
|
|
636
|
+
if (options === void 0) return void 0;
|
|
637
|
+
if (options.phrases === void 0 && options.keys === void 0) return void 0;
|
|
638
|
+
const matcher = matcherFor(options.keys);
|
|
639
|
+
return {
|
|
640
|
+
phrases: options.phrases ?? EMPTY,
|
|
641
|
+
isProse: matcher.isProse,
|
|
642
|
+
text: matcher.text,
|
|
643
|
+
onMiss: options.onMiss
|
|
644
|
+
};
|
|
645
|
+
};
|
|
646
|
+
var swap = (value, where, pass) => {
|
|
647
|
+
if (!isPhrase(value)) return value;
|
|
648
|
+
const hit = pass.phrases[value];
|
|
649
|
+
if (hit !== void 0) return hit;
|
|
650
|
+
const trimmed = value.trim();
|
|
651
|
+
if (trimmed !== value) {
|
|
652
|
+
const onTrimmed = pass.phrases[trimmed];
|
|
653
|
+
if (onTrimmed !== void 0) return value.replace(trimmed, onTrimmed);
|
|
654
|
+
}
|
|
655
|
+
pass.onMiss?.(trimmed, where);
|
|
656
|
+
return value;
|
|
657
|
+
};
|
|
658
|
+
var isPattern = (value) => typeof value["phrase"] === "string" && isObject(value["slots"]);
|
|
659
|
+
var fillPattern = (pattern, where, pass) => swap(pattern.phrase, where, pass).replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (hole, name) => {
|
|
660
|
+
const slot = pattern.slots[name];
|
|
661
|
+
if (slot === void 0 || slot === null) return hole;
|
|
662
|
+
return typeof slot === "string" && isPhrase(slot) ? swap(slot, `${where}.${name}`, pass) : String(slot);
|
|
663
|
+
});
|
|
664
|
+
var walkValue = (value, prose, where, pass) => {
|
|
665
|
+
if (typeof value === "string") return prose ? swap(value, where, pass) : value;
|
|
666
|
+
if (isArray(value)) {
|
|
667
|
+
let changed = false;
|
|
668
|
+
const out = value.map((entry, index) => {
|
|
669
|
+
const next = walkValue(entry, prose, `${where}[${String(index)}]`, pass);
|
|
670
|
+
if (next !== entry) changed = true;
|
|
671
|
+
return next;
|
|
672
|
+
});
|
|
673
|
+
return changed ? out : value;
|
|
674
|
+
}
|
|
675
|
+
if (isObject(value)) {
|
|
676
|
+
if (prose && isPattern(value)) return fillPattern(value, where, pass);
|
|
677
|
+
let changed = false;
|
|
678
|
+
const out = {};
|
|
679
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
680
|
+
const next = walkValue(entry, pass.isProse(key), `${where}.${key}`, pass);
|
|
681
|
+
if (next !== entry) changed = true;
|
|
682
|
+
out[key] = next;
|
|
683
|
+
}
|
|
684
|
+
return changed ? out : value;
|
|
685
|
+
}
|
|
686
|
+
return value;
|
|
687
|
+
};
|
|
688
|
+
|
|
689
|
+
// src/layout/renderer.ts
|
|
690
|
+
var noopOnError = (_error) => {
|
|
691
|
+
};
|
|
692
|
+
var textNode = (value) => ({ type: "text", value });
|
|
693
|
+
var fragment = (children) => ({ type: "fragment", children });
|
|
694
|
+
var errorNode = (error, nodeRef) => ({
|
|
695
|
+
type: "error",
|
|
696
|
+
code: error.code,
|
|
697
|
+
message: error.message,
|
|
698
|
+
...{}
|
|
699
|
+
});
|
|
700
|
+
var toRenderError = (err) => {
|
|
701
|
+
if (err instanceof NovaError) return err;
|
|
702
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
703
|
+
return new RenderError(message, {}, { cause: err });
|
|
704
|
+
};
|
|
705
|
+
var resolveDataPath = (binding, scopePaths) => {
|
|
706
|
+
if (!binding.startsWith("$")) return void 0;
|
|
707
|
+
const after = binding.slice(1);
|
|
708
|
+
if (after.startsWith(".")) return after.slice(1);
|
|
709
|
+
const segments = after.split(".");
|
|
710
|
+
const head = segments[0];
|
|
711
|
+
if (head === void 0 || head.length === 0) return void 0;
|
|
712
|
+
for (let i = scopePaths.length - 1; i >= 0; i -= 1) {
|
|
713
|
+
const entry = scopePaths[i];
|
|
714
|
+
if (entry === void 0) continue;
|
|
715
|
+
const eq = entry.indexOf("=");
|
|
716
|
+
if (eq < 0) continue;
|
|
717
|
+
const key = entry.slice(0, eq);
|
|
718
|
+
if (key !== head) continue;
|
|
719
|
+
const rooted = entry.slice(eq + 1);
|
|
720
|
+
const rest = segments.slice(1).join(".");
|
|
721
|
+
if (rest.length === 0) return rooted;
|
|
722
|
+
return `${rooted}.${rest}`;
|
|
723
|
+
}
|
|
724
|
+
return void 0;
|
|
725
|
+
};
|
|
726
|
+
var makeAutoRef = (componentName, path) => `auto-${componentName}-${path}`;
|
|
727
|
+
var renderNode = (node, chain, ctx) => {
|
|
728
|
+
if (node === null) return [textNode("")];
|
|
729
|
+
if (typeof node === "string") {
|
|
730
|
+
const resolved = resolve(node, chain);
|
|
731
|
+
if (resolved === void 0 || resolved === null) return [textNode("")];
|
|
732
|
+
const value = String(resolved);
|
|
733
|
+
if (ctx.pass === void 0 || !ctx.pass.text || isBinding(node)) return [textNode(value)];
|
|
734
|
+
return [textNode(swap(value, `${ctx.where}#text`, ctx.pass))];
|
|
735
|
+
}
|
|
736
|
+
if (isLayoutPrimitive(node)) {
|
|
737
|
+
return [textNode(String(node))];
|
|
738
|
+
}
|
|
739
|
+
if (isArray(node)) {
|
|
740
|
+
const children = renderChildArray(node, chain, ctx);
|
|
741
|
+
return [fragment(children)];
|
|
742
|
+
}
|
|
743
|
+
if (isLayoutRefNode(node)) {
|
|
744
|
+
const target = ctx.store.get(node.ref);
|
|
745
|
+
if (target === void 0) {
|
|
746
|
+
throw new LayoutRefNotFoundError(`Layout ref not found: ${node.ref}`, { ref: node.ref });
|
|
747
|
+
}
|
|
748
|
+
return renderNode(target, chain, ctx);
|
|
749
|
+
}
|
|
750
|
+
if (isSlotNode(node)) {
|
|
751
|
+
return [];
|
|
752
|
+
}
|
|
753
|
+
if (isConditionalNode(node)) {
|
|
754
|
+
const condition = resolve(node.if, chain);
|
|
755
|
+
const truthy = condition !== void 0 && condition !== null && condition !== false && condition !== 0 && condition !== "";
|
|
756
|
+
const branchTruthy = isArray(condition) ? condition.length > 0 : truthy;
|
|
757
|
+
if (branchTruthy) return renderNode(node.then, chain, ctx);
|
|
758
|
+
if (node.else !== void 0) return renderNode(node.else, chain, ctx);
|
|
759
|
+
return [];
|
|
760
|
+
}
|
|
761
|
+
if (isLoopNode(node)) {
|
|
762
|
+
const items = resolve(node.for, chain);
|
|
763
|
+
if (!isArray(items)) return [];
|
|
764
|
+
const loopBasePath = typeof node.for === "string" ? resolveDataPath(node.for, ctx.scopePaths) : void 0;
|
|
765
|
+
const out = [];
|
|
766
|
+
items.forEach((item, index) => {
|
|
767
|
+
const innerChain = pushScope(chain, { [node.as]: item, index, items });
|
|
768
|
+
const nextScopePaths = loopBasePath === void 0 ? ctx.scopePaths : [...ctx.scopePaths, `${node.as}=${loopBasePath}.${index}`, `items=${loopBasePath}`];
|
|
769
|
+
const innerCtx = { ...ctx, scopePaths: nextScopePaths };
|
|
770
|
+
const idKey = node.key !== void 0 ? getPath(item, node.key) : index;
|
|
771
|
+
const rendered = safeRenderSingle(node.do, innerChain, innerCtx);
|
|
772
|
+
rendered.forEach((rn, sub) => {
|
|
773
|
+
out.push({ ...rn, key: rendered.length === 1 ? String(idKey) : `${String(idKey)}:${sub}` });
|
|
774
|
+
});
|
|
775
|
+
});
|
|
776
|
+
return [fragment(out)];
|
|
777
|
+
}
|
|
778
|
+
if (isComponentNode(node)) {
|
|
779
|
+
return [renderComponent(node, chain, ctx)];
|
|
780
|
+
}
|
|
781
|
+
return [];
|
|
782
|
+
};
|
|
783
|
+
var renderComponent = (node, chain, ctx) => {
|
|
784
|
+
if (!ctx.registry.has(node.component)) {
|
|
785
|
+
throw new ComponentNotFoundError(
|
|
786
|
+
`Component not found in registry: ${node.component}`,
|
|
787
|
+
{ name: node.component }
|
|
788
|
+
);
|
|
789
|
+
}
|
|
790
|
+
const pass = ctx.pass;
|
|
791
|
+
const at = pass === void 0 ? "" : `${ctx.where}/${node.component}`;
|
|
792
|
+
const props = Object.fromEntries(
|
|
793
|
+
Object.entries(node.props ?? {}).map(([k, v]) => {
|
|
794
|
+
const resolved = resolve(v, chain);
|
|
795
|
+
if (pass === void 0) return [k, resolved];
|
|
796
|
+
return [k, walkValue(resolved, pass.isProse(k), `${at}.${k}`, pass)];
|
|
797
|
+
})
|
|
798
|
+
);
|
|
799
|
+
const children = renderChildren(node.children, chain, pass === void 0 ? ctx : { ...ctx, where: at });
|
|
800
|
+
let model;
|
|
801
|
+
if (node.model !== void 0) {
|
|
802
|
+
const resolvedPath = resolveDataPath(node.model, ctx.scopePaths);
|
|
803
|
+
if (resolvedPath !== void 0) {
|
|
804
|
+
const ref = node.ref ?? makeAutoRef(node.component, resolvedPath);
|
|
805
|
+
model = { path: resolvedPath, ref };
|
|
806
|
+
if (!("value" in props)) {
|
|
807
|
+
props["value"] = resolve(node.model, chain);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
const component = {
|
|
812
|
+
type: "component",
|
|
813
|
+
name: node.component,
|
|
814
|
+
props,
|
|
815
|
+
children,
|
|
816
|
+
...node.ref === void 0 ? {} : { ref: node.ref },
|
|
817
|
+
...model === void 0 ? {} : { model }
|
|
818
|
+
};
|
|
819
|
+
return component;
|
|
820
|
+
};
|
|
821
|
+
var safeRenderSingle = (node, chain, ctx, nodeRef) => {
|
|
822
|
+
try {
|
|
823
|
+
return renderNode(node, chain, ctx);
|
|
824
|
+
} catch (err) {
|
|
825
|
+
const novaError = toRenderError(err);
|
|
826
|
+
if (ctx.strict) throw novaError;
|
|
827
|
+
ctx.onError(novaError);
|
|
828
|
+
return [errorNode(novaError)];
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
var renderChildArray = (nodes, chain, ctx) => {
|
|
832
|
+
const out = [];
|
|
833
|
+
for (const child of nodes) out.push(...safeRenderSingle(child, chain, ctx));
|
|
834
|
+
return out;
|
|
835
|
+
};
|
|
836
|
+
var renderChildren = (children, chain, ctx) => {
|
|
837
|
+
if (children === void 0) return [];
|
|
838
|
+
if (isArray(children)) return renderChildArray(children, chain, ctx);
|
|
839
|
+
return safeRenderSingle(children, chain, ctx);
|
|
840
|
+
};
|
|
841
|
+
var toInternal = (ctx) => ({
|
|
842
|
+
store: ctx.store,
|
|
843
|
+
registry: ctx.registry,
|
|
844
|
+
strict: ctx.strict ?? false,
|
|
845
|
+
onError: ctx.onError ?? noopOnError,
|
|
846
|
+
scopePaths: [],
|
|
847
|
+
// Built once per render call. The matcher compiles a Set and a suffix list,
|
|
848
|
+
// and doing that per node would make the cheapest branch the expensive one.
|
|
849
|
+
pass: passFor({
|
|
850
|
+
...ctx.phrases === void 0 ? {} : { phrases: ctx.phrases },
|
|
851
|
+
...ctx.phraseKeys === void 0 ? {} : { keys: ctx.phraseKeys },
|
|
852
|
+
...ctx.onPhraseMiss === void 0 ? {} : { onMiss: ctx.onPhraseMiss }
|
|
853
|
+
}),
|
|
854
|
+
where: ""
|
|
855
|
+
});
|
|
856
|
+
var renderLayout = (node, data, ctx) => {
|
|
857
|
+
const internal = toInternal(ctx);
|
|
858
|
+
return safeRenderSingle(node, createScopeChain(data), internal);
|
|
859
|
+
};
|
|
860
|
+
var render = (options) => renderLayout(options.layout, options.data ?? {}, {
|
|
861
|
+
store: options.store,
|
|
862
|
+
registry: options.registry,
|
|
863
|
+
...options.strict === void 0 ? {} : { strict: options.strict },
|
|
864
|
+
...options.onError === void 0 ? {} : { onError: options.onError },
|
|
865
|
+
...options.phrases === void 0 ? {} : { phrases: options.phrases },
|
|
866
|
+
...options.phraseKeys === void 0 ? {} : { phraseKeys: options.phraseKeys },
|
|
867
|
+
...options.onPhraseMiss === void 0 ? {} : { onPhraseMiss: options.onPhraseMiss }
|
|
868
|
+
});
|
|
869
|
+
var renderLayoutFromStore = (node, store, ctx) => {
|
|
870
|
+
const internal = toInternal(ctx);
|
|
871
|
+
return safeRenderSingle(node, createScopeChain(store.get()), internal);
|
|
872
|
+
};
|
|
873
|
+
|
|
874
|
+
// src/layout/compose.ts
|
|
875
|
+
var fillSlots = (layout, fills) => {
|
|
876
|
+
if (isSlotNode(layout)) {
|
|
877
|
+
const fill = fills[layout.slot];
|
|
878
|
+
return fill === void 0 ? layout : fill;
|
|
879
|
+
}
|
|
880
|
+
if (Array.isArray(layout)) {
|
|
881
|
+
return layout.map((node) => fillSlots(node, fills));
|
|
882
|
+
}
|
|
883
|
+
if (isComponentNode(layout)) {
|
|
884
|
+
const { children } = layout;
|
|
885
|
+
if (children === void 0) return layout;
|
|
886
|
+
const next = Array.isArray(children) ? children.map((child) => fillSlots(child, fills)) : fillSlots(children, fills);
|
|
887
|
+
return { ...layout, children: next };
|
|
888
|
+
}
|
|
889
|
+
if (isConditionalNode(layout)) {
|
|
890
|
+
return {
|
|
891
|
+
...layout,
|
|
892
|
+
then: fillSlots(layout.then, fills),
|
|
893
|
+
...layout.else === void 0 ? {} : { else: fillSlots(layout.else, fills) }
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
if (isLoopNode(layout)) {
|
|
897
|
+
return { ...layout, do: fillSlots(layout.do, fills) };
|
|
898
|
+
}
|
|
899
|
+
return layout;
|
|
900
|
+
};
|
|
901
|
+
|
|
902
|
+
// src/layout/adapter.ts
|
|
903
|
+
var NOVA_MODEL_PROP = "novaModel";
|
|
904
|
+
var NOVA_REF_PROP = "novaRef";
|
|
905
|
+
var renderNodeKey = (node, index) => {
|
|
906
|
+
if (node.key !== void 0) return `k:${node.key}`;
|
|
907
|
+
if (node.type === "component") {
|
|
908
|
+
if (node.ref !== void 0) return `c:${node.ref}`;
|
|
909
|
+
return `c:${node.name}:${index}`;
|
|
910
|
+
}
|
|
911
|
+
if (node.type === "text") return `t:${index}`;
|
|
912
|
+
if (node.type === "fragment") return `f:${index}`;
|
|
913
|
+
return `e:${node.code}:${index}`;
|
|
914
|
+
};
|
|
915
|
+
var createLayoutStore = () => {
|
|
916
|
+
const layouts = /* @__PURE__ */ new Map();
|
|
917
|
+
const get = (id) => layouts.get(id);
|
|
918
|
+
const set = (id, layout) => {
|
|
919
|
+
if (strata.exceedsDepth(layout)) {
|
|
920
|
+
throw new DefinitionValidationError(`Invalid layout for id "${id}"`, { failures: [{ id, issues: [{ code: "custom", path: [], message: strata.depthRefusal(), input: void 0 }] }] });
|
|
921
|
+
}
|
|
922
|
+
const result = LayoutNodeSchema.safeParse(layout);
|
|
923
|
+
if (!result.success) {
|
|
924
|
+
throw new DefinitionValidationError(`Invalid layout for id "${id}"`, {
|
|
925
|
+
failures: [{ id, issues: result.error.issues }]
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
layouts.set(id, layout);
|
|
929
|
+
};
|
|
930
|
+
const remove = (id) => {
|
|
931
|
+
layouts.delete(id);
|
|
932
|
+
};
|
|
933
|
+
const list = () => Array.from(layouts.keys());
|
|
934
|
+
const resolveReferences = (layout) => {
|
|
935
|
+
if (isLayoutRefNode(layout)) {
|
|
936
|
+
const target = layouts.get(layout.ref);
|
|
937
|
+
if (target === void 0) return layout;
|
|
938
|
+
return resolveReferences(target);
|
|
939
|
+
}
|
|
940
|
+
if (Array.isArray(layout)) {
|
|
941
|
+
return layout.map(resolveReferences);
|
|
942
|
+
}
|
|
943
|
+
if (isComponentNode(layout)) {
|
|
944
|
+
const children = layout.children;
|
|
945
|
+
let resolvedChildren;
|
|
946
|
+
if (children === void 0) {
|
|
947
|
+
resolvedChildren = void 0;
|
|
948
|
+
} else if (Array.isArray(children)) {
|
|
949
|
+
resolvedChildren = children.map(resolveReferences);
|
|
950
|
+
} else {
|
|
951
|
+
resolvedChildren = resolveReferences(children);
|
|
952
|
+
}
|
|
953
|
+
return {
|
|
954
|
+
...layout,
|
|
955
|
+
...resolvedChildren === void 0 ? {} : { children: resolvedChildren }
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
if (isConditionalNode(layout)) {
|
|
959
|
+
return {
|
|
960
|
+
...layout,
|
|
961
|
+
then: resolveReferences(layout.then),
|
|
962
|
+
...layout.else === void 0 ? {} : { else: resolveReferences(layout.else) }
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
if (isLoopNode(layout)) {
|
|
966
|
+
return {
|
|
967
|
+
...layout,
|
|
968
|
+
do: resolveReferences(layout.do)
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
return layout;
|
|
972
|
+
};
|
|
973
|
+
return { get, set, delete: remove, list, resolveReferences };
|
|
974
|
+
};
|
|
975
|
+
|
|
976
|
+
// src/layout/registry.ts
|
|
977
|
+
var hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
|
|
978
|
+
var isComponentMeta = (value) => {
|
|
979
|
+
if (typeof value !== "object" || value === null) return false;
|
|
980
|
+
return true;
|
|
981
|
+
};
|
|
982
|
+
var extractStaticMeta = (component) => {
|
|
983
|
+
if (typeof component !== "function" && (typeof component !== "object" || component === null)) {
|
|
984
|
+
return void 0;
|
|
985
|
+
}
|
|
986
|
+
const host = component;
|
|
987
|
+
if (!hasOwn(host, "meta")) return void 0;
|
|
988
|
+
const candidate = host.meta;
|
|
989
|
+
if (!isComponentMeta(candidate)) return void 0;
|
|
990
|
+
return candidate;
|
|
991
|
+
};
|
|
992
|
+
var isEntryShape = (value) => {
|
|
993
|
+
if (typeof value !== "object" || value === null) return false;
|
|
994
|
+
return hasOwn(value, "component");
|
|
995
|
+
};
|
|
996
|
+
var createComponentRegistry = () => {
|
|
997
|
+
const entries = /* @__PURE__ */ new Map();
|
|
998
|
+
const register = (name, component, meta) => {
|
|
999
|
+
const staticMeta = extractStaticMeta(component);
|
|
1000
|
+
const merged = { ...staticMeta ?? {}, ...meta ?? {} };
|
|
1001
|
+
entries.set(name, { component, meta: merged });
|
|
1002
|
+
};
|
|
1003
|
+
const registerAll = (batch) => {
|
|
1004
|
+
for (const name of Object.keys(batch)) {
|
|
1005
|
+
const input = batch[name];
|
|
1006
|
+
if (input === void 0) continue;
|
|
1007
|
+
if (isEntryShape(input)) {
|
|
1008
|
+
register(name, input.component, input.meta);
|
|
1009
|
+
} else {
|
|
1010
|
+
register(name, input);
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
};
|
|
1014
|
+
const get = (name) => entries.get(name);
|
|
1015
|
+
const has = (name) => entries.has(name);
|
|
1016
|
+
const list = () => Array.from(entries.keys());
|
|
1017
|
+
return { register, registerAll, get, has, list };
|
|
1018
|
+
};
|
|
1019
|
+
|
|
1020
|
+
// src/agent/palette.ts
|
|
1021
|
+
var stripProps = (schema, omit) => {
|
|
1022
|
+
const s = schema;
|
|
1023
|
+
if (s.properties === void 0) return schema;
|
|
1024
|
+
const properties = { ...s.properties };
|
|
1025
|
+
for (const p of omit) delete properties[p];
|
|
1026
|
+
const required = s.required?.filter((r) => !omit.includes(r));
|
|
1027
|
+
return { ...s, properties, ...required !== void 0 ? { required } : {} };
|
|
1028
|
+
};
|
|
1029
|
+
var paletteEntryOf = (name, meta, omitProps) => {
|
|
1030
|
+
let propsSchema;
|
|
1031
|
+
if (meta.propsSchema !== void 0) {
|
|
1032
|
+
const js = meta.propsSchema["~standard"].jsonSchema.output({ target: "draft-07" });
|
|
1033
|
+
propsSchema = omitProps !== void 0 && omitProps.length > 0 ? stripProps(js, omitProps) : js;
|
|
1034
|
+
}
|
|
1035
|
+
return { name, description: meta.description ?? "", ...propsSchema === void 0 ? {} : { propsSchema } };
|
|
1036
|
+
};
|
|
1037
|
+
var paletteFromRegistry = (registry, options = {}) => {
|
|
1038
|
+
const names = options.include ?? registry.list();
|
|
1039
|
+
const out = [];
|
|
1040
|
+
for (const name of names) {
|
|
1041
|
+
const entry = registry.get(name);
|
|
1042
|
+
if (entry === void 0) continue;
|
|
1043
|
+
out.push(paletteEntryOf(name, entry.meta, options.omitProps));
|
|
1044
|
+
}
|
|
1045
|
+
return out;
|
|
1046
|
+
};
|
|
1047
|
+
var SetByValueSchema = zod.z.object({
|
|
1048
|
+
set: zod.z.string().describe('Data path to write to, e.g. "user.name" or "items.0.title".'),
|
|
1049
|
+
value: zod.z.unknown().describe("Literal value to write at the path.")
|
|
1050
|
+
}).strict().describe("Set a field at a path to a literal value.");
|
|
1051
|
+
var SetByFromSchema = zod.z.object({
|
|
1052
|
+
set: zod.z.string().describe("Data path to write to."),
|
|
1053
|
+
from: zod.z.string().describe("Data path (or template path) to read the value from.")
|
|
1054
|
+
}).strict().describe("Set a field at a path by copying from another path.");
|
|
1055
|
+
var setValueOp = {
|
|
1056
|
+
key: "set",
|
|
1057
|
+
schema: SetByValueSchema,
|
|
1058
|
+
match: (mutation) => hasKey(mutation, "set") && hasKey(mutation, "value"),
|
|
1059
|
+
apply: (data, mutation) => {
|
|
1060
|
+
const next = setPath(data, mutation.set, mutation.value);
|
|
1061
|
+
return isObject(next) ? next : data;
|
|
1062
|
+
}
|
|
1063
|
+
};
|
|
1064
|
+
var setFromOp = {
|
|
1065
|
+
key: "set",
|
|
1066
|
+
schema: SetByFromSchema,
|
|
1067
|
+
match: (mutation) => hasKey(mutation, "set") && hasKey(mutation, "from"),
|
|
1068
|
+
apply: (data, mutation) => {
|
|
1069
|
+
const value = getPath(data, mutation.from);
|
|
1070
|
+
const next = setPath(data, mutation.set, value);
|
|
1071
|
+
return isObject(next) ? next : data;
|
|
1072
|
+
}
|
|
1073
|
+
};
|
|
1074
|
+
var ToggleSchema = zod.z.object({
|
|
1075
|
+
toggle: zod.z.string().describe("Boolean data path to flip.")
|
|
1076
|
+
}).strict().describe("Flip a boolean at the given path.");
|
|
1077
|
+
var toggleOp = {
|
|
1078
|
+
key: "toggle",
|
|
1079
|
+
schema: ToggleSchema,
|
|
1080
|
+
apply: (data, mutation) => {
|
|
1081
|
+
const current = getPath(data, mutation.toggle);
|
|
1082
|
+
const flipped = !(current === true);
|
|
1083
|
+
const next = setPath(data, mutation.toggle, flipped);
|
|
1084
|
+
return isObject(next) ? next : data;
|
|
1085
|
+
}
|
|
1086
|
+
};
|
|
1087
|
+
var IncrementSchema = zod.z.object({
|
|
1088
|
+
increment: zod.z.string().describe("Numeric data path to increment."),
|
|
1089
|
+
by: zod.z.number().optional().describe("Amount to increment by; defaults to 1.")
|
|
1090
|
+
}).strict().describe("Increment a numeric field.");
|
|
1091
|
+
var incrementOp = {
|
|
1092
|
+
key: "increment",
|
|
1093
|
+
schema: IncrementSchema,
|
|
1094
|
+
apply: (data, mutation) => {
|
|
1095
|
+
const current = getPath(data, mutation.increment);
|
|
1096
|
+
const base = typeof current === "number" ? current : 0;
|
|
1097
|
+
const by = mutation.by ?? 1;
|
|
1098
|
+
const next = setPath(data, mutation.increment, base + by);
|
|
1099
|
+
return isObject(next) ? next : data;
|
|
1100
|
+
}
|
|
1101
|
+
};
|
|
1102
|
+
var DecrementSchema = zod.z.object({
|
|
1103
|
+
decrement: zod.z.string().describe("Numeric data path to decrement."),
|
|
1104
|
+
by: zod.z.number().optional().describe("Amount to decrement by; defaults to 1.")
|
|
1105
|
+
}).strict().describe("Decrement a numeric field.");
|
|
1106
|
+
var decrementOp = {
|
|
1107
|
+
key: "decrement",
|
|
1108
|
+
schema: DecrementSchema,
|
|
1109
|
+
apply: (data, mutation) => {
|
|
1110
|
+
const current = getPath(data, mutation.decrement);
|
|
1111
|
+
const base = typeof current === "number" ? current : 0;
|
|
1112
|
+
const by = mutation.by ?? 1;
|
|
1113
|
+
const next = setPath(data, mutation.decrement, base - by);
|
|
1114
|
+
return isObject(next) ? next : data;
|
|
1115
|
+
}
|
|
1116
|
+
};
|
|
1117
|
+
var PushSchema = zod.z.object({
|
|
1118
|
+
push: zod.z.string().describe("Array data path to append to."),
|
|
1119
|
+
value: zod.z.unknown().optional().describe("Value to append.")
|
|
1120
|
+
}).strict().describe("Append a value to an array field.");
|
|
1121
|
+
var pushOp = {
|
|
1122
|
+
key: "push",
|
|
1123
|
+
schema: PushSchema,
|
|
1124
|
+
// Guard against the PushEffect navigation effect whose `push` is an object.
|
|
1125
|
+
match: (mutation) => typeof mutation.push === "string",
|
|
1126
|
+
apply: (data, mutation, ctx) => {
|
|
1127
|
+
const current = getPath(data, mutation.push);
|
|
1128
|
+
if (current !== void 0 && !isArray(current)) {
|
|
1129
|
+
if (ctx.strict) {
|
|
1130
|
+
throw new MutationError(
|
|
1131
|
+
`push: path "${mutation.push}" is not an array`,
|
|
1132
|
+
{ op: "push", path: mutation.push, reason: "wrong-type" }
|
|
1133
|
+
);
|
|
1134
|
+
}
|
|
1135
|
+
return data;
|
|
1136
|
+
}
|
|
1137
|
+
if (current === void 0 && ctx.strict) {
|
|
1138
|
+
throw new MutationError(
|
|
1139
|
+
`push: path "${mutation.push}" does not exist`,
|
|
1140
|
+
{ op: "push", path: mutation.push, reason: "missing" }
|
|
1141
|
+
);
|
|
1142
|
+
}
|
|
1143
|
+
const arr = isArray(current) ? current.slice() : [];
|
|
1144
|
+
arr.push(mutation.value);
|
|
1145
|
+
const next = setPath(data, mutation.push, arr);
|
|
1146
|
+
return isObject(next) ? next : data;
|
|
1147
|
+
}
|
|
1148
|
+
};
|
|
1149
|
+
var PopSchema = zod.z.object({
|
|
1150
|
+
pop: zod.z.string().describe("Array data path to remove the last element from.")
|
|
1151
|
+
}).strict().describe("Remove the last element from an array field.");
|
|
1152
|
+
var popOp = {
|
|
1153
|
+
key: "pop",
|
|
1154
|
+
schema: PopSchema,
|
|
1155
|
+
// Guard against the PopEffect whose `pop` is the literal `true`.
|
|
1156
|
+
match: (mutation) => typeof mutation.pop === "string",
|
|
1157
|
+
apply: (data, mutation, ctx) => {
|
|
1158
|
+
const current = getPath(data, mutation.pop);
|
|
1159
|
+
if (!isArray(current)) {
|
|
1160
|
+
if (ctx.strict) {
|
|
1161
|
+
throw new MutationError(
|
|
1162
|
+
`pop: path "${mutation.pop}" ${current === void 0 ? "does not exist" : "is not an array"}`,
|
|
1163
|
+
{ op: "pop", path: mutation.pop, reason: current === void 0 ? "missing" : "wrong-type" }
|
|
1164
|
+
);
|
|
1165
|
+
}
|
|
1166
|
+
return data;
|
|
1167
|
+
}
|
|
1168
|
+
const arr = current.slice();
|
|
1169
|
+
arr.pop();
|
|
1170
|
+
const next = setPath(data, mutation.pop, arr);
|
|
1171
|
+
return isObject(next) ? next : data;
|
|
1172
|
+
}
|
|
1173
|
+
};
|
|
1174
|
+
var RemoveAtSchema = zod.z.object({
|
|
1175
|
+
removeAt: zod.z.string().describe("Array data path to remove an element from."),
|
|
1176
|
+
index: zod.z.union([zod.z.number().int(), zod.z.string()]).describe('Index to remove. A string is a template (e.g. "{{@event.payload}}") resolved before applying.')
|
|
1177
|
+
}).strict().describe("Remove an element at a specific index of an array field.");
|
|
1178
|
+
var removeAtOp = {
|
|
1179
|
+
key: "removeAt",
|
|
1180
|
+
schema: RemoveAtSchema,
|
|
1181
|
+
apply: (data, mutation, ctx) => {
|
|
1182
|
+
const current = getPath(data, mutation.removeAt);
|
|
1183
|
+
if (!isArray(current)) {
|
|
1184
|
+
if (ctx.strict) {
|
|
1185
|
+
throw new MutationError(
|
|
1186
|
+
`removeAt: path "${mutation.removeAt}" ${current === void 0 ? "does not exist" : "is not an array"}`,
|
|
1187
|
+
{
|
|
1188
|
+
op: "removeAt",
|
|
1189
|
+
path: mutation.removeAt,
|
|
1190
|
+
reason: current === void 0 ? "missing" : "wrong-type"
|
|
1191
|
+
}
|
|
1192
|
+
);
|
|
1193
|
+
}
|
|
1194
|
+
return data;
|
|
1195
|
+
}
|
|
1196
|
+
const index = Number(mutation.index);
|
|
1197
|
+
if (!Number.isInteger(index)) return data;
|
|
1198
|
+
const arr = current.slice();
|
|
1199
|
+
arr.splice(index, 1);
|
|
1200
|
+
const next = setPath(data, mutation.removeAt, arr);
|
|
1201
|
+
return isObject(next) ? next : data;
|
|
1202
|
+
}
|
|
1203
|
+
};
|
|
1204
|
+
var MoveSchema = zod.z.object({
|
|
1205
|
+
move: zod.z.string().describe("Array data path to reorder within."),
|
|
1206
|
+
from: zod.z.union([zod.z.number().int(), zod.z.string()]).describe('Index to move. A string is a template (e.g. "{{@event.payload}}") resolved before applying.'),
|
|
1207
|
+
to: zod.z.union([zod.z.number().int(), zod.z.string()]).describe("Destination index. A string is a template resolved before applying.")
|
|
1208
|
+
}).strict().describe("Move an array element from one index to another.");
|
|
1209
|
+
var moveOp = {
|
|
1210
|
+
key: "move",
|
|
1211
|
+
schema: MoveSchema,
|
|
1212
|
+
apply: (data, mutation, ctx) => {
|
|
1213
|
+
const current = getPath(data, mutation.move);
|
|
1214
|
+
if (!isArray(current)) {
|
|
1215
|
+
if (ctx.strict) {
|
|
1216
|
+
throw new MutationError(
|
|
1217
|
+
`move: path "${mutation.move}" ${current === void 0 ? "does not exist" : "is not an array"}`,
|
|
1218
|
+
{
|
|
1219
|
+
op: "move",
|
|
1220
|
+
path: mutation.move,
|
|
1221
|
+
reason: current === void 0 ? "missing" : "wrong-type"
|
|
1222
|
+
}
|
|
1223
|
+
);
|
|
1224
|
+
}
|
|
1225
|
+
return data;
|
|
1226
|
+
}
|
|
1227
|
+
const from = Number(mutation.from);
|
|
1228
|
+
const to = Number(mutation.to);
|
|
1229
|
+
if (!Number.isInteger(from) || !Number.isInteger(to)) return data;
|
|
1230
|
+
if (from < 0 || from >= current.length) return data;
|
|
1231
|
+
const arr = current.slice();
|
|
1232
|
+
const [item] = arr.splice(from, 1);
|
|
1233
|
+
arr.splice(Math.max(0, Math.min(to, arr.length)), 0, item);
|
|
1234
|
+
const next = setPath(data, mutation.move, arr);
|
|
1235
|
+
return isObject(next) ? next : data;
|
|
1236
|
+
}
|
|
1237
|
+
};
|
|
1238
|
+
var ClearSchema = zod.z.object({
|
|
1239
|
+
clear: zod.z.string().describe("Array or object data path to clear.")
|
|
1240
|
+
}).strict().describe("Clear an array or object field.");
|
|
1241
|
+
var clearOp = {
|
|
1242
|
+
key: "clear",
|
|
1243
|
+
schema: ClearSchema,
|
|
1244
|
+
apply: (data, mutation, ctx) => {
|
|
1245
|
+
const current = getPath(data, mutation.clear);
|
|
1246
|
+
if (isArray(current)) {
|
|
1247
|
+
const next2 = setPath(data, mutation.clear, []);
|
|
1248
|
+
return isObject(next2) ? next2 : data;
|
|
1249
|
+
}
|
|
1250
|
+
if (isObject(current)) {
|
|
1251
|
+
const next2 = setPath(data, mutation.clear, {});
|
|
1252
|
+
return isObject(next2) ? next2 : data;
|
|
1253
|
+
}
|
|
1254
|
+
if (ctx.strict) {
|
|
1255
|
+
throw new MutationError(
|
|
1256
|
+
`clear: path "${mutation.clear}" ${current === void 0 ? "does not exist" : "is not an array or object"}`,
|
|
1257
|
+
{
|
|
1258
|
+
op: "clear",
|
|
1259
|
+
path: mutation.clear,
|
|
1260
|
+
reason: current === void 0 ? "missing" : "wrong-type"
|
|
1261
|
+
}
|
|
1262
|
+
);
|
|
1263
|
+
}
|
|
1264
|
+
const next = deletePath(data, mutation.clear);
|
|
1265
|
+
return isObject(next) ? next : data;
|
|
1266
|
+
}
|
|
1267
|
+
};
|
|
1268
|
+
var ResetSchema = zod.z.object({
|
|
1269
|
+
reset: zod.z.string().describe("Data path to reset to its initial (definition.data) value.")
|
|
1270
|
+
}).strict().describe("Reset a field to its initial value from the action definition.");
|
|
1271
|
+
var resetOp = {
|
|
1272
|
+
key: "reset",
|
|
1273
|
+
schema: ResetSchema,
|
|
1274
|
+
apply: (data, mutation, ctx) => {
|
|
1275
|
+
const initialValue = getPath(ctx.initial, mutation.reset);
|
|
1276
|
+
const next = setPath(data, mutation.reset, initialValue);
|
|
1277
|
+
return isObject(next) ? next : data;
|
|
1278
|
+
}
|
|
1279
|
+
};
|
|
1280
|
+
|
|
1281
|
+
// src/action/mutations/ops/index.ts
|
|
1282
|
+
var OPS = [
|
|
1283
|
+
setValueOp,
|
|
1284
|
+
setFromOp,
|
|
1285
|
+
toggleOp,
|
|
1286
|
+
incrementOp,
|
|
1287
|
+
decrementOp,
|
|
1288
|
+
pushOp,
|
|
1289
|
+
popOp,
|
|
1290
|
+
removeAtOp,
|
|
1291
|
+
moveOp,
|
|
1292
|
+
clearOp,
|
|
1293
|
+
resetOp
|
|
1294
|
+
];
|
|
1295
|
+
var MutationSchema = zod.z.union(
|
|
1296
|
+
OPS.map((op) => op.schema)
|
|
1297
|
+
).describe("A single immutable mutation applied to the action data.");
|
|
1298
|
+
|
|
1299
|
+
// src/action/mutations/registry.ts
|
|
1300
|
+
var toDispatchOp = (op) => ({
|
|
1301
|
+
key: op.key,
|
|
1302
|
+
match: op.match ?? ((mutation) => hasKey(mutation, op.key)),
|
|
1303
|
+
run: (data, mutation, ctx) => op.apply(data, op.schema.parse(mutation), ctx)
|
|
1304
|
+
});
|
|
1305
|
+
var DISPATCH = OPS.map(toDispatchOp);
|
|
1306
|
+
var findOp = (mutation) => {
|
|
1307
|
+
for (const op of DISPATCH) {
|
|
1308
|
+
if (op.match(mutation)) return op;
|
|
1309
|
+
}
|
|
1310
|
+
return void 0;
|
|
1311
|
+
};
|
|
1312
|
+
var buildCtx = (opts) => ({
|
|
1313
|
+
initial: opts.initial ?? {},
|
|
1314
|
+
strict: opts.strict ?? false
|
|
1315
|
+
});
|
|
1316
|
+
var applyMutations = (data, mutations, opts = {}) => {
|
|
1317
|
+
if (mutations.length === 0) return data;
|
|
1318
|
+
const ctx = buildCtx(opts);
|
|
1319
|
+
let current = data;
|
|
1320
|
+
for (const mutation of mutations) {
|
|
1321
|
+
if (!isObject(mutation)) continue;
|
|
1322
|
+
const op = findOp(mutation);
|
|
1323
|
+
if (op === void 0) continue;
|
|
1324
|
+
current = op.run(current, mutation, ctx);
|
|
1325
|
+
}
|
|
1326
|
+
return current;
|
|
1327
|
+
};
|
|
1328
|
+
var HttpEndpointSchema = zod.z.object({
|
|
1329
|
+
url: zod.z.string().describe('Template URL, e.g. "/api/users/{{$.userId}}".'),
|
|
1330
|
+
method: zod.z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).describe("HTTP method."),
|
|
1331
|
+
headers: zod.z.record(zod.z.string(), zod.z.string()).optional().describe("Static request headers."),
|
|
1332
|
+
request: zod.z.unknown().optional().describe(
|
|
1333
|
+
'Transform config run by the injected evaluator over the ACTION DATA to build the request body \u2014 EVALUATED ON EVERY CALL, so body values can follow screen state. Static parts are literal JSON; a dynamic part is an evaluator op over the data root, e.g. { "q": { "$ref": "$.search" } } makes body field q carry the current $.search each call. Requires an injected transform.'
|
|
1334
|
+
),
|
|
1335
|
+
response: zod.z.unknown().optional().describe(
|
|
1336
|
+
"Transform config run by the injected evaluator over the reply as received (`$` is the reply \u2014 object, array, or scalar) to produce the value stored at `target`. Requires an injected transform."
|
|
1337
|
+
),
|
|
1338
|
+
target: zod.z.string().optional().describe("Data path to store the result at on success."),
|
|
1339
|
+
errorTarget: zod.z.string().optional().describe("Data path to store the error at on failure."),
|
|
1340
|
+
timeoutMs: zod.z.number().int().positive().optional().describe("How long to wait for the reply, in ms, before the call fails to onError. Defaults to the shell default (30000). Set it on an endpoint that is slow by nature \u2014 a model call that may take minutes.")
|
|
1341
|
+
}).strict().describe("A named HTTP call. `request`/`response` shape the body/reply via the injected transform.");
|
|
1342
|
+
var FunctionEndpointSchema = zod.z.object({
|
|
1343
|
+
fn: zod.z.string().describe(
|
|
1344
|
+
"Key of a function registered in `ShellConfig.functions`. The host must register the name before the action runs."
|
|
1345
|
+
),
|
|
1346
|
+
target: zod.z.string().optional().describe("Data path to store the return value at on success."),
|
|
1347
|
+
errorTarget: zod.z.string().optional().describe("Data path to store the error at on failure."),
|
|
1348
|
+
timeoutMs: zod.z.number().int().positive().optional().describe("How long to wait for the reply, in ms, before the call fails to onError. Defaults to the shell default (30000). Set it on an endpoint that is slow by nature \u2014 a model call that may take minutes.")
|
|
1349
|
+
}).strict().describe("A named local function call. Handler is provided via `ShellConfig.functions`.");
|
|
1350
|
+
var EndpointConfigSchema = zod.z.union([HttpEndpointSchema, FunctionEndpointSchema]).describe("An endpoint \u2014 either an HTTP call or a local function.");
|
|
1351
|
+
var StepSchema = zod.z.lazy(
|
|
1352
|
+
() => zod.z.union([MutationSchema, EffectSchema]).describe("A step is either a mutation or an effect.")
|
|
1353
|
+
);
|
|
1354
|
+
var CallEffectSchema = zod.z.lazy(
|
|
1355
|
+
() => zod.z.object({
|
|
1356
|
+
call: zod.z.string().describe("Name of the endpoint to invoke."),
|
|
1357
|
+
onSuccess: zod.z.array(StepSchema).optional().describe("Steps to run after a successful response."),
|
|
1358
|
+
onError: zod.z.array(StepSchema).optional().describe("Steps to run after an error response (with @error scope available).")
|
|
1359
|
+
}).strict().describe("Invoke a named endpoint with optional success/error step branches.")
|
|
1360
|
+
);
|
|
1361
|
+
var EmitEffectSchema = zod.z.object({
|
|
1362
|
+
emit: zod.z.object({
|
|
1363
|
+
channel: zod.z.string().describe("Channel name to publish on."),
|
|
1364
|
+
payload: zod.z.unknown().optional().describe("Payload to publish; templates are resolved against the current data.")
|
|
1365
|
+
}).strict().describe("Channel + payload to publish.")
|
|
1366
|
+
}).strict().describe("Publish a payload to a message channel.");
|
|
1367
|
+
var PushEffectSchema = zod.z.object({
|
|
1368
|
+
push: zod.z.object({
|
|
1369
|
+
action: zod.z.string().describe("Definition id of the action to push onto a canvas \u2014 MUST be an id that actually exists (an unknown id fails at click time, invisible to a mount check)."),
|
|
1370
|
+
canvas: zod.z.string().optional().describe("Canvas id to push onto; defaults to the current canvas."),
|
|
1371
|
+
input: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Initial input merged into the new action data. Keys must belong to the target action's declared input contract \u2014 invented keys are silently useless."),
|
|
1372
|
+
with: zod.z.array(zod.z.string()).optional().describe("Fragment ids to compose the action with before it is instantiated. Each wraps the action (the action fills its `{ slot }`) and contributes its triggers/data; the action wins on conflict. See ActionFragment.")
|
|
1373
|
+
}).strict().describe("Push parameters.")
|
|
1374
|
+
}).strict().describe("Push a new action onto a canvas (escapes via onNavigate callback).");
|
|
1375
|
+
var PopEffectSchema = zod.z.object({
|
|
1376
|
+
pop: zod.z.literal(true).describe("Sentinel literal \u2014 must be true.")
|
|
1377
|
+
}).strict().describe("Pop the current action (escapes via onNavigate callback).");
|
|
1378
|
+
var ReplaceEffectSchema = zod.z.object({
|
|
1379
|
+
replace: zod.z.object({
|
|
1380
|
+
action: zod.z.string().describe("Definition id of the replacement action."),
|
|
1381
|
+
canvas: zod.z.string().optional().describe("Canvas id to replace on; defaults to the current canvas."),
|
|
1382
|
+
input: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Initial input merged into the new action data."),
|
|
1383
|
+
with: zod.z.array(zod.z.string()).optional().describe("Fragment ids to compose the action with before it is instantiated. Each wraps the action (the action fills its `{ slot }`) and contributes its triggers/data; the action wins on conflict. See ActionFragment.")
|
|
1384
|
+
}).strict().describe("Replace parameters.")
|
|
1385
|
+
}).strict().describe("Replace the current action (escapes via onNavigate callback).");
|
|
1386
|
+
var PopToEffectSchema = zod.z.object({
|
|
1387
|
+
popTo: zod.z.object({
|
|
1388
|
+
canvas: zod.z.string().optional().describe("Canvas id to pop on; defaults to the current canvas."),
|
|
1389
|
+
instance: zod.z.string().describe("Pop the canvas until this instance id is on top (no-op if absent).")
|
|
1390
|
+
}).strict().describe("Pop-to-instance parameters.")
|
|
1391
|
+
}).strict().describe("Pop a canvas down to a given instance (escapes via onNavigate callback).");
|
|
1392
|
+
var ResetToEffectSchema = zod.z.object({
|
|
1393
|
+
resetTo: zod.z.object({
|
|
1394
|
+
action: zod.z.string().describe("Definition id of the new root action."),
|
|
1395
|
+
canvas: zod.z.string().optional().describe("Canvas id to reset; defaults to the current canvas."),
|
|
1396
|
+
input: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Initial input merged into the new root action."),
|
|
1397
|
+
with: zod.z.array(zod.z.string()).optional().describe("Fragment ids to compose the action with. See ActionFragment.")
|
|
1398
|
+
}).strict().describe("Reset parameters.")
|
|
1399
|
+
}).strict().describe("Clear a canvas and push a single new root action (escapes via onNavigate callback).");
|
|
1400
|
+
var RemoveInstanceEffectSchema = zod.z.object({
|
|
1401
|
+
removeInstance: zod.z.object({
|
|
1402
|
+
canvas: zod.z.string().optional().describe("Canvas id to remove from; defaults to the current canvas."),
|
|
1403
|
+
instance: zod.z.string().describe("Instance id to unmount and drop from the stack (no-op if absent).")
|
|
1404
|
+
}).strict().describe("Remove-instance parameters.")
|
|
1405
|
+
}).strict().describe("Remove one instance anywhere in a canvas stack (escapes via onNavigate callback).");
|
|
1406
|
+
var RemoveSelfEffectSchema = zod.z.object({
|
|
1407
|
+
removeSelf: zod.z.literal(true).describe("Sentinel literal \u2014 must be true. Removes the firing instance (desugars to removeInstance).")
|
|
1408
|
+
}).strict().describe("Close the firing instance \u2014 the list-card X (escapes via onNavigate callback).");
|
|
1409
|
+
var ReconcileEffectSchema = zod.z.object({
|
|
1410
|
+
reconcile: zod.z.object({
|
|
1411
|
+
to: zod.z.string().describe('Binding to the desired list, e.g. "$.tools" \u2014 an array of rows; anything else is an empty list.'),
|
|
1412
|
+
action: zod.z.string().describe('The row field naming the action to place, e.g. "tool_id". Rows without it are skipped.'),
|
|
1413
|
+
input: zod.z.string().optional().describe("The row field holding that action's input (an object), if any."),
|
|
1414
|
+
canvas: zod.z.string().optional().describe("Canvas id to reconcile; defaults to the current canvas."),
|
|
1415
|
+
own: zod.z.enum(["pushed", "canvas"]).optional().describe('What this step may remove: "pushed" (default) only what this action placed there; "canvas" everything on it \u2014 for an action that owns the canvas outright.'),
|
|
1416
|
+
with: zod.z.array(zod.z.string()).optional().describe("Fragment ids to compose each placed action with. See ActionFragment.")
|
|
1417
|
+
}).strict().describe("Reconcile parameters.")
|
|
1418
|
+
}).strict().describe("Make a canvas hold exactly the actions a list names: push the missing, remove the unlisted, keep the rest mounted (escapes via onNavigate callback).");
|
|
1419
|
+
var ReloadEffectSchema = zod.z.object({
|
|
1420
|
+
reload: zod.z.literal(true).describe("Sentinel literal \u2014 must be true. Re-runs this instance's mount hook.")
|
|
1421
|
+
}).strict().describe("Re-read the firing instance in place \u2014 the list-card open.");
|
|
1422
|
+
var EffectSchema = zod.z.lazy(
|
|
1423
|
+
() => zod.z.union([CallEffectSchema, EmitEffectSchema, PushEffectSchema, PopEffectSchema, ReplaceEffectSchema, PopToEffectSchema, ResetToEffectSchema, RemoveInstanceEffectSchema, RemoveSelfEffectSchema, ReconcileEffectSchema, ReloadEffectSchema]).describe("An effect that touches the outside world.")
|
|
1424
|
+
);
|
|
1425
|
+
|
|
1426
|
+
// src/action/schemas/lifecycle.ts
|
|
1427
|
+
var LifecycleConfigSchema = zod.z.object({
|
|
1428
|
+
mount: zod.z.array(StepSchema).optional().describe("Steps to run when the action mounts."),
|
|
1429
|
+
unmount: zod.z.array(StepSchema).optional().describe("Steps to run when the action unmounts."),
|
|
1430
|
+
suspend: zod.z.array(StepSchema).optional().describe("Steps to run when the action is suspended."),
|
|
1431
|
+
resume: zod.z.array(StepSchema).optional().describe("Steps to run when the action resumes.")
|
|
1432
|
+
}).strict().describe("Lifecycle hooks for the action runtime state machine.");
|
|
1433
|
+
var TriggerConfigSchema = zod.z.object({
|
|
1434
|
+
event: zod.z.string().optional().describe(`UI event type to listen for: "ui:click" (activations, incl. table rows), "ui:model" (an input's value changed), "ui:key".`),
|
|
1435
|
+
message: zod.z.string().optional().describe("Message bus channel name to listen on (fired by an `emit` step, possibly from another action)."),
|
|
1436
|
+
ref: zod.z.string().optional().describe("Component ref to filter events by \u2014 MUST match a `ref` carried by a node in this action's layout; a trigger on a ref no layout node carries never fires."),
|
|
1437
|
+
key: zod.z.string().optional().describe('Key to filter "ui:key" events by, e.g. "ArrowDown".'),
|
|
1438
|
+
do: zod.z.array(StepSchema).describe(`Ordered steps to execute when the trigger fires. Steps may reference the firing event as "@event" \u2014 "@event.payload" is the fired value (a table row click: the row's clickKey/rowKey field; an input's ui:model: the typed text).`)
|
|
1439
|
+
}).strict().refine((trigger) => trigger.event !== void 0 || trigger.message !== void 0, {
|
|
1440
|
+
message: 'A trigger must specify either "event" or "message".'
|
|
1441
|
+
}).describe("Binds an event or message source to an ordered sequence of steps.");
|
|
1442
|
+
|
|
1443
|
+
// src/action/schemas/index.ts
|
|
1444
|
+
var ActionDefinitionSchema = zod.z.object({
|
|
1445
|
+
id: zod.z.string().describe("Stable definition id."),
|
|
1446
|
+
name: zod.z.string().optional().describe("Human-readable name."),
|
|
1447
|
+
description: zod.z.string().optional().describe("Free-form description."),
|
|
1448
|
+
title: zod.z.string().optional().describe(
|
|
1449
|
+
"A resolvable label for this instance, evaluated against its own data (e.g. '{{$.view.record.name}}'). Exposed as `instance.title` on a canvas's actionLayout scope so stack-nav chrome can label crumbs/tabs; falls back to `name` then the action id."
|
|
1450
|
+
),
|
|
1451
|
+
layout: zod.z.union([zod.z.string(), LayoutNodeSchema]).optional().describe("Either a layout id stored in the layout store, or an inline LayoutNode."),
|
|
1452
|
+
data: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Static default data merged with input on mount."),
|
|
1453
|
+
input: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe(
|
|
1454
|
+
"JSON Schema of the data keys an opener may seed when loading this action \u2014 its public, openable-input contract (author in Zod, convert with z.toJSONSchema). Fields must be a subset of `data`. Descriptive only: the runtime does not validate loads against it."
|
|
1455
|
+
),
|
|
1456
|
+
triggers: zod.z.array(TriggerConfigSchema).optional().describe("Event/message triggers."),
|
|
1457
|
+
endpoints: zod.z.record(zod.z.string(), EndpointConfigSchema).optional().describe("Named endpoints \u2014 HTTP calls or local functions."),
|
|
1458
|
+
lifecycle: LifecycleConfigSchema.optional().describe("Lifecycle hooks.")
|
|
1459
|
+
}).strict().describe("Definition of an action: layout + data + behavior.");
|
|
1460
|
+
var ActionFragmentSchema = zod.z.object({
|
|
1461
|
+
kind: zod.z.literal("fragment").describe("Discriminator \u2014 marks this as an abstract, merge-only fragment."),
|
|
1462
|
+
id: zod.z.string().describe("Stable fragment id, referenced from a push/replace `with: [...]`."),
|
|
1463
|
+
name: zod.z.string().optional().describe("Human-readable name."),
|
|
1464
|
+
description: zod.z.string().optional().describe("Free-form description."),
|
|
1465
|
+
layout: zod.z.union([zod.z.string(), LayoutNodeSchema]).optional().describe('The wrapping (chrome) layout, or a layout id. Put a `{ slot: "body" }` node where the composing action\'s own layout is dropped in.'),
|
|
1466
|
+
data: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Partial default data; deep-merged under the action (the action wins on conflict)."),
|
|
1467
|
+
triggers: zod.z.array(TriggerConfigSchema).optional().describe("Pre-wired triggers (e.g. a modal's close/cancel). Concatenated before the action's triggers."),
|
|
1468
|
+
endpoints: zod.z.record(zod.z.string(), EndpointConfigSchema).optional().describe("Named endpoints, merged under the action (the action wins on a name clash)."),
|
|
1469
|
+
lifecycle: LifecycleConfigSchema.optional().describe("Lifecycle hooks; per-hook steps run before the action's.")
|
|
1470
|
+
}).strict().describe("A reusable partial action \u2014 layout + wired behavior \u2014 merged into a concrete action at a push `with`. Abstract: only exists merged, never instantiated alone.");
|
|
1471
|
+
|
|
1472
|
+
// src/action/compose.ts
|
|
1473
|
+
var HOOKS = ["mount", "unmount", "suspend", "resume"];
|
|
1474
|
+
var composeAction = (action, fragments) => {
|
|
1475
|
+
if (fragments.length === 0) return action;
|
|
1476
|
+
let layout = action.layout;
|
|
1477
|
+
for (const frag of fragments) {
|
|
1478
|
+
const wrap = frag.layout;
|
|
1479
|
+
if (wrap === void 0) continue;
|
|
1480
|
+
if (typeof wrap === "string") {
|
|
1481
|
+
layout = wrap;
|
|
1482
|
+
continue;
|
|
1483
|
+
}
|
|
1484
|
+
layout = fillSlots(wrap, layout === void 0 ? {} : { body: layout });
|
|
1485
|
+
}
|
|
1486
|
+
const data = {};
|
|
1487
|
+
for (const frag of fragments) Object.assign(data, frag.data ?? {});
|
|
1488
|
+
Object.assign(data, action.data ?? {});
|
|
1489
|
+
const triggers = [
|
|
1490
|
+
...fragments.flatMap((f) => f.triggers ?? []),
|
|
1491
|
+
...action.triggers ?? []
|
|
1492
|
+
];
|
|
1493
|
+
const endpoints = {};
|
|
1494
|
+
for (const frag of fragments) Object.assign(endpoints, frag.endpoints ?? {});
|
|
1495
|
+
Object.assign(endpoints, action.endpoints ?? {});
|
|
1496
|
+
const lifecycle = {};
|
|
1497
|
+
for (const hook of HOOKS) {
|
|
1498
|
+
const steps = [
|
|
1499
|
+
...fragments.flatMap((f) => f.lifecycle?.[hook] ?? []),
|
|
1500
|
+
...action.lifecycle?.[hook] ?? []
|
|
1501
|
+
];
|
|
1502
|
+
if (steps.length > 0) lifecycle[hook] = steps;
|
|
1503
|
+
}
|
|
1504
|
+
return {
|
|
1505
|
+
id: action.id,
|
|
1506
|
+
...action.name === void 0 ? {} : { name: action.name },
|
|
1507
|
+
...action.description === void 0 ? {} : { description: action.description },
|
|
1508
|
+
...action.title === void 0 ? {} : { title: action.title },
|
|
1509
|
+
...action.input === void 0 ? {} : { input: action.input },
|
|
1510
|
+
...layout === void 0 ? {} : { layout },
|
|
1511
|
+
...Object.keys(data).length > 0 ? { data } : {},
|
|
1512
|
+
...triggers.length > 0 ? { triggers } : {},
|
|
1513
|
+
...Object.keys(endpoints).length > 0 ? { endpoints } : {},
|
|
1514
|
+
...Object.keys(lifecycle).length > 0 ? { lifecycle } : {}
|
|
1515
|
+
};
|
|
1516
|
+
};
|
|
1517
|
+
|
|
1518
|
+
// src/agent/affordances.ts
|
|
1519
|
+
var KEY_PATTERN = /\$\.([A-Za-z_][A-Za-z0-9_]*)/g;
|
|
1520
|
+
var VAR_PATTERN = /\$([A-Za-z_][A-Za-z0-9_]*)\./g;
|
|
1521
|
+
var collectInteractive = (layout) => {
|
|
1522
|
+
const refs = [];
|
|
1523
|
+
const models = [];
|
|
1524
|
+
const boundKeys = /* @__PURE__ */ new Set();
|
|
1525
|
+
const suspects = /* @__PURE__ */ new Set();
|
|
1526
|
+
let componentCount = 0;
|
|
1527
|
+
const scanString = (value, scope) => {
|
|
1528
|
+
for (const match of value.matchAll(KEY_PATTERN)) {
|
|
1529
|
+
const key = match[1];
|
|
1530
|
+
if (key !== void 0) boundKeys.add(key);
|
|
1531
|
+
}
|
|
1532
|
+
for (const match of value.matchAll(VAR_PATTERN)) {
|
|
1533
|
+
const name = match[1];
|
|
1534
|
+
if (name !== void 0 && !scope.has(name)) suspects.add(`$${name}.`);
|
|
1535
|
+
}
|
|
1536
|
+
};
|
|
1537
|
+
const walk2 = (node, scope) => {
|
|
1538
|
+
if (typeof node === "string") return scanString(node, scope);
|
|
1539
|
+
if (Array.isArray(node)) {
|
|
1540
|
+
for (const child of node) walk2(child, scope);
|
|
1541
|
+
return;
|
|
1542
|
+
}
|
|
1543
|
+
if (node === null || typeof node !== "object") return;
|
|
1544
|
+
const record = node;
|
|
1545
|
+
const loopVar = record["for"] !== void 0 && typeof record["as"] === "string" ? record["as"] : void 0;
|
|
1546
|
+
const childScope = loopVar !== void 0 ? /* @__PURE__ */ new Set([...scope, loopVar]) : scope;
|
|
1547
|
+
const component = typeof record["component"] === "string" ? record["component"] : void 0;
|
|
1548
|
+
if (component !== void 0) {
|
|
1549
|
+
componentCount += 1;
|
|
1550
|
+
if (typeof record["ref"] === "string" && record["ref"].length > 0) {
|
|
1551
|
+
refs.push({ ref: record["ref"], component, via: "ref" });
|
|
1552
|
+
}
|
|
1553
|
+
if (typeof record["model"] === "string" && record["model"].length > 0) {
|
|
1554
|
+
models.push({ path: record["model"], component });
|
|
1555
|
+
}
|
|
1556
|
+
const props = record["props"];
|
|
1557
|
+
if (props !== null && typeof props === "object" && !Array.isArray(props)) {
|
|
1558
|
+
for (const [key, value] of Object.entries(props)) {
|
|
1559
|
+
if (key.endsWith("Ref") && typeof value === "string" && value.length > 0) {
|
|
1560
|
+
refs.push({ ref: value, component, via: key });
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
for (const value of Object.values(record)) walk2(value, childScope);
|
|
1566
|
+
};
|
|
1567
|
+
walk2(layout, /* @__PURE__ */ new Set());
|
|
1568
|
+
return {
|
|
1569
|
+
refs,
|
|
1570
|
+
models,
|
|
1571
|
+
boundKeys: [...boundKeys].sort(),
|
|
1572
|
+
suspectBindings: [...suspects].sort(),
|
|
1573
|
+
componentCount
|
|
1574
|
+
};
|
|
1575
|
+
};
|
|
1576
|
+
|
|
1577
|
+
// src/action/grammar.ts
|
|
1578
|
+
var MUTATION_KEYS = [...new Set(OPS.map((op) => op.key))];
|
|
1579
|
+
var MATCHERS = OPS.map((op) => op.match ?? ((step) => op.key in step));
|
|
1580
|
+
var isMutationStep = (step) => MATCHERS.some((match) => match(step));
|
|
1581
|
+
var rootOf = (path) => path.split(".")[0] ?? path;
|
|
1582
|
+
|
|
1583
|
+
// src/action/audit.ts
|
|
1584
|
+
var collectChannels = (definition) => {
|
|
1585
|
+
const emits = /* @__PURE__ */ new Set();
|
|
1586
|
+
const listens = /* @__PURE__ */ new Set();
|
|
1587
|
+
const walkSteps = (list) => {
|
|
1588
|
+
if (!Array.isArray(list)) return;
|
|
1589
|
+
for (const step of list) {
|
|
1590
|
+
if (!isRecord(step)) continue;
|
|
1591
|
+
const emit = step["emit"];
|
|
1592
|
+
if (isRecord(emit) && typeof emit["channel"] === "string") emits.add(emit["channel"]);
|
|
1593
|
+
if (typeof step["call"] === "string") {
|
|
1594
|
+
walkSteps(step["onSuccess"]);
|
|
1595
|
+
walkSteps(step["onError"]);
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
};
|
|
1599
|
+
for (const trigger of definition.triggers ?? []) {
|
|
1600
|
+
if (typeof trigger.message === "string") listens.add(trigger.message);
|
|
1601
|
+
walkSteps(trigger.do);
|
|
1602
|
+
}
|
|
1603
|
+
for (const hook of Object.values(definition.lifecycle ?? {})) walkSteps(hook);
|
|
1604
|
+
return { emits: [...emits].sort(), listens: [...listens].sort() };
|
|
1605
|
+
};
|
|
1606
|
+
var firstSegment = (path) => {
|
|
1607
|
+
const segment = path.split(".")[0];
|
|
1608
|
+
return segment === void 0 || segment.length === 0 ? path : segment;
|
|
1609
|
+
};
|
|
1610
|
+
var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1611
|
+
var navTargetOf = (step) => {
|
|
1612
|
+
for (const key of ["push", "replace", "resetTo"]) {
|
|
1613
|
+
const value = step[key];
|
|
1614
|
+
if (isRecord(value) && typeof value["action"] === "string") {
|
|
1615
|
+
const input = value["input"];
|
|
1616
|
+
return { action: value["action"], ...isRecord(input) ? { input } : {} };
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
return void 0;
|
|
1620
|
+
};
|
|
1621
|
+
var auditAction = (definition, options) => {
|
|
1622
|
+
const issues = [];
|
|
1623
|
+
const dataKeys = new Set(Object.keys(definition.data ?? {}));
|
|
1624
|
+
const endpointNames = new Set(Object.keys(definition.endpoints ?? {}));
|
|
1625
|
+
const steps = [];
|
|
1626
|
+
const pushSteps = (list) => {
|
|
1627
|
+
if (!Array.isArray(list)) return;
|
|
1628
|
+
for (const step of list) {
|
|
1629
|
+
if (!isRecord(step)) continue;
|
|
1630
|
+
steps.push(step);
|
|
1631
|
+
if (typeof step["call"] === "string") {
|
|
1632
|
+
pushSteps(step["onSuccess"]);
|
|
1633
|
+
pushSteps(step["onError"]);
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
};
|
|
1637
|
+
for (const trigger of definition.triggers ?? []) pushSteps(trigger.do);
|
|
1638
|
+
for (const hook of Object.values(definition.lifecycle ?? {})) pushSteps(hook);
|
|
1639
|
+
for (const step of steps) {
|
|
1640
|
+
const call = step["call"];
|
|
1641
|
+
if (typeof call === "string" && !endpointNames.has(call)) {
|
|
1642
|
+
issues.push(`step calls endpoint "${call}" but endpoints has no "${call}"`);
|
|
1643
|
+
}
|
|
1644
|
+
for (const key of MUTATION_KEYS) {
|
|
1645
|
+
const path = step[key];
|
|
1646
|
+
if (typeof path === "string" && path.length > 0 && !dataKeys.has(firstSegment(path))) {
|
|
1647
|
+
issues.push(`step "${key}: ${path}" writes a key with no default in data`);
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
const nav = navTargetOf(step);
|
|
1651
|
+
if (nav !== void 0 && options?.catalog !== void 0) {
|
|
1652
|
+
const entry = options.catalog.find((candidate) => candidate.id === nav.action);
|
|
1653
|
+
if (entry === void 0 && nav.action !== definition.id) {
|
|
1654
|
+
issues.push(`step pushes action "${nav.action}" which is not in the catalog`);
|
|
1655
|
+
continue;
|
|
1656
|
+
}
|
|
1657
|
+
const properties = entry?.input?.["properties"];
|
|
1658
|
+
if (nav.input !== void 0 && isRecord(properties)) {
|
|
1659
|
+
for (const key of Object.keys(nav.input)) {
|
|
1660
|
+
if (!(key in properties)) {
|
|
1661
|
+
issues.push(`push to "${nav.action}" seeds input key "${key}" which is not in its input contract`);
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
for (const [name, endpoint] of Object.entries(definition.endpoints ?? {})) {
|
|
1668
|
+
for (const field of ["target", "errorTarget"]) {
|
|
1669
|
+
const target = endpoint[field];
|
|
1670
|
+
if (typeof target === "string" && target.length > 0 && !dataKeys.has(firstSegment(target))) {
|
|
1671
|
+
issues.push(`endpoint "${name}" ${field} "${target}" has no default in data`);
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
if (options?.channels !== void 0) {
|
|
1676
|
+
const known = new Set(options.channels);
|
|
1677
|
+
const usage = collectChannels(definition);
|
|
1678
|
+
for (const channel of usage.listens) {
|
|
1679
|
+
if (!known.has(channel) && !usage.emits.includes(channel)) {
|
|
1680
|
+
issues.push(`trigger listens on channel "${channel}" which nothing is known to emit`);
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
for (const channel of usage.emits) {
|
|
1684
|
+
if (!known.has(channel) && !usage.listens.includes(channel)) {
|
|
1685
|
+
issues.push(`step emits channel "${channel}" which nothing is known to listen on`);
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
if (definition.layout !== void 0 && typeof definition.layout !== "string") {
|
|
1690
|
+
const surface = collectInteractive(definition.layout);
|
|
1691
|
+
for (const key of surface.boundKeys) {
|
|
1692
|
+
if (!dataKeys.has(key)) {
|
|
1693
|
+
issues.push(`layout binds "$.${key}" but data has no "${key}" default`);
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
for (const suspect of surface.suspectBindings) {
|
|
1697
|
+
issues.push(
|
|
1698
|
+
`layout binding "${suspect}\u2026" is malformed \u2014 the data root is "$." ("$.key"), and "$name." is only legal for a loop variable declared by an enclosing for/as`
|
|
1699
|
+
);
|
|
1700
|
+
}
|
|
1701
|
+
const layoutRefs = new Set(surface.refs.map((entry) => entry.ref));
|
|
1702
|
+
const triggerRefs = new Set(
|
|
1703
|
+
(definition.triggers ?? []).map((trigger) => trigger.ref).filter((ref) => typeof ref === "string")
|
|
1704
|
+
);
|
|
1705
|
+
for (const ref of layoutRefs) {
|
|
1706
|
+
if (!triggerRefs.has(ref)) {
|
|
1707
|
+
issues.push(`layout ref "${ref}" has no trigger \u2014 dead chrome`);
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
for (const ref of triggerRefs) {
|
|
1711
|
+
if (!layoutRefs.has(ref)) {
|
|
1712
|
+
issues.push(`trigger listens on ref "${ref}" but no layout node carries it`);
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
return { ok: issues.length === 0, issues };
|
|
1717
|
+
};
|
|
1718
|
+
|
|
1719
|
+
// src/action/runtime/endpoints.ts
|
|
1720
|
+
var stringifyForBody = (value) => {
|
|
1721
|
+
if (typeof value === "string") return value;
|
|
1722
|
+
try {
|
|
1723
|
+
return JSON.stringify(value);
|
|
1724
|
+
} catch {
|
|
1725
|
+
return void 0;
|
|
1726
|
+
}
|
|
1727
|
+
};
|
|
1728
|
+
var resolveHeaders = (headers, chain) => {
|
|
1729
|
+
if (headers === void 0) return void 0;
|
|
1730
|
+
const out = {};
|
|
1731
|
+
for (const key of Object.keys(headers)) {
|
|
1732
|
+
const value = resolve(headers[key], chain);
|
|
1733
|
+
out[key] = typeof value === "string" ? value : String(value ?? "");
|
|
1734
|
+
}
|
|
1735
|
+
return out;
|
|
1736
|
+
};
|
|
1737
|
+
var defaultFetch = () => {
|
|
1738
|
+
throw new Error("No fetch implementation provided to action runtime");
|
|
1739
|
+
};
|
|
1740
|
+
var tryParseJson = async (response) => {
|
|
1741
|
+
try {
|
|
1742
|
+
return await response.json();
|
|
1743
|
+
} catch {
|
|
1744
|
+
try {
|
|
1745
|
+
return await response.text();
|
|
1746
|
+
} catch {
|
|
1747
|
+
return void 0;
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
};
|
|
1751
|
+
var DEFAULT_ENDPOINT_TIMEOUT_MS = 3e4;
|
|
1752
|
+
var callEndpoint = async (options) => {
|
|
1753
|
+
const wait = options.endpoint.timeoutMs ?? options.timeoutMs ?? DEFAULT_ENDPOINT_TIMEOUT_MS;
|
|
1754
|
+
const expiry = new AbortController();
|
|
1755
|
+
const signal = options.signal === void 0 ? expiry.signal : AbortSignal.any([options.signal, expiry.signal]);
|
|
1756
|
+
const called = { ...options, signal };
|
|
1757
|
+
let timer;
|
|
1758
|
+
const expired = new Promise((settle) => {
|
|
1759
|
+
timer = setTimeout(() => {
|
|
1760
|
+
settle({ ok: false, error: { status: 0, message: `no reply within ${wait}ms`, data: void 0, timedOut: true } });
|
|
1761
|
+
expiry.abort();
|
|
1762
|
+
}, wait);
|
|
1763
|
+
});
|
|
1764
|
+
try {
|
|
1765
|
+
const call = "fn" in options.endpoint ? callFunctionEndpoint(options.endpoint, called) : callHttpEndpoint(options.endpoint, called);
|
|
1766
|
+
return await Promise.race([call, expired]);
|
|
1767
|
+
} finally {
|
|
1768
|
+
clearTimeout(timer);
|
|
1769
|
+
}
|
|
1770
|
+
};
|
|
1771
|
+
var callHttpEndpoint = async (endpoint, { data, fetch: fetchFn = defaultFetch, transform, signal }) => {
|
|
1772
|
+
const chain = createScopeChain(data);
|
|
1773
|
+
const resolvedUrl = resolve(endpoint.url, chain);
|
|
1774
|
+
const url = typeof resolvedUrl === "string" ? resolvedUrl : String(resolvedUrl ?? "");
|
|
1775
|
+
const headers = resolveHeaders(endpoint.headers, chain);
|
|
1776
|
+
let body;
|
|
1777
|
+
if (endpoint.request !== void 0) {
|
|
1778
|
+
if (transform === void 0) {
|
|
1779
|
+
return { ok: false, error: { status: 0, message: "endpoint declares `request` but no transform was injected into the shell", data: void 0 } };
|
|
1780
|
+
}
|
|
1781
|
+
try {
|
|
1782
|
+
body = stringifyForBody(transform(endpoint.request, data));
|
|
1783
|
+
} catch (err) {
|
|
1784
|
+
const message = err instanceof Error ? err.message : "request transform failed";
|
|
1785
|
+
return { ok: false, error: { status: 0, message, data: void 0 } };
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
let response;
|
|
1789
|
+
try {
|
|
1790
|
+
response = await fetchFn(url, {
|
|
1791
|
+
method: endpoint.method,
|
|
1792
|
+
...headers === void 0 ? {} : { headers },
|
|
1793
|
+
...body === void 0 ? {} : { body },
|
|
1794
|
+
...signal === void 0 ? {} : { signal }
|
|
1795
|
+
});
|
|
1796
|
+
} catch (err) {
|
|
1797
|
+
const isAbort = err instanceof Error && err.name === "AbortError";
|
|
1798
|
+
const message = err instanceof Error ? err.message : "fetch failed";
|
|
1799
|
+
if (isAbort) return { ok: false, error: { status: 0, message, data: void 0, aborted: true } };
|
|
1800
|
+
return { ok: false, error: { status: 0, message, data: void 0 } };
|
|
1801
|
+
}
|
|
1802
|
+
if (!response.ok) {
|
|
1803
|
+
const failed = await tryParseJson(response);
|
|
1804
|
+
const message = hasKey(failed, "message") && typeof failed["message"] === "string" ? failed["message"] : `HTTP ${response.status}`;
|
|
1805
|
+
return { ok: false, error: { status: response.status, message, data: failed } };
|
|
1806
|
+
}
|
|
1807
|
+
if (response.status === 204 || response.status === 205) {
|
|
1808
|
+
return { ok: true, data: void 0, status: response.status };
|
|
1809
|
+
}
|
|
1810
|
+
let payload;
|
|
1811
|
+
try {
|
|
1812
|
+
payload = await response.json();
|
|
1813
|
+
} catch {
|
|
1814
|
+
return { ok: false, error: { status: response.status, message: `the reply is not JSON (HTTP ${response.status})`, data: void 0 } };
|
|
1815
|
+
}
|
|
1816
|
+
let result = payload;
|
|
1817
|
+
if (endpoint.response !== void 0) {
|
|
1818
|
+
if (transform === void 0) {
|
|
1819
|
+
return { ok: false, error: { status: response.status, message: "endpoint declares `response` but no transform was injected into the shell", data: payload } };
|
|
1820
|
+
}
|
|
1821
|
+
try {
|
|
1822
|
+
result = transform(endpoint.response, payload);
|
|
1823
|
+
} catch (err) {
|
|
1824
|
+
const message = err instanceof Error ? err.message : "response transform failed";
|
|
1825
|
+
return { ok: false, error: { status: response.status, message, data: payload } };
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
const onChange = laterBodiesOf(response, endpoint.response, transform);
|
|
1829
|
+
return { ok: true, data: result, status: response.status, ...onChange === void 0 ? {} : { onChange } };
|
|
1830
|
+
};
|
|
1831
|
+
var laterBodiesOf = (response, config, transform) => {
|
|
1832
|
+
const subscribe = response.onChange;
|
|
1833
|
+
if (subscribe === void 0) return void 0;
|
|
1834
|
+
if (config !== void 0 && transform === void 0) return void 0;
|
|
1835
|
+
return (handler) => subscribe((body) => {
|
|
1836
|
+
if (config === void 0 || transform === void 0) {
|
|
1837
|
+
handler(body);
|
|
1838
|
+
return;
|
|
1839
|
+
}
|
|
1840
|
+
let shaped;
|
|
1841
|
+
try {
|
|
1842
|
+
shaped = transform(config, body);
|
|
1843
|
+
} catch {
|
|
1844
|
+
return;
|
|
1845
|
+
}
|
|
1846
|
+
handler(shaped);
|
|
1847
|
+
});
|
|
1848
|
+
};
|
|
1849
|
+
var callFunctionEndpoint = async (endpoint, { data, signal, functions }) => {
|
|
1850
|
+
if (signal === void 0) {
|
|
1851
|
+
throw new Error("callEndpoint: function variant requires an AbortSignal");
|
|
1852
|
+
}
|
|
1853
|
+
const handler = functions?.[endpoint.fn];
|
|
1854
|
+
if (handler === void 0) {
|
|
1855
|
+
throw new Error(`callEndpoint: function "${endpoint.fn}" is not registered`);
|
|
1856
|
+
}
|
|
1857
|
+
try {
|
|
1858
|
+
const result = await handler(data, signal);
|
|
1859
|
+
if (signal.aborted) {
|
|
1860
|
+
return {
|
|
1861
|
+
ok: false,
|
|
1862
|
+
error: { status: 0, message: "aborted", data: void 0, aborted: true }
|
|
1863
|
+
};
|
|
1864
|
+
}
|
|
1865
|
+
return { ok: true, data: result, status: 0 };
|
|
1866
|
+
} catch (err) {
|
|
1867
|
+
const isAbort = err instanceof Error && err.name === "AbortError";
|
|
1868
|
+
const message = err instanceof Error ? err.message : "function failed";
|
|
1869
|
+
if (isAbort) {
|
|
1870
|
+
return { ok: false, error: { status: 0, message, data: void 0, aborted: true } };
|
|
1871
|
+
}
|
|
1872
|
+
return { ok: false, error: { status: 0, message, data: void 0 } };
|
|
1873
|
+
}
|
|
1874
|
+
};
|
|
1875
|
+
|
|
1876
|
+
// src/action/runtime/cause.ts
|
|
1877
|
+
var CAUSE_DEPTH_LIMIT = 64;
|
|
1878
|
+
var CAUSE_HOPS_LIMIT = 1024;
|
|
1879
|
+
var minted = /* @__PURE__ */ new WeakSet();
|
|
1880
|
+
var mint = (cause) => {
|
|
1881
|
+
minted.add(cause);
|
|
1882
|
+
return cause;
|
|
1883
|
+
};
|
|
1884
|
+
var isMinted = (value) => minted.has(value);
|
|
1885
|
+
var rootCause = () => mint({ depth: 0, root: { hops: 0 } });
|
|
1886
|
+
var asCause = (value) => typeof value === "object" && value !== null && isMinted(value) ? value : void 0;
|
|
1887
|
+
var nextCause = (parent) => {
|
|
1888
|
+
if (parent === void 0) return rootCause();
|
|
1889
|
+
parent.root.hops += 1;
|
|
1890
|
+
return mint({ depth: parent.depth + 1, root: parent.root });
|
|
1891
|
+
};
|
|
1892
|
+
var isRunaway = (cause) => cause.depth > CAUSE_DEPTH_LIMIT || cause.root.hops > CAUSE_HOPS_LIMIT;
|
|
1893
|
+
var runawayMessage = (cause, what) => `${what} stopped: its chain ran ${cause.depth} hops deep and ${cause.root.hops} hops in total from the gesture that started it (limits ${CAUSE_DEPTH_LIMIT} and ${CAUSE_HOPS_LIMIT}). A trigger that re-emits its own channel, or a mount that reloads itself, never ends.`;
|
|
1894
|
+
var ambient;
|
|
1895
|
+
var withCause = (cause, run) => {
|
|
1896
|
+
const before = ambient;
|
|
1897
|
+
ambient = cause;
|
|
1898
|
+
try {
|
|
1899
|
+
return run();
|
|
1900
|
+
} finally {
|
|
1901
|
+
ambient = before;
|
|
1902
|
+
}
|
|
1903
|
+
};
|
|
1904
|
+
var ambientCause = () => ambient;
|
|
1905
|
+
|
|
1906
|
+
// src/action/runtime/next-task.ts
|
|
1907
|
+
var viaChannel = () => {
|
|
1908
|
+
const queue = [];
|
|
1909
|
+
const channel = new MessageChannel();
|
|
1910
|
+
channel.port1.onmessage = () => {
|
|
1911
|
+
queue.shift()?.();
|
|
1912
|
+
};
|
|
1913
|
+
return (task) => {
|
|
1914
|
+
queue.push(task);
|
|
1915
|
+
channel.port2.postMessage(null);
|
|
1916
|
+
};
|
|
1917
|
+
};
|
|
1918
|
+
var pick = () => {
|
|
1919
|
+
const host = globalThis;
|
|
1920
|
+
if ("setImmediate" in host && typeof host.setImmediate === "function") {
|
|
1921
|
+
const immediate = host.setImmediate;
|
|
1922
|
+
return (task) => void immediate(task);
|
|
1923
|
+
}
|
|
1924
|
+
if (typeof MessageChannel === "function") return viaChannel();
|
|
1925
|
+
return (task) => void setTimeout(task, 0);
|
|
1926
|
+
};
|
|
1927
|
+
var scheduler;
|
|
1928
|
+
var nextTask = (task) => {
|
|
1929
|
+
scheduler ??= pick();
|
|
1930
|
+
scheduler(task);
|
|
1931
|
+
};
|
|
1932
|
+
|
|
1933
|
+
// src/action/runtime/steps.ts
|
|
1934
|
+
var now = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
|
|
1935
|
+
var noopOnError2 = (_error) => {
|
|
1936
|
+
};
|
|
1937
|
+
var resolveMutationValues = (list, chain, extras) => {
|
|
1938
|
+
return list.map((m) => {
|
|
1939
|
+
if ("set" in m && "value" in m) {
|
|
1940
|
+
return { ...m, value: resolve(m.value, chain, extras) };
|
|
1941
|
+
}
|
|
1942
|
+
if ("push" in m && typeof m.push === "string" && "value" in m) {
|
|
1943
|
+
return { ...m, value: resolve(m.value, chain, extras) };
|
|
1944
|
+
}
|
|
1945
|
+
if ("removeAt" in m && typeof m.index === "string") {
|
|
1946
|
+
return { ...m, index: Number(resolve(m.index, chain, extras)) };
|
|
1947
|
+
}
|
|
1948
|
+
if ("move" in m) {
|
|
1949
|
+
return {
|
|
1950
|
+
...m,
|
|
1951
|
+
from: typeof m.from === "string" ? Number(resolve(m.from, chain, extras)) : m.from,
|
|
1952
|
+
to: typeof m.to === "string" ? Number(resolve(m.to, chain, extras)) : m.to
|
|
1953
|
+
};
|
|
1954
|
+
}
|
|
1955
|
+
return m;
|
|
1956
|
+
});
|
|
1957
|
+
};
|
|
1958
|
+
var writeTarget = (dataStore, target, value) => {
|
|
1959
|
+
if (target === void 0) return;
|
|
1960
|
+
dataStore.update((curr) => {
|
|
1961
|
+
const next = setPath(curr, target, value);
|
|
1962
|
+
return isObject(next) ? next : curr;
|
|
1963
|
+
});
|
|
1964
|
+
};
|
|
1965
|
+
var raiseUnknown = async (message, onError, ctx, strictError) => {
|
|
1966
|
+
if (onError) {
|
|
1967
|
+
const errorExtras = {
|
|
1968
|
+
...ctx.extras,
|
|
1969
|
+
"@error": { message, status: 0 }
|
|
1970
|
+
};
|
|
1971
|
+
await executeSteps(onError, { ...ctx, extras: errorExtras });
|
|
1972
|
+
return;
|
|
1973
|
+
}
|
|
1974
|
+
if (ctx.lifecycleHook !== void 0) {
|
|
1975
|
+
throw new LifecycleError(message, { hook: ctx.lifecycleHook });
|
|
1976
|
+
}
|
|
1977
|
+
if (ctx.strict && strictError !== void 0) throw strictError;
|
|
1978
|
+
};
|
|
1979
|
+
var runCall = async (callName, onSuccess, onError, ctx) => {
|
|
1980
|
+
const raw = ctx.endpoints[callName];
|
|
1981
|
+
if (raw === void 0) {
|
|
1982
|
+
await raiseUnknown(`unknown endpoint: ${callName}`, onError, ctx);
|
|
1983
|
+
return;
|
|
1984
|
+
}
|
|
1985
|
+
let endpoint = raw;
|
|
1986
|
+
if ("fn" in raw) {
|
|
1987
|
+
const chain = createScopeChain(ctx.dataStore.get());
|
|
1988
|
+
const fn = String(resolve(raw.fn, chain, ctx.extras) ?? "");
|
|
1989
|
+
endpoint = { ...raw, fn };
|
|
1990
|
+
if (ctx.functions[fn] === void 0) {
|
|
1991
|
+
await raiseUnknown(`unknown function: ${fn}`, onError, ctx, new UnknownFunctionError(fn));
|
|
1992
|
+
return;
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
const ticket = ctx.calls?.begin(callName);
|
|
1996
|
+
const t0 = now();
|
|
1997
|
+
const result = await callEndpoint({
|
|
1998
|
+
endpoint,
|
|
1999
|
+
data: ctx.dataStore.get(),
|
|
2000
|
+
fetch: ctx.fetch,
|
|
2001
|
+
transform: ctx.transform,
|
|
2002
|
+
signal: ctx.signal,
|
|
2003
|
+
functions: ctx.functions,
|
|
2004
|
+
...ctx.endpointTimeoutMs === void 0 ? {} : { timeoutMs: ctx.endpointTimeoutMs }
|
|
2005
|
+
});
|
|
2006
|
+
if (ctx.signal.aborted) return;
|
|
2007
|
+
if (!result.ok && result.error.aborted === true) return;
|
|
2008
|
+
ctx.onEndpoint?.({
|
|
2009
|
+
name: callName,
|
|
2010
|
+
kind: "fn" in endpoint ? "fn" : "http",
|
|
2011
|
+
ok: result.ok,
|
|
2012
|
+
status: result.ok ? result.status : result.error.status,
|
|
2013
|
+
ms: now() - t0
|
|
2014
|
+
});
|
|
2015
|
+
if (result.ok) {
|
|
2016
|
+
const isCurrent = ticket === void 0 || ctx.calls === void 0 || ctx.calls.land(callName, ticket);
|
|
2017
|
+
if (isCurrent) {
|
|
2018
|
+
writeTarget(ctx.dataStore, endpoint.target, result.data);
|
|
2019
|
+
const { dataStore } = ctx;
|
|
2020
|
+
const { target } = endpoint;
|
|
2021
|
+
if (result.onChange !== void 0 && ticket !== void 0 && ctx.calls !== void 0) {
|
|
2022
|
+
ctx.calls.follow(callName, ticket, result.onChange((data) => writeTarget(dataStore, target, data)));
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
if (onSuccess) await executeSteps(onSuccess, ctx);
|
|
2026
|
+
return;
|
|
2027
|
+
}
|
|
2028
|
+
writeTarget(ctx.dataStore, endpoint.errorTarget, result.error);
|
|
2029
|
+
if (onError) {
|
|
2030
|
+
const errorExtras = { ...ctx.extras, "@error": result.error };
|
|
2031
|
+
await executeSteps(onError, { ...ctx, extras: errorExtras });
|
|
2032
|
+
return;
|
|
2033
|
+
}
|
|
2034
|
+
if (ctx.lifecycleHook !== void 0) {
|
|
2035
|
+
throw new LifecycleError(`endpoint '${callName}' failed: ${result.error.message}`, {
|
|
2036
|
+
hook: ctx.lifecycleHook
|
|
2037
|
+
});
|
|
2038
|
+
}
|
|
2039
|
+
};
|
|
2040
|
+
var navigate = (effect, ctx) => {
|
|
2041
|
+
const { onNavigate } = ctx;
|
|
2042
|
+
if (onNavigate === void 0) return;
|
|
2043
|
+
withCause(ctx.cause, () => onNavigate(effect));
|
|
2044
|
+
};
|
|
2045
|
+
var resolveInputMap = (input, ctx) => {
|
|
2046
|
+
const chain = createScopeChain(ctx.dataStore.get());
|
|
2047
|
+
return Object.fromEntries(
|
|
2048
|
+
Object.entries(input).map(([key, value]) => [key, resolve(value, chain, ctx.extras)])
|
|
2049
|
+
);
|
|
2050
|
+
};
|
|
2051
|
+
var resolveNavTarget = (nav, ctx) => {
|
|
2052
|
+
const chain = createScopeChain(ctx.dataStore.get());
|
|
2053
|
+
const out = { ...nav, action: String(resolve(nav.action, chain, ctx.extras) ?? "") };
|
|
2054
|
+
if (nav.input !== void 0) out.input = resolveInputMap(nav.input, ctx);
|
|
2055
|
+
return out;
|
|
2056
|
+
};
|
|
2057
|
+
var resolveNavInput = (effect, ctx) => {
|
|
2058
|
+
if ("push" in effect) return { push: resolveNavTarget(effect.push, ctx) };
|
|
2059
|
+
if ("replace" in effect) return { replace: resolveNavTarget(effect.replace, ctx) };
|
|
2060
|
+
if ("resetTo" in effect) return { resetTo: resolveNavTarget(effect.resetTo, ctx) };
|
|
2061
|
+
if ("popTo" in effect) {
|
|
2062
|
+
const chain = createScopeChain(ctx.dataStore.get());
|
|
2063
|
+
return { popTo: { ...effect.popTo, instance: String(resolve(effect.popTo.instance, chain, ctx.extras) ?? "") } };
|
|
2064
|
+
}
|
|
2065
|
+
if ("removeInstance" in effect) {
|
|
2066
|
+
const chain = createScopeChain(ctx.dataStore.get());
|
|
2067
|
+
return { removeInstance: { ...effect.removeInstance, instance: String(resolve(effect.removeInstance.instance, chain, ctx.extras) ?? "") } };
|
|
2068
|
+
}
|
|
2069
|
+
return effect;
|
|
2070
|
+
};
|
|
2071
|
+
var resolveReconcile = (step, ctx) => {
|
|
2072
|
+
const { to, action, input, ...rest } = step.reconcile;
|
|
2073
|
+
const rows = resolve(to, createScopeChain(ctx.dataStore.get()), ctx.extras);
|
|
2074
|
+
const desired = (Array.isArray(rows) ? rows : []).flatMap((row) => {
|
|
2075
|
+
if (!isObject(row)) return [];
|
|
2076
|
+
const actionId = row[action];
|
|
2077
|
+
if (typeof actionId !== "string" || actionId === "") return [];
|
|
2078
|
+
const seeded = input === void 0 ? void 0 : row[input];
|
|
2079
|
+
return [isObject(seeded) ? { actionId, input: seeded } : { actionId }];
|
|
2080
|
+
});
|
|
2081
|
+
return { reconcile: { ...rest, desired } };
|
|
2082
|
+
};
|
|
2083
|
+
var executeSteps = async (steps, ctx) => {
|
|
2084
|
+
let buffer = [];
|
|
2085
|
+
const flush = () => {
|
|
2086
|
+
if (buffer.length === 0) return;
|
|
2087
|
+
const list = buffer;
|
|
2088
|
+
buffer = [];
|
|
2089
|
+
const chain = createScopeChain(ctx.dataStore.get());
|
|
2090
|
+
const resolved = resolveMutationValues(list, chain, ctx.extras);
|
|
2091
|
+
ctx.dataStore.update((curr) => applyMutations(curr, resolved));
|
|
2092
|
+
};
|
|
2093
|
+
for (const step of steps) {
|
|
2094
|
+
if (ctx.signal.aborted) {
|
|
2095
|
+
buffer = [];
|
|
2096
|
+
return;
|
|
2097
|
+
}
|
|
2098
|
+
if (isMutationStep(step)) {
|
|
2099
|
+
buffer.push(step);
|
|
2100
|
+
continue;
|
|
2101
|
+
}
|
|
2102
|
+
flush();
|
|
2103
|
+
if ("call" in step) {
|
|
2104
|
+
await runCall(step.call, step.onSuccess, step.onError, ctx);
|
|
2105
|
+
if (ctx.signal.aborted) return;
|
|
2106
|
+
continue;
|
|
2107
|
+
}
|
|
2108
|
+
if ("emit" in step) {
|
|
2109
|
+
const data = ctx.dataStore.get();
|
|
2110
|
+
const chain = createScopeChain(data);
|
|
2111
|
+
const resolvedChannel = resolve(step.emit.channel, chain, ctx.extras);
|
|
2112
|
+
const channel = typeof resolvedChannel === "string" ? resolvedChannel : String(resolvedChannel ?? "");
|
|
2113
|
+
const payload = step.emit.payload === void 0 ? void 0 : resolve(step.emit.payload, chain, ctx.extras);
|
|
2114
|
+
const { messageBus, cause } = ctx;
|
|
2115
|
+
nextTask(() => messageBus.publish(channel, payload, cause));
|
|
2116
|
+
continue;
|
|
2117
|
+
}
|
|
2118
|
+
if ("push" in step) {
|
|
2119
|
+
navigate(resolveNavInput(step, ctx), ctx);
|
|
2120
|
+
continue;
|
|
2121
|
+
}
|
|
2122
|
+
if ("pop" in step) {
|
|
2123
|
+
navigate(step, ctx);
|
|
2124
|
+
continue;
|
|
2125
|
+
}
|
|
2126
|
+
if ("replace" in step) {
|
|
2127
|
+
navigate(resolveNavInput(step, ctx), ctx);
|
|
2128
|
+
continue;
|
|
2129
|
+
}
|
|
2130
|
+
if ("popTo" in step) {
|
|
2131
|
+
navigate(resolveNavInput(step, ctx), ctx);
|
|
2132
|
+
continue;
|
|
2133
|
+
}
|
|
2134
|
+
if ("resetTo" in step) {
|
|
2135
|
+
navigate(resolveNavInput(step, ctx), ctx);
|
|
2136
|
+
continue;
|
|
2137
|
+
}
|
|
2138
|
+
if ("removeInstance" in step) {
|
|
2139
|
+
navigate(resolveNavInput(step, ctx), ctx);
|
|
2140
|
+
continue;
|
|
2141
|
+
}
|
|
2142
|
+
if ("reconcile" in step) {
|
|
2143
|
+
navigate(resolveReconcile(step, ctx), ctx);
|
|
2144
|
+
continue;
|
|
2145
|
+
}
|
|
2146
|
+
if ("removeSelf" in step) {
|
|
2147
|
+
navigate(step, ctx);
|
|
2148
|
+
continue;
|
|
2149
|
+
}
|
|
2150
|
+
if ("reload" in step) {
|
|
2151
|
+
await ctx.onReload?.(ctx.cause);
|
|
2152
|
+
if (ctx.signal.aborted) return;
|
|
2153
|
+
continue;
|
|
2154
|
+
}
|
|
2155
|
+
}
|
|
2156
|
+
flush();
|
|
2157
|
+
};
|
|
2158
|
+
|
|
2159
|
+
// src/action/runtime/lifecycle.ts
|
|
2160
|
+
var buildInitialData = (definition, input) => {
|
|
2161
|
+
const defaults = definition.data ?? {};
|
|
2162
|
+
return structuredClone({ ...defaults, ...input ?? {} });
|
|
2163
|
+
};
|
|
2164
|
+
var runLifecycleHook = async (hook, definition, buildContext) => {
|
|
2165
|
+
const lifecycle = definition.lifecycle;
|
|
2166
|
+
if (lifecycle === void 0) return;
|
|
2167
|
+
const steps = lifecycle[hook];
|
|
2168
|
+
if (steps === void 0 || steps.length === 0) return;
|
|
2169
|
+
const ctx = { ...buildContext(), lifecycleHook: hook };
|
|
2170
|
+
try {
|
|
2171
|
+
await executeSteps(steps, ctx);
|
|
2172
|
+
} catch (err) {
|
|
2173
|
+
if (!ctx.strict) {
|
|
2174
|
+
ctx.onError(
|
|
2175
|
+
err instanceof LifecycleError ? err : new LifecycleError(
|
|
2176
|
+
err instanceof Error ? err.message : String(err),
|
|
2177
|
+
{ hook },
|
|
2178
|
+
{ cause: err }
|
|
2179
|
+
)
|
|
2180
|
+
);
|
|
2181
|
+
return;
|
|
2182
|
+
}
|
|
2183
|
+
if (err instanceof LifecycleError) throw err;
|
|
2184
|
+
throw new LifecycleError(
|
|
2185
|
+
err instanceof Error ? err.message : String(err),
|
|
2186
|
+
{ hook },
|
|
2187
|
+
{ cause: err }
|
|
2188
|
+
);
|
|
2189
|
+
}
|
|
2190
|
+
};
|
|
2191
|
+
|
|
2192
|
+
// src/action/runtime/model-bindings.ts
|
|
2193
|
+
var walk = (node, out) => {
|
|
2194
|
+
if (node.type === "component") {
|
|
2195
|
+
if (node.model !== void 0) {
|
|
2196
|
+
out.push({ ref: node.model.ref, path: node.model.path });
|
|
2197
|
+
}
|
|
2198
|
+
for (const child of node.children) walk(child, out);
|
|
2199
|
+
return;
|
|
2200
|
+
}
|
|
2201
|
+
if (node.type === "fragment") {
|
|
2202
|
+
for (const child of node.children) walk(child, out);
|
|
2203
|
+
}
|
|
2204
|
+
};
|
|
2205
|
+
var collectModelBindings = (nodes) => {
|
|
2206
|
+
const out = [];
|
|
2207
|
+
for (const node of nodes) walk(node, out);
|
|
2208
|
+
return out;
|
|
2209
|
+
};
|
|
2210
|
+
|
|
2211
|
+
// src/action/runtime/render.ts
|
|
2212
|
+
var isLayoutNode2 = (value) => {
|
|
2213
|
+
if (value === null) return true;
|
|
2214
|
+
const t = typeof value;
|
|
2215
|
+
if (t === "string" || t === "number" || t === "boolean") return true;
|
|
2216
|
+
if (isArray(value)) return true;
|
|
2217
|
+
if (isObject(value)) return true;
|
|
2218
|
+
return false;
|
|
2219
|
+
};
|
|
2220
|
+
var renderRuntime = (definition, dataStore, ctx) => {
|
|
2221
|
+
const layout = definition.layout;
|
|
2222
|
+
if (layout === void 0) return [];
|
|
2223
|
+
if (typeof layout === "string") {
|
|
2224
|
+
const target = ctx.store.get(layout);
|
|
2225
|
+
if (target === void 0) return [];
|
|
2226
|
+
return renderLayoutFromStore(target, dataStore, ctx);
|
|
2227
|
+
}
|
|
2228
|
+
if (!isLayoutNode2(layout)) return [];
|
|
2229
|
+
return renderLayoutFromStore(layout, dataStore, ctx);
|
|
2230
|
+
};
|
|
2231
|
+
|
|
2232
|
+
// src/action/runtime/triggers.ts
|
|
2233
|
+
var eventRef = (event) => {
|
|
2234
|
+
if (!hasKey(event, "ref")) return void 0;
|
|
2235
|
+
const candidate = event["ref"];
|
|
2236
|
+
return typeof candidate === "string" ? candidate : void 0;
|
|
2237
|
+
};
|
|
2238
|
+
var eventKey = (event) => {
|
|
2239
|
+
if (!hasKey(event, "key")) return void 0;
|
|
2240
|
+
const candidate = event["key"];
|
|
2241
|
+
return typeof candidate === "string" ? candidate : void 0;
|
|
2242
|
+
};
|
|
2243
|
+
var toNovaError = (err) => {
|
|
2244
|
+
if (err instanceof NovaError) return err;
|
|
2245
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2246
|
+
return new NovaError(ErrorCodes.lifecycle, message, {}, { cause: err });
|
|
2247
|
+
};
|
|
2248
|
+
var fireTrigger = (trigger, buildContext, event, cause) => {
|
|
2249
|
+
const built = buildContext();
|
|
2250
|
+
if (built.signal.aborted) return;
|
|
2251
|
+
if (built.suspended === true) return;
|
|
2252
|
+
if (isRunaway(cause)) {
|
|
2253
|
+
const what = trigger.message === void 0 ? "A trigger" : `The trigger on "${trigger.message}"`;
|
|
2254
|
+
built.onError(new NovaError(ErrorCodes.runaway, runawayMessage(cause, what), { channel: trigger.message, depth: cause.depth, hops: cause.root.hops }));
|
|
2255
|
+
return;
|
|
2256
|
+
}
|
|
2257
|
+
const base = { ...built, cause };
|
|
2258
|
+
const ctx = event === void 0 ? base : { ...base, extras: { ...base.extras, "@event": event } };
|
|
2259
|
+
void executeSteps(trigger.do, ctx).catch((err) => {
|
|
2260
|
+
ctx.onError(toNovaError(err));
|
|
2261
|
+
});
|
|
2262
|
+
};
|
|
2263
|
+
var eventOrigin = (event) => {
|
|
2264
|
+
if (!hasKey(event, "origin")) return void 0;
|
|
2265
|
+
const candidate = event["origin"];
|
|
2266
|
+
return typeof candidate === "string" ? candidate : void 0;
|
|
2267
|
+
};
|
|
2268
|
+
var attachTriggers = (triggers, eventBus, messageBus, buildContext, ownInstanceId) => {
|
|
2269
|
+
const unsubscribes = [];
|
|
2270
|
+
for (const trigger of triggers) {
|
|
2271
|
+
if (trigger.event !== void 0) {
|
|
2272
|
+
const expectedRef = trigger.ref;
|
|
2273
|
+
const expectedKey = trigger.key;
|
|
2274
|
+
const triggerType = trigger.event;
|
|
2275
|
+
const off = eventBus.on(triggerType, (event) => {
|
|
2276
|
+
const origin = eventOrigin(event);
|
|
2277
|
+
if (origin !== void 0 && origin !== ownInstanceId) return;
|
|
2278
|
+
if (expectedRef !== void 0 && eventRef(event) !== expectedRef) return;
|
|
2279
|
+
if (expectedKey !== void 0 && eventKey(event) !== expectedKey) return;
|
|
2280
|
+
fireTrigger(trigger, buildContext, event, rootCause());
|
|
2281
|
+
});
|
|
2282
|
+
unsubscribes.push(off);
|
|
2283
|
+
continue;
|
|
2284
|
+
}
|
|
2285
|
+
if (trigger.message !== void 0) {
|
|
2286
|
+
const off = messageBus.subscribe(trigger.message, (payload, _from, cause) => {
|
|
2287
|
+
fireTrigger(trigger, buildContext, { payload }, nextCause(asCause(cause)));
|
|
2288
|
+
});
|
|
2289
|
+
unsubscribes.push(off);
|
|
2290
|
+
}
|
|
2291
|
+
}
|
|
2292
|
+
const detach = () => {
|
|
2293
|
+
for (const off of unsubscribes) off();
|
|
2294
|
+
};
|
|
2295
|
+
return { detach };
|
|
2296
|
+
};
|
|
2297
|
+
|
|
2298
|
+
// src/action/runtime/runtime.ts
|
|
2299
|
+
var defaultInstanceIdFactory = createIdFactory("act");
|
|
2300
|
+
var createActionRuntime = (config) => {
|
|
2301
|
+
const definition = config.definition;
|
|
2302
|
+
const initialData = buildInitialData(definition, config.input);
|
|
2303
|
+
const initialSnapshot = structuredClone(initialData);
|
|
2304
|
+
const dataStore = createDataStore(initialData);
|
|
2305
|
+
const abortController = new AbortController();
|
|
2306
|
+
const strict = config.strict ?? false;
|
|
2307
|
+
const onError = config.onError ?? noopOnError2;
|
|
2308
|
+
const instanceIdFn = config.instanceIdFn ?? defaultInstanceIdFactory;
|
|
2309
|
+
const instance = {
|
|
2310
|
+
id: config.instanceId ?? instanceIdFn(),
|
|
2311
|
+
definitionId: definition.id,
|
|
2312
|
+
canvasId: config.canvasId ?? "default",
|
|
2313
|
+
status: "initializing",
|
|
2314
|
+
data: dataStore.get()
|
|
2315
|
+
};
|
|
2316
|
+
const statusSubscribers = [];
|
|
2317
|
+
let triggerHandle;
|
|
2318
|
+
let modelWriteOff;
|
|
2319
|
+
const modelListeners = /* @__PURE__ */ new Map();
|
|
2320
|
+
dataStore.subscribe((next) => {
|
|
2321
|
+
instance.data = next;
|
|
2322
|
+
});
|
|
2323
|
+
const ledger = /* @__PURE__ */ new Map();
|
|
2324
|
+
const entryOf = (endpoint) => {
|
|
2325
|
+
const existing = ledger.get(endpoint);
|
|
2326
|
+
if (existing !== void 0) return existing;
|
|
2327
|
+
const created = { issued: 0, landed: 0 };
|
|
2328
|
+
ledger.set(endpoint, created);
|
|
2329
|
+
return created;
|
|
2330
|
+
};
|
|
2331
|
+
const calls = {
|
|
2332
|
+
begin: (endpoint) => {
|
|
2333
|
+
const entry = entryOf(endpoint);
|
|
2334
|
+
entry.issued += 1;
|
|
2335
|
+
return entry.issued;
|
|
2336
|
+
},
|
|
2337
|
+
land: (endpoint, ticket) => {
|
|
2338
|
+
const entry = entryOf(endpoint);
|
|
2339
|
+
if (ticket < entry.landed) return false;
|
|
2340
|
+
entry.landed = ticket;
|
|
2341
|
+
entry.stop?.();
|
|
2342
|
+
delete entry.stop;
|
|
2343
|
+
return true;
|
|
2344
|
+
},
|
|
2345
|
+
follow: (endpoint, ticket, stop) => {
|
|
2346
|
+
const entry = entryOf(endpoint);
|
|
2347
|
+
if (ticket !== entry.landed || abortController.signal.aborted) {
|
|
2348
|
+
stop();
|
|
2349
|
+
return;
|
|
2350
|
+
}
|
|
2351
|
+
entry.stop?.();
|
|
2352
|
+
entry.stop = stop;
|
|
2353
|
+
}
|
|
2354
|
+
};
|
|
2355
|
+
const stopFollowing = () => {
|
|
2356
|
+
for (const entry of ledger.values()) {
|
|
2357
|
+
entry.stop?.();
|
|
2358
|
+
delete entry.stop;
|
|
2359
|
+
}
|
|
2360
|
+
};
|
|
2361
|
+
const stamp = (effect) => {
|
|
2362
|
+
if ("removeSelf" in effect) return { removeInstance: { instance: instance.id } };
|
|
2363
|
+
if ("reconcile" in effect) return { reconcile: { origin: instance.definitionId, ...effect.reconcile } };
|
|
2364
|
+
return effect;
|
|
2365
|
+
};
|
|
2366
|
+
const onNavigate = config.onNavigate === void 0 ? void 0 : (effect) => config.onNavigate(stamp(effect));
|
|
2367
|
+
let reloading = false;
|
|
2368
|
+
let reloadAgain;
|
|
2369
|
+
const reload = async (cause) => {
|
|
2370
|
+
if (reloading) {
|
|
2371
|
+
reloadAgain = { cause };
|
|
2372
|
+
return;
|
|
2373
|
+
}
|
|
2374
|
+
reloading = true;
|
|
2375
|
+
try {
|
|
2376
|
+
let next = { cause };
|
|
2377
|
+
while (next !== void 0) {
|
|
2378
|
+
reloadAgain = void 0;
|
|
2379
|
+
const hop = nextCause(next.cause);
|
|
2380
|
+
if (isRunaway(hop)) {
|
|
2381
|
+
onError(new NovaError(ErrorCodes.runaway, runawayMessage(hop, `Reloading "${definition.id}"`), { depth: hop.depth, hops: hop.root.hops }));
|
|
2382
|
+
return;
|
|
2383
|
+
}
|
|
2384
|
+
await runLifecycleHook("mount", definition, () => buildContext(abortController.signal, hop));
|
|
2385
|
+
next = reloadAgain;
|
|
2386
|
+
}
|
|
2387
|
+
} finally {
|
|
2388
|
+
reloading = false;
|
|
2389
|
+
reloadAgain = void 0;
|
|
2390
|
+
}
|
|
2391
|
+
};
|
|
2392
|
+
const buildContext = (signal = abortController.signal, cause) => ({
|
|
2393
|
+
dataStore,
|
|
2394
|
+
endpoints: definition.endpoints ?? {},
|
|
2395
|
+
functions: config.functions ?? {},
|
|
2396
|
+
...config.endpointTimeoutMs === void 0 ? {} : { endpointTimeoutMs: config.endpointTimeoutMs },
|
|
2397
|
+
eventBus: config.eventBus,
|
|
2398
|
+
messageBus: config.messageBus,
|
|
2399
|
+
...config.fetch === void 0 ? {} : { fetch: config.fetch },
|
|
2400
|
+
...config.transform === void 0 ? {} : { transform: config.transform },
|
|
2401
|
+
...onNavigate === void 0 ? {} : { onNavigate },
|
|
2402
|
+
// Stamp the call event with this instance's identity before it flows up to
|
|
2403
|
+
// the shell's telemetry — `runCall` only knows the endpoint, the runtime
|
|
2404
|
+
// knows who made it.
|
|
2405
|
+
...config.onEndpoint === void 0 ? {} : { onEndpoint: (event) => config.onEndpoint({ ...event, instanceId: instance.id, canvasId: instance.canvasId }) },
|
|
2406
|
+
calls,
|
|
2407
|
+
extras: {},
|
|
2408
|
+
strict,
|
|
2409
|
+
onError,
|
|
2410
|
+
signal,
|
|
2411
|
+
suspended: instance.status === "suspended",
|
|
2412
|
+
// `reload` — re-run this instance's own mount hook. The same refresh
|
|
2413
|
+
// `resume` performs, made available as a step for canvases that never
|
|
2414
|
+
// suspend (a list keeps every card active, so nothing else would ever
|
|
2415
|
+
// re-read one).
|
|
2416
|
+
onReload: reload,
|
|
2417
|
+
...cause === void 0 ? {} : { cause }
|
|
2418
|
+
});
|
|
2419
|
+
const setStatus = (next) => {
|
|
2420
|
+
if (instance.status === next) return;
|
|
2421
|
+
instance.status = next;
|
|
2422
|
+
for (const handler of statusSubscribers.slice()) {
|
|
2423
|
+
try {
|
|
2424
|
+
handler(next);
|
|
2425
|
+
} catch {
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
};
|
|
2429
|
+
const attach = () => {
|
|
2430
|
+
if (modelWriteOff === void 0) {
|
|
2431
|
+
modelWriteOff = config.eventBus.on("ui:model", (event) => {
|
|
2432
|
+
if (event.type !== "ui:model" || instance.status === "suspended") return;
|
|
2433
|
+
if (event.origin !== void 0 && event.origin !== instance.id) return;
|
|
2434
|
+
if (event.ref === void 0) return;
|
|
2435
|
+
const path = modelListeners.get(event.ref);
|
|
2436
|
+
if (path === void 0) return;
|
|
2437
|
+
dataStore.update(
|
|
2438
|
+
(curr) => applyMutations(curr, [{ set: path, value: event.payload }], { initial: initialSnapshot, strict })
|
|
2439
|
+
);
|
|
2440
|
+
});
|
|
2441
|
+
}
|
|
2442
|
+
if (triggerHandle !== void 0) return;
|
|
2443
|
+
const triggers = definition.triggers;
|
|
2444
|
+
if (triggers === void 0 || triggers.length === 0) return;
|
|
2445
|
+
triggerHandle = attachTriggers(triggers, config.eventBus, config.messageBus, buildContext, instance.id);
|
|
2446
|
+
};
|
|
2447
|
+
const detach = () => {
|
|
2448
|
+
if (modelWriteOff !== void 0) {
|
|
2449
|
+
modelWriteOff();
|
|
2450
|
+
modelWriteOff = void 0;
|
|
2451
|
+
}
|
|
2452
|
+
if (triggerHandle === void 0) return;
|
|
2453
|
+
triggerHandle.detach();
|
|
2454
|
+
triggerHandle = void 0;
|
|
2455
|
+
};
|
|
2456
|
+
const getData = () => dataStore.get();
|
|
2457
|
+
const updateData = (updates) => {
|
|
2458
|
+
dataStore.update((curr) => ({ ...curr, ...updates }));
|
|
2459
|
+
};
|
|
2460
|
+
const setData = (next) => {
|
|
2461
|
+
dataStore.update(() => next);
|
|
2462
|
+
};
|
|
2463
|
+
const applyMutationList = (mutations) => {
|
|
2464
|
+
if (mutations.length === 0) return;
|
|
2465
|
+
dataStore.update(
|
|
2466
|
+
(curr) => applyMutations(curr, mutations, { initial: initialSnapshot, strict })
|
|
2467
|
+
);
|
|
2468
|
+
};
|
|
2469
|
+
const StepArraySchema = zod.z.array(StepSchema);
|
|
2470
|
+
const runSteps = async (steps) => {
|
|
2471
|
+
const parsed = StepArraySchema.safeParse(steps);
|
|
2472
|
+
if (!parsed.success) {
|
|
2473
|
+
const error = new DefinitionValidationError(
|
|
2474
|
+
"Invalid steps passed to runtime.executeSteps",
|
|
2475
|
+
{ failures: [{ id: definition.id, issues: parsed.error.issues }] }
|
|
2476
|
+
);
|
|
2477
|
+
if (strict) throw error;
|
|
2478
|
+
onError(error);
|
|
2479
|
+
return;
|
|
2480
|
+
}
|
|
2481
|
+
await executeSteps(parsed.data, buildContext());
|
|
2482
|
+
};
|
|
2483
|
+
const mount = async (input) => {
|
|
2484
|
+
if (input !== void 0) {
|
|
2485
|
+
const next = buildInitialData(definition, input);
|
|
2486
|
+
dataStore.update(() => next);
|
|
2487
|
+
}
|
|
2488
|
+
attach();
|
|
2489
|
+
const parent = ambientCause();
|
|
2490
|
+
const cause = nextCause(parent);
|
|
2491
|
+
if (isRunaway(cause)) {
|
|
2492
|
+
onError(new NovaError(ErrorCodes.runaway, runawayMessage(cause, `Mounting "${definition.id}"`), { depth: cause.depth, hops: cause.root.hops }));
|
|
2493
|
+
} else {
|
|
2494
|
+
await runLifecycleHook("mount", definition, () => buildContext(abortController.signal, cause));
|
|
2495
|
+
}
|
|
2496
|
+
setStatus("active");
|
|
2497
|
+
};
|
|
2498
|
+
const unmount = async () => {
|
|
2499
|
+
abortController.abort();
|
|
2500
|
+
stopFollowing();
|
|
2501
|
+
detach();
|
|
2502
|
+
teardownModelListeners();
|
|
2503
|
+
const unmountController = new AbortController();
|
|
2504
|
+
await runLifecycleHook(
|
|
2505
|
+
"unmount",
|
|
2506
|
+
definition,
|
|
2507
|
+
() => buildContext(unmountController.signal)
|
|
2508
|
+
);
|
|
2509
|
+
setStatus("unmounted");
|
|
2510
|
+
};
|
|
2511
|
+
const suspend = async () => {
|
|
2512
|
+
await runLifecycleHook("suspend", definition, buildContext);
|
|
2513
|
+
setStatus("suspended");
|
|
2514
|
+
};
|
|
2515
|
+
const resume = async () => {
|
|
2516
|
+
setStatus("active");
|
|
2517
|
+
await runLifecycleHook("mount", definition, buildContext);
|
|
2518
|
+
await runLifecycleHook("resume", definition, buildContext);
|
|
2519
|
+
};
|
|
2520
|
+
const reconcileModelBindings = (nodes) => {
|
|
2521
|
+
modelListeners.clear();
|
|
2522
|
+
for (const b of collectModelBindings(nodes)) modelListeners.set(b.ref, b.path);
|
|
2523
|
+
};
|
|
2524
|
+
const teardownModelListeners = () => {
|
|
2525
|
+
modelListeners.clear();
|
|
2526
|
+
};
|
|
2527
|
+
const render2 = () => {
|
|
2528
|
+
const language = config.i18n?.();
|
|
2529
|
+
const out = renderRuntime(definition, dataStore, {
|
|
2530
|
+
store: config.layoutStore,
|
|
2531
|
+
registry: config.registry,
|
|
2532
|
+
strict,
|
|
2533
|
+
onError,
|
|
2534
|
+
...language?.phrases === void 0 ? {} : { phrases: language.phrases },
|
|
2535
|
+
...language?.phraseKeys === void 0 ? {} : { phraseKeys: language.phraseKeys },
|
|
2536
|
+
...language?.onPhraseMiss === void 0 ? {} : { onPhraseMiss: language.onPhraseMiss }
|
|
2537
|
+
});
|
|
2538
|
+
reconcileModelBindings(out);
|
|
2539
|
+
return out;
|
|
2540
|
+
};
|
|
2541
|
+
const onDataChange = (handler) => dataStore.subscribe(handler);
|
|
2542
|
+
const onStatusChange = (handler) => {
|
|
2543
|
+
statusSubscribers.push(handler);
|
|
2544
|
+
return () => {
|
|
2545
|
+
const idx = statusSubscribers.indexOf(handler);
|
|
2546
|
+
if (idx >= 0) statusSubscribers.splice(idx, 1);
|
|
2547
|
+
};
|
|
2548
|
+
};
|
|
2549
|
+
const dispose = () => {
|
|
2550
|
+
stopFollowing();
|
|
2551
|
+
detach();
|
|
2552
|
+
teardownModelListeners();
|
|
2553
|
+
statusSubscribers.length = 0;
|
|
2554
|
+
};
|
|
2555
|
+
return {
|
|
2556
|
+
get instance() {
|
|
2557
|
+
return instance;
|
|
2558
|
+
},
|
|
2559
|
+
get definition() {
|
|
2560
|
+
return definition;
|
|
2561
|
+
},
|
|
2562
|
+
get dataStore() {
|
|
2563
|
+
return dataStore;
|
|
2564
|
+
},
|
|
2565
|
+
getData,
|
|
2566
|
+
setData,
|
|
2567
|
+
updateData,
|
|
2568
|
+
applyMutations: applyMutationList,
|
|
2569
|
+
executeSteps: runSteps,
|
|
2570
|
+
mount,
|
|
2571
|
+
unmount,
|
|
2572
|
+
suspend,
|
|
2573
|
+
resume,
|
|
2574
|
+
render: render2,
|
|
2575
|
+
onDataChange,
|
|
2576
|
+
onStatusChange,
|
|
2577
|
+
dispose
|
|
2578
|
+
};
|
|
2579
|
+
};
|
|
2580
|
+
var validateActions = (actions) => {
|
|
2581
|
+
const failures = [];
|
|
2582
|
+
for (const [actionId, def] of Object.entries(actions)) {
|
|
2583
|
+
if (strata.exceedsDepth(def)) {
|
|
2584
|
+
failures.push({ id: actionId, issues: [{ code: "custom", path: [], message: strata.depthRefusal(), input: void 0 }] });
|
|
2585
|
+
continue;
|
|
2586
|
+
}
|
|
2587
|
+
const result = ActionDefinitionSchema.safeParse(def);
|
|
2588
|
+
if (!result.success) failures.push({ id: actionId, issues: result.error.issues });
|
|
2589
|
+
}
|
|
2590
|
+
if (failures.length > 0) {
|
|
2591
|
+
throw new DefinitionValidationError(
|
|
2592
|
+
`${failures.length} action definition(s) failed validation`,
|
|
2593
|
+
{ failures }
|
|
2594
|
+
);
|
|
2595
|
+
}
|
|
2596
|
+
};
|
|
2597
|
+
var validateFragments = (fragments) => {
|
|
2598
|
+
const failures = [];
|
|
2599
|
+
for (const [fragmentId, frag] of Object.entries(fragments)) {
|
|
2600
|
+
if (strata.exceedsDepth(frag)) {
|
|
2601
|
+
failures.push({ id: fragmentId, issues: [{ code: "custom", path: [], message: strata.depthRefusal(), input: void 0 }] });
|
|
2602
|
+
continue;
|
|
2603
|
+
}
|
|
2604
|
+
const result = ActionFragmentSchema.safeParse(frag);
|
|
2605
|
+
if (!result.success) failures.push({ id: fragmentId, issues: result.error.issues });
|
|
2606
|
+
}
|
|
2607
|
+
if (failures.length > 0) {
|
|
2608
|
+
throw new DefinitionValidationError(
|
|
2609
|
+
`${failures.length} action fragment(s) failed validation`,
|
|
2610
|
+
{ failures }
|
|
2611
|
+
);
|
|
2612
|
+
}
|
|
2613
|
+
};
|
|
2614
|
+
var snapshotCanvas = (canvas) => {
|
|
2615
|
+
const stack = canvas.stack.slice();
|
|
2616
|
+
return {
|
|
2617
|
+
id: canvas.id,
|
|
2618
|
+
stack,
|
|
2619
|
+
active: stack.length === 0 ? void 0 : stack[stack.length - 1]
|
|
2620
|
+
};
|
|
2621
|
+
};
|
|
2622
|
+
var createRuntimeFactory = (deps) => (canvasId, definition, input) => createActionRuntime({
|
|
2623
|
+
definition,
|
|
2624
|
+
canvasId,
|
|
2625
|
+
...input === void 0 ? {} : { input },
|
|
2626
|
+
eventBus: deps.eventBus,
|
|
2627
|
+
messageBus: deps.messageBus,
|
|
2628
|
+
layoutStore: deps.layoutStore,
|
|
2629
|
+
registry: deps.registry,
|
|
2630
|
+
...deps.transform === void 0 ? {} : { transform: deps.transform },
|
|
2631
|
+
...deps.fetch === void 0 ? {} : { fetch: deps.fetch },
|
|
2632
|
+
...deps.functions === void 0 ? {} : { functions: deps.functions },
|
|
2633
|
+
...deps.endpointTimeoutMs === void 0 ? {} : { endpointTimeoutMs: deps.endpointTimeoutMs },
|
|
2634
|
+
onNavigate: (effect) => deps.onNavigate(canvasId, effect),
|
|
2635
|
+
...deps.onEndpoint === void 0 ? {} : { onEndpoint: deps.onEndpoint },
|
|
2636
|
+
strict: deps.strict,
|
|
2637
|
+
...deps.onError === void 0 ? {} : { onError: deps.onError },
|
|
2638
|
+
...deps.i18n === void 0 ? {} : { i18n: deps.i18n },
|
|
2639
|
+
instanceIdFn: deps.instanceIdFn
|
|
2640
|
+
});
|
|
2641
|
+
var shellRegistries = /* @__PURE__ */ new WeakMap();
|
|
2642
|
+
var rememberShellRegistry = (shell, registry) => {
|
|
2643
|
+
shellRegistries.set(shell, registry);
|
|
2644
|
+
};
|
|
2645
|
+
|
|
2646
|
+
// src/shell/canvas.ts
|
|
2647
|
+
var createCanvas = (id) => {
|
|
2648
|
+
const stack = [];
|
|
2649
|
+
const peek = () => {
|
|
2650
|
+
if (stack.length === 0) return void 0;
|
|
2651
|
+
return stack[stack.length - 1];
|
|
2652
|
+
};
|
|
2653
|
+
const pushInstance = (inst) => {
|
|
2654
|
+
stack.push(inst);
|
|
2655
|
+
};
|
|
2656
|
+
const popInstance = () => {
|
|
2657
|
+
return stack.pop();
|
|
2658
|
+
};
|
|
2659
|
+
const replaceTop = (inst) => {
|
|
2660
|
+
const prev = stack.pop();
|
|
2661
|
+
stack.push(inst);
|
|
2662
|
+
return prev;
|
|
2663
|
+
};
|
|
2664
|
+
const clearStack = () => {
|
|
2665
|
+
const removed = stack.slice();
|
|
2666
|
+
stack.length = 0;
|
|
2667
|
+
return removed;
|
|
2668
|
+
};
|
|
2669
|
+
return { id, stack, peek, pushInstance, popInstance, replaceTop, clearStack };
|
|
2670
|
+
};
|
|
2671
|
+
|
|
2672
|
+
// src/shell/slot-names.ts
|
|
2673
|
+
var CANVAS_SLOT_NAME = "CanvasSlot";
|
|
2674
|
+
var ACTION_SLOT_NAME = "ActionSlot";
|
|
2675
|
+
|
|
2676
|
+
// src/shell/default-layouts.ts
|
|
2677
|
+
var DEFAULT_SHELL_LAYOUT = {
|
|
2678
|
+
component: "Stack",
|
|
2679
|
+
props: { direction: "row" },
|
|
2680
|
+
children: [
|
|
2681
|
+
{
|
|
2682
|
+
for: "$.canvases",
|
|
2683
|
+
as: "c",
|
|
2684
|
+
key: "id",
|
|
2685
|
+
do: {
|
|
2686
|
+
component: CANVAS_SLOT_NAME,
|
|
2687
|
+
props: { canvasId: "$.c.id" }
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
]
|
|
2691
|
+
};
|
|
2692
|
+
var DEFAULT_ACTION_LAYOUT = {
|
|
2693
|
+
component: ACTION_SLOT_NAME,
|
|
2694
|
+
props: { instanceId: "$.active.id" }
|
|
2695
|
+
};
|
|
2696
|
+
|
|
2697
|
+
// src/shell/flatten-render-tree.ts
|
|
2698
|
+
var asString = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
|
|
2699
|
+
var emptyFragment = () => ({ type: "fragment", children: [] });
|
|
2700
|
+
var flattenRenderTree = (tree, shell) => tree.map((node) => flattenNode(node, shell));
|
|
2701
|
+
var flattenNode = (node, shell) => {
|
|
2702
|
+
if (node.type !== "component") {
|
|
2703
|
+
if (node.type === "fragment") {
|
|
2704
|
+
return { type: "fragment", children: flattenRenderTree(node.children, shell) };
|
|
2705
|
+
}
|
|
2706
|
+
return node;
|
|
2707
|
+
}
|
|
2708
|
+
if (node.name === CANVAS_SLOT_NAME) {
|
|
2709
|
+
const canvasId = asString(node.props["canvasId"]);
|
|
2710
|
+
if (canvasId === void 0) return emptyFragment();
|
|
2711
|
+
return { type: "fragment", children: flattenRenderTree(shell.getCanvasRenderTree(canvasId), shell) };
|
|
2712
|
+
}
|
|
2713
|
+
if (node.name === ACTION_SLOT_NAME) {
|
|
2714
|
+
const instanceId = asString(node.props["instanceId"]);
|
|
2715
|
+
if (instanceId === void 0) return emptyFragment();
|
|
2716
|
+
const runtime = shell.getRuntime(instanceId);
|
|
2717
|
+
if (runtime === void 0) return emptyFragment();
|
|
2718
|
+
return {
|
|
2719
|
+
type: "component",
|
|
2720
|
+
name: ACTION_SLOT_NAME,
|
|
2721
|
+
// identity only — never the definition itself (wire weight)
|
|
2722
|
+
props: { instanceId, canvasId: runtime.instance.canvasId, definitionId: runtime.instance.definitionId },
|
|
2723
|
+
children: runtime.render(),
|
|
2724
|
+
// keyed by instance so a renderer remounts when the instance changes
|
|
2725
|
+
// (no stale DOM state across instance swaps, enter animations fire)
|
|
2726
|
+
key: instanceId
|
|
2727
|
+
};
|
|
2728
|
+
}
|
|
2729
|
+
return { ...node, children: flattenRenderTree(node.children, shell) };
|
|
2730
|
+
};
|
|
2731
|
+
|
|
2732
|
+
// src/reflect/grammar.ts
|
|
2733
|
+
var declaredKeys = (definition) => Object.keys(definition.input?.properties ?? {});
|
|
2734
|
+
var mountCalls = (definition) => {
|
|
2735
|
+
const names = /* @__PURE__ */ new Set();
|
|
2736
|
+
const walk2 = (node) => {
|
|
2737
|
+
if (Array.isArray(node)) {
|
|
2738
|
+
for (const item of node) walk2(item);
|
|
2739
|
+
return;
|
|
2740
|
+
}
|
|
2741
|
+
if (node === null || typeof node !== "object") return;
|
|
2742
|
+
const step = node;
|
|
2743
|
+
if (typeof step["call"] === "string") names.add(step["call"]);
|
|
2744
|
+
walk2(step["onSuccess"]);
|
|
2745
|
+
walk2(step["onError"]);
|
|
2746
|
+
};
|
|
2747
|
+
walk2(definition.lifecycle?.mount);
|
|
2748
|
+
return names;
|
|
2749
|
+
};
|
|
2750
|
+
var requestKeys = (request) => {
|
|
2751
|
+
const found = [];
|
|
2752
|
+
const walk2 = (node) => {
|
|
2753
|
+
if (typeof node === "string") {
|
|
2754
|
+
if (node.startsWith("$.")) found.push(rootOf(node.slice(2)));
|
|
2755
|
+
return;
|
|
2756
|
+
}
|
|
2757
|
+
if (Array.isArray(node)) {
|
|
2758
|
+
for (const item of node) walk2(item);
|
|
2759
|
+
return;
|
|
2760
|
+
}
|
|
2761
|
+
if (node === null || typeof node !== "object") return;
|
|
2762
|
+
for (const value of Object.values(node)) walk2(value);
|
|
2763
|
+
};
|
|
2764
|
+
walk2(request);
|
|
2765
|
+
return found.filter((key) => key !== "");
|
|
2766
|
+
};
|
|
2767
|
+
var mountInputCache = /* @__PURE__ */ new WeakMap();
|
|
2768
|
+
var mountInputKeys = (definition) => {
|
|
2769
|
+
const cached = mountInputCache.get(definition);
|
|
2770
|
+
if (cached !== void 0) return cached;
|
|
2771
|
+
const called = mountCalls(definition);
|
|
2772
|
+
const declared = new Set(declaredKeys(definition));
|
|
2773
|
+
const keys = /* @__PURE__ */ new Set();
|
|
2774
|
+
for (const [name, endpoint] of Object.entries(definition.endpoints ?? {})) {
|
|
2775
|
+
if (!called.has(name)) continue;
|
|
2776
|
+
for (const key of requestKeys(endpoint.request)) if (declared.has(key)) keys.add(key);
|
|
2777
|
+
}
|
|
2778
|
+
mountInputCache.set(definition, keys);
|
|
2779
|
+
return keys;
|
|
2780
|
+
};
|
|
2781
|
+
|
|
2782
|
+
// src/shell/reconcile.ts
|
|
2783
|
+
var differs = (before, input) => Object.entries(input).some(([key, value]) => JSON.stringify(before[key]) !== JSON.stringify(value));
|
|
2784
|
+
var reconcileCanvas = (shell, canvasId, desired, options) => {
|
|
2785
|
+
const { origin, definitionOf } = options;
|
|
2786
|
+
const ownsCanvas = options.own === "canvas";
|
|
2787
|
+
const notes = [];
|
|
2788
|
+
let changed = false;
|
|
2789
|
+
if (shell.getState().canvases[canvasId] === void 0) return { changed: false, notes: [`no canvas "${canvasId}"`] };
|
|
2790
|
+
const wanted = [];
|
|
2791
|
+
for (const entry of desired) if (!wanted.some((other) => other.actionId === entry.actionId)) wanted.push(entry);
|
|
2792
|
+
const mine = (shell.getState().canvases[canvasId]?.stack ?? []).filter((item) => ownsCanvas || shell.originOf(item.id) === origin);
|
|
2793
|
+
for (const item of mine) {
|
|
2794
|
+
if (wanted.some((entry) => entry.actionId === item.definitionId)) continue;
|
|
2795
|
+
shell.removeInstance(canvasId, item.id);
|
|
2796
|
+
changed = true;
|
|
2797
|
+
notes.push(`closed ${item.definitionId}`);
|
|
2798
|
+
}
|
|
2799
|
+
for (const entry of wanted) {
|
|
2800
|
+
const input = entry.input ?? {};
|
|
2801
|
+
const existing = (shell.getState().canvases[canvasId]?.stack ?? []).find((item) => item.definitionId === entry.actionId);
|
|
2802
|
+
if (existing !== void 0 && !ownsCanvas && shell.originOf(existing.id) !== origin) {
|
|
2803
|
+
notes.push(`left ${entry.actionId}: not mine`);
|
|
2804
|
+
continue;
|
|
2805
|
+
}
|
|
2806
|
+
if (existing !== void 0) {
|
|
2807
|
+
const runtime = shell.getRuntime(existing.id);
|
|
2808
|
+
const before = runtime?.getData() ?? {};
|
|
2809
|
+
if (runtime === void 0 || Object.keys(input).length === 0 || !differs(before, input)) continue;
|
|
2810
|
+
const definition = definitionOf?.(entry.actionId);
|
|
2811
|
+
const reAims = definition !== void 0 && Object.keys(input).some((key) => mountInputKeys(definition).has(key));
|
|
2812
|
+
if (!reAims) {
|
|
2813
|
+
runtime.setData({ ...before, ...input });
|
|
2814
|
+
changed = true;
|
|
2815
|
+
notes.push(`set ${Object.keys(input).join(", ")} on ${entry.actionId}`);
|
|
2816
|
+
continue;
|
|
2817
|
+
}
|
|
2818
|
+
shell.removeInstance(canvasId, existing.id);
|
|
2819
|
+
notes.push(`re-opened ${entry.actionId}`);
|
|
2820
|
+
}
|
|
2821
|
+
shell.push(canvasId, entry.actionId, input, entry.with, { origin });
|
|
2822
|
+
changed = true;
|
|
2823
|
+
notes.push(`placed ${entry.actionId}`);
|
|
2824
|
+
}
|
|
2825
|
+
return { changed, notes };
|
|
2826
|
+
};
|
|
2827
|
+
|
|
2828
|
+
// src/shell/journal.ts
|
|
2829
|
+
var DEFAULT_HISTORY_DEPTH = 50;
|
|
2830
|
+
var createJournal = (limit) => {
|
|
2831
|
+
const entries = [];
|
|
2832
|
+
let mutes = 0;
|
|
2833
|
+
const off = () => limit <= 0 || mutes > 0;
|
|
2834
|
+
return {
|
|
2835
|
+
record: (canvas, stack) => {
|
|
2836
|
+
if (off()) return;
|
|
2837
|
+
entries.push({ canvas, stack });
|
|
2838
|
+
if (entries.length > limit) entries.shift();
|
|
2839
|
+
},
|
|
2840
|
+
// A pop somebody performed themselves IS a back. Without this the journal
|
|
2841
|
+
// would still hold the entry that pop just satisfied, and the next press of
|
|
2842
|
+
// the back button would spend itself restoring a position already on screen
|
|
2843
|
+
// — the double-tap that makes a back button feel broken.
|
|
2844
|
+
consume: (canvas) => {
|
|
2845
|
+
if (off()) return;
|
|
2846
|
+
for (let i = entries.length - 1; i >= 0; i -= 1) {
|
|
2847
|
+
if (entries[i]?.canvas !== canvas) continue;
|
|
2848
|
+
entries.splice(i, 1);
|
|
2849
|
+
return;
|
|
2850
|
+
}
|
|
2851
|
+
},
|
|
2852
|
+
take: () => entries.pop(),
|
|
2853
|
+
// REVOCATION REACHES THE JOURNAL OR IT IS NOT REVOCATION. An entry naming
|
|
2854
|
+
// an action this shell no longer serves would hand it back on the way out —
|
|
2855
|
+
// a grant dropped at the front door and returned through the back one.
|
|
2856
|
+
forgetAction: (actionId) => {
|
|
2857
|
+
for (let i = entries.length - 1; i >= 0; i -= 1) {
|
|
2858
|
+
if (entries[i]?.stack.some((frame) => frame.action === actionId) === true) entries.splice(i, 1);
|
|
2859
|
+
}
|
|
2860
|
+
},
|
|
2861
|
+
forgetCanvas: (canvas) => {
|
|
2862
|
+
for (let i = entries.length - 1; i >= 0; i -= 1) {
|
|
2863
|
+
if (entries[i]?.canvas === canvas) entries.splice(i, 1);
|
|
2864
|
+
}
|
|
2865
|
+
},
|
|
2866
|
+
mute: (fn) => {
|
|
2867
|
+
mutes += 1;
|
|
2868
|
+
try {
|
|
2869
|
+
return fn();
|
|
2870
|
+
} finally {
|
|
2871
|
+
mutes -= 1;
|
|
2872
|
+
}
|
|
2873
|
+
},
|
|
2874
|
+
depth: () => entries.length
|
|
2875
|
+
};
|
|
2876
|
+
};
|
|
2877
|
+
|
|
2878
|
+
// src/shell/lifecycle-ops.ts
|
|
2879
|
+
var createLifecycleOps = (deps) => {
|
|
2880
|
+
const { registry, onLifecycleError, onUnmount } = deps;
|
|
2881
|
+
const unmounted = /* @__PURE__ */ new Set();
|
|
2882
|
+
const unmountInstance = (instanceId) => {
|
|
2883
|
+
if (unmounted.has(instanceId)) return;
|
|
2884
|
+
const runtime = registry.get(instanceId);
|
|
2885
|
+
if (runtime === void 0) return;
|
|
2886
|
+
unmounted.add(instanceId);
|
|
2887
|
+
runtime.unmount().catch(onLifecycleError);
|
|
2888
|
+
runtime.dispose();
|
|
2889
|
+
registry.unregister(instanceId);
|
|
2890
|
+
onUnmount?.(instanceId);
|
|
2891
|
+
unmounted.delete(instanceId);
|
|
2892
|
+
};
|
|
2893
|
+
const suspendTop = (canvas) => {
|
|
2894
|
+
const top = canvas.peek();
|
|
2895
|
+
if (top === void 0) return;
|
|
2896
|
+
if (top.status === "suspended") return;
|
|
2897
|
+
const runtime = registry.get(top.id);
|
|
2898
|
+
if (runtime !== void 0) runtime.suspend().catch(onLifecycleError);
|
|
2899
|
+
};
|
|
2900
|
+
const resumeTop = (canvas) => {
|
|
2901
|
+
const top = canvas.peek();
|
|
2902
|
+
if (top === void 0) return;
|
|
2903
|
+
const runtime = registry.get(top.id);
|
|
2904
|
+
if (runtime !== void 0) runtime.resume().catch(onLifecycleError);
|
|
2905
|
+
};
|
|
2906
|
+
return { unmountInstance, suspendTop, resumeTop };
|
|
2907
|
+
};
|
|
2908
|
+
|
|
2909
|
+
// src/shell/navigation.ts
|
|
2910
|
+
var navigatedChannel = (canvasId) => `nova:navigated:${canvasId}`;
|
|
2911
|
+
var createNavigationHandler = (ops) => {
|
|
2912
|
+
return (currentCanvasId, effect) => {
|
|
2913
|
+
if ("push" in effect) {
|
|
2914
|
+
const target = effect.push.canvas ?? currentCanvasId;
|
|
2915
|
+
ops.push(target, effect.push.action, effect.push.input, effect.push.with);
|
|
2916
|
+
return;
|
|
2917
|
+
}
|
|
2918
|
+
if ("pop" in effect) {
|
|
2919
|
+
ops.pop(currentCanvasId);
|
|
2920
|
+
return;
|
|
2921
|
+
}
|
|
2922
|
+
if ("replace" in effect) {
|
|
2923
|
+
const target = effect.replace.canvas ?? currentCanvasId;
|
|
2924
|
+
ops.replace(target, effect.replace.action, effect.replace.input, effect.replace.with);
|
|
2925
|
+
return;
|
|
2926
|
+
}
|
|
2927
|
+
if ("popTo" in effect) {
|
|
2928
|
+
ops.popTo(effect.popTo.canvas ?? currentCanvasId, effect.popTo.instance);
|
|
2929
|
+
return;
|
|
2930
|
+
}
|
|
2931
|
+
if ("resetTo" in effect) {
|
|
2932
|
+
const target = effect.resetTo.canvas ?? currentCanvasId;
|
|
2933
|
+
ops.resetTo(target, effect.resetTo.action, effect.resetTo.input, effect.resetTo.with);
|
|
2934
|
+
return;
|
|
2935
|
+
}
|
|
2936
|
+
if ("removeInstance" in effect) {
|
|
2937
|
+
ops.removeInstance(effect.removeInstance.canvas ?? currentCanvasId, effect.removeInstance.instance);
|
|
2938
|
+
return;
|
|
2939
|
+
}
|
|
2940
|
+
if ("reconcile" in effect) {
|
|
2941
|
+
const { canvas, desired, origin, own, with: fragments } = effect.reconcile;
|
|
2942
|
+
ops.reconcile(canvas ?? currentCanvasId, desired, {
|
|
2943
|
+
origin: origin ?? "reconcile",
|
|
2944
|
+
...own === void 0 ? {} : { own },
|
|
2945
|
+
...fragments === void 0 ? {} : { with: fragments }
|
|
2946
|
+
});
|
|
2947
|
+
}
|
|
2948
|
+
};
|
|
2949
|
+
};
|
|
2950
|
+
|
|
2951
|
+
// src/shell/runtime-registry.ts
|
|
2952
|
+
var createRuntimeRegistry = () => {
|
|
2953
|
+
const runtimes = /* @__PURE__ */ new Map();
|
|
2954
|
+
const unsubs = /* @__PURE__ */ new Map();
|
|
2955
|
+
const register = (runtime, onData) => {
|
|
2956
|
+
const id = runtime.instance.id;
|
|
2957
|
+
runtimes.set(id, runtime);
|
|
2958
|
+
unsubs.set(id, runtime.onDataChange(onData));
|
|
2959
|
+
};
|
|
2960
|
+
const unregister = (instanceId) => {
|
|
2961
|
+
const off = unsubs.get(instanceId);
|
|
2962
|
+
if (off !== void 0) off();
|
|
2963
|
+
unsubs.delete(instanceId);
|
|
2964
|
+
runtimes.delete(instanceId);
|
|
2965
|
+
};
|
|
2966
|
+
const get = (instanceId) => runtimes.get(instanceId);
|
|
2967
|
+
const disposeAll = () => {
|
|
2968
|
+
for (const off of unsubs.values()) off();
|
|
2969
|
+
unsubs.clear();
|
|
2970
|
+
runtimes.clear();
|
|
2971
|
+
};
|
|
2972
|
+
return { register, unregister, get, disposeAll };
|
|
2973
|
+
};
|
|
2974
|
+
|
|
2975
|
+
// src/shell/telemetry.ts
|
|
2976
|
+
var safeCall = (fn, arg) => {
|
|
2977
|
+
if (fn === void 0) return;
|
|
2978
|
+
try {
|
|
2979
|
+
fn(arg);
|
|
2980
|
+
} catch {
|
|
2981
|
+
}
|
|
2982
|
+
};
|
|
2983
|
+
var createTelemetry = (config) => {
|
|
2984
|
+
const stateSubscribers = [];
|
|
2985
|
+
const dataSubscribers = [];
|
|
2986
|
+
const endpointSubscribers = [];
|
|
2987
|
+
const fireStateChange = (snapshot) => {
|
|
2988
|
+
safeCall(config?.onStateChange, snapshot);
|
|
2989
|
+
for (const handler of stateSubscribers.slice()) safeCall(handler, snapshot);
|
|
2990
|
+
};
|
|
2991
|
+
const fireDataChange = (change) => {
|
|
2992
|
+
safeCall(config?.onDataChange, change);
|
|
2993
|
+
for (const handler of dataSubscribers.slice()) safeCall(handler, change);
|
|
2994
|
+
};
|
|
2995
|
+
const fireEndpoint = (event) => {
|
|
2996
|
+
safeCall(config?.onEndpoint, event);
|
|
2997
|
+
for (const handler of endpointSubscribers.slice()) safeCall(handler, event);
|
|
2998
|
+
};
|
|
2999
|
+
const onStateChange = (handler) => {
|
|
3000
|
+
stateSubscribers.push(handler);
|
|
3001
|
+
return () => {
|
|
3002
|
+
const idx = stateSubscribers.indexOf(handler);
|
|
3003
|
+
if (idx >= 0) stateSubscribers.splice(idx, 1);
|
|
3004
|
+
};
|
|
3005
|
+
};
|
|
3006
|
+
const onDataChange = (handler) => {
|
|
3007
|
+
dataSubscribers.push(handler);
|
|
3008
|
+
return () => {
|
|
3009
|
+
const idx = dataSubscribers.indexOf(handler);
|
|
3010
|
+
if (idx >= 0) dataSubscribers.splice(idx, 1);
|
|
3011
|
+
};
|
|
3012
|
+
};
|
|
3013
|
+
const onEndpoint = (handler) => {
|
|
3014
|
+
endpointSubscribers.push(handler);
|
|
3015
|
+
return () => {
|
|
3016
|
+
const idx = endpointSubscribers.indexOf(handler);
|
|
3017
|
+
if (idx >= 0) endpointSubscribers.splice(idx, 1);
|
|
3018
|
+
};
|
|
3019
|
+
};
|
|
3020
|
+
const clear = () => {
|
|
3021
|
+
stateSubscribers.length = 0;
|
|
3022
|
+
dataSubscribers.length = 0;
|
|
3023
|
+
endpointSubscribers.length = 0;
|
|
3024
|
+
};
|
|
3025
|
+
return { fireStateChange, fireDataChange, fireEndpoint, onStateChange, onDataChange, onEndpoint, clear };
|
|
3026
|
+
};
|
|
3027
|
+
|
|
3028
|
+
// src/shell/shell.ts
|
|
3029
|
+
var defaultShellIdFactory = createIdFactory("shell");
|
|
3030
|
+
var createShell = (config) => {
|
|
3031
|
+
validateActions(config.actions);
|
|
3032
|
+
const id = (config.shellIdFn ?? defaultShellIdFactory)();
|
|
3033
|
+
const instanceIdFn = config.instanceIdFn ?? createIdFactory("act");
|
|
3034
|
+
const strict = config.strict ?? false;
|
|
3035
|
+
const eventBus = config.eventBus ?? createEventBus();
|
|
3036
|
+
const messageBus = config.messageBus ?? createMessageBus();
|
|
3037
|
+
const registry = createRuntimeRegistry();
|
|
3038
|
+
const telemetry = createTelemetry(config.telemetry);
|
|
3039
|
+
const componentRegistry = config.registry ?? createComponentRegistry();
|
|
3040
|
+
if (config.components !== void 0) componentRegistry.registerAll(config.components);
|
|
3041
|
+
const layoutStore = config.layoutStore ?? createLayoutStore();
|
|
3042
|
+
let pendingStrictError;
|
|
3043
|
+
const toLifecycleError = (err) => {
|
|
3044
|
+
if (err instanceof LifecycleError) return err;
|
|
3045
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
3046
|
+
return new LifecycleError(message, {}, { cause: err });
|
|
3047
|
+
};
|
|
3048
|
+
const handleLifecycleRejection = (err) => {
|
|
3049
|
+
const lifecycleErr = toLifecycleError(err);
|
|
3050
|
+
if (strict && pendingStrictError === void 0) {
|
|
3051
|
+
pendingStrictError = lifecycleErr;
|
|
3052
|
+
}
|
|
3053
|
+
if (config.onError === void 0) return;
|
|
3054
|
+
if (err instanceof NovaError) {
|
|
3055
|
+
config.onError(err);
|
|
3056
|
+
return;
|
|
3057
|
+
}
|
|
3058
|
+
config.onError(lifecycleErr);
|
|
3059
|
+
};
|
|
3060
|
+
const origins = /* @__PURE__ */ new Map();
|
|
3061
|
+
const births = /* @__PURE__ */ new Map();
|
|
3062
|
+
const journal = createJournal(config.historyDepth ?? DEFAULT_HISTORY_DEPTH);
|
|
3063
|
+
const ops = createLifecycleOps({
|
|
3064
|
+
registry,
|
|
3065
|
+
onLifecycleError: handleLifecycleRejection,
|
|
3066
|
+
onUnmount: (instanceId) => {
|
|
3067
|
+
origins.delete(instanceId);
|
|
3068
|
+
births.delete(instanceId);
|
|
3069
|
+
}
|
|
3070
|
+
});
|
|
3071
|
+
const canvases = /* @__PURE__ */ new Map();
|
|
3072
|
+
const actionLayouts = /* @__PURE__ */ new Map();
|
|
3073
|
+
const listCanvases = /* @__PURE__ */ new Set();
|
|
3074
|
+
for (const cfg of config.canvases) {
|
|
3075
|
+
canvases.set(cfg.id, createCanvas(cfg.id));
|
|
3076
|
+
if (cfg.actionLayout !== void 0) actionLayouts.set(cfg.id, cfg.actionLayout);
|
|
3077
|
+
if (cfg.mode === "list") listCanvases.add(cfg.id);
|
|
3078
|
+
}
|
|
3079
|
+
const canvasOrder = config.canvases.map((cfg) => cfg.id);
|
|
3080
|
+
let canvasLayout = config.canvasLayout;
|
|
3081
|
+
const actions = { ...config.actions };
|
|
3082
|
+
let phrases = config.phrases;
|
|
3083
|
+
let bearing = config.phrases !== void 0 || config.phraseKeys !== void 0;
|
|
3084
|
+
const SOURCE = {};
|
|
3085
|
+
const language = () => {
|
|
3086
|
+
if (!bearing) return void 0;
|
|
3087
|
+
return {
|
|
3088
|
+
// An empty book translates nothing and still fills patterns, which is
|
|
3089
|
+
// exactly what the source language needs.
|
|
3090
|
+
phrases: phrases ?? SOURCE,
|
|
3091
|
+
...config.phraseKeys === void 0 ? {} : { phraseKeys: config.phraseKeys },
|
|
3092
|
+
...config.onPhraseMiss === void 0 ? {} : { onPhraseMiss: config.onPhraseMiss }
|
|
3093
|
+
};
|
|
3094
|
+
};
|
|
3095
|
+
const fragments = { ...config.fragments ?? {} };
|
|
3096
|
+
let disposed = false;
|
|
3097
|
+
const guardNotDisposed = () => {
|
|
3098
|
+
if (disposed) throw new ShellDisposedError("Shell disposed");
|
|
3099
|
+
};
|
|
3100
|
+
const guardNoPendingStrictError = () => {
|
|
3101
|
+
if (pendingStrictError === void 0) return;
|
|
3102
|
+
const err = pendingStrictError;
|
|
3103
|
+
pendingStrictError = void 0;
|
|
3104
|
+
throw err;
|
|
3105
|
+
};
|
|
3106
|
+
const guard = () => {
|
|
3107
|
+
guardNotDisposed();
|
|
3108
|
+
guardNoPendingStrictError();
|
|
3109
|
+
};
|
|
3110
|
+
const getCanvas = (canvasId) => {
|
|
3111
|
+
const existing = canvases.get(canvasId);
|
|
3112
|
+
if (existing !== void 0) return existing;
|
|
3113
|
+
const created = createCanvas(canvasId);
|
|
3114
|
+
canvases.set(canvasId, created);
|
|
3115
|
+
return created;
|
|
3116
|
+
};
|
|
3117
|
+
const getDefinition = (actionId) => {
|
|
3118
|
+
const def = actions[actionId];
|
|
3119
|
+
if (def === void 0) throw new UnknownActionError(`Unknown action: ${actionId}`, { actionId });
|
|
3120
|
+
return def;
|
|
3121
|
+
};
|
|
3122
|
+
const registerAction = (definition) => {
|
|
3123
|
+
guard();
|
|
3124
|
+
validateActions({ [definition.id]: definition });
|
|
3125
|
+
actions[definition.id] = definition;
|
|
3126
|
+
};
|
|
3127
|
+
const removeAction = (actionId) => {
|
|
3128
|
+
guard();
|
|
3129
|
+
if (actions[actionId] === void 0) return;
|
|
3130
|
+
delete actions[actionId];
|
|
3131
|
+
journal.forgetAction(actionId);
|
|
3132
|
+
let changed = false;
|
|
3133
|
+
for (const [, canvas] of canvases) {
|
|
3134
|
+
if (!canvas.stack.some((inst) => inst.definitionId === actionId)) continue;
|
|
3135
|
+
const previousTop = canvas.peek();
|
|
3136
|
+
for (const inst of canvas.clearStack()) {
|
|
3137
|
+
if (inst.definitionId === actionId) ops.unmountInstance(inst.id);
|
|
3138
|
+
else canvas.pushInstance(inst);
|
|
3139
|
+
}
|
|
3140
|
+
if (canvas.peek() !== previousTop) ops.resumeTop(canvas);
|
|
3141
|
+
changed = true;
|
|
3142
|
+
}
|
|
3143
|
+
if (changed) fireState();
|
|
3144
|
+
};
|
|
3145
|
+
const getFragment = (fragmentId) => {
|
|
3146
|
+
const frag = fragments[fragmentId];
|
|
3147
|
+
if (frag === void 0) throw new UnknownFragmentError(`Unknown fragment: ${fragmentId}`, { fragmentId });
|
|
3148
|
+
return frag;
|
|
3149
|
+
};
|
|
3150
|
+
const registerFragment = (fragment2) => {
|
|
3151
|
+
guard();
|
|
3152
|
+
if (fragment2.id === void 0) throw new UnknownFragmentError("Fragment is missing an id", { fragmentId: "" });
|
|
3153
|
+
validateFragments({ [fragment2.id]: fragment2 });
|
|
3154
|
+
fragments[fragment2.id] = fragment2;
|
|
3155
|
+
};
|
|
3156
|
+
const resolveDefinition = (actionId, fragmentIds) => {
|
|
3157
|
+
const def = getDefinition(actionId);
|
|
3158
|
+
if (fragmentIds === void 0 || fragmentIds.length === 0) return def;
|
|
3159
|
+
return composeAction(def, fragmentIds.map(getFragment));
|
|
3160
|
+
};
|
|
3161
|
+
const announced = /* @__PURE__ */ new Map();
|
|
3162
|
+
let announcing = false;
|
|
3163
|
+
const announceNavigation = () => {
|
|
3164
|
+
if (announcing || disposed) return;
|
|
3165
|
+
announcing = true;
|
|
3166
|
+
queueMicrotask(() => {
|
|
3167
|
+
announcing = false;
|
|
3168
|
+
if (disposed) return;
|
|
3169
|
+
for (const [canvasId, canvas] of canvases) {
|
|
3170
|
+
const active = canvas.peek();
|
|
3171
|
+
if (announced.get(canvasId) === active?.id) continue;
|
|
3172
|
+
announced.set(canvasId, active?.id);
|
|
3173
|
+
const message = active === void 0 ? { canvas: canvasId } : { canvas: canvasId, action: active.definitionId, instance: active.id };
|
|
3174
|
+
messageBus.publish(navigatedChannel(canvasId), message);
|
|
3175
|
+
}
|
|
3176
|
+
});
|
|
3177
|
+
};
|
|
3178
|
+
const fireState = () => {
|
|
3179
|
+
if (disposed) return;
|
|
3180
|
+
const out = {};
|
|
3181
|
+
for (const [cid, c] of canvases) out[cid] = snapshotCanvas(c);
|
|
3182
|
+
const snapshot = { canvases: out };
|
|
3183
|
+
telemetry.fireStateChange(snapshot);
|
|
3184
|
+
announceNavigation();
|
|
3185
|
+
};
|
|
3186
|
+
const positionOf = (canvasId) => {
|
|
3187
|
+
const canvas = canvases.get(canvasId);
|
|
3188
|
+
if (canvas === void 0) return [];
|
|
3189
|
+
return canvas.stack.map((inst) => {
|
|
3190
|
+
const birth = births.get(inst.id);
|
|
3191
|
+
return {
|
|
3192
|
+
instance: inst.id,
|
|
3193
|
+
action: birth?.action ?? inst.definitionId,
|
|
3194
|
+
...birth?.input === void 0 ? {} : { input: birth.input },
|
|
3195
|
+
...birth?.with === void 0 ? {} : { with: birth.with }
|
|
3196
|
+
};
|
|
3197
|
+
});
|
|
3198
|
+
};
|
|
3199
|
+
const record = (canvasId) => journal.record(canvasId, positionOf(canvasId));
|
|
3200
|
+
const navigationHandler = createNavigationHandler({
|
|
3201
|
+
push: (cid, aid, input, frags) => push(cid, aid, input, frags),
|
|
3202
|
+
pop: (cid) => pop(cid),
|
|
3203
|
+
replace: (cid, aid, input, frags) => replace(cid, aid, input, frags),
|
|
3204
|
+
clear: (cid) => clear(cid),
|
|
3205
|
+
// ONE position, then both halves — see ShellNavOps.resetTo. The record is
|
|
3206
|
+
// taken outside the mute so the deck being thrown away is what back returns
|
|
3207
|
+
// to; the calls inside it record nothing of their own.
|
|
3208
|
+
resetTo: (cid, aid, input, frags) => {
|
|
3209
|
+
record(cid);
|
|
3210
|
+
journal.mute(() => {
|
|
3211
|
+
clear(cid);
|
|
3212
|
+
push(cid, aid, input, frags);
|
|
3213
|
+
});
|
|
3214
|
+
},
|
|
3215
|
+
popTo: (cid, iid) => popTo(cid, iid),
|
|
3216
|
+
removeInstance: (cid, iid) => removeInstance(cid, iid),
|
|
3217
|
+
// ONE movement, like resetTo: the position before it is what back returns
|
|
3218
|
+
// to — recorded only when something actually moved, so a reconcile that
|
|
3219
|
+
// found the canvas already right leaves no empty step in history. Rows
|
|
3220
|
+
// naming an action this shell does not have are skipped: ungranted is
|
|
3221
|
+
// absent, as an ungranted `initial` candidate is.
|
|
3222
|
+
reconcile: (cid, desired, options) => {
|
|
3223
|
+
const before = positionOf(cid);
|
|
3224
|
+
const known = desired.filter((entry) => actions[entry.actionId] !== void 0).map((entry) => options.with === void 0 ? entry : { ...entry, with: options.with });
|
|
3225
|
+
const result = journal.mute(
|
|
3226
|
+
() => reconcileCanvas(shell, cid, known, {
|
|
3227
|
+
origin: options.origin,
|
|
3228
|
+
...options.own === void 0 ? {} : { own: options.own },
|
|
3229
|
+
definitionOf: (actionId) => actions[actionId]
|
|
3230
|
+
})
|
|
3231
|
+
);
|
|
3232
|
+
if (result.changed) journal.record(cid, before);
|
|
3233
|
+
}
|
|
3234
|
+
});
|
|
3235
|
+
const buildRuntime = createRuntimeFactory({
|
|
3236
|
+
eventBus,
|
|
3237
|
+
messageBus,
|
|
3238
|
+
layoutStore,
|
|
3239
|
+
registry: componentRegistry,
|
|
3240
|
+
...config.transform === void 0 ? {} : { transform: config.transform },
|
|
3241
|
+
...config.fetch === void 0 ? {} : { fetch: config.fetch },
|
|
3242
|
+
...config.functions === void 0 ? {} : { functions: config.functions },
|
|
3243
|
+
...config.endpointTimeoutMs === void 0 ? {} : { endpointTimeoutMs: config.endpointTimeoutMs },
|
|
3244
|
+
strict,
|
|
3245
|
+
...config.onError === void 0 ? {} : { onError: config.onError },
|
|
3246
|
+
i18n: language,
|
|
3247
|
+
instanceIdFn,
|
|
3248
|
+
onNavigate: (cid, effect) => navigationHandler(cid, effect),
|
|
3249
|
+
// Every endpoint call an action makes flows to telemetry — the shell's one
|
|
3250
|
+
// observability surface (state, data, and now endpoints all land here).
|
|
3251
|
+
onEndpoint: (event) => telemetry.fireEndpoint(event)
|
|
3252
|
+
});
|
|
3253
|
+
const spawn = (canvasId, definition, input) => {
|
|
3254
|
+
const runtime = buildRuntime(canvasId, definition, input);
|
|
3255
|
+
const instId = runtime.instance.id;
|
|
3256
|
+
registry.register(runtime, (data) => {
|
|
3257
|
+
if (disposed) return;
|
|
3258
|
+
telemetry.fireDataChange({ instanceId: instId, canvasId: runtime.instance.canvasId, data });
|
|
3259
|
+
});
|
|
3260
|
+
runtime.mount(input).catch(handleLifecycleRejection);
|
|
3261
|
+
return runtime;
|
|
3262
|
+
};
|
|
3263
|
+
const push = (canvasId, actionId, input, fragmentIds, options) => {
|
|
3264
|
+
guard();
|
|
3265
|
+
if (options?.history !== false) record(canvasId);
|
|
3266
|
+
const canvas = getCanvas(canvasId);
|
|
3267
|
+
const definition = resolveDefinition(actionId, fragmentIds);
|
|
3268
|
+
if (!listCanvases.has(canvasId)) ops.suspendTop(canvas);
|
|
3269
|
+
const runtime = spawn(canvasId, definition, input);
|
|
3270
|
+
canvas.pushInstance(runtime.instance);
|
|
3271
|
+
births.set(runtime.instance.id, {
|
|
3272
|
+
action: actionId,
|
|
3273
|
+
...input === void 0 ? {} : { input },
|
|
3274
|
+
...fragmentIds === void 0 ? {} : { with: fragmentIds }
|
|
3275
|
+
});
|
|
3276
|
+
if (options?.origin !== void 0) origins.set(runtime.instance.id, options.origin);
|
|
3277
|
+
fireState();
|
|
3278
|
+
return runtime.instance.id;
|
|
3279
|
+
};
|
|
3280
|
+
const removeInstance = (canvasId, instanceId) => {
|
|
3281
|
+
if (disposed) return;
|
|
3282
|
+
guardNoPendingStrictError();
|
|
3283
|
+
const canvas = canvases.get(canvasId);
|
|
3284
|
+
if (canvas === void 0) return;
|
|
3285
|
+
if (!canvas.stack.some((i) => i.id === instanceId)) return;
|
|
3286
|
+
const previousTop = canvas.peek();
|
|
3287
|
+
for (const inst of canvas.clearStack()) {
|
|
3288
|
+
if (inst.id === instanceId) ops.unmountInstance(inst.id);
|
|
3289
|
+
else canvas.pushInstance(inst);
|
|
3290
|
+
}
|
|
3291
|
+
journal.consume(canvasId);
|
|
3292
|
+
if (!listCanvases.has(canvasId) && canvas.peek() !== previousTop) ops.resumeTop(canvas);
|
|
3293
|
+
fireState();
|
|
3294
|
+
};
|
|
3295
|
+
const pop = (canvasId) => {
|
|
3296
|
+
if (disposed) return;
|
|
3297
|
+
guardNoPendingStrictError();
|
|
3298
|
+
const canvas = canvases.get(canvasId);
|
|
3299
|
+
if (canvas === void 0) return;
|
|
3300
|
+
const top = canvas.popInstance();
|
|
3301
|
+
if (top === void 0) return;
|
|
3302
|
+
ops.unmountInstance(top.id);
|
|
3303
|
+
journal.consume(canvasId);
|
|
3304
|
+
ops.resumeTop(canvas);
|
|
3305
|
+
fireState();
|
|
3306
|
+
};
|
|
3307
|
+
const popTo = (canvasId, instanceId) => {
|
|
3308
|
+
if (disposed) return;
|
|
3309
|
+
guardNoPendingStrictError();
|
|
3310
|
+
const canvas = canvases.get(canvasId);
|
|
3311
|
+
if (canvas === void 0) return;
|
|
3312
|
+
if (!snapshotCanvas(canvas).stack.some((i) => i.id === instanceId)) return;
|
|
3313
|
+
let changed = false;
|
|
3314
|
+
for (; ; ) {
|
|
3315
|
+
const active = snapshotCanvas(canvas).active;
|
|
3316
|
+
if (active === void 0 || active.id === instanceId) break;
|
|
3317
|
+
const top = canvas.popInstance();
|
|
3318
|
+
if (top === void 0) break;
|
|
3319
|
+
ops.unmountInstance(top.id);
|
|
3320
|
+
changed = true;
|
|
3321
|
+
}
|
|
3322
|
+
if (changed) {
|
|
3323
|
+
journal.consume(canvasId);
|
|
3324
|
+
ops.resumeTop(canvas);
|
|
3325
|
+
fireState();
|
|
3326
|
+
}
|
|
3327
|
+
};
|
|
3328
|
+
const replace = (canvasId, actionId, input, fragmentIds) => {
|
|
3329
|
+
guard();
|
|
3330
|
+
record(canvasId);
|
|
3331
|
+
const canvas = getCanvas(canvasId);
|
|
3332
|
+
const definition = resolveDefinition(actionId, fragmentIds);
|
|
3333
|
+
const old = canvas.popInstance();
|
|
3334
|
+
if (old !== void 0) ops.unmountInstance(old.id);
|
|
3335
|
+
const runtime = spawn(canvasId, definition, input);
|
|
3336
|
+
canvas.pushInstance(runtime.instance);
|
|
3337
|
+
births.set(runtime.instance.id, {
|
|
3338
|
+
action: actionId,
|
|
3339
|
+
...input === void 0 ? {} : { input },
|
|
3340
|
+
...fragmentIds === void 0 ? {} : { with: fragmentIds }
|
|
3341
|
+
});
|
|
3342
|
+
fireState();
|
|
3343
|
+
return runtime.instance.id;
|
|
3344
|
+
};
|
|
3345
|
+
const clear = (canvasId) => {
|
|
3346
|
+
if (disposed) return;
|
|
3347
|
+
guardNoPendingStrictError();
|
|
3348
|
+
const canvas = canvases.get(canvasId);
|
|
3349
|
+
if (canvas === void 0) return;
|
|
3350
|
+
if (canvas.stack.length > 0) record(canvasId);
|
|
3351
|
+
for (const inst of canvas.clearStack()) ops.unmountInstance(inst.id);
|
|
3352
|
+
fireState();
|
|
3353
|
+
};
|
|
3354
|
+
const restore = (entry) => {
|
|
3355
|
+
const canvas = canvases.get(entry.canvas);
|
|
3356
|
+
if (canvas === void 0) return false;
|
|
3357
|
+
let common = 0;
|
|
3358
|
+
while (common < canvas.stack.length && common < entry.stack.length && canvas.stack[common]?.id === entry.stack[common]?.instance) {
|
|
3359
|
+
common += 1;
|
|
3360
|
+
}
|
|
3361
|
+
if (common === canvas.stack.length && common === entry.stack.length) return false;
|
|
3362
|
+
for (let i = common; i < entry.stack.length; i += 1) {
|
|
3363
|
+
const frame = entry.stack[i];
|
|
3364
|
+
if (frame !== void 0 && actions[frame.action] === void 0) return false;
|
|
3365
|
+
}
|
|
3366
|
+
journal.mute(() => {
|
|
3367
|
+
const standing = canvas.clearStack();
|
|
3368
|
+
for (let i = 0; i < standing.length; i += 1) {
|
|
3369
|
+
const inst = standing[i];
|
|
3370
|
+
if (inst === void 0) continue;
|
|
3371
|
+
if (i < common) canvas.pushInstance(inst);
|
|
3372
|
+
else ops.unmountInstance(inst.id);
|
|
3373
|
+
}
|
|
3374
|
+
if (common === entry.stack.length) {
|
|
3375
|
+
if (!listCanvases.has(entry.canvas)) ops.resumeTop(canvas);
|
|
3376
|
+
return;
|
|
3377
|
+
}
|
|
3378
|
+
for (let i = common; i < entry.stack.length; i += 1) {
|
|
3379
|
+
const frame = entry.stack[i];
|
|
3380
|
+
if (frame === void 0) continue;
|
|
3381
|
+
push(entry.canvas, frame.action, frame.input, frame.with);
|
|
3382
|
+
}
|
|
3383
|
+
});
|
|
3384
|
+
fireState();
|
|
3385
|
+
return true;
|
|
3386
|
+
};
|
|
3387
|
+
const back = () => {
|
|
3388
|
+
if (disposed) return false;
|
|
3389
|
+
guardNoPendingStrictError();
|
|
3390
|
+
for (; ; ) {
|
|
3391
|
+
const entry = journal.take();
|
|
3392
|
+
if (entry === void 0) return false;
|
|
3393
|
+
if (restore(entry)) return true;
|
|
3394
|
+
}
|
|
3395
|
+
};
|
|
3396
|
+
const seedCanvas = (cfg) => {
|
|
3397
|
+
if (cfg.initial === void 0) return;
|
|
3398
|
+
const seeds = Array.isArray(cfg.initial) ? cfg.initial : [cfg.initial];
|
|
3399
|
+
journal.mute(() => {
|
|
3400
|
+
for (const seed of seeds) {
|
|
3401
|
+
if (typeof seed === "string") push(cfg.id, seed);
|
|
3402
|
+
else push(cfg.id, seed.action, seed.input, seed.with);
|
|
3403
|
+
}
|
|
3404
|
+
});
|
|
3405
|
+
};
|
|
3406
|
+
const addCanvas = (cfg) => {
|
|
3407
|
+
guard();
|
|
3408
|
+
if (canvases.has(cfg.id)) return;
|
|
3409
|
+
canvases.set(cfg.id, createCanvas(cfg.id));
|
|
3410
|
+
if (cfg.actionLayout !== void 0) actionLayouts.set(cfg.id, cfg.actionLayout);
|
|
3411
|
+
canvasOrder.push(cfg.id);
|
|
3412
|
+
seedCanvas(cfg);
|
|
3413
|
+
fireState();
|
|
3414
|
+
};
|
|
3415
|
+
const removeCanvas = (canvasId) => {
|
|
3416
|
+
if (disposed) return;
|
|
3417
|
+
guardNoPendingStrictError();
|
|
3418
|
+
const canvas = canvases.get(canvasId);
|
|
3419
|
+
if (canvas === void 0) return;
|
|
3420
|
+
for (const inst of canvas.clearStack()) ops.unmountInstance(inst.id);
|
|
3421
|
+
canvases.delete(canvasId);
|
|
3422
|
+
journal.forgetCanvas(canvasId);
|
|
3423
|
+
announced.delete(canvasId);
|
|
3424
|
+
actionLayouts.delete(canvasId);
|
|
3425
|
+
const index = canvasOrder.indexOf(canvasId);
|
|
3426
|
+
if (index >= 0) canvasOrder.splice(index, 1);
|
|
3427
|
+
fireState();
|
|
3428
|
+
};
|
|
3429
|
+
const setCanvasLayout = (layout) => {
|
|
3430
|
+
guard();
|
|
3431
|
+
canvasLayout = layout;
|
|
3432
|
+
fireState();
|
|
3433
|
+
};
|
|
3434
|
+
const setLayout = (refId, layout) => {
|
|
3435
|
+
guard();
|
|
3436
|
+
layoutStore.set(refId, layout);
|
|
3437
|
+
fireState();
|
|
3438
|
+
};
|
|
3439
|
+
const setPhrases = (next) => {
|
|
3440
|
+
guard();
|
|
3441
|
+
phrases = next;
|
|
3442
|
+
if (next !== void 0) bearing = true;
|
|
3443
|
+
fireState();
|
|
3444
|
+
};
|
|
3445
|
+
const getPhrases = () => phrases;
|
|
3446
|
+
const getCanvasState = (canvasId) => {
|
|
3447
|
+
guardNoPendingStrictError();
|
|
3448
|
+
const canvas = canvases.get(canvasId);
|
|
3449
|
+
if (canvas === void 0) return { id: canvasId, stack: [], active: void 0 };
|
|
3450
|
+
return snapshotCanvas(canvas);
|
|
3451
|
+
};
|
|
3452
|
+
const dispose = () => {
|
|
3453
|
+
if (disposed) return;
|
|
3454
|
+
disposed = true;
|
|
3455
|
+
for (const [, canvas] of canvases) {
|
|
3456
|
+
for (const inst of canvas.clearStack()) ops.unmountInstance(inst.id);
|
|
3457
|
+
}
|
|
3458
|
+
registry.disposeAll();
|
|
3459
|
+
canvases.clear();
|
|
3460
|
+
telemetry.clear();
|
|
3461
|
+
};
|
|
3462
|
+
const getRuntime = (iid) => registry.get(iid);
|
|
3463
|
+
const onStateChange = (h) => telemetry.onStateChange(h);
|
|
3464
|
+
const onDataChange = (h) => telemetry.onDataChange(h);
|
|
3465
|
+
const onEndpoint = (h) => telemetry.onEndpoint(h);
|
|
3466
|
+
const sameCanvasState = (a, b) => {
|
|
3467
|
+
if (a.stack.length !== b.stack.length) return false;
|
|
3468
|
+
if (a.active?.id !== b.active?.id) return false;
|
|
3469
|
+
for (let i = 0; i < a.stack.length; i += 1) {
|
|
3470
|
+
const aItem = a.stack[i];
|
|
3471
|
+
const bItem = b.stack[i];
|
|
3472
|
+
if (aItem === void 0 || bItem === void 0) return false;
|
|
3473
|
+
if (aItem.id !== bItem.id || aItem.status !== bItem.status) return false;
|
|
3474
|
+
}
|
|
3475
|
+
return true;
|
|
3476
|
+
};
|
|
3477
|
+
const onCanvasChange = (canvasId, handler) => {
|
|
3478
|
+
let prev = getCanvasState(canvasId);
|
|
3479
|
+
return telemetry.onStateChange(() => {
|
|
3480
|
+
const next = getCanvasState(canvasId);
|
|
3481
|
+
if (sameCanvasState(prev, next)) return;
|
|
3482
|
+
prev = next;
|
|
3483
|
+
handler(next);
|
|
3484
|
+
});
|
|
3485
|
+
};
|
|
3486
|
+
const getState = () => {
|
|
3487
|
+
const out = {};
|
|
3488
|
+
for (const [cid, c] of canvases) out[cid] = snapshotCanvas(c);
|
|
3489
|
+
return { canvases: out };
|
|
3490
|
+
};
|
|
3491
|
+
const renderLayoutOrRef = (layout, data) => {
|
|
3492
|
+
const resolved = typeof layout === "string" ? layoutStore.get(layout) : layout;
|
|
3493
|
+
if (resolved === void 0) return [];
|
|
3494
|
+
const current = language();
|
|
3495
|
+
return renderLayoutFromStore(
|
|
3496
|
+
resolved,
|
|
3497
|
+
{ get: () => data },
|
|
3498
|
+
{
|
|
3499
|
+
store: layoutStore,
|
|
3500
|
+
registry: componentRegistry,
|
|
3501
|
+
strict,
|
|
3502
|
+
...config.onError === void 0 ? {} : { onError: config.onError },
|
|
3503
|
+
...current?.phrases === void 0 ? {} : { phrases: current.phrases },
|
|
3504
|
+
...current?.phraseKeys === void 0 ? {} : { phraseKeys: current.phraseKeys },
|
|
3505
|
+
...current?.onPhraseMiss === void 0 ? {} : { onPhraseMiss: current.onPhraseMiss }
|
|
3506
|
+
}
|
|
3507
|
+
);
|
|
3508
|
+
};
|
|
3509
|
+
const getShellRenderTree = () => {
|
|
3510
|
+
const canvasList = [];
|
|
3511
|
+
for (const cid of canvasOrder) {
|
|
3512
|
+
const c = canvases.get(cid);
|
|
3513
|
+
canvasList.push(c === void 0 ? { id: cid, stack: [], active: void 0 } : snapshotCanvas(c));
|
|
3514
|
+
}
|
|
3515
|
+
return renderLayoutOrRef(canvasLayout ?? DEFAULT_SHELL_LAYOUT, { canvases: canvasList });
|
|
3516
|
+
};
|
|
3517
|
+
const titleOf = (instance) => {
|
|
3518
|
+
const def = registry.get(instance.id)?.definition ?? actions[instance.definitionId];
|
|
3519
|
+
if (def?.title !== void 0) {
|
|
3520
|
+
const resolved = resolve(def.title, createScopeChain(instance.data));
|
|
3521
|
+
if (resolved !== void 0 && resolved !== null && resolved !== "") return String(resolved);
|
|
3522
|
+
}
|
|
3523
|
+
return def?.name ?? instance.definitionId;
|
|
3524
|
+
};
|
|
3525
|
+
const getCanvasRenderTree = (canvasId) => {
|
|
3526
|
+
const canvas = canvases.get(canvasId);
|
|
3527
|
+
const state = canvas === void 0 ? { stack: []} : snapshotCanvas(canvas);
|
|
3528
|
+
const instances = state.stack.map((i) => ({ ...i, title: titleOf(i) }));
|
|
3529
|
+
const scope = {
|
|
3530
|
+
instances,
|
|
3531
|
+
active: instances.length === 0 ? void 0 : instances[instances.length - 1],
|
|
3532
|
+
count: instances.length
|
|
3533
|
+
};
|
|
3534
|
+
return renderLayoutOrRef(actionLayouts.get(canvasId) ?? DEFAULT_ACTION_LAYOUT, scope);
|
|
3535
|
+
};
|
|
3536
|
+
const dispatch = (event) => {
|
|
3537
|
+
eventBus.emit(event);
|
|
3538
|
+
};
|
|
3539
|
+
const publish = (channel, payload) => {
|
|
3540
|
+
messageBus.publish(channel, payload);
|
|
3541
|
+
};
|
|
3542
|
+
const shell = {
|
|
3543
|
+
id,
|
|
3544
|
+
registry: componentRegistry,
|
|
3545
|
+
layoutStore,
|
|
3546
|
+
push,
|
|
3547
|
+
originOf: (instanceId) => origins.get(instanceId),
|
|
3548
|
+
pop,
|
|
3549
|
+
popTo,
|
|
3550
|
+
removeInstance,
|
|
3551
|
+
replace,
|
|
3552
|
+
clear,
|
|
3553
|
+
back,
|
|
3554
|
+
registerAction,
|
|
3555
|
+
removeAction,
|
|
3556
|
+
registerFragment,
|
|
3557
|
+
addCanvas,
|
|
3558
|
+
removeCanvas,
|
|
3559
|
+
setCanvasLayout,
|
|
3560
|
+
setPhrases,
|
|
3561
|
+
getPhrases,
|
|
3562
|
+
setLayout,
|
|
3563
|
+
getCanvasState,
|
|
3564
|
+
getRuntime,
|
|
3565
|
+
getState,
|
|
3566
|
+
getShellRenderTree,
|
|
3567
|
+
getCanvasRenderTree,
|
|
3568
|
+
flattenRenderTree: (tree) => flattenRenderTree(tree, shell),
|
|
3569
|
+
dispatch,
|
|
3570
|
+
publish,
|
|
3571
|
+
onStateChange,
|
|
3572
|
+
onDataChange,
|
|
3573
|
+
onEndpoint,
|
|
3574
|
+
onCanvasChange,
|
|
3575
|
+
dispose
|
|
3576
|
+
};
|
|
3577
|
+
rememberShellRegistry(shell, registry);
|
|
3578
|
+
for (const cfg of config.canvases) seedCanvas(cfg);
|
|
3579
|
+
return shell;
|
|
3580
|
+
};
|
|
3581
|
+
|
|
3582
|
+
// src/shell/view.ts
|
|
3583
|
+
var hasVisibleContent = (nodes) => nodes.some((node) => {
|
|
3584
|
+
if (node.type === "text") return node.value !== "";
|
|
3585
|
+
if (node.type === "fragment") return hasVisibleContent(node.children);
|
|
3586
|
+
if (node.type === "component" && node.name === ACTION_SLOT_NAME) return hasVisibleContent(node.children);
|
|
3587
|
+
return true;
|
|
3588
|
+
});
|
|
3589
|
+
var canvasTreeOf = (shell, canvasId) => {
|
|
3590
|
+
const tree = shell.flattenRenderTree(shell.getCanvasRenderTree(canvasId));
|
|
3591
|
+
return hasVisibleContent(tree) ? tree : [];
|
|
3592
|
+
};
|
|
3593
|
+
var shellView = (shell) => ({
|
|
3594
|
+
api: {
|
|
3595
|
+
frame: () => shell.getShellRenderTree(),
|
|
3596
|
+
canvasTree: (canvasId) => canvasTreeOf(shell, canvasId),
|
|
3597
|
+
// An event that names no origin belongs to the canvas's ACTIVE instance — on
|
|
3598
|
+
// a card deck that is the only one drawn. One that names its own (an
|
|
3599
|
+
// adapter stamps it at the instance boundary, `scopeDispatch`) keeps it. A
|
|
3600
|
+
// canvas with nothing mounted dispatches unstamped.
|
|
3601
|
+
dispatch: (canvasId, event) => {
|
|
3602
|
+
const active = shell.getState().canvases[canvasId]?.active;
|
|
3603
|
+
shell.dispatch(event.origin === void 0 && active !== void 0 ? { ...event, origin: active.id } : event);
|
|
3604
|
+
},
|
|
3605
|
+
publish: (channel, payload) => shell.publish(channel, payload)
|
|
3606
|
+
},
|
|
3607
|
+
subscribe: (listener) => {
|
|
3608
|
+
let pending = false;
|
|
3609
|
+
let stopped = false;
|
|
3610
|
+
const changed = () => {
|
|
3611
|
+
if (pending || stopped) return;
|
|
3612
|
+
pending = true;
|
|
3613
|
+
queueMicrotask(() => {
|
|
3614
|
+
pending = false;
|
|
3615
|
+
if (!stopped) listener();
|
|
3616
|
+
});
|
|
3617
|
+
};
|
|
3618
|
+
const offState = shell.onStateChange(changed);
|
|
3619
|
+
const offData = shell.onDataChange(changed);
|
|
3620
|
+
return () => {
|
|
3621
|
+
stopped = true;
|
|
3622
|
+
offState();
|
|
3623
|
+
offData();
|
|
3624
|
+
};
|
|
3625
|
+
}
|
|
3626
|
+
});
|
|
3627
|
+
var DEFAULT_SETTLE_WAIT_MS = 300;
|
|
3628
|
+
var shellSettled = async (shell, options = {}) => {
|
|
3629
|
+
const waitMs = options.waitMs ?? DEFAULT_SETTLE_WAIT_MS;
|
|
3630
|
+
const mounting = () => Object.values(shell.getState().canvases).some((canvas) => canvas.stack.some((instance) => instance.status === "initializing"));
|
|
3631
|
+
let timer;
|
|
3632
|
+
const deadline = new Promise((resolve2) => {
|
|
3633
|
+
timer = setTimeout(() => resolve2(false), waitMs);
|
|
3634
|
+
});
|
|
3635
|
+
const quiet = (async () => {
|
|
3636
|
+
for (; ; ) {
|
|
3637
|
+
if (options.stopped?.() === true) return false;
|
|
3638
|
+
if (!mounting()) {
|
|
3639
|
+
await new Promise((resolve2) => setTimeout(resolve2, 0));
|
|
3640
|
+
if (!mounting()) return true;
|
|
3641
|
+
}
|
|
3642
|
+
await new Promise((resolve2) => {
|
|
3643
|
+
const off = shell.onStateChange(() => {
|
|
3644
|
+
off();
|
|
3645
|
+
resolve2();
|
|
3646
|
+
});
|
|
3647
|
+
setTimeout(() => {
|
|
3648
|
+
off();
|
|
3649
|
+
resolve2();
|
|
3650
|
+
}, 10);
|
|
3651
|
+
});
|
|
3652
|
+
}
|
|
3653
|
+
})();
|
|
3654
|
+
const settled = await Promise.race([quiet, deadline]);
|
|
3655
|
+
clearTimeout(timer);
|
|
3656
|
+
return settled;
|
|
3657
|
+
};
|
|
3658
|
+
|
|
3659
|
+
exports.ACTION_SLOT_NAME = ACTION_SLOT_NAME;
|
|
3660
|
+
exports.ActionDefinitionSchema = ActionDefinitionSchema;
|
|
3661
|
+
exports.ActionFragmentSchema = ActionFragmentSchema;
|
|
3662
|
+
exports.CANVAS_SLOT_NAME = CANVAS_SLOT_NAME;
|
|
3663
|
+
exports.ComponentNodeSchema = ComponentNodeSchema;
|
|
3664
|
+
exports.ComponentNotFoundError = ComponentNotFoundError;
|
|
3665
|
+
exports.ConditionalNodeSchema = ConditionalNodeSchema;
|
|
3666
|
+
exports.DEFAULT_HISTORY_DEPTH = DEFAULT_HISTORY_DEPTH;
|
|
3667
|
+
exports.DEFAULT_SETTLE_WAIT_MS = DEFAULT_SETTLE_WAIT_MS;
|
|
3668
|
+
exports.DefinitionValidationError = DefinitionValidationError;
|
|
3669
|
+
exports.EffectSchema = EffectSchema;
|
|
3670
|
+
exports.EndpointConfigSchema = EndpointConfigSchema;
|
|
3671
|
+
exports.ErrorCodes = ErrorCodes;
|
|
3672
|
+
exports.LayoutNodeSchema = LayoutNodeSchema;
|
|
3673
|
+
exports.LayoutPrimitiveSchema = LayoutPrimitiveSchema;
|
|
3674
|
+
exports.LayoutRefNodeSchema = LayoutRefNodeSchema;
|
|
3675
|
+
exports.LayoutRefNotFoundError = LayoutRefNotFoundError;
|
|
3676
|
+
exports.LifecycleConfigSchema = LifecycleConfigSchema;
|
|
3677
|
+
exports.LifecycleError = LifecycleError;
|
|
3678
|
+
exports.LoopNodeSchema = LoopNodeSchema;
|
|
3679
|
+
exports.MessageEnvelopeSchema = MessageEnvelopeSchema;
|
|
3680
|
+
exports.MutationSchema = MutationSchema;
|
|
3681
|
+
exports.NOVA_MODEL_PROP = NOVA_MODEL_PROP;
|
|
3682
|
+
exports.NOVA_REF_PROP = NOVA_REF_PROP;
|
|
3683
|
+
exports.NovaError = NovaError;
|
|
3684
|
+
exports.NovaEventSchema = NovaEventSchema;
|
|
3685
|
+
exports.RenderError = RenderError;
|
|
3686
|
+
exports.ShellDisposedError = ShellDisposedError;
|
|
3687
|
+
exports.SlotNodeSchema = SlotNodeSchema;
|
|
3688
|
+
exports.StepSchema = StepSchema;
|
|
3689
|
+
exports.TriggerConfigSchema = TriggerConfigSchema;
|
|
3690
|
+
exports.UnknownActionError = UnknownActionError;
|
|
3691
|
+
exports.UnknownFragmentError = UnknownFragmentError;
|
|
3692
|
+
exports.UnknownFunctionError = UnknownFunctionError;
|
|
3693
|
+
exports.auditAction = auditAction;
|
|
3694
|
+
exports.canvasTreeOf = canvasTreeOf;
|
|
3695
|
+
exports.collectChannels = collectChannels;
|
|
3696
|
+
exports.composeAction = composeAction;
|
|
3697
|
+
exports.createComponentRegistry = createComponentRegistry;
|
|
3698
|
+
exports.createIdFactory = createIdFactory;
|
|
3699
|
+
exports.createLayoutStore = createLayoutStore;
|
|
3700
|
+
exports.createShell = createShell;
|
|
3701
|
+
exports.fillSlots = fillSlots;
|
|
3702
|
+
exports.getPath = getPath;
|
|
3703
|
+
exports.hasVisibleContent = hasVisibleContent;
|
|
3704
|
+
exports.isComponentNode = isComponentNode;
|
|
3705
|
+
exports.isConditionalNode = isConditionalNode;
|
|
3706
|
+
exports.isLayoutNode = isLayoutNode;
|
|
3707
|
+
exports.isLayoutPrimitive = isLayoutPrimitive;
|
|
3708
|
+
exports.isLayoutRefNode = isLayoutRefNode;
|
|
3709
|
+
exports.isLoopNode = isLoopNode;
|
|
3710
|
+
exports.isSlotNode = isSlotNode;
|
|
3711
|
+
exports.navigatedChannel = navigatedChannel;
|
|
3712
|
+
exports.paletteEntryOf = paletteEntryOf;
|
|
3713
|
+
exports.paletteFromRegistry = paletteFromRegistry;
|
|
3714
|
+
exports.reconcileCanvas = reconcileCanvas;
|
|
3715
|
+
exports.render = render;
|
|
3716
|
+
exports.renderLayout = renderLayout;
|
|
3717
|
+
exports.renderLayoutFromStore = renderLayoutFromStore;
|
|
3718
|
+
exports.renderNodeKey = renderNodeKey;
|
|
3719
|
+
exports.scopeDispatch = scopeDispatch;
|
|
3720
|
+
exports.shellSettled = shellSettled;
|
|
3721
|
+
exports.shellView = shellView;
|
|
3722
|
+
//# sourceMappingURL=index.cjs.map
|
|
3723
|
+
//# sourceMappingURL=index.cjs.map
|