@app-compose/core 3.0.0-beta.7

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,98 @@
1
+ # App Compose
2
+
3
+ Lightweight IoC for the front-end. Compose apps you can control and trust.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/%40app-compose%2Fcore?color=orange)](https://www.npmjs.com/package/@app-compose/core)
6
+ ![npm license](https://img.shields.io/npm/l/%40app-compose%2Fcore?color=blue)
7
+ ![bundle size](https://deno.bundlejs.com/badge?q=@app-compose/core&treeshake=[*])
8
+ ![zero dependencies](https://img.shields.io/badge/dependencies-0-blue)
9
+ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/grlt-hub/app-compose)
10
+ [![npm provenance](https://img.shields.io/badge/provenance-yes-brightgreen?logo=npm)](https://www.npmjs.com/@app-compose/core)
11
+ [![llms.txt](https://img.shields.io/badge/llms.txt-ready-blue)](https://app-compose.dev/llms.txt)
12
+
13
+ [Learn](https://app-compose.dev/learn/quick-start/) | [Guides](https://app-compose.dev/guides/) | [Reference](https://app-compose.dev/reference/)
14
+
15
+ ## What it's for
16
+
17
+ Features, services, and modules often know about each other directly. That makes them hard to test, reuse, and
18
+ maintain.
19
+
20
+ With App-Compose, each part declares what it needs, and you supply it — so you stay in control as your app
21
+ grows.
22
+
23
+ ## What you get
24
+
25
+ - **Simplicity** — lightweight, no containers/providers/decorators, zero dependencies. Framework-agnostic.
26
+ - **Clarity** — no magic, no globals; context flows through typed wiring.
27
+ - **Reusability** — same code, different context per compose.
28
+ - **Testability** — missing context, duplicates, unused wires fail in CI.
29
+ - **Observability** — your app as plain JSON; hooks for start, complete, fail.
30
+
31
+ ## Adopt it gradually
32
+
33
+ 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.
34
+
35
+ ## See it run
36
+
37
+ A minimal example built on the three key pieces: Task, Tag, and Wire (how they connect).
38
+ Two features share data without knowing about each other.
39
+
40
+ ```ts
41
+ import { createTask, createWire, compose, tag } from "@app-compose/core"
42
+
43
+ // where the name to greet will live
44
+ const whoToGreet = tag<string>("whoToGreet")
45
+
46
+ const greeting = createTask({
47
+ name: "greeting",
48
+ run: {
49
+ // greeting reads from it
50
+ context: whoToGreet.value,
51
+ fn: (name) => console.log(`Hello, ${name}!`),
52
+ },
53
+ })
54
+
55
+ const user = createTask({
56
+ name: "user",
57
+ run: { fn: () => ({ name: "World" }) },
58
+ })
59
+
60
+ compose()
61
+ .step(user)
62
+ // filled by the user task
63
+ .step(createWire({ from: user.result.name, to: whoToGreet }))
64
+ .step(greeting)
65
+ .run()
66
+ ```
67
+
68
+ ## AI tools
69
+
70
+ App-Compose publishes LLM-friendly docs and is available on [DeepWiki](https://deepwiki.com/grlt-hub/app-compose).
71
+
72
+ ### Cursor
73
+
74
+ 1. Open chat and type `@docs`
75
+ 2. Click **Add new doc**
76
+ 3. Paste the URL and confirm:
77
+
78
+ ```
79
+ https://app-compose.dev/llms-full.txt
80
+ ```
81
+
82
+ ### Claude / ChatGPT / Copilot
83
+
84
+ Paste this URL into the chat — most assistants accept URLs as context:
85
+
86
+ ```
87
+ https://app-compose.dev/llms-full.txt
88
+ ```
89
+
90
+ Use [`llms-small.txt`](https://app-compose.dev/llms-small.txt) for models with a smaller context window (e.g. GPT-3.5, free-tier plans).
91
+
92
+ ### DeepWiki
93
+
94
+ Open [deepwiki.com/grlt-hub/app-compose](https://deepwiki.com/grlt-hub/app-compose) and ask anything about the codebase.
95
+
96
+ ## Ready to try it?
97
+
98
+ [Quick start](https://app-compose.dev/learn/quick-start/) — a step-by-step guide to the core concepts. Or browse the full [docs](https://app-compose.dev) and [guides](https://app-compose.dev/guides/).
package/dist/index.cjs ADDED
@@ -0,0 +1,587 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/runnable/definition.ts
3
+ const Context$ = Symbol("$context");
4
+ const Execute$ = Symbol("$execute");
5
+ const Dispatch$ = Symbol("$dispatch");
6
+ //#endregion
7
+ //#region src/computable/definition.ts
8
+ const Spot$ = Symbol("$spot");
9
+ const Read$ = Symbol("$read");
10
+ const Build$ = Symbol("$build");
11
+ const Literal$ = Symbol("$literal");
12
+ const Compute$ = Symbol("$compute");
13
+ const Missing$ = Symbol("$missing");
14
+ const Optional$ = Symbol("$optional");
15
+ //#endregion
16
+ //#region src/computable/build.ts
17
+ /**
18
+ * Creates a build context from a shape
19
+ *
20
+ * @internal
21
+ */
22
+ const build = (context) => {
23
+ return {
24
+ [Spot$]: true,
25
+ [Build$]: context,
26
+ [Compute$]: [],
27
+ [Optional$]: false
28
+ };
29
+ };
30
+ //#endregion
31
+ //#region src/shared.ts
32
+ const LIBRARY_NAME = "[app-compose]";
33
+ const isObject = (x) => Object.prototype.toString.call(x) === "[object Object]";
34
+ const identity = (x) => x;
35
+ const T = () => true;
36
+ //#endregion
37
+ //#region src/computable/computer.ts
38
+ const createComputer = (registry) => {
39
+ const context = (value) => {
40
+ if (isObject(value)) if (Spot$ in value) return compute(value);
41
+ else {
42
+ let out = {};
43
+ for (const key of Object.keys(value)) if ((out[key] = context(value[key])) === Missing$) return Missing$;
44
+ return out;
45
+ }
46
+ else if (Array.isArray(value)) {
47
+ const out = Array.from({ length: value.length });
48
+ for (let i = 0; i < value.length; i++) if ((out[i] = context(value[i])) === Missing$) return Missing$;
49
+ return out;
50
+ } else throw new Error(`${LIBRARY_NAME} Literal value found in context: ${String(value)}.`);
51
+ };
52
+ /**
53
+ * `compute` - resolve a `Spot` to its final value.
54
+ *
55
+ * Resolves the spot's underlying value (`Build$`, `Literal$`, or `Read$`),
56
+ * then applies all `Compute$` transformations in order.
57
+ *
58
+ * `Missing$` flow is three-step `read -> compute -> optional`
59
+ *
60
+ * 1. Read `source` value (either literal, built, or from registry) as-is
61
+ * 2. Map the `source` value through the `Compute$` pipeline, preserving `Missing$` and delegating to internal-land
62
+ * 3. Guard `Missing$` according to `Optional$`, coercing to `undefined` if optional, or propagating as-is if not
63
+ *
64
+ * @param spot The `Spot` to evaluate
65
+ * @returns The resolved value, or `Missing$` when non-optional spot resolution fails
66
+ */
67
+ const compute = (spot) => {
68
+ let resolved;
69
+ if (Build$ in spot) resolved = context(spot[Build$]);
70
+ else if (Literal$ in spot) resolved = spot[Literal$];
71
+ else if (Read$ in spot) resolved = registry.has(spot[Read$]) ? registry.get(spot[Read$]) : Missing$;
72
+ else throw new Error(`${LIBRARY_NAME} Invalid Unit.`);
73
+ for (const step of spot[Compute$]) resolved = step(resolved);
74
+ if (resolved === Missing$ && spot[Optional$]) return void 0;
75
+ else return resolved;
76
+ };
77
+ const computeSafe = (spot) => {
78
+ const result = compute(spot);
79
+ return result === Missing$ ? void 0 : result;
80
+ };
81
+ return {
82
+ compute,
83
+ computeSafe
84
+ };
85
+ };
86
+ //#endregion
87
+ //#region src/computable/literal.ts
88
+ const literal = (value) => {
89
+ return {
90
+ [Spot$]: true,
91
+ [Literal$]: value,
92
+ [Compute$]: [],
93
+ [Optional$]: false
94
+ };
95
+ };
96
+ //#endregion
97
+ //#region src/computable/lens.ts
98
+ const Self$ = Symbol();
99
+ const raise = () => {
100
+ throw new Error(`${LIBRARY_NAME} Modifying a Reference is not allowed.`);
101
+ };
102
+ const reader = (property) => (value) => value === Missing$ ? Missing$ : value?.[property];
103
+ const get = (target, property, recv) => typeof property === "string" ? proxy({
104
+ ...target,
105
+ [Compute$]: target[Compute$].concat(reader(property))
106
+ }) : property === Self$ ? target : Reflect.get(target, property, recv);
107
+ const set = () => raise();
108
+ const proxy = (ref) => new Proxy(ref, {
109
+ get,
110
+ set
111
+ });
112
+ proxy.self = (lensable) => lensable[Self$] ?? lensable;
113
+ //#endregion
114
+ //#region src/computable/optional.ts
115
+ /**
116
+ * Mark a `Spot` as optional.
117
+ */
118
+ const optional = (spot) => {
119
+ return {
120
+ ...proxy.self(spot),
121
+ [Optional$]: true
122
+ };
123
+ };
124
+ //#endregion
125
+ //#region src/computable/reference.ts
126
+ const reference = (id) => {
127
+ return {
128
+ [Spot$]: true,
129
+ [Read$]: id,
130
+ [Compute$]: [],
131
+ [Optional$]: false
132
+ };
133
+ };
134
+ reference.lensed = (id) => {
135
+ return proxy({
136
+ [Spot$]: true,
137
+ [Read$]: id,
138
+ [Compute$]: [],
139
+ [Optional$]: false
140
+ });
141
+ };
142
+ //#endregion
143
+ //#region src/computable/shape.ts
144
+ const safe = (fn) => (value) => {
145
+ try {
146
+ return value === Missing$ ? Missing$ : fn(value);
147
+ } catch {
148
+ return Missing$;
149
+ }
150
+ };
151
+ function shape(ctxOrSpot, fn) {
152
+ const spot = build(ctxOrSpot);
153
+ if (fn) spot[Compute$].push(safe(fn));
154
+ return spot;
155
+ }
156
+ //#endregion
157
+ //#region src/runnable/task.ts
158
+ const dispatch = {
159
+ result: (result) => result.status === "done" ? result.value : Missing$,
160
+ status: (result) => result.status,
161
+ error: (result) => result.status === "fail" ? result.error : Missing$
162
+ };
163
+ const createTask = (config) => {
164
+ const id = {
165
+ result: Symbol(`Task[${config.name}]::result`),
166
+ status: Symbol(`Task[${config.name}]::status`),
167
+ error: Symbol(`Task[${config.name}]::error`)
168
+ };
169
+ const context = {
170
+ run: config.run.context ?? literal(void 0),
171
+ enabled: config.enabled?.context ?? literal(void 0)
172
+ };
173
+ return {
174
+ name: config.name,
175
+ kind: "task",
176
+ result: reference.lensed(id.result),
177
+ status: reference(id.status),
178
+ error: reference(id.error),
179
+ [Context$]: build(context),
180
+ [Execute$]: async (built) => {
181
+ const ctx = built;
182
+ if (ctx === Missing$) return { status: "skip" };
183
+ try {
184
+ if (!await (config.enabled?.fn ?? T)(ctx.enabled)) return { status: "skip" };
185
+ } catch (error) {
186
+ return {
187
+ status: "fail",
188
+ error
189
+ };
190
+ }
191
+ try {
192
+ return {
193
+ status: "done",
194
+ value: await config.run.fn(ctx.run)
195
+ };
196
+ } catch (error) {
197
+ return {
198
+ status: "fail",
199
+ error
200
+ };
201
+ }
202
+ },
203
+ [Dispatch$]: {
204
+ [id.result]: dispatch.result,
205
+ [id.status]: dispatch.status,
206
+ [id.error]: dispatch.error
207
+ }
208
+ };
209
+ };
210
+ //#endregion
211
+ //#region src/is.ts
212
+ const is = {
213
+ tag: (x) => isObject(x) && Tag$ in x,
214
+ runnable: (x) => isObject(x) && Execute$ in x,
215
+ task: (x) => is.runnable(x) && x.kind === "task",
216
+ wire: (x) => is.runnable(x) && x.kind === "wire"
217
+ };
218
+ //#endregion
219
+ //#region src/runnable/wire.ts
220
+ const Tag$ = Symbol("$tag");
221
+ const tag = (name) => {
222
+ const id = Symbol(`Tag[${name}]`);
223
+ return {
224
+ [Tag$]: id,
225
+ name,
226
+ value: reference.lensed(id)
227
+ };
228
+ };
229
+ const pluck = (path) => (value) => path.reduce((acc, key) => acc?.[key], value);
230
+ function* walk(shape, path = []) {
231
+ if (is.tag(shape)) yield {
232
+ tag: shape,
233
+ fn: pluck(path)
234
+ };
235
+ else if (Array.isArray(shape)) for (let index = 0; index < shape.length; index++) yield* walk(shape[index], [...path, index]);
236
+ else if (isObject(shape)) for (const key of Object.keys(shape)) yield* walk(shape[key], [...path, key]);
237
+ else throw new Error(`${LIBRARY_NAME} Invalid shape ${String(shape)} provided to Wire at path "${path.join(".")}".`);
238
+ }
239
+ const createWire = (config) => {
240
+ const tags = /* @__PURE__ */ new Set();
241
+ const dispatch = {};
242
+ 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.`);
243
+ else tags.add(entry.tag), dispatch[entry.tag[Tag$]] = entry.fn;
244
+ return {
245
+ name: Array.from(tags).map((tag) => tag.name).join(" + "),
246
+ kind: "wire",
247
+ [Context$]: build(config.from),
248
+ [Execute$]: identity,
249
+ [Dispatch$]: dispatch
250
+ };
251
+ };
252
+ //#endregion
253
+ //#region src/compose/resolver.ts
254
+ function* scanShape(shape) {
255
+ if (isObject(shape)) if (Spot$ in shape) yield* scanSpot(shape);
256
+ else for (const key of Object.keys(shape)) yield* scanShape(shape[key]);
257
+ else if (Array.isArray(shape)) for (const item of shape) yield* scanShape(item);
258
+ else throw new Error(`${LIBRARY_NAME} Literal value found in context: ${String(shape)}.`);
259
+ }
260
+ function* scanSpot(spot) {
261
+ if (Literal$ in spot) return;
262
+ else if (Read$ in spot) return yield {
263
+ id: spot[Read$],
264
+ optional: spot[Optional$]
265
+ };
266
+ else if (Build$ in spot) for (const entry of scanShape(spot[Build$])) yield {
267
+ id: entry.id,
268
+ optional: entry.optional || spot[Optional$]
269
+ };
270
+ else throw new Error(`${LIBRARY_NAME} Invalid Unit.`);
271
+ }
272
+ function resolve(spot) {
273
+ const required = /* @__PURE__ */ new Set();
274
+ const optional = /* @__PURE__ */ new Set();
275
+ for (const entry of scanSpot(spot)) if (entry.optional) optional.add(entry.id);
276
+ else required.add(entry.id);
277
+ return {
278
+ required,
279
+ optional
280
+ };
281
+ }
282
+ //#endregion
283
+ //#region src/compose/analyze.ts
284
+ const analyze = (runnable) => {
285
+ const internal = runnable;
286
+ const writes = Object.getOwnPropertySymbols(internal[Dispatch$]);
287
+ const dependencies = resolve(internal[Context$]);
288
+ return {
289
+ type: internal.kind,
290
+ display: { name: internal.name },
291
+ writes,
292
+ dependencies
293
+ };
294
+ };
295
+ const createAnalyzer = () => {
296
+ const cache = /* @__PURE__ */ new WeakMap();
297
+ const get = (runnable) => {
298
+ const analysis = cache.get(runnable) ?? analyze(runnable);
299
+ return cache.set(runnable, analysis), analysis;
300
+ };
301
+ return { get };
302
+ };
303
+ //#endregion
304
+ //#region src/compose/graph.ts
305
+ const graph = (root) => {
306
+ let entryID = 0;
307
+ const symbolToID = /* @__PURE__ */ new Map();
308
+ const analyzer = createAnalyzer();
309
+ const toEntry = (runnable) => {
310
+ const { type, display, writes, dependencies } = analyzer.get(runnable);
311
+ writes.forEach((x) => symbolToID.set(x, entryID));
312
+ return {
313
+ type: "run",
314
+ meta: {
315
+ name: display.name,
316
+ kind: type
317
+ },
318
+ id: entryID++,
319
+ dependencies: {
320
+ required: Array.from(dependencies.required, (x) => symbolToID.get(x) ?? -1),
321
+ optional: Array.from(dependencies.optional, (x) => symbolToID.get(x)).filter((x) => x !== void 0)
322
+ }
323
+ };
324
+ };
325
+ const traverse = (node) => {
326
+ switch (node.type) {
327
+ case "con":
328
+ case "seq": return {
329
+ type: node.type,
330
+ meta: { name: node.meta?.name },
331
+ children: node.children.map(traverse)
332
+ };
333
+ case "run": return toEntry(node.value);
334
+ }
335
+ };
336
+ return traverse(root);
337
+ };
338
+ //#endregion
339
+ //#region src/compose/guard.ts
340
+ const UNKNOWN_NAME = "<unknown>";
341
+ const TypeMap = {
342
+ task: "Task",
343
+ wire: "Wire"
344
+ };
345
+ const metaOf = (node, key) => "meta" in node && node.meta?.[key] ? node.meta[key] : void 0;
346
+ const stackToName = (stack) => stack.map(({ node, index }) => {
347
+ const name = metaOf(node, "name");
348
+ if (index !== void 0) return name ? `#${index + 1} (${name})` : `#${index + 1}`;
349
+ else return name ?? "root";
350
+ }).join(" > ");
351
+ const createNotify = (handler) => ({
352
+ duplicate: ({ type, name, stack }) => {
353
+ const message = `A duplicate ${TypeMap[type]} found with name ${TypeMap[type]}[${name}] in step ${stackToName(stack)}.`;
354
+ handler.error(message);
355
+ },
356
+ notSatisfied: ({ type, name, stack, missing: set }) => {
357
+ const list = Array.from(set, (id) => id.description ?? UNKNOWN_NAME).join(", ");
358
+ const message = `Unsatisfied dependencies found for ${TypeMap[type]} with name ${TypeMap[type]}[${name}] in step ${stackToName(stack)}: missing ${list}.`;
359
+ handler.error(message);
360
+ },
361
+ unused: ({ type, name, stack, id }) => {
362
+ const target = `${TypeMap[type]}[${name}] for ${id.description ?? UNKNOWN_NAME}`;
363
+ const message = `Unused ${TypeMap[type]} found with name ${target} in step ${stackToName(stack)}.`;
364
+ handler.warn(message);
365
+ }
366
+ });
367
+ const createGuard = ({ handler }) => {
368
+ const notify = createNotify(handler);
369
+ const analyzer = createAnalyzer();
370
+ const duplicate = (root) => {
371
+ const seen = /* @__PURE__ */ new Set();
372
+ const traverse = (stack) => {
373
+ const { node: current } = stack.at(-1);
374
+ if (current.type === "con" || current.type === "seq") return current.children.forEach((node, index) => traverse([...stack, {
375
+ node,
376
+ index
377
+ }]));
378
+ if (current.type === "run") {
379
+ const { type, display, writes } = analyzer.get(current.value);
380
+ if (writes.some((write) => seen.has(write))) notify.duplicate({
381
+ type,
382
+ name: display.name,
383
+ stack
384
+ });
385
+ writes.forEach((w) => seen.add(w));
386
+ }
387
+ };
388
+ traverse([{ node: root }]);
389
+ };
390
+ const unused = (root) => {
391
+ const candidates = /* @__PURE__ */ new Map();
392
+ const traverse = (stack) => {
393
+ const { node: current } = stack.at(-1);
394
+ if (current.type === "con" || current.type === "seq") return current.children.forEach((node, index) => traverse([...stack, {
395
+ node,
396
+ index
397
+ }]));
398
+ if (current.type === "run") {
399
+ const { type, display, writes, dependencies } = analyzer.get(current.value);
400
+ if (type === "wire") writes.forEach((id) => candidates.set(id, {
401
+ id,
402
+ type,
403
+ name: display.name,
404
+ stack
405
+ }));
406
+ dependencies.required.forEach((id) => candidates.delete(id));
407
+ dependencies.optional.forEach((id) => candidates.delete(id));
408
+ }
409
+ };
410
+ traverse([{ node: root }]);
411
+ for (const context of candidates.values()) notify.unused(context);
412
+ };
413
+ const unsatisfied = (root) => {
414
+ const traverse = (stack, available) => {
415
+ const { node: current } = stack.at(-1);
416
+ switch (current.type) {
417
+ case "run":
418
+ const { type, display, writes, dependencies } = analyzer.get(current.value);
419
+ const missing = /* @__PURE__ */ new Set();
420
+ for (const id of dependencies.required) if (!available.has(id)) missing.add(id);
421
+ if (missing.size > 0) notify.notSatisfied({
422
+ type,
423
+ name: display.name,
424
+ stack,
425
+ missing
426
+ });
427
+ return new Set(writes);
428
+ case "con": {
429
+ const wrote = /* @__PURE__ */ new Set();
430
+ for (const [index, node] of current.children.entries()) traverse([...stack, {
431
+ node,
432
+ index
433
+ }], available).forEach((item) => wrote.add(item));
434
+ return wrote;
435
+ }
436
+ case "seq": {
437
+ const wrote = /* @__PURE__ */ new Set(), local = new Set(available);
438
+ for (const [index, node] of current.children.entries()) traverse([...stack, {
439
+ node,
440
+ index
441
+ }], local).forEach((item) => (wrote.add(item), local.add(item)));
442
+ return wrote;
443
+ }
444
+ }
445
+ };
446
+ traverse([{ node: root }], /* @__PURE__ */ new Set());
447
+ };
448
+ return (root) => (duplicate(root), unsatisfied(root), unused(root));
449
+ };
450
+ //#endregion
451
+ //#region src/compose/observer.ts
452
+ const eventToUserland = { onTaskFail: (event) => {
453
+ const runnable = event.runnable;
454
+ const result = event.value;
455
+ if (runnable.kind === "task" && result.status === "fail") return {
456
+ task: runnable,
457
+ error: result.error
458
+ };
459
+ else return null;
460
+ } };
461
+ const observe = (event) => {
462
+ let userland;
463
+ const current = event.stack.at(-1);
464
+ switch (event.type) {
465
+ case "node:start":
466
+ if ("meta" in current) current.meta?.hooks?.onStart?.({ meta: current.meta });
467
+ break;
468
+ case "node:complete":
469
+ if ("meta" in current) current.meta?.hooks?.onComplete?.({ meta: current.meta });
470
+ break;
471
+ case "execute:complete":
472
+ if (userland = eventToUserland.onTaskFail(event)) {
473
+ for (const node of event.stack) if ("meta" in node) node.meta?.hooks?.onTaskFail?.(userland);
474
+ }
475
+ break;
476
+ }
477
+ };
478
+ //#endregion
479
+ //#region src/compose/runner.ts
480
+ const execute = (ctx, runnable) => Promise.resolve().then(() => ctx.computer.compute(runnable[Context$])).then((value) => runnable[Execute$](value)).then((value) => {
481
+ for (const key of Object.getOwnPropertySymbols(runnable[Dispatch$])) ctx.registry.set(key, runnable[Dispatch$][key](value));
482
+ return value;
483
+ });
484
+ const traverse = async (ctx, stack) => {
485
+ const current = stack.at(-1);
486
+ observe({
487
+ type: "node:start",
488
+ stack
489
+ });
490
+ switch (current.type) {
491
+ case "seq":
492
+ for (const child of current.children) await traverse(ctx, [...stack, child]);
493
+ break;
494
+ case "con":
495
+ await Promise.all(current.children.map((child) => traverse(ctx, [...stack, child])));
496
+ break;
497
+ case "run":
498
+ const runnable = current.value;
499
+ await execute(ctx, runnable).then((value) => observe({
500
+ type: "execute:complete",
501
+ stack,
502
+ runnable,
503
+ value
504
+ }));
505
+ break;
506
+ }
507
+ observe({
508
+ type: "node:complete",
509
+ stack
510
+ });
511
+ };
512
+ const run = async (node) => {
513
+ const registry = /* @__PURE__ */ new Map();
514
+ const computer = createComputer(registry);
515
+ await traverse({
516
+ computer,
517
+ registry
518
+ }, [node]);
519
+ return { get: (spot) => computer.computeSafe(spot) };
520
+ };
521
+ //#endregion
522
+ //#region src/compose/compose.ts
523
+ const Node$ = Symbol("$node");
524
+ const normalize = (arg) => {
525
+ if (Node$ in arg) return arg[Node$];
526
+ else if (Execute$ in arg) return {
527
+ type: "run",
528
+ value: arg
529
+ };
530
+ else throw new Error(`${LIBRARY_NAME} Invalid argument passed to step.`);
531
+ };
532
+ const raiseOnGuard = (message) => {
533
+ throw new Error(message);
534
+ };
535
+ const builder = (node) => {
536
+ return {
537
+ [Node$]: node,
538
+ meta: (meta) => builder({
539
+ ...node,
540
+ meta: {
541
+ ...node.meta,
542
+ ...meta
543
+ }
544
+ }),
545
+ step: (arg) => {
546
+ if (Array.isArray(arg)) return builder({
547
+ ...node,
548
+ children: [...node.children, {
549
+ type: "con",
550
+ children: arg.map(normalize)
551
+ }]
552
+ });
553
+ else return builder({
554
+ ...node,
555
+ children: [...node.children, normalize(arg)]
556
+ });
557
+ },
558
+ run: () => {
559
+ return createGuard({ handler: {
560
+ warn: console.warn.bind(console, LIBRARY_NAME),
561
+ error: raiseOnGuard
562
+ } })(node), run(node);
563
+ },
564
+ guard: () => {
565
+ return createGuard({ handler: {
566
+ warn: raiseOnGuard,
567
+ error: raiseOnGuard
568
+ } })(node);
569
+ },
570
+ graph: () => graph(node)
571
+ };
572
+ };
573
+ const compose = () => {
574
+ return builder({
575
+ type: "seq",
576
+ children: []
577
+ });
578
+ };
579
+ //#endregion
580
+ exports.compose = compose;
581
+ exports.createTask = createTask;
582
+ exports.createWire = createWire;
583
+ exports.is = is;
584
+ exports.literal = literal;
585
+ exports.optional = optional;
586
+ exports.shape = shape;
587
+ exports.tag = tag;