@app-compose/core 3.0.0-beta.10

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 The grlt-hub Authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,80 @@
1
+ # App Compose
2
+
3
+ App Compose helps you build front-end applications from isolated tasks with explicit dependencies and predictable execution order—without containers, decorators, or framework-specific APIs.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/%40app-compose%2Fcore?color=orange)](https://www.npmjs.com/package/@app-compose/core)
6
+ ![bundle size](https://deno.bundlejs.com/badge?q=@app-compose/core&treeshake=[*])
7
+ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/grlt-hub/app-compose)
8
+ [![llms.txt](https://img.shields.io/badge/llms.txt-ready-blue)](https://app-compose.dev/llms.txt)
9
+
10
+ [Learn](https://app-compose.dev/learn/quick-start/) | [Guides](https://app-compose.dev/guides/) | [Reference](https://app-compose.dev/reference/)
11
+
12
+ > [!NOTE]
13
+ > **Beta:** This project is currently in beta. The API may change before the stable release.
14
+ >
15
+ > - `@app-compose/core@3.0.0-beta.8`
16
+ > - `@app-compose/eslint-plugin@3.0.0-beta.8`
17
+ > - `@app-compose/coda@3.0.0-beta.8`
18
+
19
+ ## Features
20
+
21
+ - **Simplicity** — lightweight, no containers/providers/decorators, zero dependencies. Framework-agnostic.
22
+ - **Clarity** — no magic, no globals; context flows through typed wiring.
23
+ - **Reusability** — same code, different context per compose.
24
+ - **Testability** — missing context, duplicates, unused wires fail in CI.
25
+ - **Observability** — your app as plain JSON; hooks for start, complete, fail.
26
+
27
+ ## Adopt it gradually
28
+
29
+ If you want to use App-Compose for a part of your existing app, you don't have to rewrite the rest. Add it to your stack, and bring in more when you're ready.
30
+
31
+ ## See it run
32
+
33
+ A minimal example built on the three key pieces: Task, Tag, and Wire (how they connect).
34
+ Two features share data without knowing about each other.
35
+
36
+ ```ts
37
+ import { compose, createTask, createWire, tag } from "@app-compose/core"
38
+
39
+ const name = tag<string>("name")
40
+ const user = createTask({
41
+ name: "user",
42
+ run: { fn: () => ({ name: "World" }) },
43
+ })
44
+ const greeting = createTask({
45
+ name: "greeting",
46
+ run: {
47
+ context: name.value,
48
+ fn: (name) => console.log(`Hello, ${name}!`),
49
+ },
50
+ })
51
+
52
+ await compose()
53
+ .step(user)
54
+ .step(createWire({ from: user.result.name, to: name }))
55
+ .step(greeting)
56
+ .run() // Hello, World!
57
+ ```
58
+
59
+ ## Get started
60
+
61
+ Try App Compose in the [online sandbox](https://app-compose.dev/sandbox/) without installing anything, or add `@app-compose/core` with your package manager:
62
+
63
+ - npm: `npm install --save-exact @app-compose/core`
64
+ - pnpm: `pnpm add --save-exact @app-compose/core`
65
+ - Yarn: `yarn add --exact @app-compose/core`
66
+ - Bun: `bun add --exact @app-compose/core`
67
+
68
+ Continue with the [Quick Start](https://app-compose.dev/learn/quick-start/).
69
+
70
+ ## AI tools
71
+
72
+ Give your coding assistant the [documentation index](https://app-compose.dev/llms.txt) to find the pages relevant to your task.
73
+
74
+ ### DeepWiki
75
+
76
+ Open [deepwiki](https://deepwiki.com/grlt-hub/app-compose) and ask anything about the codebase.
77
+
78
+ ## License
79
+
80
+ App Compose is available under the [MIT License](LICENSE).
package/dist/index.cjs ADDED
@@ -0,0 +1,598 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/runnable/definition.ts
3
+ const Context$ = Symbol("$context");
4
+ const Execute$ = Symbol("$execute");
5
+ const Dispatch$ = Symbol("$dispatch");
6
+ // src/computable/definition.ts
7
+ const Spot$ = Symbol("$spot");
8
+ const Read$ = Symbol("$read");
9
+ const Build$ = Symbol("$build");
10
+ const Literal$ = Symbol("$literal");
11
+ const Compute$ = Symbol("$compute");
12
+ const Missing$ = Symbol("$missing");
13
+ const Optional$ = Symbol("$optional");
14
+ // src/computable/build.ts
15
+ /**
16
+ * Creates a build context from a shape
17
+ *
18
+ * @internal
19
+ */
20
+ const build = (context) => {
21
+ return {
22
+ [Spot$]: true,
23
+ [Build$]: context,
24
+ [Compute$]: [],
25
+ [Optional$]: false
26
+ };
27
+ };
28
+ // src/shared.ts
29
+ const LIBRARY_NAME = "[app-compose]";
30
+ const isObject = (x) => Object.prototype.toString.call(x) === "[object Object]";
31
+ const identity = (x) => x;
32
+ const T = () => true;
33
+ // src/computable/computer.ts
34
+ const createComputer = (registry) => {
35
+ const context = (value) => {
36
+ if (isObject(value)) if (Spot$ in value) return compute(value);
37
+ else {
38
+ let out = {};
39
+ for (const key of Object.keys(value)) if ((out[key] = context(value[key])) === Missing$) return Missing$;
40
+ return out;
41
+ }
42
+ else if (Array.isArray(value)) {
43
+ const out = Array.from({ length: value.length });
44
+ for (let i = 0; i < value.length; i++) if ((out[i] = context(value[i])) === Missing$) return Missing$;
45
+ return out;
46
+ } else throw new Error(`${LIBRARY_NAME} Literal value found in context: ${String(value)}.`);
47
+ };
48
+ /**
49
+ * `compute` - resolve a `Spot` to its final value.
50
+ *
51
+ * Resolves the spot's underlying value (`Build$`, `Literal$`, or `Read$`),
52
+ * then applies all `Compute$` transformations in order.
53
+ *
54
+ * `Missing$` flow is three-step `read -> compute -> optional`
55
+ *
56
+ * 1. Read `source` value (either literal, built, or from registry) as-is
57
+ * 2. Map the `source` value through the `Compute$` pipeline, preserving `Missing$` and delegating to internal-land
58
+ * 3. Guard `Missing$` according to `Optional$`, coercing to `undefined` if optional, or propagating as-is if not
59
+ *
60
+ * @param spot The `Spot` to evaluate
61
+ * @returns The resolved value, or `Missing$` when non-optional spot resolution fails
62
+ */
63
+ const compute = (spot) => {
64
+ let resolved;
65
+ if (Build$ in spot) resolved = context(spot[Build$]);
66
+ else if (Literal$ in spot) resolved = spot[Literal$];
67
+ else if (Read$ in spot) resolved = registry.has(spot[Read$]) ? registry.get(spot[Read$]) : Missing$;
68
+ else throw new Error(`${LIBRARY_NAME} Invalid Unit.`);
69
+ for (const step of spot[Compute$]) resolved = step(resolved);
70
+ if (resolved === Missing$ && spot[Optional$]) return void 0;
71
+ else return resolved;
72
+ };
73
+ const computeSafe = (spot) => {
74
+ const result = compute(spot);
75
+ return result === Missing$ ? void 0 : result;
76
+ };
77
+ return {
78
+ compute,
79
+ computeSafe
80
+ };
81
+ };
82
+ // src/computable/literal.ts
83
+ const literal = (value) => {
84
+ return {
85
+ [Spot$]: true,
86
+ [Literal$]: value,
87
+ [Compute$]: [],
88
+ [Optional$]: false
89
+ };
90
+ };
91
+ // src/computable/lens.ts
92
+ const Self$ = Symbol();
93
+ const raise = () => {
94
+ throw new Error(`${LIBRARY_NAME} Modifying a Reference is not allowed.`);
95
+ };
96
+ const reader = (property) => (value) => value === Missing$ ? Missing$ : value?.[property];
97
+ const get = (target, property, recv) => typeof property === "string" ? proxy({
98
+ ...target,
99
+ [Compute$]: target[Compute$].concat(reader(property))
100
+ }) : property === Self$ ? target : Reflect.get(target, property, recv);
101
+ const set = () => raise();
102
+ const proxy = (ref) => new Proxy(ref, {
103
+ get,
104
+ set
105
+ });
106
+ proxy.self = (lensable) => lensable[Self$] ?? lensable;
107
+ // src/computable/optional.ts
108
+ /**
109
+ * Mark a `Spot` as optional.
110
+ */
111
+ const optional = (spot) => {
112
+ return {
113
+ ...proxy.self(spot),
114
+ [Optional$]: true
115
+ };
116
+ };
117
+ // src/computable/reference.ts
118
+ const reference = (id) => {
119
+ return {
120
+ [Spot$]: true,
121
+ [Read$]: id,
122
+ [Compute$]: [],
123
+ [Optional$]: false
124
+ };
125
+ };
126
+ reference.lensed = (id) => {
127
+ return proxy({
128
+ [Spot$]: true,
129
+ [Read$]: id,
130
+ [Compute$]: [],
131
+ [Optional$]: false
132
+ });
133
+ };
134
+ // src/computable/shape.ts
135
+ const safe = (fn) => (value) => {
136
+ try {
137
+ return value === Missing$ ? Missing$ : fn(value);
138
+ } catch {
139
+ return Missing$;
140
+ }
141
+ };
142
+ function shape(ctxOrSpot, fn) {
143
+ const spot = build(ctxOrSpot);
144
+ if (fn) spot[Compute$].push(safe(fn));
145
+ return spot;
146
+ }
147
+ // src/runnable/task.ts
148
+ const dispatch = {
149
+ result: (result) => result.status === "done" ? result.value : Missing$,
150
+ status: (result) => result.status,
151
+ error: (result) => result.status === "fail" ? result.error : Missing$
152
+ };
153
+ const createTask = (config) => {
154
+ const id = {
155
+ result: Symbol(`Task[${config.name}]::result`),
156
+ status: Symbol(`Task[${config.name}]::status`),
157
+ error: Symbol(`Task[${config.name}]::error`)
158
+ };
159
+ const context = {
160
+ run: config.run.context ?? literal(void 0),
161
+ enabled: config.enabled?.context ?? literal(void 0)
162
+ };
163
+ return {
164
+ name: config.name,
165
+ kind: "task",
166
+ result: reference.lensed(id.result),
167
+ status: reference(id.status),
168
+ error: reference(id.error),
169
+ [Context$]: build(context),
170
+ [Execute$]: async (built) => {
171
+ const ctx = built;
172
+ if (ctx === Missing$) return { status: "skip" };
173
+ try {
174
+ if (!await (config.enabled?.fn ?? T)(ctx.enabled)) return { status: "skip" };
175
+ } catch (error) {
176
+ return {
177
+ status: "fail",
178
+ error
179
+ };
180
+ }
181
+ try {
182
+ return {
183
+ status: "done",
184
+ value: await config.run.fn(ctx.run)
185
+ };
186
+ } catch (error) {
187
+ return {
188
+ status: "fail",
189
+ error
190
+ };
191
+ }
192
+ },
193
+ [Dispatch$]: {
194
+ [id.result]: dispatch.result,
195
+ [id.status]: dispatch.status,
196
+ [id.error]: dispatch.error
197
+ }
198
+ };
199
+ };
200
+ // src/is.ts
201
+ const is = {
202
+ spot: (x) => isObject(x) && Spot$ in x,
203
+ tag: (x) => isObject(x) && Tag$ in x,
204
+ runnable: (x) => isObject(x) && Execute$ in x,
205
+ task: (x) => is.runnable(x) && x.kind === "task",
206
+ wire: (x) => is.runnable(x) && x.kind === "wire"
207
+ };
208
+ // src/runnable/wire.ts
209
+ const Tag$ = Symbol("$tag");
210
+ const tag = (name) => {
211
+ const id = Symbol(`Tag[${name}]`);
212
+ return {
213
+ [Tag$]: id,
214
+ name,
215
+ value: reference.lensed(id)
216
+ };
217
+ };
218
+ const pluck = (path) => (value) => path.reduce((acc, key) => acc?.[key], value);
219
+ function* walk(shape, path = []) {
220
+ if (is.tag(shape)) yield {
221
+ tag: shape,
222
+ fn: pluck(path)
223
+ };
224
+ else if (Array.isArray(shape)) for (let index = 0; index < shape.length; index++) yield* walk(shape[index], [...path, index]);
225
+ else if (isObject(shape)) for (const key of Object.keys(shape)) yield* walk(shape[key], [...path, key]);
226
+ else throw new Error(`${LIBRARY_NAME} Invalid shape ${String(shape)} provided to Wire at path "${path.join(".")}".`);
227
+ }
228
+ const createWire = (config) => {
229
+ const tags = /* @__PURE__ */ new Set();
230
+ const dispatch = {};
231
+ for (const entry of walk(config.to)) if (tags.has(entry.tag)) throw new Error(`${LIBRARY_NAME} Duplicate tag "${entry.tag.name}" found in Wire destination.`);
232
+ else tags.add(entry.tag), dispatch[entry.tag[Tag$]] = entry.fn;
233
+ return {
234
+ name: Array.from(tags).map((tag) => tag.name).join(" + "),
235
+ kind: "wire",
236
+ [Context$]: build(config.from),
237
+ [Execute$]: identity,
238
+ [Dispatch$]: dispatch
239
+ };
240
+ };
241
+ // src/compose/resolver.ts
242
+ function* scanShape(shape) {
243
+ if (isObject(shape)) if (Spot$ in shape) yield* scanSpot(shape);
244
+ else for (const key of Object.keys(shape)) yield* scanShape(shape[key]);
245
+ else if (Array.isArray(shape)) for (const item of shape) yield* scanShape(item);
246
+ else throw new Error(`${LIBRARY_NAME} Literal value found in context: ${String(shape)}.`);
247
+ }
248
+ function* scanSpot(spot) {
249
+ if (Literal$ in spot) return;
250
+ else if (Read$ in spot) return yield {
251
+ id: spot[Read$],
252
+ optional: spot[Optional$]
253
+ };
254
+ else if (Build$ in spot) for (const entry of scanShape(spot[Build$])) yield {
255
+ id: entry.id,
256
+ optional: entry.optional || spot[Optional$]
257
+ };
258
+ else throw new Error(`${LIBRARY_NAME} Invalid Unit.`);
259
+ }
260
+ function resolve(spot) {
261
+ const required = /* @__PURE__ */ new Set();
262
+ const optional = /* @__PURE__ */ new Set();
263
+ for (const entry of scanSpot(spot)) if (entry.optional) optional.add(entry.id);
264
+ else required.add(entry.id);
265
+ return {
266
+ required,
267
+ optional
268
+ };
269
+ }
270
+ // src/compose/analyze.ts
271
+ const analyze = (runnable) => {
272
+ const internal = runnable;
273
+ const writes = Object.getOwnPropertySymbols(internal[Dispatch$]);
274
+ const dependencies = resolve(internal[Context$]);
275
+ return {
276
+ type: internal.kind,
277
+ display: { name: internal.name },
278
+ writes,
279
+ dependencies
280
+ };
281
+ };
282
+ const createAnalyzer = () => {
283
+ const cache = /* @__PURE__ */ new WeakMap();
284
+ const get = (runnable) => {
285
+ const analysis = cache.get(runnable) ?? analyze(runnable);
286
+ return cache.set(runnable, analysis), analysis;
287
+ };
288
+ return { get };
289
+ };
290
+ // src/compose/graph.ts
291
+ const Scope = Map;
292
+ const graph = (root) => {
293
+ let entryID = 0;
294
+ const analyzer = createAnalyzer();
295
+ const toRun = (current, outer) => {
296
+ const { type, display, writes, dependencies } = analyzer.get(current.value);
297
+ const wrote = writes.reduce((acc, sym) => acc.set(sym, entryID), new Scope());
298
+ return {
299
+ node: {
300
+ type: "run",
301
+ meta: {
302
+ name: display.name,
303
+ kind: type
304
+ },
305
+ id: entryID++,
306
+ dependencies: {
307
+ required: Array.from(dependencies.required, (id) => outer.get(id) ?? -1),
308
+ optional: Array.from(dependencies.optional, (id) => outer.get(id)).filter((id) => id !== void 0)
309
+ }
310
+ },
311
+ wrote
312
+ };
313
+ };
314
+ const toCon = (current, outer) => {
315
+ const wrote = new Scope();
316
+ const visit = visitorOn(outer, [wrote]);
317
+ const children = current.children.map(visit);
318
+ return {
319
+ node: {
320
+ type: "con",
321
+ meta: { name: current.meta?.name },
322
+ children
323
+ },
324
+ wrote
325
+ };
326
+ };
327
+ const toSeq = (current, outer) => {
328
+ const wrote = new Scope(), local = new Scope(outer);
329
+ const visit = visitorOn(local, [local, wrote]);
330
+ const children = current.children.map(visit);
331
+ return {
332
+ node: {
333
+ type: "seq",
334
+ meta: { name: current.meta?.name },
335
+ children
336
+ },
337
+ wrote
338
+ };
339
+ };
340
+ /** using `local`, traverse `node` and update `into` scopes */
341
+ const visitorOn = (local, into) => (node) => {
342
+ const step = traverse(node, local);
343
+ for (const target of into) step.wrote.forEach((id, sym) => target.set(sym, id));
344
+ return step.node;
345
+ };
346
+ const traverse = (current, outer) => {
347
+ switch (current.type) {
348
+ case "run": return toRun(current, outer);
349
+ case "con": return toCon(current, outer);
350
+ case "seq": return toSeq(current, outer);
351
+ }
352
+ };
353
+ return traverse(root, new Scope()).node;
354
+ };
355
+ // src/compose/guard.ts
356
+ const UNKNOWN_NAME = "<unknown>";
357
+ const TypeMap = {
358
+ task: "Task",
359
+ wire: "Wire"
360
+ };
361
+ const metaOf = (node, key) => "meta" in node && node.meta?.[key] ? node.meta[key] : void 0;
362
+ const stackToName = (stack) => stack.map(({ node, index }) => {
363
+ const name = metaOf(node, "name");
364
+ if (index !== void 0) return name ? `#${index + 1} (${name})` : `#${index + 1}`;
365
+ else return name ?? "root";
366
+ }).join(" > ");
367
+ const createNotify = (handler) => ({
368
+ duplicate: ({ type, name, stack }) => {
369
+ const message = `A duplicate ${TypeMap[type]} found with name ${TypeMap[type]}[${name}] in step ${stackToName(stack)}.`;
370
+ handler.error(message);
371
+ },
372
+ notSatisfied: ({ type, name, stack, missing: set }) => {
373
+ const list = Array.from(set, (id) => id.description ?? UNKNOWN_NAME).join(", ");
374
+ const message = `Unsatisfied dependencies found for ${TypeMap[type]} with name ${TypeMap[type]}[${name}] in step ${stackToName(stack)}: missing ${list}.`;
375
+ handler.error(message);
376
+ },
377
+ unused: ({ type, name, stack, id }) => {
378
+ const target = `${TypeMap[type]}[${name}] for ${id.description ?? UNKNOWN_NAME}`;
379
+ const message = `Unused ${TypeMap[type]} found with name ${target} in step ${stackToName(stack)}.`;
380
+ handler.warn(message);
381
+ }
382
+ });
383
+ const createGuard = ({ handler }) => {
384
+ const notify = createNotify(handler);
385
+ const analyzer = createAnalyzer();
386
+ const duplicate = (root) => {
387
+ const seen = /* @__PURE__ */ new Set();
388
+ const traverse = (stack) => {
389
+ const { node: current } = stack.at(-1);
390
+ if (current.type === "con" || current.type === "seq") return current.children.forEach((node, index) => traverse([...stack, {
391
+ node,
392
+ index
393
+ }]));
394
+ if (current.type === "run") {
395
+ const { type, display, writes } = analyzer.get(current.value);
396
+ if (writes.some((write) => seen.has(write))) notify.duplicate({
397
+ type,
398
+ name: display.name,
399
+ stack
400
+ });
401
+ writes.forEach((w) => seen.add(w));
402
+ }
403
+ };
404
+ traverse([{ node: root }]);
405
+ };
406
+ const unused = (root) => {
407
+ const candidates = /* @__PURE__ */ new Map();
408
+ const traverse = (stack) => {
409
+ const { node: current } = stack.at(-1);
410
+ if (current.type === "con" || current.type === "seq") return current.children.forEach((node, index) => traverse([...stack, {
411
+ node,
412
+ index
413
+ }]));
414
+ if (current.type === "run") {
415
+ const { type, display, writes, dependencies } = analyzer.get(current.value);
416
+ if (type === "wire") writes.forEach((id) => candidates.set(id, {
417
+ id,
418
+ type,
419
+ name: display.name,
420
+ stack
421
+ }));
422
+ dependencies.required.forEach((id) => candidates.delete(id));
423
+ dependencies.optional.forEach((id) => candidates.delete(id));
424
+ }
425
+ };
426
+ traverse([{ node: root }]);
427
+ for (const context of candidates.values()) notify.unused(context);
428
+ };
429
+ const unsatisfied = (root) => {
430
+ const traverse = (stack, available) => {
431
+ const { node: current } = stack.at(-1);
432
+ switch (current.type) {
433
+ case "run":
434
+ const { type, display, writes, dependencies } = analyzer.get(current.value);
435
+ const missing = /* @__PURE__ */ new Set();
436
+ for (const id of dependencies.required) if (!available.has(id)) missing.add(id);
437
+ if (missing.size > 0) notify.notSatisfied({
438
+ type,
439
+ name: display.name,
440
+ stack,
441
+ missing
442
+ });
443
+ return new Set(writes);
444
+ case "con": {
445
+ const wrote = /* @__PURE__ */ new Set();
446
+ for (const [index, node] of current.children.entries()) traverse([...stack, {
447
+ node,
448
+ index
449
+ }], available).forEach((item) => wrote.add(item));
450
+ return wrote;
451
+ }
452
+ case "seq": {
453
+ const wrote = /* @__PURE__ */ new Set(), local = new Set(available);
454
+ for (const [index, node] of current.children.entries()) traverse([...stack, {
455
+ node,
456
+ index
457
+ }], local).forEach((item) => (wrote.add(item), local.add(item)));
458
+ return wrote;
459
+ }
460
+ }
461
+ };
462
+ traverse([{ node: root }], /* @__PURE__ */ new Set());
463
+ };
464
+ return (root) => (duplicate(root), unsatisfied(root), unused(root));
465
+ };
466
+ // src/compose/observer.ts
467
+ const toEvent = (node, scope, phase) => {
468
+ switch (node.type) {
469
+ case "seq": return {
470
+ node: "seq",
471
+ scope,
472
+ phase,
473
+ meta: node.meta
474
+ };
475
+ case "con": return {
476
+ node: "con",
477
+ scope,
478
+ phase,
479
+ meta: node.meta
480
+ };
481
+ case "run": return {
482
+ node: "run",
483
+ scope,
484
+ phase,
485
+ runnable: node.value
486
+ };
487
+ }
488
+ };
489
+ const notify = (observe, event, path) => void Promise.resolve().then(() => observe(event, path)).catch((error) => console.error(LIBRARY_NAME, error));
490
+ const createObserver = (scope) => (stack, phase) => {
491
+ const event = toEvent(stack.at(-1), scope, phase);
492
+ const path = [];
493
+ for (const node of [...stack].reverse()) {
494
+ const meta = "meta" in node ? node.meta : void 0;
495
+ if (meta) path.push(meta);
496
+ if (meta?.observe) notify(meta.observe, event, [...path]);
497
+ }
498
+ };
499
+ // src/compose/scope.ts
500
+ const createScope = (computer) => {
501
+ return { get: (spot) => computer.computeSafe(spot) };
502
+ };
503
+ // src/compose/runner.ts
504
+ const execute = (ctx, runnable) => Promise.resolve().then(() => ctx.computer.compute(runnable[Context$])).then((value) => runnable[Execute$](value)).then((value) => {
505
+ for (const key of Object.getOwnPropertySymbols(runnable[Dispatch$])) ctx.registry.set(key, runnable[Dispatch$][key](value));
506
+ return value;
507
+ });
508
+ const traverse = async (ctx, stack) => {
509
+ const current = stack.at(-1);
510
+ ctx.dispatch(stack, "enter");
511
+ switch (current.type) {
512
+ case "seq":
513
+ for (const child of current.children) await traverse(ctx, [...stack, child]);
514
+ break;
515
+ case "con":
516
+ await Promise.all(current.children.map((child) => traverse(ctx, [...stack, child])));
517
+ break;
518
+ case "run": await execute(ctx, current.value);
519
+ }
520
+ ctx.dispatch(stack, "exit");
521
+ };
522
+ const run = async (node) => {
523
+ const registry = /* @__PURE__ */ new Map();
524
+ const computer = createComputer(registry);
525
+ const scope = createScope(computer);
526
+ const ctx = {
527
+ computer,
528
+ registry,
529
+ dispatch: createObserver(scope)
530
+ };
531
+ await traverse(ctx, [node]);
532
+ return scope;
533
+ };
534
+ // src/compose/compose.ts
535
+ const Node$ = Symbol("$node");
536
+ const normalize = (arg) => {
537
+ if (Node$ in arg) return arg[Node$];
538
+ else if (Execute$ in arg) return {
539
+ type: "run",
540
+ value: arg
541
+ };
542
+ else throw new Error(`${LIBRARY_NAME} Invalid argument passed to step.`);
543
+ };
544
+ const raiseOnGuard = (message) => {
545
+ throw new Error(message);
546
+ };
547
+ const builder = (node) => {
548
+ return {
549
+ [Node$]: node,
550
+ meta: (meta) => builder({
551
+ ...node,
552
+ meta: {
553
+ ...node.meta,
554
+ ...meta
555
+ }
556
+ }),
557
+ step: (arg) => {
558
+ if (Array.isArray(arg)) return builder({
559
+ ...node,
560
+ children: [...node.children, {
561
+ type: "con",
562
+ children: arg.map(normalize)
563
+ }]
564
+ });
565
+ else return builder({
566
+ ...node,
567
+ children: [...node.children, normalize(arg)]
568
+ });
569
+ },
570
+ run: () => {
571
+ return createGuard({ handler: {
572
+ warn: (message) => console.warn(LIBRARY_NAME, message),
573
+ error: raiseOnGuard
574
+ } })(node), run(node);
575
+ },
576
+ guard: () => {
577
+ return createGuard({ handler: {
578
+ warn: raiseOnGuard,
579
+ error: raiseOnGuard
580
+ } })(node);
581
+ },
582
+ graph: () => graph(node)
583
+ };
584
+ };
585
+ const compose = () => {
586
+ return builder({
587
+ type: "seq",
588
+ children: []
589
+ });
590
+ };
591
+ exports.compose = compose;
592
+ exports.createTask = createTask;
593
+ exports.createWire = createWire;
594
+ exports.is = is;
595
+ exports.literal = literal;
596
+ exports.optional = optional;
597
+ exports.shape = shape;
598
+ exports.tag = tag;