@fabricorg/platform-temporal 4.2.1 → 4.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,301 +1,343 @@
1
- // index.ts
1
+ //#region index.ts
2
2
  function temporalInvocationIdentity(input) {
3
- return { idempotencyKey: `temporal:${input.workflowId}:${input.stepId}`, correlationId: `temporal:${input.workflowId}` };
3
+ return {
4
+ idempotencyKey: `temporal:${input.workflowId}:${input.stepId}`,
5
+ correlationId: `temporal:${input.workflowId}`
6
+ };
4
7
  }
8
+ /** Activity implementation. It always enters through the governed Host; handlers are never called directly. */
5
9
  function createGovernedActionActivities(invoker) {
6
- return {
7
- invokeGovernedAction: async (input) => {
8
- const identity = temporalInvocationIdentity(input);
9
- return invoker.invoke({
10
- actionId: input.actionId,
11
- parameters: input.parameters,
12
- tenantId: input.tenantId,
13
- spaceId: input.spaceId,
14
- actorId: input.actorId,
15
- actorType: input.actorType,
16
- ...identity,
17
- ...input.parentInvocationId ? { causationId: input.parentInvocationId } : {},
18
- executionEvidence: { temporalWorkflowId: input.workflowId, temporalRunId: input.runId, temporalStepId: input.stepId }
19
- });
20
- }
21
- };
10
+ return { invokeGovernedAction: async (input) => {
11
+ const identity = temporalInvocationIdentity(input);
12
+ return invoker.invoke({
13
+ actionId: input.actionId,
14
+ parameters: input.parameters,
15
+ tenantId: input.tenantId,
16
+ spaceId: input.spaceId,
17
+ actorId: input.actorId,
18
+ actorType: input.actorType,
19
+ ...identity,
20
+ ...input.parentInvocationId ? { causationId: input.parentInvocationId } : {},
21
+ executionEvidence: {
22
+ temporalWorkflowId: input.workflowId,
23
+ temporalRunId: input.runId,
24
+ temporalStepId: input.stepId
25
+ }
26
+ });
27
+ } };
22
28
  }
23
29
  function createSagaSignalDispatcher(client) {
24
- return (workflowId, envelope) => {
25
- assertSignalIdentity(envelope);
26
- return client.signal(workflowId, envelope.signal, envelope);
27
- };
30
+ return (workflowId, envelope) => {
31
+ assertSignalIdentity(envelope);
32
+ return client.signal(workflowId, envelope.signal, envelope);
33
+ };
28
34
  }
29
35
  function assertSignalIdentity(envelope) {
30
- if (envelope.signalId === void 0) return;
31
- if (typeof envelope.signalId !== "string" || !envelope.signalId.trim()) {
32
- throw new Error(`Saga signal "${envelope.signal}" for saga "${envelope.sagaId}" has a blank signalId; omit it or supply a stable non-blank identity.`);
33
- }
36
+ if (envelope.signalId === void 0) return;
37
+ if (typeof envelope.signalId !== "string" || !envelope.signalId.trim()) throw new Error(`Saga signal "${envelope.signal}" for saga "${envelope.sagaId}" has a blank signalId; omit it or supply a stable non-blank identity.`);
34
38
  }
39
+ /** A stable identity a receiver can deduplicate on, or undefined when the envelope carries none. */
35
40
  function signalIdentity(envelope) {
36
- return typeof envelope.signalId === "string" && envelope.signalId.trim() ? envelope.signalId : void 0;
41
+ return typeof envelope.signalId === "string" && envelope.signalId.trim() ? envelope.signalId : void 0;
37
42
  }
