@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/dist/index.js ADDED
@@ -0,0 +1,592 @@
1
+ // src/runnable/definition.ts
2
+ const Context$ = Symbol("$context");
3
+ const Execute$ = Symbol("$execute");
4
+ const Dispatch$ = Symbol("$dispatch");
5
+ // src/computable/definition.ts
6
+ const Spot$ = Symbol("$spot");
7
+ const Read$ = Symbol("$read");
8
+ const Build$ = Symbol("$build");
9
+ const Literal$ = Symbol("$literal");
10
+ const Compute$ = Symbol("$compute");
11
+ const Missing$ = Symbol("$missing");
12
+ const Optional$ = Symbol("$optional");
13
+ // src/computable/build.ts
14
+ /**
15
+ * Creates a build context from a shape
16
+ *
17
+ * @internal
18
+ */
19
+ const build = (context) => {
20
+ return {
21
+ [Spot$]: true,
22
+ [Build$]: context,
23
+ [Compute$]: [],
24
+ [Optional$]: false
25
+ };
26
+ };
27
+ // src/shared.ts
28
+ const LIBRARY_NAME = "[app-compose]";
29
+ const isObject = (x) => Object.prototype.toString.call(x) === "[object Object]";
30
+ const identity = (x) => x;
31
+ const T = () => true;
32
+ // src/computable/computer.ts
33
+ const createComputer = (registry) => {
34
+ const context = (value) => {
35
+ if (isObject(value)) if (Spot$ in value) return compute(value);
36
+ else {
37
+ let out = {};
38
+ for (const key of Object.keys(value)) if ((out[key] = context(value[key])) === Missing$) return Missing$;
39
+ return out;
40
+ }
41
+ else if (Array.isArray(value)) {
42
+ const out = Array.from({ length: value.length });
43
+ for (let i = 0; i < value.length; i++) if ((out[i] = context(value[i])) === Missing$) return Missing$;
44
+ return out;
45
+ } else throw new Error(`${LIBRARY_NAME} Literal value found in context: ${String(value)}.`);
46
+ };
47
+ /**
48
+ * `compute` - resolve a `Spot` to its final value.
49
+ *
50
+ * Resolves the spot's underlying value (`Build$`, `Literal$`, or `Read$`),
51
+ * then applies all `Compute$` transformations in order.
52
+ *
53
+ * `Missing$` flow is three-step `read -> compute -> optional`
54
+ *
55
+ * 1. Read `source` value (either literal, built, or from registry) as-is
56
+ * 2. Map the `source` value through the `Compute$` pipeline, preserving `Missing$` and delegating to internal-land
57
+ * 3. Guard `Missing$` according to `Optional$`, coercing to `undefined` if optional, or propagating as-is if not
58
+ *
59
+ * @param spot The `Spot` to evaluate
60
+ * @returns The resolved value, or `Missing$` when non-optional spot resolution fails
61
+ */
62
+ const compute = (spot) => {
63
+ let resolved;
64
+ if (Build$ in spot) resolved = context(spot[Build$]);
65
+ else if (Literal$ in spot) resolved = spot[Literal$];
66
+ else if (Read$ in spot) resolved = registry.has(spot[Read$]) ? registry.get(spot[Read$]) : Missing$;
67
+ else throw new Error(`${LIBRARY_NAME} Invalid Unit.`);
68
+ for (const step of spot[Compute$]) resolved = step(resolved);
69
+ if (resolved === Missing$ && spot[Optional$]) return void 0;
70
+ else return resolved;
71
+ };
72
+ const computeSafe = (spot) => {
73
+ const result = compute(spot);
74
+ return result === Missing$ ? void 0 : result;
75
+ };
76
+ return {
77
+ compute,
78
+ computeSafe
79
+ };
80
+ };
81
+ // src/computable/literal.ts
82
+ const literal = (value) => {
83
+ return {
84
+ [Spot$]: true,
85
+ [Literal$]: value,
86
+ [Compute$]: [],
87
+ [Optional$]: false
88
+ };
89
+ };
90
+ // src/computable/lens.ts
91
+ const Self$ = Symbol();
92
+ const raise = () => {
93
+ throw new Error(`${LIBRARY_NAME} Modifying a Reference is not allowed.`);
94
+ };
95
+ const reader = (property) => (value) => value === Missing$ ? Missing$ : value?.[property];
96
+ const get = (target, property, recv) => typeof property === "string" ? proxy({
97
+ ...target,
98
+ [Compute$]: target[Compute$].concat(reader(property))
99
+ }) : property === Self$ ? target : Reflect.get(target, property, recv);
100
+ const set = () => raise();
101
+ const proxy = (ref) => new Proxy(ref, {
102
+ get,
103
+ set
104
+ });
105
+ proxy.self = (lensable) => lensable[Self$] ?? lensable;
106
+ // src/computable/optional.ts
107
+ /**
108
+ * Mark a `Spot` as optional.
109
+ */
110
+ const optional = (spot) => {
111
+ return {
112
+ ...proxy.self(spot),
113
+ [Optional$]: true
114
+ };
115
+ };
116
+ // src/computable/reference.ts
117
+ const reference = (id) => {
118
+ return {
119
+ [Spot$]: true,
120
+ [Read$]: id,
121
+ [Compute$]: [],
122
+ [Optional$]: false
123
+ };
124
+ };
125
+ reference.lensed = (id) => {
126
+ return proxy({
127
+ [Spot$]: true,
128
+ [Read$]: id,
129
+ [Compute$]: [],
130
+ [Optional$]: false
131
+ });
132
+ };
133
+ // src/computable/shape.ts
134
+ const safe = (fn) => (value) => {
135
+ try {
136
+ return value === Missing$ ? Missing$ : fn(value);
137
+ } catch {
138
+ return Missing$;
139
+ }
140
+ };
141
+ function shape(ctxOrSpot, fn) {
142
+ const spot = build(ctxOrSpot);
143
+ if (fn) spot[Compute$].push(safe(fn));
144
+ return spot;
145
+ }
146
+ // src/runnable/task.ts
147
+ const dispatch = {
148
+ result: (result) => result.status === "done" ? result.value : Missing$,
149
+ status: (result) => result.status,
150
+ error: (result) => result.status === "fail" ? result.error : Missing$
151
+ };
152
+ const createTask = (config) => {
153
+ const id = {
154
+ result: Symbol(`Task[${config.name}]::result`),
155
+ status: Symbol(`Task[${config.name}]::status`),
156
+ error: Symbol(`Task[${config.name}]::error`)
157
+ };
158
+ const context = {
159
+ run: config.run.context ?? literal(void 0),
160
+ enabled: config.enabled?.context ?? literal(void 0)
161
+ };
162
+ return {
163
+ name: config.name,
164
+ kind: "task",
165
+ result: reference.lensed(id.result),
166
+ status: reference(id.status),
167
+ error: reference(id.error),
168
+ [Context$]: build(context),
169
+ [Execute$]: async (built) => {
170
+ const ctx = built;
171
+ if (ctx === Missing$) return { status: "skip" };
172
+ try {
173
+ if (!await (config.enabled?.fn ?? T)(ctx.enabled)) return { status: "skip" };
174
+ } catch (error) {
175
+ return {
176
+ status: "fail",
177
+ error
178
+ };
179
+ }
180
+ try {
181
+ return {
182
+ status: "done",
183
+ value: await config.run.fn(ctx.run)
184
+ };
185
+ } catch (error) {
186
+ return {
187
+ status: "fail",
188
+ error
189
+ };
190
+ }
191
+ },
192
+ [Dispatch$]: {
193
+ [id.result]: dispatch.result,
194
+ [id.status]: dispatch.status,
195
+ [id.error]: dispatch.error
196
+ }
197
+ };
198
+ };
199
+ // src/is.ts
200
+ const is = {
201
+ spot: (x) => isObject(x) && Spot$ in x,
202
+ tag: (x) => isObject(x) && Tag$ in x,
203
+ runnable: (x) => isObject(x) && Execute$ in x,
204
+ task: (x) => is.runnable(x) && x.kind === "task",
205
+ wire: (x) => is.runnable(x) && x.kind === "wire"
206
+ };
207
+ // src/runnable/wire.ts
208
+ const Tag$ = Symbol("$tag");
209
+ const tag = (name) => {
210
+ const id = Symbol(`Tag[${name}]`);
211
+ return {
212
+ [Tag$]: id,
213
+ name,
214
+ value: reference.lensed(id)
215
+ };
216
+ };
217
+ const pluck = (path) => (value) => path.reduce((acc, key) => acc?.[key], value);
218
+ function* walk(shape, path = []) {
219
+ if (is.tag(shape)) yield {
220
+ tag: shape,
221
+ fn: pluck(path)
222
+ };
223
+ else if (Array.isArray(shape)) for (let index = 0; index < shape.length; index++) yield* walk(shape[index], [...path, index]);
224
+ else if (isObject(shape)) for (const key of Object.keys(shape)) yield* walk(shape[key], [...path, key]);
225
+ else throw new Error(`${LIBRARY_NAME} Invalid shape ${String(shape)} provided to Wire at path "${path.join(".")}".`);
226
+ }
227
+ const createWire = (config) => {
228
+ const tags = /* @__PURE__ */ new Set();
229
+ const dispatch = {};
230
+ 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.`);
231
+ else tags.add(entry.tag), dispatch[entry.tag[Tag$]] = entry.fn;
232
+ return {
233
+ name: Array.from(tags).map((tag) => tag.name).join(" + "),
234
+ kind: "wire",
235
+ [Context$]: build(config.from),
236
+ [Execute$]: identity,
237
+ [Dispatch$]: dispatch
238
+ };
239
+ };
240
+ // src/compose/resolver.ts
241
+ function* scanShape(shape) {
242
+ if (isObject(shape)) if (Spot$ in shape) yield* scanSpot(shape);
243
+ else for (const key of Object.keys(shape)) yield* scanShape(shape[key]);
244
+ else if (Array.isArray(shape)) for (const item of shape) yield* scanShape(item);
245
+ else throw new Error(`${LIBRARY_NAME} Literal value found in context: ${String(shape)}.`);
246
+ }
247
+ function* scanSpot(spot) {
248
+ if (Literal$ in spot) return;
249
+ else if (Read$ in spot) return yield {
250
+ id: spot[Read$],
251
+ optional: spot[Optional$]
252
+ };
253
+ else if (Build$ in spot) for (const entry of scanShape(spot[Build$])) yield {
254
+ id: entry.id,
255
+ optional: entry.optional || spot[Optional$]
256
+ };
257
+ else throw new Error(`${LIBRARY_NAME} Invalid Unit.`);
258
+ }
259
+ function resolve(spot) {
260
+ const required = /* @__PURE__ */ new Set();
261
+ const optional = /* @__PURE__ */ new Set();
262
+ for (const entry of scanSpot(spot)) if (entry.optional) optional.add(entry.id);
263
+ else required.add(entry.id);
264
+ return {
265
+ required,
266
+ optional
267
+ };
268
+ }
269
+ // src/compose/analyze.ts
270
+ const analyze = (runnable) => {
271
+ const internal = runnable;
272
+ const writes = Object.getOwnPropertySymbols(internal[Dispatch$]);
273
+ const dependencies = resolve(internal[Context$]);
274
+ return {
275
+ type: internal.kind,
276
+ display: { name: internal.name },
277
+ writes,
278
+ dependencies
279
+ };
280
+ };
281
+ const createAnalyzer = () => {
282
+ const cache = /* @__PURE__ */ new WeakMap();
283
+ const get = (runnable) => {
284
+ const analysis = cache.get(runnable) ?? analyze(runnable);
285
+ return cache.set(runnable, analysis), analysis;
286
+ };
287
+ return { get };
288
+ };
289
+ // src/compose/graph.ts
290
+ const Scope = Map;
291
+ const graph = (root) => {
292
+ let entryID = 0;
293
+ const analyzer = createAnalyzer();
294
+ const toRun = (current, outer) => {
295
+ const { type, display, writes, dependencies } = analyzer.get(current.value);
296
+ const wrote = writes.reduce((acc, sym) => acc.set(sym, entryID), new Scope());
297
+ return {
298
+ node: {
299
+ type: "run",
300
+ meta: {
301
+ name: display.name,
302
+ kind: type
303
+ },
304
+ id: entryID++,
305
+ dependencies: {
306
+ required: Array.from(dependencies.required, (id) => outer.get(id) ?? -1),
307
+ optional: Array.from(dependencies.optional, (id) => outer.get(id)).filter((id) => id !== void 0)
308
+ }
309
+ },
310
+ wrote
311
+ };
312
+ };
313
+ const toCon = (current, outer) => {
314
+ const wrote = new Scope();
315
+ const visit = visitorOn(outer, [wrote]);
316
+ const children = current.children.map(visit);
317
+ return {
318
+ node: {
319
+ type: "con",
320
+ meta: { name: current.meta?.name },
321
+ children
322
+ },
323
+ wrote
324
+ };
325
+ };
326
+ const toSeq = (current, outer) => {
327
+ const wrote = new Scope(), local = new Scope(outer);
328
+ const visit = visitorOn(local, [local, wrote]);
329
+ const children = current.children.map(visit);
330
+ return {
331
+ node: {
332
+ type: "seq",
333
+ meta: { name: current.meta?.name },
334
+ children
335
+ },
336
+ wrote
337
+ };
338
+ };
339
+ /** using `local`, traverse `node` and update `into` scopes */
340
+ const visitorOn = (local, into) => (node) => {
341
+ const step = traverse(node, local);
342
+ for (const target of into) step.wrote.forEach((id, sym) => target.set(sym, id));
343
+ return step.node;
344
+ };
345
+ const traverse = (current, outer) => {
346
+ switch (current.type) {
347
+ case "run": return toRun(current, outer);
348
+ case "con": return toCon(current, outer);
349
+ case "seq": return toSeq(current, outer);
350
+ }
351
+ };
352
+ return traverse(root, new Scope()).node;
353
+ };
354
+ // src/compose/guard.ts
355
+ const UNKNOWN_NAME = "<unknown>";
356
+ const TypeMap = {
357
+ task: "Task",
358
+ wire: "Wire"
359
+ };
360
+ const metaOf = (node, key) => "meta" in node && node.meta?.[key] ? node.meta[key] : void 0;
361
+ const stackToName = (stack) => stack.map(({ node, index }) => {
362
+ const name = metaOf(node, "name");
363
+ if (index !== void 0) return name ? `#${index + 1} (${name})` : `#${index + 1}`;
364
+ else return name ?? "root";
365
+ }).join(" > ");
366
+ const createNotify = (handler) => ({
367
+ duplicate: ({ type, name, stack }) => {
368
+ const message = `A duplicate ${TypeMap[type]} found with name ${TypeMap[type]}[${name}] in step ${stackToName(stack)}.`;
369
+ handler.error(message);
370
+ },
371
+ notSatisfied: ({ type, name, stack, missing: set }) => {
372
+ const list = Array.from(set, (id) => id.description ?? UNKNOWN_NAME).join(", ");
373
+ const message = `Unsatisfied dependencies found for ${TypeMap[type]} with name ${TypeMap[type]}[${name}] in step ${stackToName(stack)}: missing ${list}.`;
374
+ handler.error(message);
375
+ },
376
+ unused: ({ type, name, stack, id }) => {
377
+ const target = `${TypeMap[type]}[${name}] for ${id.description ?? UNKNOWN_NAME}`;
378
+ const message = `Unused ${TypeMap[type]} found with name ${target} in step ${stackToName(stack)}.`;
379
+ handler.warn(message);
380
+ }
381
+ });
382
+ const createGuard = ({ handler }) => {
383
+ const notify = createNotify(handler);
384
+ const analyzer = createAnalyzer();
385
+ const duplicate = (root) => {
386
+ const seen = /* @__PURE__ */ new Set();
387
+ const traverse = (stack) => {
388
+ const { node: current } = stack.at(-1);
389
+ if (current.type === "con" || current.type === "seq") return current.children.forEach((node, index) => traverse([...stack, {
390
+ node,
391
+ index
392
+ }]));
393
+ if (current.type === "run") {
394
+ const { type, display, writes } = analyzer.get(current.value);
395
+ if (writes.some((write) => seen.has(write))) notify.duplicate({
396
+ type,
397
+ name: display.name,
398
+ stack
399
+ });
400
+ writes.forEach((w) => seen.add(w));
401
+ }
402
+ };
403
+ traverse([{ node: root }]);
404
+ };
405
+ const unused = (root) => {
406
+ const candidates = /* @__PURE__ */ new Map();
407
+ const traverse = (stack) => {
408
+ const { node: current } = stack.at(-1);
409
+ if (current.type === "con" || current.type === "seq") return current.children.forEach((node, index) => traverse([...stack, {
410
+ node,
411
+ index
412
+ }]));
413
+ if (current.type === "run") {
414
+ const { type, display, writes, dependencies } = analyzer.get(current.value);
415
+ if (type === "wire") writes.forEach((id) => candidates.set(id, {
416
+ id,
417
+ type,
418
+ name: display.name,
419
+ stack
420
+ }));
421
+ dependencies.required.forEach((id) => candidates.delete(id));
422
+ dependencies.optional.forEach((id) => candidates.delete(id));
423
+ }
424
+ };
425
+ traverse([{ node: root }]);
426
+ for (const context of candidates.values()) notify.unused(context);
427
+ };
428
+ const unsatisfied = (root) => {
429
+ const traverse = (stack, available) => {
430
+ const { node: current } = stack.at(-1);
431
+ switch (current.type) {
432
+ case "run":
433
+ const { type, display, writes, dependencies } = analyzer.get(current.value);
434
+ const missing = /* @__PURE__ */ new Set();
435
+ for (const id of dependencies.required) if (!available.has(id)) missing.add(id);
436
+ if (missing.size > 0) notify.notSatisfied({
437
+ type,
438
+ name: display.name,
439
+ stack,
440
+ missing
441
+ });
442
+ return new Set(writes);
443
+ case "con": {
444
+ const wrote = /* @__PURE__ */ new Set();
445
+ for (const [index, node] of current.children.entries()) traverse([...stack, {
446
+ node,
447
+ index
448
+ }], available).forEach((item) => wrote.add(item));
449
+ return wrote;
450
+ }
451
+ case "seq": {
452
+ const wrote = /* @__PURE__ */ new Set(), local = new Set(available);
453
+ for (const [index, node] of current.children.entries()) traverse([...stack, {
454
+ node,
455
+ index
456
+ }], local).forEach((item) => (wrote.add(item), local.add(item)));
457
+ return wrote;
458
+ }
459
+ }
460
+ };
461
+ traverse([{ node: root }], /* @__PURE__ */ new Set());
462
+ };
463
+ return (root) => (duplicate(root), unsatisfied(root), unused(root));
464
+ };
465
+ // src/compose/observer.ts
466
+ const toEvent = (node, scope, phase) => {
467
+ switch (node.type) {
468
+ case "seq": return {
469
+ node: "seq",
470
+ scope,
471
+ phase,
472
+ meta: node.meta
473
+ };
474
+ case "con": return {
475
+ node: "con",
476
+ scope,
477
+ phase,
478
+ meta: node.meta
479
+ };
480
+ case "run": return {
481
+ node: "run",
482
+ scope,
483
+ phase,
484
+ runnable: node.value
485
+ };
486
+ }
487
+ };
488
+ const notify = (observe, event, path) => void Promise.resolve().then(() => observe(event, path)).catch((error) => console.error(LIBRARY_NAME, error));
489
+ const createObserver = (scope) => (stack, phase) => {
490
+ const event = toEvent(stack.at(-1), scope, phase);
491
+ const path = [];
492
+ for (const node of [...stack].reverse()) {
493
+ const meta = "meta" in node ? node.meta : void 0;
494
+ if (meta) path.push(meta);
495
+ if (meta?.observe) notify(meta.observe, event, [...path]);
496
+ }
497
+ };
498
+ // src/compose/scope.ts
499
+ const createScope = (computer) => {
500
+ return { get: (spot) => computer.computeSafe(spot) };
501
+ };
502
+ // src/compose/runner.ts
503
+ const execute = (ctx, runnable) => Promise.resolve().then(() => ctx.computer.compute(runnable[Context$])).then((value) => runnable[Execute$](value)).then((value) => {
504
+ for (const key of Object.getOwnPropertySymbols(runnable[Dispatch$])) ctx.registry.set(key, runnable[Dispatch$][key](value));
505
+ return value;
506
+ });
507
+ const traverse = async (ctx, stack) => {
508
+ const current = stack.at(-1);
509
+ ctx.dispatch(stack, "enter");
510
+ switch (current.type) {
511
+ case "seq":
512
+ for (const child of current.children) await traverse(ctx, [...stack, child]);
513
+ break;
514
+ case "con":
515
+ await Promise.all(current.children.map((child) => traverse(ctx, [...stack, child])));
516
+ break;
517
+ case "run": await execute(ctx, current.value);
518
+ }
519
+ ctx.dispatch(stack, "exit");
520
+ };
521
+ const run = async (node) => {
522
+ const registry = /* @__PURE__ */ new Map();
523
+ const computer = createComputer(registry);
524
+ const scope = createScope(computer);
525
+ const ctx = {
526
+ computer,
527
+ registry,
528
+ dispatch: createObserver(scope)
529
+ };
530
+ await traverse(ctx, [node]);
531
+ return scope;
532
+ };
533
+ // src/compose/compose.ts
534
+ const Node$ = Symbol("$node");
535
+ const normalize = (arg) => {
536
+ if (Node$ in arg) return arg[Node$];
537
+ else if (Execute$ in arg) return {
538
+ type: "run",
539
+ value: arg
540
+ };
541
+ else throw new Error(`${LIBRARY_NAME} Invalid argument passed to step.`);
542
+ };
543
+ const raiseOnGuard = (message) => {
544
+ throw new Error(message);
545
+ };
546
+ const builder = (node) => {
547
+ return {
548
+ [Node$]: node,
549
+ meta: (meta) => builder({
550
+ ...node,
551
+ meta: {
552
+ ...node.meta,
553
+ ...meta
554
+ }
555
+ }),
556
+ step: (arg) => {
557
+ if (Array.isArray(arg)) return builder({
558
+ ...node,
559
+ children: [...node.children, {
560
+ type: "con",
561
+ children: arg.map(normalize)
562
+ }]
563
+ });
564
+ else return builder({
565
+ ...node,
566
+ children: [...node.children, normalize(arg)]
567
+ });
568
+ },
569
+ run: () => {
570
+ return createGuard({ handler: {
571
+ warn: (message) => console.warn(LIBRARY_NAME, message),
572
+ error: raiseOnGuard
573
+ } })(node), run(node);
574
+ },
575
+ guard: () => {
576
+ return createGuard({ handler: {
577
+ warn: raiseOnGuard,
578
+ error: raiseOnGuard
579
+ } })(node);
580
+ },
581
+ graph: () => graph(node)
582
+ };
583
+ };
584
+ const compose = () => {
585
+ return builder({
586
+ type: "seq",
587
+ children: []
588
+ });
589
+ };
590
+ export { compose, createTask, createWire, is, literal, optional, shape, tag };
591
+
592
+ //# sourceMappingURL=index.js.map