@dudousxd/nestjs-durable 0.64.0 → 0.66.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/dist/index.cjs +752 -359
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +216 -23
- package/dist/index.d.ts +216 -23
- package/dist/index.js +605 -212
- package/dist/index.js.map +1 -1
- package/dist/migrate-from-nestjs-workflows.cjs +8 -2
- package/dist/migrate-from-nestjs-workflows.cjs.map +1 -1
- package/dist/migrate-from-nestjs-workflows.js +8 -2
- package/dist/migrate-from-nestjs-workflows.js.map +1 -1
- package/package.json +4 -4
- package/skills/durable-setup/SKILL.md +5 -1
- package/skills/durable-signals-and-timers/SKILL.md +12 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/attributes-of.ts","../src/decorators.ts","../src/origin.ts","../src/durable-start-client.ts","../src/tenancy.ts","../src/tenancy-reader.ts","../src/tenant-contracts.ts","../src/worker-sdk.ts","../src/durable-worker.module.ts","../src/schema-parse.ts","../src/discovery-helpers.ts","../src/on-error-handlers.ts","../src/workflow-io.ts","../src/runtime-registration.ts","../src/tokens.ts","../src/durable.module.ts","../src/durable-step.registrar.ts","../src/role.ts","../src/entity.ts","../src/in-app-worker.ts","../src/proxy-run-gateway.ts","../src/run-request-responder.ts","../src/retention-poller.ts","../src/settle-within.ts","../src/sweep-leases.ts","../src/store-run-gateway.ts","../src/tenant-event-republisher.ts","../src/timer-poller.ts","../src/workflow.registrar.ts","../src/step-interceptor.ts","../src/workflow.service.ts","../src/federated-app-gateway.ts","../src/index.ts"],"sourcesContent":["import {\n type SearchAttributes,\n type WorkflowClass,\n type WorkflowCtx,\n readSearchAttributes,\n} from '@dudousxd/nestjs-durable-core';\nimport { getWorkflowMeta } from './decorators';\n\n/**\n * The search-attributes shape a `@Workflow` class declares — extracted from its `run` method's\n * `ctx: WorkflowCtx<A>` annotation, mirroring the `WorkflowInputOf`/`WorkflowOutputOf` structural-\n * typing idiom in core's `workflow-ref.ts` (which extract `run`'s `input`/return type the same way).\n * A class whose `run` leaves `ctx` untyped (or types it as the bare `WorkflowCtx`) resolves to the\n * untyped `SearchAttributes` default — matching `WorkflowCtx` itself.\n */\nexport type WorkflowAttributesOf<C> = C extends abstract new (\n ...args: never[]\n) => {\n run(ctx: WorkflowCtx<infer A>, input: never): unknown;\n}\n ? A\n : SearchAttributes;\n\n/**\n * Read a run's search attributes **by workflow class**, with the schema resolved from that class's\n * `@Workflow({ searchAttributes })` decorator metadata — the same single-source-of-truth idiom as\n * triggering a workflow by class (`ctx.child(ShippingWorkflow, input)`, `engine.start(CheckoutWorkflow,\n * input)`): the decorator is the one place the schema lives, and every reader references the\n * WORKFLOW, never re-imports or re-declares the schema itself. The return type is inferred\n * structurally from the class's `run(ctx: WorkflowCtx<A>, …)` annotation (see\n * {@link WorkflowAttributesOf}), so a valid read is typed to `A` with no explicit type argument.\n *\n * Delegates to core's `readSearchAttributes(schema, run)` for the actual read, so the same lenient\n * safe-parse semantics apply: a run whose stored `searchAttributes` predate the schema, or fail it,\n * reads back as `{}` rather than throwing (see `readSearchAttributes`'s doc comment).\n *\n * @throws if `workflow` isn't a `@Workflow`-decorated class (no metadata at all — nothing to resolve\n * the schema from).\n * @throws if `workflow` is a `@Workflow` class that never declared a `searchAttributes` schema —\n * reading attributes by class needs one to resolve against.\n *\n * @example\n * ```ts\n * import { z } from 'zod';\n * import { Injectable } from '@nestjs/common';\n * import {\n * attributesOf,\n * InferSearchAttributes,\n * Workflow,\n * WorkflowCtx,\n * WorkflowHandler,\n * } from '@dudousxd/nestjs-durable';\n *\n * const orderAttrs = z.object({ tier: z.enum(['free', 'pro']), amount: z.number() });\n * type OrderAttrs = InferSearchAttributes<typeof orderAttrs>;\n *\n * @Workflow({ name: 'checkout', searchAttributes: orderAttrs })\n * class CheckoutWorkflow implements WorkflowHandler<{ orderId: string }, void, OrderAttrs> {\n * async run(ctx: WorkflowCtx<OrderAttrs>, input: { orderId: string }): Promise<void> {\n * await ctx.upsertSearchAttributes({ tier: 'pro', amount: 100 });\n * }\n * }\n *\n * @Injectable()\n * class CheckoutDashboardService {\n * constructor(private readonly store: StateStore) {}\n *\n * async tierOf(runId: string) {\n * const run = await this.store.getRun(runId);\n * const attrs = attributesOf(CheckoutWorkflow, run ?? {}); // OrderAttrs\n * return attrs.tier;\n * }\n * }\n * ```\n */\nexport function attributesOf<C extends WorkflowClass>(\n workflow: C,\n run: { searchAttributes?: SearchAttributes | null | undefined },\n): WorkflowAttributesOf<C> {\n // biome-ignore lint/complexity/noBannedTypes: getWorkflowMeta reads reflect-metadata off the class target, same contract as workflowName/bindWorkflowClass\n const meta = getWorkflowMeta(workflow as unknown as Function);\n if (!meta) {\n throw new Error(\n `attributesOf: ${workflow.name} is not a @Workflow class — is it decorated with @Workflow({ name, searchAttributes })?`,\n );\n }\n if (!meta.searchAttributes) {\n throw new Error(\n `attributesOf: workflow '${meta.name}' declares no searchAttributes schema — reading attributes by class requires the workflow to declare its schema: @Workflow({ name: '${meta.name}', searchAttributes: mySchema }).`,\n );\n }\n return readSearchAttributes(meta.searchAttributes, run) as WorkflowAttributesOf<C>;\n}\n","import {\n type ConcurrencyConfig,\n DURABLE_STEP_CONFIG,\n DURABLE_STEP_NAME,\n type EventBatchConfig,\n type LifecycleEventOf,\n type OnErrorInput,\n type OnEventEntry,\n type SearchAttributesSchema,\n type SingletonConfig,\n type StepConfig,\n type StepError,\n WORKFLOW_NAME_KEY,\n type WorkflowClass,\n type WorkflowCtx,\n type WorkflowLifecycleEvent,\n type WorkflowRef,\n parseDuration,\n runCompletedEvent,\n runFailedEvent,\n} from '@dudousxd/nestjs-durable-core';\nimport 'reflect-metadata';\nimport { declaringFile, rememberDeclaringFile } from './origin';\nimport type { IoSchema } from './schema-parse';\n\nexport const WORKFLOW_METADATA = Symbol('nestjs-durable:workflow');\n\nexport interface WorkflowMeta {\n name: string;\n version: string;\n /** The workflow this workflow's dead runs route to (a name or a class). See `WorkflowOptions`. */\n deadLetterWorkflow?: WorkflowRef | undefined;\n /** Where failed runs are routed by error code. See `WorkflowOptions`. */\n onError?: { code?: string | ErrorClassWithCode; workflow: WorkflowRef }[] | undefined;\n /** Static searchable labels stamped on every run of this workflow. See `WorkflowOptions`. */\n tags?: string[] | undefined;\n /** Per-key serialization (a durable mutex). See `WorkflowOptions`. */\n singleton?: SingletonConfig | undefined;\n /** Start-time concurrency quota (rejecting). See `WorkflowOptions`. */\n concurrency?: ConcurrencyConfig | undefined;\n /** Max wall-clock lifetime before a run is cancelled (e.g. `'2h'`). See `WorkflowOptions`. */\n executionTimeout?: string | number | undefined;\n /** Input schema (Standard Schema or DTO class), parsed at start and before every turn. See\n * `WorkflowOptions`. */\n input?: IoSchema | undefined;\n /** Output schema, parsed before the run completes. See `WorkflowOptions`. */\n output?: IoSchema | undefined;\n /** Custom input validator (throws on invalid). See `WorkflowOptions`. */\n validateInput?: ((input: unknown) => void | Promise<void>) | undefined;\n /** Typed/validated `searchAttributes` shape. See `WorkflowOptions`. */\n searchAttributes?: SearchAttributesSchema | undefined;\n /** Events that start a fresh run of this workflow. See `WorkflowOptions`. */\n onEvent?: OnEventEntry[] | undefined;\n /** Debounce `onEvent` triggers — fire once it's quiet for this long. See `WorkflowOptions`. */\n debounce?: string | number | undefined;\n /** Batch `onEvent` triggers — fire on size or window. See `WorkflowOptions`. */\n batch?: { maxSize: number; within: string | number } | undefined;\n /** Capabilities a live worker must advertise to run this workflow's turns (handshake §7.5). See\n * `WorkflowOptions`. */\n requires?: string[] | undefined;\n}\n\nexport interface WorkflowOptions {\n name: string;\n version?: string;\n /**\n * Route this workflow's dead-lettered runs to another **registered** workflow — by class\n * (`deadLetterWorkflow: CheckoutDlqWorkflow`, refactor-safe) or by name for a cross-runtime\n * handler. For a handler co-located on the same class, prefer an inline `@DeadLetter()` method\n * instead — it takes precedence, and declaring both is a boot-time error. The handler receives a\n * {@link DeadLetter} payload, idempotent by a `dlq:<runId>` id.\n */\n deadLetterWorkflow?: WorkflowRef;\n /**\n * Route failed runs of this workflow to other **registered** workflows by error code — the\n * separate-class form of an `@OnError` method (see it for the semantics). Each handler receives an\n * {@link OnErrorInput}; omit `code` for the catch-all. A code routed here and by an `@OnError`\n * method on the class is a boot-time error.\n */\n onError?: { code?: string | ErrorClassWithCode; workflow: WorkflowRef }[];\n /**\n * Static labels stamped on **every run** of this workflow (e.g. `tags: ['etl', 'critical']`) and\n * merged with any per-run tags passed to `start`. Searchable/filterable in the dashboard.\n */\n tags?: string[];\n /**\n * Serialize runs of this workflow that share a key — a durable FIFO mutex. e.g.\n * `singleton: { key: (input) => `base:${input.baseId}` }` runs at most one pipeline per base at a\n * time; same-key runs queue (suspended) and admit in creation order as slots free. `limit` (default\n * 1) raises the concurrency.\n */\n singleton?: SingletonConfig;\n /**\n * A start-time concurrency QUOTA: at most `limit` runs sharing a key in flight, and a start over it\n * is REJECTED (`ConcurrencyLimitError`, nothing created) rather than queued. e.g.\n * `concurrency: { key: (input) => `tenant:${input.tenantId}`, limit: 8 }` caps what one tenant can\n * have executing at once. The key is shared across workflows; `limit` may be a (async) function of\n * the key for per-plan limits; `countStatuses` narrows what occupies a slot (default: every\n * non-terminal status). Use `singleton` instead when excess runs should wait their turn.\n */\n concurrency?: ConcurrencyConfig;\n /**\n * Max wall-clock lifetime for a run of this workflow (e.g. `'2h'`, `'7 days'`, or ms), counted from\n * the run's creation. A run that outlives it is moved to `cancelled` (`execution_timeout`) by the\n * timer poller — whether it is `pending`, `blocked`, `running` or `suspended` — a backstop for runs\n * that get stuck, loop forever or are never picked up. A run in `cancelling` finishes its saga undo\n * instead. Omit for no limit.\n */\n executionTimeout?: string | number;\n /**\n * Capabilities a live worker MUST advertise to run this workflow's turns (handshake design §7.5).\n * Only meaningful for a group-served / remote workflow (an in-app worker or a cross-runtime body):\n * the control-plane dispatches a turn only to a capability-capable + protocol-compatible worker, and\n * if descriptors are published on its group but none qualifies the run parks `blocked` until the\n * recovery poll finds one. Absent/empty = \"runs anywhere\" (a legacy fleet skips the guard, §7.7).\n */\n requires?: string[];\n /**\n * The run's input schema — a **Standard Schema** (zod 3.24+, valibot, arktype, …) or a\n * **class-validator DTO class** (the same `plainToInstance` + `validate` NestJS's `ValidationPipe`\n * runs; needs the optional peers `class-validator` + `class-transformer`). The same option\n * `@Step({ input })` takes.\n *\n * Parsed at `start`, so invalid input is rejected before any run is created. The run stores the\n * input **as it was sent**; `run(ctx, input)` receives the **parsed** value (coerced/transformed —\n * a `Date` from `z.coerce.date()`, a DTO instance), re-parsed from the stored input before every\n * turn, so a replay sees the same value the first execution did. The schema must therefore be\n * deterministic (no `default(() => Date.now())`), and changing it is a breaking change to the\n * workflow — bump `version`. A stored input that no longer parses fails the run with\n * `code: 'invalid_input'`.\n *\n * `@Workflow({ name: 'checkout', input: CheckoutInput })` or `input: z.object({ … })`.\n */\n input?: IoSchema;\n /**\n * The run's output schema (same forms as {@link input}). The value `run()` returns is parsed before\n * the run completes, and the parsed value is what the run stores as its output. A mismatch fails the\n * run with `code: 'invalid_output'`. The same option `@Step({ output })` takes.\n */\n output?: IoSchema;\n /**\n * A custom check at `start` (throw to reject) for a rule a schema can't express — a cross-field\n * invariant, an async lookup. It runs after `input` parses and receives the parsed value (the input\n * as sent when there is no `input` schema).\n */\n validateInput?: (input: unknown) => void | Promise<void>;\n /**\n * Validate this workflow's {@link WorkflowCtx.upsertSearchAttributes} writes against a **Standard\n * Schema** (https://standardschema.dev — zod 3.24+, valibot, arktype, …). `ctx.upsertSearchAttributes`\n * validates the MERGED result (existing attributes shallow-merged with the patch) on every call —\n * an invalid merge throws a `SchemaValidationError` (code `schema_validation`) naming this workflow,\n * with the schema's issues. The\n * schema's inferred output must be search-attribute-shaped (flat `string`/`number`/`boolean` values\n * only) — a schema whose output has a nested object/array is a compile-time error here. Omit for\n * the prior unvalidated behavior.\n *\n * ```ts\n * import { z } from 'zod';\n *\n * const orderAttrs = z.object({\n * tier: z.enum(['free', 'pro']),\n * amount: z.number(),\n * });\n *\n * @Workflow({ name: 'checkout', searchAttributes: orderAttrs })\n * class CheckoutWorkflow {\n * async run(ctx: WorkflowCtx<InferSearchAttributes<typeof orderAttrs>>, input: CheckoutInput) {\n * await ctx.upsertSearchAttributes({ tier: input.tier, amount: input.total });\n * }\n * }\n * ```\n */\n searchAttributes?: SearchAttributesSchema;\n /**\n * Start a fresh run of this workflow whenever any of these events is published via\n * `publishEvent(name, payload)` — the payload becomes the run's input. e.g.\n * `onEvent: ['user.registered', 'user.invited']`. The same subscription can also be declared with\n * the `@OnDurableEvent(...)` class decorator; the two are merged. An entry can also be\n * `{ event, where }`, where `where(payload)` decides per event whether this workflow starts.\n */\n onEvent?: OnEventEntry[];\n /**\n * Coalesce `onEvent` triggers by **debouncing** — start one run only once events have been quiet\n * for this long (resets on each event), with the LAST payload. e.g. `debounce: '30s'`.\n */\n debounce?: string | number;\n /**\n * Coalesce `onEvent` triggers by **batching** — start one run with all payloads (`{ events: [...] }`)\n * once `maxSize` is reached or `within` elapses from the first event. e.g.\n * `batch: { maxSize: 100, within: '10s' }`.\n */\n batch?: { maxSize: number; within: string | number };\n}\n\n/**\n * Marks a provider class as a durable workflow. Its `run(ctx, input)` method becomes the\n * workflow function the engine executes and replays.\n */\nexport function Workflow(options: WorkflowOptions): ClassDecorator {\n // Captured HERE, in the factory, because this is the one moment we are provably executing inside\n // the module that declares the workflow — by the time a registrar scans providers, the only thing\n // left of that module is a class object with no file on it. The path is resolved to the owning\n // package lazily, at registration (see `origin.ts`); a runtime that yields no usable frame simply\n // leaves the workflow unattributed, which the registrar reports at boot.\n const declaredIn = declaringFile(Workflow);\n return (target) => {\n rememberDeclaringFile(target, declaredIn);\n const meta: WorkflowMeta = {\n name: options.name,\n version: options.version ?? '1',\n deadLetterWorkflow: options.deadLetterWorkflow,\n onError: options.onError,\n tags: options.tags,\n singleton: options.singleton,\n concurrency: options.concurrency,\n executionTimeout: options.executionTimeout,\n input: options.input,\n output: options.output,\n validateInput: options.validateInput,\n searchAttributes: options.searchAttributes,\n onEvent: options.onEvent,\n debounce: options.debounce,\n batch: options.batch,\n requires: options.requires,\n };\n Reflect.defineMetadata(WORKFLOW_METADATA, meta, target);\n // Stamp the registered name so this class can be used as a typed workflow ref (ctx.child,\n // engine.start, deadLetterWorkflow) and resolved back to its name via `workflowName`.\n Object.defineProperty(target, WORKFLOW_NAME_KEY, {\n value: options.name,\n configurable: true,\n });\n };\n}\n\n// biome-ignore lint/complexity/noBannedTypes: matches reflect-metadata's class target type\nexport function getWorkflowMeta(target: Function): WorkflowMeta | undefined {\n return Reflect.getMetadata(WORKFLOW_METADATA, target) as WorkflowMeta | undefined;\n}\n\nexport const DURABLE_STEP_METADATA = Symbol('nestjs-durable:step-handler');\n\nexport interface DurableStepMeta {\n /** The resolved routing name — derived (`Class.method`) or explicit, always present. */\n name: string;\n /** Opt-in runtime input schema, validated when the handler is served (see `scanSteps`). Absent on\n * a bare `@Step()` — compile-time types from the method signature only, no runtime check. */\n input?: IoSchema | undefined;\n /** Opt-in runtime output schema, validated before the handler's result is handed back. */\n output?: IoSchema | undefined;\n}\n\n/**\n * `@Step({ name?, input?, output?, retries?, backoff?, backoffMs?, backoffMaxMs?, jitter?,\n * timeoutMs? })` — the object call form. See {@link Step}.\n */\nexport interface StepOptions {\n /** Explicit routing name, overriding the derived `Class.method`. */\n name?: string;\n /** Runtime input schema, validated at the serve boundary (opt-in — a bare `@Step()` skips it). A\n * Standard Schema (zod, valibot, …) or a class-validator DTO class — the same forms\n * `@Workflow({ input })` takes. The method receives the parsed value. */\n input?: IoSchema;\n /** Runtime output schema, validated before the result is returned (opt-in). */\n output?: IoSchema;\n /**\n * Def-level durable-dispatch policy stamped under `DURABLE_STEP_CONFIG` and read by `ctx.step` at\n * the dispatch boundary (see `stepConfigOf`) — a per-call `ctx.step(ref, input, opts)` overrides\n * these field-by-field. Max attempts before the step (and run) fails.\n */\n retries?: number;\n /** How the delay between retries grows: `fixed` (constant) or `exp` (doubles each attempt). */\n backoff?: 'fixed' | 'exp';\n /** Base delay in ms between retries. Omit (or 0) to retry with no delay. */\n backoffMs?: number;\n /** Upper bound on the (exponential) backoff delay. */\n backoffMaxMs?: number;\n /** Add random jitter (50–100% of the computed delay) to avoid thundering-herd retries. */\n jitter?: boolean;\n /**\n * Liveness window for a dispatched step: no result/heartbeat within this many ms presumes the\n * worker dead and fails the dispatch with a `RemoteStepTimeout` (retryable — re-dispatches per\n * `retries`). Omit to wait indefinitely.\n */\n timeoutMs?: number;\n /**\n * Capabilities a live worker MUST advertise to run this step (handshake design §7.5). The\n * control-plane routes the step only to workers whose descriptor advertises every name here; if\n * descriptors are published on the step's group but none is capability-capable + protocol-compatible,\n * the run parks `blocked` (never a silent hang) until the recovery poll finds one. Absent/empty =\n * \"runs anywhere\" (the default — a legacy fleet publishing no descriptors skips the guard, §7.7). A\n * per-call `ctx.step(ref, input, { requires })` overrides this.\n */\n requires?: string[];\n}\n\n/** Build the {@link StepConfig} to stamp under `DURABLE_STEP_CONFIG` from `@Step` options — omitting\n * every unset field, so a bare `@Step()` (or one with only `name`/`input`/`output`) stamps `undefined`\n * and leaves `ctx.step` reading nothing but a per-call `opts` override. */\nfunction stepConfigFrom(options: StepOptions): StepConfig | undefined {\n const config: StepConfig = {\n retries: options.retries,\n backoff: options.backoff,\n backoffMs: options.backoffMs,\n backoffMaxMs: options.backoffMaxMs,\n jitter: options.jitter,\n timeoutMs: options.timeoutMs,\n requires: options.requires,\n };\n const hasAnyField = Object.values(config).some((value) => value !== undefined);\n return hasAnyField ? config : undefined;\n}\n\n/**\n * Marks a provider method as a durable step handler. An in-process transport (e.g. the\n * event-emitter transport) or a co-located/thin worker runtime routes a dispatched task to it BY\n * NAME — `ctx.step(this.svc.method, input)` reads that same name off the method reference (stamped\n * via the shared, cross-package `DURABLE_STEP_NAME` symbol from `@dudousxd/nestjs-durable-core`), so\n * there's no separately-declared def linking a call site to this handler. The method's single\n * argument is the step input (plus an optional `StepLogger` second arg); its return value is the\n * step output.\n *\n * Three call forms:\n * - `@Step()` — bare: the routing name is DERIVED from the method as `` `${ClassName}.${method}` ``\n * (e.g. `ExtractionService.runExtractionPage`) — refactor-safe, no magic string.\n * - `@Step('custom:name')` — explicit name override (stable across refactors, or a cross-runtime\n * contract with a non-JS worker that has no `@Step` of its own).\n * - `@Step({ name?, input?, output?, retries?, backoff?, backoffMs?, backoffMaxMs?, jitter?,\n * timeoutMs? })` — optional name override, opt-in RUNTIME schemas (a Standard Schema or a DTO\n * class), and a def-level durable-retry/liveness-timeout policy. `input` validates before the method runs; `output`\n * validates its return value before it's handed back (see `scanSteps`). `retries`/`backoff`/\n * `backoffMs`/`backoffMaxMs`/`jitter`/`timeoutMs` are the policy `ctx.step` reads off this method\n * reference (via `stepConfigOf`) to build the dispatched `StepDef`'s durable retry/backoff and\n * remote-liveness timeout — a per-call `ctx.step(ref, input, opts)` overrides them field-by-field.\n * A bare `@Step()` carries none of this and skips validation/retry/timeout — compile-time types\n * from the method signature are the only check, and the step dispatches with no retry/timeout.\n */\nexport function Step(nameOrOptions?: string | StepOptions): MethodDecorator {\n return (target, propertyKey, descriptor: PropertyDescriptor) => {\n const options =\n typeof nameOrOptions === 'string' ? { name: nameOrOptions } : (nameOrOptions ?? {});\n const derivedName = options.name ?? `${target.constructor.name}.${String(propertyKey)}`;\n const meta: DurableStepMeta = {\n name: derivedName,\n input: options.input,\n output: options.output,\n };\n Reflect.defineMetadata(DURABLE_STEP_METADATA, meta, descriptor.value as object);\n // Stamp the SAME resolved name core's `ctx.step` reads off a method reference (`stepNameOf`) —\n // the cross-package contract letting `ctx.step(this.svc.method, input)` route without a\n // separately-declared def. `DURABLE_STEP_NAME` is core's `Symbol.for`-keyed constant, so a\n // duplicate copy of core still reads back the same key (see `step-name-symbol.ts`).\n (descriptor.value as { [DURABLE_STEP_NAME]?: string })[DURABLE_STEP_NAME] = derivedName;\n // Stamp the def-level dispatch policy (retries/backoff/timeoutMs) core's `ctx.step` reads via\n // `stepConfigOf`, under the same `Symbol.for`-keyed contract as `DURABLE_STEP_NAME`. Omitted\n // entirely when no policy field is set, so a bare `@Step()` stamps nothing extra.\n const config = stepConfigFrom(options);\n if (config !== undefined) {\n (descriptor.value as { [DURABLE_STEP_CONFIG]?: StepConfig })[DURABLE_STEP_CONFIG] = config;\n }\n return descriptor;\n };\n}\n\n// biome-ignore lint/complexity/noBannedTypes: reflect-metadata reads from the method function\nexport function getDurableStepMeta(method: Function): DurableStepMeta | undefined {\n return Reflect.getMetadata(DURABLE_STEP_METADATA, method) as DurableStepMeta | undefined;\n}\n\nexport const DEAD_LETTER_METADATA = Symbol('nestjs-durable:dead-letter');\n\n/**\n * The payload a dead-letter handler receives: the dead run's id, its workflow, the input it was\n * started with (typed via `TInput`), and the failure that killed it.\n */\nexport interface DeadLetter<TInput = unknown> {\n /** Id of the run that was dead-lettered (inspectable + retriable in the dashboard). */\n deadRunId: string;\n /** Name of the workflow whose run died. */\n workflow: string;\n /** The original input the dead run was started with. */\n input: TInput;\n /** The structured error that moved the run to `dead`, when known. */\n error?: StepError;\n}\n\n/**\n * Marks a method on a `@Workflow` class as that workflow's **inline dead-letter handler**. When a\n * run of the workflow is moved to `dead` (exceeded `maxRecoveryAttempts`), this method runs — as a\n * durable workflow itself, auto-registered as `<workflow>.dlq` with a `dlq:<runId>` id — receiving a\n * {@link DeadLetter} payload. It shares the class's injected dependencies, so the handler lives in\n * the same file as the workflow it protects.\n *\n * Takes precedence over `@Workflow({ deadLetterWorkflow })` and the module-level `deadLetterWorkflow`\n * default. The method signature is `(ctx, dead)` — the same `ctx` a workflow `run` gets.\n */\nexport function DeadLetter(): MethodDecorator {\n return (_target, _propertyKey, descriptor: PropertyDescriptor) => {\n Reflect.defineMetadata(DEAD_LETTER_METADATA, true, descriptor.value as object);\n return descriptor;\n };\n}\n\n// biome-ignore lint/complexity/noBannedTypes: reflect-metadata reads from the method function\nexport function isDeadLetterHandler(method: Function): boolean {\n return Reflect.getMetadata(DEAD_LETTER_METADATA, method) === true;\n}\n\nexport const ON_ERROR_METADATA = Symbol('nestjs-durable:on-error');\n\n/**\n * An error class that declares the `code` it is thrown with (`static readonly code = 'invalid_line'`).\n * `@OnError(Class)` matches on that code, not on `instanceof`: a dispatched step's error reaches the\n * workflow as a plain `{ message, code }`, without its class.\n */\nexport interface ErrorClassWithCode {\n readonly code: string;\n}\n\ntype WorkflowShape = { run(ctx: any, input: any): Promise<unknown> };\n\n/**\n * An `@OnError` method: a workflow body that receives the failed run's {@link OnErrorInput}, typed with\n * `run`'s input, and returns what `run` returns.\n */\nexport type OnErrorMethod<T extends WorkflowShape> = (\n ctx: WorkflowCtx<any>,\n failure: OnErrorInput<Parameters<T['run']>[1]>,\n) => Promise<Awaited<ReturnType<T['run']>>>;\n\n/**\n * Marks a method on a `@Workflow` class as the handler for a failure of that workflow's runs. When a\n * run ends `failed` with an error of the given `code` (a string, or an {@link ErrorClassWithCode}),\n * the engine starts the method as its own durable workflow — registered as\n * `<workflow>.onError.<method>`, with a `<runId>.onError` id — and the failed run waits for it, then\n * settles with its outcome: the method's return value as its output, or its error. Without an\n * argument it takes any failure no other code matches.\n *\n * The engine routes the failure, so this holds for whatever ran the body (inline, an in-app worker,\n * another runtime). The method's signature is checked against the workflow: `(ctx, failure)`, with\n * `failure.input` typed as `run`'s input and the return type as `run`'s. Stack the decorator to give\n * one method several codes. Saga compensations of the failed body run before the handoff;\n * cancellation and non-determinism are never routed.\n */\nexport function OnError(match?: string | ErrorClassWithCode) {\n const code = match === undefined || typeof match === 'string' ? match : match.code;\n if (match !== undefined && typeof code !== 'string') {\n throw new Error(\n '@OnError(ErrorClass): the class has no static `code`. Declare `static readonly code = \"...\"` on it, or pass the code string.',\n );\n }\n return <T extends WorkflowShape>(\n _target: T,\n _propertyKey: string | symbol,\n descriptor: { value?: OnErrorMethod<T> | undefined },\n ): void => {\n const method = descriptor.value as object;\n const codes: (string | undefined)[] = Reflect.getMetadata(ON_ERROR_METADATA, method) ?? [];\n Reflect.defineMetadata(ON_ERROR_METADATA, [...codes, code], method);\n };\n}\n\n/** The codes an `@OnError` method takes (`undefined` for the catch-all), or undefined if it has none. */\n// biome-ignore lint/complexity/noBannedTypes: reflect-metadata reads from the method function\nexport function onErrorCodesOf(method: Function): (string | undefined)[] | undefined {\n return Reflect.getMetadata(ON_ERROR_METADATA, method);\n}\n\nexport const ON_EVENT_METADATA = Symbol('nestjs-durable:on-event');\n\n/**\n * Subscribe a `@Workflow` class to one or more events: when any of them is published via\n * `publishEvent(name, payload)`, a fresh run of the workflow starts with the payload as input.\n * Equivalent to `@Workflow({ onEvent })` — use whichever reads better; multiple\n * `@OnDurableEvent(...)` decorators and the option are all merged.\n *\n * Named \"durable\" on purpose: `@nestjs/event-emitter` exports an `@OnEvent` decorator, and in an\n * app using both libs an auto-import picking the wrong one fails silently in either direction.\n */\nexport function OnDurableEvent(...events: OnEventEntry[]): ClassDecorator {\n return (target) => addEventSubscriptions(target, events);\n}\n\n/**\n * Coalesce a subscriber's triggers by **debouncing**: start it once events have been quiet for\n * `windowMs`, with the last one. `key` splits that per key: it receives the subscriber's input (what\n * `input` builds), and each distinct key debounces on its own.\n */\nexport interface SubscriberDebounce<TRunInput> {\n windowMs: number | string;\n key?: ((input: TRunInput) => string) | undefined;\n}\n\n/**\n * Coalesce a subscriber's triggers by **batching**: start it with `{ events }` once `maxSize` arrive\n * or `windowMs` passes since the first. `key` batches each distinct key on its own.\n */\nexport interface SubscriberBatch<TRunInput> {\n maxSize: number;\n windowMs: number | string;\n key?: ((input: TRunInput) => string) | undefined;\n}\n\n/** Options for {@link OnWorkflowCompleted} / {@link OnWorkflowFailed}. */\nexport interface OnWorkflowSettledOptions<TEvent, TRunInput> {\n /** Start only for the settled runs this returns true for, e.g. by `input` or `searchAttributes`. */\n where?: ((event: TEvent) => boolean) | undefined;\n /**\n * The started run's input, built from the event. Without it the run receives the\n * {@link WorkflowLifecycleEvent} itself. Lets an existing workflow subscribe with its own input\n * shape, and keeps the settled run's whole input and output out of the new run's row.\n */\n input?: ((event: TEvent) => TRunInput) | undefined;\n /**\n * Debounce this workflow's triggers (see {@link SubscriberDebounce}). Sets the workflow's\n * `onEvent` coalescing, so it applies to every event it subscribes to; a different `debounce` or\n * `batch` already declared on it fails at registration. Not with `batch`.\n */\n debounce?: SubscriberDebounce<TRunInput> | undefined;\n /**\n * Batch this workflow's triggers (see {@link SubscriberBatch}); the run's input becomes\n * `{ events: TRunInput[] }`. Same scope and conflicts as `debounce`. Not with `debounce`.\n */\n batch?: SubscriberBatch<TRunInput> | undefined;\n}\n\n/** Options for {@link OnWorkflowFailed}: also which endings start the subscriber. */\nexport interface OnWorkflowFailedOptions<TEvent, TRunInput>\n extends OnWorkflowSettledOptions<TEvent, TRunInput> {\n /** The endings that start it. Defaults to all three: `failed`, `cancelled` and `dead`. */\n statuses?: Array<'failed' | 'cancelled' | 'dead'> | undefined;\n}\n\n/** `O` with a required `batch` (and no `debounce`): the overload whose subscriber takes `{ events }`. */\ntype Batched<O, TRunInput> = O & { batch: SubscriberBatch<TRunInput>; debounce?: undefined };\n/** `O` without `batch`: the overload whose subscriber takes `TRunInput` itself. */\ntype Unbatched<O> = O & { batch?: undefined };\n\n/**\n * A class decorator that only accepts a workflow whose `run(ctx, input)` takes `TRunInput`, so a\n * subscriber with the wrong input shape fails to compile instead of failing at runtime.\n */\nexport type SubscriberDecorator<TRunInput> = <\n T extends abstract new (\n ...args: never[]\n ) => { run: (ctx: never, input: TRunInput) => unknown },\n>(\n target: T,\n) => void;\n\n/**\n * Start a fresh run of the decorated workflow whenever a run of `workflow` **completes**. The new\n * run's input is the {@link WorkflowLifecycleEvent} (run id, input, output, tags, search\n * attributes), or what `input` builds from it. The settling workflow does not know about its\n * subscribers. Exactly once per settled run: see `runCompletedEvent` in\n * `@dudousxd/nestjs-durable-core`.\n *\n * With a class ref, the decorated workflow's `run` input is type-checked against the event (or\n * against `input`'s return type, or `{ events }` of it with `batch`). Child runs publish too, so a\n * workflow that `etl` starts as a child also starts its subscribers.\n *\n * ```ts\n * @Workflow({ name: 'refresh-summaries' })\n * @OnWorkflowCompleted(IngestionWorkflow, {\n * where: (e) => e.input.type === 'mvr',\n * input: (e) => ({ baseId: e.input.baseId }),\n * debounce: { windowMs: '30s', key: (input) => input.baseId },\n * })\n * class RefreshSummariesWorkflow {\n * async run(ctx: WorkflowCtx, input: { baseId: string }) {}\n * }\n * ```\n */\nexport function OnWorkflowCompleted<C extends WorkflowClass, TRunInput = LifecycleEventOf<C>>(\n workflow: C,\n options: Batched<OnWorkflowSettledOptions<LifecycleEventOf<C>, TRunInput>, TRunInput>,\n): SubscriberDecorator<{ events: TRunInput[] }>;\nexport function OnWorkflowCompleted<C extends WorkflowClass, TRunInput = LifecycleEventOf<C>>(\n workflow: C,\n options?: Unbatched<OnWorkflowSettledOptions<LifecycleEventOf<C>, TRunInput>>,\n): SubscriberDecorator<TRunInput>;\nexport function OnWorkflowCompleted(\n workflow: string,\n options?: OnWorkflowSettledOptions<WorkflowLifecycleEvent, unknown>,\n): ClassDecorator;\nexport function OnWorkflowCompleted(\n workflow: WorkflowRef,\n options?: OnWorkflowSettledOptions<WorkflowLifecycleEvent, unknown>,\n): ClassDecorator {\n return onWorkflowSettled(runCompletedEvent(workflow), options?.where, options);\n}\n\n/**\n * Start a fresh run of the decorated workflow whenever a run of `workflow` ends **failed,\n * cancelled or dead** (narrow it with `statuses`). Same contract as {@link OnWorkflowCompleted};\n * the event carries `error` and `status` instead of `output`.\n */\nexport function OnWorkflowFailed<C extends WorkflowClass, TRunInput = LifecycleEventOf<C>>(\n workflow: C,\n options: Batched<OnWorkflowFailedOptions<LifecycleEventOf<C>, TRunInput>, TRunInput>,\n): SubscriberDecorator<{ events: TRunInput[] }>;\nexport function OnWorkflowFailed<C extends WorkflowClass, TRunInput = LifecycleEventOf<C>>(\n workflow: C,\n options?: Unbatched<OnWorkflowFailedOptions<LifecycleEventOf<C>, TRunInput>>,\n): SubscriberDecorator<TRunInput>;\nexport function OnWorkflowFailed(\n workflow: string,\n options?: OnWorkflowFailedOptions<WorkflowLifecycleEvent, unknown>,\n): ClassDecorator;\nexport function OnWorkflowFailed(\n workflow: WorkflowRef,\n options?: OnWorkflowFailedOptions<WorkflowLifecycleEvent, unknown>,\n): ClassDecorator {\n const statuses = options?.statuses;\n const where = options?.where;\n const accepts =\n statuses || where\n ? (event: WorkflowLifecycleEvent) =>\n (!statuses || (statuses as string[]).includes(event.status)) && (!where || where(event))\n : undefined;\n return onWorkflowSettled(runFailedEvent(workflow), accepts, options);\n}\n\n/** Metadata key for the `onEvent` coalescing `@OnWorkflowCompleted` / `@OnWorkflowFailed` declare. */\nexport const ON_EVENT_BATCH_METADATA = Symbol('nestjs-durable:on-event-batch');\n\nfunction onWorkflowSettled(\n event: string,\n where: ((event: WorkflowLifecycleEvent) => boolean) | undefined,\n options: OnWorkflowSettledOptions<WorkflowLifecycleEvent, unknown> | undefined,\n): ClassDecorator {\n const subscription = {\n event,\n where: where as ((payload: unknown) => boolean) | undefined,\n input: options?.input as ((payload: unknown) => unknown) | undefined,\n };\n const batch = subscriberEventBatch(event, options);\n return (target) => {\n addEventSubscriptions(target, [subscription]);\n if (!batch) return;\n const existing = Reflect.getMetadata(ON_EVENT_BATCH_METADATA, target) as\n | EventBatchConfig\n | undefined;\n if (existing && !sameEventBatch(existing, batch)) {\n throw new Error(\n `${(target as { name?: string }).name ?? 'workflow'}: two lifecycle subscriptions declare different debounce/batch settings; a workflow coalesces all its triggers one way`,\n );\n }\n Reflect.defineMetadata(ON_EVENT_BATCH_METADATA, batch, target);\n };\n}\n\n/** The workflow-level coalescing a lifecycle subscription's `debounce` / `batch` option maps to. */\nfunction subscriberEventBatch(\n event: string,\n options: OnWorkflowSettledOptions<WorkflowLifecycleEvent, unknown> | undefined,\n): EventBatchConfig | undefined {\n if (options?.debounce && options.batch) {\n throw new Error(`${event}: a subscription takes debounce or batch, not both`);\n }\n if (options?.debounce) {\n return {\n mode: 'debounce',\n windowMs: parseDuration(options.debounce.windowMs),\n ...(options.debounce.key ? { key: options.debounce.key } : {}),\n };\n }\n if (options?.batch) {\n return {\n mode: 'batch',\n maxSize: options.batch.maxSize,\n windowMs: parseDuration(options.batch.windowMs),\n ...(options.batch.key ? { key: options.batch.key } : {}),\n };\n }\n return undefined;\n}\n\n/**\n * Whether two coalescing settings are the same: mode, window, size and key. Keys compare by source\n * text (`key.toString()`), so the same arrow written on two decorators matches; keys written\n * differently do not, even when they compute the same thing.\n */\nfunction sameEventBatch(a: EventBatchConfig, b: EventBatchConfig): boolean {\n return (\n a.mode === b.mode &&\n a.windowMs === b.windowMs &&\n a.key?.toString() === b.key?.toString() &&\n (a.mode !== 'batch' || b.mode !== 'batch' || a.maxSize === b.maxSize)\n );\n}\n\n/**\n * How a workflow coalesces its `onEvent` triggers: `@Workflow({ debounce | batch })`, or what its\n * `@OnWorkflowCompleted` / `@OnWorkflowFailed` declare. Throws when both are set and differ, so a\n * workflow never silently coalesces one way while its decorator says another.\n */\nexport function eventBatchOf(meta: WorkflowMeta, target: object): EventBatchConfig | undefined {\n const declared: EventBatchConfig | undefined = meta.debounce\n ? { mode: 'debounce', windowMs: parseDuration(meta.debounce) }\n : meta.batch\n ? {\n mode: 'batch',\n maxSize: meta.batch.maxSize,\n windowMs: parseDuration(meta.batch.within),\n }\n : undefined;\n const fromSubscription = Reflect.getMetadata(ON_EVENT_BATCH_METADATA, target) as\n | EventBatchConfig\n | undefined;\n if (declared && fromSubscription && !sameEventBatch(declared, fromSubscription)) {\n throw new Error(\n `workflow ${meta.name}: @Workflow declares ${declared.mode} but a lifecycle subscription declares a different ${fromSubscription.mode}; declare it in one place`,\n );\n }\n return fromSubscription ?? declared;\n}\n\nfunction addEventSubscriptions(target: object, entries: OnEventEntry[]): void {\n const existing =\n (Reflect.getMetadata(ON_EVENT_METADATA, target) as OnEventEntry[] | undefined) ?? [];\n Reflect.defineMetadata(ON_EVENT_METADATA, [...existing, ...entries], target);\n}\n\n/**\n * All events a workflow class subscribes to: `@Workflow({ onEvent })`, `@OnDurableEvent`,\n * `@OnWorkflowCompleted` and `@OnWorkflowFailed`. Repeated bare names collapse to one.\n */\nexport function getOnEvents(meta: WorkflowMeta, target: object): OnEventEntry[] {\n const fromDecorator =\n (Reflect.getMetadata(ON_EVENT_METADATA, target) as OnEventEntry[] | undefined) ?? [];\n const names = new Set<string>();\n return [...(meta.onEvent ?? []), ...fromDecorator].filter((entry) => {\n if (typeof entry !== 'string') return true;\n if (names.has(entry)) return false;\n names.add(entry);\n return true;\n });\n}\n","import { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Derives a workflow's **origin** — the npm package that declared it (`@dudousxd/nestjs-agent`, the\n * host app's own `package.json` `name`, …) — so every run can say which lib produced it (see\n * {@link import('@dudousxd/nestjs-durable-core').WorkflowRun.origin}).\n *\n * WHY IT IS DERIVED AND NOT DECLARED: anything a lib has to opt into (a `@Workflow({ tags })`\n * convention, a registry of known packages) is already wrong in the field the day a lib forgets, and\n * a facet that lists two of the five libs actually running is worse than no facet at all. So the only\n * acceptable input is one the lib cannot fail to provide: the file it declared its `@Workflow` class\n * in. That file is captured by {@link declaringFile} at decoration time — the one moment we are\n * guaranteed to be executing inside the declaring module — and mapped here to the nearest enclosing\n * `package.json` `name`.\n *\n * WHY NOT THE NEST MODULE: the `InstanceWrapper` a `DiscoveryService` scan hands back does name the\n * module a provider came from (`wrapper.host.metatype`), but a module class is just a class — it\n * carries no file location, and the app's own module is a perfectly normal place to register a lib's\n * workflow, which would then be attributed to the app. The declaring file of the `@Workflow` class is\n * both available and strictly more precise, so the wrapper is used only to reach that class.\n *\n * EVERY step here can fail, and each failure yields `undefined` (= unknown) rather than a guess:\n * - a runtime without V8's `Error.captureStackTrace`, or an app that set `Error.stackTraceLimit = 0`\n * - a declaring frame that is not a real file (`node:` internals, `eval`, `<anonymous>`) — notably a\n * single-file bundle can also collapse several packages into one file, and where the file IS real\n * but shared, the origin will be the bundle's package: that is the one shape this cannot detect\n * - no `package.json` carrying a `name` anywhere above the file\n * `WorkflowRegistrar` reports the workflows that came back unattributed once, at boot.\n */\n\n/** The file each decorated class was declared in, keyed by the class itself. */\nconst declaringFileByClass = new WeakMap<object, string>();\n\n/** Memoized directory → owning package name (or `undefined` when the walk found none). */\nconst packageNameByDir = new Map<string, string | undefined>();\n\ntype AnyFunction = (...args: never[]) => unknown;\n\n/**\n * The absolute path of the file that is calling `boundary` right now — i.e. the file whose top level\n * is applying a decorator, when called from inside that decorator's factory. `boundary` is clipped\n * off the captured stack (`Error.captureStackTrace`'s second argument), so the first remaining frame\n * is the caller's, with no frame counting to go stale when this file is refactored.\n *\n * Returns `undefined` on any runtime that does not give us a usable frame.\n */\nexport function declaringFile(boundary: AnyFunction): string | undefined {\n const capture = Error.captureStackTrace;\n if (typeof capture !== 'function') return undefined;\n const holder: { stack?: string } = {};\n capture(holder, boundary);\n return topFrameFile(holder.stack);\n}\n\n/** Records the file `target` was declared in, so {@link originOfClass} can resolve it later. */\nexport function rememberDeclaringFile(target: object, file: string | undefined): void {\n if (file) declaringFileByClass.set(target, file);\n}\n\n/**\n * The package that declared `target`, or `undefined` if it cannot be resolved with confidence.\n *\n * Walks the prototype chain, matching `Reflect.getMetadata`'s inheritance: a subclass that inherits\n * its `@Workflow` metadata from a decorated base also inherits that base's origin, because the base\n * is where the decorated body was declared.\n */\nexport function originOfClass(target: unknown): string | undefined {\n for (\n let ctor: unknown = target;\n typeof ctor === 'function' || (typeof ctor === 'object' && ctor !== null);\n ctor = Object.getPrototypeOf(ctor)\n ) {\n const file = declaringFileByClass.get(ctor);\n if (file) return packageNameFor(file);\n }\n return undefined;\n}\n\n/**\n * The package that declared the workflow behind a discovered provider. Structurally typed against\n * Nest's `InstanceWrapper` (the shape `DiscoveryService.getProviders()` returns) so this package does\n * not deep-import an internal Nest path: `metatype` is the registered class, and `instance.constructor`\n * covers a provider whose metatype is absent (a `useValue`/factory-built instance of a decorated class).\n */\nexport function originOfProvider(wrapper: {\n metatype?: unknown;\n instance?: unknown;\n}): string | undefined {\n const fromMetatype = originOfClass(wrapper.metatype);\n if (fromMetatype) return fromMetatype;\n const instance = wrapper.instance;\n if (typeof instance !== 'object' || instance === null) return undefined;\n return originOfClass(instance.constructor);\n}\n\n/**\n * The `name` of the nearest `package.json` at or above `file`'s directory. For a lib this is the\n * installed package (`…/node_modules/@scope/lib/dist/index.cjs` → `@scope/lib`, pnpm's nested layout\n * included); for a workflow written in the app it is the app's own name. Memoized per directory —\n * the walk hits the filesystem once per distinct directory, not once per workflow.\n */\nfunction packageNameFor(file: string): string | undefined {\n const start = dirname(file);\n const visited: string[] = [];\n let dir = start;\n for (;;) {\n if (packageNameByDir.has(dir)) {\n const cached = packageNameByDir.get(dir);\n for (const seen of visited) packageNameByDir.set(seen, cached);\n return cached;\n }\n visited.push(dir);\n const name = readPackageName(join(dir, 'package.json'));\n if (name !== undefined) {\n for (const seen of visited) packageNameByDir.set(seen, name);\n return name;\n }\n const parent = dirname(dir);\n // `dirname('/')` is `'/'` — the filesystem root is the end of the walk.\n if (parent === dir) {\n for (const seen of visited) packageNameByDir.set(seen, undefined);\n return undefined;\n }\n dir = parent;\n }\n}\n\n/** The `name` field of a `package.json`, or `undefined` if it is missing, unreadable or unnamed. */\nfunction readPackageName(path: string): string | undefined {\n let raw: string;\n try {\n raw = readFileSync(path, 'utf8');\n } catch {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // A malformed package.json is not ours to fail on — keep walking up.\n return undefined;\n }\n if (!isRecord(parsed)) return undefined;\n const name = parsed.name;\n return typeof name === 'string' && name.length > 0 ? name : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * The file named by the FIRST frame of a captured stack. Deliberately only the first: with the\n * capture boundary clipped, frame 0 IS the declaring site, and falling through to a deeper frame\n * when it is unparseable would attribute the workflow to whatever happened to be further up the\n * stack (the test runner, Nest's loader) — a confident-looking wrong answer.\n */\nfunction topFrameFile(stack: string | undefined): string | undefined {\n if (typeof stack !== 'string') return undefined;\n for (const line of stack.split('\\n')) {\n const frame = line.trim();\n if (!frame.startsWith('at ')) continue;\n return fileOfFrame(frame.slice(3));\n }\n return undefined;\n}\n\n/** `foo (/a/b.ts:1:2)` / `/a/b.ts:1:2` / `file:///a/b.js:1:2` → an absolute path, else `undefined`. */\nfunction fileOfFrame(frame: string): string | undefined {\n const match = /\\((.+):\\d+:\\d+\\)$/.exec(frame) ?? /^(.+):\\d+:\\d+$/.exec(frame);\n const location = match?.[1];\n if (location === undefined) return undefined;\n if (location.startsWith('file://')) {\n try {\n return fileURLToPath(location);\n } catch {\n return undefined;\n }\n }\n // Anything that is not an absolute path is not a file we can resolve a package from: `node:internal/…`,\n // `<anonymous>`, `eval at …`, a bundler's virtual id.\n const absolute = location.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(location);\n return absolute ? location : undefined;\n}\n","import type { StartRunDeps } from '@dudousxd/durable-worker';\nimport {\n type RunResult,\n type StartOptions,\n type TenantTokenSource,\n type WorkflowClass,\n type WorkflowInputOf,\n resolveTenantToken,\n workflowName,\n} from '@dudousxd/nestjs-durable-core';\nimport { Injectable } from '@nestjs/common';\nimport type { ContextAccessor } from './context-accessor';\nimport type { DurableModuleOptions } from './durable.module';\nimport { currentTenant } from './tenancy';\nimport { resolveTenantTokenSource } from './tenant-contracts';\nimport { startRun } from './worker-sdk';\n\n/**\n * The **store-less `engine.start` facade** for a tenant worker. Provided under the `WorkflowEngine`\n * DI token by {@link import('./durable.module').DurableModule} (`forRoot({ connection })`, no\n * `store`), so tenant code calls `engine.start(...)` UNCHANGED — it has no idea it is a tenant.\n * Instead of touching a DB, `start` publishes a `StartRunMessage` on the SHARED `durable-start-run`\n * queue (Option B: tenant rides as message DATA, never as wire segmentation). The operator (control\n * plane, `namespace: undefined`) consumes it, stamps the run's namespace from `tenant`, and routes\n * the run's task to `<workflow>@<tenant>` — the partition THIS tenant's worker serves.\n *\n * `cancel`/`deleteRun` need the store/driver a tenant does not have; they throw. No wire message\n * exists for them (the operator owns cancellation/retention).\n */\n@Injectable()\nexport class DurableStartClient {\n private readonly tenant: string;\n private readonly tenantToken: TenantTokenSource | undefined;\n\n constructor(\n private readonly options: DurableModuleOptions,\n private readonly deps?: StartRunDeps,\n /** The context accessor, for the customer tenant a start claims (else the global slot). */\n private readonly accessor?: ContextAccessor,\n ) {\n this.tenant = options.partition ?? 'default';\n this.tenantToken = resolveTenantTokenSource(options.tenantToken);\n }\n\n start<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n runId?: string,\n opts?: StartOptions,\n ): Promise<RunResult>;\n start(workflow: string, input: unknown, runId?: string, opts?: StartOptions): Promise<RunResult>;\n async start(\n workflow: string,\n input: unknown,\n runId: string = globalThis.crypto.randomUUID(),\n opts?: StartOptions,\n ): Promise<RunResult> {\n const name = workflowName(workflow);\n // The customer tenant this run claims: an explicit `tenantId` (`null` = none), else the\n // request's tenant when tenancy is on. The control plane keeps it only with a `tenancy:`\n // capability on this process's token.\n const tenant =\n opts?.tenantId !== undefined\n ? opts.tenantId === null\n ? undefined\n : { id: opts.tenantId, kind: opts.tenantKind }\n : currentTenant(this.options.tenancy, this.accessor);\n await startRun(this.options.connection, {\n // The signed token (when configured) rides in the `tenant` field, as on every run request; an\n // operator with `verifyTenant` derives the run's namespace from it.\n tenant:\n this.tenantToken !== undefined ? await resolveTenantToken(this.tenantToken) : this.tenant,\n workflow: name,\n input,\n runId,\n // Option B: DO NOT pass `namespace` — the start-run queue stays the shared\n // `durable-start-run` the operator consumes; tenant rides only as message data.\n ...(this.options.prefix !== undefined ? { prefix: this.options.prefix } : {}),\n ...(opts?.tags !== undefined ? { tags: opts.tags } : {}),\n ...(opts?.searchAttributes !== undefined ? { searchAttributes: opts.searchAttributes } : {}),\n // The start options the control plane applies (version pin, priority, delayed start, quota).\n ...(opts?.version !== undefined ? { version: opts.version } : {}),\n ...(opts?.priority !== undefined ? { priority: opts.priority } : {}),\n ...(opts?.startAt !== undefined ? { startAt: opts.startAt } : {}),\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n ...(tenant\n ? {\n tenantId: tenant.id,\n ...(tenant.kind !== undefined ? { tenantKind: tenant.kind } : {}),\n }\n : {}),\n ...(this.deps !== undefined ? { deps: this.deps } : {}),\n });\n // As `engine.start` reports it: a start delayed into the future reads `suspended` until it fires.\n const startAtMs = opts?.startAt instanceof Date ? opts.startAt.getTime() : opts?.startAt;\n return {\n runId,\n status:\n startAtMs !== undefined && Number.isFinite(startAtMs) && startAtMs > Date.now()\n ? 'suspended'\n : 'pending',\n };\n }\n\n cancel(_runId: string): Promise<void> {\n return tenantUnsupported('cancel');\n }\n\n deleteRun(_runId: string): Promise<void> {\n return tenantUnsupported('deleteRun');\n }\n\n // — everything below rejects: a tenant worker holds no store/driver, only the start channel. —\n\n // The remaining WorkflowEngine surface WorkflowService delegates to (resume/waitForRun/signal/\n // signalWithStart/publishEvent) all need the store or driver a tenant does not have. A tenant only\n // ever calls `start`; these exist so a mistaken call fails with a CLEAR, named tenant error instead\n // of a cryptic `this.engine.X is not a function` — the facade is honest about what it cannot do.\n // Params mirror the WorkflowEngine surface being faced; every method rejects without reading them.\n resume(_runId: string): Promise<void> {\n return tenantUnsupported('resume');\n }\n\n waitForRun(\n _runId: string,\n _opts?: { timeoutMs?: number; until?: 'settled' | 'terminal' },\n ): Promise<void> {\n return tenantUnsupported('waitForRun');\n }\n\n signal(_token: string, _payload: unknown): Promise<void> {\n return tenantUnsupported('signal');\n }\n\n signalWithStart(\n _workflow: string,\n _input: unknown,\n _runId: string,\n _signal: { token: string; payload?: unknown },\n _opts?: StartOptions,\n ): Promise<void> {\n return tenantUnsupported('signalWithStart');\n }\n\n publishEvent(\n _name: string,\n _payload: unknown,\n _opts?: { id?: string; buffer?: boolean },\n ): Promise<void> {\n return tenantUnsupported('publishEvent');\n }\n}\n\n/** Reject with a clear, named tenant error for an operation that needs a store/driver. */\nfunction tenantUnsupported(method: string): Promise<void> {\n return Promise.reject(\n new Error(\n `${method}() is not available on a tenant worker (no store). Use the control plane for it.`,\n ),\n );\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { EngineTenancy, RunTenant, TenantFilter } from '@dudousxd/nestjs-durable-core';\nimport type { ContextAccessor } from './context-accessor';\nimport {\n type Tenancy,\n type TenancyOption,\n type TenantLevel,\n readTenancy as readContextTenancy,\n tenantLabels as readTenantLabels,\n} from './tenancy-reader';\n\n/**\n * Tenancy for durable: the CUSTOMER a run belongs to (`@dudousxd/nestjs-context`'s tenant), not the\n * worker-pool `namespace`. Read through the local copy of the context's tenancy reader\n * (`./tenancy-reader`): durable never imports nestjs-context, so it works with any context version\n * or none at all. With the accessor (or its tenancy methods) missing, tenancy reads as off and\n * durable behaves exactly as without it.\n */\n\n/**\n * The `tenancy` option of `DurableModule`. Same shape in every Aviary lib:\n * - `enabled`: `'inherit'` (default) follows `ContextModule`'s `tenancy.enabled`;\n * - `kinds`: the tenant kinds durable stamps and filters by. On a nested tenant (clinic → unit) the\n * most specific level of the active chain whose kind is listed is the one used;\n * - `family`: read a secondary tenant family (e.g. `'account'`) instead of the primary one;\n * - `required`: with no tenant, an app-facing read or start throws the context's\n * `TenantRequiredError` (403) instead of running tenantless. Defaults to the context's own\n * `tenancy.required`. Durable's own work (turns, recovery, schedules, worker steps) never throws;\n * - `nullRows: 'shared'`: a tenant also sees runs with no tenant (default `'tenantless'`: it does not).\n */\nexport type DurableTenancyOption = TenancyOption;\n\n/** Marks durable's own work, where no request asks for a tenant (see {@link inDurableWork}). */\nconst durableWork = new AsyncLocalStorage<true>();\n\n/**\n * Run `fn` as durable's own work (a workflow turn, recovery, a worker's step): reads inside it pass\n * `required: false`, so a tenant-required app does not reject a run or a task with no tenant.\n */\nexport function inDurableWork<T>(fn: () => T): T {\n return durableWork.getStore() ? fn() : durableWork.run(true, fn);\n}\n\n/**\n * Read tenancy for one operation (call per operation, never once at boot). Inside durable's own work\n * (see {@link inDurableWork}) a missing tenant never throws, whatever `required` says.\n */\nexport function readTenancy(\n option: DurableTenancyOption | undefined,\n accessor: ContextAccessor | undefined,\n): Tenancy {\n const own = option ?? 'inherit';\n const effective: TenancyOption =\n durableWork.getStore() && own !== false\n ? { ...(typeof own === 'object' ? own : {}), required: false }\n : own;\n return readContextTenancy(effective, accessor);\n}\n\n/** The slice of nestjs-context's runtime `Context` that restores a tenant (context ≥ 1.2). */\nexport interface TenantRuntime {\n withTenant<T>(\n input: { id: string; kind: string; source?: string } | null,\n fn: () => T,\n options?: { family?: string },\n ): T;\n}\n\nexport function isTenantRuntime(x: unknown): x is TenantRuntime {\n return !!x && typeof (x as TenantRuntime).withTenant === 'function';\n}\n\n/** The read/write tenancy slot nestjs-context ≥ 2.1 publishes; read structurally, version 1. */\nconst TENANCY_SLOT = Symbol.for('@dudousxd/nestjs-context:tenancy');\n\n/** The context's tenancy slot when one of a version this copy reads is published, else undefined. */\nexport function tenancySlot(): TenantRuntime | undefined {\n const slot = (globalThis as unknown as Record<symbol, unknown>)[TENANCY_SLOT] as\n | { version?: unknown; withTenant?: unknown }\n | undefined;\n return slot?.version === 1 && isTenantRuntime(slot) ? slot : undefined;\n}\n\n/** What restores a tenant: the context's tenancy slot when published, else the runtime `Context`. */\nfunction restorer(runtime: TenantRuntime | undefined): TenantRuntime | undefined {\n return tenancySlot() ?? runtime;\n}\n\n/** Restore `tenant` (read from a run row or a task carrier) as the context tenant around `fn`. */\nfunction restore<T>(\n runtime: TenantRuntime,\n option: DurableTenancyOption | undefined,\n tenant: RunTenant,\n fn: () => T,\n): T {\n const family = typeof option === 'object' ? option.family : undefined;\n const ref = { id: tenant.id, kind: tenant.kind ?? 'unknown', source: 'carrier' };\n return family !== undefined\n ? runtime.withTenant(ref, fn, { family })\n : runtime.withTenant(ref, fn);\n}\n\n/**\n * The engine's tenancy seam (core `EngineTenancy`), or undefined when durable's tenancy is `false`\n * or the installed context cannot restore a tenant. Every member reads the context at call time.\n */\nexport function buildEngineTenancy(\n option: DurableTenancyOption | undefined,\n accessor: ContextAccessor | undefined,\n runtime: TenantRuntime | undefined,\n): EngineTenancy | undefined {\n if (option === false || !restorer(runtime)) return undefined;\n return {\n current(): RunTenant | undefined {\n const t = readTenancy(option, accessor);\n if (!t.enabled) return undefined;\n const f = t.filter();\n return f.mode === 'tenant' ? { id: f.tenant.id, kind: f.tenant.kind } : undefined;\n },\n filter: () => tenantFilterNow(option, accessor),\n run: (tenant, fn) => {\n const using = restorer(runtime);\n return using ? restore(using, option, tenant, fn) : fn();\n },\n system: inDurableWork,\n };\n}\n\n/** The matching filter (core `TenantFilter`) for an app-facing call made now. */\nexport function tenantFilterNow(\n option: DurableTenancyOption | undefined,\n accessor: ContextAccessor | undefined,\n): TenantFilter {\n const t = readTenancy(option, accessor);\n if (!t.enabled) return { mode: 'system' };\n const f = t.filter();\n if (f.mode === 'tenant') return { mode: 'tenant', tenantId: f.tenant.id, nullRows: t.nullRows };\n if (f.mode === 'tenantless') return { mode: 'tenantless' };\n return f.mode === 'all' ? { mode: 'all' } : { mode: 'system' };\n}\n\n/** The tenant a task carrier holds (`tenant`, else a plain `tenantId`), or undefined. */\nexport function tenantFromCarrier(\n carrier: Record<string, unknown> | undefined,\n): RunTenant | undefined {\n const ref = carrier?.tenant as { id?: unknown; kind?: unknown } | undefined;\n if (ref && typeof ref.id === 'string') {\n return typeof ref.kind === 'string' ? { id: ref.id, kind: ref.kind } : { id: ref.id };\n }\n const id = carrier?.tenantId;\n return typeof id === 'string' ? { id } : undefined;\n}\n\n/**\n * A durable execution wrapper that runs each dispatched step handler in the tenant its task\n * carries, whatever transport delivered it and whichever process runs it. The handler runs as\n * durable's own work, so a task with no tenant does not trip a tenant-required context.\n */\nexport function stepTenantWrapper(\n option: DurableTenancyOption | undefined,\n accessor: ContextAccessor | undefined,\n runtime: TenantRuntime | undefined,\n): (\n execution: { unit: 'workflow' | 'step'; context?: Record<string, unknown> | undefined },\n next: () => Promise<unknown>,\n) => Promise<unknown> {\n return (execution, next) => {\n if (execution.unit !== 'step') return next();\n return inDurableWork(() => {\n const tenant = tenantFromCarrier(execution.context);\n const using = restorer(runtime);\n if (!tenant || !using || !readTenancy(option, accessor).enabled) return next();\n return restore(using, option, tenant, next);\n });\n };\n}\n\n/** Whether durable's tenancy can restore a tenant here: the context's slot, or its runtime. */\nexport function canRestoreTenant(runtime: unknown): boolean {\n return tenancySlot() !== undefined || isTenantRuntime(runtime);\n}\n\n/** The tenant a `start` made now is stamped with (tenancy on), for a store-less tenant process. */\nexport function currentTenant(\n option: DurableTenancyOption | undefined,\n accessor: ContextAccessor | undefined,\n): RunTenant | undefined {\n const t = readTenancy(option, accessor);\n if (!t.enabled) return undefined;\n const f = t.filter();\n return f.mode === 'tenant' ? { id: f.tenant.id, kind: f.tenant.kind } : undefined;\n}\n\n/** Console labels keyed by tenant id: the app's `tenancy.label`, else the slug, else the id. */\nexport function tenantLabels(\n tenants: TenantLevel[],\n accessor?: ContextAccessor | undefined,\n): Promise<Record<string, string>> {\n return readTenantLabels(tenants, accessor);\n}\n","// Local reader for the @dudousxd/nestjs-context tenancy contract. Copied into each lib;\n// it imports nothing, so the lib works with any context version or none at all.\nexport interface TenantLevel {\n id: string;\n kind: string;\n slug?: string;\n role?: string;\n}\nexport interface TenantRef extends TenantLevel {\n source: string;\n chain?: TenantLevel[]; // root first, this tenant last; absent for a flat tenant\n family?: string;\n}\nexport type TenantFilter =\n | { mode: 'system' }\n | { mode: 'all' }\n | { mode: 'tenantless' }\n | { mode: 'tenant'; tenant: TenantRef; chain?: TenantLevel[] }; // `chain`: context >= 2.1\nexport type TenancyOption =\n | 'inherit'\n | false\n | {\n enabled?: 'inherit' | boolean;\n kinds?: string[];\n family?: string;\n required?: boolean;\n nullRows?: 'tenantless' | 'shared';\n };\nexport type Tenancy =\n | { enabled: false }\n | { enabled: true; nullRows: 'tenantless' | 'shared'; filter(): TenantFilter };\n\ninterface FilterOptions {\n kinds?: string[];\n family?: string;\n required?: boolean;\n}\ninterface Accessor {\n tenancy?(): { enabled: boolean; kinds?: string[]; required?: boolean };\n tenantFilter?(options?: FilterOptions): TenantFilter;\n tenantLabels?(tenants: TenantLevel[]): Promise<Record<string, string>>;\n}\nconst SLOT = Symbol.for('@dudousxd/nestjs-diagnostics:accessor');\n\nfunction accessorOf(accessor: unknown): Accessor | undefined {\n const slot = (globalThis as unknown as Record<symbol, { current?: unknown } | undefined>)[SLOT];\n return (accessor ?? slot?.current ?? undefined) as Accessor | undefined;\n}\n\n/** `accessor`: the `CONTEXT_ACCESSOR` injected with `@Optional()`, if any. Call per operation. */\nexport function readTenancy(option: TenancyOption = 'inherit', accessor?: unknown): Tenancy {\n const a = accessorOf(accessor);\n if (option === false || typeof a?.tenancy !== 'function' || !a.tenantFilter) {\n return { enabled: false };\n }\n const own = typeof option === 'object' ? option : {};\n const inherit = own.enabled === undefined || own.enabled === 'inherit';\n if (!(inherit ? a.tenancy().enabled : own.enabled)) return { enabled: false };\n const options: FilterOptions = {};\n if (own.kinds) options.kinds = own.kinds;\n if (own.family !== undefined) options.family = own.family;\n if (own.required !== undefined) options.required = own.required;\n const tenantFilter = a.tenantFilter.bind(a);\n return {\n enabled: true,\n nullRows: own.nullRows ?? 'tenantless',\n // Throws the context's TenantRequiredError (403) when a tenant is required and missing.\n filter: () => tenantFilter(Object.keys(options).length > 0 ? options : undefined),\n };\n}\n\n/** The matching rule: may this request see a row whose tenant column holds `rowTenantId`? */\nexport function canSeeRow(t: Tenancy, rowTenantId: string | null | undefined): boolean {\n if (!t.enabled) return true;\n const f = t.filter();\n if (f.mode === 'system' || f.mode === 'all') return true;\n if (rowTenantId === null || rowTenantId === undefined) {\n return f.mode === 'tenantless' || t.nullRows === 'shared';\n }\n return f.mode === 'tenant' && f.tenant.id === rowTenantId;\n}\n\n/** The tenant id to stamp on a new row: the active tenant's id, else `null`. */\nexport function rowTenantId(t: Tenancy): string | null {\n if (!t.enabled) return null;\n const f = t.filter();\n return f.mode === 'tenant' ? f.tenant.id : null;\n}\n\n/** Console labels keyed by tenant id: the app's `tenancy.label`, else the slug, else the id. */\nexport async function tenantLabels(\n tenants: TenantLevel[],\n accessor?: unknown,\n): Promise<Record<string, string>> {\n const a = accessorOf(accessor);\n if (typeof a?.tenantLabels === 'function') {\n try {\n return await a.tenantLabels(tenants);\n } catch {\n // Fall back to slug/id below.\n }\n }\n const out: Record<string, string> = {};\n for (const t of tenants) out[t.id] = t.slug || t.id;\n return out;\n}\n","import type {\n TenantTokenSource,\n TenantVerifier,\n VerifiedTenant,\n} from '@dudousxd/nestjs-durable-core';\nimport type { ModuleRef } from '@nestjs/core';\n\n/** What a tenant verifier receives for each request a tenant process sends. */\nexport interface TenantVerifierInput {\n /** The token presented on the request (the wire `tenant` field). */\n token?: string | undefined;\n /** The tenant the request *claims* to be. Advisory only: derive the real one from the token. */\n tenant?: string | undefined;\n}\n\n/**\n * The object/class form of `verifyTenant`. Runs on the control plane for every request a tenant\n * process sends.\n */\nexport interface TenantVerifierContract {\n /**\n * Turn the wire token into the tenant it authenticates as. Return `null` to reject: the request is\n * answered `unauthorized` and never touches a run. Throw when you cannot decide (the identity\n * provider is down): the request fails with the error and the next one calls `verify` again. The\n * returned `tenant` is trusted as-is, so derive it from the verified token, never from\n * `input.tenant`.\n */\n verify(input: TenantVerifierInput): VerifiedTenant | null | Promise<VerifiedTenant | null>;\n}\n\n/**\n * The object/class form of `tenantToken`. Runs on the tenant process before every request it sends.\n */\nexport interface TenantCredentialsContract {\n /**\n * The token to present on the next request, sent as-is in the wire `tenant` field. Called once per\n * request, so cache the token and fetch a new one before it expires. A throw (or an empty string)\n * fails that request; the next request calls `token()` again.\n */\n token(): string | Promise<string>;\n}\n\n/** A class implementing a contract; its constructor parameters are resolved by Nest DI. */\nexport type ContractClass<T> = new (...args: any[]) => T;\n\n/** A lazy import of a module whose default export is a contract class or object. */\nexport type LazyContract<T> = () => Promise<{ default: ContractClass<T> | T }>;\n\n/**\n * The `verifyTenant` option: a function (e.g. `hmacTenantVerifier(secret)`), an object implementing\n * {@link TenantVerifierContract}, a class implementing it (built once through Nest DI: the registered\n * provider when there is one, else `ModuleRef.create`), or a lazy import of a module whose default\n * export is such a class or object (imported once).\n */\nexport type TenantVerifierOption =\n | TenantVerifier\n | TenantVerifierContract\n | ContractClass<TenantVerifierContract>\n | LazyContract<TenantVerifierContract>;\n\n/**\n * The `tenantToken` option: a string, a function called before every request, an object implementing\n * {@link TenantCredentialsContract}, a class implementing it (built once through Nest DI), or a lazy\n * import of a module whose default export is such a class or object (imported once).\n */\nexport type TenantTokenOption =\n | TenantTokenSource\n | TenantCredentialsContract\n | ContractClass<TenantCredentialsContract>\n | LazyContract<TenantCredentialsContract>;\n\n/** Marks a function this module already resolved, so resolving it again returns it unchanged. */\nconst RESOLVED = Symbol('nestjs-durable:resolved-tenant-auth');\n\nfunction markResolved<F extends object>(fn: F): F {\n Object.defineProperty(fn, RESOLVED, { value: true });\n return fn;\n}\n\nfunction isResolved(value: unknown): boolean {\n return typeof value === 'function' && (value as { [RESOLVED]?: true })[RESOLVED] === true;\n}\n\n/** Any `class`, or a function whose prototype carries `method` (a transpiled class). */\nfunction isClass(value: unknown, method: string): value is ContractClass<unknown> {\n if (typeof value !== 'function') return false;\n const proto = (value as { prototype?: Record<string, unknown> }).prototype;\n if (typeof proto?.[method] === 'function') return true;\n return /^class[\\s{]/.test(Function.prototype.toString.call(value));\n}\n\nfunction hasMethod<T>(value: unknown, method: string): value is T {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Record<string, unknown>)[method] === 'function'\n );\n}\n\n/** A module object returned by a lazy `import()`: its `default` is a contract class or object. */\nfunction lazyDefault(value: unknown, method: string): unknown {\n if (typeof value !== 'object' || value === null || !('default' in value)) return undefined;\n const target = (value as { default: unknown }).default;\n return isClass(target, method) || hasMethod(target, method) ? target : undefined;\n}\n\n/**\n * Builds a contract class once: the registered provider when the app registers it, else a fresh\n * instance through `ModuleRef.create` (so constructor injection works). Without a `ModuleRef` it is\n * constructed with `new`. A failed construction is retried on the next call.\n */\nfunction instanceFactory<T>(\n Class: ContractClass<T>,\n moduleRef: ModuleRef | undefined,\n): () => Promise<T> {\n let pending: Promise<T> | undefined;\n return () => {\n pending ??= (async (): Promise<T> => {\n if (!moduleRef) return new Class();\n try {\n const registered = moduleRef.get<T>(Class, { strict: false });\n if (registered) return registered;\n } catch {\n // Not a registered provider: create it below.\n }\n try {\n return await moduleRef.create<T>(Class);\n } catch (cause) {\n throw new Error(\n `could not build ${Class.name || 'the tenant auth class'}: register it as a provider in your module, or make its dependencies global`,\n { cause },\n );\n }\n })();\n pending.catch(() => {\n pending = undefined;\n });\n return pending;\n };\n}\n\n/** Resolves a contract target (class or object) to a getter of its instance. */\nfunction contractInstance<T>(\n target: unknown,\n method: string,\n moduleRef: ModuleRef | undefined,\n): () => Promise<T> {\n if (isClass(target, method)) return instanceFactory(target as ContractClass<T>, moduleRef);\n const instance = Promise.resolve(target as T);\n return () => instance;\n}\n\n/** What a function-form option turned out to be on a call: a contract instance, or a plain result. */\ntype Probed<T> = { contract: T } | { result: unknown };\n\n/**\n * Calls a function-form option, which is either the plain function or a lazy import; which one is\n * only known once it has run. The first call probes, and calls racing it wait for that probe, so a\n * lazy import runs exactly once and its default export is built once. A failed probe (the import\n * threw) is retried by the next call. Once known to be plain, the function is called on every call.\n */\nfunction functionOrLazy<T>(\n fn: (...args: any[]) => unknown,\n method: string,\n moduleRef: ModuleRef | undefined,\n): (...args: unknown[]) => Promise<Probed<T>> {\n let lazy: (() => Promise<T>) | undefined;\n let plain = false;\n let probing: Promise<unknown> | undefined;\n return async (...args) => {\n for (;;) {\n if (lazy) return { contract: await lazy() };\n if (plain) return { result: await fn(...args) };\n if (!probing) {\n const probe = (async () => fn(...args))();\n probing = probe;\n try {\n const result = await probe;\n const target = lazyDefault(result, method);\n if (target === undefined) {\n plain = true;\n return { result };\n }\n lazy = contractInstance<T>(target, method, moduleRef);\n return { contract: await lazy() };\n } finally {\n if (probing === probe) probing = undefined;\n }\n }\n await probing.catch(() => undefined);\n }\n };\n}\n\n/**\n * Turns any {@link TenantVerifierOption} into the plain {@link TenantVerifier} the engine and the\n * responder call. A class is built once, on the first request; a lazy import runs once.\n */\nexport function resolveTenantVerifier(\n option: TenantVerifierOption | undefined,\n moduleRef?: ModuleRef,\n): TenantVerifier | undefined {\n if (option === undefined || isResolved(option)) return option as TenantVerifier | undefined;\n const instance =\n isClass(option, 'verify') || hasMethod<TenantVerifierContract>(option, 'verify')\n ? contractInstance<TenantVerifierContract>(option, 'verify', moduleRef)\n : undefined;\n if (!instance && typeof option !== 'function') {\n throw new Error(\n '`verifyTenant` must be a function, an object or class with verify(), or a lazy import of one.',\n );\n }\n const call = functionOrLazy<TenantVerifierContract>(\n option as (input: TenantVerifierInput) => unknown,\n 'verify',\n moduleRef,\n );\n return markResolved(async (input: TenantVerifierInput): Promise<VerifiedTenant | null> => {\n if (instance) return (await instance()).verify(input);\n const probed = await call(input);\n if ('contract' in probed) return probed.contract.verify(input);\n return probed.result as VerifiedTenant | null;\n });\n}\n\nfunction requireToken(token: unknown): string {\n if (typeof token !== 'string' || token.length === 0) {\n throw new Error('tenantToken produced no token (an empty or non-string value)');\n }\n return token;\n}\n\n/**\n * Turns any {@link TenantTokenOption} into the {@link TenantTokenSource} the wire layer uses: a\n * static string stays a string, every other form becomes a function called before each request.\n */\nexport function resolveTenantTokenSource(\n option: TenantTokenOption | undefined,\n moduleRef?: ModuleRef,\n): TenantTokenSource | undefined {\n if (typeof option === 'string') {\n if (option.length === 0) {\n throw new Error(\n '`tenantToken` is an empty string. Set the token this tenant presents, or remove `tenantToken` to send the partition.',\n );\n }\n return option;\n }\n if (option === undefined || isResolved(option)) return option as TenantTokenSource | undefined;\n const instance =\n isClass(option, 'token') || hasMethod<TenantCredentialsContract>(option, 'token')\n ? contractInstance<TenantCredentialsContract>(option, 'token', moduleRef)\n : undefined;\n if (!instance && typeof option !== 'function') {\n throw new Error(\n '`tenantToken` must be a string, a function, an object or class with token(), or a lazy import of one.',\n );\n }\n const call = functionOrLazy<TenantCredentialsContract>(\n option as () => unknown,\n 'token',\n moduleRef,\n );\n return markResolved(async (): Promise<string> => {\n if (instance) return requireToken(await (await instance()).token());\n const probed = await call();\n if ('contract' in probed) return requireToken(await probed.contract.token());\n return requireToken(probed.result);\n });\n}\n","import type { DurableWorkerRuntime } from '@dudousxd/durable-worker';\n\n/** The `@dudousxd/durable-worker` module shape. `typeof import()` is erased, so this costs nothing. */\ntype WorkerSdk = typeof import('@dudousxd/durable-worker');\n\n/**\n * The single gate to `@dudousxd/durable-worker`. It is an OPTIONAL peer because only the roles that\n * EXECUTE workflow bodies need it — a pure operator (`store` + `transport`, no `connection`) never\n * runs a worker and is entitled to install without it. A static import would resolve it for every\n * consumer at `import '@dudousxd/nestjs-durable'`, so such an operator would die at boot with\n * `ERR_MODULE_NOT_FOUND` on a package it was told was optional.\n *\n * Every value from the SDK therefore crosses this module and nothing here is reachable from an\n * import of the package entry. Node caches the resolved module, so each call after the first is a\n * cache hit; the call sites below are per-`start` or per-bootstrap, never per-turn. Mirrors how\n * `@dudousxd/durable-worker` itself reaches its own optional `bullmq`/`ioredis` peers.\n */\nasync function workerSdk(): Promise<WorkerSdk> {\n try {\n return await import('@dudousxd/durable-worker');\n } catch (cause) {\n throw new Error(\n '@dudousxd/durable-worker is not installed. It is an optional peer needed only by the roles that run workflow bodies (`connection` set on DurableModule.forRoot) — install it, or drop `connection`.',\n { cause },\n );\n }\n}\n\n/** Publish a `StartRunMessage` on the shared start-run queue. One import per `start`, then cached. */\nexport const startRun: WorkerSdk['startRun'] = async (connection, options) =>\n (await workerSdk()).startRun(connection, options);\n\n/** Start a BullMQ consumer for a runtime's registered names. Called once, on app bootstrap. */\nexport const runRedisWorker: WorkerSdk['runRedisWorker'] = async (options) =>\n (await workerSdk()).runRedisWorker(options);\n\n/** Construct the store-less runtime a worker registers its bodies on. Called once, per role gate. */\nexport async function createWorkerRuntime(\n options: ConstructorParameters<WorkerSdk['DurableWorkerRuntime']>[0],\n): Promise<DurableWorkerRuntime> {\n const { DurableWorkerRuntime: Runtime } = await workerSdk();\n return new Runtime(options);\n}\n","import type {\n DurableWorkerRuntime,\n RunRedisWorkerOptions,\n RunningWorker,\n} from '@dudousxd/durable-worker';\nimport {\n type AnnouncedSchedule,\n DURABLE_OPTIONS_CANONICAL,\n type DurableTopology,\n type EngineEvent,\n type GroupHealth,\n type RunDetail,\n type RunFacetQuery,\n type RunFacetRow,\n type RunGateway,\n type RunListItem,\n type RunQuery,\n type RunResult,\n type RunValueAxis,\n type RunValueFacetOptions,\n type RunValueFacetRow,\n type RunWaiting,\n type ScheduleAnnouncement,\n type ScheduledWorkflow,\n type TenantTokenSource,\n WorkflowEngine,\n type WorkflowStartClient,\n bindWorkflowClass,\n resolveTenantToken,\n workflowName,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n Inject,\n Injectable,\n type OnApplicationBootstrap,\n type OnApplicationShutdown,\n type OnModuleInit,\n type Provider,\n} from '@nestjs/common';\nimport { DiscoveryService, MetadataScanner } from '@nestjs/core';\nimport { scanSteps, scanWorkflows } from './discovery-helpers';\nimport type { DurableModuleOptions, ResolvedTenantAuth } from './durable.module';\nimport { registerOnRuntime } from './runtime-registration';\nimport { TENANT_AUTH } from './tokens';\nimport { createWorkerRuntime, runRedisWorker as defaultRunRedisWorker } from './worker-sdk';\n\n/**\n * The `runRedisWorker` function the module uses to start each partition's BullMQ consumer.\n * Defaults to the real one from `@dudousxd/durable-worker`; tests `overrideProvider` it with a\n * fake so no real Redis is needed.\n */\nexport const RUN_REDIS_WORKER = Symbol('nestjs-durable:run-redis-worker');\n\n/**\n * The store-less {@link DurableWorkerRuntime} a pure thin worker registers its bodies on — `null` in\n * every other role. A Symbol rather than the class itself: the class lives in an optional peer, and\n * using it as a DI token would drag that peer into the package's static import graph.\n */\nexport const DURABLE_WORKER_RUNTIME = Symbol('nestjs-durable:worker-runtime');\n\n/** The list of started {@link RunningWorker} handles (the single handle {@link ThinWorkerBootstrap}\n * starts), closed on shutdown. */\nexport const DURABLE_WORKER_RUNNERS = Symbol('nestjs-durable:worker-runners');\n\n/** The signature of `runRedisWorker` — injected behind {@link RUN_REDIS_WORKER}. */\nexport type RunRedisWorkerFn = (opts: RunRedisWorkerOptions) => Promise<RunningWorker>;\n\n/** True for the **pure thin-worker** role — `connection` set, `store` unset. `DurableModule`\n * keeps {@link ThinWorkflowRegistrar}/{@link ThinStepRegistrar}/{@link ThinWorkerBootstrap} inert\n * (registered but no-op) outside this role — an operator (`store` set) drives its own bodies\n * inline or, with `connection` also set, through the separate in-app-worker mechanics instead. */\nfunction isPureThinWorker(options: DurableModuleOptions): boolean {\n return options.store === undefined && options.connection !== undefined;\n}\n\n/**\n * Discovers every provider carrying `@Workflow` metadata and registers its `run(ctx, input)` on the\n * thin {@link DurableWorkerRuntime}. Mirrors the engine-side `WorkflowRegistrar`, but registers on\n * the runner-core runtime instead of a `WorkflowEngine` — the runtime drives `run` with the thin\n * `WorkflowContext` (which `implements WorkflowCtx`), so the body runs unchanged. NO store/engine.\n * Inert (skips registration) outside the pure thin-worker role — see {@link isPureThinWorker}.\n */\n@Injectable()\nexport class ThinWorkflowRegistrar implements OnModuleInit {\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly metadataScanner: MetadataScanner,\n @Inject(DURABLE_WORKER_RUNTIME) private readonly runtime: DurableWorkerRuntime | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n /** In this role the store-less `DurableStartClient` facade the module binds under this token. */\n @Inject(WorkflowEngine) private readonly starter: WorkflowStartClient,\n ) {}\n\n onModuleInit(): void {\n const runtime = this.runtime;\n if (runtime === null || !isPureThinWorker(this.options)) return;\n const starter = this.starter;\n // The `@Workflow` metadata is also what this worker ANNOUNCES about each body it serves (design\n // §7.9) — version, capability demand, and the declaring package `scanWorkflows` derived. It is\n // passed straight through: the registry states what the decorator states, and an option the\n // decorator left off stays un-stated rather than becoming a default.\n scanWorkflows(this.discovery, (meta, instance, origin) => {\n registerOnRuntime(runtime, this.metadataScanner, meta, instance, origin);\n // Class-first statics (`MyWorkflow.start()`), as on an operator: bound to the start facade, so\n // they publish a start-run message to the control plane. `waitForRun` stays unbound (a tenant\n // has no store), so `MyWorkflow.execute()` outside a workflow fails with a clear error.\n bindWorkflowClass(instance.constructor, {\n start: (name, input, runId, opts) => starter.start(name, input, runId, opts),\n });\n });\n }\n}\n\n/**\n * Discovers every `@Step` method and registers it as a step handler on the thin\n * {@link DurableWorkerRuntime}. Mirrors the engine-side `DurableStepRegistrar`, but always registers\n * on the runtime (a thin worker IS the consumer — there is no in-process-vs-queue branch). Inert\n * outside the pure thin-worker role — see {@link isPureThinWorker}.\n */\n@Injectable()\nexport class ThinStepRegistrar implements OnModuleInit {\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly metadataScanner: MetadataScanner,\n @Inject(DURABLE_WORKER_RUNTIME) private readonly runtime: DurableWorkerRuntime | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n ) {}\n\n onModuleInit(): void {\n const runtime = this.runtime;\n if (runtime === null || !isPureThinWorker(this.options)) return;\n scanSteps(this.discovery, this.metadataScanner, (meta, handler) =>\n runtime.registerStep(meta.name, handler),\n );\n }\n}\n\n/**\n * Starts ONE `runRedisWorker` call on bootstrap — after both registrars have run, so every handler\n * is registered before any task is consumed — and closes it on shutdown. The runner (`@dudousxd/\n * durable-worker`) derives its subscription from `runtime.registeredNames()` (one queue per\n * registered `@Workflow`/`@Step` name), not a hand-declared group list. Inert outside the pure\n * thin-worker role — see {@link isPureThinWorker}: an operator (`store` set) never starts this\n * consumer, and `store + connection` starts its OWN co-located consumer instead (`in-app-worker.ts`).\n *\n * For the shutdown close to fire, enable Nest's shutdown hooks: `app.enableShutdownHooks()`.\n */\n@Injectable()\nexport class ThinWorkerBootstrap implements OnApplicationBootstrap, OnApplicationShutdown {\n private readonly runners: RunningWorker[] = [];\n\n constructor(\n @Inject(DURABLE_WORKER_RUNTIME) private readonly runtime: DurableWorkerRuntime | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n @Inject(RUN_REDIS_WORKER) private readonly runRedisWorker: RunRedisWorkerFn,\n @Inject(DURABLE_WORKER_RUNNERS) private readonly runnersSink: RunningWorker[],\n @Inject(TENANT_AUTH) private readonly auth: ResolvedTenantAuth,\n ) {}\n\n async onApplicationBootstrap(): Promise<void> {\n const options = this.options;\n const runtime = this.runtime;\n if (runtime === null || !isPureThinWorker(options) || options.connection === undefined) return;\n // `consumers: false`: a producer-only process (CLI, REPL, script) starts no consumer.\n if (options.consumers === false) {\n if ((options.schedules?.length ?? 0) > 0) {\n console.warn(\n '[nestjs-durable] `schedules` on a tenant with `consumers: false` are not announced: a tenant announces its schedules on its worker descriptor, so declare them on the processes that run its workers.',\n );\n }\n return;\n }\n // ONE call: the runner subscribes one queue per name registered on `runtime` — populated by\n // `ThinWorkflowRegistrar`/`ThinStepRegistrar`'s `onModuleInit`, which Nest's lifecycle guarantees\n // run (across the whole app) before any `onApplicationBootstrap` hook.\n const handle = await this.runRedisWorker({\n runtime,\n connection: options.connection,\n ...(options.partition !== undefined ? { partition: options.partition } : {}),\n ...(options.prefix !== undefined ? { prefix: options.prefix } : {}),\n ...(options.instanceId !== undefined ? { instanceId: options.instanceId } : {}),\n ...(options.concurrency !== undefined ? { concurrency: options.concurrency } : {}),\n // Announce the app's schedules (an empty list too) so the control plane adopts, updates and\n // withdraws them: a tenant has no store to fire them from.\n ...(await tenantScheduleAnnouncement(options, this.auth.tenantToken)),\n });\n this.runners.push(handle);\n this.runnersSink.push(handle);\n }\n\n async onApplicationShutdown(): Promise<void> {\n await Promise.allSettled(this.runners.map((h) => h.close()));\n }\n}\n\n/**\n * The tenant's `schedules`, as its worker announces them: under the wire tenant its starts carry (the\n * signed token when the app has one, else the partition), one {@link AnnouncedSchedule} per schedule.\n * A schedule's `namespace` is dropped (a tenant's runs always belong to its own namespace), and\n * `backfill` becomes the control plane's `catchup: 'latest'` (at most one late window).\n */\nexport async function tenantScheduleAnnouncement(\n options: DurableModuleOptions,\n tenantToken: TenantTokenSource | undefined,\n): Promise<{ schedules?: ScheduleAnnouncement }> {\n let tenant: string;\n try {\n tenant =\n tenantToken !== undefined\n ? await resolveTenantToken(tenantToken)\n : (options.partition ?? 'default');\n } catch (error) {\n // A token source that fails at boot must not keep the worker from starting: it announces no\n // schedules (the control plane then neither adopts nor withdraws any for it) and says so.\n console.warn(\n `[nestjs-durable] this worker announces no schedules: its tenantToken failed (${error instanceof Error ? error.message : String(error)})`,\n );\n return {};\n }\n return { schedules: { tenant, items: (options.schedules ?? []).map(announcedSchedule) } };\n}\n\nfunction announcedSchedule(s: ScheduledWorkflow): AnnouncedSchedule {\n const item: AnnouncedSchedule = { key: s.key, workflow: workflowName(s.workflow) };\n if (s.input !== undefined) item.input = s.input;\n if (s.everyMs !== undefined) item.everyMs = s.everyMs;\n if (s.cron !== undefined) item.cron = s.cron;\n if (s.timezone !== undefined) item.timezone = s.timezone;\n if (s.paused === true) item.paused = true;\n if (s.overlap !== undefined) item.overlap = s.overlap;\n if (s.jitter !== undefined && s.jitter > 0) item.jitterMs = s.jitter;\n return item;\n}\n\n/**\n * The thin-worker slice of {@link import('./durable.module').DurableModule}'s unified provider set —\n * active for the pure thin-worker role (`connection` set, `store` unset): registers discovered\n * `@Workflow`/`@Step` on a store-less {@link DurableWorkerRuntime} and starts ONE `runRedisWorker`\n * consumer, one queue PER REGISTERED NAME. Always present in the provider list (so a single\n * `DurableModule.forRootAsync` can serve any role once its options resolve); every class/factory here\n * is inert (see {@link isPureThinWorker}) outside that role.\n */\nexport function thinWorkerProviders(): Provider[] {\n return [\n {\n provide: DURABLE_WORKER_RUNTIME,\n // The runtime's `WorkflowWorker` falls back to its own `group` ctor param as the WORKFLOW's\n // `workflowPartition` for any `ctx.step` call (see `workflow-context.ts`'s `resolveCallGroup`)\n // — that fallback MUST equal this module's own `partition`, or a dispatched step's decision\n // carries a mismatched token and the engine dispatches it to a queue nothing here subscribes\n // to. Explicit `''` (never\n // `undefined`) so it does NOT fall through to `WorkflowWorker`'s unrelated `'workflows'`\n // default parameter.\n //\n // The role gate lives HERE, not just in the consumers: constructing the runtime resolves the\n // optional `@dudousxd/durable-worker` peer, so an operator that never runs a worker must not\n // reach this branch at all.\n useFactory: (options: DurableModuleOptions) =>\n isPureThinWorker(options)\n ? createWorkerRuntime({ workflowGroup: options.partition ?? '' })\n : null,\n inject: [DURABLE_OPTIONS_CANONICAL],\n },\n { provide: RUN_REDIS_WORKER, useValue: defaultRunRedisWorker },\n { provide: DURABLE_WORKER_RUNNERS, useValue: [] as RunningWorker[] },\n ThinWorkflowRegistrar,\n ThinStepRegistrar,\n ThinWorkerBootstrap,\n ];\n}\n\n/** Reject with a clear, named tenant error for a `RunGateway` call made without a `transport`. The\n * call site pins `T` from its own declared return type (e.g. `Promise<RunDetail | null>`); this\n * helper only ever rejects, so it never actually produces a `T` value. */\nfunction tenantGatewayUnavailable<T>(method: string): Promise<T> {\n return Promise.reject(\n new Error(`RunGateway.${method}() is not available — pass \\`transport\\` to use RunGateway.`),\n );\n}\n\n/**\n * The no-transport fallback bound to `RunGateway` for a thin worker (`connection` set, `store`\n * unset) that didn't also pass a `transport` — mirrors `DurableStartClient`'s tenant-error idiom\n * (`tenantUnsupported`): every method rejects with a clear, named error instead of a cryptic\n * `this.gateway.X is not a function`. `subscribe` is synchronous on the `RunGateway` port, so it\n * throws synchronously (same message) rather than returning a rejected promise.\n */\nexport function unavailableRunGateway(): RunGateway {\n return {\n // Topology is local metadata, always answerable — a thin worker with no transport is still a tenant.\n topology(): DurableTopology {\n return { role: 'tenant' };\n },\n getRunDetail(_runId: string): Promise<RunDetail | null> {\n return tenantGatewayUnavailable<RunDetail | null>('getRunDetail');\n },\n listRuns(_query: RunQuery): Promise<RunListItem[]> {\n return tenantGatewayUnavailable<RunListItem[]>('listRuns');\n },\n runFacets(_query: RunFacetQuery): Promise<RunFacetRow[]> {\n return tenantGatewayUnavailable<RunFacetRow[]>('runFacets');\n },\n runValueFacets(\n _axis: RunValueAxis,\n _query: RunFacetQuery,\n _opts?: RunValueFacetOptions,\n ): Promise<RunValueFacetRow[]> {\n return tenantGatewayUnavailable<RunValueFacetRow[]>('runValueFacets');\n },\n waitingFor(_runIds: string[]): Promise<Record<string, RunWaiting>> {\n return tenantGatewayUnavailable<Record<string, RunWaiting>>('waitingFor');\n },\n workerHealth(): Promise<GroupHealth[]> {\n return tenantGatewayUnavailable<GroupHealth[]>('workerHealth');\n },\n cancel(_runId: string): Promise<RunResult | null> {\n return tenantGatewayUnavailable<RunResult | null>('cancel');\n },\n retry(_runId: string): Promise<RunResult | null> {\n return tenantGatewayUnavailable<RunResult | null>('retry');\n },\n continue(_runId: string): Promise<RunResult | null> {\n return tenantGatewayUnavailable<RunResult | null>('continue');\n },\n retryWithInput(_runId: string, _input: unknown): Promise<{ runId: string } | null> {\n return tenantGatewayUnavailable<{ runId: string } | null>('retryWithInput');\n },\n redispatchPending(_runId: string): Promise<(RunResult & { redispatched: number }) | null> {\n return tenantGatewayUnavailable<(RunResult & { redispatched: number }) | null>(\n 'redispatchPending',\n );\n },\n subscribe(_runId: string, _onEvent: (event: EngineEvent) => void): () => void {\n throw new Error(\n 'RunGateway.subscribe() is not available — pass `transport` to use RunGateway.',\n );\n },\n };\n}\n","import {\n type SchemaValidationCode,\n SchemaValidationError,\n type StandardSchemaV1,\n} from '@dudousxd/nestjs-durable-core';\nimport type { z } from 'zod';\n\n/** A class-validator DTO class — validated with the same `plainToInstance` + `validate` NestJS's\n * `ValidationPipe` runs. */\nexport type DtoClass = new (...args: any[]) => object;\n\n/**\n * What `@Workflow({ input, output })` and `@Step({ input, output })` accept: a **Standard Schema**\n * (https://standardschema.dev — zod 3.24+, valibot, arktype, …) or a **class-validator DTO class**.\n * The two are told apart at runtime: a value with a `~standard` property is a Standard Schema, a\n * constructor is a DTO. A zod schema older than 3.24 (no `~standard`) still works through its `parse`.\n */\nexport type IoSchema = StandardSchemaV1 | DtoClass | z.ZodType;\n\n/** Parses a value against a schema: resolves the schema's output (coerced/transformed), or throws. */\nexport type Parser = (value: unknown) => Promise<unknown>;\n\n/**\n * Build a {@link Parser} for `schema`. A failure throws a {@link SchemaValidationError} (a\n * `FatalError`: retrying cannot fix a value that does not match its schema) with `code`\n * (`invalid_input` / `invalid_output`, so a dashboard, an alert or an `onError` route can tell it\n * apart) and the schema's issues in `issues` and `details.issues`.\n * `label` names what was being checked (`workflow \"checkout\" input`) in the message.\n */\nexport function schemaParser(schema: IoSchema, kind: 'input' | 'output', label: string): Parser {\n const code: SchemaValidationCode = kind === 'input' ? 'invalid_input' : 'invalid_output';\n if (isStandardSchema(schema)) {\n return async (value) => {\n const result = await schema['~standard'].validate(value);\n if (result.issues) throw new SchemaValidationError(label, result.issues, code);\n return result.value;\n };\n }\n if (isZodLike(schema)) {\n // zod < 3.24: no `~standard`, but `safeParse` reports the same issues.\n return async (value) => {\n const result = schema.safeParse(value);\n if (!result.success) throw new SchemaValidationError(label, result.error.issues, code);\n return result.data;\n };\n }\n if (typeof schema === 'function') return classValidatorParser(schema, code, label);\n throw new Error(\n `${label}: expected a Standard Schema (zod, valibot, …) or a class-validator DTO class`,\n );\n}\n\n/**\n * The class-validator path. `class-validator` and `class-transformer` are optional peers (only needed\n * if a DTO class is used), so they are reached through a dynamic `import()`: a static import would\n * resolve them for every consumer of the package, and a `require()` cannot work at all in the ESM\n * build. That defers the \"peer missing\" error to the first value parsed — the only moment the peers\n * are actually needed.\n */\nfunction classValidatorParser(cls: DtoClass, code: SchemaValidationCode, label: string): Parser {\n return async (value) => {\n let cv: any;\n let ct: any;\n try {\n cv = await import('class-validator');\n ct = await import('class-transformer');\n } catch {\n throw new Error(\n `${label} uses a class-validator DTO, which needs the optional peers \"class-validator\" and \"class-transformer\" — install them, or use a Standard Schema (zod, valibot, …) instead.`,\n );\n }\n // A DTO describes an object. class-validator crashes on `null`/`undefined` (a bare TypeError) and\n // reports nothing useful for a string or an array (which `plainToInstance` turns into an array of\n // instances), so anything else is rejected here, on the same coded contract as a failed check.\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n const got = value === null ? 'null' : Array.isArray(value) ? 'an array' : typeof value;\n throw new SchemaValidationError(label, [{ message: `expected an object, got ${got}` }], code);\n }\n const instance = ct.plainToInstance(cls, value);\n const errors = await cv.validate(instance, { whitelist: true });\n if (errors.length > 0) {\n const issues = errors.map((e: any) => ({\n message: Object.values(e.constraints ?? { _: `${e.property} is invalid` }).join(', '),\n path: [String(e.property)],\n }));\n // class-validator's messages already name the property (`orderId must be a string`).\n const summary = issues.map((i: { message: string }) => i.message).join('; ');\n throw new SchemaValidationError(label, issues, code, summary);\n }\n return instance;\n };\n}\n\nfunction isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n return (\n (typeof schema === 'object' || typeof schema === 'function') &&\n schema !== null &&\n '~standard' in schema\n );\n}\n\ninterface ZodLike {\n safeParse(value: unknown):\n | { success: true; data: unknown }\n | {\n success: false;\n error: { issues: { message: string; path: (string | number)[] }[] };\n };\n}\n\nfunction isZodLike(schema: unknown): schema is ZodLike {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n typeof (schema as { safeParse?: unknown }).safeParse === 'function'\n );\n}\n","import type { StepLogger, WorkflowCtx } from '@dudousxd/nestjs-durable-core';\nimport { DiscoveryService, MetadataScanner } from '@nestjs/core';\nimport { getDurableStepMeta, getWorkflowMeta } from './decorators';\nimport type { DurableStepMeta, WorkflowMeta } from './decorators';\nimport { originOfProvider } from './origin';\nimport { schemaParser } from './schema-parse';\n\nexport interface WorkflowInstance {\n run(ctx: WorkflowCtx, input: unknown): Promise<unknown>;\n}\n\n/**\n * Walks every provider that carries `@Workflow` metadata and invokes\n * `register(meta, instance, origin)`.\n *\n * `origin` is the package that declared the workflow class ({@link originOfProvider}), derived from\n * the provider wrapper — this is the ONE path every `@Workflow` in the app reaches, whichever role\n * the app runs in, so a lib that has never heard of the feature is attributed anyway. It is\n * `undefined` when the derivation could not answer confidently; the engine-side registrar\n * (`WorkflowRegistrar`) reports those at boot, and their runs carry no origin rather than a guess.\n *\n * Guards applied (same as both registrars):\n * - null / non-object provider instances are skipped\n * - providers without `@Workflow` metadata are skipped\n * - a `@Workflow` provider that has no `run` method throws at boot\n */\nexport function scanWorkflows(\n discovery: DiscoveryService,\n register: (meta: WorkflowMeta, instance: WorkflowInstance, origin: string | undefined) => void,\n): void {\n for (const wrapper of discovery.getProviders()) {\n const { instance } = wrapper;\n if (!instance || typeof instance !== 'object') continue;\n const meta = getWorkflowMeta(instance.constructor);\n if (!meta) continue;\n const workflow = instance as WorkflowInstance;\n if (typeof workflow.run !== 'function') {\n throw new Error(`@Workflow ${meta.name} must define a run(ctx, input) method`);\n }\n register(meta, workflow, originOfProvider(wrapper));\n }\n}\n\n/**\n * Walks every provider method that carries `@Step` metadata and invokes\n * `register(meta, boundHandler)`.\n *\n * Guards applied (same as both registrars):\n * - null / non-object provider instances are skipped\n * - non-function methods are skipped\n * - methods without `@Step` metadata are skipped\n *\n * The handler passed to `register` is already bound to its instance, and is the ONE place a `@Step`\n * method actually runs with real input/output in this package — every registrar\n * (`DurableStepRegistrar`, `InAppWorkerBootstrap`, `ThinStepRegistrar`) funnels through here — so\n * this is where `@Step`'s optional `input`/`output` schemas are enforced: `input` validates\n * before the method runs, `output` validates its return value before it's handed back. A bare\n * `@Step()` (no schemas attached) skips both checks — `meta.input`/`meta.output` are `undefined`.\n */\nexport function scanSteps(\n discovery: DiscoveryService,\n scanner: MetadataScanner,\n register: (\n meta: DurableStepMeta,\n handler: (input: unknown, log: StepLogger) => Promise<unknown>,\n ) => void,\n): void {\n for (const wrapper of discovery.getProviders()) {\n const { instance } = wrapper;\n if (!instance || typeof instance !== 'object') continue;\n const prototype = Object.getPrototypeOf(instance);\n for (const methodName of scanner.getAllMethodNames(prototype)) {\n const method = (instance as Record<string, unknown>)[methodName];\n if (typeof method !== 'function') continue;\n const meta = getDurableStepMeta(method);\n if (!meta) continue;\n const boundMethod = method as (input: unknown, log: StepLogger) => unknown;\n const parseInput =\n meta.input && schemaParser(meta.input, 'input', `step \"${meta.name}\" input`);\n const parseOutput =\n meta.output && schemaParser(meta.output, 'output', `step \"${meta.name}\" output`);\n const handler = async (input: unknown, log: StepLogger): Promise<unknown> => {\n const validInput = parseInput ? await parseInput(input) : input;\n const output = await boundMethod.call(instance, validInput, log);\n return parseOutput ? parseOutput(output) : output;\n };\n register(meta, handler);\n }\n }\n}\n","import { type OnErrorRoute, type WorkflowCtx, workflowName } from '@dudousxd/nestjs-durable-core';\nimport type { MetadataScanner } from '@nestjs/core';\nimport { type WorkflowMeta, onErrorCodesOf } from './decorators';\n\ntype WorkflowFn = (ctx: WorkflowCtx, input: unknown) => Promise<unknown>;\n\n/**\n * A `@Workflow` instance's onError routes and the handler workflows they name. Each `@OnError`\n * method becomes the workflow `<workflow>.onError.<method>`, bound to the instance, with one route per\n * code it declares; `@Workflow({ onError })` adds routes to workflows registered elsewhere.\n *\n * Shared by every registrar: the engine registers the handlers and the routes, and a worker runtime\n * registers the handlers and announces the routes, so a workflow served by convention is routed the\n * same as one the engine registered.\n */\nexport function onErrorHandlersOf(\n meta: WorkflowMeta,\n instance: object,\n scanner: MetadataScanner,\n): { handlers: [string, WorkflowFn][]; routes: OnErrorRoute[] } {\n const handlers: [string, WorkflowFn][] = [];\n const routes: OnErrorRoute[] = [];\n for (const methodName of scanner.getAllMethodNames(Object.getPrototypeOf(instance))) {\n const method = (instance as Record<string, unknown>)[methodName];\n const codes = typeof method === 'function' ? onErrorCodesOf(method) : undefined;\n if (!codes) continue;\n const name = `${meta.name}.onError.${methodName}`;\n handlers.push([name, (ctx, input) => (method as WorkflowFn).call(instance, ctx, input)]);\n for (const code of codes) routes.push({ code, workflow: name });\n }\n for (const r of meta.onError ?? []) {\n routes.push({\n code: r.code === undefined || typeof r.code === 'string' ? r.code : r.code.code,\n workflow: workflowName(r.workflow),\n });\n }\n return { handlers, routes };\n}\n","import type { WorkflowCtx } from '@dudousxd/nestjs-durable-core';\nimport type { WorkflowMeta } from './decorators';\nimport { schemaParser } from './schema-parse';\n\ntype WorkflowBody = (ctx: WorkflowCtx, input: unknown) => Promise<unknown>;\n\n/**\n * The `@Workflow({ input, output, validateInput })` contract, split into the two places it applies.\n *\n * - `validateAtStart` is handed to the engine, which calls it in `start` before any run is created:\n * the input schema must parse, then `validateInput` must not throw on the parsed value. The parsed\n * value is then discarded — the run stores the input as it was sent.\n * - `wrap` turns `run(ctx, input)` into the body every role registers (inline, in-app worker, thin\n * worker): the stored input is parsed before the body runs and the returned value is parsed before\n * it becomes the run's output. It wraps the BODY, not `start`, because the body is what runs on\n * every turn — including a replay on another process — so every turn sees the same parsed value,\n * even one (a `Date`, a DTO instance) the stored JSON can't carry.\n */\nexport function workflowIo(meta: WorkflowMeta): {\n validateAtStart: ((input: unknown) => Promise<void>) | undefined;\n wrap(body: WorkflowBody): WorkflowBody;\n} {\n const parseInput =\n meta.input && schemaParser(meta.input, 'input', `workflow \"${meta.name}\" input`);\n const parseOutput =\n meta.output && schemaParser(meta.output, 'output', `workflow \"${meta.name}\" output`);\n const validateInput = meta.validateInput;\n return {\n validateAtStart:\n parseInput || validateInput\n ? async (input) => {\n const parsed = parseInput ? await parseInput(input) : input;\n await validateInput?.(parsed);\n }\n : undefined,\n wrap: (body) =>\n !parseInput && !parseOutput\n ? body\n : async (ctx, input) => {\n const output = await body(ctx, parseInput ? await parseInput(input) : input);\n return parseOutput ? parseOutput(output) : output;\n },\n };\n}\n","import type { DurableWorkerRuntime } from '@dudousxd/durable-worker';\nimport type { MetadataScanner } from '@nestjs/core';\nimport { type WorkflowMeta, getOnEvents } from './decorators';\nimport type { WorkflowInstance } from './discovery-helpers';\nimport { onErrorHandlersOf } from './on-error-handlers';\nimport { workflowIo } from './workflow-io';\n\n/**\n * Register a `@Workflow` body on a worker runtime with what it ANNOUNCES about it (design §7.9):\n * version, capability demand, declaring package, its onError routes, which the engine applies to a\n * workflow it serves by convention, and the events it subscribes to, which an engine settling a run\n * reads to owe its lifecycle event to a subscriber only this worker has. The `@OnError` handler workflows are registered beside it, so\n * the queue the engine dispatches a handler to by name is one this worker consumes.\n */\nexport function registerOnRuntime(\n runtime: DurableWorkerRuntime,\n scanner: MetadataScanner,\n meta: WorkflowMeta,\n instance: WorkflowInstance,\n origin: string | undefined,\n): void {\n const { handlers, routes } = onErrorHandlersOf(meta, instance, scanner);\n const announced = {\n version: meta.version,\n ...(origin !== undefined ? { origin } : {}),\n };\n // The same parse-around-the-body the engine-side registrar applies, so a turn this worker replays\n // sees the parsed input too.\n const body = workflowIo(meta).wrap((ctx, input) => instance.run(ctx, input));\n const subscribes = [\n ...new Set(\n getOnEvents(meta, instance.constructor).map((entry) =>\n typeof entry === 'string' ? entry : entry.event,\n ),\n ),\n ];\n runtime.registerWorkflow(meta.name, body, {\n ...announced,\n ...(meta.requires !== undefined ? { requires: meta.requires } : {}),\n // A catch-all goes on the wire without a `code` key, not with an undefined one.\n ...(routes.length > 0\n ? {\n onError: routes.map(({ code, workflow }) =>\n code === undefined ? { workflow } : { code, workflow },\n ),\n }\n : {}),\n ...(subscribes.length > 0 ? { subscribes } : {}),\n });\n for (const [name, fn] of handlers) runtime.registerWorkflow(name, fn, announced);\n}\n","import { RunGateway } from '@dudousxd/nestjs-durable-core';\n\n/**\n * Cross-lib injection token for the current-request context accessor, owned by\n * `@dudousxd/nestjs-context`. We do NOT import nestjs-context (it is an OPTIONAL\n * peer dependency) — instead we share its well-known token by value so DI\n * resolves the same provider when nestjs-context is installed and present.\n *\n * `Symbol.for(key)` uses the global symbol registry, so this resolves to the\n * SAME symbol instance as nestjs-context's `tokens.ts` (and the identical token\n * declared by `@dudousxd/nestjs-authz`) without any import. The key MUST stay\n * byte-identical with nestjs-context's export.\n */\nexport const CONTEXT_ACCESSOR = Symbol.for('@dudousxd/nestjs-context:accessor');\n\n/**\n * Internal: the module's resolved tenant auth (`verifyTenant` and `tenantToken`, resolved through\n * DI). Shared by the module and the thin-worker providers, which announce under the tenant token.\n */\nexport const TENANT_AUTH = Symbol('nestjs-durable:tenant-auth');\n\n/**\n * @deprecated Inject the `RunGateway` class, which is its own DI token:\n * `constructor(private readonly gateway: RunGateway)`. Kept because published\n * `@dudousxd/nestjs-agent` and `@dudousxd/nestjs-agent-opencode` releases import it; it is the\n * `RunGateway` class itself, so `@Inject(RUN_GATEWAY)` resolves the same provider.\n */\nexport const RUN_GATEWAY = RunGateway;\n","import type { ConcurrencyOption } from '@dudousxd/durable-worker';\nimport {\n type AdmissionBackend,\n type ControlPlane,\n DURABLE_OPTIONS,\n DURABLE_OPTIONS_CANONICAL,\n type NamedTransport,\n type QueueConfig,\n type RetentionPolicy,\n RunGateway,\n STATE_STORE,\n STATE_STORE_CANONICAL,\n type ScheduledWorkflow,\n type StalledRunInfo,\n type StateStore,\n TRANSPORT,\n TRANSPORT_CANONICAL,\n type TenantTokenSource,\n type TenantVerifier,\n type Transport,\n WorkflowEngine,\n type WorkflowRef,\n sealDurableCopies,\n useDurableExecution,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n type DynamicModule,\n Inject,\n Injectable,\n type InjectionToken,\n Module,\n type OnApplicationBootstrap,\n type OnModuleDestroy,\n type Provider,\n} from '@nestjs/common';\nimport { DiscoveryModule, ModuleRef } from '@nestjs/core';\nimport type { ContextAccessor } from './context-accessor';\nimport { DurableStartClient } from './durable-start-client';\nimport { DurableStepRegistrar } from './durable-step.registrar';\nimport { thinWorkerProviders, unavailableRunGateway } from './durable-worker.module';\nimport { EntityService } from './entity';\nimport { inAppWorkerProviders } from './in-app-worker';\nimport { ProxyRunGateway } from './proxy-run-gateway';\nimport { RetentionPoller } from './retention-poller';\nimport { isDrivingOperator } from './role';\nimport { RunRequestResponder, type RunRequestTransport } from './run-request-responder';\nimport { StoreRunGateway } from './store-run-gateway';\nimport { SweepLeases } from './sweep-leases';\nimport {\n type DurableTenancyOption,\n type TenantRuntime,\n buildEngineTenancy,\n canRestoreTenant,\n isTenantRuntime,\n readTenancy,\n stepTenantWrapper,\n tenantFilterNow,\n} from './tenancy';\nimport {\n type TenantTokenOption,\n type TenantVerifierOption,\n resolveTenantTokenSource,\n resolveTenantVerifier,\n} from './tenant-contracts';\nimport { TenantEventRepublisher } from './tenant-event-republisher';\nimport { TimerPoller } from './timer-poller';\nimport { CONTEXT_ACCESSOR, TENANT_AUTH } from './tokens';\nimport { WorkflowRegistrar } from './workflow.registrar';\nimport { WorkflowService } from './workflow.service';\n\n/**\n * Locate the context accessor non-strictly: an accessor provided by ANY module (a global\n * `ContextModule` from `@dudousxd/nestjs-context`, or the app root) is found via {@link ModuleRef},\n * because DurableModule is `global` and its engine factory can't see another module's local\n * providers directly. Returns undefined when the optional peer isn't installed/bound.\n */\nfunction resolveAccessor(moduleRef: ModuleRef): ContextAccessor | undefined {\n try {\n return moduleRef.get<ContextAccessor>(CONTEXT_ACCESSOR, { strict: false });\n } catch {\n return undefined;\n }\n}\n\n/**\n * Build an opaque context carrier from a {@link ContextAccessor} — the auto-feed default for the\n * engine's `context` option when `@dudousxd/nestjs-context` is present and the app passed no own\n * reader. Drops fields the accessor doesn't populate, so an empty/anonymous request yields `{}`.\n */\nfunction carrierFromAccessor(accessor: ContextAccessor): Record<string, unknown> | undefined {\n const carrier: Record<string, unknown> = {};\n const traceId = accessor.traceId();\n if (traceId !== undefined) carrier.traceId = traceId;\n const tenantId = accessor.tenantId();\n if (tenantId !== undefined) carrier.tenantId = tenantId;\n // The full tenant (with its kind), so a worker restores `{ id, kind }` and not `kind: 'unknown'`.\n // A `legacy` one (only a plain `tenantId` was set) adds nothing the `tenantId` above doesn't carry.\n const tenant = accessor.tenant?.();\n if (tenant !== undefined && tenant.source !== 'legacy') carrier.tenant = tenant;\n const userRef = accessor.userRef();\n if (userRef !== undefined) carrier.userRef = userRef;\n return carrier;\n}\n\n/** True when nestjs-context publishes its accessor on the global slot (even with no DI binding). */\nfunction contextSlotPresent(): boolean {\n const slot = (globalThis as unknown as Record<symbol, { current?: unknown } | undefined>)[\n Symbol.for('@dudousxd/nestjs-diagnostics:accessor')\n ];\n return !!slot?.current;\n}\n\n/**\n * The slice of `@dudousxd/nestjs-context`'s module-level `Context` singleton we use to re-hydrate the\n * originating context around a local step body. Structural — we never import the package's types (it\n * is an OPTIONAL peer); the guarded dynamic import below captures whatever the installed package\n * exports as `Context`.\n */\ninterface ContextRuntime {\n /** Re-hydrate a context from an opaque carrier and run `fn` inside its ALS scope. */\n deserialize<T>(carrier: Record<string, unknown>, fn: () => T): T;\n /** Run `fn` with a tenant (nestjs-context ≥ 1.2). Absent on an older context: tenancy stays off. */\n withTenant?: TenantRuntime['withTenant'];\n}\n\nfunction isContextRuntime(x: unknown): x is ContextRuntime {\n return !!x && typeof (x as ContextRuntime).deserialize === 'function';\n}\n\n/**\n * Resolve `@dudousxd/nestjs-context`'s runtime `Context` singleton via a GUARDED dynamic import — used\n * to build the engine's `rehydrate` bridge. The runtime `Context` (its `deserialize`/ALS `run`) is a\n * module-level singleton, NOT a DI provider behind {@link CONTEXT_ACCESSOR}, so it can't be resolved\n * through ModuleRef — we import it directly. We do NOT add a hard/static import (the peer is optional):\n * a failure (peer not installed) returns undefined and the engine falls back to passthrough re-hydration.\n */\nasync function resolveContextRuntime(): Promise<ContextRuntime | undefined> {\n try {\n // Indirect the specifier through a variable so the compiler does not try to STATICALLY resolve\n // the optional peer (it may be uninstalled). This stays a runtime guarded import — a missing\n // module rejects and is caught below.\n const specifier = '@dudousxd/nestjs-context';\n const mod = (await import(specifier)) as { Context?: unknown };\n return isContextRuntime(mod.Context) ? mod.Context : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** True when `x` can act as a control plane (broadcast pub/sub) — e.g. a broadcast-capable transport. */\nfunction isControlPlane(x: unknown): x is ControlPlane {\n return (\n !!x &&\n typeof (x as ControlPlane).publishControl === 'function' &&\n typeof (x as ControlPlane).onControl === 'function'\n );\n}\n\n/** A store that can derive a tenant-namespace-scoped view of itself (the MikroORM adapter). */\ninterface ScopeableStore {\n /** Derive a store confined to `scope.namespace`, sharing the same backing connection. */\n withScope(scope: { namespace?: string }): StateStore;\n}\n\n/**\n * True when `store` can produce a namespace-scoped view of itself. Structural check (same idiom as\n * {@link isControlPlane}) so the store-agnostic module never imports a concrete adapter — the\n * pre-built `store` is only re-scoped when it actually carries the capability.\n */\nfunction isScopeableStore(store: StateStore): store is StateStore & ScopeableStore {\n return typeof (store as StateStore & Partial<ScopeableStore>).withScope === 'function';\n}\n\n/**\n * Apply opt-in tenant read scoping to a pre-built store. The module receives `store` already\n * instantiated (it is store-agnostic — no MikroORM import), so it cannot reconstruct it; instead it\n * asks the store for a scoped view via the optional {@link ScopeableStore.withScope} capability. When\n * `scopeReads` is off, `namespace` is unset, or the store can't scope itself, the original store is\n * returned unchanged (the operator view) — the caller can always pass an already-scoped store.\n */\nfunction scopedStore(store: StateStore, options: DurableModuleOptions): StateStore {\n if (options.scopeReads !== true || options.namespace === undefined) return store;\n if (!isScopeableStore(store)) return store;\n return store.withScope({ namespace: options.namespace });\n}\n\n/**\n * Retention config for the {@link RetentionPoller}. One or more {@link RetentionPolicy policies}\n * (status sets must be disjoint per scope — validated at boot), swept together on a shared interval.\n *\n * ```ts\n * retention: {\n * sweepInterval: '1m',\n * batchSize: 1_000,\n * policies: [\n * { statuses: ['completed', 'cancelled'], maxAge: '14d', maxCount: 200 },\n * { statuses: ['failed'], maxAge: '90d' }, // keep failures longer for debugging\n * // Scoped: chat turns age out after a day, whatever the defaults above say.\n * { statuses: ['completed', 'failed', 'cancelled'], maxAge: '1d', scope: { tags: ['chat'] } },\n * ],\n * }\n * ```\n *\n * Policies are applied one after another, so a run matched by several scopes is pruned by the\n * strictest of them.\n */\nexport interface DurableRetentionOptions {\n /** The retention rules, one per (disjoint) status group. */\n policies: RetentionPolicy[];\n /**\n * How often to run the prune sweep. A number is milliseconds; a string is an `ms`-style duration\n * (`'1m'`, `'5m'` — `'m'` is minutes). `0` runs it once on boot only. Defaults to 60000 (1 minute).\n */\n sweepInterval?: number | string;\n /** Max runs hard-deleted per batch (per policy, looped until drained). Defaults to 1000. */\n batchSize?: number;\n}\n\n/**\n * The options every {@link DurableModuleOptions} variant shares. With no `topology` (or\n * `topology: 'standalone'`) the **role is inferred** from which of `store`/`connection` are set:\n *\n * - `{ store, transport }`: **operator**, a real `WorkflowEngine` + `StoreRunGateway` + drivers/\n * timer/retention/registrars, executing registered bodies INLINE. Driven by {@link drive} (default\n * `true`).\n * - `{ connection }` (no `store`): **thin worker**, `WorkflowEngine` resolves to a store-less\n * `DurableStartClient`; `RunGateway` is a `ProxyRunGateway` when `transport` is also given, else\n * every method rejects with a clear error. No store/timer/retention/entity, just discovered\n * `@Workflow`/`@Step` handlers served over ONE `runRedisWorker` consumer.\n * - `{ store, transport, connection }`: an **operator that also runs a co-located worker**: every\n * `@Workflow` is registered GROUP-SERVED (dispatched over the transport, PER WORKFLOW NAME, instead\n * of inline) and a co-located consumer (one `runRedisWorker` call) replays the same bodies.\n *\n * `forRoot` throws when neither `store` nor `connection` is set, and when `store` is set without a\n * `transport`.\n */\nexport interface DurableModuleSharedOptions {\n /** State store — set this to play the **operator** role (see the interface doc for the full role\n * matrix). Omit for a store-less **thin worker** (`connection` only). */\n store?: StateStore;\n transport?: Transport;\n /**\n * An ordered pool of named transports for failover / multi-broker setups. The engine dispatches on\n * the first and fails over to the next; a step pins one via `ctx.step(handler, input, { transport })`.\n * Use instead of `transport`.\n */\n transports?: NamedTransport[];\n /**\n * Cross-instance broadcast pub/sub (lifecycle events + cancellation). Defaults to the (first)\n * transport when it can broadcast (event-emitter, BullMQ); set explicitly to use a dedicated one.\n */\n controlPlane?: ControlPlane;\n /** Interval (ms) for the durable-timer poller. `0` disables it. Defaults to 1000. Operator only. */\n timerPollMs?: number;\n /**\n * The longest wait (ms) between two timer polls while there is nothing to do. After a poll that\n * found no work the wait doubles from `timerPollMs` up to this, and goes back to `timerPollMs` as\n * soon as there is work or any run event (here, or from another instance over the control plane).\n * It never outlasts a known due time: before each longer wait the poller reads when the next timer,\n * blocked-run recovery poll, persisted schedule or in-process `schedules` window is due. What it\n * delays is recovery only: a crashed instance's runs, execution timeouts and the stalled/\n * buffered-signal sweeps are picked up at most this late. A value at or below `timerPollMs` keeps\n * the fixed tick, and so does an engine with neither a control plane nor a run queue (a run another\n * instance starts reaches it only through the pending-run poll). Defaults to 5000. Operator only.\n */\n maxIdleIntervalMs?: number;\n /**\n * How often (ms) the timer poller lists the settled runs that still owe a lifecycle event, and\n * heals the ones that missed a newly announced subscriber. That listing is the recovery path for a\n * publish that never happened (the live publish gets a 30 s grace first) and filters runs by tag,\n * so running it on every tick cost a scan of the runs table each second for nothing. The run-wait\n * delivery and registry heartbeat still run every tick. A failed sweep is retried on the next tick.\n * `0` sweeps on every tick (the old behavior). Defaults to 10000. Operator only.\n */\n owedLifecycleSweepMs?: number;\n /**\n * Auto-create the durable tables on boot via `store.ensureSchema()`. Defaults to true. Turn\n * off in production and call the store adapter's `ensure*DurableSchema()` from a migration.\n * Operator only.\n */\n autoSchema?: boolean;\n /**\n * Worker-pool namespace for this instance (forwarded to the engine). The poll paths\n * (`runPending`/`recoverIncomplete`/`resumeDueTimers`/`sweepTimeouts`) only act on runs in this\n * namespace. Set distinct values to safely share ONE state store across non-interchangeable\n * pools — e.g. a developer's local instance vs the deployed cluster. **Omit it to make this\n * instance an OPERATOR** — an unset namespace drives/recovers/resumes runs of EVERY namespace and\n * leaves the transport on its bare prefix. See `WorkflowEngineDeps.namespace`. Not to be confused\n * with {@link partition} (the co-located/thin-worker QUEUE routing suffix).\n */\n namespace?: string;\n /**\n * Multi-instance recovery lease, in ms — how long an instance owns a run it picked up before\n * another may take over. Defaults to 30000. Set above your longest synchronous run. Operator only.\n */\n leaseMs?: number;\n /** Unique id for this instance (for leases, and the co-located/thin-worker consumer's heartbeats). */\n instanceId?: string;\n /**\n * Cap recovery attempts before a still-`running` run is moved to the `dead` dead-letter state\n * (a poison pill that crashes the process every boot). Omit for unlimited. Operator only.\n */\n maxRecoveryAttempts?: number;\n /**\n * How long (ms) a run may stay unresumable because its workflow version is registered nowhere (a\n * renamed or deleted workflow) before it is dead-lettered. Default 24h; `0` skips it forever.\n */\n unregisteredWorkflowGraceMs?: number;\n /**\n * Opt-in liveness deadline (ms) for a remote (polyglot) workflow `advance`. If the worker neither\n * returns a decision nor sends a run-scoped heartbeat within this window, the engine presumes it dead\n * and lets recovery re-drive; each heartbeat rearms the window so a slow-but-alive worker is never\n * re-driven. Pair with a worker SDK that emits run-scoped heartbeats (`@dudousxd/durable-worker` ≥ the\n * release that ships them, and the Python `durable-worker`). Omitted, a turn dispatched over a\n * broker (a tenant's worker, another SDK's) takes {@link reconcileMs} as its window, so a run whose\n * worker died mid-turn is re-driven within it; `reconcileMs: 0` keeps the unbounded wait.\n * Operator only.\n */\n remoteAdvanceSilenceMs?: number;\n /**\n * Opt-in self-heal window (ms) for a dispatched remote step whose job was LOST — the worker was\n * killed mid-step (an OOM kill leaves no result, and a non-TS consumer has no way to bridge the\n * job's terminal failure back into one), or the broker dropped the job. The `pending` checkpoint\n * then has nothing left to settle it, so the run waits forever. When set, the pending checkpoint\n * carries a LEASE: a result — or a step-scoped heartbeat, which renews it, so a worker still\n * holding the step is never double-dispatched — must land within the window, else the engine\n * re-dispatches the same step (bumping `attempts`, bounded by {@link remoteRedispatchMax}).\n * Covers both `ctx.step` and a polyglot workflow's `call` fan-out (`ctx.gather_calls`).\n *\n * Off by default: a re-dispatch double-runs a step whose original job was merely SLOW, so the\n * window MUST exceed your longest remote step and the step MUST be idempotent. Operator only.\n */\n remoteRedispatchMs?: number;\n /**\n * Max times {@link remoteRedispatchMs} re-dispatches one lost step before failing it\n * (`remote_step_lost`, surfaced on the run) instead of re-dispatching forever. Defaults to 10.\n * Ignored when `remoteRedispatchMs` is unset. Operator only.\n */\n remoteRedispatchMax?: number;\n /**\n * Fallback wake-up (ms) for a run suspended on an event (child, signal, `waitForEvent`, remote\n * result) whose wake-up was lost: the reconcile pass re-drives it after this window, an idempotent\n * replay that re-suspends a still-pending wait. Defaults to 300000 (5min); `0` disables it. Also\n * the re-drive window of a dispatched workflow turn when {@link remoteAdvanceSilenceMs} is unset.\n * See `WorkflowEngineDeps.reconcileMs`. Operator only.\n */\n reconcileMs?: number;\n /**\n * Idle time (ms) before a stranded in-flight run is reported to {@link onStalled} listeners.\n * Defaults to 900000 (15 min), floored at 60000. See `WorkflowEngineDeps.stalledAfterMs`.\n * Operator only.\n */\n stalledAfterMs?: number;\n /**\n * Pager hook for stranded runs, registered on the engine as `engine.onStalled(...)`: a run\n * suspended with no wake timer, or parked on an old pending remote step nothing is leasing. The\n * timer poller sweeps once a minute and reports each stranded episode once per instance.\n * Equivalent to calling `engine.onStalled` from a provider; only a DRIVING operator sweeps.\n */\n onStalled?: (info: StalledRunInfo) => void;\n /**\n * The most due timers one timer-poll pass loads and drives, most overdue first, so a wave of\n * thousands of due runs is worked through in batches. Defaults to 500; a non-finite or sub-1 value\n * falls back to the default. See `WorkflowEngineDeps.timerBatchSize`. Operator only.\n */\n timerBatchSize?: number;\n /**\n * Retention (ms) for a buffered event that no `waitForEvent` ever claims; the reconcile pass prunes\n * rows past `publishedAt + eventBufferTtlMs`. Omit (or `0`) to keep them until consumed, the\n * default. See `WorkflowEngineDeps.eventBufferTtlMs`. Operator only.\n */\n eventBufferTtlMs?: number;\n /**\n * How long `signal(token, payload, { id })` remembers an id (ms, or a duration like `'7d'`); a\n * re-send with the same token and id within it is dropped. Default 7 days. See\n * `WorkflowEngineDeps.signalIdTtl`.\n */\n signalIdTtl?: string | number;\n /**\n * How long (ms) a run parked `blocked` (no capable, protocol-compatible live worker) waits before\n * the blocked-recovery poll re-checks the fleet. Defaults to 5000. See\n * `WorkflowEngineDeps.blockedPollMs`. Operator only.\n */\n blockedPollMs?: number;\n /**\n * How long (ms) the routing guard reuses the worker descriptors it read for a queue token. On\n * BullMQ each read scans the Redis keyspace. Default 2000; `0` reads on every dispatch. See\n * `WorkflowEngineDeps.workerDescriptorCacheMs`. Operator only.\n */\n workerDescriptorCacheMs?: number;\n /**\n * Persist a `running` checkpoint when a local step's body begins, so an in-flight step survives a\n * dashboard reload. Defaults to `true`; set `false` on hot paths with many short local steps to\n * halve their checkpoint writes. See `WorkflowEngineDeps.trackStepStart`. Operator only.\n */\n trackStepStart?: boolean;\n /**\n * How many workflow bodies parked on dispatched `ctx.step` calls this instance keeps in memory\n * between turns, so a step's result continues the body instead of replaying it over the run's\n * whole history. Default 1000 (~26 KB of heap each); `0` turns it off. See `WorkflowEngineDeps.stickyRuns` and the\n * \"Performance\" section of the production guide. Operator only.\n */\n stickyRuns?: number;\n /** How long a parked body may stay idle in that cache. Default 5 min. Operator only. */\n stickyIdleMs?: number;\n /**\n * Send each dispatched `ctx.step` result back to the engine instance that dispatched it (and holds\n * the parked body), on transports that can route replies (BullMQ). Default `true`. See\n * `WorkflowEngineDeps.routeReplies`. Operator only.\n */\n routeReplies?: boolean;\n /**\n * The **default** workflow to route dead-lettered runs to, for workflows that don't declare their\n * own. When a run is moved to `dead` (exceeded `maxRecoveryAttempts`), the started handler gets a\n * `DeadLetter` payload `{ deadRunId, workflow, input, error }` (idempotent by a `dlq:<runId>` id) —\n * it can alert, compensate, or queue for review. Resolution per dead run: the workflow's inline\n * `@DeadLetter()` method → its `@Workflow({ deadLetterWorkflow })` reference → this default. Omit\n * everything to just leave dead runs parked (inspectable + retriable from the dashboard). Accepts a\n * workflow class (refactor-safe) or a name (cross-runtime). Operator only.\n */\n deadLetterWorkflow?: WorkflowRef;\n /**\n * Whether an **operator** instance actively DRIVES runs — polls pending, recovers crashed\n * (`recoverIncomplete`), resumes due timers, sweeps timeouts, prunes retention, and consumes local\n * steps — as opposed to a read-only/dashboard replica. Defaults to `true`. Set `false` for a\n * **dashboard/dispatch-only** instance (e.g. an API pod) that mounts the store/dashboard but must\n * not process or recover workflows — leave that to another driving instance. `drive: false` also\n * installs the engine's no-op run dispatcher, so a freshly `start()`ed run stays enqueue-only until\n * a driving instance's poll picks it up. Ignored (irrelevant) for a thin worker (no `store`).\n */\n drive?: boolean;\n /**\n * Whether this process CONSUMES from the broker. Defaults to `true`. Set `false` in a process that\n * boots the module without being a worker — a CLI command, a REPL, a migration or seed script — so\n * it doesn't compete with the real fleet: every transport that supports it (`BullMQTransport`) has\n * its point-to-point consumers (step tasks, results, decisions, step events, start-run, run-request)\n * parked via `deferConsumers()`, and no co-located/thin worker consumer starts. The process still\n * dispatches and starts runs; the jobs stay on the queues for the fleet. Pair it with\n * `drive: false` so it doesn't poll/recover runs either. To consume later in the same process, call\n * `startConsumers()` on your transport. A transport without `deferConsumers()` (the SQL/SQS/in-process\n * transports) keeps consuming — a warning says so.\n */\n consumers?: boolean;\n /** Max ms to wait for in-flight runs on shutdown before exiting. Defaults to 10000. Operator only. */\n shutdownTimeoutMs?: number;\n /**\n * Recurring workflows to start on a schedule (fixed interval or cron). The timer poller fires\n * them each tick on **driving** instances only; `engine.start` is idempotent by the schedule's\n * time-bucket run id, so racing instances start each window exactly once. Cron schedules need the\n * optional `cron-parser` peer dependency. Operator only.\n */\n schedules?: ScheduledWorkflow[];\n /**\n * Fire the PERSISTED schedules managed at runtime through `engine.schedules` (create/upsert/pause/\n * resume/delete/list) on every timer-poll tick of a driving instance — one indexed \"due by now\"\n * query per tick. Off by default, so a deployment that never uses them doesn't need the\n * `durable_schedules` table. Safe with any number of driving instances: each window's run id is\n * deterministic and advancing a schedule is a compare-and-set. Operator only.\n */\n persistedSchedules?: boolean;\n /**\n * Adopt the `schedules` that TENANT apps declare and fire them here (a tenant has no store to fire\n * them from). Each tenant worker announces its app's schedules on its descriptor; every `syncMs`\n * (default 15 s) a driving instance turns them into persisted schedules (id\n * `app:<partition>:<key>`, tagged `schedule:announced`), applies a changed definition, and pauses\n * one that no live worker of its app has announced for `graceMs` (default 10 minutes). It then\n * fires them on every tick, through the tenant start path: with no live worker of the app, a run\n * waits `blocked` (`no_live_worker`) for one. On by default for a driving instance with a store\n * that persists schedules and a transport that reads worker descriptors (BullMQ); `false` turns it\n * off. Operator only.\n */\n announcedSchedules?: boolean | { syncMs?: number; graceMs?: number };\n /**\n * Hard-prune terminal run history on an interval so `durable_workflow_runs` (and its child tables)\n * stays bounded — without it, completed/failed/cancelled runs accumulate forever and the timer\n * poller's per-tick status scans get linearly slower. Driving instances only. Omit to keep all\n * history (the default). Requires a store adapter that implements `pruneTerminalRuns` (every\n * first-party adapter does); a custom store without it no-ops with a warning. See\n * {@link DurableRetentionOptions}.\n * Operator only.\n */\n retention?: DurableRetentionOptions;\n /**\n * Build the public callback URL for a `ctx.webhook()` token, e.g.\n * ``(t) => `https://api.example.com/durable/api/webhooks/${t}` ``. Populates `DurableWebhook.url`\n * so a step can hand the URL to a third party. The dashboard's `POST webhooks/:token` receives the\n * callback. Omit to build URLs yourself from the token. Operator only.\n */\n webhookUrl?: (token: string) => string;\n /**\n * Flow-control queues for remote steps, registered on the engine at startup. Reference one from a\n * workflow with `ctx.step(handler, input, { queue: name })` to cap its concurrency / admission rate.\n * Operator only.\n */\n queues?: QueueConfig[];\n /**\n * Admission backend for the flow-control `queues`. Defaults to in-process (per-instance) caps. Pass\n * a `RedisAdmissionBackend` (from `@dudousxd/nestjs-durable-admission-redis`) to make concurrency /\n * rate-limit / priority ordering GLOBAL across every engine replica. Operator only.\n */\n admission?: AdmissionBackend;\n /**\n * Provide the current W3C `traceparent` to stamp on dispatched remote tasks, so workers continue\n * the distributed trace. Pass `otelTraceparent` from `@dudousxd/nestjs-durable-otel`. Operator only.\n */\n traceparent?: () => string | undefined;\n /**\n * Provide an opaque context carrier (tenant / user / correlation ids) to stamp on dispatched remote\n * tasks, so workers re-expose it to the step handler alongside the `traceparent`. The engine never\n * inspects its shape.\n *\n * **Auto-feed**: if you omit this AND `@dudousxd/nestjs-context` is installed (its accessor is bound\n * to the shared `CONTEXT_ACCESSOR` token), DurableModule defaults this to a reader that builds\n * `{ traceId, tenantId, userRef }` from the accessor — so a workflow dispatched within a request\n * automatically carries the originating context across process boundaries. Pass your own reader to\n * override the auto-feed; with neither, the carrier is omitted (unchanged behavior).\n *\n * Re-evaluated at each (re)dispatch — including a retry or a crash/scale-down resume that the engine\n * drives OUTSIDE the originating request scope, where this reader may return empty or stale values.\n * Treat the carrier as best-effort correlation/propagation metadata only — do NOT treat it as an\n * authorization boundary. Operator only.\n */\n context?: () => Record<string, unknown> | undefined;\n /**\n * Tenancy: scope runs by the CUSTOMER they belong to (`@dudousxd/nestjs-context`'s tenant), not by\n * the worker-pool {@link namespace}. With it on, `start` stamps the request's tenant on the run\n * (an explicit `StartOptions.tenantId` wins), children, `continueAsNew` and schedules inherit it,\n * every turn runs with it restored as the context tenant, and app-facing reads and control calls\n * (`getRun`, `signal`, `cancel`, retry, the dashboard) only see the caller's tenant's runs.\n *\n * `'inherit'` (default) follows `ContextModule.forRoot({ tenancy: { enabled } })`, which is off by\n * default; `false` keeps durable out of tenancy. Without nestjs-context ≥ 1.2, tenancy is off.\n */\n tenancy?: DurableTenancyOption;\n /** Attempts for each saga compensation when a run fails. Default 1 (no retry). Idempotent undos.\n * Operator only. */\n compensationRetries?: number;\n /**\n * Opt into tenant read scoping: when `true` AND {@link namespace} is set, the module confines the\n * store's reads to that namespace (a tenant-boundary view) instead of the operator view that sees\n * all namespaces. Default `false` — the control plane (e.g. flip's `/ctrl` operator screens) stays\n * unscoped. Requires a store that exposes the `withScope` capability (the MikroORM adapter does);\n * a pre-built store without it is used as-is (construct it already-scoped instead). Operator only.\n */\n scopeReads?: boolean;\n /**\n * ioredis connection (string or options) for a **thin worker** (`connection` only) or the\n * **co-located worker** consumer (`store` + `connection`). Set this to play a worker role (see the\n * interface doc for the full role matrix). Omit to keep every `@Workflow` on the operator's inline\n * fast path with zero dispatch round-trips.\n */\n connection?: string | Record<string, unknown>;\n /**\n * The isolation partition a worker role serves — a thin worker's or co-located worker's queue\n * subscription, AND (for a co-located worker) the suffix each `@Workflow`'s dispatch token carries.\n * Each handler's queue token is `tenantGroup(sanitizeQueueToken(name), partition)`\n * (`@dudousxd/nestjs-durable-core`), so `undefined`, `''`, or `'default'` stays byte-identical to\n * the bare (sanitized) name (single-tenant deployment unchanged), and any other partition serves\n * `<name>@<partition>` — matching the queue name an operator's convention dispatch routes that\n * tenant's runs to (`tenantGroup(run.workflow, run.namespace)` on the engine side). Not to be\n * confused with {@link namespace} (the operator's own poll-scoping axis). Ignored for a plain\n * operator (no `connection`).\n */\n partition?: string;\n /** Key prefix namespacing the durable queues for a worker role's consumer. Defaults to `durable`\n * (matches the transport). Ignored for a plain operator (no `connection`). */\n prefix?: string;\n /**\n * How many tasks a worker role's co-located/thin consumer runs concurrently PER SUBSCRIBED QUEUE\n * (BullMQ Worker concurrency — the same limit is applied to every per-name queue the single\n * `runRedisWorker` call starts). Defaults to 1. Raise it so a fanned-out batch (e.g. the N remote\n * steps of a `gather`) runs in parallel instead of serially.\n *\n * Pass `'adaptive'` (or `{ mode:'adaptive', ... }`) to let the consumer self-tune its concurrency\n * (latency gradient + RAM brake + backpressure) and publish a live status on its heartbeat. Ignored\n * for a plain operator (no `connection`).\n */\n concurrency?: ConcurrencyOption;\n /**\n * Per-handler concurrency override, keyed by workflow/step NAME. Falls back to {@link concurrency}\n * (then 1). NOT YET WIRED THROUGH: `runRedisWorker` (`@dudousxd/durable-worker`) currently applies\n * one {@link concurrency} limit uniformly across every per-name queue it subscribes to from a\n * single call — reserved here for when per-name concurrency lands there.\n */\n concurrencyByHandler?: Record<string, ConcurrencyOption>;\n /** Timeout for a thin worker's `RunGateway` round-trip over `transport` before it rejects. Defaults\n * to 10_000ms inside `ProxyRunGateway`. Ignored for an operator (bound to `StoreRunGateway`). */\n runGatewayTimeoutMs?: number;\n /**\n * **Operator.** Verifies the signed tenant token a store-less tenant worker presents in the wire\n * `tenant` field of every run request and start-run message, and DERIVES the tenant from it,\n * discarding the wire claim. An invalid, tampered or absent token is rejected: a run request gets\n * an `unauthorized` error reply, a start-run creates nothing; a verifier that throws fails the\n * request with its error. Use `hmacTenantVerifier(secret)` (tokens minted by `signTenantToken`,\n * wire-compatible with Agora) or supply your own: a function, an object or class implementing\n * `TenantVerifierContract` (a class is built once through Nest DI), or a lazy import of one\n * (`() => import('./tenant-verifier.js')`, imported once).\n *\n * Optional. Absent: the wire `tenant` is trusted verbatim (prefix/network isolation only), exactly\n * as before. `topology: 'control-plane'` without a verifier logs a warning at boot; a standalone\n * operator boots silently.\n */\n verifyTenant?: TenantVerifierOption;\n /**\n * **Tenant worker.** The signed token (see `signTenantToken`) this worker presents, verbatim, in\n * the `tenant` field of every run request (`ProxyRunGateway`) and start-run (`engine.start`), so\n * an operator with {@link verifyTenant} can authenticate it. A string, a function called before\n * every request (rotation, short-lived tokens), an object or class implementing\n * `TenantCredentialsContract` (a class is built once through Nest DI), or a lazy import of one.\n * Every form but the string is called per request and owns its caching. Optional: absent, the raw\n * {@link partition} is sent, as before. Live-tail stays keyed by the partition, never the token.\n */\n tenantToken?: TenantTokenOption;\n}\n\n/** The process roles a {@link DurableModuleOptions.topology} names. Same vocabulary as Agora. */\nexport type DurableTopologyName = 'standalone' | 'control-plane' | 'tenant';\n\n/**\n * The default topology: today's role inference from `store`/`connection` (see\n * {@link DurableModuleSharedOptions}). `partition` is the queue suffix a worker role serves.\n */\nexport interface StandaloneDurableOptions extends DurableModuleSharedOptions {\n topology?: 'standalone';\n}\n\n/**\n * A coordinator: owns the store, dispatches over the transport, recovers, fires timers, prunes\n * retention and answers tenant requests. Requires `store` and `transport` (or `transports`).\n */\nexport interface ControlPlaneDurableOptions\n extends Omit<DurableModuleSharedOptions, 'store' | 'tenantToken'> {\n topology: 'control-plane';\n store: StateStore;\n /**\n * The namespace this control plane serves. Omit it on a deployed control plane, which then drives\n * every tenant's runs. Set it to scope a self-contained stack (a developer's machine sharing a\n * broker with a deployed cluster) to its own runs: it becomes this node's `namespace` and the\n * `<name>@<partition>` queues its co-located consumers subscribe to.\n */\n partition?: string;\n /** A control plane verifies tenant tokens; it does not present one. */\n tenantToken?: never;\n}\n\n/**\n * A store-less worker for one partition: it pulls `<name>@<partition>` tasks from the broker over\n * `connection` and, with a `transport`, proxies reads and control actions to the control plane.\n */\nexport interface TenantDurableOptions\n extends Omit<\n DurableModuleSharedOptions,\n 'store' | 'namespace' | 'partition' | 'connection' | 'verifyTenant'\n > {\n topology: 'tenant';\n /** A tenant is store-less: everything goes over the wire to the control plane. */\n store?: never;\n /** `namespace` scopes an operator's poll loop; a tenant has none. Use `partition`. */\n namespace?: never;\n /** The partition this process serves and acts as. Required. */\n partition: string;\n /** The broker connection the tenant's consumer pulls its partition's tasks from. Required. */\n connection: string | Record<string, unknown>;\n /** A tenant presents a token (`tenantToken`); the control plane verifies it. */\n verifyTenant?: never;\n}\n\n/**\n * Options for `DurableModule.forRoot`/`forRootAsync`, discriminated on `topology`:\n *\n * ```ts\n * // Control plane: owns the store, dispatches over the transport, prunes old runs.\n * DurableModule.forRoot({\n * topology: 'control-plane',\n * store,\n * transport,\n * retention: { policies: [{ statuses: ['completed', 'cancelled'], maxAge: '14d' }] },\n * });\n *\n * // Tenant: a store-less worker serving its own partition.\n * DurableModule.forRoot({\n * topology: 'tenant',\n * partition: 'acme-corp',\n * connection: process.env.REDIS_URL,\n * });\n * ```\n *\n * Omit `topology` (or pass `'standalone'`) to keep the role inference described on\n * {@link DurableModuleSharedOptions}. TypeScript rejects a `store` on a tenant; the rest is\n * validated at `forRoot`/`forRootAsync` resolution time.\n */\nexport type DurableModuleOptions =\n | StandaloneDurableOptions\n | ControlPlaneDurableOptions\n | TenantDurableOptions;\n\nexport interface DurableModuleAsyncOptions {\n // `never[]` (not `object[]`) is intentional: a contravariant bottom-type rest param is what lets a\n // consumer supply a factory with concrete injected args, e.g. `(config: ConfigService) => …`.\n useFactory: (...args: never[]) => DurableModuleOptions | Promise<DurableModuleOptions>;\n inject?: InjectionToken[];\n}\n\n/** Park `transport`'s point-to-point consumers (`consumers: false`) when it supports it. */\nfunction deferTransportConsumers(transport: Transport): void {\n const deferrable = transport as Transport & { deferConsumers?: () => void };\n if (typeof deferrable.deferConsumers === 'function') {\n deferrable.deferConsumers();\n return;\n }\n console.warn(\n `[nestjs-durable] consumers: false — ${transport.constructor?.name ?? 'this transport'} cannot defer its consumers and will keep consuming in this process`,\n );\n}\n\n/** Throws the exact role-inference contract errors documented on {@link DurableModuleOptions}. */\nfunction assertValidRole(options: DurableModuleOptions): void {\n const hasStore = options.store !== undefined;\n const hasConnection = options.connection !== undefined;\n if (!hasStore && !hasConnection) {\n throw new Error(\n 'a durable module needs either a `store` (operator) or a `connection` (worker)',\n );\n }\n if (hasStore && options.transport === undefined && options.transports === undefined) {\n throw new Error('an operator (`store`) needs a `transport` (or `transports`)');\n }\n}\n\nconst TOPOLOGIES: readonly DurableTopologyName[] = ['standalone', 'control-plane', 'tenant'];\n\n/**\n * Validates {@link DurableModuleOptions.topology}. `standalone` (or none) keeps the role inference\n * of {@link assertValidRole}; the two named roles check their own axes, and each message names the\n * option at fault and the axis it protects: `namespace` scopes an operator's poll loop, `partition`\n * is the queue suffix a worker serves.\n */\nfunction assertValidTopology(options: DurableModuleOptions): void {\n const topology: unknown = options.topology;\n if (topology === undefined || topology === 'standalone') {\n assertValidRole(options);\n return;\n }\n if (typeof topology !== 'string' || !TOPOLOGIES.includes(topology as DurableTopologyName)) {\n const hint =\n typeof topology === 'object' && topology !== null\n ? \"\\nThe object form is gone: `topology: { role: 'tenant', tenant: 'acme' }` is now \" +\n \"`topology: 'tenant', partition: 'acme'`.\"\n : '';\n throw new Error(\n `topology must be 'standalone', 'control-plane' or 'tenant' (got ${JSON.stringify(topology)}).${hint}`,\n );\n }\n\n if (topology === 'control-plane') {\n if (\n options.store === undefined ||\n (options.transport === undefined && options.transports === undefined)\n ) {\n throw new Error(\n \"topology: 'control-plane' needs `store` AND (`transport` or `transports`).\\n\" +\n 'A control-plane node is the durable operator: it owns the state store and dispatches ' +\n 'runs to workers over a transport. Without both, there is nothing for it to operate.',\n );\n }\n if ((options as { tenantToken?: unknown }).tenantToken !== undefined) {\n throw new Error(\n \"topology: 'control-plane' forbids `tenantToken`.\\n\" +\n 'A control plane verifies tenant tokens (`verifyTenant`); it does not present one. ' +\n \"`tenantToken` belongs on the `topology: 'tenant'` process.\",\n );\n }\n const { partition, namespace } = options;\n if (partition !== undefined && namespace !== undefined && namespace !== partition) {\n throw new Error(\n `topology: 'control-plane' with \\`partition: '${partition}'\\` conflicts with \\`namespace: '${namespace}'\\`.\\nOn a control plane, partition becomes its namespace (the runs it drives). Set only \\`partition\\`, or set \\`namespace\\` to the same value.`,\n );\n }\n return;\n }\n\n const partition: unknown = options.partition;\n if (typeof partition !== 'string' || partition.length === 0) {\n throw new Error(\n \"topology: 'tenant' needs `partition`.\\nIt names the tenant this process serves: its \" +\n 'consumers pull `<name>@<partition>` tasks and its requests act as that tenant.',\n );\n }\n if (options.connection === undefined) {\n throw new Error(\n `topology: 'tenant' (partition '${partition}') needs \\`connection\\`.\\nA tenant is a store-less worker: it connects to the broker directly to pull its own partition of tasks instead of polling a store it does not have.`,\n );\n }\n if (options.store !== undefined) {\n throw new Error(\n \"topology: 'tenant' forbids `store`.\\n\" +\n 'A tenant is store-less BY DEFINITION. A `store` present means you actually wanted ' +\n \"`topology: 'control-plane'` (the store-owning role).\",\n );\n }\n if ((options as { verifyTenant?: unknown }).verifyTenant !== undefined) {\n throw new Error(\n \"topology: 'tenant' forbids `verifyTenant`.\\n\" +\n 'A tenant presents a token (`tenantToken`); the control plane verifies it. ' +\n \"`verifyTenant` belongs on the `topology: 'control-plane'` process.\",\n );\n }\n if (options.namespace !== undefined) {\n throw new Error(\n \"topology: 'tenant' forbids `namespace`.\\n\" +\n \"namespace is the OPERATOR's poll-scoping axis (which runs a control-plane instance \" +\n 'drives/recovers/resumes); a tenant worker has no poll loop for it to scope. Use ' +\n '`partition` for the tenant this process serves.',\n );\n }\n}\n\n/**\n * Applies the topology's `partition` mapping and the serving-partition default. Validated already by\n * {@link assertValidTopology}.\n */\nfunction resolveTopology(options: DurableModuleOptions): DurableModuleOptions {\n return servingPartition(resolveTopologyPreset(options));\n}\n\n/**\n * Fill the WORKER-side `partition` from this node's own `namespace` when it wasn't declared. The two\n * are one axis on the wire: the engine dispatches a run's steps to `<name>@<run.namespace>` (core's\n * `stepGroup`), so a node that stamps its runs with a namespace must SERVE the matching token or it\n * enqueues into queues nobody consumes. This is what keeps the documented local-dev recipe\n * (`docs/namespaces.md`, a namespaced engine on a private Redis) working with no extra wiring.\n *\n * An explicit `partition` always wins, so a node deliberately serving a different pool stays put.\n */\nfunction servingPartition(options: DurableModuleOptions): DurableModuleOptions {\n if (options.partition !== undefined || options.namespace === undefined) return options;\n return { ...options, partition: options.namespace } as DurableModuleOptions;\n}\n\nfunction resolveTopologyPreset(options: DurableModuleOptions): DurableModuleOptions {\n if (options.topology !== 'control-plane' || options.partition === undefined) return options;\n // A control plane's partition is its namespace: the engine stamps its runs with it and routes their\n // steps to `<name>@<partition>` (core's `stepGroup`), so its own co-located consumers keep\n // `partition` and subscribe those same tokens. It stays a STORE-side axis and never re-scopes the\n // transport keyspace. An explicit equal `namespace` was validated by assertValidTopology.\n return { ...options, namespace: options.namespace ?? options.partition };\n}\n\n/** The `verifyTenant` / `tenantToken` options, resolved to the plain functions the wire layer calls. */\nexport interface ResolvedTenantAuth {\n verifyTenant: TenantVerifier | undefined;\n tenantToken: TenantTokenSource | undefined;\n}\n\n/**\n * Boot-time wiring for the tenant run gateway's OPERATOR side, gated by {@link isDrivingOperator} (an\n * operator instance drives by default; `drive: false` — or a thin worker with no `store` at all —\n * does not). Two independent capabilities, each wired only when the transport carries it:\n *\n * 1. **`RunRequestResponder`** — answers a tenant's {@link RunRequest} against the bound\n * {@link RunGateway}, tenant-scoped. Wired when the transport implements both\n * `onRunRequest`/`publishRunReply` (only broker transports carry the protocol).\n * 2. **Tenant-event re-publisher** ({@link TenantEventRepublisher}) — mirrors every engine\n * lifecycle event onto its run's per-tenant channel via `publishTenantEvent`, so a store-less\n * tenant worker can live-tail its OWN runs. See that class for the namespace-resolution and\n * cache-eviction details.\n */\n@Injectable()\nclass RunGatewayBootstrap implements OnApplicationBootstrap, OnModuleDestroy {\n private unsubscribe?: () => void;\n\n constructor(\n private readonly engine: WorkflowEngine,\n @Inject(TRANSPORT_CANONICAL) private readonly transport: Transport | null,\n private readonly gateway: RunGateway,\n @Inject(STATE_STORE_CANONICAL) private readonly store: StateStore | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n @Inject(TENANT_AUTH) private readonly auth: ResolvedTenantAuth,\n ) {}\n\n onApplicationBootstrap(): void {\n if (!isDrivingOperator(this.options) || !this.transport) return;\n const store = this.store;\n if (!store) return; // unreachable when isDrivingOperator is true — keeps types honest\n\n const { onRunRequest, publishRunReply, publishTenantEvent } = this.transport;\n if (typeof onRunRequest === 'function' && typeof publishRunReply === 'function') {\n // Bind to the transport: these are real methods that touch the transport's private fields\n // (e.g. BullMQTransport's `this.#runRequestName()`), so they must keep their receiver — passing\n // them destructured/unbound makes `this` the literal below and throws \"Receiver must be an\n // instance of class\" on first use. (Mirrors the `publishTenantEvent.bind` just below.)\n const runRequestTransport: RunRequestTransport = {\n onRunRequest: onRunRequest.bind(this.transport),\n publishRunReply: publishRunReply.bind(this.transport),\n };\n new RunRequestResponder(runRequestTransport, this.gateway, {\n verifyTenant: this.auth.verifyTenant,\n // Mirrors Agora's rule (`warnWithoutVerifier: topology === 'control-plane'`): only a deployment\n // that EXPLICITLY names itself the control plane is told it runs without tenant auth. On a\n // `standalone` operator (role inferred from `store`) anyone with broker access\n // can already enqueue steps and results there, so the warning would be noise on every boot\n // of an app that never serves tenants.\n warnWithoutVerifier: this.options.topology === 'control-plane',\n }).start();\n }\n\n if (typeof publishTenantEvent === 'function') {\n const republisher = new TenantEventRepublisher(\n store,\n publishTenantEvent.bind(this.transport),\n );\n this.unsubscribe = this.engine.subscribe((event) => {\n // Tenant event mirroring is best-effort; a namespace lookup outage must not kill the worker.\n void republisher.handle(event).catch(() => undefined);\n });\n }\n }\n\n onModuleDestroy(): void {\n this.unsubscribe?.();\n }\n}\n\n/**\n * Restores the tenant a dispatched step task carries around its handler, in whichever process and on\n * whichever transport runs it (an operator's in-process consumer or a thin worker). Registered only\n * when durable's tenancy is on at boot, so an app without tenancy keeps an empty execution-hook\n * registry (zero cost).\n */\n@Injectable()\nclass DurableTenancyBridge implements OnApplicationBootstrap, OnModuleDestroy {\n private unregister?: () => void;\n\n constructor(\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n private readonly moduleRef: ModuleRef,\n ) {}\n\n async onApplicationBootstrap(): Promise<void> {\n if (this.options.tenancy === false) return;\n const accessor = resolveAccessor(this.moduleRef);\n if (!readTenancy(this.options.tenancy, accessor).enabled) return;\n const runtime = await resolveContextRuntime();\n if (!canRestoreTenant(runtime)) return;\n this.unregister = useDurableExecution(\n stepTenantWrapper(\n this.options.tenancy,\n accessor,\n isTenantRuntime(runtime) ? runtime : undefined,\n ),\n );\n }\n\n onModuleDestroy(): void {\n this.unregister?.();\n }\n}\n\n/**\n * `forRoot` / `forRootAsync` first refuse to boot when two different installs of\n * `@dudousxd/nestjs-durable-core` are loaded in this process (a pnpm peer-variant split): each copy\n * has its own `WorkflowEngine` class, so code from one copy cannot resolve the engine the other copy\n * registered. They throw `DuplicateDurableCopyError` naming both installs, and a distinct copy that\n * loads afterwards throws on load.\n */\n@Module({})\nexport class DurableModule {\n static forRoot(options: DurableModuleOptions): DynamicModule {\n sealDurableCopies();\n DurableModule.assertValid(options);\n return DurableModule.build({\n provide: DURABLE_OPTIONS_CANONICAL,\n useValue: resolveTopology(options),\n });\n }\n\n static forRootAsync(options: DurableModuleAsyncOptions): DynamicModule {\n sealDurableCopies();\n return DurableModule.build({\n provide: DURABLE_OPTIONS_CANONICAL,\n useFactory: async (...args: Parameters<DurableModuleAsyncOptions['useFactory']>) => {\n const resolved = await options.useFactory(...args);\n DurableModule.assertValid(resolved);\n return resolveTopology(resolved);\n },\n inject: options.inject ?? [],\n });\n }\n\n /** Validates the topology and its role/axis constraints; see {@link assertValidTopology}. */\n private static assertValid(options: DurableModuleOptions): void {\n assertValidTopology(options);\n }\n\n private static build(optionsProvider: Provider): DynamicModule {\n return {\n module: DurableModule,\n global: true,\n imports: [DiscoveryModule],\n providers: [\n optionsProvider,\n {\n provide: STATE_STORE_CANONICAL,\n useFactory: (options: DurableModuleOptions): StateStore | null =>\n options.store !== undefined ? scopedStore(options.store, options) : null,\n inject: [DURABLE_OPTIONS_CANONICAL],\n },\n {\n provide: TRANSPORT_CANONICAL,\n // With a POOL (`transports`) and no singular `transport`, the canonical transport is the\n // pool's PRIMARY — the same one the engine dispatches on first. Leaving it null starved\n // the step registrar / in-app worker of a transport, so a pool-configured operator\n // registered NO step handlers and its own steps parked in `wait` with no consumer.\n useFactory: (options: DurableModuleOptions) =>\n options.transport ?? options.transports?.[0]?.transport ?? null,\n inject: [DURABLE_OPTIONS_CANONICAL],\n },\n {\n provide: TENANT_AUTH,\n useFactory: (\n options: DurableModuleOptions,\n moduleRef: ModuleRef,\n ): ResolvedTenantAuth => ({\n verifyTenant: resolveTenantVerifier(options.verifyTenant, moduleRef),\n tenantToken: resolveTenantTokenSource(options.tenantToken, moduleRef),\n }),\n inject: [DURABLE_OPTIONS_CANONICAL, ModuleRef],\n },\n // Deprecated tokens that published releases still import resolve to the same instances:\n { provide: STATE_STORE, useExisting: STATE_STORE_CANONICAL },\n { provide: TRANSPORT, useExisting: TRANSPORT_CANONICAL },\n { provide: DURABLE_OPTIONS, useExisting: DURABLE_OPTIONS_CANONICAL },\n {\n // Shared token, bound EXACTLY once: a real engine for the operator role, or a store-less\n // `DurableStartClient` facade for a thin worker (no `store`) — either way, `WorkflowService`\n // and app code call `engine.start(...)` unchanged.\n provide: WorkflowEngine,\n useFactory: async (\n options: DurableModuleOptions,\n store: StateStore | null,\n transport: Transport | null,\n // The accessor from `@dudousxd/nestjs-context` is resolved at construction via ModuleRef\n // (shared CONTEXT_ACCESSOR symbol — no hard import). Absent → unchanged behavior.\n moduleRef: ModuleRef,\n auth: ResolvedTenantAuth,\n ) => {\n if (options.store === undefined) {\n return new DurableStartClient(\n {\n ...options,\n ...(auth.tenantToken !== undefined ? { tenantToken: auth.tenantToken } : {}),\n } as DurableModuleOptions,\n undefined,\n resolveAccessor(moduleRef),\n );\n }\n if (!store) {\n throw new Error(\n 'unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set',\n );\n }\n // The control-plane default is the primary task transport (single, or the pool's first)\n // when it can broadcast.\n const primary = transport ?? options.transports?.[0]?.transport;\n // Auto-feed the carrier from nestjs-context when an accessor is present AND the app didn't\n // pass its own `context` reader. The app's own reader always wins; with no accessor the\n // carrier stays `undefined` (unchanged behavior — `traceparent` etc. still work).\n const accessor = resolveAccessor(moduleRef);\n const context =\n options.context ?? (accessor ? () => carrierFromAccessor(accessor) : undefined);\n const runtimeNeeded = accessor !== undefined || contextSlotPresent();\n // Consume side: when nestjs-context is present (an accessor is bound), re-hydrate the\n // originating context AROUND each local step body, so a `@Step` reader sees the\n // tenant/user/trace ids ambiently via nestjs-context's ALS — no consumer wrapping needed.\n // The runtime `Context` is a module-level singleton (not the accessor token), resolved\n // ONCE here via a guarded dynamic import (optional peer — failure leaves the default\n // passthrough). Best-effort: an empty/undefined carrier just runs the handler normally.\n // The engine re-applies the run row's tenant INSIDE this bridge, so an app deserializer\n // that drops the tenant cannot take it away from a local step.\n const runtime = runtimeNeeded ? await resolveContextRuntime() : undefined;\n const rehydrate =\n runtime &&\n (<T>(carrier: Record<string, unknown> | undefined, fn: () => T): T =>\n carrier && Object.keys(carrier).length > 0\n ? runtime.deserialize(carrier, fn)\n : fn());\n // `consumers: false`: park every transport's point-to-point consumers BEFORE the engine\n // subscribes to them (its constructor registers the results/decisions consumers).\n if (options.consumers === false) {\n for (const t of [transport, ...(options.transports ?? []).map((n) => n.transport)]) {\n if (t) deferTransportConsumers(t);\n }\n }\n const engine = new WorkflowEngine({\n store,\n transport: transport ?? undefined,\n transports: options.transports,\n controlPlane: options.controlPlane ?? (isControlPlane(primary) ? primary : undefined),\n leaseMs: options.leaseMs,\n admission: options.admission,\n maxRecoveryAttempts: options.maxRecoveryAttempts,\n unregisteredWorkflowGraceMs: options.unregisteredWorkflowGraceMs,\n remoteAdvanceSilenceMs: options.remoteAdvanceSilenceMs,\n remoteRedispatchMs: options.remoteRedispatchMs,\n remoteRedispatchMax: options.remoteRedispatchMax,\n reconcileMs: options.reconcileMs,\n stalledAfterMs: options.stalledAfterMs,\n timerBatchSize: options.timerBatchSize,\n eventBufferTtlMs: options.eventBufferTtlMs,\n signalIdTtl: options.signalIdTtl,\n blockedPollMs: options.blockedPollMs,\n workerDescriptorCacheMs: options.workerDescriptorCacheMs,\n trackStepStart: options.trackStepStart,\n stickyRuns: options.stickyRuns,\n stickyIdleMs: options.stickyIdleMs,\n routeReplies: options.routeReplies,\n instanceId: options.instanceId,\n namespace: options.namespace,\n webhookUrl: options.webhookUrl,\n traceparent: options.traceparent,\n context,\n rehydrate: (accessor && rehydrate) || undefined,\n // The run's tenant, restored around every turn (see `tenancy` above).\n tenancy: buildEngineTenancy(\n options.tenancy,\n accessor,\n isTenantRuntime(runtime) ? runtime : undefined,\n ),\n compensationRetries: options.compensationRetries,\n verifyTenant: auth.verifyTenant,\n // A non-driving (dashboard/API) operator must not run workflows: enqueue-only, leaving\n // each `pending` run in the store for a DRIVING instance's poll. A driving operator gets\n // the engine's default in-process dispatcher: for a body registered inline, it runs\n // locally; for one registered GROUP-SERVED (co-located worker) or left unregistered, the\n // SAME default dispatcher routes it out remotely (group-served executor, or convention\n // dispatch — always on) instead.\n runDispatcher: options.drive === false ? { dispatch: () => {} } : undefined,\n });\n for (const queue of options.queues ?? []) engine.registerQueue(queue);\n if (options.onStalled) engine.onStalled(options.onStalled);\n // Dead-letter routing (per-workflow `@DeadLetter()` / `deadLetterWorkflow` + this global\n // default) is wired by the WorkflowRegistrar, which owns the `@Workflow` metadata.\n return engine;\n },\n inject: [\n DURABLE_OPTIONS_CANONICAL,\n STATE_STORE_CANONICAL,\n TRANSPORT_CANONICAL,\n ModuleRef,\n TENANT_AUTH,\n ],\n },\n WorkflowService,\n EntityService,\n WorkflowRegistrar,\n DurableStepRegistrar,\n SweepLeases,\n TimerPoller,\n RetentionPoller,\n // Tenant run gateway: bound EXACTLY once — the store-backed `StoreRunGateway` for an operator,\n // or (for a thin worker, no `store`) a `ProxyRunGateway` over `transport` when given, else a\n // gateway whose every method rejects with a clear tenant error.\n {\n provide: RunGateway,\n useFactory: (\n options: DurableModuleOptions,\n store: StateStore | null,\n engine: WorkflowEngine,\n auth: ResolvedTenantAuth,\n moduleRef: ModuleRef,\n ): RunGateway => {\n if (options.store !== undefined) {\n if (!store) {\n throw new Error(\n 'unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set',\n );\n }\n return new StoreRunGateway(store, engine);\n }\n return options.transport\n ? new ProxyRunGateway(\n options.transport,\n options.partition ?? 'default',\n options.runGatewayTimeoutMs,\n undefined,\n auth.tenantToken,\n options.tenancy === false\n ? undefined\n : () => tenantFilterNow(options.tenancy, resolveAccessor(moduleRef)),\n )\n : unavailableRunGateway();\n },\n inject: [\n DURABLE_OPTIONS_CANONICAL,\n STATE_STORE_CANONICAL,\n WorkflowEngine,\n TENANT_AUTH,\n ModuleRef,\n ],\n },\n RunGatewayBootstrap,\n DurableTenancyBridge,\n // Co-located in-app worker (uniform dispatch): inert unless BOTH `store` and `connection` are\n // set — see `in-app-worker.ts`.\n ...inAppWorkerProviders(),\n // Pure thin-worker consumer: inert unless `connection` is set WITHOUT `store` — see\n // `durable-worker.module.ts`.\n ...thinWorkerProviders(),\n ],\n exports: [\n WorkflowService,\n EntityService,\n WorkflowEngine,\n STATE_STORE,\n STATE_STORE_CANONICAL,\n TRANSPORT,\n TRANSPORT_CANONICAL,\n DURABLE_OPTIONS_CANONICAL,\n RunGateway,\n ],\n };\n }\n}\n","import {\n DURABLE_OPTIONS_CANONICAL,\n type StepLogger,\n TRANSPORT_CANONICAL,\n type Transport,\n} from '@dudousxd/nestjs-durable-core';\nimport { Inject, Injectable, type OnModuleInit } from '@nestjs/common';\nimport { DiscoveryService, MetadataScanner } from '@nestjs/core';\nimport { scanSteps } from './discovery-helpers';\nimport type { DurableModuleOptions } from './durable.module';\nimport { isDrivingOperator } from './role';\n\n/** A transport that can run step handlers in-process (e.g. the event-emitter transport). */\ninterface LocalTaskHandling {\n handle(\n name: string,\n fn: (input: unknown, log: StepLogger) => Promise<unknown> | unknown,\n /** Isolation partition to SERVE — the queue token is `tenantGroup(sanitizeQueueToken(name),\n * partition)`. Omitted (or undefined) keeps the transport's own constructor partition. */\n partition?: string | undefined,\n ): void;\n}\n\nfunction supportsHandle(transport: unknown): transport is LocalTaskHandling {\n return typeof (transport as LocalTaskHandling | null)?.handle === 'function';\n}\n\n/**\n * Discovers `@Step` methods and registers them — under their RESOLVED name (derived `Class.method`\n * for a bare `@Step()`, or the explicit override) — as step handlers on the configured transport,\n * when that transport runs handlers in-process. With a queue/remote transport the handlers live in\n * the worker process instead, so there is nothing to wire here.\n *\n * **Context re-hydration (consume side) is the consumer's responsibility.** DurableModule's\n * produce side auto-feeds an opaque carrier (`{ traceId, tenantId, userRef }`) from\n * `@dudousxd/nestjs-context` onto each dispatched `RemoteTask.context` (see DurableModule). A worker\n * that wants its `@Step` reads to SEE the originating context must re-establish it from\n * `task.context`. We do NOT do this here because: (a) re-hydration needs nestjs-context's module-level\n * `Context.deserialize(carrier, fn)` at runtime, and it is an OPTIONAL peer we must not hard-import;\n * and (b) the in-process `StepHandler` contract is `(input, log)` — the engine never surfaces\n * `task.context` to the handler closure, so wrapping it here would require widening the core\n * transport/handler signature (a non-additive cross-cutting change). Instead, a worker that consumes\n * the carrier should wrap its handler with `Context.deserialize(task.context, () => handler(...))`\n * from its own transport/worker bootstrap, where `task` is in scope.\n */\n@Injectable()\nexport class DurableStepRegistrar implements OnModuleInit {\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly metadataScanner: MetadataScanner,\n @Inject(TRANSPORT_CANONICAL) private readonly transport: Transport | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n ) {}\n\n onModuleInit(): void {\n // A non-driving operator (`drive: false`) or a thin worker (no `store`) must not consume the\n // queue — receiving and running step tasks locally is exactly the driving-operator role we're\n // switching off here (a thin worker registers its steps via `ThinStepRegistrar` instead).\n if (!isDrivingOperator(this.options)) return;\n if (!supportsHandle(this.transport)) return;\n const transport = this.transport;\n\n // Forward the step logger as a second arg; methods that only declare `(input)` ignore it.\n // The partition is the node's own tenant axis (`topology: 'control-plane'` with a `partition`\n // resolves it, see `resolveTopology`): this engine DISPATCHES a tenant run's steps to\n // `<name>@<tenant>`, so its in-process handlers must SERVE that same token. Undefined on a global\n // operator — the bare token, byte-identical to before.\n scanSteps(this.discovery, this.metadataScanner, (meta, handler) =>\n transport.handle(meta.name, handler, this.options.partition),\n );\n }\n}\n","import type { DurableModuleOptions } from './durable.module';\n\n/**\n * True for the **operator** role — `store` is set (with or without a co-located `connection`). See\n * {@link DurableModuleOptions} for the full role matrix. Kept in its own module (rather than\n * `durable.module.ts`) so the poller/registrar classes can import it as a plain VALUE without a\n * circular value dependency on the module that also imports them as providers.\n */\nexport function isOperatorRole(options: DurableModuleOptions): boolean {\n return options.store !== undefined;\n}\n\n/**\n * True when an operator instance actively DRIVES runs — polls pending, recovers crashed, resumes due\n * timers, sweeps timeouts, prunes retention, consumes local steps — as opposed to a read-only/\n * dashboard replica (`drive: false`) that mounts the store/dashboard but leaves driving to another\n * instance. Meaningless (`false`) outside the operator role. Defaults to `true` for an operator.\n */\nexport function isDrivingOperator(options: DurableModuleOptions): boolean {\n return isOperatorRole(options) && options.drive !== false;\n}\n","import { type EntityHandler, WorkflowEngine } from '@dudousxd/nestjs-durable-core';\nimport { Injectable } from '@nestjs/common';\nimport 'reflect-metadata';\n\nexport const ENTITY_METADATA = Symbol('nestjs-durable:entity');\nexport const ENTITY_ON_METADATA = Symbol('nestjs-durable:entity-on');\n\n/**\n * Marks an `@Injectable()` class as a **durable entity** (a virtual object): its `@On(op)` methods run\n * serialized per key over the instance's fields as durable state. e.g.\n *\n * ```ts\n * @Entity({ name: 'cart' }) @Injectable()\n * class Cart { items: Item[] = []; @On('add') add(i: Item) { this.items.push(i); } @On('list') list() { return this.items; } }\n * ```\n *\n * The class must be **constructible with no arguments** (a fresh instance is the initial state per key)\n * — keep entities pure state, no DI. Drive them with `EntityService` or `ctx.signalEntity`/`callEntity`.\n */\nexport function Entity(options: { name: string }): ClassDecorator {\n return (target) => {\n Reflect.defineMetadata(ENTITY_METADATA, options, target);\n };\n}\n\n/** Marks an entity method as the handler for operation `op`. */\nexport function On(op: string): MethodDecorator {\n return (target, propertyKey) => {\n // biome-ignore lint/complexity/noBannedTypes: reflect-metadata keys on the class constructor\n const ctor = (target as { constructor: Function }).constructor;\n const ops = (Reflect.getMetadata(ENTITY_ON_METADATA, ctor) as Map<string, string>) ?? new Map();\n ops.set(op, propertyKey as string);\n Reflect.defineMetadata(ENTITY_ON_METADATA, ops, ctor);\n };\n}\n\n// biome-ignore lint/complexity/noBannedTypes: matches reflect-metadata's class target type\nexport function getEntityMeta(target: Function): { name: string } | undefined {\n return Reflect.getMetadata(ENTITY_METADATA, target) as { name: string } | undefined;\n}\n\n/**\n * Build the engine `EntityConfig` for a discovered `@Entity` class: a fresh instance per key, and\n * handlers that rehydrate the class prototype onto the (serialized) state before dispatching the op,\n * so methods work after replay.\n */\n// biome-ignore lint/complexity/noBannedTypes: a class constructor\nexport function entityConfigFor(ctor: Function): {\n initialState: () => object;\n handlers: Record<string, EntityHandler>;\n} {\n const ops = (Reflect.getMetadata(ENTITY_ON_METADATA, ctor) as Map<string, string>) ?? new Map();\n const Cls = ctor as new () => Record<string, (arg: unknown) => unknown>;\n const handlers: Record<string, EntityHandler> = {};\n for (const [op, method] of ops) {\n handlers[op] = (state, arg) => {\n Object.setPrototypeOf(state as object, Cls.prototype); // re-attach methods to the plain state\n const fn = (state as Record<string, ((a: unknown) => unknown) | undefined>)[method];\n if (typeof fn !== 'function') throw new Error(`entity handler \"${method}\" is not a method`);\n return fn.call(state, arg);\n };\n }\n return { initialState: () => new Cls(), handlers };\n}\n\n/** Inject this to drive durable entities from outside a workflow. */\n@Injectable()\nexport class EntityService {\n constructor(private readonly engine: WorkflowEngine) {}\n\n /** Send an operation to an entity (fire-and-forget; ordered + exactly-once per key). */\n signal(name: string, key: string, op: string, arg?: unknown): Promise<void> {\n return this.engine.signalEntity(name, key, op, arg);\n }\n\n /** Read an entity's current durable state (or undefined if it has none yet). */\n getState<S = unknown>(name: string, key: string): Promise<S | undefined> {\n return this.engine.getEntityState<S>(name, key);\n }\n}\n","import type { DurableWorkerRuntime, RunningWorker } from '@dudousxd/durable-worker';\nimport {\n DURABLE_OPTIONS_CANONICAL,\n TRANSPORT_CANONICAL,\n type Transport,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n Inject,\n Injectable,\n type OnApplicationBootstrap,\n type OnApplicationShutdown,\n type OnModuleInit,\n type Provider,\n} from '@nestjs/common';\nimport { DiscoveryService, MetadataScanner } from '@nestjs/core';\nimport { scanSteps, scanWorkflows } from './discovery-helpers';\nimport type { RunRedisWorkerFn } from './durable-worker.module';\nimport type { DurableModuleOptions } from './durable.module';\nimport { registerOnRuntime } from './runtime-registration';\nimport { createWorkerRuntime, runRedisWorker as defaultRunRedisWorker } from './worker-sdk';\n\n/**\n * The **co-located in-app worker** (uniform dispatch): active whenever an app supplies BOTH `store`\n * AND `connection` (`DurableModule.forRoot({ store, transport, connection, partition? })`) — the same\n * process runs the engine AND serves its own discovered `@Workflow`/`@Step`. The engine registers each\n * `@Workflow` GROUP-SERVED — its turns are dispatched, PER WORKFLOW NAME, to\n * `tenantGroup(sanitizeQueueToken(name), partition)` over the transport via a per-workflow\n * `RemoteWorkflowExecutor` instead of run inline — and a co-located {@link DurableWorkerRuntime}\n * subscribes one queue per discovered name (via `runRedisWorker`) and replays the very same TS bodies.\n * This is the uniform-dispatch \"one app, both roles\" shape — every turn pays a transport round-trip\n * even though the worker is the same process. Requires a transport that carries workflow tasks\n * (BullMQ); an in-process-only transport cannot dispatch a `WorkflowExecutor`.\n *\n * Distinct from the PURE thin-worker role (`connection` set, `store` unset — see\n * `durable-worker.module.ts`'s `ThinWorkflowRegistrar`/`ThinStepRegistrar`/`ThinWorkerBootstrap`),\n * which has no engine/store of its own at all.\n */\nexport const IN_APP_WORKER_BINDING = Symbol('nestjs-durable:in-app-worker-binding');\n\n/** The co-located worker's {@link DurableWorkerRuntime} (the consumer half). */\nexport const IN_APP_WORKER_RUNTIME = Symbol('nestjs-durable:in-app-worker-runtime');\n\n/** `runRedisWorker`, injected so tests can substitute a fake (no real Redis). Defaults to the real one. */\nexport const IN_APP_RUN_REDIS_WORKER = Symbol('nestjs-durable:in-app-run-redis-worker');\n\n/** Started {@link RunningWorker} handles for the in-app worker, closed on shutdown. */\nexport const IN_APP_WORKER_RUNNERS = Symbol('nestjs-durable:in-app-worker-runners');\n\n/** The group-served binding shape resolved behind {@link IN_APP_WORKER_BINDING}. */\nexport interface InAppWorkerBinding {\n transport: Transport;\n partition?: string;\n}\n\n/** True for the **co-located** role — both `store` AND `connection` set. */\nfunction isCoLocatedWorker(options: DurableModuleOptions): boolean {\n return options.store !== undefined && options.connection !== undefined;\n}\n\n/**\n * Builds the {@link IN_APP_WORKER_BINDING}: when this app is co-located (`store` + `connection`), the\n * engine's transport plus the configured partition — the registrar builds a PER-WORKFLOW\n * `RemoteWorkflowExecutor` from these, one per discovered name; otherwise `null` (inline default).\n * Fails fast if co-located but the transport can't carry workflow tasks — a group-served run would\n * otherwise dead-end at dispatch.\n */\nfunction inAppWorkerBinding(\n transport: Transport | null,\n options: DurableModuleOptions,\n): InAppWorkerBinding | null {\n if (!isCoLocatedWorker(options)) return null;\n if (!transport?.dispatchWorkflowTask || !transport.onDecision) {\n throw new Error(\n 'a co-located worker (store + connection) requires a transport that carries workflow tasks (dispatchWorkflowTask + onDecision), e.g. BullMQTransport. An in-process transport cannot serve a group-served workflow.',\n );\n }\n return {\n transport,\n ...(options.partition !== undefined ? { partition: options.partition } : {}),\n };\n}\n\n/**\n * The consumer half of the in-app worker: on init it registers every discovered `@Workflow`/`@Step`\n * on a {@link DurableWorkerRuntime} (the SAME bodies the engine registered group-served), and on\n * bootstrap it starts one `runRedisWorker` call that subscribes one queue per discovered name,\n * suffixed by the configured partition, closing it on shutdown. A no-op outside the co-located role\n * (see {@link isCoLocatedWorker}). Mirrors the thin {@link\n * import('./durable-worker.module').ThinWorkerBootstrap}, but co-located with a full engine.\n */\n@Injectable()\nexport class InAppWorkerBootstrap\n implements OnModuleInit, OnApplicationBootstrap, OnApplicationShutdown\n{\n private readonly runners: RunningWorker[] = [];\n\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly metadataScanner: MetadataScanner,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n @Inject(IN_APP_WORKER_RUNTIME) private readonly runtime: DurableWorkerRuntime | null,\n @Inject(IN_APP_RUN_REDIS_WORKER) private readonly runRedisWorker: RunRedisWorkerFn,\n @Inject(IN_APP_WORKER_RUNNERS) private readonly runnersSink: RunningWorker[],\n ) {}\n\n onModuleInit(): void {\n const runtime = this.runtime;\n if (runtime === null || !isCoLocatedWorker(this.options)) return;\n // Register the same TS bodies the engine serves group-served, so the consumer can replay them.\n // The metadata rides along as this worker's ANNOUNCEMENT of what it can execute (design §7.9):\n // co-located or not, the process that CONSUMES the queue is the one entitled to announce the\n // workflow, and here that is this runtime — not the engine sharing its process.\n scanWorkflows(this.discovery, (meta, instance, origin) =>\n registerOnRuntime(runtime, this.metadataScanner, meta, instance, origin),\n );\n scanSteps(this.discovery, this.metadataScanner, (meta, handler) =>\n runtime.registerStep(meta.name, handler),\n );\n }\n\n async onApplicationBootstrap(): Promise<void> {\n const options = this.options;\n const runtime = this.runtime;\n if (runtime === null || !isCoLocatedWorker(options) || options.connection === undefined) return;\n // `consumers: false`: a producer-only process (CLI, REPL, script) starts no consumer.\n if (options.consumers === false) return;\n const handle = await this.runRedisWorker({\n runtime,\n connection: options.connection,\n ...(options.partition !== undefined ? { partition: options.partition } : {}),\n ...(options.prefix !== undefined ? { prefix: options.prefix } : {}),\n ...(options.instanceId !== undefined ? { instanceId: options.instanceId } : {}),\n ...(options.concurrency !== undefined ? { concurrency: options.concurrency } : {}),\n });\n this.runners.push(handle);\n this.runnersSink.push(handle);\n }\n\n async onApplicationShutdown(): Promise<void> {\n await Promise.allSettled(this.runners.map((handle) => handle.close()));\n }\n}\n\n/**\n * The providers that stand up the co-located in-app worker, added to {@link\n * import('./durable.module').DurableModule}'s unified provider set. All are inert outside the\n * co-located role (`store` + `connection` both set — see {@link isCoLocatedWorker}), so a plain\n * operator (`store` only) or pure thin worker (`connection` only) is unaffected.\n */\nexport function inAppWorkerProviders(): Provider[] {\n return [\n {\n provide: IN_APP_WORKER_BINDING,\n useFactory: (transport: Transport | null, options: DurableModuleOptions) =>\n inAppWorkerBinding(transport, options),\n inject: [TRANSPORT_CANONICAL, DURABLE_OPTIONS_CANONICAL],\n },\n {\n provide: IN_APP_WORKER_RUNTIME,\n // The runtime's `WorkflowWorker` uses its `group` ctor param as the WORKFLOW's\n // `workflowPartition` for any `ctx.step` call (see `workflow-context.ts`'s `resolveCallGroup`)\n // — that fallback MUST equal this app's own `partition`, or a dispatched step's decision\n // carries a mismatched token and the engine dispatches it to a queue nothing here subscribes\n // to. Explicit `''` (never\n // `undefined`) so it does NOT fall through to `WorkflowWorker`'s unrelated `'workflows'`\n // default parameter.\n //\n // The role gate lives HERE, not just in the consumer: constructing the runtime resolves the\n // optional `@dudousxd/durable-worker` peer, so an operator that never runs a worker must not\n // reach this branch at all.\n useFactory: (options: DurableModuleOptions) =>\n isCoLocatedWorker(options)\n ? createWorkerRuntime({ workflowGroup: options.partition ?? '' })\n : null,\n inject: [DURABLE_OPTIONS_CANONICAL],\n },\n { provide: IN_APP_RUN_REDIS_WORKER, useValue: defaultRunRedisWorker },\n { provide: IN_APP_WORKER_RUNNERS, useValue: [] as RunningWorker[] },\n InAppWorkerBootstrap,\n ];\n}\n","import type {\n DurableTopology,\n EngineEvent,\n FanPage,\n FanPageQuery,\n GroupHealth,\n RepublishLifecycleResult,\n RepublishLifecycleTarget,\n RunDetail,\n RunDetailOptions,\n RunFacetQuery,\n RunFacetRow,\n RunGateway,\n RunListItem,\n RunQuery,\n RunReply,\n RunRequestKind,\n RunResult,\n RunValueAxis,\n RunValueFacetOptions,\n RunValueFacetRow,\n RunWaiting,\n TenantTokenSource,\n Transport,\n WorkflowLifecycleLinks,\n WorkflowRun,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n SUMMARY_CHILD_LIMIT,\n type TenantFilter,\n childIdsOf,\n pageFan,\n resolveTenantToken,\n scopeTenantQuery,\n summarizeTimeline,\n tenantVisible,\n} from '@dudousxd/nestjs-durable-core';\nimport { Injectable } from '@nestjs/common';\nimport { BAD_RUN_REQUEST, UNSUPPORTED_RUN_REQUEST } from './run-request-responder';\n\n/**\n * Method-shorthand signatures (not arrow-function-typed properties) are deliberate: TypeScript\n * checks method parameters bivariantly, so a `Promise<T>`'s own `resolve`/`reject` (typed for that\n * call's concrete `T`) can be stored here erased to `unknown` with no cast — the one place the\n * generic `T` from {@link ProxyRunGateway.request} crosses into the untyped bookkeeping map.\n */\ninterface PendingRequest {\n resolve(data: unknown): void;\n reject(err: Error): void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * An error reply from the control plane. `code` carries the reply's machine-readable reason when it\n * sent one — `unauthorized` (the tenant token was rejected), `cross-tenant` (the run belongs to\n * another tenant), `bad-request` (the request was malformed or not allowed), ... — so a caller can tell an authentication failure from a real one, as with\n * Agora's proxy.\n */\n/**\n * The codes the run-request responder replies with. `string & {}` keeps a code from a newer control\n * plane assignable without losing autocomplete on the known ones.\n */\nexport type RunGatewayErrorCode =\n | 'unauthorized'\n | 'cross-tenant'\n | typeof BAD_RUN_REQUEST\n | typeof UNSUPPORTED_RUN_REQUEST\n | (string & {});\n\nexport class RunGatewayError extends Error {\n readonly code: RunGatewayErrorCode | undefined;\n constructor(message: string, code?: RunGatewayErrorCode) {\n super(message);\n this.name = 'RunGatewayError';\n this.code = code;\n }\n}\n\n/** The control plane answered a verb it does not know — an older release than this tenant's. */\nclass UnsupportedRunRequestError extends RunGatewayError {}\n\n/** An {@link UNSUPPORTED_RUN_REQUEST} error reply. Older responders answer an unknown verb with\n * `ok: true` and no `data` instead, which `getFanMembers` checks for itself. */\nfunction isUnsupported(err: unknown): boolean {\n return err instanceof UnsupportedRunRequestError;\n}\n\n/**\n * Tenant-side `RunGateway` — round-trips every verb as a `RunRequest`/`RunReply` pair over the\n * transport, correlated by a minted `requestId`, and bridges `subscribe` onto the transport's\n * per-tenant event stream. Bound under `RunGateway` by `DurableModule`'s thin-worker role\n * (`connection` set, no `store`) when the app supplies a `transport` (see `unavailableRunGateway`\n * for the no-transport fallback). The counterpart to the operator-side `StoreRunGateway`: a tenant\n * worker never touches a store/driver directly, only this proxy.\n */\n@Injectable()\nexport class ProxyRunGateway implements RunGateway {\n private readonly pending = new Map<string, PendingRequest>();\n /** Verb → when to ask the control plane for it again, after it answered that it does not know it.\n * During a rolling upgrade the control plane is several pods of mixed versions behind one queue,\n * and a reply does not say which pod sent it, so the whole control plane is assumed old until the\n * entry expires. */\n private readonly unsupportedUntil = new Map<RunRequestKind['kind'], number>();\n\n constructor(\n private readonly transport: Transport,\n private readonly tenant: string,\n private readonly timeoutMs = 10_000,\n private readonly capabilityTtlMs = 60_000,\n /**\n * The tenant's signed token (see `signTenantToken`), presented VERBATIM in the `tenant` field of\n * every {@link RunRequest} so an operator with `verifyTenant` can authenticate it and derive the\n * tenant from it. A function is called before every request (rotation / short-lived tokens).\n * Omit to send the raw `tenant` (prefix/network isolation only). The live-tail channel always\n * stays keyed by `tenant`, never the token: the operator republishes by the run's namespace.\n */\n private readonly tenantToken?: TenantTokenSource,\n /**\n * The customer-tenancy filter of the request being served (durable's `tenancy` on this process).\n * The control plane answers for this process's namespace; this narrows it to the request's\n * customer tenant: lists and counts get the tenant predicate, and a run of another tenant reads\n * (and is controlled) as missing. Absent: no narrowing.\n */\n private readonly tenantFilter?: () => TenantFilter,\n ) {\n this.transport.onRunReply?.((reply: RunReply) => this.handleReply(reply));\n }\n\n /** The request's tenant filter when it can hide runs (`tenant` / `tenantless`), else undefined. */\n private restrictive(): TenantFilter | undefined {\n const filter = this.tenantFilter?.();\n return filter && filter.mode !== 'system' && filter.mode !== 'all' ? filter : undefined;\n }\n\n /**\n * Send `query`, narrowed to the runs the request may see. A tenant-required request with no\n * tenant rejects (never throws synchronously).\n */\n private scoped<Q extends RunQuery | RunFacetQuery, T>(\n query: Q,\n send: (q: Q) => Promise<T>,\n ): Promise<T> {\n let filter: TenantFilter | undefined;\n try {\n filter = this.restrictive();\n } catch (err) {\n return Promise.reject(err);\n }\n return send(filter ? scopeTenantQuery(query, filter) : query);\n }\n\n /** `run` when the request may see it, else null (an invisible run reads like a missing one). */\n private visible<T extends { tenantId?: string | null | undefined }>(\n run: T | null | undefined,\n filter = this.restrictive(),\n ): T | null {\n if (!run) return null;\n return !filter || tenantVisible(run, filter) ? run : null;\n }\n\n /** Run a control call unless the request may not act on `runId` (then `null`, like a missing run).\n * Sent at once when nothing narrows the request. */\n private guarded<T>(runId: string, call: () => Promise<T | null>): Promise<T | null> {\n let filter: TenantFilter | undefined;\n try {\n filter = this.restrictive();\n } catch (err) {\n // A tenant-required request with no tenant: reject, like every other read.\n return Promise.reject(err);\n }\n if (!filter) return call();\n return this.hidden(runId).then((hidden) => (hidden ? null : call()));\n }\n\n /** Before a control call: true when the request may NOT act on `runId`. */\n private async hidden(runId: string): Promise<boolean> {\n const filter = this.restrictive();\n if (!filter) return false;\n return this.visible(await this.getRunUnscoped(runId), filter) === null;\n }\n\n private handleReply(reply: RunReply): void {\n const pending = this.pending.get(reply.requestId);\n if (!pending) return;\n clearTimeout(pending.timer);\n this.pending.delete(reply.requestId);\n if (reply.result.ok) {\n pending.resolve(reply.result.data);\n } else if (reply.result.error.code === UNSUPPORTED_RUN_REQUEST) {\n pending.reject(\n new UnsupportedRunRequestError(reply.result.error.message, UNSUPPORTED_RUN_REQUEST),\n );\n } else {\n pending.reject(new RunGatewayError(reply.result.error.message, reply.result.error.code));\n }\n }\n\n private request<T>(body: RunRequestKind): Promise<T> {\n // A static token (or none) dispatches synchronously, exactly as before. A token PROVIDER is\n // resolved first, and the `timeoutMs` clock starts only once it has: the deadline bounds the\n // control plane's round trip, not the provider's latency. A provider that rejects fails the request.\n const source = this.tenantToken;\n if (typeof source !== 'function') return this.send<T>(source ?? this.tenant, body);\n return resolveTenantToken(source).then((tenant) => this.send<T>(tenant, body));\n }\n\n private send<T>(tenant: string, body: RunRequestKind): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const requestId = globalThis.crypto.randomUUID();\n const timer = setTimeout(() => {\n this.pending.delete(requestId);\n reject(\n new Error(`control plane did not respond to ${body.kind} within ${this.timeoutMs}ms`),\n );\n }, this.timeoutMs);\n this.pending.set(requestId, { resolve, reject, timer });\n this.transport.dispatchRunRequest?.({ requestId, tenant, body })?.catch((error: unknown) => {\n const stillPending = this.pending.get(requestId);\n if (!stillPending) return;\n clearTimeout(stillPending.timer);\n this.pending.delete(requestId);\n stillPending.reject(error instanceof Error ? error : new Error(String(error)));\n });\n });\n }\n\n topology(): DurableTopology {\n return { role: 'tenant', tenant: this.tenant };\n }\n\n /**\n * A control plane that predates {@link RunDetailOptions} ignores them and sends the full detail;\n * a summarized detail always carries `fans`, so its absence means the summary is made here.\n */\n async getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null> {\n const filter = this.restrictive();\n const detail = await this.request<RunDetail | null>(\n options === undefined\n ? { kind: 'getRunDetail', runId }\n : { kind: 'getRunDetail', runId, options },\n );\n if (detail && filter && !this.visible(detail.run, filter)) return null;\n const over = options?.summarizeFansOver;\n if (over === undefined || !detail || detail.fans !== undefined) return detail;\n const { timeline, fans } = summarizeTimeline(detail.timeline, over);\n const ids = childIdsOf(detail.timeline);\n return {\n ...detail,\n timeline,\n children: ids.slice(0, SUMMARY_CHILD_LIMIT),\n fans,\n childCount: ids.length,\n };\n }\n\n /** Paged from the full detail when the control plane is too old to page a fan itself. */\n async getFanMembers(runId: string, group: string, query: FanPageQuery): Promise<FanPage | null> {\n if (this.restrictive() && (await this.hidden(runId))) return null;\n if (!this.knownUnsupported('getFanMembers')) {\n try {\n const page = await this.request<FanPage | null | undefined>({\n kind: 'getFanMembers',\n runId,\n group,\n query,\n });\n if (page !== undefined) return page;\n } catch (err) {\n if (!isUnsupported(err)) throw err;\n }\n this.unsupportedUntil.set('getFanMembers', Date.now() + this.capabilityTtlMs);\n }\n const detail = await this.request<RunDetail | null>({ kind: 'getRunDetail', runId });\n return detail ? pageFan(detail.timeline, group, query) : null;\n }\n\n /**\n * The run alone, without its timeline. Read from the full detail when the control plane is too old\n * to know the verb: it then answers with no data, or with an unsupported-request error.\n */\n async getRun(runId: string): Promise<WorkflowRun | null> {\n return this.visible(await this.getRunUnscoped(runId));\n }\n\n private async getRunUnscoped(runId: string): Promise<WorkflowRun | null> {\n if (!this.knownUnsupported('getRun')) {\n try {\n const run = await this.request<WorkflowRun | null | undefined>({ kind: 'getRun', runId });\n if (run !== undefined) return run;\n } catch (err) {\n if (!isUnsupported(err)) throw err;\n }\n this.unsupportedUntil.set('getRun', Date.now() + this.capabilityTtlMs);\n }\n const detail = await this.request<RunDetail | null>({ kind: 'getRunDetail', runId });\n return detail?.run ?? null;\n }\n\n private knownUnsupported(kind: RunRequestKind['kind']): boolean {\n const until = this.unsupportedUntil.get(kind);\n if (until === undefined) return false;\n if (Date.now() < until) return true;\n this.unsupportedUntil.delete(kind);\n return false;\n }\n\n /** The control plane's `StoreRunGateway` resolves each run's `waiting` descriptor; the reply carries\n * it through as plain JSON, so a tenant's list rows name the wait too. */\n listRuns(query: RunQuery): Promise<RunListItem[]> {\n return this.scoped(query, (q) => this.request<RunListItem[]>({ kind: 'listRuns', query: q }));\n }\n\n /** Counted on the operator, over the same tenant-scoped predicates its `listRuns` reply obeys. */\n runFacets(query: RunFacetQuery): Promise<RunFacetRow[]> {\n return this.scoped(query, (q) => this.request<RunFacetRow[]>({ kind: 'runFacets', query: q }));\n }\n\n /** Enumerated on the operator, over the same tenant-scoped predicates its `listRuns` reply obeys —\n * so a tenant's pickers offer its own tenants/tags/attributes and never another's. */\n runValueFacets(\n axis: RunValueAxis,\n query: RunFacetQuery,\n opts?: RunValueFacetOptions,\n ): Promise<RunValueFacetRow[]> {\n return this.scoped(query, (q) =>\n this.request<RunValueFacetRow[]>({ kind: 'runValueFacets', axis, query: q, opts }),\n );\n }\n\n /** Round-trips to the operator, which scopes the result to this tenant's own `@<tenant>` groups. */\n workerHealth(): Promise<GroupHealth[]> {\n return this.request<GroupHealth[]>({ kind: 'workerHealth' });\n }\n\n /** Bulk, one request for the whole id list (like `listRuns`, not one request per id). The operator\n * filters the reply to runs this tenant actually owns (see `RunRequestResponder`). */\n waitingFor(runIds: string[]): Promise<Record<string, RunWaiting>> {\n return this.request<Record<string, RunWaiting>>({ kind: 'waitingFor', runIds });\n }\n\n cancel(runId: string, opts?: { compensate?: boolean }): Promise<RunResult | null> {\n return this.guarded(runId, () =>\n this.request<RunResult | null>(\n opts === undefined ? { kind: 'cancel', runId } : { kind: 'cancel', runId, opts },\n ),\n );\n }\n\n retry(runId: string): Promise<RunResult | null> {\n return this.guarded(runId, () => this.request<RunResult | null>({ kind: 'retry', runId }));\n }\n\n continue(runId: string): Promise<RunResult | null> {\n return this.guarded(runId, () => this.request<RunResult | null>({ kind: 'continue', runId }));\n }\n\n retryWithInput(runId: string, input: unknown): Promise<{ runId: string } | null> {\n return this.guarded(runId, () =>\n this.request<{ runId: string } | null>({ kind: 'retryWithInput', runId, input }),\n );\n }\n\n redispatchPending(runId: string): Promise<(RunResult & { redispatched: number }) | null> {\n return this.guarded(runId, () =>\n this.request<(RunResult & { redispatched: number }) | null>({ kind: 'redispatch', runId }),\n );\n }\n\n /**\n * Republished on the control plane: a one-run target is checked against this tenant like\n * `retry`, a by-workflow one is read over this tenant's namespace only. A control plane too old to\n * know the verb fails it with an {@link UNSUPPORTED_RUN_REQUEST} error rather than a timeout.\n */\n republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult> {\n return this.requestNewVerb<RepublishLifecycleResult>({ kind: 'republishLifecycle', target });\n }\n\n /** Answered by the control plane's engine; same version-skew error as {@link republishLifecycle}. */\n workflowLifecycle(workflow: string): Promise<WorkflowLifecycleLinks> {\n return this.requestNewVerb<WorkflowLifecycleLinks>({ kind: 'workflowLifecycle', workflow });\n }\n\n /**\n * A verb with no fallback on an older control plane: its unsupported-request error, or the empty\n * `ok: true` reply the oldest responders send for an unknown verb, becomes a\n * {@link RunGatewayError} with code {@link UNSUPPORTED_RUN_REQUEST}.\n */\n private async requestNewVerb<T>(body: RunRequestKind): Promise<T> {\n const notSupported = () =>\n new RunGatewayError(\n `${body.kind} is not supported by this server: the control plane is older than this tenant`,\n UNSUPPORTED_RUN_REQUEST,\n );\n if (this.knownUnsupported(body.kind)) throw notSupported();\n let data: T | undefined;\n try {\n data = await this.request<T | undefined>(body);\n } catch (err) {\n if (!isUnsupported(err)) throw err;\n }\n if (data !== undefined && data !== null) return data;\n this.unsupportedUntil.set(body.kind, Date.now() + this.capabilityTtlMs);\n throw notSupported();\n }\n\n subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void {\n const unsubscribe = this.transport.onTenantEvent?.(this.tenant, (evt) => {\n if (evt.event.runId === runId) onEvent(evt.event);\n });\n return unsubscribe ?? (() => {});\n }\n}\n","import {\n type LifecycleKind,\n type RepublishLifecycleTarget,\n type RunDetail,\n type RunGateway,\n type RunReply,\n type RunRequest,\n type RunRequestKind,\n type RunWaiting,\n type TenantVerifier,\n lifecycleKindOf,\n resolveWireTenant,\n} from '@dudousxd/nestjs-durable-core';\n\n/**\n * The error `code` a responder replies with for a verb it does not know, so a newer tenant can tell\n * \"this control plane is older than me\" from a real failure and fall back at once. Earlier\n * responders reply `ok: true` with no `data` instead; `ProxyRunGateway` reads both.\n */\nexport const UNSUPPORTED_RUN_REQUEST = 'unsupported-request';\n\n/** The error `code` a responder replies with for a request it rejects as malformed or not allowed. */\nexport const BAD_RUN_REQUEST = 'bad-request';\n\n/** The most settled runs one tenant republish reads; a larger `limit` is lowered to it. */\nexport const TENANT_REPUBLISH_MAX_LIMIT = 1000;\n\nconst KNOWN_KINDS: ReadonlySet<string> = new Set<RunRequestKind['kind']>([\n 'getRunDetail',\n 'getFanMembers',\n 'getRun',\n 'listRuns',\n 'runFacets',\n 'runValueFacets',\n 'workerHealth',\n 'cancel',\n 'retry',\n 'continue',\n 'retryWithInput',\n 'redispatch',\n 'waitingFor',\n 'republishLifecycle',\n 'workflowLifecycle',\n 'signal',\n 'schedule',\n]);\n\n/** A wire `since`/`until` (an ISO string after JSON) back to a `Date`. */\nfunction wireDate(value: Date | string | undefined): Date | undefined {\n if (value === undefined || value === null) return undefined;\n const date = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(date.getTime())) throw new Error(`invalid date ${String(value)}`);\n return date;\n}\n\n/** The narrow slice of `Transport` the responder needs — a tenant's read/control request in, a\n * correlated reply out. Both are OPTIONAL on the full `Transport` interface (only broker\n * transports carry the run-request/reply protocol); the caller capability-checks before wiring\n * this up (see `durable.module.ts`). */\nexport interface RunRequestTransport {\n onRunRequest(handler: (msg: RunRequest) => Promise<void>): void;\n publishRunReply(reply: RunReply): Promise<void>;\n}\n\n/** Options for {@link RunRequestResponder}. */\nexport interface RunRequestResponderOptions {\n /**\n * Verifies the signed token a tenant presents in the wire `tenant` field and DERIVES the real\n * tenant from it (see `hmacTenantVerifier`). Present: an invalid, tampered or absent token is\n * rejected with an `unauthorized` error reply and the wire claim is discarded in favour of the\n * verified tenant. Absent: the wire `tenant` is trusted verbatim (prefix/network isolation only).\n */\n verifyTenant?: TenantVerifier | undefined;\n /**\n * Warn at construction when no {@link verifyTenant} is set. Default `true`. `DurableModule` passes\n * `true` only for `topology: 'control-plane'`, so a standalone operator app that\n * never serves tenants boots silently.\n */\n warnWithoutVerifier?: boolean | undefined;\n}\n\n/**\n * Operator-side consumer of a tenant's {@link RunRequest}s: answers each one against a\n * `RunGateway`, enforcing the tenant boundary before touching the run. For every runId-bearing\n * verb it loads the run via `getRunDetail` FIRST and compares `run.namespace` to the requesting\n * `msg.tenant` — a mismatch short-circuits into a `cross-tenant` error reply WITHOUT calling the\n * verb, so a tenant can never read or act on another tenant's run. `listRuns` is scoped by\n * overwriting the query's `namespace` with the requester's tenant, ignoring whatever the client\n * sent. This is the security boundary of the tenant run gateway — do not weaken it.\n *\n * With {@link RunRequestResponderOptions.verifyTenant}, every request is authenticated FIRST: the\n * wire `tenant` is treated as a signed token, the real tenant is derived from it, and an invalid\n * token short-circuits into an `unauthorized` error reply before any run is touched. A verifier\n * that throws becomes an error reply too.\n */\n/**\n * `detail` with its links to other runs kept to `tenant`'s namespace: `awaitedBy` without the\n * waiting runs of other namespaces, and what was read of a `triggeredBy`, `waitsFor` or started\n * `lifecycleDeliveries` run (its status, namespace and trace id) only when that run is the tenant's.\n */\nfunction scopeRunLinks(detail: RunDetail, tenant: string): RunDetail {\n const own = (link: { namespace?: string | undefined }) => link.namespace === tenant;\n const bare = <T extends { status?: unknown; namespace?: string | undefined }>(link: T): T => {\n if (own(link)) return link;\n const { status: _status, namespace: _namespace, ...rest } = link;\n return rest as T;\n };\n const awaitedBy = detail.awaitedBy?.filter(own);\n const { awaitedBy: _awaitedBy, ...rest } = detail;\n const source = detail.triggeredBy;\n return {\n ...rest,\n ...(source\n ? { triggeredBy: own(source) ? source : { runId: source.runId, kind: source.kind } }\n : {}),\n ...(awaitedBy && awaitedBy.length > 0 ? { awaitedBy } : {}),\n ...(detail.waitsFor ? { waitsFor: detail.waitsFor.map(bare) } : {}),\n ...(detail.lifecycleDeliveries\n ? { lifecycleDeliveries: detail.lifecycleDeliveries.map(bare) }\n : {}),\n };\n}\n\nexport class RunRequestResponder {\n private readonly verifyTenant: TenantVerifier | undefined;\n\n constructor(\n private readonly transport: RunRequestTransport,\n private readonly gateway: RunGateway,\n options: RunRequestResponderOptions = {},\n ) {\n this.verifyTenant = options.verifyTenant;\n if (!this.verifyTenant && options.warnWithoutVerifier !== false) {\n // Loud on purpose: without a verifier the anti-IDOR checks below are bypassable by CLAIMING\n // another tenant's name in the wire `tenant` field. Prefix/network isolation may be an\n // acceptable posture, but it must be a chosen one.\n console.warn(\n '[nestjs-durable] run-request responder started WITHOUT a tenant verifier: the wire ' +\n '`tenant` claim is trusted verbatim (prefix/network isolation only). Any broker client ' +\n 'can act as any tenant. Configure `verifyTenant` (e.g. hmacTenantVerifier(secret)) and ' +\n 'signed tenant tokens unless your broker is fully isolated per tenant.',\n );\n }\n }\n\n /** Register the consumer on the transport. Each request is answered independently; a handler\n * failure never throws back into the transport (errors are captured into an error reply). */\n start(): void {\n this.transport.onRunRequest(async (msg) => {\n let reply: RunReply;\n try {\n reply = await this.handle(msg);\n } catch (err) {\n // Without a reply the tenant waits out its whole timeout for an answer that never comes.\n reply = {\n requestId: msg.requestId,\n result: {\n ok: false,\n error: { message: err instanceof Error ? err.message : String(err) },\n },\n };\n }\n await this.transport.publishRunReply(reply);\n });\n }\n\n private async handle(wire: RunRequest): Promise<RunReply> {\n const tenant = await resolveWireTenant(wire.tenant, this.verifyTenant);\n if (tenant === null) {\n return {\n requestId: wire.requestId,\n result: {\n ok: false,\n error: { message: 'invalid or unauthorized tenant token', code: 'unauthorized' },\n },\n };\n }\n // From here on `msg.tenant` is the VERIFIED tenant (the wire claim itself when no verifier is set).\n const msg: RunRequest = { ...wire, tenant };\n const { body } = msg;\n if (!KNOWN_KINDS.has(body.kind)) return unsupported(msg.requestId, String(body.kind));\n if (body.kind === 'listRuns') {\n // Force the namespace to the requester's tenant — the client-supplied value is discarded,\n // never merely validated, so a tenant can't widen its own query into another's namespace.\n const data = await this.gateway.listRuns({ ...body.query, namespace: msg.tenant });\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'runFacets') {\n // Same forced scope as `listRuns` above, for the same reason: the counts label a tenant's own\n // page, so they must be taken over exactly that tenant's runs and no one else's.\n const data = await this.gateway.runFacets({ ...body.query, namespace: msg.tenant });\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'runValueFacets') {\n // Same forced scope as `listRuns`/`runFacets`: the values fill a picker for the tenant's own\n // list, so enumerating them over anyone else's runs would both leak other tenants' tag and\n // attribute vocabulary and offer choices this tenant's list can never match.\n const data = await this.gateway.runValueFacets(\n body.axis,\n { ...body.query, namespace: msg.tenant },\n body.opts,\n );\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'workerHealth') {\n // Not runId-bearing, so it can't ride the getRunDetail namespace check below. Scope by the\n // group-name convention instead: a tenant's queues are suffixed `<name>@<tenant>`, so keep only\n // groups ending in the requester's `@<tenant>` — the operator's own bare groups and every other\n // tenant's are dropped, so a tenant's Workers panel only ever sees ITS OWN queues.\n const all = await this.gateway.workerHealth();\n const data = all.filter((h) => h.group.endsWith(`@${msg.tenant}`));\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'workflowLifecycle') {\n if (!this.gateway.workflowLifecycle) return unsupported(msg.requestId, body.kind);\n // Scoped to the requester: subscribers another tenant registers or announces stay unseen.\n const data = await this.gateway.workflowLifecycle(body.workflow, { namespace: msg.tenant });\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'republishLifecycle' && !('runId' in body.target)) {\n // Not runId-bearing: forced onto the requester's namespace, like `listRuns`, so a tenant can\n // only republish its own runs whatever namespace it sent.\n if (!this.gateway.republishLifecycle) return unsupported(msg.requestId, body.kind);\n const { since, until, limit, ...rest } = body.target as Extract<\n RepublishLifecycleTarget,\n { workflow: string }\n > & { since?: Date | string; until?: Date | string };\n if (\n limit !== undefined &&\n (typeof limit !== 'number' || !Number.isSafeInteger(limit) || limit < 1)\n ) {\n return badRequest(\n msg.requestId,\n `limit must be a positive integer, got ${JSON.stringify(limit)}`,\n );\n }\n const refused = await this.refuseSubscriber(\n rest.workflow,\n rest.kind,\n rest.subscriber,\n msg.tenant,\n );\n if (refused) return badRequest(msg.requestId, refused);\n const target: RepublishLifecycleTarget = {\n ...rest,\n namespace: msg.tenant,\n limit: Math.min(limit ?? TENANT_REPUBLISH_MAX_LIMIT, TENANT_REPUBLISH_MAX_LIMIT),\n ...(since !== undefined ? { since: wireDate(since) } : {}),\n ...(until !== undefined ? { until: wireDate(until) } : {}),\n };\n try {\n const data = await this.gateway.republishLifecycle(target);\n return { requestId: msg.requestId, result: { ok: true, data } };\n } catch (err) {\n return {\n requestId: msg.requestId,\n result: {\n ok: false,\n error: { message: err instanceof Error ? err.message : String(err) },\n },\n };\n }\n }\n\n if (body.kind === 'waitingFor') {\n // Bulk, like `listRuns` — but unlike `listRuns` (which forces the query's namespace and so\n // scopes itself) the caller supplies arbitrary ids, which could probe another tenant's runs. The\n // gateway's own `waitingFor` has no namespace to filter by, so verify ownership per MATCHED entry\n // (bounded by how many of the requested ids are actually waiting, never by `runIds.length`) the\n // same way every other runId-bearing verb does below: `getRunDetail` + a `namespace` check.\n const all = await this.gateway.waitingFor(body.runIds);\n const owned = await Promise.all(\n Object.entries(all).map(async ([runId, waiting]) => {\n const owner = this.gateway.getRun\n ? await this.gateway.getRun(runId)\n : (await this.gateway.getRunDetail(runId))?.run;\n return owner && owner.namespace === msg.tenant ? ([runId, waiting] as const) : undefined;\n }),\n );\n const data: Record<string, RunWaiting> = {};\n for (const entry of owned) {\n if (entry) data[entry[0]] = entry[1];\n }\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'schedule') {\n // Not runId-bearing: the schedule's own namespace is checked against the requester's, so a\n // requester can only pause, resume or trigger the schedules of its own namespace.\n const { getSchedule, scheduleAction } = this.gateway;\n if (!getSchedule || !scheduleAction) return unsupported(msg.requestId, body.kind);\n if (body.action !== 'pause' && body.action !== 'resume' && body.action !== 'trigger') {\n return badRequest(msg.requestId, `unknown schedule action ${JSON.stringify(body.action)}`);\n }\n const schedule = await getSchedule.call(this.gateway, body.id);\n if (!schedule || schedule.namespace !== msg.tenant) {\n // Another namespace's schedule reads as missing: its existence is not the requester's to learn.\n return {\n requestId: msg.requestId,\n result: {\n ok: false,\n error: { message: `schedule \"${body.id}\" not found`, code: 'not-found' },\n },\n };\n }\n return this.answer(msg.requestId, () =>\n scheduleAction.call(this.gateway, body.id, body.action),\n );\n }\n\n if (body.kind === 'signal') {\n // A token names no run, so the run waiting on it is looked up and checked like a runId-bearing\n // verb. A token no run waits on yet is answered `null` and NOT buffered: buffering would let a\n // requester plant a payload for a wait another namespace opens later.\n const { signal, signalWaiter } = this.gateway;\n if (!signal || !signalWaiter) return unsupported(msg.requestId, body.kind);\n const waiterRunId = await signalWaiter.call(this.gateway, body.token);\n const waiter = waiterRunId ? await this.runOf(waiterRunId) : null;\n if (!waiter || waiter.namespace !== msg.tenant) {\n return { requestId: msg.requestId, result: { ok: true, data: null } };\n }\n return this.answer(msg.requestId, () => signal.call(this.gateway, body.token, body.payload));\n }\n\n if (body.kind === 'republishLifecycle' && !this.gateway.republishLifecycle) {\n return unsupported(msg.requestId, body.kind);\n }\n\n // Every remaining verb is runId-bearing. Load the run FIRST — before calling the verb — so a\n // cross-tenant request never reaches the gateway's mutating methods (cancel/retry/continue/redispatch).\n // Only `getRunDetail` needs the timeline; every other verb checks ownership on the run alone.\n const runId = runIdOf(body);\n const detail =\n body.kind === 'getRunDetail' || !this.gateway.getRun\n ? await this.gateway.getRunDetail(\n runId,\n body.kind === 'getRunDetail' ? body.options : undefined,\n )\n : undefined;\n const run = detail !== undefined ? (detail?.run ?? null) : await this.gateway.getRun?.(runId);\n if (run && run.namespace !== msg.tenant) {\n return {\n requestId: msg.requestId,\n result: {\n ok: false,\n error: { message: 'run belongs to another tenant', code: 'cross-tenant' },\n },\n };\n }\n\n if (body.kind === 'getRunDetail') {\n const data = detail ? await this.scopeLifecycle(detail, msg.tenant) : detail;\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'getRun') {\n return { requestId: msg.requestId, result: { ok: true, data: run ?? null } };\n }\n\n if (body.kind === 'getFanMembers') {\n const data = run\n ? ((await this.gateway.getFanMembers?.(body.runId, body.group, body.query)) ?? null)\n : null;\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'republishLifecycle' && 'runId' in body.target && run) {\n const kind = lifecycleKindOf(run.status);\n const refused = kind\n ? await this.refuseSubscriber(run.workflow, kind, body.target.subscriber, msg.tenant)\n : undefined;\n if (refused) return badRequest(msg.requestId, refused);\n }\n\n try {\n const data = await this.callVerb(body);\n return { requestId: msg.requestId, result: { ok: true, data } };\n } catch (err) {\n return {\n requestId: msg.requestId,\n result: { ok: false, error: { message: err instanceof Error ? err.message : String(err) } },\n };\n }\n }\n\n /** The run alone (`getRun`, else from its detail), or null when it does not exist. */\n private async runOf(runId: string) {\n return this.gateway.getRun\n ? this.gateway.getRun(runId)\n : ((await this.gateway.getRunDetail(runId))?.run ?? null);\n }\n\n /** `call`'s result as an `ok` reply, or its rejection as an error reply. */\n private async answer(requestId: string, call: () => Promise<unknown>): Promise<RunReply> {\n try {\n return { requestId, result: { ok: true, data: await call() } };\n } catch (err) {\n return {\n requestId,\n result: { ok: false, error: { message: err instanceof Error ? err.message : String(err) } },\n };\n }\n }\n\n /**\n * `detail` scoped to `tenant` (see {@link scopeRunLinks}), with its lifecycle links\n * (`workflowLifecycle`, `lifecycleSubscribers`) narrowed to the subscriptions of `tenant`'s\n * namespace, as the `workflowLifecycle` verb answers them.\n */\n private async scopeLifecycle(input: RunDetail, tenant: string): Promise<RunDetail> {\n const detail = scopeRunLinks(input, tenant);\n if (detail.workflowLifecycle === undefined && detail.lifecycleSubscribers === undefined) {\n return detail;\n }\n const { workflowLifecycle: _links, lifecycleSubscribers: _subscribers, ...rest } = detail;\n const links = await this.gateway.workflowLifecycle?.(detail.run.workflow, {\n namespace: tenant,\n });\n if (!links) return rest;\n const kind = lifecycleKindOf(detail.run.status);\n const subscribers = kind\n ? [...new Set(links.startsOnSettle.filter((l) => l.kind === kind).map((l) => l.workflow))]\n : [];\n const linked = links.startsOnSettle.length > 0 || links.startedBy.length > 0;\n return {\n ...rest,\n ...(subscribers.length > 0 ? { lifecycleSubscribers: subscribers } : {}),\n ...(linked ? { workflowLifecycle: links } : {}),\n };\n }\n\n /**\n * Why a tenant republish naming `subscriber` is refused, or undefined when it may go ahead: the\n * subscriber must be owed the event of `workflow` settling (as `kind`, when given) by a run of\n * the tenant's namespace (the gateway's `lifecycleSubscribers`, else the tenant's\n * `workflowLifecycle` links), so a tenant cannot have the event owed to an arbitrary name. Without\n * `subscriber` there is nothing to check.\n */\n private async refuseSubscriber(\n workflow: string,\n kind: LifecycleKind | undefined,\n subscriber: string | undefined,\n tenant: string,\n ): Promise<string | undefined> {\n if (subscriber === undefined) return undefined;\n const kinds: LifecycleKind[] = kind ? [kind] : ['completed', 'failed'];\n let subscribes = false;\n if (this.gateway.lifecycleSubscribers) {\n for (const k of kinds) {\n const subscribers = await this.gateway.lifecycleSubscribers(workflow, k, tenant);\n subscribes ||= subscribers.includes(subscriber);\n }\n } else {\n const links = await this.gateway.workflowLifecycle?.(workflow, { namespace: tenant });\n subscribes =\n links?.startsOnSettle.some(\n (link) => link.workflow === subscriber && kinds.includes(link.kind),\n ) ?? false;\n }\n if (subscribes) return undefined;\n const events = kind\n ? `run.${kind}:${workflow}`\n : `run.completed:${workflow} or run.failed:${workflow}`;\n return `subscriber ${subscriber} does not subscribe to ${events} in namespace ${tenant}`;\n }\n\n private callVerb(\n body: Exclude<\n RunRequest['body'],\n | { kind: 'listRuns' }\n | { kind: 'runFacets' }\n | { kind: 'runValueFacets' }\n | { kind: 'getRunDetail' }\n | { kind: 'getFanMembers' }\n | { kind: 'getRun' }\n | { kind: 'workerHealth' }\n | { kind: 'waitingFor' }\n | { kind: 'workflowLifecycle' }\n | { kind: 'signal' }\n | { kind: 'schedule' }\n >,\n ): Promise<unknown> {\n switch (body.kind) {\n case 'republishLifecycle':\n return (\n this.gateway.republishLifecycle?.(body.target) ??\n Promise.reject(new Error('republishLifecycle is not supported'))\n );\n case 'cancel':\n return this.gateway.cancel(body.runId, body.opts);\n case 'retry':\n return this.gateway.retry(body.runId);\n case 'continue':\n return this.gateway.continue(body.runId);\n case 'retryWithInput':\n return this.gateway.retryWithInput(body.runId, body.input);\n case 'redispatch':\n return this.gateway.redispatchPending(body.runId);\n }\n }\n}\n\n/** The run a runId-bearing request acts on; a one-run republish names it in its target. */\nfunction runIdOf(\n body: Exclude<\n RunRequestKind,\n | { kind: 'listRuns' }\n | { kind: 'runFacets' }\n | { kind: 'runValueFacets' }\n | { kind: 'workerHealth' }\n | { kind: 'waitingFor' }\n | { kind: 'workflowLifecycle' }\n | { kind: 'signal' }\n | { kind: 'schedule' }\n >,\n): string {\n if (body.kind !== 'republishLifecycle') return body.runId;\n return 'runId' in body.target ? body.target.runId : '';\n}\n\n/** The reply to a request this responder rejects (see {@link BAD_RUN_REQUEST}). */\nfunction badRequest(requestId: string, message: string): RunReply {\n return { requestId, result: { ok: false, error: { message, code: BAD_RUN_REQUEST } } };\n}\n\n/** The reply to a verb this responder knows but its gateway cannot answer. */\nfunction unsupported(requestId: string, kind: string): RunReply {\n return {\n requestId,\n result: {\n ok: false,\n error: {\n message: `the control plane does not support the ${kind} run request`,\n code: UNSUPPORTED_RUN_REQUEST,\n },\n },\n };\n}\n","import {\n DURABLE_OPTIONS_CANONICAL,\n STATE_STORE_CANONICAL,\n type StateStore,\n TERMINAL_RUN_STATUSES,\n parseDuration,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n Inject,\n Injectable,\n type OnApplicationBootstrap,\n type OnModuleDestroy,\n Optional,\n} from '@nestjs/common';\nimport type { DurableModuleOptions, DurableRetentionOptions } from './durable.module';\nimport { isDrivingOperator } from './role';\nimport { settleWithin } from './settle-within';\nimport { SweepLeases } from './sweep-leases';\n\nconst DEFAULT_SWEEP_INTERVAL_MS = 60_000;\nconst DEFAULT_BATCH_SIZE = 1_000;\n// Backstop so a single sweep can never loop unbounded. At the default batch size this still drains up\n// to 100k runs per policy per sweep before yielding the event loop to the next tick.\nconst MAX_BATCHES_PER_POLICY = 100;\n\n/**\n * Reject a retention config that would silently misbehave: every policy must set at least one bound,\n * list only terminal statuses (pruning a live status would race the engine), and the status sets must\n * be disjoint (so \"most recent N\" is unambiguous per status group). Throws on the first violation.\n */\nexport function validateRetention(retention: DurableRetentionOptions): void {\n // Disjointness is per SCOPE: two policies over the same runs must not both claim a status (\"keep 100\"\n // vs \"keep 10\" of the same set is ambiguous), but `{ namespace: 'a' }` and `{ namespace: 'b' }` — or a\n // tenant-scoped policy next to an unscoped default — each rule their own selection.\n const seen = new Set<string>();\n for (const policy of retention.policies) {\n const scopeKey = policy.scope ? stableKey(policy.scope) : '';\n if (policy.statuses.length === 0) {\n throw new Error('durable retention: each policy must list at least one status');\n }\n if (policy.maxAge == null && policy.maxCount == null) {\n throw new Error('durable retention: each policy must set maxAge and/or maxCount');\n }\n // Fail fast on a typo'd duration string ('7days', '1 month') at boot rather than silently never pruning.\n if (policy.maxAge != null) parseDuration(policy.maxAge);\n for (const status of policy.statuses) {\n if (!TERMINAL_RUN_STATUSES.includes(status)) {\n throw new Error(\n `durable retention: status \"${status}\" is not terminal; only ${TERMINAL_RUN_STATUSES.join(\n ', ',\n )} can be pruned`,\n );\n }\n const key = `${scopeKey}|${status}`;\n if (seen.has(key)) {\n throw new Error(\n `durable retention: status \"${status}\" appears in more than one policy with the same scope; status sets must be disjoint per scope`,\n );\n }\n seen.add(key);\n }\n }\n}\n\n/** A key-order-independent JSON key for a scope, so `{a,b}` and `{b,a}` compare equal. */\nfunction stableKey(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableKey).join(',')}]`;\n if (value && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => a.localeCompare(b));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableKey(v)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n}\n\n/**\n * Hard-prunes terminal run history on an interval per the configured `retention` policies, keeping the\n * `durable_workflow_runs` table (and its children) bounded so the poller's per-tick scans stay cheap.\n *\n * Worker-only (a dashboard-only instance never prunes), separate from the 1s timer poll (defaults to a\n * 60s sweep), and self-draining: each policy is swept in `batchSize` chunks until a batch comes back\n * short. No-ops with a warning if the store adapter doesn't implement `pruneTerminalRuns`.\n */\n@Injectable()\nexport class RetentionPoller implements OnApplicationBootstrap, OnModuleDestroy {\n private timer?: ReturnType<typeof setInterval>;\n private sweeping = false;\n private stopping = false;\n /** The sweep in flight, so shutdown can wait for it before the store closes. */\n private current: Promise<void> | undefined;\n\n constructor(\n @Inject(STATE_STORE_CANONICAL) private readonly store: StateStore | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n // One pod prunes when the app has `LocksModule` from `@nestjs/locks` (detected, see SweepLeases).\n @Optional() private readonly leases: SweepLeases = new SweepLeases(),\n ) {}\n\n /** Non-null once past the `isDrivingOperator` guard (which requires `options.store` to be set). */\n private requireStore(): StateStore {\n if (!this.store) {\n throw new Error(\n 'unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set',\n );\n }\n return this.store;\n }\n\n async onApplicationBootstrap(): Promise<void> {\n // Only a DRIVING operator prunes — a dashboard/dispatch-only instance, or a thin worker with no\n // `store` at all, must not delete history.\n if (!isDrivingOperator(this.options)) return;\n const retention = this.options.retention;\n if (!retention || retention.policies.length === 0) return;\n validateRetention(retention);\n if (typeof this.requireStore().pruneTerminalRuns !== 'function') {\n console.warn(\n '[nestjs-durable] `retention` is configured but the store adapter does not implement pruneTerminalRuns; retention is disabled.',\n );\n return;\n }\n // Started, not awaited: a first prune over a large history must not hold the host's boot (its\n // HTTP server listens only after every `onApplicationBootstrap`). Shutdown waits for it.\n void this.sweep();\n const intervalMs =\n retention.sweepInterval != null\n ? parseDuration(retention.sweepInterval)\n : DEFAULT_SWEEP_INTERVAL_MS;\n if (intervalMs > 0) {\n this.timer = setInterval(() => void this.sweep(), intervalMs);\n this.timer.unref?.();\n }\n }\n\n /** Stop sweeping and wait for the sweep in flight (bounded by `shutdownTimeoutMs`, default 10s),\n * so no prune is still pending when the host closes its connection pool. This wait runs concurrently\n * with the timer poller's and is NOT deducted from the engine's drain budget (the retention poller\n * holds no engine), so a slow prune can add up to one more `shutdownTimeoutMs` before the drain. */\n async onModuleDestroy(): Promise<void> {\n if (this.timer) clearInterval(this.timer);\n this.stopping = true;\n if (!this.current) return;\n const budget = this.options.shutdownTimeoutMs ?? 10_000;\n if (await settleWithin(this.current, budget)) {\n console.warn(\n `[nestjs-durable] retention sweep still running after ${budget}ms at shutdown; continuing`,\n );\n }\n }\n\n /**\n * Prune one round.\n *\n * Never rejects, for the same reason {@link TimerPoller.poll} does not: it is fired as `void` on\n * boot and on the interval, so a rejection would be an unhandled one, which is fatal.\n * Pruning history is the least urgent thing this package does — a `pruneTerminalRuns` that fails\n * on a locked table must cost this sweep and nothing more.\n */\n private sweep(): Promise<void> {\n if (this.sweeping) return this.current ?? Promise.resolve(); // never overlap two sweeps\n const run = this.sweepOnce().finally(() => {\n if (this.current === run) this.current = undefined;\n });\n this.current = run;\n return run;\n }\n\n private async sweepOnce(): Promise<void> {\n if (this.stopping) return;\n const retention = this.options.retention;\n const store = this.requireStore();\n const prune = store.pruneTerminalRuns;\n if (!retention || typeof prune !== 'function') return;\n this.sweeping = true;\n try {\n await this.leases.run('retention', () => this.prune(retention, store, prune));\n } catch (error) {\n console.error('[nestjs-durable] retention sweep failed; retrying next interval:', error);\n } finally {\n this.sweeping = false;\n }\n }\n\n private async prune(\n retention: DurableRetentionOptions,\n store: StateStore,\n prune: NonNullable<StateStore['pruneTerminalRuns']>,\n ): Promise<void> {\n const batchSize = retention.batchSize ?? DEFAULT_BATCH_SIZE;\n const now = Date.now();\n for (const policy of retention.policies) {\n for (let batch = 0; batch < MAX_BATCHES_PER_POLICY; batch++) {\n if (this.stopping) return;\n const deleted = await prune.call(store, policy, now, batchSize);\n if (deleted < batchSize) break; // backlog drained for this policy\n }\n }\n }\n}\n","/** Resolve when `p` settles or after `timeoutMs`, whichever comes first; never rejects. Returns\n * true when the wait timed out with `p` still pending. */\nexport async function settleWithin(p: Promise<unknown>, timeoutMs: number): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(() => {\n timedOut = true;\n resolve();\n }, timeoutMs);\n timer.unref?.();\n });\n try {\n await Promise.race([p.then(undefined, () => undefined), timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n return timedOut;\n}\n","import { DURABLE_OPTIONS_CANONICAL } from '@dudousxd/nestjs-durable-core';\nimport { Inject, Injectable, Logger, type OnModuleInit, Optional } from '@nestjs/common';\nimport { ModuleRef } from '@nestjs/core';\nimport type { DurableModuleOptions } from './durable.module';\n\n/**\n * The slice of `@nestjs/locks` used here, structurally: the package is an OPTIONAL peer, so nothing\n * from it is imported statically (the main entry must load without it).\n */\ninterface HeldLock {\n readonly held: boolean;\n}\ninterface LocksLike {\n acquire(\n key: string,\n options?: { ttl?: number | string; wait?: number | string },\n ): Promise<HeldLock | null>;\n}\n\n/** The fleet-wide sweeps gated by a lease when `@nestjs/locks` is present. */\nexport type FleetSweep =\n | 'retention'\n | 'stalled-pager'\n | 'buffered-signals'\n | 'signal-ids'\n | 'announced-schedules';\n\n/**\n * Runs durable's FLEET-WIDE sweeps (retention pruning, the stalled-run pager, the orphaned\n * buffered-signal cleanup, the expired signal dedupe ids) on one pod at a time when the app imports\n * `LocksModule` from `@nestjs/locks`. Detected, never configured: with no `Locks` provider in the app, every sweep runs\n * on every driving pod exactly as before.\n *\n * Each sweep holds its own lease, `durable:<sweep>` (suffixed `:<namespace>` on a namespaced engine).\n * The first pod to tick takes it and KEEPS it (the official `Lock` renews itself every `ttl / 3`);\n * the others skip that sweep on every tick until the holder stops renewing (crash, shutdown, a lost\n * lease), and the next tick elsewhere takes over. A lease held across ticks, rather than a lock per\n * tick, is what keeps the pager from paging once per pod: pods tick at different moments, so a lock\n * released after each tick would be won by each pod in turn.\n *\n * The leases go back at shutdown with every other lock (`Locks.beforeApplicationShutdown`, after\n * the pollers have waited for their sweep in `onModuleDestroy`).\n *\n * Work-claiming sweeps (pending runs, recovery, timers, timeouts, schedules, lifecycle events) stay\n * on every pod: they already arbitrate per run with leases / compare-and-set.\n */\n@Injectable()\nexport class SweepLeases implements OnModuleInit {\n private readonly logger = new Logger('nestjs-durable');\n /** Set by {@link onModuleInit} (before any poller's bootstrap). `null`: no `@nestjs/locks`. */\n private locks: LocksLike | null = null;\n private readonly leases = new Map<FleetSweep, HeldLock>();\n\n constructor(\n @Optional() private readonly moduleRef?: ModuleRef,\n @Optional()\n @Inject(DURABLE_OPTIONS_CANONICAL)\n private readonly options?: DurableModuleOptions,\n ) {}\n\n /**\n * Run `fn` if this pod holds (or now takes) the lease of `sweep`; otherwise skip it and resolve\n * `undefined`. Without `@nestjs/locks` it always runs `fn`.\n */\n async run<T>(sweep: FleetSweep, fn: () => Promise<T>): Promise<T | undefined> {\n const locks = this.locks;\n // No `@nestjs/locks`: straight through, with no extra await (today's timing, unchanged).\n if (!locks) return fn();\n if (!(await this.holds(locks, sweep))) return undefined;\n return fn();\n }\n\n private async holds(locks: LocksLike, sweep: FleetSweep): Promise<boolean> {\n if (this.leases.get(sweep)?.held) return true;\n this.leases.delete(sweep);\n let lock: HeldLock | null;\n try {\n lock = await locks.acquire(this.key(sweep));\n } catch (error) {\n // A lock store that fails or times out costs this tick of this sweep, nothing more.\n this.logger.warn(\n `could not take the ${sweep} sweep lease; skipping this tick: ${String(error)}`,\n );\n return false;\n }\n if (!lock) return false;\n this.leases.set(sweep, lock);\n return true;\n }\n\n private key(sweep: FleetSweep): string {\n const ns = this.options?.namespace;\n return ns ? `durable:${sweep}:${ns}` : `durable:${sweep}`;\n }\n\n /** Detects `Locks` once, and logs which mode is active. Nest awaits it before any bootstrap hook. */\n async onModuleInit(): Promise<void> {\n this.locks = await this.detect();\n this.logger.log(\n this.locks\n ? 'fleet-wide sweeps (retention, stalled-run pager, buffered-signal cleanup, expired signal-id cleanup) run on one pod at a time, through @nestjs/locks'\n : 'fleet-wide sweeps run on every driving pod (import LocksModule from @nestjs/locks to run them on one)',\n );\n }\n\n private async detect(): Promise<LocksLike | null> {\n let locks: LocksLike | null = null;\n if (this.moduleRef) {\n try {\n // Indirect specifier: the optional peer must not be resolved statically by the compiler or\n // the bundler. A missing package rejects and lands in the catch.\n const specifier = '@nestjs/locks';\n const mod = (await import(specifier)) as {\n Locks?: abstract new (...args: never[]) => unknown;\n };\n if (mod.Locks) {\n locks = this.moduleRef.get(mod.Locks, { strict: false }) as unknown as LocksLike;\n }\n } catch {\n locks = null;\n }\n }\n return locks;\n }\n}\n","import {\n type DurableTopology,\n type EngineEvent,\n type FanPage,\n type FanPageQuery,\n type GroupHealth,\n LIFECYCLE_REGISTRY_WORKFLOW,\n type LifecycleDelivery,\n type LifecycleKind,\n type RepublishLifecycleResult,\n type RepublishLifecycleTarget,\n type RunDetail,\n type RunDetailOptions,\n type RunFacetQuery,\n type RunFacetRow,\n type RunGateway,\n type RunListItem,\n type RunQuery,\n type RunResult,\n type RunValueAxis,\n type RunValueFacetOptions,\n type RunValueFacetRow,\n type RunWaitLink,\n type RunWaiting,\n STATE_STORE_CANONICAL,\n SUMMARY_CHILD_LIMIT,\n type ScheduleAction,\n type ScheduleDescription,\n type ScheduleListQuery,\n type StateStore,\n WorkflowEngine,\n type WorkflowLifecycleLinks,\n type WorkflowRun,\n aggregatesCheckpoints,\n childIdsOf,\n etagMatches,\n extendEtag,\n fanPageEtag,\n indexWaitersByRun,\n lifecycleDeliveriesOf,\n lifecycleKindOf,\n lifecycleSourceOf,\n lifecycleTraceparentOf,\n listSignalWaitersOfRuns,\n mergeRunFacetRows,\n pageFan,\n pageFanFromStore,\n readRunsByIds,\n resolveRunWaiting,\n runDetailEtag,\n runWaitPrefix,\n runWaitTargetOf,\n summarizeRunFromStore,\n summarizeTimeline,\n traceIdOfTraceparent,\n} from '@dudousxd/nestjs-durable-core';\nimport { Inject, Injectable } from '@nestjs/common';\n\n/**\n * What a run detail reads from outside the run row and its checkpoints, folded into its ETag: the\n * subscribers and where each delivery stands, and the status of every run its links point at.\n * Undefined when it has none of them.\n */\nfunction detailExtras(\n links: Pick<\n RunDetail,\n 'lifecycleSubscribers' | 'lifecycleDeliveries' | 'waitsFor' | 'awaitedBy' | 'triggeredBy'\n >,\n): unknown {\n const { lifecycleSubscribers, lifecycleDeliveries, waitsFor, awaitedBy, triggeredBy } = links;\n if (!lifecycleSubscribers && !lifecycleDeliveries && !waitsFor && !awaitedBy && !triggeredBy) {\n return undefined;\n }\n return { lifecycleSubscribers, lifecycleDeliveries, waitsFor, awaitedBy, triggeredBy };\n}\n\n/**\n * `query` without the lifecycle registry's runs, engine bookkeeping that is not a run anyone\n * started, unless the query names that workflow itself.\n */\nfunction withoutRegistry<Q extends RunFacetQuery>(query: Q): Q {\n if (\n query.workflow === LIFECYCLE_REGISTRY_WORKFLOW ||\n query.workflows?.includes(LIFECYCLE_REGISTRY_WORKFLOW)\n ) {\n return query;\n }\n return {\n ...query,\n excludeWorkflows: [...(query.excludeWorkflows ?? []), LIFECYCLE_REGISTRY_WORKFLOW],\n };\n}\n\n/**\n * Store-backed `RunGateway` — the operator-side implementation, bound to {@link RunGateway} on\n * worker/drive instances. Reuses `DashboardService`'s six read/control method bodies verbatim\n * (`dashboard.service.ts:76-172`), so a consumer that only needs the bounded `RunGateway` surface\n * (the `RunRequestResponder`, a thin controller) doesn't have to depend on the dashboard package.\n */\n@Injectable()\nexport class StoreRunGateway implements RunGateway {\n constructor(\n @Inject(STATE_STORE_CANONICAL) private readonly store: StateStore,\n private readonly engine: WorkflowEngine,\n ) {}\n\n topology(): DurableTopology {\n return { role: 'control-plane' };\n }\n\n /**\n * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s\n * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).\n */\n private scoped<Q extends RunQuery | RunFacetQuery>(query: Q): Q {\n return typeof this.engine?.scopeRunQuery === 'function'\n ? (this.engine.scopeRunQuery(query as RunQuery) as Q)\n : query;\n }\n\n /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */\n private async visibleRun(runId: string): Promise<WorkflowRun | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n const { tenantIds } = this.scoped({} as RunQuery);\n return !tenantIds || tenantIds.includes(run.tenantId ?? null) ? run : null;\n }\n\n async getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null> {\n const run = await this.visibleRun(runId);\n if (!run) return null;\n const links = await this.lifecycleLinks(run);\n const over = options?.summarizeFansOver;\n if (over === undefined) {\n const [timeline, children] = await Promise.all([\n this.store.listCheckpoints(runId),\n this.engine.getRunChildren(runId), // canonical parent→children edge (shared with cancel cascade)\n ]);\n return { run, timeline, children, ...links };\n }\n // Summarized: the children come from the checkpoints, rather than from a read of every\n // child-edge checkpoint plus the waiters. A child whose waiter is written but whose placeholder\n // checkpoint is not yet is missing for that one read; the next one lists it.\n if (aggregatesCheckpoints(this.store)) {\n // The buckets are read before any row, so a write landing mid-read leaves the ETag older than\n // the body: the next poll misses and re-reads, rather than pinning a stale body.\n const stats = await this.store.checkpointStats(runId);\n const etag = extendEtag(runDetailEtag(run, stats, over), detailExtras(links));\n if (etagMatches(options?.ifNoneMatch, etag)) {\n return { run, timeline: [], children: [], notModified: true, etag };\n }\n return {\n run,\n ...(await summarizeRunFromStore(this.store, runId, over, stats)),\n etag,\n ...links,\n };\n }\n const full = await this.store.listCheckpoints(runId);\n const { timeline, fans } = summarizeTimeline(full, over);\n const ids = childIdsOf(full);\n return {\n run,\n timeline,\n children: ids.slice(0, SUMMARY_CHILD_LIMIT),\n fans,\n childCount: ids.length,\n ...links,\n };\n }\n\n /**\n * What a run detail reads beyond the run row and its checkpoints: what this run's settling\n * started, the subscribers its lifecycle event goes to (of its namespace) and where it stands for\n * each, what started it, its workflow's lifecycle links, and the `ctx.waitForRun` waits on either\n * side of it with the other run's status. A few reads per detail: the run's own waiters while it\n * is suspended, the waiters on it (one prefix read), and one batched read of every linked run.\n */\n private async lifecycleLinks(\n run: WorkflowRun,\n ): Promise<\n Pick<\n RunDetail,\n | 'triggered'\n | 'triggeredBy'\n | 'lifecycleSubscribers'\n | 'workflowLifecycle'\n | 'lifecycleDeliveries'\n | 'waitsFor'\n | 'awaitedBy'\n >\n > {\n const triggered = await this.engine.triggeredRuns(run);\n const source = lifecycleSourceOf(run);\n const kind = lifecycleKindOf(run.status);\n const subscribers = kind\n ? await this.engine.lifecycleSubscribers(run.workflow, kind, run.namespace || 'default')\n : [];\n const workflowLifecycle = await this.engine.workflowLifecycle(run.workflow);\n const linked =\n workflowLifecycle.startsOnSettle.length > 0 || workflowLifecycle.startedBy.length > 0;\n const deliveries = kind\n ? lifecycleDeliveriesOf(run, {\n subscribers,\n live: new Set(subscribers),\n coalesced: this.engine.coalescedSubscribers(run),\n })\n : [];\n const [own, onIt] = await Promise.all([\n run.status === 'suspended' ? listSignalWaitersOfRuns(this.store, [run.id]) : [],\n run.workflow.startsWith('__') ? [] : this.store.listSignalWaiters(runWaitPrefix(run.id)),\n ]);\n const waitsFor: RunWaitLink[] = own.flatMap((w) => {\n const target = runWaitTargetOf(w);\n return target !== undefined ? [{ runId: target, seq: w.seq }] : [];\n });\n const awaitedBy: RunWaitLink[] = onIt\n .filter((w) => runWaitTargetOf(w) === run.id)\n .map((w) => ({ runId: w.runId, seq: w.seq }));\n const started = deliveries.flatMap((d) =>\n d.state === 'started' && d.runId !== undefined ? [d.runId] : [],\n );\n const { runs } = await readRunsByIds(this.store, [\n ...(source ? [source.runId] : []),\n ...started,\n ...waitsFor.map((l) => l.runId),\n ...awaitedBy.map((l) => l.runId),\n ]);\n const withRun = <T extends { runId?: string | undefined }>(link: T): T => {\n const other = link.runId !== undefined ? runs.get(link.runId) : undefined;\n return other ? { ...link, status: other.status, namespace: other.namespace } : link;\n };\n const sourceRun = source ? runs.get(source.runId) : undefined;\n const traceId = traceIdOfTraceparent(lifecycleTraceparentOf(sourceRun?.tags));\n return {\n ...(triggered.length > 0 ? { triggered } : {}),\n ...(source\n ? {\n triggeredBy: {\n ...source,\n ...(sourceRun ? { status: sourceRun.status, namespace: sourceRun.namespace } : {}),\n ...(traceId ? { traceId } : {}),\n },\n }\n : {}),\n ...(subscribers.length > 0 ? { lifecycleSubscribers: subscribers } : {}),\n ...(linked ? { workflowLifecycle } : {}),\n ...(deliveries.length > 0\n ? {\n lifecycleDeliveries: deliveries.map(\n (d): LifecycleDelivery => (d.state === 'started' ? withRun(d) : d),\n ),\n }\n : {}),\n ...(waitsFor.length > 0 ? { waitsFor: waitsFor.map(withRun) } : {}),\n ...(awaitedBy.length > 0 ? { awaitedBy: awaitedBy.map(withRun) } : {}),\n };\n }\n\n workflowLifecycle(\n workflow: string,\n opts?: { namespace?: string | undefined },\n ): Promise<WorkflowLifecycleLinks> {\n return this.engine.workflowLifecycle(workflow, opts);\n }\n\n lifecycleSubscribers(\n workflow: string,\n kind: LifecycleKind,\n namespace: string,\n ): Promise<string[]> {\n return this.engine.lifecycleSubscribers(workflow, kind, namespace);\n }\n\n getRun(runId: string): Promise<WorkflowRun | null> {\n return this.visibleRun(runId);\n }\n\n async getFanMembers(runId: string, group: string, query: FanPageQuery): Promise<FanPage | null> {\n if (!(await this.visibleRun(runId))) return null;\n if (aggregatesCheckpoints(this.store)) {\n const stats = await this.store.checkpointStats(runId, { group });\n const etag = fanPageEtag(group, stats, query);\n if (etagMatches(query.ifNoneMatch, etag)) {\n return { items: [], total: 0, notModified: true, etag };\n }\n return { ...(await pageFanFromStore(this.store, runId, group, query, stats)), etag };\n }\n return pageFan(await this.store.listCheckpoints(runId), group, query);\n }\n\n async listRuns(query: RunQuery): Promise<RunListItem[]> {\n const runs = await this.store.listRuns(this.scoped(withoutRegistry(query)));\n // One read of the listed suspended runs' signal waiters resolves what each is parked on — signal\n // / webhook / child — with no per-run timeline fetch. A timer wait falls back to the run's own\n // `wakeAt`. Non-suspended (and remote-step-in-flight) runs carry no `waiting`.\n const waiterByRun = indexWaitersByRun(\n await listSignalWaitersOfRuns(\n this.store,\n runs.filter((run) => run.status === 'suspended').map((run) => run.id),\n ),\n );\n return runs.map((run) => {\n const waiting = resolveRunWaiting(run, waiterByRun);\n return waiting ? { ...run, waiting } : run;\n });\n }\n\n /**\n * The `(status, origin)` counts behind a console's chips, straight off the store's aggregate. The\n * console needs this precisely BECAUSE its list is paginated: the page bounds what is rendered,\n * these counts stay whole-set exact. A store with no aggregate falls back to counting a full\n * listing — correct, but the unbounded read this exists to avoid, so it is the last resort.\n */\n async runFacets(query: RunFacetQuery): Promise<RunFacetRow[]> {\n const scoped = this.scoped(withoutRegistry(query));\n if (this.store.runFacets) return this.store.runFacets(scoped);\n const runs = await this.store.listRuns(scoped);\n return mergeRunFacetRows(runs.map((r) => ({ status: r.status, origin: r.origin, count: 1 })));\n }\n\n /**\n * The distinct values behind a console's pickers, straight off the store's enumeration. A store\n * without one answers `[]` rather than falling back to a listing: unlike the facet counts above —\n * where a full listing is at least the RIGHT answer expensively — a picker built from an unbounded\n * scan would be the same unbounded read on every keystroke, for a control whose free-text entry\n * still works without it.\n */\n async runValueFacets(\n axis: RunValueAxis,\n query: RunFacetQuery,\n opts?: RunValueFacetOptions,\n ): Promise<RunValueFacetRow[]> {\n return this.store.runValueFacets?.(axis, this.scoped(withoutRegistry(query)), opts) ?? [];\n }\n\n /**\n * Bulk-resolve what each of `runIds` is currently parked on — for a consumer with its own filtered/\n * paginated run listing (e.g. \"which of MY suspended runs are stuck at a breakpoint\") without\n * re-deriving `listRuns`' waiter read or querying `durable_step_checkpoints` directly. Mirrors\n * `listRuns`' waiting computation (the requested runs' signal waiters + `resolveRunWaiting`), but ALSO\n * bulk-fetches the currently-suspended runs to check real status: `engine.cancel` (the non-compensate\n * path) doesn't clear a run's signal waiter row, so a cancelled run can leave an ORPHANED waiter\n * behind — trusting waiter presence alone would wrongly report a terminal run as still waiting.\n * Two bulk reads total (never one query per requested id), same as `listRuns`.\n */\n async waitingFor(runIds: string[]): Promise<Record<string, RunWaiting>> {\n if (runIds.length === 0) return {};\n const idSet = new Set(runIds);\n const [suspended, waiters] = await Promise.all([\n this.store.listRuns(this.scoped({ statuses: ['suspended'] })),\n listSignalWaitersOfRuns(this.store, runIds),\n ]);\n const waiterByRun = indexWaitersByRun(waiters);\n const result: Record<string, RunWaiting> = {};\n for (const run of suspended) {\n if (!idSet.has(run.id)) continue;\n const waiting = resolveRunWaiting(run, waiterByRun);\n if (waiting) result[run.id] = waiting;\n }\n return result;\n }\n\n /** Every group the engine knows about — unscoped. A tenant proxy's request is scoped by the\n * `RunRequestResponder` (to the requester's `@<tenant>` groups); the operator's own UI sees all. */\n workerHealth(): Promise<GroupHealth[]> {\n return this.engine.workerHealth();\n }\n\n cancel(runId: string, opts?: { compensate?: boolean }): Promise<RunResult | null> {\n return this.engine.cancel(runId, opts);\n }\n\n /** Re-enqueue (dispatch model) instead of resuming inline — a worker picks the run up and replays it. */\n retry(runId: string): Promise<RunResult | null> {\n return this.engine.requeue(runId);\n }\n\n continue(runId: string): Promise<RunResult | null> {\n return this.engine.continue(runId);\n }\n\n retryWithInput(runId: string, input: unknown): Promise<{ runId: string } | null> {\n return this.engine.retryWithInput(runId, input);\n }\n\n redispatchPending(runId: string): Promise<(RunResult & { redispatched: number }) | null> {\n return this.engine.redispatchPending(runId);\n }\n\n republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult> {\n return this.engine.republishLifecycle(target);\n }\n\n /** The persisted schedules (`[]` when the store does not persist them). */\n async listSchedules(query: ScheduleListQuery): Promise<ScheduleDescription[]> {\n return this.engine.schedules?.supported ? this.engine.schedules.list(query) : [];\n }\n\n async getSchedule(id: string): Promise<ScheduleDescription | null> {\n if (!this.engine.schedules?.supported) return null;\n return (await this.engine.schedules.get(id)) ?? null;\n }\n\n scheduleAction(id: string, action: ScheduleAction): Promise<ScheduleDescription | RunResult> {\n if (action === 'pause') return this.engine.schedules.pause(id);\n if (action === 'resume') return this.engine.schedules.resume(id);\n if (action === 'trigger') return this.engine.schedules.trigger(id);\n return Promise.reject(new Error(`unknown schedule action ${String(action)}`));\n }\n\n signal(token: string, payload: unknown): Promise<RunResult | null> {\n return this.engine.signal(token, payload);\n }\n\n async signalWaiter(token: string): Promise<string | null> {\n const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);\n return waiter?.runId ?? null;\n }\n\n /**\n * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a\n * run that does not exist yet are held until its row shows whose it is.\n */\n subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void {\n // Read the caller's tenant now: the events arrive outside its async context.\n const { tenantIds } = this.scoped({} as RunQuery);\n if (!tenantIds) {\n return this.engine.subscribe((event) => {\n if (event.runId === runId) onEvent(event);\n });\n }\n let visible: boolean | undefined; // undefined until the run's row has been read\n let held: EngineEvent[] = [];\n let checking = false;\n const check = (): void => {\n if (checking || visible !== undefined) return;\n checking = true;\n void this.store\n .getRun(runId)\n .then(\n (run) => {\n if (run) visible = tenantIds.includes(run.tenantId ?? null);\n },\n () => undefined,\n )\n .finally(() => {\n checking = false;\n if (visible === undefined) return;\n const pending = held;\n held = [];\n if (visible) for (const event of pending) onEvent(event);\n });\n };\n const off = this.engine.subscribe((event) => {\n if (event.runId !== runId || visible === false) return;\n if (visible) return onEvent(event);\n held.push(event);\n check();\n });\n check();\n return () => {\n held = [];\n off();\n };\n }\n}\n","import type { EngineEvent, StateStore, TenantEvent } from '@dudousxd/nestjs-durable-core';\n\n/** The narrow slice of `StateStore` the republisher needs — the `step.*`-event namespace fallback\n * (see {@link TenantEventRepublisher.namespaceFor}). Mirrors the `RunRequestTransport` narrowing\n * convention (`run-request-responder.ts`): depend on the smallest surface, not the whole store. */\nexport type RunLookupStore = Pick<StateStore, 'getRun'>;\n\n/** `EngineEvent` types that end a run's lifecycle — no further event for that `runId` will ever\n * follow one of these, so it is the safe point to drop the run from `TenantEventRepublisher`'s\n * namespace cache. Matches the terminal members of `EngineEventType` (`packages/core/src/interfaces.ts`)\n * exactly: `run.suspended` is NOT terminal (a suspended run resumes and emits more events), and\n * there is no separate `run.cancelled`/`run.dead` event type — both cancellation and dead-lettering\n * are published as `run.failed`. */\nfunction isTerminalRunEvent(event: EngineEvent): boolean {\n return event.type === 'run.completed' || event.type === 'run.failed';\n}\n\n/**\n * Re-publishes engine lifecycle events onto a run's per-tenant channel via `publish` (bound from\n * `Transport.publishTenantEvent`), so a store-less tenant worker can live-tail its OWN runs.\n *\n * The run's namespace is read straight off `event.namespace` (stamped by `engine.ts`'s `emit()` on\n * every `run.*` lifecycle event, where the run is already in hand); a `step.*` event doesn't carry\n * it, so those fall back to `store.getRun`. EVERY run's resolved namespace is memoized in\n * `runNamespaces` — including a bare/`default` run — so the store is read at most ONCE per run id\n * regardless of how many `step.*` events that run emits; a `null` cache entry means \"resolved, not\n * a tenant\" (distinct from \"not yet resolved\", i.e. absent from the map). A run's entry is deleted\n * the moment its terminal event is handled, so the cache stays bounded to in-flight runs (tenant and\n * default alike) — the same order of magnitude it was already paying for tenant runs alone, in\n * exchange for turning a per-event store read into a per-run one.\n */\nexport class TenantEventRepublisher {\n private readonly runNamespaces = new Map<string, string | null>();\n\n constructor(\n private readonly store: RunLookupStore,\n private readonly publish: (event: TenantEvent) => Promise<void>,\n ) {}\n\n async handle(event: EngineEvent): Promise<void> {\n const namespace = await this.namespaceFor(event);\n // A terminal run emits no further events — drop its cache entry now regardless of whether this\n // event was itself re-published, so the slot is reclaimed even for a bare/default run.\n if (isTerminalRunEvent(event)) this.runNamespaces.delete(event.runId);\n // Skip bare/default runs — no real tenant to re-publish to, and it would just be noise on an\n // unpartitioned operator.\n if (!namespace || namespace === 'default') return;\n await this.publish({ tenant: namespace, event }).catch(() => undefined);\n }\n\n private async namespaceFor(event: EngineEvent): Promise<string | undefined> {\n if (this.runNamespaces.has(event.runId)) {\n const cached = this.runNamespaces.get(event.runId);\n return cached === null ? undefined : cached;\n }\n if (event.namespace !== undefined) {\n this.runNamespaces.set(event.runId, event.namespace === 'default' ? null : event.namespace);\n return event.namespace;\n }\n const run = await this.store.getRun(event.runId);\n const tenantNamespace =\n run?.namespace !== undefined && run.namespace !== 'default' ? run.namespace : null;\n this.runNamespaces.set(event.runId, tenantNamespace);\n return tenantNamespace === null ? undefined : tenantNamespace;\n }\n}\n","import * as durableCore from '@dudousxd/nestjs-durable-core';\nimport {\n ANNOUNCED_SCHEDULE_TAG,\n DURABLE_OPTIONS_CANONICAL,\n type ScheduledWorkflow,\n WorkflowEngine,\n runSchedules,\n workflowName,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n Inject,\n Injectable,\n type OnApplicationBootstrap,\n type OnModuleDestroy,\n Optional,\n} from '@nestjs/common';\nimport type { DurableModuleOptions } from './durable.module';\nimport { isDrivingOperator } from './role';\nimport { settleWithin } from './settle-within';\nimport { SweepLeases } from './sweep-leases';\n\n/** What {@link TimerPoller.sweep} resolves when the sweep threw. */\nconst SWEEP_FAILED = Symbol('sweep failed');\n\n/**\n * The in-process schedules' next window (core `nextScheduleFireAt`), read off the module namespace\n * because an older core (the peer range is wide) does not export it; the poller then keeps the fixed\n * tick when `schedules` are configured.\n */\nconst nextScheduleFireAt = (\n durableCore as {\n nextScheduleFireAt?: (\n engine: object,\n schedules: readonly ScheduledWorkflow[],\n nowMs: number,\n ) => number | undefined;\n }\n).nextScheduleFireAt;\n\n/**\n * Resumes suspended runs whose durable timer (`ctx.sleep`) is due, and fires any configured\n * recurring `schedules` (plus the persisted `engine.schedules` when `persistedSchedules` is on) —\n * once on boot, then on an interval. Set `timerPollMs` to `0` to disable\n * the interval (e.g. when an external scheduler drives `WorkflowEngine.resumeDueTimers`).\n *\n * The boot poll is started, not awaited: `onApplicationBootstrap` runs before the host's HTTP server\n * listens, so a first poll held up by a large backlog would keep the pod from ever passing its\n * readiness probe. Shutdown still waits for whichever poll is in flight.\n *\n * While polls find nothing to do the wait between them backs off to `maxIdleIntervalMs` (default\n * 5 s), never past the next known due time and back to `timerPollMs` on any run event — see\n * {@link DurableModuleOptions.maxIdleIntervalMs}. The owed-lifecycle listing runs once per\n * `owedLifecycleSweepMs` (default 10 s) instead of on every poll.\n */\n@Injectable()\nexport class TimerPoller implements OnApplicationBootstrap, OnModuleDestroy {\n private timer?: ReturnType<typeof setInterval>;\n private polling = false;\n /** The sweep in flight, so shutdown can wait for it instead of racing the store's close. */\n private current: Promise<boolean> | undefined;\n private unsubscribeEnqueued?: () => void;\n private unsubscribeEvents?: () => void;\n /** Set by shutdown: the backoff loop stops scheduling polls. */\n private stopped = false;\n /** Something happened (a run event, an enqueue nudge) since the last poll started. */\n private activity = false;\n /** Ends the backoff loop's current wait early (set only while it waits). */\n private endWait: (() => void) | undefined;\n /** When the owed-lifecycle listing last succeeded (see {@link owedSweepDue}). */\n private owedSweptAt: number | undefined;\n /** When the tenant schedule announcements were last reconciled (see {@link announcedSchedules}). */\n private announcedSyncedAt: number | undefined;\n\n constructor(\n private readonly engine: WorkflowEngine,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n // Fleet-wide sweeps run under a `@nestjs/locks` lease when the app has `LocksModule` (detected).\n @Optional() private readonly leases: SweepLeases = new SweepLeases(),\n ) {}\n\n async onApplicationBootstrap(): Promise<void> {\n // A schedule whose `workflow` is a class that was never decorated would only fail on its first\n // fire, logged and retried every tick. Resolve every class now so the app fails to boot instead.\n for (const s of this.options.schedules ?? []) workflowName(s.workflow);\n // Drive suspended runs forward when this operator instance is DRIVING (defaults to true) — it\n // may execute locally or dispatch remotely (group-served / convention), either way it drives. A\n // non-driving (dashboard-only) operator, or a thin worker with no `store` at all, must not\n // resume timers — leave that to a driving instance.\n if (!isDrivingOperator(this.options)) return;\n // A driving instance consumes the transport's run queue when the transport carries one, so the\n // runs any instance starts (a `ctx.all` fan's children included), re-dispatches or finds due\n // spread over every driving instance. `engine.beginDrain` (below, at shutdown) stops it, and\n // the registrar's `drain` waits for the runs it holds within `shutdownTimeoutMs`. Optional for\n // an older core.\n this.engine.consumeRuns?.();\n // Low-latency dispatch: when a run is enqueued elsewhere (e.g. an API pod), pick it up at once\n // over the control plane instead of waiting for the next poll tick. Leasing dedups across workers.\n // The `.catch` is load-bearing, not decorative: this is fire-and-forget, so an unhandled\n // rejection here terminates the process under Node's default policy — and the run it could not\n // drive is still waiting for the next poll tick either way.\n //\n // `runEnqueued` is bounded and skips a run another instance already took; every instance\n // receives every announcement, so a wide fan would otherwise lease and replay every child here\n // at once. Optional for an older core.\n this.unsubscribeEnqueued = this.engine.onEnqueued((runId) => {\n this.noteActivity();\n if (typeof this.engine.runEnqueued === 'function') {\n this.engine.runEnqueued(runId);\n return;\n }\n void this.engine.runOne(runId).catch((error) => {\n console.error(`[nestjs-durable] could not run enqueued run ${runId}:`, error);\n });\n });\n const intervalMs = this.options.timerPollMs ?? 1_000;\n const maxIdleMs = this.options.maxIdleIntervalMs ?? 5_000;\n if (intervalMs > 0 && maxIdleMs > intervalMs && this.canBackOff()) {\n // Any run event, local or from another instance (control plane), ends an idle wait.\n this.unsubscribeEvents = this.engine.subscribe(() => this.noteActivity());\n void this.loop(intervalMs, maxIdleMs);\n return;\n }\n void this.poll();\n if (intervalMs > 0) {\n this.timer = setInterval(() => void this.poll(), intervalMs);\n this.timer.unref?.();\n }\n }\n\n /**\n * Whether polls may be spaced out while idle: the engine must reach new runs without the\n * pending-run poll and say when its next timer is due, and the in-process schedules must be able\n * to say when their next window is. Optional calls throughout: an older core keeps the fixed tick.\n */\n private canBackOff(): boolean {\n if (this.engine.idleBackoffSupported !== true) return false;\n if (typeof this.engine.nextDueAt !== 'function') return false;\n if ((this.options.schedules?.length ?? 0) > 0 && nextScheduleFireAt === undefined) return false;\n return true;\n }\n\n private noteActivity(): void {\n this.activity = true;\n this.endWait?.();\n }\n\n /**\n * Poll, then wait: `intervalMs` after a poll that found work (or while anything happened), else\n * twice the last wait up to `maxIdleMs`, cut short so the next poll runs no later than the earliest\n * known due time. A run event or an enqueue nudge ends a wait at once.\n */\n private async loop(intervalMs: number, maxIdleMs: number): Promise<void> {\n let wait = intervalMs;\n while (!this.stopped) {\n // Whatever arrived during the wait (it ended the wait) counts as this poll's work.\n const arrived = this.activity;\n this.activity = false;\n const worked = await this.poll();\n if (this.stopped) return;\n const idle = !worked && !arrived && !this.activity;\n wait = idle ? Math.min(wait * 2, maxIdleMs) : intervalMs;\n let next = wait;\n if (next > intervalMs) next = await this.untilDue(next, intervalMs);\n if (this.stopped) return;\n if (this.activity) next = Math.min(next, intervalMs); // something happened during the read\n await new Promise<void>((resolve) => {\n const done = () => {\n clearTimeout(timer);\n this.endWait = undefined;\n resolve();\n };\n const timer = setTimeout(done, next);\n timer.unref?.();\n // Only a wait longer than the regular tick is ended early; shutdown ends any.\n this.endWait = () => {\n if (this.stopped || next > intervalMs) done();\n };\n });\n }\n }\n\n /**\n * `wait`, shortened so the next poll runs no later than the earliest known due time: the engine's\n * next timer, blocked-run recovery poll or persisted schedule, and the next window of the\n * in-process `schedules`. Never below `intervalMs` (the regular tick catches what is due sooner). A\n * failed read keeps the regular tick.\n */\n private async untilDue(wait: number, intervalMs: number): Promise<number> {\n try {\n const now = Date.now();\n const stored = await this.engine.nextDueAt(now + wait, {\n persistedSchedules: this.options.persistedSchedules === true,\n announcedSchedules: this.announcedSchedules() !== undefined,\n });\n const schedules = this.options.schedules;\n const scheduled =\n schedules && schedules.length > 0 && nextScheduleFireAt\n ? nextScheduleFireAt(this.engine, schedules, now)\n : undefined;\n let due = wait;\n for (const at of [stored, scheduled]) {\n if (at !== undefined) due = Math.min(due, at - Date.now());\n }\n return Math.max(intervalMs, due);\n } catch {\n return intervalMs;\n }\n }\n\n /**\n * The tenant schedule adoption settings when it is on (see\n * {@link DurableModuleOptions.announcedSchedules}), else undefined: off by option, on a core\n * without it, or on a store that does not persist schedules.\n */\n private announcedSchedules(): { syncMs: number; graceMs: number | undefined } | undefined {\n const option = this.options.announcedSchedules;\n if (option === false) return undefined;\n if (typeof this.engine.syncAnnouncedSchedules !== 'function') return undefined;\n if (this.engine.schedules?.supported !== true) return undefined;\n const settings = typeof option === 'object' ? option : {};\n return { syncMs: settings.syncMs ?? 15_000, graceMs: settings.graceMs };\n }\n\n /**\n * Whether this poll lists the owed lifecycle runs: until a sweep that listed them succeeded, then\n * once per `owedLifecycleSweepMs` (a clock that went back lists them again).\n */\n private owedSweepDue(now: number): boolean {\n const every = this.options.owedLifecycleSweepMs ?? 10_000;\n const last = this.owedSweptAt;\n return every <= 0 || last === undefined || now < last || now - last >= every;\n }\n\n /**\n * Stop polling and wait for the sweep in flight (bounded by `shutdownTimeoutMs`, default 10s).\n * Nest runs every `onModuleDestroy` before any `onApplicationShutdown`, so returning here only once\n * the sweep has settled means no store call is still pending when the registrar drains and the\n * host closes its connection pool. The engine is told to stop first so a sweep working through a\n * backlog stops locking runs instead of finishing the backlog. The time spent waiting is deducted\n * from the later `engine.drain()`, so poll wait plus drain stay within one `shutdownTimeoutMs`.\n */\n async onModuleDestroy(): Promise<void> {\n this.stopped = true;\n if (this.timer) clearInterval(this.timer);\n this.endWait?.();\n this.unsubscribeEnqueued?.();\n this.unsubscribeEvents?.();\n // Only an operator that DRIVES the engine has a poll to wait for, and only it stops taking work\n // here. A non-driving operator (dashboard-only, `drive: false`) keeps running whatever its\n // finishing requests or `beforeApplicationShutdown` hooks start; `drain()` in the registrar\n // still waits for those.\n if (!isDrivingOperator(this.options)) return;\n // Optional call: an older core (the peer range is wide) has no `beginDrain`, and a TypeError here\n // would reject `app.close()` on Nest 10/11 before the registrar ever drains.\n this.engine.beginDrain?.();\n if (!this.current) return;\n const budget = this.options.shutdownTimeoutMs ?? 10_000;\n const started = Date.now();\n const timedOut = await settleWithin(this.current, budget);\n // Charge the drain only for the time spent waiting here, not for whatever Nest does between this\n // hook and the registrar's drain.\n this.engine.beginDrain?.(Date.now() - started);\n if (timedOut) {\n console.warn(\n `[nestjs-durable] timer poll still running after ${budget}ms at shutdown; continuing (it may report store errors if the host ends its pool now)`,\n );\n }\n }\n\n /**\n * One sweep of the engine's recovery work.\n *\n * **This method never rejects, and that is a hard requirement rather than defensiveness.** Both\n * callers (the boot kick-off and the interval) fire it as `void`, so a rejection would surface as\n * an unhandled rejection, which is fatal, and would re-occur on the next boot with the same state:\n * a single unrecoverable run would crash-loop every worker in the deployment, taking down every\n * other workflow with it. A poll that goes wrong must cost this tick, not the pod.\n *\n * Each sweep is isolated separately because they are independent: a store that fails\n * `recoverIncomplete` says nothing about whether durable timers should still fire, and skipping\n * the rest of the tick would silently widen one subsystem's outage into all of them.\n */\n private poll(): Promise<boolean> {\n if (this.polling) return this.current ?? Promise.resolve(true); // never overlap two sweeps\n this.polling = true;\n const run = this.pollOnce().finally(() => {\n this.polling = false;\n if (this.current === run) this.current = undefined;\n });\n this.current = run;\n return run;\n }\n\n /** One poll of every sweep. Resolves whether it found work (or a sweep failed): see {@link loop}. */\n private async pollOnce(): Promise<boolean> {\n let worked = false;\n // Work: a sweep returned runs (or run ids) it acted on, or failed (the loop keeps the regular\n // tick so the failure is retried soon).\n const note = (result: unknown) => {\n if (result === SWEEP_FAILED || (Array.isArray(result) && result.length > 0)) worked = true;\n };\n // Pick up runs enqueued elsewhere (an API pod's `start`, or another worker) still `pending`,\n // reclaim runs orphaned by a crashed worker (lease expired — a live worker renews its lease so\n // only dead ones are reclaimed), then resume due timers and sweep execution timeouts.\n note(await this.sweep('runPending', () => this.engine.runPending()));\n note(await this.sweep('recoverIncomplete', () => this.engine.recoverIncomplete()));\n note(await this.sweep('resumeDueTimers', () => this.engine.resumeDueTimers()));\n note(await this.sweep('sweepTimeouts', () => this.engine.sweepTimeouts()));\n // The stalled-run pager: throttled to a pass a minute inside the engine, a no-op without an\n // `onStalled` listener. Optional call: an older core (the peer range is wide) has no sweep.\n // One pod pages when `@nestjs/locks` is present (see SweepLeases); every pod otherwise.\n note(\n await this.sweep('sweepStalled', () =>\n this.leases.run('stalled-pager', async () => this.engine.sweepStalled?.()),\n ),\n );\n // Buffered child completions no parent will consume: a few pages per tick until a pass ends,\n // then a rest (throttled inside the engine). Optional call, like the stalled sweep.\n note(\n await this.sweep('sweepBufferedSignals', () =>\n this.leases.run('buffered-signals', async () => this.engine.sweepBufferedSignals?.()),\n ),\n );\n // Signal dedupe ids past their TTL (`signal(..., { id })`): a few bounded deletes per tick, one\n // pod at a time like the buffered-signals sweep.\n note(\n await this.sweep('sweepExpiredSignalIds', () =>\n this.leases.run('signal-ids', async () => this.engine.sweepExpiredSignalIds?.()),\n ),\n );\n // Lifecycle events a settled run still owes to a subscriber this instance has (its process\n // died before publishing, or did not have the subscriber), and `ctx.waitForRun` waits whose\n // run settled without resuming them. The owed listing (a tag filter over settled runs) and the\n // heal run once per `owedLifecycleSweepMs`; the run waits every poll. Only a listing that got\n // through starts the interval: a failed one is retried on the next poll. Optional call, like\n // the sweeps above (an older core ignores the third argument and sweeps everything).\n const now = Date.now();\n const owed = this.owedSweepDue(now);\n note(\n await this.sweep('sweepLifecycleEvents', async () => {\n const published = await this.engine.sweepLifecycleEvents?.(undefined, undefined, {\n owed,\n });\n if (owed) this.owedSweptAt = now;\n return published;\n }),\n );\n const schedules = this.options.schedules;\n if (schedules && schedules.length > 0) {\n note(await this.sweep('schedules', () => runSchedules(this.engine, schedules, Date.now())));\n }\n const announced = this.announcedSchedules();\n if (announced) {\n // Reconcile what tenant apps announce, once per `syncMs` and on one pod at a time when\n // `@nestjs/locks` is present. Only a sync that got through starts the interval.\n const at = Date.now();\n const last = this.announcedSyncedAt;\n if (last === undefined || at < last || at - last >= announced.syncMs) {\n await this.sweep('announcedSchedules', () =>\n this.leases.run('announced-schedules', async () => {\n await this.engine.syncAnnouncedSchedules({\n ...(announced.graceMs !== undefined ? { graceMs: announced.graceMs } : {}),\n });\n this.announcedSyncedAt = at;\n }),\n );\n }\n }\n if (this.options.persistedSchedules) {\n // Every persisted schedule, the adopted tenant ones included.\n note(await this.sweep('persistedSchedules', () => this.engine.schedules.tick()));\n } else if (announced) {\n note(\n await this.sweep('announcedScheduleFires', () =>\n this.engine.schedules.tick(Date.now(), { tag: ANNOUNCED_SCHEDULE_TAG }),\n ),\n );\n }\n return worked;\n }\n\n /** Run one sweep, absorbing and reporting its failure — see {@link poll}. */\n private async sweep(name: string, run: () => Promise<unknown>): Promise<unknown> {\n try {\n return await run();\n } catch (error) {\n console.error(`[nestjs-durable] timer poll: ${name} failed; continuing:`, error);\n return SWEEP_FAILED;\n }\n }\n}\n","import {\n DURABLE_OPTIONS_CANONICAL,\n RemoteWorkflowExecutor,\n STATE_STORE_CANONICAL,\n type StateStore,\n type WorkflowCtx,\n WorkflowEngine,\n type WorkflowRun,\n bindWorkflowClass,\n parseDuration,\n sanitizeQueueToken,\n tenantGroup,\n workflowName,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n Inject,\n Injectable,\n type OnApplicationBootstrap,\n type OnApplicationShutdown,\n type OnModuleInit,\n} from '@nestjs/common';\nimport { DiscoveryService, MetadataScanner } from '@nestjs/core';\nimport {\n type WorkflowMeta,\n eventBatchOf,\n getOnEvents,\n isDeadLetterHandler,\n onErrorCodesOf,\n} from './decorators';\nimport { scanWorkflows } from './discovery-helpers';\nimport type { DurableModuleOptions } from './durable.module';\nimport { entityConfigFor, getEntityMeta } from './entity';\nimport { IN_APP_WORKER_BINDING, type InAppWorkerBinding } from './in-app-worker';\nimport { onErrorHandlersOf } from './on-error-handlers';\nimport { isDrivingOperator, isOperatorRole } from './role';\nimport { type DurableStepInterceptor, isStepInterceptor } from './step-interceptor';\nimport { workflowIo } from './workflow-io';\n\ntype WorkflowFn = (ctx: WorkflowCtx, input: unknown) => Promise<unknown>;\n\n/**\n * Ensures the schema (auto-schema) and registers `@Workflow` providers on init, resumes runs left\n * incomplete by a previous process once booted, and drains in-flight runs on shutdown.\n *\n * For the shutdown drain to fire, enable Nest's shutdown hooks: `app.enableShutdownHooks()`.\n */\n/** How long after boot an onError route unserved at boot is checked again before it is reported. */\nconst UNSERVED_ROUTES_RECHECK_MS = 30_000;\n\n@Injectable()\nexport class WorkflowRegistrar\n implements OnModuleInit, OnApplicationBootstrap, OnApplicationShutdown\n{\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly metadataScanner: MetadataScanner,\n private readonly engine: WorkflowEngine,\n @Inject(STATE_STORE_CANONICAL) private readonly store: StateStore | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n // Group-served binding when the app opted into an in-app worker (uniform dispatch); null = inline.\n @Inject(IN_APP_WORKER_BINDING) private readonly inAppWorker: InAppWorkerBinding | null,\n ) {}\n\n async onApplicationBootstrap(): Promise<void> {\n // Recover runs left incomplete by a crash/deploy when this operator instance is DRIVING\n // (defaults to true). A non-driving (dashboard-only) operator, or a thin worker with no `store`\n // at all, must not pick up and re-run workflows — leave that to a driving instance.\n if (!isDrivingOperator(this.options)) return;\n await this.engine.recoverIncomplete();\n }\n\n /** On deploy/shutdown: stop picking up new runs and wait for in-flight ones to settle, then close\n * the transport(s) so the broker workers stop consuming and connections are released. Closing\n * AFTER the drain keeps the transport alive while in-flight runs dispatch/await their remote steps.\n * Operator only — a thin worker (no `store`) holds no engine to drain. */\n async onApplicationShutdown(): Promise<void> {\n if (!isOperatorRole(this.options)) return;\n await this.engine.drain(this.options.shutdownTimeoutMs);\n const transports = [\n this.options.transport,\n ...(this.options.transports ?? []).map((t) => t.transport),\n ];\n await Promise.allSettled(transports.map((t) => t?.close?.()));\n }\n\n async onModuleInit(): Promise<void> {\n // Operator only — a thin worker (no `store`) registers its bodies on a `DurableWorkerRuntime`\n // instead (see `durable-worker.module.ts`'s `ThinWorkflowRegistrar`), never on this engine.\n if (!isOperatorRole(this.options)) return;\n const store = this.store;\n if (!store) {\n throw new Error(\n 'unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set',\n );\n }\n if (this.options.autoSchema !== false) {\n await store.ensureSchema?.();\n }\n // Maps a workflow name to the workflow its dead runs route to. Built from each `@Workflow`'s\n // inline `@DeadLetter()` method (preferred) or its `deadLetterWorkflow` reference; the\n // module-level `deadLetterWorkflow` is the fallback applied in the onDead listener below.\n const deadLetterByWorkflow = new Map<string, string>();\n\n // Pre-pass: wire interceptors and register @Entity providers (engine-only concerns).\n for (const wrapper of this.discovery.getProviders()) {\n const { instance } = wrapper;\n if (!instance || typeof instance !== 'object') continue;\n if (isStepInterceptor(instance.constructor)) {\n const interceptor = instance as DurableStepInterceptor;\n this.engine.use((invocation, next) => interceptor.intercept(invocation, next));\n }\n const entityMeta = getEntityMeta(instance.constructor);\n if (entityMeta) {\n this.engine.registerEntity(entityMeta.name, entityConfigFor(instance.constructor));\n }\n }\n\n // Workflows whose declaring package could not be derived — reported once, after the scan.\n const unattributed: string[] = [];\n\n // Workflow registration pass — shared scan, engine-specific registration callback.\n scanWorkflows(this.discovery, (meta, workflow, origin) => {\n if (origin === undefined) unattributed.push(meta.name);\n // `input`/`output` schemas: checked at start, and parsed around the body on every turn.\n const io = workflowIo(meta);\n const body = io.wrap((ctx, input) => workflow.run(ctx, input));\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const workflowCtor: object = (workflow as any).constructor as object;\n const eventBatch = eventBatchOf(meta, workflowCtor);\n // Each `@OnError` method is a durable workflow of its own, inline like an `@DeadLetter` one.\n const onError = onErrorHandlersOf(meta, workflow as unknown as object, this.metadataScanner);\n for (const [name, fn] of onError.handlers) {\n this.engine.register(name, meta.version, fn, { origin });\n }\n this.engine.register(meta.name, meta.version, body, {\n // Stamped onto every run this workflow starts (see `WorkflowRun.origin`). Derived from the\n // class's declaring file, so a lib gets attributed without opting in; `undefined` when it\n // could not be derived, which the engine records as unknown rather than defaulting.\n origin,\n tags: meta.tags,\n singleton: meta.singleton,\n concurrency: meta.concurrency,\n executionTimeout: meta.executionTimeout,\n requires: meta.requires,\n validateInput: io.validateAtStart,\n searchAttributesSchema: meta.searchAttributes,\n onEvent: getOnEvents(meta, workflowCtor),\n eventBatch,\n onError: onError.routes,\n // Uniform dispatch (opt-in): when an in-app worker is configured, register the body GROUP-SERVED\n // so the engine dispatches its turns over the transport instead of running it inline; the\n // co-located worker consumer (Task 5: one queue PER REGISTERED NAME) replays the same body.\n // The routing token — and the executor that dispatches under it — MUST be keyed by THIS\n // workflow's own name (`tenantGroup(sanitizeQueueToken(meta.name), partition)`), not a single\n // group shared across every discovered `@Workflow`: a fixed shared token would dispatch every\n // workflow's turns to one queue while the co-located worker subscribes one queue per name,\n // so a turn dispatched under the wrong token would never be consumed. Absent → the inline fast\n // path (unchanged).\n ...(this.inAppWorker\n ? {\n group: tenantGroup(sanitizeQueueToken(meta.name), this.inAppWorker.partition),\n executor: new RemoteWorkflowExecutor(\n this.inAppWorker.transport,\n meta.name,\n this.inAppWorker.partition,\n ),\n }\n : {}),\n });\n\n // Class-first statics (`MyWorkflow.start()` / `.execute()`): bind the class to THIS engine,\n // so the statics resolve the engine that registered it — no global engine singleton.\n bindWorkflowClass(workflowCtor as new () => object, {\n start: (name, input, runId, opts) => this.engine.start(name, input, runId, opts),\n waitForRun: (runId, opts) => this.engine.waitForRun(runId, opts),\n });\n\n const inline = this.findDeadLetterHandler(workflow as unknown as object);\n if (inline && meta.deadLetterWorkflow) {\n // Two dead-letter targets for one workflow is ambiguous config, not a precedence question —\n // fail fast at boot rather than silently picking one.\n throw new Error(\n `@Workflow ${meta.name} declares both an inline @DeadLetter() method and a deadLetterWorkflow option. Use one: the inline handler, or the reference.`,\n );\n }\n if (inline) {\n // The inline handler is itself a durable workflow, registered as `<name>.dlq`, so it gets\n // checkpointing and a dashboard run linked to the dead run via the `dlq:<runId>` id.\n const dlqName = `${meta.name}.dlq`;\n // Declared on the very same class, so it carries the same origin.\n this.engine.register(dlqName, meta.version, inline, { origin });\n deadLetterByWorkflow.set(meta.name, dlqName);\n } else if (meta.deadLetterWorkflow) {\n deadLetterByWorkflow.set(meta.name, workflowName(meta.deadLetterWorkflow));\n }\n });\n\n this.reportUnattributed(unattributed);\n void this.reportUnservedOnErrorRoutes();\n this.installDeadLetterRouting(deadLetterByWorkflow);\n }\n\n /**\n * Says, once at boot, which workflows could not be attributed to a package — their runs are stamped\n * with no `origin` at all, so an operator filtering the dashboard by origin will not see them. That\n * is the deliberate trade (an absent origin over an invented one), but it has to be visible: a\n * silently-dropped run is indistinguishable from a run that never happened.\n */\n private reportUnattributed(names: string[]): void {\n if (names.length === 0) return;\n console.warn(\n `[nestjs-durable] could not derive an origin (declaring package) for ${names.length} workflow(s): ${names.join(', ')}. Their runs carry no origin and will not match an origin filter.`,\n );\n }\n\n /**\n * Says, once after boot, which onError routes name a handler workflow nothing can run, so a typo is\n * caught before the first failure goes nowhere. Routes unserved at boot are checked again after\n * {@link UNSERVED_ROUTES_RECHECK_MS}, so a handler whose workers start after this process is not\n * reported.\n */\n async reportUnservedOnErrorRoutes(recheckMs = UNSERVED_ROUTES_RECHECK_MS): Promise<void> {\n if ((await this.engine.unservedOnErrorRoutes().catch(() => [])).length === 0) return;\n await new Promise<void>((resolve) => setTimeout(resolve, recheckMs).unref());\n const unserved = await this.engine.unservedOnErrorRoutes().catch(() => []);\n if (unserved.length === 0) return;\n const list = unserved\n .map(({ workflow, route }) => `${workflow} → ${route.workflow} (code ${route.code ?? '*'})`)\n .join(', ');\n console.warn(\n `[nestjs-durable] ${unserved.length} onError route(s) name a handler workflow that is not registered here and has no live worker: ${list}.`,\n );\n }\n\n /** Returns the instance's `@DeadLetter()` method bound to the instance, or undefined if none. */\n private findDeadLetterHandler(instance: object): WorkflowFn | undefined {\n const prototype = Object.getPrototypeOf(instance);\n for (const methodName of this.metadataScanner.getAllMethodNames(prototype)) {\n const method = (instance as Record<string, unknown>)[methodName];\n if (typeof method === 'function' && isDeadLetterHandler(method)) {\n return (ctx, input) => method.call(instance, ctx, input);\n }\n }\n return undefined;\n }\n\n /**\n * Installs a single onDead listener that routes a dead run to its workflow's handler (from the\n * map) or the module-level `deadLetterWorkflow` default. The handler is started idempotently with\n * a `dlq:<runId>` id, so re-recovery never double-dispatches.\n */\n private installDeadLetterRouting(byWorkflow: Map<string, string>): void {\n const fallback = this.options.deadLetterWorkflow\n ? workflowName(this.options.deadLetterWorkflow)\n : undefined;\n if (byWorkflow.size === 0 && !fallback) return;\n this.engine.onDead((run: WorkflowRun) => {\n const target = byWorkflow.get(run.workflow) ?? fallback;\n if (!target) return;\n void this.engine\n .start(\n target,\n { deadRunId: run.id, workflow: run.workflow, input: run.input, error: run.error },\n `dlq:${run.id}`,\n // Route the dead-letter handler to the dead run's OWN tenant so an operator dispatches it to\n // that tenant's worker group (`target@<tenant>`), not the bare group.\n { namespace: run.namespace },\n )\n .catch(() => undefined);\n });\n }\n}\n","import type { StepInvocation } from '@dudousxd/nestjs-durable-core';\nimport 'reflect-metadata';\n\nexport const STEP_INTERCEPTOR_METADATA = Symbol('nestjs-durable:step-interceptor');\n\n/**\n * The shape a `@StepInterceptor()` provider must implement: `intercept(invocation, next)` wraps the\n * real execution of every local `ctx.step` (call `next()` to run the step body / next interceptor,\n * and return — or transform — its result). The engine-level {@link StepInterceptor} primitive, with\n * NestJS dependency injection.\n */\nexport interface DurableStepInterceptor {\n intercept(invocation: StepInvocation, next: () => Promise<unknown>): Promise<unknown>;\n}\n\n/**\n * Marks an `@Injectable()` class as a durable step interceptor. The module discovers it on boot and\n * registers its `intercept` method with the engine (so it can inject loggers/tracers/etc.). First\n * declared is outermost. Interceptors fire only when a step actually executes, never on replay.\n */\nexport function StepInterceptor(): ClassDecorator {\n return (target) => {\n Reflect.defineMetadata(STEP_INTERCEPTOR_METADATA, true, target);\n };\n}\n\n// biome-ignore lint/complexity/noBannedTypes: matches reflect-metadata's class target type\nexport function isStepInterceptor(target: Function): boolean {\n return Reflect.getMetadata(STEP_INTERCEPTOR_METADATA, target) === true;\n}\n","import { randomUUID } from 'node:crypto';\nimport {\n type RepublishLifecycleResult,\n type RepublishLifecycleTarget,\n type RunResult,\n type SignalOptions,\n type StartOptions,\n type WorkflowClass,\n WorkflowEngine,\n type WorkflowInputOf,\n} from '@dudousxd/nestjs-durable-core';\nimport { Injectable } from '@nestjs/common';\n\n/** Public entry point for starting and resuming workflow runs. */\n@Injectable()\nexport class WorkflowService {\n constructor(private readonly engine: WorkflowEngine) {}\n\n /**\n * Enqueue a workflow run — it creates the run (`pending`) and returns `{ runId, status: 'pending' }`\n * immediately; a worker executes the body (so the caller never blocks on workflow logic). Use\n * {@link waitForRun} when you need the outcome. Pass the workflow's **class**\n * (`start(CheckoutWorkflow, input)`) for a typed input + refactor-safety, or a **name** string for a\n * cross-runtime workflow. `runId` defaults to a random id; pass your own to make the start idempotent\n * (a redelivery returns the existing run). `opts.tags` are merged with the workflow's static\n * `@Workflow({ tags })`; `opts.searchAttributes` stamp typed, queryable run data.\n */\n start<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n runId?: string,\n opts?: StartOptions,\n ): Promise<RunResult>;\n start(workflow: string, input: unknown, runId?: string, opts?: StartOptions): Promise<RunResult>;\n start(\n workflow: string,\n input: unknown,\n runId: string = randomUUID(),\n opts?: StartOptions,\n ): Promise<RunResult> {\n return this.engine.start(workflow, input, runId, opts);\n }\n\n resume(runId: string): Promise<RunResult> {\n return this.engine.resume(runId);\n }\n\n /**\n * Resolve once a run settles — terminal (completed/failed/cancelled/dead) or suspended. `start`\n * only enqueues (a worker runs the body), so pair them when a request needs the outcome:\n * `const { runId } = await svc.start(...); const result = await svc.waitForRun(runId)`.\n * `until: 'terminal'` waits past suspensions until the run completes/fails/is cancelled — what a\n * delayed start (`opts.startAt`) needs, since it is `suspended` until its timer fires.\n */\n waitForRun(\n runId: string,\n opts?: { timeoutMs?: number; until?: 'settled' | 'terminal' },\n ): Promise<RunResult> {\n return this.engine.waitForRun(runId, opts);\n }\n\n /**\n * Deliver an external signal (e.g. from a webhook) to the run waiting on `token`, or buffer it for\n * the next wait on it. With `{ id }`, a re-send with the same token and id is dropped (resolves\n * `null`): see {@link SignalOptions}.\n */\n signal(token: string, payload: unknown, opts?: SignalOptions): Promise<RunResult | null> {\n return this.engine.signal(token, payload, opts);\n }\n\n /**\n * Ensure a run exists for `runId`, then deliver a signal to it — race-free (the signal is buffered\n * until the run reaches its `waitForSignal`). The durable-entity / accumulator pattern: one\n * long-lived run per key fed events by many calls. See {@link WorkflowEngine.signalWithStart}.\n */\n signalWithStart<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n runId: string,\n signal: { token: string; payload?: unknown },\n opts?: StartOptions,\n ): Promise<{ runId: string }>;\n signalWithStart(\n workflow: string,\n input: unknown,\n runId: string,\n signal: { token: string; payload?: unknown },\n opts?: StartOptions,\n ): Promise<{ runId: string }>;\n signalWithStart(\n workflow: string,\n input: unknown,\n runId: string,\n signal: { token: string; payload?: unknown },\n opts?: StartOptions,\n ): Promise<{ runId: string }> {\n return this.engine.signalWithStart(workflow, input, runId, signal, opts);\n }\n\n /**\n * Publish a named event. Resumes runs waiting on it via `ctx.waitForEvent(name, { match })` and\n * starts a fresh run of every workflow subscribed via `@Workflow({ onEvent })` / `@OnDurableEvent` (the\n * payload becomes its input). Pass `opts.id` to dedupe redeliveries. Returns how many runs it\n * touched (resumed + started).\n *\n * Reliable by default: a publish that touches NOBODY (no live waiter, no subscriber) buffers ONE\n * copy so a LATER `waitForEvent(name, { match })` still consumes it instead of it being dropped —\n * see {@link WorkflowEngine.publishEvent}'s full semantics doc. Pass `opts.buffer: false` to opt out.\n */\n publishEvent(\n name: string,\n payload: unknown,\n opts?: { id?: string; buffer?: boolean },\n ): Promise<number> {\n return this.engine.publishEvent(name, payload, opts);\n }\n\n /**\n * The runs started by `runId` settling, through `@OnWorkflowCompleted` / `@OnWorkflowFailed` (or\n * an `onEvent` on `runCompletedEvent(...)`). Only subscribers registered on this engine are\n * considered. For the reverse link, `lifecycleSourceOf(run)` reads it from the run itself.\n */\n triggeredRuns(runId: string): Promise<string[]> {\n return this.engine.triggeredRuns(runId);\n }\n\n /**\n * Publish settled runs' lifecycle events again: to a subscriber registered after they settled, or\n * one restricted by `subscriber`. Subscribers already started for a run are not started again.\n * See `WorkflowEngine.republishLifecycle`.\n */\n republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult> {\n return this.engine.republishLifecycle(target);\n }\n}\n","import {\n type ControlMessage,\n type ControlPlane,\n type DurableTopology,\n type EngineEvent,\n type FanPage,\n type FanPageQuery,\n type GroupHealth,\n type LifecycleKind,\n type RepublishLifecycleResult,\n type RepublishLifecycleTarget,\n type RunDetail,\n type RunDetailOptions,\n type RunFacetQuery,\n type RunFacetRow,\n type RunGateway,\n type RunListItem,\n type RunQuery,\n type RunReply,\n type RunRequestKind,\n type RunResult,\n type RunValueAxis,\n type RunValueFacetOptions,\n type RunValueFacetRow,\n type RunWaiting,\n type ScheduleAction,\n type ScheduleDescription,\n type ScheduleListQuery,\n type StateStore,\n type Transport,\n WorkflowEngine,\n type WorkflowLifecycleLinks,\n type WorkflowRun,\n} from '@dudousxd/nestjs-durable-core';\nimport { RunGatewayError } from './proxy-run-gateway';\nimport { StoreRunGateway } from './store-run-gateway';\n\n/** Options for {@link federatedAppGateway}. */\nexport interface FederatedAppGatewayOptions {\n /**\n * A handle on the app's state store, used for READS only (runs, timelines, facets, schedules).\n * Typically a store adapter over the app's schema with a database user granted `SELECT` on it.\n * Nothing on this handle is written: actions go to the app (see {@link transport}).\n */\n store: StateStore;\n /**\n * A transport on the app's broker and prefix (e.g. `new BullMQTransport({ connection, prefix })`\n * with the app's own `prefix`), dedicated to this gateway. It carries the actions to the app as run\n * requests, which the app's own engine answers and executes, plus its live run events and worker\n * health. The gateway consumes no queue on it: the app's work is never taken by the console.\n */\n transport: Transport;\n /**\n * The token presented as the requester of each action, for an app whose engine verifies tenants\n * (`verifyTenant`, e.g. `hmacTenantVerifier(secret)`): `(namespace) => signTenantToken(namespace,\n * secret)`. Called with the namespace of the run or schedule acted on. Omitted: the namespace\n * itself is sent, which an app without `verifyTenant` trusts.\n */\n tenantToken?: (namespace: string) => string | Promise<string>;\n /**\n * Where the app's engines broadcast their lifecycle events (its `controlPlane`): what the console's\n * live tail of an app run listens on. Default: {@link transport} when it can broadcast (BullMQ\n * can), which is also the app's default. Only listened to, never published on.\n */\n controlPlane?: ControlPlane;\n /** How long an action waits for the app to answer. Default 10000 ms. */\n timeoutMs?: number;\n}\n\ninterface Pending {\n resolve(data: unknown): void;\n reject(err: Error): void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * A `RunGateway` for ANOTHER app, for a federated console (the dashboard's `federation` option).\n * Reads come from the app's store; every action (cancel, retry, continue, signal, schedule\n * pause/resume/trigger, …) is published to the app over its broker as a run request, and the app's\n * own engine executes it, through the run-request responder every operator with a broker transport\n * already runs. The console process never drives, recovers or executes the app's runs.\n *\n * Each action names the namespace of the run (or schedule) it acts on as the requester, which the\n * app's responder checks the run against, exactly as it checks a tenant's request.\n */\nexport class FederatedAppGateway implements RunGateway {\n private readonly reads: StoreRunGateway;\n private readonly pending = new Map<string, Pending>();\n private listening = false;\n private readonly timeoutMs: number;\n /** Live-tail listeners by run id, fed by ONE subscription to the app's control channel. */\n private readonly tails = new Map<string, Set<(event: EngineEvent) => void>>();\n private tailing = false;\n\n constructor(private readonly options: FederatedAppGatewayOptions) {\n // An engine over the app's store with no transport and no driver: it only answers the reads\n // `StoreRunGateway` makes of it (children, lifecycle links). It starts no poller and consumes\n // nothing, so it never touches the app's runs.\n this.reads = new StoreRunGateway(options.store, new WorkflowEngine({ store: options.store }));\n this.timeoutMs = options.timeoutMs ?? 10_000;\n }\n\n topology(): DurableTopology {\n return { role: 'control-plane' };\n }\n\n getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null> {\n return this.reads.getRunDetail(runId, options);\n }\n\n getFanMembers(runId: string, group: string, query: FanPageQuery): Promise<FanPage | null> {\n return this.reads.getFanMembers(runId, group, query);\n }\n\n getRun(runId: string): Promise<WorkflowRun | null> {\n return this.reads.getRun(runId);\n }\n\n listRuns(query: RunQuery): Promise<RunListItem[]> {\n return this.reads.listRuns(query);\n }\n\n runFacets(query: RunFacetQuery): Promise<RunFacetRow[]> {\n return this.reads.runFacets(query);\n }\n\n runValueFacets(\n axis: RunValueAxis,\n query: RunFacetQuery,\n opts?: RunValueFacetOptions,\n ): Promise<RunValueFacetRow[]> {\n return this.reads.runValueFacets(axis, query, opts);\n }\n\n waitingFor(runIds: string[]): Promise<Record<string, RunWaiting>> {\n return this.reads.waitingFor(runIds);\n }\n\n workflowLifecycle(\n workflow: string,\n opts?: { namespace?: string | undefined },\n ): Promise<WorkflowLifecycleLinks> {\n return this.reads.workflowLifecycle(workflow, opts);\n }\n\n lifecycleSubscribers(\n workflow: string,\n kind: LifecycleKind,\n namespace: string,\n ): Promise<string[]> {\n return this.reads.lifecycleSubscribers(workflow, kind, namespace);\n }\n\n /** The app's worker groups, read from its broker (read-only). `[]` when the transport can't. */\n async workerHealth(): Promise<GroupHealth[]> {\n const { transport } = this.options;\n if (!transport.listWorkerGroups || !transport.groupHealth) return [];\n const groups = await transport.listWorkerGroups();\n return Promise.all(\n groups.map((group) => transport.groupHealth?.(group) as Promise<GroupHealth>),\n );\n }\n\n listSchedules(query: ScheduleListQuery): Promise<ScheduleDescription[]> {\n return this.reads.listSchedules(query);\n }\n\n getSchedule(id: string): Promise<ScheduleDescription | null> {\n return this.reads.getSchedule(id);\n }\n\n signalWaiter(token: string): Promise<string | null> {\n return this.reads.signalWaiter(token);\n }\n\n cancel(runId: string, opts?: { compensate?: boolean }): Promise<RunResult | null> {\n return this.onRun(runId, (namespace) =>\n this.request(\n namespace,\n opts === undefined ? { kind: 'cancel', runId } : { kind: 'cancel', runId, opts },\n ),\n );\n }\n\n retry(runId: string): Promise<RunResult | null> {\n return this.onRun(runId, (namespace) => this.request(namespace, { kind: 'retry', runId }));\n }\n\n continue(runId: string): Promise<RunResult | null> {\n return this.onRun(runId, (namespace) => this.request(namespace, { kind: 'continue', runId }));\n }\n\n retryWithInput(runId: string, input: unknown): Promise<{ runId: string } | null> {\n return this.onRun(runId, (namespace) =>\n this.request(namespace, { kind: 'retryWithInput', runId, input }),\n );\n }\n\n redispatchPending(runId: string): Promise<(RunResult & { redispatched: number }) | null> {\n return this.onRun(runId, (namespace) => this.request(namespace, { kind: 'redispatch', runId }));\n }\n\n async republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult> {\n let namespace: string | undefined;\n if ('runId' in target) {\n const run = await this.reads.getRun(target.runId);\n if (!run) throw new Error(`run ${target.runId} not found`);\n namespace = run.namespace || 'default';\n } else {\n namespace = target.namespace;\n if (namespace === undefined) {\n throw Object.assign(\n new Error('republish by workflow needs a namespace on a federated app'),\n {\n code: 'bad-request',\n },\n );\n }\n }\n return this.request(namespace, { kind: 'republishLifecycle', target });\n }\n\n /**\n * Pause, resume or trigger one of the app's persisted schedules, executed by the app. A schedule\n * that does not exist rejects with a `ScheduleNotFoundError`, as the engine's own client does.\n */\n async scheduleAction(\n id: string,\n action: ScheduleAction,\n ): Promise<ScheduleDescription | RunResult> {\n const schedule = await this.reads.getSchedule(id);\n if (!schedule) throw scheduleNotFound(id);\n try {\n return await this.request(schedule.namespace, { kind: 'schedule', id, action });\n } catch (err) {\n if (err instanceof RunGatewayError && err.code === 'not-found') throw scheduleNotFound(id);\n throw err;\n }\n }\n\n /**\n * Deliver `payload` to the app's run waiting on `token`, by the app. Null when no run of the app\n * waits on it yet: unlike the engine's own `signal`, nothing is buffered for a later wait.\n */\n async signal(token: string, payload: unknown): Promise<RunResult | null> {\n const runId = await this.reads.signalWaiter(token);\n if (!runId) return null;\n return this.onRun(runId, (namespace) =>\n this.request(namespace, { kind: 'signal', token, payload }),\n );\n }\n\n /**\n * The app's live events for `runId`, from the control channel its engines broadcast every event on\n * (see {@link FederatedAppGatewayOptions.controlPlane}). Nothing when there is none.\n */\n subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void {\n const control = this.controlPlane();\n if (!control) return () => undefined;\n if (!this.tailing) {\n this.tailing = true;\n control.onControl((msg) => this.deliver(msg));\n }\n let listeners = this.tails.get(runId);\n if (!listeners) {\n listeners = new Set();\n this.tails.set(runId, listeners);\n }\n listeners.add(onEvent);\n return () => {\n const current = this.tails.get(runId);\n current?.delete(onEvent);\n if (current?.size === 0) this.tails.delete(runId);\n };\n }\n\n private controlPlane(): ControlPlane | undefined {\n if (this.options.controlPlane) return this.options.controlPlane;\n const candidate = this.options.transport as Partial<ControlPlane>;\n return typeof candidate.onControl === 'function'\n ? (this.options.transport as unknown as ControlPlane)\n : undefined;\n }\n\n private deliver(msg: ControlMessage): void {\n if (this.tails.size === 0) return;\n const events = msg.kind === 'event' ? [msg.event] : msg.kind === 'events' ? msg.events : [];\n for (const event of events) {\n const listeners = this.tails.get(event.runId);\n if (!listeners) continue;\n // `at` crosses the wire as a string.\n const live = { ...event, at: new Date(event.at) };\n for (const listener of listeners) listener(live);\n }\n }\n\n /** `act` with the namespace of `runId`, or null when the app has no such run. */\n private async onRun<T>(\n runId: string,\n act: (namespace: string) => Promise<T | null>,\n ): Promise<T | null> {\n const run = await this.reads.getRun(runId);\n if (!run) return null;\n return act(run.namespace || 'default');\n }\n\n /** Send `body` to the app as a run request from `namespace`, and wait for its reply. */\n private async request<T>(namespace: string, body: RunRequestKind): Promise<T> {\n const { transport, tenantToken } = this.options;\n if (!transport.dispatchRunRequest || !transport.onRunReply) {\n throw new Error(\n 'a federated app needs a transport that carries run requests (e.g. BullMQTransport)',\n );\n }\n this.listen();\n const tenant = tenantToken ? await tenantToken(namespace) : namespace;\n return new Promise<T>((resolve, reject) => {\n const requestId = globalThis.crypto.randomUUID();\n const timer = setTimeout(() => {\n this.pending.delete(requestId);\n reject(new Error(`the app did not answer ${body.kind} within ${this.timeoutMs}ms`));\n }, this.timeoutMs);\n this.pending.set(requestId, {\n resolve: (data) => resolve(data as T),\n reject,\n timer,\n });\n transport.dispatchRunRequest?.({ requestId, tenant, body })?.catch((error: unknown) => {\n const entry = this.pending.get(requestId);\n if (!entry) return;\n clearTimeout(entry.timer);\n this.pending.delete(requestId);\n entry.reject(error instanceof Error ? error : new Error(String(error)));\n });\n });\n }\n\n private listen(): void {\n if (this.listening) return;\n this.listening = true;\n this.options.transport.onRunReply?.((reply) => this.handleReply(reply));\n }\n\n private handleReply(reply: RunReply): void {\n const entry = this.pending.get(reply.requestId);\n if (!entry) return;\n clearTimeout(entry.timer);\n this.pending.delete(reply.requestId);\n if (reply.result.ok) entry.resolve(reply.result.data);\n else entry.reject(new RunGatewayError(reply.result.error.message, reply.result.error.code));\n }\n}\n\nfunction scheduleNotFound(id: string): Error {\n return Object.assign(new Error(`schedule \"${id}\" not found`), { name: 'ScheduleNotFoundError' });\n}\n\n/**\n * A `RunGateway` over another app's store (reads) and broker (actions, executed by that app), for\n * the dashboard's `federation.apps`. See {@link FederatedAppGateway}.\n */\nexport function federatedAppGateway(options: FederatedAppGatewayOptions): FederatedAppGateway {\n return new FederatedAppGateway(options);\n}\n","export * from './attributes-of';\nexport * from './context-accessor';\nexport * from './decorators';\nexport { DurableStartClient } from './durable-start-client';\nexport * from './durable-worker.module';\nexport * from './durable.module';\nexport type {\n ContractClass,\n LazyContract,\n TenantCredentialsContract,\n TenantTokenOption,\n TenantVerifierContract,\n TenantVerifierInput,\n TenantVerifierOption,\n} from './tenant-contracts';\nexport * from './entity';\nexport * from './federated-app-gateway';\nexport * from './in-app-worker';\nexport * from './proxy-run-gateway';\nexport * from './role';\nexport type { DtoClass, IoSchema } from './schema-parse';\nexport * from './run-request-responder';\nexport * from './step-interceptor';\nexport * from './store-run-gateway';\nexport * from './tenant-event-republisher';\nexport * from './tokens';\nexport * from './workflow.service';\n\n// Facade re-exports: the everyday `@dudousxd/nestjs-durable-core` surface a consumer touches\n// alongside this package's own decorators/module/tokens, so e.g. the `Workflow` decorator (here)\n// and `WorkflowEngine`/`WorkflowCtx` (core) no longer require importing both packages to pick up the paired symbol. Additive only —\n// re-exports only what already exists on core's public index; core's own new exports (e.g. typed\n// search-attribute helpers) are surfaced there, not duplicated here.\n//\n// Anything in core that is a CLASS — `RunGateway` and `WorkflowEngine` are both abstract classes\n// that double as their own DI token — has to be re-exported below as a VALUE. Putting one in the\n// `export type` block breaks consumers in a way neither `tsc` nor a build catches: the emitted\n// `.d.ts` rollup drops the `type` modifier, so the name type-checks as a value, while the JS\n// bundle correctly omits it — `import { RunGateway } from '@dudousxd/nestjs-durable'` compiles\n// green and is `undefined` at runtime, and `moduleRef.get(undefined)` fails only on the code path\n// that resolves it. Keep classes here, types above.\nexport type {\n AttributeFilter,\n DynamicWorkflowCtx,\n EngineEvent,\n OnErrorInput,\n InferSearchAttributes,\n RunDetail,\n RunListItem,\n RunQuery,\n RunStatus,\n RunWaiting,\n SearchAttributes,\n SearchAttributesSchema,\n StepCheckpoint,\n StepEvent,\n StepLogger,\n WorkflowCtx,\n WorkflowHandler,\n RunSchedulesOptions,\n ScheduledWorkflow,\n TenantTokenSource,\n TenantVerifier,\n VerifiedTenant,\n WorkflowRun,\n EventSubscription,\n LifecycleEventOf,\n LifecycleKind,\n OnEventEntry,\n WorkflowLifecycleEvent,\n} from '@dudousxd/nestjs-durable-core';\nexport {\n DuplicateDurableCopyError,\n hmacTenantVerifier,\n LIFECYCLE_PENDING_TAG,\n lifecycleRunId,\n lifecycleSourceOf,\n prevCronFireMs,\n readSearchAttributes,\n RunGateway,\n runCompletedEvent,\n runFailedEvent,\n runSchedules,\n scheduledRunId,\n scheduleRunIdAt,\n signTenantToken,\n triggeredRunsOf,\n WorkflowEngine,\n} from '@dudousxd/nestjs-durable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Q,KAAK3G,QAAQ2E,IAAImC,MAAMZ,SAAS;AAC9C,QAAI,CAACS,MAAO;AACZC,iBAAaD,MAAML,KAAK;AACxB,SAAKtG,QAAQgF,OAAO8B,MAAMZ,SAAS;AACnC,QAAIY,MAAME,OAAOC,GAAIN,OAAMX,QAAQc,MAAME,OAAOR,IAAI;QAC/CG,OAAMV,OAAO,IAAIjC,gBAAgB8C,MAAME,OAAON,MAAMQ,SAASJ,MAAME,OAAON,MAAMhD,IAAI,CAAA;EAC3F;AACF;AAEA,SAASI,iBAAiBtB,IAAU;AAClC,SAAOgB,OAAOC,OAAO,IAAIF,MAAM,aAAaf,EAAAA,aAAe,GAAG;IAAE2E,MAAM;EAAwB,CAAA;AAChG;AAFSrD;AAQF,SAASsD,oBAAoB9G,SAAmC;AACrE,SAAO,IAAIR,oBAAoBQ,OAAAA;AACjC;AAFgB8G;;;AClShB,SACEC,2BACAC,oBACAC,uBACAC,gBACAC,qBAAAA,oBACAC,gBACAC,wBAAAA,uBACAC,cAAAA,aACAC,qBAAAA,oBACAC,kBAAAA,iBACAC,gBAAAA,eACAC,gBACAC,iBACAC,iBACAC,iBACAC,kBAAAA,uBACK;","names":["readSearchAttributes","DURABLE_STEP_CONFIG","DURABLE_STEP_NAME","WORKFLOW_NAME_KEY","parseDuration","runCompletedEvent","runFailedEvent","readFileSync","dirname","join","fileURLToPath","declaringFileByClass","WeakMap","packageNameByDir","Map","declaringFile","boundary","capture","Error","captureStackTrace","undefined","holder","topFrameFile","stack","rememberDeclaringFile","target","file","set","originOfClass","ctor","Object","getPrototypeOf","get","packageNameFor","originOfProvider","wrapper","fromMetatype","metatype","instance","start","dirname","visited","dir","has","cached","seen","push","name","readPackageName","join","parent","path","raw","readFileSync","parsed","JSON","parse","isRecord","length","value","line","split","frame","trim","startsWith","fileOfFrame","slice","match","exec","location","fileURLToPath","absolute","test","WORKFLOW_METADATA","Symbol","Workflow","options","declaredIn","declaringFile","target","rememberDeclaringFile","meta","name","version","deadLetterWorkflow","onError","tags","singleton","concurrency","executionTimeout","input","output","validateInput","searchAttributes","onEvent","debounce","batch","requires","Reflect","defineMetadata","Object","defineProperty","WORKFLOW_NAME_KEY","value","configurable","getWorkflowMeta","getMetadata","DURABLE_STEP_METADATA","stepConfigFrom","config","retries","backoff","backoffMs","backoffMaxMs","jitter","timeoutMs","hasAnyField","values","some","undefined","Step","nameOrOptions","propertyKey","descriptor","derivedName","String","DURABLE_STEP_NAME","DURABLE_STEP_CONFIG","getDurableStepMeta","method","DEAD_LETTER_METADATA","DeadLetter","_target","_propertyKey","isDeadLetterHandler","ON_ERROR_METADATA","OnError","match","code","Error","codes","onErrorCodesOf","ON_EVENT_METADATA","OnDurableEvent","events","addEventSubscriptions","OnWorkflowCompleted","workflow","onWorkflowSettled","runCompletedEvent","where","OnWorkflowFailed","statuses","accepts","event","includes","status","runFailedEvent","ON_EVENT_BATCH_METADATA","subscription","subscriberEventBatch","existing","sameEventBatch","mode","windowMs","parseDuration","key","maxSize","a","b","toString","eventBatchOf","declared","within","fromSubscription","entries","getOnEvents","fromDecorator","names","Set","filter","entry","has","add","attributesOf","workflow","run","meta","getWorkflowMeta","Error","name","searchAttributes","readSearchAttributes","resolveTenantToken","workflowName","Injectable","AsyncLocalStorage","SLOT","Symbol","for","accessorOf","accessor","slot","globalThis","current","undefined","readTenancy","option","a","tenancy","tenantFilter","enabled","own","inherit","options","kinds","family","required","bind","nullRows","filter","Object","keys","length","durableWork","AsyncLocalStorage","inDurableWork","fn","getStore","run","readTenancy","option","accessor","own","effective","required","readContextTenancy","isTenantRuntime","x","withTenant","TENANCY_SLOT","Symbol","for","tenancySlot","slot","globalThis","version","undefined","restorer","runtime","restore","tenant","family","ref","id","kind","source","buildEngineTenancy","current","t","enabled","f","filter","mode","tenantFilterNow","using","system","tenantId","nullRows","tenantFromCarrier","carrier","stepTenantWrapper","execution","next","unit","context","canRestoreTenant","currentTenant","RESOLVED","Symbol","markResolved","fn","Object","defineProperty","value","isResolved","isClass","method","proto","prototype","test","Function","toString","call","hasMethod","lazyDefault","undefined","target","default","instanceFactory","Class","moduleRef","pending","registered","get","strict","create","cause","Error","name","catch","contractInstance","instance","Promise","resolve","functionOrLazy","lazy","plain","probing","args","contract","result","probe","resolveTenantVerifier","option","input","verify","probed","requireToken","token","length","resolveTenantTokenSource","workerSdk","cause","Error","startRun","connection","options","runRedisWorker","createWorkerRuntime","DurableWorkerRuntime","Runtime","DurableStartClient","tenant","tenantToken","options","deps","accessor","partition","resolveTenantTokenSource","start","workflow","input","runId","globalThis","crypto","randomUUID","opts","name","workflowName","tenantId","undefined","id","kind","tenantKind","currentTenant","tenancy","startRun","connection","resolveTenantToken","prefix","tags","searchAttributes","version","priority","startAt","concurrency","startAtMs","Date","getTime","status","Number","isFinite","now","cancel","_runId","tenantUnsupported","deleteRun","resume","waitForRun","_opts","signal","_token","_payload","signalWithStart","_workflow","_input","_signal","publishEvent","_name","method","Promise","reject","Error","DURABLE_OPTIONS_CANONICAL","WorkflowEngine","bindWorkflowClass","resolveTenantToken","workflowName","Inject","Injectable","DiscoveryService","MetadataScanner","SchemaValidationError","schemaParser","schema","kind","label","code","isStandardSchema","value","result","validate","issues","SchemaValidationError","isZodLike","safeParse","success","error","data","classValidatorParser","Error","cls","cv","ct","Array","isArray","got","message","instance","plainToInstance","errors","whitelist","length","map","e","Object","values","constraints","_","property","join","path","String","summary","i","scanWorkflows","discovery","register","wrapper","getProviders","instance","meta","getWorkflowMeta","workflow","run","Error","name","originOfProvider","scanSteps","scanner","prototype","Object","getPrototypeOf","methodName","getAllMethodNames","method","getDurableStepMeta","boundMethod","parseInput","input","schemaParser","parseOutput","output","handler","log","validInput","call","workflowName","onErrorHandlersOf","meta","instance","scanner","handlers","routes","methodName","getAllMethodNames","Object","getPrototypeOf","method","codes","onErrorCodesOf","undefined","name","push","ctx","input","call","code","workflow","r","onError","workflowName","workflowIo","meta","parseInput","input","schemaParser","name","parseOutput","output","validateInput","validateAtStart","parsed","undefined","wrap","body","ctx","registerOnRuntime","runtime","scanner","meta","instance","origin","handlers","routes","onErrorHandlersOf","announced","version","undefined","body","workflowIo","wrap","ctx","input","run","subscribes","Set","getOnEvents","map","entry","event","registerWorkflow","name","requires","length","onError","code","workflow","fn","RunGateway","CONTEXT_ACCESSOR","Symbol","for","TENANT_AUTH","RUN_GATEWAY","RUN_REDIS_WORKER","Symbol","DURABLE_WORKER_RUNTIME","DURABLE_WORKER_RUNNERS","isPureThinWorker","options","store","undefined","connection","ThinWorkflowRegistrar","discovery","metadataScanner","runtime","starter","onModuleInit","scanWorkflows","meta","instance","origin","registerOnRuntime","bindWorkflowClass","start","name","input","runId","opts","ThinStepRegistrar","scanSteps","handler","registerStep","ThinWorkerBootstrap","runners","runRedisWorker","runnersSink","auth","onApplicationBootstrap","consumers","schedules","length","console","warn","handle","partition","prefix","instanceId","concurrency","tenantScheduleAnnouncement","tenantToken","push","onApplicationShutdown","Promise","allSettled","map","h","close","tenant","resolveTenantToken","error","Error","message","String","items","announcedSchedule","s","item","key","workflow","workflowName","everyMs","cron","timezone","paused","overlap","jitter","jitterMs","thinWorkerProviders","provide","useFactory","createWorkerRuntime","workflowGroup","inject","DURABLE_OPTIONS_CANONICAL","useValue","defaultRunRedisWorker","tenantGatewayUnavailable","method","reject","unavailableRunGateway","topology","role","getRunDetail","_runId","listRuns","_query","runFacets","runValueFacets","_axis","_opts","waitingFor","_runIds","workerHealth","cancel","retry","continue","retryWithInput","_input","redispatchPending","subscribe","_onEvent","DURABLE_OPTIONS","DURABLE_OPTIONS_CANONICAL","RunGateway","STATE_STORE","STATE_STORE_CANONICAL","TRANSPORT","TRANSPORT_CANONICAL","WorkflowEngine","sealDurableCopies","useDurableExecution","Inject","Injectable","Module","DiscoveryModule","ModuleRef","DURABLE_OPTIONS_CANONICAL","TRANSPORT_CANONICAL","Inject","Injectable","DiscoveryService","MetadataScanner","isOperatorRole","options","store","undefined","isDrivingOperator","drive","supportsHandle","transport","handle","DurableStepRegistrar","discovery","metadataScanner","options","onModuleInit","isDrivingOperator","scanSteps","meta","handler","name","partition","WorkflowEngine","Injectable","ENTITY_METADATA","Symbol","ENTITY_ON_METADATA","Entity","options","target","Reflect","defineMetadata","On","op","propertyKey","ctor","ops","getMetadata","Map","set","getEntityMeta","entityConfigFor","Cls","handlers","method","state","arg","Object","setPrototypeOf","prototype","fn","Error","call","initialState","EntityService","engine","signal","name","key","signalEntity","getState","getEntityState","DURABLE_OPTIONS_CANONICAL","TRANSPORT_CANONICAL","Inject","Injectable","DiscoveryService","MetadataScanner","IN_APP_WORKER_BINDING","Symbol","IN_APP_WORKER_RUNTIME","IN_APP_RUN_REDIS_WORKER","IN_APP_WORKER_RUNNERS","isCoLocatedWorker","options","store","undefined","connection","inAppWorkerBinding","transport","dispatchWorkflowTask","onDecision","Error","partition","InAppWorkerBootstrap","runners","discovery","metadataScanner","runtime","runRedisWorker","runnersSink","onModuleInit","scanWorkflows","meta","instance","origin","registerOnRuntime","scanSteps","handler","registerStep","name","onApplicationBootstrap","consumers","handle","prefix","instanceId","concurrency","push","onApplicationShutdown","Promise","allSettled","map","close","inAppWorkerProviders","provide","useFactory","inject","TRANSPORT_CANONICAL","DURABLE_OPTIONS_CANONICAL","createWorkerRuntime","workflowGroup","useValue","defaultRunRedisWorker","SUMMARY_CHILD_LIMIT","childIdsOf","pageFan","resolveTenantToken","scopeTenantQuery","summarizeTimeline","tenantVisible","Injectable","lifecycleKindOf","resolveWireTenant","UNSUPPORTED_RUN_REQUEST","BAD_RUN_REQUEST","TENANT_REPUBLISH_MAX_LIMIT","KNOWN_KINDS","Set","wireDate","value","undefined","date","Date","Number","isNaN","getTime","Error","String","scopeRunLinks","detail","tenant","own","link","namespace","bare","status","_status","_namespace","rest","awaitedBy","filter","_awaitedBy","source","triggeredBy","runId","kind","length","waitsFor","map","lifecycleDeliveries","RunRequestResponder","verifyTenant","transport","gateway","options","warnWithoutVerifier","console","warn","start","onRunRequest","msg","reply","handle","err","requestId","result","ok","error","message","publishRunReply","wire","resolveWireTenant","code","body","has","unsupported","data","listRuns","query","runFacets","runValueFacets","axis","opts","all","workerHealth","h","group","endsWith","workflowLifecycle","workflow","target","republishLifecycle","since","until","limit","isSafeInteger","badRequest","JSON","stringify","refused","refuseSubscriber","subscriber","Math","min","waitingFor","runIds","owned","Promise","Object","entries","waiting","owner","getRun","getRunDetail","run","entry","getSchedule","scheduleAction","action","schedule","call","id","answer","signal","signalWaiter","waiterRunId","token","waiter","runOf","payload","runIdOf","scopeLifecycle","getFanMembers","lifecycleKindOf","callVerb","input","lifecycleSubscribers","_links","_subscribers","links","subscribers","startsOnSettle","l","linked","startedBy","kinds","subscribes","k","includes","some","events","reject","cancel","retry","continue","retryWithInput","redispatchPending","RunGatewayError","Error","code","message","name","UnsupportedRunRequestError","isUnsupported","err","ProxyRunGateway","pending","Map","unsupportedUntil","transport","tenant","timeoutMs","capabilityTtlMs","tenantToken","tenantFilter","onRunReply","reply","handleReply","restrictive","filter","mode","undefined","scoped","query","send","Promise","reject","scopeTenantQuery","visible","run","tenantVisible","guarded","runId","call","hidden","then","getRunUnscoped","get","requestId","clearTimeout","timer","delete","result","ok","resolve","data","error","UNSUPPORTED_RUN_REQUEST","request","body","source","resolveTenantToken","globalThis","crypto","randomUUID","setTimeout","kind","set","dispatchRunRequest","catch","stillPending","String","topology","role","getRunDetail","options","detail","over","summarizeFansOver","fans","timeline","summarizeTimeline","ids","childIdsOf","children","slice","SUMMARY_CHILD_LIMIT","childCount","length","getFanMembers","group","knownUnsupported","page","Date","now","pageFan","getRun","until","listRuns","q","runFacets","runValueFacets","axis","opts","workerHealth","waitingFor","runIds","cancel","retry","continue","retryWithInput","input","redispatchPending","republishLifecycle","target","requestNewVerb","workflowLifecycle","workflow","notSupported","subscribe","onEvent","unsubscribe","onTenantEvent","evt","event","DURABLE_OPTIONS_CANONICAL","STATE_STORE_CANONICAL","TERMINAL_RUN_STATUSES","parseDuration","Inject","Injectable","Optional","settleWithin","p","timeoutMs","timer","timedOut","timeout","Promise","resolve","setTimeout","unref","race","then","undefined","clearTimeout","DURABLE_OPTIONS_CANONICAL","Inject","Injectable","Logger","Optional","ModuleRef","SweepLeases","logger","Logger","locks","leases","Map","moduleRef","options","run","sweep","fn","holds","undefined","get","held","delete","lock","acquire","key","error","warn","String","set","ns","namespace","onModuleInit","detect","log","specifier","mod","Locks","strict","DEFAULT_SWEEP_INTERVAL_MS","DEFAULT_BATCH_SIZE","MAX_BATCHES_PER_POLICY","validateRetention","retention","seen","Set","policy","policies","scopeKey","scope","stableKey","statuses","length","Error","maxAge","maxCount","parseDuration","status","TERMINAL_RUN_STATUSES","includes","join","key","has","add","value","Array","isArray","map","entries","Object","filter","v","undefined","sort","a","b","localeCompare","k","JSON","stringify","RetentionPoller","timer","sweeping","stopping","current","store","options","leases","SweepLeases","requireStore","onApplicationBootstrap","isDrivingOperator","pruneTerminalRuns","console","warn","sweep","intervalMs","sweepInterval","setInterval","unref","onModuleDestroy","clearInterval","budget","shutdownTimeoutMs","settleWithin","Promise","resolve","run","sweepOnce","finally","prune","error","batchSize","now","Date","batch","deleted","call","LIFECYCLE_REGISTRY_WORKFLOW","STATE_STORE_CANONICAL","SUMMARY_CHILD_LIMIT","WorkflowEngine","aggregatesCheckpoints","childIdsOf","etagMatches","extendEtag","fanPageEtag","indexWaitersByRun","lifecycleDeliveriesOf","lifecycleKindOf","lifecycleSourceOf","lifecycleTraceparentOf","listSignalWaitersOfRuns","mergeRunFacetRows","pageFan","pageFanFromStore","readRunsByIds","resolveRunWaiting","runDetailEtag","runWaitPrefix","runWaitTargetOf","summarizeRunFromStore","summarizeTimeline","traceIdOfTraceparent","Inject","Injectable","detailExtras","links","lifecycleSubscribers","lifecycleDeliveries","waitsFor","awaitedBy","triggeredBy","undefined","withoutRegistry","query","workflow","LIFECYCLE_REGISTRY_WORKFLOW","workflows","includes","excludeWorkflows","StoreRunGateway","store","engine","topology","role","scoped","scopeRunQuery","visibleRun","runId","run","getRun","tenantIds","tenantId","getRunDetail","options","lifecycleLinks","over","summarizeFansOver","timeline","children","Promise","all","listCheckpoints","getRunChildren","aggregatesCheckpoints","stats","checkpointStats","etag","extendEtag","runDetailEtag","etagMatches","ifNoneMatch","notModified","summarizeRunFromStore","full","fans","summarizeTimeline","ids","childIdsOf","slice","SUMMARY_CHILD_LIMIT","childCount","length","triggered","triggeredRuns","source","lifecycleSourceOf","kind","lifecycleKindOf","status","subscribers","namespace","workflowLifecycle","linked","startsOnSettle","startedBy","deliveries","lifecycleDeliveriesOf","live","Set","coalesced","coalescedSubscribers","own","onIt","listSignalWaitersOfRuns","id","startsWith","listSignalWaiters","runWaitPrefix","flatMap","w","target","runWaitTargetOf","seq","filter","map","started","d","state","runs","readRunsByIds","l","withRun","link","other","get","sourceRun","traceId","traceIdOfTraceparent","lifecycleTraceparentOf","tags","opts","getFanMembers","group","fanPageEtag","items","total","pageFanFromStore","pageFan","listRuns","waiterByRun","indexWaitersByRun","waiting","resolveRunWaiting","runFacets","mergeRunFacetRows","r","origin","count","runValueFacets","axis","waitingFor","runIds","idSet","suspended","waiters","statuses","result","has","workerHealth","cancel","retry","requeue","continue","retryWithInput","input","redispatchPending","republishLifecycle","listSchedules","schedules","supported","list","getSchedule","scheduleAction","action","pause","resume","trigger","reject","Error","String","signal","token","payload","signalWaiter","waiter","find","subscribe","onEvent","event","visible","held","checking","check","then","finally","pending","off","push","isTerminalRunEvent","event","type","TenantEventRepublisher","runNamespaces","Map","store","publish","handle","namespace","namespaceFor","delete","runId","tenant","catch","undefined","has","cached","get","set","run","getRun","tenantNamespace","durableCore","ANNOUNCED_SCHEDULE_TAG","DURABLE_OPTIONS_CANONICAL","WorkflowEngine","runSchedules","workflowName","Inject","Injectable","Optional","SWEEP_FAILED","Symbol","nextScheduleFireAt","TimerPoller","timer","polling","current","unsubscribeEnqueued","unsubscribeEvents","stopped","activity","endWait","owedSweptAt","announcedSyncedAt","engine","options","leases","SweepLeases","onApplicationBootstrap","s","schedules","workflowName","workflow","isDrivingOperator","consumeRuns","onEnqueued","runId","noteActivity","runEnqueued","runOne","catch","error","console","intervalMs","timerPollMs","maxIdleMs","maxIdleIntervalMs","canBackOff","subscribe","loop","poll","setInterval","unref","idleBackoffSupported","nextDueAt","length","undefined","wait","arrived","worked","idle","Math","min","next","untilDue","Promise","resolve","done","clearTimeout","setTimeout","now","Date","stored","persistedSchedules","announcedSchedules","scheduled","due","at","max","option","syncAnnouncedSchedules","supported","settings","syncMs","graceMs","owedSweepDue","every","owedLifecycleSweepMs","last","onModuleDestroy","clearInterval","beginDrain","budget","shutdownTimeoutMs","started","timedOut","settleWithin","warn","run","pollOnce","finally","note","result","Array","isArray","sweep","runPending","recoverIncomplete","resumeDueTimers","sweepTimeouts","sweepStalled","sweepBufferedSignals","sweepExpiredSignalIds","owed","published","sweepLifecycleEvents","runSchedules","announced","tick","tag","ANNOUNCED_SCHEDULE_TAG","name","DURABLE_OPTIONS_CANONICAL","RemoteWorkflowExecutor","STATE_STORE_CANONICAL","WorkflowEngine","bindWorkflowClass","sanitizeQueueToken","tenantGroup","workflowName","Inject","Injectable","DiscoveryService","MetadataScanner","STEP_INTERCEPTOR_METADATA","Symbol","StepInterceptor","target","Reflect","defineMetadata","isStepInterceptor","getMetadata","UNSERVED_ROUTES_RECHECK_MS","WorkflowRegistrar","discovery","metadataScanner","engine","store","options","inAppWorker","onApplicationBootstrap","isDrivingOperator","recoverIncomplete","onApplicationShutdown","isOperatorRole","drain","shutdownTimeoutMs","transports","transport","map","t","Promise","allSettled","close","onModuleInit","Error","autoSchema","ensureSchema","deadLetterByWorkflow","Map","wrapper","getProviders","instance","isStepInterceptor","interceptor","use","invocation","next","intercept","entityMeta","getEntityMeta","registerEntity","name","entityConfigFor","unattributed","scanWorkflows","meta","workflow","origin","undefined","push","io","workflowIo","body","wrap","ctx","input","run","workflowCtor","eventBatch","eventBatchOf","onError","onErrorHandlersOf","fn","handlers","register","version","tags","singleton","concurrency","executionTimeout","requires","validateInput","validateAtStart","searchAttributesSchema","searchAttributes","onEvent","getOnEvents","routes","group","tenantGroup","sanitizeQueueToken","partition","executor","RemoteWorkflowExecutor","bindWorkflowClass","start","runId","opts","waitForRun","inline","findDeadLetterHandler","deadLetterWorkflow","dlqName","set","workflowName","reportUnattributed","reportUnservedOnErrorRoutes","installDeadLetterRouting","names","length","console","warn","join","recheckMs","unservedOnErrorRoutes","catch","resolve","setTimeout","unref","unserved","list","route","code","prototype","Object","getPrototypeOf","methodName","getAllMethodNames","method","isDeadLetterHandler","call","byWorkflow","fallback","size","onDead","target","get","deadRunId","id","error","namespace","randomUUID","WorkflowEngine","Injectable","WorkflowService","engine","start","workflow","input","runId","randomUUID","opts","resume","waitForRun","signal","token","payload","signalWithStart","publishEvent","name","triggeredRuns","republishLifecycle","target","resolveAccessor","moduleRef","get","CONTEXT_ACCESSOR","strict","undefined","carrierFromAccessor","accessor","carrier","traceId","tenantId","tenant","source","userRef","contextSlotPresent","slot","globalThis","Symbol","for","current","isContextRuntime","x","deserialize","resolveContextRuntime","specifier","mod","Context","isControlPlane","publishControl","onControl","isScopeableStore","store","withScope","scopedStore","options","scopeReads","namespace","deferTransportConsumers","transport","deferrable","deferConsumers","console","warn","name","assertValidRole","hasStore","hasConnection","connection","Error","transports","TOPOLOGIES","assertValidTopology","topology","includes","hint","JSON","stringify","tenantToken","partition","length","verifyTenant","resolveTopology","servingPartition","resolveTopologyPreset","RunGatewayBootstrap","unsubscribe","engine","gateway","auth","onApplicationBootstrap","isDrivingOperator","onRunRequest","publishRunReply","publishTenantEvent","runRequestTransport","bind","RunRequestResponder","warnWithoutVerifier","start","republisher","TenantEventRepublisher","subscribe","event","handle","catch","onModuleDestroy","DurableTenancyBridge","unregister","tenancy","readTenancy","enabled","runtime","canRestoreTenant","useDurableExecution","stepTenantWrapper","isTenantRuntime","DurableModule","forRoot","sealDurableCopies","assertValid","build","provide","DURABLE_OPTIONS_CANONICAL","useValue","forRootAsync","useFactory","args","resolved","inject","optionsProvider","module","global","imports","DiscoveryModule","providers","STATE_STORE_CANONICAL","TRANSPORT_CANONICAL","TENANT_AUTH","resolveTenantVerifier","resolveTenantTokenSource","ModuleRef","STATE_STORE","useExisting","TRANSPORT","DURABLE_OPTIONS","WorkflowEngine","DurableStartClient","primary","context","runtimeNeeded","rehydrate","fn","Object","keys","consumers","t","map","n","controlPlane","leaseMs","admission","maxRecoveryAttempts","unregisteredWorkflowGraceMs","remoteAdvanceSilenceMs","remoteRedispatchMs","remoteRedispatchMax","reconcileMs","stalledAfterMs","timerBatchSize","eventBufferTtlMs","signalIdTtl","blockedPollMs","workerDescriptorCacheMs","trackStepStart","stickyRuns","stickyIdleMs","routeReplies","instanceId","webhookUrl","traceparent","buildEngineTenancy","compensationRetries","runDispatcher","drive","dispatch","queue","queues","registerQueue","onStalled","WorkflowService","EntityService","WorkflowRegistrar","DurableStepRegistrar","SweepLeases","TimerPoller","RetentionPoller","RunGateway","StoreRunGateway","ProxyRunGateway","runGatewayTimeoutMs","tenantFilterNow","unavailableRunGateway","inAppWorkerProviders","thinWorkerProviders","exports","WorkflowEngine","FederatedAppGateway","reads","pending","Map","listening","timeoutMs","tails","tailing","options","StoreRunGateway","store","WorkflowEngine","topology","role","getRunDetail","runId","getFanMembers","group","query","getRun","listRuns","runFacets","runValueFacets","axis","opts","waitingFor","runIds","workflowLifecycle","workflow","lifecycleSubscribers","kind","namespace","workerHealth","transport","listWorkerGroups","groupHealth","groups","Promise","all","map","listSchedules","getSchedule","id","signalWaiter","token","cancel","onRun","request","undefined","retry","continue","retryWithInput","input","redispatchPending","republishLifecycle","target","run","Error","Object","assign","code","scheduleAction","action","schedule","scheduleNotFound","err","RunGatewayError","signal","payload","subscribe","onEvent","control","controlPlane","onControl","msg","deliver","listeners","get","Set","set","add","current","delete","size","candidate","events","event","live","at","Date","listener","act","body","tenantToken","dispatchRunRequest","onRunReply","listen","tenant","resolve","reject","requestId","globalThis","crypto","randomUUID","timer","setTimeout","data","catch","error","entry","clearTimeout","String","reply","handleReply","result","ok","message","name","federatedAppGateway","DuplicateDurableCopyError","hmacTenantVerifier","LIFECYCLE_PENDING_TAG","lifecycleRunId","lifecycleSourceOf","prevCronFireMs","readSearchAttributes","RunGateway","runCompletedEvent","runFailedEvent","runSchedules","scheduledRunId","scheduleRunIdAt","signTenantToken","triggeredRunsOf","WorkflowEngine"]}
|
|
1
|
+
{"version":3,"sources":["../src/attributes-of.ts","../src/decorators.ts","../src/origin.ts","../src/durable-start-client.ts","../src/tenancy.ts","../src/tenancy-reader.ts","../src/tenant-contracts.ts","../src/worker-sdk.ts","../src/durable-worker.module.ts","../src/schema-parse.ts","../src/discovery-helpers.ts","../src/entity.ts","../src/runtime-registration.ts","../src/on-error-handlers.ts","../src/workflow-io.ts","../src/step-interceptor.ts","../src/tokens.ts","../src/durable.module.ts","../src/durable-step.registrar.ts","../src/role.ts","../src/in-app-worker.ts","../src/proxy-run-gateway.ts","../src/run-request-responder.ts","../src/retention-poller.ts","../src/settle-within.ts","../src/sweep-leases.ts","../src/store-run-gateway.ts","../src/tenant-event-republisher.ts","../src/timer-poller.ts","../src/workflow.registrar.ts","../src/workflow.service.ts","../src/federated-app-gateway.ts","../src/index.ts"],"sourcesContent":["import {\n type SearchAttributes,\n type WorkflowClass,\n type WorkflowCtx,\n readSearchAttributes,\n} from '@dudousxd/nestjs-durable-core';\nimport { getWorkflowMeta } from './decorators';\n\n/**\n * The search-attributes shape a `@Workflow` class declares — extracted from its `run` method's\n * `ctx: WorkflowCtx<A>` annotation, mirroring the `WorkflowInputOf`/`WorkflowOutputOf` structural-\n * typing idiom in core's `workflow-ref.ts` (which extract `run`'s `input`/return type the same way).\n * A class whose `run` leaves `ctx` untyped (or types it as the bare `WorkflowCtx`) resolves to the\n * untyped `SearchAttributes` default — matching `WorkflowCtx` itself.\n */\nexport type WorkflowAttributesOf<C> = C extends abstract new (\n ...args: never[]\n) => {\n run(ctx: WorkflowCtx<infer A>, input: never): unknown;\n}\n ? A\n : SearchAttributes;\n\n/**\n * Read a run's search attributes **by workflow class**, with the schema resolved from that class's\n * `@Workflow({ searchAttributes })` decorator metadata — the same single-source-of-truth idiom as\n * triggering a workflow by class (`ctx.child(ShippingWorkflow, input)`, `engine.start(CheckoutWorkflow,\n * input)`): the decorator is the one place the schema lives, and every reader references the\n * WORKFLOW, never re-imports or re-declares the schema itself. The return type is inferred\n * structurally from the class's `run(ctx: WorkflowCtx<A>, …)` annotation (see\n * {@link WorkflowAttributesOf}), so a valid read is typed to `A` with no explicit type argument.\n *\n * Delegates to core's `readSearchAttributes(schema, run)` for the actual read, so the same lenient\n * safe-parse semantics apply: a run whose stored `searchAttributes` predate the schema, or fail it,\n * reads back as `{}` rather than throwing (see `readSearchAttributes`'s doc comment).\n *\n * @throws if `workflow` isn't a `@Workflow`-decorated class (no metadata at all — nothing to resolve\n * the schema from).\n * @throws if `workflow` is a `@Workflow` class that never declared a `searchAttributes` schema —\n * reading attributes by class needs one to resolve against.\n *\n * @example\n * ```ts\n * import { z } from 'zod';\n * import { Injectable } from '@nestjs/common';\n * import {\n * attributesOf,\n * InferSearchAttributes,\n * Workflow,\n * WorkflowCtx,\n * WorkflowHandler,\n * } from '@dudousxd/nestjs-durable';\n *\n * const orderAttrs = z.object({ tier: z.enum(['free', 'pro']), amount: z.number() });\n * type OrderAttrs = InferSearchAttributes<typeof orderAttrs>;\n *\n * @Workflow({ name: 'checkout', searchAttributes: orderAttrs })\n * class CheckoutWorkflow implements WorkflowHandler<{ orderId: string }, void, OrderAttrs> {\n * async run(ctx: WorkflowCtx<OrderAttrs>, input: { orderId: string }): Promise<void> {\n * await ctx.upsertSearchAttributes({ tier: 'pro', amount: 100 });\n * }\n * }\n *\n * @Injectable()\n * class CheckoutDashboardService {\n * constructor(private readonly store: StateStore) {}\n *\n * async tierOf(runId: string) {\n * const run = await this.store.getRun(runId);\n * const attrs = attributesOf(CheckoutWorkflow, run ?? {}); // OrderAttrs\n * return attrs.tier;\n * }\n * }\n * ```\n */\nexport function attributesOf<C extends WorkflowClass>(\n workflow: C,\n run: { searchAttributes?: SearchAttributes | null | undefined },\n): WorkflowAttributesOf<C> {\n // biome-ignore lint/complexity/noBannedTypes: getWorkflowMeta reads reflect-metadata off the class target, same contract as workflowName/bindWorkflowClass\n const meta = getWorkflowMeta(workflow as unknown as Function);\n if (!meta) {\n throw new Error(\n `attributesOf: ${workflow.name} is not a @Workflow class — is it decorated with @Workflow({ name, searchAttributes })?`,\n );\n }\n if (!meta.searchAttributes) {\n throw new Error(\n `attributesOf: workflow '${meta.name}' declares no searchAttributes schema — reading attributes by class requires the workflow to declare its schema: @Workflow({ name: '${meta.name}', searchAttributes: mySchema }).`,\n );\n }\n return readSearchAttributes(meta.searchAttributes, run) as WorkflowAttributesOf<C>;\n}\n","import {\n type ConcurrencyConfig,\n DURABLE_STEP_CONFIG,\n DURABLE_STEP_NAME,\n type EventBatchConfig,\n type LifecycleEventOf,\n type OnErrorInput,\n type OnEventEntry,\n type SearchAttributesSchema,\n type SingletonConfig,\n type StepConfig,\n type StepError,\n WORKFLOW_NAME_KEY,\n type WorkflowClass,\n type WorkflowCtx,\n type WorkflowLifecycleEvent,\n type WorkflowRef,\n parseDuration,\n runCompletedEvent,\n runFailedEvent,\n} from '@dudousxd/nestjs-durable-core';\nimport 'reflect-metadata';\nimport { declaringFile, rememberDeclaringFile } from './origin';\nimport type { InferWorkflowInput, IoSchema } from './schema-parse';\n\nexport const WORKFLOW_METADATA = Symbol('nestjs-durable:workflow');\n\nexport interface WorkflowMeta {\n name: string;\n version: string;\n /** The workflow this workflow's dead runs route to (a name or a class). See `WorkflowOptions`. */\n deadLetterWorkflow?: WorkflowRef | undefined;\n /** Where failed runs are routed by error code. See `WorkflowOptions`. */\n onError?: { code?: string | ErrorClassWithCode; workflow: WorkflowRef }[] | undefined;\n /** Static searchable labels stamped on every run of this workflow. See `WorkflowOptions`. */\n tags?: string[] | undefined;\n /** Per-key serialization (a durable mutex). See `WorkflowOptions`. */\n singleton?: SingletonConfig | undefined;\n /** Start-time concurrency quota (rejecting). See `WorkflowOptions`. */\n concurrency?: ConcurrencyConfig | undefined;\n /** Max wall-clock lifetime before a run is cancelled (e.g. `'2h'`). See `WorkflowOptions`. */\n executionTimeout?: string | number | undefined;\n /** Input schema (Standard Schema or DTO class), parsed at start and before every turn. See\n * `WorkflowOptions`. */\n input?: IoSchema | undefined;\n /** Output schema, parsed before the run completes. See `WorkflowOptions`. */\n output?: IoSchema | undefined;\n /** Custom input validator (throws on invalid). See `WorkflowOptions`. */\n validateInput?: ((input: unknown) => void | Promise<void>) | undefined;\n /** Typed/validated `searchAttributes` shape. See `WorkflowOptions`. */\n searchAttributes?: SearchAttributesSchema | undefined;\n /** Events that start a fresh run of this workflow. See `WorkflowOptions`. */\n onEvent?: OnEventEntry[] | undefined;\n /** Debounce `onEvent` triggers — fire once it's quiet for this long. See `WorkflowOptions`. */\n debounce?: string | number | undefined;\n /** Batch `onEvent` triggers — fire on size or window. See `WorkflowOptions`. */\n batch?: { maxSize: number; within: string | number } | undefined;\n /** Capabilities a live worker must advertise to run this workflow's turns (handshake §7.5). See\n * `WorkflowOptions`. */\n requires?: string[] | undefined;\n}\n\n/**\n * `@Workflow` options. `S` is the `input` schema's type, inferred from the option: the `singleton`\n * and `concurrency` keys and `validateInput` then take the schema's parsed type (see\n * {@link InferWorkflowInput}); without an `input` schema they take `unknown`, as they always did.\n * Written without a type argument (`const opts: WorkflowOptions = …`, an interface extending it),\n * it accepts any `input` schema and the callbacks take `unknown`, as before.\n */\nexport interface WorkflowOptions<S extends IoSchema | undefined = IoSchema | undefined> {\n name: string;\n version?: string;\n /**\n * Route this workflow's dead-lettered runs to another **registered** workflow — by class\n * (`deadLetterWorkflow: CheckoutDlqWorkflow`, refactor-safe) or by name for a cross-runtime\n * handler. For a handler co-located on the same class, prefer an inline `@DeadLetter()` method\n * instead — it takes precedence, and declaring both is a boot-time error. The handler receives a\n * {@link DeadLetter} payload, idempotent by a `dlq:<runId>` id.\n */\n deadLetterWorkflow?: WorkflowRef;\n /**\n * Route failed runs of this workflow to other **registered** workflows by error code — the\n * separate-class form of an `@OnError` method (see it for the semantics). Each handler receives an\n * {@link OnErrorInput}; omit `code` for the catch-all. A code routed here and by an `@OnError`\n * method on the class is a boot-time error.\n */\n onError?: { code?: string | ErrorClassWithCode; workflow: WorkflowRef }[];\n /**\n * Static labels stamped on **every run** of this workflow (e.g. `tags: ['etl', 'critical']`) and\n * merged with any per-run tags passed to `start`. Searchable/filterable in the dashboard.\n */\n tags?: string[];\n /**\n * Serialize runs of this workflow that share a key — a durable FIFO mutex. e.g.\n * `singleton: { key: (input) => `base:${input.baseId}` }` runs at most one pipeline per base at a\n * time; same-key runs queue (suspended) and admit in creation order as slots free. `limit` (default\n * 1) raises the concurrency. With an `input` schema, `key` receives the parsed input (typed from\n * the schema, the same value `run` gets); without one, the input as sent (`unknown`).\n */\n singleton?: SingletonConfig<InferWorkflowInput<S>>;\n /**\n * A start-time concurrency QUOTA: at most `limit` runs sharing a key in flight, and a start over it\n * is REJECTED (`ConcurrencyLimitError`, nothing created) rather than queued. e.g.\n * `concurrency: { key: (input) => `tenant:${input.tenantId}`, limit: 8 }` caps what one tenant can\n * have executing at once. The key is shared across workflows; `limit` may be a (async) function of\n * the key for per-plan limits; `countStatuses` narrows what occupies a slot (default: every\n * non-terminal status). Use `singleton` instead when excess runs should wait their turn. With an\n * `input` schema, `key` receives the parsed input, typed from the schema, like `singleton`'s.\n */\n concurrency?: ConcurrencyConfig<InferWorkflowInput<S>>;\n /**\n * Max wall-clock lifetime for a run of this workflow (e.g. `'2h'`, `'7 days'`, or ms), counted from\n * the run's creation. A run that outlives it is moved to `cancelled` (`execution_timeout`) by the\n * timer poller — whether it is `pending`, `blocked`, `running` or `suspended` — a backstop for runs\n * that get stuck, loop forever or are never picked up. A run in `cancelling` finishes its saga undo\n * instead. Omit for no limit.\n */\n executionTimeout?: string | number;\n /**\n * Capabilities a live worker MUST advertise to run this workflow's turns (handshake design §7.5).\n * Only meaningful for a group-served / remote workflow (an in-app worker or a cross-runtime body):\n * the control-plane dispatches a turn only to a capability-capable + protocol-compatible worker, and\n * if descriptors are published on its group but none qualifies the run parks `blocked` until the\n * recovery poll finds one. Absent/empty = \"runs anywhere\" (a legacy fleet skips the guard, §7.7).\n */\n requires?: string[];\n /**\n * The run's input schema — a **Standard Schema** (zod 3.24+, valibot, arktype, …) or a\n * **class-validator DTO class** (the same `plainToInstance` + `validate` NestJS's `ValidationPipe`\n * runs; needs the optional peers `class-validator` + `class-transformer`). The same option\n * `@Step({ input })` takes.\n *\n * Parsed at `start`, so invalid input is rejected before any run is created. The run stores the\n * input **as it was sent**; `run(ctx, input)` receives the **parsed** value (coerced/transformed —\n * a `Date` from `z.coerce.date()`, a DTO instance), re-parsed from the stored input before every\n * turn, so a replay sees the same value the first execution did. The schema must therefore be\n * deterministic (no `default(() => Date.now())`), and changing it is a breaking change to the\n * workflow — bump `version`. A stored input that no longer parses fails the run with\n * `code: 'invalid_input'`.\n *\n * `@Workflow({ name: 'checkout', input: CheckoutInput })` or `input: z.object({ … })`. Type `run`'s\n * input from the same schema with `InferWorkflowInput<typeof CheckoutInput>`.\n */\n input?: S;\n /**\n * The run's output schema (same forms as {@link input}). The value `run()` returns is parsed before\n * the run completes, and the parsed value is what the run stores as its output. A mismatch fails the\n * run with `code: 'invalid_output'`. The same option `@Step({ output })` takes.\n */\n output?: IoSchema;\n /**\n * A custom check at `start` (throw to reject) for a rule a schema can't express — a cross-field\n * invariant, an async lookup. It runs after `input` parses and receives the parsed value (the input\n * as sent when there is no `input` schema), typed from the schema.\n */\n validateInput?: (input: InferWorkflowInput<S>) => void | Promise<void>;\n /**\n * Validate this workflow's {@link WorkflowCtx.upsertSearchAttributes} writes against a **Standard\n * Schema** (https://standardschema.dev — zod 3.24+, valibot, arktype, …). `ctx.upsertSearchAttributes`\n * validates the MERGED result (existing attributes shallow-merged with the patch) on every call —\n * an invalid merge throws a `SchemaValidationError` (code `schema_validation`) naming this workflow,\n * with the schema's issues. The\n * schema's inferred output must be search-attribute-shaped (flat `string`/`number`/`boolean` values\n * only) — a schema whose output has a nested object/array is a compile-time error here. Omit for\n * the prior unvalidated behavior.\n *\n * ```ts\n * import { z } from 'zod';\n *\n * const orderAttrs = z.object({\n * tier: z.enum(['free', 'pro']),\n * amount: z.number(),\n * });\n *\n * @Workflow({ name: 'checkout', searchAttributes: orderAttrs })\n * class CheckoutWorkflow {\n * async run(ctx: WorkflowCtx<InferSearchAttributes<typeof orderAttrs>>, input: CheckoutInput) {\n * await ctx.upsertSearchAttributes({ tier: input.tier, amount: input.total });\n * }\n * }\n * ```\n */\n searchAttributes?: SearchAttributesSchema;\n /**\n * Start a fresh run of this workflow whenever any of these events is published via\n * `publishEvent(name, payload)` — the payload becomes the run's input. e.g.\n * `onEvent: ['user.registered', 'user.invited']`. The same subscription can also be declared with\n * the `@OnDurableEvent(...)` class decorator; the two are merged. An entry can also be\n * `{ event, where }`, where `where(payload)` decides per event whether this workflow starts.\n */\n onEvent?: OnEventEntry[];\n /**\n * Coalesce `onEvent` triggers by **debouncing** — start one run only once events have been quiet\n * for this long (resets on each event), with the LAST payload. e.g. `debounce: '30s'`.\n */\n debounce?: string | number;\n /**\n * Coalesce `onEvent` triggers by **batching** — start one run with all payloads (`{ events: [...] }`)\n * once `maxSize` is reached or `within` elapses from the first event. e.g.\n * `batch: { maxSize: 100, within: '10s' }`.\n */\n batch?: { maxSize: number; within: string | number };\n}\n\n/**\n * Marks a provider class as a durable workflow. Its `run(ctx, input)` method becomes the\n * workflow function the engine executes and replays.\n */\nexport function Workflow<S extends IoSchema | undefined = undefined>(\n options: WorkflowOptions<S>,\n): ClassDecorator {\n // Captured HERE, in the factory, because this is the one moment we are provably executing inside\n // the module that declares the workflow — by the time a registrar scans providers, the only thing\n // left of that module is a class object with no file on it. The path is resolved to the owning\n // package lazily, at registration (see `origin.ts`); a runtime that yields no usable frame simply\n // leaves the workflow unattributed, which the registrar reports at boot.\n const declaredIn = declaringFile(Workflow);\n return (target) => {\n rememberDeclaringFile(target, declaredIn);\n const meta: WorkflowMeta = {\n name: options.name,\n version: options.version ?? '1',\n deadLetterWorkflow: options.deadLetterWorkflow,\n onError: options.onError,\n tags: options.tags,\n // The typed callbacks are stored erased: the engine calls them with the parsed input, which is\n // exactly the type `S` gave them (see `workflowIo`).\n singleton: options.singleton as SingletonConfig | undefined,\n concurrency: options.concurrency as ConcurrencyConfig | undefined,\n executionTimeout: options.executionTimeout,\n input: options.input,\n output: options.output,\n validateInput: options.validateInput as WorkflowMeta['validateInput'],\n searchAttributes: options.searchAttributes,\n onEvent: options.onEvent,\n debounce: options.debounce,\n batch: options.batch,\n requires: options.requires,\n };\n Reflect.defineMetadata(WORKFLOW_METADATA, meta, target);\n // Stamp the registered name so this class can be used as a typed workflow ref (ctx.child,\n // engine.start, deadLetterWorkflow) and resolved back to its name via `workflowName`.\n Object.defineProperty(target, WORKFLOW_NAME_KEY, {\n value: options.name,\n configurable: true,\n });\n };\n}\n\n// biome-ignore lint/complexity/noBannedTypes: matches reflect-metadata's class target type\nexport function getWorkflowMeta(target: Function): WorkflowMeta | undefined {\n return Reflect.getMetadata(WORKFLOW_METADATA, target) as WorkflowMeta | undefined;\n}\n\nexport const DURABLE_STEP_METADATA = Symbol('nestjs-durable:step-handler');\n\nexport interface DurableStepMeta {\n /** The resolved routing name — derived (`Class.method`) or explicit, always present. */\n name: string;\n /** Opt-in runtime input schema, validated when the handler is served (see `scanSteps`). Absent on\n * a bare `@Step()` — compile-time types from the method signature only, no runtime check. */\n input?: IoSchema | undefined;\n /** Opt-in runtime output schema, validated before the handler's result is handed back. */\n output?: IoSchema | undefined;\n}\n\n/**\n * `@Step({ name?, input?, output?, retries?, backoff?, backoffMs?, backoffMaxMs?, jitter?,\n * timeoutMs? })` — the object call form. See {@link Step}.\n */\nexport interface StepOptions {\n /** Explicit routing name, overriding the derived `Class.method`. */\n name?: string;\n /** Runtime input schema, validated at the serve boundary (opt-in — a bare `@Step()` skips it). A\n * Standard Schema (zod, valibot, …) or a class-validator DTO class — the same forms\n * `@Workflow({ input })` takes. The method receives the parsed value. */\n input?: IoSchema;\n /** Runtime output schema, validated before the result is returned (opt-in). */\n output?: IoSchema;\n /**\n * Def-level durable-dispatch policy stamped under `DURABLE_STEP_CONFIG` and read by `ctx.step` at\n * the dispatch boundary (see `stepConfigOf`) — a per-call `ctx.step(ref, input, opts)` overrides\n * these field-by-field. Max attempts before the step (and run) fails.\n */\n retries?: number;\n /** How the delay between retries grows: `fixed` (constant) or `exp` (doubles each attempt). */\n backoff?: 'fixed' | 'exp';\n /** Base delay in ms between retries. Omit (or 0) to retry with no delay. */\n backoffMs?: number;\n /** Upper bound on the (exponential) backoff delay. */\n backoffMaxMs?: number;\n /** Add random jitter (50–100% of the computed delay) to avoid thundering-herd retries. */\n jitter?: boolean;\n /**\n * Liveness window for a dispatched step: no result/heartbeat within this many ms presumes the\n * worker dead and fails the dispatch with a `RemoteStepTimeout` (retryable — re-dispatches per\n * `retries`). Omit to wait indefinitely.\n */\n timeoutMs?: number;\n /**\n * Capabilities a live worker MUST advertise to run this step (handshake design §7.5). The\n * control-plane routes the step only to workers whose descriptor advertises every name here; if\n * descriptors are published on the step's group but none is capability-capable + protocol-compatible,\n * the run parks `blocked` (never a silent hang) until the recovery poll finds one. Absent/empty =\n * \"runs anywhere\" (the default — a legacy fleet publishing no descriptors skips the guard, §7.7). A\n * per-call `ctx.step(ref, input, { requires })` overrides this.\n */\n requires?: string[];\n}\n\n/** Build the {@link StepConfig} to stamp under `DURABLE_STEP_CONFIG` from `@Step` options — omitting\n * every unset field, so a bare `@Step()` (or one with only `name`/`input`/`output`) stamps `undefined`\n * and leaves `ctx.step` reading nothing but a per-call `opts` override. */\nfunction stepConfigFrom(options: StepOptions): StepConfig | undefined {\n const config: StepConfig = {\n retries: options.retries,\n backoff: options.backoff,\n backoffMs: options.backoffMs,\n backoffMaxMs: options.backoffMaxMs,\n jitter: options.jitter,\n timeoutMs: options.timeoutMs,\n requires: options.requires,\n };\n const hasAnyField = Object.values(config).some((value) => value !== undefined);\n return hasAnyField ? config : undefined;\n}\n\n/**\n * Marks a provider method as a durable step handler. An in-process transport (e.g. the\n * event-emitter transport) or a co-located/thin worker runtime routes a dispatched task to it BY\n * NAME — `ctx.step(this.svc.method, input)` reads that same name off the method reference (stamped\n * via the shared, cross-package `DURABLE_STEP_NAME` symbol from `@dudousxd/nestjs-durable-core`), so\n * there's no separately-declared def linking a call site to this handler. The method's single\n * argument is the step input (plus an optional `StepLogger` second arg); its return value is the\n * step output.\n *\n * Three call forms:\n * - `@Step()` — bare: the routing name is DERIVED from the method as `` `${ClassName}.${method}` ``\n * (e.g. `ExtractionService.runExtractionPage`) — refactor-safe, no magic string.\n * - `@Step('custom:name')` — explicit name override (stable across refactors, or a cross-runtime\n * contract with a non-JS worker that has no `@Step` of its own).\n * - `@Step({ name?, input?, output?, retries?, backoff?, backoffMs?, backoffMaxMs?, jitter?,\n * timeoutMs? })` — optional name override, opt-in RUNTIME schemas (a Standard Schema or a DTO\n * class), and a def-level durable-retry/liveness-timeout policy. `input` validates before the method runs; `output`\n * validates its return value before it's handed back (see `scanSteps`). `retries`/`backoff`/\n * `backoffMs`/`backoffMaxMs`/`jitter`/`timeoutMs` are the policy `ctx.step` reads off this method\n * reference (via `stepConfigOf`) to build the dispatched `StepDef`'s durable retry/backoff and\n * remote-liveness timeout — a per-call `ctx.step(ref, input, opts)` overrides them field-by-field.\n * A bare `@Step()` carries none of this and skips validation/retry/timeout — compile-time types\n * from the method signature are the only check, and the step dispatches with no retry/timeout.\n */\nexport function Step(nameOrOptions?: string | StepOptions): MethodDecorator {\n return (target, propertyKey, descriptor: PropertyDescriptor) => {\n const options =\n typeof nameOrOptions === 'string' ? { name: nameOrOptions } : (nameOrOptions ?? {});\n const derivedName = options.name ?? `${target.constructor.name}.${String(propertyKey)}`;\n const meta: DurableStepMeta = {\n name: derivedName,\n input: options.input,\n output: options.output,\n };\n Reflect.defineMetadata(DURABLE_STEP_METADATA, meta, descriptor.value as object);\n // Stamp the SAME resolved name core's `ctx.step` reads off a method reference (`stepNameOf`) —\n // the cross-package contract letting `ctx.step(this.svc.method, input)` route without a\n // separately-declared def. `DURABLE_STEP_NAME` is core's `Symbol.for`-keyed constant, so a\n // duplicate copy of core still reads back the same key (see `step-name-symbol.ts`).\n (descriptor.value as { [DURABLE_STEP_NAME]?: string })[DURABLE_STEP_NAME] = derivedName;\n // Stamp the def-level dispatch policy (retries/backoff/timeoutMs) core's `ctx.step` reads via\n // `stepConfigOf`, under the same `Symbol.for`-keyed contract as `DURABLE_STEP_NAME`. Omitted\n // entirely when no policy field is set, so a bare `@Step()` stamps nothing extra.\n const config = stepConfigFrom(options);\n if (config !== undefined) {\n (descriptor.value as { [DURABLE_STEP_CONFIG]?: StepConfig })[DURABLE_STEP_CONFIG] = config;\n }\n return descriptor;\n };\n}\n\n// biome-ignore lint/complexity/noBannedTypes: reflect-metadata reads from the method function\nexport function getDurableStepMeta(method: Function): DurableStepMeta | undefined {\n return Reflect.getMetadata(DURABLE_STEP_METADATA, method) as DurableStepMeta | undefined;\n}\n\nexport const DEAD_LETTER_METADATA = Symbol('nestjs-durable:dead-letter');\n\n/**\n * The payload a dead-letter handler receives: the dead run's id, its workflow, the input it was\n * started with (typed via `TInput`), and the failure that killed it.\n */\nexport interface DeadLetter<TInput = unknown> {\n /** Id of the run that was dead-lettered (inspectable + retriable in the dashboard). */\n deadRunId: string;\n /** Name of the workflow whose run died. */\n workflow: string;\n /** The original input the dead run was started with. */\n input: TInput;\n /** The structured error that moved the run to `dead`, when known. */\n error?: StepError;\n}\n\n/**\n * Marks a method on a `@Workflow` class as that workflow's **inline dead-letter handler**. When a\n * run of the workflow is moved to `dead` (exceeded `maxRecoveryAttempts`), this method runs — as a\n * durable workflow itself, auto-registered as `<workflow>.dlq` with a `dlq:<runId>` id — receiving a\n * {@link DeadLetter} payload. It shares the class's injected dependencies, so the handler lives in\n * the same file as the workflow it protects.\n *\n * Takes precedence over `@Workflow({ deadLetterWorkflow })` and the module-level `deadLetterWorkflow`\n * default. The method signature is `(ctx, dead)` — the same `ctx` a workflow `run` gets.\n */\nexport function DeadLetter(): MethodDecorator {\n return (_target, _propertyKey, descriptor: PropertyDescriptor) => {\n Reflect.defineMetadata(DEAD_LETTER_METADATA, true, descriptor.value as object);\n return descriptor;\n };\n}\n\n// biome-ignore lint/complexity/noBannedTypes: reflect-metadata reads from the method function\nexport function isDeadLetterHandler(method: Function): boolean {\n return Reflect.getMetadata(DEAD_LETTER_METADATA, method) === true;\n}\n\nexport const ON_ERROR_METADATA = Symbol('nestjs-durable:on-error');\n\n/**\n * An error class that declares the `code` it is thrown with (`static readonly code = 'invalid_line'`).\n * `@OnError(Class)` matches on that code, not on `instanceof`: a dispatched step's error reaches the\n * workflow as a plain `{ message, code }`, without its class.\n */\nexport interface ErrorClassWithCode {\n readonly code: string;\n}\n\ntype WorkflowShape = { run(ctx: any, input: any): Promise<unknown> };\n\n/**\n * An `@OnError` method: a workflow body that receives the failed run's {@link OnErrorInput}, typed with\n * `run`'s input, and returns what `run` returns.\n */\nexport type OnErrorMethod<T extends WorkflowShape> = (\n ctx: WorkflowCtx<any>,\n failure: OnErrorInput<Parameters<T['run']>[1]>,\n) => Promise<Awaited<ReturnType<T['run']>>>;\n\n/**\n * Marks a method on a `@Workflow` class as the handler for a failure of that workflow's runs. When a\n * run ends `failed` with an error of the given `code` (a string, or an {@link ErrorClassWithCode}),\n * the engine starts the method as its own durable workflow — registered as\n * `<workflow>.onError.<method>`, with a `<runId>.onError` id — and the failed run waits for it, then\n * settles with its outcome: the method's return value as its output, or its error. Without an\n * argument it takes any failure no other code matches.\n *\n * The engine routes the failure, so this holds for whatever ran the body (inline, an in-app worker,\n * another runtime). The method's signature is checked against the workflow: `(ctx, failure)`, with\n * `failure.input` typed as `run`'s input and the return type as `run`'s. Stack the decorator to give\n * one method several codes. Saga compensations of the failed body run before the handoff;\n * cancellation and non-determinism are never routed.\n */\nexport function OnError(match?: string | ErrorClassWithCode) {\n const code = match === undefined || typeof match === 'string' ? match : match.code;\n if (match !== undefined && typeof code !== 'string') {\n throw new Error(\n '@OnError(ErrorClass): the class has no static `code`. Declare `static readonly code = \"...\"` on it, or pass the code string.',\n );\n }\n return <T extends WorkflowShape>(\n _target: T,\n _propertyKey: string | symbol,\n descriptor: { value?: OnErrorMethod<T> | undefined },\n ): void => {\n const method = descriptor.value as object;\n const codes: (string | undefined)[] = Reflect.getMetadata(ON_ERROR_METADATA, method) ?? [];\n Reflect.defineMetadata(ON_ERROR_METADATA, [...codes, code], method);\n };\n}\n\n/** The codes an `@OnError` method takes (`undefined` for the catch-all), or undefined if it has none. */\n// biome-ignore lint/complexity/noBannedTypes: reflect-metadata reads from the method function\nexport function onErrorCodesOf(method: Function): (string | undefined)[] | undefined {\n return Reflect.getMetadata(ON_ERROR_METADATA, method);\n}\n\nexport const ON_EVENT_METADATA = Symbol('nestjs-durable:on-event');\n\n/**\n * Subscribe a `@Workflow` class to one or more events: when any of them is published via\n * `publishEvent(name, payload)`, a fresh run of the workflow starts with the payload as input.\n * Equivalent to `@Workflow({ onEvent })` — use whichever reads better; multiple\n * `@OnDurableEvent(...)` decorators and the option are all merged.\n *\n * Named \"durable\" on purpose: `@nestjs/event-emitter` exports an `@OnEvent` decorator, and in an\n * app using both libs an auto-import picking the wrong one fails silently in either direction.\n */\nexport function OnDurableEvent(...events: OnEventEntry[]): ClassDecorator {\n return (target) => addEventSubscriptions(target, events);\n}\n\n/**\n * Coalesce a subscriber's triggers by **debouncing**: start it once events have been quiet for\n * `windowMs`, with the last one. `key` splits that per key: it receives the subscriber's input (what\n * `input` builds), and each distinct key debounces on its own.\n */\nexport interface SubscriberDebounce<TRunInput> {\n windowMs: number | string;\n key?: ((input: TRunInput) => string) | undefined;\n}\n\n/**\n * Coalesce a subscriber's triggers by **batching**: start it with `{ events }` once `maxSize` arrive\n * or `windowMs` passes since the first. `key` batches each distinct key on its own.\n */\nexport interface SubscriberBatch<TRunInput> {\n maxSize: number;\n windowMs: number | string;\n key?: ((input: TRunInput) => string) | undefined;\n}\n\n/** Options for {@link OnWorkflowCompleted} / {@link OnWorkflowFailed}. */\nexport interface OnWorkflowSettledOptions<TEvent, TRunInput> {\n /** Start only for the settled runs this returns true for, e.g. by `input` or `searchAttributes`. */\n where?: ((event: TEvent) => boolean) | undefined;\n /**\n * The started run's input, built from the event. Without it the run receives the\n * {@link WorkflowLifecycleEvent} itself. Lets an existing workflow subscribe with its own input\n * shape, and keeps the settled run's whole input and output out of the new run's row.\n */\n input?: ((event: TEvent) => TRunInput) | undefined;\n /**\n * Debounce this workflow's triggers (see {@link SubscriberDebounce}). Sets the workflow's\n * `onEvent` coalescing, so it applies to every event it subscribes to; a different `debounce` or\n * `batch` already declared on it fails at registration. Not with `batch`.\n */\n debounce?: SubscriberDebounce<TRunInput> | undefined;\n /**\n * Batch this workflow's triggers (see {@link SubscriberBatch}); the run's input becomes\n * `{ events: TRunInput[] }`. Same scope and conflicts as `debounce`. Not with `debounce`.\n */\n batch?: SubscriberBatch<TRunInput> | undefined;\n}\n\n/** Options for {@link OnWorkflowFailed}: also which endings start the subscriber. */\nexport interface OnWorkflowFailedOptions<TEvent, TRunInput>\n extends OnWorkflowSettledOptions<TEvent, TRunInput> {\n /** The endings that start it. Defaults to all three: `failed`, `cancelled` and `dead`. */\n statuses?: Array<'failed' | 'cancelled' | 'dead'> | undefined;\n}\n\n/** `O` with a required `batch` (and no `debounce`): the overload whose subscriber takes `{ events }`. */\ntype Batched<O, TRunInput> = O & { batch: SubscriberBatch<TRunInput>; debounce?: undefined };\n/** `O` without `batch`: the overload whose subscriber takes `TRunInput` itself. */\ntype Unbatched<O> = O & { batch?: undefined };\n\n/**\n * A class decorator that only accepts a workflow whose `run(ctx, input)` takes `TRunInput`, so a\n * subscriber with the wrong input shape fails to compile instead of failing at runtime.\n */\nexport type SubscriberDecorator<TRunInput> = <\n T extends abstract new (\n ...args: never[]\n ) => { run: (ctx: never, input: TRunInput) => unknown },\n>(\n target: T,\n) => void;\n\n/**\n * Start a fresh run of the decorated workflow whenever a run of `workflow` **completes**. The new\n * run's input is the {@link WorkflowLifecycleEvent} (run id, input, output, tags, search\n * attributes), or what `input` builds from it. The settling workflow does not know about its\n * subscribers. Exactly once per settled run: see `runCompletedEvent` in\n * `@dudousxd/nestjs-durable-core`.\n *\n * With a class ref, the decorated workflow's `run` input is type-checked against the event (or\n * against `input`'s return type, or `{ events }` of it with `batch`). Child runs publish too, so a\n * workflow that `etl` starts as a child also starts its subscribers.\n *\n * ```ts\n * @Workflow({ name: 'refresh-summaries' })\n * @OnWorkflowCompleted(IngestionWorkflow, {\n * where: (e) => e.input.type === 'mvr',\n * input: (e) => ({ baseId: e.input.baseId }),\n * debounce: { windowMs: '30s', key: (input) => input.baseId },\n * })\n * class RefreshSummariesWorkflow {\n * async run(ctx: WorkflowCtx, input: { baseId: string }) {}\n * }\n * ```\n */\nexport function OnWorkflowCompleted<C extends WorkflowClass, TRunInput = LifecycleEventOf<C>>(\n workflow: C,\n options: Batched<OnWorkflowSettledOptions<LifecycleEventOf<C>, TRunInput>, TRunInput>,\n): SubscriberDecorator<{ events: TRunInput[] }>;\nexport function OnWorkflowCompleted<C extends WorkflowClass, TRunInput = LifecycleEventOf<C>>(\n workflow: C,\n options?: Unbatched<OnWorkflowSettledOptions<LifecycleEventOf<C>, TRunInput>>,\n): SubscriberDecorator<TRunInput>;\nexport function OnWorkflowCompleted(\n workflow: string,\n options?: OnWorkflowSettledOptions<WorkflowLifecycleEvent, unknown>,\n): ClassDecorator;\nexport function OnWorkflowCompleted(\n workflow: WorkflowRef,\n options?: OnWorkflowSettledOptions<WorkflowLifecycleEvent, unknown>,\n): ClassDecorator {\n return onWorkflowSettled(runCompletedEvent(workflow), options?.where, options);\n}\n\n/**\n * Start a fresh run of the decorated workflow whenever a run of `workflow` ends **failed,\n * cancelled or dead** (narrow it with `statuses`). Same contract as {@link OnWorkflowCompleted};\n * the event carries `error` and `status` instead of `output`.\n */\nexport function OnWorkflowFailed<C extends WorkflowClass, TRunInput = LifecycleEventOf<C>>(\n workflow: C,\n options: Batched<OnWorkflowFailedOptions<LifecycleEventOf<C>, TRunInput>, TRunInput>,\n): SubscriberDecorator<{ events: TRunInput[] }>;\nexport function OnWorkflowFailed<C extends WorkflowClass, TRunInput = LifecycleEventOf<C>>(\n workflow: C,\n options?: Unbatched<OnWorkflowFailedOptions<LifecycleEventOf<C>, TRunInput>>,\n): SubscriberDecorator<TRunInput>;\nexport function OnWorkflowFailed(\n workflow: string,\n options?: OnWorkflowFailedOptions<WorkflowLifecycleEvent, unknown>,\n): ClassDecorator;\nexport function OnWorkflowFailed(\n workflow: WorkflowRef,\n options?: OnWorkflowFailedOptions<WorkflowLifecycleEvent, unknown>,\n): ClassDecorator {\n const statuses = options?.statuses;\n const where = options?.where;\n const accepts =\n statuses || where\n ? (event: WorkflowLifecycleEvent) =>\n (!statuses || (statuses as string[]).includes(event.status)) && (!where || where(event))\n : undefined;\n return onWorkflowSettled(runFailedEvent(workflow), accepts, options);\n}\n\n/** Metadata key for the `onEvent` coalescing `@OnWorkflowCompleted` / `@OnWorkflowFailed` declare. */\nexport const ON_EVENT_BATCH_METADATA = Symbol('nestjs-durable:on-event-batch');\n\nfunction onWorkflowSettled(\n event: string,\n where: ((event: WorkflowLifecycleEvent) => boolean) | undefined,\n options: OnWorkflowSettledOptions<WorkflowLifecycleEvent, unknown> | undefined,\n): ClassDecorator {\n const subscription = {\n event,\n where: where as ((payload: unknown) => boolean) | undefined,\n input: options?.input as ((payload: unknown) => unknown) | undefined,\n };\n const batch = subscriberEventBatch(event, options);\n return (target) => {\n addEventSubscriptions(target, [subscription]);\n if (!batch) return;\n const existing = Reflect.getMetadata(ON_EVENT_BATCH_METADATA, target) as\n | EventBatchConfig\n | undefined;\n if (existing && !sameEventBatch(existing, batch)) {\n throw new Error(\n `${(target as { name?: string }).name ?? 'workflow'}: two lifecycle subscriptions declare different debounce/batch settings; a workflow coalesces all its triggers one way`,\n );\n }\n Reflect.defineMetadata(ON_EVENT_BATCH_METADATA, batch, target);\n };\n}\n\n/** The workflow-level coalescing a lifecycle subscription's `debounce` / `batch` option maps to. */\nfunction subscriberEventBatch(\n event: string,\n options: OnWorkflowSettledOptions<WorkflowLifecycleEvent, unknown> | undefined,\n): EventBatchConfig | undefined {\n if (options?.debounce && options.batch) {\n throw new Error(`${event}: a subscription takes debounce or batch, not both`);\n }\n if (options?.debounce) {\n return {\n mode: 'debounce',\n windowMs: parseDuration(options.debounce.windowMs),\n ...(options.debounce.key ? { key: options.debounce.key } : {}),\n };\n }\n if (options?.batch) {\n return {\n mode: 'batch',\n maxSize: options.batch.maxSize,\n windowMs: parseDuration(options.batch.windowMs),\n ...(options.batch.key ? { key: options.batch.key } : {}),\n };\n }\n return undefined;\n}\n\n/**\n * Whether two coalescing settings are the same: mode, window, size and key. Keys compare by source\n * text (`key.toString()`), so the same arrow written on two decorators matches; keys written\n * differently do not, even when they compute the same thing.\n */\nfunction sameEventBatch(a: EventBatchConfig, b: EventBatchConfig): boolean {\n return (\n a.mode === b.mode &&\n a.windowMs === b.windowMs &&\n a.key?.toString() === b.key?.toString() &&\n (a.mode !== 'batch' || b.mode !== 'batch' || a.maxSize === b.maxSize)\n );\n}\n\n/**\n * How a workflow coalesces its `onEvent` triggers: `@Workflow({ debounce | batch })`, or what its\n * `@OnWorkflowCompleted` / `@OnWorkflowFailed` declare. Throws when both are set and differ, so a\n * workflow never silently coalesces one way while its decorator says another.\n */\nexport function eventBatchOf(meta: WorkflowMeta, target: object): EventBatchConfig | undefined {\n const declared: EventBatchConfig | undefined = meta.debounce\n ? { mode: 'debounce', windowMs: parseDuration(meta.debounce) }\n : meta.batch\n ? {\n mode: 'batch',\n maxSize: meta.batch.maxSize,\n windowMs: parseDuration(meta.batch.within),\n }\n : undefined;\n const fromSubscription = Reflect.getMetadata(ON_EVENT_BATCH_METADATA, target) as\n | EventBatchConfig\n | undefined;\n if (declared && fromSubscription && !sameEventBatch(declared, fromSubscription)) {\n throw new Error(\n `workflow ${meta.name}: @Workflow declares ${declared.mode} but a lifecycle subscription declares a different ${fromSubscription.mode}; declare it in one place`,\n );\n }\n return fromSubscription ?? declared;\n}\n\nfunction addEventSubscriptions(target: object, entries: OnEventEntry[]): void {\n const existing =\n (Reflect.getMetadata(ON_EVENT_METADATA, target) as OnEventEntry[] | undefined) ?? [];\n Reflect.defineMetadata(ON_EVENT_METADATA, [...existing, ...entries], target);\n}\n\n/**\n * All events a workflow class subscribes to: `@Workflow({ onEvent })`, `@OnDurableEvent`,\n * `@OnWorkflowCompleted` and `@OnWorkflowFailed`. Repeated bare names collapse to one.\n */\nexport function getOnEvents(meta: WorkflowMeta, target: object): OnEventEntry[] {\n const fromDecorator =\n (Reflect.getMetadata(ON_EVENT_METADATA, target) as OnEventEntry[] | undefined) ?? [];\n const names = new Set<string>();\n return [...(meta.onEvent ?? []), ...fromDecorator].filter((entry) => {\n if (typeof entry !== 'string') return true;\n if (names.has(entry)) return false;\n names.add(entry);\n return true;\n });\n}\n","import { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/**\n * Derives a workflow's **origin** — the npm package that declared it (`@dudousxd/nestjs-agent`, the\n * host app's own `package.json` `name`, …) — so every run can say which lib produced it (see\n * {@link import('@dudousxd/nestjs-durable-core').WorkflowRun.origin}).\n *\n * WHY IT IS DERIVED AND NOT DECLARED: anything a lib has to opt into (a `@Workflow({ tags })`\n * convention, a registry of known packages) is already wrong in the field the day a lib forgets, and\n * a facet that lists two of the five libs actually running is worse than no facet at all. So the only\n * acceptable input is one the lib cannot fail to provide: the file it declared its `@Workflow` class\n * in. That file is captured by {@link declaringFile} at decoration time — the one moment we are\n * guaranteed to be executing inside the declaring module — and mapped here to the nearest enclosing\n * `package.json` `name`.\n *\n * WHY NOT THE NEST MODULE: the `InstanceWrapper` a `DiscoveryService` scan hands back does name the\n * module a provider came from (`wrapper.host.metatype`), but a module class is just a class — it\n * carries no file location, and the app's own module is a perfectly normal place to register a lib's\n * workflow, which would then be attributed to the app. The declaring file of the `@Workflow` class is\n * both available and strictly more precise, so the wrapper is used only to reach that class.\n *\n * EVERY step here can fail, and each failure yields `undefined` (= unknown) rather than a guess:\n * - a runtime without V8's `Error.captureStackTrace`, or an app that set `Error.stackTraceLimit = 0`\n * - a declaring frame that is not a real file (`node:` internals, `eval`, `<anonymous>`) — notably a\n * single-file bundle can also collapse several packages into one file, and where the file IS real\n * but shared, the origin will be the bundle's package: that is the one shape this cannot detect\n * - no `package.json` carrying a `name` anywhere above the file\n * `WorkflowRegistrar` reports the workflows that came back unattributed once, at boot.\n */\n\n/** The file each decorated class was declared in, keyed by the class itself. */\nconst declaringFileByClass = new WeakMap<object, string>();\n\n/** Memoized directory → owning package name (or `undefined` when the walk found none). */\nconst packageNameByDir = new Map<string, string | undefined>();\n\ntype AnyFunction = (...args: never[]) => unknown;\n\n/**\n * The absolute path of the file that is calling `boundary` right now — i.e. the file whose top level\n * is applying a decorator, when called from inside that decorator's factory. `boundary` is clipped\n * off the captured stack (`Error.captureStackTrace`'s second argument), so the first remaining frame\n * is the caller's, with no frame counting to go stale when this file is refactored.\n *\n * Returns `undefined` on any runtime that does not give us a usable frame.\n */\nexport function declaringFile(boundary: AnyFunction): string | undefined {\n const capture = Error.captureStackTrace;\n if (typeof capture !== 'function') return undefined;\n const holder: { stack?: string } = {};\n capture(holder, boundary);\n return topFrameFile(holder.stack);\n}\n\n/** Records the file `target` was declared in, so {@link originOfClass} can resolve it later. */\nexport function rememberDeclaringFile(target: object, file: string | undefined): void {\n if (file) declaringFileByClass.set(target, file);\n}\n\n/**\n * The package that declared `target`, or `undefined` if it cannot be resolved with confidence.\n *\n * Walks the prototype chain, matching `Reflect.getMetadata`'s inheritance: a subclass that inherits\n * its `@Workflow` metadata from a decorated base also inherits that base's origin, because the base\n * is where the decorated body was declared.\n */\nexport function originOfClass(target: unknown): string | undefined {\n for (\n let ctor: unknown = target;\n typeof ctor === 'function' || (typeof ctor === 'object' && ctor !== null);\n ctor = Object.getPrototypeOf(ctor)\n ) {\n const file = declaringFileByClass.get(ctor);\n if (file) return packageNameFor(file);\n }\n return undefined;\n}\n\n/**\n * The package that declared the workflow behind a discovered provider. Structurally typed against\n * Nest's `InstanceWrapper` (the shape `DiscoveryService.getProviders()` returns) so this package does\n * not deep-import an internal Nest path: `metatype` is the registered class, and `instance.constructor`\n * covers a provider whose metatype is absent (a `useValue`/factory-built instance of a decorated class).\n */\nexport function originOfProvider(wrapper: {\n metatype?: unknown;\n instance?: unknown;\n}): string | undefined {\n const fromMetatype = originOfClass(wrapper.metatype);\n if (fromMetatype) return fromMetatype;\n const instance = wrapper.instance;\n if (typeof instance !== 'object' || instance === null) return undefined;\n return originOfClass(instance.constructor);\n}\n\n/**\n * The `name` of the nearest `package.json` at or above `file`'s directory. For a lib this is the\n * installed package (`…/node_modules/@scope/lib/dist/index.cjs` → `@scope/lib`, pnpm's nested layout\n * included); for a workflow written in the app it is the app's own name. Memoized per directory —\n * the walk hits the filesystem once per distinct directory, not once per workflow.\n */\nfunction packageNameFor(file: string): string | undefined {\n const start = dirname(file);\n const visited: string[] = [];\n let dir = start;\n for (;;) {\n if (packageNameByDir.has(dir)) {\n const cached = packageNameByDir.get(dir);\n for (const seen of visited) packageNameByDir.set(seen, cached);\n return cached;\n }\n visited.push(dir);\n const name = readPackageName(join(dir, 'package.json'));\n if (name !== undefined) {\n for (const seen of visited) packageNameByDir.set(seen, name);\n return name;\n }\n const parent = dirname(dir);\n // `dirname('/')` is `'/'` — the filesystem root is the end of the walk.\n if (parent === dir) {\n for (const seen of visited) packageNameByDir.set(seen, undefined);\n return undefined;\n }\n dir = parent;\n }\n}\n\n/** The `name` field of a `package.json`, or `undefined` if it is missing, unreadable or unnamed. */\nfunction readPackageName(path: string): string | undefined {\n let raw: string;\n try {\n raw = readFileSync(path, 'utf8');\n } catch {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // A malformed package.json is not ours to fail on — keep walking up.\n return undefined;\n }\n if (!isRecord(parsed)) return undefined;\n const name = parsed.name;\n return typeof name === 'string' && name.length > 0 ? name : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * The file named by the FIRST frame of a captured stack. Deliberately only the first: with the\n * capture boundary clipped, frame 0 IS the declaring site, and falling through to a deeper frame\n * when it is unparseable would attribute the workflow to whatever happened to be further up the\n * stack (the test runner, Nest's loader) — a confident-looking wrong answer.\n */\nfunction topFrameFile(stack: string | undefined): string | undefined {\n if (typeof stack !== 'string') return undefined;\n for (const line of stack.split('\\n')) {\n const frame = line.trim();\n if (!frame.startsWith('at ')) continue;\n return fileOfFrame(frame.slice(3));\n }\n return undefined;\n}\n\n/** `foo (/a/b.ts:1:2)` / `/a/b.ts:1:2` / `file:///a/b.js:1:2` → an absolute path, else `undefined`. */\nfunction fileOfFrame(frame: string): string | undefined {\n const match = /\\((.+):\\d+:\\d+\\)$/.exec(frame) ?? /^(.+):\\d+:\\d+$/.exec(frame);\n const location = match?.[1];\n if (location === undefined) return undefined;\n if (location.startsWith('file://')) {\n try {\n return fileURLToPath(location);\n } catch {\n return undefined;\n }\n }\n // Anything that is not an absolute path is not a file we can resolve a package from: `node:internal/…`,\n // `<anonymous>`, `eval at …`, a bundler's virtual id.\n const absolute = location.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(location);\n return absolute ? location : undefined;\n}\n","import type { StartRunDeps } from '@dudousxd/durable-worker';\nimport {\n type ConcurrencyConfig,\n type OnEventEntry,\n type RunResult,\n type RunTenant,\n type SignalOptions,\n type SingletonConfig,\n type StartOptions,\n type StartRunMessage,\n type StartRunSingleton,\n type TenantTokenSource,\n type WorkflowClass,\n type WorkflowInputOf,\n acceptingSubscription,\n resolveConcurrency,\n resolveTenantToken,\n toEventSubscription,\n workflowName,\n} from '@dudousxd/nestjs-durable-core';\nimport { Injectable } from '@nestjs/common';\nimport type { ContextAccessor } from './context-accessor';\nimport type { DurableModuleOptions } from './durable.module';\nimport { currentTenant } from './tenancy';\nimport { resolveTenantTokenSource } from './tenant-contracts';\nimport { startRun } from './worker-sdk';\n\n/**\n * The `@Workflow` options a tenant's start applies itself, before it publishes the start-run: the\n * ones that are functions of the input, which the control plane (knowing the workflow by name\n * alone) cannot evaluate. Declared by `ThinWorkflowRegistrar` for every `@Workflow` it discovers.\n */\nexport interface TenantWorkflowStartPolicy {\n /** `@Workflow({ input })`: parses the input once (throwing rejects the start before anything is\n * published); `validateInput` and the singleton and concurrency keys read the parsed value. */\n parseInput?: ((input: unknown) => unknown) | undefined;\n /** `@Workflow({ validateInput })`: rejects the start (throws) before anything is published. It\n * receives the value `parseInput` returned, or the input as sent without one. */\n validateInput?: ((input: unknown) => void | Promise<void>) | undefined;\n /** `@Workflow({ singleton })`: its key is evaluated here and carried on the start-run. */\n singleton?: SingletonConfig | undefined;\n /** `@Workflow({ concurrency })`: the default quota, evaluated here unless the start passes one. */\n concurrency?: ConcurrencyConfig | undefined;\n /** `@Workflow({ onEvent })` / `@OnDurableEvent`: started by this app's own `publishEvent`. */\n onEvent?: OnEventEntry[] | undefined;\n /** The workflow coalesces its event triggers (`debounce`/`batch`), which a tenant cannot apply. */\n coalesces?: boolean | undefined;\n}\n\n/**\n * Where a tenant's `signal`/`signalWithStart`/`publishEvent` go: run requests to the control plane\n * (the module's `ProxyRunGateway` over `transport`).\n */\nexport interface TenantRunRequests {\n signal(token: string, payload: unknown, opts?: SignalOptions): Promise<RunResult | null>;\n signalWithStart(\n start: Omit<StartRunMessage, 'tenant'> & { runId: string },\n signal: { token: string; payload?: unknown },\n ): Promise<{ runId: string; signalled: boolean }>;\n publishEvent(name: string, payload: unknown, opts?: { id?: string }): Promise<number>;\n}\n\n/**\n * The **store-less `engine.start` facade** for a tenant worker. Provided under the `WorkflowEngine`\n * DI token by {@link import('./durable.module').DurableModule} (`forRoot({ connection })`, no\n * `store`), so tenant code calls `engine.start(...)` UNCHANGED — it has no idea it is a tenant.\n * Instead of touching a DB, `start` publishes a `StartRunMessage` on the SHARED `durable-start-run`\n * queue (Option B: tenant rides as message DATA, never as wire segmentation). The operator (control\n * plane, `namespace: undefined`) consumes it, stamps the run's namespace from `tenant`, and routes\n * the run's task to `<workflow>@<tenant>` — the partition THIS tenant's worker serves.\n *\n * `cancel`/`deleteRun` need the store/driver a tenant does not have; they throw. No wire message\n * exists for them (the operator owns cancellation/retention).\n */\n@Injectable()\nexport class DurableStartClient {\n private readonly tenant: string;\n private readonly tenantToken: TenantTokenSource | undefined;\n private readonly policies = new Map<string, TenantWorkflowStartPolicy>();\n private readonly warnedCoalescing = new Set<string>();\n\n constructor(\n private readonly options: DurableModuleOptions,\n private readonly deps?: StartRunDeps,\n /** The context accessor, for the customer tenant a start claims (else the global slot). */\n private readonly accessor?: ContextAccessor,\n /**\n * Sends `signal`/`signalWithStart`/`publishEvent` to the control plane as run requests (the\n * module's `ProxyRunGateway` over `transport`). Absent (no `transport`): they reject, naming it.\n */\n private readonly requests?: () => TenantRunRequests | undefined,\n ) {\n this.tenant = options.partition ?? 'default';\n this.tenantToken = resolveTenantTokenSource(options.tenantToken);\n }\n\n /**\n * Apply `policy` to every start of `workflow` from this process (see\n * {@link TenantWorkflowStartPolicy}). Called by `ThinWorkflowRegistrar` at boot.\n */\n declareWorkflow(workflow: string, policy: TenantWorkflowStartPolicy): void {\n this.policies.set(workflow, policy);\n }\n\n /**\n * The start-run fields a declared policy adds for `input`: it validates the input (throwing), and\n * evaluates the singleton key and the default quota against the parsed input. A per-start `concurrency` wins over the\n * workflow's.\n */\n private async applyPolicy(\n workflow: string,\n input: unknown,\n opts: StartOptions | undefined,\n ): Promise<{ singleton?: StartRunSingleton; concurrency?: StartOptions['concurrency'] }> {\n const policy = this.policies.get(workflow);\n if (!policy) return opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {};\n // Parsed once, as on a local start: `validateInput` and the keys read the input as `run` will.\n const keyInput = policy.parseInput ? await policy.parseInput(input) : input;\n await policy.validateInput?.(keyInput);\n const concurrency = await resolveConcurrency(opts?.concurrency, policy.concurrency, keyInput);\n const singleton = policy.singleton\n ? {\n key: policy.singleton.key(keyInput),\n ...(policy.singleton.limit !== undefined ? { limit: policy.singleton.limit } : {}),\n ...(policy.singleton.maxQueueDepth !== undefined\n ? { maxQueueDepth: policy.singleton.maxQueueDepth }\n : {}),\n }\n : undefined;\n return {\n ...(singleton ? { singleton } : {}),\n ...(concurrency ? { concurrency } : {}),\n };\n }\n\n /** The wire `tenant`: the signed token when configured, else the partition. */\n private async wireTenant(): Promise<string> {\n return this.tenantToken !== undefined\n ? await resolveTenantToken(this.tenantToken)\n : this.tenant;\n }\n\n /**\n * The customer tenant a start claims: an explicit `tenantId` (`null` = none), else the request's\n * tenant when tenancy is on.\n */\n private claimedTenant(opts: StartOptions | undefined): RunTenant | undefined {\n return opts?.tenantId !== undefined\n ? opts.tenantId === null\n ? undefined\n : { id: opts.tenantId, ...(opts.tenantKind !== undefined ? { kind: opts.tenantKind } : {}) }\n : currentTenant(this.options.tenancy, this.accessor);\n }\n\n start<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n runId?: string,\n opts?: StartOptions,\n ): Promise<RunResult>;\n start(workflow: string, input: unknown, runId?: string, opts?: StartOptions): Promise<RunResult>;\n async start(\n workflow: string,\n input: unknown,\n runId: string = globalThis.crypto.randomUUID(),\n opts?: StartOptions,\n ): Promise<RunResult> {\n const message = await this.startMessage(workflowName(workflow), input, runId, opts);\n await startRun(this.options.connection, {\n // The signed token (when configured) rides in the `tenant` field, as on every run request; an\n // operator with `verifyTenant` derives the run's namespace from it.\n tenant: await this.wireTenant(),\n ...message,\n // Option B: DO NOT pass `namespace` — the start-run queue stays the shared\n // `durable-start-run` the operator consumes; tenant rides only as message data.\n ...(this.options.prefix !== undefined ? { prefix: this.options.prefix } : {}),\n ...(this.deps !== undefined ? { deps: this.deps } : {}),\n });\n // As `engine.start` reports it: a start delayed into the future reads `suspended` until it fires.\n const startAtMs = message.startAt;\n return {\n runId,\n status:\n startAtMs !== undefined && Number.isFinite(startAtMs) && startAtMs > Date.now()\n ? 'suspended'\n : 'pending',\n };\n }\n\n /**\n * The start-run a start of `name` sends (everything but the wire `tenant`): the start options the\n * control plane applies (version pin, priority, delayed start, quota), the singleton key and the\n * customer tenant this run claims. Applies the workflow's declared policy first, so a rejected\n * input throws before anything is published, as `engine.start` does.\n */\n private async startMessage(\n name: string,\n input: unknown,\n runId: string,\n opts: StartOptions | undefined,\n ): Promise<Omit<StartRunMessage, 'tenant'> & { runId: string }> {\n // The control plane keeps the claimed customer tenant only with a `tenancy:` capability on\n // this process's token.\n const tenant = this.claimedTenant(opts);\n const policy = await this.applyPolicy(name, input, opts);\n const startAt = opts?.startAt instanceof Date ? opts.startAt.getTime() : opts?.startAt;\n return {\n workflow: name,\n input,\n runId,\n ...(opts?.tags !== undefined ? { tags: opts.tags } : {}),\n ...(opts?.searchAttributes !== undefined ? { searchAttributes: opts.searchAttributes } : {}),\n ...(opts?.version !== undefined ? { version: opts.version } : {}),\n ...(opts?.priority !== undefined ? { priority: opts.priority } : {}),\n ...(startAt !== undefined ? { startAt } : {}),\n ...(policy.concurrency !== undefined ? { concurrency: policy.concurrency } : {}),\n ...(policy.singleton !== undefined ? { singleton: policy.singleton } : {}),\n ...(tenant\n ? { tenantId: tenant.id, ...(tenant.kind !== undefined ? { tenantKind: tenant.kind } : {}) }\n : {}),\n };\n }\n\n /** The control plane's run requests, or a clear error naming what is missing. */\n private runRequests(method: string): TenantRunRequests {\n const requests = this.requests?.();\n if (!requests) {\n throw new Error(\n `${method}() on a tenant is sent to the control plane as a run request, which needs \\`transport\\` on DurableModule.forRoot (the tenant's BullMQTransport).`,\n );\n }\n return requests;\n }\n\n /**\n * Signal the run of this tenant's partition waiting on `token`, through the control plane.\n * Resolves the resumed run, or null when no run of this partition waits on it: unlike\n * `engine.signal` on a control plane, a tenant's signal is NOT buffered for a wait opened later\n * (another partition's run could open it). Use `signalWithStart` to signal a run that may not wait\n * yet. `opts.id` deduplicates like `engine.signal`.\n */\n async signal(token: string, payload: unknown, opts?: SignalOptions): Promise<RunResult | null> {\n return this.runRequests('signal').signal(token, payload, opts);\n }\n\n /**\n * Ensure the run `runId` of `workflow` exists in this tenant's partition (started like\n * {@link start}, with the same options and policy), then signal it. The control plane buffers the\n * signal until the run waits on `signal.token` only when the token contains `runId` (a run-scoped\n * token, the pattern `signalWithStart` is for): a token that does not is delivered only to a run\n * of this partition already waiting on it, and refused otherwise.\n */\n signalWithStart<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n runId: string,\n signal: { token: string; payload?: unknown },\n opts?: StartOptions,\n ): Promise<{ runId: string }>;\n signalWithStart(\n workflow: string,\n input: unknown,\n runId: string,\n signal: { token: string; payload?: unknown },\n opts?: StartOptions,\n ): Promise<{ runId: string }>;\n async signalWithStart(\n workflow: string,\n input: unknown,\n runId: string,\n signal: { token: string; payload?: unknown },\n opts?: StartOptions,\n ): Promise<{ runId: string }> {\n const requests = this.runRequests('signalWithStart');\n const start = await this.startMessage(workflowName(workflow), input, runId, opts);\n const result = await requests.signalWithStart(start, signal);\n return { runId: result.runId };\n }\n\n /**\n * Publish event `name` from this tenant. Starts this app's own `onEvent` subscribers (each one\n * whose `where` accepts the payload, with its `input` mapping) as runs of this partition, by the\n * start path ({@link start}, run id `evt:<id>:<workflow>`), and has the control plane resume the\n * runs of this partition waiting on it (`ctx.waitForEvent`). Resolves how many runs it started or\n * resumed; a subscriber that throws is warned about and skipped. Unlike a control plane's\n * `publishEvent`, an event nobody received is not buffered (there is no `buffer` option), and\n * a subscriber's `debounce`/`batch` is not applied (it starts once per event, with a warning).\n */\n async publishEvent(name: string, payload: unknown, opts?: { id?: string }): Promise<number> {\n const requests = this.runRequests('publishEvent');\n const eventId = opts?.id ?? globalThis.crypto.randomUUID();\n let started = 0;\n for (const [workflow, policy] of this.policies) {\n // One subscriber that throws (its `where`, its `input`, or its start) must not keep the\n // others, or the control plane's resume of the waiting runs, from getting the event: as on a\n // control plane, it is reported and skipped.\n try {\n const subscriptions = (policy.onEvent ?? [])\n .map(toEventSubscription)\n .filter((sub) => sub.event === name);\n const { accepted, errors } = acceptingSubscription(subscriptions, payload);\n if (!accepted) {\n if (errors.length > 0) throw errors[0];\n continue;\n }\n if (policy.coalesces && !this.warnedCoalescing.has(workflow)) {\n this.warnedCoalescing.add(workflow);\n console.warn(\n `[nestjs-durable] ${workflow} debounces/batches its events, which a tenant's publishEvent does not apply: it starts once per event.`,\n );\n }\n const input = accepted.input ? accepted.input(payload) : payload;\n await this.start(workflow, input, `evt:${eventId}:${workflow}`);\n started += 1;\n } catch (error) {\n console.warn(`[nestjs-durable] event ${name}: subscriber ${workflow} not started:`, error);\n }\n }\n const resumed = await requests.publishEvent(name, payload, { id: eventId });\n return started + resumed;\n }\n\n cancel(_runId: string): Promise<void> {\n return tenantUnsupported('cancel');\n }\n\n deleteRun(_runId: string): Promise<void> {\n return tenantUnsupported('deleteRun');\n }\n\n // — everything below rejects: a tenant worker holds no store/driver. —\n\n // `resume`/`waitForRun` need the store or driver a tenant does not have. They exist so a mistaken\n // call fails with a CLEAR, named tenant error instead of a cryptic `this.engine.X is not a\n // function`. Params mirror the WorkflowEngine surface; every method rejects without reading them.\n resume(_runId: string): Promise<void> {\n return tenantUnsupported('resume');\n }\n\n waitForRun(\n _runId: string,\n _opts?: { timeoutMs?: number; until?: 'settled' | 'terminal' },\n ): Promise<void> {\n return tenantUnsupported('waitForRun');\n }\n}\n\n/** Reject with a clear, named tenant error for an operation that needs a store/driver. */\nfunction tenantUnsupported(method: string): Promise<void> {\n return Promise.reject(\n new Error(\n `${method}() is not available on a tenant worker (no store). Use the control plane for it.`,\n ),\n );\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { EngineTenancy, RunTenant, TenantFilter } from '@dudousxd/nestjs-durable-core';\nimport type { ContextAccessor } from './context-accessor';\nimport {\n type Tenancy,\n type TenancyOption,\n type TenantLevel,\n readTenancy as readContextTenancy,\n tenantLabels as readTenantLabels,\n} from './tenancy-reader';\n\n/**\n * Tenancy for durable: the CUSTOMER a run belongs to (`@dudousxd/nestjs-context`'s tenant), not the\n * worker-pool `namespace`. Read through the local copy of the context's tenancy reader\n * (`./tenancy-reader`): durable never imports nestjs-context, so it works with any context version\n * or none at all. With the accessor (or its tenancy methods) missing, tenancy reads as off and\n * durable behaves exactly as without it.\n */\n\n/**\n * The `tenancy` option of `DurableModule`. Same shape in every Aviary lib:\n * - `enabled`: `'inherit'` (default) follows `ContextModule`'s `tenancy.enabled`;\n * - `kinds`: the tenant kinds durable stamps and filters by. On a nested tenant (clinic → unit) the\n * most specific level of the active chain whose kind is listed is the one used;\n * - `family`: read a secondary tenant family (e.g. `'account'`) instead of the primary one;\n * - `required`: with no tenant, an app-facing read or start throws the context's\n * `TenantRequiredError` (403) instead of running tenantless. Defaults to the context's own\n * `tenancy.required`. Durable's own work (turns, recovery, schedules, worker steps) never throws;\n * - `nullRows: 'shared'`: a tenant also sees runs with no tenant (default `'tenantless'`: it does not).\n */\nexport type DurableTenancyOption = TenancyOption;\n\n/** Marks durable's own work, where no request asks for a tenant (see {@link inDurableWork}). */\nconst durableWork = new AsyncLocalStorage<true>();\n\n/**\n * Run `fn` as durable's own work (a workflow turn, recovery, a worker's step): reads inside it pass\n * `required: false`, so a tenant-required app does not reject a run or a task with no tenant.\n */\nexport function inDurableWork<T>(fn: () => T): T {\n return durableWork.getStore() ? fn() : durableWork.run(true, fn);\n}\n\n/**\n * Read tenancy for one operation (call per operation, never once at boot). Inside durable's own work\n * (see {@link inDurableWork}) a missing tenant never throws, whatever `required` says.\n */\nexport function readTenancy(\n option: DurableTenancyOption | undefined,\n accessor: ContextAccessor | undefined,\n): Tenancy {\n const own = option ?? 'inherit';\n const effective: TenancyOption =\n durableWork.getStore() && own !== false\n ? { ...(typeof own === 'object' ? own : {}), required: false }\n : own;\n return readContextTenancy(effective, accessor);\n}\n\n/** The slice of nestjs-context's runtime `Context` that restores a tenant (context ≥ 1.2). */\nexport interface TenantRuntime {\n withTenant<T>(\n input: { id: string; kind: string; source?: string } | null,\n fn: () => T,\n options?: { family?: string },\n ): T;\n}\n\nexport function isTenantRuntime(x: unknown): x is TenantRuntime {\n return !!x && typeof (x as TenantRuntime).withTenant === 'function';\n}\n\n/** The read/write tenancy slot nestjs-context ≥ 2.1 publishes; read structurally, version 1. */\nconst TENANCY_SLOT = Symbol.for('@dudousxd/nestjs-context:tenancy');\n\n/** The context's tenancy slot when one of a version this copy reads is published, else undefined. */\nexport function tenancySlot(): TenantRuntime | undefined {\n const slot = (globalThis as unknown as Record<symbol, unknown>)[TENANCY_SLOT] as\n | { version?: unknown; withTenant?: unknown }\n | undefined;\n return slot?.version === 1 && isTenantRuntime(slot) ? slot : undefined;\n}\n\n/** What restores a tenant: the context's tenancy slot when published, else the runtime `Context`. */\nfunction restorer(runtime: TenantRuntime | undefined): TenantRuntime | undefined {\n return tenancySlot() ?? runtime;\n}\n\n/** Restore `tenant` (read from a run row or a task carrier) as the context tenant around `fn`. */\nfunction restore<T>(\n runtime: TenantRuntime,\n option: DurableTenancyOption | undefined,\n tenant: RunTenant,\n fn: () => T,\n): T {\n const family = typeof option === 'object' ? option.family : undefined;\n const ref = { id: tenant.id, kind: tenant.kind ?? 'unknown', source: 'carrier' };\n return family !== undefined\n ? runtime.withTenant(ref, fn, { family })\n : runtime.withTenant(ref, fn);\n}\n\n/**\n * The engine's tenancy seam (core `EngineTenancy`), or undefined when durable's tenancy is `false`\n * or the installed context cannot restore a tenant. Every member reads the context at call time.\n */\nexport function buildEngineTenancy(\n option: DurableTenancyOption | undefined,\n accessor: ContextAccessor | undefined,\n runtime: TenantRuntime | undefined,\n): EngineTenancy | undefined {\n if (option === false || !restorer(runtime)) return undefined;\n return {\n current(): RunTenant | undefined {\n const t = readTenancy(option, accessor);\n if (!t.enabled) return undefined;\n const f = t.filter();\n return f.mode === 'tenant' ? { id: f.tenant.id, kind: f.tenant.kind } : undefined;\n },\n filter: () => tenantFilterNow(option, accessor),\n run: (tenant, fn) => {\n const using = restorer(runtime);\n return using ? restore(using, option, tenant, fn) : fn();\n },\n system: inDurableWork,\n };\n}\n\n/** The matching filter (core `TenantFilter`) for an app-facing call made now. */\nexport function tenantFilterNow(\n option: DurableTenancyOption | undefined,\n accessor: ContextAccessor | undefined,\n): TenantFilter {\n const t = readTenancy(option, accessor);\n if (!t.enabled) return { mode: 'system' };\n const f = t.filter();\n if (f.mode === 'tenant') return { mode: 'tenant', tenantId: f.tenant.id, nullRows: t.nullRows };\n if (f.mode === 'tenantless') return { mode: 'tenantless' };\n return f.mode === 'all' ? { mode: 'all' } : { mode: 'system' };\n}\n\n/** The tenant a task carrier holds (`tenant`, else a plain `tenantId`), or undefined. */\nexport function tenantFromCarrier(\n carrier: Record<string, unknown> | undefined,\n): RunTenant | undefined {\n const ref = carrier?.tenant as { id?: unknown; kind?: unknown } | undefined;\n if (ref && typeof ref.id === 'string') {\n return typeof ref.kind === 'string' ? { id: ref.id, kind: ref.kind } : { id: ref.id };\n }\n const id = carrier?.tenantId;\n return typeof id === 'string' ? { id } : undefined;\n}\n\n/**\n * A durable execution wrapper that runs each dispatched step handler in the tenant its task\n * carries, whatever transport delivered it and whichever process runs it. The handler runs as\n * durable's own work, so a task with no tenant does not trip a tenant-required context.\n */\nexport function stepTenantWrapper(\n option: DurableTenancyOption | undefined,\n accessor: ContextAccessor | undefined,\n runtime: TenantRuntime | undefined,\n): (\n execution: { unit: 'workflow' | 'step'; context?: Record<string, unknown> | undefined },\n next: () => Promise<unknown>,\n) => Promise<unknown> {\n return (execution, next) => {\n if (execution.unit !== 'step') return next();\n return inDurableWork(() => {\n const tenant = tenantFromCarrier(execution.context);\n const using = restorer(runtime);\n if (!tenant || !using || !readTenancy(option, accessor).enabled) return next();\n return restore(using, option, tenant, next);\n });\n };\n}\n\n/** Whether durable's tenancy can restore a tenant here: the context's slot, or its runtime. */\nexport function canRestoreTenant(runtime: unknown): boolean {\n return tenancySlot() !== undefined || isTenantRuntime(runtime);\n}\n\n/** The tenant a `start` made now is stamped with (tenancy on), for a store-less tenant process. */\nexport function currentTenant(\n option: DurableTenancyOption | undefined,\n accessor: ContextAccessor | undefined,\n): RunTenant | undefined {\n const t = readTenancy(option, accessor);\n if (!t.enabled) return undefined;\n const f = t.filter();\n return f.mode === 'tenant' ? { id: f.tenant.id, kind: f.tenant.kind } : undefined;\n}\n\n/** Console labels keyed by tenant id: the app's `tenancy.label`, else the slug, else the id. */\nexport function tenantLabels(\n tenants: TenantLevel[],\n accessor?: ContextAccessor | undefined,\n): Promise<Record<string, string>> {\n return readTenantLabels(tenants, accessor);\n}\n","// Local reader for the @dudousxd/nestjs-context tenancy contract. Copied into each lib;\n// it imports nothing, so the lib works with any context version or none at all.\nexport interface TenantLevel {\n id: string;\n kind: string;\n slug?: string;\n role?: string;\n}\nexport interface TenantRef extends TenantLevel {\n source: string;\n chain?: TenantLevel[]; // root first, this tenant last; absent for a flat tenant\n family?: string;\n}\nexport type TenantFilter =\n | { mode: 'system' }\n | { mode: 'all' }\n | { mode: 'tenantless' }\n | { mode: 'tenant'; tenant: TenantRef; chain?: TenantLevel[] }; // `chain`: context >= 2.1\nexport type TenancyOption =\n | 'inherit'\n | false\n | {\n enabled?: 'inherit' | boolean;\n kinds?: string[];\n family?: string;\n required?: boolean;\n nullRows?: 'tenantless' | 'shared';\n };\nexport type Tenancy =\n | { enabled: false }\n | { enabled: true; nullRows: 'tenantless' | 'shared'; filter(): TenantFilter };\n\ninterface FilterOptions {\n kinds?: string[];\n family?: string;\n required?: boolean;\n}\ninterface Accessor {\n tenancy?(): { enabled: boolean; kinds?: string[]; required?: boolean };\n tenantFilter?(options?: FilterOptions): TenantFilter;\n tenantLabels?(tenants: TenantLevel[]): Promise<Record<string, string>>;\n}\nconst SLOT = Symbol.for('@dudousxd/nestjs-diagnostics:accessor');\n\nfunction accessorOf(accessor: unknown): Accessor | undefined {\n const slot = (globalThis as unknown as Record<symbol, { current?: unknown } | undefined>)[SLOT];\n return (accessor ?? slot?.current ?? undefined) as Accessor | undefined;\n}\n\n/** `accessor`: the `CONTEXT_ACCESSOR` injected with `@Optional()`, if any. Call per operation. */\nexport function readTenancy(option: TenancyOption = 'inherit', accessor?: unknown): Tenancy {\n const a = accessorOf(accessor);\n if (option === false || typeof a?.tenancy !== 'function' || !a.tenantFilter) {\n return { enabled: false };\n }\n const own = typeof option === 'object' ? option : {};\n const inherit = own.enabled === undefined || own.enabled === 'inherit';\n if (!(inherit ? a.tenancy().enabled : own.enabled)) return { enabled: false };\n const options: FilterOptions = {};\n if (own.kinds) options.kinds = own.kinds;\n if (own.family !== undefined) options.family = own.family;\n if (own.required !== undefined) options.required = own.required;\n const tenantFilter = a.tenantFilter.bind(a);\n return {\n enabled: true,\n nullRows: own.nullRows ?? 'tenantless',\n // Throws the context's TenantRequiredError (403) when a tenant is required and missing.\n filter: () => tenantFilter(Object.keys(options).length > 0 ? options : undefined),\n };\n}\n\n/** The matching rule: may this request see a row whose tenant column holds `rowTenantId`? */\nexport function canSeeRow(t: Tenancy, rowTenantId: string | null | undefined): boolean {\n if (!t.enabled) return true;\n const f = t.filter();\n if (f.mode === 'system' || f.mode === 'all') return true;\n if (rowTenantId === null || rowTenantId === undefined) {\n return f.mode === 'tenantless' || t.nullRows === 'shared';\n }\n return f.mode === 'tenant' && f.tenant.id === rowTenantId;\n}\n\n/** The tenant id to stamp on a new row: the active tenant's id, else `null`. */\nexport function rowTenantId(t: Tenancy): string | null {\n if (!t.enabled) return null;\n const f = t.filter();\n return f.mode === 'tenant' ? f.tenant.id : null;\n}\n\n/** Console labels keyed by tenant id: the app's `tenancy.label`, else the slug, else the id. */\nexport async function tenantLabels(\n tenants: TenantLevel[],\n accessor?: unknown,\n): Promise<Record<string, string>> {\n const a = accessorOf(accessor);\n if (typeof a?.tenantLabels === 'function') {\n try {\n return await a.tenantLabels(tenants);\n } catch {\n // Fall back to slug/id below.\n }\n }\n const out: Record<string, string> = {};\n for (const t of tenants) out[t.id] = t.slug || t.id;\n return out;\n}\n","import type {\n TenantTokenSource,\n TenantVerifier,\n VerifiedTenant,\n} from '@dudousxd/nestjs-durable-core';\nimport type { ModuleRef } from '@nestjs/core';\n\n/** What a tenant verifier receives for each request a tenant process sends. */\nexport interface TenantVerifierInput {\n /** The token presented on the request (the wire `tenant` field). */\n token?: string | undefined;\n /** The tenant the request *claims* to be. Advisory only: derive the real one from the token. */\n tenant?: string | undefined;\n}\n\n/**\n * The object/class form of `verifyTenant`. Runs on the control plane for every request a tenant\n * process sends.\n */\nexport interface TenantVerifierContract {\n /**\n * Turn the wire token into the tenant it authenticates as. Return `null` to reject: the request is\n * answered `unauthorized` and never touches a run. Throw when you cannot decide (the identity\n * provider is down): the request fails with the error and the next one calls `verify` again. The\n * returned `tenant` is trusted as-is, so derive it from the verified token, never from\n * `input.tenant`.\n */\n verify(input: TenantVerifierInput): VerifiedTenant | null | Promise<VerifiedTenant | null>;\n}\n\n/**\n * The object/class form of `tenantToken`. Runs on the tenant process before every request it sends.\n */\nexport interface TenantCredentialsContract {\n /**\n * The token to present on the next request, sent as-is in the wire `tenant` field. Called once per\n * request, so cache the token and fetch a new one before it expires. A throw (or an empty string)\n * fails that request; the next request calls `token()` again.\n */\n token(): string | Promise<string>;\n}\n\n/** A class implementing a contract; its constructor parameters are resolved by Nest DI. */\nexport type ContractClass<T> = new (...args: any[]) => T;\n\n/** A lazy import of a module whose default export is a contract class or object. */\nexport type LazyContract<T> = () => Promise<{ default: ContractClass<T> | T }>;\n\n/**\n * The `verifyTenant` option: a function (e.g. `hmacTenantVerifier(secret)`), an object implementing\n * {@link TenantVerifierContract}, a class implementing it (built once through Nest DI: the registered\n * provider when there is one, else `ModuleRef.create`), or a lazy import of a module whose default\n * export is such a class or object (imported once).\n */\nexport type TenantVerifierOption =\n | TenantVerifier\n | TenantVerifierContract\n | ContractClass<TenantVerifierContract>\n | LazyContract<TenantVerifierContract>;\n\n/**\n * The `tenantToken` option: a string, a function called before every request, an object implementing\n * {@link TenantCredentialsContract}, a class implementing it (built once through Nest DI), or a lazy\n * import of a module whose default export is such a class or object (imported once).\n */\nexport type TenantTokenOption =\n | TenantTokenSource\n | TenantCredentialsContract\n | ContractClass<TenantCredentialsContract>\n | LazyContract<TenantCredentialsContract>;\n\n/** Marks a function this module already resolved, so resolving it again returns it unchanged. */\nconst RESOLVED = Symbol('nestjs-durable:resolved-tenant-auth');\n\nfunction markResolved<F extends object>(fn: F): F {\n Object.defineProperty(fn, RESOLVED, { value: true });\n return fn;\n}\n\nfunction isResolved(value: unknown): boolean {\n return typeof value === 'function' && (value as { [RESOLVED]?: true })[RESOLVED] === true;\n}\n\n/** Any `class`, or a function whose prototype carries `method` (a transpiled class). */\nfunction isClass(value: unknown, method: string): value is ContractClass<unknown> {\n if (typeof value !== 'function') return false;\n const proto = (value as { prototype?: Record<string, unknown> }).prototype;\n if (typeof proto?.[method] === 'function') return true;\n return /^class[\\s{]/.test(Function.prototype.toString.call(value));\n}\n\nfunction hasMethod<T>(value: unknown, method: string): value is T {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Record<string, unknown>)[method] === 'function'\n );\n}\n\n/** A module object returned by a lazy `import()`: its `default` is a contract class or object. */\nfunction lazyDefault(value: unknown, method: string): unknown {\n if (typeof value !== 'object' || value === null || !('default' in value)) return undefined;\n const target = (value as { default: unknown }).default;\n return isClass(target, method) || hasMethod(target, method) ? target : undefined;\n}\n\n/**\n * Builds a contract class once: the registered provider when the app registers it, else a fresh\n * instance through `ModuleRef.create` (so constructor injection works). Without a `ModuleRef` it is\n * constructed with `new`. A failed construction is retried on the next call.\n */\nfunction instanceFactory<T>(\n Class: ContractClass<T>,\n moduleRef: ModuleRef | undefined,\n): () => Promise<T> {\n let pending: Promise<T> | undefined;\n return () => {\n pending ??= (async (): Promise<T> => {\n if (!moduleRef) return new Class();\n try {\n const registered = moduleRef.get<T>(Class, { strict: false });\n if (registered) return registered;\n } catch {\n // Not a registered provider: create it below.\n }\n try {\n return await moduleRef.create<T>(Class);\n } catch (cause) {\n throw new Error(\n `could not build ${Class.name || 'the tenant auth class'}: register it as a provider in your module, or make its dependencies global`,\n { cause },\n );\n }\n })();\n pending.catch(() => {\n pending = undefined;\n });\n return pending;\n };\n}\n\n/** Resolves a contract target (class or object) to a getter of its instance. */\nfunction contractInstance<T>(\n target: unknown,\n method: string,\n moduleRef: ModuleRef | undefined,\n): () => Promise<T> {\n if (isClass(target, method)) return instanceFactory(target as ContractClass<T>, moduleRef);\n const instance = Promise.resolve(target as T);\n return () => instance;\n}\n\n/** What a function-form option turned out to be on a call: a contract instance, or a plain result. */\ntype Probed<T> = { contract: T } | { result: unknown };\n\n/**\n * Calls a function-form option, which is either the plain function or a lazy import; which one is\n * only known once it has run. The first call probes, and calls racing it wait for that probe, so a\n * lazy import runs exactly once and its default export is built once. A failed probe (the import\n * threw) is retried by the next call. Once known to be plain, the function is called on every call.\n */\nfunction functionOrLazy<T>(\n fn: (...args: any[]) => unknown,\n method: string,\n moduleRef: ModuleRef | undefined,\n): (...args: unknown[]) => Promise<Probed<T>> {\n let lazy: (() => Promise<T>) | undefined;\n let plain = false;\n let probing: Promise<unknown> | undefined;\n return async (...args) => {\n for (;;) {\n if (lazy) return { contract: await lazy() };\n if (plain) return { result: await fn(...args) };\n if (!probing) {\n const probe = (async () => fn(...args))();\n probing = probe;\n try {\n const result = await probe;\n const target = lazyDefault(result, method);\n if (target === undefined) {\n plain = true;\n return { result };\n }\n lazy = contractInstance<T>(target, method, moduleRef);\n return { contract: await lazy() };\n } finally {\n if (probing === probe) probing = undefined;\n }\n }\n await probing.catch(() => undefined);\n }\n };\n}\n\n/**\n * Turns any {@link TenantVerifierOption} into the plain {@link TenantVerifier} the engine and the\n * responder call. A class is built once, on the first request; a lazy import runs once.\n */\nexport function resolveTenantVerifier(\n option: TenantVerifierOption | undefined,\n moduleRef?: ModuleRef,\n): TenantVerifier | undefined {\n if (option === undefined || isResolved(option)) return option as TenantVerifier | undefined;\n const instance =\n isClass(option, 'verify') || hasMethod<TenantVerifierContract>(option, 'verify')\n ? contractInstance<TenantVerifierContract>(option, 'verify', moduleRef)\n : undefined;\n if (!instance && typeof option !== 'function') {\n throw new Error(\n '`verifyTenant` must be a function, an object or class with verify(), or a lazy import of one.',\n );\n }\n const call = functionOrLazy<TenantVerifierContract>(\n option as (input: TenantVerifierInput) => unknown,\n 'verify',\n moduleRef,\n );\n return markResolved(async (input: TenantVerifierInput): Promise<VerifiedTenant | null> => {\n if (instance) return (await instance()).verify(input);\n const probed = await call(input);\n if ('contract' in probed) return probed.contract.verify(input);\n return probed.result as VerifiedTenant | null;\n });\n}\n\nfunction requireToken(token: unknown): string {\n if (typeof token !== 'string' || token.length === 0) {\n throw new Error('tenantToken produced no token (an empty or non-string value)');\n }\n return token;\n}\n\n/**\n * Turns any {@link TenantTokenOption} into the {@link TenantTokenSource} the wire layer uses: a\n * static string stays a string, every other form becomes a function called before each request.\n */\nexport function resolveTenantTokenSource(\n option: TenantTokenOption | undefined,\n moduleRef?: ModuleRef,\n): TenantTokenSource | undefined {\n if (typeof option === 'string') {\n if (option.length === 0) {\n throw new Error(\n '`tenantToken` is an empty string. Set the token this tenant presents, or remove `tenantToken` to send the partition.',\n );\n }\n return option;\n }\n if (option === undefined || isResolved(option)) return option as TenantTokenSource | undefined;\n const instance =\n isClass(option, 'token') || hasMethod<TenantCredentialsContract>(option, 'token')\n ? contractInstance<TenantCredentialsContract>(option, 'token', moduleRef)\n : undefined;\n if (!instance && typeof option !== 'function') {\n throw new Error(\n '`tenantToken` must be a string, a function, an object or class with token(), or a lazy import of one.',\n );\n }\n const call = functionOrLazy<TenantCredentialsContract>(\n option as () => unknown,\n 'token',\n moduleRef,\n );\n return markResolved(async (): Promise<string> => {\n if (instance) return requireToken(await (await instance()).token());\n const probed = await call();\n if ('contract' in probed) return requireToken(await probed.contract.token());\n return requireToken(probed.result);\n });\n}\n","import type { DurableWorkerRuntime } from '@dudousxd/durable-worker';\n\n/** The `@dudousxd/durable-worker` module shape. `typeof import()` is erased, so this costs nothing. */\ntype WorkerSdk = typeof import('@dudousxd/durable-worker');\n\n/**\n * The single gate to `@dudousxd/durable-worker`. It is an OPTIONAL peer because only the roles that\n * EXECUTE workflow bodies need it — a pure operator (`store` + `transport`, no `connection`) never\n * runs a worker and is entitled to install without it. A static import would resolve it for every\n * consumer at `import '@dudousxd/nestjs-durable'`, so such an operator would die at boot with\n * `ERR_MODULE_NOT_FOUND` on a package it was told was optional.\n *\n * Every value from the SDK therefore crosses this module and nothing here is reachable from an\n * import of the package entry. Node caches the resolved module, so each call after the first is a\n * cache hit; the call sites below are per-`start` or per-bootstrap, never per-turn. Mirrors how\n * `@dudousxd/durable-worker` itself reaches its own optional `bullmq`/`ioredis` peers.\n */\nasync function workerSdk(): Promise<WorkerSdk> {\n try {\n return await import('@dudousxd/durable-worker');\n } catch (cause) {\n throw new Error(\n '@dudousxd/durable-worker is not installed. It is an optional peer needed only by the roles that run workflow bodies (`connection` set on DurableModule.forRoot) — install it, or drop `connection`.',\n { cause },\n );\n }\n}\n\n/** Publish a `StartRunMessage` on the shared start-run queue. One import per `start`, then cached. */\nexport const startRun: WorkerSdk['startRun'] = async (connection, options) =>\n (await workerSdk()).startRun(connection, options);\n\n/** Start a BullMQ consumer for a runtime's registered names. Called once, on app bootstrap. */\nexport const runRedisWorker: WorkerSdk['runRedisWorker'] = async (options) =>\n (await workerSdk()).runRedisWorker(options);\n\n/** Construct the store-less runtime a worker registers its bodies on. Called once, per role gate. */\nexport async function createWorkerRuntime(\n options: ConstructorParameters<WorkerSdk['DurableWorkerRuntime']>[0],\n): Promise<DurableWorkerRuntime> {\n const { DurableWorkerRuntime: Runtime } = await workerSdk();\n return new Runtime(options);\n}\n","import type {\n DurableWorkerRuntime,\n RunRedisWorkerOptions,\n RunningWorker,\n} from '@dudousxd/durable-worker';\nimport {\n type AnnouncedSchedule,\n DURABLE_OPTIONS_CANONICAL,\n type DurableTopology,\n type EngineEvent,\n type GroupHealth,\n type RunDetail,\n type RunFacetQuery,\n type RunFacetRow,\n type RunGateway,\n type RunListItem,\n type RunQuery,\n type RunResult,\n type RunValueAxis,\n type RunValueFacetOptions,\n type RunValueFacetRow,\n type RunWaiting,\n type ScheduleAnnouncement,\n type ScheduledWorkflow,\n type TenantTokenSource,\n WorkflowEngine,\n type WorkflowStartClient,\n bindWorkflowClass,\n resolveTenantToken,\n workflowName,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n Inject,\n Injectable,\n type OnApplicationBootstrap,\n type OnApplicationShutdown,\n type OnModuleInit,\n type Provider,\n} from '@nestjs/common';\nimport { DiscoveryService, MetadataScanner } from '@nestjs/core';\nimport { eventBatchOf, getOnEvents, getWorkflowMeta, isDeadLetterHandler } from './decorators';\nimport { scanSteps, scanWorkflows } from './discovery-helpers';\nimport type { DurableStartClient, TenantWorkflowStartPolicy } from './durable-start-client';\nimport type { DurableModuleOptions, ResolvedTenantAuth } from './durable.module';\nimport { getEntityMeta } from './entity';\nimport { registerOnRuntime } from './runtime-registration';\nimport { type DurableStepInterceptor, isStepInterceptor } from './step-interceptor';\nimport { TENANT_AUTH } from './tokens';\nimport { createWorkerRuntime, runRedisWorker as defaultRunRedisWorker } from './worker-sdk';\nimport { workflowIo } from './workflow-io';\n\n/** The instance's `@DeadLetter()` method bound to it, or undefined if it has none. */\nfunction deadLetterHandlerOf(\n instance: object,\n scanner: MetadataScanner,\n): ((ctx: unknown, input: unknown) => Promise<unknown>) | undefined {\n for (const name of scanner.getAllMethodNames(Object.getPrototypeOf(instance))) {\n const method = (instance as Record<string, unknown>)[name];\n if (typeof method === 'function' && isDeadLetterHandler(method)) {\n return (ctx, input) => method.call(instance, ctx, input);\n }\n }\n return undefined;\n}\n\n/**\n * The `runRedisWorker` function the module uses to start each partition's BullMQ consumer.\n * Defaults to the real one from `@dudousxd/durable-worker`; tests `overrideProvider` it with a\n * fake so no real Redis is needed.\n */\nexport const RUN_REDIS_WORKER = Symbol('nestjs-durable:run-redis-worker');\n\n/**\n * The store-less {@link DurableWorkerRuntime} a pure thin worker registers its bodies on — `null` in\n * every other role. A Symbol rather than the class itself: the class lives in an optional peer, and\n * using it as a DI token would drag that peer into the package's static import graph.\n */\nexport const DURABLE_WORKER_RUNTIME = Symbol('nestjs-durable:worker-runtime');\n\n/** The list of started {@link RunningWorker} handles (the single handle {@link ThinWorkerBootstrap}\n * starts), closed on shutdown. */\nexport const DURABLE_WORKER_RUNNERS = Symbol('nestjs-durable:worker-runners');\n\n/** The signature of `runRedisWorker` — injected behind {@link RUN_REDIS_WORKER}. */\nexport type RunRedisWorkerFn = (opts: RunRedisWorkerOptions) => Promise<RunningWorker>;\n\n/** True for the **pure thin-worker** role — `connection` set, `store` unset. `DurableModule`\n * keeps {@link ThinWorkflowRegistrar}/{@link ThinStepRegistrar}/{@link ThinWorkerBootstrap} inert\n * (registered but no-op) outside this role — an operator (`store` set) drives its own bodies\n * inline or, with `connection` also set, through the separate in-app-worker mechanics instead. */\nfunction isPureThinWorker(options: DurableModuleOptions): boolean {\n return options.store === undefined && options.connection !== undefined;\n}\n\n/**\n * Discovers every provider carrying `@Workflow` metadata and registers its `run(ctx, input)` on the\n * thin {@link DurableWorkerRuntime}. Mirrors the engine-side `WorkflowRegistrar`, but registers on\n * the runner-core runtime instead of a `WorkflowEngine` — the runtime drives `run` with the thin\n * `WorkflowContext` (which `implements WorkflowCtx`), so the body runs unchanged. NO store/engine.\n * Inert (skips registration) outside the pure thin-worker role — see {@link isPureThinWorker}.\n */\n@Injectable()\nexport class ThinWorkflowRegistrar implements OnModuleInit {\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly metadataScanner: MetadataScanner,\n @Inject(DURABLE_WORKER_RUNTIME) private readonly runtime: DurableWorkerRuntime | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n /** In this role the store-less `DurableStartClient` facade the module binds under this token. */\n @Inject(WorkflowEngine) private readonly starter: WorkflowStartClient,\n ) {}\n\n onModuleInit(): void {\n const runtime = this.runtime;\n if (runtime === null || !isPureThinWorker(this.options)) return;\n const starter = this.starter;\n this.assertNoEntities();\n this.useInterceptors(runtime);\n const fallback = this.options.deadLetterWorkflow\n ? workflowName(this.options.deadLetterWorkflow)\n : undefined;\n // The `@Workflow` metadata is also what this worker ANNOUNCES about each body it serves (design\n // §7.9) — version, capability demand, and the declaring package `scanWorkflows` derived. It is\n // passed straight through: the registry states what the decorator states, and an option the\n // decorator left off stays un-stated rather than becoming a default.\n scanWorkflows(this.discovery, (meta, instance, origin) => {\n // A dead run of this workflow is routed by the control plane to the handler announced here: an\n // inline `@DeadLetter()` method (registered beside the body as `<name>.dlq`, so it runs on this\n // app), else the `deadLetterWorkflow` reference, else the module-level default.\n const inline = deadLetterHandlerOf(instance as unknown as object, this.metadataScanner);\n if (inline && meta.deadLetterWorkflow) {\n throw new Error(\n `@Workflow ${meta.name} declares both an inline @DeadLetter() method and a deadLetterWorkflow option. Use one: the inline handler, or the reference.`,\n );\n }\n const deadLetter = inline\n ? `${meta.name}.dlq`\n : meta.deadLetterWorkflow\n ? workflowName(meta.deadLetterWorkflow)\n : fallback;\n registerOnRuntime(runtime, this.metadataScanner, meta, instance, origin, deadLetter);\n if (inline) {\n runtime.registerWorkflow(`${meta.name}.dlq`, inline, {\n version: meta.version,\n ...(origin !== undefined ? { origin } : {}),\n });\n }\n // The options only this app can evaluate (they are functions of the input), applied by its\n // own starts: the input schema, the singleton key, the default quota, the event subscriptions.\n const declare = (starter as unknown as Partial<DurableStartClient>).declareWorkflow;\n if (typeof declare === 'function') {\n const io = workflowIo(meta);\n const policy: TenantWorkflowStartPolicy = {\n validateInput: io.validateParsed,\n parseInput: io.parseInput,\n singleton: meta.singleton,\n concurrency: meta.concurrency,\n onEvent: getOnEvents(meta, instance.constructor),\n coalesces: eventBatchOf(meta, instance.constructor) !== undefined,\n };\n declare.call(starter, meta.name, policy);\n }\n // Class-first statics (`MyWorkflow.start()`), as on an operator: bound to the start facade, so\n // they publish a start-run message to the control plane. `waitForRun` stays unbound (a tenant\n // has no store), so `MyWorkflow.execute()` outside a workflow fails with a clear error.\n bindWorkflowClass(instance.constructor, {\n start: (name, input, runId, opts) => starter.start(name, input, runId, opts),\n });\n });\n }\n\n /**\n * `@Entity` providers are refused on a tenant, at boot: an entity's state is a run on the store\n * and its `@On` handlers run inside the engine that owns that store (`EntityService` and\n * `ctx.callEntity`/`signalEntity` read and serialize it there). A tenant has no store and no\n * engine, so an entity declared here would never run. Declare it on the control plane.\n */\n private assertNoEntities(): void {\n const entities = this.discovery\n .getProviders()\n .map((w) => w.instance as object | undefined)\n .filter((i): i is object => !!i && typeof i === 'object' && !!getEntityMeta(i.constructor))\n .map((i) => getEntityMeta(i.constructor)?.name);\n if (entities.length === 0) return;\n throw new Error(\n `@Entity ${entities.join(', ')} cannot be declared on a DurableModule tenant (connection, no store): an entity's state and handlers live in the engine that owns the store. Declare it on the control plane.`,\n );\n }\n\n /**\n * `@StepInterceptor()` providers wrap every step this tenant runs (each `ctx.step` its workers\n * execute), as `engine.use` does on an engine. A `@durable-worker` too old to take interceptors\n * says so instead of dropping them silently.\n */\n private useInterceptors(runtime: DurableWorkerRuntime): void {\n for (const wrapper of this.discovery.getProviders()) {\n const instance = wrapper.instance as object | undefined;\n if (!instance || typeof instance !== 'object' || !isStepInterceptor(instance.constructor)) {\n continue;\n }\n const interceptor = instance as DurableStepInterceptor;\n if (typeof runtime.use !== 'function') {\n console.warn(\n `[nestjs-durable] @StepInterceptor ${instance.constructor.name} is not applied: this @dudousxd/durable-worker predates step interceptors on a tenant; upgrade it.`,\n );\n continue;\n }\n runtime.use((invocation, next) => interceptor.intercept(invocation, next));\n }\n }\n}\n\n/**\n * Discovers every `@Step` method and registers it as a step handler on the thin\n * {@link DurableWorkerRuntime}. Mirrors the engine-side `DurableStepRegistrar`, but always registers\n * on the runtime (a thin worker IS the consumer — there is no in-process-vs-queue branch). Inert\n * outside the pure thin-worker role — see {@link isPureThinWorker}.\n */\n@Injectable()\nexport class ThinStepRegistrar implements OnModuleInit {\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly metadataScanner: MetadataScanner,\n @Inject(DURABLE_WORKER_RUNTIME) private readonly runtime: DurableWorkerRuntime | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n ) {}\n\n onModuleInit(): void {\n const runtime = this.runtime;\n if (runtime === null || !isPureThinWorker(this.options)) return;\n scanSteps(this.discovery, this.metadataScanner, (meta, handler) =>\n runtime.registerStep(meta.name, handler),\n );\n }\n}\n\n/**\n * Starts ONE `runRedisWorker` call on bootstrap — after both registrars have run, so every handler\n * is registered before any task is consumed — and closes it on shutdown. The runner (`@dudousxd/\n * durable-worker`) derives its subscription from `runtime.registeredNames()` (one queue per\n * registered `@Workflow`/`@Step` name), not a hand-declared group list. Inert outside the pure\n * thin-worker role — see {@link isPureThinWorker}: an operator (`store` set) never starts this\n * consumer, and `store + connection` starts its OWN co-located consumer instead (`in-app-worker.ts`).\n *\n * For the shutdown close to fire, enable Nest's shutdown hooks: `app.enableShutdownHooks()`.\n */\n@Injectable()\nexport class ThinWorkerBootstrap implements OnApplicationBootstrap, OnApplicationShutdown {\n private readonly runners: RunningWorker[] = [];\n\n constructor(\n @Inject(DURABLE_WORKER_RUNTIME) private readonly runtime: DurableWorkerRuntime | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n @Inject(RUN_REDIS_WORKER) private readonly runRedisWorker: RunRedisWorkerFn,\n @Inject(DURABLE_WORKER_RUNNERS) private readonly runnersSink: RunningWorker[],\n @Inject(TENANT_AUTH) private readonly auth: ResolvedTenantAuth,\n ) {}\n\n async onApplicationBootstrap(): Promise<void> {\n const options = this.options;\n const runtime = this.runtime;\n if (runtime === null || !isPureThinWorker(options) || options.connection === undefined) return;\n // `consumers: false`: a producer-only process (CLI, REPL, script) starts no consumer.\n if (options.consumers === false) {\n if ((options.schedules?.length ?? 0) > 0) {\n console.warn(\n '[nestjs-durable] `schedules` on a tenant with `consumers: false` are not announced: a tenant announces its schedules on its worker descriptor, so declare them on the processes that run its workers.',\n );\n }\n return;\n }\n // ONE call: the runner subscribes one queue per name registered on `runtime` — populated by\n // `ThinWorkflowRegistrar`/`ThinStepRegistrar`'s `onModuleInit`, which Nest's lifecycle guarantees\n // run (across the whole app) before any `onApplicationBootstrap` hook.\n const handle = await this.runRedisWorker({\n runtime,\n connection: options.connection,\n ...(options.partition !== undefined ? { partition: options.partition } : {}),\n ...(options.prefix !== undefined ? { prefix: options.prefix } : {}),\n ...(options.instanceId !== undefined ? { instanceId: options.instanceId } : {}),\n ...(options.concurrency !== undefined ? { concurrency: options.concurrency } : {}),\n // Announce the app's schedules (an empty list too) so the control plane adopts, updates and\n // withdraws them: a tenant has no store to fire them from.\n ...(await tenantScheduleAnnouncement(options, this.auth.tenantToken)),\n });\n this.runners.push(handle);\n this.runnersSink.push(handle);\n }\n\n async onApplicationShutdown(): Promise<void> {\n await Promise.allSettled(this.runners.map((h) => h.close()));\n }\n}\n\n/**\n * The tenant's `schedules`, as its worker announces them: under the wire tenant its starts carry (the\n * signed token when the app has one, else the partition), one {@link AnnouncedSchedule} per schedule.\n * A schedule's `namespace` is dropped (a tenant's runs always belong to its own namespace), and\n * `backfill` becomes the control plane's `catchup: 'latest'` (at most one late window).\n */\nexport async function tenantScheduleAnnouncement(\n options: DurableModuleOptions,\n tenantToken: TenantTokenSource | undefined,\n): Promise<{ schedules?: ScheduleAnnouncement }> {\n let tenant: string;\n try {\n tenant =\n tenantToken !== undefined\n ? await resolveTenantToken(tenantToken)\n : (options.partition ?? 'default');\n } catch (error) {\n // A token source that fails at boot must not keep the worker from starting: it announces no\n // schedules (the control plane then neither adopts nor withdraws any for it) and says so.\n console.warn(\n `[nestjs-durable] this worker announces no schedules: its tenantToken failed (${error instanceof Error ? error.message : String(error)})`,\n );\n return {};\n }\n return {\n schedules: {\n tenant,\n items: await Promise.all((options.schedules ?? []).map(announcedSchedule)),\n },\n };\n}\n\n/** A schedule's input as its singleton key reads it: parsed when the workflow has an `input` schema.\n * A fixed input that does not parse keeps the input as written (each fire is then rejected at start,\n * where the error is reported), so one bad schedule does not keep the worker from announcing. */\nasync function scheduleKeyInput(\n parseInput: ((input: unknown) => Promise<unknown>) | undefined,\n input: unknown,\n): Promise<unknown> {\n if (!parseInput) return input;\n try {\n return await parseInput(input);\n } catch {\n return input;\n }\n}\n\nasync function announcedSchedule(s: ScheduledWorkflow): Promise<AnnouncedSchedule> {\n const item: AnnouncedSchedule = { key: s.key, workflow: workflowName(s.workflow) };\n if (s.input !== undefined) item.input = s.input;\n if (s.everyMs !== undefined) item.everyMs = s.everyMs;\n if (s.cron !== undefined) item.cron = s.cron;\n if (s.timezone !== undefined) item.timezone = s.timezone;\n if (s.paused === true) item.paused = true;\n if (s.overlap !== undefined) item.overlap = s.overlap;\n if (s.jitter !== undefined && s.jitter > 0) item.jitterMs = s.jitter;\n // A singleton workflow's key is a function of the input, so it is evaluated here, once, against\n // the schedule's fixed input (by class only: a name gives no `@Workflow` metadata to read). Like\n // every key, it reads the input as `run` will: parsed by the workflow's `input` schema.\n const meta = typeof s.workflow === 'function' ? getWorkflowMeta(s.workflow) : undefined;\n const singleton = meta?.singleton;\n if (meta && singleton) {\n const parseInput = workflowIo(meta).parseInput;\n item.singleton = {\n key: singleton.key(await scheduleKeyInput(parseInput, s.input)),\n ...(singleton.limit !== undefined ? { limit: singleton.limit } : {}),\n ...(singleton.maxQueueDepth !== undefined ? { maxQueueDepth: singleton.maxQueueDepth } : {}),\n };\n }\n return item;\n}\n\n/**\n * The thin-worker slice of {@link import('./durable.module').DurableModule}'s unified provider set —\n * active for the pure thin-worker role (`connection` set, `store` unset): registers discovered\n * `@Workflow`/`@Step` on a store-less {@link DurableWorkerRuntime} and starts ONE `runRedisWorker`\n * consumer, one queue PER REGISTERED NAME. Always present in the provider list (so a single\n * `DurableModule.forRootAsync` can serve any role once its options resolve); every class/factory here\n * is inert (see {@link isPureThinWorker}) outside that role.\n */\nexport function thinWorkerProviders(): Provider[] {\n return [\n {\n provide: DURABLE_WORKER_RUNTIME,\n // The runtime's `WorkflowWorker` falls back to its own `group` ctor param as the WORKFLOW's\n // `workflowPartition` for any `ctx.step` call (see `workflow-context.ts`'s `resolveCallGroup`)\n // — that fallback MUST equal this module's own `partition`, or a dispatched step's decision\n // carries a mismatched token and the engine dispatches it to a queue nothing here subscribes\n // to. Explicit `''` (never\n // `undefined`) so it does NOT fall through to `WorkflowWorker`'s unrelated `'workflows'`\n // default parameter.\n //\n // The role gate lives HERE, not just in the consumers: constructing the runtime resolves the\n // optional `@dudousxd/durable-worker` peer, so an operator that never runs a worker must not\n // reach this branch at all.\n useFactory: (options: DurableModuleOptions) =>\n isPureThinWorker(options)\n ? createWorkerRuntime({ workflowGroup: options.partition ?? '' })\n : null,\n inject: [DURABLE_OPTIONS_CANONICAL],\n },\n { provide: RUN_REDIS_WORKER, useValue: defaultRunRedisWorker },\n { provide: DURABLE_WORKER_RUNNERS, useValue: [] as RunningWorker[] },\n ThinWorkflowRegistrar,\n ThinStepRegistrar,\n ThinWorkerBootstrap,\n ];\n}\n\n/** Reject with a clear, named tenant error for a `RunGateway` call made without a `transport`. The\n * call site pins `T` from its own declared return type (e.g. `Promise<RunDetail | null>`); this\n * helper only ever rejects, so it never actually produces a `T` value. */\nfunction tenantGatewayUnavailable<T>(method: string): Promise<T> {\n return Promise.reject(\n new Error(`RunGateway.${method}() is not available — pass \\`transport\\` to use RunGateway.`),\n );\n}\n\n/**\n * The no-transport fallback bound to `RunGateway` for a thin worker (`connection` set, `store`\n * unset) that didn't also pass a `transport` — mirrors `DurableStartClient`'s tenant-error idiom\n * (`tenantUnsupported`): every method rejects with a clear, named error instead of a cryptic\n * `this.gateway.X is not a function`. `subscribe` is synchronous on the `RunGateway` port, so it\n * throws synchronously (same message) rather than returning a rejected promise.\n */\nexport function unavailableRunGateway(): RunGateway {\n return {\n // Topology is local metadata, always answerable — a thin worker with no transport is still a tenant.\n topology(): DurableTopology {\n return { role: 'tenant' };\n },\n getRunDetail(_runId: string): Promise<RunDetail | null> {\n return tenantGatewayUnavailable<RunDetail | null>('getRunDetail');\n },\n listRuns(_query: RunQuery): Promise<RunListItem[]> {\n return tenantGatewayUnavailable<RunListItem[]>('listRuns');\n },\n runFacets(_query: RunFacetQuery): Promise<RunFacetRow[]> {\n return tenantGatewayUnavailable<RunFacetRow[]>('runFacets');\n },\n runValueFacets(\n _axis: RunValueAxis,\n _query: RunFacetQuery,\n _opts?: RunValueFacetOptions,\n ): Promise<RunValueFacetRow[]> {\n return tenantGatewayUnavailable<RunValueFacetRow[]>('runValueFacets');\n },\n waitingFor(_runIds: string[]): Promise<Record<string, RunWaiting>> {\n return tenantGatewayUnavailable<Record<string, RunWaiting>>('waitingFor');\n },\n workerHealth(): Promise<GroupHealth[]> {\n return tenantGatewayUnavailable<GroupHealth[]>('workerHealth');\n },\n cancel(_runId: string): Promise<RunResult | null> {\n return tenantGatewayUnavailable<RunResult | null>('cancel');\n },\n retry(_runId: string): Promise<RunResult | null> {\n return tenantGatewayUnavailable<RunResult | null>('retry');\n },\n continue(_runId: string): Promise<RunResult | null> {\n return tenantGatewayUnavailable<RunResult | null>('continue');\n },\n retryWithInput(_runId: string, _input: unknown): Promise<{ runId: string } | null> {\n return tenantGatewayUnavailable<{ runId: string } | null>('retryWithInput');\n },\n redispatchPending(_runId: string): Promise<(RunResult & { redispatched: number }) | null> {\n return tenantGatewayUnavailable<(RunResult & { redispatched: number }) | null>(\n 'redispatchPending',\n );\n },\n subscribe(_runId: string, _onEvent: (event: EngineEvent) => void): () => void {\n throw new Error(\n 'RunGateway.subscribe() is not available — pass `transport` to use RunGateway.',\n );\n },\n };\n}\n","import {\n type SchemaValidationCode,\n SchemaValidationError,\n type StandardSchemaV1,\n} from '@dudousxd/nestjs-durable-core';\nimport type { z } from 'zod';\n\n/** A class-validator DTO class — validated with the same `plainToInstance` + `validate` NestJS's\n * `ValidationPipe` runs. */\nexport type DtoClass = new (...args: any[]) => object;\n\n/**\n * What `@Workflow({ input, output })` and `@Step({ input, output })` accept: a **Standard Schema**\n * (https://standardschema.dev — zod 3.24+, valibot, arktype, …) or a **class-validator DTO class**.\n * The two are told apart at runtime: a value with a `~standard` property is a Standard Schema, a\n * constructor is a DTO. A zod schema older than 3.24 (no `~standard`) still works through its `parse`.\n */\nexport type IoSchema = StandardSchemaV1 | DtoClass | z.ZodType;\n\n/**\n * The value a schema parses to, which is what `run(ctx, input)`, `validateInput` and the `singleton`\n * / `concurrency` keys receive: a Standard Schema's output type (`z.output` for zod), a DTO class's\n * instance, `unknown` without a schema. Use it to type `run`'s input from the same schema:\n *\n * ```ts\n * const Input = z.object({ companyId: z.string() });\n *\n * @Workflow({ name: 'sync', input: Input, singleton: { key: (input) => input.companyId } })\n * class SyncWorkflow {\n * async run(ctx: WorkflowCtx, input: InferWorkflowInput<typeof Input>) {}\n * }\n * ```\n */\nexport type InferWorkflowInput<S> = [S] extends [undefined]\n ? unknown\n : [S] extends [StandardSchemaV1]\n ? StandardSchemaV1.InferOutput<S>\n : [S] extends [z.ZodType]\n ? z.output<S>\n : [S] extends [DtoClass]\n ? InstanceType<S>\n : // A union of schema kinds (`WorkflowOptions` written without a type argument): unknown.\n unknown;\n\n/** Parses a value against a schema: resolves the schema's output (coerced/transformed), or throws. */\nexport type Parser = (value: unknown) => Promise<unknown>;\n\n/**\n * Build a {@link Parser} for `schema`. A failure throws a {@link SchemaValidationError} (a\n * `FatalError`: retrying cannot fix a value that does not match its schema) with `code`\n * (`invalid_input` / `invalid_output`, so a dashboard, an alert or an `onError` route can tell it\n * apart) and the schema's issues in `issues` and `details.issues`.\n * `label` names what was being checked (`workflow \"checkout\" input`) in the message.\n */\nexport function schemaParser(schema: IoSchema, kind: 'input' | 'output', label: string): Parser {\n const code: SchemaValidationCode = kind === 'input' ? 'invalid_input' : 'invalid_output';\n if (isStandardSchema(schema)) {\n return async (value) => {\n const result = await schema['~standard'].validate(value);\n if (result.issues) throw new SchemaValidationError(label, result.issues, code);\n return result.value;\n };\n }\n if (isZodLike(schema)) {\n // zod < 3.24: no `~standard`, but `safeParse` reports the same issues.\n return async (value) => {\n const result = schema.safeParse(value);\n if (!result.success) throw new SchemaValidationError(label, result.error.issues, code);\n return result.data;\n };\n }\n if (typeof schema === 'function') return classValidatorParser(schema, code, label);\n throw new Error(\n `${label}: expected a Standard Schema (zod, valibot, …) or a class-validator DTO class`,\n );\n}\n\n/**\n * The class-validator path. `class-validator` and `class-transformer` are optional peers (only needed\n * if a DTO class is used), so they are reached through a dynamic `import()`: a static import would\n * resolve them for every consumer of the package, and a `require()` cannot work at all in the ESM\n * build. That defers the \"peer missing\" error to the first value parsed — the only moment the peers\n * are actually needed.\n */\nfunction classValidatorParser(cls: DtoClass, code: SchemaValidationCode, label: string): Parser {\n return async (value) => {\n let cv: any;\n let ct: any;\n try {\n cv = await import('class-validator');\n ct = await import('class-transformer');\n } catch {\n throw new Error(\n `${label} uses a class-validator DTO, which needs the optional peers \"class-validator\" and \"class-transformer\" — install them, or use a Standard Schema (zod, valibot, …) instead.`,\n );\n }\n // A DTO describes an object. class-validator crashes on `null`/`undefined` (a bare TypeError) and\n // reports nothing useful for a string or an array (which `plainToInstance` turns into an array of\n // instances), so anything else is rejected here, on the same coded contract as a failed check.\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n const got = value === null ? 'null' : Array.isArray(value) ? 'an array' : typeof value;\n throw new SchemaValidationError(label, [{ message: `expected an object, got ${got}` }], code);\n }\n const instance = ct.plainToInstance(cls, value);\n const errors = await cv.validate(instance, { whitelist: true });\n if (errors.length > 0) {\n const issues = errors.map((e: any) => ({\n message: Object.values(e.constraints ?? { _: `${e.property} is invalid` }).join(', '),\n path: [String(e.property)],\n }));\n // class-validator's messages already name the property (`orderId must be a string`).\n const summary = issues.map((i: { message: string }) => i.message).join('; ');\n throw new SchemaValidationError(label, issues, code, summary);\n }\n return instance;\n };\n}\n\nfunction isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n return (\n (typeof schema === 'object' || typeof schema === 'function') &&\n schema !== null &&\n '~standard' in schema\n );\n}\n\ninterface ZodLike {\n safeParse(value: unknown):\n | { success: true; data: unknown }\n | {\n success: false;\n error: { issues: { message: string; path: (string | number)[] }[] };\n };\n}\n\nfunction isZodLike(schema: unknown): schema is ZodLike {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n typeof (schema as { safeParse?: unknown }).safeParse === 'function'\n );\n}\n","import type { StepLogger, WorkflowCtx } from '@dudousxd/nestjs-durable-core';\nimport { DiscoveryService, MetadataScanner } from '@nestjs/core';\nimport { getDurableStepMeta, getWorkflowMeta } from './decorators';\nimport type { DurableStepMeta, WorkflowMeta } from './decorators';\nimport { originOfProvider } from './origin';\nimport { schemaParser } from './schema-parse';\n\nexport interface WorkflowInstance {\n run(ctx: WorkflowCtx, input: unknown): Promise<unknown>;\n}\n\n/**\n * Walks every provider that carries `@Workflow` metadata and invokes\n * `register(meta, instance, origin)`.\n *\n * `origin` is the package that declared the workflow class ({@link originOfProvider}), derived from\n * the provider wrapper — this is the ONE path every `@Workflow` in the app reaches, whichever role\n * the app runs in, so a lib that has never heard of the feature is attributed anyway. It is\n * `undefined` when the derivation could not answer confidently; the engine-side registrar\n * (`WorkflowRegistrar`) reports those at boot, and their runs carry no origin rather than a guess.\n *\n * Guards applied (same as both registrars):\n * - null / non-object provider instances are skipped\n * - providers without `@Workflow` metadata are skipped\n * - a `@Workflow` provider that has no `run` method throws at boot\n */\nexport function scanWorkflows(\n discovery: DiscoveryService,\n register: (meta: WorkflowMeta, instance: WorkflowInstance, origin: string | undefined) => void,\n): void {\n for (const wrapper of discovery.getProviders()) {\n const { instance } = wrapper;\n if (!instance || typeof instance !== 'object') continue;\n const meta = getWorkflowMeta(instance.constructor);\n if (!meta) continue;\n const workflow = instance as WorkflowInstance;\n if (typeof workflow.run !== 'function') {\n throw new Error(`@Workflow ${meta.name} must define a run(ctx, input) method`);\n }\n register(meta, workflow, originOfProvider(wrapper));\n }\n}\n\n/**\n * Walks every provider method that carries `@Step` metadata and invokes\n * `register(meta, boundHandler)`.\n *\n * Guards applied (same as both registrars):\n * - null / non-object provider instances are skipped\n * - non-function methods are skipped\n * - methods without `@Step` metadata are skipped\n *\n * The handler passed to `register` is already bound to its instance, and is the ONE place a `@Step`\n * method actually runs with real input/output in this package — every registrar\n * (`DurableStepRegistrar`, `InAppWorkerBootstrap`, `ThinStepRegistrar`) funnels through here — so\n * this is where `@Step`'s optional `input`/`output` schemas are enforced: `input` validates\n * before the method runs, `output` validates its return value before it's handed back. A bare\n * `@Step()` (no schemas attached) skips both checks — `meta.input`/`meta.output` are `undefined`.\n */\nexport function scanSteps(\n discovery: DiscoveryService,\n scanner: MetadataScanner,\n register: (\n meta: DurableStepMeta,\n handler: (input: unknown, log: StepLogger) => Promise<unknown>,\n ) => void,\n): void {\n for (const wrapper of discovery.getProviders()) {\n const { instance } = wrapper;\n if (!instance || typeof instance !== 'object') continue;\n const prototype = Object.getPrototypeOf(instance);\n for (const methodName of scanner.getAllMethodNames(prototype)) {\n const method = (instance as Record<string, unknown>)[methodName];\n if (typeof method !== 'function') continue;\n const meta = getDurableStepMeta(method);\n if (!meta) continue;\n const boundMethod = method as (input: unknown, log: StepLogger) => unknown;\n const parseInput =\n meta.input && schemaParser(meta.input, 'input', `step \"${meta.name}\" input`);\n const parseOutput =\n meta.output && schemaParser(meta.output, 'output', `step \"${meta.name}\" output`);\n const handler = async (input: unknown, log: StepLogger): Promise<unknown> => {\n const validInput = parseInput ? await parseInput(input) : input;\n const output = await boundMethod.call(instance, validInput, log);\n return parseOutput ? parseOutput(output) : output;\n };\n register(meta, handler);\n }\n }\n}\n","import { type EntityHandler, WorkflowEngine } from '@dudousxd/nestjs-durable-core';\nimport { Injectable } from '@nestjs/common';\nimport 'reflect-metadata';\n\nexport const ENTITY_METADATA = Symbol('nestjs-durable:entity');\nexport const ENTITY_ON_METADATA = Symbol('nestjs-durable:entity-on');\n\n/**\n * Marks an `@Injectable()` class as a **durable entity** (a virtual object): its `@On(op)` methods run\n * serialized per key over the instance's fields as durable state. e.g.\n *\n * ```ts\n * @Entity({ name: 'cart' }) @Injectable()\n * class Cart { items: Item[] = []; @On('add') add(i: Item) { this.items.push(i); } @On('list') list() { return this.items; } }\n * ```\n *\n * The class must be **constructible with no arguments** (a fresh instance is the initial state per key)\n * — keep entities pure state, no DI. Drive them with `EntityService` or `ctx.signalEntity`/`callEntity`.\n */\nexport function Entity(options: { name: string }): ClassDecorator {\n return (target) => {\n Reflect.defineMetadata(ENTITY_METADATA, options, target);\n };\n}\n\n/** Marks an entity method as the handler for operation `op`. */\nexport function On(op: string): MethodDecorator {\n return (target, propertyKey) => {\n // biome-ignore lint/complexity/noBannedTypes: reflect-metadata keys on the class constructor\n const ctor = (target as { constructor: Function }).constructor;\n const ops = (Reflect.getMetadata(ENTITY_ON_METADATA, ctor) as Map<string, string>) ?? new Map();\n ops.set(op, propertyKey as string);\n Reflect.defineMetadata(ENTITY_ON_METADATA, ops, ctor);\n };\n}\n\n// biome-ignore lint/complexity/noBannedTypes: matches reflect-metadata's class target type\nexport function getEntityMeta(target: Function): { name: string } | undefined {\n return Reflect.getMetadata(ENTITY_METADATA, target) as { name: string } | undefined;\n}\n\n/**\n * Build the engine `EntityConfig` for a discovered `@Entity` class: a fresh instance per key, and\n * handlers that rehydrate the class prototype onto the (serialized) state before dispatching the op,\n * so methods work after replay.\n */\n// biome-ignore lint/complexity/noBannedTypes: a class constructor\nexport function entityConfigFor(ctor: Function): {\n initialState: () => object;\n handlers: Record<string, EntityHandler>;\n} {\n const ops = (Reflect.getMetadata(ENTITY_ON_METADATA, ctor) as Map<string, string>) ?? new Map();\n const Cls = ctor as new () => Record<string, (arg: unknown) => unknown>;\n const handlers: Record<string, EntityHandler> = {};\n for (const [op, method] of ops) {\n handlers[op] = (state, arg) => {\n Object.setPrototypeOf(state as object, Cls.prototype); // re-attach methods to the plain state\n const fn = (state as Record<string, ((a: unknown) => unknown) | undefined>)[method];\n if (typeof fn !== 'function') throw new Error(`entity handler \"${method}\" is not a method`);\n return fn.call(state, arg);\n };\n }\n return { initialState: () => new Cls(), handlers };\n}\n\n/** Inject this to drive durable entities from outside a workflow. */\n@Injectable()\nexport class EntityService {\n constructor(private readonly engine: WorkflowEngine) {}\n\n /** Send an operation to an entity (fire-and-forget; ordered + exactly-once per key). */\n signal(name: string, key: string, op: string, arg?: unknown): Promise<void> {\n return this.engine.signalEntity(name, key, op, arg);\n }\n\n /** Read an entity's current durable state (or undefined if it has none yet). */\n getState<S = unknown>(name: string, key: string): Promise<S | undefined> {\n return this.engine.getEntityState<S>(name, key);\n }\n}\n","import type { DurableWorkerRuntime } from '@dudousxd/durable-worker';\nimport { type AnnouncedWorkflowOptions, parseDuration } from '@dudousxd/nestjs-durable-core';\nimport type { MetadataScanner } from '@nestjs/core';\nimport { type WorkflowMeta, getOnEvents } from './decorators';\nimport type { WorkflowInstance } from './discovery-helpers';\nimport { onErrorHandlersOf } from './on-error-handlers';\nimport { workflowIo } from './workflow-io';\n\n/**\n * Register a `@Workflow` body on a worker runtime with what it ANNOUNCES about it (design §7.9):\n * version, capability demand, declaring package, its onError routes, which the engine applies to a\n * workflow it serves by convention, and the events it subscribes to, which an engine settling a run\n * reads to owe its lifecycle event to a subscriber only this worker has. The `@OnError` handler workflows are registered beside it, so\n * the queue the engine dispatches a handler to by name is one this worker consumes.\n */\nexport function registerOnRuntime(\n runtime: DurableWorkerRuntime,\n scanner: MetadataScanner,\n meta: WorkflowMeta,\n instance: WorkflowInstance,\n origin: string | undefined,\n /** The workflow its dead-lettered runs route to, announced so a control plane starts it. */\n deadLetter?: string,\n): void {\n const { handlers, routes } = onErrorHandlersOf(meta, instance, scanner);\n const announced = {\n version: meta.version,\n ...(origin !== undefined ? { origin } : {}),\n };\n // The same parse-around-the-body the engine-side registrar applies, so a turn this worker replays\n // sees the parsed input too.\n const body = workflowIo(meta).wrap((ctx, input) => instance.run(ctx, input));\n const subscribes = [\n ...new Set(\n getOnEvents(meta, instance.constructor).map((entry) =>\n typeof entry === 'string' ? entry : entry.event,\n ),\n ),\n ];\n runtime.registerWorkflow(meta.name, body, {\n ...announced,\n ...(meta.requires !== undefined ? { requires: meta.requires } : {}),\n // A catch-all goes on the wire without a `code` key, not with an undefined one.\n ...(routes.length > 0\n ? {\n onError: routes.map(({ code, workflow }) =>\n code === undefined ? { workflow } : { code, workflow },\n ),\n }\n : {}),\n ...(subscribes.length > 0 ? { subscribes } : {}),\n ...announcedOptions(meta),\n ...(deadLetter !== undefined ? { deadLetter } : {}),\n });\n for (const [name, fn] of handlers) runtime.registerWorkflow(name, fn, announced);\n}\n\n/**\n * The `@Workflow` options a worker announces (see `WorkflowRegistration.options`): the data ones a\n * control plane serving the workflow by convention applies. `{}` when the decorator states none, so\n * such a registration keeps its pre-options bytes and hash.\n */\nexport function announcedOptions(meta: WorkflowMeta): { options?: AnnouncedWorkflowOptions } {\n const options: AnnouncedWorkflowOptions = {};\n if (meta.tags !== undefined && meta.tags.length > 0) options.tags = [...meta.tags];\n if (meta.executionTimeout !== undefined) {\n options.executionTimeoutMs = parseDuration(meta.executionTimeout);\n }\n if (meta.singleton !== undefined) {\n options.singleton = {\n ...(meta.singleton.limit !== undefined ? { limit: meta.singleton.limit } : {}),\n ...(meta.singleton.maxQueueDepth !== undefined\n ? { maxQueueDepth: meta.singleton.maxQueueDepth }\n : {}),\n };\n }\n return Object.keys(options).length > 0 ? { options } : {};\n}\n","import { type OnErrorRoute, type WorkflowCtx, workflowName } from '@dudousxd/nestjs-durable-core';\nimport type { MetadataScanner } from '@nestjs/core';\nimport { type WorkflowMeta, onErrorCodesOf } from './decorators';\n\ntype WorkflowFn = (ctx: WorkflowCtx, input: unknown) => Promise<unknown>;\n\n/**\n * A `@Workflow` instance's onError routes and the handler workflows they name. Each `@OnError`\n * method becomes the workflow `<workflow>.onError.<method>`, bound to the instance, with one route per\n * code it declares; `@Workflow({ onError })` adds routes to workflows registered elsewhere.\n *\n * Shared by every registrar: the engine registers the handlers and the routes, and a worker runtime\n * registers the handlers and announces the routes, so a workflow served by convention is routed the\n * same as one the engine registered.\n */\nexport function onErrorHandlersOf(\n meta: WorkflowMeta,\n instance: object,\n scanner: MetadataScanner,\n): { handlers: [string, WorkflowFn][]; routes: OnErrorRoute[] } {\n const handlers: [string, WorkflowFn][] = [];\n const routes: OnErrorRoute[] = [];\n for (const methodName of scanner.getAllMethodNames(Object.getPrototypeOf(instance))) {\n const method = (instance as Record<string, unknown>)[methodName];\n const codes = typeof method === 'function' ? onErrorCodesOf(method) : undefined;\n if (!codes) continue;\n const name = `${meta.name}.onError.${methodName}`;\n handlers.push([name, (ctx, input) => (method as WorkflowFn).call(instance, ctx, input)]);\n for (const code of codes) routes.push({ code, workflow: name });\n }\n for (const r of meta.onError ?? []) {\n routes.push({\n code: r.code === undefined || typeof r.code === 'string' ? r.code : r.code.code,\n workflow: workflowName(r.workflow),\n });\n }\n return { handlers, routes };\n}\n","import type { WorkflowCtx } from '@dudousxd/nestjs-durable-core';\nimport type { WorkflowMeta } from './decorators';\nimport { schemaParser } from './schema-parse';\n\ntype WorkflowBody = (ctx: WorkflowCtx, input: unknown) => Promise<unknown>;\n\n/**\n * The `@Workflow({ input, output, validateInput })` contract, split into the two places it applies.\n *\n * - `parseInput` and `validateParsed` are handed to the engine (and a tenant's start policy), which\n * checks the input in `start` before any run is created: it parses the input once, then runs\n * `validateInput` on the parsed value, and the `singleton` and `concurrency` keys read that value\n * too. The parsed value is then discarded — the run stores the input as it was sent. Each turn's\n * singleton admission parses the stored input again for its key.\n * - `wrap` turns `run(ctx, input)` into the body every role registers (inline, in-app worker, thin\n * worker): the stored input is parsed before the body runs and the returned value is parsed before\n * it becomes the run's output. It wraps the BODY, not `start`, because the body is what runs on\n * every turn — including a replay on another process — so every turn sees the same parsed value,\n * even one (a `Date`, a DTO instance) the stored JSON can't carry.\n */\nexport function workflowIo(meta: WorkflowMeta): {\n /** The input schema's parser, or undefined without one. Handed to the engine (and a tenant's\n * start policy) with {@link validateParsed}: it parses once at start, then `validateInput` and\n * the `singleton` and `concurrency` keys read the parsed value, the one `run(ctx, input)` gets. */\n parseInput: ((input: unknown) => Promise<unknown>) | undefined;\n /** `@Workflow({ validateInput })` alone, for a caller that already parsed with\n * {@link parseInput}. */\n validateParsed: ((input: unknown) => void | Promise<void>) | undefined;\n wrap(body: WorkflowBody): WorkflowBody;\n} {\n const parseInput =\n meta.input && schemaParser(meta.input, 'input', `workflow \"${meta.name}\" input`);\n const parseOutput =\n meta.output && schemaParser(meta.output, 'output', `workflow \"${meta.name}\" output`);\n const validateInput = meta.validateInput;\n return {\n parseInput: parseInput || undefined,\n validateParsed: validateInput,\n wrap: (body) =>\n !parseInput && !parseOutput\n ? body\n : async (ctx, input) => {\n const output = await body(ctx, parseInput ? await parseInput(input) : input);\n return parseOutput ? parseOutput(output) : output;\n },\n };\n}\n","import type { StepInvocation } from '@dudousxd/nestjs-durable-core';\nimport 'reflect-metadata';\n\nexport const STEP_INTERCEPTOR_METADATA = Symbol('nestjs-durable:step-interceptor');\n\n/**\n * The shape a `@StepInterceptor()` provider must implement: `intercept(invocation, next)` wraps the\n * real execution of every local `ctx.step` (call `next()` to run the step body / next interceptor,\n * and return — or transform — its result). The engine-level {@link StepInterceptor} primitive, with\n * NestJS dependency injection.\n */\nexport interface DurableStepInterceptor {\n intercept(invocation: StepInvocation, next: () => Promise<unknown>): Promise<unknown>;\n}\n\n/**\n * Marks an `@Injectable()` class as a durable step interceptor. The module discovers it on boot and\n * registers its `intercept` method with the engine (so it can inject loggers/tracers/etc.). First\n * declared is outermost. Interceptors fire only when a step actually executes, never on replay.\n */\nexport function StepInterceptor(): ClassDecorator {\n return (target) => {\n Reflect.defineMetadata(STEP_INTERCEPTOR_METADATA, true, target);\n };\n}\n\n// biome-ignore lint/complexity/noBannedTypes: matches reflect-metadata's class target type\nexport function isStepInterceptor(target: Function): boolean {\n return Reflect.getMetadata(STEP_INTERCEPTOR_METADATA, target) === true;\n}\n","import { RunGateway } from '@dudousxd/nestjs-durable-core';\n\n/**\n * Cross-lib injection token for the current-request context accessor, owned by\n * `@dudousxd/nestjs-context`. We do NOT import nestjs-context (it is an OPTIONAL\n * peer dependency) — instead we share its well-known token by value so DI\n * resolves the same provider when nestjs-context is installed and present.\n *\n * `Symbol.for(key)` uses the global symbol registry, so this resolves to the\n * SAME symbol instance as nestjs-context's `tokens.ts` (and the identical token\n * declared by `@dudousxd/nestjs-authz`) without any import. The key MUST stay\n * byte-identical with nestjs-context's export.\n */\nexport const CONTEXT_ACCESSOR = Symbol.for('@dudousxd/nestjs-context:accessor');\n\n/**\n * Internal: the module's resolved tenant auth (`verifyTenant` and `tenantToken`, resolved through\n * DI). Shared by the module and the thin-worker providers, which announce under the tenant token.\n */\nexport const TENANT_AUTH = Symbol('nestjs-durable:tenant-auth');\n\n/**\n * @deprecated Inject the `RunGateway` class, which is its own DI token:\n * `constructor(private readonly gateway: RunGateway)`. Kept because published\n * `@dudousxd/nestjs-agent` and `@dudousxd/nestjs-agent-opencode` releases import it; it is the\n * `RunGateway` class itself, so `@Inject(RUN_GATEWAY)` resolves the same provider.\n */\nexport const RUN_GATEWAY = RunGateway;\n","import type { ConcurrencyOption } from '@dudousxd/durable-worker';\nimport {\n type AdmissionBackend,\n type ControlPlane,\n DURABLE_OPTIONS,\n DURABLE_OPTIONS_CANONICAL,\n type NamedTransport,\n type QueueConfig,\n type RetentionPolicy,\n RunGateway,\n STATE_STORE,\n STATE_STORE_CANONICAL,\n type ScheduledWorkflow,\n type StalledRunInfo,\n type StateStore,\n TRANSPORT,\n TRANSPORT_CANONICAL,\n type TenantTokenSource,\n type TenantVerifier,\n type Transport,\n WorkflowEngine,\n type WorkflowRef,\n sealDurableCopies,\n useDurableExecution,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n type DynamicModule,\n Inject,\n Injectable,\n type InjectionToken,\n Module,\n type OnApplicationBootstrap,\n type OnModuleDestroy,\n type Provider,\n} from '@nestjs/common';\nimport { DiscoveryModule, ModuleRef } from '@nestjs/core';\nimport type { ContextAccessor } from './context-accessor';\nimport { DurableStartClient } from './durable-start-client';\nimport { DurableStepRegistrar } from './durable-step.registrar';\nimport { thinWorkerProviders, unavailableRunGateway } from './durable-worker.module';\nimport { EntityService } from './entity';\nimport { inAppWorkerProviders } from './in-app-worker';\nimport { ProxyRunGateway } from './proxy-run-gateway';\nimport { RetentionPoller } from './retention-poller';\nimport { isDrivingOperator } from './role';\nimport { RunRequestResponder, type RunRequestTransport } from './run-request-responder';\nimport { StoreRunGateway } from './store-run-gateway';\nimport { SweepLeases } from './sweep-leases';\nimport {\n type DurableTenancyOption,\n type TenantRuntime,\n buildEngineTenancy,\n canRestoreTenant,\n isTenantRuntime,\n readTenancy,\n stepTenantWrapper,\n tenantFilterNow,\n} from './tenancy';\nimport {\n type TenantTokenOption,\n type TenantVerifierOption,\n resolveTenantTokenSource,\n resolveTenantVerifier,\n} from './tenant-contracts';\nimport { TenantEventRepublisher } from './tenant-event-republisher';\nimport { TimerPoller } from './timer-poller';\nimport { CONTEXT_ACCESSOR, TENANT_AUTH } from './tokens';\nimport { WorkflowRegistrar } from './workflow.registrar';\nimport { WorkflowService } from './workflow.service';\n\n/**\n * Locate the context accessor non-strictly: an accessor provided by ANY module (a global\n * `ContextModule` from `@dudousxd/nestjs-context`, or the app root) is found via {@link ModuleRef},\n * because DurableModule is `global` and its engine factory can't see another module's local\n * providers directly. Returns undefined when the optional peer isn't installed/bound.\n */\nfunction resolveAccessor(moduleRef: ModuleRef): ContextAccessor | undefined {\n try {\n return moduleRef.get<ContextAccessor>(CONTEXT_ACCESSOR, { strict: false });\n } catch {\n return undefined;\n }\n}\n\n/**\n * Build an opaque context carrier from a {@link ContextAccessor} — the auto-feed default for the\n * engine's `context` option when `@dudousxd/nestjs-context` is present and the app passed no own\n * reader. Drops fields the accessor doesn't populate, so an empty/anonymous request yields `{}`.\n */\nfunction carrierFromAccessor(accessor: ContextAccessor): Record<string, unknown> | undefined {\n const carrier: Record<string, unknown> = {};\n const traceId = accessor.traceId();\n if (traceId !== undefined) carrier.traceId = traceId;\n const tenantId = accessor.tenantId();\n if (tenantId !== undefined) carrier.tenantId = tenantId;\n // The full tenant (with its kind), so a worker restores `{ id, kind }` and not `kind: 'unknown'`.\n // A `legacy` one (only a plain `tenantId` was set) adds nothing the `tenantId` above doesn't carry.\n const tenant = accessor.tenant?.();\n if (tenant !== undefined && tenant.source !== 'legacy') carrier.tenant = tenant;\n const userRef = accessor.userRef();\n if (userRef !== undefined) carrier.userRef = userRef;\n return carrier;\n}\n\n/** True when nestjs-context publishes its accessor on the global slot (even with no DI binding). */\nfunction contextSlotPresent(): boolean {\n const slot = (globalThis as unknown as Record<symbol, { current?: unknown } | undefined>)[\n Symbol.for('@dudousxd/nestjs-diagnostics:accessor')\n ];\n return !!slot?.current;\n}\n\n/**\n * The slice of `@dudousxd/nestjs-context`'s module-level `Context` singleton we use to re-hydrate the\n * originating context around a local step body. Structural — we never import the package's types (it\n * is an OPTIONAL peer); the guarded dynamic import below captures whatever the installed package\n * exports as `Context`.\n */\ninterface ContextRuntime {\n /** Re-hydrate a context from an opaque carrier and run `fn` inside its ALS scope. */\n deserialize<T>(carrier: Record<string, unknown>, fn: () => T): T;\n /** Run `fn` with a tenant (nestjs-context ≥ 1.2). Absent on an older context: tenancy stays off. */\n withTenant?: TenantRuntime['withTenant'];\n}\n\nfunction isContextRuntime(x: unknown): x is ContextRuntime {\n return !!x && typeof (x as ContextRuntime).deserialize === 'function';\n}\n\n/**\n * Resolve `@dudousxd/nestjs-context`'s runtime `Context` singleton via a GUARDED dynamic import — used\n * to build the engine's `rehydrate` bridge. The runtime `Context` (its `deserialize`/ALS `run`) is a\n * module-level singleton, NOT a DI provider behind {@link CONTEXT_ACCESSOR}, so it can't be resolved\n * through ModuleRef — we import it directly. We do NOT add a hard/static import (the peer is optional):\n * a failure (peer not installed) returns undefined and the engine falls back to passthrough re-hydration.\n */\nasync function resolveContextRuntime(): Promise<ContextRuntime | undefined> {\n try {\n // Indirect the specifier through a variable so the compiler does not try to STATICALLY resolve\n // the optional peer (it may be uninstalled). This stays a runtime guarded import — a missing\n // module rejects and is caught below.\n const specifier = '@dudousxd/nestjs-context';\n const mod = (await import(specifier)) as { Context?: unknown };\n return isContextRuntime(mod.Context) ? mod.Context : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** True when `x` can act as a control plane (broadcast pub/sub) — e.g. a broadcast-capable transport. */\nfunction isControlPlane(x: unknown): x is ControlPlane {\n return (\n !!x &&\n typeof (x as ControlPlane).publishControl === 'function' &&\n typeof (x as ControlPlane).onControl === 'function'\n );\n}\n\n/** A store that can derive a tenant-namespace-scoped view of itself (the MikroORM adapter). */\ninterface ScopeableStore {\n /** Derive a store confined to `scope.namespace`, sharing the same backing connection. */\n withScope(scope: { namespace?: string }): StateStore;\n}\n\n/**\n * True when `store` can produce a namespace-scoped view of itself. Structural check (same idiom as\n * {@link isControlPlane}) so the store-agnostic module never imports a concrete adapter — the\n * pre-built `store` is only re-scoped when it actually carries the capability.\n */\nfunction isScopeableStore(store: StateStore): store is StateStore & ScopeableStore {\n return typeof (store as StateStore & Partial<ScopeableStore>).withScope === 'function';\n}\n\n/**\n * Apply opt-in tenant read scoping to a pre-built store. The module receives `store` already\n * instantiated (it is store-agnostic — no MikroORM import), so it cannot reconstruct it; instead it\n * asks the store for a scoped view via the optional {@link ScopeableStore.withScope} capability. When\n * `scopeReads` is off, `namespace` is unset, or the store can't scope itself, the original store is\n * returned unchanged (the operator view) — the caller can always pass an already-scoped store.\n */\nfunction scopedStore(store: StateStore, options: DurableModuleOptions): StateStore {\n if (options.scopeReads !== true || options.namespace === undefined) return store;\n if (!isScopeableStore(store)) return store;\n return store.withScope({ namespace: options.namespace });\n}\n\n/**\n * Retention config for the {@link RetentionPoller}. One or more {@link RetentionPolicy policies}\n * (status sets must be disjoint per scope — validated at boot), swept together on a shared interval.\n *\n * ```ts\n * retention: {\n * sweepInterval: '1m',\n * batchSize: 1_000,\n * policies: [\n * { statuses: ['completed', 'cancelled'], maxAge: '14d', maxCount: 200 },\n * { statuses: ['failed'], maxAge: '90d' }, // keep failures longer for debugging\n * // Scoped: chat turns age out after a day, whatever the defaults above say.\n * { statuses: ['completed', 'failed', 'cancelled'], maxAge: '1d', scope: { tags: ['chat'] } },\n * ],\n * }\n * ```\n *\n * Policies are applied one after another, so a run matched by several scopes is pruned by the\n * strictest of them.\n */\nexport interface DurableRetentionOptions {\n /** The retention rules, one per (disjoint) status group. */\n policies: RetentionPolicy[];\n /**\n * How often to run the prune sweep. A number is milliseconds; a string is an `ms`-style duration\n * (`'1m'`, `'5m'` — `'m'` is minutes). `0` runs it once on boot only. Defaults to 60000 (1 minute).\n */\n sweepInterval?: number | string;\n /** Max runs hard-deleted per batch (per policy, looped until drained). Defaults to 1000. */\n batchSize?: number;\n}\n\n/**\n * The options every {@link DurableModuleOptions} variant shares. With no `topology` (or\n * `topology: 'standalone'`) the **role is inferred** from which of `store`/`connection` are set:\n *\n * - `{ store, transport }`: **operator**, a real `WorkflowEngine` + `StoreRunGateway` + drivers/\n * timer/retention/registrars, executing registered bodies INLINE. Driven by {@link drive} (default\n * `true`).\n * - `{ connection }` (no `store`): **thin worker**, `WorkflowEngine` resolves to a store-less\n * `DurableStartClient`; `RunGateway` is a `ProxyRunGateway` when `transport` is also given, else\n * every method rejects with a clear error. No store/timer/retention/entity, just discovered\n * `@Workflow`/`@Step` handlers served over ONE `runRedisWorker` consumer.\n * - `{ store, transport, connection }`: an **operator that also runs a co-located worker**: every\n * `@Workflow` is registered GROUP-SERVED (dispatched over the transport, PER WORKFLOW NAME, instead\n * of inline) and a co-located consumer (one `runRedisWorker` call) replays the same bodies.\n *\n * `forRoot` throws when neither `store` nor `connection` is set, and when `store` is set without a\n * `transport`.\n */\nexport interface DurableModuleSharedOptions {\n /** State store — set this to play the **operator** role (see the interface doc for the full role\n * matrix). Omit for a store-less **thin worker** (`connection` only). */\n store?: StateStore;\n transport?: Transport;\n /**\n * An ordered pool of named transports for failover / multi-broker setups. The engine dispatches on\n * the first and fails over to the next; a step pins one via `ctx.step(handler, input, { transport })`.\n * Use instead of `transport`.\n */\n transports?: NamedTransport[];\n /**\n * Cross-instance broadcast pub/sub (lifecycle events + cancellation). Defaults to the (first)\n * transport when it can broadcast (event-emitter, BullMQ); set explicitly to use a dedicated one.\n */\n controlPlane?: ControlPlane;\n /** Interval (ms) for the durable-timer poller. `0` disables it. Defaults to 1000. Operator only. */\n timerPollMs?: number;\n /**\n * The longest wait (ms) between two timer polls while there is nothing to do. After a poll that\n * found no work the wait doubles from `timerPollMs` up to this, and goes back to `timerPollMs` as\n * soon as there is work or any run event (here, or from another instance over the control plane).\n * It never outlasts a known due time: before each longer wait the poller reads when the next timer,\n * blocked-run recovery poll, persisted schedule or in-process `schedules` window is due. What it\n * delays is recovery only: a crashed instance's runs, execution timeouts and the stalled/\n * buffered-signal sweeps are picked up at most this late. A value at or below `timerPollMs` keeps\n * the fixed tick, and so does an engine with neither a control plane nor a run queue (a run another\n * instance starts reaches it only through the pending-run poll). Defaults to 5000. Operator only.\n */\n maxIdleIntervalMs?: number;\n /**\n * How often (ms) the timer poller lists the settled runs that still owe a lifecycle event, and\n * heals the ones that missed a newly announced subscriber. That listing is the recovery path for a\n * publish that never happened (the live publish gets a 30 s grace first) and filters runs by tag,\n * so running it on every tick cost a scan of the runs table each second for nothing. The run-wait\n * delivery and registry heartbeat still run every tick. A failed sweep is retried on the next tick.\n * `0` sweeps on every tick (the old behavior). Defaults to 10000. Operator only.\n */\n owedLifecycleSweepMs?: number;\n /**\n * Auto-create the durable tables on boot via `store.ensureSchema()`. Defaults to true. Turn\n * off in production and call the store adapter's `ensure*DurableSchema()` from a migration.\n * Operator only.\n */\n autoSchema?: boolean;\n /**\n * Worker-pool namespace for this instance (forwarded to the engine). The poll paths\n * (`runPending`/`recoverIncomplete`/`resumeDueTimers`/`sweepTimeouts`) only act on runs in this\n * namespace. Set distinct values to safely share ONE state store across non-interchangeable\n * pools — e.g. a developer's local instance vs the deployed cluster. **Omit it to make this\n * instance an OPERATOR** — an unset namespace drives/recovers/resumes runs of EVERY namespace and\n * leaves the transport on its bare prefix. See `WorkflowEngineDeps.namespace`. Not to be confused\n * with {@link partition} (the co-located/thin-worker QUEUE routing suffix).\n */\n namespace?: string;\n /**\n * Multi-instance recovery lease, in ms — how long an instance owns a run it picked up before\n * another may take over. Defaults to 30000. Set above your longest synchronous run. Operator only.\n */\n leaseMs?: number;\n /** Unique id for this instance (for leases, and the co-located/thin-worker consumer's heartbeats). */\n instanceId?: string;\n /**\n * Cap recovery attempts before a still-`running` run is moved to the `dead` dead-letter state\n * (a poison pill that crashes the process every boot). Omit for unlimited. Operator only.\n */\n maxRecoveryAttempts?: number;\n /**\n * How long (ms) a run may stay unresumable because its workflow version is registered nowhere (a\n * renamed or deleted workflow) before it is dead-lettered. Default 24h; `0` skips it forever.\n */\n unregisteredWorkflowGraceMs?: number;\n /**\n * Opt-in liveness deadline (ms) for a remote (polyglot) workflow `advance`. If the worker neither\n * returns a decision nor sends a run-scoped heartbeat within this window, the engine presumes it dead\n * and lets recovery re-drive; each heartbeat rearms the window so a slow-but-alive worker is never\n * re-driven. Pair with a worker SDK that emits run-scoped heartbeats (`@dudousxd/durable-worker` ≥ the\n * release that ships them, and the Python `durable-worker`). Omitted, a turn dispatched over a\n * broker (a tenant's worker, another SDK's) takes {@link reconcileMs} as its window, so a run whose\n * worker died mid-turn is re-driven within it; `reconcileMs: 0` keeps the unbounded wait.\n * Operator only.\n */\n remoteAdvanceSilenceMs?: number;\n /**\n * Opt-in self-heal window (ms) for a dispatched remote step whose job was LOST — the worker was\n * killed mid-step (an OOM kill leaves no result, and a non-TS consumer has no way to bridge the\n * job's terminal failure back into one), or the broker dropped the job. The `pending` checkpoint\n * then has nothing left to settle it, so the run waits forever. When set, the pending checkpoint\n * carries a LEASE: a result — or a step-scoped heartbeat, which renews it, so a worker still\n * holding the step is never double-dispatched — must land within the window, else the engine\n * re-dispatches the same step (bumping `attempts`, bounded by {@link remoteRedispatchMax}).\n * Covers both `ctx.step` and a polyglot workflow's `call` fan-out (`ctx.gather_calls`).\n *\n * Off by default: a re-dispatch double-runs a step whose original job was merely SLOW, so the\n * window MUST exceed your longest remote step and the step MUST be idempotent. Operator only.\n */\n remoteRedispatchMs?: number;\n /**\n * Max times {@link remoteRedispatchMs} re-dispatches one lost step before failing it\n * (`remote_step_lost`, surfaced on the run) instead of re-dispatching forever. Defaults to 10.\n * Ignored when `remoteRedispatchMs` is unset. Operator only.\n */\n remoteRedispatchMax?: number;\n /**\n * Fallback wake-up (ms) for a run suspended on an event (child, signal, `waitForEvent`, remote\n * result) whose wake-up was lost: the reconcile pass re-drives it after this window, an idempotent\n * replay that re-suspends a still-pending wait. Defaults to 300000 (5min); `0` disables it. Also\n * the re-drive window of a dispatched workflow turn when {@link remoteAdvanceSilenceMs} is unset.\n * See `WorkflowEngineDeps.reconcileMs`. Operator only.\n */\n reconcileMs?: number;\n /**\n * Idle time (ms) before a stranded in-flight run is reported to {@link onStalled} listeners.\n * Defaults to 900000 (15 min), floored at 60000. See `WorkflowEngineDeps.stalledAfterMs`.\n * Operator only.\n */\n stalledAfterMs?: number;\n /**\n * Pager hook for stranded runs, registered on the engine as `engine.onStalled(...)`: a run\n * suspended with no wake timer, or parked on an old pending remote step nothing is leasing. The\n * timer poller sweeps once a minute and reports each stranded episode once per instance.\n * Equivalent to calling `engine.onStalled` from a provider; only a DRIVING operator sweeps.\n */\n onStalled?: (info: StalledRunInfo) => void;\n /**\n * The most due timers one timer-poll pass loads and drives, most overdue first, so a wave of\n * thousands of due runs is worked through in batches. Defaults to 500; a non-finite or sub-1 value\n * falls back to the default. See `WorkflowEngineDeps.timerBatchSize`. Operator only.\n */\n timerBatchSize?: number;\n /**\n * Retention (ms) for a buffered event that no `waitForEvent` ever claims; the reconcile pass prunes\n * rows past `publishedAt + eventBufferTtlMs`. Omit (or `0`) to keep them until consumed, the\n * default. See `WorkflowEngineDeps.eventBufferTtlMs`. Operator only.\n */\n eventBufferTtlMs?: number;\n /**\n * How long `signal(token, payload, { id })` remembers an id (ms, or a duration like `'7d'`); a\n * re-send with the same token and id within it is dropped. Default 7 days. See\n * `WorkflowEngineDeps.signalIdTtl`.\n */\n signalIdTtl?: string | number;\n /**\n * How long (ms) a run parked `blocked` (no capable, protocol-compatible live worker) waits before\n * the blocked-recovery poll re-checks the fleet. Defaults to 5000. See\n * `WorkflowEngineDeps.blockedPollMs`. Operator only.\n */\n blockedPollMs?: number;\n /**\n * How long (ms) the routing guard reuses the worker descriptors it read for a queue token. On\n * BullMQ each read scans the Redis keyspace. Default 2000; `0` reads on every dispatch. See\n * `WorkflowEngineDeps.workerDescriptorCacheMs`. Operator only.\n */\n workerDescriptorCacheMs?: number;\n /**\n * Persist a `running` checkpoint when a local step's body begins, so an in-flight step survives a\n * dashboard reload. Defaults to `true`; set `false` on hot paths with many short local steps to\n * halve their checkpoint writes. See `WorkflowEngineDeps.trackStepStart`. Operator only.\n */\n trackStepStart?: boolean;\n /**\n * How many workflow bodies parked on dispatched `ctx.step` calls this instance keeps in memory\n * between turns, so a step's result continues the body instead of replaying it over the run's\n * whole history. Default 1000 (~26 KB of heap each); `0` turns it off. See `WorkflowEngineDeps.stickyRuns` and the\n * \"Performance\" section of the production guide. Operator only.\n */\n stickyRuns?: number;\n /** How long a parked body may stay idle in that cache. Default 5 min. Operator only. */\n stickyIdleMs?: number;\n /**\n * Send each dispatched `ctx.step` result back to the engine instance that dispatched it (and holds\n * the parked body), on transports that can route replies (BullMQ). Default `true`. See\n * `WorkflowEngineDeps.routeReplies`. Operator only.\n */\n routeReplies?: boolean;\n /**\n * The **default** workflow to route dead-lettered runs to, for workflows that don't declare their\n * own. When a run is moved to `dead` (exceeded `maxRecoveryAttempts`), the started handler gets a\n * `DeadLetter` payload `{ deadRunId, workflow, input, error }` (idempotent by a `dlq:<runId>` id) —\n * it can alert, compensate, or queue for review. Resolution per dead run: the workflow's inline\n * `@DeadLetter()` method → its `@Workflow({ deadLetterWorkflow })` reference → this default. Omit\n * everything to just leave dead runs parked (inspectable + retriable from the dashboard). Accepts a\n * workflow class (refactor-safe) or a name (cross-runtime). Operator only.\n */\n deadLetterWorkflow?: WorkflowRef;\n /**\n * Whether an **operator** instance actively DRIVES runs — polls pending, recovers crashed\n * (`recoverIncomplete`), resumes due timers, sweeps timeouts, prunes retention, and consumes local\n * steps — as opposed to a read-only/dashboard replica. Defaults to `true`. Set `false` for a\n * **dashboard/dispatch-only** instance (e.g. an API pod) that mounts the store/dashboard but must\n * not process or recover workflows — leave that to another driving instance. `drive: false` also\n * installs the engine's no-op run dispatcher, so a freshly `start()`ed run stays enqueue-only until\n * a driving instance's poll picks it up. Ignored (irrelevant) for a thin worker (no `store`).\n */\n drive?: boolean;\n /**\n * Whether this process CONSUMES from the broker. Defaults to `true`. Set `false` in a process that\n * boots the module without being a worker — a CLI command, a REPL, a migration or seed script — so\n * it doesn't compete with the real fleet: every transport that supports it (`BullMQTransport`) has\n * its point-to-point consumers (step tasks, results, decisions, step events, start-run, run-request)\n * parked via `deferConsumers()`, and no co-located/thin worker consumer starts. The process still\n * dispatches and starts runs; the jobs stay on the queues for the fleet. Pair it with\n * `drive: false` so it doesn't poll/recover runs either. To consume later in the same process, call\n * `startConsumers()` on your transport. A transport without `deferConsumers()` (the SQL/SQS/in-process\n * transports) keeps consuming — a warning says so.\n */\n consumers?: boolean;\n /** Max ms to wait for in-flight runs on shutdown before exiting. Defaults to 10000. Operator only. */\n shutdownTimeoutMs?: number;\n /**\n * Recurring workflows to start on a schedule (fixed interval or cron). The timer poller fires\n * them each tick on **driving** instances only; `engine.start` is idempotent by the schedule's\n * time-bucket run id, so racing instances start each window exactly once. Cron schedules need the\n * optional `cron-parser` peer dependency. Operator only.\n */\n schedules?: ScheduledWorkflow[];\n /**\n * Fire the PERSISTED schedules managed at runtime through `engine.schedules` (create/upsert/pause/\n * resume/delete/list) on every timer-poll tick of a driving instance — one indexed \"due by now\"\n * query per tick. Off by default, so a deployment that never uses them doesn't need the\n * `durable_schedules` table. Safe with any number of driving instances: each window's run id is\n * deterministic and advancing a schedule is a compare-and-set. Operator only.\n */\n persistedSchedules?: boolean;\n /**\n * Adopt the `schedules` that TENANT apps declare and fire them here (a tenant has no store to fire\n * them from). Each tenant worker announces its app's schedules on its descriptor; every `syncMs`\n * (default 15 s) a driving instance turns them into persisted schedules (id\n * `app:<partition>:<key>`, tagged `schedule:announced`), applies a changed definition, and pauses\n * one that no live worker of its app has announced for `graceMs` (default 10 minutes). It then\n * fires them on every tick, through the tenant start path: with no live worker of the app, a run\n * waits `blocked` (`no_live_worker`) for one. On by default for a driving instance with a store\n * that persists schedules and a transport that reads worker descriptors (BullMQ); `false` turns it\n * off. Operator only.\n */\n announcedSchedules?: boolean | { syncMs?: number; graceMs?: number };\n /**\n * Hard-prune terminal run history on an interval so `durable_workflow_runs` (and its child tables)\n * stays bounded — without it, completed/failed/cancelled runs accumulate forever and the timer\n * poller's per-tick status scans get linearly slower. Driving instances only. Omit to keep all\n * history (the default). Requires a store adapter that implements `pruneTerminalRuns` (every\n * first-party adapter does); a custom store without it no-ops with a warning. See\n * {@link DurableRetentionOptions}.\n * Operator only.\n */\n retention?: DurableRetentionOptions;\n /**\n * Build the public callback URL for a `ctx.webhook()` token, e.g.\n * ``(t) => `https://api.example.com/durable/api/webhooks/${t}` ``. Populates `DurableWebhook.url`\n * so a step can hand the URL to a third party. The dashboard's `POST webhooks/:token` receives the\n * callback. Omit to build URLs yourself from the token. Operator only.\n */\n webhookUrl?: (token: string) => string;\n /**\n * Flow-control queues for remote steps, registered on the engine at startup. Reference one from a\n * workflow with `ctx.step(handler, input, { queue: name })` to cap its concurrency / admission rate.\n * Operator only.\n */\n queues?: QueueConfig[];\n /**\n * Admission backend for the flow-control `queues`. Defaults to in-process (per-instance) caps. Pass\n * a `RedisAdmissionBackend` (from `@dudousxd/nestjs-durable-admission-redis`) to make concurrency /\n * rate-limit / priority ordering GLOBAL across every engine replica. Operator only.\n */\n admission?: AdmissionBackend;\n /**\n * Provide the current W3C `traceparent` to stamp on dispatched remote tasks, so workers continue\n * the distributed trace. Pass `otelTraceparent` from `@dudousxd/nestjs-durable-otel`. Operator only.\n */\n traceparent?: () => string | undefined;\n /**\n * Provide an opaque context carrier (tenant / user / correlation ids) to stamp on dispatched remote\n * tasks, so workers re-expose it to the step handler alongside the `traceparent`. The engine never\n * inspects its shape.\n *\n * **Auto-feed**: if you omit this AND `@dudousxd/nestjs-context` is installed (its accessor is bound\n * to the shared `CONTEXT_ACCESSOR` token), DurableModule defaults this to a reader that builds\n * `{ traceId, tenantId, userRef }` from the accessor — so a workflow dispatched within a request\n * automatically carries the originating context across process boundaries. Pass your own reader to\n * override the auto-feed; with neither, the carrier is omitted (unchanged behavior).\n *\n * Re-evaluated at each (re)dispatch — including a retry or a crash/scale-down resume that the engine\n * drives OUTSIDE the originating request scope, where this reader may return empty or stale values.\n * Treat the carrier as best-effort correlation/propagation metadata only — do NOT treat it as an\n * authorization boundary. Operator only.\n */\n context?: () => Record<string, unknown> | undefined;\n /**\n * Tenancy: scope runs by the CUSTOMER they belong to (`@dudousxd/nestjs-context`'s tenant), not by\n * the worker-pool {@link namespace}. With it on, `start` stamps the request's tenant on the run\n * (an explicit `StartOptions.tenantId` wins), children, `continueAsNew` and schedules inherit it,\n * every turn runs with it restored as the context tenant, and app-facing reads and control calls\n * (`getRun`, `signal`, `cancel`, retry, the dashboard) only see the caller's tenant's runs.\n *\n * `'inherit'` (default) follows `ContextModule.forRoot({ tenancy: { enabled } })`, which is off by\n * default; `false` keeps durable out of tenancy. Without nestjs-context ≥ 1.2, tenancy is off.\n */\n tenancy?: DurableTenancyOption;\n /** Attempts for each saga compensation when a run fails. Default 1 (no retry). Idempotent undos.\n * Operator only. */\n compensationRetries?: number;\n /**\n * Opt into tenant read scoping: when `true` AND {@link namespace} is set, the module confines the\n * store's reads to that namespace (a tenant-boundary view) instead of the operator view that sees\n * all namespaces. Default `false` — the control plane (e.g. flip's `/ctrl` operator screens) stays\n * unscoped. Requires a store that exposes the `withScope` capability (the MikroORM adapter does);\n * a pre-built store without it is used as-is (construct it already-scoped instead). Operator only.\n */\n scopeReads?: boolean;\n /**\n * ioredis connection (string or options) for a **thin worker** (`connection` only) or the\n * **co-located worker** consumer (`store` + `connection`). Set this to play a worker role (see the\n * interface doc for the full role matrix). Omit to keep every `@Workflow` on the operator's inline\n * fast path with zero dispatch round-trips.\n */\n connection?: string | Record<string, unknown>;\n /**\n * The isolation partition a worker role serves — a thin worker's or co-located worker's queue\n * subscription, AND (for a co-located worker) the suffix each `@Workflow`'s dispatch token carries.\n * Each handler's queue token is `tenantGroup(sanitizeQueueToken(name), partition)`\n * (`@dudousxd/nestjs-durable-core`), so `undefined`, `''`, or `'default'` stays byte-identical to\n * the bare (sanitized) name (single-tenant deployment unchanged), and any other partition serves\n * `<name>@<partition>` — matching the queue name an operator's convention dispatch routes that\n * tenant's runs to (`tenantGroup(run.workflow, run.namespace)` on the engine side). Not to be\n * confused with {@link namespace} (the operator's own poll-scoping axis). Ignored for a plain\n * operator (no `connection`).\n */\n partition?: string;\n /** Key prefix namespacing the durable queues for a worker role's consumer. Defaults to `durable`\n * (matches the transport). Ignored for a plain operator (no `connection`). */\n prefix?: string;\n /**\n * How many tasks a worker role's co-located/thin consumer runs concurrently PER SUBSCRIBED QUEUE\n * (BullMQ Worker concurrency — the same limit is applied to every per-name queue the single\n * `runRedisWorker` call starts). Defaults to 1. Raise it so a fanned-out batch (e.g. the N remote\n * steps of a `gather`) runs in parallel instead of serially.\n *\n * Pass `'adaptive'` (or `{ mode:'adaptive', ... }`) to let the consumer self-tune its concurrency\n * (latency gradient + RAM brake + backpressure) and publish a live status on its heartbeat. Ignored\n * for a plain operator (no `connection`).\n */\n concurrency?: ConcurrencyOption;\n /**\n * Per-handler concurrency override, keyed by workflow/step NAME. Falls back to {@link concurrency}\n * (then 1). NOT YET WIRED THROUGH: `runRedisWorker` (`@dudousxd/durable-worker`) currently applies\n * one {@link concurrency} limit uniformly across every per-name queue it subscribes to from a\n * single call — reserved here for when per-name concurrency lands there.\n */\n concurrencyByHandler?: Record<string, ConcurrencyOption>;\n /** Timeout for a thin worker's `RunGateway` round-trip over `transport` before it rejects. Defaults\n * to 10_000ms inside `ProxyRunGateway`. Ignored for an operator (bound to `StoreRunGateway`). */\n runGatewayTimeoutMs?: number;\n /**\n * **Operator.** Verifies the signed tenant token a store-less tenant worker presents in the wire\n * `tenant` field of every run request and start-run message, and DERIVES the tenant from it,\n * discarding the wire claim. An invalid, tampered or absent token is rejected: a run request gets\n * an `unauthorized` error reply, a start-run creates nothing; a verifier that throws fails the\n * request with its error. Use `hmacTenantVerifier(secret)` (tokens minted by `signTenantToken`,\n * wire-compatible with Agora) or supply your own: a function, an object or class implementing\n * `TenantVerifierContract` (a class is built once through Nest DI), or a lazy import of one\n * (`() => import('./tenant-verifier.js')`, imported once).\n *\n * Optional. Absent: the wire `tenant` is trusted verbatim (prefix/network isolation only), exactly\n * as before. `topology: 'control-plane'` without a verifier logs a warning at boot; a standalone\n * operator boots silently.\n */\n verifyTenant?: TenantVerifierOption;\n /**\n * **Tenant worker.** The signed token (see `signTenantToken`) this worker presents, verbatim, in\n * the `tenant` field of every run request (`ProxyRunGateway`) and start-run (`engine.start`), so\n * an operator with {@link verifyTenant} can authenticate it. A string, a function called before\n * every request (rotation, short-lived tokens), an object or class implementing\n * `TenantCredentialsContract` (a class is built once through Nest DI), or a lazy import of one.\n * Every form but the string is called per request and owns its caching. Optional: absent, the raw\n * {@link partition} is sent, as before. Live-tail stays keyed by the partition, never the token.\n */\n tenantToken?: TenantTokenOption;\n}\n\n/** The process roles a {@link DurableModuleOptions.topology} names. Same vocabulary as Agora. */\nexport type DurableTopologyName = 'standalone' | 'control-plane' | 'tenant';\n\n/**\n * The default topology: today's role inference from `store`/`connection` (see\n * {@link DurableModuleSharedOptions}). `partition` is the queue suffix a worker role serves.\n */\nexport interface StandaloneDurableOptions extends DurableModuleSharedOptions {\n topology?: 'standalone';\n}\n\n/**\n * A coordinator: owns the store, dispatches over the transport, recovers, fires timers, prunes\n * retention and answers tenant requests. Requires `store` and `transport` (or `transports`).\n */\nexport interface ControlPlaneDurableOptions\n extends Omit<DurableModuleSharedOptions, 'store' | 'tenantToken'> {\n topology: 'control-plane';\n store: StateStore;\n /**\n * The namespace this control plane serves. Omit it on a deployed control plane, which then drives\n * every tenant's runs. Set it to scope a self-contained stack (a developer's machine sharing a\n * broker with a deployed cluster) to its own runs: it becomes this node's `namespace` and the\n * `<name>@<partition>` queues its co-located consumers subscribe to.\n */\n partition?: string;\n /** A control plane verifies tenant tokens; it does not present one. */\n tenantToken?: never;\n}\n\n/**\n * A store-less worker for one partition: it pulls `<name>@<partition>` tasks from the broker over\n * `connection` and, with a `transport`, proxies reads and control actions to the control plane.\n */\nexport interface TenantDurableOptions\n extends Omit<\n DurableModuleSharedOptions,\n 'store' | 'namespace' | 'partition' | 'connection' | 'verifyTenant'\n > {\n topology: 'tenant';\n /** A tenant is store-less: everything goes over the wire to the control plane. */\n store?: never;\n /** `namespace` scopes an operator's poll loop; a tenant has none. Use `partition`. */\n namespace?: never;\n /** The partition this process serves and acts as. Required. */\n partition: string;\n /** The broker connection the tenant's consumer pulls its partition's tasks from. Required. */\n connection: string | Record<string, unknown>;\n /** A tenant presents a token (`tenantToken`); the control plane verifies it. */\n verifyTenant?: never;\n}\n\n/**\n * Options for `DurableModule.forRoot`/`forRootAsync`, discriminated on `topology`:\n *\n * ```ts\n * // Control plane: owns the store, dispatches over the transport, prunes old runs.\n * DurableModule.forRoot({\n * topology: 'control-plane',\n * store,\n * transport,\n * retention: { policies: [{ statuses: ['completed', 'cancelled'], maxAge: '14d' }] },\n * });\n *\n * // Tenant: a store-less worker serving its own partition.\n * DurableModule.forRoot({\n * topology: 'tenant',\n * partition: 'acme-corp',\n * connection: process.env.REDIS_URL,\n * });\n * ```\n *\n * Omit `topology` (or pass `'standalone'`) to keep the role inference described on\n * {@link DurableModuleSharedOptions}. TypeScript rejects a `store` on a tenant; the rest is\n * validated at `forRoot`/`forRootAsync` resolution time.\n */\nexport type DurableModuleOptions =\n | StandaloneDurableOptions\n | ControlPlaneDurableOptions\n | TenantDurableOptions;\n\nexport interface DurableModuleAsyncOptions {\n // `never[]` (not `object[]`) is intentional: a contravariant bottom-type rest param is what lets a\n // consumer supply a factory with concrete injected args, e.g. `(config: ConfigService) => …`.\n useFactory: (...args: never[]) => DurableModuleOptions | Promise<DurableModuleOptions>;\n inject?: InjectionToken[];\n}\n\n/** Park `transport`'s point-to-point consumers (`consumers: false`) when it supports it. */\nfunction deferTransportConsumers(transport: Transport): void {\n const deferrable = transport as Transport & { deferConsumers?: () => void };\n if (typeof deferrable.deferConsumers === 'function') {\n deferrable.deferConsumers();\n return;\n }\n console.warn(\n `[nestjs-durable] consumers: false — ${transport.constructor?.name ?? 'this transport'} cannot defer its consumers and will keep consuming in this process`,\n );\n}\n\n/** Throws the exact role-inference contract errors documented on {@link DurableModuleOptions}. */\nfunction assertValidRole(options: DurableModuleOptions): void {\n const hasStore = options.store !== undefined;\n const hasConnection = options.connection !== undefined;\n if (!hasStore && !hasConnection) {\n throw new Error(\n 'a durable module needs either a `store` (operator) or a `connection` (worker)',\n );\n }\n if (hasStore && options.transport === undefined && options.transports === undefined) {\n throw new Error('an operator (`store`) needs a `transport` (or `transports`)');\n }\n}\n\nconst TOPOLOGIES: readonly DurableTopologyName[] = ['standalone', 'control-plane', 'tenant'];\n\n/**\n * Validates {@link DurableModuleOptions.topology}. `standalone` (or none) keeps the role inference\n * of {@link assertValidRole}; the two named roles check their own axes, and each message names the\n * option at fault and the axis it protects: `namespace` scopes an operator's poll loop, `partition`\n * is the queue suffix a worker serves.\n */\nfunction assertValidTopology(options: DurableModuleOptions): void {\n const topology: unknown = options.topology;\n if (topology === undefined || topology === 'standalone') {\n assertValidRole(options);\n return;\n }\n if (typeof topology !== 'string' || !TOPOLOGIES.includes(topology as DurableTopologyName)) {\n const hint =\n typeof topology === 'object' && topology !== null\n ? \"\\nThe object form is gone: `topology: { role: 'tenant', tenant: 'acme' }` is now \" +\n \"`topology: 'tenant', partition: 'acme'`.\"\n : '';\n throw new Error(\n `topology must be 'standalone', 'control-plane' or 'tenant' (got ${JSON.stringify(topology)}).${hint}`,\n );\n }\n\n if (topology === 'control-plane') {\n if (\n options.store === undefined ||\n (options.transport === undefined && options.transports === undefined)\n ) {\n throw new Error(\n \"topology: 'control-plane' needs `store` AND (`transport` or `transports`).\\n\" +\n 'A control-plane node is the durable operator: it owns the state store and dispatches ' +\n 'runs to workers over a transport. Without both, there is nothing for it to operate.',\n );\n }\n if ((options as { tenantToken?: unknown }).tenantToken !== undefined) {\n throw new Error(\n \"topology: 'control-plane' forbids `tenantToken`.\\n\" +\n 'A control plane verifies tenant tokens (`verifyTenant`); it does not present one. ' +\n \"`tenantToken` belongs on the `topology: 'tenant'` process.\",\n );\n }\n const { partition, namespace } = options;\n if (partition !== undefined && namespace !== undefined && namespace !== partition) {\n throw new Error(\n `topology: 'control-plane' with \\`partition: '${partition}'\\` conflicts with \\`namespace: '${namespace}'\\`.\\nOn a control plane, partition becomes its namespace (the runs it drives). Set only \\`partition\\`, or set \\`namespace\\` to the same value.`,\n );\n }\n return;\n }\n\n const partition: unknown = options.partition;\n if (typeof partition !== 'string' || partition.length === 0) {\n throw new Error(\n \"topology: 'tenant' needs `partition`.\\nIt names the tenant this process serves: its \" +\n 'consumers pull `<name>@<partition>` tasks and its requests act as that tenant.',\n );\n }\n if (options.connection === undefined) {\n throw new Error(\n `topology: 'tenant' (partition '${partition}') needs \\`connection\\`.\\nA tenant is a store-less worker: it connects to the broker directly to pull its own partition of tasks instead of polling a store it does not have.`,\n );\n }\n if (options.store !== undefined) {\n throw new Error(\n \"topology: 'tenant' forbids `store`.\\n\" +\n 'A tenant is store-less BY DEFINITION. A `store` present means you actually wanted ' +\n \"`topology: 'control-plane'` (the store-owning role).\",\n );\n }\n if ((options as { verifyTenant?: unknown }).verifyTenant !== undefined) {\n throw new Error(\n \"topology: 'tenant' forbids `verifyTenant`.\\n\" +\n 'A tenant presents a token (`tenantToken`); the control plane verifies it. ' +\n \"`verifyTenant` belongs on the `topology: 'control-plane'` process.\",\n );\n }\n if (options.namespace !== undefined) {\n throw new Error(\n \"topology: 'tenant' forbids `namespace`.\\n\" +\n \"namespace is the OPERATOR's poll-scoping axis (which runs a control-plane instance \" +\n 'drives/recovers/resumes); a tenant worker has no poll loop for it to scope. Use ' +\n '`partition` for the tenant this process serves.',\n );\n }\n}\n\n/**\n * Applies the topology's `partition` mapping and the serving-partition default. Validated already by\n * {@link assertValidTopology}.\n */\nfunction resolveTopology(options: DurableModuleOptions): DurableModuleOptions {\n return servingPartition(resolveTopologyPreset(options));\n}\n\n/**\n * Fill the WORKER-side `partition` from this node's own `namespace` when it wasn't declared. The two\n * are one axis on the wire: the engine dispatches a run's steps to `<name>@<run.namespace>` (core's\n * `stepGroup`), so a node that stamps its runs with a namespace must SERVE the matching token or it\n * enqueues into queues nobody consumes. This is what keeps the documented local-dev recipe\n * (`docs/namespaces.md`, a namespaced engine on a private Redis) working with no extra wiring.\n *\n * An explicit `partition` always wins, so a node deliberately serving a different pool stays put.\n */\nfunction servingPartition(options: DurableModuleOptions): DurableModuleOptions {\n if (options.partition !== undefined || options.namespace === undefined) return options;\n return { ...options, partition: options.namespace } as DurableModuleOptions;\n}\n\nfunction resolveTopologyPreset(options: DurableModuleOptions): DurableModuleOptions {\n if (options.topology !== 'control-plane' || options.partition === undefined) return options;\n // A control plane's partition is its namespace: the engine stamps its runs with it and routes their\n // steps to `<name>@<partition>` (core's `stepGroup`), so its own co-located consumers keep\n // `partition` and subscribe those same tokens. It stays a STORE-side axis and never re-scopes the\n // transport keyspace. An explicit equal `namespace` was validated by assertValidTopology.\n return { ...options, namespace: options.namespace ?? options.partition };\n}\n\n/** The `verifyTenant` / `tenantToken` options, resolved to the plain functions the wire layer calls. */\nexport interface ResolvedTenantAuth {\n verifyTenant: TenantVerifier | undefined;\n tenantToken: TenantTokenSource | undefined;\n}\n\n/**\n * Boot-time wiring for the tenant run gateway's OPERATOR side, gated by {@link isDrivingOperator} (an\n * operator instance drives by default; `drive: false` — or a thin worker with no `store` at all —\n * does not). Two independent capabilities, each wired only when the transport carries it:\n *\n * 1. **`RunRequestResponder`** — answers a tenant's {@link RunRequest} against the bound\n * {@link RunGateway}, tenant-scoped. Wired when the transport implements both\n * `onRunRequest`/`publishRunReply` (only broker transports carry the protocol).\n * 2. **Tenant-event re-publisher** ({@link TenantEventRepublisher}) — mirrors every engine\n * lifecycle event onto its run's per-tenant channel via `publishTenantEvent`, so a store-less\n * tenant worker can live-tail its OWN runs. See that class for the namespace-resolution and\n * cache-eviction details.\n */\n@Injectable()\nclass RunGatewayBootstrap implements OnApplicationBootstrap, OnModuleDestroy {\n private unsubscribe?: () => void;\n\n constructor(\n private readonly engine: WorkflowEngine,\n @Inject(TRANSPORT_CANONICAL) private readonly transport: Transport | null,\n private readonly gateway: RunGateway,\n @Inject(STATE_STORE_CANONICAL) private readonly store: StateStore | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n @Inject(TENANT_AUTH) private readonly auth: ResolvedTenantAuth,\n ) {}\n\n onApplicationBootstrap(): void {\n if (!isDrivingOperator(this.options) || !this.transport) return;\n const store = this.store;\n if (!store) return; // unreachable when isDrivingOperator is true — keeps types honest\n\n const { onRunRequest, publishRunReply, publishTenantEvent } = this.transport;\n if (typeof onRunRequest === 'function' && typeof publishRunReply === 'function') {\n // Bind to the transport: these are real methods that touch the transport's private fields\n // (e.g. BullMQTransport's `this.#runRequestName()`), so they must keep their receiver — passing\n // them destructured/unbound makes `this` the literal below and throws \"Receiver must be an\n // instance of class\" on first use. (Mirrors the `publishTenantEvent.bind` just below.)\n const runRequestTransport: RunRequestTransport = {\n onRunRequest: onRunRequest.bind(this.transport),\n publishRunReply: publishRunReply.bind(this.transport),\n };\n new RunRequestResponder(runRequestTransport, this.gateway, {\n verifyTenant: this.auth.verifyTenant,\n // Mirrors Agora's rule (`warnWithoutVerifier: topology === 'control-plane'`): only a deployment\n // that EXPLICITLY names itself the control plane is told it runs without tenant auth. On a\n // `standalone` operator (role inferred from `store`) anyone with broker access\n // can already enqueue steps and results there, so the warning would be noise on every boot\n // of an app that never serves tenants.\n warnWithoutVerifier: this.options.topology === 'control-plane',\n }).start();\n }\n\n if (typeof publishTenantEvent === 'function') {\n const republisher = new TenantEventRepublisher(\n store,\n publishTenantEvent.bind(this.transport),\n );\n this.unsubscribe = this.engine.subscribe((event) => {\n // Tenant event mirroring is best-effort; a namespace lookup outage must not kill the worker.\n void republisher.handle(event).catch(() => undefined);\n });\n }\n }\n\n onModuleDestroy(): void {\n this.unsubscribe?.();\n }\n}\n\n/**\n * Restores the tenant a dispatched step task carries around its handler, in whichever process and on\n * whichever transport runs it (an operator's in-process consumer or a thin worker). Registered only\n * when durable's tenancy is on at boot, so an app without tenancy keeps an empty execution-hook\n * registry (zero cost).\n */\n@Injectable()\nclass DurableTenancyBridge implements OnApplicationBootstrap, OnModuleDestroy {\n private unregister?: () => void;\n\n constructor(\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n private readonly moduleRef: ModuleRef,\n ) {}\n\n async onApplicationBootstrap(): Promise<void> {\n if (this.options.tenancy === false) return;\n const accessor = resolveAccessor(this.moduleRef);\n if (!readTenancy(this.options.tenancy, accessor).enabled) return;\n const runtime = await resolveContextRuntime();\n if (!canRestoreTenant(runtime)) return;\n this.unregister = useDurableExecution(\n stepTenantWrapper(\n this.options.tenancy,\n accessor,\n isTenantRuntime(runtime) ? runtime : undefined,\n ),\n );\n }\n\n onModuleDestroy(): void {\n this.unregister?.();\n }\n}\n\n/**\n * `forRoot` / `forRootAsync` first refuse to boot when two different installs of\n * `@dudousxd/nestjs-durable-core` are loaded in this process (a pnpm peer-variant split): each copy\n * has its own `WorkflowEngine` class, so code from one copy cannot resolve the engine the other copy\n * registered. They throw `DuplicateDurableCopyError` naming both installs, and a distinct copy that\n * loads afterwards throws on load.\n */\n@Module({})\nexport class DurableModule {\n static forRoot(options: DurableModuleOptions): DynamicModule {\n sealDurableCopies();\n DurableModule.assertValid(options);\n return DurableModule.build({\n provide: DURABLE_OPTIONS_CANONICAL,\n useValue: resolveTopology(options),\n });\n }\n\n static forRootAsync(options: DurableModuleAsyncOptions): DynamicModule {\n sealDurableCopies();\n return DurableModule.build({\n provide: DURABLE_OPTIONS_CANONICAL,\n useFactory: async (...args: Parameters<DurableModuleAsyncOptions['useFactory']>) => {\n const resolved = await options.useFactory(...args);\n DurableModule.assertValid(resolved);\n return resolveTopology(resolved);\n },\n inject: options.inject ?? [],\n });\n }\n\n /** Validates the topology and its role/axis constraints; see {@link assertValidTopology}. */\n private static assertValid(options: DurableModuleOptions): void {\n assertValidTopology(options);\n }\n\n private static build(optionsProvider: Provider): DynamicModule {\n return {\n module: DurableModule,\n global: true,\n imports: [DiscoveryModule],\n providers: [\n optionsProvider,\n {\n provide: STATE_STORE_CANONICAL,\n useFactory: (options: DurableModuleOptions): StateStore | null =>\n options.store !== undefined ? scopedStore(options.store, options) : null,\n inject: [DURABLE_OPTIONS_CANONICAL],\n },\n {\n provide: TRANSPORT_CANONICAL,\n // With a POOL (`transports`) and no singular `transport`, the canonical transport is the\n // pool's PRIMARY — the same one the engine dispatches on first. Leaving it null starved\n // the step registrar / in-app worker of a transport, so a pool-configured operator\n // registered NO step handlers and its own steps parked in `wait` with no consumer.\n useFactory: (options: DurableModuleOptions) =>\n options.transport ?? options.transports?.[0]?.transport ?? null,\n inject: [DURABLE_OPTIONS_CANONICAL],\n },\n {\n provide: TENANT_AUTH,\n useFactory: (\n options: DurableModuleOptions,\n moduleRef: ModuleRef,\n ): ResolvedTenantAuth => ({\n verifyTenant: resolveTenantVerifier(options.verifyTenant, moduleRef),\n tenantToken: resolveTenantTokenSource(options.tenantToken, moduleRef),\n }),\n inject: [DURABLE_OPTIONS_CANONICAL, ModuleRef],\n },\n // Deprecated tokens that published releases still import resolve to the same instances:\n { provide: STATE_STORE, useExisting: STATE_STORE_CANONICAL },\n { provide: TRANSPORT, useExisting: TRANSPORT_CANONICAL },\n { provide: DURABLE_OPTIONS, useExisting: DURABLE_OPTIONS_CANONICAL },\n {\n // Shared token, bound EXACTLY once: a real engine for the operator role, or a store-less\n // `DurableStartClient` facade for a thin worker (no `store`) — either way, `WorkflowService`\n // and app code call `engine.start(...)` unchanged.\n provide: WorkflowEngine,\n useFactory: async (\n options: DurableModuleOptions,\n store: StateStore | null,\n transport: Transport | null,\n // The accessor from `@dudousxd/nestjs-context` is resolved at construction via ModuleRef\n // (shared CONTEXT_ACCESSOR symbol — no hard import). Absent → unchanged behavior.\n moduleRef: ModuleRef,\n auth: ResolvedTenantAuth,\n ) => {\n if (options.store === undefined) {\n return new DurableStartClient(\n {\n ...options,\n ...(auth.tenantToken !== undefined ? { tenantToken: auth.tenantToken } : {}),\n } as DurableModuleOptions,\n undefined,\n resolveAccessor(moduleRef),\n // `signal`/`signalWithStart`/`publishEvent` go to the control plane as run requests,\n // over the one `ProxyRunGateway` bound under `RunGateway` (it owns the reply\n // subscription). Resolved lazily: that gateway is built after this facade.\n () => {\n try {\n const gateway = moduleRef.get(RunGateway, { strict: false });\n return gateway instanceof ProxyRunGateway ? gateway : undefined;\n } catch {\n return undefined;\n }\n },\n );\n }\n if (!store) {\n throw new Error(\n 'unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set',\n );\n }\n // The control-plane default is the primary task transport (single, or the pool's first)\n // when it can broadcast.\n const primary = transport ?? options.transports?.[0]?.transport;\n // Auto-feed the carrier from nestjs-context when an accessor is present AND the app didn't\n // pass its own `context` reader. The app's own reader always wins; with no accessor the\n // carrier stays `undefined` (unchanged behavior — `traceparent` etc. still work).\n const accessor = resolveAccessor(moduleRef);\n const context =\n options.context ?? (accessor ? () => carrierFromAccessor(accessor) : undefined);\n const runtimeNeeded = accessor !== undefined || contextSlotPresent();\n // Consume side: when nestjs-context is present (an accessor is bound), re-hydrate the\n // originating context AROUND each local step body, so a `@Step` reader sees the\n // tenant/user/trace ids ambiently via nestjs-context's ALS — no consumer wrapping needed.\n // The runtime `Context` is a module-level singleton (not the accessor token), resolved\n // ONCE here via a guarded dynamic import (optional peer — failure leaves the default\n // passthrough). Best-effort: an empty/undefined carrier just runs the handler normally.\n // The engine re-applies the run row's tenant INSIDE this bridge, so an app deserializer\n // that drops the tenant cannot take it away from a local step.\n const runtime = runtimeNeeded ? await resolveContextRuntime() : undefined;\n const rehydrate =\n runtime &&\n (<T>(carrier: Record<string, unknown> | undefined, fn: () => T): T =>\n carrier && Object.keys(carrier).length > 0\n ? runtime.deserialize(carrier, fn)\n : fn());\n // `consumers: false`: park every transport's point-to-point consumers BEFORE the engine\n // subscribes to them (its constructor registers the results/decisions consumers).\n if (options.consumers === false) {\n for (const t of [transport, ...(options.transports ?? []).map((n) => n.transport)]) {\n if (t) deferTransportConsumers(t);\n }\n }\n const engine = new WorkflowEngine({\n store,\n transport: transport ?? undefined,\n transports: options.transports,\n controlPlane: options.controlPlane ?? (isControlPlane(primary) ? primary : undefined),\n leaseMs: options.leaseMs,\n admission: options.admission,\n maxRecoveryAttempts: options.maxRecoveryAttempts,\n unregisteredWorkflowGraceMs: options.unregisteredWorkflowGraceMs,\n remoteAdvanceSilenceMs: options.remoteAdvanceSilenceMs,\n remoteRedispatchMs: options.remoteRedispatchMs,\n remoteRedispatchMax: options.remoteRedispatchMax,\n reconcileMs: options.reconcileMs,\n stalledAfterMs: options.stalledAfterMs,\n timerBatchSize: options.timerBatchSize,\n eventBufferTtlMs: options.eventBufferTtlMs,\n signalIdTtl: options.signalIdTtl,\n blockedPollMs: options.blockedPollMs,\n workerDescriptorCacheMs: options.workerDescriptorCacheMs,\n trackStepStart: options.trackStepStart,\n stickyRuns: options.stickyRuns,\n stickyIdleMs: options.stickyIdleMs,\n routeReplies: options.routeReplies,\n instanceId: options.instanceId,\n namespace: options.namespace,\n webhookUrl: options.webhookUrl,\n traceparent: options.traceparent,\n context,\n rehydrate: (accessor && rehydrate) || undefined,\n // The run's tenant, restored around every turn (see `tenancy` above).\n tenancy: buildEngineTenancy(\n options.tenancy,\n accessor,\n isTenantRuntime(runtime) ? runtime : undefined,\n ),\n compensationRetries: options.compensationRetries,\n verifyTenant: auth.verifyTenant,\n // A non-driving (dashboard/API) operator must not run workflows: enqueue-only, leaving\n // each `pending` run in the store for a DRIVING instance's poll. A driving operator gets\n // the engine's default in-process dispatcher: for a body registered inline, it runs\n // locally; for one registered GROUP-SERVED (co-located worker) or left unregistered, the\n // SAME default dispatcher routes it out remotely (group-served executor, or convention\n // dispatch — always on) instead.\n runDispatcher: options.drive === false ? { dispatch: () => {} } : undefined,\n });\n for (const queue of options.queues ?? []) engine.registerQueue(queue);\n if (options.onStalled) engine.onStalled(options.onStalled);\n // Dead-letter routing (per-workflow `@DeadLetter()` / `deadLetterWorkflow` + this global\n // default) is wired by the WorkflowRegistrar, which owns the `@Workflow` metadata.\n return engine;\n },\n inject: [\n DURABLE_OPTIONS_CANONICAL,\n STATE_STORE_CANONICAL,\n TRANSPORT_CANONICAL,\n ModuleRef,\n TENANT_AUTH,\n ],\n },\n WorkflowService,\n EntityService,\n WorkflowRegistrar,\n DurableStepRegistrar,\n SweepLeases,\n TimerPoller,\n RetentionPoller,\n // Tenant run gateway: bound EXACTLY once — the store-backed `StoreRunGateway` for an operator,\n // or (for a thin worker, no `store`) a `ProxyRunGateway` over `transport` when given, else a\n // gateway whose every method rejects with a clear tenant error.\n {\n provide: RunGateway,\n useFactory: (\n options: DurableModuleOptions,\n store: StateStore | null,\n engine: WorkflowEngine,\n auth: ResolvedTenantAuth,\n moduleRef: ModuleRef,\n ): RunGateway => {\n if (options.store !== undefined) {\n if (!store) {\n throw new Error(\n 'unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set',\n );\n }\n return new StoreRunGateway(store, engine);\n }\n return options.transport\n ? new ProxyRunGateway(\n options.transport,\n options.partition ?? 'default',\n options.runGatewayTimeoutMs,\n undefined,\n auth.tenantToken,\n options.tenancy === false\n ? undefined\n : () => tenantFilterNow(options.tenancy, resolveAccessor(moduleRef)),\n )\n : unavailableRunGateway();\n },\n inject: [\n DURABLE_OPTIONS_CANONICAL,\n STATE_STORE_CANONICAL,\n WorkflowEngine,\n TENANT_AUTH,\n ModuleRef,\n ],\n },\n RunGatewayBootstrap,\n DurableTenancyBridge,\n // Co-located in-app worker (uniform dispatch): inert unless BOTH `store` and `connection` are\n // set — see `in-app-worker.ts`.\n ...inAppWorkerProviders(),\n // Pure thin-worker consumer: inert unless `connection` is set WITHOUT `store` — see\n // `durable-worker.module.ts`.\n ...thinWorkerProviders(),\n ],\n exports: [\n WorkflowService,\n EntityService,\n WorkflowEngine,\n STATE_STORE,\n STATE_STORE_CANONICAL,\n TRANSPORT,\n TRANSPORT_CANONICAL,\n DURABLE_OPTIONS_CANONICAL,\n RunGateway,\n ],\n };\n }\n}\n","import {\n DURABLE_OPTIONS_CANONICAL,\n type StepLogger,\n TRANSPORT_CANONICAL,\n type Transport,\n} from '@dudousxd/nestjs-durable-core';\nimport { Inject, Injectable, type OnModuleInit } from '@nestjs/common';\nimport { DiscoveryService, MetadataScanner } from '@nestjs/core';\nimport { scanSteps } from './discovery-helpers';\nimport type { DurableModuleOptions } from './durable.module';\nimport { isDrivingOperator } from './role';\n\n/** A transport that can run step handlers in-process (e.g. the event-emitter transport). */\ninterface LocalTaskHandling {\n handle(\n name: string,\n fn: (input: unknown, log: StepLogger) => Promise<unknown> | unknown,\n /** Isolation partition to SERVE — the queue token is `tenantGroup(sanitizeQueueToken(name),\n * partition)`. Omitted (or undefined) keeps the transport's own constructor partition. */\n partition?: string | undefined,\n ): void;\n}\n\nfunction supportsHandle(transport: unknown): transport is LocalTaskHandling {\n return typeof (transport as LocalTaskHandling | null)?.handle === 'function';\n}\n\n/**\n * Discovers `@Step` methods and registers them — under their RESOLVED name (derived `Class.method`\n * for a bare `@Step()`, or the explicit override) — as step handlers on the configured transport,\n * when that transport runs handlers in-process. With a queue/remote transport the handlers live in\n * the worker process instead, so there is nothing to wire here.\n *\n * **Context re-hydration (consume side) is the consumer's responsibility.** DurableModule's\n * produce side auto-feeds an opaque carrier (`{ traceId, tenantId, userRef }`) from\n * `@dudousxd/nestjs-context` onto each dispatched `RemoteTask.context` (see DurableModule). A worker\n * that wants its `@Step` reads to SEE the originating context must re-establish it from\n * `task.context`. We do NOT do this here because: (a) re-hydration needs nestjs-context's module-level\n * `Context.deserialize(carrier, fn)` at runtime, and it is an OPTIONAL peer we must not hard-import;\n * and (b) the in-process `StepHandler` contract is `(input, log)` — the engine never surfaces\n * `task.context` to the handler closure, so wrapping it here would require widening the core\n * transport/handler signature (a non-additive cross-cutting change). Instead, a worker that consumes\n * the carrier should wrap its handler with `Context.deserialize(task.context, () => handler(...))`\n * from its own transport/worker bootstrap, where `task` is in scope.\n */\n@Injectable()\nexport class DurableStepRegistrar implements OnModuleInit {\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly metadataScanner: MetadataScanner,\n @Inject(TRANSPORT_CANONICAL) private readonly transport: Transport | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n ) {}\n\n onModuleInit(): void {\n // A non-driving operator (`drive: false`) or a thin worker (no `store`) must not consume the\n // queue — receiving and running step tasks locally is exactly the driving-operator role we're\n // switching off here (a thin worker registers its steps via `ThinStepRegistrar` instead).\n if (!isDrivingOperator(this.options)) return;\n if (!supportsHandle(this.transport)) return;\n const transport = this.transport;\n\n // Forward the step logger as a second arg; methods that only declare `(input)` ignore it.\n // The partition is the node's own tenant axis (`topology: 'control-plane'` with a `partition`\n // resolves it, see `resolveTopology`): this engine DISPATCHES a tenant run's steps to\n // `<name>@<tenant>`, so its in-process handlers must SERVE that same token. Undefined on a global\n // operator — the bare token, byte-identical to before.\n scanSteps(this.discovery, this.metadataScanner, (meta, handler) =>\n transport.handle(meta.name, handler, this.options.partition),\n );\n }\n}\n","import type { DurableModuleOptions } from './durable.module';\n\n/**\n * True for the **operator** role — `store` is set (with or without a co-located `connection`). See\n * {@link DurableModuleOptions} for the full role matrix. Kept in its own module (rather than\n * `durable.module.ts`) so the poller/registrar classes can import it as a plain VALUE without a\n * circular value dependency on the module that also imports them as providers.\n */\nexport function isOperatorRole(options: DurableModuleOptions): boolean {\n return options.store !== undefined;\n}\n\n/**\n * True when an operator instance actively DRIVES runs — polls pending, recovers crashed, resumes due\n * timers, sweeps timeouts, prunes retention, consumes local steps — as opposed to a read-only/\n * dashboard replica (`drive: false`) that mounts the store/dashboard but leaves driving to another\n * instance. Meaningless (`false`) outside the operator role. Defaults to `true` for an operator.\n */\nexport function isDrivingOperator(options: DurableModuleOptions): boolean {\n return isOperatorRole(options) && options.drive !== false;\n}\n","import type { DurableWorkerRuntime, RunningWorker } from '@dudousxd/durable-worker';\nimport {\n DURABLE_OPTIONS_CANONICAL,\n TRANSPORT_CANONICAL,\n type Transport,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n Inject,\n Injectable,\n type OnApplicationBootstrap,\n type OnApplicationShutdown,\n type OnModuleInit,\n type Provider,\n} from '@nestjs/common';\nimport { DiscoveryService, MetadataScanner } from '@nestjs/core';\nimport { scanSteps, scanWorkflows } from './discovery-helpers';\nimport type { RunRedisWorkerFn } from './durable-worker.module';\nimport type { DurableModuleOptions } from './durable.module';\nimport { registerOnRuntime } from './runtime-registration';\nimport { createWorkerRuntime, runRedisWorker as defaultRunRedisWorker } from './worker-sdk';\n\n/**\n * The **co-located in-app worker** (uniform dispatch): active whenever an app supplies BOTH `store`\n * AND `connection` (`DurableModule.forRoot({ store, transport, connection, partition? })`) — the same\n * process runs the engine AND serves its own discovered `@Workflow`/`@Step`. The engine registers each\n * `@Workflow` GROUP-SERVED — its turns are dispatched, PER WORKFLOW NAME, to\n * `tenantGroup(sanitizeQueueToken(name), partition)` over the transport via a per-workflow\n * `RemoteWorkflowExecutor` instead of run inline — and a co-located {@link DurableWorkerRuntime}\n * subscribes one queue per discovered name (via `runRedisWorker`) and replays the very same TS bodies.\n * This is the uniform-dispatch \"one app, both roles\" shape — every turn pays a transport round-trip\n * even though the worker is the same process. Requires a transport that carries workflow tasks\n * (BullMQ); an in-process-only transport cannot dispatch a `WorkflowExecutor`.\n *\n * Distinct from the PURE thin-worker role (`connection` set, `store` unset — see\n * `durable-worker.module.ts`'s `ThinWorkflowRegistrar`/`ThinStepRegistrar`/`ThinWorkerBootstrap`),\n * which has no engine/store of its own at all.\n */\nexport const IN_APP_WORKER_BINDING = Symbol('nestjs-durable:in-app-worker-binding');\n\n/** The co-located worker's {@link DurableWorkerRuntime} (the consumer half). */\nexport const IN_APP_WORKER_RUNTIME = Symbol('nestjs-durable:in-app-worker-runtime');\n\n/** `runRedisWorker`, injected so tests can substitute a fake (no real Redis). Defaults to the real one. */\nexport const IN_APP_RUN_REDIS_WORKER = Symbol('nestjs-durable:in-app-run-redis-worker');\n\n/** Started {@link RunningWorker} handles for the in-app worker, closed on shutdown. */\nexport const IN_APP_WORKER_RUNNERS = Symbol('nestjs-durable:in-app-worker-runners');\n\n/** The group-served binding shape resolved behind {@link IN_APP_WORKER_BINDING}. */\nexport interface InAppWorkerBinding {\n transport: Transport;\n partition?: string;\n}\n\n/** True for the **co-located** role — both `store` AND `connection` set. */\nfunction isCoLocatedWorker(options: DurableModuleOptions): boolean {\n return options.store !== undefined && options.connection !== undefined;\n}\n\n/**\n * Builds the {@link IN_APP_WORKER_BINDING}: when this app is co-located (`store` + `connection`), the\n * engine's transport plus the configured partition — the registrar builds a PER-WORKFLOW\n * `RemoteWorkflowExecutor` from these, one per discovered name; otherwise `null` (inline default).\n * Fails fast if co-located but the transport can't carry workflow tasks — a group-served run would\n * otherwise dead-end at dispatch.\n */\nfunction inAppWorkerBinding(\n transport: Transport | null,\n options: DurableModuleOptions,\n): InAppWorkerBinding | null {\n if (!isCoLocatedWorker(options)) return null;\n if (!transport?.dispatchWorkflowTask || !transport.onDecision) {\n throw new Error(\n 'a co-located worker (store + connection) requires a transport that carries workflow tasks (dispatchWorkflowTask + onDecision), e.g. BullMQTransport. An in-process transport cannot serve a group-served workflow.',\n );\n }\n return {\n transport,\n ...(options.partition !== undefined ? { partition: options.partition } : {}),\n };\n}\n\n/**\n * The consumer half of the in-app worker: on init it registers every discovered `@Workflow`/`@Step`\n * on a {@link DurableWorkerRuntime} (the SAME bodies the engine registered group-served), and on\n * bootstrap it starts one `runRedisWorker` call that subscribes one queue per discovered name,\n * suffixed by the configured partition, closing it on shutdown. A no-op outside the co-located role\n * (see {@link isCoLocatedWorker}). Mirrors the thin {@link\n * import('./durable-worker.module').ThinWorkerBootstrap}, but co-located with a full engine.\n */\n@Injectable()\nexport class InAppWorkerBootstrap\n implements OnModuleInit, OnApplicationBootstrap, OnApplicationShutdown\n{\n private readonly runners: RunningWorker[] = [];\n\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly metadataScanner: MetadataScanner,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n @Inject(IN_APP_WORKER_RUNTIME) private readonly runtime: DurableWorkerRuntime | null,\n @Inject(IN_APP_RUN_REDIS_WORKER) private readonly runRedisWorker: RunRedisWorkerFn,\n @Inject(IN_APP_WORKER_RUNNERS) private readonly runnersSink: RunningWorker[],\n ) {}\n\n onModuleInit(): void {\n const runtime = this.runtime;\n if (runtime === null || !isCoLocatedWorker(this.options)) return;\n // Register the same TS bodies the engine serves group-served, so the consumer can replay them.\n // The metadata rides along as this worker's ANNOUNCEMENT of what it can execute (design §7.9):\n // co-located or not, the process that CONSUMES the queue is the one entitled to announce the\n // workflow, and here that is this runtime — not the engine sharing its process.\n scanWorkflows(this.discovery, (meta, instance, origin) =>\n registerOnRuntime(runtime, this.metadataScanner, meta, instance, origin),\n );\n scanSteps(this.discovery, this.metadataScanner, (meta, handler) =>\n runtime.registerStep(meta.name, handler),\n );\n }\n\n async onApplicationBootstrap(): Promise<void> {\n const options = this.options;\n const runtime = this.runtime;\n if (runtime === null || !isCoLocatedWorker(options) || options.connection === undefined) return;\n // `consumers: false`: a producer-only process (CLI, REPL, script) starts no consumer.\n if (options.consumers === false) return;\n const handle = await this.runRedisWorker({\n runtime,\n connection: options.connection,\n ...(options.partition !== undefined ? { partition: options.partition } : {}),\n ...(options.prefix !== undefined ? { prefix: options.prefix } : {}),\n ...(options.instanceId !== undefined ? { instanceId: options.instanceId } : {}),\n ...(options.concurrency !== undefined ? { concurrency: options.concurrency } : {}),\n });\n this.runners.push(handle);\n this.runnersSink.push(handle);\n }\n\n async onApplicationShutdown(): Promise<void> {\n await Promise.allSettled(this.runners.map((handle) => handle.close()));\n }\n}\n\n/**\n * The providers that stand up the co-located in-app worker, added to {@link\n * import('./durable.module').DurableModule}'s unified provider set. All are inert outside the\n * co-located role (`store` + `connection` both set — see {@link isCoLocatedWorker}), so a plain\n * operator (`store` only) or pure thin worker (`connection` only) is unaffected.\n */\nexport function inAppWorkerProviders(): Provider[] {\n return [\n {\n provide: IN_APP_WORKER_BINDING,\n useFactory: (transport: Transport | null, options: DurableModuleOptions) =>\n inAppWorkerBinding(transport, options),\n inject: [TRANSPORT_CANONICAL, DURABLE_OPTIONS_CANONICAL],\n },\n {\n provide: IN_APP_WORKER_RUNTIME,\n // The runtime's `WorkflowWorker` uses its `group` ctor param as the WORKFLOW's\n // `workflowPartition` for any `ctx.step` call (see `workflow-context.ts`'s `resolveCallGroup`)\n // — that fallback MUST equal this app's own `partition`, or a dispatched step's decision\n // carries a mismatched token and the engine dispatches it to a queue nothing here subscribes\n // to. Explicit `''` (never\n // `undefined`) so it does NOT fall through to `WorkflowWorker`'s unrelated `'workflows'`\n // default parameter.\n //\n // The role gate lives HERE, not just in the consumer: constructing the runtime resolves the\n // optional `@dudousxd/durable-worker` peer, so an operator that never runs a worker must not\n // reach this branch at all.\n useFactory: (options: DurableModuleOptions) =>\n isCoLocatedWorker(options)\n ? createWorkerRuntime({ workflowGroup: options.partition ?? '' })\n : null,\n inject: [DURABLE_OPTIONS_CANONICAL],\n },\n { provide: IN_APP_RUN_REDIS_WORKER, useValue: defaultRunRedisWorker },\n { provide: IN_APP_WORKER_RUNNERS, useValue: [] as RunningWorker[] },\n InAppWorkerBootstrap,\n ];\n}\n","import type {\n DurableTopology,\n EngineEvent,\n FanPage,\n FanPageQuery,\n GroupHealth,\n RepublishLifecycleResult,\n RepublishLifecycleTarget,\n RunDetail,\n RunDetailOptions,\n RunFacetQuery,\n RunFacetRow,\n RunGateway,\n RunListItem,\n RunQuery,\n RunReply,\n RunRequestKind,\n RunResult,\n RunValueAxis,\n RunValueFacetOptions,\n RunValueFacetRow,\n RunWaiting,\n SignalOptions,\n StartRunMessage,\n TenantTokenSource,\n Transport,\n WorkflowLifecycleLinks,\n WorkflowRun,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n SUMMARY_CHILD_LIMIT,\n type TenantFilter,\n childIdsOf,\n pageFan,\n resolveTenantToken,\n scopeTenantQuery,\n summarizeTimeline,\n tenantVisible,\n} from '@dudousxd/nestjs-durable-core';\nimport { Injectable } from '@nestjs/common';\nimport { BAD_RUN_REQUEST, UNSUPPORTED_RUN_REQUEST } from './run-request-responder';\n\n/**\n * Method-shorthand signatures (not arrow-function-typed properties) are deliberate: TypeScript\n * checks method parameters bivariantly, so a `Promise<T>`'s own `resolve`/`reject` (typed for that\n * call's concrete `T`) can be stored here erased to `unknown` with no cast — the one place the\n * generic `T` from {@link ProxyRunGateway.request} crosses into the untyped bookkeeping map.\n */\ninterface PendingRequest {\n resolve(data: unknown): void;\n reject(err: Error): void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * An error reply from the control plane. `code` carries the reply's machine-readable reason when it\n * sent one — `unauthorized` (the tenant token was rejected), `cross-tenant` (the run belongs to\n * another tenant), `bad-request` (the request was malformed or not allowed), ... — so a caller can tell an authentication failure from a real one, as with\n * Agora's proxy.\n */\n/**\n * The codes the run-request responder replies with. `string & {}` keeps a code from a newer control\n * plane assignable without losing autocomplete on the known ones.\n */\nexport type RunGatewayErrorCode =\n | 'unauthorized'\n | 'cross-tenant'\n | typeof BAD_RUN_REQUEST\n | typeof UNSUPPORTED_RUN_REQUEST\n | (string & {});\n\nexport class RunGatewayError extends Error {\n readonly code: RunGatewayErrorCode | undefined;\n constructor(message: string, code?: RunGatewayErrorCode) {\n super(message);\n this.name = 'RunGatewayError';\n this.code = code;\n }\n}\n\n/** The error a verb the control plane does not know fails with (see `requestNewVerb`). */\nfunction unsupportedVerb(kind: string): RunGatewayError {\n return new RunGatewayError(\n `${kind} is not supported by this server: the control plane is older than this tenant`,\n UNSUPPORTED_RUN_REQUEST,\n );\n}\n\n/** The control plane answered a verb it does not know — an older release than this tenant's. */\nclass UnsupportedRunRequestError extends RunGatewayError {}\n\n/** An {@link UNSUPPORTED_RUN_REQUEST} error reply. Older responders answer an unknown verb with\n * `ok: true` and no `data` instead, which `getFanMembers` checks for itself. */\nfunction isUnsupported(err: unknown): boolean {\n return err instanceof UnsupportedRunRequestError;\n}\n\n/**\n * Tenant-side `RunGateway` — round-trips every verb as a `RunRequest`/`RunReply` pair over the\n * transport, correlated by a minted `requestId`, and bridges `subscribe` onto the transport's\n * per-tenant event stream. Bound under `RunGateway` by `DurableModule`'s thin-worker role\n * (`connection` set, no `store`) when the app supplies a `transport` (see `unavailableRunGateway`\n * for the no-transport fallback). The counterpart to the operator-side `StoreRunGateway`: a tenant\n * worker never touches a store/driver directly, only this proxy.\n */\n@Injectable()\nexport class ProxyRunGateway implements RunGateway {\n private readonly pending = new Map<string, PendingRequest>();\n /** Verb → when to ask the control plane for it again, after it answered that it does not know it.\n * During a rolling upgrade the control plane is several pods of mixed versions behind one queue,\n * and a reply does not say which pod sent it, so the whole control plane is assumed old until the\n * entry expires. */\n private readonly unsupportedUntil = new Map<RunRequestKind['kind'], number>();\n\n constructor(\n private readonly transport: Transport,\n private readonly tenant: string,\n private readonly timeoutMs = 10_000,\n private readonly capabilityTtlMs = 60_000,\n /**\n * The tenant's signed token (see `signTenantToken`), presented VERBATIM in the `tenant` field of\n * every {@link RunRequest} so an operator with `verifyTenant` can authenticate it and derive the\n * tenant from it. A function is called before every request (rotation / short-lived tokens).\n * Omit to send the raw `tenant` (prefix/network isolation only). The live-tail channel always\n * stays keyed by `tenant`, never the token: the operator republishes by the run's namespace.\n */\n private readonly tenantToken?: TenantTokenSource,\n /**\n * The customer-tenancy filter of the request being served (durable's `tenancy` on this process).\n * The control plane answers for this process's namespace; this narrows it to the request's\n * customer tenant: lists and counts get the tenant predicate, and a run of another tenant reads\n * (and is controlled) as missing. Absent: no narrowing.\n */\n private readonly tenantFilter?: () => TenantFilter,\n ) {\n this.transport.onRunReply?.((reply: RunReply) => this.handleReply(reply));\n }\n\n /** The request's tenant filter when it can hide runs (`tenant` / `tenantless`), else undefined. */\n private restrictive(): TenantFilter | undefined {\n const filter = this.tenantFilter?.();\n return filter && filter.mode !== 'system' && filter.mode !== 'all' ? filter : undefined;\n }\n\n /**\n * Send `query`, narrowed to the runs the request may see. A tenant-required request with no\n * tenant rejects (never throws synchronously).\n */\n private scoped<Q extends RunQuery | RunFacetQuery, T>(\n query: Q,\n send: (q: Q) => Promise<T>,\n ): Promise<T> {\n let filter: TenantFilter | undefined;\n try {\n filter = this.restrictive();\n } catch (err) {\n return Promise.reject(err);\n }\n return send(filter ? scopeTenantQuery(query, filter) : query);\n }\n\n /** `run` when the request may see it, else null (an invisible run reads like a missing one). */\n private visible<T extends { tenantId?: string | null | undefined }>(\n run: T | null | undefined,\n filter = this.restrictive(),\n ): T | null {\n if (!run) return null;\n return !filter || tenantVisible(run, filter) ? run : null;\n }\n\n /** Run a control call unless the request may not act on `runId` (then `null`, like a missing run).\n * Sent at once when nothing narrows the request. */\n private guarded<T>(runId: string, call: () => Promise<T | null>): Promise<T | null> {\n let filter: TenantFilter | undefined;\n try {\n filter = this.restrictive();\n } catch (err) {\n // A tenant-required request with no tenant: reject, like every other read.\n return Promise.reject(err);\n }\n if (!filter) return call();\n return this.hidden(runId).then((hidden) => (hidden ? null : call()));\n }\n\n /** Before a control call: true when the request may NOT act on `runId`. */\n private async hidden(runId: string): Promise<boolean> {\n const filter = this.restrictive();\n if (!filter) return false;\n return this.visible(await this.getRunUnscoped(runId), filter) === null;\n }\n\n private handleReply(reply: RunReply): void {\n const pending = this.pending.get(reply.requestId);\n if (!pending) return;\n clearTimeout(pending.timer);\n this.pending.delete(reply.requestId);\n if (reply.result.ok) {\n pending.resolve(reply.result.data);\n } else if (reply.result.error.code === UNSUPPORTED_RUN_REQUEST) {\n pending.reject(\n new UnsupportedRunRequestError(reply.result.error.message, UNSUPPORTED_RUN_REQUEST),\n );\n } else {\n pending.reject(new RunGatewayError(reply.result.error.message, reply.result.error.code));\n }\n }\n\n private request<T>(body: RunRequestKind): Promise<T> {\n // A static token (or none) dispatches synchronously, exactly as before. A token PROVIDER is\n // resolved first, and the `timeoutMs` clock starts only once it has: the deadline bounds the\n // control plane's round trip, not the provider's latency. A provider that rejects fails the request.\n const source = this.tenantToken;\n if (typeof source !== 'function') return this.send<T>(source ?? this.tenant, body);\n return resolveTenantToken(source).then((tenant) => this.send<T>(tenant, body));\n }\n\n private send<T>(tenant: string, body: RunRequestKind): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const requestId = globalThis.crypto.randomUUID();\n const timer = setTimeout(() => {\n this.pending.delete(requestId);\n reject(\n new Error(`control plane did not respond to ${body.kind} within ${this.timeoutMs}ms`),\n );\n }, this.timeoutMs);\n this.pending.set(requestId, { resolve, reject, timer });\n this.transport.dispatchRunRequest?.({ requestId, tenant, body })?.catch((error: unknown) => {\n const stillPending = this.pending.get(requestId);\n if (!stillPending) return;\n clearTimeout(stillPending.timer);\n this.pending.delete(requestId);\n stillPending.reject(error instanceof Error ? error : new Error(String(error)));\n });\n });\n }\n\n topology(): DurableTopology {\n return { role: 'tenant', tenant: this.tenant };\n }\n\n /**\n * A control plane that predates {@link RunDetailOptions} ignores them and sends the full detail;\n * a summarized detail always carries `fans`, so its absence means the summary is made here.\n */\n async getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null> {\n const filter = this.restrictive();\n const detail = await this.request<RunDetail | null>(\n options === undefined\n ? { kind: 'getRunDetail', runId }\n : { kind: 'getRunDetail', runId, options },\n );\n if (detail && filter && !this.visible(detail.run, filter)) return null;\n const over = options?.summarizeFansOver;\n if (over === undefined || !detail || detail.fans !== undefined) return detail;\n const { timeline, fans } = summarizeTimeline(detail.timeline, over);\n const ids = childIdsOf(detail.timeline);\n return {\n ...detail,\n timeline,\n children: ids.slice(0, SUMMARY_CHILD_LIMIT),\n fans,\n childCount: ids.length,\n };\n }\n\n /** Paged from the full detail when the control plane is too old to page a fan itself. */\n async getFanMembers(runId: string, group: string, query: FanPageQuery): Promise<FanPage | null> {\n if (this.restrictive() && (await this.hidden(runId))) return null;\n if (!this.knownUnsupported('getFanMembers')) {\n try {\n const page = await this.request<FanPage | null | undefined>({\n kind: 'getFanMembers',\n runId,\n group,\n query,\n });\n if (page !== undefined) return page;\n } catch (err) {\n if (!isUnsupported(err)) throw err;\n }\n this.unsupportedUntil.set('getFanMembers', Date.now() + this.capabilityTtlMs);\n }\n const detail = await this.request<RunDetail | null>({ kind: 'getRunDetail', runId });\n return detail ? pageFan(detail.timeline, group, query) : null;\n }\n\n /**\n * The run alone, without its timeline. Read from the full detail when the control plane is too old\n * to know the verb: it then answers with no data, or with an unsupported-request error.\n */\n async getRun(runId: string): Promise<WorkflowRun | null> {\n return this.visible(await this.getRunUnscoped(runId));\n }\n\n private async getRunUnscoped(runId: string): Promise<WorkflowRun | null> {\n if (!this.knownUnsupported('getRun')) {\n try {\n const run = await this.request<WorkflowRun | null | undefined>({ kind: 'getRun', runId });\n if (run !== undefined) return run;\n } catch (err) {\n if (!isUnsupported(err)) throw err;\n }\n this.unsupportedUntil.set('getRun', Date.now() + this.capabilityTtlMs);\n }\n const detail = await this.request<RunDetail | null>({ kind: 'getRunDetail', runId });\n return detail?.run ?? null;\n }\n\n private knownUnsupported(kind: RunRequestKind['kind']): boolean {\n const until = this.unsupportedUntil.get(kind);\n if (until === undefined) return false;\n if (Date.now() < until) return true;\n this.unsupportedUntil.delete(kind);\n return false;\n }\n\n /** The control plane's `StoreRunGateway` resolves each run's `waiting` descriptor; the reply carries\n * it through as plain JSON, so a tenant's list rows name the wait too. */\n listRuns(query: RunQuery): Promise<RunListItem[]> {\n return this.scoped(query, (q) => this.request<RunListItem[]>({ kind: 'listRuns', query: q }));\n }\n\n /** Counted on the operator, over the same tenant-scoped predicates its `listRuns` reply obeys. */\n runFacets(query: RunFacetQuery): Promise<RunFacetRow[]> {\n return this.scoped(query, (q) => this.request<RunFacetRow[]>({ kind: 'runFacets', query: q }));\n }\n\n /** Enumerated on the operator, over the same tenant-scoped predicates its `listRuns` reply obeys —\n * so a tenant's pickers offer its own tenants/tags/attributes and never another's. */\n runValueFacets(\n axis: RunValueAxis,\n query: RunFacetQuery,\n opts?: RunValueFacetOptions,\n ): Promise<RunValueFacetRow[]> {\n return this.scoped(query, (q) =>\n this.request<RunValueFacetRow[]>({ kind: 'runValueFacets', axis, query: q, opts }),\n );\n }\n\n /** Round-trips to the operator, which scopes the result to this tenant's own `@<tenant>` groups. */\n workerHealth(): Promise<GroupHealth[]> {\n return this.request<GroupHealth[]>({ kind: 'workerHealth' });\n }\n\n /** Bulk, one request for the whole id list (like `listRuns`, not one request per id). The operator\n * filters the reply to runs this tenant actually owns (see `RunRequestResponder`). */\n waitingFor(runIds: string[]): Promise<Record<string, RunWaiting>> {\n return this.request<Record<string, RunWaiting>>({ kind: 'waitingFor', runIds });\n }\n\n cancel(runId: string, opts?: { compensate?: boolean }): Promise<RunResult | null> {\n return this.guarded(runId, () =>\n this.request<RunResult | null>(\n opts === undefined ? { kind: 'cancel', runId } : { kind: 'cancel', runId, opts },\n ),\n );\n }\n\n retry(runId: string): Promise<RunResult | null> {\n return this.guarded(runId, () => this.request<RunResult | null>({ kind: 'retry', runId }));\n }\n\n continue(runId: string): Promise<RunResult | null> {\n return this.guarded(runId, () => this.request<RunResult | null>({ kind: 'continue', runId }));\n }\n\n retryWithInput(runId: string, input: unknown): Promise<{ runId: string } | null> {\n return this.guarded(runId, () =>\n this.request<{ runId: string } | null>({ kind: 'retryWithInput', runId, input }),\n );\n }\n\n redispatchPending(runId: string): Promise<(RunResult & { redispatched: number }) | null> {\n return this.guarded(runId, () =>\n this.request<(RunResult & { redispatched: number }) | null>({ kind: 'redispatch', runId }),\n );\n }\n\n /**\n * Republished on the control plane: a one-run target is checked against this tenant like\n * `retry`, a by-workflow one is read over this tenant's namespace only. A control plane too old to\n * know the verb fails it with an {@link UNSUPPORTED_RUN_REQUEST} error rather than a timeout.\n */\n republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult> {\n return this.requestNewVerb<RepublishLifecycleResult>({ kind: 'republishLifecycle', target });\n }\n\n /** Answered by the control plane's engine; same version-skew error as {@link republishLifecycle}. */\n workflowLifecycle(workflow: string): Promise<WorkflowLifecycleLinks> {\n return this.requestNewVerb<WorkflowLifecycleLinks>({ kind: 'workflowLifecycle', workflow });\n }\n\n /**\n * A verb with no fallback on an older control plane: its unsupported-request error, or the empty\n * `ok: true` reply the oldest responders send for an unknown verb, becomes a\n * {@link RunGatewayError} with code {@link UNSUPPORTED_RUN_REQUEST}.\n */\n private async requestNewVerb<T>(body: RunRequestKind): Promise<T> {\n const notSupported = () => unsupportedVerb(body.kind);\n if (this.knownUnsupported(body.kind)) throw notSupported();\n let data: T | undefined;\n try {\n data = await this.request<T | undefined>(body);\n } catch (err) {\n if (!isUnsupported(err)) throw err;\n }\n if (data !== undefined && data !== null) return data;\n this.unsupportedUntil.set(body.kind, Date.now() + this.capabilityTtlMs);\n throw notSupported();\n }\n\n /**\n * Signal the run of this tenant's namespace waiting on `token` (`engine.signal`). Resolves null\n * when no run of this namespace waits on it: the control plane does NOT buffer a tenant's signal\n * for a wait opened later (another namespace's run could open it). A control plane that predates\n * the verb fails it with an {@link UNSUPPORTED_RUN_REQUEST} error.\n */\n async signal(token: string, payload: unknown, opts?: SignalOptions): Promise<RunResult | null> {\n if (this.knownUnsupported('signal')) throw unsupportedVerb('signal');\n let data: RunResult | null | undefined;\n try {\n data = await this.request<RunResult | null | undefined>(\n opts === undefined\n ? { kind: 'signal', token, payload }\n : { kind: 'signal', token, payload, opts },\n );\n } catch (err) {\n if (!isUnsupported(err)) throw err;\n }\n // The oldest responders answer an unknown verb `ok: true` with no data at all; a real \"nobody\n // waits\" answer is an explicit null.\n if (data !== undefined) return data;\n this.unsupportedUntil.set('signal', Date.now() + this.capabilityTtlMs);\n throw unsupportedVerb('signal');\n }\n\n /**\n * `engine.signalWithStart` for this tenant: the control plane starts `start` in this tenant's\n * namespace unless its run exists, then signals it (buffered until the run waits, when the token\n * names the run id). See the responder for the authorization rule.\n */\n signalWithStart(\n start: Omit<StartRunMessage, 'tenant'> & { runId: string },\n signal: { token: string; payload?: unknown },\n ): Promise<{ runId: string; signalled: boolean }> {\n return this.requestNewVerb({ kind: 'signalWithStart', start, signal });\n }\n\n /**\n * Resume the runs of this tenant's namespace waiting on event `name` (`ctx.waitForEvent`).\n * Resolves how many it resumed. The tenant's own `onEvent` subscribers are started by the caller\n * (`DurableStartClient.publishEvent`), not here.\n */\n publishEvent(name: string, payload: unknown, opts?: { id?: string }): Promise<number> {\n return this.requestNewVerb({\n kind: 'publishEvent',\n name,\n payload,\n ...(opts?.id !== undefined ? { opts: { id: opts.id } } : {}),\n });\n }\n\n subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void {\n const unsubscribe = this.transport.onTenantEvent?.(this.tenant, (evt) => {\n if (evt.event.runId === runId) onEvent(evt.event);\n });\n return unsubscribe ?? (() => {});\n }\n}\n","import {\n type LifecycleKind,\n type RepublishLifecycleTarget,\n type RunDetail,\n type RunGateway,\n type RunReply,\n type RunRequest,\n type RunRequestKind,\n type RunWaiting,\n type StartOptions,\n type TenantVerifier,\n type VerifiedTenant,\n grantsClientTenant,\n lifecycleKindOf,\n verifyWireTenant,\n} from '@dudousxd/nestjs-durable-core';\n\n/**\n * The error `code` a responder replies with for a verb it does not know, so a newer tenant can tell\n * \"this control plane is older than me\" from a real failure and fall back at once. Earlier\n * responders reply `ok: true` with no `data` instead; `ProxyRunGateway` reads both.\n */\nexport const UNSUPPORTED_RUN_REQUEST = 'unsupported-request';\n\n/** The error `code` a responder replies with for a request it rejects as malformed or not allowed. */\nexport const BAD_RUN_REQUEST = 'bad-request';\n\n/** The most settled runs one tenant republish reads; a larger `limit` is lowered to it. */\nexport const TENANT_REPUBLISH_MAX_LIMIT = 1000;\n\nconst KNOWN_KINDS: ReadonlySet<string> = new Set<RunRequestKind['kind']>([\n 'getRunDetail',\n 'getFanMembers',\n 'getRun',\n 'listRuns',\n 'runFacets',\n 'runValueFacets',\n 'workerHealth',\n 'cancel',\n 'retry',\n 'continue',\n 'retryWithInput',\n 'redispatch',\n 'waitingFor',\n 'republishLifecycle',\n 'workflowLifecycle',\n 'signal',\n 'schedule',\n 'signalWithStart',\n 'publishEvent',\n]);\n\n/** A wire `since`/`until` (an ISO string after JSON) back to a `Date`. */\nfunction wireDate(value: Date | string | undefined): Date | undefined {\n if (value === undefined || value === null) return undefined;\n const date = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(date.getTime())) throw new Error(`invalid date ${String(value)}`);\n return date;\n}\n\n/** The narrow slice of `Transport` the responder needs — a tenant's read/control request in, a\n * correlated reply out. Both are OPTIONAL on the full `Transport` interface (only broker\n * transports carry the run-request/reply protocol); the caller capability-checks before wiring\n * this up (see `durable.module.ts`). */\nexport interface RunRequestTransport {\n onRunRequest(handler: (msg: RunRequest) => Promise<void>): void;\n publishRunReply(reply: RunReply): Promise<void>;\n}\n\n/** Options for {@link RunRequestResponder}. */\nexport interface RunRequestResponderOptions {\n /**\n * Verifies the signed token a tenant presents in the wire `tenant` field and DERIVES the real\n * tenant from it (see `hmacTenantVerifier`). Present: an invalid, tampered or absent token is\n * rejected with an `unauthorized` error reply and the wire claim is discarded in favour of the\n * verified tenant. Absent: the wire `tenant` is trusted verbatim (prefix/network isolation only).\n */\n verifyTenant?: TenantVerifier | undefined;\n /**\n * Warn at construction when no {@link verifyTenant} is set. Default `true`. `DurableModule` passes\n * `true` only for `topology: 'control-plane'`, so a standalone operator app that\n * never serves tenants boots silently.\n */\n warnWithoutVerifier?: boolean | undefined;\n}\n\n/**\n * Operator-side consumer of a tenant's {@link RunRequest}s: answers each one against a\n * `RunGateway`, enforcing the tenant boundary before touching the run. For every runId-bearing\n * verb it loads the run via `getRunDetail` FIRST and compares `run.namespace` to the requesting\n * `msg.tenant` — a mismatch short-circuits into a `cross-tenant` error reply WITHOUT calling the\n * verb, so a tenant can never read or act on another tenant's run. `listRuns` is scoped by\n * overwriting the query's `namespace` with the requester's tenant, ignoring whatever the client\n * sent. This is the security boundary of the tenant run gateway — do not weaken it.\n *\n * With {@link RunRequestResponderOptions.verifyTenant}, every request is authenticated FIRST: the\n * wire `tenant` is treated as a signed token, the real tenant is derived from it, and an invalid\n * token short-circuits into an `unauthorized` error reply before any run is touched. A verifier\n * that throws becomes an error reply too.\n */\n/**\n * `detail` with its links to other runs kept to `tenant`'s namespace: `awaitedBy` without the\n * waiting runs of other namespaces, and what was read of a `triggeredBy`, `waitsFor` or started\n * `lifecycleDeliveries` run (its status, namespace and trace id) only when that run is the tenant's.\n */\nfunction scopeRunLinks(detail: RunDetail, tenant: string): RunDetail {\n const own = (link: { namespace?: string | undefined }) => link.namespace === tenant;\n const bare = <T extends { status?: unknown; namespace?: string | undefined }>(link: T): T => {\n if (own(link)) return link;\n const { status: _status, namespace: _namespace, ...rest } = link;\n return rest as T;\n };\n const awaitedBy = detail.awaitedBy?.filter(own);\n const { awaitedBy: _awaitedBy, ...rest } = detail;\n const source = detail.triggeredBy;\n return {\n ...rest,\n ...(source\n ? { triggeredBy: own(source) ? source : { runId: source.runId, kind: source.kind } }\n : {}),\n ...(awaitedBy && awaitedBy.length > 0 ? { awaitedBy } : {}),\n ...(detail.waitsFor ? { waitsFor: detail.waitsFor.map(bare) } : {}),\n ...(detail.lifecycleDeliveries\n ? { lifecycleDeliveries: detail.lifecycleDeliveries.map(bare) }\n : {}),\n };\n}\n\nexport class RunRequestResponder {\n private readonly verifyTenant: TenantVerifier | undefined;\n\n constructor(\n private readonly transport: RunRequestTransport,\n private readonly gateway: RunGateway,\n options: RunRequestResponderOptions = {},\n ) {\n this.verifyTenant = options.verifyTenant;\n if (!this.verifyTenant && options.warnWithoutVerifier !== false) {\n // Loud on purpose: without a verifier the anti-IDOR checks below are bypassable by CLAIMING\n // another tenant's name in the wire `tenant` field. Prefix/network isolation may be an\n // acceptable posture, but it must be a chosen one.\n console.warn(\n '[nestjs-durable] run-request responder started WITHOUT a tenant verifier: the wire ' +\n '`tenant` claim is trusted verbatim (prefix/network isolation only). Any broker client ' +\n 'can act as any tenant. Configure `verifyTenant` (e.g. hmacTenantVerifier(secret)) and ' +\n 'signed tenant tokens unless your broker is fully isolated per tenant.',\n );\n }\n }\n\n /** Register the consumer on the transport. Each request is answered independently; a handler\n * failure never throws back into the transport (errors are captured into an error reply). */\n start(): void {\n this.transport.onRunRequest(async (msg) => {\n let reply: RunReply;\n try {\n reply = await this.handle(msg);\n } catch (err) {\n // Without a reply the tenant waits out its whole timeout for an answer that never comes.\n reply = {\n requestId: msg.requestId,\n result: {\n ok: false,\n error: { message: err instanceof Error ? err.message : String(err) },\n },\n };\n }\n await this.transport.publishRunReply(reply);\n });\n }\n\n private async handle(wire: RunRequest): Promise<RunReply> {\n const verified = await verifyWireTenant(wire.tenant, this.verifyTenant);\n const tenant = verified?.tenant ?? null;\n if (tenant === null) {\n return {\n requestId: wire.requestId,\n result: {\n ok: false,\n error: { message: 'invalid or unauthorized tenant token', code: 'unauthorized' },\n },\n };\n }\n // From here on `msg.tenant` is the VERIFIED tenant (the wire claim itself when no verifier is set).\n const msg: RunRequest = { ...wire, tenant };\n const { body } = msg;\n if (!KNOWN_KINDS.has(body.kind)) return unsupported(msg.requestId, String(body.kind));\n if (body.kind === 'listRuns') {\n // Force the namespace to the requester's tenant — the client-supplied value is discarded,\n // never merely validated, so a tenant can't widen its own query into another's namespace.\n const data = await this.gateway.listRuns({ ...body.query, namespace: msg.tenant });\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'runFacets') {\n // Same forced scope as `listRuns` above, for the same reason: the counts label a tenant's own\n // page, so they must be taken over exactly that tenant's runs and no one else's.\n const data = await this.gateway.runFacets({ ...body.query, namespace: msg.tenant });\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'runValueFacets') {\n // Same forced scope as `listRuns`/`runFacets`: the values fill a picker for the tenant's own\n // list, so enumerating them over anyone else's runs would both leak other tenants' tag and\n // attribute vocabulary and offer choices this tenant's list can never match.\n const data = await this.gateway.runValueFacets(\n body.axis,\n { ...body.query, namespace: msg.tenant },\n body.opts,\n );\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'workerHealth') {\n // Not runId-bearing, so it can't ride the getRunDetail namespace check below. Scope by the\n // group-name convention instead: a tenant's queues are suffixed `<name>@<tenant>`, so keep only\n // groups ending in the requester's `@<tenant>` — the operator's own bare groups and every other\n // tenant's are dropped, so a tenant's Workers panel only ever sees ITS OWN queues.\n const all = await this.gateway.workerHealth();\n const data = all.filter((h) => h.group.endsWith(`@${msg.tenant}`));\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'workflowLifecycle') {\n if (!this.gateway.workflowLifecycle) return unsupported(msg.requestId, body.kind);\n // Scoped to the requester: subscribers another tenant registers or announces stay unseen.\n const data = await this.gateway.workflowLifecycle(body.workflow, { namespace: msg.tenant });\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'republishLifecycle' && !('runId' in body.target)) {\n // Not runId-bearing: forced onto the requester's namespace, like `listRuns`, so a tenant can\n // only republish its own runs whatever namespace it sent.\n if (!this.gateway.republishLifecycle) return unsupported(msg.requestId, body.kind);\n const { since, until, limit, ...rest } = body.target as Extract<\n RepublishLifecycleTarget,\n { workflow: string }\n > & { since?: Date | string; until?: Date | string };\n if (\n limit !== undefined &&\n (typeof limit !== 'number' || !Number.isSafeInteger(limit) || limit < 1)\n ) {\n return badRequest(\n msg.requestId,\n `limit must be a positive integer, got ${JSON.stringify(limit)}`,\n );\n }\n const refused = await this.refuseSubscriber(\n rest.workflow,\n rest.kind,\n rest.subscriber,\n msg.tenant,\n );\n if (refused) return badRequest(msg.requestId, refused);\n const target: RepublishLifecycleTarget = {\n ...rest,\n namespace: msg.tenant,\n limit: Math.min(limit ?? TENANT_REPUBLISH_MAX_LIMIT, TENANT_REPUBLISH_MAX_LIMIT),\n ...(since !== undefined ? { since: wireDate(since) } : {}),\n ...(until !== undefined ? { until: wireDate(until) } : {}),\n };\n try {\n const data = await this.gateway.republishLifecycle(target);\n return { requestId: msg.requestId, result: { ok: true, data } };\n } catch (err) {\n return {\n requestId: msg.requestId,\n result: {\n ok: false,\n error: { message: err instanceof Error ? err.message : String(err) },\n },\n };\n }\n }\n\n if (body.kind === 'waitingFor') {\n // Bulk, like `listRuns` — but unlike `listRuns` (which forces the query's namespace and so\n // scopes itself) the caller supplies arbitrary ids, which could probe another tenant's runs. The\n // gateway's own `waitingFor` has no namespace to filter by, so verify ownership per MATCHED entry\n // (bounded by how many of the requested ids are actually waiting, never by `runIds.length`) the\n // same way every other runId-bearing verb does below: `getRunDetail` + a `namespace` check.\n const all = await this.gateway.waitingFor(body.runIds);\n const owned = await Promise.all(\n Object.entries(all).map(async ([runId, waiting]) => {\n const owner = this.gateway.getRun\n ? await this.gateway.getRun(runId)\n : (await this.gateway.getRunDetail(runId))?.run;\n return owner && owner.namespace === msg.tenant ? ([runId, waiting] as const) : undefined;\n }),\n );\n const data: Record<string, RunWaiting> = {};\n for (const entry of owned) {\n if (entry) data[entry[0]] = entry[1];\n }\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'schedule') {\n // Not runId-bearing: the schedule's own namespace is checked against the requester's, so a\n // requester can only pause, resume or trigger the schedules of its own namespace.\n const { getSchedule, scheduleAction } = this.gateway;\n if (!getSchedule || !scheduleAction) return unsupported(msg.requestId, body.kind);\n if (body.action !== 'pause' && body.action !== 'resume' && body.action !== 'trigger') {\n return badRequest(msg.requestId, `unknown schedule action ${JSON.stringify(body.action)}`);\n }\n const schedule = await getSchedule.call(this.gateway, body.id);\n if (!schedule || schedule.namespace !== msg.tenant) {\n // Another namespace's schedule reads as missing: its existence is not the requester's to learn.\n return {\n requestId: msg.requestId,\n result: {\n ok: false,\n error: { message: `schedule \"${body.id}\" not found`, code: 'not-found' },\n },\n };\n }\n return this.answer(msg.requestId, () =>\n scheduleAction.call(this.gateway, body.id, body.action),\n );\n }\n\n if (body.kind === 'signal') {\n // A token names no run, so the run waiting on it is looked up and checked like a runId-bearing\n // verb. A token no run waits on yet is answered `null` and NOT buffered: buffering would let a\n // requester plant a payload for a wait another namespace opens later.\n const { signal, signalWaiter } = this.gateway;\n if (!signal || !signalWaiter) return unsupported(msg.requestId, body.kind);\n const waiterRunId = await signalWaiter.call(this.gateway, body.token);\n const waiter = waiterRunId ? await this.runOf(waiterRunId) : null;\n if (!waiter || waiter.namespace !== msg.tenant) {\n return { requestId: msg.requestId, result: { ok: true, data: null } };\n }\n return this.answer(msg.requestId, () =>\n body.opts === undefined\n ? signal.call(this.gateway, body.token, body.payload)\n : signal.call(this.gateway, body.token, body.payload, body.opts),\n );\n }\n\n if (body.kind === 'signalWithStart') {\n return this.signalWithStart(msg.requestId, body, msg.tenant, verified);\n }\n\n if (body.kind === 'publishEvent') {\n // Scoped to the requester: only its own namespace's waiting runs are resumed, and nothing is\n // buffered (see `WorkflowEngine.publishEventForTenant`).\n const { publishEventForTenant } = this.gateway;\n if (!publishEventForTenant) return unsupported(msg.requestId, body.kind);\n if (typeof body.name !== 'string' || body.name === '') {\n return badRequest(msg.requestId, 'publishEvent needs an event name');\n }\n return this.answer(msg.requestId, () =>\n publishEventForTenant.call(this.gateway, body.name, body.payload, msg.tenant),\n );\n }\n\n if (body.kind === 'republishLifecycle' && !this.gateway.republishLifecycle) {\n return unsupported(msg.requestId, body.kind);\n }\n\n // Every remaining verb is runId-bearing. Load the run FIRST — before calling the verb — so a\n // cross-tenant request never reaches the gateway's mutating methods (cancel/retry/continue/redispatch).\n // Only `getRunDetail` needs the timeline; every other verb checks ownership on the run alone.\n const runId = runIdOf(body);\n const detail =\n body.kind === 'getRunDetail' || !this.gateway.getRun\n ? await this.gateway.getRunDetail(\n runId,\n body.kind === 'getRunDetail' ? body.options : undefined,\n )\n : undefined;\n const run = detail !== undefined ? (detail?.run ?? null) : await this.gateway.getRun?.(runId);\n if (run && run.namespace !== msg.tenant) {\n return {\n requestId: msg.requestId,\n result: {\n ok: false,\n error: { message: 'run belongs to another tenant', code: 'cross-tenant' },\n },\n };\n }\n\n if (body.kind === 'getRunDetail') {\n const data = detail ? await this.scopeLifecycle(detail, msg.tenant) : detail;\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'getRun') {\n return { requestId: msg.requestId, result: { ok: true, data: run ?? null } };\n }\n\n if (body.kind === 'getFanMembers') {\n const data = run\n ? ((await this.gateway.getFanMembers?.(body.runId, body.group, body.query)) ?? null)\n : null;\n return { requestId: msg.requestId, result: { ok: true, data } };\n }\n\n if (body.kind === 'republishLifecycle' && 'runId' in body.target && run) {\n const kind = lifecycleKindOf(run.status);\n const refused = kind\n ? await this.refuseSubscriber(run.workflow, kind, body.target.subscriber, msg.tenant)\n : undefined;\n if (refused) return badRequest(msg.requestId, refused);\n }\n\n try {\n const data = await this.callVerb(body);\n return { requestId: msg.requestId, result: { ok: true, data } };\n } catch (err) {\n return {\n requestId: msg.requestId,\n result: { ok: false, error: { message: err instanceof Error ? err.message : String(err) } },\n };\n }\n }\n\n /**\n * A tenant's `signalWithStart`: the run it names must be the requester's when it exists, and so\n * must a run already waiting on the token; anything else is refused `cross-tenant` before the\n * gateway is called. The run is started in the requester's namespace (a customer tenant it claims\n * is kept only when its verified token grants it, as for a start-run).\n */\n private async signalWithStart(\n requestId: string,\n body: Extract<RunRequestKind, { kind: 'signalWithStart' }>,\n tenant: string,\n verified: VerifiedTenant | null,\n ): Promise<RunReply> {\n const { signalWithStartForTenant, signalWaiter } = this.gateway;\n if (!signalWithStartForTenant) return unsupported(requestId, body.kind);\n const start = body.start;\n if (\n !start ||\n typeof start.runId !== 'string' ||\n start.runId === '' ||\n typeof start.workflow !== 'string' ||\n start.workflow === '' ||\n typeof body.signal?.token !== 'string' ||\n body.signal.token === ''\n ) {\n return badRequest(requestId, 'signalWithStart needs a workflow, a run id and a signal token');\n }\n const crossTenant: RunReply = {\n requestId,\n result: {\n ok: false,\n error: { message: 'run belongs to another tenant', code: 'cross-tenant' },\n },\n };\n const existing = await this.runOf(start.runId);\n if (existing && existing.namespace !== tenant) return crossTenant;\n const waiterRunId = signalWaiter\n ? await signalWaiter.call(this.gateway, body.signal.token)\n : null;\n const waiter = waiterRunId ? await this.runOf(waiterRunId) : null;\n if (waiter && waiter.namespace !== tenant) return crossTenant;\n const claim: Pick<StartOptions, 'tenantId' | 'tenantKind'> =\n start.tenantId !== undefined\n ? grantsClientTenant(verified, start.tenantId)\n ? {\n tenantId: start.tenantId,\n ...(start.tenantKind !== undefined ? { tenantKind: start.tenantKind } : {}),\n }\n : { tenantId: null }\n : {};\n return this.answer(requestId, () =>\n signalWithStartForTenant.call(this.gateway, { ...start, tenant }, tenant, claim, {\n token: body.signal.token,\n payload: body.signal.payload,\n }),\n );\n }\n\n /** The run alone (`getRun`, else from its detail), or null when it does not exist. */\n private async runOf(runId: string) {\n return this.gateway.getRun\n ? this.gateway.getRun(runId)\n : ((await this.gateway.getRunDetail(runId))?.run ?? null);\n }\n\n /** `call`'s result as an `ok` reply, or its rejection as an error reply. */\n private async answer(requestId: string, call: () => Promise<unknown>): Promise<RunReply> {\n try {\n return { requestId, result: { ok: true, data: await call() } };\n } catch (err) {\n return {\n requestId,\n result: { ok: false, error: { message: err instanceof Error ? err.message : String(err) } },\n };\n }\n }\n\n /**\n * `detail` scoped to `tenant` (see {@link scopeRunLinks}), with its lifecycle links\n * (`workflowLifecycle`, `lifecycleSubscribers`) narrowed to the subscriptions of `tenant`'s\n * namespace, as the `workflowLifecycle` verb answers them.\n */\n private async scopeLifecycle(input: RunDetail, tenant: string): Promise<RunDetail> {\n const detail = scopeRunLinks(input, tenant);\n if (detail.workflowLifecycle === undefined && detail.lifecycleSubscribers === undefined) {\n return detail;\n }\n const { workflowLifecycle: _links, lifecycleSubscribers: _subscribers, ...rest } = detail;\n const links = await this.gateway.workflowLifecycle?.(detail.run.workflow, {\n namespace: tenant,\n });\n if (!links) return rest;\n const kind = lifecycleKindOf(detail.run.status);\n const subscribers = kind\n ? [...new Set(links.startsOnSettle.filter((l) => l.kind === kind).map((l) => l.workflow))]\n : [];\n const linked = links.startsOnSettle.length > 0 || links.startedBy.length > 0;\n return {\n ...rest,\n ...(subscribers.length > 0 ? { lifecycleSubscribers: subscribers } : {}),\n ...(linked ? { workflowLifecycle: links } : {}),\n };\n }\n\n /**\n * Why a tenant republish naming `subscriber` is refused, or undefined when it may go ahead: the\n * subscriber must be owed the event of `workflow` settling (as `kind`, when given) by a run of\n * the tenant's namespace (the gateway's `lifecycleSubscribers`, else the tenant's\n * `workflowLifecycle` links), so a tenant cannot have the event owed to an arbitrary name. Without\n * `subscriber` there is nothing to check.\n */\n private async refuseSubscriber(\n workflow: string,\n kind: LifecycleKind | undefined,\n subscriber: string | undefined,\n tenant: string,\n ): Promise<string | undefined> {\n if (subscriber === undefined) return undefined;\n const kinds: LifecycleKind[] = kind ? [kind] : ['completed', 'failed'];\n let subscribes = false;\n if (this.gateway.lifecycleSubscribers) {\n for (const k of kinds) {\n const subscribers = await this.gateway.lifecycleSubscribers(workflow, k, tenant);\n subscribes ||= subscribers.includes(subscriber);\n }\n } else {\n const links = await this.gateway.workflowLifecycle?.(workflow, { namespace: tenant });\n subscribes =\n links?.startsOnSettle.some(\n (link) => link.workflow === subscriber && kinds.includes(link.kind),\n ) ?? false;\n }\n if (subscribes) return undefined;\n const events = kind\n ? `run.${kind}:${workflow}`\n : `run.completed:${workflow} or run.failed:${workflow}`;\n return `subscriber ${subscriber} does not subscribe to ${events} in namespace ${tenant}`;\n }\n\n private callVerb(\n body: Exclude<\n RunRequest['body'],\n | { kind: 'listRuns' }\n | { kind: 'runFacets' }\n | { kind: 'runValueFacets' }\n | { kind: 'getRunDetail' }\n | { kind: 'getFanMembers' }\n | { kind: 'getRun' }\n | { kind: 'workerHealth' }\n | { kind: 'waitingFor' }\n | { kind: 'workflowLifecycle' }\n | { kind: 'signal' }\n | { kind: 'schedule' }\n | { kind: 'signalWithStart' }\n | { kind: 'publishEvent' }\n >,\n ): Promise<unknown> {\n switch (body.kind) {\n case 'republishLifecycle':\n return (\n this.gateway.republishLifecycle?.(body.target) ??\n Promise.reject(new Error('republishLifecycle is not supported'))\n );\n case 'cancel':\n return this.gateway.cancel(body.runId, body.opts);\n case 'retry':\n return this.gateway.retry(body.runId);\n case 'continue':\n return this.gateway.continue(body.runId);\n case 'retryWithInput':\n return this.gateway.retryWithInput(body.runId, body.input);\n case 'redispatch':\n return this.gateway.redispatchPending(body.runId);\n }\n }\n}\n\n/** The run a runId-bearing request acts on; a one-run republish names it in its target. */\nfunction runIdOf(\n body: Exclude<\n RunRequestKind,\n | { kind: 'listRuns' }\n | { kind: 'runFacets' }\n | { kind: 'runValueFacets' }\n | { kind: 'workerHealth' }\n | { kind: 'waitingFor' }\n | { kind: 'workflowLifecycle' }\n | { kind: 'signal' }\n | { kind: 'schedule' }\n | { kind: 'signalWithStart' }\n | { kind: 'publishEvent' }\n >,\n): string {\n if (body.kind !== 'republishLifecycle') return body.runId;\n return 'runId' in body.target ? body.target.runId : '';\n}\n\n/** The reply to a request this responder rejects (see {@link BAD_RUN_REQUEST}). */\nfunction badRequest(requestId: string, message: string): RunReply {\n return { requestId, result: { ok: false, error: { message, code: BAD_RUN_REQUEST } } };\n}\n\n/** The reply to a verb this responder knows but its gateway cannot answer. */\nfunction unsupported(requestId: string, kind: string): RunReply {\n return {\n requestId,\n result: {\n ok: false,\n error: {\n message: `the control plane does not support the ${kind} run request`,\n code: UNSUPPORTED_RUN_REQUEST,\n },\n },\n };\n}\n","import {\n DURABLE_OPTIONS_CANONICAL,\n STATE_STORE_CANONICAL,\n type StateStore,\n TERMINAL_RUN_STATUSES,\n parseDuration,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n Inject,\n Injectable,\n type OnApplicationBootstrap,\n type OnModuleDestroy,\n Optional,\n} from '@nestjs/common';\nimport type { DurableModuleOptions, DurableRetentionOptions } from './durable.module';\nimport { isDrivingOperator } from './role';\nimport { settleWithin } from './settle-within';\nimport { SweepLeases } from './sweep-leases';\n\nconst DEFAULT_SWEEP_INTERVAL_MS = 60_000;\nconst DEFAULT_BATCH_SIZE = 1_000;\n// Backstop so a single sweep can never loop unbounded. At the default batch size this still drains up\n// to 100k runs per policy per sweep before yielding the event loop to the next tick.\nconst MAX_BATCHES_PER_POLICY = 100;\n\n/**\n * Reject a retention config that would silently misbehave: every policy must set at least one bound,\n * list only terminal statuses (pruning a live status would race the engine), and the status sets must\n * be disjoint (so \"most recent N\" is unambiguous per status group). Throws on the first violation.\n */\nexport function validateRetention(retention: DurableRetentionOptions): void {\n // Disjointness is per SCOPE: two policies over the same runs must not both claim a status (\"keep 100\"\n // vs \"keep 10\" of the same set is ambiguous), but `{ namespace: 'a' }` and `{ namespace: 'b' }` — or a\n // tenant-scoped policy next to an unscoped default — each rule their own selection.\n const seen = new Set<string>();\n for (const policy of retention.policies) {\n const scopeKey = policy.scope ? stableKey(policy.scope) : '';\n if (policy.statuses.length === 0) {\n throw new Error('durable retention: each policy must list at least one status');\n }\n if (policy.maxAge == null && policy.maxCount == null) {\n throw new Error('durable retention: each policy must set maxAge and/or maxCount');\n }\n // Fail fast on a typo'd duration string ('7days', '1 month') at boot rather than silently never pruning.\n if (policy.maxAge != null) parseDuration(policy.maxAge);\n for (const status of policy.statuses) {\n if (!TERMINAL_RUN_STATUSES.includes(status)) {\n throw new Error(\n `durable retention: status \"${status}\" is not terminal; only ${TERMINAL_RUN_STATUSES.join(\n ', ',\n )} can be pruned`,\n );\n }\n const key = `${scopeKey}|${status}`;\n if (seen.has(key)) {\n throw new Error(\n `durable retention: status \"${status}\" appears in more than one policy with the same scope; status sets must be disjoint per scope`,\n );\n }\n seen.add(key);\n }\n }\n}\n\n/** A key-order-independent JSON key for a scope, so `{a,b}` and `{b,a}` compare equal. */\nfunction stableKey(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableKey).join(',')}]`;\n if (value && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => a.localeCompare(b));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableKey(v)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n}\n\n/**\n * Hard-prunes terminal run history on an interval per the configured `retention` policies, keeping the\n * `durable_workflow_runs` table (and its children) bounded so the poller's per-tick scans stay cheap.\n *\n * Worker-only (a dashboard-only instance never prunes), separate from the 1s timer poll (defaults to a\n * 60s sweep), and self-draining: each policy is swept in `batchSize` chunks until a batch comes back\n * short. No-ops with a warning if the store adapter doesn't implement `pruneTerminalRuns`.\n */\n@Injectable()\nexport class RetentionPoller implements OnApplicationBootstrap, OnModuleDestroy {\n private timer?: ReturnType<typeof setInterval>;\n private sweeping = false;\n private stopping = false;\n /** The sweep in flight, so shutdown can wait for it before the store closes. */\n private current: Promise<void> | undefined;\n\n constructor(\n @Inject(STATE_STORE_CANONICAL) private readonly store: StateStore | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n // One pod prunes when the app has `LocksModule` from `@nestjs/locks` (detected, see SweepLeases).\n @Optional() private readonly leases: SweepLeases = new SweepLeases(),\n ) {}\n\n /** Non-null once past the `isDrivingOperator` guard (which requires `options.store` to be set). */\n private requireStore(): StateStore {\n if (!this.store) {\n throw new Error(\n 'unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set',\n );\n }\n return this.store;\n }\n\n async onApplicationBootstrap(): Promise<void> {\n // Only a DRIVING operator prunes — a dashboard/dispatch-only instance, or a thin worker with no\n // `store` at all, must not delete history.\n if (!isDrivingOperator(this.options)) return;\n const retention = this.options.retention;\n if (!retention || retention.policies.length === 0) return;\n validateRetention(retention);\n if (typeof this.requireStore().pruneTerminalRuns !== 'function') {\n console.warn(\n '[nestjs-durable] `retention` is configured but the store adapter does not implement pruneTerminalRuns; retention is disabled.',\n );\n return;\n }\n // Started, not awaited: a first prune over a large history must not hold the host's boot (its\n // HTTP server listens only after every `onApplicationBootstrap`). Shutdown waits for it.\n void this.sweep();\n const intervalMs =\n retention.sweepInterval != null\n ? parseDuration(retention.sweepInterval)\n : DEFAULT_SWEEP_INTERVAL_MS;\n if (intervalMs > 0) {\n this.timer = setInterval(() => void this.sweep(), intervalMs);\n this.timer.unref?.();\n }\n }\n\n /** Stop sweeping and wait for the sweep in flight (bounded by `shutdownTimeoutMs`, default 10s),\n * so no prune is still pending when the host closes its connection pool. This wait runs concurrently\n * with the timer poller's and is NOT deducted from the engine's drain budget (the retention poller\n * holds no engine), so a slow prune can add up to one more `shutdownTimeoutMs` before the drain. */\n async onModuleDestroy(): Promise<void> {\n if (this.timer) clearInterval(this.timer);\n this.stopping = true;\n if (!this.current) return;\n const budget = this.options.shutdownTimeoutMs ?? 10_000;\n if (await settleWithin(this.current, budget)) {\n console.warn(\n `[nestjs-durable] retention sweep still running after ${budget}ms at shutdown; continuing`,\n );\n }\n }\n\n /**\n * Prune one round.\n *\n * Never rejects, for the same reason {@link TimerPoller.poll} does not: it is fired as `void` on\n * boot and on the interval, so a rejection would be an unhandled one, which is fatal.\n * Pruning history is the least urgent thing this package does — a `pruneTerminalRuns` that fails\n * on a locked table must cost this sweep and nothing more.\n */\n private sweep(): Promise<void> {\n if (this.sweeping) return this.current ?? Promise.resolve(); // never overlap two sweeps\n const run = this.sweepOnce().finally(() => {\n if (this.current === run) this.current = undefined;\n });\n this.current = run;\n return run;\n }\n\n private async sweepOnce(): Promise<void> {\n if (this.stopping) return;\n const retention = this.options.retention;\n const store = this.requireStore();\n const prune = store.pruneTerminalRuns;\n if (!retention || typeof prune !== 'function') return;\n this.sweeping = true;\n try {\n await this.leases.run('retention', () => this.prune(retention, store, prune));\n } catch (error) {\n console.error('[nestjs-durable] retention sweep failed; retrying next interval:', error);\n } finally {\n this.sweeping = false;\n }\n }\n\n private async prune(\n retention: DurableRetentionOptions,\n store: StateStore,\n prune: NonNullable<StateStore['pruneTerminalRuns']>,\n ): Promise<void> {\n const batchSize = retention.batchSize ?? DEFAULT_BATCH_SIZE;\n const now = Date.now();\n for (const policy of retention.policies) {\n for (let batch = 0; batch < MAX_BATCHES_PER_POLICY; batch++) {\n if (this.stopping) return;\n const deleted = await prune.call(store, policy, now, batchSize);\n if (deleted < batchSize) break; // backlog drained for this policy\n }\n }\n }\n}\n","/** Resolve when `p` settles or after `timeoutMs`, whichever comes first; never rejects. Returns\n * true when the wait timed out with `p` still pending. */\nexport async function settleWithin(p: Promise<unknown>, timeoutMs: number): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(() => {\n timedOut = true;\n resolve();\n }, timeoutMs);\n timer.unref?.();\n });\n try {\n await Promise.race([p.then(undefined, () => undefined), timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n return timedOut;\n}\n","import { DURABLE_OPTIONS_CANONICAL } from '@dudousxd/nestjs-durable-core';\nimport { Inject, Injectable, Logger, type OnModuleInit, Optional } from '@nestjs/common';\nimport { ModuleRef } from '@nestjs/core';\nimport type { DurableModuleOptions } from './durable.module';\n\n/**\n * The slice of `@nestjs/locks` used here, structurally: the package is an OPTIONAL peer, so nothing\n * from it is imported statically (the main entry must load without it).\n */\ninterface HeldLock {\n readonly held: boolean;\n}\ninterface LocksLike {\n acquire(\n key: string,\n options?: { ttl?: number | string; wait?: number | string },\n ): Promise<HeldLock | null>;\n}\n\n/** The fleet-wide sweeps gated by a lease when `@nestjs/locks` is present. */\nexport type FleetSweep =\n | 'retention'\n | 'stalled-pager'\n | 'buffered-signals'\n | 'signal-ids'\n | 'announced-schedules';\n\n/**\n * Runs durable's FLEET-WIDE sweeps (retention pruning, the stalled-run pager, the orphaned\n * buffered-signal cleanup, the expired signal dedupe ids) on one pod at a time when the app imports\n * `LocksModule` from `@nestjs/locks`. Detected, never configured: with no `Locks` provider in the app, every sweep runs\n * on every driving pod exactly as before.\n *\n * Each sweep holds its own lease, `durable:<sweep>` (suffixed `:<namespace>` on a namespaced engine).\n * The first pod to tick takes it and KEEPS it (the official `Lock` renews itself every `ttl / 3`);\n * the others skip that sweep on every tick until the holder stops renewing (crash, shutdown, a lost\n * lease), and the next tick elsewhere takes over. A lease held across ticks, rather than a lock per\n * tick, is what keeps the pager from paging once per pod: pods tick at different moments, so a lock\n * released after each tick would be won by each pod in turn.\n *\n * The leases go back at shutdown with every other lock (`Locks.beforeApplicationShutdown`, after\n * the pollers have waited for their sweep in `onModuleDestroy`).\n *\n * Work-claiming sweeps (pending runs, recovery, timers, timeouts, schedules, lifecycle events) stay\n * on every pod: they already arbitrate per run with leases / compare-and-set.\n */\n@Injectable()\nexport class SweepLeases implements OnModuleInit {\n private readonly logger = new Logger('nestjs-durable');\n /** Set by {@link onModuleInit} (before any poller's bootstrap). `null`: no `@nestjs/locks`. */\n private locks: LocksLike | null = null;\n private readonly leases = new Map<FleetSweep, HeldLock>();\n\n constructor(\n @Optional() private readonly moduleRef?: ModuleRef,\n @Optional()\n @Inject(DURABLE_OPTIONS_CANONICAL)\n private readonly options?: DurableModuleOptions,\n ) {}\n\n /**\n * Run `fn` if this pod holds (or now takes) the lease of `sweep`; otherwise skip it and resolve\n * `undefined`. Without `@nestjs/locks` it always runs `fn`.\n */\n async run<T>(sweep: FleetSweep, fn: () => Promise<T>): Promise<T | undefined> {\n const locks = this.locks;\n // No `@nestjs/locks`: straight through, with no extra await (today's timing, unchanged).\n if (!locks) return fn();\n if (!(await this.holds(locks, sweep))) return undefined;\n return fn();\n }\n\n private async holds(locks: LocksLike, sweep: FleetSweep): Promise<boolean> {\n if (this.leases.get(sweep)?.held) return true;\n this.leases.delete(sweep);\n let lock: HeldLock | null;\n try {\n lock = await locks.acquire(this.key(sweep));\n } catch (error) {\n // A lock store that fails or times out costs this tick of this sweep, nothing more.\n this.logger.warn(\n `could not take the ${sweep} sweep lease; skipping this tick: ${String(error)}`,\n );\n return false;\n }\n if (!lock) return false;\n this.leases.set(sweep, lock);\n return true;\n }\n\n private key(sweep: FleetSweep): string {\n const ns = this.options?.namespace;\n return ns ? `durable:${sweep}:${ns}` : `durable:${sweep}`;\n }\n\n /** Detects `Locks` once, and logs which mode is active. Nest awaits it before any bootstrap hook. */\n async onModuleInit(): Promise<void> {\n this.locks = await this.detect();\n this.logger.log(\n this.locks\n ? 'fleet-wide sweeps (retention, stalled-run pager, buffered-signal cleanup, expired signal-id cleanup) run on one pod at a time, through @nestjs/locks'\n : 'fleet-wide sweeps run on every driving pod (import LocksModule from @nestjs/locks to run them on one)',\n );\n }\n\n private async detect(): Promise<LocksLike | null> {\n let locks: LocksLike | null = null;\n if (this.moduleRef) {\n try {\n // Indirect specifier: the optional peer must not be resolved statically by the compiler or\n // the bundler. A missing package rejects and lands in the catch.\n const specifier = '@nestjs/locks';\n const mod = (await import(specifier)) as {\n Locks?: abstract new (...args: never[]) => unknown;\n };\n if (mod.Locks) {\n locks = this.moduleRef.get(mod.Locks, { strict: false }) as unknown as LocksLike;\n }\n } catch {\n locks = null;\n }\n }\n return locks;\n }\n}\n","import {\n type DurableTopology,\n type EngineEvent,\n type FanPage,\n type FanPageQuery,\n type GroupHealth,\n LIFECYCLE_REGISTRY_WORKFLOW,\n type LifecycleDelivery,\n type LifecycleKind,\n type RepublishLifecycleResult,\n type RepublishLifecycleTarget,\n type RunDetail,\n type RunDetailOptions,\n type RunFacetQuery,\n type RunFacetRow,\n type RunGateway,\n type RunListItem,\n type RunQuery,\n type RunResult,\n type RunValueAxis,\n type RunValueFacetOptions,\n type RunValueFacetRow,\n type RunWaitLink,\n type RunWaiting,\n STATE_STORE_CANONICAL,\n SUMMARY_CHILD_LIMIT,\n type ScheduleAction,\n type ScheduleDescription,\n type ScheduleListQuery,\n type SignalOptions,\n type StartOptions,\n type StartRunMessage,\n type StateStore,\n WorkflowEngine,\n type WorkflowLifecycleLinks,\n type WorkflowRun,\n aggregatesCheckpoints,\n childIdsOf,\n etagMatches,\n extendEtag,\n fanPageEtag,\n indexWaitersByRun,\n lifecycleDeliveriesOf,\n lifecycleKindOf,\n lifecycleSourceOf,\n lifecycleTraceparentOf,\n listSignalWaitersOfRuns,\n mergeRunFacetRows,\n pageFan,\n pageFanFromStore,\n readRunsByIds,\n resolveRunWaiting,\n runDetailEtag,\n runWaitPrefix,\n runWaitTargetOf,\n summarizeRunFromStore,\n summarizeTimeline,\n traceIdOfTraceparent,\n} from '@dudousxd/nestjs-durable-core';\nimport { Inject, Injectable } from '@nestjs/common';\n\n/**\n * What a run detail reads from outside the run row and its checkpoints, folded into its ETag: the\n * subscribers and where each delivery stands, and the status of every run its links point at.\n * Undefined when it has none of them.\n */\nfunction detailExtras(\n links: Pick<\n RunDetail,\n 'lifecycleSubscribers' | 'lifecycleDeliveries' | 'waitsFor' | 'awaitedBy' | 'triggeredBy'\n >,\n): unknown {\n const { lifecycleSubscribers, lifecycleDeliveries, waitsFor, awaitedBy, triggeredBy } = links;\n if (!lifecycleSubscribers && !lifecycleDeliveries && !waitsFor && !awaitedBy && !triggeredBy) {\n return undefined;\n }\n return { lifecycleSubscribers, lifecycleDeliveries, waitsFor, awaitedBy, triggeredBy };\n}\n\n/**\n * `query` without the lifecycle registry's runs, engine bookkeeping that is not a run anyone\n * started, unless the query names that workflow itself.\n */\nfunction withoutRegistry<Q extends RunFacetQuery>(query: Q): Q {\n if (\n query.workflow === LIFECYCLE_REGISTRY_WORKFLOW ||\n query.workflows?.includes(LIFECYCLE_REGISTRY_WORKFLOW)\n ) {\n return query;\n }\n return {\n ...query,\n excludeWorkflows: [...(query.excludeWorkflows ?? []), LIFECYCLE_REGISTRY_WORKFLOW],\n };\n}\n\n/**\n * Store-backed `RunGateway` — the operator-side implementation, bound to {@link RunGateway} on\n * worker/drive instances. Reuses `DashboardService`'s six read/control method bodies verbatim\n * (`dashboard.service.ts:76-172`), so a consumer that only needs the bounded `RunGateway` surface\n * (the `RunRequestResponder`, a thin controller) doesn't have to depend on the dashboard package.\n */\n@Injectable()\nexport class StoreRunGateway implements RunGateway {\n constructor(\n @Inject(STATE_STORE_CANONICAL) private readonly store: StateStore,\n private readonly engine: WorkflowEngine,\n ) {}\n\n topology(): DurableTopology {\n return { role: 'control-plane' };\n }\n\n /**\n * Narrow `query` to the caller's tenant (the tenancy matching rule; see `DurableModule`'s\n * `tenancy`). A no-op with tenancy off, or for a caller outside any request (`system`).\n */\n private scoped<Q extends RunQuery | RunFacetQuery>(query: Q): Q {\n return typeof this.engine?.scopeRunQuery === 'function'\n ? (this.engine.scopeRunQuery(query as RunQuery) as Q)\n : query;\n }\n\n /** The run, or null when it is missing OR belongs to a tenant the caller may not see (404). */\n private async visibleRun(runId: string): Promise<WorkflowRun | null> {\n const run = await this.store.getRun(runId);\n if (!run) return null;\n const { tenantIds } = this.scoped({} as RunQuery);\n return !tenantIds || tenantIds.includes(run.tenantId ?? null) ? run : null;\n }\n\n async getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null> {\n const run = await this.visibleRun(runId);\n if (!run) return null;\n const links = await this.lifecycleLinks(run);\n const over = options?.summarizeFansOver;\n if (over === undefined) {\n const [timeline, children] = await Promise.all([\n this.store.listCheckpoints(runId),\n this.engine.getRunChildren(runId), // canonical parent→children edge (shared with cancel cascade)\n ]);\n return { run, timeline, children, ...links };\n }\n // Summarized: the children come from the checkpoints, rather than from a read of every\n // child-edge checkpoint plus the waiters. A child whose waiter is written but whose placeholder\n // checkpoint is not yet is missing for that one read; the next one lists it.\n if (aggregatesCheckpoints(this.store)) {\n // The buckets are read before any row, so a write landing mid-read leaves the ETag older than\n // the body: the next poll misses and re-reads, rather than pinning a stale body.\n const stats = await this.store.checkpointStats(runId);\n const etag = extendEtag(runDetailEtag(run, stats, over), detailExtras(links));\n if (etagMatches(options?.ifNoneMatch, etag)) {\n return { run, timeline: [], children: [], notModified: true, etag };\n }\n return {\n run,\n ...(await summarizeRunFromStore(this.store, runId, over, stats)),\n etag,\n ...links,\n };\n }\n const full = await this.store.listCheckpoints(runId);\n const { timeline, fans } = summarizeTimeline(full, over);\n const ids = childIdsOf(full);\n return {\n run,\n timeline,\n children: ids.slice(0, SUMMARY_CHILD_LIMIT),\n fans,\n childCount: ids.length,\n ...links,\n };\n }\n\n /**\n * What a run detail reads beyond the run row and its checkpoints: what this run's settling\n * started, the subscribers its lifecycle event goes to (of its namespace) and where it stands for\n * each, what started it, its workflow's lifecycle links, and the `ctx.waitForRun` waits on either\n * side of it with the other run's status. A few reads per detail: the run's own waiters while it\n * is suspended, the waiters on it (one prefix read), and one batched read of every linked run.\n */\n private async lifecycleLinks(\n run: WorkflowRun,\n ): Promise<\n Pick<\n RunDetail,\n | 'triggered'\n | 'triggeredBy'\n | 'lifecycleSubscribers'\n | 'workflowLifecycle'\n | 'lifecycleDeliveries'\n | 'waitsFor'\n | 'awaitedBy'\n >\n > {\n const triggered = await this.engine.triggeredRuns(run);\n const source = lifecycleSourceOf(run);\n const kind = lifecycleKindOf(run.status);\n const subscribers = kind\n ? await this.engine.lifecycleSubscribers(run.workflow, kind, run.namespace || 'default')\n : [];\n const workflowLifecycle = await this.engine.workflowLifecycle(run.workflow);\n const linked =\n workflowLifecycle.startsOnSettle.length > 0 || workflowLifecycle.startedBy.length > 0;\n const deliveries = kind\n ? lifecycleDeliveriesOf(run, {\n subscribers,\n live: new Set(subscribers),\n coalesced: this.engine.coalescedSubscribers(run),\n })\n : [];\n const [own, onIt] = await Promise.all([\n run.status === 'suspended' ? listSignalWaitersOfRuns(this.store, [run.id]) : [],\n run.workflow.startsWith('__') ? [] : this.store.listSignalWaiters(runWaitPrefix(run.id)),\n ]);\n const waitsFor: RunWaitLink[] = own.flatMap((w) => {\n const target = runWaitTargetOf(w);\n return target !== undefined ? [{ runId: target, seq: w.seq }] : [];\n });\n const awaitedBy: RunWaitLink[] = onIt\n .filter((w) => runWaitTargetOf(w) === run.id)\n .map((w) => ({ runId: w.runId, seq: w.seq }));\n const started = deliveries.flatMap((d) =>\n d.state === 'started' && d.runId !== undefined ? [d.runId] : [],\n );\n const { runs } = await readRunsByIds(this.store, [\n ...(source ? [source.runId] : []),\n ...started,\n ...waitsFor.map((l) => l.runId),\n ...awaitedBy.map((l) => l.runId),\n ]);\n const withRun = <T extends { runId?: string | undefined }>(link: T): T => {\n const other = link.runId !== undefined ? runs.get(link.runId) : undefined;\n return other ? { ...link, status: other.status, namespace: other.namespace } : link;\n };\n const sourceRun = source ? runs.get(source.runId) : undefined;\n const traceId = traceIdOfTraceparent(lifecycleTraceparentOf(sourceRun?.tags));\n return {\n ...(triggered.length > 0 ? { triggered } : {}),\n ...(source\n ? {\n triggeredBy: {\n ...source,\n ...(sourceRun ? { status: sourceRun.status, namespace: sourceRun.namespace } : {}),\n ...(traceId ? { traceId } : {}),\n },\n }\n : {}),\n ...(subscribers.length > 0 ? { lifecycleSubscribers: subscribers } : {}),\n ...(linked ? { workflowLifecycle } : {}),\n ...(deliveries.length > 0\n ? {\n lifecycleDeliveries: deliveries.map(\n (d): LifecycleDelivery => (d.state === 'started' ? withRun(d) : d),\n ),\n }\n : {}),\n ...(waitsFor.length > 0 ? { waitsFor: waitsFor.map(withRun) } : {}),\n ...(awaitedBy.length > 0 ? { awaitedBy: awaitedBy.map(withRun) } : {}),\n };\n }\n\n workflowLifecycle(\n workflow: string,\n opts?: { namespace?: string | undefined },\n ): Promise<WorkflowLifecycleLinks> {\n return this.engine.workflowLifecycle(workflow, opts);\n }\n\n lifecycleSubscribers(\n workflow: string,\n kind: LifecycleKind,\n namespace: string,\n ): Promise<string[]> {\n return this.engine.lifecycleSubscribers(workflow, kind, namespace);\n }\n\n getRun(runId: string): Promise<WorkflowRun | null> {\n return this.visibleRun(runId);\n }\n\n async getFanMembers(runId: string, group: string, query: FanPageQuery): Promise<FanPage | null> {\n if (!(await this.visibleRun(runId))) return null;\n if (aggregatesCheckpoints(this.store)) {\n const stats = await this.store.checkpointStats(runId, { group });\n const etag = fanPageEtag(group, stats, query);\n if (etagMatches(query.ifNoneMatch, etag)) {\n return { items: [], total: 0, notModified: true, etag };\n }\n return { ...(await pageFanFromStore(this.store, runId, group, query, stats)), etag };\n }\n return pageFan(await this.store.listCheckpoints(runId), group, query);\n }\n\n async listRuns(query: RunQuery): Promise<RunListItem[]> {\n const runs = await this.store.listRuns(this.scoped(withoutRegistry(query)));\n // One read of the listed suspended runs' signal waiters resolves what each is parked on — signal\n // / webhook / child — with no per-run timeline fetch. A timer wait falls back to the run's own\n // `wakeAt`. Non-suspended (and remote-step-in-flight) runs carry no `waiting`.\n const waiterByRun = indexWaitersByRun(\n await listSignalWaitersOfRuns(\n this.store,\n runs.filter((run) => run.status === 'suspended').map((run) => run.id),\n ),\n );\n return runs.map((run) => {\n const waiting = resolveRunWaiting(run, waiterByRun);\n return waiting ? { ...run, waiting } : run;\n });\n }\n\n /**\n * The `(status, origin)` counts behind a console's chips, straight off the store's aggregate. The\n * console needs this precisely BECAUSE its list is paginated: the page bounds what is rendered,\n * these counts stay whole-set exact. A store with no aggregate falls back to counting a full\n * listing — correct, but the unbounded read this exists to avoid, so it is the last resort.\n */\n async runFacets(query: RunFacetQuery): Promise<RunFacetRow[]> {\n const scoped = this.scoped(withoutRegistry(query));\n if (this.store.runFacets) return this.store.runFacets(scoped);\n const runs = await this.store.listRuns(scoped);\n return mergeRunFacetRows(runs.map((r) => ({ status: r.status, origin: r.origin, count: 1 })));\n }\n\n /**\n * The distinct values behind a console's pickers, straight off the store's enumeration. A store\n * without one answers `[]` rather than falling back to a listing: unlike the facet counts above —\n * where a full listing is at least the RIGHT answer expensively — a picker built from an unbounded\n * scan would be the same unbounded read on every keystroke, for a control whose free-text entry\n * still works without it.\n */\n async runValueFacets(\n axis: RunValueAxis,\n query: RunFacetQuery,\n opts?: RunValueFacetOptions,\n ): Promise<RunValueFacetRow[]> {\n return this.store.runValueFacets?.(axis, this.scoped(withoutRegistry(query)), opts) ?? [];\n }\n\n /**\n * Bulk-resolve what each of `runIds` is currently parked on — for a consumer with its own filtered/\n * paginated run listing (e.g. \"which of MY suspended runs are stuck at a breakpoint\") without\n * re-deriving `listRuns`' waiter read or querying `durable_step_checkpoints` directly. Mirrors\n * `listRuns`' waiting computation (the requested runs' signal waiters + `resolveRunWaiting`), but ALSO\n * bulk-fetches the currently-suspended runs to check real status: `engine.cancel` (the non-compensate\n * path) doesn't clear a run's signal waiter row, so a cancelled run can leave an ORPHANED waiter\n * behind — trusting waiter presence alone would wrongly report a terminal run as still waiting.\n * Two bulk reads total (never one query per requested id), same as `listRuns`.\n */\n async waitingFor(runIds: string[]): Promise<Record<string, RunWaiting>> {\n if (runIds.length === 0) return {};\n const idSet = new Set(runIds);\n const [suspended, waiters] = await Promise.all([\n this.store.listRuns(this.scoped({ statuses: ['suspended'] })),\n listSignalWaitersOfRuns(this.store, runIds),\n ]);\n const waiterByRun = indexWaitersByRun(waiters);\n const result: Record<string, RunWaiting> = {};\n for (const run of suspended) {\n if (!idSet.has(run.id)) continue;\n const waiting = resolveRunWaiting(run, waiterByRun);\n if (waiting) result[run.id] = waiting;\n }\n return result;\n }\n\n /** Every group the engine knows about — unscoped. A tenant proxy's request is scoped by the\n * `RunRequestResponder` (to the requester's `@<tenant>` groups); the operator's own UI sees all. */\n workerHealth(): Promise<GroupHealth[]> {\n return this.engine.workerHealth();\n }\n\n cancel(runId: string, opts?: { compensate?: boolean }): Promise<RunResult | null> {\n return this.engine.cancel(runId, opts);\n }\n\n /** Re-enqueue (dispatch model) instead of resuming inline — a worker picks the run up and replays it. */\n retry(runId: string): Promise<RunResult | null> {\n return this.engine.requeue(runId);\n }\n\n continue(runId: string): Promise<RunResult | null> {\n return this.engine.continue(runId);\n }\n\n retryWithInput(runId: string, input: unknown): Promise<{ runId: string } | null> {\n return this.engine.retryWithInput(runId, input);\n }\n\n redispatchPending(runId: string): Promise<(RunResult & { redispatched: number }) | null> {\n return this.engine.redispatchPending(runId);\n }\n\n republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult> {\n return this.engine.republishLifecycle(target);\n }\n\n /** The persisted schedules (`[]` when the store does not persist them). */\n async listSchedules(query: ScheduleListQuery): Promise<ScheduleDescription[]> {\n return this.engine.schedules?.supported ? this.engine.schedules.list(query) : [];\n }\n\n async getSchedule(id: string): Promise<ScheduleDescription | null> {\n if (!this.engine.schedules?.supported) return null;\n return (await this.engine.schedules.get(id)) ?? null;\n }\n\n scheduleAction(id: string, action: ScheduleAction): Promise<ScheduleDescription | RunResult> {\n if (action === 'pause') return this.engine.schedules.pause(id);\n if (action === 'resume') return this.engine.schedules.resume(id);\n if (action === 'trigger') return this.engine.schedules.trigger(id);\n return Promise.reject(new Error(`unknown schedule action ${String(action)}`));\n }\n\n signal(token: string, payload: unknown, opts?: SignalOptions): Promise<RunResult | null> {\n return this.engine.signal(token, payload, opts);\n }\n\n signalWithStartForTenant(\n start: StartRunMessage & { runId: string },\n namespace: string,\n clientTenant: Pick<StartOptions, 'tenantId' | 'tenantKind'>,\n signal: { token: string; payload?: unknown },\n ): Promise<{ runId: string; signalled: boolean }> {\n return this.engine.signalWithStartForTenant(start, namespace, clientTenant, signal);\n }\n\n publishEventForTenant(name: string, payload: unknown, namespace: string): Promise<number> {\n return this.engine.publishEventForTenant(name, payload, namespace);\n }\n\n async signalWaiter(token: string): Promise<string | null> {\n const waiter = (await this.store.listSignalWaiters(token)).find((w) => w.token === token);\n return waiter?.runId ?? null;\n }\n\n /**\n * Stream `runId`'s events. With tenancy, a run the caller may not see streams nothing; events of a\n * run that does not exist yet are held until its row shows whose it is.\n */\n subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void {\n // Read the caller's tenant now: the events arrive outside its async context.\n const { tenantIds } = this.scoped({} as RunQuery);\n if (!tenantIds) {\n return this.engine.subscribe((event) => {\n if (event.runId === runId) onEvent(event);\n });\n }\n let visible: boolean | undefined; // undefined until the run's row has been read\n let held: EngineEvent[] = [];\n let checking = false;\n const check = (): void => {\n if (checking || visible !== undefined) return;\n checking = true;\n void this.store\n .getRun(runId)\n .then(\n (run) => {\n if (run) visible = tenantIds.includes(run.tenantId ?? null);\n },\n () => undefined,\n )\n .finally(() => {\n checking = false;\n if (visible === undefined) return;\n const pending = held;\n held = [];\n if (visible) for (const event of pending) onEvent(event);\n });\n };\n const off = this.engine.subscribe((event) => {\n if (event.runId !== runId || visible === false) return;\n if (visible) return onEvent(event);\n held.push(event);\n check();\n });\n check();\n return () => {\n held = [];\n off();\n };\n }\n}\n","import type { EngineEvent, StateStore, TenantEvent } from '@dudousxd/nestjs-durable-core';\n\n/** The narrow slice of `StateStore` the republisher needs — the `step.*`-event namespace fallback\n * (see {@link TenantEventRepublisher.namespaceFor}). Mirrors the `RunRequestTransport` narrowing\n * convention (`run-request-responder.ts`): depend on the smallest surface, not the whole store. */\nexport type RunLookupStore = Pick<StateStore, 'getRun'>;\n\n/** `EngineEvent` types that end a run's lifecycle — no further event for that `runId` will ever\n * follow one of these, so it is the safe point to drop the run from `TenantEventRepublisher`'s\n * namespace cache. Matches the terminal members of `EngineEventType` (`packages/core/src/interfaces.ts`)\n * exactly: `run.suspended` is NOT terminal (a suspended run resumes and emits more events), and\n * there is no separate `run.cancelled`/`run.dead` event type — both cancellation and dead-lettering\n * are published as `run.failed`. */\nfunction isTerminalRunEvent(event: EngineEvent): boolean {\n return event.type === 'run.completed' || event.type === 'run.failed';\n}\n\n/**\n * Re-publishes engine lifecycle events onto a run's per-tenant channel via `publish` (bound from\n * `Transport.publishTenantEvent`), so a store-less tenant worker can live-tail its OWN runs.\n *\n * The run's namespace is read straight off `event.namespace` (stamped by `engine.ts`'s `emit()` on\n * every `run.*` lifecycle event, where the run is already in hand); a `step.*` event doesn't carry\n * it, so those fall back to `store.getRun`. EVERY run's resolved namespace is memoized in\n * `runNamespaces` — including a bare/`default` run — so the store is read at most ONCE per run id\n * regardless of how many `step.*` events that run emits; a `null` cache entry means \"resolved, not\n * a tenant\" (distinct from \"not yet resolved\", i.e. absent from the map). A run's entry is deleted\n * the moment its terminal event is handled, so the cache stays bounded to in-flight runs (tenant and\n * default alike) — the same order of magnitude it was already paying for tenant runs alone, in\n * exchange for turning a per-event store read into a per-run one.\n */\nexport class TenantEventRepublisher {\n private readonly runNamespaces = new Map<string, string | null>();\n\n constructor(\n private readonly store: RunLookupStore,\n private readonly publish: (event: TenantEvent) => Promise<void>,\n ) {}\n\n async handle(event: EngineEvent): Promise<void> {\n const namespace = await this.namespaceFor(event);\n // A terminal run emits no further events — drop its cache entry now regardless of whether this\n // event was itself re-published, so the slot is reclaimed even for a bare/default run.\n if (isTerminalRunEvent(event)) this.runNamespaces.delete(event.runId);\n // Skip bare/default runs — no real tenant to re-publish to, and it would just be noise on an\n // unpartitioned operator.\n if (!namespace || namespace === 'default') return;\n await this.publish({ tenant: namespace, event }).catch(() => undefined);\n }\n\n private async namespaceFor(event: EngineEvent): Promise<string | undefined> {\n if (this.runNamespaces.has(event.runId)) {\n const cached = this.runNamespaces.get(event.runId);\n return cached === null ? undefined : cached;\n }\n if (event.namespace !== undefined) {\n this.runNamespaces.set(event.runId, event.namespace === 'default' ? null : event.namespace);\n return event.namespace;\n }\n const run = await this.store.getRun(event.runId);\n const tenantNamespace =\n run?.namespace !== undefined && run.namespace !== 'default' ? run.namespace : null;\n this.runNamespaces.set(event.runId, tenantNamespace);\n return tenantNamespace === null ? undefined : tenantNamespace;\n }\n}\n","import * as durableCore from '@dudousxd/nestjs-durable-core';\nimport {\n ANNOUNCED_SCHEDULE_TAG,\n DURABLE_OPTIONS_CANONICAL,\n type ScheduledWorkflow,\n WorkflowEngine,\n runSchedules,\n workflowName,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n Inject,\n Injectable,\n type OnApplicationBootstrap,\n type OnModuleDestroy,\n Optional,\n} from '@nestjs/common';\nimport type { DurableModuleOptions } from './durable.module';\nimport { isDrivingOperator } from './role';\nimport { settleWithin } from './settle-within';\nimport { SweepLeases } from './sweep-leases';\n\n/** What {@link TimerPoller.sweep} resolves when the sweep threw. */\nconst SWEEP_FAILED = Symbol('sweep failed');\n\n/**\n * The in-process schedules' next window (core `nextScheduleFireAt`), read off the module namespace\n * because an older core (the peer range is wide) does not export it; the poller then keeps the fixed\n * tick when `schedules` are configured.\n */\nconst nextScheduleFireAt = (\n durableCore as {\n nextScheduleFireAt?: (\n engine: object,\n schedules: readonly ScheduledWorkflow[],\n nowMs: number,\n ) => number | undefined;\n }\n).nextScheduleFireAt;\n\n/**\n * Resumes suspended runs whose durable timer (`ctx.sleep`) is due, and fires any configured\n * recurring `schedules` (plus the persisted `engine.schedules` when `persistedSchedules` is on) —\n * once on boot, then on an interval. Set `timerPollMs` to `0` to disable\n * the interval (e.g. when an external scheduler drives `WorkflowEngine.resumeDueTimers`).\n *\n * The boot poll is started, not awaited: `onApplicationBootstrap` runs before the host's HTTP server\n * listens, so a first poll held up by a large backlog would keep the pod from ever passing its\n * readiness probe. Shutdown still waits for whichever poll is in flight.\n *\n * While polls find nothing to do the wait between them backs off to `maxIdleIntervalMs` (default\n * 5 s), never past the next known due time and back to `timerPollMs` on any run event — see\n * {@link DurableModuleOptions.maxIdleIntervalMs}. The owed-lifecycle listing runs once per\n * `owedLifecycleSweepMs` (default 10 s) instead of on every poll.\n */\n@Injectable()\nexport class TimerPoller implements OnApplicationBootstrap, OnModuleDestroy {\n private timer?: ReturnType<typeof setInterval>;\n private polling = false;\n /** The sweep in flight, so shutdown can wait for it instead of racing the store's close. */\n private current: Promise<boolean> | undefined;\n private unsubscribeEnqueued?: () => void;\n private unsubscribeEvents?: () => void;\n /** Set by shutdown: the backoff loop stops scheduling polls. */\n private stopped = false;\n /** Something happened (a run event, an enqueue nudge) since the last poll started. */\n private activity = false;\n /** Ends the backoff loop's current wait early (set only while it waits). */\n private endWait: (() => void) | undefined;\n /** When the owed-lifecycle listing last succeeded (see {@link owedSweepDue}). */\n private owedSweptAt: number | undefined;\n /** When the tenant schedule announcements were last reconciled (see {@link announcedSchedules}). */\n private announcedSyncedAt: number | undefined;\n\n constructor(\n private readonly engine: WorkflowEngine,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n // Fleet-wide sweeps run under a `@nestjs/locks` lease when the app has `LocksModule` (detected).\n @Optional() private readonly leases: SweepLeases = new SweepLeases(),\n ) {}\n\n async onApplicationBootstrap(): Promise<void> {\n // A schedule whose `workflow` is a class that was never decorated would only fail on its first\n // fire, logged and retried every tick. Resolve every class now so the app fails to boot instead.\n for (const s of this.options.schedules ?? []) workflowName(s.workflow);\n // Drive suspended runs forward when this operator instance is DRIVING (defaults to true) — it\n // may execute locally or dispatch remotely (group-served / convention), either way it drives. A\n // non-driving (dashboard-only) operator, or a thin worker with no `store` at all, must not\n // resume timers — leave that to a driving instance.\n if (!isDrivingOperator(this.options)) return;\n // A driving instance consumes the transport's run queue when the transport carries one, so the\n // runs any instance starts (a `ctx.all` fan's children included), re-dispatches or finds due\n // spread over every driving instance. `engine.beginDrain` (below, at shutdown) stops it, and\n // the registrar's `drain` waits for the runs it holds within `shutdownTimeoutMs`. Optional for\n // an older core.\n this.engine.consumeRuns?.();\n // Low-latency dispatch: when a run is enqueued elsewhere (e.g. an API pod), pick it up at once\n // over the control plane instead of waiting for the next poll tick. Leasing dedups across workers.\n // The `.catch` is load-bearing, not decorative: this is fire-and-forget, so an unhandled\n // rejection here terminates the process under Node's default policy — and the run it could not\n // drive is still waiting for the next poll tick either way.\n //\n // `runEnqueued` is bounded and skips a run another instance already took; every instance\n // receives every announcement, so a wide fan would otherwise lease and replay every child here\n // at once. Optional for an older core.\n this.unsubscribeEnqueued = this.engine.onEnqueued((runId) => {\n this.noteActivity();\n if (typeof this.engine.runEnqueued === 'function') {\n this.engine.runEnqueued(runId);\n return;\n }\n void this.engine.runOne(runId).catch((error) => {\n console.error(`[nestjs-durable] could not run enqueued run ${runId}:`, error);\n });\n });\n const intervalMs = this.options.timerPollMs ?? 1_000;\n const maxIdleMs = this.options.maxIdleIntervalMs ?? 5_000;\n if (intervalMs > 0 && maxIdleMs > intervalMs && this.canBackOff()) {\n // Any run event, local or from another instance (control plane), ends an idle wait.\n this.unsubscribeEvents = this.engine.subscribe(() => this.noteActivity());\n void this.loop(intervalMs, maxIdleMs);\n return;\n }\n void this.poll();\n if (intervalMs > 0) {\n this.timer = setInterval(() => void this.poll(), intervalMs);\n this.timer.unref?.();\n }\n }\n\n /**\n * Whether polls may be spaced out while idle: the engine must reach new runs without the\n * pending-run poll and say when its next timer is due, and the in-process schedules must be able\n * to say when their next window is. Optional calls throughout: an older core keeps the fixed tick.\n */\n private canBackOff(): boolean {\n if (this.engine.idleBackoffSupported !== true) return false;\n if (typeof this.engine.nextDueAt !== 'function') return false;\n if ((this.options.schedules?.length ?? 0) > 0 && nextScheduleFireAt === undefined) return false;\n return true;\n }\n\n private noteActivity(): void {\n this.activity = true;\n this.endWait?.();\n }\n\n /**\n * Poll, then wait: `intervalMs` after a poll that found work (or while anything happened), else\n * twice the last wait up to `maxIdleMs`, cut short so the next poll runs no later than the earliest\n * known due time. A run event or an enqueue nudge ends a wait at once.\n */\n private async loop(intervalMs: number, maxIdleMs: number): Promise<void> {\n let wait = intervalMs;\n while (!this.stopped) {\n // Whatever arrived during the wait (it ended the wait) counts as this poll's work.\n const arrived = this.activity;\n this.activity = false;\n const worked = await this.poll();\n if (this.stopped) return;\n const idle = !worked && !arrived && !this.activity;\n wait = idle ? Math.min(wait * 2, maxIdleMs) : intervalMs;\n let next = wait;\n if (next > intervalMs) next = await this.untilDue(next, intervalMs);\n if (this.stopped) return;\n if (this.activity) next = Math.min(next, intervalMs); // something happened during the read\n await new Promise<void>((resolve) => {\n const done = () => {\n clearTimeout(timer);\n this.endWait = undefined;\n resolve();\n };\n const timer = setTimeout(done, next);\n timer.unref?.();\n // Only a wait longer than the regular tick is ended early; shutdown ends any.\n this.endWait = () => {\n if (this.stopped || next > intervalMs) done();\n };\n });\n }\n }\n\n /**\n * `wait`, shortened so the next poll runs no later than the earliest known due time: the engine's\n * next timer, blocked-run recovery poll or persisted schedule, and the next window of the\n * in-process `schedules`. Never below `intervalMs` (the regular tick catches what is due sooner). A\n * failed read keeps the regular tick.\n */\n private async untilDue(wait: number, intervalMs: number): Promise<number> {\n try {\n const now = Date.now();\n const stored = await this.engine.nextDueAt(now + wait, {\n persistedSchedules: this.options.persistedSchedules === true,\n announcedSchedules: this.announcedSchedules() !== undefined,\n });\n const schedules = this.options.schedules;\n const scheduled =\n schedules && schedules.length > 0 && nextScheduleFireAt\n ? nextScheduleFireAt(this.engine, schedules, now)\n : undefined;\n let due = wait;\n for (const at of [stored, scheduled]) {\n if (at !== undefined) due = Math.min(due, at - Date.now());\n }\n return Math.max(intervalMs, due);\n } catch {\n return intervalMs;\n }\n }\n\n /**\n * The tenant schedule adoption settings when it is on (see\n * {@link DurableModuleOptions.announcedSchedules}), else undefined: off by option, on a core\n * without it, or on a store that does not persist schedules.\n */\n private announcedSchedules(): { syncMs: number; graceMs: number | undefined } | undefined {\n const option = this.options.announcedSchedules;\n if (option === false) return undefined;\n if (typeof this.engine.syncAnnouncedSchedules !== 'function') return undefined;\n if (this.engine.schedules?.supported !== true) return undefined;\n const settings = typeof option === 'object' ? option : {};\n return { syncMs: settings.syncMs ?? 15_000, graceMs: settings.graceMs };\n }\n\n /**\n * Whether this poll lists the owed lifecycle runs: until a sweep that listed them succeeded, then\n * once per `owedLifecycleSweepMs` (a clock that went back lists them again).\n */\n private owedSweepDue(now: number): boolean {\n const every = this.options.owedLifecycleSweepMs ?? 10_000;\n const last = this.owedSweptAt;\n return every <= 0 || last === undefined || now < last || now - last >= every;\n }\n\n /**\n * Stop polling and wait for the sweep in flight (bounded by `shutdownTimeoutMs`, default 10s).\n * Nest runs every `onModuleDestroy` before any `onApplicationShutdown`, so returning here only once\n * the sweep has settled means no store call is still pending when the registrar drains and the\n * host closes its connection pool. The engine is told to stop first so a sweep working through a\n * backlog stops locking runs instead of finishing the backlog. The time spent waiting is deducted\n * from the later `engine.drain()`, so poll wait plus drain stay within one `shutdownTimeoutMs`.\n */\n async onModuleDestroy(): Promise<void> {\n this.stopped = true;\n if (this.timer) clearInterval(this.timer);\n this.endWait?.();\n this.unsubscribeEnqueued?.();\n this.unsubscribeEvents?.();\n // Only an operator that DRIVES the engine has a poll to wait for, and only it stops taking work\n // here. A non-driving operator (dashboard-only, `drive: false`) keeps running whatever its\n // finishing requests or `beforeApplicationShutdown` hooks start; `drain()` in the registrar\n // still waits for those.\n if (!isDrivingOperator(this.options)) return;\n // Optional call: an older core (the peer range is wide) has no `beginDrain`, and a TypeError here\n // would reject `app.close()` on Nest 10/11 before the registrar ever drains.\n this.engine.beginDrain?.();\n if (!this.current) return;\n const budget = this.options.shutdownTimeoutMs ?? 10_000;\n const started = Date.now();\n const timedOut = await settleWithin(this.current, budget);\n // Charge the drain only for the time spent waiting here, not for whatever Nest does between this\n // hook and the registrar's drain.\n this.engine.beginDrain?.(Date.now() - started);\n if (timedOut) {\n console.warn(\n `[nestjs-durable] timer poll still running after ${budget}ms at shutdown; continuing (it may report store errors if the host ends its pool now)`,\n );\n }\n }\n\n /**\n * One sweep of the engine's recovery work.\n *\n * **This method never rejects, and that is a hard requirement rather than defensiveness.** Both\n * callers (the boot kick-off and the interval) fire it as `void`, so a rejection would surface as\n * an unhandled rejection, which is fatal, and would re-occur on the next boot with the same state:\n * a single unrecoverable run would crash-loop every worker in the deployment, taking down every\n * other workflow with it. A poll that goes wrong must cost this tick, not the pod.\n *\n * Each sweep is isolated separately because they are independent: a store that fails\n * `recoverIncomplete` says nothing about whether durable timers should still fire, and skipping\n * the rest of the tick would silently widen one subsystem's outage into all of them.\n */\n private poll(): Promise<boolean> {\n if (this.polling) return this.current ?? Promise.resolve(true); // never overlap two sweeps\n this.polling = true;\n const run = this.pollOnce().finally(() => {\n this.polling = false;\n if (this.current === run) this.current = undefined;\n });\n this.current = run;\n return run;\n }\n\n /** One poll of every sweep. Resolves whether it found work (or a sweep failed): see {@link loop}. */\n private async pollOnce(): Promise<boolean> {\n let worked = false;\n // Work: a sweep returned runs (or run ids) it acted on, or failed (the loop keeps the regular\n // tick so the failure is retried soon).\n const note = (result: unknown) => {\n if (result === SWEEP_FAILED || (Array.isArray(result) && result.length > 0)) worked = true;\n };\n // Pick up runs enqueued elsewhere (an API pod's `start`, or another worker) still `pending`,\n // reclaim runs orphaned by a crashed worker (lease expired — a live worker renews its lease so\n // only dead ones are reclaimed), then resume due timers and sweep execution timeouts.\n note(await this.sweep('runPending', () => this.engine.runPending()));\n note(await this.sweep('recoverIncomplete', () => this.engine.recoverIncomplete()));\n note(await this.sweep('resumeDueTimers', () => this.engine.resumeDueTimers()));\n note(await this.sweep('sweepTimeouts', () => this.engine.sweepTimeouts()));\n // The stalled-run pager: throttled to a pass a minute inside the engine, a no-op without an\n // `onStalled` listener. Optional call: an older core (the peer range is wide) has no sweep.\n // One pod pages when `@nestjs/locks` is present (see SweepLeases); every pod otherwise.\n note(\n await this.sweep('sweepStalled', () =>\n this.leases.run('stalled-pager', async () => this.engine.sweepStalled?.()),\n ),\n );\n // Buffered child completions no parent will consume: a few pages per tick until a pass ends,\n // then a rest (throttled inside the engine). Optional call, like the stalled sweep.\n note(\n await this.sweep('sweepBufferedSignals', () =>\n this.leases.run('buffered-signals', async () => this.engine.sweepBufferedSignals?.()),\n ),\n );\n // Signal dedupe ids past their TTL (`signal(..., { id })`): a few bounded deletes per tick, one\n // pod at a time like the buffered-signals sweep.\n note(\n await this.sweep('sweepExpiredSignalIds', () =>\n this.leases.run('signal-ids', async () => this.engine.sweepExpiredSignalIds?.()),\n ),\n );\n // Lifecycle events a settled run still owes to a subscriber this instance has (its process\n // died before publishing, or did not have the subscriber), and `ctx.waitForRun` waits whose\n // run settled without resuming them. The owed listing (a tag filter over settled runs) and the\n // heal run once per `owedLifecycleSweepMs`; the run waits every poll. Only a listing that got\n // through starts the interval: a failed one is retried on the next poll. Optional call, like\n // the sweeps above (an older core ignores the third argument and sweeps everything).\n const now = Date.now();\n const owed = this.owedSweepDue(now);\n note(\n await this.sweep('sweepLifecycleEvents', async () => {\n const published = await this.engine.sweepLifecycleEvents?.(undefined, undefined, {\n owed,\n });\n if (owed) this.owedSweptAt = now;\n return published;\n }),\n );\n const schedules = this.options.schedules;\n if (schedules && schedules.length > 0) {\n note(await this.sweep('schedules', () => runSchedules(this.engine, schedules, Date.now())));\n }\n const announced = this.announcedSchedules();\n if (announced) {\n // Reconcile what tenant apps announce, once per `syncMs` and on one pod at a time when\n // `@nestjs/locks` is present. Only a sync that got through starts the interval.\n const at = Date.now();\n const last = this.announcedSyncedAt;\n if (last === undefined || at < last || at - last >= announced.syncMs) {\n await this.sweep('announcedSchedules', () =>\n this.leases.run('announced-schedules', async () => {\n await this.engine.syncAnnouncedSchedules({\n ...(announced.graceMs !== undefined ? { graceMs: announced.graceMs } : {}),\n });\n this.announcedSyncedAt = at;\n }),\n );\n }\n }\n if (this.options.persistedSchedules) {\n // Every persisted schedule, the adopted tenant ones included.\n note(await this.sweep('persistedSchedules', () => this.engine.schedules.tick()));\n } else if (announced) {\n note(\n await this.sweep('announcedScheduleFires', () =>\n this.engine.schedules.tick(Date.now(), { tag: ANNOUNCED_SCHEDULE_TAG }),\n ),\n );\n }\n return worked;\n }\n\n /** Run one sweep, absorbing and reporting its failure — see {@link poll}. */\n private async sweep(name: string, run: () => Promise<unknown>): Promise<unknown> {\n try {\n return await run();\n } catch (error) {\n console.error(`[nestjs-durable] timer poll: ${name} failed; continuing:`, error);\n return SWEEP_FAILED;\n }\n }\n}\n","import {\n DURABLE_OPTIONS_CANONICAL,\n RemoteWorkflowExecutor,\n STATE_STORE_CANONICAL,\n type StateStore,\n type WorkflowCtx,\n WorkflowEngine,\n type WorkflowRun,\n bindWorkflowClass,\n parseDuration,\n sanitizeQueueToken,\n tenantGroup,\n workflowName,\n} from '@dudousxd/nestjs-durable-core';\nimport {\n Inject,\n Injectable,\n type OnApplicationBootstrap,\n type OnApplicationShutdown,\n type OnModuleInit,\n} from '@nestjs/common';\nimport { DiscoveryService, MetadataScanner } from '@nestjs/core';\nimport {\n type WorkflowMeta,\n eventBatchOf,\n getOnEvents,\n isDeadLetterHandler,\n onErrorCodesOf,\n} from './decorators';\nimport { scanWorkflows } from './discovery-helpers';\nimport type { DurableModuleOptions } from './durable.module';\nimport { entityConfigFor, getEntityMeta } from './entity';\nimport { IN_APP_WORKER_BINDING, type InAppWorkerBinding } from './in-app-worker';\nimport { onErrorHandlersOf } from './on-error-handlers';\nimport { isDrivingOperator, isOperatorRole } from './role';\nimport { type DurableStepInterceptor, isStepInterceptor } from './step-interceptor';\nimport { workflowIo } from './workflow-io';\n\ntype WorkflowFn = (ctx: WorkflowCtx, input: unknown) => Promise<unknown>;\n\n/**\n * Ensures the schema (auto-schema) and registers `@Workflow` providers on init, resumes runs left\n * incomplete by a previous process once booted, and drains in-flight runs on shutdown.\n *\n * For the shutdown drain to fire, enable Nest's shutdown hooks: `app.enableShutdownHooks()`.\n */\n/** How long after boot an onError route unserved at boot is checked again before it is reported. */\nconst UNSERVED_ROUTES_RECHECK_MS = 30_000;\n\n@Injectable()\nexport class WorkflowRegistrar\n implements OnModuleInit, OnApplicationBootstrap, OnApplicationShutdown\n{\n constructor(\n private readonly discovery: DiscoveryService,\n private readonly metadataScanner: MetadataScanner,\n private readonly engine: WorkflowEngine,\n @Inject(STATE_STORE_CANONICAL) private readonly store: StateStore | null,\n @Inject(DURABLE_OPTIONS_CANONICAL) private readonly options: DurableModuleOptions,\n // Group-served binding when the app opted into an in-app worker (uniform dispatch); null = inline.\n @Inject(IN_APP_WORKER_BINDING) private readonly inAppWorker: InAppWorkerBinding | null,\n ) {}\n\n async onApplicationBootstrap(): Promise<void> {\n // Recover runs left incomplete by a crash/deploy when this operator instance is DRIVING\n // (defaults to true). A non-driving (dashboard-only) operator, or a thin worker with no `store`\n // at all, must not pick up and re-run workflows — leave that to a driving instance.\n if (!isDrivingOperator(this.options)) return;\n await this.engine.recoverIncomplete();\n }\n\n /** On deploy/shutdown: stop picking up new runs and wait for in-flight ones to settle, then close\n * the transport(s) so the broker workers stop consuming and connections are released. Closing\n * AFTER the drain keeps the transport alive while in-flight runs dispatch/await their remote steps.\n * Operator only — a thin worker (no `store`) holds no engine to drain. */\n async onApplicationShutdown(): Promise<void> {\n if (!isOperatorRole(this.options)) return;\n await this.engine.drain(this.options.shutdownTimeoutMs);\n const transports = [\n this.options.transport,\n ...(this.options.transports ?? []).map((t) => t.transport),\n ];\n await Promise.allSettled(transports.map((t) => t?.close?.()));\n }\n\n async onModuleInit(): Promise<void> {\n // Operator only — a thin worker (no `store`) registers its bodies on a `DurableWorkerRuntime`\n // instead (see `durable-worker.module.ts`'s `ThinWorkflowRegistrar`), never on this engine.\n if (!isOperatorRole(this.options)) return;\n const store = this.store;\n if (!store) {\n throw new Error(\n 'unreachable: STATE_STORE_CANONICAL must resolve a store when options.store is set',\n );\n }\n if (this.options.autoSchema !== false) {\n await store.ensureSchema?.();\n }\n // Maps a workflow name to the workflow its dead runs route to. Built from each `@Workflow`'s\n // inline `@DeadLetter()` method (preferred) or its `deadLetterWorkflow` reference; the\n // module-level `deadLetterWorkflow` is the fallback applied in the onDead listener below.\n const deadLetterByWorkflow = new Map<string, string>();\n\n // Pre-pass: wire interceptors and register @Entity providers (engine-only concerns).\n for (const wrapper of this.discovery.getProviders()) {\n const { instance } = wrapper;\n if (!instance || typeof instance !== 'object') continue;\n if (isStepInterceptor(instance.constructor)) {\n const interceptor = instance as DurableStepInterceptor;\n this.engine.use((invocation, next) => interceptor.intercept(invocation, next));\n }\n const entityMeta = getEntityMeta(instance.constructor);\n if (entityMeta) {\n this.engine.registerEntity(entityMeta.name, entityConfigFor(instance.constructor));\n }\n }\n\n // Workflows whose declaring package could not be derived — reported once, after the scan.\n const unattributed: string[] = [];\n\n // Workflow registration pass — shared scan, engine-specific registration callback.\n scanWorkflows(this.discovery, (meta, workflow, origin) => {\n if (origin === undefined) unattributed.push(meta.name);\n // `input`/`output` schemas: checked at start, and parsed around the body on every turn.\n const io = workflowIo(meta);\n const body = io.wrap((ctx, input) => workflow.run(ctx, input));\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const workflowCtor: object = (workflow as any).constructor as object;\n const eventBatch = eventBatchOf(meta, workflowCtor);\n // Each `@OnError` method is a durable workflow of its own, inline like an `@DeadLetter` one.\n const onError = onErrorHandlersOf(meta, workflow as unknown as object, this.metadataScanner);\n for (const [name, fn] of onError.handlers) {\n this.engine.register(name, meta.version, fn, { origin });\n }\n this.engine.register(meta.name, meta.version, body, {\n // Stamped onto every run this workflow starts (see `WorkflowRun.origin`). Derived from the\n // class's declaring file, so a lib gets attributed without opting in; `undefined` when it\n // could not be derived, which the engine records as unknown rather than defaulting.\n origin,\n tags: meta.tags,\n singleton: meta.singleton,\n concurrency: meta.concurrency,\n executionTimeout: meta.executionTimeout,\n requires: meta.requires,\n validateInput: io.validateParsed,\n parseInput: io.parseInput,\n searchAttributesSchema: meta.searchAttributes,\n onEvent: getOnEvents(meta, workflowCtor),\n eventBatch,\n onError: onError.routes,\n // Uniform dispatch (opt-in): when an in-app worker is configured, register the body GROUP-SERVED\n // so the engine dispatches its turns over the transport instead of running it inline; the\n // co-located worker consumer (Task 5: one queue PER REGISTERED NAME) replays the same body.\n // The routing token — and the executor that dispatches under it — MUST be keyed by THIS\n // workflow's own name (`tenantGroup(sanitizeQueueToken(meta.name), partition)`), not a single\n // group shared across every discovered `@Workflow`: a fixed shared token would dispatch every\n // workflow's turns to one queue while the co-located worker subscribes one queue per name,\n // so a turn dispatched under the wrong token would never be consumed. Absent → the inline fast\n // path (unchanged).\n ...(this.inAppWorker\n ? {\n group: tenantGroup(sanitizeQueueToken(meta.name), this.inAppWorker.partition),\n executor: new RemoteWorkflowExecutor(\n this.inAppWorker.transport,\n meta.name,\n this.inAppWorker.partition,\n ),\n }\n : {}),\n });\n\n // Class-first statics (`MyWorkflow.start()` / `.execute()`): bind the class to THIS engine,\n // so the statics resolve the engine that registered it — no global engine singleton.\n bindWorkflowClass(workflowCtor as new () => object, {\n start: (name, input, runId, opts) => this.engine.start(name, input, runId, opts),\n waitForRun: (runId, opts) => this.engine.waitForRun(runId, opts),\n });\n\n const inline = this.findDeadLetterHandler(workflow as unknown as object);\n if (inline && meta.deadLetterWorkflow) {\n // Two dead-letter targets for one workflow is ambiguous config, not a precedence question —\n // fail fast at boot rather than silently picking one.\n throw new Error(\n `@Workflow ${meta.name} declares both an inline @DeadLetter() method and a deadLetterWorkflow option. Use one: the inline handler, or the reference.`,\n );\n }\n if (inline) {\n // The inline handler is itself a durable workflow, registered as `<name>.dlq`, so it gets\n // checkpointing and a dashboard run linked to the dead run via the `dlq:<runId>` id.\n const dlqName = `${meta.name}.dlq`;\n // Declared on the very same class, so it carries the same origin.\n this.engine.register(dlqName, meta.version, inline, { origin });\n deadLetterByWorkflow.set(meta.name, dlqName);\n } else if (meta.deadLetterWorkflow) {\n deadLetterByWorkflow.set(meta.name, workflowName(meta.deadLetterWorkflow));\n }\n });\n\n this.reportUnattributed(unattributed);\n void this.reportUnservedOnErrorRoutes();\n this.installDeadLetterRouting(deadLetterByWorkflow);\n }\n\n /**\n * Says, once at boot, which workflows could not be attributed to a package — their runs are stamped\n * with no `origin` at all, so an operator filtering the dashboard by origin will not see them. That\n * is the deliberate trade (an absent origin over an invented one), but it has to be visible: a\n * silently-dropped run is indistinguishable from a run that never happened.\n */\n private reportUnattributed(names: string[]): void {\n if (names.length === 0) return;\n console.warn(\n `[nestjs-durable] could not derive an origin (declaring package) for ${names.length} workflow(s): ${names.join(', ')}. Their runs carry no origin and will not match an origin filter.`,\n );\n }\n\n /**\n * Says, once after boot, which onError routes name a handler workflow nothing can run, so a typo is\n * caught before the first failure goes nowhere. Routes unserved at boot are checked again after\n * {@link UNSERVED_ROUTES_RECHECK_MS}, so a handler whose workers start after this process is not\n * reported.\n */\n async reportUnservedOnErrorRoutes(recheckMs = UNSERVED_ROUTES_RECHECK_MS): Promise<void> {\n if ((await this.engine.unservedOnErrorRoutes().catch(() => [])).length === 0) return;\n await new Promise<void>((resolve) => setTimeout(resolve, recheckMs).unref());\n const unserved = await this.engine.unservedOnErrorRoutes().catch(() => []);\n if (unserved.length === 0) return;\n const list = unserved\n .map(({ workflow, route }) => `${workflow} → ${route.workflow} (code ${route.code ?? '*'})`)\n .join(', ');\n console.warn(\n `[nestjs-durable] ${unserved.length} onError route(s) name a handler workflow that is not registered here and has no live worker: ${list}.`,\n );\n }\n\n /** Returns the instance's `@DeadLetter()` method bound to the instance, or undefined if none. */\n private findDeadLetterHandler(instance: object): WorkflowFn | undefined {\n const prototype = Object.getPrototypeOf(instance);\n for (const methodName of this.metadataScanner.getAllMethodNames(prototype)) {\n const method = (instance as Record<string, unknown>)[methodName];\n if (typeof method === 'function' && isDeadLetterHandler(method)) {\n return (ctx, input) => method.call(instance, ctx, input);\n }\n }\n return undefined;\n }\n\n /**\n * Installs a single onDead listener that routes a dead run to its workflow's handler (from the\n * map) or the module-level `deadLetterWorkflow` default. The handler is started idempotently with\n * a `dlq:<runId>` id, so re-recovery never double-dispatches.\n */\n private installDeadLetterRouting(byWorkflow: Map<string, string>): void {\n const fallback = this.options.deadLetterWorkflow\n ? workflowName(this.options.deadLetterWorkflow)\n : undefined;\n if (byWorkflow.size === 0 && !fallback) return;\n this.engine.onDead((run: WorkflowRun) => {\n void this.routeDead(run, byWorkflow, fallback).catch(() => undefined);\n });\n }\n\n /** {@link installDeadLetterRouting}'s routing of one dead run. */\n private async routeDead(\n run: WorkflowRun,\n byWorkflow: Map<string, string>,\n fallback: string | undefined,\n ): Promise<void> {\n let target = byWorkflow.get(run.workflow);\n if (!target && fallback) {\n // A tenant's workflow whose workers announce their own dead-letter route: the engine starts\n // that one (see `WorkflowEngine.announcedDeadLetter`), and this app's default stands aside.\n // Optional call: an older core (the peer range is wide) announces nothing.\n if (await this.engine.announcedDeadLetter?.(run).catch(() => undefined)) return;\n target = fallback;\n }\n if (!target) return;\n await this.engine\n .start(\n target,\n { deadRunId: run.id, workflow: run.workflow, input: run.input, error: run.error },\n `dlq:${run.id}`,\n // Route the dead-letter handler to the dead run's OWN tenant so an operator dispatches it to\n // that tenant's worker group (`target@<tenant>`), not the bare group.\n { namespace: run.namespace },\n )\n .catch(() => undefined);\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport {\n type RepublishLifecycleResult,\n type RepublishLifecycleTarget,\n type RunResult,\n type SignalOptions,\n type StartOptions,\n type WorkflowClass,\n WorkflowEngine,\n type WorkflowInputOf,\n} from '@dudousxd/nestjs-durable-core';\nimport { Injectable } from '@nestjs/common';\n\n/** Public entry point for starting and resuming workflow runs. */\n@Injectable()\nexport class WorkflowService {\n constructor(private readonly engine: WorkflowEngine) {}\n\n /**\n * Enqueue a workflow run — it creates the run (`pending`) and returns `{ runId, status: 'pending' }`\n * immediately; a worker executes the body (so the caller never blocks on workflow logic). Use\n * {@link waitForRun} when you need the outcome. Pass the workflow's **class**\n * (`start(CheckoutWorkflow, input)`) for a typed input + refactor-safety, or a **name** string for a\n * cross-runtime workflow. `runId` defaults to a random id; pass your own to make the start idempotent\n * (a redelivery returns the existing run). `opts.tags` are merged with the workflow's static\n * `@Workflow({ tags })`; `opts.searchAttributes` stamp typed, queryable run data.\n */\n start<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n runId?: string,\n opts?: StartOptions,\n ): Promise<RunResult>;\n start(workflow: string, input: unknown, runId?: string, opts?: StartOptions): Promise<RunResult>;\n start(\n workflow: string,\n input: unknown,\n runId: string = randomUUID(),\n opts?: StartOptions,\n ): Promise<RunResult> {\n return this.engine.start(workflow, input, runId, opts);\n }\n\n resume(runId: string): Promise<RunResult> {\n return this.engine.resume(runId);\n }\n\n /**\n * Resolve once a run settles — terminal (completed/failed/cancelled/dead) or suspended. `start`\n * only enqueues (a worker runs the body), so pair them when a request needs the outcome:\n * `const { runId } = await svc.start(...); const result = await svc.waitForRun(runId)`.\n * `until: 'terminal'` waits past suspensions until the run completes/fails/is cancelled — what a\n * delayed start (`opts.startAt`) needs, since it is `suspended` until its timer fires.\n */\n waitForRun(\n runId: string,\n opts?: { timeoutMs?: number; until?: 'settled' | 'terminal' },\n ): Promise<RunResult> {\n return this.engine.waitForRun(runId, opts);\n }\n\n /**\n * Deliver an external signal (e.g. from a webhook) to the run waiting on `token`, or buffer it for\n * the next wait on it. With `{ id }`, a re-send with the same token and id is dropped (resolves\n * `null`): see {@link SignalOptions}.\n */\n signal(token: string, payload: unknown, opts?: SignalOptions): Promise<RunResult | null> {\n return this.engine.signal(token, payload, opts);\n }\n\n /**\n * Ensure a run exists for `runId`, then deliver a signal to it — race-free (the signal is buffered\n * until the run reaches its `waitForSignal`). The durable-entity / accumulator pattern: one\n * long-lived run per key fed events by many calls. See {@link WorkflowEngine.signalWithStart}.\n */\n signalWithStart<C extends WorkflowClass>(\n workflow: C,\n input: WorkflowInputOf<C>,\n runId: string,\n signal: { token: string; payload?: unknown },\n opts?: StartOptions,\n ): Promise<{ runId: string }>;\n signalWithStart(\n workflow: string,\n input: unknown,\n runId: string,\n signal: { token: string; payload?: unknown },\n opts?: StartOptions,\n ): Promise<{ runId: string }>;\n signalWithStart(\n workflow: string,\n input: unknown,\n runId: string,\n signal: { token: string; payload?: unknown },\n opts?: StartOptions,\n ): Promise<{ runId: string }> {\n return this.engine.signalWithStart(workflow, input, runId, signal, opts);\n }\n\n /**\n * Publish a named event. Resumes runs waiting on it via `ctx.waitForEvent(name, { match })` and\n * starts a fresh run of every workflow subscribed via `@Workflow({ onEvent })` / `@OnDurableEvent` (the\n * payload becomes its input). Pass `opts.id` to dedupe redeliveries. Returns how many runs it\n * touched (resumed + started).\n *\n * Reliable by default: a publish that touches NOBODY (no live waiter, no subscriber) buffers ONE\n * copy so a LATER `waitForEvent(name, { match })` still consumes it instead of it being dropped —\n * see {@link WorkflowEngine.publishEvent}'s full semantics doc. Pass `opts.buffer: false` to opt out.\n */\n publishEvent(\n name: string,\n payload: unknown,\n opts?: { id?: string; buffer?: boolean },\n ): Promise<number> {\n return this.engine.publishEvent(name, payload, opts);\n }\n\n /**\n * The runs started by `runId` settling, through `@OnWorkflowCompleted` / `@OnWorkflowFailed` (or\n * an `onEvent` on `runCompletedEvent(...)`). Only subscribers registered on this engine are\n * considered. For the reverse link, `lifecycleSourceOf(run)` reads it from the run itself.\n */\n triggeredRuns(runId: string): Promise<string[]> {\n return this.engine.triggeredRuns(runId);\n }\n\n /**\n * Publish settled runs' lifecycle events again: to a subscriber registered after they settled, or\n * one restricted by `subscriber`. Subscribers already started for a run are not started again.\n * See `WorkflowEngine.republishLifecycle`.\n */\n republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult> {\n return this.engine.republishLifecycle(target);\n }\n}\n","import {\n type ControlMessage,\n type ControlPlane,\n type DurableTopology,\n type EngineEvent,\n type FanPage,\n type FanPageQuery,\n type GroupHealth,\n type LifecycleKind,\n type RepublishLifecycleResult,\n type RepublishLifecycleTarget,\n type RunDetail,\n type RunDetailOptions,\n type RunFacetQuery,\n type RunFacetRow,\n type RunGateway,\n type RunListItem,\n type RunQuery,\n type RunReply,\n type RunRequestKind,\n type RunResult,\n type RunValueAxis,\n type RunValueFacetOptions,\n type RunValueFacetRow,\n type RunWaiting,\n type ScheduleAction,\n type ScheduleDescription,\n type ScheduleListQuery,\n type StateStore,\n type Transport,\n WorkflowEngine,\n type WorkflowLifecycleLinks,\n type WorkflowRun,\n} from '@dudousxd/nestjs-durable-core';\nimport { RunGatewayError } from './proxy-run-gateway';\nimport { StoreRunGateway } from './store-run-gateway';\n\n/** Options for {@link federatedAppGateway}. */\nexport interface FederatedAppGatewayOptions {\n /**\n * A handle on the app's state store, used for READS only (runs, timelines, facets, schedules).\n * Typically a store adapter over the app's schema with a database user granted `SELECT` on it.\n * Nothing on this handle is written: actions go to the app (see {@link transport}).\n */\n store: StateStore;\n /**\n * A transport on the app's broker and prefix (e.g. `new BullMQTransport({ connection, prefix })`\n * with the app's own `prefix`), dedicated to this gateway. It carries the actions to the app as run\n * requests, which the app's own engine answers and executes, plus its live run events and worker\n * health. The gateway consumes no queue on it: the app's work is never taken by the console.\n */\n transport: Transport;\n /**\n * The token presented as the requester of each action, for an app whose engine verifies tenants\n * (`verifyTenant`, e.g. `hmacTenantVerifier(secret)`): `(namespace) => signTenantToken(namespace,\n * secret)`. Called with the namespace of the run or schedule acted on. Omitted: the namespace\n * itself is sent, which an app without `verifyTenant` trusts.\n */\n tenantToken?: (namespace: string) => string | Promise<string>;\n /**\n * Where the app's engines broadcast their lifecycle events (its `controlPlane`): what the console's\n * live tail of an app run listens on. Default: {@link transport} when it can broadcast (BullMQ\n * can), which is also the app's default. Only listened to, never published on.\n */\n controlPlane?: ControlPlane;\n /** How long an action waits for the app to answer. Default 10000 ms. */\n timeoutMs?: number;\n}\n\ninterface Pending {\n resolve(data: unknown): void;\n reject(err: Error): void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * A `RunGateway` for ANOTHER app, for a federated console (the dashboard's `federation` option).\n * Reads come from the app's store; every action (cancel, retry, continue, signal, schedule\n * pause/resume/trigger, …) is published to the app over its broker as a run request, and the app's\n * own engine executes it, through the run-request responder every operator with a broker transport\n * already runs. The console process never drives, recovers or executes the app's runs.\n *\n * Each action names the namespace of the run (or schedule) it acts on as the requester, which the\n * app's responder checks the run against, exactly as it checks a tenant's request.\n */\nexport class FederatedAppGateway implements RunGateway {\n private readonly reads: StoreRunGateway;\n private readonly pending = new Map<string, Pending>();\n private listening = false;\n private readonly timeoutMs: number;\n /** Live-tail listeners by run id, fed by ONE subscription to the app's control channel. */\n private readonly tails = new Map<string, Set<(event: EngineEvent) => void>>();\n private tailing = false;\n\n constructor(private readonly options: FederatedAppGatewayOptions) {\n // An engine over the app's store with no transport and no driver: it only answers the reads\n // `StoreRunGateway` makes of it (children, lifecycle links). It starts no poller and consumes\n // nothing, so it never touches the app's runs.\n this.reads = new StoreRunGateway(options.store, new WorkflowEngine({ store: options.store }));\n this.timeoutMs = options.timeoutMs ?? 10_000;\n }\n\n topology(): DurableTopology {\n return { role: 'control-plane' };\n }\n\n getRunDetail(runId: string, options?: RunDetailOptions): Promise<RunDetail | null> {\n return this.reads.getRunDetail(runId, options);\n }\n\n getFanMembers(runId: string, group: string, query: FanPageQuery): Promise<FanPage | null> {\n return this.reads.getFanMembers(runId, group, query);\n }\n\n getRun(runId: string): Promise<WorkflowRun | null> {\n return this.reads.getRun(runId);\n }\n\n listRuns(query: RunQuery): Promise<RunListItem[]> {\n return this.reads.listRuns(query);\n }\n\n runFacets(query: RunFacetQuery): Promise<RunFacetRow[]> {\n return this.reads.runFacets(query);\n }\n\n runValueFacets(\n axis: RunValueAxis,\n query: RunFacetQuery,\n opts?: RunValueFacetOptions,\n ): Promise<RunValueFacetRow[]> {\n return this.reads.runValueFacets(axis, query, opts);\n }\n\n waitingFor(runIds: string[]): Promise<Record<string, RunWaiting>> {\n return this.reads.waitingFor(runIds);\n }\n\n workflowLifecycle(\n workflow: string,\n opts?: { namespace?: string | undefined },\n ): Promise<WorkflowLifecycleLinks> {\n return this.reads.workflowLifecycle(workflow, opts);\n }\n\n lifecycleSubscribers(\n workflow: string,\n kind: LifecycleKind,\n namespace: string,\n ): Promise<string[]> {\n return this.reads.lifecycleSubscribers(workflow, kind, namespace);\n }\n\n /** The app's worker groups, read from its broker (read-only). `[]` when the transport can't. */\n async workerHealth(): Promise<GroupHealth[]> {\n const { transport } = this.options;\n if (!transport.listWorkerGroups || !transport.groupHealth) return [];\n const groups = await transport.listWorkerGroups();\n return Promise.all(\n groups.map((group) => transport.groupHealth?.(group) as Promise<GroupHealth>),\n );\n }\n\n listSchedules(query: ScheduleListQuery): Promise<ScheduleDescription[]> {\n return this.reads.listSchedules(query);\n }\n\n getSchedule(id: string): Promise<ScheduleDescription | null> {\n return this.reads.getSchedule(id);\n }\n\n signalWaiter(token: string): Promise<string | null> {\n return this.reads.signalWaiter(token);\n }\n\n cancel(runId: string, opts?: { compensate?: boolean }): Promise<RunResult | null> {\n return this.onRun(runId, (namespace) =>\n this.request(\n namespace,\n opts === undefined ? { kind: 'cancel', runId } : { kind: 'cancel', runId, opts },\n ),\n );\n }\n\n retry(runId: string): Promise<RunResult | null> {\n return this.onRun(runId, (namespace) => this.request(namespace, { kind: 'retry', runId }));\n }\n\n continue(runId: string): Promise<RunResult | null> {\n return this.onRun(runId, (namespace) => this.request(namespace, { kind: 'continue', runId }));\n }\n\n retryWithInput(runId: string, input: unknown): Promise<{ runId: string } | null> {\n return this.onRun(runId, (namespace) =>\n this.request(namespace, { kind: 'retryWithInput', runId, input }),\n );\n }\n\n redispatchPending(runId: string): Promise<(RunResult & { redispatched: number }) | null> {\n return this.onRun(runId, (namespace) => this.request(namespace, { kind: 'redispatch', runId }));\n }\n\n async republishLifecycle(target: RepublishLifecycleTarget): Promise<RepublishLifecycleResult> {\n let namespace: string | undefined;\n if ('runId' in target) {\n const run = await this.reads.getRun(target.runId);\n if (!run) throw new Error(`run ${target.runId} not found`);\n namespace = run.namespace || 'default';\n } else {\n namespace = target.namespace;\n if (namespace === undefined) {\n throw Object.assign(\n new Error('republish by workflow needs a namespace on a federated app'),\n {\n code: 'bad-request',\n },\n );\n }\n }\n return this.request(namespace, { kind: 'republishLifecycle', target });\n }\n\n /**\n * Pause, resume or trigger one of the app's persisted schedules, executed by the app. A schedule\n * that does not exist rejects with a `ScheduleNotFoundError`, as the engine's own client does.\n */\n async scheduleAction(\n id: string,\n action: ScheduleAction,\n ): Promise<ScheduleDescription | RunResult> {\n const schedule = await this.reads.getSchedule(id);\n if (!schedule) throw scheduleNotFound(id);\n try {\n return await this.request(schedule.namespace, { kind: 'schedule', id, action });\n } catch (err) {\n if (err instanceof RunGatewayError && err.code === 'not-found') throw scheduleNotFound(id);\n throw err;\n }\n }\n\n /**\n * Deliver `payload` to the app's run waiting on `token`, by the app. Null when no run of the app\n * waits on it yet: unlike the engine's own `signal`, nothing is buffered for a later wait.\n */\n async signal(token: string, payload: unknown): Promise<RunResult | null> {\n const runId = await this.reads.signalWaiter(token);\n if (!runId) return null;\n return this.onRun(runId, (namespace) =>\n this.request(namespace, { kind: 'signal', token, payload }),\n );\n }\n\n /**\n * The app's live events for `runId`, from the control channel its engines broadcast every event on\n * (see {@link FederatedAppGatewayOptions.controlPlane}). Nothing when there is none.\n */\n subscribe(runId: string, onEvent: (event: EngineEvent) => void): () => void {\n const control = this.controlPlane();\n if (!control) return () => undefined;\n if (!this.tailing) {\n this.tailing = true;\n control.onControl((msg) => this.deliver(msg));\n }\n let listeners = this.tails.get(runId);\n if (!listeners) {\n listeners = new Set();\n this.tails.set(runId, listeners);\n }\n listeners.add(onEvent);\n return () => {\n const current = this.tails.get(runId);\n current?.delete(onEvent);\n if (current?.size === 0) this.tails.delete(runId);\n };\n }\n\n private controlPlane(): ControlPlane | undefined {\n if (this.options.controlPlane) return this.options.controlPlane;\n const candidate = this.options.transport as Partial<ControlPlane>;\n return typeof candidate.onControl === 'function'\n ? (this.options.transport as unknown as ControlPlane)\n : undefined;\n }\n\n private deliver(msg: ControlMessage): void {\n if (this.tails.size === 0) return;\n const events = msg.kind === 'event' ? [msg.event] : msg.kind === 'events' ? msg.events : [];\n for (const event of events) {\n const listeners = this.tails.get(event.runId);\n if (!listeners) continue;\n // `at` crosses the wire as a string.\n const live = { ...event, at: new Date(event.at) };\n for (const listener of listeners) listener(live);\n }\n }\n\n /** `act` with the namespace of `runId`, or null when the app has no such run. */\n private async onRun<T>(\n runId: string,\n act: (namespace: string) => Promise<T | null>,\n ): Promise<T | null> {\n const run = await this.reads.getRun(runId);\n if (!run) return null;\n return act(run.namespace || 'default');\n }\n\n /** Send `body` to the app as a run request from `namespace`, and wait for its reply. */\n private async request<T>(namespace: string, body: RunRequestKind): Promise<T> {\n const { transport, tenantToken } = this.options;\n if (!transport.dispatchRunRequest || !transport.onRunReply) {\n throw new Error(\n 'a federated app needs a transport that carries run requests (e.g. BullMQTransport)',\n );\n }\n this.listen();\n const tenant = tenantToken ? await tenantToken(namespace) : namespace;\n return new Promise<T>((resolve, reject) => {\n const requestId = globalThis.crypto.randomUUID();\n const timer = setTimeout(() => {\n this.pending.delete(requestId);\n reject(new Error(`the app did not answer ${body.kind} within ${this.timeoutMs}ms`));\n }, this.timeoutMs);\n this.pending.set(requestId, {\n resolve: (data) => resolve(data as T),\n reject,\n timer,\n });\n transport.dispatchRunRequest?.({ requestId, tenant, body })?.catch((error: unknown) => {\n const entry = this.pending.get(requestId);\n if (!entry) return;\n clearTimeout(entry.timer);\n this.pending.delete(requestId);\n entry.reject(error instanceof Error ? error : new Error(String(error)));\n });\n });\n }\n\n private listen(): void {\n if (this.listening) return;\n this.listening = true;\n this.options.transport.onRunReply?.((reply) => this.handleReply(reply));\n }\n\n private handleReply(reply: RunReply): void {\n const entry = this.pending.get(reply.requestId);\n if (!entry) return;\n clearTimeout(entry.timer);\n this.pending.delete(reply.requestId);\n if (reply.result.ok) entry.resolve(reply.result.data);\n else entry.reject(new RunGatewayError(reply.result.error.message, reply.result.error.code));\n }\n}\n\nfunction scheduleNotFound(id: string): Error {\n return Object.assign(new Error(`schedule \"${id}\" not found`), { name: 'ScheduleNotFoundError' });\n}\n\n/**\n * A `RunGateway` over another app's store (reads) and broker (actions, executed by that app), for\n * the dashboard's `federation.apps`. See {@link FederatedAppGateway}.\n */\nexport function federatedAppGateway(options: FederatedAppGatewayOptions): FederatedAppGateway {\n return new FederatedAppGateway(options);\n}\n","export * from './attributes-of';\nexport * from './context-accessor';\nexport * from './decorators';\nexport { DurableStartClient } from './durable-start-client';\nexport * from './durable-worker.module';\nexport * from './durable.module';\nexport type {\n ContractClass,\n LazyContract,\n TenantCredentialsContract,\n TenantTokenOption,\n TenantVerifierContract,\n TenantVerifierInput,\n TenantVerifierOption,\n} from './tenant-contracts';\nexport * from './entity';\nexport * from './federated-app-gateway';\nexport * from './in-app-worker';\nexport * from './proxy-run-gateway';\nexport * from './role';\nexport type { DtoClass, InferWorkflowInput, IoSchema } from './schema-parse';\nexport * from './run-request-responder';\nexport * from './step-interceptor';\nexport * from './store-run-gateway';\nexport * from './tenant-event-republisher';\nexport * from './tokens';\nexport * from './workflow.service';\n\n// Facade re-exports: the everyday `@dudousxd/nestjs-durable-core` surface a consumer touches\n// alongside this package's own decorators/module/tokens, so e.g. the `Workflow` decorator (here)\n// and `WorkflowEngine`/`WorkflowCtx` (core) no longer require importing both packages to pick up the paired symbol. Additive only —\n// re-exports only what already exists on core's public index; core's own new exports (e.g. typed\n// search-attribute helpers) are surfaced there, not duplicated here.\n//\n// Anything in core that is a CLASS — `RunGateway` and `WorkflowEngine` are both abstract classes\n// that double as their own DI token — has to be re-exported below as a VALUE. Putting one in the\n// `export type` block breaks consumers in a way neither `tsc` nor a build catches: the emitted\n// `.d.ts` rollup drops the `type` modifier, so the name type-checks as a value, while the JS\n// bundle correctly omits it — `import { RunGateway } from '@dudousxd/nestjs-durable'` compiles\n// green and is `undefined` at runtime, and `moduleRef.get(undefined)` fails only on the code path\n// that resolves it. Keep classes here, types above.\nexport type {\n AttributeFilter,\n DynamicWorkflowCtx,\n EngineEvent,\n OnErrorInput,\n InferSearchAttributes,\n RunDetail,\n RunListItem,\n RunQuery,\n RunStatus,\n RunWaiting,\n SearchAttributes,\n SearchAttributesSchema,\n StepCheckpoint,\n StepEvent,\n StepLogger,\n WorkflowCtx,\n WorkflowHandler,\n RunSchedulesOptions,\n ScheduledWorkflow,\n TenantTokenSource,\n TenantVerifier,\n VerifiedTenant,\n WorkflowRun,\n EventSubscription,\n LifecycleEventOf,\n LifecycleKind,\n OnEventEntry,\n WorkflowLifecycleEvent,\n} from '@dudousxd/nestjs-durable-core';\nexport {\n DuplicateDurableCopyError,\n hmacTenantVerifier,\n LIFECYCLE_PENDING_TAG,\n lifecycleRunId,\n lifecycleSourceOf,\n prevCronFireMs,\n readSearchAttributes,\n RunGateway,\n runCompletedEvent,\n runFailedEvent,\n runSchedules,\n scheduledRunId,\n scheduleRunIdAt,\n signTenantToken,\n triggeredRunsOf,\n WorkflowEngine,\n} from '@dudousxd/nestjs-durable-core';\n"],"mappings":";;;;AAAA,SAIEA,4BACK;;;ACLP,SAEEC,qBACAC,mBASAC,mBAKAC,eACAC,mBACAC,sBACK;AACP,OAAO;;;ACrBP,SAASC,oBAAoB;AAC7B,SAASC,SAASC,YAAY;AAC9B,SAASC,qBAAqB;AA+B9B,IAAMC,uBAAuB,oBAAIC,QAAAA;AAGjC,IAAMC,mBAAmB,oBAAIC,IAAAA;AAYtB,SAASC,cAAcC,UAAqB;AACjD,QAAMC,UAAUC,MAAMC;AACtB,MAAI,OAAOF,YAAY,WAAY,QAAOG;AAC1C,QAAMC,SAA6B,CAAC;AACpCJ,UAAQI,QAAQL,QAAAA;AAChB,SAAOM,aAAaD,OAAOE,KAAK;AAClC;AANgBR;AAST,SAASS,sBAAsBC,QAAgBC,MAAwB;AAC5E,MAAIA,KAAMf,sBAAqBgB,IAAIF,QAAQC,IAAAA;AAC7C;AAFgBF;AAWT,SAASI,cAAcH,QAAe;AAC3C,WACMI,OAAgBJ,QACpB,OAAOI,SAAS,cAAe,OAAOA,SAAS,YAAYA,SAAS,MACpEA,OAAOC,OAAOC,eAAeF,IAAAA,GAC7B;AACA,UAAMH,OAAOf,qBAAqBqB,IAAIH,IAAAA;AACtC,QAAIH,KAAM,QAAOO,eAAeP,IAAAA;EAClC;AACA,SAAON;AACT;AAVgBQ;AAkBT,SAASM,iBA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AIuB,SAAAA;AAC/B,YAAI,CAACS,MAAO;AACZC,qBAAaD,MAAML,KAAK;AACxB,aAAKtG,QAAQgF,OAAOkB,SAAAA;AACpBS,cAAMV,OAAOS,iBAAiBnD,QAAQmD,QAAQ,IAAInD,MAAMsD,OAAOH,KAAAA,CAAAA,CAAAA;MACjE,CAAA;IACF,CAAA;EACF;EAEQZ,SAAe;AACrB,QAAI,KAAK5F,UAAW;AACpB,SAAKA,YAAY;AACjB,SAAKI,QAAQyB,UAAU8D,aAAa,CAACiB,UAAU,KAAKC,YAAYD,KAAAA,CAAAA;EAClE;EAEQC,YAAYD,OAAuB;AACzC,UAAMH,QAAQ,KAAK3G,QAAQ2E,IAAImC,MAAMZ,SAAS;AAC9C,QAAI,CAACS,MAAO;AACZC,iBAAaD,MAAML,KAAK;AACxB,SAAKtG,QAAQgF,OAAO8B,MAAMZ,SAAS;AACnC,QAAIY,MAAME,OAAOC,GAAIN,OAAMX,QAAQc,MAAME,OAAOR,IAAI;QAC/CG,OAAMV,OAAO,IAAIjC,gBAAgB8C,MAAME,OAAON,MAAMQ,SAASJ,MAAME,OAAON,MAAMhD,IAAI,CAAA;EAC3F;AACF;AAEA,SAASI,iBAAiBtB,IAAU;AAClC,SAAOgB,OAAOC,OAAO,IAAIF,MAAM,aAAaf,EAAAA,aAAe,GAAG;IAAE2E,MAAM;EAAwB,CAAA;AAChG;AAFSrD;AAQF,SAASsD,oBAAoB9G,SAAmC;AACrE,SAAO,IAAIR,oBAAoBQ,OAAAA;AACjC;AAFgB8G;;;AClShB,SACEC,2BACAC,oBACAC,uBACAC,gBACAC,qBAAAA,oBACAC,gBACAC,wBAAAA,uBACAC,cAAAA,aACAC,qBAAAA,oBACAC,kBAAAA,iBACAC,gBAAAA,eACAC,gBACAC,iBACAC,iBACAC,iBACAC,kBAAAA,uBACK;","names":["readSearchAttributes","DURABLE_STEP_CONFIG","DURABLE_STEP_NAME","WORKFLOW_NAME_KEY","parseDuration","runCompletedEvent","runFailedEvent","readFileSync","dirname","join","fileURLToPath","declaringFileByClass","WeakMap","packageNameByDir","Map","declaringFile","boundary","capture","Error","captureStackTrace","undefined","holder","topFrameFile","stack","rememberDeclaringFile","target","file","set","originOfClass","ctor","Object","getPrototypeOf","get","packageNameFor","originOfProvider","wrapper","fromMetatype","metatype","instance","start","dirname","visited","dir","has","cached","seen","push","name","readPackageName","join","parent","path","raw","readFileSync","parsed","JSON","parse","isRecord","length","value","line","split","frame","trim","startsWith","fileOfFrame","slice","match","exec","location","fileURLToPath","absolute","test","WORKFLOW_METADATA","Symbol","Workflow","options","declaredIn","declaringFile","target","rememberDeclaringFile","meta","name","version","deadLetterWorkflow","onError","tags","singleton","concurrency","executionTimeout","input","output","validateInput","searchAttributes","onEvent","debounce","batch","requires","Reflect","defineMetadata","Object","defineProperty","WORKFLOW_NAME_KEY","value","configurable","getWorkflowMeta","getMetadata","DURABLE_STEP_METADATA","stepConfigFrom","config","retries","backoff","backoffMs","backoffMaxMs","jitter","timeoutMs","hasAnyField","values","some","undefined","Step","nameOrOptions","propertyKey","descriptor","derivedName","String","DURABLE_STEP_NAME","DURABLE_STEP_CONFIG","getDurableStepMeta","method","DEAD_LETTER_METADATA","DeadLetter","_target","_propertyKey","isDeadLetterHandler","ON_ERROR_METADATA","OnError","match","code","Error","codes","onErrorCodesOf","ON_EVENT_METADATA","OnDurableEvent","events","addEventSubscriptions","OnWorkflowCompleted","workflow","onWorkflowSettled","runCompletedEvent","where","OnWorkflowFailed","statuses","accepts","event","includes","status","runFailedEvent","ON_EVENT_BATCH_METADATA","subscription","subscriberEventBatch","existing","sameEventBatch","mode","windowMs","parseDuration","key","maxSize","a","b","toString","eventBatchOf","declared","within","fromSubscription","entries","getOnEvents","fromDecorator","names","Set","filter","entry","has","add","attributesOf","workflow","run","meta","getWorkflowMeta","Error","name","searchAttributes","readSearchAttributes","acceptingSubscription","resolveConcurrency","resolveTenantToken","toEventSubscription","workflowName","Injectable","AsyncLocalStorage","SLOT","Symbol","for","accessorOf","accessor","slot","globalThis","current","undefined","readTenancy","option","a","tenancy","tenantFilter","enabled","own","inherit","options","kinds","family","required","bind","nullRows","filter","Object","keys","length","durableWork","AsyncLocalStorage","inDurableWork","fn","getStore","run","readTenancy","option","accessor","own","effective","required","readContextTenancy","isTenantRuntime","x","withTenant","TENANCY_SLOT","Symbol","for","tenancySlot","slot","globalThis","version","undefined","restorer","runtime","restore","tenant","family","ref","id","kind","source","buildEngineTenancy","current","t","enabled","f","filter","mode","tenantFilterNow","using","system","tenantId","nullRows","tenantFromCarrier","carrier","stepTenantWrapper","execution","next","unit","context","canRestoreTenant","currentTenant","RESOLVED","Symbol","markResolved","fn","Object","defineProperty","value","isResolved","isClass","method","proto","prototype","test","Function","toString","call","hasMethod","lazyDefault","undefined","target","default","instanceFactory","Class","moduleRef","pending","registered","get","strict","create","cause","Error","name","catch","contractInstance","instance","Promise","resolve","functionOrLazy","lazy","plain","probing","args","contract","result","probe","resolveTenantVerifier","option","input","verify","probed","requireToken","token","length","resolveTenantTokenSource","workerSdk","cause","Error","startRun","connection","options","runRedisWorker","createWorkerRuntime","DurableWorkerRuntime","Runtime","DurableStartClient","tenant","tenantToken","policies","Map","warnedCoalescing","Set","options","deps","accessor","requests","partition","resolveTenantTokenSource","declareWorkflow","workflow","policy","set","applyPolicy","input","opts","get","concurrency","undefined","keyInput","parseInput","validateInput","resolveConcurrency","singleton","key","limit","maxQueueDepth","wireTenant","resolveTenantToken","claimedTenant","tenantId","id","tenantKind","kind","currentTenant","tenancy","start","runId","globalThis","crypto","randomUUID","message","startMessage","workflowName","startRun","connection","prefix","startAtMs","startAt","status","Number","isFinite","Date","now","name","getTime","tags","searchAttributes","version","priority","runRequests","method","Error","signal","token","payload","signalWithStart","result","publishEvent","eventId","started","subscriptions","onEvent","map","toEventSubscription","filter","sub","event","accepted","errors","acceptingSubscription","length","coalesces","has","add","console","warn","error","resumed","cancel","_runId","tenantUnsupported","deleteRun","resume","waitForRun","_opts","Promise","reject","DURABLE_OPTIONS_CANONICAL","WorkflowEngine","bindWorkflowClass","resolveTenantToken","workflowName","Inject","Injectable","DiscoveryService","MetadataScanner","SchemaValidationError","schemaParser","schema","kind","label","code","isStandardSchema","value","result","validate","issues","SchemaValidationError","isZodLike","safeParse","success","error","data","classValidatorParser","Error","cls","cv","ct","Array","isArray","got","message","instance","plainToInstance","errors","whitelist","length","map","e","Object","values","constraints","_","property","join","path","String","summary","i","scanWorkflows","discovery","register","wrapper","getProviders","instance","meta","getWorkflowMeta","workflow","run","Error","name","originOfProvider","scanSteps","scanner","prototype","Object","getPrototypeOf","methodName","getAllMethodNames","method","getDurableStepMeta","boundMethod","parseInput","input","schemaParser","parseOutput","output","handler","log","validInput","call","WorkflowEngine","Injectable","ENTITY_METADATA","Symbol","ENTITY_ON_METADATA","Entity","options","target","Reflect","defineMetadata","On","op","propertyKey","ctor","ops","getMetadata","Map","set","getEntityMeta","entityConfigFor","Cls","handlers","method","state","arg","Object","setPrototypeOf","prototype","fn","Error","call","initialState","EntityService","engine","signal","name","key","signalEntity","getState","getEntityState","parseDuration","workflowName","onErrorHandlersOf","meta","instance","scanner","handlers","routes","methodName","getAllMethodNames","Object","getPrototypeOf","method","codes","onErrorCodesOf","undefined","name","push","ctx","input","call","code","workflow","r","onError","workflowName","workflowIo","meta","parseInput","input","schemaParser","name","parseOutput","output","validateInput","undefined","validateParsed","wrap","body","ctx","registerOnRuntime","runtime","scanner","meta","instance","origin","deadLetter","handlers","routes","onErrorHandlersOf","announced","version","undefined","body","workflowIo","wrap","ctx","input","run","subscribes","Set","getOnEvents","map","entry","event","registerWorkflow","name","requires","length","onError","code","workflow","announcedOptions","fn","options","tags","executionTimeout","executionTimeoutMs","parseDuration","singleton","limit","maxQueueDepth","Object","keys","STEP_INTERCEPTOR_METADATA","Symbol","StepInterceptor","target","Reflect","defineMetadata","isStepInterceptor","getMetadata","RunGateway","CONTEXT_ACCESSOR","Symbol","for","TENANT_AUTH","RUN_GATEWAY","deadLetterHandlerOf","instance","scanner","name","getAllMethodNames","Object","getPrototypeOf","method","isDeadLetterHandler","ctx","input","call","undefined","RUN_REDIS_WORKER","Symbol","DURABLE_WORKER_RUNTIME","DURABLE_WORKER_RUNNERS","isPureThinWorker","options","store","connection","ThinWorkflowRegistrar","discovery","metadataScanner","runtime","starter","onModuleInit","assertNoEntities","useInterceptors","fallback","deadLetterWorkflow","workflowName","scanWorkflows","meta","origin","inline","Error","deadLetter","registerOnRuntime","registerWorkflow","version","declare","declareWorkflow","io","workflowIo","policy","validateInput","validateParsed","parseInput","singleton","concurrency","onEvent","getOnEvents","coalesces","eventBatchOf","bindWorkflowClass","start","runId","opts","entities","getProviders","map","w","filter","i","getEntityMeta","length","join","wrapper","isStepInterceptor","interceptor","use","console","warn","invocation","next","intercept","ThinStepRegistrar","scanSteps","handler","registerStep","ThinWorkerBootstrap","runners","runRedisWorker","runnersSink","auth","onApplicationBootstrap","consumers","schedules","handle","partition","prefix","instanceId","tenantScheduleAnnouncement","tenantToken","push","onApplicationShutdown","Promise","allSettled","h","close","tenant","resolveTenantToken","error","message","String","items","all","announcedSchedule","scheduleKeyInput","s","item","key","workflow","everyMs","cron","timezone","paused","overlap","jitter","jitterMs","getWorkflowMeta","limit","maxQueueDepth","thinWorkerProviders","provide","useFactory","createWorkerRuntime","workflowGroup","inject","DURABLE_OPTIONS_CANONICAL","useValue","defaultRunRedisWorker","tenantGatewayUnavailable","reject","unavailableRunGateway","topology","role","getRunDetail","_runId","listRuns","_query","runFacets","runValueFacets","_axis","_opts","waitingFor","_runIds","workerHealth","cancel","retry","continue","retryWithInput","_input","redispatchPending","subscribe","_onEvent","DURABLE_OPTIONS","DURABLE_OPTIONS_CANONICAL","RunGateway","STATE_STORE","STATE_STORE_CANONICAL","TRANSPORT","TRANSPORT_CANONICAL","WorkflowEngine","sealDurableCopies","useDurableExecution","Inject","Injectable","Module","DiscoveryModule","ModuleRef","DURABLE_OPTIONS_CANONICAL","TRANSPORT_CANONICAL","Inject","Injectable","DiscoveryService","MetadataScanner","isOperatorRole","options","store","undefined","isDrivingOperator","drive","supportsHandle","transport","handle","DurableStepRegistrar","discovery","metadataScanner","options","onModuleInit","isDrivingOperator","scanSteps","meta","handler","name","partition","DURABLE_OPTIONS_CANONICAL","TRANSPORT_CANONICAL","Inject","Injectable","DiscoveryService","MetadataScanner","IN_APP_WORKER_BINDING","Symbol","IN_APP_WORKER_RUNTIME","IN_APP_RUN_REDIS_WORKER","IN_APP_WORKER_RUNNERS","isCoLocatedWorker","options","store","undefined","connection","inAppWorkerBinding","transport","dispatchWorkflowTask","onDecision","Error","partition","InAppWorkerBootstrap","runners","discovery","metadataScanner","runtime","runRedisWorker","runnersSink","onModuleInit","scanWorkflows","meta","instance","origin","registerOnRuntime","scanSteps","handler","registerStep","name","onApplicationBootstrap","consumers","handle","prefix","instanceId","concurrency","push","onApplicationShutdown","Promise","allSettled","map","close","inAppWorkerProviders","provide","useFactory","inject","TRANSPORT_CANONICAL","DURABLE_OPTIONS_CANONICAL","createWorkerRuntime","workflowGroup","useValue","defaultRunRedisWorker","SUMMARY_CHILD_LIMIT","childIdsOf","pageFan","resolveTenantToken","scopeTenantQuery","summarizeTimeline","tenantVisible","Injectable","grantsClientTenant","lifecycleKindOf","verifyWireTenant","UNSUPPORTED_RUN_REQUEST","BAD_RUN_REQUEST","TENANT_REPUBLISH_MAX_LIMIT","KNOWN_KINDS","Set","wireDate","value","undefined","date","Date","Number","isNaN","getTime","Error","String","scopeRunLinks","detail","tenant","own","link","namespace","bare","status","_status","_namespace","rest","awaitedBy","filter","_awaitedBy","source","triggeredBy","runId","kind","length","waitsFor","map","lifecycleDeliveries","RunRequestResponder","verifyTenant","transport","gateway","options","warnWithoutVerifier","console","warn","start","onRunRequest","msg","reply","handle","err","requestId","result","ok","error","message","publishRunReply","wire","verified","verifyWireTenant","code","body","has","unsupported","data","listRuns","query","runFacets","runValueFacets","axis","opts","all","workerHealth","h","group","endsWith","workflowLifecycle","workflow","target","republishLifecycle","since","until","limit","isSafeInteger","badRequest","JSON","stringify","refused","refuseSubscriber","subscriber","Math","min","waitingFor","runIds","owned","Promise","Object","entries","waiting","owner","getRun","getRunDetail","run","entry","getSchedule","scheduleAction","action","schedule","call","id","answer","signal","signalWaiter","waiterRunId","token","waiter","runOf","payload","signalWithStart","publishEventForTenant","name","runIdOf","scopeLifecycle","getFanMembers","lifecycleKindOf","callVerb","signalWithStartForTenant","crossTenant","existing","claim","tenantId","grantsClientTenant","tenantKind","input","lifecycleSubscribers","_links","_subscribers","links","subscribers","startsOnSettle","l","linked","startedBy","kinds","subscribes","k","includes","some","events","reject","cancel","retry","continue","retryWithInput","redispatchPending","RunGatewayError","Error","code","message","name","unsupportedVerb","kind","UNSUPPORTED_RUN_REQUEST","UnsupportedRunRequestError","isUnsupported","err","ProxyRunGateway","pending","Map","unsupportedUntil","transport","tenant","timeoutMs","capabilityTtlMs","tenantToken","tenantFilter","onRunReply","reply","handleReply","restrictive","filter","mode","undefined","scoped","query","send","Promise","reject","scopeTenantQuery","visible","run","tenantVisible","guarded","runId","call","hidden","then","getRunUnscoped","get","requestId","clearTimeout","timer","delete","result","ok","resolve","data","error","request","body","source","resolveTenantToken","globalThis","crypto","randomUUID","setTimeout","set","dispatchRunRequest","catch","stillPending","String","topology","role","getRunDetail","options","detail","over","summarizeFansOver","fans","timeline","summarizeTimeline","ids","childIdsOf","children","slice","SUMMARY_CHILD_LIMIT","childCount","length","getFanMembers","group","knownUnsupported","page","Date","now","pageFan","getRun","until","listRuns","q","runFacets","runValueFacets","axis","opts","workerHealth","waitingFor","runIds","cancel","retry","continue","retryWithInput","input","redispatchPending","republishLifecycle","target","requestNewVerb","workflowLifecycle","workflow","notSupported","signal","token","payload","signalWithStart","start","publishEvent","id","subscribe","onEvent","unsubscribe","onTenantEvent","evt","event","DURABLE_OPTIONS_CANONICAL","STATE_STORE_CANONICAL","TERMINAL_RUN_STATUSES","parseDuration","Inject","Injectable","Optional","settleWithin","p","timeoutMs","timer","timedOut","timeout","Promise","resolve","setTimeout","unref","race","then","undefined","clearTimeout","DURABLE_OPTIONS_CANONICAL","Inject","Injectable","Logger","Optional","ModuleRef","SweepLeases","logger","Logger","locks","leases","Map","moduleRef","options","run","sweep","fn","holds","undefined","get","held","delete","lock","acquire","key","error","warn","String","set","ns","namespace","onModuleInit","detect","log","specifier","mod","Locks","strict","DEFAULT_SWEEP_INTERVAL_MS","DEFAULT_BATCH_SIZE","MAX_BATCHES_PER_POLICY","validateRetention","retention","seen","Set","policy","policies","scopeKey","scope","stableKey","statuses","length","Error","maxAge","maxCount","parseDuration","status","TERMINAL_RUN_STATUSES","includes","join","key","has","add","value","Array","isArray","map","entries","Object","filter","v","undefined","sort","a","b","localeCompare","k","JSON","stringify","RetentionPoller","timer","sweeping","stopping","current","store","options","leases","SweepLeases","requireStore","onApplicationBootstrap","isDrivingOperator","pruneTerminalRuns","console","warn","sweep","intervalMs","sweepInterval","setInterval","unref","onModuleDestroy","clearInterval","budget","shutdownTimeoutMs","settleWithin","Promise","resolve","run","sweepOnce","finally","prune","error","batchSize","now","Date","batch","deleted","call","LIFECYCLE_REGISTRY_WORKFLOW","STATE_STORE_CANONICAL","SUMMARY_CHILD_LIMIT","WorkflowEngine","aggregatesCheckpoints","childIdsOf","etagMatches","extendEtag","fanPageEtag","indexWaitersByRun","lifecycleDeliveriesOf","lifecycleKindOf","lifecycleSourceOf","lifecycleTraceparentOf","listSignalWaitersOfRuns","mergeRunFacetRows","pageFan","pageFanFromStore","readRunsByIds","resolveRunWaiting","runDetailEtag","runWaitPrefix","runWaitTargetOf","summarizeRunFromStore","summarizeTimeline","traceIdOfTraceparent","Inject","Injectable","detailExtras","links","lifecycleSubscribers","lifecycleDeliveries","waitsFor","awaitedBy","triggeredBy","undefined","withoutRegistry","query","workflow","LIFECYCLE_REGISTRY_WORKFLOW","workflows","includes","excludeWorkflows","StoreRunGateway","store","engine","topology","role","scoped","scopeRunQuery","visibleRun","runId","run","getRun","tenantIds","tenantId","getRunDetail","options","lifecycleLinks","over","summarizeFansOver","timeline","children","Promise","all","listCheckpoints","getRunChildren","aggregatesCheckpoints","stats","checkpointStats","etag","extendEtag","runDetailEtag","etagMatches","ifNoneMatch","notModified","summarizeRunFromStore","full","fans","summarizeTimeline","ids","childIdsOf","slice","SUMMARY_CHILD_LIMIT","childCount","length","triggered","triggeredRuns","source","lifecycleSourceOf","kind","lifecycleKindOf","status","subscribers","namespace","workflowLifecycle","linked","startsOnSettle","startedBy","deliveries","lifecycleDeliveriesOf","live","Set","coalesced","coalescedSubscribers","own","onIt","listSignalWaitersOfRuns","id","startsWith","listSignalWaiters","runWaitPrefix","flatMap","w","target","runWaitTargetOf","seq","filter","map","started","d","state","runs","readRunsByIds","l","withRun","link","other","get","sourceRun","traceId","traceIdOfTraceparent","lifecycleTraceparentOf","tags","opts","getFanMembers","group","fanPageEtag","items","total","pageFanFromStore","pageFan","listRuns","waiterByRun","indexWaitersByRun","waiting","resolveRunWaiting","runFacets","mergeRunFacetRows","r","origin","count","runValueFacets","axis","waitingFor","runIds","idSet","suspended","waiters","statuses","result","has","workerHealth","cancel","retry","requeue","continue","retryWithInput","input","redispatchPending","republishLifecycle","listSchedules","schedules","supported","list","getSchedule","scheduleAction","action","pause","resume","trigger","reject","Error","String","signal","token","payload","signalWithStartForTenant","start","clientTenant","publishEventForTenant","name","signalWaiter","waiter","find","subscribe","onEvent","event","visible","held","checking","check","then","finally","pending","off","push","isTerminalRunEvent","event","type","TenantEventRepublisher","runNamespaces","Map","store","publish","handle","namespace","namespaceFor","delete","runId","tenant","catch","undefined","has","cached","get","set","run","getRun","tenantNamespace","durableCore","ANNOUNCED_SCHEDULE_TAG","DURABLE_OPTIONS_CANONICAL","WorkflowEngine","runSchedules","workflowName","Inject","Injectable","Optional","SWEEP_FAILED","Symbol","nextScheduleFireAt","TimerPoller","timer","polling","current","unsubscribeEnqueued","unsubscribeEvents","stopped","activity","endWait","owedSweptAt","announcedSyncedAt","engine","options","leases","SweepLeases","onApplicationBootstrap","s","schedules","workflowName","workflow","isDrivingOperator","consumeRuns","onEnqueued","runId","noteActivity","runEnqueued","runOne","catch","error","console","intervalMs","timerPollMs","maxIdleMs","maxIdleIntervalMs","canBackOff","subscribe","loop","poll","setInterval","unref","idleBackoffSupported","nextDueAt","length","undefined","wait","arrived","worked","idle","Math","min","next","untilDue","Promise","resolve","done","clearTimeout","setTimeout","now","Date","stored","persistedSchedules","announcedSchedules","scheduled","due","at","max","option","syncAnnouncedSchedules","supported","settings","syncMs","graceMs","owedSweepDue","every","owedLifecycleSweepMs","last","onModuleDestroy","clearInterval","beginDrain","budget","shutdownTimeoutMs","started","timedOut","settleWithin","warn","run","pollOnce","finally","note","result","Array","isArray","sweep","runPending","recoverIncomplete","resumeDueTimers","sweepTimeouts","sweepStalled","sweepBufferedSignals","sweepExpiredSignalIds","owed","published","sweepLifecycleEvents","runSchedules","announced","tick","tag","ANNOUNCED_SCHEDULE_TAG","name","DURABLE_OPTIONS_CANONICAL","RemoteWorkflowExecutor","STATE_STORE_CANONICAL","WorkflowEngine","bindWorkflowClass","sanitizeQueueToken","tenantGroup","workflowName","Inject","Injectable","DiscoveryService","MetadataScanner","UNSERVED_ROUTES_RECHECK_MS","WorkflowRegistrar","discovery","metadataScanner","engine","store","options","inAppWorker","onApplicationBootstrap","isDrivingOperator","recoverIncomplete","onApplicationShutdown","isOperatorRole","drain","shutdownTimeoutMs","transports","transport","map","t","Promise","allSettled","close","onModuleInit","Error","autoSchema","ensureSchema","deadLetterByWorkflow","Map","wrapper","getProviders","instance","isStepInterceptor","interceptor","use","invocation","next","intercept","entityMeta","getEntityMeta","registerEntity","name","entityConfigFor","unattributed","scanWorkflows","meta","workflow","origin","undefined","push","io","workflowIo","body","wrap","ctx","input","run","workflowCtor","eventBatch","eventBatchOf","onError","onErrorHandlersOf","fn","handlers","register","version","tags","singleton","concurrency","executionTimeout","requires","validateInput","validateParsed","parseInput","searchAttributesSchema","searchAttributes","onEvent","getOnEvents","routes","group","tenantGroup","sanitizeQueueToken","partition","executor","RemoteWorkflowExecutor","bindWorkflowClass","start","runId","opts","waitForRun","inline","findDeadLetterHandler","deadLetterWorkflow","dlqName","set","workflowName","reportUnattributed","reportUnservedOnErrorRoutes","installDeadLetterRouting","names","length","console","warn","join","recheckMs","unservedOnErrorRoutes","catch","resolve","setTimeout","unref","unserved","list","route","code","prototype","Object","getPrototypeOf","methodName","getAllMethodNames","method","isDeadLetterHandler","call","byWorkflow","fallback","size","onDead","routeDead","target","get","announcedDeadLetter","deadRunId","id","error","namespace","randomUUID","WorkflowEngine","Injectable","WorkflowService","engine","start","workflow","input","runId","randomUUID","opts","resume","waitForRun","signal","token","payload","signalWithStart","publishEvent","name","triggeredRuns","republishLifecycle","target","resolveAccessor","moduleRef","get","CONTEXT_ACCESSOR","strict","undefined","carrierFromAccessor","accessor","carrier","traceId","tenantId","tenant","source","userRef","contextSlotPresent","slot","globalThis","Symbol","for","current","isContextRuntime","x","deserialize","resolveContextRuntime","specifier","mod","Context","isControlPlane","publishControl","onControl","isScopeableStore","store","withScope","scopedStore","options","scopeReads","namespace","deferTransportConsumers","transport","deferrable","deferConsumers","console","warn","name","assertValidRole","hasStore","hasConnection","connection","Error","transports","TOPOLOGIES","assertValidTopology","topology","includes","hint","JSON","stringify","tenantToken","partition","length","verifyTenant","resolveTopology","servingPartition","resolveTopologyPreset","RunGatewayBootstrap","unsubscribe","engine","gateway","auth","onApplicationBootstrap","isDrivingOperator","onRunRequest","publishRunReply","publishTenantEvent","runRequestTransport","bind","RunRequestResponder","warnWithoutVerifier","start","republisher","TenantEventRepublisher","subscribe","event","handle","catch","onModuleDestroy","DurableTenancyBridge","unregister","tenancy","readTenancy","enabled","runtime","canRestoreTenant","useDurableExecution","stepTenantWrapper","isTenantRuntime","DurableModule","forRoot","sealDurableCopies","assertValid","build","provide","DURABLE_OPTIONS_CANONICAL","useValue","forRootAsync","useFactory","args","resolved","inject","optionsProvider","module","global","imports","DiscoveryModule","providers","STATE_STORE_CANONICAL","TRANSPORT_CANONICAL","TENANT_AUTH","resolveTenantVerifier","resolveTenantTokenSource","ModuleRef","STATE_STORE","useExisting","TRANSPORT","DURABLE_OPTIONS","WorkflowEngine","DurableStartClient","RunGateway","ProxyRunGateway","primary","context","runtimeNeeded","rehydrate","fn","Object","keys","consumers","t","map","n","controlPlane","leaseMs","admission","maxRecoveryAttempts","unregisteredWorkflowGraceMs","remoteAdvanceSilenceMs","remoteRedispatchMs","remoteRedispatchMax","reconcileMs","stalledAfterMs","timerBatchSize","eventBufferTtlMs","signalIdTtl","blockedPollMs","workerDescriptorCacheMs","trackStepStart","stickyRuns","stickyIdleMs","routeReplies","instanceId","webhookUrl","traceparent","buildEngineTenancy","compensationRetries","runDispatcher","drive","dispatch","queue","queues","registerQueue","onStalled","WorkflowService","EntityService","WorkflowRegistrar","DurableStepRegistrar","SweepLeases","TimerPoller","RetentionPoller","StoreRunGateway","runGatewayTimeoutMs","tenantFilterNow","unavailableRunGateway","inAppWorkerProviders","thinWorkerProviders","exports","WorkflowEngine","FederatedAppGateway","reads","pending","Map","listening","timeoutMs","tails","tailing","options","StoreRunGateway","store","WorkflowEngine","topology","role","getRunDetail","runId","getFanMembers","group","query","getRun","listRuns","runFacets","runValueFacets","axis","opts","waitingFor","runIds","workflowLifecycle","workflow","lifecycleSubscribers","kind","namespace","workerHealth","transport","listWorkerGroups","groupHealth","groups","Promise","all","map","listSchedules","getSchedule","id","signalWaiter","token","cancel","onRun","request","undefined","retry","continue","retryWithInput","input","redispatchPending","republishLifecycle","target","run","Error","Object","assign","code","scheduleAction","action","schedule","scheduleNotFound","err","RunGatewayError","signal","payload","subscribe","onEvent","control","controlPlane","onControl","msg","deliver","listeners","get","Set","set","add","current","delete","size","candidate","events","event","live","at","Date","listener","act","body","tenantToken","dispatchRunRequest","onRunReply","listen","tenant","resolve","reject","requestId","globalThis","crypto","randomUUID","timer","setTimeout","data","catch","error","entry","clearTimeout","String","reply","handleReply","result","ok","message","name","federatedAppGateway","DuplicateDurableCopyError","hmacTenantVerifier","LIFECYCLE_PENDING_TAG","lifecycleRunId","lifecycleSourceOf","prevCronFireMs","readSearchAttributes","RunGateway","runCompletedEvent","runFailedEvent","runSchedules","scheduledRunId","scheduleRunIdAt","signTenantToken","triggeredRunsOf","WorkflowEngine"]}
|