43
+ /**
44
+ * Deterministic receiver for saga signals. It has no Temporal dependency and reads
45
+ * no clock, randomness or process-global state, so it can run inside the workflow
46
+ * sandbox. Wire it with
47
+ * `setHandler(defineSignal(SAGA_SIGNALS.approval), (envelope) => { inbox.receive(envelope); })`.
48
+ *
49
+ * Buffering is FIFO per signal name. Deduplication is keyed on `signalId` across
50
+ * every signal name received by this inbox. Dedup state lives in this instance, so
51
+ * it lasts for one workflow run unless the caller carries
52
+ * {@link SagaSignalInbox.snapshot} into the next run. The remembered set grows
53
+ * with each distinct `signalId` and is not pruned, including across
54
+ * continue-as-new, because forgetting an ID would let its redelivery through.
55
+ */
38
56
  function createSagaSignalInbox(options = {}) {
39
- const seen = new Set(options.seenSignalIds ?? []);
40
- const queues = /* @__PURE__ */ new Map();
41
- const enqueue = (envelope) => {
42
- const queue = queues.get(envelope.signal);
43
- if (queue) queue.push(envelope);
44
- else queues.set(envelope.signal, [envelope]);
45
- };
46
- for (const envelope of options.pending ?? []) {
47
- const id = signalIdentity(envelope);
48
- if (id !== void 0) seen.add(id);
49
- enqueue(envelope);
50
- }
51
- return {
52
- receive(envelope) {
53
- const id = signalIdentity(envelope);
54
- if (id !== void 0) {
55
- if (seen.has(id)) return false;
56
- seen.add(id);
57
- }
58
- enqueue(envelope);
59
- return true;
60
- },
61
- take(signalName) {
62
- return queues.get(signalName)?.shift();
63
- },
64
- pending(signalName) {
65
- return queues.get(signalName)?.length ?? 0;
66
- },
67
- seenSignalIds() {
68
- return [...seen];
69
- },
70
- snapshot() {
71
- return { seenSignalIds: [...seen], pending: [...queues.values()].flat() };
72
- }
73
- };
57
+ const seen = new Set(options.seenSignalIds ?? []);
58
+ const queues = /* @__PURE__ */ new Map();
59
+ const enqueue = (envelope) => {
60
+ const queue = queues.get(envelope.signal);
61
+ if (queue) queue.push(envelope);
62
+ else queues.set(envelope.signal, [envelope]);
63
+ };
64
+ for (const envelope of options.pending ?? []) {
65
+ const id = signalIdentity(envelope);
66
+ if (id !== void 0) seen.add(id);
67
+ enqueue(envelope);
68
+ }
69
+ return {
70
+ receive(envelope) {
71
+ const id = signalIdentity(envelope);
72
+ if (id !== void 0) {
73
+ if (seen.has(id)) return false;
74
+ seen.add(id);
75
+ }
76
+ enqueue(envelope);
77
+ return true;
78
+ },
79
+ take(signalName) {
80
+ return queues.get(signalName)?.shift();
81
+ },
82
+ pending(signalName) {
83
+ return queues.get(signalName)?.length ?? 0;
84
+ },
85
+ seenSignalIds() {
86
+ return [...seen];
87
+ },
88
+ snapshot() {
89
+ return {
90
+ seenSignalIds: [...seen],
91
+ pending: [...queues.values()].flat()
92
+ };
93
+ }
94
+ };
74
95
  }
75
96
  function startGovernedWorkflow(client, input) {
76
- return client.start({ ...input, idConflictPolicy: "use_existing" });
97
+ return client.start({
98
+ ...input,
99
+ idConflictPolicy: "use_existing"
100
+ });
77
101
  }
