@entifix/business 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/compose/compose.d.ts +100 -0
  2. package/dist/compose/compose.d.ts.map +1 -0
  3. package/dist/compose/compose.js +143 -0
  4. package/dist/compose/compose.js.map +1 -0
  5. package/dist/compose/index.d.ts +2 -0
  6. package/dist/compose/index.d.ts.map +1 -0
  7. package/dist/compose/index.js +3 -0
  8. package/dist/compose/index.js.map +1 -0
  9. package/dist/flow/catalog.d.ts +51 -0
  10. package/dist/flow/catalog.d.ts.map +1 -0
  11. package/dist/flow/catalog.js +63 -0
  12. package/dist/flow/catalog.js.map +1 -0
  13. package/dist/flow/fragment.d.ts +105 -0
  14. package/dist/flow/fragment.d.ts.map +1 -0
  15. package/dist/flow/fragment.js +77 -0
  16. package/dist/flow/fragment.js.map +1 -0
  17. package/dist/flow/index.d.ts +5 -0
  18. package/dist/flow/index.d.ts.map +1 -0
  19. package/dist/flow/index.js +6 -0
  20. package/dist/flow/index.js.map +1 -0
  21. package/dist/flow/slip.d.ts +126 -0
  22. package/dist/flow/slip.d.ts.map +1 -0
  23. package/dist/flow/slip.js +68 -0
  24. package/dist/flow/slip.js.map +1 -0
  25. package/dist/flow/validate.d.ts +49 -0
  26. package/dist/flow/validate.d.ts.map +1 -0
  27. package/dist/flow/validate.js +126 -0
  28. package/dist/flow/validate.js.map +1 -0
  29. package/dist/idempotency/idempotency-store.d.ts +53 -0
  30. package/dist/idempotency/idempotency-store.d.ts.map +1 -0
  31. package/dist/idempotency/idempotency-store.js +5 -0
  32. package/dist/idempotency/idempotency-store.js.map +1 -0
  33. package/dist/idempotency/index.d.ts +2 -0
  34. package/dist/idempotency/index.d.ts.map +1 -0
  35. package/dist/idempotency/index.js +3 -0
  36. package/dist/idempotency/index.js.map +1 -0
  37. package/dist/index.d.ts +2 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +2 -0
  40. package/dist/index.js.map +1 -1
  41. package/dist/resolve/index.d.ts +3 -0
  42. package/dist/resolve/index.d.ts.map +1 -0
  43. package/dist/resolve/index.js +4 -0
  44. package/dist/resolve/index.js.map +1 -0
  45. package/dist/resolve/resolve.d.ts +70 -0
  46. package/dist/resolve/resolve.d.ts.map +1 -0
  47. package/dist/resolve/resolve.js +69 -0
  48. package/dist/resolve/resolve.js.map +1 -0
  49. package/dist/resolve/verified-context.d.ts +45 -0
  50. package/dist/resolve/verified-context.d.ts.map +1 -0
  51. package/dist/resolve/verified-context.js +8 -0
  52. package/dist/resolve/verified-context.js.map +1 -0
  53. package/dist/verified/index.d.ts +10 -0
  54. package/dist/verified/index.d.ts.map +1 -0
  55. package/dist/verified/index.js +10 -0
  56. package/dist/verified/index.js.map +1 -0
  57. package/package.json +17 -2
