@trigger.dev/core 0.0.0-v3-trigger-dirs-20240423091017 → 0.0.0-v3-update-command-20240423125505

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.
Files changed (65) hide show
  1. package/dist/v3/index.d.mts +17014 -178
  2. package/dist/v3/index.d.ts +17014 -178
  3. package/dist/v3/index.js +1273 -48
  4. package/dist/v3/index.js.map +1 -1
  5. package/dist/v3/index.mjs +1261 -50
  6. package/dist/v3/index.mjs.map +1 -1
  7. package/dist/v3/otel/index.d.mts +34 -6
  8. package/dist/v3/otel/index.d.ts +34 -6
  9. package/package.json +7 -71
  10. package/dist/consoleInterceptor-pKvaiAI6.d.ts +0 -6677
  11. package/dist/consoleInterceptor-tCKb2R0l.d.mts +0 -6677
  12. package/dist/manager-KhqZOMNe.d.mts +0 -1158
  13. package/dist/manager-KhqZOMNe.d.ts +0 -1158
  14. package/dist/messages-oFuHKbi4.d.mts +0 -8696
  15. package/dist/messages-oFuHKbi4.d.ts +0 -8696
  16. package/dist/tracingSDK-XMTLzw35.d.mts +0 -35
  17. package/dist/tracingSDK-XMTLzw35.d.ts +0 -35
  18. package/dist/v3/dev/index.d.mts +0 -28
  19. package/dist/v3/dev/index.d.ts +0 -28
  20. package/dist/v3/dev/index.js +0 -93
  21. package/dist/v3/dev/index.js.map +0 -1
  22. package/dist/v3/dev/index.mjs +0 -91
  23. package/dist/v3/dev/index.mjs.map +0 -1
  24. package/dist/v3/prod/index.d.mts +0 -45
  25. package/dist/v3/prod/index.d.ts +0 -45
  26. package/dist/v3/prod/index.js +0 -205
  27. package/dist/v3/prod/index.js.map +0 -1
  28. package/dist/v3/prod/index.mjs +0 -203
  29. package/dist/v3/prod/index.mjs.map +0 -1
  30. package/dist/v3/utils/structuredLogger.d.mts +0 -31
  31. package/dist/v3/utils/structuredLogger.d.ts +0 -31
  32. package/dist/v3/utils/structuredLogger.js +0 -88
  33. package/dist/v3/utils/structuredLogger.js.map +0 -1
  34. package/dist/v3/utils/structuredLogger.mjs +0 -86
  35. package/dist/v3/utils/structuredLogger.mjs.map +0 -1
  36. package/dist/v3/workers/index.d.mts +0 -49
  37. package/dist/v3/workers/index.d.ts +0 -49
  38. package/dist/v3/workers/index.js +0 -2056
  39. package/dist/v3/workers/index.js.map +0 -1
  40. package/dist/v3/workers/index.mjs +0 -2051
  41. package/dist/v3/workers/index.mjs.map +0 -1
  42. package/dist/v3/zodIpc.d.mts +0 -32
  43. package/dist/v3/zodIpc.d.ts +0 -32
  44. package/dist/v3/zodIpc.js +0 -268
  45. package/dist/v3/zodIpc.js.map +0 -1
  46. package/dist/v3/zodIpc.mjs +0 -266
  47. package/dist/v3/zodIpc.mjs.map +0 -1
  48. package/dist/v3/zodMessageHandler.d.mts +0 -69
  49. package/dist/v3/zodMessageHandler.d.ts +0 -69
  50. package/dist/v3/zodMessageHandler.js +0 -168
  51. package/dist/v3/zodMessageHandler.js.map +0 -1
  52. package/dist/v3/zodMessageHandler.mjs +0 -163
  53. package/dist/v3/zodMessageHandler.mjs.map +0 -1
  54. package/dist/v3/zodNamespace.d.mts +0 -3663
  55. package/dist/v3/zodNamespace.d.ts +0 -3663
  56. package/dist/v3/zodNamespace.js +0 -356
  57. package/dist/v3/zodNamespace.js.map +0 -1
  58. package/dist/v3/zodNamespace.mjs +0 -354
  59. package/dist/v3/zodNamespace.mjs.map +0 -1
  60. package/dist/v3/zodSocket.d.mts +0 -88
  61. package/dist/v3/zodSocket.d.ts +0 -88
  62. package/dist/v3/zodSocket.js +0 -309
  63. package/dist/v3/zodSocket.js.map +0 -1
  64. package/dist/v3/zodSocket.mjs +0 -305
  65. package/dist/v3/zodSocket.mjs.map +0 -1
