@temporal-contract/client 0.0.2 → 0.0.4

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/src/client.ts DELETED
@@ -1,366 +0,0 @@
1
- import { Client, WorkflowHandle } from "@temporalio/client";
2
- import type { ClientOptions, WorkflowStartOptions, WorkflowOptions } from "@temporalio/client";
3
- import type {
4
- ClientInferInput,
5
- ClientInferOutput,
6
- ClientInferWorkflowQueries,
7
- ClientInferWorkflowSignals,
8
- ClientInferWorkflowUpdates,
9
- ContractDefinition,
10
- WorkflowDefinition,
11
- QueryDefinition,
12
- SignalDefinition,
13
- UpdateDefinition,
14
- } from "@temporal-contract/contract";
15
- import {
16
- WorkflowNotFoundError,
17
- WorkflowValidationError,
18
- QueryValidationError,
19
- SignalValidationError,
20
- UpdateValidationError,
21
- } from "./errors.js";
22
-
23
- /**
24
- * Extended options for starting workflows with Temporal-specific features
25
- * Combines required workflowId with optional Temporal workflow options
26
- */
27
- export type TypedWorkflowStartOptions = Pick<
28
- WorkflowStartOptions,
29
- | "workflowId"
30
- | "workflowIdReusePolicy"
31
- | "workflowExecutionTimeout"
32
- | "workflowRunTimeout"
33
- | "workflowTaskTimeout"
34
- | "retry"
35
- | "memo"
36
- | "searchAttributes"
37
- | "cronSchedule"
38
- > &
39
- Pick<WorkflowOptions, "workflowId">;
40
-
41
- /**
42
- * Typed workflow handle with validated results, queries, signals and updates
43
- */
44
- export interface TypedWorkflowHandle<TWorkflow extends WorkflowDefinition> {
45
- workflowId: string;
46
-
47
- /**
48
- * Type-safe queries based on workflow definition
49
- */
50
- queries: ClientInferWorkflowQueries<TWorkflow>;
51
-
52
- /**
53
- * Type-safe signals based on workflow definition
54
- */
55
- signals: ClientInferWorkflowSignals<TWorkflow>;
56
-
57
- /**
58
- * Type-safe updates based on workflow definition
59
- */
60
- updates: ClientInferWorkflowUpdates<TWorkflow>;
61
-
62
- result: () => Promise<ClientInferOutput<TWorkflow>>;
63
- terminate: (reason?: string) => Promise<void>;
64
- cancel: () => Promise<void>;
65
-
66
- /**
67
- * Get workflow execution description including status and metadata
68
- *
69
- * @example
70
- * ```ts
71
- * const handle = await client.getHandle('processOrder', 'order-123');
72
- * const description = await handle.describe();
73
- * console.log(description.workflowExecutionInfo.status); // RUNNING, COMPLETED, etc.
74
- * ```
75
- */
76
- describe: () => ReturnType<WorkflowHandle["describe"]>;
77
-
78
- /**
79
- * Fetch the workflow execution history
80
- *
81
- * @example
82
- * ```ts
83
- * const handle = await client.getHandle('processOrder', 'order-123');
84
- * const history = handle.fetchHistory();
85
- * for await (const event of history) {
86
- * console.log(event);
87
- * }
88
- * ```
89
- */
90
- fetchHistory: () => ReturnType<WorkflowHandle["fetchHistory"]>;
91
- }
92
-
93
- /**
94
- * Typed Temporal client based on a contract
95
- *
96
- * Provides type-safe methods to start and execute workflows
97
- * defined in the contract.
98
- */
99
- export class TypedClient<TContract extends ContractDefinition> {
100
- private constructor(
101
- private readonly contract: TContract,
102
- private readonly client: Client,
103
- ) {}
104
-
105
- /**
106
- * Create a typed Temporal client from a contract
107
- *
108
- * @example
109
- * ```ts
110
- * const connection = await Connection.connect();
111
- * const client = TypedClient.create(myContract, {
112
- * connection,
113
- * namespace: 'default',
114
- * });
115
- *
116
- * const result = await client.executeWorkflow('processOrder', {
117
- * workflowId: 'order-123',
118
- * args: [...],
119
- * });
120
- * ```
121
- */
122
- static create<TContract extends ContractDefinition>(
123
- contract: TContract,
124
- options: ClientOptions,
125
- ): TypedClient<TContract> {
126
- const client = new Client(options);
127
- return new TypedClient(contract, client);
128
- }
129
-
130
- /**
131
- * Start a workflow and return a typed handle
132
- *
133
- * @example
134
- * ```ts
135
- * const handle = await client.startWorkflow('processOrder', {
136
- * workflowId: 'order-123',
137
- * args: ['ORD-123', 'CUST-456', [{ productId: 'PROD-1', quantity: 2 }]],
138
- * workflowExecutionTimeout: '1 day',
139
- * retry: { maximumAttempts: 3 },
140
- * });
141
- *
142
- * const result = await handle.result();
143
- * ```
144
- */
145
- async startWorkflow<TWorkflowName extends keyof TContract["workflows"]>(
146
- workflowName: TWorkflowName,
147
- {
148
- args,
149
- ...temporalOptions
150
- }: TypedWorkflowStartOptions & {
151
- args: ClientInferInput<TContract["workflows"][TWorkflowName]>;
152
- },
153
- ): Promise<TypedWorkflowHandle<TContract["workflows"][TWorkflowName]>> {
154
- const definition = this.contract.workflows[workflowName as string];
155
-
156
- if (!definition) {
157
- throw new WorkflowNotFoundError(
158
- String(workflowName),
159
- Object.keys(this.contract.workflows) as string[],
160
- );
161
- }
162
-
163
- // Validate input with Standard Schema
164
- const inputResult = await definition.input["~standard"].validate(args);
165
- if (inputResult.issues) {
166
- throw new WorkflowValidationError(String(workflowName), "input", inputResult.issues);
167
- }
168
- const validatedInput = inputResult.value as ClientInferInput<
169
- TContract["workflows"][TWorkflowName]
170
- >;
171
-
172
- // Start workflow (Temporal expects args as array, so wrap single parameter)
173
- const handle = await this.client.workflow.start(workflowName as string, {
174
- ...temporalOptions,
175
- taskQueue: this.contract.taskQueue,
176
- args: [validatedInput],
177
- });
178
-
179
- return this.createTypedHandle(handle, definition) as TypedWorkflowHandle<
180
- TContract["workflows"][TWorkflowName]
181
- >;
182
- }
183
-
184
- /**
185
- * Execute a workflow (start and wait for result)
186
- *
187
- * @example
188
- * ```ts
189
- * const result = await client.executeWorkflow('processOrder', {
190
- * workflowId: 'order-123',
191
- * args: ['ORD-123', 'CUST-456', [{ productId: 'PROD-1', quantity: 2 }]],
192
- * workflowExecutionTimeout: '1 day',
193
- * retry: { maximumAttempts: 3 },
194
- * });
195
- *
196
- * console.log(result.status); // fully typed!
197
- * ```
198
- */
199
- async executeWorkflow<TWorkflowName extends keyof TContract["workflows"]>(
200
- workflowName: TWorkflowName,
201
- {
202
- args,
203
- ...temporalOptions
204
- }: TypedWorkflowStartOptions & {
205
- args: ClientInferInput<TContract["workflows"][TWorkflowName]>;
206
- },
207
- ): Promise<ClientInferOutput<TContract["workflows"][TWorkflowName]>> {
208
- const definition = this.contract.workflows[workflowName as string];
209
-
210
- if (!definition) {
211
- throw new WorkflowNotFoundError(
212
- String(workflowName),
213
- Object.keys(this.contract.workflows) as string[],
214
- );
215
- }
216
-
217
- // Validate input with Standard Schema
218
- const inputResult = await definition.input["~standard"].validate(args);
219
- if (inputResult.issues) {
220
- throw new WorkflowValidationError(String(workflowName), "input", inputResult.issues);
221
- }
222
- const validatedInput = inputResult.value as ClientInferInput<
223
- TContract["workflows"][TWorkflowName]
224
- >;
225
-
226
- // Execute workflow (Temporal expects args as array, so wrap single parameter)
227
- const result = await this.client.workflow.execute(workflowName as string, {
228
- ...temporalOptions,
229
- taskQueue: this.contract.taskQueue,
230
- args: [validatedInput],
231
- });
232
-
233
- // Validate output with Standard Schema
234
- const outputResult = await definition.output["~standard"].validate(result);
235
- if (outputResult.issues) {
236
- throw new WorkflowValidationError(String(workflowName), "output", outputResult.issues);
237
- }
238
-
239
- return outputResult.value as ClientInferOutput<TContract["workflows"][TWorkflowName]>;
240
- }
241
-
242
- /**
243
- * Get a handle to an existing workflow
244
- *
245
- * @example
246
- * ```ts
247
- * const handle = await client.getHandle('processOrder', 'order-123');
248
- * const result = await handle.result();
249
- * ```
250
- */
251
- async getHandle<TWorkflowName extends keyof TContract["workflows"]>(
252
- workflowName: TWorkflowName,
253
- workflowId: string,
254
- ): Promise<TypedWorkflowHandle<TContract["workflows"][TWorkflowName]>> {
255
- const definition = this.contract.workflows[workflowName as string];
256
-
257
- if (!definition) {
258
- throw new WorkflowNotFoundError(
259
- String(workflowName),
260
- Object.keys(this.contract.workflows) as string[],
261
- );
262
- }
263
-
264
- const handle = this.client.workflow.getHandle(workflowId);
265
- return this.createTypedHandle(handle, definition) as TypedWorkflowHandle<
266
- TContract["workflows"][TWorkflowName]
267
- >;
268
- }
269
-
270
- private createTypedHandle<TWorkflow extends WorkflowDefinition>(
271
- handle: WorkflowHandle,
272
- definition: TWorkflow,
273
- ): TypedWorkflowHandle<TWorkflow> {
274
- // Create typed queries proxy
275
- const queries = {} as ClientInferWorkflowQueries<TWorkflow>;
276
- for (const [queryName, queryDef] of Object.entries(definition.queries ?? {}) as Array<
277
- [string, QueryDefinition]
278
- >) {
279
- (queries as Record<string, unknown>)[queryName] = async (
280
- args: ClientInferInput<typeof queryDef>,
281
- ) => {
282
- const inputResult = await queryDef.input["~standard"].validate(args);
283
- if (inputResult.issues) {
284
- throw new QueryValidationError(queryName, "input", inputResult.issues);
285
- }
286
-
287
- const result = await handle.query(queryName as string, inputResult.value);
288
-
289
- const outputResult = await queryDef.output["~standard"].validate(result);
290
- if (outputResult.issues) {
291
- throw new QueryValidationError(queryName, "output", outputResult.issues);
292
- }
293
-
294
- return outputResult.value;
295
- };
296
- }
297
-
298
- // Create typed signals proxy
299
- const signals = {} as ClientInferWorkflowSignals<TWorkflow>;
300
- for (const [signalName, signalDef] of Object.entries(definition.signals ?? {}) as Array<
301
- [string, SignalDefinition]
302
- >) {
303
- (signals as Record<string, unknown>)[signalName] = async (
304
- args: ClientInferInput<typeof signalDef>,
305
- ) => {
306
- const inputResult = await signalDef.input["~standard"].validate(args);
307
- if (inputResult.issues) {
308
- throw new SignalValidationError(signalName, inputResult.issues);
309
- }
310
- await handle.signal(signalName as string, inputResult.value);
311
- };
312
- }
313
-
314
- // Create typed updates proxy
315
- const updates = {} as ClientInferWorkflowUpdates<TWorkflow>;
316
- for (const [updateName, updateDef] of Object.entries(definition.updates ?? {}) as Array<
317
- [string, UpdateDefinition]
318
- >) {
319
- (updates as Record<string, unknown>)[updateName] = async (
320
- args: ClientInferInput<typeof updateDef>,
321
- ) => {
322
- const inputResult = await updateDef.input["~standard"].validate(args);
323
- if (inputResult.issues) {
324
- throw new UpdateValidationError(updateName, "input", inputResult.issues);
325
- }
326
-
327
- const result = await handle.executeUpdate(updateName as string, {
328
- args: [inputResult.value],
329
- });
330
-
331
- const outputResult = await updateDef.output["~standard"].validate(result);
332
- if (outputResult.issues) {
333
- throw new UpdateValidationError(updateName, "output", outputResult.issues);
334
- }
335
-
336
- return outputResult.value;
337
- };
338
- }
339
-
340
- const typedHandle: TypedWorkflowHandle<TWorkflow> = {
341
- workflowId: handle.workflowId,
342
- queries,
343
- signals,
344
- updates,
345
- result: async () => {
346
- const result = await handle.result();
347
- // Validate output with Standard Schema
348
- const outputResult = await definition.output["~standard"].validate(result);
349
- if (outputResult.issues) {
350
- throw new WorkflowValidationError(handle.workflowId, "output", outputResult.issues);
351
- }
352
- return outputResult.value as ClientInferOutput<TWorkflow>;
353
- },
354
- terminate: async (reason?: string) => {
355
- await handle.terminate(reason);
356
- },
357
- cancel: async () => {
358
- await handle.cancel();
359
- },
360
- describe: () => handle.describe(),
361
- fetchHistory: () => handle.fetchHistory(),
362
- };
363
-
364
- return typedHandle;
365
- }
366
- }
package/src/errors.ts DELETED
@@ -1,91 +0,0 @@
1
- import type { StandardSchemaV1 } from "@standard-schema/spec";
2
-
3
- /**
4
- * Base error class for typed client errors
5
- */
6
- export class TypedClientError extends Error {
7
- constructor(message: string) {
8
- super(message);
9
- this.name = "TypedClientError";
10
- // Maintains proper stack trace for where our error was thrown (only available on V8)
11
- if (Error.captureStackTrace) {
12
- Error.captureStackTrace(this, this.constructor);
13
- }
14
- }
15
- }
16
-
17
- /**
18
- * Error thrown when a workflow is not found in the contract
19
- */
20
- export class WorkflowNotFoundError extends TypedClientError {
21
- constructor(
22
- public readonly workflowName: string,
23
- public readonly availableWorkflows: readonly string[] = [],
24
- ) {
25
- const message =
26
- availableWorkflows.length > 0
27
- ? `Workflow "${workflowName}" not found in contract. Available workflows: ${availableWorkflows.join(", ")}`
28
- : `Workflow "${workflowName}" not found in contract`;
29
- super(message);
30
- this.name = "WorkflowNotFoundError";
31
- }
32
- }
33
-
34
- /**
35
- * Error thrown when workflow input or output validation fails
36
- */
37
- export class WorkflowValidationError extends TypedClientError {
38
- constructor(
39
- public readonly workflowName: string,
40
- public readonly phase: "input" | "output",
41
- public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,
42
- ) {
43
- const message = issues.map((issue) => issue.message).join("; ");
44
- super(`Validation failed for workflow "${workflowName}" ${phase}: ${message}`);
45
- this.name = "WorkflowValidationError";
46
- }
47
- }
48
-
49
- /**
50
- * Error thrown when query input or output validation fails
51
- */
52
- export class QueryValidationError extends TypedClientError {
53
- constructor(
54
- public readonly queryName: string,
55
- public readonly phase: "input" | "output",
56
- public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,
57
- ) {
58
- const message = issues.map((issue) => issue.message).join("; ");
59
- super(`Validation failed for query "${queryName}" ${phase}: ${message}`);
60
- this.name = "QueryValidationError";
61
- }
62
- }
63
-
64
- /**
65
- * Error thrown when signal input validation fails
66
- */
67
- export class SignalValidationError extends TypedClientError {
68
- constructor(
69
- public readonly signalName: string,
70
- public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,
71
- ) {
72
- const message = issues.map((issue) => issue.message).join("; ");
73
- super(`Validation failed for signal "${signalName}" input: ${message}`);
74
- this.name = "SignalValidationError";
75
- }
76
- }
77
-
78
- /**
79
- * Error thrown when update input or output validation fails
80
- */
81
- export class UpdateValidationError extends TypedClientError {
82
- constructor(
83
- public readonly updateName: string,
84
- public readonly phase: "input" | "output",
85
- public readonly issues: ReadonlyArray<StandardSchemaV1.Issue>,
86
- ) {
87
- const message = issues.map((issue) => issue.message).join("; ");
88
- super(`Validation failed for update "${updateName}" ${phase}: ${message}`);
89
- this.name = "UpdateValidationError";
90
- }
91
- }
package/src/index.ts DELETED
@@ -1,9 +0,0 @@
1
- export { TypedClient, type TypedWorkflowHandle, type TypedWorkflowStartOptions } from "./client.js";
2
- export {
3
- TypedClientError,
4
- WorkflowNotFoundError,
5
- WorkflowValidationError,
6
- QueryValidationError,
7
- SignalValidationError,
8
- UpdateValidationError,
9
- } from "./errors.js";
package/tsconfig.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "extends": "@temporal-contract/tsconfig/base.json",
3
- "compilerOptions": {
4
- "outDir": "./dist",
5
- "rootDir": "./src",
6
- },
7
- "include": ["src/**/*"],
8
- "exclude": ["node_modules", "dist"],
9
- }
package/vitest.config.ts DELETED
@@ -1,12 +0,0 @@
1
- import { defineConfig } from "vitest/config";
2
-
3
- export default defineConfig({
4
- test: {
5
- reporters: ["default"],
6
- coverage: {
7
- provider: "v8",
8
- reporter: ["text", "json", "json-summary", "html"],
9
- include: ["src/**"],
10
- },
11
- },
12
- });