@temporal-contract/worker 1.0.0 → 2.1.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/README.md +18 -21
- package/dist/activity.cjs +18 -24
- package/dist/activity.d.cts +29 -35
- package/dist/activity.d.cts.map +1 -1
- package/dist/activity.d.mts +30 -36
- package/dist/activity.d.mts.map +1 -1
- package/dist/activity.mjs +18 -24
- package/dist/activity.mjs.map +1 -1
- package/dist/{errors-CG1y7SHO.d.cts → errors-DTq5OTwH.d.cts} +69 -10
- package/dist/{errors-CG1y7SHO.d.cts.map → errors-DTq5OTwH.d.cts.map} +1 -1
- package/dist/{errors-DZhaNhwr.d.mts → errors-DbPMxULo.d.mts} +69 -10
- package/dist/{errors-DZhaNhwr.d.mts.map → errors-DbPMxULo.d.mts.map} +1 -1
- package/dist/{internal-BoNcEtYh.mjs → internal-BzG1KhEK.mjs} +132 -54
- package/dist/internal-BzG1KhEK.mjs.map +1 -0
- package/dist/{internal-Tj4m4f_K.cjs → internal-Cwch3OHR.cjs} +156 -60
- package/dist/worker.d.mts +1 -1
- package/dist/workflow.cjs +185 -133
- package/dist/workflow.d.cts +94 -81
- package/dist/workflow.d.cts.map +1 -1
- package/dist/workflow.d.mts +94 -80
- package/dist/workflow.d.mts.map +1 -1
- package/dist/workflow.mjs +183 -134
- package/dist/workflow.mjs.map +1 -1
- package/package.json +14 -14
- package/dist/internal-BoNcEtYh.mjs.map +0 -1
package/dist/workflow.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow.mjs","names":[],"sources":["../src/cancellation.ts","../src/handlers.ts","../src/workflow.ts"],"sourcesContent":["/**\n * Typed wrappers around Temporal's `CancellationScope` so workflows can\n * opt into cancellation control without reaching for\n * `@temporalio/workflow` directly. The wrappers fold cancellation into\n * the same `Future<Result<...>>` shape used elsewhere in the worker\n * context — callers branch on `Result.Error(WorkflowCancelledError)`\n * instead of catching `CancelledFailure`.\n *\n * Non-cancellation errors thrown inside the scope are *not* swallowed:\n * the Future rejects with the original error so user-domain failures\n * keep their identity.\n */\nimport { CancellationScope, isCancellation } from \"@temporalio/workflow\";\nimport { Future, Result } from \"@temporal-contract/boxed\";\nimport { WorkflowCancelledError } from \"./errors.js\";\n\n/**\n * Run `fn` inside a cancellable Temporal scope. If the workflow (or an\n * ancestor scope) is cancelled while the function is in flight, the\n * resulting Future resolves to `Result.Error(WorkflowCancelledError)`,\n * letting callers handle cancellation explicitly — typically to perform\n * a graceful exit from the current step.\n *\n * @example\n * ```ts\n * const result = await context.cancellableScope(async () => {\n * return await context.activities.processStep(...);\n * });\n *\n * result.match({\n * Ok: (output) => { ... },\n * Error: (err) => {\n * // err instanceof WorkflowCancelledError — graceful exit\n * },\n * });\n * ```\n */\nexport function cancellableScope<T>(\n fn: () => T | Promise<T>,\n): Future<Result<T, WorkflowCancelledError>> {\n return Future.fromAsync(async () => {\n try {\n // Wrap so synchronous returns satisfy CancellationScope.cancellable's\n // `() => Promise<T>` signature without forcing every caller to write\n // `async () => ...` for purely synchronous bodies.\n const value = await CancellationScope.cancellable(async () => fn());\n return Result.Ok(value);\n } catch (error) {\n if (isCancellation(error)) {\n return Result.Error(new WorkflowCancelledError(error));\n }\n throw error;\n }\n });\n}\n\n/**\n * Run `fn` inside a non-cancellable Temporal scope. Cancellation requests\n * from outside the scope are ignored for its duration — the idiomatic way\n * to perform cleanup that must not be interrupted (e.g. releasing a\n * resource after a graceful shutdown).\n *\n * Mirrors `cancellableScope`'s `Future<Result<...>>` shape for symmetry;\n * the `Result.Error` branch only triggers when cancellation is raised\n * from inside the scope (rare).\n *\n * @example\n * ```ts\n * await context.nonCancellableScope(async () => {\n * await context.activities.releaseResources(...);\n * });\n * ```\n */\nexport function nonCancellableScope<T>(\n fn: () => T | Promise<T>,\n): Future<Result<T, WorkflowCancelledError>> {\n return Future.fromAsync(async () => {\n try {\n const value = await CancellationScope.nonCancellable(async () => fn());\n return Result.Ok(value);\n } catch (error) {\n if (isCancellation(error)) {\n return Result.Error(new WorkflowCancelledError(error));\n }\n throw error;\n }\n });\n}\n","// Top-level helpers for binding signal / query / update handlers to a\n// running workflow. Previously nested inside `declareWorkflow`'s closure\n// (#185), they're hoisted here so the bodies aren't reallocated on each\n// workflow invocation. The typed call-site surface is preserved at the\n// context-assignment site in `workflow.ts` (the arrow that forwards into\n// these helpers carries the contract-derived generic constraints).\n//\n// Internally these are loosely typed (string names, broad `*Definition`\n// inputs); the call sites already do the cast against the typed\n// `WorkflowContext` shape, so the typed-vs-runtime split is the same as\n// it was before the hoist.\nimport type {\n QueryDefinition,\n SignalDefinition,\n UpdateDefinition,\n WorkflowDefinition,\n} from \"@temporal-contract/contract\";\nimport { defineQuery, defineSignal, defineUpdate, setHandler } from \"@temporalio/workflow\";\nimport {\n QueryInputValidationError,\n QueryOutputValidationError,\n SignalInputValidationError,\n UpdateInputValidationError,\n UpdateOutputValidationError,\n} from \"./errors.js\";\nimport { extractHandlerInput } from \"./internal.js\";\nimport type { WorkerInferInput, WorkerInferOutput } from \"./types.js\";\n\n/**\n * Signal handler implementation\n *\n * Processes signal input and can optionally perform asynchronous operations.\n * Should not return a value (signals are fire-and-forget).\n */\nexport type SignalHandlerImplementation<TSignal extends SignalDefinition> = (\n args: WorkerInferInput<TSignal>,\n) => void | Promise<void>;\n\n/**\n * Query handler implementation\n *\n * Processes query input and returns a synchronous response.\n * Must be synchronous to satisfy Temporal's query constraints.\n */\nexport type QueryHandlerImplementation<TQuery extends QueryDefinition> = (\n args: WorkerInferInput<TQuery>,\n) => WorkerInferOutput<TQuery>;\n\n/**\n * Update handler implementation\n *\n * Processes update input and returns a validated response after modifying workflow state.\n * Can perform asynchronous operations.\n */\nexport type UpdateHandlerImplementation<TUpdate extends UpdateDefinition> = (\n args: WorkerInferInput<TUpdate>,\n) => Promise<WorkerInferOutput<TUpdate>>;\n\n/**\n * Bind a typed signal handler to the running workflow. Validates the\n * signal payload against the contract's input schema before invoking the\n * user-supplied handler.\n *\n * The runtime guard against a missing `signals` block — and an unknown\n * signal name within it — covers the union-typed-`workflowName` case\n * where the type system's keyset constraint collapses; without the\n * check, a caller would see `Cannot read properties of undefined`\n * instead of a controlled error.\n */\nexport function bindSignalHandler(\n workflowDefinition: WorkflowDefinition,\n workflowName: string,\n signalName: string,\n handler: SignalHandlerImplementation<SignalDefinition>,\n): void {\n if (!workflowDefinition.signals) {\n throw new Error(\n `Signal \"${signalName}\" cannot be defined: workflow \"${workflowName}\" has no signals in its contract`,\n );\n }\n const signalDef = (workflowDefinition.signals as Record<string, SignalDefinition>)[signalName];\n if (!signalDef) {\n throw new Error(`Signal \"${signalName}\" not found in workflow \"${workflowName}\" contract`);\n }\n\n const signal = defineSignal(signalName);\n setHandler(signal, async (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n const inputResult = await signalDef.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new SignalInputValidationError(signalName, inputResult.issues);\n }\n await handler(inputResult.value);\n });\n}\n\n/**\n * Bind a typed query handler to the running workflow. Validates input\n * and output against the contract synchronously.\n *\n * Temporal's query API requires a synchronous handler — async\n * validation breaks replay determinism. The handler trips a clear error\n * if the schema library returns a Promise from `validate(...)`, instead\n * of letting the async path silently corrupt query semantics.\n */\nexport function bindQueryHandler(\n workflowDefinition: WorkflowDefinition,\n workflowName: string,\n queryName: string,\n handler: QueryHandlerImplementation<QueryDefinition>,\n): void {\n if (!workflowDefinition.queries) {\n throw new Error(\n `Query \"${queryName}\" cannot be defined: workflow \"${workflowName}\" has no queries in its contract`,\n );\n }\n const queryDef = (workflowDefinition.queries as Record<string, QueryDefinition>)[queryName];\n if (!queryDef) {\n throw new Error(`Query \"${queryName}\" not found in workflow \"${workflowName}\" contract`);\n }\n\n const query = defineQuery(queryName);\n setHandler(query, (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n const inputResult = queryDef.input[\"~standard\"].validate(input);\n\n if (inputResult instanceof Promise) {\n throw new Error(\n `Query \"${queryName}\" validation must be synchronous. Use a schema library that supports synchronous validation for queries.`,\n );\n }\n if (inputResult.issues) {\n throw new QueryInputValidationError(queryName, inputResult.issues);\n }\n\n const result = handler(inputResult.value);\n\n const outputResult = queryDef.output[\"~standard\"].validate(result);\n if (outputResult instanceof Promise) {\n throw new Error(\n `Query \"${queryName}\" output validation must be synchronous. Use a schema library that supports synchronous validation for queries.`,\n );\n }\n if (outputResult.issues) {\n throw new QueryOutputValidationError(queryName, outputResult.issues);\n }\n\n return outputResult.value;\n });\n}\n\n/**\n * Bind a typed update handler to the running workflow. Validates both\n * input and output (asynchronously, like signals).\n */\nexport function bindUpdateHandler(\n workflowDefinition: WorkflowDefinition,\n workflowName: string,\n updateName: string,\n handler: UpdateHandlerImplementation<UpdateDefinition>,\n): void {\n if (!workflowDefinition.updates) {\n throw new Error(\n `Update \"${updateName}\" cannot be defined: workflow \"${workflowName}\" has no updates in its contract`,\n );\n }\n const updateDef = (workflowDefinition.updates as Record<string, UpdateDefinition>)[updateName];\n if (!updateDef) {\n throw new Error(`Update \"${updateName}\" not found in workflow \"${workflowName}\" contract`);\n }\n\n const update = defineUpdate(updateName);\n setHandler(update, async (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n const inputResult = await updateDef.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new UpdateInputValidationError(updateName, inputResult.issues);\n }\n\n const result = await handler(inputResult.value);\n\n const outputResult = await updateDef.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n throw new UpdateOutputValidationError(updateName, outputResult.issues);\n }\n\n return outputResult.value;\n });\n}\n","// Entry point for workflow implementations.\n//\n// Workflows run inside Temporal's deterministic sandbox, which intercepts\n// timers, randomness, and Promise scheduling for replay. We use the in-house\n// `@temporal-contract/boxed` `Result`/`Future` here because they don't reach\n// for any non-deterministic primitive. Activity code (see activity.ts) is not\n// subject to this constraint and uses `@swan-io/boxed` instead.\nimport {\n ActivityDefinition,\n ContractDefinition,\n QueryDefinition,\n SignalDefinition,\n UpdateDefinition,\n WorkflowDefinition,\n} from \"@temporal-contract/contract\";\nimport {\n ActivityInputValidationError,\n ActivityOutputValidationError,\n ChildWorkflowError,\n ChildWorkflowNotFoundError,\n WorkflowCancelledError,\n WorkflowInputValidationError,\n WorkflowOutputValidationError,\n} from \"./errors.js\";\nimport { cancellableScope, nonCancellableScope } from \"./cancellation.js\";\nimport {\n bindQueryHandler,\n bindSignalHandler,\n bindUpdateHandler,\n type QueryHandlerImplementation,\n type SignalHandlerImplementation,\n type UpdateHandlerImplementation,\n} from \"./handlers.js\";\nimport {\n ClientInferInput,\n ClientInferOutput,\n WorkerInferInput,\n WorkerInferOutput,\n} from \"./types.js\";\nimport { Future, Result } from \"@temporal-contract/boxed\";\nimport {\n buildRawActivitiesProxy,\n createContinueAsNew,\n extractHandlerInput,\n formatChildWorkflowValidationMessage,\n type TypedContinueAsNewOptions,\n} from \"./internal.js\";\nimport {\n ActivityOptions,\n ChildWorkflowHandle,\n ChildWorkflowOptions,\n executeChild,\n startChild,\n WorkflowInfo,\n workflowInfo,\n} from \"@temporalio/workflow\";\n\nexport {\n ActivityInputValidationError,\n ActivityOutputValidationError,\n ChildWorkflowError,\n ChildWorkflowNotFoundError,\n QueryInputValidationError,\n QueryOutputValidationError,\n SignalInputValidationError,\n UpdateInputValidationError,\n UpdateOutputValidationError,\n WorkflowCancelledError,\n WorkflowInputValidationError,\n WorkflowOutputValidationError,\n} from \"./errors.js\";\n\n/**\n * Create a typed workflow implementation with automatic validation\n *\n * This wraps a workflow implementation with:\n * - Input/output validation\n * - Typed workflow context with activities\n * - Workflow info access\n *\n * Workflows must be defined in separate files and imported by the Temporal Worker\n * via workflowsPath.\n *\n * @example\n * ```ts\n * // workflows/processOrder.ts\n * import { declareWorkflow } from '@temporal-contract/worker/workflow';\n * import myContract from '../contract';\n *\n * export const processOrder = declareWorkflow({\n * workflowName: 'processOrder',\n * contract: myContract,\n * activityOptions: {\n * startToCloseTimeout: '1 minute',\n * },\n * // Optional: override `activityOptions` for specific activities. Each\n * // entry shallow-merges over the workflow default — the override wins on\n * // every property it specifies, including the whole `retry` block.\n * activityOptionsByName: {\n * chargePayment: {\n * startToCloseTimeout: '5 minutes',\n * retry: { maximumAttempts: 5 },\n * },\n * },\n * implementation: async (context, args) => {\n * // context.activities: typed activities (workflow + global)\n * // context.info: WorkflowInfo\n *\n * const inventory = await context.activities.validateInventory({\n * orderId: args.orderId,\n * });\n *\n * if (!inventory.available) {\n * return { orderId: args.orderId, status: 'out_of_stock' };\n * }\n *\n * const payment = await context.activities.chargePayment({\n * customerId: args.customerId,\n * amount: 100,\n * });\n *\n * return {\n * orderId: args.orderId,\n * status: payment.success ? 'success' : 'failed',\n * transactionId: payment.transactionId,\n * };\n * },\n * });\n * ```\n *\n * Then in your worker setup:\n * ```ts\n * // worker.ts\n * import { createWorker } from '@temporal-contract/worker/worker';\n * import { activities } from './activities';\n * import myContract from './contract';\n *\n * const worker = await createWorker({\n * contract: myContract,\n * connection,\n * workflowsPath: workflowsPathFromURL(import.meta.url, './workflows.js'),\n * activities,\n * });\n * ```\n */\nexport function declareWorkflow<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"],\n>({\n workflowName,\n contract,\n implementation,\n activityOptions,\n activityOptionsByName,\n}: DeclareWorkflowOptions<TContract, TWorkflowName>): (\n ...args: unknown[]\n) => Promise<WorkerInferOutput<TContract[\"workflows\"][TWorkflowName]>> {\n // Get the workflow definition from the contract\n const definition = contract.workflows[\n workflowName as string\n ] as TContract[\"workflows\"][TWorkflowName];\n\n return async (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n\n // Validate workflow input\n const inputResult = await definition.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new WorkflowInputValidationError(String(workflowName), inputResult.issues);\n }\n const validatedInput = inputResult.value as WorkerInferInput<\n TContract[\"workflows\"][TWorkflowName]\n >;\n\n // Create activities proxy with validation if activities are defined.\n //\n // Design note — intentional double-validation:\n // Input and output are validated here (workflow side) AND again inside\n // `declareActivitiesHandler` (activity worker side). This is deliberate:\n //\n // 1. Workflow-side validation catches bad data *before* it crosses the\n // task-queue network boundary, giving an early, descriptive error\n // instead of a confusing deserialization failure inside the activity.\n // 2. Activity-side validation is the authoritative guard, since the\n // activity may be called by other callers that do not use this library.\n //\n // The overhead is minimal relative to the network round-trip.\n let contextActivities: unknown = {};\n\n if (definition.activities || contract.activities) {\n const rawActivities = buildRawActivitiesProxy(\n definition.activities,\n contract.activities,\n activityOptions,\n activityOptionsByName,\n );\n\n contextActivities = createValidatedActivities(\n rawActivities,\n definition.activities,\n contract.activities,\n );\n }\n\n // Create workflow context.\n //\n // The defineSignal / defineQuery / defineUpdate arrows forward to the\n // hoisted helpers in `./handlers.ts`. The arrows themselves are thin\n // closures that close over `definition` and `workflowName`; the heavy\n // logic — runtime guards, validation, Temporal `defineSignal/Query/\n // Update` + `setHandler` wiring — lives at module scope so it isn't\n // reallocated on each workflow invocation.\n //\n // The cast at each assignment preserves the typed call-site surface\n // (the `K extends keyof ...` constraints declared on\n // `WorkflowContext.defineSignal/Query/Update`), while the helpers\n // themselves take loosely-typed arguments at the runtime boundary.\n const context: WorkflowContext<TContract, TWorkflowName> = {\n activities: contextActivities as WorkflowInferWorkflowContextActivities<\n TContract,\n TWorkflowName\n >,\n info: workflowInfo(),\n startChildWorkflow: createStartChildWorkflow,\n executeChildWorkflow: createExecuteChildWorkflow,\n cancellableScope,\n nonCancellableScope,\n defineSignal: ((signalName, handler) =>\n bindSignalHandler(\n definition,\n String(workflowName),\n signalName as string,\n handler as unknown as SignalHandlerImplementation<SignalDefinition>,\n )) as WorkflowContext<TContract, TWorkflowName>[\"defineSignal\"],\n defineQuery: ((queryName, handler) =>\n bindQueryHandler(\n definition,\n String(workflowName),\n queryName as string,\n handler as unknown as QueryHandlerImplementation<QueryDefinition>,\n )) as WorkflowContext<TContract, TWorkflowName>[\"defineQuery\"],\n defineUpdate: ((updateName, handler) =>\n bindUpdateHandler(\n definition,\n String(workflowName),\n updateName as string,\n handler as unknown as UpdateHandlerImplementation<UpdateDefinition>,\n )) as WorkflowContext<TContract, TWorkflowName>[\"defineUpdate\"],\n continueAsNew: createContinueAsNew(contract, workflowName) as WorkflowContext<\n TContract,\n TWorkflowName\n >[\"continueAsNew\"],\n };\n\n // Execute workflow (pass validated input as tuple)\n const result = await implementation(context, validatedInput);\n\n // Validate workflow output\n const outputResult = await definition.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n throw new WorkflowOutputValidationError(String(workflowName), outputResult.issues);\n }\n\n return outputResult.value as WorkerInferOutput<TContract[\"workflows\"][TWorkflowName]>;\n };\n}\n\n/**\n * Union of all activity names available to a workflow — the workflow-local\n * activities plus the contract's global activities.\n */\ntype ActivityNamesFor<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"],\n> =\n | (TContract[\"workflows\"][TWorkflowName][\"activities\"] extends Record<string, ActivityDefinition>\n ? keyof TContract[\"workflows\"][TWorkflowName][\"activities\"] & string\n : never)\n | (TContract[\"activities\"] extends Record<string, ActivityDefinition>\n ? keyof TContract[\"activities\"] & string\n : never);\n\n/**\n * Options for declaring a workflow implementation\n */\ntype DeclareWorkflowOptions<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"],\n> = {\n workflowName: TWorkflowName;\n contract: TContract;\n implementation: WorkflowImplementation<TContract, TWorkflowName>;\n /**\n * Default activity options applied to every activity reachable from this\n * workflow (workflow-local + global) unless overridden in\n * {@link activityOptionsByName}. See Temporal's `ActivityOptions` for the\n * full set of fields:\n * - `startToCloseTimeout`: Maximum time for a single attempt to run\n * - `scheduleToCloseTimeout`: End-to-end timeout including queuing and retries\n * - `scheduleToStartTimeout`: Maximum time the activity can wait in the queue\n * - `heartbeatTimeout`: Time between heartbeats before the activity is considered dead\n * - `retry`: Retry policy for failed activities\n *\n * @example\n * ```ts\n * activityOptions: {\n * startToCloseTimeout: '5m',\n * retry: { maximumAttempts: 3 },\n * }\n * ```\n */\n activityOptions: ActivityOptions;\n /**\n * Per-activity `ActivityOptions` overrides. Each entry shallow-merges over\n * {@link activityOptions} for that activity only — the override wins on\n * every property it specifies, replacing the default value (including the\n * entire nested `retry` block when present, matching Temporal's\n * single-options-per-`proxyActivities`-call semantics).\n *\n * Activity names are typed against the contract; typos surface as TypeScript\n * errors rather than running silently with the default options.\n *\n * @example\n * ```ts\n * activityOptions: { startToCloseTimeout: '1 minute' }, // default\n * activityOptionsByName: {\n * chargePayment: {\n * startToCloseTimeout: '5 minutes',\n * retry: { maximumAttempts: 5 },\n * },\n * fastValidation: { startToCloseTimeout: '5 seconds' },\n * },\n * ```\n */\n activityOptionsByName?: Partial<\n Record<ActivityNamesFor<TContract, TWorkflowName>, ActivityOptions>\n >;\n};\n\n/**\n * Workflow implementation function\n *\n * Receives a workflow context (with typed activities and utilities) and validated input arguments.\n * Returns the workflow output which will be validated against the contract schema.\n */\ntype WorkflowImplementation<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"],\n> = (\n context: WorkflowContext<TContract, TWorkflowName>,\n args: WorkerInferInput<TContract[\"workflows\"][TWorkflowName]>,\n) => Promise<WorkerInferOutput<TContract[\"workflows\"][TWorkflowName]>>;\n\n/**\n * Workflow execution context providing typed activities, workflow info, and interaction handlers\n *\n * Provides access to:\n * - Typed activities (both workflow-specific and global)\n * - Workflow metadata and execution info\n * - Signal, query, and update handler registration\n * - Child workflow execution capabilities\n */\ntype WorkflowContext<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"],\n> = {\n activities: WorkflowInferWorkflowContextActivities<TContract, TWorkflowName>;\n info: WorkflowInfo;\n\n /**\n * Define a signal handler within the workflow implementation\n * Allows the signal handler to access workflow state\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * let currentValue = args.initialValue;\n *\n * context.defineSignal('increment', async (signalArgs) => {\n * currentValue += signalArgs.amount;\n * });\n *\n * // ... rest of workflow\n * }\n * ```\n */\n defineSignal: <K extends keyof TContract[\"workflows\"][TWorkflowName][\"signals\"]>(\n signalName: K,\n handler: SignalHandlerImplementation<\n TContract[\"workflows\"][TWorkflowName][\"signals\"][K] extends SignalDefinition\n ? TContract[\"workflows\"][TWorkflowName][\"signals\"][K]\n : never\n >,\n ) => void;\n\n /**\n * Define a query handler within the workflow implementation\n * Allows the query handler to access workflow state\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * let currentValue = args.initialValue;\n *\n * context.defineQuery('getCurrentValue', () => {\n * return { value: currentValue };\n * });\n *\n * // ... rest of workflow\n * }\n * ```\n */\n defineQuery: <K extends keyof TContract[\"workflows\"][TWorkflowName][\"queries\"]>(\n queryName: K,\n handler: QueryHandlerImplementation<\n TContract[\"workflows\"][TWorkflowName][\"queries\"][K] extends QueryDefinition\n ? TContract[\"workflows\"][TWorkflowName][\"queries\"][K]\n : never\n >,\n ) => void;\n\n /**\n * Define an update handler within the workflow implementation\n * Allows the update handler to access and modify workflow state\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * let currentValue = args.initialValue;\n *\n * context.defineUpdate('multiply', async (updateArgs) => {\n * currentValue *= updateArgs.factor;\n * return { newValue: currentValue };\n * });\n *\n * // ... rest of workflow\n * }\n * ```\n */\n defineUpdate: <K extends keyof TContract[\"workflows\"][TWorkflowName][\"updates\"]>(\n updateName: K,\n handler: UpdateHandlerImplementation<\n TContract[\"workflows\"][TWorkflowName][\"updates\"][K] extends UpdateDefinition\n ? TContract[\"workflows\"][TWorkflowName][\"updates\"][K]\n : never\n >,\n ) => void;\n\n /**\n * Start a child workflow and return a typed handle with Future/Result pattern\n *\n * Supports both same-contract and cross-contract child workflows:\n * - Same contract: Pass workflowName from current contract\n * - Cross-contract: Pass contract and workflowName to invoke workflows from other workers\n *\n * @example\n * ```ts\n * // Same contract child workflow\n * const childResult = await context.startChildWorkflow(myContract, 'processPayment', {\n * workflowId: 'payment-123',\n * args: { amount: 100 }\n * });\n *\n * // Cross-contract child workflow (from another worker)\n * const otherResult = await context.startChildWorkflow(otherContract, 'sendNotification', {\n * workflowId: 'notification-123',\n * args: { message: 'Hello' }\n * });\n *\n * childResult.match({\n * Ok: async (handle) => {\n * const result = await handle.result();\n * // ... handle result\n * },\n * Error: (error) => console.error('Failed to start:', error),\n * });\n * ```\n */\n startChildWorkflow: <\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"],\n >(\n contract: TChildContract,\n workflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n ) => Future<\n Result<\n TypedChildWorkflowHandle<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError\n >\n >;\n\n /**\n * Execute a child workflow (start and wait for result) with Future/Result pattern\n *\n * Supports both same-contract and cross-contract child workflows:\n * - Same contract: Pass workflowName from current contract\n * - Cross-contract: Pass contract and workflowName to invoke workflows from other workers\n *\n * @example\n * ```ts\n * // Same contract child workflow\n * const result = await context.executeChildWorkflow(myContract, 'processPayment', {\n * workflowId: 'payment-123',\n * args: { amount: 100 }\n * });\n *\n * // Cross-contract child workflow (from another worker)\n * const otherResult = await context.executeChildWorkflow(otherContract, 'sendNotification', {\n * workflowId: 'notification-123',\n * args: { message: 'Hello' }\n * });\n *\n * result.match({\n * Ok: (output) => console.log('Payment processed:', output),\n * Error: (error) => console.error('Processing failed:', error),\n * });\n * ```\n */\n executeChildWorkflow: <\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"],\n >(\n contract: TChildContract,\n workflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n ) => Future<\n Result<ClientInferOutput<TChildContract[\"workflows\"][TChildWorkflowName]>, ChildWorkflowError>\n >;\n\n /**\n * Run `fn` inside a cancellable Temporal scope. If the workflow (or an\n * ancestor scope) is cancelled while `fn` is in flight, the resulting\n * Future resolves to `Result.Error(WorkflowCancelledError)` instead of\n * rejecting — letting callers handle cancellation explicitly, typically\n * to perform a graceful exit from the current step.\n *\n * Non-cancellation errors thrown by `fn` propagate as Future rejections\n * unchanged, preserving their identity for upstream `try/catch` blocks.\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * const result = await context.cancellableScope(async () => {\n * return context.activities.processStep(args);\n * });\n *\n * if (result.isError()) {\n * // workflow was cancelled — perform cleanup that must not be cancelled:\n * await context.nonCancellableScope(async () => {\n * await context.activities.releaseResources(args);\n * });\n * return { status: \"cancelled\" };\n * }\n *\n * return { status: \"ok\" };\n * }\n * ```\n */\n cancellableScope: <T>(fn: () => T | Promise<T>) => Future<Result<T, WorkflowCancelledError>>;\n\n /**\n * Run `fn` inside a non-cancellable Temporal scope. Cancellation requests\n * from outside the scope are ignored for its duration — the idiomatic way\n * to perform cleanup work that must not be interrupted.\n *\n * Returns the same `Future<Result<...>>` shape as\n * {@link WorkflowContext.cancellableScope} for symmetry; the\n * `Result.Error` branch only triggers when cancellation is raised from\n * *inside* the scope, which is rare.\n */\n nonCancellableScope: <T>(fn: () => T | Promise<T>) => Future<Result<T, WorkflowCancelledError>>;\n\n /**\n * Continue this workflow execution as a new run, optionally with a different\n * workflow type from another contract.\n *\n * Args are validated against the destination workflow's input schema before\n * Temporal's `continueAsNew` is invoked. On validation failure, throws a\n * {@link WorkflowInputValidationError}; on success, Temporal terminates the\n * current execution and starts a fresh one — which is why the function\n * never returns normally (`Promise<never>`).\n *\n * Idiomatic usage:\n *\n * @example\n * ```ts\n * // Same workflow, validated args\n * implementation: async (context, args) => {\n * if (shouldRoll(args)) {\n * return context.continueAsNew({ ...args, retryCount: args.retryCount + 1 });\n * }\n * return ...;\n * }\n *\n * // Cross-contract continueAsNew (less common — taskQueue and workflow type\n * // come from the other contract)\n * return context.continueAsNew(otherContract, \"otherWorkflow\", { ...newArgs });\n * ```\n */\n continueAsNew: {\n /** Same-workflow continuation — args typed against this workflow's input. */\n (\n args: ClientInferInput<TContract[\"workflows\"][TWorkflowName]>,\n options?: TypedContinueAsNewOptions,\n ): Promise<never>;\n /** Cross-contract continuation — args typed against the destination workflow. */\n <\n TOtherContract extends ContractDefinition,\n TOtherWorkflowName extends keyof TOtherContract[\"workflows\"],\n >(\n contract: TOtherContract,\n workflowName: TOtherWorkflowName,\n args: ClientInferInput<TOtherContract[\"workflows\"][TOtherWorkflowName]>,\n options?: TypedContinueAsNewOptions,\n ): Promise<never>;\n };\n};\n\n/**\n * Options for starting a child workflow\n */\ntype TypedChildWorkflowOptions<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"],\n> = Omit<ChildWorkflowOptions, \"taskQueue\" | \"args\"> & {\n args: ClientInferInput<TChildContract[\"workflows\"][TChildWorkflowName]>;\n};\n\n/**\n * Typed handle for a child workflow with Future/Result pattern\n */\ntype TypedChildWorkflowHandle<TWorkflow extends WorkflowDefinition> = {\n /**\n * Get child workflow result with Result pattern\n */\n result: () => Future<Result<ClientInferOutput<TWorkflow>, ChildWorkflowError>>;\n\n /**\n * Child workflow ID\n */\n workflowId: string;\n};\n\n/**\n * Activity function signature from workflow execution perspective\n *\n * Workflows call activities with validated input (z.input parsed) and receive validated output (z.output)\n */\ntype WorkflowInferActivity<TActivity extends ActivityDefinition> = (\n args: ClientInferInput<TActivity>,\n) => Promise<ClientInferOutput<TActivity>>;\n\n/**\n * All global activities from a contract (workflow execution perspective)\n */\ntype WorkflowInferActivities<TContract extends ContractDefinition> =\n TContract[\"activities\"] extends Record<string, ActivityDefinition>\n ? {\n [K in keyof TContract[\"activities\"]]: WorkflowInferActivity<TContract[\"activities\"][K]>;\n }\n : {};\n\n/**\n * Workflow-specific activities (workflow execution perspective)\n */\ntype WorkflowInferWorkflowActivities<T extends WorkflowDefinition> =\n T[\"activities\"] extends Record<string, ActivityDefinition>\n ? {\n [K in keyof T[\"activities\"]]: WorkflowInferActivity<T[\"activities\"][K]>;\n }\n : {};\n\n/**\n * All activities available in a workflow context (workflow execution perspective)\n *\n * Combines workflow-specific activities with global contract activities\n */\ntype WorkflowInferWorkflowContextActivities<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"],\n> = WorkflowInferWorkflowActivities<TContract[\"workflows\"][TWorkflowName]> &\n WorkflowInferActivities<TContract>;\n\n/**\n * Create a validated activities proxy that parses inputs and outputs\n *\n * This wrapper ensures data integrity across the network boundary between\n * workflow and activity execution.\n */\nfunction createValidatedActivities<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"],\n>(\n rawActivities: Record<string, (...args: unknown[]) => Promise<unknown>>,\n workflowActivitiesDefinition: Record<string, ActivityDefinition> | undefined,\n contractActivitiesDefinition: Record<string, ActivityDefinition> | undefined,\n): WorkflowInferWorkflowContextActivities<TContract, TWorkflowName> {\n const validatedActivities = {} as WorkflowInferWorkflowContextActivities<\n TContract,\n TWorkflowName\n >;\n\n // Merge workflow-specific and global contract activities. defineContract\n // guarantees there are no name collisions across scopes, so spread order\n // is just a stable iteration choice (workflow-local last).\n const allActivitiesDefinition = {\n ...contractActivitiesDefinition,\n ...workflowActivitiesDefinition,\n };\n\n for (const [activityName, activityDef] of Object.entries(allActivitiesDefinition)) {\n const rawActivity = rawActivities[activityName];\n\n if (!rawActivity) {\n throw new Error(\n `Activity implementation not found for: \"${activityName}\". ` +\n `Available activities: ${Object.keys(rawActivities).length > 0 ? Object.keys(rawActivities).join(\", \") : \"none\"}`,\n );\n }\n\n // Wrap activity with input/output validation\n // Register the wrapped activity\n (validatedActivities as Record<string, unknown>)[activityName] = async (input: unknown) => {\n // Validate input before sending over the network\n const inputResult = await activityDef.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new ActivityInputValidationError(activityName, inputResult.issues);\n }\n\n // Call the actual activity with validated input\n const result = await rawActivity(inputResult.value);\n\n // Validate output after receiving from the network\n const outputResult = await activityDef.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n throw new ActivityOutputValidationError(activityName, outputResult.issues);\n }\n\n return outputResult.value;\n };\n }\n\n return validatedActivities;\n}\n\nasync function validateChildWorkflowOutput<TChildWorkflow extends WorkflowDefinition>(\n childDefinition: TChildWorkflow,\n result: unknown,\n childWorkflowName: string,\n): Promise<Result<ClientInferOutput<TChildWorkflow>, ChildWorkflowError>> {\n const outputResult = await childDefinition.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n return Result.Error(\n new ChildWorkflowError(\n formatChildWorkflowValidationMessage(childWorkflowName, \"output\", outputResult.issues),\n ),\n );\n }\n return Result.Ok(outputResult.value as ClientInferOutput<TChildWorkflow>);\n}\n\nasync function getAndValidateChildWorkflow<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"],\n>(\n childContract: TChildContract,\n childWorkflowName: TChildWorkflowName,\n args: unknown,\n): Promise<\n Result<\n {\n definition: TChildContract[\"workflows\"][TChildWorkflowName];\n validatedInput: WorkerInferInput<TChildContract[\"workflows\"][TChildWorkflowName]>;\n taskQueue: string;\n },\n ChildWorkflowError\n >\n> {\n const childDefinition = childContract.workflows[childWorkflowName as string];\n\n if (!childDefinition) {\n return Result.Error(\n new ChildWorkflowNotFoundError(\n String(childWorkflowName),\n Object.keys(childContract.workflows) as string[],\n ),\n );\n }\n\n const inputResult = await childDefinition.input[\"~standard\"].validate(args);\n if (inputResult.issues) {\n return Result.Error(\n new ChildWorkflowError(\n formatChildWorkflowValidationMessage(\n String(childWorkflowName),\n \"input\",\n inputResult.issues,\n ),\n ),\n );\n }\n\n const validatedInput = inputResult.value as WorkerInferInput<\n TChildContract[\"workflows\"][TChildWorkflowName]\n >;\n\n return Result.Ok({\n definition: childDefinition as TChildContract[\"workflows\"][TChildWorkflowName],\n validatedInput,\n taskQueue: childContract.taskQueue,\n });\n}\n\nfunction createTypedChildHandle<TChildWorkflow extends WorkflowDefinition>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handle: ChildWorkflowHandle<any>,\n childDefinition: TChildWorkflow,\n childWorkflowName: string,\n): TypedChildWorkflowHandle<TChildWorkflow> {\n return {\n workflowId: handle.workflowId,\n result: (): Future<Result<ClientInferOutput<TChildWorkflow>, ChildWorkflowError>> => {\n return Future.fromAsync(async () => {\n try {\n const result = await handle.result();\n return validateChildWorkflowOutput(childDefinition, result, childWorkflowName);\n } catch (error) {\n return Result.Error(\n new ChildWorkflowError(\n `Child workflow execution failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n ),\n );\n }\n });\n },\n };\n}\n\nfunction createStartChildWorkflow<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"],\n>(\n childContract: TChildContract,\n childWorkflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n): Future<\n Result<\n TypedChildWorkflowHandle<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError\n >\n> {\n return Future.fromAsync(async () => {\n const validationResult = await getAndValidateChildWorkflow(\n childContract,\n childWorkflowName,\n options.args,\n );\n\n if (validationResult.isError()) {\n return Result.Error(validationResult.error);\n }\n\n const { definition: childDefinition, validatedInput, taskQueue } = validationResult.value;\n\n try {\n const { args: _args, ...temporalOptions } = options;\n const handle = await startChild(childWorkflowName as string, {\n ...temporalOptions,\n taskQueue,\n args: [validatedInput],\n });\n\n const typedHandle = createTypedChildHandle(\n handle,\n childDefinition,\n String(childWorkflowName),\n ) as TypedChildWorkflowHandle<TChildContract[\"workflows\"][TChildWorkflowName]>;\n\n return Result.Ok(typedHandle);\n } catch (error) {\n return Result.Error(\n new ChildWorkflowError(\n `Failed to start child workflow: ${error instanceof Error ? error.message : String(error)}`,\n error,\n ),\n );\n }\n });\n}\n\nfunction createExecuteChildWorkflow<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"],\n>(\n childContract: TChildContract,\n childWorkflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n): Future<\n Result<ClientInferOutput<TChildContract[\"workflows\"][TChildWorkflowName]>, ChildWorkflowError>\n> {\n return Future.fromAsync(async () => {\n const validationResult = await getAndValidateChildWorkflow(\n childContract,\n childWorkflowName,\n options.args,\n );\n\n if (validationResult.isError()) {\n return Result.Error(validationResult.error);\n }\n\n const { definition: childDefinition, validatedInput, taskQueue } = validationResult.value;\n\n try {\n const { args: _args, ...temporalOptions } = options;\n const result = await executeChild(childWorkflowName as string, {\n ...temporalOptions,\n taskQueue,\n args: [validatedInput],\n });\n\n const outputValidationResult = await validateChildWorkflowOutput(\n childDefinition,\n result,\n String(childWorkflowName),\n );\n\n if (outputValidationResult.isError()) {\n return Result.Error(outputValidationResult.error);\n }\n\n return Result.Ok(\n outputValidationResult.value as ClientInferOutput<\n TChildContract[\"workflows\"][TChildWorkflowName]\n >,\n );\n } catch (error) {\n return Result.Error(\n new ChildWorkflowError(\n `Failed to execute child workflow: ${error instanceof Error ? error.message : String(error)}`,\n error,\n ),\n );\n }\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,iBACd,IAC2C;AAC3C,QAAO,OAAO,UAAU,YAAY;AAClC,MAAI;GAIF,MAAM,QAAQ,MAAM,kBAAkB,YAAY,YAAY,IAAI,CAAC;AACnE,UAAO,OAAO,GAAG,MAAM;WAChB,OAAO;AACd,OAAI,eAAe,MAAM,CACvB,QAAO,OAAO,MAAM,IAAI,uBAAuB,MAAM,CAAC;AAExD,SAAM;;GAER;;;;;;;;;;;;;;;;;;;AAoBJ,SAAgB,oBACd,IAC2C;AAC3C,QAAO,OAAO,UAAU,YAAY;AAClC,MAAI;GACF,MAAM,QAAQ,MAAM,kBAAkB,eAAe,YAAY,IAAI,CAAC;AACtE,UAAO,OAAO,GAAG,MAAM;WAChB,OAAO;AACd,OAAI,eAAe,MAAM,CACvB,QAAO,OAAO,MAAM,IAAI,uBAAuB,MAAM,CAAC;AAExD,SAAM;;GAER;;;;;;;;;;;;;;;ACjBJ,SAAgB,kBACd,oBACA,cACA,YACA,SACM;AACN,K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ACA,OAAO,kBAAkB,CAC1B;AAED,UAAO,OAAO,GAAG,YAAY;WACtB,OAAO;AACd,UAAO,OAAO,MACZ,IAAI,mBACF,mCAAmC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,IACzF,MACD,CACF;;GAEH;;AAGJ,SAAS,2BAIP,eACA,mBACA,SAGA;AACA,QAAO,OAAO,UAAU,YAAY;EAClC,MAAM,mBAAmB,MAAM,4BAC7B,eACA,mBACA,QAAQ,KACT;AAED,MAAI,iBAAiB,SAAS,CAC5B,QAAO,OAAO,MAAM,iBAAiB,MAAM;EAG7C,MAAM,EAAE,YAAY,iBAAiB,gBAAgB,cAAc,iBAAiB;AAEpF,MAAI;GACF,MAAM,EAAE,MAAM,OAAO,GAAG,oBAAoB;GAO5C,MAAM,yBAAyB,MAAM,4BACnC,iBACA,MARmB,aAAa,mBAA6B;IAC7D,GAAG;IACH;IACA,MAAM,CAAC,eAAe;IACvB,CAAC,EAKA,OAAO,kBAAkB,CAC1B;AAED,OAAI,uBAAuB,SAAS,CAClC,QAAO,OAAO,MAAM,uBAAuB,MAAM;AAGnD,UAAO,OAAO,GACZ,uBAAuB,MAGxB;WACM,OAAO;AACd,UAAO,OAAO,MACZ,IAAI,mBACF,qCAAqC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,IAC3F,MACD,CACF;;GAEH"}
|
|
1
|
+
{"version":3,"file":"workflow.mjs","names":[],"sources":["../src/cancellation.ts","../src/handlers.ts","../src/child-workflow.ts","../src/activities-proxy.ts","../src/workflow.ts"],"sourcesContent":["/**\n * Typed wrappers around Temporal's `CancellationScope` so workflows can\n * opt into cancellation control without reaching for\n * `@temporalio/workflow` directly. The wrappers fold cancellation into\n * the same `ResultAsync<...>` shape used elsewhere in the worker\n * context — callers branch on `err(WorkflowCancelledError)` instead of\n * catching `CancelledFailure`.\n *\n * Non-cancellation errors thrown inside the scope are wrapped in a\n * {@link WorkflowScopeError} (with the original error preserved on\n * `cause`) and surfaced on the same `err(...)` channel. Together with\n * `WorkflowCancelledError` this makes the failure modes exhaustive on\n * `result.match(...)` — nothing escapes as an unhandled rejection.\n */\nimport { CancellationScope, isCancellation } from \"@temporalio/workflow\";\nimport { type ResultAsync, type Result, ok, err } from \"neverthrow\";\nimport { WorkflowCancelledError, WorkflowScopeError } from \"./errors.js\";\nimport { makeResultAsync } from \"./internal.js\";\n\n/**\n * Run `fn` inside a cancellable Temporal scope. If the workflow (or an\n * ancestor scope) is cancelled while the function is in flight, the\n * resulting ResultAsync resolves to `err(WorkflowCancelledError)`,\n * letting callers handle cancellation explicitly — typically to perform\n * a graceful exit from the current step.\n *\n * Non-cancellation errors thrown by `fn` resolve to\n * `err(WorkflowScopeError)` (with the original error on `cause`) so\n * domain failures surface on the same typed error channel rather than\n * leaking as unhandled rejections.\n *\n * @example\n * ```ts\n * const result = await context.cancellableScope(async () => {\n * return await context.activities.processStep(...);\n * });\n *\n * result.match(\n * (output) => { ... },\n * (error) => {\n * if (error instanceof WorkflowCancelledError) {\n * // graceful exit\n * } else {\n * // error instanceof WorkflowScopeError — domain failure on `cause`\n * }\n * },\n * );\n * ```\n */\nexport function cancellableScope<T>(\n fn: () => T | Promise<T>,\n): ResultAsync<T, WorkflowCancelledError | WorkflowScopeError> {\n const work = async (): Promise<Result<T, WorkflowCancelledError | WorkflowScopeError>> => {\n try {\n // Wrap so synchronous returns satisfy CancellationScope.cancellable's\n // `() => Promise<T>` signature without forcing every caller to write\n // `async () => ...` for purely synchronous bodies.\n const value = await CancellationScope.cancellable(async () => fn());\n return ok(value);\n } catch (error) {\n if (isCancellation(error)) {\n return err(new WorkflowCancelledError(error));\n }\n return err(new WorkflowScopeError(error));\n }\n };\n // makeResultAsync is the shared safety net from `@temporal-contract/contract`\n // — `new ResultAsync(work())` does not catch, so a synchronous throw inside\n // `work` (e.g. a buggy refactor) would escape neverthrow's railway. The\n // catch-all here funnels that back into `err(WorkflowScopeError)` for\n // parity with the in-band path above.\n return makeResultAsync(work, (e) => new WorkflowScopeError(e));\n}\n\n/**\n * Run `fn` inside a non-cancellable Temporal scope. Cancellation requests\n * from outside the scope are ignored for its duration — the idiomatic way\n * to perform cleanup that must not be interrupted (e.g. releasing a\n * resource after a graceful shutdown).\n *\n * Mirrors `cancellableScope`'s `ResultAsync<...>` shape for symmetry; the\n * `err(WorkflowCancelledError)` branch only triggers when cancellation is\n * raised from inside the scope (rare). Non-cancellation errors surface as\n * `err(WorkflowScopeError)`.\n *\n * @example\n * ```ts\n * await context.nonCancellableScope(async () => {\n * await context.activities.releaseResources(...);\n * });\n * ```\n */\nexport function nonCancellableScope<T>(\n fn: () => T | Promise<T>,\n): ResultAsync<T, WorkflowCancelledError | WorkflowScopeError> {\n const work = async (): Promise<Result<T, WorkflowCancelledError | WorkflowScopeError>> => {\n try {\n const value = await CancellationScope.nonCancellable(async () => fn());\n return ok(value);\n } catch (error) {\n if (isCancellation(error)) {\n return err(new WorkflowCancelledError(error));\n }\n return err(new WorkflowScopeError(error));\n }\n };\n return makeResultAsync(work, (e) => new WorkflowScopeError(e));\n}\n","// Top-level helpers for binding signal / query / update handlers to a\n// running workflow. Previously nested inside `declareWorkflow`'s closure\n// (#185), they're hoisted here so the bodies aren't reallocated on each\n// workflow invocation. The typed call-site surface is preserved at the\n// context-assignment site in `workflow.ts` (the arrow that forwards into\n// these helpers carries the contract-derived generic constraints).\n//\n// Internally these are loosely typed (string names, broad `*Definition`\n// inputs); the call sites already do the cast against the typed\n// `WorkflowContext` shape, so the typed-vs-runtime split is the same as\n// it was before the hoist.\nimport type {\n AnyWorkflowDefinition,\n QueryDefinition,\n SignalDefinition,\n UpdateDefinition,\n} from \"@temporal-contract/contract\";\nimport { defineQuery, defineSignal, defineUpdate, setHandler } from \"@temporalio/workflow\";\nimport {\n QueryInputValidationError,\n QueryOutputValidationError,\n SignalInputValidationError,\n UpdateInputValidationError,\n UpdateOutputValidationError,\n} from \"./errors.js\";\nimport { extractHandlerInput } from \"./internal.js\";\nimport type { WorkerInferInput, WorkerInferOutput } from \"./types.js\";\n\n/**\n * Signal handler implementation\n *\n * Processes signal input and can optionally perform asynchronous operations.\n * Should not return a value (signals are fire-and-forget).\n */\nexport type SignalHandlerImplementation<TSignal extends SignalDefinition> = (\n args: WorkerInferInput<TSignal>,\n) => void | Promise<void>;\n\n/**\n * Query handler implementation\n *\n * Processes query input and returns a synchronous response.\n * Must be synchronous to satisfy Temporal's query constraints.\n */\nexport type QueryHandlerImplementation<TQuery extends QueryDefinition> = (\n args: WorkerInferInput<TQuery>,\n) => WorkerInferOutput<TQuery>;\n\n/**\n * Update handler implementation\n *\n * Processes update input and returns a validated response after modifying workflow state.\n * Can perform asynchronous operations.\n */\nexport type UpdateHandlerImplementation<TUpdate extends UpdateDefinition> = (\n args: WorkerInferInput<TUpdate>,\n) => Promise<WorkerInferOutput<TUpdate>>;\n\n/**\n * Bind a typed signal handler to the running workflow. Validates the\n * signal payload against the contract's input schema before invoking the\n * user-supplied handler.\n *\n * The runtime guard against a missing `signals` block — and an unknown\n * signal name within it — covers the union-typed-`workflowName` case\n * where the type system's keyset constraint collapses; without the\n * check, a caller would see `Cannot read properties of undefined`\n * instead of a controlled error.\n */\nexport function bindSignalHandler(\n workflowDefinition: AnyWorkflowDefinition,\n workflowName: string,\n signalName: string,\n handler: SignalHandlerImplementation<SignalDefinition>,\n): void {\n if (!workflowDefinition.signals) {\n throw new Error(\n `Signal \"${signalName}\" cannot be defined: workflow \"${workflowName}\" has no signals in its contract`,\n );\n }\n const signalDef = (workflowDefinition.signals as Record<string, SignalDefinition>)[signalName];\n if (!signalDef) {\n throw new Error(`Signal \"${signalName}\" not found in workflow \"${workflowName}\" contract`);\n }\n\n const signal = defineSignal(signalName);\n setHandler(signal, async (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n const inputResult = await signalDef.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new SignalInputValidationError(signalName, inputResult.issues);\n }\n await handler(inputResult.value);\n });\n}\n\n/**\n * Bind a typed query handler to the running workflow. Validates input\n * and output against the contract synchronously.\n *\n * Temporal's query API requires a synchronous handler — async\n * validation breaks replay determinism. The handler trips a clear error\n * if the schema library returns a Promise from `validate(...)`, instead\n * of letting the async path silently corrupt query semantics.\n */\nexport function bindQueryHandler(\n workflowDefinition: AnyWorkflowDefinition,\n workflowName: string,\n queryName: string,\n handler: QueryHandlerImplementation<QueryDefinition>,\n): void {\n if (!workflowDefinition.queries) {\n throw new Error(\n `Query \"${queryName}\" cannot be defined: workflow \"${workflowName}\" has no queries in its contract`,\n );\n }\n const queryDef = (workflowDefinition.queries as Record<string, QueryDefinition>)[queryName];\n if (!queryDef) {\n throw new Error(`Query \"${queryName}\" not found in workflow \"${workflowName}\" contract`);\n }\n\n const query = defineQuery(queryName);\n setHandler(query, (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n const inputResult = queryDef.input[\"~standard\"].validate(input);\n\n if (inputResult instanceof Promise) {\n throw new Error(\n `Query \"${queryName}\" validation must be synchronous. Use a schema library that supports synchronous validation for queries.`,\n );\n }\n if (inputResult.issues) {\n throw new QueryInputValidationError(queryName, inputResult.issues);\n }\n\n const result = handler(inputResult.value);\n\n const outputResult = queryDef.output[\"~standard\"].validate(result);\n if (outputResult instanceof Promise) {\n throw new Error(\n `Query \"${queryName}\" output validation must be synchronous. Use a schema library that supports synchronous validation for queries.`,\n );\n }\n if (outputResult.issues) {\n throw new QueryOutputValidationError(queryName, outputResult.issues);\n }\n\n return outputResult.value;\n });\n}\n\n/**\n * Bind a typed update handler to the running workflow.\n *\n * Input validation runs in Temporal's `validator` slot — a synchronous\n * pre-admission hook. If it throws, Temporal rejects the update *before*\n * appending a workflow history event: clients see\n * `WorkflowUpdateValidationRejectedError` and the workflow's history is\n * unaffected. This is the documented contract for `setHandler`'s\n * `validator` option, and it is strictly better than running validation\n * inside the handler body — which forces Temporal to admit the update,\n * write a history event, and surface a `WorkflowUpdateFailedError` to\n * the client only after the fact.\n *\n * Because the validator slot is synchronous, the input schema must also\n * validate synchronously. Standard Schema is allowed to be async (Zod's\n * `.refine(async)` is the typical case), but we trip a clear error when\n * that happens rather than silently breaking admission semantics — same\n * approach as `bindQueryHandler`. Users who need async input checks\n * should run them inside the handler body and accept the post-admission\n * failure mode, or restructure their schema.\n *\n * Output validation continues to run inside the handler body. Update\n * outputs are *not* admission-gated — the handler must execute to\n * produce a value to validate against — so the async-allowed shape is\n * preserved.\n */\nexport function bindUpdateHandler(\n workflowDefinition: AnyWorkflowDefinition,\n workflowName: string,\n updateName: string,\n handler: UpdateHandlerImplementation<UpdateDefinition>,\n): void {\n if (!workflowDefinition.updates) {\n throw new Error(\n `Update \"${updateName}\" cannot be defined: workflow \"${workflowName}\" has no updates in its contract`,\n );\n }\n const updateDef = (workflowDefinition.updates as Record<string, UpdateDefinition>)[updateName];\n if (!updateDef) {\n throw new Error(`Update \"${updateName}\" not found in workflow \"${workflowName}\" contract`);\n }\n\n const update = defineUpdate(updateName);\n setHandler(\n update,\n async (...args: unknown[]) => {\n // The validator already accepted the payload — re-parse here so the\n // handler receives the schema's transformed value (Standard Schema\n // may rewrite shapes during validation, e.g. Zod `.transform`). This\n // is sync because the validator already proved the schema is sync;\n // any async result here would mean the schema changed under us,\n // which is a programmer error worth surfacing.\n const input = extractHandlerInput(args);\n const inputResult = updateDef.input[\"~standard\"].validate(input);\n if (inputResult instanceof Promise) {\n throw new Error(\n `Update \"${updateName}\" input validation must be synchronous. Use a schema library that supports synchronous validation for update inputs (Temporal's update validator slot is synchronous).`,\n );\n }\n if (inputResult.issues) {\n // The validator should have caught this; if we reach here, the\n // schema produced different issues on a second call (non-pure\n // validator). Surface it as the same typed error class for\n // consistency.\n throw new UpdateInputValidationError(updateName, inputResult.issues);\n }\n\n const result = await handler(inputResult.value);\n\n const outputResult = await updateDef.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n throw new UpdateOutputValidationError(updateName, outputResult.issues);\n }\n\n return outputResult.value;\n },\n {\n validator: (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n const inputResult = updateDef.input[\"~standard\"].validate(input);\n\n if (inputResult instanceof Promise) {\n throw new Error(\n `Update \"${updateName}\" input validation must be synchronous. Use a schema library that supports synchronous validation for update inputs (Temporal's update validator slot is synchronous).`,\n );\n }\n if (inputResult.issues) {\n throw new UpdateInputValidationError(updateName, inputResult.issues);\n }\n },\n },\n );\n}\n","/**\n * Child workflow types + helpers used by `declareWorkflow`. Split out of\n * `workflow.ts` to keep that file focused on `declareWorkflow` and its\n * `WorkflowContext` type. Not part of the worker package's public exports.\n */\nimport type { AnyWorkflowDefinition, ContractDefinition } from \"@temporal-contract/contract\";\nimport {\n ChildWorkflowHandle,\n ChildWorkflowOptions,\n executeChild,\n startChild,\n} from \"@temporalio/workflow\";\nimport { ResultAsync, type Result, ok, err } from \"neverthrow\";\nimport {\n ChildWorkflowCancelledError,\n ChildWorkflowError,\n ChildWorkflowNotFoundError,\n} from \"./errors.js\";\nimport {\n classifyChildWorkflowError,\n formatChildWorkflowValidationMessage,\n makeResultAsync,\n} from \"./internal.js\";\nimport type { ClientInferInput, ClientInferOutput, WorkerInferInput } from \"./types.js\";\n\n/**\n * Options for starting a child workflow. `taskQueue` and `args` come from\n * the contract; everything else is forwarded to Temporal's\n * `startChild` / `executeChild`.\n */\nexport type TypedChildWorkflowOptions<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n> = Omit<ChildWorkflowOptions, \"taskQueue\" | \"args\"> & {\n args: ClientInferInput<TChildContract[\"workflows\"][TChildWorkflowName]>;\n};\n\n/**\n * Typed handle for a child workflow with neverthrow `ResultAsync` pattern.\n */\nexport type TypedChildWorkflowHandle<TWorkflow extends AnyWorkflowDefinition> = {\n /**\n * Get child workflow result with `ResultAsync` pattern.\n */\n result: () => ResultAsync<\n ClientInferOutput<TWorkflow>,\n ChildWorkflowError | ChildWorkflowCancelledError\n >;\n\n /**\n * Child workflow ID.\n */\n workflowId: string;\n};\n\nasync function validateChildWorkflowOutput<TChildWorkflow extends AnyWorkflowDefinition>(\n childDefinition: TChildWorkflow,\n result: unknown,\n childWorkflowName: string,\n): Promise<Result<ClientInferOutput<TChildWorkflow>, ChildWorkflowError>> {\n const outputResult = await childDefinition.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n return err(\n new ChildWorkflowError(\n formatChildWorkflowValidationMessage(childWorkflowName, \"output\", outputResult.issues),\n ),\n );\n }\n return ok(outputResult.value as ClientInferOutput<TChildWorkflow>);\n}\n\nasync function getAndValidateChildWorkflow<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n>(\n childContract: TChildContract,\n childWorkflowName: TChildWorkflowName,\n args: unknown,\n): Promise<\n Result<\n {\n definition: TChildContract[\"workflows\"][TChildWorkflowName];\n validatedInput: WorkerInferInput<TChildContract[\"workflows\"][TChildWorkflowName]>;\n taskQueue: string;\n },\n ChildWorkflowError\n >\n> {\n const childDefinition = childContract.workflows[childWorkflowName];\n\n if (!childDefinition) {\n return err(\n new ChildWorkflowNotFoundError(\n childWorkflowName,\n Object.keys(childContract.workflows) as string[],\n ),\n );\n }\n\n const inputResult = await childDefinition.input[\"~standard\"].validate(args);\n if (inputResult.issues) {\n return err(\n new ChildWorkflowError(\n formatChildWorkflowValidationMessage(childWorkflowName, \"input\", inputResult.issues),\n ),\n );\n }\n\n const validatedInput = inputResult.value as WorkerInferInput<\n TChildContract[\"workflows\"][TChildWorkflowName]\n >;\n\n return ok({\n definition: childDefinition as TChildContract[\"workflows\"][TChildWorkflowName],\n validatedInput,\n taskQueue: childContract.taskQueue,\n });\n}\n\nfunction createTypedChildHandle<TChildWorkflow extends AnyWorkflowDefinition>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handle: ChildWorkflowHandle<any>,\n childDefinition: TChildWorkflow,\n childWorkflowName: string,\n): TypedChildWorkflowHandle<TChildWorkflow> {\n return {\n workflowId: handle.workflowId,\n result: (): ResultAsync<\n ClientInferOutput<TChildWorkflow>,\n ChildWorkflowError | ChildWorkflowCancelledError\n > => {\n const work = async (): Promise<\n Result<ClientInferOutput<TChildWorkflow>, ChildWorkflowError | ChildWorkflowCancelledError>\n > => {\n try {\n const result = await handle.result();\n return validateChildWorkflowOutput(childDefinition, result, childWorkflowName);\n } catch (error) {\n return err(classifyChildWorkflowError(\"result\", error, childWorkflowName));\n }\n };\n return makeResultAsync(\n work,\n (error) =>\n new ChildWorkflowError(\n `Child workflow execution failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n ),\n );\n },\n };\n}\n\nexport function createStartChildWorkflow<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n>(\n childContract: TChildContract,\n childWorkflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n): ResultAsync<\n TypedChildWorkflowHandle<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError\n> {\n type Ok = TypedChildWorkflowHandle<TChildContract[\"workflows\"][TChildWorkflowName]>;\n const work = async (): Promise<\n Result<Ok, ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError>\n > => {\n const validationResult = await getAndValidateChildWorkflow(\n childContract,\n childWorkflowName,\n options.args,\n );\n\n if (validationResult.isErr()) {\n return err(validationResult.error);\n }\n\n const { definition: childDefinition, validatedInput, taskQueue } = validationResult.value;\n\n try {\n const { args: _args, ...temporalOptions } = options;\n const handle = await startChild(childWorkflowName, {\n ...temporalOptions,\n taskQueue,\n args: [validatedInput],\n });\n\n const typedHandle = createTypedChildHandle(handle, childDefinition, childWorkflowName) as Ok;\n\n return ok(typedHandle);\n } catch (error) {\n return err(classifyChildWorkflowError(\"startChild\", error, String(childWorkflowName)));\n }\n };\n return makeResultAsync(\n work,\n (error) =>\n new ChildWorkflowError(\n `Failed to start child workflow: ${error instanceof Error ? error.message : String(error)}`,\n error,\n ),\n );\n}\n\nexport function createExecuteChildWorkflow<\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n>(\n childContract: TChildContract,\n childWorkflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n): ResultAsync<\n ClientInferOutput<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError\n> {\n type Ok = ClientInferOutput<TChildContract[\"workflows\"][TChildWorkflowName]>;\n const work = async (): Promise<\n Result<Ok, ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError>\n > => {\n const validationResult = await getAndValidateChildWorkflow(\n childContract,\n childWorkflowName,\n options.args,\n );\n\n if (validationResult.isErr()) {\n return err(validationResult.error);\n }\n\n const { definition: childDefinition, validatedInput, taskQueue } = validationResult.value;\n\n try {\n const { args: _args, ...temporalOptions } = options;\n const result = await executeChild(childWorkflowName, {\n ...temporalOptions,\n taskQueue,\n args: [validatedInput],\n });\n\n const outputValidationResult = await validateChildWorkflowOutput(\n childDefinition,\n result,\n childWorkflowName,\n );\n\n if (outputValidationResult.isErr()) {\n return err(outputValidationResult.error);\n }\n\n return ok(outputValidationResult.value as Ok);\n } catch (error) {\n return err(classifyChildWorkflowError(\"executeChild\", error, String(childWorkflowName)));\n }\n };\n return makeResultAsync(\n work,\n (error) =>\n new ChildWorkflowError(\n `Failed to execute child workflow: ${error instanceof Error ? error.message : String(error)}`,\n error,\n ),\n );\n}\n","/**\n * Activity inference types + the validated-activities proxy used by\n * `declareWorkflow`. Split out of `workflow.ts` to keep that file focused\n * on `declareWorkflow` and its `WorkflowContext` type. Not part of the\n * worker package's public exports.\n */\nimport type {\n ActivityDefinition,\n AnyWorkflowDefinition,\n ContractDefinition,\n} from \"@temporal-contract/contract\";\nimport { ActivityInputValidationError, ActivityOutputValidationError } from \"./errors.js\";\nimport type { ClientInferInput, ClientInferOutput } from \"./types.js\";\n\n/**\n * Activity function signature from workflow execution perspective.\n *\n * Workflows call activities with validated input (z.input parsed) and receive validated output (z.output).\n */\nexport type WorkflowInferActivity<TActivity extends ActivityDefinition> = (\n args: ClientInferInput<TActivity>,\n) => Promise<ClientInferOutput<TActivity>>;\n\n/**\n * All global activities from a contract (workflow execution perspective).\n */\nexport type WorkflowInferActivities<TContract extends ContractDefinition> =\n TContract[\"activities\"] extends Record<string, ActivityDefinition>\n ? {\n [K in keyof TContract[\"activities\"]]: WorkflowInferActivity<TContract[\"activities\"][K]>;\n }\n : {};\n\n/**\n * Workflow-specific activities (workflow execution perspective).\n */\nexport type WorkflowInferWorkflowActivities<T extends AnyWorkflowDefinition> =\n T[\"activities\"] extends Record<string, ActivityDefinition>\n ? {\n [K in keyof T[\"activities\"]]: WorkflowInferActivity<T[\"activities\"][K]>;\n }\n : {};\n\n/**\n * All activities available in a workflow context (workflow execution perspective).\n *\n * Combines workflow-specific activities with global contract activities.\n */\nexport type WorkflowInferWorkflowContextActivities<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> = WorkflowInferWorkflowActivities<TContract[\"workflows\"][TWorkflowName]> &\n WorkflowInferActivities<TContract>;\n\n/**\n * Wrap the raw activities proxy with input/output validation against the\n * Standard Schema definitions on the contract. The wrapper enforces data\n * integrity at the workflow → activity boundary in addition to the\n * activity-side validation that `declareActivitiesHandler` already runs.\n */\nexport function createValidatedActivities<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n>(\n rawActivities: Record<string, (...args: unknown[]) => Promise<unknown>>,\n workflowActivitiesDefinition: Record<string, ActivityDefinition> | undefined,\n contractActivitiesDefinition: Record<string, ActivityDefinition> | undefined,\n): WorkflowInferWorkflowContextActivities<TContract, TWorkflowName> {\n const validatedActivities = {} as WorkflowInferWorkflowContextActivities<\n TContract,\n TWorkflowName\n >;\n\n // Merge workflow-specific and global contract activities. defineContract\n // guarantees there are no name collisions across scopes, so spread order\n // is just a stable iteration choice (workflow-local last).\n const allActivitiesDefinition = {\n ...contractActivitiesDefinition,\n ...workflowActivitiesDefinition,\n };\n\n for (const [activityName, activityDef] of Object.entries(allActivitiesDefinition)) {\n const rawActivity = rawActivities[activityName];\n\n if (!rawActivity) {\n throw new Error(\n `Activity implementation not found for: \"${activityName}\". ` +\n `Available activities: ${Object.keys(rawActivities).length > 0 ? Object.keys(rawActivities).join(\", \") : \"none\"}`,\n );\n }\n\n (validatedActivities as Record<string, unknown>)[activityName] = async (input: unknown) => {\n const inputResult = await activityDef.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new ActivityInputValidationError(activityName, inputResult.issues);\n }\n\n const result = await rawActivity(inputResult.value);\n\n const outputResult = await activityDef.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n throw new ActivityOutputValidationError(activityName, outputResult.issues);\n }\n\n return outputResult.value;\n };\n }\n\n return validatedActivities;\n}\n","// Entry point for workflow implementations.\n//\n// Workflows run inside Temporal's deterministic sandbox, which intercepts\n// timers, randomness, and Promise scheduling for replay. neverthrow's\n// `Result`/`ResultAsync` rely only on Promise scheduling, so they replay\n// deterministically alongside Temporal's machinery. Activity code (see\n// activity.ts) uses the same neverthrow API.\nimport type {\n ActivityDefinition,\n ContractDefinition,\n QueryDefinition,\n QueryNamesOf,\n SignalDefinition,\n SignalNamesOf,\n UpdateDefinition,\n UpdateNamesOf,\n} from \"@temporal-contract/contract\";\nimport {\n ChildWorkflowCancelledError,\n ChildWorkflowError,\n ChildWorkflowNotFoundError,\n WorkflowCancelledError,\n WorkflowInputValidationError,\n WorkflowOutputValidationError,\n WorkflowScopeError,\n} from \"./errors.js\";\nimport { cancellableScope, nonCancellableScope } from \"./cancellation.js\";\nimport {\n bindQueryHandler,\n bindSignalHandler,\n bindUpdateHandler,\n type QueryHandlerImplementation,\n type SignalHandlerImplementation,\n type UpdateHandlerImplementation,\n} from \"./handlers.js\";\nimport {\n ClientInferInput,\n ClientInferOutput,\n WorkerInferInput,\n WorkerInferOutput,\n} from \"./types.js\";\nimport type { ResultAsync } from \"neverthrow\";\nimport {\n buildRawActivitiesProxy,\n createContinueAsNew,\n extractHandlerInput,\n type TypedContinueAsNewOptions,\n} from \"./internal.js\";\nimport {\n createStartChildWorkflow,\n createExecuteChildWorkflow,\n type TypedChildWorkflowHandle,\n type TypedChildWorkflowOptions,\n} from \"./child-workflow.js\";\nimport {\n createValidatedActivities,\n type WorkflowInferWorkflowContextActivities,\n} from \"./activities-proxy.js\";\nimport { ActivityOptions, WorkflowInfo, workflowInfo } from \"@temporalio/workflow\";\n\nexport {\n ActivityInputValidationError,\n ActivityOutputValidationError,\n ChildWorkflowCancelledError,\n ChildWorkflowError,\n ChildWorkflowNotFoundError,\n QueryInputValidationError,\n QueryOutputValidationError,\n SignalInputValidationError,\n UpdateInputValidationError,\n UpdateOutputValidationError,\n WorkflowCancelledError,\n WorkflowInputValidationError,\n WorkflowOutputValidationError,\n WorkflowScopeError,\n} from \"./errors.js\";\n\n/**\n * Create a typed workflow implementation with automatic validation\n *\n * This wraps a workflow implementation with:\n * - Input/output validation\n * - Typed workflow context with activities\n * - Workflow info access\n *\n * Workflows must be defined in separate files and imported by the Temporal Worker\n * via workflowsPath.\n *\n * @example\n * ```ts\n * // workflows/processOrder.ts\n * import { declareWorkflow } from '@temporal-contract/worker/workflow';\n * import myContract from '../contract';\n *\n * export const processOrder = declareWorkflow({\n * workflowName: 'processOrder',\n * contract: myContract,\n * activityOptions: {\n * startToCloseTimeout: '1 minute',\n * },\n * // Optional: override `activityOptions` for specific activities. Each\n * // entry shallow-merges over the workflow default — the override wins on\n * // every property it specifies, including the whole `retry` block.\n * activityOptionsByName: {\n * chargePayment: {\n * startToCloseTimeout: '5 minutes',\n * retry: { maximumAttempts: 5 },\n * },\n * },\n * implementation: async (context, args) => {\n * // context.activities: typed activities (workflow + global)\n * // context.info: WorkflowInfo\n *\n * const inventory = await context.activities.validateInventory({\n * orderId: args.orderId,\n * });\n *\n * if (!inventory.available) {\n * return { orderId: args.orderId, status: 'out_of_stock' };\n * }\n *\n * const payment = await context.activities.chargePayment({\n * customerId: args.customerId,\n * amount: 100,\n * });\n *\n * return {\n * orderId: args.orderId,\n * status: payment.success ? 'success' : 'failed',\n * transactionId: payment.transactionId,\n * };\n * },\n * });\n * ```\n *\n * Then in your worker setup:\n * ```ts\n * // worker.ts\n * import { createWorker } from '@temporal-contract/worker/worker';\n * import { activities } from './activities';\n * import myContract from './contract';\n *\n * const worker = await createWorker({\n * contract: myContract,\n * connection,\n * workflowsPath: workflowsPathFromURL(import.meta.url, './workflows.js'),\n * activities,\n * });\n * ```\n */\nexport function declareWorkflow<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n>({\n workflowName,\n contract,\n implementation,\n activityOptions,\n activityOptionsByName,\n}: DeclareWorkflowOptions<TContract, TWorkflowName>): (\n ...args: unknown[]\n) => Promise<WorkerInferOutput<TContract[\"workflows\"][TWorkflowName]>> {\n // Get the workflow definition from the contract\n const definition = contract.workflows[workflowName] as TContract[\"workflows\"][TWorkflowName];\n\n // Build the activities proxy *once* at declaration time, not per workflow\n // invocation. Temporal's `proxyActivities` is documented as a module-scope\n // helper — it registers stub functions and may carry bookkeeping\n // (validator pre-registration, payload-converter caching) that breaks if\n // re-invoked on every workflow run. The call depends only on contract-time\n // immutables (`definition.activities`, `contract.activities`,\n // `activityOptions`, `activityOptionsByName`), all of which are available\n // here, so hoisting is safe and deterministic.\n //\n // The validation wrapper (`createValidatedActivities`) is stateless across\n // invocations — it merely closes over the activity definitions and the raw\n // proxy, both immutable — so it is hoisted alongside the proxy. The\n // resulting `contextActivities` object is shared by every workflow run,\n // which is fine because the wrapped activity functions take their input\n // as an argument and validate it per-call (no closed-over per-invocation\n // state).\n //\n // Design note — intentional double-validation:\n // Input and output are validated here (workflow side) AND again inside\n // `declareActivitiesHandler` (activity worker side). This is deliberate:\n //\n // 1. Workflow-side validation catches bad data *before* it crosses the\n // task-queue network boundary, giving an early, descriptive error\n // instead of a confusing deserialization failure inside the activity.\n // 2. Activity-side validation is the authoritative guard, since the\n // activity may be called by other callers that do not use this library.\n //\n // The overhead is minimal relative to the network round-trip.\n let contextActivities: unknown = {};\n\n if (definition.activities || contract.activities) {\n const rawActivities = buildRawActivitiesProxy(\n definition.activities,\n contract.activities,\n activityOptions,\n activityOptionsByName,\n );\n\n contextActivities = createValidatedActivities(\n rawActivities,\n definition.activities,\n contract.activities,\n );\n\n // Shared across workflow invocations after the proxyActivities hoist\n // (PR #211); freeze so user code can't mutate one invocation's view of\n // activities and have it leak into others. The freeze is shallow, which\n // is sufficient because `createValidatedActivities` returns a flat\n // `{ [name]: (input) => Promise<output> }` map — every value is a\n // stateless validation wrapper function, not a nested object users could\n // reach into. The matching `Readonly<...>` on `WorkflowContext.activities`\n // surfaces the immutability at the type level.\n Object.freeze(contextActivities);\n }\n\n return async (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n\n // Validate workflow input\n const inputResult = await definition.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new WorkflowInputValidationError(workflowName, inputResult.issues);\n }\n const validatedInput = inputResult.value as WorkerInferInput<\n TContract[\"workflows\"][TWorkflowName]\n >;\n\n // Create workflow context.\n //\n // The defineSignal / defineQuery / defineUpdate arrows forward to the\n // hoisted helpers in `./handlers.ts`. The arrows themselves are thin\n // closures that close over `definition` and `workflowName`; the heavy\n // logic — runtime guards, validation, Temporal `defineSignal/Query/\n // Update` + `setHandler` wiring — lives at module scope so it isn't\n // reallocated on each workflow invocation.\n //\n // The cast at each assignment preserves the typed call-site surface\n // (the `K extends keyof ...` constraints declared on\n // `WorkflowContext.defineSignal/Query/Update`), while the helpers\n // themselves take loosely-typed arguments at the runtime boundary.\n const context: WorkflowContext<TContract, TWorkflowName> = {\n activities: contextActivities as WorkflowInferWorkflowContextActivities<\n TContract,\n TWorkflowName\n >,\n info: workflowInfo(),\n startChildWorkflow: createStartChildWorkflow,\n executeChildWorkflow: createExecuteChildWorkflow,\n cancellableScope,\n nonCancellableScope,\n defineSignal: ((signalName, handler) =>\n bindSignalHandler(\n definition,\n workflowName,\n signalName,\n handler as unknown as SignalHandlerImplementation<SignalDefinition>,\n )) as WorkflowContext<TContract, TWorkflowName>[\"defineSignal\"],\n defineQuery: ((queryName, handler) =>\n bindQueryHandler(\n definition,\n workflowName,\n queryName,\n handler as unknown as QueryHandlerImplementation<QueryDefinition>,\n )) as WorkflowContext<TContract, TWorkflowName>[\"defineQuery\"],\n defineUpdate: ((updateName, handler) =>\n bindUpdateHandler(\n definition,\n workflowName,\n updateName,\n handler as unknown as UpdateHandlerImplementation<UpdateDefinition>,\n )) as WorkflowContext<TContract, TWorkflowName>[\"defineUpdate\"],\n continueAsNew: createContinueAsNew(contract, workflowName) as WorkflowContext<\n TContract,\n TWorkflowName\n >[\"continueAsNew\"],\n };\n\n // Execute workflow (pass validated input as tuple)\n const result = await implementation(context, validatedInput);\n\n // Validate workflow output\n const outputResult = await definition.output[\"~standard\"].validate(result);\n if (outputResult.issues) {\n throw new WorkflowOutputValidationError(workflowName, outputResult.issues);\n }\n\n return outputResult.value as WorkerInferOutput<TContract[\"workflows\"][TWorkflowName]>;\n };\n}\n\n/**\n * Union of all activity names available to a workflow — the workflow-local\n * activities plus the contract's global activities.\n */\ntype ActivityNamesFor<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> =\n | (TContract[\"workflows\"][TWorkflowName][\"activities\"] extends Record<string, ActivityDefinition>\n ? keyof TContract[\"workflows\"][TWorkflowName][\"activities\"] & string\n : never)\n | (TContract[\"activities\"] extends Record<string, ActivityDefinition>\n ? keyof TContract[\"activities\"] & string\n : never);\n\n/**\n * Options for declaring a workflow implementation\n */\ntype DeclareWorkflowOptions<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> = {\n workflowName: TWorkflowName;\n contract: TContract;\n implementation: WorkflowImplementation<TContract, TWorkflowName>;\n /**\n * Default activity options applied to every activity reachable from this\n * workflow (workflow-local + global) unless overridden in\n * {@link activityOptionsByName}. See Temporal's `ActivityOptions` for the\n * full set of fields:\n * - `startToCloseTimeout`: Maximum time for a single attempt to run\n * - `scheduleToCloseTimeout`: End-to-end timeout including queuing and retries\n * - `scheduleToStartTimeout`: Maximum time the activity can wait in the queue\n * - `heartbeatTimeout`: Time between heartbeats before the activity is considered dead\n * - `retry`: Retry policy for failed activities\n *\n * @example\n * ```ts\n * activityOptions: {\n * startToCloseTimeout: '5m',\n * retry: { maximumAttempts: 3 },\n * }\n * ```\n */\n activityOptions: ActivityOptions;\n /**\n * Per-activity `ActivityOptions` overrides. Each entry shallow-merges over\n * {@link activityOptions} for that activity only — the override wins on\n * every property it specifies, replacing the default value (including the\n * entire nested `retry` block when present, matching Temporal's\n * single-options-per-`proxyActivities`-call semantics).\n *\n * Activity names are typed against the contract; typos surface as TypeScript\n * errors rather than running silently with the default options.\n *\n * @example\n * ```ts\n * activityOptions: { startToCloseTimeout: '1 minute' }, // default\n * activityOptionsByName: {\n * chargePayment: {\n * startToCloseTimeout: '5 minutes',\n * retry: { maximumAttempts: 5 },\n * },\n * fastValidation: { startToCloseTimeout: '5 seconds' },\n * },\n * ```\n */\n activityOptionsByName?: Partial<\n Record<ActivityNamesFor<TContract, TWorkflowName>, ActivityOptions>\n >;\n};\n\n/**\n * Workflow implementation function\n *\n * Receives a workflow context (with typed activities and utilities) and validated input arguments.\n * Returns the workflow output which will be validated against the contract schema.\n */\ntype WorkflowImplementation<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> = (\n context: WorkflowContext<TContract, TWorkflowName>,\n args: WorkerInferInput<TContract[\"workflows\"][TWorkflowName]>,\n) => Promise<WorkerInferOutput<TContract[\"workflows\"][TWorkflowName]>>;\n\n/**\n * Workflow execution context providing typed activities, workflow info, and interaction handlers\n *\n * Provides access to:\n * - Typed activities (both workflow-specific and global)\n * - Workflow metadata and execution info\n * - Signal, query, and update handler registration\n * - Child workflow execution capabilities\n */\ntype WorkflowContext<\n TContract extends ContractDefinition,\n TWorkflowName extends keyof TContract[\"workflows\"] & string,\n> = {\n activities: Readonly<WorkflowInferWorkflowContextActivities<TContract, TWorkflowName>>;\n info: WorkflowInfo;\n\n /**\n * Define a signal handler within the workflow implementation\n * Allows the signal handler to access workflow state\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * let currentValue = args.initialValue;\n *\n * context.defineSignal('increment', async (signalArgs) => {\n * currentValue += signalArgs.amount;\n * });\n *\n * // ... rest of workflow\n * }\n * ```\n */\n defineSignal: <K extends SignalNamesOf<TContract[\"workflows\"][TWorkflowName]>>(\n signalName: K,\n handler: SignalHandlerImplementation<\n NonNullable<TContract[\"workflows\"][TWorkflowName][\"signals\"]> extends Record<\n string,\n SignalDefinition\n >\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"signals\"]>[K] extends SignalDefinition\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"signals\"]>[K]\n : never\n : never\n >,\n ) => void;\n\n /**\n * Define a query handler within the workflow implementation\n * Allows the query handler to access workflow state\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * let currentValue = args.initialValue;\n *\n * context.defineQuery('getCurrentValue', () => {\n * return { value: currentValue };\n * });\n *\n * // ... rest of workflow\n * }\n * ```\n */\n defineQuery: <K extends QueryNamesOf<TContract[\"workflows\"][TWorkflowName]>>(\n queryName: K,\n handler: QueryHandlerImplementation<\n NonNullable<TContract[\"workflows\"][TWorkflowName][\"queries\"]> extends Record<\n string,\n QueryDefinition\n >\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"queries\"]>[K] extends QueryDefinition\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"queries\"]>[K]\n : never\n : never\n >,\n ) => void;\n\n /**\n * Define an update handler within the workflow implementation\n * Allows the update handler to access and modify workflow state\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * let currentValue = args.initialValue;\n *\n * context.defineUpdate('multiply', async (updateArgs) => {\n * currentValue *= updateArgs.factor;\n * return { newValue: currentValue };\n * });\n *\n * // ... rest of workflow\n * }\n * ```\n */\n defineUpdate: <K extends UpdateNamesOf<TContract[\"workflows\"][TWorkflowName]>>(\n updateName: K,\n handler: UpdateHandlerImplementation<\n NonNullable<TContract[\"workflows\"][TWorkflowName][\"updates\"]> extends Record<\n string,\n UpdateDefinition\n >\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"updates\"]>[K] extends UpdateDefinition\n ? NonNullable<TContract[\"workflows\"][TWorkflowName][\"updates\"]>[K]\n : never\n : never\n >,\n ) => void;\n\n /**\n * Start a child workflow and return a typed handle with ResultAsync pattern\n *\n * Supports both same-contract and cross-contract child workflows:\n * - Same contract: Pass workflowName from current contract\n * - Cross-contract: Pass contract and workflowName to invoke workflows from other workers\n *\n * @example\n * ```ts\n * // Same contract child workflow\n * const childResult = await context.startChildWorkflow(myContract, 'processPayment', {\n * workflowId: 'payment-123',\n * args: { amount: 100 }\n * });\n *\n * // Cross-contract child workflow (from another worker)\n * const otherResult = await context.startChildWorkflow(otherContract, 'sendNotification', {\n * workflowId: 'notification-123',\n * args: { message: 'Hello' }\n * });\n *\n * childResult.match(\n * async (handle) => {\n * const result = await handle.result();\n * // ... handle result\n * },\n * (error) => console.error('Failed to start:', error),\n * );\n * ```\n */\n startChildWorkflow: <\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n >(\n contract: TChildContract,\n workflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n ) => ResultAsync<\n TypedChildWorkflowHandle<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError\n >;\n\n /**\n * Execute a child workflow (start and wait for result) with ResultAsync pattern\n *\n * Supports both same-contract and cross-contract child workflows:\n * - Same contract: Pass workflowName from current contract\n * - Cross-contract: Pass contract and workflowName to invoke workflows from other workers\n *\n * @example\n * ```ts\n * // Same contract child workflow\n * const result = await context.executeChildWorkflow(myContract, 'processPayment', {\n * workflowId: 'payment-123',\n * args: { amount: 100 }\n * });\n *\n * // Cross-contract child workflow (from another worker)\n * const otherResult = await context.executeChildWorkflow(otherContract, 'sendNotification', {\n * workflowId: 'notification-123',\n * args: { message: 'Hello' }\n * });\n *\n * result.match(\n * (output) => console.log('Payment processed:', output),\n * (error) => console.error('Processing failed:', error),\n * );\n * ```\n */\n executeChildWorkflow: <\n TChildContract extends ContractDefinition,\n TChildWorkflowName extends keyof TChildContract[\"workflows\"] & string,\n >(\n contract: TChildContract,\n workflowName: TChildWorkflowName,\n options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>,\n ) => ResultAsync<\n ClientInferOutput<TChildContract[\"workflows\"][TChildWorkflowName]>,\n ChildWorkflowError | ChildWorkflowCancelledError | ChildWorkflowNotFoundError\n >;\n\n /**\n * Run `fn` inside a cancellable Temporal scope. If the workflow (or an\n * ancestor scope) is cancelled while `fn` is in flight, the resulting\n * ResultAsync resolves to `err(WorkflowCancelledError)` instead of\n * rejecting — letting callers handle cancellation explicitly, typically\n * to perform a graceful exit from the current step.\n *\n * Non-cancellation errors thrown by `fn` resolve to\n * `err(WorkflowScopeError)` (with the original error preserved on\n * `cause`). Both failure modes ride neverthrow's railway, so\n * `result.match(...)` is exhaustive — nothing escapes as an unhandled\n * rejection.\n *\n * @example\n * ```ts\n * implementation: async (context, args) => {\n * const result = await context.cancellableScope(async () => {\n * return context.activities.processStep(args);\n * });\n *\n * if (result.isErr()) {\n * if (result.error instanceof WorkflowCancelledError) {\n * // workflow was cancelled — perform cleanup that must not be cancelled:\n * await context.nonCancellableScope(async () => {\n * await context.activities.releaseResources(args);\n * });\n * return { status: \"cancelled\" };\n * }\n * // result.error instanceof WorkflowScopeError — domain failure\n * return { status: \"failed\" };\n * }\n *\n * return { status: \"ok\" };\n * }\n * ```\n */\n cancellableScope: <T>(\n fn: () => T | Promise<T>,\n ) => ResultAsync<T, WorkflowCancelledError | WorkflowScopeError>;\n\n /**\n * Run `fn` inside a non-cancellable Temporal scope. Cancellation requests\n * from outside the scope are ignored for its duration — the idiomatic way\n * to perform cleanup work that must not be interrupted.\n *\n * Returns the same `ResultAsync<...>` shape as\n * {@link WorkflowContext.cancellableScope} for symmetry; the\n * `err(WorkflowCancelledError)` branch only triggers when cancellation is\n * raised from *inside* the scope, which is rare. Non-cancellation errors\n * surface as `err(WorkflowScopeError)`.\n */\n nonCancellableScope: <T>(\n fn: () => T | Promise<T>,\n ) => ResultAsync<T, WorkflowCancelledError | WorkflowScopeError>;\n\n /**\n * Continue this workflow execution as a new run, optionally with a different\n * workflow type from another contract.\n *\n * Args are validated against the destination workflow's input schema before\n * Temporal's `continueAsNew` is invoked. On validation failure, throws a\n * {@link WorkflowInputValidationError}; on success, Temporal terminates the\n * current execution and starts a fresh one — which is why the function\n * never returns normally (`Promise<never>`).\n *\n * Idiomatic usage:\n *\n * @example\n * ```ts\n * // Same workflow, validated args\n * implementation: async (context, args) => {\n * if (shouldRoll(args)) {\n * return context.continueAsNew({ ...args, retryCount: args.retryCount + 1 });\n * }\n * return ...;\n * }\n *\n * // Cross-contract continueAsNew (less common — taskQueue and workflow type\n * // come from the other contract)\n * return context.continueAsNew(otherContract, \"otherWorkflow\", { ...newArgs });\n * ```\n */\n continueAsNew: {\n /** Same-workflow continuation — args typed against this workflow's input. */\n (\n args: ClientInferInput<TContract[\"workflows\"][TWorkflowName]>,\n options?: TypedContinueAsNewOptions,\n ): Promise<never>;\n /** Cross-contract continuation — args typed against the destination workflow. */\n <\n TOtherContract extends ContractDefinition,\n TOtherWorkflowName extends keyof TOtherContract[\"workflows\"] & string,\n >(\n contract: TOtherContract,\n workflowName: TOtherWorkflowName,\n args: ClientInferInput<TOtherContract[\"workflows\"][TOtherWorkflowName]>,\n options?: TypedContinueAsNewOptions,\n ): Promise<never>;\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAUD,SAAO,OAAO,kBAAkB;;AAGlC,QAAO,OAAO,GAAG,SAAoB;EACnC,MAAM,QAAQ,oBAAoB,KAAK;EAGvC,MAAM,cAAc,MAAM,WAAW,MAAM,aAAa,SAAS,MAAM;AACvE,MAAI,YAAY,OACd,OAAM,IAAI,6BAA6B,cAAc,YAAY,OAAO;EAE1E,MAAM,iBAAiB,YAAY;EAuDnC,MAAM,SAAS,MAAM,eAAe;GArClC,YAAY;GAIZ,MAAM,cAAc;GACpB,oBAAoB;GACpB,sBAAsB;GACtB;GACA;GACA,gBAAgB,YAAY,YAC1B,kBACE,YACA,cACA,YACA,QACD;GACH,eAAe,WAAW,YACxB,iBACE,YACA,cACA,WACA,QACD;GACH,gBAAgB,YAAY,YAC1B,kBACE,YACA,cACA,YACA,QACD;GACH,eAAe,oBAAoB,UAAU,aAAa;GAOjB,EAAE,eAAe;EAG5D,MAAM,eAAe,MAAM,WAAW,OAAO,aAAa,SAAS,OAAO;AAC1E,MAAI,aAAa,OACf,OAAM,IAAI,8BAA8B,cAAc,aAAa,OAAO;AAG5E,SAAO,aAAa"}
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@temporal-contract/worker",
|
|
3
|
-
"version": "1.0
|
|
4
|
-
"description": "Worker utilities with Result/
|
|
3
|
+
"version": "2.1.0",
|
|
4
|
+
"description": "Worker utilities with neverthrow Result/ResultAsync for implementing temporal-contract workflows and activities",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"contract",
|
|
7
|
-
"
|
|
7
|
+
"neverthrow",
|
|
8
8
|
"result",
|
|
9
9
|
"temporal",
|
|
10
10
|
"typescript",
|
|
@@ -60,32 +60,32 @@
|
|
|
60
60
|
},
|
|
61
61
|
"dependencies": {
|
|
62
62
|
"@standard-schema/spec": "1.1.0",
|
|
63
|
-
"@
|
|
64
|
-
"@temporal-contract/boxed": "1.0.0",
|
|
65
|
-
"@temporal-contract/contract": "1.0.0"
|
|
63
|
+
"@temporal-contract/contract": "2.1.0"
|
|
66
64
|
},
|
|
67
65
|
"devDependencies": {
|
|
68
|
-
"@temporalio/client": "1.
|
|
69
|
-
"@temporalio/common": "1.
|
|
70
|
-
"@temporalio/worker": "1.
|
|
71
|
-
"@temporalio/workflow": "1.
|
|
66
|
+
"@temporalio/client": "1.17.0",
|
|
67
|
+
"@temporalio/common": "1.17.0",
|
|
68
|
+
"@temporalio/worker": "1.17.0",
|
|
69
|
+
"@temporalio/workflow": "1.17.0",
|
|
72
70
|
"@types/node": "24.12.2",
|
|
73
71
|
"@vitest/coverage-v8": "4.1.5",
|
|
72
|
+
"neverthrow": "8.2.0",
|
|
74
73
|
"tsdown": "0.21.10",
|
|
75
74
|
"typedoc": "0.28.19",
|
|
76
75
|
"typedoc-plugin-markdown": "4.11.0",
|
|
77
76
|
"typescript": "6.0.3",
|
|
78
77
|
"vitest": "4.1.5",
|
|
79
|
-
"zod": "4.3
|
|
80
|
-
"@temporal-contract/
|
|
81
|
-
"@temporal-contract/testing": "1.0.0",
|
|
78
|
+
"zod": "4.4.3",
|
|
79
|
+
"@temporal-contract/testing": "2.1.0",
|
|
82
80
|
"@temporal-contract/tsconfig": "1.0.0",
|
|
81
|
+
"@temporal-contract/client": "2.1.0",
|
|
83
82
|
"@temporal-contract/typedoc": "0.1.0"
|
|
84
83
|
},
|
|
85
84
|
"peerDependencies": {
|
|
86
85
|
"@temporalio/common": "^1",
|
|
87
86
|
"@temporalio/worker": "^1",
|
|
88
|
-
"@temporalio/workflow": "^1"
|
|
87
|
+
"@temporalio/workflow": "^1",
|
|
88
|
+
"neverthrow": "^8"
|
|
89
89
|
},
|
|
90
90
|
"scripts": {
|
|
91
91
|
"build": "tsdown src/activity.ts src/worker.ts src/workflow.ts --format cjs,esm --dts --clean",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"internal-BoNcEtYh.mjs","names":[],"sources":["../src/format.ts","../src/errors.ts","../src/internal.ts"],"sourcesContent":["/**\n * Issue / validation-message formatters.\n *\n * Lives in its own module (separate from `errors.ts` and `internal.ts`) so\n * both can import these helpers without forming a circular dependency:\n * `errors.ts` -> `format.ts` and `internal.ts` -> `format.ts` are both safe,\n * even when `internal.ts` later needs to import error classes from\n * `errors.ts` (as `createContinueAsNew` does).\n *\n * Not part of the package's public exports map.\n */\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * Pattern for string keys safe to render with dot notation. A \"safe\" key is a\n * JavaScript identifier (letters/digits/underscore/$, not starting with a\n * digit). Anything else — keys containing dots, spaces, leading digits, the\n * empty string, the literal string `\"0\"` etc. — gets bracket-quoted so the\n * path is unambiguous. Reserved words are accepted: we are formatting a\n * diagnostic, not generating runnable code.\n */\nconst SAFE_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * Render a Standard Schema {@link StandardSchemaV1.Issue} into a human-readable\n * string that includes the failing field's path.\n */\nexport function formatIssue(issue: StandardSchemaV1.Issue): string {\n if (issue.path === undefined || issue.path.length === 0) {\n return issue.message;\n }\n let path = \"\";\n for (let i = 0; i < issue.path.length; i++) {\n const segment = issue.path[i];\n const key =\n segment !== null && typeof segment === \"object\" && \"key\" in segment ? segment.key : segment;\n if (typeof key === \"number\") {\n path += `[${key}]`;\n } else if (typeof key === \"string\" && SAFE_IDENTIFIER.test(key)) {\n path += i === 0 ? key : `.${key}`;\n } else if (typeof key === \"string\") {\n path += `[${JSON.stringify(key)}]`;\n } else {\n path += `[${String(key)}]`;\n }\n }\n return `at ${path}: ${issue.message}`;\n}\n\n/**\n * Join a list of validation issues into a single message, with each issue\n * rendered via {@link formatIssue} so field paths surface in the error text.\n */\nexport function summarizeIssues(issues: ReadonlyArray<StandardSchemaV1.Issue>): string {\n return issues.map(formatIssue).join(\"; \");\n}\n\n/**\n * Build the message attached to a `ChildWorkflowError` for input/output\n * validation failures. Centralized so the worker and any future call sites\n * format identically.\n */\nexport function formatChildWorkflowValidationMessage(\n workflowName: string,\n direction: \"input\" | \"output\",\n issues: ReadonlyArray<StandardSchemaV1.Issue>,\n): string {\n return `Child workflow \"${workflowName}\" ${direction} validation failed: ${summarizeIssues(issues)}`;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { summarizeIssues } from \"./format.js\";\n\n/**\n * Base error class for worker errors\n */\nabstract class WorkerError extends Error {\n protected constructor(message: string, cause?: unknown) {\n super(message, { cause });\n this.name = \"WorkerError\";\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Error thrown when an activity definition is not found in the contract\n */\nexport class ActivityDefinitionNotFoundError extends WorkerError {\n constructor(\n public readonly activityName: string,\n public readonly availableDefinitions: readonly string[] = [],\n ) {\n const available = availableDefinitions.length > 0 ? availableDefinitions.join(\", \") : \"none\";\n super(\n `Activity definition not found for: \"${activityName}\". Available activities: ${available}`,\n );\n this.name = \"ActivityDefinitionNotFoundError\";\n }\n}\n\n/**\n * Error thrown when activity input validation fails\n */\nexport class ActivityInputValidationError extends WorkerError {\n constructor(\n public readonly activityName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Activity \"${activityName}\" input validation failed: ${message}`);\n this.name = \"ActivityInputValidationError\";\n }\n}\n\n/**\n * Error thrown when activity output validation fails\n */\nexport class ActivityOutputValidationError extends WorkerError {\n constructor(\n public readonly activityName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Activity \"${activityName}\" output validation failed: ${message}`);\n this.name = \"ActivityOutputValidationError\";\n }\n}\n\n/**\n * Error thrown when workflow input validation fails\n */\nexport class WorkflowInputValidationError extends WorkerError {\n constructor(\n public readonly workflowName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Workflow \"${workflowName}\" input validation failed: ${message}`);\n this.name = \"WorkflowInputValidationError\";\n }\n}\n\n/**\n * Error thrown when workflow output validation fails\n */\nexport class WorkflowOutputValidationError extends WorkerError {\n constructor(\n public readonly workflowName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Workflow \"${workflowName}\" output validation failed: ${message}`);\n this.name = \"WorkflowOutputValidationError\";\n }\n}\n\n/**\n * Error thrown when signal input validation fails\n */\nexport class SignalInputValidationError extends WorkerError {\n constructor(\n public readonly signalName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Signal \"${signalName}\" input validation failed: ${message}`);\n this.name = \"SignalInputValidationError\";\n }\n}\n\n/**\n * Error thrown when query input validation fails\n */\nexport class QueryInputValidationError extends WorkerError {\n constructor(\n public readonly queryName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Query \"${queryName}\" input validation failed: ${message}`);\n this.name = \"QueryInputValidationError\";\n }\n}\n\n/**\n * Error thrown when query output validation fails\n */\nexport class QueryOutputValidationError extends WorkerError {\n constructor(\n public readonly queryName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Query \"${queryName}\" output validation failed: ${message}`);\n this.name = \"QueryOutputValidationError\";\n }\n}\n\n/**\n * Error thrown when update input validation fails\n */\nexport class UpdateInputValidationError extends WorkerError {\n constructor(\n public readonly updateName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Update \"${updateName}\" input validation failed: ${message}`);\n this.name = \"UpdateInputValidationError\";\n }\n}\n\n/**\n * Error thrown when update output validation fails\n */\nexport class UpdateOutputValidationError extends WorkerError {\n constructor(\n public readonly updateName: string,\n public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,\n ) {\n const message = summarizeIssues(issues);\n super(`Update \"${updateName}\" output validation failed: ${message}`);\n this.name = \"UpdateOutputValidationError\";\n }\n}\n\n/**\n * Error thrown when a child workflow is not found in the contract\n */\nexport class ChildWorkflowNotFoundError extends WorkerError {\n constructor(\n public readonly workflowName: string,\n public readonly availableWorkflows: readonly string[] = [],\n ) {\n const available = availableWorkflows.length > 0 ? availableWorkflows.join(\", \") : \"none\";\n super(`Child workflow not found: \"${workflowName}\". Available workflows: ${available}`);\n this.name = \"ChildWorkflowNotFoundError\";\n }\n}\n\n/**\n * Generic error for child workflow operations\n */\nexport class ChildWorkflowError extends WorkerError {\n constructor(message: string, cause?: unknown) {\n super(message, cause);\n this.name = \"ChildWorkflowError\";\n }\n}\n\n/**\n * Error returned in the `Result.Error` branch when a typed cancellation\n * scope is cancelled via Temporal's cancellation propagation. Returned by\n * both `context.cancellableScope` (when the workflow or an ancestor scope\n * cancels) and `context.nonCancellableScope` (when cancellation is raised\n * from inside the scope). Distinct from arbitrary thrown errors so call\n * sites can branch on cancellation explicitly while still surfacing\n * non-cancellation errors as Future rejections.\n */\nexport class WorkflowCancelledError extends WorkerError {\n constructor(cause?: unknown) {\n super(\"Workflow cancellation scope was cancelled\", cause);\n this.name = \"WorkflowCancelledError\";\n }\n}\n","/**\n * Internal helpers shared across the worker package's entry points.\n *\n * Not part of the public API — this module is not listed in the package's\n * `exports` map, so consumers can't import from `@temporal-contract/worker/internal`.\n * In-package tests import it directly via relative path.\n */\nimport { makeContinueAsNewFunc, proxyActivities } from \"@temporalio/workflow\";\nimport type { ActivityOptions, ContinueAsNewOptions } from \"@temporalio/workflow\";\nimport type { ActivityDefinition, ContractDefinition } from \"@temporal-contract/contract\";\nimport { WorkflowInputValidationError } from \"./errors.js\";\n\n// Re-export the formatters so workflow.ts and existing tests can keep\n// importing from `./internal.js`. Their canonical home is `./format.js`,\n// which both `errors.ts` and `internal.ts` import from to avoid a\n// circular dependency once `internal.ts` started importing error classes.\nexport { formatIssue, summarizeIssues, formatChildWorkflowValidationMessage } from \"./format.js\";\n\n/**\n * Extract the single payload from a Temporal handler's `...args` array.\n *\n * Temporal invokes handlers with whatever was passed via `args: [...]` at the\n * call site. The typed-contract layer always sends `args: [validatedInput]`,\n * so the common case is a one-element array containing the wrapped input.\n *\n * If a non-typed-contract caller passes multiple positional arguments\n * (`args: [a, b, c]`), we surface the whole array as the input — the schema\n * will then reject it unless the contract specifically modeled a tuple.\n */\nexport function extractHandlerInput(args: unknown[]): unknown {\n return args.length === 1 ? args[0] : args;\n}\n\ntype ActivityFn = (...args: unknown[]) => Promise<unknown>;\n\n/**\n * Build the raw `Record<name, fn>` proxy of activities for a workflow,\n * applying per-activity `ActivityOptions` overrides where requested.\n *\n * **Fast path (no overrides):** a single `proxyActivities(defaultOptions)`\n * call is made and returned directly. The proxy synthesizes a function for\n * any property access by name, so downstream code that looks up\n * `proxy[activityName]` works identically to before.\n *\n * **Override path:** one extra `proxyActivities(merged)` call is made *only*\n * for each activity that has an override. Activities without an entry keep\n * using the single default proxy. The result is a `Proxy` that returns the\n * override-bound function for named keys and falls back to the default proxy\n * for everything else — so the per-execution overhead scales with the number\n * of overrides, not the number of activities.\n *\n * Per-override merge is shallow: the override's properties replace the\n * default's, including the entire nested `retry` block. This matches\n * Temporal's \"one ActivityOptions per `proxyActivities` call\" semantics.\n */\nexport function buildRawActivitiesProxy(\n workflowActivities: Record<string, ActivityDefinition> | undefined,\n contractActivities: Record<string, ActivityDefinition> | undefined,\n defaultOptions: ActivityOptions,\n overrides: Partial<Record<string, ActivityOptions>> | undefined,\n): Record<string, ActivityFn> {\n const defaultProxy = proxyActivities<Record<string, ActivityFn>>(defaultOptions);\n\n // Fast path: no overrides → use the single default proxy directly.\n // (`createValidatedActivities` accesses by name, so the Proxy's get-trap\n // suffices; we don't need an enumerable map.)\n const overrideEntries = overrides\n ? Object.entries(overrides).filter(\n (entry): entry is [string, ActivityOptions] => entry[1] !== undefined,\n )\n : [];\n if (overrideEntries.length === 0) {\n return defaultProxy;\n }\n\n // Validate every override key corresponds to a declared activity.\n // Without this, a typo at runtime (or a stale options bag from a renamed\n // activity) silently builds a proxy for a non-existent activity.\n const declared = new Set<string>([\n ...Object.keys(workflowActivities ?? {}),\n ...Object.keys(contractActivities ?? {}),\n ]);\n for (const [name] of overrideEntries) {\n if (!declared.has(name)) {\n throw new Error(\n `activityOptionsByName entry \"${name}\" does not match any declared activity. Available: ${[...declared].join(\", \") || \"none\"}.`,\n );\n }\n }\n\n // Override path: build one proxy per override; combine with the default\n // proxy via a get-trap so unmatched keys still get the default options.\n const overriddenFns: Record<string, ActivityFn> = {};\n for (const [name, override] of overrideEntries) {\n const mergedOptions: ActivityOptions = { ...defaultOptions, ...override };\n const overrideProxy = proxyActivities<Record<string, ActivityFn>>(mergedOptions);\n const fn = overrideProxy[name];\n if (fn !== undefined) {\n overriddenFns[name] = fn;\n }\n }\n\n return new Proxy(overriddenFns, {\n get(target, prop) {\n if (typeof prop !== \"string\") return undefined;\n return target[prop] ?? defaultProxy[prop];\n },\n });\n}\n\n/**\n * Continue-as-new options the typed wrapper does not own. `workflowType` and\n * `taskQueue` are derived from the contract; everything else is forwarded to\n * Temporal's `makeContinueAsNewFunc`.\n */\nexport type TypedContinueAsNewOptions = Omit<ContinueAsNewOptions, \"workflowType\" | \"taskQueue\">;\n\n/**\n * Build the typed `continueAsNew` function bound to the running workflow's\n * contract. Two overloads — same-workflow and cross-contract — share one\n * implementation; the public type signature lives on `WorkflowContext` so\n * call sites are type-safe.\n *\n * Validation runs *before* Temporal's `makeContinueAsNewFunc(...)` is invoked.\n * On failure, throws a `WorkflowInputValidationError` (matching the behaviour\n * of `declareWorkflow`'s incoming-input validation), which surfaces back to\n * Temporal as a workflow failure rather than silently proceeding with an\n * invalid run.\n *\n * Temporal's `continueAsNew` never returns — it throws a `ContinueAsNew`\n * exception that the runtime intercepts. The returned function preserves\n * `Promise<never>` to encode that.\n *\n * @internal\n */\nexport function createContinueAsNew(\n currentContract: ContractDefinition,\n currentWorkflowName: string | number | symbol,\n) {\n return async function continueAsNew(\n arg1: unknown,\n arg2?: unknown,\n arg3?: unknown,\n arg4?: TypedContinueAsNewOptions,\n ): Promise<never> {\n // Cross-contract dispatch is only triggered when the call signature\n // unambiguously matches `(contract, workflowName, args, options?)`:\n //\n // 1. `arg1` is a non-null object that *looks like* a contract — it has a\n // string `taskQueue` and a non-null `workflows` object.\n // 2. `arg2` is a string — the destination workflow name.\n // 3. `arg2` resolves to a workflow definition on `arg1.workflows` with a\n // Standard Schema `input.~standard.validate` function.\n //\n // Without (2)+(3), a same-workflow input that happens to have `taskQueue`\n // and `workflows` keys (or `workflows = null`, where `typeof === \"object\"`)\n // would be silently misclassified. The full triple of structural checks\n // makes the false-positive surface vanishingly small.\n const isCrossContract = looksLikeCrossContractCall(arg1, arg2);\n\n let targetContract: ContractDefinition;\n let targetName: string;\n let rawArgs: unknown;\n let options: TypedContinueAsNewOptions | undefined;\n\n if (isCrossContract) {\n targetContract = arg1 as ContractDefinition;\n targetName = arg2 as string;\n rawArgs = arg3;\n options = arg4;\n } else {\n targetContract = currentContract;\n targetName = String(currentWorkflowName);\n rawArgs = arg1;\n options = arg2 as TypedContinueAsNewOptions | undefined;\n }\n\n const targetDef = targetContract.workflows[targetName];\n if (!targetDef) {\n throw new WorkflowInputValidationError(targetName, [\n {\n message: `continueAsNew target workflow \"${targetName}\" is not declared on the supplied contract.`,\n },\n ]);\n }\n\n const inputResult = await targetDef.input[\"~standard\"].validate(rawArgs);\n if (inputResult.issues) {\n throw new WorkflowInputValidationError(targetName, inputResult.issues);\n }\n\n // workflowType/taskQueue come from the destination contract; user\n // options are spread last so power users can override (e.g. retry,\n // memo). The public TypedContinueAsNewOptions type Omits workflowType\n // and taskQueue so this isn't a footgun on the typed call path.\n const fn = makeContinueAsNewFunc({\n workflowType: targetName,\n taskQueue: targetContract.taskQueue,\n ...options,\n });\n\n await fn(inputResult.value);\n // Unreachable — Temporal's continueAsNew throws to terminate the run.\n /* c8 ignore next */\n return undefined as never;\n };\n}\n\n/**\n * Structural check: does `(arg1, arg2)` look like the\n * `(contract, workflowName, ...)` cross-contract overload of `continueAsNew`?\n *\n * Returns `true` only when:\n * 1. `arg1` is a non-null object with a string `taskQueue` and a non-null\n * object `workflows` (handles `workflows: null`, where\n * `typeof null === \"object\"`).\n * 2. `arg2` is a string.\n *\n * Both halves matter. A same-workflow input that happens to contain\n * `taskQueue` and `workflows` keys would otherwise be misclassified — but\n * none of the same-workflow signatures (`continueAsNew(args)`,\n * `continueAsNew(args, options)`) accept a string as `arg2`, so the\n * second check makes the false-positive surface vanishingly small.\n *\n * We deliberately do *not* check that `arg1.workflows[arg2]` is a valid\n * workflow definition. If it isn't, the dispatcher falls through to the\n * `targetContract.workflows[targetName]` lookup which throws a clear\n * \"target workflow X is not declared\" error — better than silently\n * misrouting a typo back to the current workflow.\n */\nfunction looksLikeCrossContractCall(arg1: unknown, arg2: unknown): boolean {\n if (typeof arg1 !== \"object\" || arg1 === null) return false;\n if (typeof arg2 !== \"string\") return false;\n const candidate = arg1 as Record<string, unknown>;\n if (typeof candidate[\"taskQueue\"] !== \"string\") return false;\n const workflows = candidate[\"workflows\"];\n return typeof workflows === \"object\" && workflows !== null;\n}\n"],"mappings":";;;;;;;;;;AAqBA,MAAM,kBAAkB;;;;;AAMxB,SAAgB,YAAY,OAAuC;AACjE,KAAI,MAAM,SAAS,KAAA,KAAa,MAAM,KAAK,WAAW,EACpD,QAAO,MAAM;CAEf,IAAI,OAAO;AACX,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK,QAAQ,KAAK;EAC1C,MAAM,UAAU,MAAM,KAAK;EAC3B,MAAM,MACJ,YAAY,QAAQ,OAAO,YAAY,YAAY,SAAS,UAAU,QAAQ,MAAM;AACtF,MAAI,OAAO,QAAQ,SACjB,SAAQ,IAAI,IAAI;WACP,OAAO,QAAQ,YAAY,gBAAgB,KAAK,IAAI,CAC7D,SAAQ,MAAM,IAAI,MAAM,IAAI;WACnB,OAAO,QAAQ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