@fabricorg/platform-temporal 4.3.0 → 4.4.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.
- package/CHANGELOG.md +71 -0
- package/README.md +22 -0
- package/dist/index.cjs +75 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +20 -4
- package/dist/index.d.ts +20 -4
- package/dist/index.js +75 -7
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,76 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 4.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 5669886: Record a handler's declared business refusal beside its failed verdict, so a caller or parent saga
|
|
8
|
+
can tell a typed refusal from any other failure (#230, ADR 0026). Before, a handler's returned
|
|
9
|
+
`{ success: false, error, data }` settled the invocation `failed` with the error text only, and
|
|
10
|
+
`data` was dropped.
|
|
11
|
+
|
|
12
|
+
`@fabricorg/platform`: `ActionDefinition.failureSchema` (`SchemaValidator<ActionFailure>`, with the
|
|
13
|
+
new `ActionFailure` type `{ code, data? }`) and `assertActionFailureSchema`. `ActionResult` is
|
|
14
|
+
unchanged. Action and module registration reject a `failureSchema` without a `safeParse` function.
|
|
15
|
+
|
|
16
|
+
`@fabricorg/platform-host`:
|
|
17
|
+
|
|
18
|
+
- For an action that declares `failureSchema`, Host parses a returned failed result's `data` and
|
|
19
|
+
records a detached copy of the schema's parsed output as `ActionInvocationRecord.failure`, in the
|
|
20
|
+
same write as the `failed` status and error, on the ordinary, leased or owner-fenced path. A
|
|
21
|
+
failed parse, a throwing validator or getter, an invalid code or a value PostgreSQL `jsonb` would
|
|
22
|
+
refuse drops the descriptor; an envelope over 16 KiB (`MAX_HANDLER_FAILURE_BYTES`) keeps only its
|
|
23
|
+
code. For an action without `failureSchema`, Host does not read the returned `data` and behavior
|
|
24
|
+
is unchanged.
|
|
25
|
+
- `SubmitActionResult.failure` and `ExecuteActionResult.failure` report it on first execution,
|
|
26
|
+
keyed replay and terminal reads of a `failed` row.
|
|
27
|
+
- Error text, `redactErrorText` and handler retry are as before: a returned refusal is not retried.
|
|
28
|
+
- New store capability `PlatformHostStore.handlerFailureDescriptors`, set by both shipped stores.
|
|
29
|
+
Host refuses an action that declares `failureSchema` on a store without it: at host creation for
|
|
30
|
+
registered modules, at submission before writing anything, or, for an invocation created another
|
|
31
|
+
way, where its handler would run next, so recovery, approval waits and other settlements that do
|
|
32
|
+
not run the handler are as before. `CreateActionInvocationInput` cannot seed `failure`.
|
|
33
|
+
- `MemoryPlatformHostStore` keeps descriptors beside its rows: the public `invocations` array's rows
|
|
34
|
+
do not carry `failure`; reads (`getActionInvocation` and the others) return a copy with it. Rows
|
|
35
|
+
without a descriptor are handed out as before.
|
|
36
|
+
- PostgreSQL migration 20 adds nullable `action_invocations.handler_failure jsonb` (no default, no
|
|
37
|
+
backfill); rows without it, and erased rows, read as absent. Writes name the column only for a
|
|
38
|
+
patch that carries `failure`. On a schema without the column, those writes and erasure fail with
|
|
39
|
+
an error naming migration 20 and `ensureSchema()`.
|
|
40
|
+
- New exported checks `handlerFailureChecks()` and `runHandlerFailureChecks()`.
|
|
41
|
+
|
|
42
|
+
Release notes (recovery, redaction and erasure semantics):
|
|
43
|
+
|
|
44
|
+
- Recovery: `failure` is never written for a `reconciliation_required` verdict, a finalizer
|
|
45
|
+
failure, a thrown handler error, a write that lost ownership, or a recovery that found a
|
|
46
|
+
succeeded, running or ambiguous adapter row or a pending handoff. It means only that the handler
|
|
47
|
+
returned that refusal on the execution that settled the invocation failed.
|
|
48
|
+
- Redaction: only the schema's output is persisted, so the schema must allowlist what may be
|
|
49
|
+
stored. `redactActionParameters` and `redactErrorText` do not see it.
|
|
50
|
+
- Disclosure: results omit `failure` on a keyed replay that observed an identity conflict
|
|
51
|
+
(including `audit-only` conflict mode) or comes from another actor type, on an erased
|
|
52
|
+
invocation, on a result whose `error` is Host's own diagnostic (such as `notStarted`), on
|
|
53
|
+
`resumeApprovedInvocation` results before the approver is authorized, and on the row
|
|
54
|
+
`cancelWaitingApproval` returns. The
|
|
55
|
+
submission outcome receipt is unchanged.
|
|
56
|
+
- Erasure: invocation erasure removes the whole descriptor itself (PostgreSQL sets
|
|
57
|
+
`handler_failure` NULL); the redactor does not see it. Run `ensureSchema()` first, and upgrade
|
|
58
|
+
every erasure-capable Host sharing the database before enabling an action that declares
|
|
59
|
+
`failureSchema`: an older eraser leaves the column in place (upgraded Hosts read such a row
|
|
60
|
+
without it, and erasing it again clears it).
|
|
61
|
+
- Saga parent failure: `createDurableSagaParentLifecycle().fail()` leaves a compensation record's
|
|
62
|
+
`failure` member out of the `SagaParentFailed` v1 payload; everything else is written as before,
|
|
63
|
+
so payloads and digests for inputs whose records carry no `failure` member do not change. Upgrade every Host that records saga
|
|
64
|
+
parent failure before deploying saga workers on this `@fabricorg/platform-temporal` release: an
|
|
65
|
+
older Host writes the member, and a retry of that `fail()` on an upgraded Host is refused as
|
|
66
|
+
contradictory evidence.
|
|
67
|
+
|
|
68
|
+
`@fabricorg/platform-temporal`: `SagaCompensationError.result.failedStep` and a failed
|
|
69
|
+
`CompensationRecord` carry an optional `failure` (`SagaStepFailure`) when the governed child
|
|
70
|
+
resolved `failed` with one. It is accepted only on a `failed` result and in the Host's shape, and
|
|
71
|
+
copied. Error strings and unwind order are unchanged. New exported types `SagaStepFailure` and
|
|
72
|
+
`CompensatedSagaFailedStep`.
|
|
73
|
+
|
|
3
74
|
## 4.3.0
|
|
4
75
|
|
|
5
76
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -53,3 +53,25 @@ if (await wf.condition(() => inbox.pending(SAGA_SIGNALS.approval) > 0, "1 day"))
|
|
|
53
53
|
then reject their redelivery.
|
|
54
54
|
- The remembered ID set grows with each distinct `signalId` and is not pruned, so
|
|
55
55
|
continue-as-new does not shrink it. Forgetting an ID would let its redelivery through.
|
|
56
|
+
|
|
57
|
+
## Declared compensation and child refusals
|
|
58
|
+
|
|
59
|
+
`runCompensatedSaga()` runs steps in order and, when one fails, runs the accumulated reversals
|
|
60
|
+
newest-first, then throws `SagaCompensationError`. Its `result.failedStep` and each failed
|
|
61
|
+
`CompensationRecord` keep their `error` text, and also carry an optional `failure`
|
|
62
|
+
(`SagaStepFailure`, `{ code, data? }`) when the governed child resolved `failed` with a declared
|
|
63
|
+
business refusal: Platform Host 8.21.0 or later reports it as `failure` for an action that declares
|
|
64
|
+
`failureSchema`. A workflow can branch on `failure.code`; it means only that the child's handler
|
|
65
|
+
returned that refusal on the execution that settled the child failed. The activity result is
|
|
66
|
+
untyped, so the binding accepts `failure` only on a `failed` result, only as a fixed code and an
|
|
67
|
+
optional plain JSON object, and keeps a copy. A thrown activity, a policy block or another status
|
|
68
|
+
supplies no `failure`.
|
|
69
|
+
|
|
70
|
+
Passing `result.compensated` to the parent's `fail` lifecycle activity does not copy child detail
|
|
71
|
+
into the parent ledger on Platform Host 8.21.0 or later: `createDurableSagaParentLifecycle()` leaves
|
|
72
|
+
each record's `failure` member out of the `SagaParentFailed` v1 event and writes the rest as before,
|
|
73
|
+
so a retry from a worker without this field matches the recorded evidence. An older Host writes the
|
|
74
|
+
member into the event, and a retry of that `fail()` on an upgraded Host is then refused as
|
|
75
|
+
contradictory evidence, so upgrade every Host that records saga parent failure before deploying
|
|
76
|
+
workers with this release. Temporal history keeps the activity results, including `failure`,
|
|
77
|
+
outside Host's stored-record erasure.
|
package/dist/index.cjs
CHANGED
|
@@ -240,6 +240,65 @@ function stepFailure(result, label) {
|
|
|
240
240
|
const error = result.error;
|
|
241
241
|
return `${label} resolved with status "${status}"${typeof error === "string" && error ? `: ${error}` : ""}`;
|
|
242
242
|
}
|
|
243
|
+
/** Fixed code syntax the Host applies to handler failure codes. */
|
|
244
|
+
const STEP_FAILURE_CODE = /^[a-z][A-Za-z0-9_.:-]{0,127}$/;
|
|
245
|
+
/** A detached plain-JSON copy read through own data descriptors; the depth bound also ends a cycle. */
|
|
246
|
+
function plainJson(value, depth) {
|
|
247
|
+
if (value === null || typeof value === "boolean" || typeof value === "string") return value;
|
|
248
|
+
if (typeof value === "number") {
|
|
249
|
+
if (!Number.isFinite(value)) throw new Error("not JSON");
|
|
250
|
+
return value;
|
|
251
|
+
}
|
|
252
|
+
if (typeof value !== "object" || depth > 64) throw new Error("not JSON");
|
|
253
|
+
const array = Array.isArray(value);
|
|
254
|
+
if (!array && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error("not JSON");
|
|
255
|
+
const keys = Reflect.ownKeys(value);
|
|
256
|
+
if (array && keys.length !== value.length + 1) throw new Error("not JSON");
|
|
257
|
+
const copy = array ? [] : {};
|
|
258
|
+
for (const key of keys) {
|
|
259
|
+
if (array && key === "length") continue;
|
|
260
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
261
|
+
if (typeof key !== "string" || !descriptor.enumerable) throw new Error("not JSON");
|
|
262
|
+
const child = plainJson(descriptor.value, depth + 1);
|
|
263
|
+
if (array) copy[Number(key)] = child;
|
|
264
|
+
else Object.defineProperty(copy, key, {
|
|
265
|
+
value: child,
|
|
266
|
+
enumerable: true,
|
|
267
|
+
writable: true,
|
|
268
|
+
configurable: true
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
return copy;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* The activity port returns unknown: accept a `failure` only on a result whose
|
|
275
|
+
* status is `failed`, only in the shape the Host reports (a fixed code and an
|
|
276
|
+
* optional plain JSON object), and only as a detached copy. Anything else is
|
|
277
|
+
* ignored, leaving the step's error text as before.
|
|
278
|
+
*/
|
|
279
|
+
function stepFailureDescriptor(result) {
|
|
280
|
+
try {
|
|
281
|
+
if (!result || typeof result !== "object") return void 0;
|
|
282
|
+
const own = (value, key) => {
|
|
283
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
284
|
+
return descriptor && Object.hasOwn(descriptor, "value") ? descriptor.value : void 0;
|
|
285
|
+
};
|
|
286
|
+
if (own(result, "status") !== "failed") return void 0;
|
|
287
|
+
const failure = own(result, "failure");
|
|
288
|
+
if (!failure || typeof failure !== "object" || Array.isArray(failure)) return void 0;
|
|
289
|
+
const code = own(failure, "code");
|
|
290
|
+
if (typeof code !== "string" || !STEP_FAILURE_CODE.test(code)) return void 0;
|
|
291
|
+
const data = own(failure, "data");
|
|
292
|
+
if (data === void 0) return { code };
|
|
293
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return void 0;
|
|
294
|
+
return {
|
|
295
|
+
code,
|
|
296
|
+
data: plainJson(data, 1)
|
|
297
|
+
};
|
|
298
|
+
} catch {
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
243
302
|
function assertDistinctSteps(steps) {
|
|
244
303
|
const seen = /* @__PURE__ */ new Set();
|
|
245
304
|
for (const step of steps) {
|
|
@@ -292,13 +351,18 @@ async function runCompensatedSaga(activity, input) {
|
|
|
292
351
|
actionId: reversal.actionId
|
|
293
352
|
};
|
|
294
353
|
try {
|
|
295
|
-
const
|
|
354
|
+
const result = await activity({
|
|
296
355
|
...scope,
|
|
297
356
|
actionId: reversal.actionId,
|
|
298
357
|
parameters: reversal.parameters ?? applied.parameters,
|
|
299
358
|
stepId: `compensate:${applied.stepId}`
|
|
300
|
-
})
|
|
301
|
-
|
|
359
|
+
});
|
|
360
|
+
const refused = stepFailure(result, `reversal "${reversal.actionId}"`);
|
|
361
|
+
if (refused) {
|
|
362
|
+
record.error = refused;
|
|
363
|
+
const failure = stepFailureDescriptor(result);
|
|
364
|
+
if (failure) record.failure = failure;
|
|
365
|
+
}
|
|
302
366
|
} catch (compensationError) {
|
|
303
367
|
record.error = compensationError instanceof Error ? compensationError.message : String(compensationError);
|
|
304
368
|
}
|
|
@@ -326,10 +390,14 @@ async function runCompensatedSaga(activity, input) {
|
|
|
326
390
|
});
|
|
327
391
|
}
|
|
328
392
|
const refused = stepFailure(result, `step "${step.stepId}"`);
|
|
329
|
-
if (refused)
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
393
|
+
if (refused) {
|
|
394
|
+
const failure = stepFailureDescriptor(result);
|
|
395
|
+
return await unwind({
|
|
396
|
+
stepId: step.stepId,
|
|
397
|
+
error: refused,
|
|
398
|
+
...failure ? { failure } : {}
|
|
399
|
+
});
|
|
400
|
+
}
|
|
333
401
|
completed.push(step.stepId);
|
|
334
402
|
if (step.compensateWith) reversals.push(step);
|
|
335
403
|
}
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../index.ts"],"sourcesContent":["import type { ActorType } from \"@fabricorg/platform\";\nimport type { WorkflowClient } from \"@temporalio/client\";\n\n/** Serializable input passed from deterministic workflows to a Platform activity. */\nexport interface GovernedActionActivityInput {\n\tactionId: string;\n\tparameters: Record<string, unknown>;\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\tworkflowId: string;\n\trunId: string;\n\tstepId: string;\n\tparentInvocationId?: string;\n}\n\nexport interface GovernedActionInvoker {\n\tinvoke(input: {\n\t\tactionId: string; parameters: Record<string, unknown>;\n\t\ttenantId: string; spaceId: string; actorId: string; actorType: ActorType;\n\t\tidempotencyKey: string; correlationId: string; causationId?: string;\n\t\texecutionEvidence: { temporalWorkflowId: string; temporalRunId: string; temporalStepId: string };\n\t}): Promise<unknown>;\n}\n\nexport function temporalInvocationIdentity(input: Pick<GovernedActionActivityInput, \"workflowId\" | \"stepId\">) {\n\treturn { idempotencyKey: `temporal:${input.workflowId}:${input.stepId}`, correlationId: `temporal:${input.workflowId}` };\n}\n\n/** Activity implementation. It always enters through the governed Host; handlers are never called directly. */\nexport function createGovernedActionActivities(invoker: GovernedActionInvoker) {\n\treturn {\n\t\tinvokeGovernedAction: async (input: GovernedActionActivityInput) => {\n\t\t\tconst identity = temporalInvocationIdentity(input);\n\t\t\treturn invoker.invoke({\n\t\t\t\tactionId: input.actionId, parameters: input.parameters,\n\t\t\t\ttenantId: input.tenantId, spaceId: input.spaceId,\n\t\t\t\tactorId: input.actorId, actorType: input.actorType,\n\t\t\t\t...identity,\n\t\t\t\t...(input.parentInvocationId ? { causationId: input.parentInvocationId } : {}),\n\t\t\t\texecutionEvidence: { temporalWorkflowId: input.workflowId, temporalRunId: input.runId, temporalStepId: input.stepId },\n\t\t\t});\n\t\t},\n\t};\n}\n\nexport interface SagaSignalEnvelope<T = unknown> {\n\tsagaId: string;\n\tsignal: string;\n\tpayload: T;\n\tactorId: string;\n\treceivedAt: string;\n\t/**\n\t * Identifies one logical signal. A sender should reuse the same value on each\n\t * redelivery of that signal, for example a webhook delivery ID or an approval\n\t * decision ID, so a retried `client.signal()` after a timeout carries the\n\t * same `signalId` as the first attempt.\n\t *\n\t * A receiver built on {@link createSagaSignalInbox} drops an envelope whose\n\t * `signalId` it has already received. Envelopes without a `signalId` are not\n\t * deduplicated. {@link createSagaSignalDispatcher} throws on a blank value\n\t * before sending.\n\t */\n\tsignalId?: string;\n}\nexport interface TemporalSignalClient { signal(workflowId: string, signalName: string, payload: unknown): Promise<void> }\nexport function createSagaSignalDispatcher(client: TemporalSignalClient) {\n\t// Not async: a synchronous throw from the client keeps propagating synchronously, as before.\n\treturn (workflowId: string, envelope: SagaSignalEnvelope) => {\n\t\tassertSignalIdentity(envelope);\n\t\treturn client.signal(workflowId, envelope.signal, envelope);\n\t};\n}\n\nfunction assertSignalIdentity(envelope: SagaSignalEnvelope): void {\n\tif (envelope.signalId === undefined) return;\n\tif (typeof envelope.signalId !== \"string\" || !envelope.signalId.trim()) {\n\t\tthrow new Error(`Saga signal \"${envelope.signal}\" for saga \"${envelope.sagaId}\" has a blank signalId; omit it or supply a stable non-blank identity.`);\n\t}\n}\n\n/** A stable identity a receiver can deduplicate on, or undefined when the envelope carries none. */\nfunction signalIdentity(envelope: SagaSignalEnvelope): string | undefined {\n\treturn typeof envelope.signalId === \"string\" && envelope.signalId.trim() ? envelope.signalId : undefined;\n}\n\n/** Serializable inbox state, as returned by {@link SagaSignalInbox.snapshot}. */\nexport interface SagaSignalInboxSnapshot {\n\t/** Signal IDs already received, so a redelivery after the handover is still dropped. */\n\tseenSignalIds: string[];\n\t/** Envelopes received but not yet taken, FIFO within each signal name. */\n\tpending: SagaSignalEnvelope[];\n}\n\nexport interface SagaSignalInboxOptions {\n\t/**\n\t * Signal IDs already received by an earlier run of this saga. Prefer passing a\n\t * whole {@link SagaSignalInbox.snapshot}: carrying IDs without `pending` drops\n\t * any envelope that was accepted but not yet taken.\n\t */\n\tseenSignalIds?: readonly string[];\n\t/**\n\t * Envelopes an earlier run accepted but did not take. They are buffered again\n\t * in order without a dedup check, since they were already accepted once.\n\t */\n\tpending?: readonly SagaSignalEnvelope[];\n}\n\nexport interface SagaSignalInbox {\n\t/**\n\t * Buffers the envelope at the back of the queue for its signal name and returns\n\t * `true`. Returns `false` and drops the envelope when its `signalId` was already\n\t * received by this inbox under any signal name. An envelope without a `signalId`\n\t * (or with a blank one) is buffered and not remembered.\n\t */\n\treceive(envelope: SagaSignalEnvelope): boolean;\n\t/** Removes and returns the oldest buffered envelope for `signalName`, or `undefined` when none is buffered. */\n\ttake<T = unknown>(signalName: string): SagaSignalEnvelope<T> | undefined;\n\t/** Number of envelopes buffered for `signalName`, for use in `condition(() => inbox.pending(name) > 0, timeout)`. */\n\tpending(signalName: string): number;\n\t/** Signal IDs received so far, carried-forward ones first, in the order they were first received. */\n\tseenSignalIds(): string[];\n\t/**\n\t * Copies the seen IDs and every buffered envelope. Pass it into the next run across\n\t * continue-as-new and hand it back to `createSagaSignalInbox()`, so neither a\n\t * redelivery nor an accepted-but-untaken signal is lost.\n\t */\n\tsnapshot(): SagaSignalInboxSnapshot;\n}\n\n/**\n * Deterministic receiver for saga signals. It has no Temporal dependency and reads\n * no clock, randomness or process-global state, so it can run inside the workflow\n * sandbox. Wire it with\n * `setHandler(defineSignal(SAGA_SIGNALS.approval), (envelope) => { inbox.receive(envelope); })`.\n *\n * Buffering is FIFO per signal name. Deduplication is keyed on `signalId` across\n * every signal name received by this inbox. Dedup state lives in this instance, so\n * it lasts for one workflow run unless the caller carries\n * {@link SagaSignalInbox.snapshot} into the next run. The remembered set grows\n * with each distinct `signalId` and is not pruned, including across\n * continue-as-new, because forgetting an ID would let its redelivery through.\n */\nexport function createSagaSignalInbox(options: SagaSignalInboxOptions = {}): SagaSignalInbox {\n\tconst seen = new Set<string>(options.seenSignalIds ?? []);\n\tconst queues = new Map<string, SagaSignalEnvelope[]>();\n\tconst enqueue = (envelope: SagaSignalEnvelope) => {\n\t\tconst queue = queues.get(envelope.signal);\n\t\tif (queue) queue.push(envelope);\n\t\telse queues.set(envelope.signal, [envelope]);\n\t};\n\tfor (const envelope of options.pending ?? []) {\n\t\tconst id = signalIdentity(envelope);\n\t\tif (id !== undefined) seen.add(id);\n\t\tenqueue(envelope);\n\t}\n\treturn {\n\t\treceive(envelope) {\n\t\t\tconst id = signalIdentity(envelope);\n\t\t\tif (id !== undefined) {\n\t\t\t\tif (seen.has(id)) return false;\n\t\t\t\tseen.add(id);\n\t\t\t}\n\t\t\tenqueue(envelope);\n\t\t\treturn true;\n\t\t},\n\t\ttake<T = unknown>(signalName: string) {\n\t\t\treturn queues.get(signalName)?.shift() as SagaSignalEnvelope<T> | undefined;\n\t\t},\n\t\tpending(signalName) {\n\t\t\treturn queues.get(signalName)?.length ?? 0;\n\t\t},\n\t\tseenSignalIds() {\n\t\t\treturn [...seen];\n\t\t},\n\t\tsnapshot() {\n\t\t\treturn { seenSignalIds: [...seen], pending: [...queues.values()].flat() };\n\t\t},\n\t};\n}\n\nexport interface WorkflowStartClient<THandle = unknown> {\n\tstart(input: { workflowType: string; workflowId: string; taskQueue: string; args: unknown[]; idConflictPolicy: \"use_existing\" }): Promise<THandle>;\n}\nexport function startGovernedWorkflow<THandle>(client: WorkflowStartClient<THandle>, input: { workflowType: string; workflowId: string; taskQueue: string; args: unknown[] }) {\n\treturn client.start({ ...input, idConflictPolicy: \"use_existing\" });\n}\n\nexport interface SagaWorkflowBinding {\n\tactionId: `${string}.${string}`;\n\tworkflowType: string;\n\ttaskQueue: string;\n}\n\n/** Instance-scoped registry; registration order never changes resolution. */\nexport class SagaWorkflowRegistry {\n\tprivate readonly bindings = new Map<string, SagaWorkflowBinding>();\n\n\tconstructor(bindings: readonly SagaWorkflowBinding[] = []) {\n\t\tfor (const binding of bindings) this.register(binding);\n\t}\n\n\tregister(binding: SagaWorkflowBinding): void {\n\t\tif (this.bindings.has(binding.actionId)) {\n\t\t\tthrow new Error(`Saga workflow binding already registered: ${binding.actionId}`);\n\t\t}\n\t\tif (!binding.workflowType.trim() || !binding.taskQueue.trim()) {\n\t\t\tthrow new Error(`Saga workflow binding ${binding.actionId} requires workflowType and taskQueue`);\n\t\t}\n\t\tthis.bindings.set(binding.actionId, { ...binding });\n\t}\n\n\trequire(actionId: string): SagaWorkflowBinding {\n\t\tconst binding = this.bindings.get(actionId);\n\t\tif (!binding) throw new Error(`No saga workflow binding registered for ${actionId}`);\n\t\treturn { ...binding };\n\t}\n}\n\nexport interface TemporalSagaDispatchInput {\n\tactionInvocationId: string;\n\tactionId: `${string}.${string}`;\n\ttenantId: string;\n\tspaceId: string;\n\tworkflowId: string;\n}\n\n/** Starts the registered parent workflow with an invocation-only durable identity. */\nexport function createTemporalSagaDispatcher<THandle>(\n\tclient: WorkflowStartClient<THandle>,\n\tregistry: SagaWorkflowRegistry,\n) {\n\treturn {\n\t\tdispatch: async (input: TemporalSagaDispatchInput) => {\n\t\t\tconst binding = registry.require(input.actionId);\n\t\t\tconst handle = await startGovernedWorkflow(client, {\n\t\t\t\tworkflowType: binding.workflowType,\n\t\t\t\tworkflowId: input.workflowId,\n\t\t\t\ttaskQueue: binding.taskQueue,\n\t\t\t\targs: [{\n\t\t\t\t\tparentInvocationId: input.actionInvocationId,\n\t\t\t\t\tactionId: input.actionId,\n\t\t\t\t\ttenantId: input.tenantId,\n\t\t\t\t\tspaceId: input.spaceId,\n\t\t\t\t}],\n\t\t\t});\n\t\t\tconst runId = runIdFromHandle(handle);\n\t\t\treturn { workflowId: input.workflowId, ...(runId ? { runId } : {}) };\n\t\t},\n\t};\n}\n\nfunction runIdFromHandle(handle: unknown): string | undefined {\n\tif (!handle || typeof handle !== \"object\") return undefined;\n\tconst candidate = (handle as { firstExecutionRunId?: unknown }).firstExecutionRunId;\n\treturn typeof candidate === \"string\" && candidate ? candidate : undefined;\n}\n\n/** Durable record of a single step completing within a saga parent. */\nexport interface SagaParentProgressRecord {\n\t/** The step that just completed. */\n\tstepId: string;\n\t/** Zero-based position of this step in the declared sequence. */\n\tindex: number;\n\t/** Total steps declared for this saga. */\n\ttotal: number;\n\t/** ISO-8601 timestamp the progress was recorded. */\n\tcompletedAt: string;\n}\n\nexport interface SagaParentProgressInput {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Stable identity shared by every retry of this lifecycle transition. */\n\tlifecycleId?: string;\n\tprogress: SagaParentProgressRecord;\n}\n\nexport interface SagaParentApprovalInput {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Stable identity shared by every retry of this lifecycle transition. */\n\tlifecycleId?: string;\n\t/** The step at which the saga paused for human approval. */\n\tstepId: string;\n\t/** Stable identifier for the approval gate, so a later signal can resume it. */\n\tapprovalId: string;\n\treason: string;\n}\n\nexport interface SagaParentCancellationInput {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Stable identity shared by every retry of this lifecycle transition. */\n\tlifecycleId?: string;\n\treason: string;\n\t/** Actor requesting the cancellation, for audit attribution. */\n\tactorId: string;\n}\n\nexport interface SagaParentLifecycle {\n\t/** Record durable progress as each step completes. */\n\trecordProgress(input: SagaParentProgressInput): Promise<void>;\n\t/** Park the parent for human approval at a specific step. */\n\tparkApproval(input: SagaParentApprovalInput): Promise<void>;\n\t/** Cancel the parent saga with an attributable reason. */\n\tcancel(input: SagaParentCancellationInput): Promise<void>;\n\t/** Complete the parent saga with its final result. */\n\tcomplete(input: { parentInvocationId: string; tenantId: string; spaceId: string; lifecycleId?: string; result: Record<string, unknown> }): Promise<void>;\n\t/** Fail the parent saga, surfacing any compensation records. */\n\tfail(input: { parentInvocationId: string; tenantId: string; spaceId: string; lifecycleId?: string; error: string; compensation: CompensationRecord[] }): Promise<void>;\n}\n\n/** Parent lifecycle remains explicit durable activities, never workflow-local state. */\nexport function createSagaParentActivities(lifecycle: SagaParentLifecycle) {\n\treturn {\n\t\trecordSagaProgress: (input: SagaParentProgressInput) => lifecycle.recordProgress({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"progress\",\n\t\t\t\t`${input.progress.stepId}:${input.progress.index}`,\n\t\t\t).idempotencyKey,\n\t\t}),\n\t\tparkSagaApproval: (input: SagaParentApprovalInput) => lifecycle.parkApproval({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"approval\",\n\t\t\t\tinput.approvalId,\n\t\t\t).idempotencyKey,\n\t\t}),\n\t\tcancelSagaParent: (input: SagaParentCancellationInput) => lifecycle.cancel({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"cancel\",\n\t\t\t).idempotencyKey,\n\t\t}),\n\t\tcompleteSagaParent: (input: Parameters<SagaParentLifecycle[\"complete\"]>[0]) =>\n\t\t\tlifecycle.complete({\n\t\t\t\t...input,\n\t\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\t\"complete\",\n\t\t\t\t).idempotencyKey,\n\t\t\t}),\n\t\tfailSagaParent: (input: Parameters<SagaParentLifecycle[\"fail\"]>[0]) => lifecycle.fail({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"fail\",\n\t\t\t).idempotencyKey,\n\t\t}),\n\t};\n}\n\n// ── Stable parent and child causation identities ───────────────────────────\n\n/**\n * Stable identity for a saga parent's own lifecycle activity (progress,\n * cancellation, approval parking, completion, failure). The activity stepId\n * is namespaced under `parent:` so it can never collide with a forward step or\n * a `compensate:` reversal.\n */\nexport function sagaParentActivityIdentity(\n\tworkflowId: string,\n\tactivity: SagaParentActivityKind,\n\tdiscriminator?: string,\n) {\n\treturn temporalInvocationIdentity({\n\t\tworkflowId,\n\t\tstepId: `parent:${activity}${discriminator ? `:${discriminator}` : \"\"}`,\n\t});\n}\n\nexport type SagaParentActivityKind = \"progress\" | \"approval\" | \"cancel\" | \"complete\" | \"fail\";\n\n/**\n * Stable causation identity linking a child step to its parent invocation.\n * The parent invocation ID becomes the causation ID; the step keeps its own\n * deterministic idempotency key and shares the workflow correlation ID.\n */\nexport function sagaChildCausation(workflowId: string, parentInvocationId: string, stepId: string) {\n\treturn { ...temporalInvocationIdentity({ workflowId, stepId }), causationId: parentInvocationId };\n}\n\n// ── Saga signal names ───────────────────────────────────────────────────────\n\n/** Stable signal names a saga workflow may register handlers for. */\nexport const SAGA_SIGNALS = {\n\tproceed: \"saga.proceed\",\n\tcancel: \"saga.cancel\",\n\tapproval: \"saga.approval\",\n} as const;\n\n/** Adapts the official Temporal TypeScript `WorkflowClient` to the narrow testable binding seam. */\nexport function temporalWorkflowStartClient(client: WorkflowClient): WorkflowStartClient {\n\treturn {\n\t\tstart: ({ workflowType, workflowId, taskQueue, args }) =>\n\t\t\tclient.start(workflowType, { workflowId, taskQueue, args, workflowIdConflictPolicy: \"USE_EXISTING\" }),\n\t};\n}\n\nexport interface WorkerVersionEvidence { buildId: string; deploymentName: string; rampPercent?: number }\nexport function assertWorkerVersionEvidence(value: WorkerVersionEvidence): void {\n\tif (!value.buildId.trim() || !value.deploymentName.trim()) throw new Error(\"Temporal worker buildId and deploymentName are required for rollover evidence.\");\n}\n\n// ── Declared compensation ───────────────────────────────────────────────────\n\nexport interface CompensatedStep {\n\t/** Workflow-local step identity. Must match the compensation declared in the module manifest. */\n\tstepId: string;\n\tactionId: string;\n\tparameters: Record<string, unknown>;\n\t/**\n\t * Governed action that reverses this step's effect. Omit for a step with\n\t * nothing to undo; a step whose effect is externally visible should declare one.\n\t */\n\tcompensateWith?: { actionId: string; parameters?: Record<string, unknown> };\n}\n\nexport interface CompensatedSagaInput {\n\tworkflowId: string;\n\trunId: string;\n\tsteps: CompensatedStep[];\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\tparentInvocationId?: string;\n\t/** When supplied, every step's reversal must match what the manifest declares. */\n\tworkflow?: DeclaredWorkflow;\n}\n\nexport interface CompensationRecord {\n\tstepId: string;\n\tactionId: string;\n\t/** Present when the reversal itself failed; the saga surfaces it rather than swallowing it. */\n\terror?: string;\n}\n\nexport interface CompensatedSagaResult {\n\tcompleted: string[];\n\tcompensated: CompensationRecord[];\n\tfailedStep?: { stepId: string; error: string };\n}\n\n/** Reversals are governed invocations too, so they carry their own stable identity. */\nexport function compensationInvocationIdentity(input: { workflowId: string; stepId: string }) {\n\treturn temporalInvocationIdentity({ workflowId: input.workflowId, stepId: `compensate:${input.stepId}` });\n}\n\nexport class SagaCompensationError extends Error {\n\toverride readonly name = \"SagaCompensationError\";\n\tconstructor(readonly result: CompensatedSagaResult) {\n\t\tsuper(`Saga step \"${result.failedStep?.stepId}\" failed: ${result.failedStep?.error}`);\n\t}\n}\n\ntype GovernedActivity = ReturnType<typeof createGovernedActionActivities>[\"invokeGovernedAction\"];\n\n/**\n * The governed Host resolves for outcomes that are not success — a blocked policy, a\n * failed validation, a reconciliation, an approval park. Treating a resolved promise\n * as a completed step would silently skip the unwind, so the status is inspected.\n */\nconst SUCCESSFUL_STATUS = \"completed\";\n\nfunction stepFailure(result: unknown, label: string): string | undefined {\n\tif (!result || typeof result !== \"object\") return undefined;\n\tconst status = (result as { status?: unknown }).status;\n\tif (typeof status !== \"string\" || status === SUCCESSFUL_STATUS) return undefined;\n\tconst error = (result as { error?: unknown }).error;\n\treturn `${label} resolved with status \"${status}\"${typeof error === \"string\" && error ? `: ${error}` : \"\"}`;\n}\n\nfunction assertDistinctSteps(steps: CompensatedStep[]): void {\n\tconst seen = new Set<string>();\n\tfor (const step of steps) {\n\t\tif (!step.stepId.trim()) throw new Error(\"Every saga step requires a stepId.\");\n\t\t// A forward step called \"compensate:x\" would share an identity with the reversal of \"x\".\n\t\tif (step.stepId.startsWith(\"compensate:\")) throw new Error(`Saga step \"${step.stepId}\" must not use the reserved \"compensate:\" prefix.`);\n\t\t// A forward step called \"parent:x\" would share an identity with a parent lifecycle activity.\n\t\tif (step.stepId.startsWith(\"parent:\")) throw new Error(`Saga step \"${step.stepId}\" must not use the reserved \"parent:\" prefix.`);\n\t\tif (seen.has(step.stepId)) throw new Error(`Saga declares duplicate step \"${step.stepId}\"; step identity must be unique within a workflow.`);\n\t\tseen.add(step.stepId);\n\t}\n}\n\n/** The manifest declaration this saga is expected to honour, when one is supplied. */\nexport interface DeclaredWorkflow {\n\tname: string;\n\tcompensations?: Array<{ step: string; actionId: string }>;\n}\n\nfunction assertMatchesDeclaration(steps: CompensatedStep[], workflow: DeclaredWorkflow): void {\n\tconst declared = new Map((workflow.compensations ?? []).map((entry) => [entry.step, entry.actionId]));\n\tfor (const step of steps) {\n\t\tconst expected = declared.get(step.stepId);\n\t\tif (expected === undefined) {\n\t\t\tif (step.compensateWith) throw new Error(`Workflow \"${workflow.name}\" step \"${step.stepId}\" supplies a reversal the manifest does not declare.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!step.compensateWith) throw new Error(`Workflow \"${workflow.name}\" step \"${step.stepId}\" omits the reversal \"${expected}\" its manifest declares.`);\n\t\tif (step.compensateWith.actionId !== expected) {\n\t\t\tthrow new Error(`Workflow \"${workflow.name}\" step \"${step.stepId}\" reverses with \"${step.compensateWith.actionId}\" but its manifest declares \"${expected}\".`);\n\t\t}\n\t}\n\tfor (const [step, actionId] of declared) {\n\t\tif (!steps.some((candidate) => candidate.stepId === step)) {\n\t\t\tthrow new Error(`Workflow \"${workflow.name}\" declares a reversal \"${actionId}\" for step \"${step}\", which this saga never runs.`);\n\t\t}\n\t}\n}\n\n/**\n * Runs steps in order, accumulating reversals as each succeeds. On failure the\n * accumulated reversals run newest-first, so an unwind never leaves an orphan.\n * Every forward step and every reversal enters through the governed Host with a\n * deterministic idempotency key, so a retried or replayed unwind is not double-applied.\n */\nexport async function runCompensatedSaga(\n\tactivity: GovernedActivity,\n\tinput: CompensatedSagaInput,\n): Promise<CompensatedSagaResult> {\n\tconst scope = {\n\t\ttenantId: input.tenantId,\n\t\tspaceId: input.spaceId,\n\t\tactorId: input.actorId,\n\t\tactorType: input.actorType,\n\t\tworkflowId: input.workflowId,\n\t\trunId: input.runId,\n\t\t...(input.parentInvocationId ? { parentInvocationId: input.parentInvocationId } : {}),\n\t};\n\tassertDistinctSteps(input.steps);\n\tif (input.workflow) assertMatchesDeclaration(input.steps, input.workflow);\n\n\tconst completed: string[] = [];\n\tconst reversals: CompensatedStep[] = [];\n\n\tconst unwind = async (failedStep: { stepId: string; error: string }): Promise<never> => {\n\t\tconst compensated: CompensationRecord[] = [];\n\t\t// Newest-first: the last effect applied is the first one withdrawn.\n\t\tfor (const applied of [...reversals].reverse()) {\n\t\t\tconst reversal = applied.compensateWith!;\n\t\t\tconst record: CompensationRecord = { stepId: applied.stepId, actionId: reversal.actionId };\n\t\t\ttry {\n\t\t\t\tconst result = await activity({\n\t\t\t\t\t...scope,\n\t\t\t\t\tactionId: reversal.actionId,\n\t\t\t\t\tparameters: reversal.parameters ?? applied.parameters,\n\t\t\t\t\tstepId: `compensate:${applied.stepId}`,\n\t\t\t\t});\n\t\t\t\tconst refused = stepFailure(result, `reversal \"${reversal.actionId}\"`);\n\t\t\t\tif (refused) record.error = refused;\n\t\t\t} catch (compensationError) {\n\t\t\t\trecord.error = compensationError instanceof Error ? compensationError.message : String(compensationError);\n\t\t\t}\n\t\t\tcompensated.push(record);\n\t\t}\n\t\tthrow new SagaCompensationError({ completed, compensated, failedStep });\n\t};\n\n\tfor (const step of input.steps) {\n\t\tlet result: unknown;\n\t\ttry {\n\t\t\tresult = await activity({ ...scope, actionId: step.actionId, parameters: step.parameters, stepId: step.stepId });\n\t\t} catch (error) {\n\t\t\treturn await unwind({ stepId: step.stepId, error: error instanceof Error ? error.message : String(error) });\n\t\t}\n\t\tconst refused = stepFailure(result, `step \"${step.stepId}\"`);\n\t\tif (refused) return await unwind({ stepId: step.stepId, error: refused });\n\t\tcompleted.push(step.stepId);\n\t\tif (step.compensateWith) reversals.push(step);\n\t}\n\n\treturn { completed, compensated: [] };\n}\n"],"mappings":";;AA0BA,SAAgB,2BAA2B,OAAmE;CAC7G,OAAO;EAAE,gBAAgB,YAAY,MAAM,WAAW,GAAG,MAAM;EAAU,eAAe,YAAY,MAAM;CAAa;AACxH;;AAGA,SAAgB,+BAA+B,SAAgC;CAC9E,OAAO,EACN,sBAAsB,OAAO,UAAuC;EACnE,MAAM,WAAW,2BAA2B,KAAK;EACjD,OAAO,QAAQ,OAAO;GACrB,UAAU,MAAM;GAAU,YAAY,MAAM;GAC5C,UAAU,MAAM;GAAU,SAAS,MAAM;GACzC,SAAS,MAAM;GAAS,WAAW,MAAM;GACzC,GAAG;GACH,GAAI,MAAM,qBAAqB,EAAE,aAAa,MAAM,mBAAmB,IAAI,CAAC;GAC5E,mBAAmB;IAAE,oBAAoB,MAAM;IAAY,eAAe,MAAM;IAAO,gBAAgB,MAAM;GAAO;EACrH,CAAC;CACF,EACD;AACD;AAsBA,SAAgB,2BAA2B,QAA8B;CAExE,QAAQ,YAAoB,aAAiC;EAC5D,qBAAqB,QAAQ;EAC7B,OAAO,OAAO,OAAO,YAAY,SAAS,QAAQ,QAAQ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import type { ActorType } from \"@fabricorg/platform\";\nimport type { WorkflowClient } from \"@temporalio/client\";\n\n/** Serializable input passed from deterministic workflows to a Platform activity. */\nexport interface GovernedActionActivityInput {\n\tactionId: string;\n\tparameters: Record<string, unknown>;\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\tworkflowId: string;\n\trunId: string;\n\tstepId: string;\n\tparentInvocationId?: string;\n}\n\nexport interface GovernedActionInvoker {\n\tinvoke(input: {\n\t\tactionId: string; parameters: Record<string, unknown>;\n\t\ttenantId: string; spaceId: string; actorId: string; actorType: ActorType;\n\t\tidempotencyKey: string; correlationId: string; causationId?: string;\n\t\texecutionEvidence: { temporalWorkflowId: string; temporalRunId: string; temporalStepId: string };\n\t}): Promise<unknown>;\n}\n\nexport function temporalInvocationIdentity(input: Pick<GovernedActionActivityInput, \"workflowId\" | \"stepId\">) {\n\treturn { idempotencyKey: `temporal:${input.workflowId}:${input.stepId}`, correlationId: `temporal:${input.workflowId}` };\n}\n\n/** Activity implementation. It always enters through the governed Host; handlers are never called directly. */\nexport function createGovernedActionActivities(invoker: GovernedActionInvoker) {\n\treturn {\n\t\tinvokeGovernedAction: async (input: GovernedActionActivityInput) => {\n\t\t\tconst identity = temporalInvocationIdentity(input);\n\t\t\treturn invoker.invoke({\n\t\t\t\tactionId: input.actionId, parameters: input.parameters,\n\t\t\t\ttenantId: input.tenantId, spaceId: input.spaceId,\n\t\t\t\tactorId: input.actorId, actorType: input.actorType,\n\t\t\t\t...identity,\n\t\t\t\t...(input.parentInvocationId ? { causationId: input.parentInvocationId } : {}),\n\t\t\t\texecutionEvidence: { temporalWorkflowId: input.workflowId, temporalRunId: input.runId, temporalStepId: input.stepId },\n\t\t\t});\n\t\t},\n\t};\n}\n\nexport interface SagaSignalEnvelope<T = unknown> {\n\tsagaId: string;\n\tsignal: string;\n\tpayload: T;\n\tactorId: string;\n\treceivedAt: string;\n\t/**\n\t * Identifies one logical signal. A sender should reuse the same value on each\n\t * redelivery of that signal, for example a webhook delivery ID or an approval\n\t * decision ID, so a retried `client.signal()` after a timeout carries the\n\t * same `signalId` as the first attempt.\n\t *\n\t * A receiver built on {@link createSagaSignalInbox} drops an envelope whose\n\t * `signalId` it has already received. Envelopes without a `signalId` are not\n\t * deduplicated. {@link createSagaSignalDispatcher} throws on a blank value\n\t * before sending.\n\t */\n\tsignalId?: string;\n}\nexport interface TemporalSignalClient { signal(workflowId: string, signalName: string, payload: unknown): Promise<void> }\nexport function createSagaSignalDispatcher(client: TemporalSignalClient) {\n\t// Not async: a synchronous throw from the client keeps propagating synchronously, as before.\n\treturn (workflowId: string, envelope: SagaSignalEnvelope) => {\n\t\tassertSignalIdentity(envelope);\n\t\treturn client.signal(workflowId, envelope.signal, envelope);\n\t};\n}\n\nfunction assertSignalIdentity(envelope: SagaSignalEnvelope): void {\n\tif (envelope.signalId === undefined) return;\n\tif (typeof envelope.signalId !== \"string\" || !envelope.signalId.trim()) {\n\t\tthrow new Error(`Saga signal \"${envelope.signal}\" for saga \"${envelope.sagaId}\" has a blank signalId; omit it or supply a stable non-blank identity.`);\n\t}\n}\n\n/** A stable identity a receiver can deduplicate on, or undefined when the envelope carries none. */\nfunction signalIdentity(envelope: SagaSignalEnvelope): string | undefined {\n\treturn typeof envelope.signalId === \"string\" && envelope.signalId.trim() ? envelope.signalId : undefined;\n}\n\n/** Serializable inbox state, as returned by {@link SagaSignalInbox.snapshot}. */\nexport interface SagaSignalInboxSnapshot {\n\t/** Signal IDs already received, so a redelivery after the handover is still dropped. */\n\tseenSignalIds: string[];\n\t/** Envelopes received but not yet taken, FIFO within each signal name. */\n\tpending: SagaSignalEnvelope[];\n}\n\nexport interface SagaSignalInboxOptions {\n\t/**\n\t * Signal IDs already received by an earlier run of this saga. Prefer passing a\n\t * whole {@link SagaSignalInbox.snapshot}: carrying IDs without `pending` drops\n\t * any envelope that was accepted but not yet taken.\n\t */\n\tseenSignalIds?: readonly string[];\n\t/**\n\t * Envelopes an earlier run accepted but did not take. They are buffered again\n\t * in order without a dedup check, since they were already accepted once.\n\t */\n\tpending?: readonly SagaSignalEnvelope[];\n}\n\nexport interface SagaSignalInbox {\n\t/**\n\t * Buffers the envelope at the back of the queue for its signal name and returns\n\t * `true`. Returns `false` and drops the envelope when its `signalId` was already\n\t * received by this inbox under any signal name. An envelope without a `signalId`\n\t * (or with a blank one) is buffered and not remembered.\n\t */\n\treceive(envelope: SagaSignalEnvelope): boolean;\n\t/** Removes and returns the oldest buffered envelope for `signalName`, or `undefined` when none is buffered. */\n\ttake<T = unknown>(signalName: string): SagaSignalEnvelope<T> | undefined;\n\t/** Number of envelopes buffered for `signalName`, for use in `condition(() => inbox.pending(name) > 0, timeout)`. */\n\tpending(signalName: string): number;\n\t/** Signal IDs received so far, carried-forward ones first, in the order they were first received. */\n\tseenSignalIds(): string[];\n\t/**\n\t * Copies the seen IDs and every buffered envelope. Pass it into the next run across\n\t * continue-as-new and hand it back to `createSagaSignalInbox()`, so neither a\n\t * redelivery nor an accepted-but-untaken signal is lost.\n\t */\n\tsnapshot(): SagaSignalInboxSnapshot;\n}\n\n/**\n * Deterministic receiver for saga signals. It has no Temporal dependency and reads\n * no clock, randomness or process-global state, so it can run inside the workflow\n * sandbox. Wire it with\n * `setHandler(defineSignal(SAGA_SIGNALS.approval), (envelope) => { inbox.receive(envelope); })`.\n *\n * Buffering is FIFO per signal name. Deduplication is keyed on `signalId` across\n * every signal name received by this inbox. Dedup state lives in this instance, so\n * it lasts for one workflow run unless the caller carries\n * {@link SagaSignalInbox.snapshot} into the next run. The remembered set grows\n * with each distinct `signalId` and is not pruned, including across\n * continue-as-new, because forgetting an ID would let its redelivery through.\n */\nexport function createSagaSignalInbox(options: SagaSignalInboxOptions = {}): SagaSignalInbox {\n\tconst seen = new Set<string>(options.seenSignalIds ?? []);\n\tconst queues = new Map<string, SagaSignalEnvelope[]>();\n\tconst enqueue = (envelope: SagaSignalEnvelope) => {\n\t\tconst queue = queues.get(envelope.signal);\n\t\tif (queue) queue.push(envelope);\n\t\telse queues.set(envelope.signal, [envelope]);\n\t};\n\tfor (const envelope of options.pending ?? []) {\n\t\tconst id = signalIdentity(envelope);\n\t\tif (id !== undefined) seen.add(id);\n\t\tenqueue(envelope);\n\t}\n\treturn {\n\t\treceive(envelope) {\n\t\t\tconst id = signalIdentity(envelope);\n\t\t\tif (id !== undefined) {\n\t\t\t\tif (seen.has(id)) return false;\n\t\t\t\tseen.add(id);\n\t\t\t}\n\t\t\tenqueue(envelope);\n\t\t\treturn true;\n\t\t},\n\t\ttake<T = unknown>(signalName: string) {\n\t\t\treturn queues.get(signalName)?.shift() as SagaSignalEnvelope<T> | undefined;\n\t\t},\n\t\tpending(signalName) {\n\t\t\treturn queues.get(signalName)?.length ?? 0;\n\t\t},\n\t\tseenSignalIds() {\n\t\t\treturn [...seen];\n\t\t},\n\t\tsnapshot() {\n\t\t\treturn { seenSignalIds: [...seen], pending: [...queues.values()].flat() };\n\t\t},\n\t};\n}\n\nexport interface WorkflowStartClient<THandle = unknown> {\n\tstart(input: { workflowType: string; workflowId: string; taskQueue: string; args: unknown[]; idConflictPolicy: \"use_existing\" }): Promise<THandle>;\n}\nexport function startGovernedWorkflow<THandle>(client: WorkflowStartClient<THandle>, input: { workflowType: string; workflowId: string; taskQueue: string; args: unknown[] }) {\n\treturn client.start({ ...input, idConflictPolicy: \"use_existing\" });\n}\n\nexport interface SagaWorkflowBinding {\n\tactionId: `${string}.${string}`;\n\tworkflowType: string;\n\ttaskQueue: string;\n}\n\n/** Instance-scoped registry; registration order never changes resolution. */\nexport class SagaWorkflowRegistry {\n\tprivate readonly bindings = new Map<string, SagaWorkflowBinding>();\n\n\tconstructor(bindings: readonly SagaWorkflowBinding[] = []) {\n\t\tfor (const binding of bindings) this.register(binding);\n\t}\n\n\tregister(binding: SagaWorkflowBinding): void {\n\t\tif (this.bindings.has(binding.actionId)) {\n\t\t\tthrow new Error(`Saga workflow binding already registered: ${binding.actionId}`);\n\t\t}\n\t\tif (!binding.workflowType.trim() || !binding.taskQueue.trim()) {\n\t\t\tthrow new Error(`Saga workflow binding ${binding.actionId} requires workflowType and taskQueue`);\n\t\t}\n\t\tthis.bindings.set(binding.actionId, { ...binding });\n\t}\n\n\trequire(actionId: string): SagaWorkflowBinding {\n\t\tconst binding = this.bindings.get(actionId);\n\t\tif (!binding) throw new Error(`No saga workflow binding registered for ${actionId}`);\n\t\treturn { ...binding };\n\t}\n}\n\nexport interface TemporalSagaDispatchInput {\n\tactionInvocationId: string;\n\tactionId: `${string}.${string}`;\n\ttenantId: string;\n\tspaceId: string;\n\tworkflowId: string;\n}\n\n/** Starts the registered parent workflow with an invocation-only durable identity. */\nexport function createTemporalSagaDispatcher<THandle>(\n\tclient: WorkflowStartClient<THandle>,\n\tregistry: SagaWorkflowRegistry,\n) {\n\treturn {\n\t\tdispatch: async (input: TemporalSagaDispatchInput) => {\n\t\t\tconst binding = registry.require(input.actionId);\n\t\t\tconst handle = await startGovernedWorkflow(client, {\n\t\t\t\tworkflowType: binding.workflowType,\n\t\t\t\tworkflowId: input.workflowId,\n\t\t\t\ttaskQueue: binding.taskQueue,\n\t\t\t\targs: [{\n\t\t\t\t\tparentInvocationId: input.actionInvocationId,\n\t\t\t\t\tactionId: input.actionId,\n\t\t\t\t\ttenantId: input.tenantId,\n\t\t\t\t\tspaceId: input.spaceId,\n\t\t\t\t}],\n\t\t\t});\n\t\t\tconst runId = runIdFromHandle(handle);\n\t\t\treturn { workflowId: input.workflowId, ...(runId ? { runId } : {}) };\n\t\t},\n\t};\n}\n\nfunction runIdFromHandle(handle: unknown): string | undefined {\n\tif (!handle || typeof handle !== \"object\") return undefined;\n\tconst candidate = (handle as { firstExecutionRunId?: unknown }).firstExecutionRunId;\n\treturn typeof candidate === \"string\" && candidate ? candidate : undefined;\n}\n\n/** Durable record of a single step completing within a saga parent. */\nexport interface SagaParentProgressRecord {\n\t/** The step that just completed. */\n\tstepId: string;\n\t/** Zero-based position of this step in the declared sequence. */\n\tindex: number;\n\t/** Total steps declared for this saga. */\n\ttotal: number;\n\t/** ISO-8601 timestamp the progress was recorded. */\n\tcompletedAt: string;\n}\n\nexport interface SagaParentProgressInput {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Stable identity shared by every retry of this lifecycle transition. */\n\tlifecycleId?: string;\n\tprogress: SagaParentProgressRecord;\n}\n\nexport interface SagaParentApprovalInput {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Stable identity shared by every retry of this lifecycle transition. */\n\tlifecycleId?: string;\n\t/** The step at which the saga paused for human approval. */\n\tstepId: string;\n\t/** Stable identifier for the approval gate, so a later signal can resume it. */\n\tapprovalId: string;\n\treason: string;\n}\n\nexport interface SagaParentCancellationInput {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Stable identity shared by every retry of this lifecycle transition. */\n\tlifecycleId?: string;\n\treason: string;\n\t/** Actor requesting the cancellation, for audit attribution. */\n\tactorId: string;\n}\n\nexport interface SagaParentLifecycle {\n\t/** Record durable progress as each step completes. */\n\trecordProgress(input: SagaParentProgressInput): Promise<void>;\n\t/** Park the parent for human approval at a specific step. */\n\tparkApproval(input: SagaParentApprovalInput): Promise<void>;\n\t/** Cancel the parent saga with an attributable reason. */\n\tcancel(input: SagaParentCancellationInput): Promise<void>;\n\t/** Complete the parent saga with its final result. */\n\tcomplete(input: { parentInvocationId: string; tenantId: string; spaceId: string; lifecycleId?: string; result: Record<string, unknown> }): Promise<void>;\n\t/** Fail the parent saga, surfacing any compensation records. */\n\tfail(input: { parentInvocationId: string; tenantId: string; spaceId: string; lifecycleId?: string; error: string; compensation: CompensationRecord[] }): Promise<void>;\n}\n\n/** Parent lifecycle remains explicit durable activities, never workflow-local state. */\nexport function createSagaParentActivities(lifecycle: SagaParentLifecycle) {\n\treturn {\n\t\trecordSagaProgress: (input: SagaParentProgressInput) => lifecycle.recordProgress({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"progress\",\n\t\t\t\t`${input.progress.stepId}:${input.progress.index}`,\n\t\t\t).idempotencyKey,\n\t\t}),\n\t\tparkSagaApproval: (input: SagaParentApprovalInput) => lifecycle.parkApproval({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"approval\",\n\t\t\t\tinput.approvalId,\n\t\t\t).idempotencyKey,\n\t\t}),\n\t\tcancelSagaParent: (input: SagaParentCancellationInput) => lifecycle.cancel({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"cancel\",\n\t\t\t).idempotencyKey,\n\t\t}),\n\t\tcompleteSagaParent: (input: Parameters<SagaParentLifecycle[\"complete\"]>[0]) =>\n\t\t\tlifecycle.complete({\n\t\t\t\t...input,\n\t\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\t\"complete\",\n\t\t\t\t).idempotencyKey,\n\t\t\t}),\n\t\tfailSagaParent: (input: Parameters<SagaParentLifecycle[\"fail\"]>[0]) => lifecycle.fail({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"fail\",\n\t\t\t).idempotencyKey,\n\t\t}),\n\t};\n}\n\n// ── Stable parent and child causation identities ───────────────────────────\n\n/**\n * Stable identity for a saga parent's own lifecycle activity (progress,\n * cancellation, approval parking, completion, failure). The activity stepId\n * is namespaced under `parent:` so it can never collide with a forward step or\n * a `compensate:` reversal.\n */\nexport function sagaParentActivityIdentity(\n\tworkflowId: string,\n\tactivity: SagaParentActivityKind,\n\tdiscriminator?: string,\n) {\n\treturn temporalInvocationIdentity({\n\t\tworkflowId,\n\t\tstepId: `parent:${activity}${discriminator ? `:${discriminator}` : \"\"}`,\n\t});\n}\n\nexport type SagaParentActivityKind = \"progress\" | \"approval\" | \"cancel\" | \"complete\" | \"fail\";\n\n/**\n * Stable causation identity linking a child step to its parent invocation.\n * The parent invocation ID becomes the causation ID; the step keeps its own\n * deterministic idempotency key and shares the workflow correlation ID.\n */\nexport function sagaChildCausation(workflowId: string, parentInvocationId: string, stepId: string) {\n\treturn { ...temporalInvocationIdentity({ workflowId, stepId }), causationId: parentInvocationId };\n}\n\n// ── Saga signal names ───────────────────────────────────────────────────────\n\n/** Stable signal names a saga workflow may register handlers for. */\nexport const SAGA_SIGNALS = {\n\tproceed: \"saga.proceed\",\n\tcancel: \"saga.cancel\",\n\tapproval: \"saga.approval\",\n} as const;\n\n/** Adapts the official Temporal TypeScript `WorkflowClient` to the narrow testable binding seam. */\nexport function temporalWorkflowStartClient(client: WorkflowClient): WorkflowStartClient {\n\treturn {\n\t\tstart: ({ workflowType, workflowId, taskQueue, args }) =>\n\t\t\tclient.start(workflowType, { workflowId, taskQueue, args, workflowIdConflictPolicy: \"USE_EXISTING\" }),\n\t};\n}\n\nexport interface WorkerVersionEvidence { buildId: string; deploymentName: string; rampPercent?: number }\nexport function assertWorkerVersionEvidence(value: WorkerVersionEvidence): void {\n\tif (!value.buildId.trim() || !value.deploymentName.trim()) throw new Error(\"Temporal worker buildId and deploymentName are required for rollover evidence.\");\n}\n\n// ── Declared compensation ───────────────────────────────────────────────────\n\nexport interface CompensatedStep {\n\t/** Workflow-local step identity. Must match the compensation declared in the module manifest. */\n\tstepId: string;\n\tactionId: string;\n\tparameters: Record<string, unknown>;\n\t/**\n\t * Governed action that reverses this step's effect. Omit for a step with\n\t * nothing to undo; a step whose effect is externally visible should declare one.\n\t */\n\tcompensateWith?: { actionId: string; parameters?: Record<string, unknown> };\n}\n\nexport interface CompensatedSagaInput {\n\tworkflowId: string;\n\trunId: string;\n\tsteps: CompensatedStep[];\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\tparentInvocationId?: string;\n\t/** When supplied, every step's reversal must match what the manifest declares. */\n\tworkflow?: DeclaredWorkflow;\n}\n\n/**\n * The declared business refusal a governed step's handler returned, as the\n * Host reports it on a `failed` result (`failure` on\n * `@fabricorg/platform-host`'s SubmitActionResult): a fixed code and optional\n * plain JSON detail. It means only that the handler returned this refusal on\n * the execution that settled the step's invocation as failed.\n */\nexport interface SagaStepFailure {\n\treadonly code: string;\n\treadonly data?: Readonly<Record<string, unknown>>;\n}\n\nexport interface CompensationRecord {\n\tstepId: string;\n\tactionId: string;\n\t/** Present when the reversal itself failed; the saga surfaces it rather than swallowing it. */\n\terror?: string;\n\t/** Present when the reversal resolved `failed` with a declared business refusal. */\n\tfailure?: SagaStepFailure;\n}\n\nexport interface CompensatedSagaFailedStep {\n\tstepId: string;\n\terror: string;\n\t/** Present when the step resolved `failed` with a declared business refusal. */\n\tfailure?: SagaStepFailure;\n}\n\nexport interface CompensatedSagaResult {\n\tcompleted: string[];\n\tcompensated: CompensationRecord[];\n\tfailedStep?: CompensatedSagaFailedStep;\n}\n\n/** Reversals are governed invocations too, so they carry their own stable identity. */\nexport function compensationInvocationIdentity(input: { workflowId: string; stepId: string }) {\n\treturn temporalInvocationIdentity({ workflowId: input.workflowId, stepId: `compensate:${input.stepId}` });\n}\n\nexport class SagaCompensationError extends Error {\n\toverride readonly name = \"SagaCompensationError\";\n\tconstructor(readonly result: CompensatedSagaResult) {\n\t\tsuper(`Saga step \"${result.failedStep?.stepId}\" failed: ${result.failedStep?.error}`);\n\t}\n}\n\ntype GovernedActivity = ReturnType<typeof createGovernedActionActivities>[\"invokeGovernedAction\"];\n\n/**\n * The governed Host resolves for outcomes that are not success — a blocked policy, a\n * failed validation, a reconciliation, an approval park. Treating a resolved promise\n * as a completed step would silently skip the unwind, so the status is inspected.\n */\nconst SUCCESSFUL_STATUS = \"completed\";\n\nfunction stepFailure(result: unknown, label: string): string | undefined {\n\tif (!result || typeof result !== \"object\") return undefined;\n\tconst status = (result as { status?: unknown }).status;\n\tif (typeof status !== \"string\" || status === SUCCESSFUL_STATUS) return undefined;\n\tconst error = (result as { error?: unknown }).error;\n\treturn `${label} resolved with status \"${status}\"${typeof error === \"string\" && error ? `: ${error}` : \"\"}`;\n}\n\n/** Fixed code syntax the Host applies to handler failure codes. */\nconst STEP_FAILURE_CODE = /^[a-z][A-Za-z0-9_.:-]{0,127}$/;\n\n/** A detached plain-JSON copy read through own data descriptors; the depth bound also ends a cycle. */\nfunction plainJson(value: unknown, depth: number): unknown {\n\tif (value === null || typeof value === \"boolean\" || typeof value === \"string\") return value;\n\tif (typeof value === \"number\") { if (!Number.isFinite(value)) throw new Error(\"not JSON\"); return value; }\n\tif (typeof value !== \"object\" || depth > 64) throw new Error(\"not JSON\");\n\tconst array = Array.isArray(value);\n\tif (!array && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error(\"not JSON\");\n\tconst keys = Reflect.ownKeys(value);\n\tif (array && keys.length !== value.length + 1) throw new Error(\"not JSON\");\n\tconst copy: unknown[] | Record<string, unknown> = array ? [] : {};\n\tfor (const key of keys) {\n\t\tif (array && key === \"length\") continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n\t\t// An accessor's descriptor has no value: undefined, which plainJson refuses, so no getter runs.\n\t\tif (typeof key !== \"string\" || !descriptor.enumerable) throw new Error(\"not JSON\");\n\t\tconst child = plainJson(descriptor.value, depth + 1);\n\t\tif (array) (copy as unknown[])[Number(key)] = child;\n\t\telse Object.defineProperty(copy, key, { value: child, enumerable: true, writable: true, configurable: true });\n\t}\n\treturn copy;\n}\n\n/**\n * The activity port returns unknown: accept a `failure` only on a result whose\n * status is `failed`, only in the shape the Host reports (a fixed code and an\n * optional plain JSON object), and only as a detached copy. Anything else is\n * ignored, leaving the step's error text as before.\n */\nfunction stepFailureDescriptor(result: unknown): SagaStepFailure | undefined {\n\ttry {\n\t\tif (!result || typeof result !== \"object\") return undefined;\n\t\tconst own = (value: object, key: string) => {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\treturn descriptor && Object.hasOwn(descriptor, \"value\") ? descriptor.value as unknown : undefined;\n\t\t};\n\t\tif (own(result, \"status\") !== \"failed\") return undefined;\n\t\tconst failure = own(result, \"failure\");\n\t\tif (!failure || typeof failure !== \"object\" || Array.isArray(failure)) return undefined;\n\t\tconst code = own(failure, \"code\");\n\t\tif (typeof code !== \"string\" || !STEP_FAILURE_CODE.test(code)) return undefined;\n\t\tconst data = own(failure, \"data\");\n\t\tif (data === undefined) return { code };\n\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) return undefined;\n\t\treturn { code, data: plainJson(data, 1) as Record<string, unknown> };\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction assertDistinctSteps(steps: CompensatedStep[]): void {\n\tconst seen = new Set<string>();\n\tfor (const step of steps) {\n\t\tif (!step.stepId.trim()) throw new Error(\"Every saga step requires a stepId.\");\n\t\t// A forward step called \"compensate:x\" would share an identity with the reversal of \"x\".\n\t\tif (step.stepId.startsWith(\"compensate:\")) throw new Error(`Saga step \"${step.stepId}\" must not use the reserved \"compensate:\" prefix.`);\n\t\t// A forward step called \"parent:x\" would share an identity with a parent lifecycle activity.\n\t\tif (step.stepId.startsWith(\"parent:\")) throw new Error(`Saga step \"${step.stepId}\" must not use the reserved \"parent:\" prefix.`);\n\t\tif (seen.has(step.stepId)) throw new Error(`Saga declares duplicate step \"${step.stepId}\"; step identity must be unique within a workflow.`);\n\t\tseen.add(step.stepId);\n\t}\n}\n\n/** The manifest declaration this saga is expected to honour, when one is supplied. */\nexport interface DeclaredWorkflow {\n\tname: string;\n\tcompensations?: Array<{ step: string; actionId: string }>;\n}\n\nfunction assertMatchesDeclaration(steps: CompensatedStep[], workflow: DeclaredWorkflow): void {\n\tconst declared = new Map((workflow.compensations ?? []).map((entry) => [entry.step, entry.actionId]));\n\tfor (const step of steps) {\n\t\tconst expected = declared.get(step.stepId);\n\t\tif (expected === undefined) {\n\t\t\tif (step.compensateWith) throw new Error(`Workflow \"${workflow.name}\" step \"${step.stepId}\" supplies a reversal the manifest does not declare.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!step.compensateWith) throw new Error(`Workflow \"${workflow.name}\" step \"${step.stepId}\" omits the reversal \"${expected}\" its manifest declares.`);\n\t\tif (step.compensateWith.actionId !== expected) {\n\t\t\tthrow new Error(`Workflow \"${workflow.name}\" step \"${step.stepId}\" reverses with \"${step.compensateWith.actionId}\" but its manifest declares \"${expected}\".`);\n\t\t}\n\t}\n\tfor (const [step, actionId] of declared) {\n\t\tif (!steps.some((candidate) => candidate.stepId === step)) {\n\t\t\tthrow new Error(`Workflow \"${workflow.name}\" declares a reversal \"${actionId}\" for step \"${step}\", which this saga never runs.`);\n\t\t}\n\t}\n}\n\n/**\n * Runs steps in order, accumulating reversals as each succeeds. On failure the\n * accumulated reversals run newest-first, so an unwind never leaves an orphan.\n * Every forward step and every reversal enters through the governed Host with a\n * deterministic idempotency key, so a retried or replayed unwind is not double-applied.\n */\nexport async function runCompensatedSaga(\n\tactivity: GovernedActivity,\n\tinput: CompensatedSagaInput,\n): Promise<CompensatedSagaResult> {\n\tconst scope = {\n\t\ttenantId: input.tenantId,\n\t\tspaceId: input.spaceId,\n\t\tactorId: input.actorId,\n\t\tactorType: input.actorType,\n\t\tworkflowId: input.workflowId,\n\t\trunId: input.runId,\n\t\t...(input.parentInvocationId ? { parentInvocationId: input.parentInvocationId } : {}),\n\t};\n\tassertDistinctSteps(input.steps);\n\tif (input.workflow) assertMatchesDeclaration(input.steps, input.workflow);\n\n\tconst completed: string[] = [];\n\tconst reversals: CompensatedStep[] = [];\n\n\tconst unwind = async (failedStep: CompensatedSagaFailedStep): Promise<never> => {\n\t\tconst compensated: CompensationRecord[] = [];\n\t\t// Newest-first: the last effect applied is the first one withdrawn.\n\t\tfor (const applied of [...reversals].reverse()) {\n\t\t\tconst reversal = applied.compensateWith!;\n\t\t\tconst record: CompensationRecord = { stepId: applied.stepId, actionId: reversal.actionId };\n\t\t\ttry {\n\t\t\t\tconst result = await activity({\n\t\t\t\t\t...scope,\n\t\t\t\t\tactionId: reversal.actionId,\n\t\t\t\t\tparameters: reversal.parameters ?? applied.parameters,\n\t\t\t\t\tstepId: `compensate:${applied.stepId}`,\n\t\t\t\t});\n\t\t\t\tconst refused = stepFailure(result, `reversal \"${reversal.actionId}\"`);\n\t\t\t\tif (refused) {\n\t\t\t\t\trecord.error = refused;\n\t\t\t\t\tconst failure = stepFailureDescriptor(result);\n\t\t\t\t\tif (failure) record.failure = failure;\n\t\t\t\t}\n\t\t\t} catch (compensationError) {\n\t\t\t\trecord.error = compensationError instanceof Error ? compensationError.message : String(compensationError);\n\t\t\t}\n\t\t\tcompensated.push(record);\n\t\t}\n\t\tthrow new SagaCompensationError({ completed, compensated, failedStep });\n\t};\n\n\tfor (const step of input.steps) {\n\t\tlet result: unknown;\n\t\ttry {\n\t\t\tresult = await activity({ ...scope, actionId: step.actionId, parameters: step.parameters, stepId: step.stepId });\n\t\t} catch (error) {\n\t\t\treturn await unwind({ stepId: step.stepId, error: error instanceof Error ? error.message : String(error) });\n\t\t}\n\t\tconst refused = stepFailure(result, `step \"${step.stepId}\"`);\n\t\tif (refused) {\n\t\t\tconst failure = stepFailureDescriptor(result);\n\t\t\treturn await unwind({ stepId: step.stepId, error: refused, ...(failure ? { failure } : {}) });\n\t\t}\n\t\tcompleted.push(step.stepId);\n\t\tif (step.compensateWith) reversals.push(step);\n\t}\n\n\treturn { completed, compensated: [] };\n}\n"],"mappings":";;AA0BA,SAAgB,2BAA2B,OAAmE;CAC7G,OAAO;EAAE,gBAAgB,YAAY,MAAM,WAAW,GAAG,MAAM;EAAU,eAAe,YAAY,MAAM;CAAa;AACxH;;AAGA,SAAgB,+BAA+B,SAAgC;CAC9E,OAAO,EACN,sBAAsB,OAAO,UAAuC;EACnE,MAAM,WAAW,2BA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match what the manifest declares. */
|
|
294
294
|
workflow?: DeclaredWorkflow;
|
|
295
295
|
}
|
|
296
|
+
/**
|
|
297
|
+
* The declared business refusal a governed step's handler returned, as the
|
|
298
|
+
* Host reports it on a `failed` result (`failure` on
|
|
299
|
+
* `@fabricorg/platform-host`'s SubmitActionResult): a fixed code and optional
|
|
300
|
+
* plain JSON detail. It means only that the handler returned this refusal on
|
|
301
|
+
* the execution that settled the step's invocation as failed.
|
|
302
|
+
*/
|
|
303
|
+
export interface SagaStepFailure {
|
|
304
|
+
readonly code: string;
|
|
305
|
+
readonly data?: Readonly<Record<string, unknown>>;
|
|
306
|
+
}
|
|
296
307
|
export interface CompensationRecord {
|
|
297
308
|
stepId: string;
|
|
298
309
|
actionId: string;
|
|
299
310
|
/** Present when the reversal itself failed; the saga surfaces it rather than swallowing it. */
|
|
300
311
|
error?: string;
|
|
312
|
+
/** Present when the reversal resolved `failed` with a declared business refusal. */
|
|
313
|
+
failure?: SagaStepFailure;
|
|
314
|
+
}
|
|
315
|
+
export interface CompensatedSagaFailedStep {
|
|
316
|
+
stepId: string;
|
|
317
|
+
error: string;
|
|
318
|
+
/** Present when the step resolved `failed` with a declared business refusal. */
|
|
319
|
+
failure?: SagaStepFailure;
|
|
301
320
|
}
|
|
302
321
|
export interface CompensatedSagaResult {
|
|
303
322
|
completed: string[];
|
|
304
323
|
compensated: CompensationRecord[];
|
|
305
|
-
failedStep?:
|
|
306
|
-
stepId: string;
|
|
307
|
-
error: string;
|
|
308
|
-
};
|
|
324
|
+
failedStep?: CompensatedSagaFailedStep;
|
|
309
325
|
}
|
|
310
326
|
/** Reversals are governed invocations too, so they carry their own stable identity. */
|
|
311
327
|
export declare function compensationInvocationIdentity(input: {
|
package/dist/index.d.ts
CHANGED
|
@@ -293,19 +293,35 @@ export interface CompensatedSagaInput {
|
|
|
293
293
|
/** When supplied, every step's reversal must match what the manifest declares. */
|
|
294
294
|
workflow?: DeclaredWorkflow;
|
|
295
295
|
}
|
|
296
|
+
/**
|
|
297
|
+
* The declared business refusal a governed step's handler returned, as the
|
|
298
|
+
* Host reports it on a `failed` result (`failure` on
|
|
299
|
+
* `@fabricorg/platform-host`'s SubmitActionResult): a fixed code and optional
|
|
300
|
+
* plain JSON detail. It means only that the handler returned this refusal on
|
|
301
|
+
* the execution that settled the step's invocation as failed.
|
|
302
|
+
*/
|
|
303
|
+
export interface SagaStepFailure {
|
|
304
|
+
readonly code: string;
|
|
305
|
+
readonly data?: Readonly<Record<string, unknown>>;
|
|
306
|
+
}
|
|
296
307
|
export interface CompensationRecord {
|
|
297
308
|
stepId: string;
|
|
298
309
|
actionId: string;
|
|
299
310
|
/** Present when the reversal itself failed; the saga surfaces it rather than swallowing it. */
|
|
300
311
|
error?: string;
|
|
312
|
+
/** Present when the reversal resolved `failed` with a declared business refusal. */
|
|
313
|
+
failure?: SagaStepFailure;
|
|
314
|
+
}
|
|
315
|
+
export interface CompensatedSagaFailedStep {
|
|
316
|
+
stepId: string;
|
|
317
|
+
error: string;
|
|
318
|
+
/** Present when the step resolved `failed` with a declared business refusal. */
|
|
319
|
+
failure?: SagaStepFailure;
|
|
301
320
|
}
|
|
302
321
|
export interface CompensatedSagaResult {
|
|
303
322
|
completed: string[];
|
|
304
323
|
compensated: CompensationRecord[];
|
|
305
|
-
failedStep?:
|
|
306
|
-
stepId: string;
|
|
307
|
-
error: string;
|
|
308
|
-
};
|
|
324
|
+
failedStep?: CompensatedSagaFailedStep;
|
|
309
325
|
}
|
|
310
326
|
/** Reversals are governed invocations too, so they carry their own stable identity. */
|
|
311
327
|
export declare function compensationInvocationIdentity(input: {
|
package/dist/index.js
CHANGED
|
@@ -239,6 +239,65 @@ function stepFailure(result, label) {
|
|
|
239
239
|
const error = result.error;
|
|
240
240
|
return `${label} resolved with status "${status}"${typeof error === "string" && error ? `: ${error}` : ""}`;
|
|
241
241
|
}
|
|
242
|
+
/** Fixed code syntax the Host applies to handler failure codes. */
|
|
243
|
+
const STEP_FAILURE_CODE = /^[a-z][A-Za-z0-9_.:-]{0,127}$/;
|
|
244
|
+
/** A detached plain-JSON copy read through own data descriptors; the depth bound also ends a cycle. */
|
|
245
|
+
function plainJson(value, depth) {
|
|
246
|
+
if (value === null || typeof value === "boolean" || typeof value === "string") return value;
|
|
247
|
+
if (typeof value === "number") {
|
|
248
|
+
if (!Number.isFinite(value)) throw new Error("not JSON");
|
|
249
|
+
return value;
|
|
250
|
+
}
|
|
251
|
+
if (typeof value !== "object" || depth > 64) throw new Error("not JSON");
|
|
252
|
+
const array = Array.isArray(value);
|
|
253
|
+
if (!array && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error("not JSON");
|
|
254
|
+
const keys = Reflect.ownKeys(value);
|
|
255
|
+
if (array && keys.length !== value.length + 1) throw new Error("not JSON");
|
|
256
|
+
const copy = array ? [] : {};
|
|
257
|
+
for (const key of keys) {
|
|
258
|
+
if (array && key === "length") continue;
|
|
259
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
260
|
+
if (typeof key !== "string" || !descriptor.enumerable) throw new Error("not JSON");
|
|
261
|
+
const child = plainJson(descriptor.value, depth + 1);
|
|
262
|
+
if (array) copy[Number(key)] = child;
|
|
263
|
+
else Object.defineProperty(copy, key, {
|
|
264
|
+
value: child,
|
|
265
|
+
enumerable: true,
|
|
266
|
+
writable: true,
|
|
267
|
+
configurable: true
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
return copy;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* The activity port returns unknown: accept a `failure` only on a result whose
|
|
274
|
+
* status is `failed`, only in the shape the Host reports (a fixed code and an
|
|
275
|
+
* optional plain JSON object), and only as a detached copy. Anything else is
|
|
276
|
+
* ignored, leaving the step's error text as before.
|
|
277
|
+
*/
|
|
278
|
+
function stepFailureDescriptor(result) {
|
|
279
|
+
try {
|
|
280
|
+
if (!result || typeof result !== "object") return void 0;
|
|
281
|
+
const own = (value, key) => {
|
|
282
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
283
|
+
return descriptor && Object.hasOwn(descriptor, "value") ? descriptor.value : void 0;
|
|
284
|
+
};
|
|
285
|
+
if (own(result, "status") !== "failed") return void 0;
|
|
286
|
+
const failure = own(result, "failure");
|
|
287
|
+
if (!failure || typeof failure !== "object" || Array.isArray(failure)) return void 0;
|
|
288
|
+
const code = own(failure, "code");
|
|
289
|
+
if (typeof code !== "string" || !STEP_FAILURE_CODE.test(code)) return void 0;
|
|
290
|
+
const data = own(failure, "data");
|
|
291
|
+
if (data === void 0) return { code };
|
|
292
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return void 0;
|
|
293
|
+
return {
|
|
294
|
+
code,
|
|
295
|
+
data: plainJson(data, 1)
|
|
296
|
+
};
|
|
297
|
+
} catch {
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
242
301
|
function assertDistinctSteps(steps) {
|
|
243
302
|
const seen = /* @__PURE__ */ new Set();
|
|
244
303
|
for (const step of steps) {
|
|
@@ -291,13 +350,18 @@ async function runCompensatedSaga(activity, input) {
|
|
|
291
350
|
actionId: reversal.actionId
|
|
292
351
|
};
|
|
293
352
|
try {
|
|
294
|
-
const
|
|
353
|
+
const result = await activity({
|
|
295
354
|
...scope,
|
|
296
355
|
actionId: reversal.actionId,
|
|
297
356
|
parameters: reversal.parameters ?? applied.parameters,
|
|
298
357
|
stepId: `compensate:${applied.stepId}`
|
|
299
|
-
})
|
|
300
|
-
|
|
358
|
+
});
|
|
359
|
+
const refused = stepFailure(result, `reversal "${reversal.actionId}"`);
|
|
360
|
+
if (refused) {
|
|
361
|
+
record.error = refused;
|
|
362
|
+
const failure = stepFailureDescriptor(result);
|
|
363
|
+
if (failure) record.failure = failure;
|
|
364
|
+
}
|
|
301
365
|
} catch (compensationError) {
|
|
302
366
|
record.error = compensationError instanceof Error ? compensationError.message : String(compensationError);
|
|
303
367
|
}
|
|
@@ -325,10 +389,14 @@ async function runCompensatedSaga(activity, input) {
|
|
|
325
389
|
});
|
|
326
390
|
}
|
|
327
391
|
const refused = stepFailure(result, `step "${step.stepId}"`);
|
|
328
|
-
if (refused)
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
392
|
+
if (refused) {
|
|
393
|
+
const failure = stepFailureDescriptor(result);
|
|
394
|
+
return await unwind({
|
|
395
|
+
stepId: step.stepId,
|
|
396
|
+
error: refused,
|
|
397
|
+
...failure ? { failure } : {}
|
|
398
|
+
});
|
|
399
|
+
}
|
|
332
400
|
completed.push(step.stepId);
|
|
333
401
|
if (step.compensateWith) reversals.push(step);
|
|
334
402
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../index.ts"],"sourcesContent":["import type { ActorType } from \"@fabricorg/platform\";\nimport type { WorkflowClient } from \"@temporalio/client\";\n\n/** Serializable input passed from deterministic workflows to a Platform activity. */\nexport interface GovernedActionActivityInput {\n\tactionId: string;\n\tparameters: Record<string, unknown>;\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\tworkflowId: string;\n\trunId: string;\n\tstepId: string;\n\tparentInvocationId?: string;\n}\n\nexport interface GovernedActionInvoker {\n\tinvoke(input: {\n\t\tactionId: string; parameters: Record<string, unknown>;\n\t\ttenantId: string; spaceId: string; actorId: string; actorType: ActorType;\n\t\tidempotencyKey: string; correlationId: string; causationId?: string;\n\t\texecutionEvidence: { temporalWorkflowId: string; temporalRunId: string; temporalStepId: string };\n\t}): Promise<unknown>;\n}\n\nexport function temporalInvocationIdentity(input: Pick<GovernedActionActivityInput, \"workflowId\" | \"stepId\">) {\n\treturn { idempotencyKey: `temporal:${input.workflowId}:${input.stepId}`, correlationId: `temporal:${input.workflowId}` };\n}\n\n/** Activity implementation. It always enters through the governed Host; handlers are never called directly. */\nexport function createGovernedActionActivities(invoker: GovernedActionInvoker) {\n\treturn {\n\t\tinvokeGovernedAction: async (input: GovernedActionActivityInput) => {\n\t\t\tconst identity = temporalInvocationIdentity(input);\n\t\t\treturn invoker.invoke({\n\t\t\t\tactionId: input.actionId, parameters: input.parameters,\n\t\t\t\ttenantId: input.tenantId, spaceId: input.spaceId,\n\t\t\t\tactorId: input.actorId, actorType: input.actorType,\n\t\t\t\t...identity,\n\t\t\t\t...(input.parentInvocationId ? { causationId: input.parentInvocationId } : {}),\n\t\t\t\texecutionEvidence: { temporalWorkflowId: input.workflowId, temporalRunId: input.runId, temporalStepId: input.stepId },\n\t\t\t});\n\t\t},\n\t};\n}\n\nexport interface SagaSignalEnvelope<T = unknown> {\n\tsagaId: string;\n\tsignal: string;\n\tpayload: T;\n\tactorId: string;\n\treceivedAt: string;\n\t/**\n\t * Identifies one logical signal. A sender should reuse the same value on each\n\t * redelivery of that signal, for example a webhook delivery ID or an approval\n\t * decision ID, so a retried `client.signal()` after a timeout carries the\n\t * same `signalId` as the first attempt.\n\t *\n\t * A receiver built on {@link createSagaSignalInbox} drops an envelope whose\n\t * `signalId` it has already received. Envelopes without a `signalId` are not\n\t * deduplicated. {@link createSagaSignalDispatcher} throws on a blank value\n\t * before sending.\n\t */\n\tsignalId?: string;\n}\nexport interface TemporalSignalClient { signal(workflowId: string, signalName: string, payload: unknown): Promise<void> }\nexport function createSagaSignalDispatcher(client: TemporalSignalClient) {\n\t// Not async: a synchronous throw from the client keeps propagating synchronously, as before.\n\treturn (workflowId: string, envelope: SagaSignalEnvelope) => {\n\t\tassertSignalIdentity(envelope);\n\t\treturn client.signal(workflowId, envelope.signal, envelope);\n\t};\n}\n\nfunction assertSignalIdentity(envelope: SagaSignalEnvelope): void {\n\tif (envelope.signalId === undefined) return;\n\tif (typeof envelope.signalId !== \"string\" || !envelope.signalId.trim()) {\n\t\tthrow new Error(`Saga signal \"${envelope.signal}\" for saga \"${envelope.sagaId}\" has a blank signalId; omit it or supply a stable non-blank identity.`);\n\t}\n}\n\n/** A stable identity a receiver can deduplicate on, or undefined when the envelope carries none. */\nfunction signalIdentity(envelope: SagaSignalEnvelope): string | undefined {\n\treturn typeof envelope.signalId === \"string\" && envelope.signalId.trim() ? envelope.signalId : undefined;\n}\n\n/** Serializable inbox state, as returned by {@link SagaSignalInbox.snapshot}. */\nexport interface SagaSignalInboxSnapshot {\n\t/** Signal IDs already received, so a redelivery after the handover is still dropped. */\n\tseenSignalIds: string[];\n\t/** Envelopes received but not yet taken, FIFO within each signal name. */\n\tpending: SagaSignalEnvelope[];\n}\n\nexport interface SagaSignalInboxOptions {\n\t/**\n\t * Signal IDs already received by an earlier run of this saga. Prefer passing a\n\t * whole {@link SagaSignalInbox.snapshot}: carrying IDs without `pending` drops\n\t * any envelope that was accepted but not yet taken.\n\t */\n\tseenSignalIds?: readonly string[];\n\t/**\n\t * Envelopes an earlier run accepted but did not take. They are buffered again\n\t * in order without a dedup check, since they were already accepted once.\n\t */\n\tpending?: readonly SagaSignalEnvelope[];\n}\n\nexport interface SagaSignalInbox {\n\t/**\n\t * Buffers the envelope at the back of the queue for its signal name and returns\n\t * `true`. Returns `false` and drops the envelope when its `signalId` was already\n\t * received by this inbox under any signal name. An envelope without a `signalId`\n\t * (or with a blank one) is buffered and not remembered.\n\t */\n\treceive(envelope: SagaSignalEnvelope): boolean;\n\t/** Removes and returns the oldest buffered envelope for `signalName`, or `undefined` when none is buffered. */\n\ttake<T = unknown>(signalName: string): SagaSignalEnvelope<T> | undefined;\n\t/** Number of envelopes buffered for `signalName`, for use in `condition(() => inbox.pending(name) > 0, timeout)`. */\n\tpending(signalName: string): number;\n\t/** Signal IDs received so far, carried-forward ones first, in the order they were first received. */\n\tseenSignalIds(): string[];\n\t/**\n\t * Copies the seen IDs and every buffered envelope. Pass it into the next run across\n\t * continue-as-new and hand it back to `createSagaSignalInbox()`, so neither a\n\t * redelivery nor an accepted-but-untaken signal is lost.\n\t */\n\tsnapshot(): SagaSignalInboxSnapshot;\n}\n\n/**\n * Deterministic receiver for saga signals. It has no Temporal dependency and reads\n * no clock, randomness or process-global state, so it can run inside the workflow\n * sandbox. Wire it with\n * `setHandler(defineSignal(SAGA_SIGNALS.approval), (envelope) => { inbox.receive(envelope); })`.\n *\n * Buffering is FIFO per signal name. Deduplication is keyed on `signalId` across\n * every signal name received by this inbox. Dedup state lives in this instance, so\n * it lasts for one workflow run unless the caller carries\n * {@link SagaSignalInbox.snapshot} into the next run. The remembered set grows\n * with each distinct `signalId` and is not pruned, including across\n * continue-as-new, because forgetting an ID would let its redelivery through.\n */\nexport function createSagaSignalInbox(options: SagaSignalInboxOptions = {}): SagaSignalInbox {\n\tconst seen = new Set<string>(options.seenSignalIds ?? []);\n\tconst queues = new Map<string, SagaSignalEnvelope[]>();\n\tconst enqueue = (envelope: SagaSignalEnvelope) => {\n\t\tconst queue = queues.get(envelope.signal);\n\t\tif (queue) queue.push(envelope);\n\t\telse queues.set(envelope.signal, [envelope]);\n\t};\n\tfor (const envelope of options.pending ?? []) {\n\t\tconst id = signalIdentity(envelope);\n\t\tif (id !== undefined) seen.add(id);\n\t\tenqueue(envelope);\n\t}\n\treturn {\n\t\treceive(envelope) {\n\t\t\tconst id = signalIdentity(envelope);\n\t\t\tif (id !== undefined) {\n\t\t\t\tif (seen.has(id)) return false;\n\t\t\t\tseen.add(id);\n\t\t\t}\n\t\t\tenqueue(envelope);\n\t\t\treturn true;\n\t\t},\n\t\ttake<T = unknown>(signalName: string) {\n\t\t\treturn queues.get(signalName)?.shift() as SagaSignalEnvelope<T> | undefined;\n\t\t},\n\t\tpending(signalName) {\n\t\t\treturn queues.get(signalName)?.length ?? 0;\n\t\t},\n\t\tseenSignalIds() {\n\t\t\treturn [...seen];\n\t\t},\n\t\tsnapshot() {\n\t\t\treturn { seenSignalIds: [...seen], pending: [...queues.values()].flat() };\n\t\t},\n\t};\n}\n\nexport interface WorkflowStartClient<THandle = unknown> {\n\tstart(input: { workflowType: string; workflowId: string; taskQueue: string; args: unknown[]; idConflictPolicy: \"use_existing\" }): Promise<THandle>;\n}\nexport function startGovernedWorkflow<THandle>(client: WorkflowStartClient<THandle>, input: { workflowType: string; workflowId: string; taskQueue: string; args: unknown[] }) {\n\treturn client.start({ ...input, idConflictPolicy: \"use_existing\" });\n}\n\nexport interface SagaWorkflowBinding {\n\tactionId: `${string}.${string}`;\n\tworkflowType: string;\n\ttaskQueue: string;\n}\n\n/** Instance-scoped registry; registration order never changes resolution. */\nexport class SagaWorkflowRegistry {\n\tprivate readonly bindings = new Map<string, SagaWorkflowBinding>();\n\n\tconstructor(bindings: readonly SagaWorkflowBinding[] = []) {\n\t\tfor (const binding of bindings) this.register(binding);\n\t}\n\n\tregister(binding: SagaWorkflowBinding): void {\n\t\tif (this.bindings.has(binding.actionId)) {\n\t\t\tthrow new Error(`Saga workflow binding already registered: ${binding.actionId}`);\n\t\t}\n\t\tif (!binding.workflowType.trim() || !binding.taskQueue.trim()) {\n\t\t\tthrow new Error(`Saga workflow binding ${binding.actionId} requires workflowType and taskQueue`);\n\t\t}\n\t\tthis.bindings.set(binding.actionId, { ...binding });\n\t}\n\n\trequire(actionId: string): SagaWorkflowBinding {\n\t\tconst binding = this.bindings.get(actionId);\n\t\tif (!binding) throw new Error(`No saga workflow binding registered for ${actionId}`);\n\t\treturn { ...binding };\n\t}\n}\n\nexport interface TemporalSagaDispatchInput {\n\tactionInvocationId: string;\n\tactionId: `${string}.${string}`;\n\ttenantId: string;\n\tspaceId: string;\n\tworkflowId: string;\n}\n\n/** Starts the registered parent workflow with an invocation-only durable identity. */\nexport function createTemporalSagaDispatcher<THandle>(\n\tclient: WorkflowStartClient<THandle>,\n\tregistry: SagaWorkflowRegistry,\n) {\n\treturn {\n\t\tdispatch: async (input: TemporalSagaDispatchInput) => {\n\t\t\tconst binding = registry.require(input.actionId);\n\t\t\tconst handle = await startGovernedWorkflow(client, {\n\t\t\t\tworkflowType: binding.workflowType,\n\t\t\t\tworkflowId: input.workflowId,\n\t\t\t\ttaskQueue: binding.taskQueue,\n\t\t\t\targs: [{\n\t\t\t\t\tparentInvocationId: input.actionInvocationId,\n\t\t\t\t\tactionId: input.actionId,\n\t\t\t\t\ttenantId: input.tenantId,\n\t\t\t\t\tspaceId: input.spaceId,\n\t\t\t\t}],\n\t\t\t});\n\t\t\tconst runId = runIdFromHandle(handle);\n\t\t\treturn { workflowId: input.workflowId, ...(runId ? { runId } : {}) };\n\t\t},\n\t};\n}\n\nfunction runIdFromHandle(handle: unknown): string | undefined {\n\tif (!handle || typeof handle !== \"object\") return undefined;\n\tconst candidate = (handle as { firstExecutionRunId?: unknown }).firstExecutionRunId;\n\treturn typeof candidate === \"string\" && candidate ? candidate : undefined;\n}\n\n/** Durable record of a single step completing within a saga parent. */\nexport interface SagaParentProgressRecord {\n\t/** The step that just completed. */\n\tstepId: string;\n\t/** Zero-based position of this step in the declared sequence. */\n\tindex: number;\n\t/** Total steps declared for this saga. */\n\ttotal: number;\n\t/** ISO-8601 timestamp the progress was recorded. */\n\tcompletedAt: string;\n}\n\nexport interface SagaParentProgressInput {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Stable identity shared by every retry of this lifecycle transition. */\n\tlifecycleId?: string;\n\tprogress: SagaParentProgressRecord;\n}\n\nexport interface SagaParentApprovalInput {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Stable identity shared by every retry of this lifecycle transition. */\n\tlifecycleId?: string;\n\t/** The step at which the saga paused for human approval. */\n\tstepId: string;\n\t/** Stable identifier for the approval gate, so a later signal can resume it. */\n\tapprovalId: string;\n\treason: string;\n}\n\nexport interface SagaParentCancellationInput {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Stable identity shared by every retry of this lifecycle transition. */\n\tlifecycleId?: string;\n\treason: string;\n\t/** Actor requesting the cancellation, for audit attribution. */\n\tactorId: string;\n}\n\nexport interface SagaParentLifecycle {\n\t/** Record durable progress as each step completes. */\n\trecordProgress(input: SagaParentProgressInput): Promise<void>;\n\t/** Park the parent for human approval at a specific step. */\n\tparkApproval(input: SagaParentApprovalInput): Promise<void>;\n\t/** Cancel the parent saga with an attributable reason. */\n\tcancel(input: SagaParentCancellationInput): Promise<void>;\n\t/** Complete the parent saga with its final result. */\n\tcomplete(input: { parentInvocationId: string; tenantId: string; spaceId: string; lifecycleId?: string; result: Record<string, unknown> }): Promise<void>;\n\t/** Fail the parent saga, surfacing any compensation records. */\n\tfail(input: { parentInvocationId: string; tenantId: string; spaceId: string; lifecycleId?: string; error: string; compensation: CompensationRecord[] }): Promise<void>;\n}\n\n/** Parent lifecycle remains explicit durable activities, never workflow-local state. */\nexport function createSagaParentActivities(lifecycle: SagaParentLifecycle) {\n\treturn {\n\t\trecordSagaProgress: (input: SagaParentProgressInput) => lifecycle.recordProgress({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"progress\",\n\t\t\t\t`${input.progress.stepId}:${input.progress.index}`,\n\t\t\t).idempotencyKey,\n\t\t}),\n\t\tparkSagaApproval: (input: SagaParentApprovalInput) => lifecycle.parkApproval({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"approval\",\n\t\t\t\tinput.approvalId,\n\t\t\t).idempotencyKey,\n\t\t}),\n\t\tcancelSagaParent: (input: SagaParentCancellationInput) => lifecycle.cancel({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"cancel\",\n\t\t\t).idempotencyKey,\n\t\t}),\n\t\tcompleteSagaParent: (input: Parameters<SagaParentLifecycle[\"complete\"]>[0]) =>\n\t\t\tlifecycle.complete({\n\t\t\t\t...input,\n\t\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\t\"complete\",\n\t\t\t\t).idempotencyKey,\n\t\t\t}),\n\t\tfailSagaParent: (input: Parameters<SagaParentLifecycle[\"fail\"]>[0]) => lifecycle.fail({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"fail\",\n\t\t\t).idempotencyKey,\n\t\t}),\n\t};\n}\n\n// ── Stable parent and child causation identities ───────────────────────────\n\n/**\n * Stable identity for a saga parent's own lifecycle activity (progress,\n * cancellation, approval parking, completion, failure). The activity stepId\n * is namespaced under `parent:` so it can never collide with a forward step or\n * a `compensate:` reversal.\n */\nexport function sagaParentActivityIdentity(\n\tworkflowId: string,\n\tactivity: SagaParentActivityKind,\n\tdiscriminator?: string,\n) {\n\treturn temporalInvocationIdentity({\n\t\tworkflowId,\n\t\tstepId: `parent:${activity}${discriminator ? `:${discriminator}` : \"\"}`,\n\t});\n}\n\nexport type SagaParentActivityKind = \"progress\" | \"approval\" | \"cancel\" | \"complete\" | \"fail\";\n\n/**\n * Stable causation identity linking a child step to its parent invocation.\n * The parent invocation ID becomes the causation ID; the step keeps its own\n * deterministic idempotency key and shares the workflow correlation ID.\n */\nexport function sagaChildCausation(workflowId: string, parentInvocationId: string, stepId: string) {\n\treturn { ...temporalInvocationIdentity({ workflowId, stepId }), causationId: parentInvocationId };\n}\n\n// ── Saga signal names ───────────────────────────────────────────────────────\n\n/** Stable signal names a saga workflow may register handlers for. */\nexport const SAGA_SIGNALS = {\n\tproceed: \"saga.proceed\",\n\tcancel: \"saga.cancel\",\n\tapproval: \"saga.approval\",\n} as const;\n\n/** Adapts the official Temporal TypeScript `WorkflowClient` to the narrow testable binding seam. */\nexport function temporalWorkflowStartClient(client: WorkflowClient): WorkflowStartClient {\n\treturn {\n\t\tstart: ({ workflowType, workflowId, taskQueue, args }) =>\n\t\t\tclient.start(workflowType, { workflowId, taskQueue, args, workflowIdConflictPolicy: \"USE_EXISTING\" }),\n\t};\n}\n\nexport interface WorkerVersionEvidence { buildId: string; deploymentName: string; rampPercent?: number }\nexport function assertWorkerVersionEvidence(value: WorkerVersionEvidence): void {\n\tif (!value.buildId.trim() || !value.deploymentName.trim()) throw new Error(\"Temporal worker buildId and deploymentName are required for rollover evidence.\");\n}\n\n// ── Declared compensation ───────────────────────────────────────────────────\n\nexport interface CompensatedStep {\n\t/** Workflow-local step identity. Must match the compensation declared in the module manifest. */\n\tstepId: string;\n\tactionId: string;\n\tparameters: Record<string, unknown>;\n\t/**\n\t * Governed action that reverses this step's effect. Omit for a step with\n\t * nothing to undo; a step whose effect is externally visible should declare one.\n\t */\n\tcompensateWith?: { actionId: string; parameters?: Record<string, unknown> };\n}\n\nexport interface CompensatedSagaInput {\n\tworkflowId: string;\n\trunId: string;\n\tsteps: CompensatedStep[];\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\tparentInvocationId?: string;\n\t/** When supplied, every step's reversal must match what the manifest declares. */\n\tworkflow?: DeclaredWorkflow;\n}\n\nexport interface CompensationRecord {\n\tstepId: string;\n\tactionId: string;\n\t/** Present when the reversal itself failed; the saga surfaces it rather than swallowing it. */\n\terror?: string;\n}\n\nexport interface CompensatedSagaResult {\n\tcompleted: string[];\n\tcompensated: CompensationRecord[];\n\tfailedStep?: { stepId: string; error: string };\n}\n\n/** Reversals are governed invocations too, so they carry their own stable identity. */\nexport function compensationInvocationIdentity(input: { workflowId: string; stepId: string }) {\n\treturn temporalInvocationIdentity({ workflowId: input.workflowId, stepId: `compensate:${input.stepId}` });\n}\n\nexport class SagaCompensationError extends Error {\n\toverride readonly name = \"SagaCompensationError\";\n\tconstructor(readonly result: CompensatedSagaResult) {\n\t\tsuper(`Saga step \"${result.failedStep?.stepId}\" failed: ${result.failedStep?.error}`);\n\t}\n}\n\ntype GovernedActivity = ReturnType<typeof createGovernedActionActivities>[\"invokeGovernedAction\"];\n\n/**\n * The governed Host resolves for outcomes that are not success — a blocked policy, a\n * failed validation, a reconciliation, an approval park. Treating a resolved promise\n * as a completed step would silently skip the unwind, so the status is inspected.\n */\nconst SUCCESSFUL_STATUS = \"completed\";\n\nfunction stepFailure(result: unknown, label: string): string | undefined {\n\tif (!result || typeof result !== \"object\") return undefined;\n\tconst status = (result as { status?: unknown }).status;\n\tif (typeof status !== \"string\" || status === SUCCESSFUL_STATUS) return undefined;\n\tconst error = (result as { error?: unknown }).error;\n\treturn `${label} resolved with status \"${status}\"${typeof error === \"string\" && error ? `: ${error}` : \"\"}`;\n}\n\nfunction assertDistinctSteps(steps: CompensatedStep[]): void {\n\tconst seen = new Set<string>();\n\tfor (const step of steps) {\n\t\tif (!step.stepId.trim()) throw new Error(\"Every saga step requires a stepId.\");\n\t\t// A forward step called \"compensate:x\" would share an identity with the reversal of \"x\".\n\t\tif (step.stepId.startsWith(\"compensate:\")) throw new Error(`Saga step \"${step.stepId}\" must not use the reserved \"compensate:\" prefix.`);\n\t\t// A forward step called \"parent:x\" would share an identity with a parent lifecycle activity.\n\t\tif (step.stepId.startsWith(\"parent:\")) throw new Error(`Saga step \"${step.stepId}\" must not use the reserved \"parent:\" prefix.`);\n\t\tif (seen.has(step.stepId)) throw new Error(`Saga declares duplicate step \"${step.stepId}\"; step identity must be unique within a workflow.`);\n\t\tseen.add(step.stepId);\n\t}\n}\n\n/** The manifest declaration this saga is expected to honour, when one is supplied. */\nexport interface DeclaredWorkflow {\n\tname: string;\n\tcompensations?: Array<{ step: string; actionId: string }>;\n}\n\nfunction assertMatchesDeclaration(steps: CompensatedStep[], workflow: DeclaredWorkflow): void {\n\tconst declared = new Map((workflow.compensations ?? []).map((entry) => [entry.step, entry.actionId]));\n\tfor (const step of steps) {\n\t\tconst expected = declared.get(step.stepId);\n\t\tif (expected === undefined) {\n\t\t\tif (step.compensateWith) throw new Error(`Workflow \"${workflow.name}\" step \"${step.stepId}\" supplies a reversal the manifest does not declare.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!step.compensateWith) throw new Error(`Workflow \"${workflow.name}\" step \"${step.stepId}\" omits the reversal \"${expected}\" its manifest declares.`);\n\t\tif (step.compensateWith.actionId !== expected) {\n\t\t\tthrow new Error(`Workflow \"${workflow.name}\" step \"${step.stepId}\" reverses with \"${step.compensateWith.actionId}\" but its manifest declares \"${expected}\".`);\n\t\t}\n\t}\n\tfor (const [step, actionId] of declared) {\n\t\tif (!steps.some((candidate) => candidate.stepId === step)) {\n\t\t\tthrow new Error(`Workflow \"${workflow.name}\" declares a reversal \"${actionId}\" for step \"${step}\", which this saga never runs.`);\n\t\t}\n\t}\n}\n\n/**\n * Runs steps in order, accumulating reversals as each succeeds. On failure the\n * accumulated reversals run newest-first, so an unwind never leaves an orphan.\n * Every forward step and every reversal enters through the governed Host with a\n * deterministic idempotency key, so a retried or replayed unwind is not double-applied.\n */\nexport async function runCompensatedSaga(\n\tactivity: GovernedActivity,\n\tinput: CompensatedSagaInput,\n): Promise<CompensatedSagaResult> {\n\tconst scope = {\n\t\ttenantId: input.tenantId,\n\t\tspaceId: input.spaceId,\n\t\tactorId: input.actorId,\n\t\tactorType: input.actorType,\n\t\tworkflowId: input.workflowId,\n\t\trunId: input.runId,\n\t\t...(input.parentInvocationId ? { parentInvocationId: input.parentInvocationId } : {}),\n\t};\n\tassertDistinctSteps(input.steps);\n\tif (input.workflow) assertMatchesDeclaration(input.steps, input.workflow);\n\n\tconst completed: string[] = [];\n\tconst reversals: CompensatedStep[] = [];\n\n\tconst unwind = async (failedStep: { stepId: string; error: string }): Promise<never> => {\n\t\tconst compensated: CompensationRecord[] = [];\n\t\t// Newest-first: the last effect applied is the first one withdrawn.\n\t\tfor (const applied of [...reversals].reverse()) {\n\t\t\tconst reversal = applied.compensateWith!;\n\t\t\tconst record: CompensationRecord = { stepId: applied.stepId, actionId: reversal.actionId };\n\t\t\ttry {\n\t\t\t\tconst result = await activity({\n\t\t\t\t\t...scope,\n\t\t\t\t\tactionId: reversal.actionId,\n\t\t\t\t\tparameters: reversal.parameters ?? applied.parameters,\n\t\t\t\t\tstepId: `compensate:${applied.stepId}`,\n\t\t\t\t});\n\t\t\t\tconst refused = stepFailure(result, `reversal \"${reversal.actionId}\"`);\n\t\t\t\tif (refused) record.error = refused;\n\t\t\t} catch (compensationError) {\n\t\t\t\trecord.error = compensationError instanceof Error ? compensationError.message : String(compensationError);\n\t\t\t}\n\t\t\tcompensated.push(record);\n\t\t}\n\t\tthrow new SagaCompensationError({ completed, compensated, failedStep });\n\t};\n\n\tfor (const step of input.steps) {\n\t\tlet result: unknown;\n\t\ttry {\n\t\t\tresult = await activity({ ...scope, actionId: step.actionId, parameters: step.parameters, stepId: step.stepId });\n\t\t} catch (error) {\n\t\t\treturn await unwind({ stepId: step.stepId, error: error instanceof Error ? error.message : String(error) });\n\t\t}\n\t\tconst refused = stepFailure(result, `step \"${step.stepId}\"`);\n\t\tif (refused) return await unwind({ stepId: step.stepId, error: refused });\n\t\tcompleted.push(step.stepId);\n\t\tif (step.compensateWith) reversals.push(step);\n\t}\n\n\treturn { completed, compensated: [] };\n}\n"],"mappings":";AA0BA,SAAgB,2BAA2B,OAAmE;CAC7G,OAAO;EAAE,gBAAgB,YAAY,MAAM,WAAW,GAAG,MAAM;EAAU,eAAe,YAAY,MAAM;CAAa;AACxH;;AAGA,SAAgB,+BAA+B,SAAgC;CAC9E,OAAO,EACN,sBAAsB,OAAO,UAAuC;EACnE,MAAM,WAAW,2BAA2B,KAAK;EACjD,OAAO,QAAQ,OAAO;GACrB,UAAU,MAAM;GAAU,YAAY,MAAM;GAC5C,UAAU,MAAM;GAAU,SAAS,MAAM;GACzC,SAAS,MAAM;GAAS,WAAW,MAAM;GACzC,GAAG;GACH,GAAI,MAAM,qBAAqB,EAAE,aAAa,MAAM,mBAAmB,IAAI,CAAC;GAC5E,mBAAmB;IAAE,oBAAoB,MAAM;IAAY,eAAe,MAAM;IAAO,gBAAgB,MAAM;GAAO;EACrH,CAAC;CACF,EACD;AACD;AAsBA,SAAgB,2BAA2B,QAA8B;CAExE,QAAQ,YAAoB,aAAiC;EAC5D,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C"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../index.ts"],"sourcesContent":["import type { ActorType } from \"@fabricorg/platform\";\nimport type { WorkflowClient } from \"@temporalio/client\";\n\n/** Serializable input passed from deterministic workflows to a Platform activity. */\nexport interface GovernedActionActivityInput {\n\tactionId: string;\n\tparameters: Record<string, unknown>;\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\tworkflowId: string;\n\trunId: string;\n\tstepId: string;\n\tparentInvocationId?: string;\n}\n\nexport interface GovernedActionInvoker {\n\tinvoke(input: {\n\t\tactionId: string; parameters: Record<string, unknown>;\n\t\ttenantId: string; spaceId: string; actorId: string; actorType: ActorType;\n\t\tidempotencyKey: string; correlationId: string; causationId?: string;\n\t\texecutionEvidence: { temporalWorkflowId: string; temporalRunId: string; temporalStepId: string };\n\t}): Promise<unknown>;\n}\n\nexport function temporalInvocationIdentity(input: Pick<GovernedActionActivityInput, \"workflowId\" | \"stepId\">) {\n\treturn { idempotencyKey: `temporal:${input.workflowId}:${input.stepId}`, correlationId: `temporal:${input.workflowId}` };\n}\n\n/** Activity implementation. It always enters through the governed Host; handlers are never called directly. */\nexport function createGovernedActionActivities(invoker: GovernedActionInvoker) {\n\treturn {\n\t\tinvokeGovernedAction: async (input: GovernedActionActivityInput) => {\n\t\t\tconst identity = temporalInvocationIdentity(input);\n\t\t\treturn invoker.invoke({\n\t\t\t\tactionId: input.actionId, parameters: input.parameters,\n\t\t\t\ttenantId: input.tenantId, spaceId: input.spaceId,\n\t\t\t\tactorId: input.actorId, actorType: input.actorType,\n\t\t\t\t...identity,\n\t\t\t\t...(input.parentInvocationId ? { causationId: input.parentInvocationId } : {}),\n\t\t\t\texecutionEvidence: { temporalWorkflowId: input.workflowId, temporalRunId: input.runId, temporalStepId: input.stepId },\n\t\t\t});\n\t\t},\n\t};\n}\n\nexport interface SagaSignalEnvelope<T = unknown> {\n\tsagaId: string;\n\tsignal: string;\n\tpayload: T;\n\tactorId: string;\n\treceivedAt: string;\n\t/**\n\t * Identifies one logical signal. A sender should reuse the same value on each\n\t * redelivery of that signal, for example a webhook delivery ID or an approval\n\t * decision ID, so a retried `client.signal()` after a timeout carries the\n\t * same `signalId` as the first attempt.\n\t *\n\t * A receiver built on {@link createSagaSignalInbox} drops an envelope whose\n\t * `signalId` it has already received. Envelopes without a `signalId` are not\n\t * deduplicated. {@link createSagaSignalDispatcher} throws on a blank value\n\t * before sending.\n\t */\n\tsignalId?: string;\n}\nexport interface TemporalSignalClient { signal(workflowId: string, signalName: string, payload: unknown): Promise<void> }\nexport function createSagaSignalDispatcher(client: TemporalSignalClient) {\n\t// Not async: a synchronous throw from the client keeps propagating synchronously, as before.\n\treturn (workflowId: string, envelope: SagaSignalEnvelope) => {\n\t\tassertSignalIdentity(envelope);\n\t\treturn client.signal(workflowId, envelope.signal, envelope);\n\t};\n}\n\nfunction assertSignalIdentity(envelope: SagaSignalEnvelope): void {\n\tif (envelope.signalId === undefined) return;\n\tif (typeof envelope.signalId !== \"string\" || !envelope.signalId.trim()) {\n\t\tthrow new Error(`Saga signal \"${envelope.signal}\" for saga \"${envelope.sagaId}\" has a blank signalId; omit it or supply a stable non-blank identity.`);\n\t}\n}\n\n/** A stable identity a receiver can deduplicate on, or undefined when the envelope carries none. */\nfunction signalIdentity(envelope: SagaSignalEnvelope): string | undefined {\n\treturn typeof envelope.signalId === \"string\" && envelope.signalId.trim() ? envelope.signalId : undefined;\n}\n\n/** Serializable inbox state, as returned by {@link SagaSignalInbox.snapshot}. */\nexport interface SagaSignalInboxSnapshot {\n\t/** Signal IDs already received, so a redelivery after the handover is still dropped. */\n\tseenSignalIds: string[];\n\t/** Envelopes received but not yet taken, FIFO within each signal name. */\n\tpending: SagaSignalEnvelope[];\n}\n\nexport interface SagaSignalInboxOptions {\n\t/**\n\t * Signal IDs already received by an earlier run of this saga. Prefer passing a\n\t * whole {@link SagaSignalInbox.snapshot}: carrying IDs without `pending` drops\n\t * any envelope that was accepted but not yet taken.\n\t */\n\tseenSignalIds?: readonly string[];\n\t/**\n\t * Envelopes an earlier run accepted but did not take. They are buffered again\n\t * in order without a dedup check, since they were already accepted once.\n\t */\n\tpending?: readonly SagaSignalEnvelope[];\n}\n\nexport interface SagaSignalInbox {\n\t/**\n\t * Buffers the envelope at the back of the queue for its signal name and returns\n\t * `true`. Returns `false` and drops the envelope when its `signalId` was already\n\t * received by this inbox under any signal name. An envelope without a `signalId`\n\t * (or with a blank one) is buffered and not remembered.\n\t */\n\treceive(envelope: SagaSignalEnvelope): boolean;\n\t/** Removes and returns the oldest buffered envelope for `signalName`, or `undefined` when none is buffered. */\n\ttake<T = unknown>(signalName: string): SagaSignalEnvelope<T> | undefined;\n\t/** Number of envelopes buffered for `signalName`, for use in `condition(() => inbox.pending(name) > 0, timeout)`. */\n\tpending(signalName: string): number;\n\t/** Signal IDs received so far, carried-forward ones first, in the order they were first received. */\n\tseenSignalIds(): string[];\n\t/**\n\t * Copies the seen IDs and every buffered envelope. Pass it into the next run across\n\t * continue-as-new and hand it back to `createSagaSignalInbox()`, so neither a\n\t * redelivery nor an accepted-but-untaken signal is lost.\n\t */\n\tsnapshot(): SagaSignalInboxSnapshot;\n}\n\n/**\n * Deterministic receiver for saga signals. It has no Temporal dependency and reads\n * no clock, randomness or process-global state, so it can run inside the workflow\n * sandbox. Wire it with\n * `setHandler(defineSignal(SAGA_SIGNALS.approval), (envelope) => { inbox.receive(envelope); })`.\n *\n * Buffering is FIFO per signal name. Deduplication is keyed on `signalId` across\n * every signal name received by this inbox. Dedup state lives in this instance, so\n * it lasts for one workflow run unless the caller carries\n * {@link SagaSignalInbox.snapshot} into the next run. The remembered set grows\n * with each distinct `signalId` and is not pruned, including across\n * continue-as-new, because forgetting an ID would let its redelivery through.\n */\nexport function createSagaSignalInbox(options: SagaSignalInboxOptions = {}): SagaSignalInbox {\n\tconst seen = new Set<string>(options.seenSignalIds ?? []);\n\tconst queues = new Map<string, SagaSignalEnvelope[]>();\n\tconst enqueue = (envelope: SagaSignalEnvelope) => {\n\t\tconst queue = queues.get(envelope.signal);\n\t\tif (queue) queue.push(envelope);\n\t\telse queues.set(envelope.signal, [envelope]);\n\t};\n\tfor (const envelope of options.pending ?? []) {\n\t\tconst id = signalIdentity(envelope);\n\t\tif (id !== undefined) seen.add(id);\n\t\tenqueue(envelope);\n\t}\n\treturn {\n\t\treceive(envelope) {\n\t\t\tconst id = signalIdentity(envelope);\n\t\t\tif (id !== undefined) {\n\t\t\t\tif (seen.has(id)) return false;\n\t\t\t\tseen.add(id);\n\t\t\t}\n\t\t\tenqueue(envelope);\n\t\t\treturn true;\n\t\t},\n\t\ttake<T = unknown>(signalName: string) {\n\t\t\treturn queues.get(signalName)?.shift() as SagaSignalEnvelope<T> | undefined;\n\t\t},\n\t\tpending(signalName) {\n\t\t\treturn queues.get(signalName)?.length ?? 0;\n\t\t},\n\t\tseenSignalIds() {\n\t\t\treturn [...seen];\n\t\t},\n\t\tsnapshot() {\n\t\t\treturn { seenSignalIds: [...seen], pending: [...queues.values()].flat() };\n\t\t},\n\t};\n}\n\nexport interface WorkflowStartClient<THandle = unknown> {\n\tstart(input: { workflowType: string; workflowId: string; taskQueue: string; args: unknown[]; idConflictPolicy: \"use_existing\" }): Promise<THandle>;\n}\nexport function startGovernedWorkflow<THandle>(client: WorkflowStartClient<THandle>, input: { workflowType: string; workflowId: string; taskQueue: string; args: unknown[] }) {\n\treturn client.start({ ...input, idConflictPolicy: \"use_existing\" });\n}\n\nexport interface SagaWorkflowBinding {\n\tactionId: `${string}.${string}`;\n\tworkflowType: string;\n\ttaskQueue: string;\n}\n\n/** Instance-scoped registry; registration order never changes resolution. */\nexport class SagaWorkflowRegistry {\n\tprivate readonly bindings = new Map<string, SagaWorkflowBinding>();\n\n\tconstructor(bindings: readonly SagaWorkflowBinding[] = []) {\n\t\tfor (const binding of bindings) this.register(binding);\n\t}\n\n\tregister(binding: SagaWorkflowBinding): void {\n\t\tif (this.bindings.has(binding.actionId)) {\n\t\t\tthrow new Error(`Saga workflow binding already registered: ${binding.actionId}`);\n\t\t}\n\t\tif (!binding.workflowType.trim() || !binding.taskQueue.trim()) {\n\t\t\tthrow new Error(`Saga workflow binding ${binding.actionId} requires workflowType and taskQueue`);\n\t\t}\n\t\tthis.bindings.set(binding.actionId, { ...binding });\n\t}\n\n\trequire(actionId: string): SagaWorkflowBinding {\n\t\tconst binding = this.bindings.get(actionId);\n\t\tif (!binding) throw new Error(`No saga workflow binding registered for ${actionId}`);\n\t\treturn { ...binding };\n\t}\n}\n\nexport interface TemporalSagaDispatchInput {\n\tactionInvocationId: string;\n\tactionId: `${string}.${string}`;\n\ttenantId: string;\n\tspaceId: string;\n\tworkflowId: string;\n}\n\n/** Starts the registered parent workflow with an invocation-only durable identity. */\nexport function createTemporalSagaDispatcher<THandle>(\n\tclient: WorkflowStartClient<THandle>,\n\tregistry: SagaWorkflowRegistry,\n) {\n\treturn {\n\t\tdispatch: async (input: TemporalSagaDispatchInput) => {\n\t\t\tconst binding = registry.require(input.actionId);\n\t\t\tconst handle = await startGovernedWorkflow(client, {\n\t\t\t\tworkflowType: binding.workflowType,\n\t\t\t\tworkflowId: input.workflowId,\n\t\t\t\ttaskQueue: binding.taskQueue,\n\t\t\t\targs: [{\n\t\t\t\t\tparentInvocationId: input.actionInvocationId,\n\t\t\t\t\tactionId: input.actionId,\n\t\t\t\t\ttenantId: input.tenantId,\n\t\t\t\t\tspaceId: input.spaceId,\n\t\t\t\t}],\n\t\t\t});\n\t\t\tconst runId = runIdFromHandle(handle);\n\t\t\treturn { workflowId: input.workflowId, ...(runId ? { runId } : {}) };\n\t\t},\n\t};\n}\n\nfunction runIdFromHandle(handle: unknown): string | undefined {\n\tif (!handle || typeof handle !== \"object\") return undefined;\n\tconst candidate = (handle as { firstExecutionRunId?: unknown }).firstExecutionRunId;\n\treturn typeof candidate === \"string\" && candidate ? candidate : undefined;\n}\n\n/** Durable record of a single step completing within a saga parent. */\nexport interface SagaParentProgressRecord {\n\t/** The step that just completed. */\n\tstepId: string;\n\t/** Zero-based position of this step in the declared sequence. */\n\tindex: number;\n\t/** Total steps declared for this saga. */\n\ttotal: number;\n\t/** ISO-8601 timestamp the progress was recorded. */\n\tcompletedAt: string;\n}\n\nexport interface SagaParentProgressInput {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Stable identity shared by every retry of this lifecycle transition. */\n\tlifecycleId?: string;\n\tprogress: SagaParentProgressRecord;\n}\n\nexport interface SagaParentApprovalInput {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Stable identity shared by every retry of this lifecycle transition. */\n\tlifecycleId?: string;\n\t/** The step at which the saga paused for human approval. */\n\tstepId: string;\n\t/** Stable identifier for the approval gate, so a later signal can resume it. */\n\tapprovalId: string;\n\treason: string;\n}\n\nexport interface SagaParentCancellationInput {\n\tparentInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\t/** Stable identity shared by every retry of this lifecycle transition. */\n\tlifecycleId?: string;\n\treason: string;\n\t/** Actor requesting the cancellation, for audit attribution. */\n\tactorId: string;\n}\n\nexport interface SagaParentLifecycle {\n\t/** Record durable progress as each step completes. */\n\trecordProgress(input: SagaParentProgressInput): Promise<void>;\n\t/** Park the parent for human approval at a specific step. */\n\tparkApproval(input: SagaParentApprovalInput): Promise<void>;\n\t/** Cancel the parent saga with an attributable reason. */\n\tcancel(input: SagaParentCancellationInput): Promise<void>;\n\t/** Complete the parent saga with its final result. */\n\tcomplete(input: { parentInvocationId: string; tenantId: string; spaceId: string; lifecycleId?: string; result: Record<string, unknown> }): Promise<void>;\n\t/** Fail the parent saga, surfacing any compensation records. */\n\tfail(input: { parentInvocationId: string; tenantId: string; spaceId: string; lifecycleId?: string; error: string; compensation: CompensationRecord[] }): Promise<void>;\n}\n\n/** Parent lifecycle remains explicit durable activities, never workflow-local state. */\nexport function createSagaParentActivities(lifecycle: SagaParentLifecycle) {\n\treturn {\n\t\trecordSagaProgress: (input: SagaParentProgressInput) => lifecycle.recordProgress({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"progress\",\n\t\t\t\t`${input.progress.stepId}:${input.progress.index}`,\n\t\t\t).idempotencyKey,\n\t\t}),\n\t\tparkSagaApproval: (input: SagaParentApprovalInput) => lifecycle.parkApproval({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"approval\",\n\t\t\t\tinput.approvalId,\n\t\t\t).idempotencyKey,\n\t\t}),\n\t\tcancelSagaParent: (input: SagaParentCancellationInput) => lifecycle.cancel({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"cancel\",\n\t\t\t).idempotencyKey,\n\t\t}),\n\t\tcompleteSagaParent: (input: Parameters<SagaParentLifecycle[\"complete\"]>[0]) =>\n\t\t\tlifecycle.complete({\n\t\t\t\t...input,\n\t\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\t\"complete\",\n\t\t\t\t).idempotencyKey,\n\t\t\t}),\n\t\tfailSagaParent: (input: Parameters<SagaParentLifecycle[\"fail\"]>[0]) => lifecycle.fail({\n\t\t\t...input,\n\t\t\tlifecycleId: input.lifecycleId ?? sagaParentActivityIdentity(\n\t\t\t\tinput.parentInvocationId,\n\t\t\t\t\"fail\",\n\t\t\t).idempotencyKey,\n\t\t}),\n\t};\n}\n\n// ── Stable parent and child causation identities ───────────────────────────\n\n/**\n * Stable identity for a saga parent's own lifecycle activity (progress,\n * cancellation, approval parking, completion, failure). The activity stepId\n * is namespaced under `parent:` so it can never collide with a forward step or\n * a `compensate:` reversal.\n */\nexport function sagaParentActivityIdentity(\n\tworkflowId: string,\n\tactivity: SagaParentActivityKind,\n\tdiscriminator?: string,\n) {\n\treturn temporalInvocationIdentity({\n\t\tworkflowId,\n\t\tstepId: `parent:${activity}${discriminator ? `:${discriminator}` : \"\"}`,\n\t});\n}\n\nexport type SagaParentActivityKind = \"progress\" | \"approval\" | \"cancel\" | \"complete\" | \"fail\";\n\n/**\n * Stable causation identity linking a child step to its parent invocation.\n * The parent invocation ID becomes the causation ID; the step keeps its own\n * deterministic idempotency key and shares the workflow correlation ID.\n */\nexport function sagaChildCausation(workflowId: string, parentInvocationId: string, stepId: string) {\n\treturn { ...temporalInvocationIdentity({ workflowId, stepId }), causationId: parentInvocationId };\n}\n\n// ── Saga signal names ───────────────────────────────────────────────────────\n\n/** Stable signal names a saga workflow may register handlers for. */\nexport const SAGA_SIGNALS = {\n\tproceed: \"saga.proceed\",\n\tcancel: \"saga.cancel\",\n\tapproval: \"saga.approval\",\n} as const;\n\n/** Adapts the official Temporal TypeScript `WorkflowClient` to the narrow testable binding seam. */\nexport function temporalWorkflowStartClient(client: WorkflowClient): WorkflowStartClient {\n\treturn {\n\t\tstart: ({ workflowType, workflowId, taskQueue, args }) =>\n\t\t\tclient.start(workflowType, { workflowId, taskQueue, args, workflowIdConflictPolicy: \"USE_EXISTING\" }),\n\t};\n}\n\nexport interface WorkerVersionEvidence { buildId: string; deploymentName: string; rampPercent?: number }\nexport function assertWorkerVersionEvidence(value: WorkerVersionEvidence): void {\n\tif (!value.buildId.trim() || !value.deploymentName.trim()) throw new Error(\"Temporal worker buildId and deploymentName are required for rollover evidence.\");\n}\n\n// ── Declared compensation ───────────────────────────────────────────────────\n\nexport interface CompensatedStep {\n\t/** Workflow-local step identity. Must match the compensation declared in the module manifest. */\n\tstepId: string;\n\tactionId: string;\n\tparameters: Record<string, unknown>;\n\t/**\n\t * Governed action that reverses this step's effect. Omit for a step with\n\t * nothing to undo; a step whose effect is externally visible should declare one.\n\t */\n\tcompensateWith?: { actionId: string; parameters?: Record<string, unknown> };\n}\n\nexport interface CompensatedSagaInput {\n\tworkflowId: string;\n\trunId: string;\n\tsteps: CompensatedStep[];\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\tparentInvocationId?: string;\n\t/** When supplied, every step's reversal must match what the manifest declares. */\n\tworkflow?: DeclaredWorkflow;\n}\n\n/**\n * The declared business refusal a governed step's handler returned, as the\n * Host reports it on a `failed` result (`failure` on\n * `@fabricorg/platform-host`'s SubmitActionResult): a fixed code and optional\n * plain JSON detail. It means only that the handler returned this refusal on\n * the execution that settled the step's invocation as failed.\n */\nexport interface SagaStepFailure {\n\treadonly code: string;\n\treadonly data?: Readonly<Record<string, unknown>>;\n}\n\nexport interface CompensationRecord {\n\tstepId: string;\n\tactionId: string;\n\t/** Present when the reversal itself failed; the saga surfaces it rather than swallowing it. */\n\terror?: string;\n\t/** Present when the reversal resolved `failed` with a declared business refusal. */\n\tfailure?: SagaStepFailure;\n}\n\nexport interface CompensatedSagaFailedStep {\n\tstepId: string;\n\terror: string;\n\t/** Present when the step resolved `failed` with a declared business refusal. */\n\tfailure?: SagaStepFailure;\n}\n\nexport interface CompensatedSagaResult {\n\tcompleted: string[];\n\tcompensated: CompensationRecord[];\n\tfailedStep?: CompensatedSagaFailedStep;\n}\n\n/** Reversals are governed invocations too, so they carry their own stable identity. */\nexport function compensationInvocationIdentity(input: { workflowId: string; stepId: string }) {\n\treturn temporalInvocationIdentity({ workflowId: input.workflowId, stepId: `compensate:${input.stepId}` });\n}\n\nexport class SagaCompensationError extends Error {\n\toverride readonly name = \"SagaCompensationError\";\n\tconstructor(readonly result: CompensatedSagaResult) {\n\t\tsuper(`Saga step \"${result.failedStep?.stepId}\" failed: ${result.failedStep?.error}`);\n\t}\n}\n\ntype GovernedActivity = ReturnType<typeof createGovernedActionActivities>[\"invokeGovernedAction\"];\n\n/**\n * The governed Host resolves for outcomes that are not success — a blocked policy, a\n * failed validation, a reconciliation, an approval park. Treating a resolved promise\n * as a completed step would silently skip the unwind, so the status is inspected.\n */\nconst SUCCESSFUL_STATUS = \"completed\";\n\nfunction stepFailure(result: unknown, label: string): string | undefined {\n\tif (!result || typeof result !== \"object\") return undefined;\n\tconst status = (result as { status?: unknown }).status;\n\tif (typeof status !== \"string\" || status === SUCCESSFUL_STATUS) return undefined;\n\tconst error = (result as { error?: unknown }).error;\n\treturn `${label} resolved with status \"${status}\"${typeof error === \"string\" && error ? `: ${error}` : \"\"}`;\n}\n\n/** Fixed code syntax the Host applies to handler failure codes. */\nconst STEP_FAILURE_CODE = /^[a-z][A-Za-z0-9_.:-]{0,127}$/;\n\n/** A detached plain-JSON copy read through own data descriptors; the depth bound also ends a cycle. */\nfunction plainJson(value: unknown, depth: number): unknown {\n\tif (value === null || typeof value === \"boolean\" || typeof value === \"string\") return value;\n\tif (typeof value === \"number\") { if (!Number.isFinite(value)) throw new Error(\"not JSON\"); return value; }\n\tif (typeof value !== \"object\" || depth > 64) throw new Error(\"not JSON\");\n\tconst array = Array.isArray(value);\n\tif (!array && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error(\"not JSON\");\n\tconst keys = Reflect.ownKeys(value);\n\tif (array && keys.length !== value.length + 1) throw new Error(\"not JSON\");\n\tconst copy: unknown[] | Record<string, unknown> = array ? [] : {};\n\tfor (const key of keys) {\n\t\tif (array && key === \"length\") continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n\t\t// An accessor's descriptor has no value: undefined, which plainJson refuses, so no getter runs.\n\t\tif (typeof key !== \"string\" || !descriptor.enumerable) throw new Error(\"not JSON\");\n\t\tconst child = plainJson(descriptor.value, depth + 1);\n\t\tif (array) (copy as unknown[])[Number(key)] = child;\n\t\telse Object.defineProperty(copy, key, { value: child, enumerable: true, writable: true, configurable: true });\n\t}\n\treturn copy;\n}\n\n/**\n * The activity port returns unknown: accept a `failure` only on a result whose\n * status is `failed`, only in the shape the Host reports (a fixed code and an\n * optional plain JSON object), and only as a detached copy. Anything else is\n * ignored, leaving the step's error text as before.\n */\nfunction stepFailureDescriptor(result: unknown): SagaStepFailure | undefined {\n\ttry {\n\t\tif (!result || typeof result !== \"object\") return undefined;\n\t\tconst own = (value: object, key: string) => {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(value, key);\n\t\t\treturn descriptor && Object.hasOwn(descriptor, \"value\") ? descriptor.value as unknown : undefined;\n\t\t};\n\t\tif (own(result, \"status\") !== \"failed\") return undefined;\n\t\tconst failure = own(result, \"failure\");\n\t\tif (!failure || typeof failure !== \"object\" || Array.isArray(failure)) return undefined;\n\t\tconst code = own(failure, \"code\");\n\t\tif (typeof code !== \"string\" || !STEP_FAILURE_CODE.test(code)) return undefined;\n\t\tconst data = own(failure, \"data\");\n\t\tif (data === undefined) return { code };\n\t\tif (!data || typeof data !== \"object\" || Array.isArray(data)) return undefined;\n\t\treturn { code, data: plainJson(data, 1) as Record<string, unknown> };\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction assertDistinctSteps(steps: CompensatedStep[]): void {\n\tconst seen = new Set<string>();\n\tfor (const step of steps) {\n\t\tif (!step.stepId.trim()) throw new Error(\"Every saga step requires a stepId.\");\n\t\t// A forward step called \"compensate:x\" would share an identity with the reversal of \"x\".\n\t\tif (step.stepId.startsWith(\"compensate:\")) throw new Error(`Saga step \"${step.stepId}\" must not use the reserved \"compensate:\" prefix.`);\n\t\t// A forward step called \"parent:x\" would share an identity with a parent lifecycle activity.\n\t\tif (step.stepId.startsWith(\"parent:\")) throw new Error(`Saga step \"${step.stepId}\" must not use the reserved \"parent:\" prefix.`);\n\t\tif (seen.has(step.stepId)) throw new Error(`Saga declares duplicate step \"${step.stepId}\"; step identity must be unique within a workflow.`);\n\t\tseen.add(step.stepId);\n\t}\n}\n\n/** The manifest declaration this saga is expected to honour, when one is supplied. */\nexport interface DeclaredWorkflow {\n\tname: string;\n\tcompensations?: Array<{ step: string; actionId: string }>;\n}\n\nfunction assertMatchesDeclaration(steps: CompensatedStep[], workflow: DeclaredWorkflow): void {\n\tconst declared = new Map((workflow.compensations ?? []).map((entry) => [entry.step, entry.actionId]));\n\tfor (const step of steps) {\n\t\tconst expected = declared.get(step.stepId);\n\t\tif (expected === undefined) {\n\t\t\tif (step.compensateWith) throw new Error(`Workflow \"${workflow.name}\" step \"${step.stepId}\" supplies a reversal the manifest does not declare.`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!step.compensateWith) throw new Error(`Workflow \"${workflow.name}\" step \"${step.stepId}\" omits the reversal \"${expected}\" its manifest declares.`);\n\t\tif (step.compensateWith.actionId !== expected) {\n\t\t\tthrow new Error(`Workflow \"${workflow.name}\" step \"${step.stepId}\" reverses with \"${step.compensateWith.actionId}\" but its manifest declares \"${expected}\".`);\n\t\t}\n\t}\n\tfor (const [step, actionId] of declared) {\n\t\tif (!steps.some((candidate) => candidate.stepId === step)) {\n\t\t\tthrow new Error(`Workflow \"${workflow.name}\" declares a reversal \"${actionId}\" for step \"${step}\", which this saga never runs.`);\n\t\t}\n\t}\n}\n\n/**\n * Runs steps in order, accumulating reversals as each succeeds. On failure the\n * accumulated reversals run newest-first, so an unwind never leaves an orphan.\n * Every forward step and every reversal enters through the governed Host with a\n * deterministic idempotency key, so a retried or replayed unwind is not double-applied.\n */\nexport async function runCompensatedSaga(\n\tactivity: GovernedActivity,\n\tinput: CompensatedSagaInput,\n): Promise<CompensatedSagaResult> {\n\tconst scope = {\n\t\ttenantId: input.tenantId,\n\t\tspaceId: input.spaceId,\n\t\tactorId: input.actorId,\n\t\tactorType: input.actorType,\n\t\tworkflowId: input.workflowId,\n\t\trunId: input.runId,\n\t\t...(input.parentInvocationId ? { parentInvocationId: input.parentInvocationId } : {}),\n\t};\n\tassertDistinctSteps(input.steps);\n\tif (input.workflow) assertMatchesDeclaration(input.steps, input.workflow);\n\n\tconst completed: string[] = [];\n\tconst reversals: CompensatedStep[] = [];\n\n\tconst unwind = async (failedStep: CompensatedSagaFailedStep): Promise<never> => {\n\t\tconst compensated: CompensationRecord[] = [];\n\t\t// Newest-first: the last effect applied is the first one withdrawn.\n\t\tfor (const applied of [...reversals].reverse()) {\n\t\t\tconst reversal = applied.compensateWith!;\n\t\t\tconst record: CompensationRecord = { stepId: applied.stepId, actionId: reversal.actionId };\n\t\t\ttry {\n\t\t\t\tconst result = await activity({\n\t\t\t\t\t...scope,\n\t\t\t\t\tactionId: reversal.actionId,\n\t\t\t\t\tparameters: reversal.parameters ?? applied.parameters,\n\t\t\t\t\tstepId: `compensate:${applied.stepId}`,\n\t\t\t\t});\n\t\t\t\tconst refused = stepFailure(result, `reversal \"${reversal.actionId}\"`);\n\t\t\t\tif (refused) {\n\t\t\t\t\trecord.error = refused;\n\t\t\t\t\tconst failure = stepFailureDescriptor(result);\n\t\t\t\t\tif (failure) record.failure = failure;\n\t\t\t\t}\n\t\t\t} catch (compensationError) {\n\t\t\t\trecord.error = compensationError instanceof Error ? compensationError.message : String(compensationError);\n\t\t\t}\n\t\t\tcompensated.push(record);\n\t\t}\n\t\tthrow new SagaCompensationError({ completed, compensated, failedStep });\n\t};\n\n\tfor (const step of input.steps) {\n\t\tlet result: unknown;\n\t\ttry {\n\t\t\tresult = await activity({ ...scope, actionId: step.actionId, parameters: step.parameters, stepId: step.stepId });\n\t\t} catch (error) {\n\t\t\treturn await unwind({ stepId: step.stepId, error: error instanceof Error ? error.message : String(error) });\n\t\t}\n\t\tconst refused = stepFailure(result, `step \"${step.stepId}\"`);\n\t\tif (refused) {\n\t\t\tconst failure = stepFailureDescriptor(result);\n\t\t\treturn await unwind({ stepId: step.stepId, error: refused, ...(failure ? { failure } : {}) });\n\t\t}\n\t\tcompleted.push(step.stepId);\n\t\tif (step.compensateWith) reversals.push(step);\n\t}\n\n\treturn { completed, compensated: [] };\n}\n"],"mappings":";AA0BA,SAAgB,2BAA2B,OAAmE;CAC7G,OAAO;EAAE,gBAAgB,YAAY,MAAM,WAAW,GAAG,MAAM;EAAU,eAAe,YAAY,MAAM;CAAa;AACxH;;AAGA,SAAgB,+BAA+B,SAAgC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6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabricorg/platform-temporal",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.4.0",
|
|
4
4
|
"description": "Temporal binding contracts for governed TechFabric Platform actions and sagas.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -33,12 +33,12 @@
|
|
|
33
33
|
"@temporalio/testing": "^1.25.0",
|
|
34
34
|
"@temporalio/worker": "^1.25.0",
|
|
35
35
|
"@temporalio/workflow": "^1.25.0",
|
|
36
|
-
"@types/node": "^22.
|
|
36
|
+
"@types/node": "^22.20.5",
|
|
37
37
|
"tsdown": "^0.23.7",
|
|
38
38
|
"typescript": "^5.7.3",
|
|
39
|
-
"vitest": "^
|
|
40
|
-
"@fabricorg/platform": "1.
|
|
41
|
-
"@fabricorg/platform-host": "8.
|
|
39
|
+
"vitest": "^5.1.0",
|
|
40
|
+
"@fabricorg/platform": "1.21.0",
|
|
41
|
+
"@fabricorg/platform-host": "8.21.0"
|
|
42
42
|
},
|
|
43
43
|
"engines": {
|
|
44
44
|
"node": ">=22"
|