@temporal-contract/worker 0.2.0 → 2.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.
@@ -0,0 +1,453 @@
1
+ let _temporalio_workflow = require("@temporalio/workflow");
2
+ //#region src/format.ts
3
+ /**
4
+ * Pattern for string keys safe to render with dot notation. A "safe" key is a
5
+ * JavaScript identifier (letters/digits/underscore/$, not starting with a
6
+ * digit). Anything else — keys containing dots, spaces, leading digits, the
7
+ * empty string, the literal string `"0"` etc. — gets bracket-quoted so the
8
+ * path is unambiguous. Reserved words are accepted: we are formatting a
9
+ * diagnostic, not generating runnable code.
10
+ */
11
+ const SAFE_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
12
+ /**
13
+ * Render a Standard Schema {@link StandardSchemaV1.Issue} into a human-readable
14
+ * string that includes the failing field's path.
15
+ */
16
+ function formatIssue(issue) {
17
+ if (issue.path === void 0 || issue.path.length === 0) return issue.message;
18
+ let path = "";
19
+ for (let i = 0; i < issue.path.length; i++) {
20
+ const segment = issue.path[i];
21
+ const key = segment !== null && typeof segment === "object" && "key" in segment ? segment.key : segment;
22
+ if (typeof key === "number") path += `[${key}]`;
23
+ else if (typeof key === "string" && SAFE_IDENTIFIER.test(key)) path += i === 0 ? key : `.${key}`;
24
+ else if (typeof key === "string") path += `[${JSON.stringify(key)}]`;
25
+ else path += `[${String(key)}]`;
26
+ }
27
+ return `at ${path}: ${issue.message}`;
28
+ }
29
+ /**
30
+ * Join a list of validation issues into a single message, with each issue
31
+ * rendered via {@link formatIssue} so field paths surface in the error text.
32
+ */
33
+ function summarizeIssues(issues) {
34
+ return issues.map(formatIssue).join("; ");
35
+ }
36
+ /**
37
+ * Build the message attached to a `ChildWorkflowError` for input/output
38
+ * validation failures. Centralized so the worker and any future call sites
39
+ * format identically.
40
+ */
41
+ function formatChildWorkflowValidationMessage(workflowName, direction, issues) {
42
+ return `Child workflow "${workflowName}" ${direction} validation failed: ${summarizeIssues(issues)}`;
43
+ }
44
+ //#endregion
45
+ //#region src/errors.ts
46
+ /**
47
+ * Base error class for worker errors
48
+ */
49
+ var WorkerError = class extends Error {
50
+ constructor(message, cause) {
51
+ super(message, { cause });
52
+ this.name = "WorkerError";
53
+ if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
54
+ }
55
+ };
56
+ /**
57
+ * Error thrown when an activity definition is not found in the contract
58
+ */
59
+ var ActivityDefinitionNotFoundError = class extends WorkerError {
60
+ constructor(activityName, availableDefinitions = []) {
61
+ const available = availableDefinitions.length > 0 ? availableDefinitions.join(", ") : "none";
62
+ super(`Activity definition not found for: "${activityName}". Available activities: ${available}`);
63
+ this.activityName = activityName;
64
+ this.availableDefinitions = availableDefinitions;
65
+ this.name = "ActivityDefinitionNotFoundError";
66
+ }
67
+ };
68
+ /**
69
+ * Error thrown when activity input validation fails
70
+ */
71
+ var ActivityInputValidationError = class extends WorkerError {
72
+ constructor(activityName, issues) {
73
+ const message = summarizeIssues(issues);
74
+ super(`Activity "${activityName}" input validation failed: ${message}`);
75
+ this.activityName = activityName;
76
+ this.issues = issues;
77
+ this.name = "ActivityInputValidationError";
78
+ }
79
+ };
80
+ /**
81
+ * Error thrown when activity output validation fails
82
+ */
83
+ var ActivityOutputValidationError = class extends WorkerError {
84
+ constructor(activityName, issues) {
85
+ const message = summarizeIssues(issues);
86
+ super(`Activity "${activityName}" output validation failed: ${message}`);
87
+ this.activityName = activityName;
88
+ this.issues = issues;
89
+ this.name = "ActivityOutputValidationError";
90
+ }
91
+ };
92
+ /**
93
+ * Error thrown when workflow input validation fails
94
+ */
95
+ var WorkflowInputValidationError = class extends WorkerError {
96
+ constructor(workflowName, issues) {
97
+ const message = summarizeIssues(issues);
98
+ super(`Workflow "${workflowName}" input validation failed: ${message}`);
99
+ this.workflowName = workflowName;
100
+ this.issues = issues;
101
+ this.name = "WorkflowInputValidationError";
102
+ }
103
+ };
104
+ /**
105
+ * Error thrown when workflow output validation fails
106
+ */
107
+ var WorkflowOutputValidationError = class extends WorkerError {
108
+ constructor(workflowName, issues) {
109
+ const message = summarizeIssues(issues);
110
+ super(`Workflow "${workflowName}" output validation failed: ${message}`);
111
+ this.workflowName = workflowName;
112
+ this.issues = issues;
113
+ this.name = "WorkflowOutputValidationError";
114
+ }
115
+ };
116
+ /**
117
+ * Error thrown when signal input validation fails
118
+ */
119
+ var SignalInputValidationError = class extends WorkerError {
120
+ constructor(signalName, issues) {
121
+ const message = summarizeIssues(issues);
122
+ super(`Signal "${signalName}" input validation failed: ${message}`);
123
+ this.signalName = signalName;
124
+ this.issues = issues;
125
+ this.name = "SignalInputValidationError";
126
+ }
127
+ };
128
+ /**
129
+ * Error thrown when query input validation fails
130
+ */
131
+ var QueryInputValidationError = class extends WorkerError {
132
+ constructor(queryName, issues) {
133
+ const message = summarizeIssues(issues);
134
+ super(`Query "${queryName}" input validation failed: ${message}`);
135
+ this.queryName = queryName;
136
+ this.issues = issues;
137
+ this.name = "QueryInputValidationError";
138
+ }
139
+ };
140
+ /**
141
+ * Error thrown when query output validation fails
142
+ */
143
+ var QueryOutputValidationError = class extends WorkerError {
144
+ constructor(queryName, issues) {
145
+ const message = summarizeIssues(issues);
146
+ super(`Query "${queryName}" output validation failed: ${message}`);
147
+ this.queryName = queryName;
148
+ this.issues = issues;
149
+ this.name = "QueryOutputValidationError";
150
+ }
151
+ };
152
+ /**
153
+ * Error thrown when update input validation fails
154
+ */
155
+ var UpdateInputValidationError = class extends WorkerError {
156
+ constructor(updateName, issues) {
157
+ const message = summarizeIssues(issues);
158
+ super(`Update "${updateName}" input validation failed: ${message}`);
159
+ this.updateName = updateName;
160
+ this.issues = issues;
161
+ this.name = "UpdateInputValidationError";
162
+ }
163
+ };
164
+ /**
165
+ * Error thrown when update output validation fails
166
+ */
167
+ var UpdateOutputValidationError = class extends WorkerError {
168
+ constructor(updateName, issues) {
169
+ const message = summarizeIssues(issues);
170
+ super(`Update "${updateName}" output validation failed: ${message}`);
171
+ this.updateName = updateName;
172
+ this.issues = issues;
173
+ this.name = "UpdateOutputValidationError";
174
+ }
175
+ };
176
+ /**
177
+ * Error thrown when a child workflow is not found in the contract
178
+ */
179
+ var ChildWorkflowNotFoundError = class extends WorkerError {
180
+ constructor(workflowName, availableWorkflows = []) {
181
+ const available = availableWorkflows.length > 0 ? availableWorkflows.join(", ") : "none";
182
+ super(`Child workflow not found: "${workflowName}". Available workflows: ${available}`);
183
+ this.workflowName = workflowName;
184
+ this.availableWorkflows = availableWorkflows;
185
+ this.name = "ChildWorkflowNotFoundError";
186
+ }
187
+ };
188
+ /**
189
+ * Generic error for child workflow operations
190
+ */
191
+ var ChildWorkflowError = class extends WorkerError {
192
+ constructor(message, cause) {
193
+ super(message, cause);
194
+ this.name = "ChildWorkflowError";
195
+ }
196
+ };
197
+ /**
198
+ * Error surfaced in the `err(...)` branch of a `ResultAsync` when a typed
199
+ * cancellation scope is cancelled via Temporal's cancellation propagation.
200
+ * Returned by both `context.cancellableScope` (when the workflow or an
201
+ * ancestor scope cancels) and `context.nonCancellableScope` (when
202
+ * cancellation is raised from inside the scope). Distinct from arbitrary
203
+ * thrown errors so call sites can branch on cancellation explicitly while
204
+ * still surfacing non-cancellation errors as ResultAsync rejections.
205
+ */
206
+ var WorkflowCancelledError = class extends WorkerError {
207
+ constructor(cause) {
208
+ super("Workflow cancellation scope was cancelled", cause);
209
+ this.name = "WorkflowCancelledError";
210
+ }
211
+ };
212
+ //#endregion
213
+ //#region src/internal.ts
214
+ /**
215
+ * Internal helpers shared across the worker package's entry points.
216
+ *
217
+ * Not part of the public API — this module is not listed in the package's
218
+ * `exports` map, so consumers can't import from `@temporal-contract/worker/internal`.
219
+ * In-package tests import it directly via relative path.
220
+ */
221
+ /**
222
+ * Extract the single payload from a Temporal handler's `...args` array.
223
+ *
224
+ * Temporal invokes handlers with whatever was passed via `args: [...]` at the
225
+ * call site. The typed-contract layer always sends `args: [validatedInput]`,
226
+ * so the common case is a one-element array containing the wrapped input.
227
+ *
228
+ * If a non-typed-contract caller passes multiple positional arguments
229
+ * (`args: [a, b, c]`), we surface the whole array as the input — the schema
230
+ * will then reject it unless the contract specifically modeled a tuple.
231
+ */
232
+ function extractHandlerInput(args) {
233
+ return args.length === 1 ? args[0] : args;
234
+ }
235
+ /**
236
+ * Build the raw `Record<name, fn>` proxy of activities for a workflow,
237
+ * applying per-activity `ActivityOptions` overrides where requested.
238
+ *
239
+ * **Fast path (no overrides):** a single `proxyActivities(defaultOptions)`
240
+ * call is made and returned directly. The proxy synthesizes a function for
241
+ * any property access by name, so downstream code that looks up
242
+ * `proxy[activityName]` works identically to before.
243
+ *
244
+ * **Override path:** one extra `proxyActivities(merged)` call is made *only*
245
+ * for each activity that has an override. Activities without an entry keep
246
+ * using the single default proxy. The result is a `Proxy` that returns the
247
+ * override-bound function for named keys and falls back to the default proxy
248
+ * for everything else — so the per-execution overhead scales with the number
249
+ * of overrides, not the number of activities.
250
+ *
251
+ * Per-override merge is shallow: the override's properties replace the
252
+ * default's, including the entire nested `retry` block. This matches
253
+ * Temporal's "one ActivityOptions per `proxyActivities` call" semantics.
254
+ */
255
+ function buildRawActivitiesProxy(workflowActivities, contractActivities, defaultOptions, overrides) {
256
+ const defaultProxy = (0, _temporalio_workflow.proxyActivities)(defaultOptions);
257
+ const overrideEntries = overrides ? Object.entries(overrides).filter((entry) => entry[1] !== void 0) : [];
258
+ if (overrideEntries.length === 0) return defaultProxy;
259
+ const declared = new Set([...Object.keys(workflowActivities ?? {}), ...Object.keys(contractActivities ?? {})]);
260
+ for (const [name] of overrideEntries) if (!declared.has(name)) throw new Error(`activityOptionsByName entry "${name}" does not match any declared activity. Available: ${[...declared].join(", ") || "none"}.`);
261
+ const overriddenFns = {};
262
+ for (const [name, override] of overrideEntries) {
263
+ const fn = (0, _temporalio_workflow.proxyActivities)({
264
+ ...defaultOptions,
265
+ ...override
266
+ })[name];
267
+ if (fn !== void 0) overriddenFns[name] = fn;
268
+ }
269
+ return new Proxy(overriddenFns, { get(target, prop) {
270
+ if (typeof prop !== "string") return void 0;
271
+ return target[prop] ?? defaultProxy[prop];
272
+ } });
273
+ }
274
+ /**
275
+ * Build the typed `continueAsNew` function bound to the running workflow's
276
+ * contract. Two overloads — same-workflow and cross-contract — share one
277
+ * implementation; the public type signature lives on `WorkflowContext` so
278
+ * call sites are type-safe.
279
+ *
280
+ * Validation runs *before* Temporal's `makeContinueAsNewFunc(...)` is invoked.
281
+ * On failure, throws a `WorkflowInputValidationError` (matching the behaviour
282
+ * of `declareWorkflow`'s incoming-input validation), which surfaces back to
283
+ * Temporal as a workflow failure rather than silently proceeding with an
284
+ * invalid run.
285
+ *
286
+ * Temporal's `continueAsNew` never returns — it throws a `ContinueAsNew`
287
+ * exception that the runtime intercepts. The returned function preserves
288
+ * `Promise<never>` to encode that.
289
+ *
290
+ * @internal
291
+ */
292
+ function createContinueAsNew(currentContract, currentWorkflowName) {
293
+ return async function continueAsNew(arg1, arg2, arg3, arg4) {
294
+ const isCrossContract = looksLikeCrossContractCall(arg1, arg2);
295
+ let targetContract;
296
+ let targetName;
297
+ let rawArgs;
298
+ let options;
299
+ if (isCrossContract) {
300
+ targetContract = arg1;
301
+ targetName = arg2;
302
+ rawArgs = arg3;
303
+ options = arg4;
304
+ } else {
305
+ targetContract = currentContract;
306
+ targetName = String(currentWorkflowName);
307
+ rawArgs = arg1;
308
+ options = arg2;
309
+ }
310
+ const targetDef = targetContract.workflows[targetName];
311
+ if (!targetDef) throw new WorkflowInputValidationError(targetName, [{ message: `continueAsNew target workflow "${targetName}" is not declared on the supplied contract.` }]);
312
+ const inputResult = await targetDef.input["~standard"].validate(rawArgs);
313
+ if (inputResult.issues) throw new WorkflowInputValidationError(targetName, inputResult.issues);
314
+ await (0, _temporalio_workflow.makeContinueAsNewFunc)({
315
+ workflowType: targetName,
316
+ taskQueue: targetContract.taskQueue,
317
+ ...options
318
+ })(inputResult.value);
319
+ };
320
+ }
321
+ /**
322
+ * Structural check: does `(arg1, arg2)` look like the
323
+ * `(contract, workflowName, ...)` cross-contract overload of `continueAsNew`?
324
+ *
325
+ * Returns `true` only when:
326
+ * 1. `arg1` is a non-null object with a string `taskQueue` and a non-null
327
+ * object `workflows` (handles `workflows: null`, where
328
+ * `typeof null === "object"`).
329
+ * 2. `arg2` is a string.
330
+ *
331
+ * Both halves matter. A same-workflow input that happens to contain
332
+ * `taskQueue` and `workflows` keys would otherwise be misclassified — but
333
+ * none of the same-workflow signatures (`continueAsNew(args)`,
334
+ * `continueAsNew(args, options)`) accept a string as `arg2`, so the
335
+ * second check makes the false-positive surface vanishingly small.
336
+ *
337
+ * We deliberately do *not* check that `arg1.workflows[arg2]` is a valid
338
+ * workflow definition. If it isn't, the dispatcher falls through to the
339
+ * `targetContract.workflows[targetName]` lookup which throws a clear
340
+ * "target workflow X is not declared" error — better than silently
341
+ * misrouting a typo back to the current workflow.
342
+ */
343
+ function looksLikeCrossContractCall(arg1, arg2) {
344
+ if (typeof arg1 !== "object" || arg1 === null) return false;
345
+ if (typeof arg2 !== "string") return false;
346
+ const candidate = arg1;
347
+ if (typeof candidate["taskQueue"] !== "string") return false;
348
+ const workflows = candidate["workflows"];
349
+ return typeof workflows === "object" && workflows !== null;
350
+ }
351
+ //#endregion
352
+ Object.defineProperty(exports, "ActivityDefinitionNotFoundError", {
353
+ enumerable: true,
354
+ get: function() {
355
+ return ActivityDefinitionNotFoundError;
356
+ }
357
+ });
358
+ Object.defineProperty(exports, "ActivityInputValidationError", {
359
+ enumerable: true,
360
+ get: function() {
361
+ return ActivityInputValidationError;
362
+ }
363
+ });
364
+ Object.defineProperty(exports, "ActivityOutputValidationError", {
365
+ enumerable: true,
366
+ get: function() {
367
+ return ActivityOutputValidationError;
368
+ }
369
+ });
370
+ Object.defineProperty(exports, "ChildWorkflowError", {
371
+ enumerable: true,
372
+ get: function() {
373
+ return ChildWorkflowError;
374
+ }
375
+ });
376
+ Object.defineProperty(exports, "ChildWorkflowNotFoundError", {
377
+ enumerable: true,
378
+ get: function() {
379
+ return ChildWorkflowNotFoundError;
380
+ }
381
+ });
382
+ Object.defineProperty(exports, "QueryInputValidationError", {
383
+ enumerable: true,
384
+ get: function() {
385
+ return QueryInputValidationError;
386
+ }
387
+ });
388
+ Object.defineProperty(exports, "QueryOutputValidationError", {
389
+ enumerable: true,
390
+ get: function() {
391
+ return QueryOutputValidationError;
392
+ }
393
+ });
394
+ Object.defineProperty(exports, "SignalInputValidationError", {
395
+ enumerable: true,
396
+ get: function() {
397
+ return SignalInputValidationError;
398
+ }
399
+ });
400
+ Object.defineProperty(exports, "UpdateInputValidationError", {
401
+ enumerable: true,
402
+ get: function() {
403
+ return UpdateInputValidationError;
404
+ }
405
+ });
406
+ Object.defineProperty(exports, "UpdateOutputValidationError", {
407
+ enumerable: true,
408
+ get: function() {
409
+ return UpdateOutputValidationError;
410
+ }
411
+ });
412
+ Object.defineProperty(exports, "WorkflowCancelledError", {
413
+ enumerable: true,
414
+ get: function() {
415
+ return WorkflowCancelledError;
416
+ }
417
+ });
418
+ Object.defineProperty(exports, "WorkflowInputValidationError", {
419
+ enumerable: true,
420
+ get: function() {
421
+ return WorkflowInputValidationError;
422
+ }
423
+ });
424
+ Object.defineProperty(exports, "WorkflowOutputValidationError", {
425
+ enumerable: true,
426
+ get: function() {
427
+ return WorkflowOutputValidationError;
428
+ }
429
+ });
430
+ Object.defineProperty(exports, "buildRawActivitiesProxy", {
431
+ enumerable: true,
432
+ get: function() {
433
+ return buildRawActivitiesProxy;
434
+ }
435
+ });
436
+ Object.defineProperty(exports, "createContinueAsNew", {
437
+ enumerable: true,
438
+ get: function() {
439
+ return createContinueAsNew;
440
+ }
441
+ });
442
+ Object.defineProperty(exports, "extractHandlerInput", {
443
+ enumerable: true,
444
+ get: function() {
445
+ return extractHandlerInput;
446
+ }
447
+ });
448
+ Object.defineProperty(exports, "formatChildWorkflowValidationMessage", {
449
+ enumerable: true,
450
+ get: function() {
451
+ return formatChildWorkflowValidationMessage;
452
+ }
453
+ });
package/dist/worker.cjs CHANGED
@@ -1,7 +1,6 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _temporalio_worker = require("@temporalio/worker");
3
3
  let node_url = require("node:url");
