@temporal-contract/worker 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/activity.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_internal = require("./internal-C8MB-kez.cjs");
2
+ const require_internal = require("./internal-Cwch3OHR.cjs");
3
3
  let _temporalio_common = require("@temporalio/common");
4
4
  //#region src/activity.ts
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { _ as WorkerInferOutput, g as WorkerInferInput, n as ActivityInputValidationError, r as ActivityOutputValidationError, t as ActivityDefinitionNotFoundError } from "./errors-BeIXtRJe.cjs";
1
+ import { n as ActivityInputValidationError, r as ActivityOutputValidationError, t as ActivityDefinitionNotFoundError, v as WorkerInferInput, y as WorkerInferOutput } from "./errors-DTq5OTwH.cjs";
2
2
  import { ActivityDefinition, ContractDefinition } from "@temporal-contract/contract";
3
3
  import { ResultAsync } from "neverthrow";
4
4
  import { ApplicationFailure, ApplicationFailure as ApplicationFailure$1 } from "@temporalio/common";
@@ -15,7 +15,27 @@ import { ApplicationFailure, ApplicationFailure as ApplicationFailure$1 } from "
15
15
  */
16
16
  type ResultActivityImplementation<TActivity extends ActivityDefinition> = (args: WorkerInferInput<TActivity>) => ResultAsync<WorkerInferOutput<TActivity>, ApplicationFailure$1>;
17
17
  /**
18
- * Map of all activity implementations for a contract (global + all workflow-specific)
18
+ * Map of all activity implementations for a contract (global + all workflow-specific).
19
+ *
20
+ * **Shape note — input is nested by workflow, output is flat.** This
21
+ * asymmetry is deliberate:
22
+ *
23
+ * - The implementation map you write **mirrors the contract's structure**:
24
+ * global activities sit at the root, workflow-local activities nest
25
+ * under their owning workflow's name. Mirroring the contract gives
26
+ * IDE autocomplete that matches `defineContract`, prevents typos that
27
+ * put a workflow-local activity at the global level, and makes
28
+ * ownership visible at definition time.
29
+ * - The handler returned by {@link declareActivitiesHandler} (see
30
+ * {@link ActivitiesHandler}) is **flat** because Temporal's worker
31
+ * sees a single activity namespace at runtime —
32
+ * `proxyActivities<...>()` resolves names from one map regardless of
33
+ * which workflow consumes them. `defineContract` enforces no name
34
+ * collisions across global + workflow-local scopes, so the flat
35
+ * output has no ambiguity to resolve.
36
+ *
37
+ * In short: write nested (mirror the contract); the wrapper flattens
38
+ * for Temporal.
19
39
  */
20
40
  type ContractResultActivitiesImplementations<TContract extends ContractDefinition> = (TContract["activities"] extends Record<string, ActivityDefinition> ? ResultActivitiesImplementations<TContract["activities"]> : {}) & { [TWorkflow in keyof TContract["workflows"]]: TContract["workflows"][TWorkflow]["activities"] extends Record<string, ActivityDefinition> ? ResultActivitiesImplementations<TContract["workflows"][TWorkflow]["activities"]> : {} };
21
41
  type ResultActivitiesImplementations<TActivities extends Record<string, ActivityDefinition>> = { [K in keyof TActivities]: ResultActivityImplementation<TActivities[K]> };