@@ -1,2056 +0,0 @@
1
- 'use strict';
2
-
3
- var api = require('@opentelemetry/api');
4
- require('path');
5
- var async_hooks = require('async_hooks');
6
- var zod = require('zod');
7
- var zodValidationError = require('zod-validation-error');
8
- var preciseDate = require('@google-cloud/precise-date');
9
-
10
- var __defProp = Object.defineProperty;
11
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
- var __publicField = (obj, key, value) => {
14
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
15
- return value;
16
- };
17
- var __accessCheck = (obj, member, msg) => {
18
- if (!member.has(obj))
19
- throw TypeError("Cannot " + msg);
20
- };
21
- var __privateGet = (obj, member, getter) => {
22
- __accessCheck(obj, member, "read from private field");
23
- return getter ? getter.call(obj) : member.get(obj);
24
- };
25
- var __privateAdd = (obj, member, value) => {
26
- if (member.has(obj))
27
- throw TypeError("Cannot add the same private member more than once");
28
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
29
- };
30
- var __privateMethod = (obj, member, method) => {
31
- __accessCheck(obj, member, "access private method");
32
- return method;
33
- };
34
- function parseError(error) {
35
- if (error instanceof Error) {
36
- return {
37
- type: "BUILT_IN_ERROR",
38
- name: error.name,
39
- message: error.message,
40
- stackTrace: error.stack ?? ""
41
- };
42
- }
43
- if (typeof error === "string") {
44
- return {
45
- type: "STRING_ERROR",
46
- raw: error
47
- };
48
- }
49
- try {
50
- return {
51
- type: "CUSTOM_ERROR",
52
- raw: JSON.stringify(error)
53
- };
54
- } catch (e) {
55
- return {
56
- type: "CUSTOM_ERROR",
57
- raw: String(error)
58
- };
59
- }
60
- }
61
- __name(parseError, "parseError");
62
-
63
- // src/v3/limits.ts
64
- var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
65
-
66
- // src/v3/semanticInternalAttributes.ts
67
- var SemanticInternalAttributes = {
68
- ENVIRONMENT_ID: "ctx.environment.id",
69
- ENVIRONMENT_TYPE: "ctx.environment.type",
70
- ORGANIZATION_ID: "ctx.organization.id",
71
- ORGANIZATION_SLUG: "ctx.organization.slug",
72
- ORGANIZATION_NAME: "ctx.organization.name",
73
- PROJECT_ID: "ctx.project.id",
74
- PROJECT_REF: "ctx.project.ref",
75
- PROJECT_NAME: "ctx.project.title",
76
- PROJECT_DIR: "project.dir",
77
- ATTEMPT_ID: "ctx.attempt.id",
78
- ATTEMPT_NUMBER: "ctx.attempt.number",
79
- RUN_ID: "ctx.run.id",
80
- RUN_IS_TEST: "ctx.run.isTest",
81
- BATCH_ID: "ctx.batch.id",
82
- TASK_SLUG: "ctx.task.id",
83
- TASK_PATH: "ctx.task.filePath",
84
- TASK_EXPORT_NAME: "ctx.task.exportName",
85
- QUEUE_NAME: "ctx.queue.name",
86
- QUEUE_ID: "ctx.queue.id",
87
- SPAN_PARTIAL: "$span.partial",
88
- SPAN_ID: "$span.span_id",
89
- OUTPUT: "$output",
90
- OUTPUT_TYPE: "$mime_type_output",
91
- STYLE: "$style",
92
- STYLE_ICON: "$style.icon",
93
- STYLE_VARIANT: "$style.variant",
94
- STYLE_ACCESSORY: "$style.accessory",
95
- METADATA: "$metadata",
96
- TRIGGER: "$trigger",
97
- PAYLOAD: "$payload",
98
- PAYLOAD_TYPE: "$mime_type_payload",
99
- SHOW: "$show",
100
- SHOW_ACTIONS: "$show.actions",
101
- WORKER_ID: "worker.id",
102
- WORKER_VERSION: "worker.version",
103
- CLI_VERSION: "cli.version",
104
- SDK_VERSION: "sdk.version",
105
- SDK_LANGUAGE: "sdk.language",
106
- RETRY_AT: "retry.at",
107
- RETRY_DELAY: "retry.delay",
108
- RETRY_COUNT: "retry.count",
109
- LINK_TITLE: "$link.title",
110
- IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
111
- };
112
-
113
- // src/v3/utils/flattenAttributes.ts
114
- function flattenAttributes(obj, prefix) {
115
- const result = {};
116
- if (!obj) {
117
- return result;
118
- }
119
- if (typeof obj === "string") {
120
- result[prefix || ""] = obj;
121
- return result;
122
- }
123
- if (typeof obj === "number") {
124
- result[prefix || ""] = obj;
125
- return result;
126
- }
127
- if (typeof obj === "boolean") {
128
- result[prefix || ""] = obj;
129
- return result;
130
- }
131
- for (const [key, value] of Object.entries(obj)) {
132
- const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
133
- if (Array.isArray(value)) {
134
- for (let i = 0; i < value.length; i++) {
135
- if (typeof value[i] === "object" && value[i] !== null) {
136
- Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
137
- } else {
138
- result[`${newPrefix}.[${i}]`] = value[i];
139
- }
140
- }
141
- } else if (isRecord(value)) {
142
- Object.assign(result, flattenAttributes(value, newPrefix));
143
- } else {
144
- if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
145
- result[newPrefix] = value;
146
- }
147
- }
148
- }
149
- return result;
150
- }
151
- __name(flattenAttributes, "flattenAttributes");
152
- function isRecord(value) {
153
- return value !== null && typeof value === "object" && !Array.isArray(value);
154
- }
155
- __name(isRecord, "isRecord");
156
- var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
157
- constructor() {
158
- this.storage = new async_hooks.AsyncLocalStorage();
159
- }
160
- runWith(context2, fn) {
161
- return this.storage.run(context2, fn);
162
- }
163
- getStore() {
164
- return this.storage.getStore();
165
- }
166
- };
167
- __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
168
- var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
169
-
170
- // src/v3/tasks/taskContextManager.ts
171
- var _getStore, getStore_fn;
172
- var _TaskContextManager = class _TaskContextManager {
173
- constructor() {
174
- __privateAdd(this, _getStore);
175
- __publicField(this, "_storage", new SafeAsyncLocalStorage());
176
- }
177
- get isInsideTask() {
178
- return __privateMethod(this, _getStore, getStore_fn).call(this) !== void 0;
179
- }
180
- get ctx() {
181
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
182
- return store?.ctx;
183
- }
184
- get worker() {
185
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
186
- return store?.worker;
187
- }
188
- get attributes() {
189
- if (this.ctx) {
190
- return {
191
- ...this.contextAttributes,
192
- ...this.workerAttributes
193
- };
194
- }
195
- return {};
196
- }
197
- get workerAttributes() {
198
- if (this.worker) {
199
- return {
200
- [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
201
- [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
202
- };
203
- }
204
- return {};
205
- }
206
- get contextAttributes() {
207
- if (this.ctx) {
208
- return {
209
- [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
210
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
211
- [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
212
- [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
213
- [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
214
- [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
215
- [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
216
- [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
217
- [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
218
- [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
219
- [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
220
- [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
221
- [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
222
- [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
223
- [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
224
- [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
225
- [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
226
- [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
227
- [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
228
- };
229
- }
230
- return {};
231
- }
232
- runWith(context2, fn) {
233
- return this._storage.runWith(context2, fn);
234
- }
235
- };
236
- _getStore = new WeakSet();
237
- getStore_fn = /* @__PURE__ */ __name(function() {
238
- return this._storage.getStore();
239
- }, "#getStore");
240
- __name(_TaskContextManager, "TaskContextManager");
241
- var TaskContextManager = _TaskContextManager;
242
- var taskContextManager = new TaskContextManager();
243
- var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
244
- constructor(innerProcessor) {
245
- this._innerProcessor = innerProcessor;
246
- }
247
- // Called when a span starts
248
- onStart(span, parentContext) {
249
- if (taskContextManager.ctx) {
250
- span.setAttributes(flattenAttributes({
251
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
252
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
253
- }, SemanticInternalAttributes.METADATA));
254
- }
255
- this._innerProcessor.onStart(span, parentContext);
256
- }
257
- // Delegate the rest of the methods to the wrapped processor
258
- onEnd(span) {
259
- this._innerProcessor.onEnd(span);
260
- }
261
- shutdown() {
262
- return this._innerProcessor.shutdown();
263
- }
264
- forceFlush() {
265
- return this._innerProcessor.forceFlush();
266
- }
267
- };
268
- __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
269
- var TaskContextSpanProcessor = _TaskContextSpanProcessor;
270
-
271
- // src/v3/utils/getEnv.ts
272
- function getEnvVar(name) {
273
- if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
274
- return process.env[name];
275
- }
276
- }
277
- __name(getEnvVar, "getEnvVar");
278
-
279
- // src/v3/otel/index.ts
280
- function recordSpanException(span, error) {
281
- if (error instanceof Error) {
282
- span.recordException(error);
283
- } else if (typeof error === "string") {
284
- span.recordException(new Error(error));
285
- } else {
286
- span.recordException(new Error(JSON.stringify(error)));
287
- }
288
- span.setStatus({
289
- code: api.SpanStatusCode.ERROR
290
- });
291
- }
292
- __name(recordSpanException, "recordSpanException");
293
- var TaskRunBuiltInError = zod.z.object({
294
- type: zod.z.literal("BUILT_IN_ERROR"),
295
- name: zod.z.string(),
296
- message: zod.z.string(),
297
- stackTrace: zod.z.string()
298
- });
299
- var TaskRunCustomErrorObject = zod.z.object({
300
- type: zod.z.literal("CUSTOM_ERROR"),
301
- raw: zod.z.string()
302
- });
303
- var TaskRunStringError = zod.z.object({
304
- type: zod.z.literal("STRING_ERROR"),
305
- raw: zod.z.string()
306
- });
307
- var TaskRunErrorCodes = {
308
- COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
309
- COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
310
- CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
311
- TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
312
- TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
313
- TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
314
- TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
315
- TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
316
- TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
317
- HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
318
- GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
319
- };
320
- var TaskRunInternalError = zod.z.object({
321
- type: zod.z.literal("INTERNAL_ERROR"),
322
- code: zod.z.enum([
323
- "COULD_NOT_FIND_EXECUTOR",
324
- "COULD_NOT_FIND_TASK",
325
- "CONFIGURED_INCORRECTLY",
326
- "TASK_ALREADY_RUNNING",
327
- "TASK_EXECUTION_FAILED",
328
- "TASK_EXECUTION_ABORTED",
329
- "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
330
- "TASK_RUN_CANCELLED",
331
- "TASK_OUTPUT_ERROR",
332
- "HANDLE_ERROR_ERROR",
333
- "GRACEFUL_EXIT_TIMEOUT"
334
- ]),
335
- message: zod.z.string().optional()
336
- });
337
- var TaskRunError = zod.z.discriminatedUnion("type", [
338
- TaskRunBuiltInError,
339
- TaskRunCustomErrorObject,
340
- TaskRunStringError,
341
- TaskRunInternalError
342
- ]);
343
- var TaskRun = zod.z.object({
344
- id: zod.z.string(),
345
- payload: zod.z.string(),
346
- payloadType: zod.z.string(),
347
- context: zod.z.any(),
348
- tags: zod.z.array(zod.z.string()),
349
- isTest: zod.z.boolean().default(false),
350
- createdAt: zod.z.coerce.date(),
351
- idempotencyKey: zod.z.string().optional()
352
- });
353
- var TaskRunExecutionTask = zod.z.object({
354
- id: zod.z.string(),
355
- filePath: zod.z.string(),
356
- exportName: zod.z.string()
357
- });
358
- var TaskRunExecutionAttempt = zod.z.object({
359
- id: zod.z.string(),
360
- number: zod.z.number(),
361
- startedAt: zod.z.coerce.date(),
362
- backgroundWorkerId: zod.z.string(),
363
- backgroundWorkerTaskId: zod.z.string(),
364
- status: zod.z.string()
365
- });
366
- var TaskRunExecutionEnvironment = zod.z.object({
367
- id: zod.z.string(),
368
- slug: zod.z.string(),
369
- type: zod.z.enum([
370
- "PRODUCTION",
371
- "STAGING",
372
- "DEVELOPMENT",
373
- "PREVIEW"
374
- ])
375
- });
376
- var TaskRunExecutionOrganization = zod.z.object({
377
- id: zod.z.string(),
378
- slug: zod.z.string(),
379
- name: zod.z.string()
380
- });
381
- var TaskRunExecutionProject = zod.z.object({
382
- id: zod.z.string(),
383
- ref: zod.z.string(),
384
- slug: zod.z.string(),
385
- name: zod.z.string()
386
- });
387
- var TaskRunExecutionQueue = zod.z.object({
388
- id: zod.z.string(),
389
- name: zod.z.string()
390
- });
391
- var TaskRunExecutionBatch = zod.z.object({
392
- id: zod.z.string()
393
- });
394
- var TaskRunExecution = zod.z.object({
395
- task: TaskRunExecutionTask,
396
- attempt: TaskRunExecutionAttempt,
397
- run: TaskRun,
398
- queue: TaskRunExecutionQueue,
399
- environment: TaskRunExecutionEnvironment,
400
- organization: TaskRunExecutionOrganization,
401
- project: TaskRunExecutionProject,
402
- batch: TaskRunExecutionBatch.optional()
403
- });
404
- var TaskRunContext = zod.z.object({
405
- task: TaskRunExecutionTask,
406
- attempt: TaskRunExecutionAttempt.omit({
407
- backgroundWorkerId: true,
408
- backgroundWorkerTaskId: true
409
- }),
410
- run: TaskRun.omit({
411
- payload: true,
412
- payloadType: true
413
- }),
414
- queue: TaskRunExecutionQueue,
415
- environment: TaskRunExecutionEnvironment,
416
- organization: TaskRunExecutionOrganization,
417
- project: TaskRunExecutionProject,
418
- batch: TaskRunExecutionBatch.optional()
419
- });
420
- var TaskRunExecutionRetry = zod.z.object({
421
- timestamp: zod.z.number(),
422
- delay: zod.z.number(),
423
- error: zod.z.unknown().optional()
424
- });
425
- var TaskRunFailedExecutionResult = zod.z.object({
426
- ok: zod.z.literal(false),
427
- id: zod.z.string(),
428
- error: TaskRunError,
429
- retry: TaskRunExecutionRetry.optional(),
430
- skippedRetrying: zod.z.boolean().optional()
431
- });
432
- var TaskRunSuccessfulExecutionResult = zod.z.object({
433
- ok: zod.z.literal(true),
434
- id: zod.z.string(),
435
- output: zod.z.string().optional(),
436
- outputType: zod.z.string()
437
- });
438
- var TaskRunExecutionResult = zod.z.discriminatedUnion("ok", [
439
- TaskRunSuccessfulExecutionResult,
440
- TaskRunFailedExecutionResult
441
- ]);
442
- var BatchTaskRunExecutionResult = zod.z.object({
443
- id: zod.z.string(),
444
- items: TaskRunExecutionResult.array()
445
- });
446
-
447
- // src/v3/schemas/messages.ts
448
- var EnvironmentType = zod.z.enum([
449
- "PRODUCTION",
450
- "STAGING",
451
- "DEVELOPMENT",
452
- "PREVIEW"
453
- ]);
454
- var MachineCpu = zod.z.union([
455
- zod.z.literal(0.25),
456
- zod.z.literal(0.5),
457
- zod.z.literal(1),
458
- zod.z.literal(2),
459
- zod.z.literal(4)
460
- ]).default(0.5);
461
- var MachineMemory = zod.z.union([
462
- zod.z.literal(0.25),
463
- zod.z.literal(0.5),
464
- zod.z.literal(1),
465
- zod.z.literal(2),
466
- zod.z.literal(4),
467
- zod.z.literal(8)
468
- ]).default(1);
469
- var Machine = zod.z.object({
470
- version: zod.z.literal("v1").default("v1"),
471
- cpu: MachineCpu,
472
- memory: MachineMemory
473
- });
474
- var TaskRunExecutionPayload = zod.z.object({
475
- execution: TaskRunExecution,
476
- traceContext: zod.z.record(zod.z.unknown()),
477
- environment: zod.z.record(zod.z.string()).optional()
478
- });
479
- var ProdTaskRunExecution = TaskRunExecution.extend({
480
- worker: zod.z.object({
481
- id: zod.z.string(),
482
- contentHash: zod.z.string(),
483
- version: zod.z.string()
484
- })
485
- });
486
- zod.z.object({
487
- execution: ProdTaskRunExecution,
488
- traceContext: zod.z.record(zod.z.unknown()),
489
- environment: zod.z.record(zod.z.string()).optional()
490
- });
491
- var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
492
- zod.z.object({
493
- type: zod.z.literal("EXECUTE_RUNS"),
494
- payloads: zod.z.array(TaskRunExecutionPayload)
495
- }),
496
- zod.z.object({
497
- type: zod.z.literal("CANCEL_ATTEMPT"),
498
- taskAttemptId: zod.z.string(),
499
- taskRunId: zod.z.string()
500
- }),
501
- zod.z.object({
502
- type: zod.z.literal("SCHEDULE_ATTEMPT"),
503
- image: zod.z.string(),
504
- version: zod.z.string(),
505
- machine: Machine,
506
- // identifiers
507
- id: zod.z.string(),
508
- envId: zod.z.string(),
509
- envType: EnvironmentType,
510
- orgId: zod.z.string(),
511
- projectId: zod.z.string(),
512
- runId: zod.z.string()
513
- })
514
- ]);
515
- ({
516
- SERVER_READY: zod.z.object({
517
- version: zod.z.literal("v1").default("v1"),
518
- id: zod.z.string()
519
- }),
520
- BACKGROUND_WORKER_MESSAGE: zod.z.object({
521
- version: zod.z.literal("v1").default("v1"),
522
- backgroundWorkerId: zod.z.string(),
523
- data: BackgroundWorkerServerMessages
524
- })
525
- });
526
- var BackgroundWorkerClientMessages = zod.z.discriminatedUnion("type", [
527
- zod.z.object({
528
- version: zod.z.literal("v1").default("v1"),
529
- type: zod.z.literal("TASK_RUN_COMPLETED"),
530
- completion: TaskRunExecutionResult,
531
- execution: TaskRunExecution
532
- }),
533
- zod.z.object({
534
- version: zod.z.literal("v1").default("v1"),
535
- type: zod.z.literal("TASK_HEARTBEAT"),
536
- id: zod.z.string()
537
- })
538
- ]);
539
- var BackgroundWorkerProperties = zod.z.object({
540
- id: zod.z.string(),
541
- version: zod.z.string(),
542
- contentHash: zod.z.string()
543
- });
544
- ({
545
- READY_FOR_TASKS: zod.z.object({
546
- version: zod.z.literal("v1").default("v1"),
547
- backgroundWorkerId: zod.z.string()
548
- }),
549
- BACKGROUND_WORKER_DEPRECATED: zod.z.object({
550
- version: zod.z.literal("v1").default("v1"),
551
- backgroundWorkerId: zod.z.string()
552
- }),
553
- BACKGROUND_WORKER_MESSAGE: zod.z.object({
554
- version: zod.z.literal("v1").default("v1"),
555
- backgroundWorkerId: zod.z.string(),
556
- data: BackgroundWorkerClientMessages
557
- })
558
- });
559
- ({
560
- EXECUTE_TASK_RUN: zod.z.object({
561
- version: zod.z.literal("v1").default("v1"),
562
- execution: TaskRunExecution,
563
- traceContext: zod.z.record(zod.z.unknown()),
564
- metadata: BackgroundWorkerProperties
565
- }),
566
- TASK_RUN_COMPLETED_NOTIFICATION: zod.z.object({
567
- version: zod.z.literal("v1").default("v1"),
568
- completion: TaskRunExecutionResult,
569
- execution: TaskRunExecution
570
- }),
571
- CLEANUP: zod.z.object({
572
- version: zod.z.literal("v1").default("v1"),
573
- flush: zod.z.boolean().default(false),
574
- kill: zod.z.boolean().default(true)
575
- })
576
- });
577
- var FixedWindowRateLimit = zod.z.object({
578
- type: zod.z.literal("fixed-window"),
579
- limit: zod.z.number(),
580
- window: zod.z.union([
581
- zod.z.object({
582
- seconds: zod.z.number()
583
- }),
584
- zod.z.object({
585
- minutes: zod.z.number()
586
- }),
587
- zod.z.object({
588
- hours: zod.z.number()
589
- })
590
- ])
591
- });
592
- var SlidingWindowRateLimit = zod.z.object({
593
- type: zod.z.literal("sliding-window"),
594
- limit: zod.z.number(),
595
- window: zod.z.union([
596
- zod.z.object({
597
- seconds: zod.z.number()
598
- }),
599
- zod.z.object({
600
- minutes: zod.z.number()
601
- }),
602
- zod.z.object({
603
- hours: zod.z.number()
604
- })
605
- ])
606
- });
607
- var RateLimitOptions = zod.z.discriminatedUnion("type", [
608
- FixedWindowRateLimit,
609
- SlidingWindowRateLimit
610
- ]);
611
- var RetryOptions = zod.z.object({
612
- /** The number of attempts before giving up */
613
- maxAttempts: zod.z.number().int().optional(),
614
- /** The exponential factor to use when calculating the next retry time.
615
- *
616
- * Each subsequent retry will be calculated as `previousTimeout * factor`
617
- */
618
- factor: zod.z.number().optional(),
619
- /** The minimum time to wait before retrying */
620
- minTimeoutInMs: zod.z.number().int().optional(),
621
- /** The maximum time to wait before retrying */
622
- maxTimeoutInMs: zod.z.number().int().optional(),
623
- /** Randomize the timeout between retries.
624
- *
625
- * This can be useful to prevent the thundering herd problem where all retries happen at the same time.
626
- */
627
- randomize: zod.z.boolean().optional()
628
- });
629
- var QueueOptions = zod.z.object({
630
- /** You can define a shared queue and then pass the name in to your task.
631
- *
632
- * @example
633
- *
634
- * ```ts
635
- * const myQueue = queue({
636
- name: "my-queue",
637
- concurrencyLimit: 1,
638
- });
639
-
640
- export const task1 = task({
641
- id: "task-1",
642
- queue: {
643
- name: "my-queue",
644
- },
645
- run: async (payload: { message: string }) => {
646
- // ...
647
- },
648
- });
649
-
650
- export const task2 = task({
651
- id: "task-2",
652
- queue: {
653
- name: "my-queue",
654
- },
655
- run: async (payload: { message: string }) => {
656
- // ...
657
- },
658
- });
659
- * ```
660
- */
661
- name: zod.z.string().optional(),
662
- /** An optional property that specifies the maximum number of concurrent run executions.
663
- *
664
- * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
665
- concurrencyLimit: zod.z.number().int().min(0).max(1e3).optional(),
666
- /** @deprecated This feature is coming soon */
667
- rateLimit: RateLimitOptions.optional()
668
- });
669
- var TaskMetadata = zod.z.object({
670
- id: zod.z.string(),
671
- packageVersion: zod.z.string(),
672
- queue: QueueOptions.optional(),
673
- retry: RetryOptions.optional(),
674
- machine: Machine.partial().optional(),
675
- triggerSource: zod.z.string().optional()
676
- });
677
- var TaskFileMetadata = zod.z.object({
678
- filePath: zod.z.string(),
679
- exportName: zod.z.string()
680
- });
681
- var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
682
- var UncaughtExceptionMessage = zod.z.object({
683
- version: zod.z.literal("v1").default("v1"),
684
- error: zod.z.object({
685
- name: zod.z.string(),
686
- message: zod.z.string(),
687
- stack: zod.z.string().optional()
688
- }),
689
- origin: zod.z.enum([
690
- "uncaughtException",
691
- "unhandledRejection"
692
- ])
693
- });
694
- var TaskMetadataFailedToParseData = zod.z.object({
695
- version: zod.z.literal("v1").default("v1"),
696
- tasks: zod.z.unknown(),
697
- zodIssues: zod.z.custom((v) => {
698
- return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
699
- })
700
- });
701
- ({
702
- TASK_RUN_COMPLETED: zod.z.object({
703
- version: zod.z.literal("v1").default("v1"),
704
- execution: TaskRunExecution,
705
- result: TaskRunExecutionResult
706
- }),
707
- TASKS_READY: zod.z.object({
708
- version: zod.z.literal("v1").default("v1"),
709
- tasks: TaskMetadataWithFilePath.array()
710
- }),
711
- TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
712
- TASK_HEARTBEAT: zod.z.object({
713
- version: zod.z.literal("v1").default("v1"),
714
- id: zod.z.string()
715
- }),
716
- READY_TO_DISPOSE: zod.z.undefined(),
717
- WAIT_FOR_DURATION: zod.z.object({
718
- version: zod.z.literal("v1").default("v1"),
719
- ms: zod.z.number()
720
- }),
721
- WAIT_FOR_TASK: zod.z.object({
722
- version: zod.z.literal("v1").default("v1"),
723
- id: zod.z.string()
724
- }),
725
- WAIT_FOR_BATCH: zod.z.object({
726
- version: zod.z.literal("v1").default("v1"),
727
- id: zod.z.string(),
728
- runs: zod.z.string().array()
729
- }),
730
- UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
731
- });
732
- ({
733
- TASK_RUN_COMPLETED: {
734
- message: zod.z.object({
735
- version: zod.z.literal("v1").default("v1"),
736
- execution: TaskRunExecution,
737
- result: TaskRunExecutionResult
738
- })
739
- },
740
- TASKS_READY: {
741
- message: zod.z.object({
742
- version: zod.z.literal("v1").default("v1"),
743
- tasks: TaskMetadataWithFilePath.array()
744
- })
745
- },
746
- TASKS_FAILED_TO_PARSE: {
747
- message: TaskMetadataFailedToParseData
748
- },
749
- TASK_HEARTBEAT: {
750
- message: zod.z.object({
751
- version: zod.z.literal("v1").default("v1"),
752
- id: zod.z.string()
753
- })
754
- },
755
- READY_TO_DISPOSE: {
756
- message: zod.z.undefined()
757
- },
758
- READY_FOR_CHECKPOINT: {
759
- message: zod.z.object({
760
- version: zod.z.literal("v1").default("v1")
761
- })
762
- },
763
- CANCEL_CHECKPOINT: {
764
- message: zod.z.object({
765
- version: zod.z.literal("v1").default("v1")
766
- })
767
- },
768
- WAIT_FOR_DURATION: {
769
- message: zod.z.object({
770
- version: zod.z.literal("v1").default("v1"),
771
- ms: zod.z.number(),
772
- now: zod.z.number()
773
- }),
774
- callback: zod.z.object({
775
- willCheckpointAndRestore: zod.z.boolean()
776
- })
777
- },
778
- WAIT_FOR_TASK: {
779
- message: zod.z.object({
780
- version: zod.z.literal("v1").default("v1"),
781
- friendlyId: zod.z.string()
782
- })
783
- },
784
- WAIT_FOR_BATCH: {
785
- message: zod.z.object({
786
- version: zod.z.literal("v1").default("v1"),
787
- batchFriendlyId: zod.z.string(),
788
- runFriendlyIds: zod.z.string().array()
789
- })
790
- },
791
- UNCAUGHT_EXCEPTION: {
792
- message: UncaughtExceptionMessage
793
- }
794
- });
795
- ({
796
- EXECUTE_TASK_RUN: {
797
- message: zod.z.object({
798
- version: zod.z.literal("v1").default("v1"),
799
- execution: TaskRunExecution,
800
- traceContext: zod.z.record(zod.z.unknown()),
801
- metadata: BackgroundWorkerProperties
802
- })
803
- },
804
- TASK_RUN_COMPLETED_NOTIFICATION: {
805
- message: zod.z.object({
806
- version: zod.z.literal("v1").default("v1"),
807
- completion: TaskRunExecutionResult,
808
- execution: TaskRunExecution
809
- })
810
- },
811
- CLEANUP: {
812
- message: zod.z.object({
813
- version: zod.z.literal("v1").default("v1"),
814
- flush: zod.z.boolean().default(false),
815
- kill: zod.z.boolean().default(true)
816
- }),
817
- callback: zod.z.void()
818
- },
819
- WAIT_COMPLETED_NOTIFICATION: {
820
- message: zod.z.object({
821
- version: zod.z.literal("v1").default("v1")
822
- })
823
- }
824
- });
825
-
826
- // src/v3/schemas/resources.ts
827
- var TaskResource = zod.z.object({
828
- id: zod.z.string(),
829
- filePath: zod.z.string(),
830
- exportName: zod.z.string(),
831
- queue: QueueOptions.optional(),
832
- retry: RetryOptions.optional(),
833
- machine: Machine.partial().optional(),
834
- triggerSource: zod.z.string().optional()
835
- });
836
- var BackgroundWorkerMetadata = zod.z.object({
837
- packageVersion: zod.z.string(),
838
- contentHash: zod.z.string(),
839
- cliPackageVersion: zod.z.string().optional(),
840
- tasks: zod.z.array(TaskResource)
841
- });
842
- zod.z.object({
843
- contentHash: zod.z.string(),
844
- imageTag: zod.z.string()
845
- });
846
-
847
- // src/v3/schemas/api.ts
848
- zod.z.object({
849
- userId: zod.z.string(),
850
- email: zod.z.string().email(),
851
- dashboardUrl: zod.z.string()
852
- });
853
- var GetProjectResponseBody = zod.z.object({
854
- id: zod.z.string(),
855
- externalRef: zod.z.string(),
856
- name: zod.z.string(),
857
- slug: zod.z.string(),
858
- createdAt: zod.z.coerce.date(),
859
- organization: zod.z.object({
860
- id: zod.z.string(),
861
- title: zod.z.string(),
862
- slug: zod.z.string(),
863
- createdAt: zod.z.coerce.date()
864
- })
865
- });
866
- zod.z.array(GetProjectResponseBody);
867
- zod.z.object({
868
- apiKey: zod.z.string(),
869
- name: zod.z.string(),
870
- apiUrl: zod.z.string()
871
- });
872
- zod.z.object({
873
- localOnly: zod.z.boolean(),
874
- metadata: BackgroundWorkerMetadata
875
- });
876
- zod.z.object({
877
- id: zod.z.string(),
878
- version: zod.z.string(),
879
- contentHash: zod.z.string()
880
- });
881
- var TriggerTaskRequestBody = zod.z.object({
882
- payload: zod.z.any(),
883
- context: zod.z.any(),
884
- options: zod.z.object({
885
- dependentAttempt: zod.z.string().optional(),
886
- dependentBatch: zod.z.string().optional(),
887
- lockToVersion: zod.z.string().optional(),
888
- queue: QueueOptions.optional(),
889
- concurrencyKey: zod.z.string().optional(),
890
- idempotencyKey: zod.z.string().optional(),
891
- test: zod.z.boolean().optional(),
892
- payloadType: zod.z.string().optional()
893
- }).optional()
894
- });
895
- var TriggerTaskResponse = zod.z.object({
896
- id: zod.z.string()
897
- });
898
- zod.z.object({
899
- items: TriggerTaskRequestBody.array(),
900
- dependentAttempt: zod.z.string().optional()
901
- });
902
- var BatchTriggerTaskResponse = zod.z.object({
903
- batchId: zod.z.string(),
904
- runs: zod.z.string().array()
905
- });
906
- zod.z.object({
907
- id: zod.z.string(),
908
- items: zod.z.array(zod.z.object({
909
- id: zod.z.string(),
910
- taskRunId: zod.z.string(),
911
- status: zod.z.enum([
912
- "PENDING",
913
- "CANCELED",
914
- "COMPLETED",
915
- "FAILED"
916
- ])
917
- }))
918
- });
919
- zod.z.object({
920
- variables: zod.z.record(zod.z.string())
921
- });
922
- zod.z.object({
923
- imageReference: zod.z.string()
924
- });
925
- zod.z.object({
926
- id: zod.z.string(),
927
- contentHash: zod.z.string()
928
- });
929
- var ExternalBuildData = zod.z.object({
930
- buildId: zod.z.string(),
931
- buildToken: zod.z.string(),
932
- projectId: zod.z.string()
933
- });
934
- zod.z.object({
935
- id: zod.z.string(),
936
- contentHash: zod.z.string(),
937
- shortCode: zod.z.string(),
938
- version: zod.z.string(),
939
- imageTag: zod.z.string(),
940
- externalBuildData: ExternalBuildData.optional().nullable(),
941
- registryHost: zod.z.string().optional()
942
- });
943
- zod.z.object({
944
- contentHash: zod.z.string(),
945
- userId: zod.z.string().optional()
946
- });
947
- var DeploymentErrorData = zod.z.object({
948
- name: zod.z.string(),
949
- message: zod.z.string(),
950
- stack: zod.z.string().optional()
951
- });
952
- zod.z.object({
953
- id: zod.z.string(),
954
- status: zod.z.enum([
955
- "PENDING",
956
- "BUILDING",
957
- "DEPLOYING",
958
- "DEPLOYED",
959
- "FAILED",
960
- "CANCELED",
961
- "TIMED_OUT"
962
- ]),
963
- contentHash: zod.z.string(),
964
- shortCode: zod.z.string(),
965
- version: zod.z.string(),
966
- imageReference: zod.z.string().optional(),
967
- errorData: DeploymentErrorData.optional().nullable(),
968
- worker: zod.z.object({
969
- id: zod.z.string(),
970
- version: zod.z.string(),
971
- tasks: zod.z.array(zod.z.object({
972
- id: zod.z.string(),
973
- slug: zod.z.string(),
974
- filePath: zod.z.string(),
975
- exportName: zod.z.string()
976
- }))
977
- }).optional()
978
- });
979
- var CreateUploadPayloadUrlResponseBody = zod.z.object({
980
- presignedUrl: zod.z.string()
981
- });
982
- var ReplayRunResponse = zod.z.object({
983
- id: zod.z.string()
984
- });
985
- var CanceledRunResponse = zod.z.object({
986
- message: zod.z.string()
987
- });
988
- zod.z.object({
989
- /** The schedule id associated with this run (you can have many schedules for the same task).
990
- You can use this to remove the schedule, update it, etc */
991
- scheduleId: zod.z.string(),
992
- /** When the task was scheduled to run.
993
- * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
994
- timestamp: zod.z.date(),
995
- /** When the task was last run (it has been).
996
- This can be undefined if it's never been run */
997
- lastTimestamp: zod.z.date().optional(),
998
- /** You can optionally provide an external id when creating the schedule.
999
- Usually you would use a userId or some other unique identifier.
1000
- This defaults to undefined if you didn't provide one. */
1001
- externalId: zod.z.string().optional(),
1002
- /** The next 5 dates this task is scheduled to run */
1003
- upcoming: zod.z.array(zod.z.date())
1004
- });
1005
- zod.z.object({
1006
- /** The id of the task you want to attach to. */
1007
- task: zod.z.string(),
1008
- /** The schedule in CRON format.
1009
- *
1010
- * ```txt
1011
- * * * * * *
1012
- ┬ ┬ ┬ ┬ ┬
1013
- │ │ │ │ |
1014
- │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
1015
- │ │ │ └───── month (1 - 12)
1016
- │ │ └────────── day of month (1 - 31, L)
1017
- │ └─────────────── hour (0 - 23)
1018
- └──────────────────── minute (0 - 59)
1019
- * ```
1020
-
1021
- "L" means the last. In the "day of week" field, 1L means the last Monday of the month. In the day of month field, L means the last day of the month.
1022
-
1023
- */
1024
- cron: zod.z.string(),
1025
- /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1026
- *
1027
- * This is useful if you don't want to create duplicate schedules for a user. */
1028
- deduplicationKey: zod.z.string().optional(),
1029
- /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
1030
- *
1031
- * This allows you to have per-user CRON tasks.
1032
- */
1033
- externalId: zod.z.string().optional()
1034
- });
1035
- var ScheduleObject = zod.z.object({
1036
- id: zod.z.string(),
1037
- task: zod.z.string(),
1038
- active: zod.z.boolean(),
1039
- deduplicationKey: zod.z.string().nullish(),
1040
- externalId: zod.z.string().nullish(),
1041
- generator: zod.z.object({
1042
- type: zod.z.literal("CRON"),
1043
- expression: zod.z.string(),
1044
- description: zod.z.string()
1045
- }),
1046
- nextRun: zod.z.coerce.date().nullish(),
1047
- environments: zod.z.array(zod.z.object({
1048
- id: zod.z.string(),
1049
- type: zod.z.string(),
1050
- userName: zod.z.string().nullish()
1051
- }))
1052
- });
1053
- var DeletedScheduleObject = zod.z.object({
1054
- id: zod.z.string()
1055
- });
1056
- var ListSchedulesResult = zod.z.object({
1057
- data: zod.z.array(ScheduleObject),
1058
- pagination: zod.z.object({
1059
- currentPage: zod.z.number(),
1060
- totalPages: zod.z.number(),
1061
- count: zod.z.number()
1062
- })
1063
- });
1064
- zod.z.object({
1065
- page: zod.z.number().optional(),
1066
- perPage: zod.z.number().optional()
1067
- });
1068
-
1069
- // src/v3/apiErrors.ts
1070
- var _APIError = class _APIError extends Error {
1071
- constructor(status, error, message, headers) {
1072
- super(`${_APIError.makeMessage(status, error, message)}`);
1073
- this.status = status;
1074
- this.headers = headers;
1075
- const data = error;
1076
- this.error = data;
1077
- this.code = data?.["code"];
1078
- this.param = data?.["param"];
1079
- this.type = data?.["type"];
1080
- }
1081
- static makeMessage(status, error, message) {
1082
- const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1083
- if (status && msg) {
1084
- return `${status} ${msg}`;
1085
- }
1086
- if (status) {
1087
- return `${status} status code (no body)`;
1088
- }
1089
- if (msg) {
1090
- return msg;
1091
- }
1092
- return "(no status code or body)";
1093
- }
1094
- static generate(status, errorResponse, message, headers) {
1095
- if (!status) {
1096
- return new APIConnectionError({
1097
- cause: castToError(errorResponse)
1098
- });
1099
- }
1100
- const error = errorResponse?.["error"];
1101
- if (status === 400) {
1102
- return new BadRequestError(status, error, message, headers);
1103
- }
1104
- if (status === 401) {
1105
- return new AuthenticationError(status, error, message, headers);
1106
- }
1107
- if (status === 403) {
1108
- return new PermissionDeniedError(status, error, message, headers);
1109
- }
1110
- if (status === 404) {
1111
- return new NotFoundError(status, error, message, headers);
1112
- }
1113
- if (status === 409) {
1114
- return new ConflictError(status, error, message, headers);
1115
- }
1116
- if (status === 422) {
1117
- return new UnprocessableEntityError(status, error, message, headers);
1118
- }
1119
- if (status === 429) {
1120
- return new RateLimitError(status, error, message, headers);
1121
- }
1122
- if (status >= 500) {
1123
- return new InternalServerError(status, error, message, headers);
1124
- }
1125
- return new _APIError(status, error, message, headers);
1126
- }
1127
- };
1128
- __name(_APIError, "APIError");
1129
- var APIError = _APIError;
1130
- var _APIConnectionError = class _APIConnectionError extends APIError {
1131
- constructor({ message, cause }) {
1132
- super(void 0, void 0, message || "Connection error.", void 0);
1133
- __publicField(this, "status");
1134
- if (cause)
1135
- this.cause = cause;
1136
- }
1137
- };
1138
- __name(_APIConnectionError, "APIConnectionError");
1139
- var APIConnectionError = _APIConnectionError;
1140
- var _BadRequestError = class _BadRequestError extends APIError {
1141
- constructor() {
1142
- super(...arguments);
1143
- __publicField(this, "status", 400);
1144
- }
1145
- };
1146
- __name(_BadRequestError, "BadRequestError");
1147
- var BadRequestError = _BadRequestError;
1148
- var _AuthenticationError = class _AuthenticationError extends APIError {
1149
- constructor() {
1150
- super(...arguments);
1151
- __publicField(this, "status", 401);
1152
- }
1153
- };
1154
- __name(_AuthenticationError, "AuthenticationError");
1155
- var AuthenticationError = _AuthenticationError;
1156
- var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
1157
- constructor() {
1158
- super(...arguments);
1159
- __publicField(this, "status", 403);
1160
- }
1161
- };
1162
- __name(_PermissionDeniedError, "PermissionDeniedError");
1163
- var PermissionDeniedError = _PermissionDeniedError;
1164
- var _NotFoundError = class _NotFoundError extends APIError {
1165
- constructor() {
1166
- super(...arguments);
1167
- __publicField(this, "status", 404);
1168
- }
1169
- };
1170
- __name(_NotFoundError, "NotFoundError");
1171
- var NotFoundError = _NotFoundError;
1172
- var _ConflictError = class _ConflictError extends APIError {
1173
- constructor() {
1174
- super(...arguments);
1175
- __publicField(this, "status", 409);
1176
- }
1177
- };
1178
- __name(_ConflictError, "ConflictError");
1179
- var ConflictError = _ConflictError;
1180
- var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
1181
- constructor() {
1182
- super(...arguments);
1183
- __publicField(this, "status", 422);
1184
- }
1185
- };
1186
- __name(_UnprocessableEntityError, "UnprocessableEntityError");
1187
- var UnprocessableEntityError = _UnprocessableEntityError;
1188
- var _RateLimitError = class _RateLimitError extends APIError {
1189
- constructor() {
1190
- super(...arguments);
1191
- __publicField(this, "status", 429);
1192
- }
1193
- };
1194
- __name(_RateLimitError, "RateLimitError");
1195
- var RateLimitError = _RateLimitError;
1196
- var _InternalServerError = class _InternalServerError extends APIError {
1197
- };
1198
- __name(_InternalServerError, "InternalServerError");
1199
- var InternalServerError = _InternalServerError;
1200
- function castToError(err) {
1201
- if (err instanceof Error)
1202
- return err;
1203
- return new Error(err);
1204
- }
1205
- __name(castToError, "castToError");
1206
-
1207
- // src/v3/utils/retries.ts
1208
- var defaultRetryOptions = {
1209
- maxAttempts: 3,
1210
- factor: 2,
1211
- minTimeoutInMs: 1e3,
1212
- maxTimeoutInMs: 6e4,
1213
- randomize: true
1214
- };
1215
- function calculateNextRetryDelay(options, attempt) {
1216
- const opts = {
1217
- ...defaultRetryOptions,
1218
- ...options
1219
- };
1220
- if (attempt >= opts.maxAttempts) {
1221
- return;
1222
- }
1223
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1224
- const random = randomize ? Math.random() + 1 : 1;
1225
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1226
- return Math.round(timeout);
1227
- }
1228
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1229
-
1230
- // src/v3/zodfetch.ts
1231
- var defaultRetryOptions2 = {
1232
- maxAttempts: 3,
1233
- factor: 2,
1234
- minTimeoutInMs: 1e3,
1235
- maxTimeoutInMs: 6e4,
1236
- randomize: false
1237
- };
1238
- async function zodfetch(schema, url, requestInit, options) {
1239
- return await _doZodFetch(schema, url, requestInit, options);
1240
- }
1241
- __name(zodfetch, "zodfetch");
1242
- async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1243
- try {
1244
- const response = await fetch(url, requestInitWithCache(requestInit));
1245
- const responseHeaders = createResponseHeaders(response.headers);
1246
- if (!response.ok) {
1247
- const retryResult = shouldRetry(response, attempt, options?.retry);
1248
- if (retryResult.retry) {
1249
- await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
1250
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1251
- } else {
1252
- const errText = await response.text().catch((e) => castToError2(e).message);
1253
- const errJSON = safeJsonParse(errText);
1254
- const errMessage = errJSON ? void 0 : errText;
1255
- throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
1256
- }
1257
- }
1258
- const jsonBody = await response.json();
1259
- const parsedResult = schema.safeParse(jsonBody);
1260
- if (parsedResult.success) {
1261
- return parsedResult.data;
1262
- }
1263
- throw zodValidationError.fromZodError(parsedResult.error);
1264
- } catch (error) {
1265
- if (error instanceof APIError) {
1266
- throw error;
1267
- }
1268
- if (options?.retry) {
1269
- const retry = {
1270
- ...defaultRetryOptions2,
1271
- ...options.retry
1272
- };
1273
- const delay = calculateNextRetryDelay(retry, attempt);
1274
- if (delay) {
1275
- await new Promise((resolve) => setTimeout(resolve, delay));
1276
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1277
- }
1278
- }
1279
- throw new APIConnectionError({
1280
- cause: castToError2(error)
1281
- });
1282
- }
1283
- }
1284
- __name(_doZodFetch, "_doZodFetch");
1285
- function castToError2(err) {
1286
- if (err instanceof Error)
1287
- return err;
1288
- return new Error(err);
1289
- }
1290
- __name(castToError2, "castToError");
1291
- function shouldRetry(response, attempt, retryOptions) {
1292
- function shouldRetryForOptions() {
1293
- const retry = {
1294
- ...defaultRetryOptions2,
1295
- ...retryOptions
1296
- };
1297
- const delay = calculateNextRetryDelay(retry, attempt);
1298
- if (delay) {
1299
- return {
1300
- retry: true,
1301
- delay
1302
- };
1303
- } else {
1304
- return {
1305
- retry: false
1306
- };
1307
- }
1308
- }
1309
- __name(shouldRetryForOptions, "shouldRetryForOptions");
1310
- const shouldRetryHeader = response.headers.get("x-should-retry");
1311
- if (shouldRetryHeader === "true")
1312
- return shouldRetryForOptions();
1313
- if (shouldRetryHeader === "false")
1314
- return {
1315
- retry: false
1316
- };
1317
- if (response.status === 408)
1318
- return shouldRetryForOptions();
1319
- if (response.status === 409)
1320
- return shouldRetryForOptions();
1321
- if (response.status === 429)
1322
- return shouldRetryForOptions();
1323
- if (response.status >= 500)
1324
- return shouldRetryForOptions();
1325
- return {
1326
- retry: false
1327
- };
1328
- }
1329
- __name(shouldRetry, "shouldRetry");
1330
- function safeJsonParse(text) {
1331
- try {
1332
- return JSON.parse(text);
1333
- } catch (e) {
1334
- return void 0;
1335
- }
1336
- }
1337
- __name(safeJsonParse, "safeJsonParse");
1338
- function createResponseHeaders(headers) {
1339
- return new Proxy(Object.fromEntries(
1340
- // @ts-ignore
1341
- headers.entries()
1342
- ), {
1343
- get(target, name) {
1344
- const key = name.toString();
1345
- return target[key.toLowerCase()] || target[key];
1346
- }
1347
- });
1348
- }
1349
- __name(createResponseHeaders, "createResponseHeaders");
1350
- function requestInitWithCache(requestInit) {
1351
- try {
1352
- const withCache = {
1353
- ...requestInit,
1354
- cache: "no-cache"
1355
- };
1356
- const _ = new Request("http://localhost", withCache);
1357
- return withCache;
1358
- } catch (error) {
1359
- return requestInit ?? {};
1360
- }
1361
- }
1362
- __name(requestInitWithCache, "requestInitWithCache");
1363
-
1364
- // src/v3/apiClient/index.ts
1365
- var zodFetchOptions = {
1366
- retry: {
1367
- maxAttempts: 3,
1368
- minTimeoutInMs: 1e3,
1369
- maxTimeoutInMs: 3e4,
1370
- factor: 2,
1371
- randomize: false
1372
- }
1373
- };
1374
- var _getHeaders, getHeaders_fn;
1375
- var _ApiClient = class _ApiClient {
1376
- constructor(baseUrl, accessToken) {
1377
- __privateAdd(this, _getHeaders);
1378
- this.accessToken = accessToken;
1379
- this.baseUrl = baseUrl.replace(/\/$/, "");
1380
- }
1381
- async getRunResult(runId) {
1382
- try {
1383
- return await zodfetch(TaskRunExecutionResult, `${this.baseUrl}/api/v1/runs/${runId}/result`, {
1384
- method: "GET",
1385
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1386
- }, zodFetchOptions);
1387
- } catch (error) {
1388
- if (error instanceof APIError) {
1389
- if (error.status === 404) {
1390
- return void 0;
1391
- }
1392
- }
1393
- throw error;
1394
- }
1395
- }
1396
- async getBatchResults(batchId) {
1397
- return await zodfetch(BatchTaskRunExecutionResult, `${this.baseUrl}/api/v1/batches/${batchId}/results`, {
1398
- method: "GET",
1399
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1400
- }, zodFetchOptions);
1401
- }
1402
- triggerTask(taskId, body, options) {
1403
- return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
1404
- method: "POST",
1405
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1406
- body: JSON.stringify(body)
1407
- }, zodFetchOptions);
1408
- }
1409
- batchTriggerTask(taskId, body, options) {
1410
- return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
1411
- method: "POST",
1412
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1413
- body: JSON.stringify(body)
1414
- }, zodFetchOptions);
1415
- }
1416
- createUploadPayloadUrl(filename) {
1417
- return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1418
- method: "PUT",
1419
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1420
- }, zodFetchOptions);
1421
- }
1422
- getPayloadUrl(filename) {
1423
- return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1424
- method: "GET",
1425
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1426
- }, zodFetchOptions);
1427
- }
1428
- replayRun(runId) {
1429
- return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
1430
- method: "POST",
1431
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1432
- }, zodFetchOptions);
1433
- }
1434
- cancelRun(runId) {
1435
- return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
1436
- method: "POST",
1437
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1438
- }, zodFetchOptions);
1439
- }
1440
- createSchedule(options) {
1441
- return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
1442
- method: "POST",
1443
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
1444
- body: JSON.stringify(options)
1445
- });
1446
- }
1447
- listSchedules(options) {
1448
- const searchParams = new URLSearchParams();
1449
- if (options?.page) {
1450
- searchParams.append("page", options.page.toString());
1451
- }
1452
- if (options?.perPage) {
1453
- searchParams.append("perPage", options.perPage.toString());
1454
- }
1455
- return zodfetch(ListSchedulesResult, `${this.baseUrl}/api/v1/schedules${searchParams.size > 0 ? `?${searchParams}` : ""}`, {
1456
- method: "GET",
1457
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1458
- });
1459
- }
1460
- retrieveSchedule(scheduleId) {
1461
- return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
1462
- method: "GET",
1463
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1464
- });
1465
- }
1466
- updateSchedule(scheduleId, options) {
1467
- return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
1468
- method: "PUT",
1469
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
1470
- body: JSON.stringify(options)
1471
- });
1472
- }
1473
- deactivateSchedule(scheduleId) {
1474
- return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
1475
- method: "POST",
1476
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1477
- });
1478
- }
1479
- activateSchedule(scheduleId) {
1480
- return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
1481
- method: "POST",
1482
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1483
- });
1484
- }
1485
- deleteSchedule(scheduleId) {
1486
- return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
1487
- method: "DELETE",
1488
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1489
- });
1490
- }
1491
- };
1492
- _getHeaders = new WeakSet();
1493
- getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
1494
- const headers = {
1495
- "Content-Type": "application/json",
1496
- Authorization: `Bearer ${this.accessToken}`
1497
- };
1498
- if (taskContextManager.isInsideTask) {
1499
- api.propagation.inject(api.context.active(), headers);
1500
- if (spanParentAsLink) {
1501
- headers["x-trigger-span-parent-as-link"] = "1";
1502
- }
1503
- }
1504
- return headers;
1505
- }, "#getHeaders");
1506
- __name(_ApiClient, "ApiClient");
1507
- var ApiClient = _ApiClient;
1508
- var _getStore2, getStore_fn2;
1509
- var _ApiClientManager = class _ApiClientManager {
1510
- constructor() {
1511
- __privateAdd(this, _getStore2);
1512
- __publicField(this, "_storage", new SafeAsyncLocalStorage());
1513
- }
1514
- get baseURL() {
1515
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
1516
- return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
1517
- }
1518
- get accessToken() {
1519
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
1520
- return store?.accessToken ?? getEnvVar("TRIGGER_SECRET_KEY");
1521
- }
1522
- get client() {
1523
- if (!this.baseURL || !this.accessToken) {
1524
- return void 0;
1525
- }
1526
- return new ApiClient(this.baseURL, this.accessToken);
1527
- }
1528
- runWith(context2, fn) {
1529
- return this._storage.runWith(context2, fn);
1530
- }
1531
- };
1532
- _getStore2 = new WeakSet();
1533
- getStore_fn2 = /* @__PURE__ */ __name(function() {
1534
- return this._storage.getStore();
1535
- }, "#getStore");
1536
- __name(_ApiClientManager, "ApiClientManager");
1537
- var ApiClientManager = _ApiClientManager;
1538
- var apiClientManager = new ApiClientManager();
1539
-
1540
- // src/v3/utils/ioSerialization.ts
1541
- async function parsePacket(value) {
1542
- if (!value.data) {
1543
- return void 0;
1544
- }
1545
- switch (value.dataType) {
1546
- case "application/json":
1547
- return JSON.parse(value.data);
1548
- case "application/super+json":
1549
- const { parse } = await loadSuperJSON();
1550
- return parse(value.data);
1551
- case "text/plain":
1552
- return value.data;
1553
- case "application/store":
1554
- throw new Error(`Cannot parse an application/store packet (${value.data}). Needs to be imported first.`);
1555
- default:
1556
- return value.data;
1557
- }
1558
- }
1559
- __name(parsePacket, "parsePacket");
1560
- async function stringifyIO(value) {
1561
- if (value === void 0) {
1562
- return {
1563
- dataType: "application/json"
1564
- };
1565
- }
1566
- if (typeof value === "string") {
1567
- return {
1568
- data: value,
1569
- dataType: "text/plain"
1570
- };
1571
- }
1572
- try {
1573
- const { stringify } = await loadSuperJSON();
1574
- const data = stringify(value);
1575
- return {
1576
- data,
1577
- dataType: "application/super+json"
1578
- };
1579
- } catch {
1580
- return {
1581
- data: value,
1582
- dataType: "application/json"
1583
- };
1584
- }
1585
- }
1586
- __name(stringifyIO, "stringifyIO");
1587
- async function conditionallyExportPacket(packet, pathPrefix, tracer) {
1588
- if (apiClientManager.client) {
1589
- const { needsOffloading, size } = packetRequiresOffloading(packet);
1590
- if (needsOffloading) {
1591
- if (!tracer) {
1592
- return await exportPacket(packet, pathPrefix);
1593
- } else {
1594
- const result = await tracer.startActiveSpan("store.uploadOutput", async (span) => {
1595
- return await exportPacket(packet, pathPrefix);
1596
- }, {
1597
- attributes: {
1598
- byteLength: size,
1599
- [SemanticInternalAttributes.STYLE_ICON]: "cloud-upload"
1600
- }
1601
- });
1602
- return result ?? packet;
1603
- }
1604
- }
1605
- }
1606
- return packet;
1607
- }
1608
- __name(conditionallyExportPacket, "conditionallyExportPacket");
1609
- function packetRequiresOffloading(packet) {
1610
- if (!packet.data) {
1611
- return {
1612
- needsOffloading: false,
1613
- size: 0
1614
- };
1615
- }
1616
- const byteSize = Buffer.byteLength(packet.data, "utf8");
1617
- return {
1618
- needsOffloading: byteSize >= OFFLOAD_IO_PACKET_LENGTH_LIMIT,
1619
- size: byteSize
1620
- };
1621
- }
1622
- __name(packetRequiresOffloading, "packetRequiresOffloading");
1623
- async function exportPacket(packet, pathPrefix) {
1624
- const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
1625
- const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
1626
- const uploadResponse = await fetch(presignedResponse.presignedUrl, {
1627
- method: "PUT",
1628
- headers: {
1629
- "Content-Type": packet.dataType
1630
- },
1631
- body: packet.data
1632
- });
1633
- if (!uploadResponse.ok) {
1634
- throw new Error(`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`);
1635
- }
1636
- return {
1637
- data: filename,
1638
- dataType: "application/store"
1639
- };
1640
- }
1641
- __name(exportPacket, "exportPacket");
1642
- async function conditionallyImportPacket(packet, tracer) {
1643
- if (packet.dataType !== "application/store") {
1644
- return packet;
1645
- }
1646
- if (!tracer) {
1647
- return await importPacket(packet);
1648
- } else {
1649
- const result = await tracer.startActiveSpan("store.downloadPayload", async (span) => {
1650
- return await importPacket(packet, span);
1651
- }, {
1652
- attributes: {
1653
- [SemanticInternalAttributes.STYLE_ICON]: "cloud-download"
1654
- }
1655
- });
1656
- return result ?? packet;
1657
- }
1658
- }
1659
- __name(conditionallyImportPacket, "conditionallyImportPacket");
1660
- async function importPacket(packet, span) {
1661
- if (!packet.data) {
1662
- return packet;
1663
- }
1664
- if (!apiClientManager.client) {
1665
- return packet;
1666
- }
1667
- const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
1668
- const response = await fetch(presignedResponse.presignedUrl);
1669
- if (!response.ok) {
1670
- throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
1671
- }
1672
- const data = await response.text();
1673
- span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
1674
- return {
1675
- data,
1676
- dataType: response.headers.get("content-type") ?? "application/json"
1677
- };
1678
- }
1679
- __name(importPacket, "importPacket");
1680
- async function createPacketAttributes(packet, dataKey, dataTypeKey) {
1681
- if (!packet.data) {
1682
- return;
1683
- }
1684
- switch (packet.dataType) {
1685
- case "application/json":
1686
- return {
1687
- ...flattenAttributes(packet, dataKey),
1688
- [dataTypeKey]: packet.dataType
1689
- };
1690
- case "application/super+json":
1691
- const { parse } = await loadSuperJSON();
1692
- if (typeof packet.data === "undefined" || packet.data === null) {
1693
- return;
1694
- }
1695
- try {
1696
- const parsed = parse(packet.data);
1697
- const jsonified = JSON.parse(JSON.stringify(parsed, safeReplacer));
1698
- return {
1699
- ...flattenAttributes(jsonified, dataKey),
1700
- [dataTypeKey]: "application/json"
1701
- };
1702
- } catch {
1703
- return;
1704
- }
1705
- case "application/store":
1706
- return {
1707
- [dataKey]: packet.data,
1708
- [dataTypeKey]: packet.dataType
1709
- };
1710
- case "text/plain":
1711
- return {
1712
- [dataKey]: packet.data,
1713
- [dataTypeKey]: packet.dataType
1714
- };
1715
- default:
1716
- return;
1717
- }
1718
- }
1719
- __name(createPacketAttributes, "createPacketAttributes");
1720
- function safeReplacer(key, value) {
1721
- if (typeof value === "bigint") {
1722
- return value.toString();
1723
- }
1724
- if (value instanceof RegExp) {
1725
- return value.toString();
1726
- }
1727
- if (value instanceof Set) {
1728
- return Array.from(value);
1729
- }
1730
- if (value instanceof Map) {
1731
- const obj = {};
1732
- value.forEach((v, k) => {
1733
- obj[k] = v;
1734
- });
1735
- return obj;
1736
- }
1737
- return value;
1738
- }
1739
- __name(safeReplacer, "safeReplacer");
1740
- function getPacketExtension(outputType) {
1741
- switch (outputType) {
1742
- case "application/json":
1743
- return "json";
1744
- case "application/super+json":
1745
- return "json";
1746
- case "text/plain":
1747
- return "txt";
1748
- default:
1749
- return "txt";
1750
- }
1751
- }
1752
- __name(getPacketExtension, "getPacketExtension");
1753
- async function loadSuperJSON() {
1754
- return await import('superjson');
1755
- }
1756
- __name(loadSuperJSON, "loadSuperJSON");
1757
-
1758
- // src/v3/utils/styleAttributes.ts
1759
- function accessoryAttributes(accessory) {
1760
- return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
1761
- }
1762
- __name(accessoryAttributes, "accessoryAttributes");
1763
-
1764
- // src/v3/workers/taskExecutor.ts
1765
- var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
1766
- var _TaskExecutor = class _TaskExecutor {
1767
- constructor(task, options) {
1768
- __privateAdd(this, _callRun);
1769
- __privateAdd(this, _callTaskInit);
1770
- __privateAdd(this, _callTaskCleanup);
1771
- __privateAdd(this, _handleError);
1772
- this.task = task;
1773
- this._tracingSDK = options.tracingSDK;
1774
- this._tracer = options.tracer;
1775
- this._consoleInterceptor = options.consoleInterceptor;
1776
- this._config = options.projectConfig;
1777
- this._importedConfig = options.importedConfig;
1778
- this._handleErrorFn = options.handleErrorFn;
1779
- }
1780
- async execute(execution, worker, traceContext) {
1781
- const ctx = TaskRunContext.parse(execution);
1782
- const attemptMessage = `Attempt ${execution.attempt.number}`;
1783
- const originalPacket = {
1784
- data: execution.run.payload,
1785
- dataType: execution.run.payloadType
1786
- };
1787
- const result = await taskContextManager.runWith({
1788
- ctx,
1789
- worker
1790
- }, async () => {
1791
- this._tracingSDK.asyncResourceDetector.resolveWithAttributes({
1792
- ...taskContextManager.attributes,
1793
- [SemanticInternalAttributes.SDK_VERSION]: this.task.packageVersion,
1794
- [SemanticInternalAttributes.SDK_LANGUAGE]: "typescript"
1795
- });
1796
- return await this._tracer.startActiveSpan(attemptMessage, async (span) => {
1797
- return await this._consoleInterceptor.intercept(console, async () => {
1798
- let parsedPayload;
1799
- let initOutput;
1800
- try {
1801
- const payloadPacket = await conditionallyImportPacket(originalPacket, this._tracer);
1802
- parsedPayload = await parsePacket(payloadPacket);
1803
- initOutput = await __privateMethod(this, _callTaskInit, callTaskInit_fn).call(this, parsedPayload, ctx);
1804
- const output = await __privateMethod(this, _callRun, callRun_fn).call(this, parsedPayload, ctx, initOutput);
1805
- try {
1806
- const stringifiedOutput = await stringifyIO(output);
1807
- const finalOutput = await conditionallyExportPacket(stringifiedOutput, `${execution.attempt.id}/output`, this._tracer);
1808
- const attributes = await createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE);
1809
- if (attributes) {
1810
- span.setAttributes(attributes);
1811
- }
1812
- return {
1813
- ok: true,
1814
- id: execution.run.id,
1815
- output: finalOutput.data,
1816
- outputType: finalOutput.dataType
1817
- };
1818
- } catch (stringifyError) {
1819
- recordSpanException(span, stringifyError);
1820
- return {
1821
- ok: false,
1822
- id: execution.run.id,
1823
- error: {
1824
- type: "INTERNAL_ERROR",
1825
- code: TaskRunErrorCodes.TASK_OUTPUT_ERROR,
1826
- message: stringifyError instanceof Error ? stringifyError.message : typeof stringifyError === "string" ? stringifyError : void 0
1827
- }
1828
- };
1829
- }
1830
- } catch (runError) {
1831
- try {
1832
- const handleErrorResult = await __privateMethod(this, _handleError, handleError_fn).call(this, execution, runError, parsedPayload, ctx);
1833
- recordSpanException(span, handleErrorResult.error ?? runError);
1834
- return {
1835
- id: execution.run.id,
1836
- ok: false,
1837
- error: handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError),
1838
- retry: handleErrorResult.status === "retry" ? handleErrorResult.retry : void 0,
1839
- skippedRetrying: handleErrorResult.status === "skipped"
1840
- };
1841
- } catch (handleErrorError) {
1842
- recordSpanException(span, handleErrorError);
1843
- return {
1844
- ok: false,
1845
- id: execution.run.id,
1846
- error: {
1847
- type: "INTERNAL_ERROR",
1848
- code: TaskRunErrorCodes.HANDLE_ERROR_ERROR,
1849
- message: handleErrorError instanceof Error ? handleErrorError.message : typeof handleErrorError === "string" ? handleErrorError : void 0
1850
- }
1851
- };
1852
- }
1853
- } finally {
1854
- await __privateMethod(this, _callTaskCleanup, callTaskCleanup_fn).call(this, parsedPayload, ctx, initOutput);
1855
- }
1856
- });
1857
- }, {
1858
- kind: api.SpanKind.CONSUMER,
1859
- attributes: {
1860
- [SemanticInternalAttributes.STYLE_ICON]: "attempt",
1861
- ...accessoryAttributes({
1862
- items: [
1863
- {
1864
- text: ctx.task.filePath
1865
- },
1866
- {
1867
- text: `${ctx.task.exportName}.run()`
1868
- }
1869
- ],
1870
- style: "codepath"
1871
- })
1872
- }
1873
- }, this._tracer.extractContext(traceContext));
1874
- });
1875
- return result;
1876
- }
1877
- };
1878
- _callRun = new WeakSet();
1879
- callRun_fn = /* @__PURE__ */ __name(async function(payload, ctx, init) {
1880
- const runFn = this.task.fns.run;
1881
- const middlewareFn = this.task.fns.middleware;
1882
- if (!runFn) {
1883
- throw new Error("Task does not have a run function");
1884
- }
1885
- if (!middlewareFn) {
1886
- return runFn(payload, {
1887
- ctx
1888
- });
1889
- }
1890
- return middlewareFn(payload, {
1891
- ctx,
1892
- next: async () => runFn(payload, {
1893
- ctx,
1894
- init
1895
- })
1896
- });
1897
- }, "#callRun");
1898
- _callTaskInit = new WeakSet();
1899
- callTaskInit_fn = /* @__PURE__ */ __name(async function(payload1, ctx1) {
1900
- const initFn = this.task.fns.init;
1901
- if (!initFn) {
1902
- return {};
1903
- }
1904
- return this._tracer.startActiveSpan("init", async (span) => {
1905
- return await initFn(payload1, {
1906
- ctx: ctx1
1907
- });
1908
- });
1909
- }, "#callTaskInit");
1910
- _callTaskCleanup = new WeakSet();
1911
- callTaskCleanup_fn = /* @__PURE__ */ __name(async function(payload2, ctx2, init1) {
1912
- const cleanupFn = this.task.fns.cleanup;
1913
- if (!cleanupFn) {
1914
- return;
1915
- }
1916
- return this._tracer.startActiveSpan("cleanup", async (span) => {
1917
- return await cleanupFn(payload2, {
1918
- ctx: ctx2,
1919
- init: init1
1920
- });
1921
- });
1922
- }, "#callTaskCleanup");
1923
- _handleError = new WeakSet();
1924
- handleError_fn = /* @__PURE__ */ __name(async function(execution, error, payload3, ctx3) {
1925
- const retriesConfig = this._importedConfig?.retries ?? this._config.retries;
1926
- const retry = this.task.retry ?? retriesConfig?.default;
1927
- if (!retry) {
1928
- return {
1929
- status: "noop"
1930
- };
1931
- }
1932
- const delay = calculateNextRetryDelay(retry, execution.attempt.number);
1933
- if (execution.environment.type === "DEVELOPMENT" && typeof retriesConfig?.enabledInDev === "boolean" && !retriesConfig.enabledInDev) {
1934
- return {
1935
- status: "skipped"
1936
- };
1937
- }
1938
- return this._tracer.startActiveSpan("handleError()", async (span) => {
1939
- const handleErrorResult = this.task.fns.handleError ? await this.task.fns.handleError(payload3, error, {
1940
- ctx: ctx3,
1941
- retry,
1942
- retryDelayInMs: delay,
1943
- retryAt: delay ? new Date(Date.now() + delay) : void 0
1944
- }) : this._importedConfig ? await this._handleErrorFn?.(payload3, error, {
1945
- ctx: ctx3,
1946
- retry,
1947
- retryDelayInMs: delay,
1948
- retryAt: delay ? new Date(Date.now() + delay) : void 0
1949
- }) : void 0;
1950
- if (!handleErrorResult) {
1951
- return typeof delay === "undefined" ? {
1952
- status: "noop"
1953
- } : {
1954
- status: "retry",
1955
- retry: {
1956
- timestamp: Date.now() + delay,
1957
- delay
1958
- }
1959
- };
1960
- }
1961
- if (handleErrorResult.skipRetrying) {
1962
- return {
1963
- status: "skipped",
1964
- error: handleErrorResult.error
1965
- };
1966
- }
1967
- if (typeof handleErrorResult.retryAt !== "undefined") {
1968
- return {
1969
- status: "retry",
1970
- retry: {
1971
- timestamp: handleErrorResult.retryAt.getTime(),
1972
- delay: handleErrorResult.retryAt.getTime() - Date.now()
1973
- },
1974
- error: handleErrorResult.error
1975
- };
1976
- }
1977
- if (typeof handleErrorResult.retryDelayInMs === "number") {
1978
- return {
1979
- status: "retry",
1980
- retry: {
1981
- timestamp: Date.now() + handleErrorResult.retryDelayInMs,
1982
- delay: handleErrorResult.retryDelayInMs
1983
- },
1984
- error: handleErrorResult.error
1985
- };
1986
- }
1987
- if (handleErrorResult.retry && typeof handleErrorResult.retry === "object") {
1988
- const delay2 = calculateNextRetryDelay(handleErrorResult.retry, execution.attempt.number);
1989
- return typeof delay2 === "undefined" ? {
1990
- status: "noop",
1991
- error: handleErrorResult.error
1992
- } : {
1993
- status: "retry",
1994
- retry: {
1995
- timestamp: Date.now() + delay2,
1996
- delay: delay2
1997
- },
1998
- error: handleErrorResult.error
1999
- };
2000
- }
2001
- return {
2002
- status: "noop",
2003
- error: handleErrorResult.error
2004
- };
2005
- }, {
2006
- attributes: {
2007
- [SemanticInternalAttributes.STYLE_ICON]: "exclamation-circle"
2008
- }
2009
- });
2010
- }, "#handleError");
2011
- __name(_TaskExecutor, "TaskExecutor");
2012
- var TaskExecutor = _TaskExecutor;
2013
- var _originClockTime, originClockTime_get, _originPreciseDate, originPreciseDate_get;
2014
- var _PreciseWallClock = class _PreciseWallClock {
2015
- constructor(options = {}) {
2016
- __privateAdd(this, _originClockTime);
2017
- __privateAdd(this, _originPreciseDate);
2018
- this._origin = {
2019
- clockTime: options.origin ?? process.hrtime(),
2020
- preciseDate: options.now ?? new preciseDate.PreciseDate()
2021
- };
2022
- }
2023
- preciseNow() {
2024
- const elapsedHrTime = process.hrtime(__privateGet(this, _originClockTime, originClockTime_get));
2025
- const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
2026
- const preciseDate$1 = new preciseDate.PreciseDate(__privateGet(this, _originPreciseDate, originPreciseDate_get).getFullTime() + elapsedNanoseconds);
2027
- const dateStruct = preciseDate$1.toStruct();
2028
- return [
2029
- dateStruct.seconds,
2030
- dateStruct.nanos
2031
- ];
2032
- }
2033
- reset() {
2034
- this._origin = {
2035
- clockTime: process.hrtime(),
2036
- preciseDate: new preciseDate.PreciseDate()
2037
- };
2038
- }
2039
- };
2040
- _originClockTime = new WeakSet();
2041
- originClockTime_get = /* @__PURE__ */ __name(function() {
2042
- return this._origin.clockTime;
2043
- }, "#originClockTime");
2044
- _originPreciseDate = new WeakSet();
2045
- originPreciseDate_get = /* @__PURE__ */ __name(function() {
2046
- return this._origin.preciseDate;
2047
- }, "#originPreciseDate");
2048
- __name(_PreciseWallClock, "PreciseWallClock");
2049
- var PreciseWallClock = _PreciseWallClock;
2050
-
2051
- exports.DurableClock = PreciseWallClock;
2052
- exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
2053
- exports.TaskExecutor = TaskExecutor;
2054
- exports.taskContextManager = taskContextManager;
2055
- //# sourceMappingURL=out.js.map
2056
- //# sourceMappingURL=index.js.map