4
-
5
4
  //#region src/worker.ts
6
5
  /**
7
6
  * Create a typed Temporal worker with contract-based configuration
@@ -65,7 +64,6 @@ async function createWorker(options) {
65
64
  function workflowsPathFromURL(baseURL, relativePath) {
66
65
  return (0, node_url.fileURLToPath)(new URL(relativePath, baseURL));
67
66
  }
68
-
69
67
  //#endregion
70
68
  exports.createWorker = createWorker;
71
- exports.workflowsPathFromURL = workflowsPathFromURL;
69
+ exports.workflowsPathFromURL = workflowsPathFromURL;
package/dist/worker.mjs CHANGED
@@ -1,6 +1,5 @@
1
1
  import { Worker } from "@temporalio/worker";
2
2
  import { fileURLToPath } from "node:url";
3
-
4
3
  //#region src/worker.ts
5
4
  /**
6
5
  * Create a typed Temporal worker with contract-based configuration
@@ -64,7 +63,7 @@ async function createWorker(options) {
64
63
  function workflowsPathFromURL(baseURL, relativePath) {
65
64
  return fileURLToPath(new URL(relativePath, baseURL));
66
65
  }
67
-
68
66
  //#endregion
69
67
  export { createWorker, workflowsPathFromURL };
68
+
70
69
  //# sourceMappingURL=worker.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"worker.mjs","names":[],"sources":["../src/worker.ts"],"sourcesContent":["// Entry point for worker creation utilities\nimport { ContractDefinition } from \"@temporal-contract/contract\";\nimport { Worker, WorkerOptions } from \"@temporalio/worker\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ActivitiesHandler } from \"./activity.js\";\n\n/**\n * Options for creating a Temporal worker\n */\nexport type CreateWorkerOptions<TContract extends ContractDefinition> = Omit<\n WorkerOptions,\n \"activities\" | \"taskQueue\"\n> & {\n /**\n * The contract definition for this worker\n */\n contract: TContract;\n\n /**\n * Activities handler for this worker\n */\n activities: ActivitiesHandler<TContract>;\n};\n\n/**\n * Create a typed Temporal worker with contract-based configuration\n *\n * This helper simplifies worker creation by:\n * - Using the contract's task queue automatically\n * - Providing type-safe configuration\n *\n * @example\n * ```ts\n * import { NativeConnection } from '@temporalio/worker';\n * import { createWorker } from '@temporal-contract/worker/worker';\n * import { activities } from './activities';\n * import myContract from './contract';\n *\n * const connection = await NativeConnection.connect({\n * address: 'localhost:7233',\n * });\n *\n * const worker = await createWorker({\n * contract: myContract,\n * connection,\n * workflowsPath: require.resolve('./workflows'),\n * activities,\n * });\n *\n * await worker.run();\n * ```\n */\nexport async function createWorker<TContract extends ContractDefinition>(\n options: CreateWorkerOptions<TContract>,\n): Promise<Worker> {\n const { contract, activities, ...workerOptions } = options;\n\n // Create the worker with contract's task queue\n return await Worker.create({\n ...workerOptions,\n activities,\n taskQueue: contract.taskQueue,\n });\n}\n\n/**\n * Helper to resolve a workflow file path relative to the current module's URL.\n *\n * Useful when using ES modules (`import.meta.url`) to locate workflow files.\n * The `relativePath` should include the file extension explicitly (e.g. `./workflows.js`)\n * to ensure the resolved path is unambiguous in both source and built contexts.\n *\n * @param baseURL - The base URL to resolve from, typically `import.meta.url`\n * @param relativePath - Relative path to the workflows file, **including extension**\n *\n * @example\n * ```ts\n * import { workflowsPathFromURL } from '@temporal-contract/worker/worker';\n *\n * const worker = await createWorker({\n * contract: myContract,\n * connection,\n * // Include the extension explicitly to work in both source (.ts) and build (.js) contexts\n * workflowsPath: workflowsPathFromURL(import.meta.url, './workflows.js'),\n * activities,\n * });\n * ```\n */\nexport function workflowsPathFromURL(baseURL: string, relativePath: string): string {\n return fileURLToPath(new URL(relativePath, baseURL));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,eAAsB,aACpB,SACiB;CACjB,MAAM,EAAE,UAAU,YAAY,GAAG,kBAAkB;AAGnD,QAAO,MAAM,OAAO,OAAO;EACzB,GAAG;EACH;EACA,WAAW,SAAS;EACrB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;AA0BJ,SAAgB,qBAAqB,SAAiB,cAA8B;AAClF,QAAO,cAAc,IAAI,IAAI,cAAc,QAAQ,CAAC"}
