@temporal-contract/worker 0.2.0 → 1.0.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 CHANGED
@@ -14,7 +14,7 @@ pnpm add @temporal-contract/worker @temporal-contract/contract @temporalio/workf
14
14
 
15
15
  ```typescript
16
16
  // activities.ts
17
- import { declareActivitiesHandler, ActivityError } from "@temporal-contract/worker/activity";
17
+ import { declareActivitiesHandler, ApplicationFailure } from "@temporal-contract/worker/activity";
18
18
  import { Future, Result } from "@swan-io/boxed";
19
19
 
20
20
  export const activities = declareActivitiesHandler({
@@ -22,13 +22,12 @@ export const activities = declareActivitiesHandler({
22
22
  activities: {
23
23
  sendEmail: ({ to, body }) => {
24
24
  return Future.fromPromise(emailService.send({ to, body }))
25
- .mapError(
26
- (error) =>
27
- new ActivityError(
28
- "EMAIL_FAILED",
29
- error instanceof Error ? error.message : "Failed to send email",
30
- error,
31
- ),
25
+ .mapError((error) =>
26
+ ApplicationFailure.create({
27
+ type: "EMAIL_FAILED",
28
+ message: error instanceof Error ? error.message : "Failed to send email",
29
+ cause: error,
30
+ }),
32
31
  )
33
32
  .mapOk(() => ({ sent: true }));
34
33
  },
package/dist/activity.cjs CHANGED
@@ -1,103 +1,13 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_errors = require('./errors-DjSZg-93.cjs');
3
-
4
- //#region src/activity-utils.ts
5
- /**
6
- * Extract activity definitions for a specific workflow from a contract
7
- *
8
- * This includes both:
9
- * - Workflow-specific activities defined under workflow.activities
10
- * - Global activities defined under contract.activities
11
- *
12
- * @param contract - The contract definition
13
- * @param workflowName - The name of the workflow
14
- * @returns Activity definitions for the workflow (workflow-specific + global activities merged)
15
- *
16
- * @example
17
- * ```ts
18
- * const orderWorkflowActivities = getWorkflowActivities(myContract, 'processOrder');
19
- * // Returns: { processPayment: ActivityDef, reserveInventory: ActivityDef, sendEmail: ActivityDef }
20
- * // where sendEmail is a global activity
21
- * ```
22
- */
23
- function getWorkflowActivities(contract, workflowName) {
24
- const workflowActivities = contract.workflows[workflowName]?.activities || {};
25
- return {
26
- ...contract.activities || {},
27
- ...workflowActivities
28
- };
29
- }
30
- /**
31
- * Extract all activity names for a specific workflow from a contract
32
- *
33
- * @param contract - The contract definition
34
- * @param workflowName - The name of the workflow
35
- * @returns Array of activity names (strings) available for the workflow
36
- *
37
- * @example
38
- * ```ts
39
- * const activityNames = getWorkflowActivityNames(myContract, 'processOrder');
40
- * // Returns: ['processPayment', 'reserveInventory', 'sendEmail']
41
- * ```
42
- */
43
- function getWorkflowActivityNames(contract, workflowName) {
44
- const activities = getWorkflowActivities(contract, workflowName);
45
- return Object.keys(activities);
46
- }
47
- /**
48
- * Check if an activity belongs to a specific workflow
49
- *
50
- * @param contract - The contract definition
51
- * @param workflowName - The name of the workflow
52
- * @param activityName - The name of the activity to check
53
- * @returns True if the activity is available for the workflow, false otherwise
54
- *
55
- * @example
56
- * ```ts
57
- * if (isWorkflowActivity(myContract, 'processOrder', 'processPayment')) {
58
- * // Activity is available for this workflow
59
- * }
60
- * ```
61
- */
62
- function isWorkflowActivity(contract, workflowName, activityName) {
63
- return activityName in getWorkflowActivities(contract, workflowName);
64
- }
65
- /**
66
- * Get all workflow names from a contract
67
- *
68
- * @param contract - The contract definition
69
- * @returns Array of workflow names defined in the contract
70
- *
71
- * @example
72
- * ```ts
73
- * const workflows = getWorkflowNames(myContract);
74
- * // Returns: ['processOrder', 'processRefund']
75
- * ```
76
- */
77
- function getWorkflowNames(contract) {
78
- return Object.keys(contract.workflows);
79
- }
80
-
81
- //#endregion
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_internal = require("./internal-Tj4m4f_K.cjs");
3
+ let _temporalio_common = require("@temporalio/common");
82
4
  //#region src/activity.ts
83
5
  /**
84
- * Activity error class that should be used to wrap all technical exceptions
85
- * Forces proper error handling and enables retry policies
86
- */
87
- var ActivityError = class ActivityError extends Error {
88
- constructor(code, message, cause) {
89
- super(message, { cause });
90
- this.code = code;
91
- this.name = "ActivityError";
92
- if (Error.captureStackTrace) Error.captureStackTrace(this, ActivityError);
93
- }
94
- };
95
- /**
96
- * Create a typed activities handler with automatic validation and Result pattern
6
+ * Create a typed activities handler with automatic validation and Result pattern.
97
7
  *
98
8
  * This wraps all activity implementations with:
99
9
  * - Validation at network boundaries
100
- * - Result<T, ActivityError> pattern for explicit error handling
10
+ * - `Result<T, ApplicationFailure>` pattern for explicit error handling
101
11
  * - Automatic conversion from Result to Promise (throwing on Error)
102
12
  *
103
13
  * TypeScript ensures ALL activities (global + workflow-specific) are implemented.
@@ -106,28 +16,30 @@ var ActivityError = class ActivityError extends Error {
106
16
  *
107
17
  * @example
108
18
  * ```ts
