@temporal-contract/worker 0.0.5 → 0.0.7
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 +23 -0
- package/dist/activity-Csptpwgf.d.cts +162 -0
- package/dist/activity-UOnp_bSX.d.mts +162 -0
- package/dist/activity.cjs +190 -7
- package/dist/activity.d.cts +3 -2
- package/dist/activity.d.mts +3 -2
- package/dist/activity.mjs +182 -2
- package/dist/errors-BqVTpfcf.mjs +155 -0
- package/dist/errors-BqYWpdvd.d.cts +137 -0
- package/dist/errors-C1RFkCuD.d.mts +137 -0
- package/dist/errors-DjSZg-93.cjs +227 -0
- package/dist/worker.cjs +65 -0
- package/dist/worker.d.cts +68 -0
- package/dist/worker.d.mts +68 -0
- package/dist/worker.mjs +64 -0
- package/dist/workflow.cjs +255 -12
- package/dist/workflow.d.cts +299 -2
- package/dist/workflow.d.mts +299 -2
- package/dist/workflow.mjs +244 -2
- package/package.json +26 -14
- package/dist/handler-BAzNuAZz.cjs +0 -597
- package/dist/handler-Cp9h_XCy.d.cts +0 -560
- package/dist/handler-DFFpSaGN.mjs +0 -502
- package/dist/handler-uAeIi9f0.d.mts +0 -560
package/dist/workflow.cjs
CHANGED
|
@@ -1,13 +1,256 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_errors = require('./errors-DjSZg-93.cjs');
|
|
2
|
+
let _temporal_contract_boxed = require("@temporal-contract/boxed");
|
|
3
|
+
let _temporalio_workflow = require("@temporalio/workflow");
|
|
2
4
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
5
|
+
//#region src/workflow.ts
|
|
6
|
+
/**
|
|
7
|
+
* Create a typed workflow implementation with automatic validation
|
|
8
|
+
*
|
|
9
|
+
* This wraps a workflow implementation with:
|
|
10
|
+
* - Input/output validation
|
|
11
|
+
* - Typed workflow context with activities
|
|
12
|
+
* - Workflow info access
|
|
13
|
+
*
|
|
14
|
+
* Workflows must be defined in separate files and imported by the Temporal Worker
|
|
15
|
+
* via workflowsPath.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* // workflows/processOrder.ts
|
|
20
|
+
* import { declareWorkflow } from '@temporal-contract/worker';
|
|
21
|
+
* import myContract from '../contract';
|
|
22
|
+
*
|
|
23
|
+
* export const processOrder = declareWorkflow({
|
|
24
|
+
* workflowName: 'processOrder',
|
|
25
|
+
* contract: myContract,
|
|
26
|
+
* implementation: async (context, orderId, customerId) => {
|
|
27
|
+
* // context.activities: typed activities (workflow + global)
|
|
28
|
+
* // context.info: WorkflowInfo
|
|
29
|
+
*
|
|
30
|
+
* const inventory = await context.activities.validateInventory(orderId);
|
|
31
|
+
*
|
|
32
|
+
* if (!inventory.available) {
|
|
33
|
+
* throw new Error('Out of stock');
|
|
34
|
+
* }
|
|
35
|
+
*
|
|
36
|
+
* const payment = await context.activities.chargePayment(customerId, 100);
|
|
37
|
+
*
|
|
38
|
+
* // Global activity
|
|
39
|
+
* await context.activities.sendEmail(
|
|
40
|
+
* customerId,
|
|
41
|
+
* 'Order processed',
|
|
42
|
+
* 'Your order has been processed'
|
|
43
|
+
* );
|
|
44
|
+
*
|
|
45
|
+
* return {
|
|
46
|
+
* orderId,
|
|
47
|
+
* status: payment.success ? 'success' : 'failed',
|
|
48
|
+
* transactionId: payment.transactionId,
|
|
49
|
+
* };
|
|
50
|
+
* },
|
|
51
|
+
* activityOptions: {
|
|
52
|
+
* startToCloseTimeout: '1 minute',
|
|
53
|
+
* },
|
|
54
|
+
* });
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* Then in your worker setup:
|
|
58
|
+
* ```ts
|
|
59
|
+
* // worker.ts
|
|
60
|
+
* import { Worker } from '@temporalio/worker';
|
|
61
|
+
* import { activitiesHandler } from './activities';
|
|
62
|
+
*
|
|
63
|
+
* const worker = await Worker.create({
|
|
64
|
+
* workflowsPath: require.resolve('./workflows'), // Imports processOrder
|
|
65
|
+
* activities: activitiesHandler.activities,
|
|
66
|
+
* taskQueue: activitiesHandler.contract.taskQueue,
|
|
67
|
+
* });
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
function declareWorkflow({ workflowName, contract, implementation, activityOptions }) {
|
|
71
|
+
const definition = contract.workflows[workflowName];
|
|
72
|
+
return async (...args) => {
|
|
73
|
+
const input = args.length === 1 ? args[0] : args;
|
|
74
|
+
const inputResult = await definition.input["~standard"].validate(input);
|
|
75
|
+
if (inputResult.issues) throw new require_errors.WorkflowInputValidationError(String(workflowName), inputResult.issues);
|
|
76
|
+
const validatedInput = inputResult.value;
|
|
77
|
+
let contextActivities = {};
|
|
78
|
+
if (definition.activities || contract.activities) contextActivities = createValidatedActivities((0, _temporalio_workflow.proxyActivities)(activityOptions), definition.activities, contract.activities);
|
|
79
|
+
async function validateChildWorkflowOutput(childDefinition, result$1, childWorkflowName) {
|
|
80
|
+
const outputResult$1 = await childDefinition.output["~standard"].validate(result$1);
|
|
81
|
+
if (outputResult$1.issues) return _temporal_contract_boxed.Result.Error(new require_errors.ChildWorkflowError(`Child workflow "${childWorkflowName}" output validation failed: ${outputResult$1.issues.map((i) => i.message).join("; ")}`));
|
|
82
|
+
return _temporal_contract_boxed.Result.Ok(outputResult$1.value);
|
|
83
|
+
}
|
|
84
|
+
async function getAndValidateChildWorkflow(childContract, childWorkflowName, args$1) {
|
|
85
|
+
const childDefinition = childContract.workflows[childWorkflowName];
|
|
86
|
+
if (!childDefinition) return _temporal_contract_boxed.Result.Error(new require_errors.ChildWorkflowNotFoundError(String(childWorkflowName), Object.keys(childContract.workflows)));
|
|
87
|
+
const inputResult$1 = await childDefinition.input["~standard"].validate(args$1);
|
|
88
|
+
if (inputResult$1.issues) return _temporal_contract_boxed.Result.Error(new require_errors.ChildWorkflowError(`Child workflow "${String(childWorkflowName)}" input validation failed: ${inputResult$1.issues.map((i) => i.message).join("; ")}`));
|
|
89
|
+
const validatedInput$1 = inputResult$1.value;
|
|
90
|
+
return _temporal_contract_boxed.Result.Ok({
|
|
91
|
+
definition: childDefinition,
|
|
92
|
+
validatedInput: validatedInput$1,
|
|
93
|
+
taskQueue: childContract.taskQueue
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
function createTypedChildHandle(handle, childDefinition, childWorkflowName) {
|
|
97
|
+
return {
|
|
98
|
+
workflowId: handle.workflowId,
|
|
99
|
+
result: () => {
|
|
100
|
+
return _temporal_contract_boxed.Future.make((resolve) => {
|
|
101
|
+
(async () => {
|
|
102
|
+
try {
|
|
103
|
+
resolve(await validateChildWorkflowOutput(childDefinition, await handle.result(), childWorkflowName));
|
|
104
|
+
} catch (error) {
|
|
105
|
+
resolve(_temporal_contract_boxed.Result.Error(new require_errors.ChildWorkflowError(`Child workflow execution failed: ${error instanceof Error ? error.message : String(error)}`, error)));
|
|
106
|
+
}
|
|
107
|
+
})();
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
function createStartChildWorkflow(childContract, childWorkflowName, options) {
|
|
113
|
+
return _temporal_contract_boxed.Future.make((resolve) => {
|
|
114
|
+
(async () => {
|
|
115
|
+
const validationResult = await getAndValidateChildWorkflow(childContract, childWorkflowName, options.args);
|
|
116
|
+
if (validationResult.isError()) {
|
|
117
|
+
resolve(_temporal_contract_boxed.Result.Error(validationResult.error));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
const { definition: childDefinition, validatedInput: validatedInput$1, taskQueue } = validationResult.value;
|
|
121
|
+
try {
|
|
122
|
+
const { args: _args, ...temporalOptions } = options;
|
|
123
|
+
const typedHandle = createTypedChildHandle(await (0, _temporalio_workflow.startChild)(childWorkflowName, {
|
|
124
|
+
...temporalOptions,
|
|
125
|
+
taskQueue,
|
|
126
|
+
args: [validatedInput$1]
|
|
127
|
+
}), childDefinition, String(childWorkflowName));
|
|
128
|
+
resolve(_temporal_contract_boxed.Result.Ok(typedHandle));
|
|
129
|
+
} catch (error) {
|
|
130
|
+
resolve(_temporal_contract_boxed.Result.Error(new require_errors.ChildWorkflowError(`Failed to start child workflow: ${error instanceof Error ? error.message : String(error)}`, error)));
|
|
131
|
+
}
|
|
132
|
+
})();
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
function createExecuteChildWorkflow(childContract, childWorkflowName, options) {
|
|
136
|
+
return _temporal_contract_boxed.Future.make((resolve) => {
|
|
137
|
+
(async () => {
|
|
138
|
+
const validationResult = await getAndValidateChildWorkflow(childContract, childWorkflowName, options.args);
|
|
139
|
+
if (validationResult.isError()) {
|
|
140
|
+
resolve(_temporal_contract_boxed.Result.Error(validationResult.error));
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const { definition: childDefinition, validatedInput: validatedInput$1, taskQueue } = validationResult.value;
|
|
144
|
+
try {
|
|
145
|
+
const { args: _args, ...temporalOptions } = options;
|
|
146
|
+
const outputValidationResult = await validateChildWorkflowOutput(childDefinition, await (0, _temporalio_workflow.executeChild)(childWorkflowName, {
|
|
147
|
+
...temporalOptions,
|
|
148
|
+
taskQueue,
|
|
149
|
+
args: [validatedInput$1]
|
|
150
|
+
}), String(childWorkflowName));
|
|
151
|
+
if (outputValidationResult.isError()) {
|
|
152
|
+
resolve(_temporal_contract_boxed.Result.Error(outputValidationResult.error));
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
resolve(_temporal_contract_boxed.Result.Ok(outputValidationResult.value));
|
|
156
|
+
} catch (error) {
|
|
157
|
+
resolve(_temporal_contract_boxed.Result.Error(new require_errors.ChildWorkflowError(`Failed to execute child workflow: ${error instanceof Error ? error.message : String(error)}`, error)));
|
|
158
|
+
}
|
|
159
|
+
})();
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
function createDefineSignal(signalName, handler) {
|
|
163
|
+
if (!definition.signals) throw new Error(`Signal "${String(signalName)}" cannot be defined: workflow "${String(workflowName)}" has no signals in its contract`);
|
|
164
|
+
const signalDef = definition.signals[signalName];
|
|
165
|
+
if (!signalDef) throw new Error(`Signal "${String(signalName)}" not found in workflow "${String(workflowName)}" contract`);
|
|
166
|
+
(0, _temporalio_workflow.setHandler)((0, _temporalio_workflow.defineSignal)(signalName), async (...args$1) => {
|
|
167
|
+
const input$1 = args$1.length === 1 ? args$1[0] : args$1;
|
|
168
|
+
const inputResult$1 = await signalDef.input["~standard"].validate(input$1);
|
|
169
|
+
if (inputResult$1.issues) throw new require_errors.SignalInputValidationError(signalName, inputResult$1.issues);
|
|
170
|
+
await handler(inputResult$1.value);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
function createDefineQuery(queryName, handler) {
|
|
174
|
+
if (!definition.queries) throw new Error(`Query "${String(queryName)}" cannot be defined: workflow "${String(workflowName)}" has no queries in its contract`);
|
|
175
|
+
const queryDef = definition.queries[queryName];
|
|
176
|
+
if (!queryDef) throw new Error(`Query "${String(queryName)}" not found in workflow "${String(workflowName)}" contract`);
|
|
177
|
+
(0, _temporalio_workflow.setHandler)((0, _temporalio_workflow.defineQuery)(queryName), (...args$1) => {
|
|
178
|
+
const input$1 = args$1.length === 1 ? args$1[0] : args$1;
|
|
179
|
+
const inputResult$1 = queryDef.input["~standard"].validate(input$1);
|
|
180
|
+
if (inputResult$1 instanceof Promise) throw new Error(`Query "${String(queryName)}" validation must be synchronous. Use a schema library that supports synchronous validation for queries.`);
|
|
181
|
+
if (inputResult$1.issues) throw new require_errors.QueryInputValidationError(queryName, inputResult$1.issues);
|
|
182
|
+
const result$1 = handler(inputResult$1.value);
|
|
183
|
+
const outputResult$1 = queryDef.output["~standard"].validate(result$1);
|
|
184
|
+
if (outputResult$1 instanceof Promise) throw new Error(`Query "${String(queryName)}" output validation must be synchronous. Use a schema library that supports synchronous validation for queries.`);
|
|
185
|
+
if (outputResult$1.issues) throw new require_errors.QueryOutputValidationError(queryName, outputResult$1.issues);
|
|
186
|
+
return outputResult$1.value;
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
function createDefineUpdate(updateName, handler) {
|
|
190
|
+
if (!definition.updates) throw new Error(`Update "${String(updateName)}" cannot be defined: workflow "${String(workflowName)}" has no updates in its contract`);
|
|
191
|
+
const updateDef = definition.updates[updateName];
|
|
192
|
+
if (!updateDef) throw new Error(`Update "${String(updateName)}" not found in workflow "${String(workflowName)}" contract`);
|
|
193
|
+
(0, _temporalio_workflow.setHandler)((0, _temporalio_workflow.defineUpdate)(updateName), async (...args$1) => {
|
|
194
|
+
const input$1 = args$1.length === 1 ? args$1[0] : args$1;
|
|
195
|
+
const inputResult$1 = await updateDef.input["~standard"].validate(input$1);
|
|
196
|
+
if (inputResult$1.issues) throw new require_errors.UpdateInputValidationError(updateName, inputResult$1.issues);
|
|
197
|
+
const result$1 = await handler(inputResult$1.value);
|
|
198
|
+
const outputResult$1 = await updateDef.output["~standard"].validate(result$1);
|
|
199
|
+
if (outputResult$1.issues) throw new require_errors.UpdateOutputValidationError(updateName, outputResult$1.issues);
|
|
200
|
+
return outputResult$1.value;
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
const result = await implementation({
|
|
204
|
+
activities: contextActivities,
|
|
205
|
+
info: (0, _temporalio_workflow.workflowInfo)(),
|
|
206
|
+
startChildWorkflow: createStartChildWorkflow,
|
|
207
|
+
executeChildWorkflow: createExecuteChildWorkflow,
|
|
208
|
+
defineSignal: createDefineSignal,
|
|
209
|
+
defineQuery: createDefineQuery,
|
|
210
|
+
defineUpdate: createDefineUpdate
|
|
211
|
+
}, validatedInput);
|
|
212
|
+
const outputResult = await definition.output["~standard"].validate(result);
|
|
213
|
+
if (outputResult.issues) throw new require_errors.WorkflowOutputValidationError(String(workflowName), outputResult.issues);
|
|
214
|
+
return outputResult.value;
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Create a validated activities proxy that parses inputs and outputs
|
|
219
|
+
*
|
|
220
|
+
* This wrapper ensures data integrity across the network boundary between
|
|
221
|
+
* workflow and activity execution.
|
|
222
|
+
*/
|
|
223
|
+
function createValidatedActivities(rawActivities, workflowActivitiesDefinition, contractActivitiesDefinition) {
|
|
224
|
+
const validatedActivities = {};
|
|
225
|
+
const allActivitiesDefinition = {
|
|
226
|
+
...contractActivitiesDefinition,
|
|
227
|
+
...workflowActivitiesDefinition
|
|
228
|
+
};
|
|
229
|
+
for (const [activityName, activityDef] of Object.entries(allActivitiesDefinition)) {
|
|
230
|
+
const rawActivity = rawActivities[activityName];
|
|
231
|
+
if (!rawActivity) throw new Error(`Activity implementation not found for: "${activityName}". Available activities: ${Object.keys(rawActivities).length > 0 ? Object.keys(rawActivities).join(", ") : "none"}`);
|
|
232
|
+
validatedActivities[activityName] = async (input) => {
|
|
233
|
+
const inputResult = await activityDef.input["~standard"].validate(input);
|
|
234
|
+
if (inputResult.issues) throw new require_errors.ActivityInputValidationError(activityName, inputResult.issues);
|
|
235
|
+
const result = await rawActivity(inputResult.value);
|
|
236
|
+
const outputResult = await activityDef.output["~standard"].validate(result);
|
|
237
|
+
if (outputResult.issues) throw new require_errors.ActivityOutputValidationError(activityName, outputResult.issues);
|
|
238
|
+
return outputResult.value;
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
return validatedActivities;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
//#endregion
|
|
245
|
+
exports.ActivityInputValidationError = require_errors.ActivityInputValidationError;
|
|
246
|
+
exports.ActivityOutputValidationError = require_errors.ActivityOutputValidationError;
|
|
247
|
+
exports.ChildWorkflowError = require_errors.ChildWorkflowError;
|
|
248
|
+
exports.ChildWorkflowNotFoundError = require_errors.ChildWorkflowNotFoundError;
|
|
249
|
+
exports.QueryInputValidationError = require_errors.QueryInputValidationError;
|
|
250
|
+
exports.QueryOutputValidationError = require_errors.QueryOutputValidationError;
|
|
251
|
+
exports.SignalInputValidationError = require_errors.SignalInputValidationError;
|
|
252
|
+
exports.UpdateInputValidationError = require_errors.UpdateInputValidationError;
|
|
253
|
+
exports.UpdateOutputValidationError = require_errors.UpdateOutputValidationError;
|
|
254
|
+
exports.WorkflowInputValidationError = require_errors.WorkflowInputValidationError;
|
|
255
|
+
exports.WorkflowOutputValidationError = require_errors.WorkflowOutputValidationError;
|
|
256
|
+
exports.declareWorkflow = declareWorkflow;
|
package/dist/workflow.d.cts
CHANGED
|
@@ -1,2 +1,299 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { a as ChildWorkflowNotFoundError, c as SignalInputValidationError, d as WorkflowInputValidationError, f as WorkflowOutputValidationError, g as WorkerInferOutput, h as WorkerInferInput, i as ChildWorkflowError, l as UpdateInputValidationError, m as ClientInferOutput, n as ActivityInputValidationError, o as QueryInputValidationError, p as ClientInferInput, r as ActivityOutputValidationError, s as QueryOutputValidationError, u as UpdateOutputValidationError } from "./errors-BqYWpdvd.cjs";
|
|
2
|
+
import { ActivityDefinition, ContractDefinition, QueryDefinition, SignalDefinition, UpdateDefinition, WorkflowDefinition } from "@temporal-contract/contract";
|
|
3
|
+
import { Future, Result } from "@temporal-contract/boxed";
|
|
4
|
+
import { ActivityOptions, ChildWorkflowOptions, WorkflowInfo } from "@temporalio/workflow";
|
|
5
|
+
|
|
6
|
+
//#region src/workflow.d.ts
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Create a typed workflow implementation with automatic validation
|
|
10
|
+
*
|
|
11
|
+
* This wraps a workflow implementation with:
|
|
12
|
+
* - Input/output validation
|
|
13
|
+
* - Typed workflow context with activities
|
|
14
|
+
* - Workflow info access
|
|
15
|
+
*
|
|
16
|
+
* Workflows must be defined in separate files and imported by the Temporal Worker
|
|
17
|
+
* via workflowsPath.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* // workflows/processOrder.ts
|
|
22
|
+
* import { declareWorkflow } from '@temporal-contract/worker';
|
|
23
|
+
* import myContract from '../contract';
|
|
24
|
+
*
|
|
25
|
+
* export const processOrder = declareWorkflow({
|
|
26
|
+
* workflowName: 'processOrder',
|
|
27
|
+
* contract: myContract,
|
|
28
|
+
* implementation: async (context, orderId, customerId) => {
|
|
29
|
+
* // context.activities: typed activities (workflow + global)
|
|
30
|
+
* // context.info: WorkflowInfo
|
|
31
|
+
*
|
|
32
|
+
* const inventory = await context.activities.validateInventory(orderId);
|
|
33
|
+
*
|
|
34
|
+
* if (!inventory.available) {
|
|
35
|
+
* throw new Error('Out of stock');
|
|
36
|
+
* }
|
|
37
|
+
*
|
|
38
|
+
* const payment = await context.activities.chargePayment(customerId, 100);
|
|
39
|
+
*
|
|
40
|
+
* // Global activity
|
|
41
|
+
* await context.activities.sendEmail(
|
|
42
|
+
* customerId,
|
|
43
|
+
* 'Order processed',
|
|
44
|
+
* 'Your order has been processed'
|
|
45
|
+
* );
|
|
46
|
+
*
|
|
47
|
+
* return {
|
|
48
|
+
* orderId,
|
|
49
|
+
* status: payment.success ? 'success' : 'failed',
|
|
50
|
+
* transactionId: payment.transactionId,
|
|
51
|
+
* };
|
|
52
|
+
* },
|
|
53
|
+
* activityOptions: {
|
|
54
|
+
* startToCloseTimeout: '1 minute',
|
|
55
|
+
* },
|
|
56
|
+
* });
|
|
57
|
+
* ```
|
|
58
|
+
*
|
|
59
|
+
* Then in your worker setup:
|
|
60
|
+
* ```ts
|
|
61
|
+
* // worker.ts
|
|
62
|
+
* import { Worker } from '@temporalio/worker';
|
|
63
|
+
* import { activitiesHandler } from './activities';
|
|
64
|
+
*
|
|
65
|
+
* const worker = await Worker.create({
|
|
66
|
+
* workflowsPath: require.resolve('./workflows'), // Imports processOrder
|
|
67
|
+
* activities: activitiesHandler.activities,
|
|
68
|
+
* taskQueue: activitiesHandler.contract.taskQueue,
|
|
69
|
+
* });
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
declare function declareWorkflow<TContract extends ContractDefinition, TWorkflowName extends keyof TContract["workflows"]>({
|
|
73
|
+
workflowName,
|
|
74
|
+
contract,
|
|
75
|
+
implementation,
|
|
76
|
+
activityOptions
|
|
77
|
+
}: DeclareWorkflowOptions<TContract, TWorkflowName>): (...args: unknown[]) => Promise<WorkerInferOutput<TContract["workflows"][TWorkflowName]>>;
|
|
78
|
+
/**
|
|
79
|
+
* Signal handler implementation
|
|
80
|
+
*
|
|
81
|
+
* Processes signal input and can optionally perform asynchronous operations.
|
|
82
|
+
* Should not return a value (signals are fire-and-forget).
|
|
83
|
+
*/
|
|
84
|
+
type SignalHandlerImplementation<TSignal extends SignalDefinition> = (args: WorkerInferInput<TSignal>) => void | Promise<void>;
|
|
85
|
+
/**
|
|
86
|
+
* Query handler implementation
|
|
87
|
+
*
|
|
88
|
+
* Processes query input and returns a synchronous response.
|
|
89
|
+
* Must be synchronous to satisfy Temporal's query constraints.
|
|
90
|
+
*/
|
|
91
|
+
type QueryHandlerImplementation<TQuery extends QueryDefinition> = (args: WorkerInferInput<TQuery>) => WorkerInferOutput<TQuery>;
|
|
92
|
+
/**
|
|
93
|
+
* Update handler implementation
|
|
94
|
+
*
|
|
95
|
+
* Processes update input and returns a validated response after modifying workflow state.
|
|
96
|
+
* Can perform asynchronous operations.
|
|
97
|
+
*/
|
|
98
|
+
type UpdateHandlerImplementation<TUpdate extends UpdateDefinition> = (args: WorkerInferInput<TUpdate>) => Promise<WorkerInferOutput<TUpdate>>;
|
|
99
|
+
/**
|
|
100
|
+
* Options for declaring a workflow implementation
|
|
101
|
+
*/
|
|
102
|
+
interface DeclareWorkflowOptions<TContract extends ContractDefinition, TWorkflowName extends keyof TContract["workflows"]> {
|
|
103
|
+
workflowName: TWorkflowName;
|
|
104
|
+
contract: TContract;
|
|
105
|
+
implementation: WorkflowImplementation<TContract, TWorkflowName>;
|
|
106
|
+
/**
|
|
107
|
+
* Default activity options applied to all activities in this workflow.
|
|
108
|
+
* For more control, you can override specific Temporal ActivityOptions like:
|
|
109
|
+
* - startToCloseTimeout: Maximum time for activity execution
|
|
110
|
+
* - scheduleToCloseTimeout: End-to-end timeout including queuing
|
|
111
|
+
* - scheduleToStartTimeout: Maximum time activity can wait in queue
|
|
112
|
+
* - heartbeatTimeout: Time between heartbeats before considering activity dead
|
|
113
|
+
* - retry: Retry policy for failed activities
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```ts
|
|
117
|
+
* activityOptions: {
|
|
118
|
+
* startToCloseTimeout: '5m',
|
|
119
|
+
* retry: { maximumAttempts: 3 }
|
|
120
|
+
* }
|
|
121
|
+
* ```
|
|
122
|
+
*/
|
|
123
|
+
activityOptions: ActivityOptions;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Workflow implementation function
|
|
127
|
+
*
|
|
128
|
+
* Receives a workflow context (with typed activities and utilities) and validated input arguments.
|
|
129
|
+
* Returns the workflow output which will be validated against the contract schema.
|
|
130
|
+
*/
|
|
131
|
+
type WorkflowImplementation<TContract extends ContractDefinition, TWorkflowName extends keyof TContract["workflows"]> = (context: WorkflowContext<TContract, TWorkflowName>, args: WorkerInferInput<TContract["workflows"][TWorkflowName]>) => Promise<WorkerInferOutput<TContract["workflows"][TWorkflowName]>>;
|
|
132
|
+
/**
|
|
133
|
+
* Workflow execution context providing typed activities, workflow info, and interaction handlers
|
|
134
|
+
*
|
|
135
|
+
* Provides access to:
|
|
136
|
+
* - Typed activities (both workflow-specific and global)
|
|
137
|
+
* - Workflow metadata and execution info
|
|
138
|
+
* - Signal, query, and update handler registration
|
|
139
|
+
* - Child workflow execution capabilities
|
|
140
|
+
*/
|
|
141
|
+
interface WorkflowContext<TContract extends ContractDefinition, TWorkflowName extends keyof TContract["workflows"]> {
|
|
142
|
+
activities: WorkflowInferWorkflowContextActivities<TContract, TWorkflowName>;
|
|
143
|
+
info: WorkflowInfo;
|
|
144
|
+
/**
|
|
145
|
+
* Define a signal handler within the workflow implementation
|
|
146
|
+
* Allows the signal handler to access workflow state
|
|
147
|
+
*
|
|
148
|
+
* @example
|
|
149
|
+
* ```ts
|
|
150
|
+
* implementation: async (context, args) => {
|
|
151
|
+
* let currentValue = args.initialValue;
|
|
152
|
+
*
|
|
153
|
+
* context.defineSignal('increment', async (signalArgs) => {
|
|
154
|
+
* currentValue += signalArgs.amount;
|
|
155
|
+
* });
|
|
156
|
+
*
|
|
157
|
+
* // ... rest of workflow
|
|
158
|
+
* }
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
defineSignal: <K$1 extends keyof TContract["workflows"][TWorkflowName]["signals"]>(signalName: K$1, handler: SignalHandlerImplementation<TContract["workflows"][TWorkflowName]["signals"][K$1] extends SignalDefinition ? TContract["workflows"][TWorkflowName]["signals"][K$1] : never>) => void;
|
|
162
|
+
/**
|
|
163
|
+
* Define a query handler within the workflow implementation
|
|
164
|
+
* Allows the query handler to access workflow state
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* ```ts
|
|
168
|
+
* implementation: async (context, args) => {
|
|
169
|
+
* let currentValue = args.initialValue;
|
|
170
|
+
*
|
|
171
|
+
* context.defineQuery('getCurrentValue', () => {
|
|
172
|
+
* return { value: currentValue };
|
|
173
|
+
* });
|
|
174
|
+
*
|
|
175
|
+
* // ... rest of workflow
|
|
176
|
+
* }
|
|
177
|
+
* ```
|
|
178
|
+
*/
|
|
179
|
+
defineQuery: <K$1 extends keyof TContract["workflows"][TWorkflowName]["queries"]>(queryName: K$1, handler: QueryHandlerImplementation<TContract["workflows"][TWorkflowName]["queries"][K$1] extends QueryDefinition ? TContract["workflows"][TWorkflowName]["queries"][K$1] : never>) => void;
|
|
180
|
+
/**
|
|
181
|
+
* Define an update handler within the workflow implementation
|
|
182
|
+
* Allows the update handler to access and modify workflow state
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* ```ts
|
|
186
|
+
* implementation: async (context, args) => {
|
|
187
|
+
* let currentValue = args.initialValue;
|
|
188
|
+
*
|
|
189
|
+
* context.defineUpdate('multiply', async (updateArgs) => {
|
|
190
|
+
* currentValue *= updateArgs.factor;
|
|
191
|
+
* return { newValue: currentValue };
|
|
192
|
+
* });
|
|
193
|
+
*
|
|
194
|
+
* // ... rest of workflow
|
|
195
|
+
* }
|
|
196
|
+
* ```
|
|
197
|
+
*/
|
|
198
|
+
defineUpdate: <K$1 extends keyof TContract["workflows"][TWorkflowName]["updates"]>(updateName: K$1, handler: UpdateHandlerImplementation<TContract["workflows"][TWorkflowName]["updates"][K$1] extends UpdateDefinition ? TContract["workflows"][TWorkflowName]["updates"][K$1] : never>) => void;
|
|
199
|
+
/**
|
|
200
|
+
* Start a child workflow and return a typed handle with Future/Result pattern
|
|
201
|
+
*
|
|
202
|
+
* Supports both same-contract and cross-contract child workflows:
|
|
203
|
+
* - Same contract: Pass workflowName from current contract
|
|
204
|
+
* - Cross-contract: Pass contract and workflowName to invoke workflows from other workers
|
|
205
|
+
*
|
|
206
|
+
* @example
|
|
207
|
+
* ```ts
|
|
208
|
+
* // Same contract child workflow
|
|
209
|
+
* const childResult = await context.startChildWorkflow(myContract, 'processPayment', {
|
|
210
|
+
* workflowId: 'payment-123',
|
|
211
|
+
* args: { amount: 100 }
|
|
212
|
+
* });
|
|
213
|
+
*
|
|
214
|
+
* // Cross-contract child workflow (from another worker)
|
|
215
|
+
* const otherResult = await context.startChildWorkflow(otherContract, 'sendNotification', {
|
|
216
|
+
* workflowId: 'notification-123',
|
|
217
|
+
* args: { message: 'Hello' }
|
|
218
|
+
* });
|
|
219
|
+
*
|
|
220
|
+
* childResult.match({
|
|
221
|
+
* Ok: async (handle) => {
|
|
222
|
+
* const result = await handle.result();
|
|
223
|
+
* // ... handle result
|
|
224
|
+
* },
|
|
225
|
+
* Error: (error) => console.error('Failed to start:', error),
|
|
226
|
+
* });
|
|
227
|
+
* ```
|
|
228
|
+
*/
|
|
229
|
+
startChildWorkflow: <TChildContract extends ContractDefinition, TChildWorkflowName extends keyof TChildContract["workflows"]>(contract: TChildContract, workflowName: TChildWorkflowName, options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>) => Future<Result<TypedChildWorkflowHandle<TChildContract["workflows"][TChildWorkflowName]>, ChildWorkflowError>>;
|
|
230
|
+
/**
|
|
231
|
+
* Execute a child workflow (start and wait for result) with Future/Result pattern
|
|
232
|
+
*
|
|
233
|
+
* Supports both same-contract and cross-contract child workflows:
|
|
234
|
+
* - Same contract: Pass workflowName from current contract
|
|
235
|
+
* - Cross-contract: Pass contract and workflowName to invoke workflows from other workers
|
|
236
|
+
*
|
|
237
|
+
* @example
|
|
238
|
+
* ```ts
|
|
239
|
+
* // Same contract child workflow
|
|
240
|
+
* const result = await context.executeChildWorkflow(myContract, 'processPayment', {
|
|
241
|
+
* workflowId: 'payment-123',
|
|
242
|
+
* args: { amount: 100 }
|
|
243
|
+
* });
|
|
244
|
+
*
|
|
245
|
+
* // Cross-contract child workflow (from another worker)
|
|
246
|
+
* const otherResult = await context.executeChildWorkflow(otherContract, 'sendNotification', {
|
|
247
|
+
* workflowId: 'notification-123',
|
|
248
|
+
* args: { message: 'Hello' }
|
|
249
|
+
* });
|
|
250
|
+
*
|
|
251
|
+
* result.match({
|
|
252
|
+
* Ok: (output) => console.log('Payment processed:', output),
|
|
253
|
+
* Error: (error) => console.error('Processing failed:', error),
|
|
254
|
+
* });
|
|
255
|
+
* ```
|
|
256
|
+
*/
|
|
257
|
+
executeChildWorkflow: <TChildContract extends ContractDefinition, TChildWorkflowName extends keyof TChildContract["workflows"]>(contract: TChildContract, workflowName: TChildWorkflowName, options: TypedChildWorkflowOptions<TChildContract, TChildWorkflowName>) => Future<Result<ClientInferOutput<TChildContract["workflows"][TChildWorkflowName]>, ChildWorkflowError>>;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Options for starting a child workflow
|
|
261
|
+
*/
|
|
262
|
+
type TypedChildWorkflowOptions<TChildContract extends ContractDefinition, TChildWorkflowName extends keyof TChildContract["workflows"]> = Omit<ChildWorkflowOptions, "taskQueue" | "args"> & {
|
|
263
|
+
args: ClientInferInput<TChildContract["workflows"][TChildWorkflowName]>;
|
|
264
|
+
};
|
|
265
|
+
/**
|
|
266
|
+
* Typed handle for a child workflow with Future/Result pattern
|
|
267
|
+
*/
|
|
268
|
+
interface TypedChildWorkflowHandle<TWorkflow extends WorkflowDefinition> {
|
|
269
|
+
/**
|
|
270
|
+
* Get child workflow result with Result pattern
|
|
271
|
+
*/
|
|
272
|
+
result: () => Future<Result<ClientInferOutput<TWorkflow>, ChildWorkflowError>>;
|
|
273
|
+
/**
|
|
274
|
+
* Child workflow ID
|
|
275
|
+
*/
|
|
276
|
+
workflowId: string;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Activity function signature from workflow execution perspective
|
|
280
|
+
*
|
|
281
|
+
* Workflows call activities with validated input (z.input parsed) and receive validated output (z.output)
|
|
282
|
+
*/
|
|
283
|
+
type WorkflowInferActivity<TActivity extends ActivityDefinition> = (args: ClientInferInput<TActivity>) => Promise<ClientInferOutput<TActivity>>;
|
|
284
|
+
/**
|
|
285
|
+
* All global activities from a contract (workflow execution perspective)
|
|
286
|
+
*/
|
|
287
|
+
type WorkflowInferActivities<TContract extends ContractDefinition> = TContract["activities"] extends Record<string, ActivityDefinition> ? { [K in keyof TContract["activities"]]: WorkflowInferActivity<TContract["activities"][K]> } : {};
|
|
288
|
+
/**
|
|
289
|
+
* Workflow-specific activities (workflow execution perspective)
|
|
290
|
+
*/
|
|
291
|
+
type WorkflowInferWorkflowActivities<T extends WorkflowDefinition> = T["activities"] extends Record<string, ActivityDefinition> ? { [K in keyof T["activities"]]: WorkflowInferActivity<T["activities"][K]> } : {};
|
|
292
|
+
/**
|
|
293
|
+
* All activities available in a workflow context (workflow execution perspective)
|
|
294
|
+
*
|
|
295
|
+
* Combines workflow-specific activities with global contract activities
|
|
296
|
+
*/
|
|
297
|
+
type WorkflowInferWorkflowContextActivities<TContract extends ContractDefinition, TWorkflowName extends keyof TContract["workflows"]> = WorkflowInferWorkflowActivities<TContract["workflows"][TWorkflowName]> & WorkflowInferActivities<TContract>;
|
|
298
|
+
//#endregion
|
|
299
|
+
export { ActivityInputValidationError, ActivityOutputValidationError, ChildWorkflowError, ChildWorkflowNotFoundError, QueryInputValidationError, QueryOutputValidationError, SignalInputValidationError, UpdateInputValidationError, UpdateOutputValidationError, WorkflowInputValidationError, WorkflowOutputValidationError, declareWorkflow };
|