@entifix/transactions 0.1.0-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 (86) hide show
  1. package/LICENSE +21 -0
  2. package/dist/contracts/command.d.ts +59 -0
  3. package/dist/contracts/command.d.ts.map +1 -0
  4. package/dist/contracts/command.js +42 -0
  5. package/dist/contracts/command.js.map +1 -0
  6. package/dist/contracts/event.d.ts +84 -0
  7. package/dist/contracts/event.d.ts.map +1 -0
  8. package/dist/contracts/event.js +67 -0
  9. package/dist/contracts/event.js.map +1 -0
  10. package/dist/contracts/inbox.d.ts +80 -0
  11. package/dist/contracts/inbox.d.ts.map +1 -0
  12. package/dist/contracts/inbox.js +5 -0
  13. package/dist/contracts/inbox.js.map +1 -0
  14. package/dist/contracts/outbox.d.ts +137 -0
  15. package/dist/contracts/outbox.d.ts.map +1 -0
  16. package/dist/contracts/outbox.js +5 -0
  17. package/dist/contracts/outbox.js.map +1 -0
  18. package/dist/contracts/record.d.ts +108 -0
  19. package/dist/contracts/record.d.ts.map +1 -0
  20. package/dist/contracts/record.js +27 -0
  21. package/dist/contracts/record.js.map +1 -0
  22. package/dist/contracts/saga-definition.d.ts +186 -0
  23. package/dist/contracts/saga-definition.d.ts.map +1 -0
  24. package/dist/contracts/saga-definition.js +95 -0
  25. package/dist/contracts/saga-definition.js.map +1 -0
  26. package/dist/engine/resolve-template.d.ts +49 -0
  27. package/dist/engine/resolve-template.d.ts.map +1 -0
  28. package/dist/engine/resolve-template.js +106 -0
  29. package/dist/engine/resolve-template.js.map +1 -0
  30. package/dist/engine/run-saga.d.ts +55 -0
  31. package/dist/engine/run-saga.d.ts.map +1 -0
  32. package/dist/engine/run-saga.js +467 -0
  33. package/dist/engine/run-saga.js.map +1 -0
  34. package/dist/engine/run-transaction.d.ts +55 -0
  35. package/dist/engine/run-transaction.d.ts.map +1 -0
  36. package/dist/engine/run-transaction.js +101 -0
  37. package/dist/engine/run-transaction.js.map +1 -0
  38. package/dist/index.d.ts +21 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +22 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/mixins/transaction-mixins.d.ts +20 -0
  43. package/dist/mixins/transaction-mixins.d.ts.map +1 -0
  44. package/dist/mixins/transaction-mixins.js +13 -0
  45. package/dist/mixins/transaction-mixins.js.map +1 -0
  46. package/dist/ports/event-bus.d.ts +98 -0
  47. package/dist/ports/event-bus.d.ts.map +1 -0
  48. package/dist/ports/event-bus.js +5 -0
  49. package/dist/ports/event-bus.js.map +1 -0
  50. package/dist/ports/event-source.d.ts +22 -0
  51. package/dist/ports/event-source.d.ts.map +1 -0
  52. package/dist/ports/event-source.js +20 -0
  53. package/dist/ports/event-source.js.map +1 -0
  54. package/dist/ports/lock-service.d.ts +24 -0
  55. package/dist/ports/lock-service.d.ts.map +1 -0
  56. package/dist/ports/lock-service.js +5 -0
  57. package/dist/ports/lock-service.js.map +1 -0
  58. package/dist/ports/saga-dispatcher.d.ts +47 -0
  59. package/dist/ports/saga-dispatcher.d.ts.map +1 -0
  60. package/dist/ports/saga-dispatcher.js +5 -0
  61. package/dist/ports/saga-dispatcher.js.map +1 -0
  62. package/dist/ports/saga-store.d.ts +98 -0
  63. package/dist/ports/saga-store.d.ts.map +1 -0
  64. package/dist/ports/saga-store.js +20 -0
  65. package/dist/ports/saga-store.js.map +1 -0
  66. package/dist/ports/sequence-service.d.ts +17 -0
  67. package/dist/ports/sequence-service.d.ts.map +1 -0
  68. package/dist/ports/sequence-service.js +5 -0
  69. package/dist/ports/sequence-service.js.map +1 -0
  70. package/dist/ports/transaction-handler.d.ts +68 -0
  71. package/dist/ports/transaction-handler.d.ts.map +1 -0
  72. package/dist/ports/transaction-handler.js +5 -0
  73. package/dist/ports/transaction-handler.js.map +1 -0
  74. package/dist/ports/transaction-sink.d.ts +119 -0
  75. package/dist/ports/transaction-sink.d.ts.map +1 -0
  76. package/dist/ports/transaction-sink.js +28 -0
  77. package/dist/ports/transaction-sink.js.map +1 -0
  78. package/dist/stream/transaction-stream-hub.d.ts +41 -0
  79. package/dist/stream/transaction-stream-hub.d.ts.map +1 -0
  80. package/dist/stream/transaction-stream-hub.js +53 -0
  81. package/dist/stream/transaction-stream-hub.js.map +1 -0
  82. package/dist/use-case/facade.uc.d.ts +22 -0
  83. package/dist/use-case/facade.uc.d.ts.map +1 -0
  84. package/dist/use-case/facade.uc.js +55 -0
  85. package/dist/use-case/facade.uc.js.map +1 -0
  86. package/package.json +65 -0