102
+ /** Instance-scoped registry; registration order never changes resolution. */
78
103
  var SagaWorkflowRegistry = class {
79
- bindings = /* @__PURE__ */ new Map();
80
- constructor(bindings = []) {
81
- for (const binding of bindings) this.register(binding);
82
- }
83
- register(binding) {
84
- if (this.bindings.has(binding.actionId)) {
85
- throw new Error(`Saga workflow binding already registered: ${binding.actionId}`);
86
- }
87
- if (!binding.workflowType.trim() || !binding.taskQueue.trim()) {
88
- throw new Error(`Saga workflow binding ${binding.actionId} requires workflowType and taskQueue`);
89
- }
90
- this.bindings.set(binding.actionId, { ...binding });
91
- }
92
- require(actionId) {
93
- const binding = this.bindings.get(actionId);
94
- if (!binding) throw new Error(`No saga workflow binding registered for ${actionId}`);
95
- return { ...binding };
96
- }
104
+ bindings = /* @__PURE__ */ new Map();
105
+ constructor(bindings = []) {
106
+ for (const binding of bindings) this.register(binding);
107
+ }
108
+ register(binding) {
109
+ if (this.bindings.has(binding.actionId)) throw new Error(`Saga workflow binding already registered: ${binding.actionId}`);
110
+ if (!binding.workflowType.trim() || !binding.taskQueue.trim()) throw new Error(`Saga workflow binding ${binding.actionId} requires workflowType and taskQueue`);
111
+ this.bindings.set(binding.actionId, { ...binding });
112
+ }
113
+ require(actionId) {
114
+ const binding = this.bindings.get(actionId);
115
+ if (!binding) throw new Error(`No saga workflow binding registered for ${actionId}`);
116
+ return { ...binding };
117
+ }
97
118
  };
119
+ /** Starts the registered parent workflow with an invocation-only durable identity. */
98
120
  function createTemporalSagaDispatcher(client, registry) {
99
- return {
100
- dispatch: async (input) => {
101
- const binding = registry.require(input.actionId);
102
- const handle = await startGovernedWorkflow(client, {
103
- workflowType: binding.workflowType,
104
- workflowId: input.workflowId,
105
- taskQueue: binding.taskQueue,
106
- args: [{
107
- parentInvocationId: input.actionInvocationId,
108
- actionId: input.actionId,
109
- tenantId: input.tenantId,
110
- spaceId: input.spaceId
111
- }]
112
- });
113
- const runId = runIdFromHandle(handle);
114
- return { workflowId: input.workflowId, ...runId ? { runId } : {} };
115
- }
116
- };
121
+ return { dispatch: async (input) => {
122
+ const binding = registry.require(input.actionId);
123
+ const runId = runIdFromHandle(await startGovernedWorkflow(client, {
124
+ workflowType: binding.workflowType,
125
+ workflowId: input.workflowId,
126
+ taskQueue: binding.taskQueue,
127
+ args: [{
128
+ parentInvocationId: input.actionInvocationId,
129
+ actionId: input.actionId,
130
+ tenantId: input.tenantId,
131
+ spaceId: input.spaceId
132
+ }]
133
+ }));
134
+ return {
135
+ workflowId: input.workflowId,
136
+ ...runId ? { runId } : {}
137
+ };
138
+ } };
117
139
  }
118
140
  function runIdFromHandle(handle) {
119
- if (!handle || typeof handle !== "object") return void 0;
120
- const candidate = handle.firstExecutionRunId;
121
- return typeof candidate === "string" && candidate ? candidate : void 0;
141
+ if (!handle || typeof handle !== "object") return void 0;
142
+ const candidate = handle.firstExecutionRunId;
143
+ return typeof candidate === "string" && candidate ? candidate : void 0;
122
144
  }
