@temporal-contract/worker 0.0.4 → 0.0.6

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.
@@ -1,316 +0,0 @@
1
- import { ActivityOptions, WorkflowInfo } from "@temporalio/workflow";
2
- import { Future, Result } from "@swan-io/boxed";
3
- import { ActivityDefinition, ContractDefinition, QueryDefinition, SignalDefinition, UpdateDefinition, WorkerInferInput, WorkerInferOutput, WorkerInferWorkflowContextActivities } from "@temporal-contract/contract";
4
- import { StandardSchemaV1 } from "@standard-schema/spec";
5
-
6
- //#region src/errors.d.ts
7
- /**
8
- * Base error class for worker errors
9
- */
10
- declare class WorkerError extends Error {
11
- constructor(message: string, cause?: unknown);
12
- }
13
- /**
14
- * Activity error class that should be used to wrap all technical exceptions
15
- * Forces proper error handling and enables retry policies
16
- */
17
- declare class ActivityError extends Error {
18
- readonly code: string;
19
- readonly cause?: unknown;
20
- constructor(code: string, message: string, cause?: unknown);
21
- }
22
- /**
23
- * Error thrown when an activity definition is not found in the contract
24
- */
25
- declare class ActivityDefinitionNotFoundError extends WorkerError {
26
- readonly activityName: string;
27
- readonly availableDefinitions: readonly string[];
28
- constructor(activityName: string, availableDefinitions?: readonly string[]);
29
- }
30
- /**
31
- * Error thrown when activity input validation fails
32
- */
33
- declare class ActivityInputValidationError extends WorkerError {
34
- readonly activityName: string;
35
- readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
36
- constructor(activityName: string, issues: ReadonlyArray<StandardSchemaV1.Issue>);
37
- }
38
- /**
39
- * Error thrown when activity output validation fails
40
- */
41
- declare class ActivityOutputValidationError extends WorkerError {
42
- readonly activityName: string;
43
- readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
44
- constructor(activityName: string, issues: ReadonlyArray<StandardSchemaV1.Issue>);
45
- }
46
- /**
47
- * Error thrown when workflow input validation fails
48
- */
49
- declare class WorkflowInputValidationError extends WorkerError {
50
- readonly workflowName: string;
51
- readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
52
- constructor(workflowName: string, issues: ReadonlyArray<StandardSchemaV1.Issue>);
53
- }
54
- /**
55
- * Error thrown when workflow output validation fails
56
- */
57
- declare class WorkflowOutputValidationError extends WorkerError {
58
- readonly workflowName: string;
59
- readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
60
- constructor(workflowName: string, issues: ReadonlyArray<StandardSchemaV1.Issue>);
61
- }
62
- /**
63
- * Error thrown when signal input validation fails
64
- */
65
- declare class SignalInputValidationError extends WorkerError {
66
- readonly signalName: string;
67
- readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
68
- constructor(signalName: string, issues: ReadonlyArray<StandardSchemaV1.Issue>);
69
- }
70
- /**
71
- * Error thrown when query input validation fails
72
- */
73
- declare class QueryInputValidationError extends WorkerError {
74
- readonly queryName: string;
75
- readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
76
- constructor(queryName: string, issues: ReadonlyArray<StandardSchemaV1.Issue>);
77
- }
78
- /**
79
- * Error thrown when query output validation fails
80
- */
81
- declare class QueryOutputValidationError extends WorkerError {
82
- readonly queryName: string;
83
- readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
84
- constructor(queryName: string, issues: ReadonlyArray<StandardSchemaV1.Issue>);
85
- }
86
- /**
87
- * Error thrown when update input validation fails
88
- */
89
- declare class UpdateInputValidationError extends WorkerError {
90
- readonly updateName: string;
91
- readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
92
- constructor(updateName: string, issues: ReadonlyArray<StandardSchemaV1.Issue>);
93
- }
94
- /**
95
- * Error thrown when update output validation fails
96
- */
97
- declare class UpdateOutputValidationError extends WorkerError {
98
- readonly updateName: string;
99
- readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
100
- constructor(updateName: string, issues: ReadonlyArray<StandardSchemaV1.Issue>);
101
- }
102
- //#endregion
103
- //#region src/handler.d.ts
104
- /**
105
- * Workflow context with typed activities (workflow + global) and workflow info
106
- * Note: activities is typed as 'any' to work around TypeScript generic type inference limitations with Zod tuples
107
- */
108
- interface WorkflowContext<TContract extends ContractDefinition, TWorkflowName extends keyof TContract["workflows"]> {
109
- activities: WorkerInferWorkflowContextActivities<TContract, TWorkflowName>;
110
- info: WorkflowInfo;
111
- }
112
- /**
113
- * Workflow implementation function (receives context + typed args as tuple)
114
- * Note: We use 'any' for args to work around TypeScript limitations with generic Zod tuple inference
115
- * The actual type will be enforced at runtime by Zod validation
116
- */
117
- type WorkflowImplementation<TContract extends ContractDefinition, TWorkflowName extends keyof TContract["workflows"]> = (context: WorkflowContext<TContract, TWorkflowName>, args: WorkerInferInput<TContract["workflows"][TWorkflowName]>) => Promise<WorkerInferOutput<TContract["workflows"][TWorkflowName]>>;
118
- /**
119
- * Activity implementation using Result pattern
120
- * Returns Future<Result<Output, ActivityError>> instead of throwing exceptions
121
- */
122
- type BoxedActivityImplementation<TActivity extends ActivityDefinition> = (args: WorkerInferInput<TActivity>) => Future<Result<WorkerInferOutput<TActivity>, ActivityError>>;
123
- /**
124
- * Signal handler implementation
125
- */
126
- type SignalHandlerImplementation<TSignal extends SignalDefinition> = (args: WorkerInferInput<TSignal>) => void | Promise<void>;
127
- /**
128
- * Query handler implementation
129
- */
130
- type QueryHandlerImplementation<TQuery extends QueryDefinition> = (args: WorkerInferInput<TQuery>) => WorkerInferOutput<TQuery>;
131
- /**
132
- * Update handler implementation
133
- */
134
- type UpdateHandlerImplementation<TUpdate extends UpdateDefinition> = (args: WorkerInferInput<TUpdate>) => Promise<WorkerInferOutput<TUpdate>>;
135
- /**
136
- * Map of all activity implementations for a contract (global + all workflow-specific)
137
- */
138
- type ActivityImplementations<T extends ContractDefinition> = (T["activities"] extends Record<string, ActivityDefinition> ? { [K in keyof T["activities"]]: BoxedActivityImplementation<T["activities"][K]> } : {}) & UnionToIntersection<{ [K in keyof T["workflows"]]: T["workflows"][K]["activities"] extends Record<string, ActivityDefinition> ? { [A in keyof T["workflows"][K]["activities"]]: BoxedActivityImplementation<T["workflows"][K]["activities"][A]> } : {} }[keyof T["workflows"]]>;
139
- /**
140
- * Utility type to convert union to intersection
141
- */
142
- type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
143
- /**
144
- * Options for creating activities handler
145
- */
146
- interface DeclareActivitiesHandlerOptions<T extends ContractDefinition> {
147
- contract: T;
148
- activities: ActivityImplementations<T>;
149
- }
150
- /**
151
- * Activities handler ready for Temporal Worker
152
- */
153
- interface ActivitiesHandler<T extends ContractDefinition> {
154
- contract: T;
155
- activities: Record<string, (...args: unknown[]) => Promise<unknown>>;
156
- }
157
- /**
158
- * Options for declaring a workflow implementation
159
- */
160
- interface DeclareWorkflowOptions<TContract extends ContractDefinition, TWorkflowName extends keyof TContract["workflows"]> {
161
- workflowName: TWorkflowName;
162
- contract: TContract;
163
- implementation: WorkflowImplementation<TContract, TWorkflowName>;
164
- /**
165
- * Default activity options applied to all activities in this workflow.
166
- * These will be merged with the default startToCloseTimeout of 60 seconds.
167
- * For more control, you can override specific Temporal ActivityOptions like:
168
- * - startToCloseTimeout: Maximum time for activity execution
169
- * - scheduleToCloseTimeout: End-to-end timeout including queuing
170
- * - scheduleToStartTimeout: Maximum time activity can wait in queue
171
- * - heartbeatTimeout: Time between heartbeats before considering activity dead
172
- * - retry: Retry policy for failed activities
173
- *
174
- * @example
175
- * ```ts
176
- * activityOptions: {
177
- * startToCloseTimeout: '5m',
178
- * retry: { maximumAttempts: 3 }
179
- * }
180
- * ```
181
- */
182
- activityOptions?: ActivityOptions;
183
- /**
184
- * Signal handlers (if defined in workflow)
185
- */
186
- signals?: TContract["workflows"][TWorkflowName]["signals"] extends Record<string, SignalDefinition> ? { [K in keyof TContract["workflows"][TWorkflowName]["signals"]]: SignalHandlerImplementation<TContract["workflows"][TWorkflowName]["signals"][K]> } : never;
187
- /**
188
- * Query handlers (if defined in workflow)
189
- */
190
- queries?: TContract["workflows"][TWorkflowName]["queries"] extends Record<string, QueryDefinition> ? { [K in keyof TContract["workflows"][TWorkflowName]["queries"]]: QueryHandlerImplementation<TContract["workflows"][TWorkflowName]["queries"][K]> } : never;
191
- /**
192
- * Update handlers (if defined in workflow)
193
- */
194
- updates?: TContract["workflows"][TWorkflowName]["updates"] extends Record<string, UpdateDefinition> ? { [K in keyof TContract["workflows"][TWorkflowName]["updates"]]: UpdateHandlerImplementation<TContract["workflows"][TWorkflowName]["updates"][K]> } : never;
195
- }
196
- /**
197
- * Create a typed activities handler with automatic validation and Result pattern
198
- *
199
- * This wraps all activity implementations with:
200
- * - Validation at network boundaries
201
- * - Result<T, ActivityError> pattern for explicit error handling
202
- * - Automatic conversion from Result to Promise (throwing on Error)
203
- *
204
- * TypeScript ensures ALL activities (global + workflow-specific) are implemented.
205
- *
206
- * Use this to create the activities object for the Temporal Worker.
207
- *
208
- * @example
209
- * ```ts
210
- * import { declareActivitiesHandler, ActivityError } from '@temporal-contract/worker/activity';
211
- * import { Result, Future } from '@swan-io/boxed';
212
- * import myContract from './contract';
213
- *
214
- * export const activitiesHandler = declareActivitiesHandler({
215
- * contract: myContract,
216
- * activities: {
217
- * // Activity returns Result instead of throwing
218
- * // All technical exceptions must be wrapped in ActivityError for retry policies
219
- * sendEmail: (args) => {
220
- * return Future.make(async resolve => {
221
- * try {
222
- * await emailService.send(args);
223
- * resolve(Result.Ok({ sent: true }));
224
- * } catch (error) {
225
- * // Wrap technical errors in ActivityError to enable retries
226
- * resolve(Result.Error(
227
- * new ActivityError(
228
- * 'EMAIL_SEND_FAILED',
229
- * 'Failed to send email',
230
- * error // Original error as cause for debugging
231
- * )
232
- * ));
233
- * }
234
- * });
235
- * },
236
- * },
237
- * });
238
- *
239
- * // Use with Temporal Worker
240
- * import { Worker } from '@temporalio/worker';
241
- *
242
- * const worker = await Worker.create({
243
- * workflowsPath: require.resolve('./workflows'),
244
- * activities: activitiesHandler.activities,
245
- * taskQueue: activitiesHandler.contract.taskQueue,
246
- * });
247
- * ```
248
- */
249
- declare function declareActivitiesHandler<T extends ContractDefinition>(options: DeclareActivitiesHandlerOptions<T>): ActivitiesHandler<T>;
250
- /**
251
- * Create a typed workflow implementation with automatic validation
252
- *
253
- * This wraps a workflow implementation with:
254
- * - Input/output validation
255
- * - Typed workflow context with activities
256
- * - Workflow info access
257
- *
258
- * Workflows must be defined in separate files and imported by the Temporal Worker
259
- * via workflowsPath.
260
- *
261
- * @example
262
- * ```ts
263
- * // workflows/processOrder.ts
264
- * import { declareWorkflow } from '@temporal-contract/worker';
265
- * import myContract from '../contract';
266
- *
267
- * export const processOrder = declareWorkflow({
268
- * workflowName: 'processOrder',
269
- * contract: myContract,
270
- * implementation: async (context, orderId, customerId) => {
271
- * // context.activities: typed activities (workflow + global)
272
- * // context.info: WorkflowInfo
273
- *
274
- * const inventory = await context.activities.validateInventory(orderId);
275
- *
276
- * if (!inventory.available) {
277
- * throw new Error('Out of stock');
278
- * }
279
- *
280
- * const payment = await context.activities.chargePayment(customerId, 100);
281
- *
282
- * // Global activity
283
- * await context.activities.sendEmail(
284
- * customerId,
285
- * 'Order processed',
286
- * 'Your order has been processed'
287
- * );
288
- *
289
- * return {
290
- * orderId,
291
- * status: payment.success ? 'success' : 'failed',
292
- * transactionId: payment.transactionId,
293
- * };
294
- * },
295
- * activityOptions: {
296
- * startToCloseTimeout: '1 minute',
297
- * },
298
- * });
299
- * ```
300
- *
301
- * Then in your worker setup:
302
- * ```ts
303
- * // worker.ts
304
- * import { Worker } from '@temporalio/worker';
305
- * import { activitiesHandler } from './activities';
306
- *
307
- * const worker = await Worker.create({
308
- * workflowsPath: require.resolve('./workflows'), // Imports processOrder
309
- * activities: activitiesHandler.activities,
310
- * taskQueue: activitiesHandler.contract.taskQueue,
311
- * });
312
- * ```
313
- */
314
- declare function declareWorkflow<TContract extends ContractDefinition, TWorkflowName extends keyof TContract["workflows"]>(options: DeclareWorkflowOptions<TContract, TWorkflowName>): (args: WorkerInferInput<TContract["workflows"][TWorkflowName]>) => Promise<WorkerInferOutput<TContract["workflows"][TWorkflowName]>>;
315
- //#endregion
316
- export { WorkflowInputValidationError as C, WorkerError as S, QueryInputValidationError as _, DeclareWorkflowOptions as a, UpdateInputValidationError as b, UpdateHandlerImplementation as c, declareActivitiesHandler as d, declareWorkflow as f, ActivityOutputValidationError as g, ActivityInputValidationError as h, DeclareActivitiesHandlerOptions as i, WorkflowContext as l, ActivityError as m, ActivityImplementations as n, QueryHandlerImplementation as o, ActivityDefinitionNotFoundError as p, BoxedActivityImplementation as r, SignalHandlerImplementation as s, ActivitiesHandler as t, WorkflowImplementation as u, QueryOutputValidationError as v, WorkflowOutputValidationError as w, UpdateOutputValidationError as x, SignalInputValidationError as y };