@@ -0,0 +1,108 @@
1
+ import { type EntifixConnError, type EntifixError, type EntityId } from '@entifix/core';
2
+ import { Context, Effect } from 'effect';
3
+ import type { TransactionEvent, TransactionState } from './event.js';
4
+ /**
5
+ * The the saga tracker's persisted view of a transaction, folded from the
6
+ * events it observes. It is the source of truth a client polls.
7
+ */
8
+ export interface TransactionRecord {
9
+ transactionId: string;
10
+ entity: string;
11
+ state: TransactionState;
12
+ code?: string;
13
+ entityId?: EntityId;
14
+ error?: string;
15
+ createdAt: string;
16
+ updatedAt: string;
17
+ /**
18
+ * Whose organization this transaction happened in, folded from the event.
19
+ *
20
+ * The `saga` store is control-plane and single-partition — it holds every
21
+ * organization's records by design — so isolation on the read routes has to be
22
+ * this filter. A record written before the member existed carries none and is
23
+ * therefore readable by nobody, which is the direction to fail (ADR 0036).
24
+ */
25
+ organizationId?: string;
26
+ }
27
+ /**
28
+ * Port the manager tracks transactions through. Implemented over Mongo in the
29
+ * service; framework-free here so the engine/manager stay environment-agnostic.
30
+ */
31
+ export interface TransactionStore {
32
+ /** Folds an event into the record, creating it on first sight. */
33
+ upsertFromEvent(event: TransactionEvent): Effect.Effect<TransactionRecord, EntifixConnError>;
34
+ get(transactionId: string): Effect.Effect<TransactionRecord | undefined, EntifixConnError>;
35
+ /** Non-terminal records not updated within `olderThanMs` — recovery input. */
36
+ findStale(olderThanMs: number): Effect.Effect<readonly TransactionRecord[], EntifixConnError>;
37
+ markStale(transactionId: string): Effect.Effect<void, EntifixConnError>;
38
+ /**
39
+ * How many records sit in each state — the recovery sweep samples it.
40
+ *
41
+ * ⚠️ **This is a count, and is not the `list` above.** It returns no record,
42
+ * no id and no organization, so it does not reopen the surface #194 deleted
43
+ * `GET /api/transaction` for: an unfiltered *listing* of this store is every
44
+ * organization's transactions, while a total of how many are `STALE` is a
45
+ * fleet health number that names nobody. The distinction is the whole reason
46
+ * one is here and the other is refused.
47
+ *
48
+ * It exists so `STALE` is something a dashboard shows rather than something a
49
+ * poll discovers — which is what the recovery sweep, whose only action is to
50
+ * apply that label, otherwise leaves entirely unobservable.
51
+ */
52
+ countByState(): Effect.Effect<Record<TransactionState, number>, EntifixConnError>;
53
+ }
54
+ declare const TransactionStoreTag_base: Context.TagClass<TransactionStoreTag, "TransactionStoreTag", TransactionStore>;
55
+ export declare class TransactionStoreTag extends TransactionStoreTag_base {
56
+ }
57
+ /**
58
+ * What a service answers a `202` with: the id to poll, and the state it starts
59
+ * in.
60
+ *
61
+ * ⚠️ **Not a {@link TransactionRecord}, which is why it has its own
62
+ * discriminant.** Nothing has been folded yet — there is no `createdAt`, no
63
+ * entity id, and no code, because the write has not run. Framing it as a record
64
+ * meant the browser's accept-shape assertion was checking a name that the
65
+ * by-id route and the bus payload also answered to, so it asserted nothing it
66
+ * claimed to (#176,
67
+ * [ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).
68
+ */
69
+ export interface TransactionAccepted {
70
+ transactionId: string;
71
+ state: TransactionState;
72
+ }
73
+ /**
74
+ * Parses a `202` accept body, for a browser about to start polling.
75
+ *
76
+ * Read for its **shape**, not its contents: it asserts the service really
77
+ * accepted a transaction rather than answering something else with a `2xx`.
78
+ */
79
+ export declare function readTransactionAcceptedEnvelope(body: unknown): Effect.Effect<TransactionAccepted, EntifixError>;
80
+ /**
81
+ * Parses the tracker's by-id response, which frames a {@link TransactionRecord}.
82
+ *
83
+ * ⚠️ **`readEnvelope` validates the discriminant and then *casts* the payload**
84
+ * — it checks no members. So a discriminant shared by two shapes hands back
85
+ * whichever one the caller asked for, typed and wrong: a record read as an
86
+ * event has no `step`, no `at`, and a `state` the caller is about to branch on.
87
+ * That is the reason the four transaction-shaped discriminants are four.
88
+ */
89
+ export declare function readTransactionRecordEnvelope(body: unknown): Effect.Effect<TransactionRecord, EntifixError>;
90
+ /**
91
+ * Reads one transaction's record, for a browser reconciling a write it started.
92
+ *
93
+ * ⚠️ **`undefined` means _not tracked yet_, not _failed_.** `accepted` reaches
94
+ * the tracker over the bus, so with the broker down the entity write commits —
95
+ * the outbox is in the same Mongo transaction — while no event is ever
96
+ * published and this answers `404`. That is a write in perfect health, and a
97
+ * caller that rolls back on it un-renders a record that is about to appear, at
98
+ * exactly the moment nobody can tell a UI bug from an outage. Only `FAILED` and
99
+ * `STALE` are terminal (ADR 0043).
100
+ */
101
+ export interface TransactionStatusReader {
102
+ read(transactionId: string): Effect.Effect<TransactionRecord | undefined, EntifixError>;
103
+ }
104
+ declare const TransactionStatusReaderTag_base: Context.TagClass<TransactionStatusReaderTag, "TransactionStatusReaderTag", TransactionStatusReader>;
105
+ export declare class TransactionStatusReaderTag extends TransactionStatusReaderTag_base {
106
+ }
107
+ export {};
108
+ //# sourceMappingURL=record.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"record.d.ts","sourceRoot":"","sources":["../../src/contracts/record.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,gBAAgB,EACrB,KAAK,YAAY,EACjB,KAAK,QAAQ,EAEd,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEzC,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAErE;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,gBAAgB,CAAC;IACxB,IAAI,CAAC,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iB,EAAE,YAAY,CAAC,CAShD;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,uBAAuB;IACtC,IAAI,CACF,aAAa,EAAE,MAAM,GACpB,MAAM,CAAC,MAAM,CAAC,iBAAiB,GAAG,SAAS,EAAE,YAAY,CAAC,CAAC;CAC/D;;AAED,qBAAa,0BAA2B,SAAQ,+BAEQ;CAAG"}
@@ -0,0 +1,27 @@
1
+ import { readEnvelope } from '@entifix/core';
2
+ import { Context, Effect } from 'effect';
3
+ export class TransactionStoreTag extends Context.Tag('TransactionStoreTag')() {
4
+ }
5
+ /**
6
+ * Parses a `202` accept body, for a browser about to start polling.
7
+ *
8
+ * Read for its **shape**, not its contents: it asserts the service really
9
+ * accepted a transaction rather than answering something else with a `2xx`.
10
+ */ export function readTransactionAcceptedEnvelope(body) {
11
+ return Effect.map(readEnvelope(body, 'transactionAccepted', 'transactionAccepted'), (envelope)=>envelope.data);
12
+ }
13
+ /**
14
+ * Parses the tracker's by-id response, which frames a {@link TransactionRecord}.
15
+ *
16
+ * ⚠️ **`readEnvelope` validates the discriminant and then *casts* the payload**
17
+ * — it checks no members. So a discriminant shared by two shapes hands back
18
+ * whichever one the caller asked for, typed and wrong: a record read as an
19
+ * event has no `step`, no `at`, and a `state` the caller is about to branch on.
20
+ * That is the reason the four transaction-shaped discriminants are four.
21
+ */ export function readTransactionRecordEnvelope(body) {
22
+ return Effect.map(readEnvelope(body, 'transactionRecord', 'transactionRecord'), (envelope)=>envelope.data);
23
+ }
24
+ export class TransactionStatusReaderTag extends Context.Tag('TransactionStatusReaderTag')() {
25
+ }
26
+
27
+ //# sourceMappingURL=record.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/contracts/record.ts"],"sourcesContent":["import {\n type EntifixConnError,\n type EntifixError,\n type EntityId,\n readEnvelope,\n} from '@entifix/core';\nimport { Context, Effect } from 'effect';\n\nimport type { TransactionEvent, TransactionState } from './event.js';\n\n/**\n * The the saga tracker's persisted view of a transaction, folded from the\n * events it observes. It is the source of truth a client polls.\n */\nexport interface TransactionRecord {\n transactionId: string;\n entity: string;\n state: TransactionState;\n code?: string;\n entityId?: EntityId;\n error?: string;\n createdAt: string;\n updatedAt: string;\n /**\n * Whose organization this transaction happened in, folded from the event.\n *\n * The `saga` store is control-plane and single-partition — it holds every\n * organization's records by design — so isolation on the read routes has to be\n * this filter. A record written before the member existed carries none and is\n * therefore readable by nobody, which is the direction to fail (ADR 0036).\n */\n organizationId?: string;\n}\n\n/**\n * Port the manager tracks transactions through. Implemented over Mongo in the\n * service; framework-free here so the engine/manager stay environment-agnostic.\n */\nexport interface TransactionStore {\n /** Folds an event into the record, creating it on first sight. */\n upsertFromEvent(\n event: TransactionEvent,\n ): Effect.Effect<TransactionRecord, EntifixConnError>;\n get(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, EntifixConnError>;\n // There is deliberately no `list`. The `saga` store is control-plane and\n // single-partition, so an unfiltered index is every organization's\n // transactions — which is the surface #194 deleted `GET /api/transaction` for.\n // Anything that needs a set of records asks for one narrow enough to scope,\n // the way `findStale` does.\n /** Non-terminal records not updated within `olderThanMs` — recovery input. */\n findStale(\n olderThanMs: number,\n ): Effect.Effect<readonly TransactionRecord[], EntifixConnError>;\n markStale(transactionId: string): Effect.Effect<void, EntifixConnError>;\n /**\n * How many records sit in each state — the recovery sweep samples it.\n *\n * ⚠️ **This is a count, and is not the `list` above.** It returns no record,\n * no id and no organization, so it does not reopen the surface #194 deleted\n * `GET /api/transaction` for: an unfiltered *listing* of this store is every\n * organization's transactions, while a total of how many are `STALE` is a\n * fleet health number that names nobody. The distinction is the whole reason\n * one is here and the other is refused.\n *\n * It exists so `STALE` is something a dashboard shows rather than something a\n * poll discovers — which is what the recovery sweep, whose only action is to\n * apply that label, otherwise leaves entirely unobservable.\n */\n countByState(): Effect.Effect<\n Record<TransactionState, number>,\n EntifixConnError\n >;\n}\n\nexport class TransactionStoreTag extends Context.Tag('TransactionStoreTag')<\n TransactionStoreTag,\n TransactionStore\n>() {}\n\n/**\n * What a service answers a `202` with: the id to poll, and the state it starts\n * in.\n *\n * ⚠️ **Not a {@link TransactionRecord}, which is why it has its own\n * discriminant.** Nothing has been folded yet — there is no `createdAt`, no\n * entity id, and no code, because the write has not run. Framing it as a record\n * meant the browser's accept-shape assertion was checking a name that the\n * by-id route and the bus payload also answered to, so it asserted nothing it\n * claimed to (#176,\n * [ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\n */\nexport interface TransactionAccepted {\n transactionId: string;\n state: TransactionState;\n}\n\n/**\n * Parses a `202` accept body, for a browser about to start polling.\n *\n * Read for its **shape**, not its contents: it asserts the service really\n * accepted a transaction rather than answering something else with a `2xx`.\n */\nexport function readTransactionAcceptedEnvelope(\n body: unknown,\n): Effect.Effect<TransactionAccepted, EntifixError> {\n return Effect.map(\n readEnvelope<TransactionAccepted>(\n body,\n 'transactionAccepted',\n 'transactionAccepted',\n ),\n envelope => envelope.data,\n );\n}\n\n/**\n * Parses the tracker's by-id response, which frames a {@link TransactionRecord}.\n *\n * ⚠️ **`readEnvelope` validates the discriminant and then *casts* the payload**\n * — it checks no members. So a discriminant shared by two shapes hands back\n * whichever one the caller asked for, typed and wrong: a record read as an\n * event has no `step`, no `at`, and a `state` the caller is about to branch on.\n * That is the reason the four transaction-shaped discriminants are four.\n */\nexport function readTransactionRecordEnvelope(\n body: unknown,\n): Effect.Effect<TransactionRecord, EntifixError> {\n return Effect.map(\n readEnvelope<TransactionRecord>(\n body,\n 'transactionRecord',\n 'transactionRecord',\n ),\n envelope => envelope.data,\n );\n}\n\n/**\n * Reads one transaction's record, for a browser reconciling a write it started.\n *\n * ⚠️ **`undefined` means _not tracked yet_, not _failed_.** `accepted` reaches\n * the tracker over the bus, so with the broker down the entity write commits —\n * the outbox is in the same Mongo transaction — while no event is ever\n * published and this answers `404`. That is a write in perfect health, and a\n * caller that rolls back on it un-renders a record that is about to appear, at\n * exactly the moment nobody can tell a UI bug from an outage. Only `FAILED` and\n * `STALE` are terminal (ADR 0043).\n */\nexport interface TransactionStatusReader {\n read(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, EntifixError>;\n}\n\nexport class TransactionStatusReaderTag extends Context.Tag(\n 'TransactionStatusReaderTag',\n)<TransactionStatusReaderTag, TransactionStatusReader>() {}\n"],"names":["readEnvelope","Context","Effect","TransactionStoreTag","Tag","readTransactionAcceptedEnvelope","body","map","envelope","data","readTransactionRecordEnvelope","TransactionStatusReaderTag"],"mappings":"AAAA,SAIEA,YAAY,QACP,gBAAgB;AACvB,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AAsEzC,OAAO,MAAMC,4BAA4BF,QAAQG,GAAG,CAAC;AAGhD;AAmBL;;;;;CAKC,GACD,OAAO,SAASC,gCACdC,IAAa;IAEb,OAAOJ,OAAOK,GAAG,CACfP,aACEM,MACA,uBACA,wBAEFE,CAAAA,WAAYA,SAASC,IAAI;AAE7B;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC,8BACdJ,IAAa;IAEb,OAAOJ,OAAOK,GAAG,CACfP,aACEM,MACA,qBACA,sBAEFE,CAAAA,WAAYA,SAASC,IAAI;AAE7B;AAmBA,OAAO,MAAME,mCAAmCV,QAAQG,GAAG,CACzD;AACwD"}
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Richardson's classification, and adopting the vocabulary is most of the answer
3
+ * to "which steps are compensable at all"
4
+ * ([ADR 0039](../../../../../../docs/adr/0039-multi-step-sagas-are-orchestrated.md)).
5
+ *
6
+ * - `compensatable` — before the point of no return; a failure downstream
7
+ * reverses it.
8
+ * - `pivot` — the point of no return. Once it commits, the saga goes forward.
9
+ * - `retriable` — after the pivot; no compensation exists, so the only path is
10
+ * to retry until it succeeds.
11
+ */
12
+ export type SagaStepKind = 'compensatable' | 'pivot' | 'retriable';
13
+ /** The HTTP verbs a step may be dispatched with. */
14
+ export type SagaMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
15
+ /**
16
+ * One call a step makes, as a template rather than a closure.
17
+ *
18
+ * `path` may carry `{…}` placeholders resolved by field path against the step's
19
+ * recorded outcome — `/api/reservation/{outcome.data.id}`.
20
+ *
21
+ * ⚠️ **A template rather than a callback, and that is the constraint that
22
+ * shaped the whole type.** A callback would have to name the participant's
23
+ * types, and a `business:domain` package may not import another
24
+ * (`docs/_shared/layering.md`) — which is exactly the import that has no legal
25
+ * home and the reason ADR 0039 made a definition **data** in the first place.
26
+ */
27
+ export interface SagaCall {
28
+ readonly method: SagaMethod;
29
+ readonly path: string;
30
+ }
31
+ /** One step of a flow. */
32
+ export interface SagaStep {
33
+ /** Unique within the definition; half of the command id `<sagaId>:<stepId>`. */
34
+ readonly id: string;
35
+ /**
36
+ * Which service answers it, as a **configuration key** — never a URI.
37
+ *
38
+ * A URI in a definition is a deployment fact written into a business
39
+ * artifact, and it is what makes a definition untestable and un-relocatable.
40
+ * The same lookup yields the crossing token for that participant, so a
41
+ * definition carries no secret and never could
42
+ * ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).
43
+ */
44
+ readonly participant: string;
45
+ readonly command: SagaCall;
46
+ /** Required on a `compensatable` step, forbidden on every other kind. */
47
+ readonly compensation?: SagaCall;
48
+ readonly kind: SagaStepKind;
49
+ /**
50
+ * Dispatch one call per element of this step's input, rather than one call.
51
+ *
52
+ * ⚠️ **Cardinality is data, because it has to be.** Checkout reserves once per
53
+ * vendor and how many vendors is known only from the cart, so writing that as
54
+ * N steps would mean generating a definition per request — at which point it
55
+ * is no longer data, and ADR 0039's whole construction collapses back into the
56
+ * class that has no legal home.
57
+ *
58
+ * The consequence carried by {@link SagaStepOutcome}: **the unit of
59
+ * compensation is the call, not the step.** Five lines with three holds taken
60
+ * and the fourth refused must release exactly three.
61
+ */
62
+ readonly fanOut?: boolean;
63
+ /**
64
+ * Fan out over an **earlier step's successful calls** instead of over an
65
+ * input the caller supplied.
66
+ *
67
+ * ⚠️ **Without this a later step cannot address what an earlier one created**,
68
+ * and checkout is the case that proves it. `convert-reservation` needs one
69
+ * call per hold, addressed by the reservation id — which stock-service mints,
70
+ * so the caller cannot know it when it starts the flow. Supplying the ids as
71
+ * input is impossible, and generating a definition per request is the thing
72
+ * ADR 0039 exists to avoid.
73
+ *
74
+ * Each element inherits that call's `organizationId`, so a tenant-plane
75
+ * participant reaches the same tenant it did the first time, and the `path`
76
+ * template resolves against `{outcome.…}` — the same scope a compensation
77
+ * gets, for the same reason: the id being addressed is in the response body.
78
+ *
79
+ * Implies {@link fanOut}. It names a step that must appear **before** this one,
80
+ * and `defineSaga` refuses a forward or self reference at module load.
81
+ */
82
+ readonly fanOutFrom?: string;
83
+ }
84
+ /** A flow, as the data a generic engine walks. */
85
+ export interface SagaDefinition {
86
+ readonly name: string;
87
+ /**
88
+ * What a caller must hold to run this flow, as a `<domain>:<entity>:<action>`
89
+ * string.
90
+ *
91
+ * ⚠️ **On the definition rather than on the route**, so the route that runs a
92
+ * flow stays generic. The alternative was one permission for every saga, which
93
+ * would make "may run a flow" a single capability regardless of what the flow
94
+ * does — and checkout writes an order.
95
+ *
96
+ * It is a plain string here rather than authz's `Permission`: this package is
97
+ * `layer:entifix`, and `@entifix/authz` sits above it. The service that
98
+ * mounts the route resolves the string against
99
+ * `SERVICE_CROSSING_PERMISSIONS`, which is where the closed list belongs.
100
+ */
101
+ readonly permission: string;
102
+ readonly steps: readonly SagaStep[];
103
+ }
104
+ /** What one dispatched call returned, kept so its compensation can read it. */
105
+ export interface SagaCallOutcome {
106
+ /** The fan-out element this call was made for; `0` on a single-call step. */
107
+ readonly index: number;
108
+ readonly status: number;
109
+ readonly body: unknown;
110
+ /**
111
+ * The organization this call acted for, carried so its compensation acts on
112
+ * the same one.
113
+ *
114
+ * ⚠️ **Not derivable from the outcome, and its absence is silent.** A
115
+ * tenant-plane participant resolves its storage handle from
116
+ * `x-organization-id`, so a compensation dispatched without it is refused
117
+ * `400` — and the saga strands with every hold still in place while the
118
+ * engine reports it tried. Measured on the live lab: two holds taken, a third
119
+ * line refused, and both releases rejected for a missing header
120
+ * ([ADR 0023](../../../../../../docs/adr/0023-service-to-service-tenant-crossing.md)).
121
+ */
122
+ readonly organizationId?: string;
123
+ }
124
+ /**
125
+ * What one step is given to work with — one element per call on a `fanOut` step,
126
+ * exactly one otherwise.
127
+ */
128
+ export interface SagaStepInput {
129
+ /** The body to send. */
130
+ readonly body?: unknown;
131
+ /** ADR 0023's explicit organization, for a tenant-plane participant. */
132
+ readonly organizationId?: string;
133
+ }
134
+ /**
135
+ * The inputs each step needs, keyed by step id, supplied by the caller.
136
+ *
137
+ * ⚠️ **Here rather than in the engine**, because the durable instance carries
138
+ * it: a resumed walk is a different process reading this off the store, so the
139
+ * port that persists it may not reach up into the engine to name its type
140
+ * ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).
141
+ */
142
+ export type SagaInputs = Readonly<Record<string, readonly SagaStepInput[]>>;
143
+ /** Every call one step made, in dispatch order. */
144
+ export interface SagaStepOutcome {
145
+ readonly stepId: string;
146
+ readonly calls: readonly SagaCallOutcome[];
147
+ /**
148
+ * Why this step stopped, when it did — absent on a step that succeeded.
149
+ *
150
+ * ⚠️ **Without it a resumed walk cannot tell a finished step from a refused
151
+ * one.** `calls` holds what succeeded either way, so the two are
152
+ * indistinguishable on the stored document, and the distinction is what
153
+ * decides whether the pivot committed. Guessing it either compensates behind
154
+ * a capture or walks past a refusal
155
+ * ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).
156
+ */
157
+ readonly error?: string;
158
+ /**
159
+ * Whether this step's calls have already been given back.
160
+ *
161
+ * ⚠️ **What keeps a resumed unwind from compensating twice.** A second
162
+ * `DELETE` of an order already deleted answers `404`, which the dispatcher
163
+ * classifies as a refusal, which strands a flow that was in fact reversed.
164
+ */
165
+ readonly compensated?: boolean;
166
+ }
167
+ /**
168
+ * Validate a definition and return it, or throw.
169
+ *
170
+ * ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path
171
+ * is a fault that ships — the same reasoning ADR 0035 used for `collection` +
172
+ * `determining`. Every definition is therefore constructed through this
173
+ * function at module scope, and loaded in a spec: a definition that never loads
174
+ * is a definition that never fails.
175
+ */
176
+ export declare function defineSaga(definition: SagaDefinition): SagaDefinition;
177
+ /**
178
+ * The command id one call is dispatched under.
179
+ *
180
+ * `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,
181
+ * so #178's `TransactionInbox` serves saga steps with no second dedup store and
182
+ * no second key. A fan-out step appends the element index, because its calls are
183
+ * separate side effects that must each be claimed on their own.
184
+ */
185
+ export declare const sagaCommandId: (sagaId: string, stepId: string, index?: number) => string;
186
+ //# sourceMappingURL=saga-definition.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"saga-definition.d.ts","sourceRoot":"","sources":["../../src/contracts/saga-definition.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;GAUG;AACH,MAAM,MAAM,YAAY,GAAG,eAAe,GAAG,OAAO,GAAG,WAAW,CAAC;AAEnE,oDAAoD;AACpD,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAC;AAErE;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,QAAQ;IACvB,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAED,0BAA0B;AAC1B,MAAM,WAAW,QAAQ;IACvB,gFAAgF;IAChF,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB;;;;;;;;OAQG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC;IAC3B,yEAAyE;IACzE,QAAQ,CAAC,YAAY,CAAC,EAAE,QAAQ,CAAC;IACjC,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAC5B;;;;;;;;;;;;OA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CAAC,UAAU,EAAE,cAAc,GAAG,cAAc,CAoGrE;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,GACxB,QAAQ,MAAM,EACd,QAAQ,MAAM,EACd,QAAQ,MAAM,KACb,MAGyC,CAAC"}
@@ -0,0 +1,95 @@
1
+ import { EntifixLogicError } from '@entifix/core';
2
+ const fail = (definition, detail)=>{
3
+ throw new EntifixLogicError(`saga definition '${definition}' is invalid: ${detail}`, undefined, {
4
+ definition
5
+ });
6
+ };
7
+ /**
8
+ * Validate a definition and return it, or throw.
9
+ *
10
+ * ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path
11
+ * is a fault that ships — the same reasoning ADR 0035 used for `collection` +
12
+ * `determining`. Every definition is therefore constructed through this
13
+ * function at module scope, and loaded in a spec: a definition that never loads
14
+ * is a definition that never fails.
15
+ */ export function defineSaga(definition) {
16
+ const { name, steps } = definition;
17
+ if (steps.length === 0) {
18
+ fail(name, 'it declares no steps');
19
+ }
20
+ const seen = new Set();
21
+ for (const step of steps){
22
+ if (seen.has(step.id)) {
23
+ // The command id is `<sagaId>:<stepId>`, so a duplicate id is two steps
24
+ // sharing one idempotency key — the second would be dropped as a
25
+ // redelivery of the first and never run at all.
26
+ fail(name, `two steps share the id '${step.id}'`);
27
+ }
28
+ seen.add(step.id);
29
+ }
30
+ // `fanOutFrom` must name a step that has already run, or the outcomes it fans
31
+ // out over do not exist yet. A forward reference would silently produce zero
32
+ // calls — a step that looks like it ran and did nothing, which is exactly how
33
+ // a conversion gets skipped while a saga reports COMPLETED.
34
+ const before = new Set();
35
+ for (const step of steps){
36
+ if (step.fanOutFrom !== undefined && !before.has(step.fanOutFrom)) {
37
+ fail(name, `step '${step.id}' fans out from '${step.fanOutFrom}', which is not a ` + 'step before it');
38
+ }
39
+ before.add(step.id);
40
+ }
41
+ const pivots = steps.filter((step)=>step.kind === 'pivot');
42
+ if (pivots.length > 1) {
43
+ // A flow with two points of no return is a flow that has not been designed
44
+ // yet, and the engine says so out loud (ADR 0039).
45
+ fail(name, `it declares ${String(pivots.length)} pivots (${pivots.map((step)=>step.id).join(', ')}); a flow has at most one point of no return`);
46
+ }
47
+ // ⚠️ **Zero pivots is legal**, and checkout is the case that forced saying so.
48
+ // Payment capture is M4; until it lands every step of checkout reverses. A
49
+ // validator demanding exactly one would push the order write into a role it
50
+ // would have to be removed from later — a wrong answer that passes
51
+ // (ADR 0052). A definition with no pivot means the whole saga can be unwound,
52
+ // which is a stronger property than a pivot rather than a missing one.
53
+ const pivot = pivots[0];
54
+ const pivotAt = pivot ? steps.indexOf(pivot) : -1;
55
+ const afterPivot = (index)=>pivot !== undefined && index > pivotAt;
56
+ for (const [index, step] of steps.entries()){
57
+ switch(step.kind){
58
+ case 'compensatable':
59
+ {
60
+ if (afterPivot(index)) {
61
+ fail(name, `step '${step.id}' is compensatable but sits after the pivot ` + `'${String(pivot == null ? void 0 : pivot.id)}', where nothing can be reversed`);
62
+ }
63
+ if (!step.compensation) {
64
+ fail(name, `step '${step.id}' is compensatable but declares no compensation`);
65
+ }
66
+ break;
67
+ }
68
+ case 'pivot':
69
+ case 'retriable':
70
+ {
71
+ if (step.compensation) {
72
+ // Not dead code — a *false assurance*. Such a compensation could
73
+ // never run, so writing one says the step is reversible when it is
74
+ // not (ADR 0039).
75
+ fail(name, `step '${step.id}' is ${step.kind} and declares a compensation, ` + 'which could never run');
76
+ }
77
+ if (step.kind === 'retriable' && !afterPivot(index)) {
78
+ fail(name, `step '${step.id}' is retriable but sits before the pivot; a step ` + 'that cannot be reversed must not run while the saga can still ' + 'be unwound');
79
+ }
80
+ break;
81
+ }
82
+ }
83
+ }
84
+ return definition;
85
+ }
86
+ /**
87
+ * The command id one call is dispatched under.
88
+ *
89
+ * `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,
90
+ * so #178's `TransactionInbox` serves saga steps with no second dedup store and
91
+ * no second key. A fan-out step appends the element index, because its calls are
92
+ * separate side effects that must each be claimed on their own.
93
+ */ export const sagaCommandId = (sagaId, stepId, index)=>index === undefined ? `${sagaId}:${stepId}` : `${sagaId}:${stepId}:${String(index)}`;
94
+
95
+ //# sourceMappingURL=saga-definition.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/contracts/saga-definition.ts"],"sourcesContent":["import { EntifixLogicError } from '@entifix/core';\n\n/**\n * Richardson's classification, and adopting the vocabulary is most of the answer\n * to \"which steps are compensable at all\"\n * ([ADR 0039](../../../../../../docs/adr/0039-multi-step-sagas-are-orchestrated.md)).\n *\n * - `compensatable` — before the point of no return; a failure downstream\n * reverses it.\n * - `pivot` — the point of no return. Once it commits, the saga goes forward.\n * - `retriable` — after the pivot; no compensation exists, so the only path is\n * to retry until it succeeds.\n */\nexport type SagaStepKind = 'compensatable' | 'pivot' | 'retriable';\n\n/** The HTTP verbs a step may be dispatched with. */\nexport type SagaMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * One call a step makes, as a template rather than a closure.\n *\n * `path` may carry `{…}` placeholders resolved by field path against the step's\n * recorded outcome — `/api/reservation/{outcome.data.id}`.\n *\n * ⚠️ **A template rather than a callback, and that is the constraint that\n * shaped the whole type.** A callback would have to name the participant's\n * types, and a `business:domain` package may not import another\n * (`docs/_shared/layering.md`) — which is exactly the import that has no legal\n * home and the reason ADR 0039 made a definition **data** in the first place.\n */\nexport interface SagaCall {\n readonly method: SagaMethod;\n readonly path: string;\n}\n\n/** One step of a flow. */\nexport interface SagaStep {\n /** Unique within the definition; half of the command id `<sagaId>:<stepId>`. */\n readonly id: string;\n /**\n * Which service answers it, as a **configuration key** — never a URI.\n *\n * A URI in a definition is a deployment fact written into a business\n * artifact, and it is what makes a definition untestable and un-relocatable.\n * The same lookup yields the crossing token for that participant, so a\n * definition carries no secret and never could\n * ([ADR 0052](../../../../../../docs/adr/0052-the-checkout-saga.md)).\n */\n readonly participant: string;\n readonly command: SagaCall;\n /** Required on a `compensatable` step, forbidden on every other kind. */\n readonly compensation?: SagaCall;\n readonly kind: SagaStepKind;\n /**\n * Dispatch one call per element of this step's input, rather than one call.\n *\n * ⚠️ **Cardinality is data, because it has to be.** Checkout reserves once per\n * vendor and how many vendors is known only from the cart, so writing that as\n * N steps would mean generating a definition per request — at which point it\n * is no longer data, and ADR 0039's whole construction collapses back into the\n * class that has no legal home.\n *\n * The consequence carried by {@link SagaStepOutcome}: **the unit of\n * compensation is the call, not the step.** Five lines with three holds taken\n * and the fourth refused must release exactly three.\n */\n readonly fanOut?: boolean;\n /**\n * Fan out over an **earlier step's successful calls** instead of over an\n * input the caller supplied.\n *\n * ⚠️ **Without this a later step cannot address what an earlier one created**,\n * and checkout is the case that proves it. `convert-reservation` needs one\n * call per hold, addressed by the reservation id — which stock-service mints,\n * so the caller cannot know it when it starts the flow. Supplying the ids as\n * input is impossible, and generating a definition per request is the thing\n * ADR 0039 exists to avoid.\n *\n * Each element inherits that call's `organizationId`, so a tenant-plane\n * participant reaches the same tenant it did the first time, and the `path`\n * template resolves against `{outcome.…}` — the same scope a compensation\n * gets, for the same reason: the id being addressed is in the response body.\n *\n * Implies {@link fanOut}. It names a step that must appear **before** this one,\n * and `defineSaga` refuses a forward or self reference at module load.\n */\n readonly fanOutFrom?: string;\n}\n\n/** A flow, as the data a generic engine walks. */\nexport interface SagaDefinition {\n readonly name: string;\n /**\n * What a caller must hold to run this flow, as a `<domain>:<entity>:<action>`\n * string.\n *\n * ⚠️ **On the definition rather than on the route**, so the route that runs a\n * flow stays generic. The alternative was one permission for every saga, which\n * would make \"may run a flow\" a single capability regardless of what the flow\n * does — and checkout writes an order.\n *\n * It is a plain string here rather than authz's `Permission`: this package is\n * `layer:entifix`, and `@entifix/authz` sits above it. The service that\n * mounts the route resolves the string against\n * `SERVICE_CROSSING_PERMISSIONS`, which is where the closed list belongs.\n */\n readonly permission: string;\n readonly steps: readonly SagaStep[];\n}\n\n/** What one dispatched call returned, kept so its compensation can read it. */\nexport interface SagaCallOutcome {\n /** The fan-out element this call was made for; `0` on a single-call step. */\n readonly index: number;\n readonly status: number;\n readonly body: unknown;\n /**\n * The organization this call acted for, carried so its compensation acts on\n * the same one.\n *\n * ⚠️ **Not derivable from the outcome, and its absence is silent.** A\n * tenant-plane participant resolves its storage handle from\n * `x-organization-id`, so a compensation dispatched without it is refused\n * `400` — and the saga strands with every hold still in place while the\n * engine reports it tried. Measured on the live lab: two holds taken, a third\n * line refused, and both releases rejected for a missing header\n * ([ADR 0023](../../../../../../docs/adr/0023-service-to-service-tenant-crossing.md)).\n */\n readonly organizationId?: string;\n}\n\n/**\n * What one step is given to work with — one element per call on a `fanOut` step,\n * exactly one otherwise.\n */\nexport interface SagaStepInput {\n /** The body to send. */\n readonly body?: unknown;\n /** ADR 0023's explicit organization, for a tenant-plane participant. */\n readonly organizationId?: string;\n}\n\n/**\n * The inputs each step needs, keyed by step id, supplied by the caller.\n *\n * ⚠️ **Here rather than in the engine**, because the durable instance carries\n * it: a resumed walk is a different process reading this off the store, so the\n * port that persists it may not reach up into the engine to name its type\n * ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\n */\nexport type SagaInputs = Readonly<Record<string, readonly SagaStepInput[]>>;\n\n/** Every call one step made, in dispatch order. */\nexport interface SagaStepOutcome {\n readonly stepId: string;\n readonly calls: readonly SagaCallOutcome[];\n /**\n * Why this step stopped, when it did — absent on a step that succeeded.\n *\n * ⚠️ **Without it a resumed walk cannot tell a finished step from a refused\n * one.** `calls` holds what succeeded either way, so the two are\n * indistinguishable on the stored document, and the distinction is what\n * decides whether the pivot committed. Guessing it either compensates behind\n * a capture or walks past a refusal\n * ([ADR 0055](../../../../../../docs/adr/0055-a-coordinator-resumes-from-its-own-record.md)).\n */\n readonly error?: string;\n /**\n * Whether this step's calls have already been given back.\n *\n * ⚠️ **What keeps a resumed unwind from compensating twice.** A second\n * `DELETE` of an order already deleted answers `404`, which the dispatcher\n * classifies as a refusal, which strands a flow that was in fact reversed.\n */\n readonly compensated?: boolean;\n}\n\nconst fail = (definition: string, detail: string): never => {\n throw new EntifixLogicError(\n `saga definition '${definition}' is invalid: ${detail}`,\n undefined,\n { definition },\n );\n};\n\n/**\n * Validate a definition and return it, or throw.\n *\n * ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path\n * is a fault that ships — the same reasoning ADR 0035 used for `collection` +\n * `determining`. Every definition is therefore constructed through this\n * function at module scope, and loaded in a spec: a definition that never loads\n * is a definition that never fails.\n */\nexport function defineSaga(definition: SagaDefinition): SagaDefinition {\n const { name, steps } = definition;\n\n if (steps.length === 0) {\n fail(name, 'it declares no steps');\n }\n\n const seen = new Set<string>();\n for (const step of steps) {\n if (seen.has(step.id)) {\n // The command id is `<sagaId>:<stepId>`, so a duplicate id is two steps\n // sharing one idempotency key — the second would be dropped as a\n // redelivery of the first and never run at all.\n fail(name, `two steps share the id '${step.id}'`);\n }\n seen.add(step.id);\n }\n\n // `fanOutFrom` must name a step that has already run, or the outcomes it fans\n // out over do not exist yet. A forward reference would silently produce zero\n // calls — a step that looks like it ran and did nothing, which is exactly how\n // a conversion gets skipped while a saga reports COMPLETED.\n const before = new Set<string>();\n for (const step of steps) {\n if (step.fanOutFrom !== undefined && !before.has(step.fanOutFrom)) {\n fail(\n name,\n `step '${step.id}' fans out from '${step.fanOutFrom}', which is not a ` +\n 'step before it',\n );\n }\n before.add(step.id);\n }\n\n const pivots = steps.filter(step => step.kind === 'pivot');\n if (pivots.length > 1) {\n // A flow with two points of no return is a flow that has not been designed\n // yet, and the engine says so out loud (ADR 0039).\n fail(\n name,\n `it declares ${String(pivots.length)} pivots (${pivots\n .map(step => step.id)\n .join(', ')}); a flow has at most one point of no return`,\n );\n }\n\n // ⚠️ **Zero pivots is legal**, and checkout is the case that forced saying so.\n // Payment capture is M4; until it lands every step of checkout reverses. A\n // validator demanding exactly one would push the order write into a role it\n // would have to be removed from later — a wrong answer that passes\n // (ADR 0052). A definition with no pivot means the whole saga can be unwound,\n // which is a stronger property than a pivot rather than a missing one.\n const pivot = pivots[0];\n const pivotAt = pivot ? steps.indexOf(pivot) : -1;\n const afterPivot = (index: number) => pivot !== undefined && index > pivotAt;\n\n for (const [index, step] of steps.entries()) {\n switch (step.kind) {\n case 'compensatable': {\n if (afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is compensatable but sits after the pivot ` +\n `'${String(pivot?.id)}', where nothing can be reversed`,\n );\n }\n if (!step.compensation) {\n fail(\n name,\n `step '${step.id}' is compensatable but declares no compensation`,\n );\n }\n break;\n }\n case 'pivot':\n case 'retriable': {\n if (step.compensation) {\n // Not dead code — a *false assurance*. Such a compensation could\n // never run, so writing one says the step is reversible when it is\n // not (ADR 0039).\n fail(\n name,\n `step '${step.id}' is ${step.kind} and declares a compensation, ` +\n 'which could never run',\n );\n }\n if (step.kind === 'retriable' && !afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is retriable but sits before the pivot; a step ` +\n 'that cannot be reversed must not run while the saga can still ' +\n 'be unwound',\n );\n }\n break;\n }\n }\n }\n\n return definition;\n}\n\n/**\n * The command id one call is dispatched under.\n *\n * `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,\n * so #178's `TransactionInbox` serves saga steps with no second dedup store and\n * no second key. A fan-out step appends the element index, because its calls are\n * separate side effects that must each be claimed on their own.\n */\nexport const sagaCommandId = (\n sagaId: string,\n stepId: string,\n index?: number,\n): string =>\n index === undefined\n ? `${sagaId}:${stepId}`\n : `${sagaId}:${stepId}:${String(index)}`;\n"],"names":["EntifixLogicError","fail","definition","detail","undefined","defineSaga","name","steps","length","seen","Set","step","has","id","add","before","fanOutFrom","pivots","filter","kind","String","map","join","pivot","pivotAt","indexOf","afterPivot","index","entries","compensation","sagaCommandId","sagaId","stepId"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,gBAAgB;AAiLlD,MAAMC,OAAO,CAACC,YAAoBC;IAChC,MAAM,IAAIH,kBACR,CAAC,iBAAiB,EAAEE,WAAW,cAAc,EAAEC,QAAQ,EACvDC,WACA;QAAEF;IAAW;AAEj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**
2
+ * Resolve a path template against a scope.
3
+ *
4
+ * `/api/reservation/{outcome.data.id}` with
5
+ * `{ outcome: { data: { id: 'r-1' } } }` becomes `/api/reservation/r-1`.
6
+ *
7
+ * ⚠️ **An unresolved placeholder throws rather than interpolating `undefined`.**
8
+ * The failure this prevents is specific and silent: a compensation whose
9
+ * template no longer matches its participant's response shape would otherwise
10
+ * `DELETE /api/reservation/undefined`, get a `404`, and be recorded as a
11
+ * compensation that ran — leaving the hold in place and the saga reporting that
12
+ * it was reversed. That is the "failed and stranded" state ADR 0039 says nobody
13
+ * plans for, arrived at by string interpolation.
14
+ *
15
+ * Values are URI-encoded: a participant's id is data, and a path segment is not
16
+ * the place to discover it contained a slash.
17
+ */
18
+ export declare function resolveTemplate(template: string, scope: Record<string, unknown>): string;
19
+ /**
20
+ * Resolve the placeholders inside a **request body**, recursively.
21
+ *
22
+ * ⚠️ **Why a body needs this at all.** A step's payload can depend on what an
23
+ * earlier step created: checkout's capture has to name the order that was just
24
+ * written, and the order id is minted by order-service — so a caller cannot put
25
+ * it in the body it sends when it starts the flow. Without this, the capture
26
+ * carries a placeholder string and the order it names never advances, which is
27
+ * precisely the defect measured on the live lab: a saga reporting `COMPLETED`
28
+ * with a payment attached to nothing.
29
+ *
30
+ * ⚠️ **The template lives in the caller's `inputs`, never in the definition.**
31
+ * That is ADR 0039's constraint, not an accident: a definition that carried
32
+ * domain payloads would be importing the shape of another domain's entity, which
33
+ * is the class of thing that has no legal home. The definition stays a list of
34
+ * verbs and addresses; what to send is the caller's, and this only lets the
35
+ * caller point at a value it could not have known yet.
36
+ *
37
+ * Two behaviours, and the difference is load-bearing:
38
+ *
39
+ * - A string that is **exactly** one placeholder resolves to the raw value, so
40
+ * a number stays a number and an object stays an object. `"{steps.x.data.qty}"`
41
+ * becoming the string `"3"` would reach a validator expecting a number.
42
+ * - A string that merely **contains** placeholders is interpolated textually,
43
+ * and — unlike {@link resolveTemplate} — **not** URI-encoded. A body is JSON,
44
+ * not a path segment; encoding here would put `%20` in a customer's name.
45
+ *
46
+ * An unresolved placeholder throws, for the same reason it does in a path.
47
+ */
48
+ export declare function resolveBodyTemplate(value: unknown, scope: Record<string, unknown>): unknown;
49
+ //# sourceMappingURL=resolve-template.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-template.d.ts","sourceRoot":"","sources":["../../src/engine/resolve-template.ts"],"names":[],"mappings":"AAgBA;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC7B,MAAM,CAYR;AAKD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC7B,OAAO,CAyCT"}
@@ -0,0 +1,106 @@
1
+ import { EntifixLogicError } from '@entifix/core';
2
+ /** The `{a.b.c}` placeholders a {@link SagaCall}'s path may carry. */ const PLACEHOLDER = /\{([^{}]+)\}/g;
3
+ const readPath = (root, path)=>{
4
+ let value = root;
5
+ for (const segment of path.split('.')){
6
+ if (value === null || typeof value !== 'object') {
7
+ return undefined;
8
+ }
9
+ value = value[segment];
10
+ }
11
+ return value;
12
+ };
13
+ /**
14
+ * Resolve a path template against a scope.
15
+ *
16
+ * `/api/reservation/{outcome.data.id}` with
17
+ * `{ outcome: { data: { id: 'r-1' } } }` becomes `/api/reservation/r-1`.
18
+ *
19
+ * ⚠️ **An unresolved placeholder throws rather than interpolating `undefined`.**
20
+ * The failure this prevents is specific and silent: a compensation whose
21
+ * template no longer matches its participant's response shape would otherwise
22
+ * `DELETE /api/reservation/undefined`, get a `404`, and be recorded as a
23
+ * compensation that ran — leaving the hold in place and the saga reporting that
24
+ * it was reversed. That is the "failed and stranded" state ADR 0039 says nobody
25
+ * plans for, arrived at by string interpolation.
26
+ *
27
+ * Values are URI-encoded: a participant's id is data, and a path segment is not
28
+ * the place to discover it contained a slash.
29
+ */ export function resolveTemplate(template, scope) {
30
+ return template.replaceAll(PLACEHOLDER, (_match, path)=>{
31
+ const value = readPath(scope, path);
32
+ if (value === undefined || value === null) {
33
+ throw new EntifixLogicError(`saga path template '${template}' has no value for '{${path}}'`, undefined, {
34
+ template,
35
+ path
36
+ });
37
+ }
38
+ return encodeURIComponent(String(value));
39
+ });
40
+ }
41
+ /** A string that is nothing but one placeholder, so its type can be preserved. */ const WHOLE_PLACEHOLDER = /^\{([^{}]+)\}$/;
42
+ /**
43
+ * Resolve the placeholders inside a **request body**, recursively.
44
+ *
45
+ * ⚠️ **Why a body needs this at all.** A step's payload can depend on what an
46
+ * earlier step created: checkout's capture has to name the order that was just
47
+ * written, and the order id is minted by order-service — so a caller cannot put
48
+ * it in the body it sends when it starts the flow. Without this, the capture
49
+ * carries a placeholder string and the order it names never advances, which is
50
+ * precisely the defect measured on the live lab: a saga reporting `COMPLETED`
51
+ * with a payment attached to nothing.
52
+ *
53
+ * ⚠️ **The template lives in the caller's `inputs`, never in the definition.**
54
+ * That is ADR 0039's constraint, not an accident: a definition that carried
55
+ * domain payloads would be importing the shape of another domain's entity, which
56
+ * is the class of thing that has no legal home. The definition stays a list of
57
+ * verbs and addresses; what to send is the caller's, and this only lets the
58
+ * caller point at a value it could not have known yet.
59
+ *
60
+ * Two behaviours, and the difference is load-bearing:
61
+ *
62
+ * - A string that is **exactly** one placeholder resolves to the raw value, so
63
+ * a number stays a number and an object stays an object. `"{steps.x.data.qty}"`
64
+ * becoming the string `"3"` would reach a validator expecting a number.
65
+ * - A string that merely **contains** placeholders is interpolated textually,
66
+ * and — unlike {@link resolveTemplate} — **not** URI-encoded. A body is JSON,
67
+ * not a path segment; encoding here would put `%20` in a customer's name.
68
+ *
69
+ * An unresolved placeholder throws, for the same reason it does in a path.
70
+ */ export function resolveBodyTemplate(value, scope) {
71
+ if (typeof value === 'string') {
72
+ const whole = WHOLE_PLACEHOLDER.exec(value);
73
+ if ((whole == null ? void 0 : whole[1]) !== undefined) {
74
+ const resolved = readPath(scope, whole[1]);
75
+ if (resolved === undefined || resolved === null) {
76
+ throw new EntifixLogicError(`saga body template '${value}' has no value for '{${whole[1]}}'`, undefined, {
77
+ template: value,
78
+ path: whole[1]
79
+ });
80
+ }
81
+ return resolved;
82
+ }
83
+ return value.replaceAll(PLACEHOLDER, (_match, path)=>{
84
+ const resolved = readPath(scope, path);
85
+ if (resolved === undefined || resolved === null) {
86
+ throw new EntifixLogicError(`saga body template '${value}' has no value for '{${path}}'`, undefined, {
87
+ template: value,
88
+ path
89
+ });
90
+ }
91
+ return String(resolved);
92
+ });
93
+ }
94
+ if (Array.isArray(value)) {
95
+ return value.map((element)=>resolveBodyTemplate(element, scope));
96
+ }
97
+ if (value !== null && typeof value === 'object') {
98
+ return Object.fromEntries(Object.entries(value).map(([key, entry])=>[
99
+ key,
100
+ resolveBodyTemplate(entry, scope)
101
+ ]));
102
+ }
103
+ return value;
104
+ }
105
+
106
+ //# sourceMappingURL=resolve-template.js.map