145
+ /** Parent lifecycle remains explicit durable activities, never workflow-local state. */
123
146
  function createSagaParentActivities(lifecycle) {
124
- return {
125
- recordSagaProgress: (input) => lifecycle.recordProgress({
126
- ...input,
127
- lifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(
128
- input.parentInvocationId,
129
- "progress",
130
- `${input.progress.stepId}:${input.progress.index}`
131
- ).idempotencyKey
132
- }),
133
- parkSagaApproval: (input) => lifecycle.parkApproval({
134
- ...input,
135
- lifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(
136
- input.parentInvocationId,
137
- "approval",
138
- input.approvalId
139
- ).idempotencyKey
140
- }),
141
- cancelSagaParent: (input) => lifecycle.cancel({
142
- ...input,
143
- lifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(
144
- input.parentInvocationId,
145
- "cancel"
146
- ).idempotencyKey
147
- }),
148
- completeSagaParent: (input) => lifecycle.complete({
149
- ...input,
150
- lifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(
151
- input.parentInvocationId,
152
- "complete"
153
- ).idempotencyKey
154
- }),
155
- failSagaParent: (input) => lifecycle.fail({
156
- ...input,
157
- lifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(
158
- input.parentInvocationId,
159
- "fail"
160
- ).idempotencyKey
161
- })
162
- };
147
+ return {
148
+ recordSagaProgress: (input) => lifecycle.recordProgress({
149
+ ...input,
150
+ lifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(input.parentInvocationId, "progress", `${input.progress.stepId}:${input.progress.index}`).idempotencyKey
151
+ }),
152
+ parkSagaApproval: (input) => lifecycle.parkApproval({
153
+ ...input,
154
+ lifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(input.parentInvocationId, "approval", input.approvalId).idempotencyKey
155
+ }),
156
+ cancelSagaParent: (input) => lifecycle.cancel({
157
+ ...input,
158
+ lifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(input.parentInvocationId, "cancel").idempotencyKey
159
+ }),
160
+ completeSagaParent: (input) => lifecycle.complete({
161
+ ...input,
162
+ lifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(input.parentInvocationId, "complete").idempotencyKey
163
+ }),
164
+ failSagaParent: (input) => lifecycle.fail({
165
+ ...input,
166
+ lifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(input.parentInvocationId, "fail").idempotencyKey
167
+ })
168
+ };
163
169
  }
170
+ /**
171
+ * Stable identity for a saga parent's own lifecycle activity (progress,
172
+ * cancellation, approval parking, completion, failure). The activity stepId
173
+ * is namespaced under `parent:` so it can never collide with a forward step or
174
+ * a `compensate:` reversal.
175
+ */
164
176
  function sagaParentActivityIdentity(workflowId, activity, discriminator) {
165
- return temporalInvocationIdentity({
166
- workflowId,
167
- stepId: `parent:${activity}${discriminator ? `:${discriminator}` : ""}`
168
- });
177
+ return temporalInvocationIdentity({
178
+ workflowId,
179
+ stepId: `parent:${activity}${discriminator ? `:${discriminator}` : ""}`
180
+ });
169
181
  }
182
+ /**
183
+ * Stable causation identity linking a child step to its parent invocation.
184
+ * The parent invocation ID becomes the causation ID; the step keeps its own
185
+ * deterministic idempotency key and shares the workflow correlation ID.
186
+ */
170
187
  function sagaChildCausation(workflowId, parentInvocationId, stepId) {
171
- return { ...temporalInvocationIdentity({ workflowId, stepId }), causationId: parentInvocationId };
188
+ return {
189
+ ...temporalInvocationIdentity({
190
+ workflowId,
191
+ stepId
192
+ }),
193
+ causationId: parentInvocationId
194
+ };
172
195
  }
