@procedures/client 0.25.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +10 -0
  3. package/dist/.tsbuildinfo +1 -1
  4. package/dist/browser.d.ts +2 -2
  5. package/dist/browser.d.ts.map +1 -1
  6. package/dist/browser.js +2 -0
  7. package/dist/browser.js.map +1 -1
  8. package/dist/client/client.d.ts +7 -1
  9. package/dist/client/client.d.ts.map +1 -1
  10. package/dist/client/client.js +30 -19
  11. package/dist/client/client.js.map +1 -1
  12. package/dist/procedures/core/index.d.ts +7 -7
  13. package/dist/procedures/core/index.d.ts.map +1 -1
  14. package/dist/procedures/core/index.js +53 -178
  15. package/dist/procedures/core/index.js.map +1 -1
  16. package/dist/procedures/core/operands.d.ts +12 -13
  17. package/dist/procedures/core/operands.d.ts.map +1 -1
  18. package/dist/procedures/core/operands.js +22 -38
  19. package/dist/procedures/core/operands.js.map +1 -1
  20. package/dist/procedures/define-procedure.d.ts.map +1 -1
  21. package/dist/procedures/define-procedure.js +6 -6
  22. package/dist/procedures/define-procedure.js.map +1 -1
  23. package/dist/procedures/envelope.d.ts +20 -11
  24. package/dist/procedures/envelope.d.ts.map +1 -1
  25. package/dist/procedures/envelope.js +51 -20
  26. package/dist/procedures/envelope.js.map +1 -1
  27. package/dist/procedures/index.d.ts +3 -1
  28. package/dist/procedures/index.d.ts.map +1 -1
  29. package/dist/procedures/index.js +3 -1
  30. package/dist/procedures/index.js.map +1 -1
  31. package/dist/procedures/program.d.ts +251 -0
  32. package/dist/procedures/program.d.ts.map +1 -0
  33. package/dist/procedures/program.js +1120 -0
  34. package/dist/procedures/program.js.map +1 -0
  35. package/dist/procedures/ref.d.ts +7 -94
  36. package/dist/procedures/ref.d.ts.map +1 -1
  37. package/dist/procedures/ref.js +16 -279
  38. package/dist/procedures/ref.js.map +1 -1
  39. package/package.json +3 -1
  40. package/src/browser.ts +23 -0
  41. package/src/client/client.ts +35 -23
  42. package/src/procedures/core/index.ts +56 -216
  43. package/src/procedures/core/operands.ts +24 -44
  44. package/src/procedures/define-procedure.ts +5 -7
  45. package/src/procedures/envelope.ts +60 -24
  46. package/src/procedures/index.ts +34 -4
  47. package/src/procedures/program.ts +1371 -0
  48. package/src/procedures/ref.ts +19 -357
@@ -4,6 +4,10 @@
4
4
  * Enables procedures-as-data: procedures can be passed as inputs to other procedures,
5
5
  * composed declaratively via JSON, or imperatively via TypeScript.
6
6
  *
7
+ * This module holds the `$proc` form of a program: its keys, its types, the builder, the JSON
8
+ * helpers, the scope that a raw input carries and the raw-input rules. The kernel of coeval runs
9
+ * a program: `program.ts` changes the `$proc` form into a run document (roadmap item M14).
10
+ *
7
11
  * Key concepts:
8
12
  * - PROCEDURE_SYMBOL: Symbol tag to identify procedure references in JSON/objects
9
13
  * - ProcedureRef: A reference to a procedure with pre-bound input
@@ -11,8 +15,6 @@
11
15
  * - $name: Names the result of a chain step, for `$ref`
12
16
  * - $ref: Reads a name of the scope (a chain step, `$last`, `item`, `acc`, `index`, `input`)
13
17
  * - $literal: Gives a value without hydration
14
- * - hydrateInput: Walks input tree and executes nested procedure references
15
- * - executeRef: Helper for procedures to execute deferred refs
16
18
  * - proc(): Factory function to create procedure references
17
19
  *
18
20
  * ## Execution Control with $when