109
- * import { declareActivitiesHandler, ActivityError } from '@temporal-contract/worker/activity';
19
+ * import { declareActivitiesHandler, ApplicationFailure } from '@temporal-contract/worker/activity';
110
20
  * import { Result, Future } from '@swan-io/boxed';
111
21
  * import myContract from './contract';
112
22
  *
113
23
  * export const activities = declareActivitiesHandler({
114
24
  * contract: myContract,
115
25
  * activities: {
116
- * // Activity returns Result instead of throwing
117
- * // All technical exceptions must be wrapped in ActivityError for retry policies
26
+ * // Activity returns Result instead of throwing.
118
27
  * sendEmail: (args) => {
119
- * return Future.make(async resolve => {
28
+ * return Future.make(async (resolve) => {
120
29
  * try {
121
30
  * await emailService.send(args);
122
31
  * resolve(Result.Ok({ sent: true }));
123
32
  * } catch (error) {
124
- * // Wrap technical errors in ActivityError to enable retries
33
+ * // Wrap technical errors in ApplicationFailure. `nonRetryable`
34
+ * // is per-instance: set it to true on permanent failures so
35
+ * // Temporal stops retrying immediately.
125
36
  * resolve(Result.Error(
126
- * new ActivityError(
127
- * 'EMAIL_SEND_FAILED',
128
- * 'Failed to send email',
129
- * error // Original error as cause for debugging
130
- * )
37
+ * ApplicationFailure.create({
38
+ * type: 'EMAIL_SEND_FAILED',
39
+ * message: 'Failed to send email',
40
+ * nonRetryable: false,
41
+ * cause: error instanceof Error ? error : undefined,
42
+ * }),
131
43
  * ));
132
44
  * }
133
45
  * });
@@ -144,19 +56,32 @@ var ActivityError = class ActivityError extends Error {
144
56
  * taskQueue: contract.taskQueue,
145
57
  * });
146
58
  * ```
59
+ *
60
+ * @remarks
61
+ * The wrapper accepts implementations in the
62
+ * `Future<Result<T, ApplicationFailure>>` shape and produces ordinary
63
+ * Promise-returning Temporal handlers (Result.Error → thrown
64
+ * `ApplicationFailure`; Result.Ok → output validated against the
65
+ * contract and resolved). It does **not** hide Temporal's
66
+ * `@temporalio/activity` runtime: inside the body you can still call
67
+ * `Context.current()` from `@temporalio/activity` to access heartbeats
68
+ * (`heartbeat(details)`, `heartbeatDetails`), activity info (attempt
69
+ * number, workflow IDs), and the async-completion task token. See the
70
+ * "Working with the Activity Context" section of the worker
71
+ * implementation guide for end-to-end examples.
147
72
  */
148
73
  function declareActivitiesHandler(options) {
149
74
  const { contract, activities } = options;
150
75
  const wrappedActivities = {};
151
76
  function makeWrapped(activityName, activityDef, activityImpl) {
152
77
  return async (...args) => {
153
- const input = args.length === 1 ? args[0] : args;
78
+ const input = require_internal.extractHandlerInput(args);
154
79
  const inputResult = await activityDef.input["~standard"].validate(input);
155
- if (inputResult.issues) throw new require_errors.ActivityInputValidationError(activityName, inputResult.issues);
80
+ if (inputResult.issues) throw new require_internal.ActivityInputValidationError(activityName, inputResult.issues);
156
81
  const result = await activityImpl(inputResult.value);
157
82
  if (result.isOk()) {
158
83
  const outputResult = await activityDef.output["~standard"].validate(result.value);
159
- if (outputResult.issues) throw new require_errors.ActivityOutputValidationError(activityName, outputResult.issues);
84
+ if (outputResult.issues) throw new require_internal.ActivityOutputValidationError(activityName, outputResult.issues);
160
85
  return outputResult.value;
161
86
  } else throw result.error;
162
87
  };
@@ -164,7 +89,7 @@ function declareActivitiesHandler(options) {
164
89
  if (contract.activities) for (const [activityName, impl] of Object.entries(activities)) {
165
90
  if (contract.workflows && activityName in contract.workflows) continue;
166
91
  const activityDef = contract.activities[activityName];
167
- if (!activityDef) throw new require_errors.ActivityDefinitionNotFoundError(activityName, Object.keys(contract.activities));
92
+ if (!activityDef) throw new require_internal.ActivityDefinitionNotFoundError(activityName, Object.keys(contract.activities));
168
93
  wrappedActivities[activityName] = makeWrapped(activityName, activityDef, impl);
169
94
  }
170
95
  if (contract.workflows) for (const [workflowName, workflowDef] of Object.entries(contract.workflows)) {
@@ -173,20 +98,20 @@ function declareActivitiesHandler(options) {
173
98
  const wfDefs = workflowDef.activities ?? {};
174
99
  for (const [activityName, impl] of Object.entries(wfActivitiesImpl)) {
175
100
  const activityDef = wfDefs[activityName];
176
- if (!activityDef) throw new require_errors.ActivityDefinitionNotFoundError(`${workflowName}.${activityName}`, Object.keys(wfDefs));
101
+ if (!activityDef) throw new require_internal.ActivityDefinitionNotFoundError(`${workflowName}.${activityName}`, Object.keys(wfDefs));
177
102
  wrappedActivities[activityName] = makeWrapped(`${workflowName}.${activityName}`, activityDef, impl);
178
103
  }
179
104
  }
180
105
  return wrappedActivities;
181
106
  }
182
-
183
107
  //#endregion
184
- exports.ActivityDefinitionNotFoundError = require_errors.ActivityDefinitionNotFoundError;
185
- exports.ActivityError = ActivityError;
186
- exports.ActivityInputValidationError = require_errors.ActivityInputValidationError;
187
- exports.ActivityOutputValidationError = require_errors.ActivityOutputValidationError;
108
+ exports.ActivityDefinitionNotFoundError = require_internal.ActivityDefinitionNotFoundError;
109
+ exports.ActivityInputValidationError = require_internal.ActivityInputValidationError;
110
+ exports.ActivityOutputValidationError = require_internal.ActivityOutputValidationError;
111
+ Object.defineProperty(exports, "ApplicationFailure", {
112
+ enumerable: true,
113
+ get: function() {
114
+ return _temporalio_common.ApplicationFailure;
115
+ }
116
+ });
188
117
  exports.declareActivitiesHandler = declareActivitiesHandler;
189
- exports.getWorkflowActivities = getWorkflowActivities;
190
- exports.getWorkflowActivityNames = getWorkflowActivityNames;
191
- exports.getWorkflowNames = getWorkflowNames;
192
- exports.isWorkflowActivity = isWorkflowActivity;
@@ -1,24 +1,19 @@
1
- import { g as WorkerInferOutput, h as WorkerInferInput, n as ActivityInputValidationError, r as ActivityOutputValidationError, t as ActivityDefinitionNotFoundError } from "./errors-4jH78z8m.cjs";
2
- import { i as isWorkflowActivity, n as getWorkflowActivityNames, r as getWorkflowNames, t as getWorkflowActivities } from "./activity-utils-RsXOceIH.cjs";
1
+ import { _ as WorkerInferOutput, g as WorkerInferInput, n as ActivityInputValidationError, r as ActivityOutputValidationError, t as ActivityDefinitionNotFoundError } from "./errors-CG1y7SHO.cjs";
3
2
  import { ActivityDefinition, ContractDefinition } from "@temporal-contract/contract";
4
3
  import { Future, Result } from "@swan-io/boxed";
4
+ import { ApplicationFailure, ApplicationFailure as ApplicationFailure$1 } from "@temporalio/common";
5
5
 
6
6
  //#region src/activity.d.ts
7
7
  /**
8
- * Activity error class that should be used to wrap all technical exceptions
9
- * Forces proper error handling and enables retry policies
10
- */
11
- declare class ActivityError extends Error {
12
- readonly code: string;
13
- constructor(code: string, message: string, cause?: unknown);
14
- }
15
- /**
16
- * Activity implementation using Future/Result pattern
8
+ * Activity implementation using Future/Result pattern.
17
9
  *
18
- * Returns Future<Result<Output, ActivityError>> for explicit error handling instead of throwing exceptions.
19
- * All errors must be wrapped in ActivityError to enable proper retry policies.
10
+ * Returns `Future<Result<Output, ApplicationFailure>>` for explicit error
11
+ * handling instead of throwing. The wrapper rethrows `Result.Error`
12
+ * payloads at the activity boundary; Temporal recognizes
13
+ * `ApplicationFailure` natively and applies the configured retry policy
14
+ * (with `nonRetryable: true` opting an instance out per-call).
20
15
  */
21
- type BoxedActivityImplementation<TActivity extends ActivityDefinition> = (args: WorkerInferInput<TActivity>) => Future<Result<WorkerInferOutput<TActivity>, ActivityError>>;
16
+ type BoxedActivityImplementation<TActivity extends ActivityDefinition> = (args: WorkerInferInput<TActivity>) => Future<Result<WorkerInferOutput<TActivity>, ApplicationFailure$1>>;
22
17
  /**
23
18
  * Map of all activity implementations for a contract (global + all workflow-specific)
24
19
  */
@@ -41,11 +36,11 @@ type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) exten
41
36
  */
42
37
  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"]]>;
43
38
  /**
44
- * Create a typed activities handler with automatic validation and Result pattern
39
+ * Create a typed activities handler with automatic validation and Result pattern.
45
40
  *
46
41
  * This wraps all activity implementations with:
47
42
  * - Validation at network boundaries
48
- * - Result<T, ActivityError> pattern for explicit error handling
43
+ * - `Result<T, ApplicationFailure>` pattern for explicit error handling
49
44
  * - Automatic conversion from Result to Promise (throwing on Error)
50
45
  *
51
46
  * TypeScript ensures ALL activities (global + workflow-specific) are implemented.
@@ -54,28 +49,30 @@ type ActivitiesHandler<TContract extends ContractDefinition> = (TContract["activ
54
49
  *
55
50
  * @example
56
51
  * ```ts
57
- * import { declareActivitiesHandler, ActivityError } from '@temporal-contract/worker/activity';
52
+ * import { declareActivitiesHandler, ApplicationFailure } from '@temporal-contract/worker/activity';
58
53
  * import { Result, Future } from '@swan-io/boxed';
59
54
  * import myContract from './contract';
60
55
  *
61
56
  * export const activities = declareActivitiesHandler({
62
57
  * contract: myContract,
63
58
  * activities: {
64
- * // Activity returns Result instead of throwing
65
- * // All technical exceptions must be wrapped in ActivityError for retry policies
59
+ * // Activity returns Result instead of throwing.
66
60
  * sendEmail: (args) => {
67
- * return Future.make(async resolve => {
61
+ * return Future.make(async (resolve) => {
68
62
  * try {
69
63
  * await emailService.send(args);
70
64
  * resolve(Result.Ok({ sent: true }));
71
65
  * } catch (error) {
72
- * // Wrap technical errors in ActivityError to enable retries
66
+ * // Wrap technical errors in ApplicationFailure. `nonRetryable`
67
+ * // is per-instance: set it to true on permanent failures so
68
+ * // Temporal stops retrying immediately.
73
69
  * resolve(Result.Error(
74
- * new ActivityError(
75
- * 'EMAIL_SEND_FAILED',
76
- * 'Failed to send email',
77
- * error // Original error as cause for debugging
78
- * )
70
+ * ApplicationFailure.create({
71
+ * type: 'EMAIL_SEND_FAILED',
72
+ * message: 'Failed to send email',
73
+ * nonRetryable: false,
74
+ * cause: error instanceof Error ? error : undefined,
75
+ * }),
79
76
  * ));
80
77
  * }
81
78
  * });
@@ -92,8 +89,21 @@ type ActivitiesHandler<TContract extends ContractDefinition> = (TContract["activ
92
89
  * taskQueue: contract.taskQueue,
93
90
  * });
94
91
  * ```
92
+ *
93
+ * @remarks
94
+ * The wrapper accepts implementations in the
95
+ * `Future<Result<T, ApplicationFailure>>` shape and produces ordinary
96
+ * Promise-returning Temporal handlers (Result.Error → thrown
97
+ * `ApplicationFailure`; Result.Ok → output validated against the
98
+ * contract and resolved). It does **not** hide Temporal's
99
+ * `@temporalio/activity` runtime: inside the body you can still call
100
+ * `Context.current()` from `@temporalio/activity` to access heartbeats
101
+ * (`heartbeat(details)`, `heartbeatDetails`), activity info (attempt
102
+ * number, workflow IDs), and the async-completion task token. See the
103
+ * "Working with the Activity Context" section of the worker
104
+ * implementation guide for end-to-end examples.
95
105
  */
96
106
  declare function declareActivitiesHandler<TContract extends ContractDefinition>(options: DeclareActivitiesHandlerOptions<TContract>): ActivitiesHandler<TContract>;
97
107
  //#endregion
98
- export { ActivitiesHandler, ActivityDefinitionNotFoundError, ActivityError, ActivityInputValidationError, ActivityOutputValidationError, declareActivitiesHandler, getWorkflowActivities, getWorkflowActivityNames, getWorkflowNames, isWorkflowActivity };
108
+ export { ActivitiesHandler, ActivityDefinitionNotFoundError, ActivityInputValidationError, ActivityOutputValidationError, ApplicationFailure, declareActivitiesHandler };
99
109
  //# sourceMappingURL=activity.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"activity.d.cts","names":[],"sources":["../src/activity.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B,SAAA,gBAAyB,SAAA,cAAuB,SAAA,wBAAiC,MAAA,SAEnG,kBAAA,IAEE,yBAAA,CAA0B,SAAA,cAAuB,SAAA,8BAE/C,SAAA;;;;;;;;;;;;;;;;;;;;;;;;AAjD2D;;;;;;;;;;;;;;;;;;;;;AAKJ;;;;;;;;;;;;;;;;;;AAQP;;;;;;iBA2G9C,wBAAA,mBAA2C,kBAAA,CAAA,CACzD,OAAA,EAAS,+BAAA,CAAgC,SAAA,IACxC,iBAAA,CAAkB,SAAA"}
@@ -1,24 +1,19 @@
1
- import { g as WorkerInferOutput, h as WorkerInferInput, n as ActivityInputValidationError, r as ActivityOutputValidationError, t as ActivityDefinitionNotFoundError } from "./errors-CmTXZ3JW.mjs";
2
- import { i as isWorkflowActivity, n as getWorkflowActivityNames, r as getWorkflowNames, t as getWorkflowActivities } from "./activity-utils-B3vP03_P.mjs";
1
+ import { _ as WorkerInferOutput, g as WorkerInferInput, n as ActivityInputValidationError, r as ActivityOutputValidationError, t as ActivityDefinitionNotFoundError } from "./errors-DZhaNhwr.mjs";
2
+ import { ApplicationFailure, ApplicationFailure as ApplicationFailure$1 } from "@temporalio/common";
3
3
  import { ActivityDefinition, ContractDefinition } from "@temporal-contract/contract";
4
4
  import { Future, Result } from "@swan-io/boxed";
5
5
 
6
6
  //#region src/activity.d.ts
7
7
  /**
8
- * Activity error class that should be used to wrap all technical exceptions
9
- * Forces proper error handling and enables retry policies
10
- */
11
- declare class ActivityError extends Error {
12
- readonly code: string;
13
- constructor(code: string, message: string, cause?: unknown);
14
- }
15
- /**
16
- * Activity implementation using Future/Result pattern
8
+ * Activity implementation using Future/Result pattern.
17
9
  *
18
- * Returns Future<Result<Output, ActivityError>> for explicit error handling instead of throwing exceptions.
19
- * All errors must be wrapped in ActivityError to enable proper retry policies.
10
+ * Returns `Future<Result<Output, ApplicationFailure>>` for explicit error
11
+ * handling instead of throwing. The wrapper rethrows `Result.Error`
12
+ * payloads at the activity boundary; Temporal recognizes
13
+ * `ApplicationFailure` natively and applies the configured retry policy
14
+ * (with `nonRetryable: true` opting an instance out per-call).
20
15
  */
21
- type BoxedActivityImplementation<TActivity extends ActivityDefinition> = (args: WorkerInferInput<TActivity>) => Future<Result<WorkerInferOutput<TActivity>, ActivityError>>;
16
+ type BoxedActivityImplementation<TActivity extends ActivityDefinition> = (args: WorkerInferInput<TActivity>) => Future<Result<WorkerInferOutput<TActivity>, ApplicationFailure$1>>;
22
17
  /**
23
18
  * Map of all activity implementations for a contract (global + all workflow-specific)
24
19
  */
@@ -41,11 +36,11 @@ type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) exten
41
36
  */
42
37
  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"]]>;
43
38
  /**
44
- * Create a typed activities handler with automatic validation and Result pattern
39
+ * Create a typed activities handler with automatic validation and Result pattern.
45
40
  *
46
41
  * This wraps all activity implementations with:
47
42
  * - Validation at network boundaries
48
- * - Result<T, ActivityError> pattern for explicit error handling
43
+ * - `Result<T, ApplicationFailure>` pattern for explicit error handling
49
44
  * - Automatic conversion from Result to Promise (throwing on Error)
50
45
  *
51
46
  * TypeScript ensures ALL activities (global + workflow-specific) are implemented.
@@ -54,28 +49,30 @@ type ActivitiesHandler<TContract extends ContractDefinition> = (TContract["activ
54
49
  *
55
50
  * @example
56
51
  * ```ts
57
- * import { declareActivitiesHandler, ActivityError } from '@temporal-contract/worker/activity';
52
+ * import { declareActivitiesHandler, ApplicationFailure } from '@temporal-contract/worker/activity';
58
53
  * import { Result, Future } from '@swan-io/boxed';
59
54
  * import myContract from './contract';
60
55
  *
61
56
  * export const activities = declareActivitiesHandler({
62
57
  * contract: myContract,
63
58
  * activities: {
64
- * // Activity returns Result instead of throwing
65
- * // All technical exceptions must be wrapped in ActivityError for retry policies
59
+ * // Activity returns Result instead of throwing.
66
60
  * sendEmail: (args) => {
67
- * return Future.make(async resolve => {
61
+ * return Future.make(async (resolve) => {
68
62
  * try {
69
63
  * await emailService.send(args);
70
64
  * resolve(Result.Ok({ sent: true }));
71
65
  * } catch (error) {
72
- * // Wrap technical errors in ActivityError to enable retries
66
+ * // Wrap technical errors in ApplicationFailure. `nonRetryable`
67
+ * // is per-instance: set it to true on permanent failures so
68
+ * // Temporal stops retrying immediately.
73
69
  * resolve(Result.Error(
74
- * new ActivityError(
75
- * 'EMAIL_SEND_FAILED',
76
- * 'Failed to send email',
77
- * error // Original error as cause for debugging
78
- * )
70
+ * ApplicationFailure.create({
71
+ * type: 'EMAIL_SEND_FAILED',
72
+ * message: 'Failed to send email',
73
+ * nonRetryable: false,
74
+ * cause: error instanceof Error ? error : undefined,
75
+ * }),
79
76
  * ));
80
77
  * }
81
78
  * });
@@ -92,8 +89,21 @@ type ActivitiesHandler<TContract extends ContractDefinition> = (TContract["activ
92
89
  * taskQueue: contract.taskQueue,
93
90
  * });
94
91
  * ```
92
+ *
93
+ * @remarks
94
+ * The wrapper accepts implementations in the
95
+ * `Future<Result<T, ApplicationFailure>>` shape and produces ordinary
96
+ * Promise-returning Temporal handlers (Result.Error → thrown
97
+ * `ApplicationFailure`; Result.Ok → output validated against the
98
+ * contract and resolved). It does **not** hide Temporal's
99
+ * `@temporalio/activity` runtime: inside the body you can still call
100
+ * `Context.current()` from `@temporalio/activity` to access heartbeats
101
+ * (`heartbeat(details)`, `heartbeatDetails`), activity info (attempt
102
+ * number, workflow IDs), and the async-completion task token. See the
103
+ * "Working with the Activity Context" section of the worker
104
+ * implementation guide for end-to-end examples.
95
105
  */
96
106
  declare function declareActivitiesHandler<TContract extends ContractDefinition>(options: DeclareActivitiesHandlerOptions<TContract>): ActivitiesHandler<TContract>;
97
107
  //#endregion
98
- export { ActivitiesHandler, ActivityDefinitionNotFoundError, ActivityError, ActivityInputValidationError, ActivityOutputValidationError, declareActivitiesHandler, getWorkflowActivities, getWorkflowActivityNames, getWorkflowNames, isWorkflowActivity };
108
+ export { ActivitiesHandler, ActivityDefinitionNotFoundError, ActivityInputValidationError, ActivityOutputValidationError, ApplicationFailure, declareActivitiesHandler };
99
109
  //# sourceMappingURL=activity.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"activity.d.mts","names":[],"sources":["../src/activity.ts"],"mappings":";;;;;;;AA2BA;;;cAAa,aAAA,SAAsB,KAAA;EAAA,SAEf,IAAA;cAAA,IAAA,UAChB,OAAA,UACA,KAAA;AAAA;;;;;;AASH;KAQI,2BAAA,mBAA8C,kBAAA,KACjD,IAAA,EAAM,gBAAA,CAAiB,SAAA,MACpB,MAAA,CAAO,MAAA,CAAO,iBAAA,CAAkB,SAAA,GAAY,aAAA;;;;KAK5C,sCAAA,mBAAyD,kBAAA,KAE3D,SAAA,uBAAgC,MAAA,SAAe,kBAAA,IAC5C,8BAAA,CAA+B,SAAA,8CAIX,SAAA,gBAAyB,SAAA,cAAuB,SAAA,wBAAiC,MAAA,SAEnG,kBAAA,IAEE,8BAAA,CAA+B,SAAA,cAAuB,SAAA;AAAA,KAI3D,8BAAA,qBAAmD,MAAA,SAAe,kBAAA,mBACzD,WAAA,GAAc,2BAAA,CAA4B,WAAA,CAAY,CAAA;;;;KAM/D,+BAAA,mBAAkD,kBAAA;EACrD,QAAA,EAAU,SAAA;EACV,UAAA,EAAY,sCAAA,CAAuC,SAAA;AAAA;AAAA,KAGhD,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,C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