173
- var SAGA_SIGNALS = {
174
- proceed: "saga.proceed",
175
- cancel: "saga.cancel",
176
- approval: "saga.approval"
196
+ /** Stable signal names a saga workflow may register handlers for. */
197
+ const SAGA_SIGNALS = {
198
+ proceed: "saga.proceed",
199
+ cancel: "saga.cancel",
200
+ approval: "saga.approval"
177
201
  };
202
+ /** Adapts the official Temporal TypeScript `WorkflowClient` to the narrow testable binding seam. */
178
203
  function temporalWorkflowStartClient(client) {
179
- return {
180
- start: ({ workflowType, workflowId, taskQueue, args }) => client.start(workflowType, { workflowId, taskQueue, args, workflowIdConflictPolicy: "USE_EXISTING" })
181
- };
204
+ return { start: ({ workflowType, workflowId, taskQueue, args }) => client.start(workflowType, {
205
+ workflowId,
206
+ taskQueue,
207
+ args,
208
+ workflowIdConflictPolicy: "USE_EXISTING"
209
+ }) };
182
210
  }
183
211
  function assertWorkerVersionEvidence(value) {
184
- if (!value.buildId.trim() || !value.deploymentName.trim()) throw new Error("Temporal worker buildId and deploymentName are required for rollover evidence.");
212
+ if (!value.buildId.trim() || !value.deploymentName.trim()) throw new Error("Temporal worker buildId and deploymentName are required for rollover evidence.");
185
213
  }
214
+ /** Reversals are governed invocations too, so they carry their own stable identity. */
186
215
  function compensationInvocationIdentity(input) {
187
- return temporalInvocationIdentity({ workflowId: input.workflowId, stepId: `compensate:${input.stepId}` });
216
+ return temporalInvocationIdentity({
217
+ workflowId: input.workflowId,
218
+ stepId: `compensate:${input.stepId}`
219
+ });
188
220
  }
189
221
  var SagaCompensationError = class extends Error {
190
- constructor(result) {
191
- super(`Saga step "${result.failedStep?.stepId}" failed: ${result.failedStep?.error}`);
192
- this.result = result;
193
- }
194
- result;
195
- name = "SagaCompensationError";
222
+ result;
223
+ name = "SagaCompensationError";
224
+ constructor(result) {
225
+ super(`Saga step "${result.failedStep?.stepId}" failed: ${result.failedStep?.error}`);
226
+ this.result = result;
227
+ }
196
228
  };
197
- var SUCCESSFUL_STATUS = "completed";
229
+ /**
230
+ * The governed Host resolves for outcomes that are not success — a blocked policy, a
231
+ * failed validation, a reconciliation, an approval park. Treating a resolved promise
232
+ * as a completed step would silently skip the unwind, so the status is inspected.
233
+ */
234
+ const SUCCESSFUL_STATUS = "completed";
198
235
  function stepFailure(result, label) {
199
- if (!result || typeof result !== "object") return void 0;
200
- const status = result.status;
201
- if (typeof status !== "string" || status === SUCCESSFUL_STATUS) return void 0;
202
- const error = result.error;
203
- return `${label} resolved with status "${status}"${typeof error === "string" && error ? `: ${error}` : ""}`;
236
+ if (!result || typeof result !== "object") return void 0;
237
+ const status = result.status;
238
+ if (typeof status !== "string" || status === SUCCESSFUL_STATUS) return void 0;
239
+ const error = result.error;
240
+ return `${label} resolved with status "${status}"${typeof error === "string" && error ? `: ${error}` : ""}`;
204
241
  }
205
242
  function assertDistinctSteps(steps) {
206
- const seen = /* @__PURE__ */ new Set();
207
- for (const step of steps) {
208
- if (!step.stepId.trim()) throw new Error("Every saga step requires a stepId.");
209
- if (step.stepId.startsWith("compensate:")) throw new Error(`Saga step "${step.stepId}" must not use the reserved "compensate:" prefix.`);
210
- if (step.stepId.startsWith("parent:")) throw new Error(`Saga step "${step.stepId}" must not use the reserved "parent:" prefix.`);
211
- if (seen.has(step.stepId)) throw new Error(`Saga declares duplicate step "${step.stepId}"; step identity must be unique within a workflow.`);
212
- seen.add(step.stepId);
213
- }
243
+ const seen = /* @__PURE__ */ new Set();
244
+ for (const step of steps) {
245
+ if (!step.stepId.trim()) throw new Error("Every saga step requires a stepId.");
246
+ if (step.stepId.startsWith("compensate:")) throw new Error(`Saga step "${step.stepId}" must not use the reserved "compensate:" prefix.`);
247
+ if (step.stepId.startsWith("parent:")) throw new Error(`Saga step "${step.stepId}" must not use the reserved "parent:" prefix.`);
248
+ if (seen.has(step.stepId)) throw new Error(`Saga declares duplicate step "${step.stepId}"; step identity must be unique within a workflow.`);
249
+ seen.add(step.stepId);
250
+ }
214
251
  }
215
252
  function assertMatchesDeclaration(steps, workflow) {
216
- const declared = new Map((workflow.compensations ?? []).map((entry) => [entry.step, entry.actionId]));
217
- for (const step of steps) {
218
- const expected = declared.get(step.stepId);
219
- if (expected === void 0) {
220
- if (step.compensateWith) throw new Error(`Workflow "${workflow.name}" step "${step.stepId}" supplies a reversal the manifest does not declare.`);
221
- continue;
222
- }
223
- if (!step.compensateWith) throw new Error(`Workflow "${workflow.name}" step "${step.stepId}" omits the reversal "${expected}" its manifest declares.`);
224
- if (step.compensateWith.actionId !== expected) {
225
- throw new Error(`Workflow "${workflow.name}" step "${step.stepId}" reverses with "${step.compensateWith.actionId}" but its manifest declares "${expected}".`);
226
- }
227
- }
228
- for (const [step, actionId] of declared) {
229
- if (!steps.some((candidate) => candidate.stepId === step)) {
230
- throw new Error(`Workflow "${workflow.name}" declares a reversal "${actionId}" for step "${step}", which this saga never runs.`);
231
- }
232
- }
253
+ const declared = new Map((workflow.compensations ?? []).map((entry) => [entry.step, entry.actionId]));
254
+ for (const step of steps) {
255
+ const expected = declared.get(step.stepId);
256
+ if (expected === void 0) {
257
+ if (step.compensateWith) throw new Error(`Workflow "${workflow.name}" step "${step.stepId}" supplies a reversal the manifest does not declare.`);
258
+ continue;
259
+ }
260
+ if (!step.compensateWith) throw new Error(`Workflow "${workflow.name}" step "${step.stepId}" omits the reversal "${expected}" its manifest declares.`);
261
+ if (step.compensateWith.actionId !== expected) throw new Error(`Workflow "${workflow.name}" step "${step.stepId}" reverses with "${step.compensateWith.actionId}" but its manifest declares "${expected}".`);
262
+ }
263
+ for (const [step, actionId] of declared) if (!steps.some((candidate) => candidate.stepId === step)) throw new Error(`Workflow "${workflow.name}" declares a reversal "${actionId}" for step "${step}", which this saga never runs.`);
233
264
  }
265
+ /**
266
+ * Runs steps in order, accumulating reversals as each succeeds. On failure the
267
+ * accumulated reversals run newest-first, so an unwind never leaves an orphan.
268
+ * Every forward step and every reversal enters through the governed Host with a
269
+ * deterministic idempotency key, so a retried or replayed unwind is not double-applied.
270
+ */
234
271
  async function runCompensatedSaga(activity, input) {
235
- const scope = {
236
- tenantId: input.tenantId,
237
- spaceId: input.spaceId,
238
- actorId: input.actorId,
239
- actorType: input.actorType,
240
- workflowId: input.workflowId,
241
- runId: input.runId,
242
- ...input.parentInvocationId ? { parentInvocationId: input.parentInvocationId } : {}
243
- };
244
- assertDistinctSteps(input.steps);
245
- if (input.workflow) assertMatchesDeclaration(input.steps, input.workflow);
246
- const completed = [];
247
- const reversals = [];
248
- const unwind = async (failedStep) => {
249
- const compensated = [];
250
- for (const applied of [...reversals].reverse()) {
251
- const reversal = applied.compensateWith;
252
- const record = { stepId: applied.stepId, actionId: reversal.actionId };
253
- try {
254
- const result = await activity({
255
- ...scope,
256
- actionId: reversal.actionId,
257
- parameters: reversal.parameters ?? applied.parameters,
258
- stepId: `compensate:${applied.stepId}`
259
- });
260
- const refused = stepFailure(result, `reversal "${reversal.actionId}"`);
261
- if (refused) record.error = refused;
262
- } catch (compensationError) {
263
- record.error = compensationError instanceof Error ? compensationError.message : String(compensationError);
264
- }
265
- compensated.push(record);
266
- }
267
- throw new SagaCompensationError({ completed, compensated, failedStep });
268
- };
269
- for (const step of input.steps) {
270
- let result;
271
- try {
272
- result = await activity({ ...scope, actionId: step.actionId, parameters: step.parameters, stepId: step.stepId });
273
- } catch (error) {
274
- return await unwind({ stepId: step.stepId, error: error instanceof Error ? error.message : String(error) });
275
- }
276
- const refused = stepFailure(result, `step "${step.stepId}"`);
277
- if (refused) return await unwind({ stepId: step.stepId, error: refused });
278
- completed.push(step.stepId);
279
- if (step.compensateWith) reversals.push(step);
280
- }
281
- return { completed, compensated: [] };
272
+ const scope = {
273
+ tenantId: input.tenantId,
274
+ spaceId: input.spaceId,
275
+ actorId: input.actorId,
276
+ actorType: input.actorType,
277
+ workflowId: input.workflowId,
278
+ runId: input.runId,
279
+ ...input.parentInvocationId ? { parentInvocationId: input.parentInvocationId } : {}
280
+ };
281
+ assertDistinctSteps(input.steps);
282
+ if (input.workflow) assertMatchesDeclaration(input.steps, input.workflow);
283
+ const completed = [];
284
+ const reversals = [];
285
+ const unwind = async (failedStep) => {
286
+ const compensated = [];
287
+ for (const applied of [...reversals].reverse()) {
288
+ const reversal = applied.compensateWith;
289
+ const record = {
290
+ stepId: applied.stepId,
291
+ actionId: reversal.actionId
292
+ };
293
+ try {
294
+ const refused = stepFailure(await activity({
295
+ ...scope,
296
+ actionId: reversal.actionId,
297
+ parameters: reversal.parameters ?? applied.parameters,
298
+ stepId: `compensate:${applied.stepId}`
299
+ }), `reversal "${reversal.actionId}"`);
300
+ if (refused) record.error = refused;
301
+ } catch (compensationError) {
302
+ record.error = compensationError instanceof Error ? compensationError.message : String(compensationError);
303
+ }
304
+ compensated.push(record);
305
+ }
306
+ throw new SagaCompensationError({
307
+ completed,
308
+ compensated,
309
+ failedStep
310
+ });
311
+ };
312
+ for (const step of input.steps) {
313
+ let result;
314
+ try {
315
+ result = await activity({
316
+ ...scope,
317
+ actionId: step.actionId,
318
+ parameters: step.parameters,
319
+ stepId: step.stepId
320
+ });
321
+ } catch (error) {
322
+ return await unwind({
323
+ stepId: step.stepId,
324
+ error: error instanceof Error ? error.message : String(error)
325
+ });
326
+ }
327
+ const refused = stepFailure(result, `step "${step.stepId}"`);
328
+ if (refused) return await unwind({
329
+ stepId: step.stepId,
330
+ error: refused
331
+ });
332
+ completed.push(step.stepId);
333
+ if (step.compensateWith) reversals.push(step);
334
+ }
335
+ return {
336
+ completed,
337
+ compensated: []
338
+ };
282
339
  }
283
- export {
284
- SAGA_SIGNALS,
285
- SagaCompensationError,
286
- SagaWorkflowRegistry,
287
- assertWorkerVersionEvidence,
288
- compensationInvocationIdentity,
289
- createGovernedActionActivities,
290
- createSagaParentActivities,
291
- createSagaSignalDispatcher,
292
- createSagaSignalInbox,
293
- createTemporalSagaDispatcher,
294
- runCompensatedSaga,
295
- sagaChildCausation,
296
- sagaParentActivityIdentity,
297
- startGovernedWorkflow,
298
- temporalInvocationIdentity,
299
- temporalWorkflowStartClient
300
- };
340
+ //#endregion
341
+ export { SAGA_SIGNALS, SagaCompensationError, SagaWorkflowRegistry, assertWorkerVersionEvidence, compensationInvocationIdentity, createGovernedActionActivities, createSagaParentActivities, createSagaSignalDispatcher, createSagaSignalInbox, createTemporalSagaDispatcher, runCompensatedSaga, sagaChildCausation, sagaParentActivityIdentity, startGovernedWorkflow, temporalInvocationIdentity, temporalWorkflowStartClient };
342
+
301
343
  //# sourceMappingURL=index.js.map