@@ -30,9 +50,12 @@ type ActivityImplementation<TActivity extends ActivityDefinition> = (args: Worke
30
50
  type ActivitiesImplementations<TActivities extends Record<string, ActivityDefinition>> = { [K in keyof TActivities]: ActivityImplementation<TActivities[K]> };
31
51
  type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
32
52
  /**
33
- * Activities handler ready for Temporal Worker
53
+ * Activities handler ready for Temporal's `Worker.create({ activities })`.
34
54
  *
35
- * Flat structure: all activities (global + all workflow-specific) are at the root level
55
+ * Flat shape: every activity (global + all workflow-local) lives at the
56
+ * root of the returned map. See the doc comment on
57
+ * {@link ContractResultActivitiesImplementations} for why the input you
58
+ * write is nested by workflow while this output is flat.
36
59
  */
37
60
  type ActivitiesHandler<TContract extends ContractDefinition> = (TContract["activities"] extends Record<string, ActivityDefinition> ? ActivitiesImplementations<TContract["activities"]> : {}) & UnionToIntersection<{ [TWorkflow in keyof TContract["workflows"]]: TContract["workflows"][TWorkflow]["activities"] extends Record<string, ActivityDefinition> ? ActivitiesImplementations<TContract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Ae,kBAAA,IAC5C,yBAAA,CAA0B,SAAA,wBAG5B,mBAAA,uBAEwB,SAAA,gBAAyB,SAAA,cAAuB,SAAA,wBAAiC,MAAA,SAEnG,kBAAA,IAEE,yBAAA,CAA0B,SAAA,cAAuB,SAAA,8BAE/C,SAAA;;;;;;;;;;;;;;;;;;;;AA/CwD;;;;;;;;;;;;;;;;;;AAQP;;;;;;;;;;;;;;;;;;;;;AAKvB;;;;iBAmGxB,wBAAA,mBAA2C,kBAAA,CAAA,CACzD,OAAA,EAAS,+BAAA,CAAgC,SAAA,IACxC,iBAAA,CAAkB,SAAA"}
@@ -1,7 +1,7 @@
1
- import { _ as WorkerInferOutput, g as WorkerInferInput, n as ActivityInputValidationError, r as ActivityOutputValidationError, t as ActivityDefinitionNotFoundError } from "./errors-BjNG_jUi.mjs";
1
+ import { n as ActivityInputValidationError, r as ActivityOutputValidationError, t as ActivityDefinitionNotFoundError, v as WorkerInferInput, y as WorkerInferOutput } from "./errors-DbPMxULo.mjs";
2
+ import { ActivityDefinition, ContractDefinition } from "@temporal-contract/contract";
2
3
  import { ApplicationFailure, ApplicationFailure as ApplicationFailure$1 } from "@temporalio/common";
3
4
  import { ResultAsync } from "neverthrow";
4
- import { ActivityDefinition, ContractDefinition } from "@temporal-contract/contract";
5
5
 
6
6
  //#region src/activity.d.ts
7
7
  /**
@@ -15,7 +15,27 @@ import { ActivityDefinition, ContractDefinition } from "@temporal-contract/contr
15
15
  */
16
16
  type ResultActivityImplementation<TActivity extends ActivityDefinition> = (args: WorkerInferInput<TActivity>) => ResultAsync<WorkerInferOutput<TActivity>, ApplicationFailure$1>;
17
17
  /**
18
- * Map of all activity implementations for a contract (global + all workflow-specific)
18
+ * Map of all activity implementations for a contract (global + all workflow-specific).
19
+ *
20
+ * **Shape note — input is nested by workflow, output is flat.** This
21
+ * asymmetry is deliberate:
22
+ *
23
+ * - The implementation map you write **mirrors the contract's structure**:
24
+ * global activities sit at the root, workflow-local activities nest
25
+ * under their owning workflow's name. Mirroring the contract gives
26
+ * IDE autocomplete that matches `defineContract`, prevents typos that
27
+ * put a workflow-local activity at the global level, and makes
28
+ * ownership visible at definition time.
29
+ * - The handler returned by {@link declareActivitiesHandler} (see
30
+ * {@link ActivitiesHandler}) is **flat** because Temporal's worker
31
+ * sees a single activity namespace at runtime —
32
+ * `proxyActivities<...>()` resolves names from one map regardless of
33
+ * which workflow consumes them. `defineContract` enforces no name
34
+ * collisions across global + workflow-local scopes, so the flat
35
+ * output has no ambiguity to resolve.
36
+ *
37
+ * In short: write nested (mirror the contract); the wrapper flattens
38
+ * for Temporal.
19
39
  */
20
40
  type ContractResultActivitiesImplementations<TContract extends ContractDefinition> = (TContract["activities"] extends Record<string, ActivityDefinition> ? ResultActivitiesImplementations<TContract["activities"]> : {}) & { [TWorkflow in keyof TContract["workflows"]]: TContract["workflows"][TWorkflow]["activities"] extends Record<string, ActivityDefinition> ? ResultActivitiesImplementations<TContract["workflows"][TWorkflow]["activities"]> : {} };
21
41
  type ResultActivitiesImplementations<TActivities extends Record<string, ActivityDefinition>> = { [K in keyof TActivities]: ResultActivityImplementation<TActivities[K]> };
@@ -30,9 +50,12 @@ type ActivityImplementation<TActivity extends ActivityDefinition> = (args: Worke
30
50
  type ActivitiesImplementations<TActivities extends Record<string, ActivityDefinition>> = { [K in keyof TActivities]: ActivityImplementation<TActivities[K]> };
31
51
  type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
32
52
  /**
33
- * Activities handler ready for Temporal Worker
53
+ * Activities handler ready for Temporal's `Worker.create({ activities })`.
34
54
  *
35
- * Flat structure: all activities (global + all workflow-specific) are at the root level
55
+ * Flat shape: every activity (global + all workflow-local) lives at the
56
+ * root of the returned map. See the doc comment on
57
+ * {@link ContractResultActivitiesImplementations} for why the input you
58
+ * write is nested by workflow while this output is flat.
36
59
  */
37
60
  type ActivitiesHandler<TContract extends ContractDefinition> = (TContract["activities"] extends Record<string, ActivityDefinition> ? ActivitiesImplementations<TContract["activities"]> : {}) & UnionToIntersection<{ [TWorkflow in keyof TContract["workflows"]]: TContract["workflows"][TWorkflow]["activities"] extends Record<string, ActivityDefinition> ? ActivitiesImplementations<TContract["workflows"][TWorkflow]["activities"]> : {} }[keyof TContract["workflows"]]>;
38
61
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"activity.d.mts","names":[],"sources":["../src/activity.ts"],"mappings":";;;;;;AA+BwD;;;;;;;;;AAAA,KAWnD,4BAAA,mBAA+C,kBAAA,KAClD,IAAA,EAAM,gBAAA,CAAiB,SAAA,MACpB,WAAA,CAAY,iBAAA,CAAkB,SAAA,GAAY,oBAAA;;;;KAK1C,uCAAA,mBAA0D,kBAAA,KAE5D,SAAA,uBAAgC,MAAA,SAAe,kBAAA,IAC5C,+BAAA,CAAgC,SAAA,8CAIZ,SAAA,gBAAyB,SAAA,cAAuB,SAAA,wBAAiC,MAAA,SAEnG,kBAAA,IAEE,+BAAA,CAAgC,SAAA,cAAuB,SAAA;AAAA,KAI5D,+BAAA,qBAAoD,MAAA,SAAe,kBAAA,mBAC1D,WAAA,GAAc,4BAAA,CAA6B,WAAA,CAAY,CAAA;;;;KAMhE,+BAAA,mBAAkD,kBAAA;EACrD,QAAA,EAAU,SAAA;EACV,UAAA,EAAY,uCAAA,CAAwC,SAAA;AAAA;AAAA,KAGjD,sBAAA,mBAAyC,kBAAA,KAC5C,IAAA,EAAM,gBAAA,CAAiB,SAAA,MACpB,OAAA,CAAQ,iBAAA,CAAkB,SAAA;AAAA,KAE1B,yBAAA,qBAA8C,MAAA,SAAe,kBAAA,mBACpD,WAAA,GAAc,sBAAA,CAAuB,WAAA,CAAY,CAAA;AAAA,KAG1D,mBAAA,OAA0B,CAAA,oBAAqB,CAAA,EAAG,CAAA,6BACrD,CAAA,sBAEE,CAAA;;;;;;KAQQ,iBAAA,mBAAoC,kBAAA,KAE7C,SAAA,uBAAgC,MAAA,SAAe,kBAAA,IAC5C,yBAAA,CAA0B,SAAA,wBAG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AAA,oBAAqB,CAAA,EAAG,CAAA,6BACrD,CAAA,sBAEE,CAAA;;;;;;;;;KAWQ,iBAAA,mBAAoC,kBAAA,KAE7C,SAAA,uBAAgC,MAAA,SAAe,kBAAA,IAC5C,yBAAA,CAA0B,SAAA,wBAG5B,mBAAA,uBAEwB,SAAA,gBAAyB,SAAA,cAAuB,SAAA,wBAAiC,MAAA,SAEnG,kBAAA,IAEE,yBAAA,CAA0B,SAAA,cAAuB,SAAA,8BAE/C,SAAA;;;;;;;;;;;;;;;;;;;;AA/CwD;;;;;;;;;;;;;;;;;;AAQP;;;;;;;;;;;;;;;;;;;;;AAKvB;;;;iBAmGxB,wBAAA,mBAA2C,kBAAA,CAAA,CACzD,OAAA,EAAS,+BAAA,CAAgC,SAAA,IACxC,iBAAA,CAAkB,SAAA"}
package/dist/activity.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ActivityInputValidationError, i as ActivityDefinitionNotFoundError, o as ActivityOutputValidationError, r as extractHandlerInput } from "./internal--45IXCxX.mjs";
1
+ import { c as ActivityInputValidationError, i as extractHandlerInput, l as ActivityOutputValidationError, s as ActivityDefinitionNotFoundError } from "./internal-BzG1KhEK.mjs";
2
2
  import { ApplicationFailure } from "@temporalio/common";
3
3
  //#region src/activity.ts
4
4
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"activity.mjs","names":[],"sources":["../src/activity.ts"],"sourcesContent":["// Entry point for activity implementations.\n//\n// Activities run *outside* the workflow sandbox, so they use neverthrow's\n// `ResultAsync` directly. Workflow code (see workflow.ts) uses the same\n// neverthrow API — neverthrow's evaluation is compatible with Temporal's\n// deterministic replay machinery.\n//\n// Errors flow through Temporal's `ApplicationFailure` (re-exported from\n// `@temporalio/common`) — it's the SDK's first-class failure shape, so we\n// don't wrap it in a custom class. `ApplicationFailure` exposes\n// `nonRetryable`, `type`, `details`, and `category` natively, and survives\n// the activity → workflow serialization boundary unchanged.\nimport { ActivityDefinition, ContractDefinition } from \"@temporal-contract/contract\";\nimport type { ResultAsync } from \"neverthrow\";\nimport { ApplicationFailure } from \"@temporalio/common\";\nimport { WorkerInferInput, WorkerInferOutput } from \"./types.js\";\nimport {\n ActivityDefinitionNotFoundError,\n ActivityInputValidationError,\n ActivityOutputValidationError,\n} from \"./errors.js\";\nimport { extractHandlerInput } from \"./internal.js\";\n\nexport {\n ActivityDefinitionNotFoundError,\n ActivityInputValidationError,\n ActivityOutputValidationError,\n} from \"./errors.js\";\n\n// Re-export the canonical activity-failure class so consumers don't need\n// a separate `@temporalio/common` import to construct one.\nexport { ApplicationFailure } from \"@temporalio/common\";\n\n/**\n * Activity implementation using neverthrow's `ResultAsync`.\n *\n * Returns `ResultAsync<Output, ApplicationFailure>` for explicit error\n * handling instead of throwing. The wrapper rethrows `err()` payloads at\n * the activity boundary; Temporal recognizes `ApplicationFailure` natively\n * and applies the configured retry policy (with `nonRetryable: true`\n * opting an instance out per-call).\n */\ntype ResultActivityImplementation<TActivity extends ActivityDefinition> = (\n args: WorkerInferInput<TActivity>,\n) => ResultAsync<WorkerInferOutput<TActivity>, ApplicationFailure>;\n\n/**\n * Map of all activity implementations for a contract (global + all workflow-specific)\n */\ntype ContractResultActivitiesImplementations<TContract extends ContractDefinition> =\n // Global activities\n (TContract[\"activities\"] extends Record<string, ActivityDefinition>\n ? ResultActivitiesImplementations<TContract[\"activities\"]>\n : {}) &\n // All workflow-specific activities merged\n {\n [TWorkflow in keyof TContract[\"workflows\"]]: TContract[\"workflows\"][TWorkflow][\"activities\"] extends Record<\n string,\n ActivityDefinition\n >\n ? ResultActivitiesImplementations<TContract[\"workflows\"][TWorkflow][\"activities\"]>\n : {};\n };\n\ntype ResultActivitiesImplementations<TActivities extends Record<string, ActivityDefinition>> = {\n [K in keyof TActivities]: ResultActivityImplementation<TActivities[K]>;\n};\n\n/**\n * Options for creating activities handler\n */\ntype DeclareActivitiesHandlerOptions<TContract extends ContractDefinition> = {\n contract: TContract;\n activities: ContractResultActivitiesImplementations<TContract>;\n};\n\ntype ActivityImplementation<TActivity extends ActivityDefinition> = (\n args: WorkerInferInput<TActivity>,\n) => Promise<WorkerInferOutput<TActivity>>;\n\ntype ActivitiesImplementations<TActivities extends Record<string, ActivityDefinition>> = {\n [K in keyof TActivities]: ActivityImplementation<TActivities[K]>;\n};\n\ntype UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (\n k: infer I,\n) => void\n ? I\n : never;\n\n/**\n * Activities handler ready for Temporal Worker\n *\n * Flat structure: all activities (global + all workflow-specific) are at the root level\n */\nexport type ActivitiesHandler<TContract extends ContractDefinition> =\n // Global activities\n (TContract[\"activities\"] extends Record<string, ActivityDefinition>\n ? ActivitiesImplementations<TContract[\"activities\"]>\n : {}) &\n // All workflow-specific activities merged at root level (flat)\n UnionToIntersection<\n {\n [TWorkflow in keyof TContract[\"workflows\"]]: TContract[\"workflows\"][TWorkflow][\"activities\"] extends Record<\n string,\n ActivityDefinition\n >\n ? ActivitiesImplementations<TContract[\"workflows\"][TWorkflow][\"activities\"]>\n : {};\n }[keyof TContract[\"workflows\"]]\n >;\n\n/**\n * Create a typed activities handler with automatic validation and Result pattern.\n *\n * This wraps all activity implementations with:\n * - Validation at network boundaries\n * - `ResultAsync<T, ApplicationFailure>` pattern for explicit error handling\n * - Automatic conversion from Result to Promise (throwing on Error)\n *\n * TypeScript ensures ALL activities (global + workflow-specific) are implemented.\n *\n * Use this to create the activities object for the Temporal Worker.\n *\n * @example\n * ```ts\n * import { declareActivitiesHandler, ApplicationFailure } from '@temporal-contract/worker/activity';\n * import { ResultAsync, errAsync, okAsync } from 'neverthrow';\n * import myContract from './contract';\n *\n * export const activities = declareActivitiesHandler({\n * contract: myContract,\n * activities: {\n * // Activity returns ResultAsync instead of throwing.\n * sendEmail: (args) =>\n * ResultAsync.fromPromise(\n * emailService.send(args),\n * (error) =>\n * // Wrap technical errors in ApplicationFailure. `nonRetryable`\n * // is per-instance: set it to true on permanent failures so\n * // Temporal stops retrying immediately.\n * ApplicationFailure.create({\n * type: 'EMAIL_SEND_FAILED',\n * message: 'Failed to send email',\n * nonRetryable: false,\n * cause: error instanceof Error ? error : undefined,\n * }),\n * ).map(() => ({ sent: true })),\n * },\n * });\n *\n * // Use with Temporal Worker\n * import { Worker } from '@temporalio/worker';\n *\n * const worker = await Worker.create({\n * workflowsPath: require.resolve('./workflows'),\n * activities: activities,\n * taskQueue: contract.taskQueue,\n * });\n * ```\n *\n * @remarks\n * The wrapper accepts implementations in the\n * `ResultAsync<T, ApplicationFailure>` shape and produces ordinary\n * Promise-returning Temporal handlers (`err(...)` → thrown\n * `ApplicationFailure`; `ok(...)` → output validated against the\n * contract and resolved). It does **not** hide Temporal's\n * `@temporalio/activity` runtime: inside the body you can still call\n * `Context.current()` from `@temporalio/activity` to access heartbeats\n * (`heartbeat(details)`, `heartbeatDetails`), activity info (attempt\n * number, workflow IDs), and the async-completion task token. See the\n * \"Working with the Activity Context\" section of the worker\n * implementation guide for end-to-end examples.\n */\nexport function declareActivitiesHandler<TContract extends ContractDefinition>(\n options: DeclareActivitiesHandlerOptions<TContract>,\n): ActivitiesHandler<TContract> {\n const { contract, activities } = options;\n\n // Prepare Temporal-compatible activities with validation and Result unwrapping\n const wrappedActivities = {} as ActivitiesHandler<TContract>;\n\n // Helper to create a wrapped implementation from a definition and impl\n function makeWrapped(\n activityName: string,\n activityDef: ActivityDefinition,\n activityImpl: (args: unknown) => ResultAsync<unknown, ApplicationFailure>,\n ) {\n return async (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n\n // Validate input\n const inputResult = await activityDef.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new ActivityInputValidationError(activityName, inputResult.issues);\n }\n\n // Execute neverthrow activity (returns ResultAsync<T, ApplicationFailure>);\n // awaiting yields a Result<T, ApplicationFailure>.\n const result = await activityImpl(inputResult.value);\n\n // Process result: validate output or throw error\n if (result.isOk()) {\n // Validate output on success\n const outputResult = await activityDef.output[\"~standard\"].validate(result.value);\n if (outputResult.issues) {\n throw new ActivityOutputValidationError(activityName, outputResult.issues);\n }\n return outputResult.value;\n } else {\n // Convert err(...) payload to thrown ApplicationFailure for Temporal.\n // Temporal recognizes this class natively and applies the\n // configured retry policy (honoring `nonRetryable: true`).\n throw result.error;\n }\n };\n }\n\n // 1) Wrap global activities defined directly under contract.activities\n if (contract.activities) {\n for (const [activityName, impl] of Object.entries(activities)) {\n // Skip workflow namespaces if present at root\n if (contract.workflows && activityName in contract.workflows) {\n continue;\n }\n\n const activityDef = contract.activities[activityName];\n if (!activityDef) {\n throw new ActivityDefinitionNotFoundError(activityName, Object.keys(contract.activities));\n }\n\n // Assign wrapped global activity\n (wrappedActivities as Record<string, unknown>)[activityName] = makeWrapped(\n activityName,\n activityDef,\n impl as (args: unknown) => ResultAsync<unknown, ApplicationFailure>,\n );\n }\n }\n\n // 2) Wrap workflow-scoped activities at root level (flat)\n if (contract.workflows) {\n for (const [workflowName, workflowDef] of Object.entries(contract.workflows)) {\n const wfActivitiesImpl = (activities as Record<string, unknown>)[workflowName] as\n | Record<string, unknown>\n | undefined;\n if (!wfActivitiesImpl) {\n // If no implementations provided for this workflow, skip (TypeScript typing should enforce completeness for declared ones)\n continue;\n }\n\n const wfDefs = workflowDef.activities ?? {};\n\n for (const [activityName, impl] of Object.entries(wfActivitiesImpl)) {\n const activityDef = wfDefs[activityName];\n if (!activityDef) {\n throw new ActivityDefinitionNotFoundError(\n `${workflowName}.${activityName}`,\n Object.keys(wfDefs),\n );\n }\n\n // Assign workflow activity directly at root level (flat structure)\n (wrappedActivities as Record<string, unknown>)[activityName] = makeWrapped(\n `${workflowName}.${activityName}`,\n activityDef,\n impl as (args: unknown) => ResultAsync<unknown, ApplicationFailure>,\n );\n }\n }\n }\n\n return wrappedActivities;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8KA,SAAgB,yBACd,SAC8B;CAC9B,MAAM,EAAE,UAAU,eAAe;CAGjC,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/activity.ts"],"sourcesContent":["// Entry point for activity implementations.\n//\n// Activities run *outside* the workflow sandbox, so they use neverthrow's\n// `ResultAsync` directly. Workflow code (see workflow.ts) uses the same\n// neverthrow API — neverthrow's evaluation is compatible with Temporal's\n// deterministic replay machinery.\n//\n// Errors flow through Temporal's `ApplicationFailure` (re-exported from\n// `@temporalio/common`) — it's the SDK's first-class failure shape, so we\n// don't wrap it in a custom class. `ApplicationFailure` exposes\n// `nonRetryable`, `type`, `details`, and `category` natively, and survives\n// the activity → workflow serialization boundary unchanged.\nimport { ActivityDefinition, ContractDefinition } from \"@temporal-contract/contract\";\nimport type { ResultAsync } from \"neverthrow\";\nimport { ApplicationFailure } from \"@temporalio/common\";\nimport { WorkerInferInput, WorkerInferOutput } from \"./types.js\";\nimport {\n ActivityDefinitionNotFoundError,\n ActivityInputValidationError,\n ActivityOutputValidationError,\n} from \"./errors.js\";\nimport { extractHandlerInput } from \"./internal.js\";\n\nexport {\n ActivityDefinitionNotFoundError,\n ActivityInputValidationError,\n ActivityOutputValidationError,\n} from \"./errors.js\";\n\n// Re-export the canonical activity-failure class so consumers don't need\n// a separate `@temporalio/common` import to construct one.\nexport { ApplicationFailure } from \"@temporalio/common\";\n\n/**\n * Activity implementation using neverthrow's `ResultAsync`.\n *\n * Returns `ResultAsync<Output, ApplicationFailure>` for explicit error\n * handling instead of throwing. The wrapper rethrows `err()` payloads at\n * the activity boundary; Temporal recognizes `ApplicationFailure` natively\n * and applies the configured retry policy (with `nonRetryable: true`\n * opting an instance out per-call).\n */\ntype ResultActivityImplementation<TActivity extends ActivityDefinition> = (\n args: WorkerInferInput<TActivity>,\n) => ResultAsync<WorkerInferOutput<TActivity>, ApplicationFailure>;\n\n/**\n * Map of all activity implementations for a contract (global + all workflow-specific).\n *\n * **Shape note — input is nested by workflow, output is flat.** This\n * asymmetry is deliberate:\n *\n * - The implementation map you write **mirrors the contract's structure**:\n * global activities sit at the root, workflow-local activities nest\n * under their owning workflow's name. Mirroring the contract gives\n * IDE autocomplete that matches `defineContract`, prevents typos that\n * put a workflow-local activity at the global level, and makes\n * ownership visible at definition time.\n * - The handler returned by {@link declareActivitiesHandler} (see\n * {@link ActivitiesHandler}) is **flat** because Temporal's worker\n * sees a single activity namespace at runtime —\n * `proxyActivities<...>()` resolves names from one map regardless of\n * which workflow consumes them. `defineContract` enforces no name\n * collisions across global + workflow-local scopes, so the flat\n * output has no ambiguity to resolve.\n *\n * In short: write nested (mirror the contract); the wrapper flattens\n * for Temporal.\n */\ntype ContractResultActivitiesImplementations<TContract extends ContractDefinition> =\n // Global activities\n (TContract[\"activities\"] extends Record<string, ActivityDefinition>\n ? ResultActivitiesImplementations<TContract[\"activities\"]>\n : {}) &\n // All workflow-specific activities merged\n {\n [TWorkflow in keyof TContract[\"workflows\"]]: TContract[\"workflows\"][TWorkflow][\"activities\"] extends Record<\n string,\n ActivityDefinition\n >\n ? ResultActivitiesImplementations<TContract[\"workflows\"][TWorkflow][\"activities\"]>\n : {};\n };\n\ntype ResultActivitiesImplementations<TActivities extends Record<string, ActivityDefinition>> = {\n [K in keyof TActivities]: ResultActivityImplementation<TActivities[K]>;\n};\n\n/**\n * Options for creating activities handler\n */\ntype DeclareActivitiesHandlerOptions<TContract extends ContractDefinition> = {\n contract: TContract;\n activities: ContractResultActivitiesImplementations<TContract>;\n};\n\ntype ActivityImplementation<TActivity extends ActivityDefinition> = (\n args: WorkerInferInput<TActivity>,\n) => Promise<WorkerInferOutput<TActivity>>;\n\ntype ActivitiesImplementations<TActivities extends Record<string, ActivityDefinition>> = {\n [K in keyof TActivities]: ActivityImplementation<TActivities[K]>;\n};\n\ntype UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (\n k: infer I,\n) => void\n ? I\n : never;\n\n/**\n * Activities handler ready for Temporal's `Worker.create({ activities })`.\n *\n * Flat shape: every activity (global + all workflow-local) lives at the\n * root of the returned map. See the doc comment on\n * {@link ContractResultActivitiesImplementations} for why the input you\n * write is nested by workflow while this output is flat.\n */\nexport type ActivitiesHandler<TContract extends ContractDefinition> =\n // Global activities\n (TContract[\"activities\"] extends Record<string, ActivityDefinition>\n ? ActivitiesImplementations<TContract[\"activities\"]>\n : {}) &\n // All workflow-specific activities merged at root level (flat)\n UnionToIntersection<\n {\n [TWorkflow in keyof TContract[\"workflows\"]]: TContract[\"workflows\"][TWorkflow][\"activities\"] extends Record<\n string,\n ActivityDefinition\n >\n ? ActivitiesImplementations<TContract[\"workflows\"][TWorkflow][\"activities\"]>\n : {};\n }[keyof TContract[\"workflows\"]]\n >;\n\n/**\n * Create a typed activities handler with automatic validation and Result pattern.\n *\n * This wraps all activity implementations with:\n * - Validation at network boundaries\n * - `ResultAsync<T, ApplicationFailure>` pattern for explicit error handling\n * - Automatic conversion from Result to Promise (throwing on Error)\n *\n * TypeScript ensures ALL activities (global + workflow-specific) are implemented.\n *\n * Use this to create the activities object for the Temporal Worker.\n *\n * @example\n * ```ts\n * import { declareActivitiesHandler, ApplicationFailure } from '@temporal-contract/worker/activity';\n * import { ResultAsync, errAsync, okAsync } from 'neverthrow';\n * import myContract from './contract';\n *\n * export const activities = declareActivitiesHandler({\n * contract: myContract,\n * activities: {\n * // Activity returns ResultAsync instead of throwing.\n * sendEmail: (args) =>\n * ResultAsync.fromPromise(\n * emailService.send(args),\n * (error) =>\n * // Wrap technical errors in ApplicationFailure. `nonRetryable`\n * // is per-instance: set it to true on permanent failures so\n * // Temporal stops retrying immediately.\n * ApplicationFailure.create({\n * type: 'EMAIL_SEND_FAILED',\n * message: 'Failed to send email',\n * nonRetryable: false,\n * cause: error instanceof Error ? error : undefined,\n * }),\n * ).map(() => ({ sent: true })),\n * },\n * });\n *\n * // Use with Temporal Worker\n * import { Worker } from '@temporalio/worker';\n *\n * const worker = await Worker.create({\n * workflowsPath: require.resolve('./workflows'),\n * activities: activities,\n * taskQueue: contract.taskQueue,\n * });\n * ```\n *\n * @remarks\n * The wrapper accepts implementations in the\n * `ResultAsync<T, ApplicationFailure>` shape and produces ordinary\n * Promise-returning Temporal handlers (`err(...)` → thrown\n * `ApplicationFailure`; `ok(...)` → output validated against the\n * contract and resolved). It does **not** hide Temporal's\n * `@temporalio/activity` runtime: inside the body you can still call\n * `Context.current()` from `@temporalio/activity` to access heartbeats\n * (`heartbeat(details)`, `heartbeatDetails`), activity info (attempt\n * number, workflow IDs), and the async-completion task token. See the\n * \"Working with the Activity Context\" section of the worker\n * implementation guide for end-to-end examples.\n */\nexport function declareActivitiesHandler<TContract extends ContractDefinition>(\n options: DeclareActivitiesHandlerOptions<TContract>,\n): ActivitiesHandler<TContract> {\n const { contract, activities } = options;\n\n // Prepare Temporal-compatible activities with validation and Result unwrapping\n const wrappedActivities = {} as ActivitiesHandler<TContract>;\n\n // Helper to create a wrapped implementation from a definition and impl\n function makeWrapped(\n activityName: string,\n activityDef: ActivityDefinition,\n activityImpl: (args: unknown) => ResultAsync<unknown, ApplicationFailure>,\n ) {\n return async (...args: unknown[]) => {\n const input = extractHandlerInput(args);\n\n // Validate input\n const inputResult = await activityDef.input[\"~standard\"].validate(input);\n if (inputResult.issues) {\n throw new ActivityInputValidationError(activityName, inputResult.issues);\n }\n\n // Execute neverthrow activity (returns ResultAsync<T, ApplicationFailure>);\n // awaiting yields a Result<T, ApplicationFailure>.\n const result = await activityImpl(inputResult.value);\n\n // Process result: validate output or throw error\n if (result.isOk()) {\n // Validate output on success\n const outputResult = await activityDef.output[\"~standard\"].validate(result.value);\n if (outputResult.issues) {\n throw new ActivityOutputValidationError(activityName, outputResult.issues);\n }\n return outputResult.value;\n } else {\n // Convert err(...) payload to thrown ApplicationFailure for Temporal.\n // Temporal recognizes this class natively and applies the\n // configured retry policy (honoring `nonRetryable: true`).\n throw result.error;\n }\n };\n }\n\n // 1) Wrap global activities defined directly under contract.activities\n if (contract.activities) {\n for (const [activityName, impl] of Object.entries(activities)) {\n // Skip workflow namespaces if present at root\n if (contract.workflows && activityName in contract.workflows) {\n continue;\n }\n\n const activityDef = contract.activities[activityName];\n if (!activityDef) {\n throw new ActivityDefinitionNotFoundError(activityName, Object.keys(contract.activities));\n }\n\n // Assign wrapped global activity\n (wrappedActivities as Record<string, unknown>)[activityName] = makeWrapped(\n activityName,\n activityDef,\n impl as (args: unknown) => ResultAsync<unknown, ApplicationFailure>,\n );\n }\n }\n\n // 2) Wrap workflow-scoped activities at root level (flat)\n if (contract.workflows) {\n for (const [workflowName, workflowDef] of Object.entries(contract.workflows)) {\n const wfActivitiesImpl = (activities as Record<string, unknown>)[workflowName] as\n | Record<string, unknown>\n | undefined;\n if (!wfActivitiesImpl) {\n // If no implementations provided for this workflow, skip (TypeScript typing should enforce completeness for declared ones)\n continue;\n }\n\n const wfDefs = workflowDef.activities ?? {};\n\n for (const [activityName, impl] of Object.entries(wfActivitiesImpl)) {\n const activityDef = wfDefs[activityName];\n if (!activityDef) {\n throw new ActivityDefinitionNotFoundError(\n `${workflowName}.${activityName}`,\n Object.keys(wfDefs),\n );\n }\n\n // Assign workflow activity directly at root level (flat structure)\n (wrappedActivities as Record<string, unknown>)[activityName] = makeWrapped(\n `${workflowName}.${activityName}`,\n activityDef,\n impl as (args: unknown) => ResultAsync<unknown, ApplicationFailure>,\n );\n }\n }\n }\n\n return wrappedActivities;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqMA,SAAgB,yBACd,SAC8B;CAC9B,MAAM,EAAE,UAAU,eAAe;CAGjC,MAAM,oBAAoB,EAAE;CAG5B,SAAS,YACP,cACA,aACA,cACA;AACA,SAAO,OAAO,GAAG,SAAoB;GACnC,MAAM,QAAQ,oBAAoB,KAAK;GAGvC,MAAM,cAAc,MAAM,YAAY,MAAM,aAAa,SAAS,MAAM;AACxE,OAAI,YAAY,OACd,OAAM,IAAI,6BAA6B,cAAc,YAAY,OAAO;GAK1E,MAAM,SAAS,MAAM,aAAa,YAAY,MAAM;AAGpD,OAAI,OAAO,MAAM,EAAE;IAEjB,MAAM,eAAe,MAAM,YAAY,OAAO,aAAa,SAAS,OAAO,MAAM;AACjF,QAAI,aAAa,OACf,OAAM,IAAI,8BAA8B,cAAc,aAAa,OAAO;AAE5E,WAAO,aAAa;SAKpB,OAAM,OAAO;;;AAMnB,KAAI,SAAS,WACX,MAAK,MAAM,CAAC,cAAc,SAAS,OAAO,QAAQ,WAAW,EAAE;AAE7D,MAAI,SAAS,aAAa,gBAAgB,SAAS,UACjD;EAGF,MAAM,cAAc,SAAS,WAAW;AACxC,MAAI,CAAC,YACH,OAAM,IAAI,gCAAgC,cAAc,OAAO,KAAK,SAAS,WAAW,CAAC;AAI1F,oBAA8C,gBAAgB,YAC7D,cACA,aACA,KACD;;AAKL,KAAI,SAAS,UACX,MAAK,MAAM,CAAC,cAAc,gBAAgB,OAAO,QAAQ,SAAS,UAAU,EAAE;EAC5E,MAAM,mBAAoB,WAAuC;AAGjE,MAAI,CAAC,iBAEH;EAGF,MAAM,SAAS,YAAY,cAAc,EAAE;AAE3C,OAAK,MAAM,CAAC,cAAc,SAAS,OAAO,QAAQ,iBAAiB,EAAE;GACnE,MAAM,cAAc,OAAO;AAC3B,OAAI,CAAC,YACH,OAAM,IAAI,gCACR,GAAG,aAAa,GAAG,gBACnB,OAAO,KAAK,OAAO,CACpB;AAIF,qBAA8C,gBAAgB,YAC7D,GAAG,aAAa,GAAG,gBACnB,aACA,KACD;;;AAKP,QAAO"}
@@ -127,23 +127,82 @@ declare class ChildWorkflowNotFoundError extends WorkerError {
127
127
  constructor(workflowName: string, availableWorkflows?: readonly string[]);
128
128
  }
129
129
  /**
130
- * Generic error for child workflow operations
130
+ * Generic error for child workflow operations.
131
+ *
132
+ * When the child execution itself fails (Temporal's `ChildWorkflowFailure`),
133
+ * `cause` is set to the *unwrapped* underlying failure (`ApplicationFailure`,
134
+ * `TimeoutFailure`, `TerminatedFailure`, etc.) lifted from Temporal's wrapper —
135
+ * mirroring the client-side `WorkflowFailedError.cause` behavior, so callers
136
+ * can branch on the failure category in one step instead of unwrapping twice.
131
137
  */
132
138
  declare class ChildWorkflowError extends WorkerError {
133
139
  constructor(message: string, cause?: unknown);
134
140
  }
141
+ /**
142
+ * Discriminated variant of {@link ChildWorkflowError} surfaced when a child
143
+ * workflow operation (start, execute, or wait-for-result) was cancelled —
144
+ * either because the parent workflow itself was cancelled, the child was
145
+ * explicitly cancelled, or its enclosing cancellation scope was. Detected via
146
+ * `@temporalio/workflow`'s `isCancellation(...)`, which sees through nested
147
+ * `ChildWorkflowFailure` / `CancelledFailure` chains.
148
+ *
149
+ * Extends {@link ChildWorkflowError} so existing `instanceof ChildWorkflowError`
150
+ * checks still match cancellation, while `instanceof ChildWorkflowCancelledError`
151
+ * lets call sites narrow further when they need to branch on cancellation
152
+ * explicitly without inspecting `error.cause` against a Temporal SDK class —
153
+ * the worker-side analogue of the client-side cause-forwarding pattern.
154
+ */
155
+ declare class ChildWorkflowCancelledError extends ChildWorkflowError {
156
+ readonly workflowName: string;
157
+ constructor(workflowName: string, cause?: unknown);
158
+ }
135
159
  /**
136
160
  * Error surfaced in the `err(...)` branch of a `ResultAsync` when a typed
137
161
  * cancellation scope is cancelled via Temporal's cancellation propagation.
138
162
  * Returned by both `context.cancellableScope` (when the workflow or an
139
163
  * ancestor scope cancels) and `context.nonCancellableScope` (when
140
164
  * cancellation is raised from inside the scope). Distinct from arbitrary
141
- * thrown errors so call sites can branch on cancellation explicitly while
142
- * still surfacing non-cancellation errors as ResultAsync rejections.
165
+ * thrown errors so call sites can branch on cancellation explicitly.
166
+ *
167
+ * Non-cancellation errors thrown inside a scope surface as a sibling
168
+ * {@link WorkflowScopeError} on the same `err(...)` channel, so callers can
169
+ * use `instanceof` to discriminate without falling back to `try/catch`.
143
170
  */
144
171
  declare class WorkflowCancelledError extends WorkerError {
145
172
  constructor(cause?: unknown);
146
173
  }
174
+ /**
175
+ * Error surfaced in the `err(...)` branch of a `ResultAsync` when the
176
+ * function passed to `cancellableScope` / `nonCancellableScope` throws a
177
+ * non-cancellation error.
178
+ *
179
+ * The original error is preserved on `cause` so call sites can introspect
180
+ * it without losing identity:
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * const result = await context.cancellableScope(async () => {
185
+ * return await context.activities.processStep(args);
186
+ * });
187
+ *
188
+ * if (result.isErr()) {
189
+ * if (result.error instanceof WorkflowCancelledError) {
190
+ * // graceful cancellation
191
+ * } else if (result.error instanceof WorkflowScopeError) {
192
+ * // domain error — `result.error.cause` is the original throwable
193
+ * }
194
+ * }
195
+ * ```
196
+ *
197
+ * Introduced so the scope helpers route every failure through neverthrow's
198
+ * railway. Previously, non-cancellation errors were re-thrown out of the
199
+ * helper, which became a `ResultAsync` rejection (`new ResultAsync(promise)`
200
+ * does not catch) — they leaked as unhandled rejections rather than
201
+ * surfacing on the typed error channel callers actually inspect.
202
+ */
203
+ declare class WorkflowScopeError extends WorkerError {
204
+ constructor(cause: unknown);
205
+ }
147
206
  //#endregion
148
- export { WorkerInferOutput as _, ChildWorkflowNotFoundError as a, SignalInputValidationError as c, WorkflowCancelledError as d, WorkflowInputValidationError as f, WorkerInferInput as g, ClientInferOutput as h, ChildWorkflowError as i, UpdateInputValidationError as l, ClientInferInput as m, ActivityInputValidationError as n, QueryInputValidationError as o, WorkflowOutputValidationError as p, ActivityOutputValidationError as r, QueryOutputValidationError as s, ActivityDefinitionNotFoundError as t, UpdateOutputValidationError as u };
149
- //# sourceMappingURL=errors-BeIXtRJe.d.cts.map
207
+ export { ClientInferOutput as _, ChildWorkflowError as a, QueryOutputValidationError as c, UpdateOutputValidationError as d, WorkflowCancelledError as f, ClientInferInput as g, WorkflowScopeError as h, ChildWorkflowCancelledError as i, SignalInputValidationError as l, WorkflowOutputValidationError as m, ActivityInputValidationError as n, ChildWorkflowNotFoundError as o, WorkflowInputValidationError as p, ActivityOutputValidationError as r, QueryInputValidationError as s, ActivityDefinitionNotFoundError as t, UpdateInputValidationError as u, WorkerInferInput as v, WorkerInferOutput as y };
208
+ //# sourceMappingURL=errors-DTq5OTwH.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A,YAAA,UAChB,KAAA;AAAA;;;;;;;;;;;;;cAmBS,sBAAA,SAA+B,WAAA;cAC9B,KAAA;AAAA;;AAlKd;;;;;;;;;;;;;;;;;;;;;;;;AAcA;;;;cAuLa,kBAAA,SAA2B,WAAA;cAC1B,KAAA;AAAA"}
@@ -127,23 +127,82 @@ declare class ChildWorkflowNotFoundError extends WorkerError {
127
127
  constructor(workflowName: string, availableWorkflows?: readonly string[]);
128
128
  }
129
129
  /**
130
- * Generic error for child workflow operations
130
+ * Generic error for child workflow operations.
131
+ *
132
+ * When the child execution itself fails (Temporal's `ChildWorkflowFailure`),
133
+ * `cause` is set to the *unwrapped* underlying failure (`ApplicationFailure`,
134
+ * `TimeoutFailure`, `TerminatedFailure`, etc.) lifted from Temporal's wrapper —
135
+ * mirroring the client-side `WorkflowFailedError.cause` behavior, so callers
136
+ * can branch on the failure category in one step instead of unwrapping twice.
131
137
  */
132
138
  declare class ChildWorkflowError extends WorkerError {
133
139
  constructor(message: string, cause?: unknown);
134
140
  }
141
+ /**
142
+ * Discriminated variant of {@link ChildWorkflowError} surfaced when a child
143
+ * workflow operation (start, execute, or wait-for-result) was cancelled —
144
+ * either because the parent workflow itself was cancelled, the child was
145
+ * explicitly cancelled, or its enclosing cancellation scope was. Detected via
146
+ * `@temporalio/workflow`'s `isCancellation(...)`, which sees through nested
147
+ * `ChildWorkflowFailure` / `CancelledFailure` chains.
148
+ *
149
+ * Extends {@link ChildWorkflowError} so existing `instanceof ChildWorkflowError`
150
+ * checks still match cancellation, while `instanceof ChildWorkflowCancelledError`
151
+ * lets call sites narrow further when they need to branch on cancellation
152
+ * explicitly without inspecting `error.cause` against a Temporal SDK class —
153
+ * the worker-side analogue of the client-side cause-forwarding pattern.
154
+ */
155
+ declare class ChildWorkflowCancelledError extends ChildWorkflowError {
156
+ readonly workflowName: string;
157
+ constructor(workflowName: string, cause?: unknown);
158
+ }
135
159
  /**
136
160
  * Error surfaced in the `err(...)` branch of a `ResultAsync` when a typed
137
161
  * cancellation scope is cancelled via Temporal's cancellation propagation.
138
162
  * Returned by both `context.cancellableScope` (when the workflow or an
139
163
  * ancestor scope cancels) and `context.nonCancellableScope` (when
140
164
  * cancellation is raised from inside the scope). Distinct from arbitrary
141
- * thrown errors so call sites can branch on cancellation explicitly while
142
- * still surfacing non-cancellation errors as ResultAsync rejections.
165
+ * thrown errors so call sites can branch on cancellation explicitly.
166
+ *
167
+ * Non-cancellation errors thrown inside a scope surface as a sibling
168
+ * {@link WorkflowScopeError} on the same `err(...)` channel, so callers can
169
+ * use `instanceof` to discriminate without falling back to `try/catch`.
143
170
  */
144
171
  declare class WorkflowCancelledError extends WorkerError {
145
172
  constructor(cause?: unknown);
146
173
  }
174
+ /**
175
+ * Error surfaced in the `err(...)` branch of a `ResultAsync` when the
176
+ * function passed to `cancellableScope` / `nonCancellableScope` throws a
177
+ * non-cancellation error.
178
+ *
179
+ * The original error is preserved on `cause` so call sites can introspect
180
+ * it without losing identity:
181
+ *
182
+ * @example
183
+ * ```ts
184
+ * const result = await context.cancellableScope(async () => {
185
+ * return await context.activities.processStep(args);
186
+ * });
187
+ *
188
+ * if (result.isErr()) {
189
+ * if (result.error instanceof WorkflowCancelledError) {
190
+ * // graceful cancellation
191
+ * } else if (result.error instanceof WorkflowScopeError) {
192
+ * // domain error — `result.error.cause` is the original throwable
193
+ * }
194
+ * }
195
+ * ```
196
+ *
197
+ * Introduced so the scope helpers route every failure through neverthrow's
198
+ * railway. Previously, non-cancellation errors were re-thrown out of the
199
+ * helper, which became a `ResultAsync` rejection (`new ResultAsync(promise)`
200
+ * does not catch) — they leaked as unhandled rejections rather than
201
+ * surfacing on the typed error channel callers actually inspect.
202
+ */
203
+ declare class WorkflowScopeError extends WorkerError {
204
+ constructor(cause: unknown);
205
+ }
147
206
  //#endregion
148
- export { WorkerInferOutput as _, ChildWorkflowNotFoundError as a, SignalInputValidationError as c, WorkflowCancelledError as d, WorkflowInputValidationError as f, WorkerInferInput as g, ClientInferOutput as h, ChildWorkflowError as i, UpdateInputValidationError as l, ClientInferInput as m, ActivityInputValidationError as n, QueryInputValidationError as o, WorkflowOutputValidationError as p, ActivityOutputValidationError as r, QueryOutputValidationError as s, ActivityDefinitionNotFoundError as t, UpdateOutputValidationError as u };
149
- //# sourceMappingURL=errors-BjNG_jUi.d.mts.map
207
+ export { ClientInferOutput as _, ChildWorkflowError as a, QueryOutputValidationError as c, UpdateOutputValidationError as d, WorkflowCancelledError as f, ClientInferInput as g, WorkflowScopeError as h, ChildWorkflowCancelledError as i, SignalInputValidationError as l, WorkflowOutputValidationError as m, ActivityInputValidationError as n, ChildWorkflowNotFoundError as o, WorkflowInputValidationError as p, ActivityOutputValidationError as r, QueryInputValidationError as s, ActivityDefinitionNotFoundError as t, UpdateInputValidationError as u, WorkerInferInput as v, WorkerInferOutput as y };
208
+ //# sourceMappingURL=errors-DbPMxULo.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-BjNG_jUi.d.mts","names":[],"sources":["../src/types.ts","../src/errors.ts"],"mappings":";;;;;;AAOA;;KAAY,gBAAA;EAA6B,KAAA,EAAO,SAAA;AAAA,KAAe,gBAAA,CAAiB,WAAA,CAC9E,CAAA;;;;;KAOU,iBAAA;EAA8B,MAAA,EAAQ,SAAA;AAAA,KAAe,gBAAA,CAAiB,UAAA,CAChF,CAAA;;;;;KAOU,gBAAA;EAA6B,KAAA,EAAO,SAAA;AAAA,KAAe,gBAAA,CAAiB,UAAA,CAC9E,CAAA;;;;;KAOU,iBAAA;EAA8B,MAAA,EAAQ,SAAA;AAAA,KAAe,gBAAA,CAAiB,WAAA,CAChF,CAAA;;;;;;uBC1Ba,WAAA,SAAoB,KAAA;EAAA,UACxB,WAAA,CAAa,OAAA,UAAiB,KAAA;AAAA;;;;cAa5B,+BAAA,SAAwC,WAAA;EAAA,SAEjC,YAAA;EAAA,SACA,oBAAA;cADA,YAAA,UACA,oBAAA;AAAA;;;;cAaP,4BAAA,SAAqC,WAAA;EAAA,SAE9B,Y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A,MAAA,EAAQ,aAAA,CAAc,gBAAA,CAAiB,KAAA;cADvC,UAAA,UACA,MAAA,EAAQ,aAAA,CAAc,gBAAA,CAAiB,KAAA;AAAA;;;AArH3D;cAgIa,2BAAA,SAAoC,WAAA;EAAA,SAE7B,UAAA;EAAA,SACA,MAAA,EAAQ,aAAA,CAAc,gBAAA,CAAiB,KAAA;cADvC,UAAA,UACA,MAAA,EAAQ,aAAA,CAAc,gBAAA,CAAiB,KAAA;AAAA;;;;cAW9C,0BAAA,SAAmC,WAAA;EAAA,SAE5B,YAAA;EAAA,SACA,kBAAA;cADA,YAAA,UACA,kBAAA;AAAA;;;;;;;;;;cAiBP,kBAAA,SAA2B,WAAA;cAC1B,OAAA,UAAiB,KAAA;AAAA;;;;;;;;;;;AArI/B;;;;cAyJa,2BAAA,SAAoC,kBAAA;EAAA,SAE7B,YAAA;cAAA,YAAA,UAChB,KAAA;AAAA;;;;;;;;;;;;;cAmBS,sBAAA,SAA+B,WAAA;cAC9B,KAAA;AAAA;;AAlKd;;;;;;;;;;;;;;;;;;;;;;;;AAcA;;;;cAuLa,kBAAA,SAA2B,WAAA;cAC1B,KAAA;AAAA"}
@@ -1,47 +1,7 @@
1
- import { makeContinueAsNewFunc, proxyActivities } from "@temporalio/workflow";
2
- //#region src/format.ts
3
- /**
4
- * Pattern for string keys safe to render with dot notation. A "safe" key is a
5
- * JavaScript identifier (letters/digits/underscore/$, not starting with a
6
- * digit). Anything else — keys containing dots, spaces, leading digits, the
7
- * empty string, the literal string `"0"` etc. — gets bracket-quoted so the
8
- * path is unambiguous. Reserved words are accepted: we are formatting a
9
- * diagnostic, not generating runnable code.
10
- */
11
- const SAFE_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
12
- /**
13
- * Render a Standard Schema {@link StandardSchemaV1.Issue} into a human-readable
14
- * string that includes the failing field's path.
15
- */
16
- function formatIssue(issue) {
17
- if (issue.path === void 0 || issue.path.length === 0) return issue.message;
18
- let path = "";
19
- for (let i = 0; i < issue.path.length; i++) {
20
- const segment = issue.path[i];
21
- const key = segment !== null && typeof segment === "object" && "key" in segment ? segment.key : segment;
22
- if (typeof key === "number") path += `[${key}]`;
23
- else if (typeof key === "string" && SAFE_IDENTIFIER.test(key)) path += i === 0 ? key : `.${key}`;
24
- else if (typeof key === "string") path += `[${JSON.stringify(key)}]`;
25
- else path += `[${String(key)}]`;
26
- }
27
- return `at ${path}: ${issue.message}`;
28
- }
29
- /**
30
- * Join a list of validation issues into a single message, with each issue
31
- * rendered via {@link formatIssue} so field paths surface in the error text.
32
- */
33
- function summarizeIssues(issues) {
34
- return issues.map(formatIssue).join("; ");
35
- }
36
- /**
37
- * Build the message attached to a `ChildWorkflowError` for input/output
38
- * validation failures. Centralized so the worker and any future call sites
39
- * format identically.
40
- */
41
- function formatChildWorkflowValidationMessage(workflowName, direction, issues) {
42
- return `Child workflow "${workflowName}" ${direction} validation failed: ${summarizeIssues(issues)}`;
43
- }
44
- //#endregion
1
+ import { summarizeIssues } from "@temporal-contract/contract";
2
+ import { isCancellation, makeContinueAsNewFunc, proxyActivities } from "@temporalio/workflow";
3
+ import { ChildWorkflowFailure } from "@temporalio/common";
4
+ import { _internal_makeResultAsync as makeResultAsync } from "@temporal-contract/contract/result-async";
45
5
  //#region src/errors.ts
46
6
  /**
47
7
  * Base error class for worker errors
@@ -186,7 +146,13 @@ var ChildWorkflowNotFoundError = class extends WorkerError {
186
146
  }
187
147
  };
188
148
  /**
189
- * Generic error for child workflow operations
149
+ * Generic error for child workflow operations.
150
+ *
151
+ * When the child execution itself fails (Temporal's `ChildWorkflowFailure`),
152
+ * `cause` is set to the *unwrapped* underlying failure (`ApplicationFailure`,
153
+ * `TimeoutFailure`, `TerminatedFailure`, etc.) lifted from Temporal's wrapper —
154
+ * mirroring the client-side `WorkflowFailedError.cause` behavior, so callers
155
+ * can branch on the failure category in one step instead of unwrapping twice.
190
156
  */
191
157
  var ChildWorkflowError = class extends WorkerError {
192
158
  constructor(message, cause) {
@@ -195,13 +161,37 @@ var ChildWorkflowError = class extends WorkerError {
195
161
  }
196
162
  };
197
163
  /**
164
+ * Discriminated variant of {@link ChildWorkflowError} surfaced when a child
165
+ * workflow operation (start, execute, or wait-for-result) was cancelled —
166
+ * either because the parent workflow itself was cancelled, the child was
167
+ * explicitly cancelled, or its enclosing cancellation scope was. Detected via
168
+ * `@temporalio/workflow`'s `isCancellation(...)`, which sees through nested
169
+ * `ChildWorkflowFailure` / `CancelledFailure` chains.
170
+ *
171
+ * Extends {@link ChildWorkflowError} so existing `instanceof ChildWorkflowError`
172
+ * checks still match cancellation, while `instanceof ChildWorkflowCancelledError`
173
+ * lets call sites narrow further when they need to branch on cancellation
174
+ * explicitly without inspecting `error.cause` against a Temporal SDK class —
175
+ * the worker-side analogue of the client-side cause-forwarding pattern.
176
+ */
177
+ var ChildWorkflowCancelledError = class extends ChildWorkflowError {
178
+ constructor(workflowName, cause) {
179
+ super(`Child workflow "${workflowName}" was cancelled`, cause);
180
+ this.workflowName = workflowName;
181
+ this.name = "ChildWorkflowCancelledError";
182
+ }
183
+ };
184
+ /**
198
185
  * Error surfaced in the `err(...)` branch of a `ResultAsync` when a typed
199
186
  * cancellation scope is cancelled via Temporal's cancellation propagation.
200
187
  * Returned by both `context.cancellableScope` (when the workflow or an
201
188
  * ancestor scope cancels) and `context.nonCancellableScope` (when
202
189
  * cancellation is raised from inside the scope). Distinct from arbitrary
203
- * thrown errors so call sites can branch on cancellation explicitly while
204
- * still surfacing non-cancellation errors as ResultAsync rejections.
190
+ * thrown errors so call sites can branch on cancellation explicitly.
191
+ *
192
+ * Non-cancellation errors thrown inside a scope surface as a sibling
193
+ * {@link WorkflowScopeError} on the same `err(...)` channel, so callers can
194
+ * use `instanceof` to discriminate without falling back to `try/catch`.
205
195
  */
206
196
  var WorkflowCancelledError = class extends WorkerError {
207
197
  constructor(cause) {
@@ -209,6 +199,42 @@ var WorkflowCancelledError = class extends WorkerError {
209
199
  this.name = "WorkflowCancelledError";
210
200
  }
211
201
  };
202
+ /**
203
+ * Error surfaced in the `err(...)` branch of a `ResultAsync` when the
204
+ * function passed to `cancellableScope` / `nonCancellableScope` throws a
205
+ * non-cancellation error.
206
+ *
207
+ * The original error is preserved on `cause` so call sites can introspect
208
+ * it without losing identity:
209
+ *
210
+ * @example
211
+ * ```ts
212
+ * const result = await context.cancellableScope(async () => {
213
+ * return await context.activities.processStep(args);
214
+ * });
215
+ *
216
+ * if (result.isErr()) {
217
+ * if (result.error instanceof WorkflowCancelledError) {
218
+ * // graceful cancellation
219
+ * } else if (result.error instanceof WorkflowScopeError) {
220
+ * // domain error — `result.error.cause` is the original throwable
221
+ * }
222
+ * }
223
+ * ```
224
+ *
225
+ * Introduced so the scope helpers route every failure through neverthrow's
226
+ * railway. Previously, non-cancellation errors were re-thrown out of the
227
+ * helper, which became a `ResultAsync` rejection (`new ResultAsync(promise)`
228
+ * does not catch) — they leaked as unhandled rejections rather than
229
+ * surfacing on the typed error channel callers actually inspect.
230
+ */
231
+ var WorkflowScopeError = class extends WorkerError {
232
+ constructor(cause) {
233
+ const message = cause instanceof Error ? `Workflow cancellation scope caught a non-cancellation error: ${cause.message}` : "Workflow cancellation scope caught a non-cancellation error";
234
+ super(message, cause);
235
+ this.name = "WorkflowScopeError";
236
+ }
237
+ };
212
238
  //#endregion
213
239
  //#region src/internal.ts
214
240
  /**
@@ -219,6 +245,15 @@ var WorkflowCancelledError = class extends WorkerError {
219
245
  * In-package tests import it directly via relative path.
220
246
  */
221
247
  /**
248
+ * Build the message attached to a `ChildWorkflowError` for input/output
249
+ * validation failures. Centralized so the worker formats child-workflow
250
+ * validation diagnostics identically across call sites. Composes the shared
251
+ * `summarizeIssues` from `@temporal-contract/contract`.
252
+ */
253
+ function formatChildWorkflowValidationMessage(workflowName, direction, issues) {
254
+ return `Child workflow "${workflowName}" ${direction} validation failed: ${summarizeIssues(issues)}`;
255
+ }
256
+ /**
222
257
  * Extract the single payload from a Temporal handler's `...args` array.
223
258
  *
224
259
  * Temporal invokes handlers with whatever was passed via `args: [...]` at the
@@ -348,7 +383,50 @@ function looksLikeCrossContractCall(arg1, arg2) {
348
383
  const workflows = candidate["workflows"];
349
384
  return typeof workflows === "object" && workflows !== null;
350
385
  }
386
+ /**
387
+ * Map a thrown error from `startChild` / `executeChild` / `handle.result()`
388
+ * (the worker-side child-workflow API) into the discriminated union surfaced
389
+ * by the typed worker. Mirrors the client's `classifyResultError`:
390
+ *
391
+ * - Cancellation (detected via `@temporalio/workflow`'s `isCancellation`,
392
+ * which sees through nested `ChildWorkflowFailure → CancelledFailure`
393
+ * chains) → {@link ChildWorkflowCancelledError}, with the original error
394
+ * carried as `cause`.
395
+ * - Temporal's `ChildWorkflowFailure` (a wrapper whose actionable failure —
396
+ * `ApplicationFailure`, `TimeoutFailure`, `TerminatedFailure`, etc. — lives
397
+ * on its `cause` field) → {@link ChildWorkflowError}, with that *inner*
398
+ * cause forwarded so consumers can match `err.cause instanceof
399
+ * ApplicationFailure` without unwrapping twice. (If the wrapper's `cause`
400
+ * is `undefined`, the wrapper itself is forwarded so identity is
401
+ * preserved.)
402
+ * - Anything else → {@link ChildWorkflowError} carrying the raw thrown value
403
+ * as `cause`.
404
+ *
405
+ * The `operation` discriminator drives the human-readable error message so
406
+ * call sites don't have to format their own.
407
+ *
408
+ * Note: `ChildWorkflowNotFoundError` is *not* produced here — it's only
409
+ * thrown from the input-validation path when the workflow definition is
410
+ * missing on the contract, before any Temporal call happens.
411
+ */
412
+ function classifyChildWorkflowError(operation, error, childWorkflowName) {
413
+ if (isCancellation(error)) return new ChildWorkflowCancelledError(childWorkflowName, error);
414
+ if (error instanceof ChildWorkflowFailure) {
415
+ const inner = error.cause ?? error;
416
+ const innerMessage = inner instanceof Error ? inner.message : String(inner);
417
+ return new ChildWorkflowError(`${describeChildWorkflowOperation(operation, childWorkflowName)}: ${innerMessage}`, inner);
418
+ }
419
+ const message = error instanceof Error ? error.message : String(error);
420
+ return new ChildWorkflowError(`${describeChildWorkflowOperation(operation, childWorkflowName)}: ${message}`, error);
421
+ }
422
+ function describeChildWorkflowOperation(operation, childWorkflowName) {
423
+ switch (operation) {
424
+ case "startChild": return `Failed to start child workflow "${childWorkflowName}"`;
425
+ case "executeChild": return `Failed to execute child workflow "${childWorkflowName}"`;
426
+ case "result": return `Child workflow "${childWorkflowName}" execution failed`;
427
+ }
428
+ }
351
429
  //#endregion
352
- export { formatChildWorkflowValidationMessage as _, ActivityInputValidationError as a, ChildWorkflowNotFoundError as c, SignalInputValidationError as d, UpdateInputValidationError as f, WorkflowOutputValidationError as g, WorkflowInputValidationError as h, ActivityDefinitionNotFoundError as i, QueryInputValidationError as l, WorkflowCancelledError as m, createContinueAsNew as n, ActivityOutputValidationError as o, UpdateOutputValidationError as p, extractHandlerInput as r, ChildWorkflowError as s, buildRawActivitiesProxy as t, QueryOutputValidationError as u };
430
+ export { UpdateOutputValidationError as _, formatChildWorkflowValidationMessage as a, WorkflowOutputValidationError as b, ActivityInputValidationError as c, ChildWorkflowError as d, ChildWorkflowNotFoundError as f, UpdateInputValidationError as g, SignalInputValidationError as h, extractHandlerInput as i, ActivityOutputValidationError as l, QueryOutputValidationError as m, classifyChildWorkflowError as n, makeResultAsync as o, QueryInputValidationError as p, createContinueAsNew as r, ActivityDefinitionNotFoundError as s, buildRawActivitiesProxy as t, ChildWorkflowCancelledError as u, WorkflowCancelledError as v, WorkflowScopeError as x, WorkflowInputValidationError as y };
353
431
 
354
- //# sourceMappingURL=internal--45IXCxX.mjs.map
432
+ //# sourceMappingURL=internal-BzG1KhEK.mjs.map