@@ -0,0 +1,100 @@
1
+ import { Invalid } from '@entifix/core';
2
+ import { Effect, Schema } from 'effect';
3
+ import type { FragmentCatalog } from '../flow/catalog.js';
4
+ import type { FragmentKeys } from '../flow/fragment.js';
5
+ import { type Slip, type SlipSegment } from '../flow/slip.js';
6
+ import { type CompositionRefused, type SlipViolation } from '../flow/validate.js';
7
+ import { type ResolutionRule, Unresolvable } from '../resolve/resolve.js';
8
+ import type { VerifiedContext } from '../resolve/verified-context.js';
9
+ /** A gate over what is known when the flow starts. Never over anything else. */
10
+ export type RecipeGate<I> = (context: VerifiedContext, input: I, segment?: SlipSegment) => boolean;
11
+ /** One step of a recipe: a fragment by its pinned reference, as a string. */
12
+ export interface RecipeStep<I> {
13
+ readonly ref: string;
14
+ /** The step's name in the slip; defaults to the fragment id. */
15
+ readonly step?: string;
16
+ readonly when?: RecipeGate<I>;
17
+ /** Parameters pinned at composition, read from the context's config. */
18
+ readonly parameters?: (context: VerifiedContext) => Readonly<Record<string, unknown>>;
19
+ }
20
+ /**
21
+ * One stage of a recipe. A `perSegment` stage is expanded once per segment the
22
+ * start input names — one per vendor, say — each step tagged with its segment
23
+ * and named `<segment key>:<step>`.
24
+ */
25
+ export interface RecipeStage<I> {
26
+ readonly name: string;
27
+ readonly when?: RecipeGate<I>;
28
+ readonly perSegment?: boolean;
29
+ readonly steps: readonly RecipeStep<I>[];
30
+ }
31
+ /** A use case the recipe resolves, recorded on the slip as it was resolved. */
32
+ export interface RecipeResolution {
33
+ readonly useCase: string;
34
+ readonly rules: readonly ResolutionRule<unknown>[];
35
+ }
36
+ /**
37
+ * A named template a slip is composed from. It references fragments by
38
+ * `id@n` strings, never by import, so no domain imports another to take part in
39
+ * a flow.
40
+ */
41
+ export interface Recipe<I> {
42
+ readonly name: string;
43
+ /** The start input, decoded before anything else is read from it. */
44
+ readonly input: Schema.Codec<I, unknown>;
45
+ /** Keys the start input provides to the first steps, with their schemas. */
46
+ readonly provides?: FragmentKeys;
47
+ /** A checkout needs a commit point even with nothing retriable in it. */
48
+ readonly requiresCommitPoint?: boolean;
49
+ /** The segments a `perSegment` stage expands over. */
50
+ readonly segments?: (input: I) => readonly SlipSegment[];
51
+ readonly resolve?: readonly RecipeResolution[];
52
+ readonly stages: readonly RecipeStage<I>[];
53
+ }
54
+ /** What a composition is stamped with: both are inputs, so composing is deterministic. */
55
+ export interface ComposeOptions {
56
+ readonly flowId: string;
57
+ readonly composedAt: string;
58
+ }
59
+ /**
60
+ * Composes a recipe into a pinned, validated slip for one caller: decodes the
61
+ * start input, resolves the recipe's use cases, expands per-segment stages,
62
+ * pins versions and parameters, stamps `slipVersion`, validates, and annotates
63
+ * the span with `entifix.slip.version` and `entifix.slip.fragments`.
64
+ *
65
+ * An unknown `id@n` is a `CompositionRefused` carrying `UnknownFragment`, never
66
+ * a throw. The same context, input and options always give the same slip.
67
+ */
68
+ export declare const compose: <I>(recipe: Recipe<I>, catalog: FragmentCatalog, context: VerifiedContext, input: unknown, options: ComposeOptions) => Effect.Effect<Slip, CompositionRefused | Unresolvable | Invalid>;
69
+ /** One axis value, labelled so a report can say which combination broke. */
70
+ export interface Labelled<T> {
71
+ readonly label: string;
72
+ readonly value: T;
73
+ }
74
+ /** The axes a recipe is enumerated over. */
75
+ export interface CompositionAxes<I> {
76
+ readonly contexts: readonly Labelled<VerifiedContext>[];
77
+ readonly inputs: readonly Labelled<I>[];
78
+ }
79
+ /** How one combination composed. */
80
+ export interface CompositionOutcome {
81
+ readonly context: string;
82
+ readonly input: string;
83
+ /** `composed`, `unresolvable` (the caller is offered no variant), or `refused`. */
84
+ readonly outcome: 'composed' | 'unresolvable' | 'refused';
85
+ readonly violations: readonly SlipViolation[];
86
+ }
87
+ /**
88
+ * Composes the recipe for every context × input and reports each outcome —
89
+ * what a CI job runs to prove that every combination a recipe can produce is a
90
+ * valid slip before it ships. An unresolvable combination is a caller who is
91
+ * offered nothing, which is not a defect; a refused one is.
92
+ */
93
+ export declare const enumerateCompositions: <I>(recipe: Recipe<I>, catalog: FragmentCatalog, axes: CompositionAxes<I>) => readonly CompositionOutcome[];
94
+ /**
95
+ * Throws, listing every refused combination, unless all of them composed or
96
+ * were unresolvable. Framework-neutral on purpose: any test runner reports a
97
+ * thrown error.
98
+ */
99
+ export declare const expectAllCompositionsValid: (outcomes: readonly CompositionOutcome[]) => void;
100
+ //# sourceMappingURL=compose.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compose.d.ts","sourceRoot":"","sources":["../../src/compose/compose.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,OAAO,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAExC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EACL,KAAK,IAAI,EAGT,KAAK,WAAW,EAGjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAEnB,MAAM,qBAAqB,CAAC;AAC7B,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B;IACjC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,mFAAmF;IACnF,QAAQ,CAAC,OAAO,EAAE,UAAU,GAAG,cAAc,GAAG,SAAS,CAAC;IAC1D,QAAQ,CAAC,UAAU,EAAE,SAAS,aAAa,EAAE,CAAC;CAC/C;AAOD;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,GAAI,CAAC,EACrC,QAAQ,MAAM,CAAC,CAAC,CAAC,EACjB,SAAS,eAAe,EACxB,MAAM,eAAe,CAAC,CAAC,CAAC,KACvB,SAAS,kBAAkB,EAsC3B,CAAC;AAEJ;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,GACrC,UAAU,SAAS,kBAAkB,EAAE,KACtC,IAeF,CAAC"}
@@ -0,0 +1,143 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ import { FieldProblem, Invalid } from '@entifix/core';
3
+ import { Effect, Schema } from 'effect';
4
+ import { SLIP_VERSION, slipSteps } from '../flow/slip.js';
5
+ import { assertValidSlip, validateSlip } from '../flow/validate.js';
6
+ import { dryRun, Unresolvable } from '../resolve/resolve.js';
7
+ const segmentKey = (segment)=>[
8
+ segment.vendor,
9
+ segment.paymentMethod
10
+ ].filter(Boolean).join('/');
11
+ const buildStep = (recipeStep, catalog, context, segment)=>{
12
+ var _ref, _recipeStep_step, _ref1;
13
+ const fragment = catalog.get(recipeStep.ref);
14
+ const name = (_ref = (_recipeStep_step = recipeStep.step) != null ? _recipeStep_step : fragment == null ? void 0 : fragment.id) != null ? _ref : recipeStep.ref;
15
+ const parameters = recipeStep.parameters == null ? void 0 : recipeStep.parameters.call(recipeStep, context);
16
+ return _extends({
17
+ ref: recipeStep.ref,
18
+ step: segment === undefined ? name : `${segmentKey(segment)}:${name}`,
19
+ cardinality: (_ref1 = fragment == null ? void 0 : fragment.cardinality) != null ? _ref1 : 'one'
20
+ }, segment === undefined ? {} : {
21
+ segment
22
+ }, (fragment == null ? void 0 : fragment.participant) === undefined ? {} : {
23
+ participant: fragment.participant
24
+ }, (fragment == null ? void 0 : fragment.call) === undefined ? {} : {
25
+ call: fragment.call
26
+ }, (fragment == null ? void 0 : fragment.compensation) === undefined ? {} : {
27
+ compensation: fragment.compensation
28
+ }, parameters === undefined ? {} : {
29
+ parameters
30
+ });
31
+ };
32
+ const resolutionOf = (resolutions, context)=>Effect.forEach(resolutions, ({ useCase, rules })=>{
33
+ const chosen = dryRun(rules, context);
34
+ return chosen === undefined ? Effect.fail(new Unresolvable({
35
+ useCase
36
+ })) : Effect.succeed({
37
+ useCase,
38
+ variant: chosen.variant,
39
+ rule: chosen.rule
40
+ });
41
+ });
42
+ /** Expands the recipe into an unvalidated slip. */ const draft = (recipe, catalog, context, input, resolution, options)=>{
43
+ var _ref;
44
+ const segments = (_ref = recipe.segments == null ? void 0 : recipe.segments.call(recipe, input)) != null ? _ref : [];
45
+ const stages = recipe.stages.filter((stage)=>{
46
+ var _ref;
47
+ return (_ref = stage.when == null ? void 0 : stage.when.call(stage, context, input)) != null ? _ref : true;
48
+ }).map((stage)=>{
49
+ const each = stage.perSegment === true ? segments : [
50
+ undefined
51
+ ];
52
+ return {
53
+ name: stage.name,
54
+ steps: each.flatMap((segment)=>stage.steps.filter((recipeStep)=>{
55
+ var _ref;
56
+ return (_ref = recipeStep.when == null ? void 0 : recipeStep.when.call(recipeStep, context, input, segment)) != null ? _ref : true;
57
+ }).map((recipeStep)=>buildStep(recipeStep, catalog, context, segment)))
58
+ };
59
+ }).filter((stage)=>stage.steps.length > 0);
60
+ return _extends({
61
+ slipVersion: SLIP_VERSION,
62
+ flowId: options.flowId,
63
+ recipe: recipe.name
64
+ }, recipe.requiresCommitPoint === undefined ? {} : {
65
+ requiresCommitPoint: recipe.requiresCommitPoint
66
+ }, {
67
+ stages,
68
+ resolution,
69
+ composedAt: options.composedAt
70
+ });
71
+ };
72
+ const decodeInput = (recipe, input)=>Schema.decodeUnknownEffect(recipe.input)(input).pipe(Effect.mapError((error)=>new Invalid({
73
+ errors: [
74
+ FieldProblem.make({
75
+ pointer: '',
76
+ detail: error.message,
77
+ code: 'invalidFlowInput'
78
+ })
79
+ ]
80
+ })));
81
+ /**
82
+ * Composes a recipe into a pinned, validated slip for one caller: decodes the
83
+ * start input, resolves the recipe's use cases, expands per-segment stages,
84
+ * pins versions and parameters, stamps `slipVersion`, validates, and annotates
85
+ * the span with `entifix.slip.version` and `entifix.slip.fragments`.
86
+ *
87
+ * An unknown `id@n` is a `CompositionRefused` carrying `UnknownFragment`, never
88
+ * a throw. The same context, input and options always give the same slip.
89
+ */ export const compose = (recipe, catalog, context, input, options)=>Effect.gen(function*() {
90
+ var _recipe_resolve;
91
+ const decoded = yield* decodeInput(recipe, input);
92
+ const resolution = yield* resolutionOf((_recipe_resolve = recipe.resolve) != null ? _recipe_resolve : [], context);
93
+ const slip = yield* assertValidSlip(draft(recipe, catalog, context, decoded, resolution, options), catalog, _extends({
94
+ context
95
+ }, recipe.provides === undefined ? {} : {
96
+ start: recipe.provides
97
+ }));
98
+ yield* Effect.annotateCurrentSpan({
99
+ 'entifix.slip.version': slip.slipVersion,
100
+ 'entifix.slip.fragments': slipSteps(slip).map((step)=>step.ref).join(',')
101
+ });
102
+ return slip;
103
+ });
104
+ const ENUMERATED = {
105
+ flowId: 'enumerated',
106
+ composedAt: '1970-01-01T00:00:00.000Z'
107
+ };
108
+ /**
109
+ * Composes the recipe for every context × input and reports each outcome —
110
+ * what a CI job runs to prove that every combination a recipe can produce is a
111
+ * valid slip before it ships. An unresolvable combination is a caller who is
112
+ * offered nothing, which is not a defect; a refused one is.
113
+ */ export const enumerateCompositions = (recipe, catalog, axes)=>axes.contexts.flatMap((context)=>axes.inputs.map((input)=>{
114
+ var _recipe_resolve;
115
+ const resolved = Effect.runSync(Effect.result(resolutionOf((_recipe_resolve = recipe.resolve) != null ? _recipe_resolve : [], context.value)));
116
+ if (resolved._tag === 'Failure') return {
117
+ context: context.label,
118
+ input: input.label,
119
+ outcome: 'unresolvable',
120
+ violations: []
121
+ };
122
+ const violations = validateSlip(draft(recipe, catalog, context.value, input.value, resolved.success, ENUMERATED), catalog, _extends({
123
+ context: context.value
124
+ }, recipe.provides === undefined ? {} : {
125
+ start: recipe.provides
126
+ }));
127
+ return {
128
+ context: context.label,
129
+ input: input.label,
130
+ outcome: violations.length === 0 ? 'composed' : 'refused',
131
+ violations
132
+ };
133
+ }));
134
+ /**
135
+ * Throws, listing every refused combination, unless all of them composed or
136
+ * were unresolvable. Framework-neutral on purpose: any test runner reports a
137
+ * thrown error.
138
+ */ export const expectAllCompositionsValid = (outcomes)=>{
139
+ const refused = outcomes.filter((outcome)=>outcome.outcome === 'refused');
140
+ if (refused.length > 0) throw new Error(`${String(refused.length)} composition(s) are not valid slips:\n` + refused.map((outcome)=>` ${outcome.context} × ${outcome.input}: ` + outcome.violations.map((violation)=>`${violation.tag} (${violation.detail})`).join('; ')).join('\n'));
141
+ };
142
+
143
+ //# sourceMappingURL=compose.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/compose/compose.ts"],"sourcesContent":["import { FieldProblem, Invalid } from '@entifix/core';\nimport { Effect, Schema } from 'effect';\n\nimport type { FragmentCatalog } from '../flow/catalog.js';\nimport type { FragmentKeys } from '../flow/fragment.js';\nimport {\n type Slip,\n SLIP_VERSION,\n type SlipResolution,\n type SlipSegment,\n type SlipStep,\n slipSteps,\n} from '../flow/slip.js';\nimport {\n assertValidSlip,\n type CompositionRefused,\n type SlipViolation,\n validateSlip,\n} from '../flow/validate.js';\nimport {\n dryRun,\n type ResolutionRule,\n Unresolvable,\n} from '../resolve/resolve.js';\nimport type { VerifiedContext } from '../resolve/verified-context.js';\n\n/** A gate over what is known when the flow starts. Never over anything else. */\nexport type RecipeGate<I> = (\n context: VerifiedContext,\n input: I,\n segment?: SlipSegment,\n) => boolean;\n\n/** One step of a recipe: a fragment by its pinned reference, as a string. */\nexport interface RecipeStep<I> {\n readonly ref: string;\n /** The step's name in the slip; defaults to the fragment id. */\n readonly step?: string;\n readonly when?: RecipeGate<I>;\n /** Parameters pinned at composition, read from the context's config. */\n readonly parameters?: (\n context: VerifiedContext,\n ) => Readonly<Record<string, unknown>>;\n}\n\n/**\n * One stage of a recipe. A `perSegment` stage is expanded once per segment the\n * start input names — one per vendor, say — each step tagged with its segment\n * and named `<segment key>:<step>`.\n */\nexport interface RecipeStage<I> {\n readonly name: string;\n readonly when?: RecipeGate<I>;\n readonly perSegment?: boolean;\n readonly steps: readonly RecipeStep<I>[];\n}\n\n/** A use case the recipe resolves, recorded on the slip as it was resolved. */\nexport interface RecipeResolution {\n readonly useCase: string;\n readonly rules: readonly ResolutionRule<unknown>[];\n}\n\n/**\n * A named template a slip is composed from. It references fragments by\n * `id@n` strings, never by import, so no domain imports another to take part in\n * a flow.\n */\nexport interface Recipe<I> {\n readonly name: string;\n /** The start input, decoded before anything else is read from it. */\n readonly input: Schema.Codec<I, unknown>;\n /** Keys the start input provides to the first steps, with their schemas. */\n readonly provides?: FragmentKeys;\n /** A checkout needs a commit point even with nothing retriable in it. */\n readonly requiresCommitPoint?: boolean;\n /** The segments a `perSegment` stage expands over. */\n readonly segments?: (input: I) => readonly SlipSegment[];\n readonly resolve?: readonly RecipeResolution[];\n readonly stages: readonly RecipeStage<I>[];\n}\n\n/** What a composition is stamped with: both are inputs, so composing is deterministic. */\nexport interface ComposeOptions {\n readonly flowId: string;\n readonly composedAt: string;\n}\n\nconst segmentKey = (segment: SlipSegment): string =>\n [segment.vendor, segment.paymentMethod].filter(Boolean).join('/');\n\nconst buildStep = <I>(\n recipeStep: RecipeStep<I>,\n catalog: FragmentCatalog,\n context: VerifiedContext,\n segment: SlipSegment | undefined,\n): SlipStep => {\n const fragment = catalog.get(recipeStep.ref);\n const name = recipeStep.step ?? fragment?.id ?? recipeStep.ref;\n const parameters = recipeStep.parameters?.(context);\n return {\n ref: recipeStep.ref,\n step: segment === undefined ? name : `${segmentKey(segment)}:${name}`,\n cardinality: fragment?.cardinality ?? 'one',\n ...(segment === undefined ? {} : { segment }),\n ...(fragment?.participant === undefined\n ? {}\n : { participant: fragment.participant }),\n ...(fragment?.call === undefined ? {} : { call: fragment.call }),\n ...(fragment?.compensation === undefined\n ? {}\n : { compensation: fragment.compensation }),\n ...(parameters === undefined ? {} : { parameters }),\n };\n};\n\nconst resolutionOf = (\n resolutions: readonly RecipeResolution[],\n context: VerifiedContext,\n): Effect.Effect<readonly SlipResolution[], Unresolvable> =>\n Effect.forEach(resolutions, ({ useCase, rules }) => {\n const chosen = dryRun(rules, context);\n return chosen === undefined\n ? Effect.fail(new Unresolvable({ useCase }))\n : Effect.succeed({ useCase, variant: chosen.variant, rule: chosen.rule });\n });\n\n/** Expands the recipe into an unvalidated slip. */\nconst draft = <I>(\n recipe: Recipe<I>,\n catalog: FragmentCatalog,\n context: VerifiedContext,\n input: I,\n resolution: readonly SlipResolution[],\n options: ComposeOptions,\n): Slip => {\n const segments = recipe.segments?.(input) ?? [];\n const stages = recipe.stages\n .filter(stage => stage.when?.(context, input) ?? true)\n .map(stage => {\n const each: readonly (SlipSegment | undefined)[] =\n stage.perSegment === true ? segments : [undefined];\n return {\n name: stage.name,\n steps: each.flatMap(segment =>\n stage.steps\n .filter(\n recipeStep => recipeStep.when?.(context, input, segment) ?? true,\n )\n .map(recipeStep =>\n buildStep(recipeStep, catalog, context, segment),\n ),\n ),\n };\n })\n .filter(stage => stage.steps.length > 0);\n return {\n slipVersion: SLIP_VERSION,\n flowId: options.flowId,\n recipe: recipe.name,\n ...(recipe.requiresCommitPoint === undefined\n ? {}\n : { requiresCommitPoint: recipe.requiresCommitPoint }),\n stages,\n resolution,\n composedAt: options.composedAt,\n };\n};\n\nconst decodeInput = <I>(recipe: Recipe<I>, input: unknown) =>\n Schema.decodeUnknownEffect(recipe.input)(input).pipe(\n Effect.mapError(\n error =>\n new Invalid({\n errors: [\n FieldProblem.make({\n pointer: '',\n detail: error.message,\n code: 'invalidFlowInput',\n }),\n ],\n }),\n ),\n );\n\n/**\n * Composes a recipe into a pinned, validated slip for one caller: decodes the\n * start input, resolves the recipe's use cases, expands per-segment stages,\n * pins versions and parameters, stamps `slipVersion`, validates, and annotates\n * the span with `entifix.slip.version` and `entifix.slip.fragments`.\n *\n * An unknown `id@n` is a `CompositionRefused` carrying `UnknownFragment`, never\n * a throw. The same context, input and options always give the same slip.\n */\nexport const compose = <I>(\n recipe: Recipe<I>,\n catalog: FragmentCatalog,\n context: VerifiedContext,\n input: unknown,\n options: ComposeOptions,\n): Effect.Effect<Slip, CompositionRefused | Unresolvable | Invalid> =>\n Effect.gen(function* () {\n const decoded = yield* decodeInput(recipe, input);\n const resolution = yield* resolutionOf(recipe.resolve ?? [], context);\n const slip = yield* assertValidSlip(\n draft(recipe, catalog, context, decoded, resolution, options),\n catalog,\n {\n context,\n ...(recipe.provides === undefined ? {} : { start: recipe.provides }),\n },\n );\n yield* Effect.annotateCurrentSpan({\n 'entifix.slip.version': slip.slipVersion,\n 'entifix.slip.fragments': slipSteps(slip)\n .map(step => step.ref)\n .join(','),\n });\n return slip;\n });\n\n/** One axis value, labelled so a report can say which combination broke. */\nexport interface Labelled<T> {\n readonly label: string;\n readonly value: T;\n}\n\n/** The axes a recipe is enumerated over. */\nexport interface CompositionAxes<I> {\n readonly contexts: readonly Labelled<VerifiedContext>[];\n readonly inputs: readonly Labelled<I>[];\n}\n\n/** How one combination composed. */\nexport interface CompositionOutcome {\n readonly context: string;\n readonly input: string;\n /** `composed`, `unresolvable` (the caller is offered no variant), or `refused`. */\n readonly outcome: 'composed' | 'unresolvable' | 'refused';\n readonly violations: readonly SlipViolation[];\n}\n\nconst ENUMERATED: ComposeOptions = {\n flowId: 'enumerated',\n composedAt: '1970-01-01T00:00:00.000Z',\n};\n\n/**\n * Composes the recipe for every context × input and reports each outcome —\n * what a CI job runs to prove that every combination a recipe can produce is a\n * valid slip before it ships. An unresolvable combination is a caller who is\n * offered nothing, which is not a defect; a refused one is.\n */\nexport const enumerateCompositions = <I>(\n recipe: Recipe<I>,\n catalog: FragmentCatalog,\n axes: CompositionAxes<I>,\n): readonly CompositionOutcome[] =>\n axes.contexts.flatMap(context =>\n axes.inputs.map(input => {\n const resolved = Effect.runSync(\n Effect.result(resolutionOf(recipe.resolve ?? [], context.value)),\n );\n if (resolved._tag === 'Failure')\n return {\n context: context.label,\n input: input.label,\n outcome: 'unresolvable' as const,\n violations: [],\n };\n const violations = validateSlip(\n draft(\n recipe,\n catalog,\n context.value,\n input.value,\n resolved.success,\n ENUMERATED,\n ),\n catalog,\n {\n context: context.value,\n ...(recipe.provides === undefined ? {} : { start: recipe.provides }),\n },\n );\n return {\n context: context.label,\n input: input.label,\n outcome:\n violations.length === 0\n ? ('composed' as const)\n : ('refused' as const),\n violations,\n };\n }),\n );\n\n/**\n * Throws, listing every refused combination, unless all of them composed or\n * were unresolvable. Framework-neutral on purpose: any test runner reports a\n * thrown error.\n */\nexport const expectAllCompositionsValid = (\n outcomes: readonly CompositionOutcome[],\n): void => {\n const refused = outcomes.filter(outcome => outcome.outcome === 'refused');\n if (refused.length > 0)\n throw new Error(\n `${String(refused.length)} composition(s) are not valid slips:\\n` +\n refused\n .map(\n outcome =>\n ` ${outcome.context} × ${outcome.input}: ` +\n outcome.violations\n .map(violation => `${violation.tag} (${violation.detail})`)\n .join('; '),\n )\n .join('\\n'),\n );\n};\n"],"names":["FieldProblem","Invalid","Effect","Schema","SLIP_VERSION","slipSteps","assertValidSlip","validateSlip","dryRun","Unresolvable","segmentKey","segment","vendor","paymentMethod","filter","Boolean","join","buildStep","recipeStep","catalog","context","fragment","get","ref","name","step","id","parameters","undefined","cardinality","participant","call","compensation","resolutionOf","resolutions","forEach","useCase","rules","chosen","fail","succeed","variant","rule","draft","recipe","input","resolution","options","segments","stages","stage","when","map","each","perSegment","steps","flatMap","length","slipVersion","flowId","requiresCommitPoint","composedAt","decodeInput","decodeUnknownEffect","pipe","mapError","error","errors","make","pointer","detail","message","code","compose","gen","decoded","resolve","slip","provides","start","annotateCurrentSpan","ENUMERATED","enumerateCompositions","axes","contexts","inputs","resolved","runSync","result","value","_tag","label","outcome","violations","success","expectAllCompositionsValid","outcomes","refused","Error","String","violation","tag"],"mappings":";AAAA,SAASA,YAAY,EAAEC,OAAO,QAAQ,gBAAgB;AACtD,SAASC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAIxC,SAEEC,YAAY,EAIZC,SAAS,QACJ,kBAAkB;AACzB,SACEC,eAAe,EAGfC,YAAY,QACP,sBAAsB;AAC7B,SACEC,MAAM,EAENC,YAAY,QACP,wBAAwB;AAiE/B,MAAMC,aAAa,CAACC,UAClB;QAACA,QAAQC,MAAM;QAAED,QAAQE,aAAa;KAAC,CAACC,MAAM,CAACC,SAASC,IAAI,CAAC;AAE/D,MAAMC,YAAY,CAChBC,YACAC,SACAC,SACAT;QAGaO,MAAAA;IADb,MAAMG,WAAWF,QAAQG,GAAG,CAACJ,WAAWK,GAAG;IAC3C,MAAMC,QAAON,QAAAA,mBAAAA,WAAWO,IAAI,YAAfP,mBAAmBG,4BAAAA,SAAUK,EAAE,YAA/BR,OAAmCA,WAAWK,GAAG;IAC9D,MAAMI,aAAaT,WAAWS,UAAU,oBAArBT,WAAWS,UAAU,MAArBT,YAAwBE;IAC3C,OAAO;QACLG,KAAKL,WAAWK,GAAG;QACnBE,MAAMd,YAAYiB,YAAYJ,OAAO,GAAGd,WAAWC,SAAS,CAAC,EAAEa,MAAM;QACrEK,WAAW,WAAER,4BAAAA,SAAUQ,WAAW,oBAAI;OAClClB,YAAYiB,YAAY,CAAC,IAAI;QAAEjB;IAAQ,GACvCU,CAAAA,4BAAAA,SAAUS,WAAW,MAAKF,YAC1B,CAAC,IACD;QAAEE,aAAaT,SAASS,WAAW;IAAC,GACpCT,CAAAA,4BAAAA,SAAUU,IAAI,MAAKH,YAAY,CAAC,IAAI;QAAEG,MAAMV,SAASU,IAAI;IAAC,GAC1DV,CAAAA,4BAAAA,SAAUW,YAAY,M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M,CAAC,CAAC,CAAC,EACzDtD,IAAI,CAAC,OAEXA,IAAI,CAAC;AAEhB,EAAE"}
@@ -0,0 +1,2 @@
1
+ export * from './compose.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/compose/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from './compose.js';
2
+
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/compose/index.ts"],"sourcesContent":["export * from './compose.js';\n"],"names":[],"mappings":"AAAA,cAAc,eAAe"}
@@ -0,0 +1,51 @@
1
+ import { type FragmentDescriptor } from './fragment.js';
2
+ /** Every fragment a host composes flows from, by pinned reference. */
3
+ export interface FragmentCatalog {
4
+ readonly get: (ref: string) => FragmentDescriptor | undefined;
5
+ readonly refs: readonly string[];
6
+ readonly fragments: readonly FragmentDescriptor[];
7
+ }
8
+ /**
9
+ * Assembles a catalog. Two fragments claiming one `id@version` throw: a pinned
10
+ * reference must name exactly one contract, or a slip pinned to it means
11
+ * whichever module happened to load last.
12
+ */
13
+ export declare const defineCatalog: (fragments: readonly FragmentDescriptor[]) => FragmentCatalog;
14
+ /**
15
+ * The catalog as a JSON document: every fragment with its contract as JSON
16
+ * Schema and its fingerprint, ordered by reference so it is snapshot-stable. It
17
+ * is what a CI check diffs, and what a register check reads without importing
18
+ * the packages that declare the fragments.
19
+ */
20
+ export declare const catalogDocument: (catalog: FragmentCatalog) => {
21
+ fragments: {
22
+ readOnly: boolean;
23
+ irreversible: boolean;
24
+ isolation: import("./fragment.js").FragmentIsolation;
25
+ requires: import("./fragment.js").FragmentRequirements;
26
+ excludedFrom: Readonly<Record<string, readonly string[]>>;
27
+ consumes: {
28
+ [k: string]: unknown;
29
+ };
30
+ provides: {
31
+ [k: string]: unknown;
32
+ };
33
+ contract: {
34
+ input: unknown;
35
+ output: unknown;
36
+ failure: unknown;
37
+ };
38
+ fingerprint: string;
39
+ compensation?: import("./fragment.js").FragmentCall | undefined;
40
+ call?: import("./fragment.js").FragmentCall | undefined;
41
+ participant?: string | undefined;
42
+ ref: string;
43
+ id: string;
44
+ version: number;
45
+ module: string;
46
+ kind: import("./fragment.js").FragmentKind;
47
+ cardinality: import("./fragment.js").FragmentCardinality;
48
+ }[];
49
+ };
50
+ export type CatalogDocument = ReturnType<typeof catalogDocument>;
51
+ //# sourceMappingURL=catalog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../src/flow/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,kBAAkB,EAKxB,MAAM,eAAe,CAAC;AAEvB,sEAAsE;AACtE,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,kBAAkB,GAAG,SAAS,CAAC;IAC9D,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;IACjC,QAAQ,CAAC,SAAS,EAAE,SAAS,kBAAkB,EAAE,CAAC;CACnD;AAED;;;;GAIG;AACH,eAAO,MAAM,aAAa,GACxB,WAAW,SAAS,kBAAkB,EAAE,KACvC,eAkBF,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,eAAe,GAAI,SAAS,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BtD,CAAC;AAEH,MAAM,MAAM,eAAe,GAAG,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC"}
@@ -0,0 +1,63 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ import { fragmentFingerprint, fragmentRef, jsonSchemaOf, keysDocument } from './fragment.js';
3
+ /**
4
+ * Assembles a catalog. Two fragments claiming one `id@version` throw: a pinned
5
+ * reference must name exactly one contract, or a slip pinned to it means
6
+ * whichever module happened to load last.
7
+ */ export const defineCatalog = (fragments)=>{
8
+ const byRef = new Map();
9
+ for (const fragment of fragments){
10
+ const ref = fragmentRef(fragment);
11
+ const existing = byRef.get(ref);
12
+ if (existing !== undefined && existing !== fragment) throw new Error(`fragment '${ref}' is declared twice, by '${existing.module}' and '${fragment.module}'. ` + 'A pinned reference names one contract: bump one of them.');
13
+ byRef.set(ref, fragment);
14
+ }
15
+ const refs = [
16
+ ...byRef.keys()
17
+ ].sort();
18
+ return {
19
+ get: (ref)=>byRef.get(ref),
20
+ refs,
21
+ fragments: refs.map((ref)=>byRef.get(ref))
22
+ };
23
+ };
24
+ /**
25
+ * The catalog as a JSON document: every fragment with its contract as JSON
26
+ * Schema and its fingerprint, ordered by reference so it is snapshot-stable. It
27
+ * is what a CI check diffs, and what a register check reads without importing
28
+ * the packages that declare the fragments.
29
+ */ export const catalogDocument = (catalog)=>({
30
+ fragments: catalog.fragments.map((fragment)=>{
31
+ var _fragment_readOnly, _fragment_irreversible, _fragment_isolation, _fragment_requires, _fragment_excludedFrom;
32
+ return _extends({
33
+ ref: fragmentRef(fragment),
34
+ id: fragment.id,
35
+ version: fragment.version,
36
+ module: fragment.module,
37
+ kind: fragment.kind,
38
+ cardinality: fragment.cardinality
39
+ }, fragment.participant === undefined ? {} : {
40
+ participant: fragment.participant
41
+ }, fragment.call === undefined ? {} : {
42
+ call: fragment.call
43
+ }, fragment.compensation === undefined ? {} : {
44
+ compensation: fragment.compensation
45
+ }, {
46
+ readOnly: (_fragment_readOnly = fragment.readOnly) != null ? _fragment_readOnly : false,
47
+ irreversible: (_fragment_irreversible = fragment.irreversible) != null ? _fragment_irreversible : false,
48
+ isolation: (_fragment_isolation = fragment.isolation) != null ? _fragment_isolation : 'none',
49
+ requires: (_fragment_requires = fragment.requires) != null ? _fragment_requires : {},
50
+ excludedFrom: (_fragment_excludedFrom = fragment.excludedFrom) != null ? _fragment_excludedFrom : {},
51
+ consumes: keysDocument(fragment.consumes),
52
+ provides: keysDocument(fragment.provides),
53
+ contract: {
54
+ input: jsonSchemaOf(fragment.contract.input),
55
+ output: jsonSchemaOf(fragment.contract.output),
56
+ failure: jsonSchemaOf(fragment.contract.failure)
57
+ },
58
+ fingerprint: fragmentFingerprint(fragment)
59
+ });
60
+ })
61
+ });
62
+
63
+ //# sourceMappingURL=catalog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/flow/catalog.ts"],"sourcesContent":["import {\n type FragmentDescriptor,\n fragmentFingerprint,\n fragmentRef,\n jsonSchemaOf,\n keysDocument,\n} from './fragment.js';\n\n/** Every fragment a host composes flows from, by pinned reference. */\nexport interface FragmentCatalog {\n readonly get: (ref: string) => FragmentDescriptor | undefined;\n readonly refs: readonly string[];\n readonly fragments: readonly FragmentDescriptor[];\n}\n\n/**\n * Assembles a catalog. Two fragments claiming one `id@version` throw: a pinned\n * reference must name exactly one contract, or a slip pinned to it means\n * whichever module happened to load last.\n */\nexport const defineCatalog = (\n fragments: readonly FragmentDescriptor[],\n): FragmentCatalog => {\n const byRef = new Map<string, FragmentDescriptor>();\n for (const fragment of fragments) {\n const ref = fragmentRef(fragment);\n const existing = byRef.get(ref);\n if (existing !== undefined && existing !== fragment)\n throw new Error(\n `fragment '${ref}' is declared twice, by '${existing.module}' and '${fragment.module}'. ` +\n 'A pinned reference names one contract: bump one of them.',\n );\n byRef.set(ref, fragment);\n }\n const refs = [...byRef.keys()].sort();\n return {\n get: ref => byRef.get(ref),\n refs,\n fragments: refs.map(ref => byRef.get(ref) as FragmentDescriptor),\n };\n};\n\n/**\n * The catalog as a JSON document: every fragment with its contract as JSON\n * Schema and its fingerprint, ordered by reference so it is snapshot-stable. It\n * is what a CI check diffs, and what a register check reads without importing\n * the packages that declare the fragments.\n */\nexport const catalogDocument = (catalog: FragmentCatalog) => ({\n fragments: catalog.fragments.map(fragment => ({\n ref: fragmentRef(fragment),\n id: fragment.id,\n version: fragment.version,\n module: fragment.module,\n kind: fragment.kind,\n cardinality: fragment.cardinality,\n ...(fragment.participant === undefined\n ? {}\n : { participant: fragment.participant }),\n ...(fragment.call === undefined ? {} : { call: fragment.call }),\n ...(fragment.compensation === undefined\n ? {}\n : { compensation: fragment.compensation }),\n readOnly: fragment.readOnly ?? false,\n irreversible: fragment.irreversible ?? false,\n isolation: fragment.isolation ?? 'none',\n requires: fragment.requires ?? {},\n excludedFrom: fragment.excludedFrom ?? {},\n consumes: keysDocument(fragment.consumes),\n provides: keysDocument(fragment.provides),\n contract: {\n input: jsonSchemaOf(fragment.contract.input),\n output: jsonSchemaOf(fragment.contract.output),\n failure: jsonSchemaOf(fragment.contract.failure),\n },\n fingerprint: fragmentFingerprint(fragment),\n })),\n});\n\nexport type CatalogDocument = ReturnType<typeof catalogDocument>;\n"],"names":["fragmentFingerprint","fragmentRef","jsonSchemaOf","keysDocument","defineCatalog","fragments","byRef","Map","fragment","ref","existing","get","undefined","Error","module","set","refs","keys","sort","map","catalogDocument","catalog","id","version","kind","cardinality","participant","call","compensation","readOnly","irreversible","isolation","requires","excludedFrom","consumes","provides","contract","input","output","failure","fingerprint"],"mappings":";AAAA,SAEEA,mBAAmB,EACnBC,WAAW,EACXC,YAAY,EACZC,YAAY,QACP,gBAAgB;AASvB;;;;CAIC,GACD,OAAO,MAAMC,gBAAgB,CAC3BC;IAEA,MAAMC,QAAQ,IAAIC;IAClB,KAAK,MAAMC,YAAYH,UAAW;QAChC,MAAMI,MAAMR,YAAYO;QACxB,MAAME,WAAWJ,MAAMK,GAAG,CAACF;QAC3B,IAAIC,aAAaE,aAAaF,aAAaF,UACzC,MAAM,IAAIK,MACR,CAAC,UAAU,EAAEJ,IAAI,yBAAyB,EAAEC,SAASI,MAAM,CAAC,OAAO,EAAEN,SAASM,MAAM,CAAC,GAAG,CAAC,GACvF;QAENR,MAAMS,GAAG,CAACN,KAAKD;IACjB;IACA,MAAMQ,OAAO;WAAIV,MAAMW,IAAI;KAAG,CAACC,IAAI;IACnC,OAAO;QACLP,KAAKF,CAAAA,MAAOH,MAAMK,GAAG,CAACF;QACtBO;QACAX,WAAWW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;gBACjD;gBACAC,aAAaxC,oBAAoBQ;;;IAErC,CAAA,EAAG"}
@@ -0,0 +1,105 @@
1
+ import { Schema } from 'effect';
2
+ /**
3
+ * How a step behaves when a later one fails
4
+ * ([ADR 0015](../../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)).
5
+ *
6
+ * - `compensatable` — can be undone, so it sits before the commit point;
7
+ * - `pivot` — the point of no return, at most one per slip;
8
+ * - `retriable` — after the commit point, retried until it succeeds;
9
+ * - `wait` — a durable wait for a signal, after the commit point.
10
+ */
11
+ export type FragmentKind = 'compensatable' | 'pivot' | 'retriable' | 'wait';
12
+ /** How many calls one step makes: one, one per vendor segment, or one per line. */
13
+ export type FragmentCardinality = 'one' | 'perVendor' | 'perLine';
14
+ /**
15
+ * The countermeasure a step relies on for the isolation a saga lacks — what
16
+ * keeps a concurrent flow from seeing, or undoing, its intermediate state.
17
+ */
18
+ export type FragmentIsolation = 'commutative' | 'semanticLock' | 'reRead' | 'pessimisticView' | 'versionFile' | 'none';
19
+ /** One HTTP call a step makes on its participant: the public path, never a template. */
20
+ export interface FragmentCall {
21
+ readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
22
+ readonly path: `/${string}`;
23
+ }
24
+ /** The facts of a verified context a step may require. */
25
+ export interface FragmentRequirements {
26
+ readonly entitlements?: readonly string[];
27
+ readonly roles?: readonly string[];
28
+ readonly partyRoles?: readonly string[];
29
+ readonly channels?: readonly string[];
30
+ }
31
+ /** A step's contract, as Schemas: what it is given, answers, and refuses with. */
32
+ export interface FragmentContract<I, O, F> {
33
+ readonly input: Schema.Codec<I, unknown>;
34
+ readonly output: Schema.Codec<O, unknown>;
35
+ readonly failure: Schema.Codec<F, unknown>;
36
+ }
37
+ /** Keys a step reads from earlier steps, or makes available to later ones. */
38
+ export type FragmentKeys = Readonly<Record<string, Schema.Codec<unknown, unknown>>>;
39
+ /**
40
+ * One step a module contributes to a flow, declared beside the use case it
41
+ * calls. Versioned (`id@version`) and typed, so a contract change without a
42
+ * version bump is visible to a catalog snapshot before it reaches a running
43
+ * flow.
44
+ */
45
+ export interface FragmentDescriptor<I = unknown, O = unknown, F = unknown> {
46
+ readonly id: string;
47
+ readonly version: number;
48
+ /** The module that owns the step — its domain. */
49
+ readonly module: string;
50
+ readonly kind: FragmentKind;
51
+ /** The service the step calls. Absent only on a marker such as `flow.commit@1`. */
52
+ readonly participant?: string;
53
+ readonly call?: FragmentCall;
54
+ /** Required on a compensatable step unless it is `readOnly`; forbidden otherwise. */
55
+ readonly compensation?: FragmentCall;
56
+ /** A compensatable step that changes nothing, and so has nothing to undo. */
57
+ readonly readOnly?: boolean;
58
+ readonly contract: FragmentContract<I, O, F>;
59
+ readonly requires?: FragmentRequirements;
60
+ readonly consumes?: FragmentKeys;
61
+ readonly provides?: FragmentKeys;
62
+ /** A step whose effect no compensation can reverse — money moved, goods shipped. */
63
+ readonly irreversible?: boolean;
64
+ readonly isolation?: FragmentIsolation;
65
+ readonly cardinality: FragmentCardinality;
66
+ /**
67
+ * Segments this step may not run in, by tag. A card capture excludes the
68
+ * cash-on-delivery segment; the framework names neither.
69
+ */
70
+ readonly excludedFrom?: Readonly<Record<string, readonly string[]>>;
71
+ }
72
+ /** The pinned reference a slip carries: `stock.reserve@1`. */
73
+ export declare const fragmentRef: (fragment: {
74
+ readonly id: string;
75
+ readonly version: number;
76
+ }) => string;
77
+ /**
78
+ * Declares a fragment, checking its shape at module load: a malformed
79
+ * descriptor is a programming error and fails the boot, not the first flow
80
+ * that reaches it. What depends on *other* fragments — order, inputs, the
81
+ * commit point — is the validator's, over a whole slip.
82
+ */
83
+ export declare const defineFragment: <I, O, F>(fragment: FragmentDescriptor<I, O, F>) => FragmentDescriptor<I, O, F>;
84
+ /**
85
+ * The commit point of a flow that has no real pivot: a pivot with no
86
+ * participant and no call. A cash-on-delivery checkout takes no money, and
87
+ * still needs a line past which its stock conversions are retried rather than
88
+ * compensated.
89
+ */
90
+ export declare const flowCommit: FragmentDescriptor<unknown, unknown, never>;
91
+ /** The JSON Schema of a codec, as a plain object. */
92
+ export declare const jsonSchemaOf: (schema: Schema.Codec<unknown, unknown>) => unknown;
93
+ /** Consumed or provided keys as JSON Schema, ordered by key. */
94
+ export declare const keysDocument: (keys: FragmentKeys | undefined) => {
95
+ [k: string]: unknown;
96
+ };
97
+ /**
98
+ * A fingerprint of what a fragment promises: its contract and the keys it
99
+ * consumes and provides. It changes when any of those change and on nothing
100
+ * else, so renaming a module or rewording a description never looks like a
101
+ * contract change — and a contract change without a version bump fails the
102
+ * catalog snapshot.
103
+ */
104
+ export declare const fragmentFingerprint: (fragment: FragmentDescriptor) => string;
105
+ //# sourceMappingURL=fragment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fragment.d.ts","sourceRoot":"","sources":["../../src/flow/fragment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC;;;;;;;;GAQG;AACH,MAAM,MAAM,YAAY,GAAG,eAAe,GAAG,OAAO,GAAG,WAAW,GAAG,MAAM,CAAC;AAE5E,mFAAmF;AACnF,MAAM,MAAM,mBAAmB,GAAG,KAAK,GAAG,WAAW,GAAG,SAAS,CAAC;AAElE;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GACzB,aAAa,GACb,cAAc,GACd,QAAQ,GACR,iBAAiB,GACjB,aAAa,GACb,MAAM,CAAC;AAEX,wFAAwF;AACxF,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAC;IAC7D,QAAQ,CAAC,IAAI,EAAE,IAAI,MAAM,EAAE,CAAC;CAC7B;AAED,0DAA0D;AAC1D,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,QAAQ,CAAC,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAA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/** The pinned reference a slip carries: `stock.reserve@1`. */ export const fragmentRef = (fragment)=>`${fragment.id}@${String(fragment.version)}`;
3
+ /** `domain.verb`, lower kebab, at least two segments. */ const FRAGMENT_ID = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
4
+ const shapeProblems = (fragment)=>{
5
+ const problems = [];
6
+ if (!FRAGMENT_ID.test(fragment.id)) problems.push(`its id must be 'domain.verb' in lower kebab case`);
7
+ if (!Number.isInteger(fragment.version) || fragment.version < 1) problems.push('its version must be a positive integer');
8
+ const marker = fragment.participant === undefined && fragment.call === undefined;
9
+ if (!marker && (fragment.participant === undefined || fragment.call === undefined)) problems.push('it names a participant and a call together, or neither');
10
+ if (marker && fragment.kind !== 'pivot') problems.push('only a pivot may be a marker with no participant and no call');
11
+ if (fragment.kind === 'compensatable') {
12
+ if (fragment.compensation === undefined && fragment.readOnly !== true) problems.push('a compensatable step declares its compensation, or is readOnly');
13
+ } else if (fragment.compensation !== undefined) {
14
+ problems.push(`a ${fragment.kind} step cannot declare a compensation`);
15
+ }
16
+ if (fragment.irreversible === true && fragment.kind === 'compensatable') problems.push('a compensatable step cannot be irreversible');
17
+ return problems;
18
+ };
19
+ /**
20
+ * Declares a fragment, checking its shape at module load: a malformed
21
+ * descriptor is a programming error and fails the boot, not the first flow
22
+ * that reaches it. What depends on *other* fragments — order, inputs, the
23
+ * commit point — is the validator's, over a whole slip.
24
+ */ export const defineFragment = (fragment)=>{
25
+ const problems = shapeProblems(fragment);
26
+ if (problems.length > 0) throw new Error(`fragment '${fragment.id}@${String(fragment.version)}' is malformed: ${problems.join('; ')}`);
27
+ return fragment;
28
+ };
29
+ /**
30
+ * The commit point of a flow that has no real pivot: a pivot with no
31
+ * participant and no call. A cash-on-delivery checkout takes no money, and
32
+ * still needs a line past which its stock conversions are retried rather than
33
+ * compensated.
34
+ */ export const flowCommit = defineFragment({
35
+ id: 'flow.commit',
36
+ version: 1,
37
+ module: 'flow',
38
+ kind: 'pivot',
39
+ cardinality: 'one',
40
+ contract: {
41
+ input: Schema.Unknown,
42
+ output: Schema.Unknown,
43
+ failure: Schema.Never
44
+ }
45
+ });
46
+ /** A stable 53-bit hash of a string, as hex — enough to see that a contract moved. */ const hash = (text)=>{
47
+ let h1 = 0xdeadbeef;
48
+ let h2 = 0x41c6ce57;
49
+ for(let index = 0; index < text.length; index += 1){
50
+ const code = text.charCodeAt(index);
51
+ h1 = Math.imul(h1 ^ code, 2654435761);
52
+ h2 = Math.imul(h2 ^ code, 1597334677);
53
+ }
54
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
55
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
56
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0');
57
+ };
58
+ /** The JSON Schema of a codec, as a plain object. */ export const jsonSchemaOf = (schema)=>Schema.toJsonSchemaDocument(schema);
59
+ /** Consumed or provided keys as JSON Schema, ordered by key. */ export const keysDocument = (keys)=>Object.fromEntries(Object.entries(keys != null ? keys : {}).sort(([a], [b])=>a.localeCompare(b)).map(([key, schema])=>[
60
+ key,
61
+ jsonSchemaOf(schema)
62
+ ]));
63
+ /**
64
+ * A fingerprint of what a fragment promises: its contract and the keys it
65
+ * consumes and provides. It changes when any of those change and on nothing
66
+ * else, so renaming a module or rewording a description never looks like a
67
+ * contract change — and a contract change without a version bump fails the
68
+ * catalog snapshot.
69
+ */ export const fragmentFingerprint = (fragment)=>hash(JSON.stringify({
70
+ input: jsonSchemaOf(fragment.contract.input),
71
+ output: jsonSchemaOf(fragment.contract.output),
72
+ failure: jsonSchemaOf(fragment.contract.failure),
73
+ consumes: keysDocument(fragment.consumes),
74
+ provides: keysDocument(fragment.provides)
75
+ }));
76
+
77
+ //# sourceMappingURL=fragment.js.map