1
+ {"version":3,"file":"worker.mjs","names":[],"sources":["../src/worker.ts"],"sourcesContent":["// Entry point for worker creation utilities\nimport { ContractDefinition } from \"@temporal-contract/contract\";\nimport { Worker, WorkerOptions } from \"@temporalio/worker\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ActivitiesHandler } from \"./activity.js\";\n\n/**\n * Options for creating a Temporal worker\n */\nexport type CreateWorkerOptions<TContract extends ContractDefinition> = Omit<\n WorkerOptions,\n \"activities\" | \"taskQueue\"\n> & {\n /**\n * The contract definition for this worker\n */\n contract: TContract;\n\n /**\n * Activities handler for this worker\n */\n activities: ActivitiesHandler<TContract>;\n};\n\n/**\n * Create a typed Temporal worker with contract-based configuration\n *\n * This helper simplifies worker creation by:\n * - Using the contract's task queue automatically\n * - Providing type-safe configuration\n *\n * @example\n * ```ts\n * import { NativeConnection } from '@temporalio/worker';\n * import { createWorker } from '@temporal-contract/worker/worker';\n * import { activities } from './activities';\n * import myContract from './contract';\n *\n * const connection = await NativeConnection.connect({\n * address: 'localhost:7233',\n * });\n *\n * const worker = await createWorker({\n * contract: myContract,\n * connection,\n * workflowsPath: require.resolve('./workflows'),\n * activities,\n * });\n *\n * await worker.run();\n * ```\n */\nexport async function createWorker<TContract extends ContractDefinition>(\n options: CreateWorkerOptions<TContract>,\n): Promise<Worker> {\n const { contract, activities, ...workerOptions } = options;\n\n // Create the worker with contract's task queue\n return await Worker.create({\n ...workerOptions,\n activities,\n taskQueue: contract.taskQueue,\n });\n}\n\n/**\n * Helper to resolve a workflow file path relative to the current module's URL.\n *\n * Useful when using ES modules (`import.meta.url`) to locate workflow files.\n * The `relativePath` should include the file extension explicitly (e.g. `./workflows.js`)\n * to ensure the resolved path is unambiguous in both source and built contexts.\n *\n * @param baseURL - The base URL to resolve from, typically `import.meta.url`\n * @param relativePath - Relative path to the workflows file, **including extension**\n *\n * @example\n * ```ts\n * import { workflowsPathFromURL } from '@temporal-contract/worker/worker';\n *\n * const worker = await createWorker({\n * contract: myContract,\n * connection,\n * // Include the extension explicitly to work in both source (.ts) and build (.js) contexts\n * workflowsPath: workflowsPathFromURL(import.meta.url, './workflows.js'),\n * activities,\n * });\n * ```\n */\nexport function workflowsPathFromURL(baseURL: string, relativePath: string): string {\n return fileURLToPath(new URL(relativePath, baseURL));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,eAAsB,aACpB,SACiB;CACjB,MAAM,EAAE,UAAU,YAAY,GAAG,kBAAkB;AAGnD,QAAO,MAAM,OAAO,OAAO;EACzB,GAAG;EACH;EACA,WAAW,SAAS;EACrB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;AA0BJ,SAAgB,qBAAqB,SAAiB,cAA8B;AAClF,QAAO,cAAc,IAAI,IAAI,cAAc,QAAQ,CAAC"}