@@ -678,9 +680,9 @@ export interface HydrateOptions {
678
680
  * Whether sibling refs run at the same time (default: false). With false, the refs run one
679
681
  * after the other, from left to right and depth first, so the order of their effects is known.
680
682
  *
681
- * Deprecated behavior (D26): after the first error, the other refs go on in the background
682
- * (`Promise.all`). From the next MINOR, the refs always operate with failFast: the other refs
683
- * stop at their next wait. When their calls must start, give `parallel: false`.
683
+ * With true, the refs operate with failFast (D26): after the first error, the other refs stop
684
+ * at their next wait. Before 0.26.0, they went on in the background (`Promise.all`). When their
685
+ * calls must start, give `parallel: false`.
684
686
  */
685
687
  parallel?: boolean | undefined;
686
688
 
@@ -732,306 +734,9 @@ export interface HydrationEvent {
732
734
  readonly consumer: AnyProcedureRef | undefined;
733
735
  }
734
736
 
735
- /** The observers of `observeHydration()`: they get the events of every hydration. */
736
- const hydrationObservers = new Set<(event: HydrationEvent) => void>();
737
-
738
- /**
739
- * This function adds an observer of every hydration in this process (or worker), and gives the
740
- * function that removes it. A host that does not call `hydrateInput` itself (the Composer of
741
- * the site runs `client.exec()`) uses it for its trace. The observer gets the events of all
742
- * concurrent hydrations: use it where one program runs at a time. For the events of one program,
743
- * give `onRef` to that program: `client.exec(ref, input, { onRef })` (docs review DOC-10).
744
- */
745
- export function observeHydration(observer: (event: HydrationEvent) => void): () => void {
746
- hydrationObservers.add(observer);
747
- return () => {
748
- hydrationObservers.delete(observer);
749
- };
750
- }
751
-
752
737
  /** The maximum nesting of plain data in an input. A deeper input is an error, not a stack overflow. */
753
738
  export const MAX_DATA_DEPTH = 1000;
754
739
 
755
- /** The objects on the path from the root of the input to a value, to find a cycle. */
756
- interface Ancestors {
757
- readonly value: object;
758
- readonly up: Ancestors | undefined;
759
- }
760
-
761
- /**
762
- * Internal context for hydration.
763
- */
764
- interface HydrateContext {
765
- executor: RefExecutor;
766
- maxDepth: number;
767
- parallel: boolean;
768
- contextStack: string[];
769
- scope?: RefScope | undefined;
770
- rawInput: (path: ProcedurePath) => boolean;
771
- /** Prevent recursive implicit chain detection */
772
- skipImplicitChain: boolean;
773
- /** Inside a deferred ref, a `$ref` name that is not known yet stays for the runner. */
774
- deferred: boolean;
775
- /** The `onRef` function of the options */
776
- onRef: ((event: HydrationEvent) => void) | undefined;
777
- }
778
-
779
- /**
780
- * Hydrate an input tree by executing any nested procedure references.
781
- *
782
- * Walks the input object tree and replaces any ProcedureRef or ProcedureRefJson
783
- * objects with the result of executing that procedure, respecting $when timing.
784
- *
785
- * The rules:
786
- * - A ref with `$when: "$immediate"` (the default) runs. A ref whose procedure takes its input
787
- * raw (see `HydrateOptions.rawInput`) gets its input unchanged, with the scope attached.
788
- * - A ref with `$when: "$never"` stays as it is, with its whole subtree.
789
- * - A ref with `$when: "$parent"` or `$when: "<name>"` stays data for its runner. Its procedure
790
- * gets that ref later. The immediate refs of its input run now, unless the procedure takes its
791
- * input raw. A named ref runs now only when `contextStack` has the name.
792
- * - A `$ref` object gives a value from the scope. `{ $literal: value }` gives the value unchanged.
793
- * - An array whose items are all refs that run now, outside the input of a ref, runs as one
794
- * `client.chain`. An array with a deferred ref is a list.
795
- * - Values that are not plain data (`Date`, `Map`, typed arrays, class instances) stay unchanged.
796
- * A subtree without refs stays the same object.
797
- *
798
- * @param input - The input object potentially containing procedure references
799
- * @param executor - Function to execute procedure references
800
- * @param options - Hydration options
801
- * @returns The hydrated input with executed procedure refs replaced by their results
802
- *
803
- * @example
804
- * ```typescript
805
- * const input = {
806
- * visit: proc(["git", "add"]).input({ all: true }).build(),
807
- * config: { nested: true },
808
- * };
809
- *
810
- * const hydrated = await hydrateInput(input, async (path, input) => {
811
- * return await client.call({ path, input });
812
- * });
813
- *
814
- * // hydrated.visit is now the result of executing git.add
815
- * ```
816
- */
817
- export async function hydrateInput<T>(
818
- input: T,
819
- executor: RefExecutor,
820
- options: HydrateOptions = {}
821
- ): Promise<T> {
822
- const ctx: HydrateContext = {
823
- executor,
824
- maxDepth: options.maxDepth ?? 10,
825
- parallel: options.parallel ?? false,
826
- contextStack: options.contextStack ?? [],
827
- scope: options.scope,
828
- rawInput: options.rawInput ?? isControlFlowPath,
829
- skipImplicitChain: false,
830
- deferred: false,
831
- onRef: options.onRef,
832
- };
833
- return hydrateValue(input, ctx, 0, undefined, 0);
834
- }
835
-
836
- /**
837
- * The path and the input of the root call of a program: the call that `client.exec()` starts.
838
- * `exec()` and the body of a procedure that `procedure.define` made both use this function, so
839
- * the same program gives the same result in both (docs review DOC-3: before, a defined body
840
- * hydrated its root call as a nested ref).
841
- *
842
- * The rules of the root call:
843
- * - A `$when` on the root call does not apply: the caller starts the root call now.
844
- * - A procedure that takes its input raw (`rawInput`) gets its input unchanged, with the scope
845
- * attached, and runs its operands itself.
846
- * - Another procedure gets its input hydrated as a root: a list of calls that run now is an
847
- * implicit chain, and the nested refs run.
848
- *
849
- * The caller then starts the call with the path and the input.
850
- */
851
- export async function prepareRootCall(
852
- ref: AnyProcedureRef,
853
- executor: RefExecutor,
854
- options: Pick<HydrateOptions, "rawInput" | "onRef" | "scope"> = {}
855
- ): Promise<{ path: ProcedurePath; input: unknown }> {
856
- const root = normalizeRef(ref);
857
- const rawInput = options.rawInput ?? isControlFlowPath;
858
- if (rawInput(root.path)) {
859
- return { path: root.path, input: withScope(root.input, options.scope) };
860
- }
861
- const input = await hydrateInput(root.input, executor, { rawInput, onRef: options.onRef, scope: options.scope });
862
- return { path: root.path, input };
863
- }
864
-
865
- /**
866
- * This function tells the observers that a ref runs now. The consumer is the nearest ref
867
- * around the ref. An observer that throws does not change the hydration.
868
- */
869
- function notifyRef(ctx: HydrateContext, ref: AnyProcedureRef, path: ProcedurePath, ancestors: Ancestors | undefined): void {
870
- if (!ctx.onRef && hydrationObservers.size === 0) return;
871
- let consumer: AnyProcedureRef | undefined;
872
- for (let current = ancestors; current; current = current.up) {
873
- if (isAnyProcedureRef(current.value)) {
874
- consumer = current.value;
875
- break;
876
- }
877
- }
878
- const event: HydrationEvent = { path, ref, consumer };
879
- for (const observer of ctx.onRef ? [ctx.onRef, ...hydrationObservers] : hydrationObservers) {
880
- try {
881
- observer(event);
882
- } catch {
883
- // A trace must not change the program
884
- }
885
- }
886
- }
887
-
888
- /** The values of `fn` for each item: one after the other, or at the same time. */
889
- async function eachValue<T>(items: readonly T[], fn: (item: T) => Promise<unknown>, parallel: boolean): Promise<unknown[]> {
890
- if (parallel) return Promise.all(items.map(fn));
891
- const results: unknown[] = [];
892
- for (const item of items) results.push(await fn(item));
893
- return results;
894
- }
895
-
896
- /** This function resolves a `$ref` in the scope of the hydration. */
897
- function resolveRefValue(value: OutputRef, ctx: HydrateContext): unknown {
898
- // No scope: the object is data (for example a JSON Schema reference), or a later scope binds it
899
- if (!ctx.scope) return value;
900
- const { found, value: resolved } = lookupOutputRef(value.$ref, ctx.scope);
901
- if (found) return resolved;
902
- // Inside a deferred ref, the runner can bind the name later
903
- if (ctx.deferred) return value;
904
- const name = value.$ref.split(".")[0];
905
- throw new Error(
906
- `Unknown $ref name "${name}" in "${value.$ref}": no step, item or input has this name here. ` +
907
- `For a literal $ref object, write { "$literal": { "$ref": ... } }.`
908
- );
909
- }
910
-
911
- /**
912
- * Internal recursive hydration function.
913
- *
914
- * `refDepth` counts the refs around the value. `dataDepth` counts all levels.
915
- */
916
- async function hydrateValue<T>(
917
- value: T,
918
- ctx: HydrateContext,
919
- refDepth: number,
920
- ancestors: Ancestors | undefined,
921
- dataDepth: number
922
- ): Promise<T> {
923
- // Handle null/undefined/primitives
924
- if (value === null || typeof value !== "object") {
925
- return value;
926
- }
927
-
928
- if (dataDepth > MAX_DATA_DEPTH) {
929
- throw new Error(`Hydration failed: the input has more than ${MAX_DATA_DEPTH} levels of nesting`);
930
- }
931
- for (let current = ancestors; current; current = current.up) {
932
- if (current.value === value) {
933
- throw new Error("Hydration failed: the input is cyclic (an object contains itself)");
934
- }
935
- }
936
-
937
- // { $literal: value } gives the value without hydration
938
- if (isLiteral(value)) {
939
- return value.$literal as T;
940
- }
941
-
942
- // Check if this is an output reference ($ref)
943
- if (isOutputRef(value)) {
944
- return resolveRefValue(value, ctx) as T;
945
- }
946
-
947
- // Check if this is a procedure reference ($proc)
948
- if (isAnyProcedureRef(value)) {
949
- return hydrateRef(value, ctx, refDepth, ancestors, dataDepth) as Promise<T>;
950
- }
951
-
952
- const inner: Ancestors = { value, up: ancestors };
953
-
954
- // Handle arrays
955
- if (Array.isArray(value)) {
956
- // An array of procedure refs that all run now is an implicit chain. A deferred ref ($never,
957
- // $parent, a context name that the runner did not give) is data, so a list with one is a list
958
- // (docs review DOC-1: before, a list of only $never refs ran as a chain). Inside an implicit
959
- // chain, the steps do not make another one.
960
- if (
961
- !ctx.skipImplicitChain &&
962
- value.length > 0 &&
963
- value.every((item) => isAnyProcedureRef(item) && shouldExecuteRef(item, ctx.contextStack, false))
964
- ) {
965
- // client.chain runs the steps in order: they reach it raw. (Before, hydration ran the steps
966
- // all at once, and client.chain got their results: deep dive, architecture review 3.4.)
967
- const implicitChain: ProcedureRefJson = { $proc: ["client", "chain"], input: { steps: value } };
968
- return hydrateRef(implicitChain, { ...ctx, skipImplicitChain: true }, refDepth, ancestors, dataDepth) as Promise<T>;
969
- }
970
-
971
- const items = await eachValue(value, (item) => hydrateValue(item, ctx, refDepth, inner, dataDepth + 1), ctx.parallel);
972
- return (items.every((item, index) => item === value[index]) ? value : items) as T;
973
- }
974
-
975
- // Values that are not plain data (Date, Map, typed arrays, class instances) stay unchanged
976
- if (!isPlainObject(value)) {
977
- return value;
978
- }
979
-
980
- // Handle plain objects
981
- const entries = Object.entries(value);
982
- const values = await eachValue(entries, ([, val]) => hydrateValue(val, ctx, refDepth, inner, dataDepth + 1), ctx.parallel);
983
- if (values.every((val, index) => val === entries[index]![1])) {
984
- return value;
985
- }
986
- // Object.fromEntries makes own properties, also for a key such as "__proto__"
987
- return Object.fromEntries(entries.map(([key], index) => [key, values[index]])) as T;
988
- }
989
-
990
- /** This function hydrates one procedure ref: it runs the ref, or it keeps the ref as data. */
991
- async function hydrateRef(
992
- value: AnyProcedureRef,
993
- ctx: HydrateContext,
994
- refDepth: number,
995
- ancestors: Ancestors | undefined,
996
- dataDepth: number
997
- ): Promise<unknown> {
998
- const when = getRefWhen(value);
999
-
1000
- // $never: pure data, with its whole subtree (deep dive CORE-11: before, its input was hydrated)
1001
- if (when === WHEN_NEVER) {
1002
- return value;
1003
- }
1004
-
1005
- if (refDepth >= ctx.maxDepth) {
1006
- throw new Error(`Hydration depth exceeded maximum of ${ctx.maxDepth}`);
1007
- }
1008
-
1009
- const ref = normalizeRef(value);
1010
- const raw = ctx.rawInput(ref.path);
1011
- const inner: Ancestors = { value, up: ancestors };
1012
- // The input of a ref is never an implicit chain
1013
- const inputCtx = (deferred: boolean): HydrateContext => ({ ...ctx, skipImplicitChain: true, deferred });
1014
-
1015
- // A ref that waits for its runner ($parent, or a name that the runner did not give) is data.
1016
- // Its own $name is not a context here: hydration of its input does not run refs that wait for
1017
- // it, at any depth (deep dive CORE-11: before, this depended on the depth of the ref).
1018
- if (!shouldExecuteRef(value, ctx.contextStack, false)) {
1019
- if (raw) return value;
1020
- const input = await hydrateValue(ref.input, inputCtx(true), refDepth + 1, inner, dataDepth + 1);
1021
- return input === ref.input ? value : { ...value, input };
1022
- }
1023
-
1024
- // A procedure that takes its input raw gets it unchanged, with the scope of the caller
1025
- if (raw) {
1026
- notifyRef(ctx, value, ref.path, ancestors);
1027
- return ctx.executor(ref.path, withScope(ref.input, ctx.scope));
1028
- }
1029
-
1030
- const input = await hydrateValue(ref.input, inputCtx(false), refDepth + 1, inner, dataDepth + 1);
1031
- notifyRef(ctx, value, ref.path, ancestors);
1032
- return ctx.executor(ref.path, input);
1033
- }
1034
-
1035
740
  // =============================================================================
1036
741
  // Control-Flow Procedures
1037
742
  // =============================================================================
@@ -1133,64 +838,21 @@ export function takesRawInput(procedure: ProcedureShape): boolean {
1133
838
  export function rawInputRule(
1134
839
  registry: { get(path: ProcedurePath): ProcedureShape | undefined } | undefined
1135
840
  ): (path: ProcedurePath) => boolean {
1136
- return (path) => {
1137
- const procedure = registry?.get(path);
1138
- return procedure ? takesRawInput(procedure) : isControlFlowPath(path);
1139
- };
1140
- }
1141
-
1142
- // =============================================================================
1143
- // Deferred Ref Execution
1144
- // =============================================================================
1145
-
1146
- /**
1147
- * Execute a deferred procedure reference.
1148
- *
1149
- * This is a helper for procedures that receive deferred refs (via $when)
1150
- * and need to execute them with additional context.
1151
- *
1152
- * @param ref - The procedure reference to execute
1153
- * @param executor - Function to execute the procedure
1154
- * @param additionalInput - Additional input to merge (e.g., cwd for dag.traverse)
1155
- * @param options - Hydration options for the input of the ref (for example the runner's `contextStack`)
1156
- * @returns The result of executing the procedure
1157
- *
1158
- * @example
1159
- * ```typescript
1160
- * // In dag.traverse, execute a deferred ref with cwd
1161
- * const result = await executeRef(
1162
- * input.visit,
1163
- * (path, input) => ctx.client.call(path, input),
1164
- * { cwd: node.repoPath }
1165
- * );
1166
- * ```
1167
- */
1168
- export async function executeRef<TOutput = unknown>(
1169
- ref: AnyProcedureRef,
1170
- executor: RefExecutor,
1171
- additionalInput?: Record<string, unknown>,
1172
- options: HydrateOptions = {}
1173
- ): Promise<TOutput> {
1174
- const normalized = normalizeRef(ref);
1175
- const baseInput = typeof normalized.input === "object" ? normalized.input : {};
1176
-
1177
- // Merge additional input
1178
- const mergedInput = {
1179
- ...(baseInput as Record<string, unknown>),
1180
- ...additionalInput,
1181
- };
1182
-
1183
- const raw = (options.rawInput ?? isControlFlowPath)(normalized.path);
1184
- if (raw) {
1185
- return executor(normalized.path, withScope(mergedInput, options.scope));
841
+ if (!registry) return isControlFlowPath;
842
+ // One rule for each registry: the rule reads the registry at each call, so it stays current
843
+ let rule = RAW_INPUT_RULES.get(registry);
844
+ if (!rule) {
845
+ rule = (path) => {
846
+ const procedure = registry.get(path);
847
+ return procedure ? takesRawInput(procedure) : isControlFlowPath(path);
848
+ };
849
+ RAW_INPUT_RULES.set(registry, rule);
1186
850
  }
1187
-
1188
- // Hydrate the merged input (execute any nested $immediate refs)
1189
- const hydratedInput = await hydrateInput(mergedInput, executor, options);
1190
-
1191
- return executor(normalized.path, hydratedInput);
851
+ return rule;
1192
852
  }
1193
853
 
854
+ const RAW_INPUT_RULES = new WeakMap<object, (path: ProcedurePath) => boolean>();
855
+
1194
856
  // =============================================================================
1195
857
  // Template Extraction
1196
858
  // =============================================================================