@trigger.dev/core 3.0.0-beta.4 → 3.0.0-beta.40

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 (79) hide show
  1. package/dist/catalog-EP9DGAGm.d.ts +242 -0
  2. package/dist/catalog-Gjy5NtAB.d.mts +242 -0
  3. package/dist/index.d.mts +60 -1
  4. package/dist/index.d.ts +60 -1
  5. package/dist/index.js +7 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +7 -1
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/manager-S98VaLUy.d.mts +1402 -0
  10. package/dist/manager-S98VaLUy.d.ts +1402 -0
  11. package/dist/messages-xJbR1Vai.d.mts +18953 -0
  12. package/dist/messages-xJbR1Vai.d.ts +18953 -0
  13. package/dist/schemas-Sb0sJcEt.d.mts +2497 -0
  14. package/dist/schemas-Sb0sJcEt.d.ts +2497 -0
  15. package/dist/v3/dev/index.d.mts +28 -0
  16. package/dist/v3/dev/index.d.ts +28 -0
  17. package/dist/v3/dev/index.js +93 -0
  18. package/dist/v3/dev/index.js.map +1 -0
  19. package/dist/v3/dev/index.mjs +91 -0
  20. package/dist/v3/dev/index.mjs.map +1 -0
  21. package/dist/v3/index.d.mts +2140 -17560
  22. package/dist/v3/index.d.ts +2140 -17560
  23. package/dist/v3/index.js +2611 -2886
  24. package/dist/v3/index.js.map +1 -1
  25. package/dist/v3/index.mjs +2563 -2858
  26. package/dist/v3/index.mjs.map +1 -1
  27. package/dist/v3/otel/index.js +106 -50
  28. package/dist/v3/otel/index.js.map +1 -1
  29. package/dist/v3/otel/index.mjs +106 -50
  30. package/dist/v3/otel/index.mjs.map +1 -1
  31. package/dist/v3/prod/index.d.mts +45 -0
  32. package/dist/v3/prod/index.d.ts +45 -0
  33. package/dist/v3/prod/index.js +304 -0
  34. package/dist/v3/prod/index.js.map +1 -0
  35. package/dist/v3/prod/index.mjs +302 -0
  36. package/dist/v3/prod/index.mjs.map +1 -0
  37. package/dist/v3/utils/structuredLogger.d.mts +31 -0
  38. package/dist/v3/utils/structuredLogger.d.ts +31 -0
  39. package/dist/v3/utils/structuredLogger.js +88 -0
  40. package/dist/v3/utils/structuredLogger.js.map +1 -0
  41. package/dist/v3/utils/structuredLogger.mjs +86 -0
  42. package/dist/v3/utils/structuredLogger.mjs.map +1 -0
  43. package/dist/v3/workers/index.d.mts +142 -0
  44. package/dist/v3/workers/index.d.ts +142 -0
  45. package/dist/v3/workers/index.js +3485 -0
  46. package/dist/v3/workers/index.js.map +1 -0
  47. package/dist/v3/workers/index.mjs +3466 -0
  48. package/dist/v3/workers/index.mjs.map +1 -0
  49. package/dist/v3/zodIpc.d.mts +32 -0
  50. package/dist/v3/zodIpc.d.ts +32 -0
  51. package/dist/v3/zodIpc.js +268 -0
  52. package/dist/v3/zodIpc.js.map +1 -0
  53. package/dist/v3/zodIpc.mjs +266 -0
  54. package/dist/v3/zodIpc.mjs.map +1 -0
  55. package/dist/v3/zodMessageHandler.d.mts +69 -0
  56. package/dist/v3/zodMessageHandler.d.ts +69 -0
  57. package/dist/v3/zodMessageHandler.js +168 -0
  58. package/dist/v3/zodMessageHandler.js.map +1 -0
  59. package/dist/v3/zodMessageHandler.mjs +163 -0
  60. package/dist/v3/zodMessageHandler.mjs.map +1 -0
  61. package/dist/v3/zodNamespace.d.mts +3663 -0
  62. package/dist/v3/zodNamespace.d.ts +3663 -0
  63. package/dist/v3/zodNamespace.js +366 -0
  64. package/dist/v3/zodNamespace.js.map +1 -0
  65. package/dist/v3/zodNamespace.mjs +364 -0
  66. package/dist/v3/zodNamespace.mjs.map +1 -0
  67. package/dist/v3/zodSocket.d.mts +88 -0
  68. package/dist/v3/zodSocket.d.ts +88 -0
  69. package/dist/v3/zodSocket.js +319 -0
  70. package/dist/v3/zodSocket.js.map +1 -0
  71. package/dist/v3/zodSocket.mjs +315 -0
  72. package/dist/v3/zodSocket.mjs.map +1 -0
  73. package/dist/v3/zodfetch.d.mts +206 -0
  74. package/dist/v3/zodfetch.d.ts +206 -0
  75. package/dist/v3/zodfetch.js +614 -0
  76. package/dist/v3/zodfetch.js.map +1 -0
  77. package/dist/v3/zodfetch.mjs +594 -0
  78. package/dist/v3/zodfetch.mjs.map +1 -0
  79. package/package.json +79 -5
@@ -0,0 +1,3485 @@
1
+ 'use strict';
2
+
3
+ var api = require('@opentelemetry/api');
4
+ var zod = require('zod');
5
+ var apiLogs = require('@opentelemetry/api-logs');
6
+ var exporterLogsOtlpHttp = require('@opentelemetry/exporter-logs-otlp-http');
7
+ var exporterTraceOtlpHttp = require('@opentelemetry/exporter-trace-otlp-http');
8
+ var instrumentation = require('@opentelemetry/instrumentation');
9
+ var resources = require('@opentelemetry/resources');
10
+ var sdkLogs = require('@opentelemetry/sdk-logs');
11
+ var sdkTraceNode = require('@opentelemetry/sdk-trace-node');
12
+ var semanticConventions = require('@opentelemetry/semantic-conventions');
13
+ var zodValidationError = require('zod-validation-error');
14
+ var preciseDate = require('@google-cloud/precise-date');
15
+ var util = require('util');
16
+ var promises = require('timers/promises');
17
+
18
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
19
+
20
+ var util__default = /*#__PURE__*/_interopDefault(util);
21
+
22
+ var __defProp = Object.defineProperty;
23
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
24
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
25
+ var __publicField = (obj, key, value) => {
26
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
27
+ return value;
28
+ };
29
+ var __accessCheck = (obj, member, msg) => {
30
+ if (!member.has(obj))
31
+ throw TypeError("Cannot " + msg);
32
+ };
33
+ var __privateGet = (obj, member, getter) => {
34
+ __accessCheck(obj, member, "read from private field");
35
+ return getter ? getter.call(obj) : member.get(obj);
36
+ };
37
+ var __privateAdd = (obj, member, value) => {
38
+ if (member.has(obj))
39
+ throw TypeError("Cannot add the same private member more than once");
40
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
41
+ };
42
+ var __privateMethod = (obj, member, method) => {
43
+ __accessCheck(obj, member, "access private method");
44
+ return method;
45
+ };
46
+ function parseError(error) {
47
+ if (error instanceof Error) {
48
+ return {
49
+ type: "BUILT_IN_ERROR",
50
+ name: error.name,
51
+ message: error.message,
52
+ stackTrace: error.stack ?? ""
53
+ };
54
+ }
55
+ if (typeof error === "string") {
56
+ return {
57
+ type: "STRING_ERROR",
58
+ raw: error
59
+ };
60
+ }
61
+ try {
62
+ return {
63
+ type: "CUSTOM_ERROR",
64
+ raw: JSON.stringify(error)
65
+ };
66
+ } catch (e) {
67
+ return {
68
+ type: "CUSTOM_ERROR",
69
+ raw: String(error)
70
+ };
71
+ }
72
+ }
73
+ __name(parseError, "parseError");
74
+ var SerializedError = zod.z.object({
75
+ message: zod.z.string(),
76
+ name: zod.z.string().optional(),
77
+ stackTrace: zod.z.string().optional()
78
+ });
79
+
80
+ // src/v3/limits.ts
81
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
82
+ var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
83
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
84
+ var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
85
+ var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
86
+ var OTEL_LINK_COUNT_LIMIT = 2;
87
+ var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
88
+ var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
89
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
90
+
91
+ // src/v3/semanticInternalAttributes.ts
92
+ var SemanticInternalAttributes = {
93
+ ENVIRONMENT_ID: "ctx.environment.id",
94
+ ENVIRONMENT_TYPE: "ctx.environment.type",
95
+ ORGANIZATION_ID: "ctx.organization.id",
96
+ ORGANIZATION_SLUG: "ctx.organization.slug",
97
+ ORGANIZATION_NAME: "ctx.organization.name",
98
+ PROJECT_ID: "ctx.project.id",
99
+ PROJECT_REF: "ctx.project.ref",
100
+ PROJECT_NAME: "ctx.project.title",
101
+ PROJECT_DIR: "project.dir",
102
+ ATTEMPT_ID: "ctx.attempt.id",
103
+ ATTEMPT_NUMBER: "ctx.attempt.number",
104
+ RUN_ID: "ctx.run.id",
105
+ RUN_IS_TEST: "ctx.run.isTest",
106
+ BATCH_ID: "ctx.batch.id",
107
+ TASK_SLUG: "ctx.task.id",
108
+ TASK_PATH: "ctx.task.filePath",
109
+ TASK_EXPORT_NAME: "ctx.task.exportName",
110
+ QUEUE_NAME: "ctx.queue.name",
111
+ QUEUE_ID: "ctx.queue.id",
112
+ MACHINE_PRESET_NAME: "ctx.machine.name",
113
+ MACHINE_PRESET_CPU: "ctx.machine.cpu",
114
+ MACHINE_PRESET_MEMORY: "ctx.machine.memory",
115
+ MACHINE_PRESET_CENTS_PER_MS: "ctx.machine.centsPerMs",
116
+ SPAN_PARTIAL: "$span.partial",
117
+ SPAN_ID: "$span.span_id",
118
+ OUTPUT: "$output",
119
+ OUTPUT_TYPE: "$mime_type_output",
120
+ STYLE: "$style",
121
+ STYLE_ICON: "$style.icon",
122
+ STYLE_VARIANT: "$style.variant",
123
+ STYLE_ACCESSORY: "$style.accessory",
124
+ METADATA: "$metadata",
125
+ TRIGGER: "$trigger",
126
+ PAYLOAD: "$payload",
127
+ PAYLOAD_TYPE: "$mime_type_payload",
128
+ SHOW: "$show",
129
+ SHOW_ACTIONS: "$show.actions",
130
+ WORKER_ID: "worker.id",
131
+ WORKER_VERSION: "worker.version",
132
+ CLI_VERSION: "cli.version",
133
+ SDK_VERSION: "sdk.version",
134
+ SDK_LANGUAGE: "sdk.language",
135
+ RETRY_AT: "retry.at",
136
+ RETRY_DELAY: "retry.delay",
137
+ RETRY_COUNT: "retry.count",
138
+ LINK_TITLE: "$link.title",
139
+ IDEMPOTENCY_KEY: "ctx.run.idempotencyKey",
140
+ USAGE_DURATION_MS: "$usage.durationMs",
141
+ USAGE_COST_IN_CENTS: "$usage.costInCents"
142
+ };
143
+
144
+ // src/v3/utils/flattenAttributes.ts
145
+ var NULL_SENTINEL = "$@null((";
146
+ function flattenAttributes(obj, prefix) {
147
+ const result = {};
148
+ if (obj === void 0) {
149
+ return result;
150
+ }
151
+ if (obj === null) {
152
+ result[prefix || ""] = NULL_SENTINEL;
153
+ return result;
154
+ }
155
+ if (typeof obj === "string") {
156
+ result[prefix || ""] = obj;
157
+ return result;
158
+ }
159
+ if (typeof obj === "number") {
160
+ result[prefix || ""] = obj;
161
+ return result;
162
+ }
163
+ if (typeof obj === "boolean") {
164
+ result[prefix || ""] = obj;
165
+ return result;
166
+ }
167
+ for (const [key, value] of Object.entries(obj)) {
168
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${Array.isArray(obj) ? `[${key}]` : key}`;
169
+ if (Array.isArray(value)) {
170
+ for (let i = 0; i < value.length; i++) {
171
+ if (typeof value[i] === "object" && value[i] !== null) {
172
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
173
+ } else {
174
+ if (value[i] === null) {
175
+ result[`${newPrefix}.[${i}]`] = NULL_SENTINEL;
176
+ } else {
177
+ result[`${newPrefix}.[${i}]`] = value[i];
178
+ }
179
+ }
180
+ }
181
+ } else if (isRecord(value)) {
182
+ Object.assign(result, flattenAttributes(value, newPrefix));
183
+ } else {
184
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
185
+ result[newPrefix] = value;
186
+ } else if (value === null) {
187
+ result[newPrefix] = NULL_SENTINEL;
188
+ }
189
+ }
190
+ }
191
+ return result;
192
+ }
193
+ __name(flattenAttributes, "flattenAttributes");
194
+ function isRecord(value) {
195
+ return value !== null && typeof value === "object" && !Array.isArray(value);
196
+ }
197
+ __name(isRecord, "isRecord");
198
+
199
+ // src/v3/utils/platform.ts
200
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
201
+
202
+ // src/v3/utils/globals.ts
203
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
204
+ var _global = _globalThis;
205
+ function registerGlobal(type, instance, allowOverride = false) {
206
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
207
+ if (!allowOverride && api[type]) {
208
+ return false;
209
+ }
210
+ api[type] = instance;
211
+ return true;
212
+ }
213
+ __name(registerGlobal, "registerGlobal");
214
+ function getGlobal(type) {
215
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
216
+ }
217
+ __name(getGlobal, "getGlobal");
218
+ function unregisterGlobal(type) {
219
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
220
+ if (api) {
221
+ delete api[type];
222
+ }
223
+ }
224
+ __name(unregisterGlobal, "unregisterGlobal");
225
+
226
+ // src/v3/taskContext/index.ts
227
+ var API_NAME = "task-context";
228
+ var _getTaskContext, getTaskContext_fn;
229
+ var _TaskContextAPI = class _TaskContextAPI {
230
+ constructor() {
231
+ __privateAdd(this, _getTaskContext);
232
+ }
233
+ static getInstance() {
234
+ if (!this._instance) {
235
+ this._instance = new _TaskContextAPI();
236
+ }
237
+ return this._instance;
238
+ }
239
+ get isInsideTask() {
240
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
241
+ }
242
+ get ctx() {
243
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
244
+ }
245
+ get worker() {
246
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
247
+ }
248
+ get attributes() {
249
+ if (this.ctx) {
250
+ return {
251
+ ...this.contextAttributes,
252
+ ...this.workerAttributes
253
+ };
254
+ }
255
+ return {};
256
+ }
257
+ get workerAttributes() {
258
+ if (this.worker) {
259
+ return {
260
+ [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
261
+ [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
262
+ };
263
+ }
264
+ return {};
265
+ }
266
+ get contextAttributes() {
267
+ if (this.ctx) {
268
+ return {
269
+ [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
270
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
271
+ [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
272
+ [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
273
+ [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
274
+ [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
275
+ [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
276
+ [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
277
+ [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
278
+ [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
279
+ [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
280
+ [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
281
+ [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
282
+ [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
283
+ [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
284
+ [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
285
+ [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
286
+ [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
287
+ [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey,
288
+ [SemanticInternalAttributes.MACHINE_PRESET_NAME]: this.ctx.machine?.name,
289
+ [SemanticInternalAttributes.MACHINE_PRESET_CPU]: this.ctx.machine?.cpu,
290
+ [SemanticInternalAttributes.MACHINE_PRESET_MEMORY]: this.ctx.machine?.memory,
291
+ [SemanticInternalAttributes.MACHINE_PRESET_CENTS_PER_MS]: this.ctx.machine?.centsPerMs
292
+ };
293
+ }
294
+ return {};
295
+ }
296
+ disable() {
297
+ unregisterGlobal(API_NAME);
298
+ }
299
+ setGlobalTaskContext(taskContext2) {
300
+ return registerGlobal(API_NAME, taskContext2);
301
+ }
302
+ };
303
+ _getTaskContext = new WeakSet();
304
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
305
+ return getGlobal(API_NAME);
306
+ }, "#getTaskContext");
307
+ __name(_TaskContextAPI, "TaskContextAPI");
308
+ var TaskContextAPI = _TaskContextAPI;
309
+
310
+ // src/v3/task-context-api.ts
311
+ var taskContext = TaskContextAPI.getInstance();
312
+
313
+ // src/v3/taskContext/otelProcessors.ts
314
+ var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
315
+ constructor(innerProcessor) {
316
+ this._innerProcessor = innerProcessor;
317
+ }
318
+ // Called when a span starts
319
+ onStart(span, parentContext) {
320
+ if (taskContext.ctx) {
321
+ span.setAttributes(flattenAttributes({
322
+ [SemanticInternalAttributes.ATTEMPT_ID]: taskContext.ctx.attempt.id,
323
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContext.ctx.attempt.number
324
+ }, SemanticInternalAttributes.METADATA));
325
+ }
326
+ this._innerProcessor.onStart(span, parentContext);
327
+ }
328
+ // Delegate the rest of the methods to the wrapped processor
329
+ onEnd(span) {
330
+ this._innerProcessor.onEnd(span);
331
+ }
332
+ shutdown() {
333
+ return this._innerProcessor.shutdown();
334
+ }
335
+ forceFlush() {
336
+ return this._innerProcessor.forceFlush();
337
+ }
338
+ };
339
+ __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
340
+ var TaskContextSpanProcessor = _TaskContextSpanProcessor;
341
+ var _TaskContextLogProcessor = class _TaskContextLogProcessor {
342
+ constructor(innerProcessor) {
343
+ this._innerProcessor = innerProcessor;
344
+ }
345
+ forceFlush() {
346
+ return this._innerProcessor.forceFlush();
347
+ }
348
+ onEmit(logRecord, context2) {
349
+ if (taskContext.ctx) {
350
+ logRecord.setAttributes(flattenAttributes({
351
+ [SemanticInternalAttributes.ATTEMPT_ID]: taskContext.ctx.attempt.id,
352
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContext.ctx.attempt.number
353
+ }, SemanticInternalAttributes.METADATA));
354
+ }
355
+ this._innerProcessor.onEmit(logRecord, context2);
356
+ }
357
+ shutdown() {
358
+ return this._innerProcessor.shutdown();
359
+ }
360
+ };
361
+ __name(_TaskContextLogProcessor, "TaskContextLogProcessor");
362
+ var TaskContextLogProcessor = _TaskContextLogProcessor;
363
+
364
+ // src/v3/utils/getEnv.ts
365
+ function getEnvVar(name) {
366
+ if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
367
+ return process.env[name];
368
+ }
369
+ }
370
+ __name(getEnvVar, "getEnvVar");
371
+
372
+ // package.json
373
+ var version = "3.0.0-beta.40";
374
+
375
+ // src/v3/otel/tracingSDK.ts
376
+ var _a;
377
+ var AsyncResourceDetector = (_a = class {
378
+ constructor() {
379
+ __publicField(this, "_resolved", false);
380
+ this._promise = new Promise((resolver) => {
381
+ this._resolver = resolver;
382
+ });
383
+ }
384
+ detect(_config) {
385
+ return new resources.Resource({}, this._promise);
386
+ }
387
+ resolveWithAttributes(attributes) {
388
+ if (!this._resolver) {
389
+ throw new Error("Resolver not available");
390
+ }
391
+ if (this._resolved) {
392
+ return;
393
+ }
394
+ this._resolved = true;
395
+ this._resolver(attributes);
396
+ }
397
+ }, __name(_a, "AsyncResourceDetector"), _a);
398
+ var _TracingSDK = class _TracingSDK {
399
+ constructor(config) {
400
+ this.config = config;
401
+ this.asyncResourceDetector = new AsyncResourceDetector();
402
+ setLogLevel(config.diagLogLevel ?? "none");
403
+ const envResourceAttributesSerialized = getEnvVar("OTEL_RESOURCE_ATTRIBUTES");
404
+ const envResourceAttributes = envResourceAttributesSerialized ? JSON.parse(envResourceAttributesSerialized) : {};
405
+ const commonResources = resources.detectResourcesSync({
406
+ detectors: [
407
+ this.asyncResourceDetector,
408
+ resources.processDetectorSync
409
+ ]
410
+ }).merge(new resources.Resource({
411
+ [semanticConventions.SemanticResourceAttributes.CLOUD_PROVIDER]: "trigger.dev",
412
+ [SemanticInternalAttributes.TRIGGER]: true,
413
+ [SemanticInternalAttributes.CLI_VERSION]: version
414
+ })).merge(config.resource ?? new resources.Resource({})).merge(new resources.Resource(envResourceAttributes));
415
+ const traceProvider = new sdkTraceNode.NodeTracerProvider({
416
+ forceFlushTimeoutMillis: config.forceFlushTimeoutMillis,
417
+ resource: commonResources,
418
+ spanLimits: {
419
+ attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
420
+ attributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
421
+ eventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT,
422
+ attributePerEventCountLimit: OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
423
+ linkCountLimit: OTEL_LINK_COUNT_LIMIT,
424
+ attributePerLinkCountLimit: OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT
425
+ }
426
+ });
427
+ const spanExporter = new exporterTraceOtlpHttp.OTLPTraceExporter({
428
+ url: `${config.url}/v1/traces`,
429
+ timeoutMillis: config.forceFlushTimeoutMillis
430
+ });
431
+ traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkTraceNode.BatchSpanProcessor(spanExporter, {
432
+ maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
433
+ scheduledDelayMillis: parseInt(getEnvVar("OTEL_SPAN_SCHEDULED_DELAY_MILLIS") ?? "200"),
434
+ exportTimeoutMillis: parseInt(getEnvVar("OTEL_SPAN_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
435
+ maxQueueSize: parseInt(getEnvVar("OTEL_SPAN_MAX_QUEUE_SIZE") ?? "512")
436
+ }) : new sdkTraceNode.SimpleSpanProcessor(spanExporter)));
437
+ traceProvider.register();
438
+ instrumentation.registerInstrumentations({
439
+ instrumentations: config.instrumentations ?? [],
440
+ tracerProvider: traceProvider
441
+ });
442
+ const logExporter = new exporterLogsOtlpHttp.OTLPLogExporter({
443
+ url: `${config.url}/v1/logs`
444
+ });
445
+ const loggerProvider = new sdkLogs.LoggerProvider({
446
+ resource: commonResources,
447
+ logRecordLimits: {
448
+ attributeCountLimit: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
449
+ attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
450
+ }
451
+ });
452
+ loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkLogs.BatchLogRecordProcessor(logExporter, {
453
+ maxExportBatchSize: parseInt(getEnvVar("OTEL_LOG_MAX_EXPORT_BATCH_SIZE") ?? "64"),
454
+ scheduledDelayMillis: parseInt(getEnvVar("OTEL_LOG_SCHEDULED_DELAY_MILLIS") ?? "200"),
455
+ exportTimeoutMillis: parseInt(getEnvVar("OTEL_LOG_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
456
+ maxQueueSize: parseInt(getEnvVar("OTEL_LOG_MAX_QUEUE_SIZE") ?? "512")
457
+ }) : new sdkLogs.SimpleLogRecordProcessor(logExporter)));
458
+ this._logProvider = loggerProvider;
459
+ this._spanExporter = spanExporter;
460
+ this._traceProvider = traceProvider;
461
+ apiLogs.logs.setGlobalLoggerProvider(loggerProvider);
462
+ this.getLogger = loggerProvider.getLogger.bind(loggerProvider);
463
+ this.getTracer = traceProvider.getTracer.bind(traceProvider);
464
+ }
465
+ async flush() {
466
+ await Promise.all([
467
+ this._traceProvider.forceFlush(),
468
+ this._logProvider.forceFlush()
469
+ ]);
470
+ }
471
+ async shutdown() {
472
+ await Promise.all([
473
+ this._traceProvider.shutdown(),
474
+ this._logProvider.shutdown()
475
+ ]);
476
+ }
477
+ };
478
+ __name(_TracingSDK, "TracingSDK");
479
+ var TracingSDK = _TracingSDK;
480
+ function setLogLevel(level) {
481
+ let diagLogLevel;
482
+ switch (level) {
483
+ case "none":
484
+ diagLogLevel = api.DiagLogLevel.NONE;
485
+ break;
486
+ case "error":
487
+ diagLogLevel = api.DiagLogLevel.ERROR;
488
+ break;
489
+ case "warn":
490
+ diagLogLevel = api.DiagLogLevel.WARN;
491
+ break;
492
+ case "info":
493
+ diagLogLevel = api.DiagLogLevel.INFO;
494
+ break;
495
+ case "debug":
496
+ diagLogLevel = api.DiagLogLevel.DEBUG;
497
+ break;
498
+ case "verbose":
499
+ diagLogLevel = api.DiagLogLevel.VERBOSE;
500
+ break;
501
+ case "all":
502
+ diagLogLevel = api.DiagLogLevel.ALL;
503
+ break;
504
+ default:
505
+ diagLogLevel = api.DiagLogLevel.NONE;
506
+ }
507
+ api.diag.setLogger(new api.DiagConsoleLogger(), diagLogLevel);
508
+ }
509
+ __name(setLogLevel, "setLogLevel");
510
+
511
+ // src/v3/otel/index.ts
512
+ function recordSpanException(span, error) {
513
+ if (error instanceof Error) {
514
+ span.recordException(error);
515
+ } else if (typeof error === "string") {
516
+ span.recordException(new Error(error));
517
+ } else {
518
+ span.recordException(new Error(JSON.stringify(error)));
519
+ }
520
+ span.setStatus({
521
+ code: api.SpanStatusCode.ERROR
522
+ });
523
+ }
524
+ __name(recordSpanException, "recordSpanException");
525
+ var MachineCpu = zod.z.union([
526
+ zod.z.literal(0.25),
527
+ zod.z.literal(0.5),
528
+ zod.z.literal(1),
529
+ zod.z.literal(2),
530
+ zod.z.literal(4)
531
+ ]);
532
+ var MachineMemory = zod.z.union([
533
+ zod.z.literal(0.25),
534
+ zod.z.literal(0.5),
535
+ zod.z.literal(1),
536
+ zod.z.literal(2),
537
+ zod.z.literal(4),
538
+ zod.z.literal(8)
539
+ ]);
540
+ var MachinePresetName = zod.z.enum([
541
+ "micro",
542
+ "small-1x",
543
+ "small-2x",
544
+ "medium-1x",
545
+ "medium-2x",
546
+ "large-1x",
547
+ "large-2x"
548
+ ]);
549
+ var MachineConfig = zod.z.object({
550
+ cpu: MachineCpu.optional(),
551
+ memory: MachineMemory.optional(),
552
+ preset: MachinePresetName.optional()
553
+ });
554
+ var MachinePreset = zod.z.object({
555
+ name: MachinePresetName,
556
+ cpu: zod.z.number(),
557
+ memory: zod.z.number(),
558
+ centsPerMs: zod.z.number()
559
+ });
560
+ var TaskRunBuiltInError = zod.z.object({
561
+ type: zod.z.literal("BUILT_IN_ERROR"),
562
+ name: zod.z.string(),
563
+ message: zod.z.string(),
564
+ stackTrace: zod.z.string()
565
+ });
566
+ var TaskRunCustomErrorObject = zod.z.object({
567
+ type: zod.z.literal("CUSTOM_ERROR"),
568
+ raw: zod.z.string()
569
+ });
570
+ var TaskRunStringError = zod.z.object({
571
+ type: zod.z.literal("STRING_ERROR"),
572
+ raw: zod.z.string()
573
+ });
574
+ var TaskRunErrorCodes = {
575
+ COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
576
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
577
+ CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
578
+ TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
579
+ TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
580
+ TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
581
+ TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
582
+ TASK_PROCESS_SIGKILL_TIMEOUT: "TASK_PROCESS_SIGKILL_TIMEOUT",
583
+ TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
584
+ TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
585
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
586
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
587
+ };
588
+ var TaskRunInternalError = zod.z.object({
589
+ type: zod.z.literal("INTERNAL_ERROR"),
590
+ code: zod.z.enum([
591
+ "COULD_NOT_FIND_EXECUTOR",
592
+ "COULD_NOT_FIND_TASK",
593
+ "CONFIGURED_INCORRECTLY",
594
+ "TASK_ALREADY_RUNNING",
595
+ "TASK_EXECUTION_FAILED",
596
+ "TASK_EXECUTION_ABORTED",
597
+ "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
598
+ "TASK_PROCESS_SIGKILL_TIMEOUT",
599
+ "TASK_RUN_CANCELLED",
600
+ "TASK_OUTPUT_ERROR",
601
+ "HANDLE_ERROR_ERROR",
602
+ "GRACEFUL_EXIT_TIMEOUT",
603
+ "TASK_RUN_HEARTBEAT_TIMEOUT"
604
+ ]),
605
+ message: zod.z.string().optional()
606
+ });
607
+ var TaskRunError = zod.z.discriminatedUnion("type", [
608
+ TaskRunBuiltInError,
609
+ TaskRunCustomErrorObject,
610
+ TaskRunStringError,
611
+ TaskRunInternalError
612
+ ]);
613
+ var TaskRun = zod.z.object({
614
+ id: zod.z.string(),
615
+ payload: zod.z.string(),
616
+ payloadType: zod.z.string(),
617
+ context: zod.z.any(),
618
+ tags: zod.z.array(zod.z.string()),
619
+ isTest: zod.z.boolean().default(false),
620
+ createdAt: zod.z.coerce.date(),
621
+ startedAt: zod.z.coerce.date().default(() => /* @__PURE__ */ new Date()),
622
+ idempotencyKey: zod.z.string().optional(),
623
+ durationMs: zod.z.number().default(0),
624
+ costInCents: zod.z.number().default(0),
625
+ baseCostInCents: zod.z.number().default(0)
626
+ });
627
+ var TaskRunExecutionTask = zod.z.object({
628
+ id: zod.z.string(),
629
+ filePath: zod.z.string(),
630
+ exportName: zod.z.string()
631
+ });
632
+ var TaskRunExecutionAttempt = zod.z.object({
633
+ id: zod.z.string(),
634
+ number: zod.z.number(),
635
+ startedAt: zod.z.coerce.date(),
636
+ backgroundWorkerId: zod.z.string(),
637
+ backgroundWorkerTaskId: zod.z.string(),
638
+ status: zod.z.string()
639
+ });
640
+ var TaskRunExecutionEnvironment = zod.z.object({
641
+ id: zod.z.string(),
642
+ slug: zod.z.string(),
643
+ type: zod.z.enum([
644
+ "PRODUCTION",
645
+ "STAGING",
646
+ "DEVELOPMENT",
647
+ "PREVIEW"
648
+ ])
649
+ });
650
+ var TaskRunExecutionOrganization = zod.z.object({
651
+ id: zod.z.string(),
652
+ slug: zod.z.string(),
653
+ name: zod.z.string()
654
+ });
655
+ var TaskRunExecutionProject = zod.z.object({
656
+ id: zod.z.string(),
657
+ ref: zod.z.string(),
658
+ slug: zod.z.string(),
659
+ name: zod.z.string()
660
+ });
661
+ var TaskRunExecutionQueue = zod.z.object({
662
+ id: zod.z.string(),
663
+ name: zod.z.string()
664
+ });
665
+ var TaskRunExecutionBatch = zod.z.object({
666
+ id: zod.z.string()
667
+ });
668
+ var TaskRunExecution = zod.z.object({
669
+ task: TaskRunExecutionTask,
670
+ attempt: TaskRunExecutionAttempt,
671
+ run: TaskRun,
672
+ queue: TaskRunExecutionQueue,
673
+ environment: TaskRunExecutionEnvironment,
674
+ organization: TaskRunExecutionOrganization,
675
+ project: TaskRunExecutionProject,
676
+ batch: TaskRunExecutionBatch.optional(),
677
+ machine: MachinePreset.optional()
678
+ });
679
+ var TaskRunContext = zod.z.object({
680
+ task: TaskRunExecutionTask,
681
+ attempt: TaskRunExecutionAttempt.omit({
682
+ backgroundWorkerId: true,
683
+ backgroundWorkerTaskId: true
684
+ }),
685
+ run: TaskRun.omit({
686
+ payload: true,
687
+ payloadType: true
688
+ }),
689
+ queue: TaskRunExecutionQueue,
690
+ environment: TaskRunExecutionEnvironment,
691
+ organization: TaskRunExecutionOrganization,
692
+ project: TaskRunExecutionProject,
693
+ batch: TaskRunExecutionBatch.optional(),
694
+ machine: MachinePreset.optional()
695
+ });
696
+ var TaskRunExecutionRetry = zod.z.object({
697
+ timestamp: zod.z.number(),
698
+ delay: zod.z.number(),
699
+ error: zod.z.unknown().optional()
700
+ });
701
+ var TaskRunExecutionUsage = zod.z.object({
702
+ durationMs: zod.z.number()
703
+ });
704
+ var TaskRunFailedExecutionResult = zod.z.object({
705
+ ok: zod.z.literal(false),
706
+ id: zod.z.string(),
707
+ error: TaskRunError,
708
+ retry: TaskRunExecutionRetry.optional(),
709
+ skippedRetrying: zod.z.boolean().optional(),
710
+ usage: TaskRunExecutionUsage.optional()
711
+ });
712
+ var TaskRunSuccessfulExecutionResult = zod.z.object({
713
+ ok: zod.z.literal(true),
714
+ id: zod.z.string(),
715
+ output: zod.z.string().optional(),
716
+ outputType: zod.z.string(),
717
+ usage: TaskRunExecutionUsage.optional()
718
+ });
719
+ var TaskRunExecutionResult = zod.z.discriminatedUnion("ok", [
720
+ TaskRunSuccessfulExecutionResult,
721
+ TaskRunFailedExecutionResult
722
+ ]);
723
+ var BatchTaskRunExecutionResult = zod.z.object({
724
+ id: zod.z.string(),
725
+ items: TaskRunExecutionResult.array()
726
+ });
727
+
728
+ // src/v3/schemas/schemas.ts
729
+ zod.z.enum([
730
+ "PRODUCTION",
731
+ "STAGING",
732
+ "DEVELOPMENT",
733
+ "PREVIEW"
734
+ ]);
735
+ zod.z.object({
736
+ execution: TaskRunExecution,
737
+ traceContext: zod.z.record(zod.z.unknown()),
738
+ environment: zod.z.record(zod.z.string()).optional()
739
+ });
740
+ var ProdTaskRunExecution = TaskRunExecution.extend({
741
+ worker: zod.z.object({
742
+ id: zod.z.string(),
743
+ contentHash: zod.z.string(),
744
+ version: zod.z.string()
745
+ }),
746
+ machine: MachinePreset.default({
747
+ name: "small-1x",
748
+ cpu: 1,
749
+ memory: 1,
750
+ centsPerMs: 0
751
+ })
752
+ });
753
+ zod.z.object({
754
+ execution: ProdTaskRunExecution,
755
+ traceContext: zod.z.record(zod.z.unknown()),
756
+ environment: zod.z.record(zod.z.string()).optional()
757
+ });
758
+ var FixedWindowRateLimit = zod.z.object({
759
+ type: zod.z.literal("fixed-window"),
760
+ limit: zod.z.number(),
761
+ window: zod.z.union([
762
+ zod.z.object({
763
+ seconds: zod.z.number()
764
+ }),
765
+ zod.z.object({
766
+ minutes: zod.z.number()
767
+ }),
768
+ zod.z.object({
769
+ hours: zod.z.number()
770
+ })
771
+ ])
772
+ });
773
+ var SlidingWindowRateLimit = zod.z.object({
774
+ type: zod.z.literal("sliding-window"),
775
+ limit: zod.z.number(),
776
+ window: zod.z.union([
777
+ zod.z.object({
778
+ seconds: zod.z.number()
779
+ }),
780
+ zod.z.object({
781
+ minutes: zod.z.number()
782
+ }),
783
+ zod.z.object({
784
+ hours: zod.z.number()
785
+ })
786
+ ])
787
+ });
788
+ var RateLimitOptions = zod.z.discriminatedUnion("type", [
789
+ FixedWindowRateLimit,
790
+ SlidingWindowRateLimit
791
+ ]);
792
+ var RetryOptions = zod.z.object({
793
+ /** The number of attempts before giving up */
794
+ maxAttempts: zod.z.number().int().optional(),
795
+ /** The exponential factor to use when calculating the next retry time.
796
+ *
797
+ * Each subsequent retry will be calculated as `previousTimeout * factor`
798
+ */
799
+ factor: zod.z.number().optional(),
800
+ /** The minimum time to wait before retrying */
801
+ minTimeoutInMs: zod.z.number().int().optional(),
802
+ /** The maximum time to wait before retrying */
803
+ maxTimeoutInMs: zod.z.number().int().optional(),
804
+ /** Randomize the timeout between retries.
805
+ *
806
+ * This can be useful to prevent the thundering herd problem where all retries happen at the same time.
807
+ */
808
+ randomize: zod.z.boolean().optional()
809
+ });
810
+ var QueueOptions = zod.z.object({
811
+ /** You can define a shared queue and then pass the name in to your task.
812
+ *
813
+ * @example
814
+ *
815
+ * ```ts
816
+ * const myQueue = queue({
817
+ name: "my-queue",
818
+ concurrencyLimit: 1,
819
+ });
820
+
821
+ export const task1 = task({
822
+ id: "task-1",
823
+ queue: {
824
+ name: "my-queue",
825
+ },
826
+ run: async (payload: { message: string }) => {
827
+ // ...
828
+ },
829
+ });
830
+
831
+ export const task2 = task({
832
+ id: "task-2",
833
+ queue: {
834
+ name: "my-queue",
835
+ },
836
+ run: async (payload: { message: string }) => {
837
+ // ...
838
+ },
839
+ });
840
+ * ```
841
+ */
842
+ name: zod.z.string().optional(),
843
+ /** An optional property that specifies the maximum number of concurrent run executions.
844
+ *
845
+ * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
846
+ concurrencyLimit: zod.z.number().int().min(0).max(1e3).optional(),
847
+ /** @deprecated This feature is coming soon */
848
+ rateLimit: RateLimitOptions.optional()
849
+ });
850
+ zod.z.object({
851
+ id: zod.z.string(),
852
+ packageVersion: zod.z.string(),
853
+ queue: QueueOptions.optional(),
854
+ retry: RetryOptions.optional(),
855
+ machine: MachineConfig.optional(),
856
+ triggerSource: zod.z.string().optional()
857
+ });
858
+ zod.z.object({
859
+ filePath: zod.z.string(),
860
+ exportName: zod.z.string()
861
+ });
862
+ zod.z.object({
863
+ id: zod.z.string(),
864
+ packageVersion: zod.z.string(),
865
+ queue: QueueOptions.optional(),
866
+ retry: RetryOptions.optional(),
867
+ machine: MachineConfig.optional(),
868
+ triggerSource: zod.z.string().optional(),
869
+ filePath: zod.z.string(),
870
+ exportName: zod.z.string()
871
+ });
872
+ zod.z.enum([
873
+ "index",
874
+ "create",
875
+ "restore"
876
+ ]);
877
+ zod.z.enum([
878
+ "terminate"
879
+ ]);
880
+ var RegexSchema = zod.z.custom((val) => {
881
+ try {
882
+ return typeof val.test === "function";
883
+ } catch {
884
+ return false;
885
+ }
886
+ });
887
+ zod.z.object({
888
+ project: zod.z.string(),
889
+ triggerDirectories: zod.z.string().array().optional(),
890
+ triggerUrl: zod.z.string().optional(),
891
+ projectDir: zod.z.string().optional(),
892
+ tsconfigPath: zod.z.string().optional(),
893
+ retries: zod.z.object({
894
+ enabledInDev: zod.z.boolean().default(true),
895
+ default: RetryOptions.optional()
896
+ }).optional(),
897
+ additionalPackages: zod.z.string().array().optional(),
898
+ additionalFiles: zod.z.string().array().optional(),
899
+ dependenciesToBundle: zod.z.array(zod.z.union([
900
+ zod.z.string(),
901
+ RegexSchema
902
+ ])).optional(),
903
+ logLevel: zod.z.string().optional(),
904
+ enableConsoleLogging: zod.z.boolean().optional(),
905
+ postInstall: zod.z.string().optional()
906
+ });
907
+ zod.z.enum([
908
+ "WAIT_FOR_DURATION",
909
+ "WAIT_FOR_TASK",
910
+ "WAIT_FOR_BATCH"
911
+ ]);
912
+ zod.z.object({
913
+ runId: zod.z.string(),
914
+ messageId: zod.z.string(),
915
+ isTest: zod.z.boolean(),
916
+ traceContext: zod.z.record(zod.z.unknown()),
917
+ environment: zod.z.record(zod.z.string()).optional()
918
+ });
919
+
920
+ // src/v3/schemas/resources.ts
921
+ var TaskResource = zod.z.object({
922
+ id: zod.z.string(),
923
+ filePath: zod.z.string(),
924
+ exportName: zod.z.string(),
925
+ queue: QueueOptions.optional(),
926
+ retry: RetryOptions.optional(),
927
+ machine: MachineConfig.optional(),
928
+ triggerSource: zod.z.string().optional()
929
+ });
930
+ var BackgroundWorkerMetadata = zod.z.object({
931
+ packageVersion: zod.z.string(),
932
+ contentHash: zod.z.string(),
933
+ cliPackageVersion: zod.z.string().optional(),
934
+ tasks: zod.z.array(TaskResource)
935
+ });
936
+ zod.z.object({
937
+ contentHash: zod.z.string(),
938
+ imageTag: zod.z.string()
939
+ });
940
+
941
+ // src/v3/schemas/api.ts
942
+ zod.z.object({
943
+ userId: zod.z.string(),
944
+ email: zod.z.string().email(),
945
+ dashboardUrl: zod.z.string()
946
+ });
947
+ var GetProjectResponseBody = zod.z.object({
948
+ id: zod.z.string(),
949
+ externalRef: zod.z.string(),
950
+ name: zod.z.string(),
951
+ slug: zod.z.string(),
952
+ createdAt: zod.z.coerce.date(),
953
+ organization: zod.z.object({
954
+ id: zod.z.string(),
955
+ title: zod.z.string(),
956
+ slug: zod.z.string(),
957
+ createdAt: zod.z.coerce.date()
958
+ })
959
+ });
960
+ zod.z.array(GetProjectResponseBody);
961
+ zod.z.object({
962
+ apiKey: zod.z.string(),
963
+ name: zod.z.string(),
964
+ apiUrl: zod.z.string()
965
+ });
966
+ zod.z.object({
967
+ localOnly: zod.z.boolean(),
968
+ metadata: BackgroundWorkerMetadata,
969
+ supportsLazyAttempts: zod.z.boolean().optional()
970
+ });
971
+ zod.z.object({
972
+ id: zod.z.string(),
973
+ version: zod.z.string(),
974
+ contentHash: zod.z.string()
975
+ });
976
+ var TriggerTaskRequestBody = zod.z.object({
977
+ payload: zod.z.any(),
978
+ context: zod.z.any(),
979
+ options: zod.z.object({
980
+ dependentAttempt: zod.z.string().optional(),
981
+ dependentBatch: zod.z.string().optional(),
982
+ lockToVersion: zod.z.string().optional(),
983
+ queue: QueueOptions.optional(),
984
+ concurrencyKey: zod.z.string().optional(),
985
+ idempotencyKey: zod.z.string().optional(),
986
+ test: zod.z.boolean().optional(),
987
+ payloadType: zod.z.string().optional()
988
+ }).optional()
989
+ });
990
+ var TriggerTaskResponse = zod.z.object({
991
+ id: zod.z.string()
992
+ });
993
+ zod.z.object({
994
+ items: TriggerTaskRequestBody.array(),
995
+ dependentAttempt: zod.z.string().optional()
996
+ });
997
+ var BatchTriggerTaskResponse = zod.z.object({
998
+ batchId: zod.z.string(),
999
+ runs: zod.z.string().array()
1000
+ });
1001
+ zod.z.object({
1002
+ id: zod.z.string(),
1003
+ items: zod.z.array(zod.z.object({
1004
+ id: zod.z.string(),
1005
+ taskRunId: zod.z.string(),
1006
+ status: zod.z.enum([
1007
+ "PENDING",
1008
+ "CANCELED",
1009
+ "COMPLETED",
1010
+ "FAILED"
1011
+ ])
1012
+ }))
1013
+ });
1014
+ zod.z.object({
1015
+ variables: zod.z.record(zod.z.string())
1016
+ });
1017
+ zod.z.object({
1018
+ imageReference: zod.z.string(),
1019
+ selfHosted: zod.z.boolean().optional()
1020
+ });
1021
+ zod.z.object({
1022
+ id: zod.z.string(),
1023
+ contentHash: zod.z.string()
1024
+ });
1025
+ var ExternalBuildData = zod.z.object({
1026
+ buildId: zod.z.string(),
1027
+ buildToken: zod.z.string(),
1028
+ projectId: zod.z.string()
1029
+ });
1030
+ zod.z.object({
1031
+ id: zod.z.string(),
1032
+ contentHash: zod.z.string(),
1033
+ shortCode: zod.z.string(),
1034
+ version: zod.z.string(),
1035
+ imageTag: zod.z.string(),
1036
+ externalBuildData: ExternalBuildData.optional().nullable(),
1037
+ registryHost: zod.z.string().optional()
1038
+ });
1039
+ zod.z.object({
1040
+ contentHash: zod.z.string(),
1041
+ userId: zod.z.string().optional()
1042
+ });
1043
+ var DeploymentErrorData = zod.z.object({
1044
+ name: zod.z.string(),
1045
+ message: zod.z.string(),
1046
+ stack: zod.z.string().optional(),
1047
+ stderr: zod.z.string().optional()
1048
+ });
1049
+ zod.z.object({
1050
+ id: zod.z.string(),
1051
+ status: zod.z.enum([
1052
+ "PENDING",
1053
+ "BUILDING",
1054
+ "DEPLOYING",
1055
+ "DEPLOYED",
1056
+ "FAILED",
1057
+ "CANCELED",
1058
+ "TIMED_OUT"
1059
+ ]),
1060
+ contentHash: zod.z.string(),
1061
+ shortCode: zod.z.string(),
1062
+ version: zod.z.string(),
1063
+ imageReference: zod.z.string().optional(),
1064
+ errorData: DeploymentErrorData.optional().nullable(),
1065
+ worker: zod.z.object({
1066
+ id: zod.z.string(),
1067
+ version: zod.z.string(),
1068
+ tasks: zod.z.array(zod.z.object({
1069
+ id: zod.z.string(),
1070
+ slug: zod.z.string(),
1071
+ filePath: zod.z.string(),
1072
+ exportName: zod.z.string()
1073
+ }))
1074
+ }).optional()
1075
+ });
1076
+ var CreateUploadPayloadUrlResponseBody = zod.z.object({
1077
+ presignedUrl: zod.z.string()
1078
+ });
1079
+ var ReplayRunResponse = zod.z.object({
1080
+ id: zod.z.string()
1081
+ });
1082
+ var CanceledRunResponse = zod.z.object({
1083
+ id: zod.z.string()
1084
+ });
1085
+ zod.z.object({
1086
+ /** The schedule id associated with this run (you can have many schedules for the same task).
1087
+ You can use this to remove the schedule, update it, etc */
1088
+ scheduleId: zod.z.string(),
1089
+ /** When the task was scheduled to run.
1090
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task.
1091
+ *
1092
+ * This date is UTC. To output it as a string with a timezone you would do this:
1093
+ * ```ts
1094
+ * const formatted = payload.timestamp.toLocaleString("en-US", {
1095
+ timeZone: payload.timezone,
1096
+ });
1097
+ ``` */
1098
+ timestamp: zod.z.date(),
1099
+ /** When the task was last run (it has been).
1100
+ This can be undefined if it's never been run. This date is UTC. */
1101
+ lastTimestamp: zod.z.date().optional(),
1102
+ /** You can optionally provide an external id when creating the schedule.
1103
+ Usually you would use a userId or some other unique identifier.
1104
+ This defaults to undefined if you didn't provide one. */
1105
+ externalId: zod.z.string().optional(),
1106
+ /** The IANA timezone the schedule is set to. The default is UTC.
1107
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
1108
+ */
1109
+ timezone: zod.z.string(),
1110
+ /** The next 5 dates this task is scheduled to run */
1111
+ upcoming: zod.z.array(zod.z.date())
1112
+ });
1113
+ var CreateScheduleOptions = zod.z.object({
1114
+ /** The id of the task you want to attach to. */
1115
+ task: zod.z.string(),
1116
+ /** The schedule in CRON format.
1117
+ *
1118
+ * ```txt
1119
+ * * * * * *
1120
+ ┬ ┬ ┬ ┬ ┬
1121
+ │ │ │ │ |
1122
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
1123
+ │ │ │ └───── month (1 - 12)
1124
+ │ │ └────────── day of month (1 - 31, L)
1125
+ │ └─────────────── hour (0 - 23)
1126
+ └──────────────────── minute (0 - 59)
1127
+ * ```
1128
+
1129
+ "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.
1130
+
1131
+ */
1132
+ cron: zod.z.string(),
1133
+ /** You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1134
+ *
1135
+ * This is required to prevent you from creating duplicate schedules. */
1136
+ deduplicationKey: zod.z.string(),
1137
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
1138
+ *
1139
+ * This allows you to have per-user CRON tasks.
1140
+ */
1141
+ externalId: zod.z.string().optional(),
1142
+ /** Optionally, you can specify a timezone in the IANA format. If unset it will use UTC.
1143
+ * If specified then the CRON will be evaluated in that timezone and will respect daylight savings.
1144
+ *
1145
+ * If you set the CRON to `0 0 * * *` and the timezone to `America/New_York` then the task will run at midnight in New York time, no matter whether it's daylight savings or not.
1146
+ *
1147
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
1148
+ *
1149
+ * @example "America/New_York", "Europe/London", "Asia/Tokyo", "Africa/Cairo"
1150
+ *
1151
+ */
1152
+ timezone: zod.z.string().optional()
1153
+ });
1154
+ CreateScheduleOptions.omit({
1155
+ deduplicationKey: true
1156
+ });
1157
+ var ScheduleGenerator = zod.z.object({
1158
+ type: zod.z.literal("CRON"),
1159
+ expression: zod.z.string(),
1160
+ description: zod.z.string()
1161
+ });
1162
+ var ScheduleObject = zod.z.object({
1163
+ id: zod.z.string(),
1164
+ task: zod.z.string(),
1165
+ active: zod.z.boolean(),
1166
+ deduplicationKey: zod.z.string().nullish(),
1167
+ externalId: zod.z.string().nullish(),
1168
+ generator: ScheduleGenerator,
1169
+ timezone: zod.z.string(),
1170
+ nextRun: zod.z.coerce.date().nullish(),
1171
+ environments: zod.z.array(zod.z.object({
1172
+ id: zod.z.string(),
1173
+ type: zod.z.string(),
1174
+ userName: zod.z.string().nullish()
1175
+ }))
1176
+ });
1177
+ var DeletedScheduleObject = zod.z.object({
1178
+ id: zod.z.string()
1179
+ });
1180
+ zod.z.object({
1181
+ data: zod.z.array(ScheduleObject),
1182
+ pagination: zod.z.object({
1183
+ currentPage: zod.z.number(),
1184
+ totalPages: zod.z.number(),
1185
+ count: zod.z.number()
1186
+ })
1187
+ });
1188
+ zod.z.object({
1189
+ page: zod.z.number().optional(),
1190
+ perPage: zod.z.number().optional()
1191
+ });
1192
+ zod.z.object({
1193
+ timezones: zod.z.array(zod.z.string())
1194
+ });
1195
+ var RunStatus = zod.z.enum([
1196
+ /// Task hasn't been deployed yet but is waiting to be executed
1197
+ "WAITING_FOR_DEPLOY",
1198
+ /// Task is waiting to be executed by a worker
1199
+ "QUEUED",
1200
+ /// Task is currently being executed by a worker
1201
+ "EXECUTING",
1202
+ /// Task has failed and is waiting to be retried
1203
+ "REATTEMPTING",
1204
+ /// Task has been paused by the system, and will be resumed by the system
1205
+ "FROZEN",
1206
+ /// Task has been completed successfully
1207
+ "COMPLETED",
1208
+ /// Task has been canceled by the user
1209
+ "CANCELED",
1210
+ /// Task has been completed with errors
1211
+ "FAILED",
1212
+ /// Task has crashed and won't be retried, most likely the worker ran out of resources, e.g. memory or storage
1213
+ "CRASHED",
1214
+ /// Task was interrupted during execution, mostly this happens in development environments
1215
+ "INTERRUPTED",
1216
+ /// Task has failed to complete, due to an error in the system
1217
+ "SYSTEM_FAILURE"
1218
+ ]);
1219
+ var AttemptStatus = zod.z.enum([
1220
+ "PENDING",
1221
+ "EXECUTING",
1222
+ "PAUSED",
1223
+ "COMPLETED",
1224
+ "FAILED",
1225
+ "CANCELED"
1226
+ ]);
1227
+ var RunEnvironmentDetails = zod.z.object({
1228
+ id: zod.z.string(),
1229
+ name: zod.z.string(),
1230
+ user: zod.z.string().optional()
1231
+ });
1232
+ var RunScheduleDetails = zod.z.object({
1233
+ id: zod.z.string(),
1234
+ externalId: zod.z.string().optional(),
1235
+ deduplicationKey: zod.z.string().optional(),
1236
+ generator: ScheduleGenerator
1237
+ });
1238
+ var CommonRunFields = {
1239
+ id: zod.z.string(),
1240
+ status: RunStatus,
1241
+ taskIdentifier: zod.z.string(),
1242
+ idempotencyKey: zod.z.string().optional(),
1243
+ version: zod.z.string().optional(),
1244
+ isQueued: zod.z.boolean(),
1245
+ isExecuting: zod.z.boolean(),
1246
+ isCompleted: zod.z.boolean(),
1247
+ isSuccess: zod.z.boolean(),
1248
+ isFailed: zod.z.boolean(),
1249
+ isCancelled: zod.z.boolean(),
1250
+ isTest: zod.z.boolean(),
1251
+ createdAt: zod.z.coerce.date(),
1252
+ updatedAt: zod.z.coerce.date(),
1253
+ startedAt: zod.z.coerce.date().optional(),
1254
+ finishedAt: zod.z.coerce.date().optional()
1255
+ };
1256
+ var RetrieveRunResponse = zod.z.object({
1257
+ ...CommonRunFields,
1258
+ payload: zod.z.any().optional(),
1259
+ output: zod.z.any().optional(),
1260
+ schedule: RunScheduleDetails.optional(),
1261
+ attempts: zod.z.array(zod.z.object({
1262
+ id: zod.z.string(),
1263
+ status: AttemptStatus,
1264
+ createdAt: zod.z.coerce.date(),
1265
+ updatedAt: zod.z.coerce.date(),
1266
+ startedAt: zod.z.coerce.date().optional(),
1267
+ completedAt: zod.z.coerce.date().optional(),
1268
+ error: SerializedError.optional()
1269
+ }).optional())
1270
+ });
1271
+ var ListRunResponseItem = zod.z.object({
1272
+ ...CommonRunFields,
1273
+ env: RunEnvironmentDetails
1274
+ });
1275
+ zod.z.object({
1276
+ data: zod.z.array(ListRunResponseItem),
1277
+ pagination: zod.z.object({
1278
+ next: zod.z.string().optional(),
1279
+ previous: zod.z.string().optional()
1280
+ })
1281
+ });
1282
+ zod.z.object({
1283
+ name: zod.z.string(),
1284
+ value: zod.z.string()
1285
+ });
1286
+ zod.z.object({
1287
+ value: zod.z.string()
1288
+ });
1289
+ zod.z.object({
1290
+ variables: zod.z.record(zod.z.string()),
1291
+ override: zod.z.boolean().optional()
1292
+ });
1293
+ var EnvironmentVariableResponseBody = zod.z.object({
1294
+ success: zod.z.boolean()
1295
+ });
1296
+ var EnvironmentVariableValue = zod.z.object({
1297
+ value: zod.z.string()
1298
+ });
1299
+ var EnvironmentVariable = zod.z.object({
1300
+ name: zod.z.string(),
1301
+ value: zod.z.string()
1302
+ });
1303
+ var EnvironmentVariables = zod.z.array(EnvironmentVariable);
1304
+
1305
+ // src/v3/apiClient/errors.ts
1306
+ var _ApiError = class _ApiError extends Error {
1307
+ constructor(status, error, message, headers) {
1308
+ super(`${_ApiError.makeMessage(status, error, message)}`);
1309
+ this.status = status;
1310
+ this.headers = headers;
1311
+ const data = error;
1312
+ this.error = data;
1313
+ this.code = data?.["code"];
1314
+ this.param = data?.["param"];
1315
+ this.type = data?.["type"];
1316
+ }
1317
+ static makeMessage(status, error, message) {
1318
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1319
+ if (status && msg) {
1320
+ return `${status} ${msg}`;
1321
+ }
1322
+ if (status) {
1323
+ return `${status} status code (no body)`;
1324
+ }
1325
+ if (msg) {
1326
+ return msg;
1327
+ }
1328
+ return "(no status code or body)";
1329
+ }
1330
+ static generate(status, errorResponse, message, headers) {
1331
+ if (!status) {
1332
+ return new ApiConnectionError({
1333
+ cause: castToError(errorResponse)
1334
+ });
1335
+ }
1336
+ const error = errorResponse?.["error"];
1337
+ if (status === 400) {
1338
+ return new BadRequestError(status, error, message, headers);
1339
+ }
1340
+ if (status === 401) {
1341
+ return new AuthenticationError(status, error, message, headers);
1342
+ }
1343
+ if (status === 403) {
1344
+ return new PermissionDeniedError(status, error, message, headers);
1345
+ }
1346
+ if (status === 404) {
1347
+ return new NotFoundError(status, error, message, headers);
1348
+ }
1349
+ if (status === 409) {
1350
+ return new ConflictError(status, error, message, headers);
1351
+ }
1352
+ if (status === 422) {
1353
+ return new UnprocessableEntityError(status, error, message, headers);
1354
+ }
1355
+ if (status === 429) {
1356
+ return new RateLimitError(status, error, message, headers);
1357
+ }
1358
+ if (status >= 500) {
1359
+ return new InternalServerError(status, error, message, headers);
1360
+ }
1361
+ return new _ApiError(status, error, message, headers);
1362
+ }
1363
+ };
1364
+ __name(_ApiError, "ApiError");
1365
+ var ApiError = _ApiError;
1366
+ var _ApiConnectionError = class _ApiConnectionError extends ApiError {
1367
+ constructor({ message, cause }) {
1368
+ super(void 0, void 0, message || "Connection error.", void 0);
1369
+ __publicField(this, "status");
1370
+ if (cause)
1371
+ this.cause = cause;
1372
+ }
1373
+ };
1374
+ __name(_ApiConnectionError, "ApiConnectionError");
1375
+ var ApiConnectionError = _ApiConnectionError;
1376
+ var _BadRequestError = class _BadRequestError extends ApiError {
1377
+ constructor() {
1378
+ super(...arguments);
1379
+ __publicField(this, "status", 400);
1380
+ }
1381
+ };
1382
+ __name(_BadRequestError, "BadRequestError");
1383
+ var BadRequestError = _BadRequestError;
1384
+ var _AuthenticationError = class _AuthenticationError extends ApiError {
1385
+ constructor() {
1386
+ super(...arguments);
1387
+ __publicField(this, "status", 401);
1388
+ }
1389
+ };
1390
+ __name(_AuthenticationError, "AuthenticationError");
1391
+ var AuthenticationError = _AuthenticationError;
1392
+ var _PermissionDeniedError = class _PermissionDeniedError extends ApiError {
1393
+ constructor() {
1394
+ super(...arguments);
1395
+ __publicField(this, "status", 403);
1396
+ }
1397
+ };
1398
+ __name(_PermissionDeniedError, "PermissionDeniedError");
1399
+ var PermissionDeniedError = _PermissionDeniedError;
1400
+ var _NotFoundError = class _NotFoundError extends ApiError {
1401
+ constructor() {
1402
+ super(...arguments);
1403
+ __publicField(this, "status", 404);
1404
+ }
1405
+ };
1406
+ __name(_NotFoundError, "NotFoundError");
1407
+ var NotFoundError = _NotFoundError;
1408
+ var _ConflictError = class _ConflictError extends ApiError {
1409
+ constructor() {
1410
+ super(...arguments);
1411
+ __publicField(this, "status", 409);
1412
+ }
1413
+ };
1414
+ __name(_ConflictError, "ConflictError");
1415
+ var ConflictError = _ConflictError;
1416
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends ApiError {
1417
+ constructor() {
1418
+ super(...arguments);
1419
+ __publicField(this, "status", 422);
1420
+ }
1421
+ };
1422
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
1423
+ var UnprocessableEntityError = _UnprocessableEntityError;
1424
+ var _RateLimitError = class _RateLimitError extends ApiError {
1425
+ constructor() {
1426
+ super(...arguments);
1427
+ __publicField(this, "status", 429);
1428
+ }
1429
+ };
1430
+ __name(_RateLimitError, "RateLimitError");
1431
+ var RateLimitError = _RateLimitError;
1432
+ var _InternalServerError = class _InternalServerError extends ApiError {
1433
+ };
1434
+ __name(_InternalServerError, "InternalServerError");
1435
+ var InternalServerError = _InternalServerError;
1436
+ function castToError(err) {
1437
+ if (err instanceof Error)
1438
+ return err;
1439
+ return new Error(err);
1440
+ }
1441
+ __name(castToError, "castToError");
1442
+
1443
+ // src/v3/utils/retries.ts
1444
+ var defaultRetryOptions = {
1445
+ maxAttempts: 3,
1446
+ factor: 2,
1447
+ minTimeoutInMs: 1e3,
1448
+ maxTimeoutInMs: 6e4,
1449
+ randomize: true
1450
+ };
1451
+ function calculateNextRetryDelay(options, attempt) {
1452
+ const opts = {
1453
+ ...defaultRetryOptions,
1454
+ ...options
1455
+ };
1456
+ if (attempt >= opts.maxAttempts) {
1457
+ return;
1458
+ }
1459
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1460
+ const random = randomize ? Math.random() + 1 : 1;
1461
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1462
+ return Math.round(timeout);
1463
+ }
1464
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1465
+
1466
+ // src/v3/apiClient/pagination.ts
1467
+ var _CursorPage = class _CursorPage {
1468
+ constructor(data, pagination, pageFetcher) {
1469
+ this.pageFetcher = pageFetcher;
1470
+ this.data = data;
1471
+ this.pagination = pagination;
1472
+ }
1473
+ getPaginatedItems() {
1474
+ return this.data ?? [];
1475
+ }
1476
+ hasNextPage() {
1477
+ return !!this.pagination.next;
1478
+ }
1479
+ hasPreviousPage() {
1480
+ return !!this.pagination.previous;
1481
+ }
1482
+ getNextPage() {
1483
+ if (!this.pagination.next) {
1484
+ throw new Error("No next page available");
1485
+ }
1486
+ return this.pageFetcher({
1487
+ after: this.pagination.next
1488
+ });
1489
+ }
1490
+ getPreviousPage() {
1491
+ if (!this.pagination.previous) {
1492
+ throw new Error("No previous page available");
1493
+ }
1494
+ return this.pageFetcher({
1495
+ before: this.pagination.previous
1496
+ });
1497
+ }
1498
+ async *iterPages() {
1499
+ let page = this;
1500
+ yield page;
1501
+ while (page.hasNextPage()) {
1502
+ page = await page.getNextPage();
1503
+ yield page;
1504
+ }
1505
+ }
1506
+ async *[Symbol.asyncIterator]() {
1507
+ for await (const page of this.iterPages()) {
1508
+ for (const item of page.getPaginatedItems()) {
1509
+ yield item;
1510
+ }
1511
+ }
1512
+ }
1513
+ };
1514
+ __name(_CursorPage, "CursorPage");
1515
+ var CursorPage = _CursorPage;
1516
+ var _OffsetLimitPage = class _OffsetLimitPage {
1517
+ constructor(data, pagination, pageFetcher) {
1518
+ this.pageFetcher = pageFetcher;
1519
+ this.data = data;
1520
+ this.pagination = pagination;
1521
+ }
1522
+ getPaginatedItems() {
1523
+ return this.data ?? [];
1524
+ }
1525
+ hasNextPage() {
1526
+ return this.pagination.currentPage < this.pagination.totalPages;
1527
+ }
1528
+ hasPreviousPage() {
1529
+ return this.pagination.currentPage > 1;
1530
+ }
1531
+ getNextPage() {
1532
+ if (!this.hasNextPage()) {
1533
+ throw new Error("No next page available");
1534
+ }
1535
+ return this.pageFetcher({
1536
+ page: this.pagination.currentPage + 1
1537
+ });
1538
+ }
1539
+ getPreviousPage() {
1540
+ if (!this.hasPreviousPage()) {
1541
+ throw new Error("No previous page available");
1542
+ }
1543
+ return this.pageFetcher({
1544
+ page: this.pagination.currentPage - 1
1545
+ });
1546
+ }
1547
+ async *iterPages() {
1548
+ let page = this;
1549
+ yield page;
1550
+ while (page.hasNextPage()) {
1551
+ page = await page.getNextPage();
1552
+ yield page;
1553
+ }
1554
+ }
1555
+ async *[Symbol.asyncIterator]() {
1556
+ for await (const page of this.iterPages()) {
1557
+ for (const item of page.getPaginatedItems()) {
1558
+ yield item;
1559
+ }
1560
+ }
1561
+ }
1562
+ };
1563
+ __name(_OffsetLimitPage, "OffsetLimitPage");
1564
+ var OffsetLimitPage = _OffsetLimitPage;
1565
+
1566
+ // src/v3/apiClient/core.ts
1567
+ var defaultRetryOptions2 = {
1568
+ maxAttempts: 3,
1569
+ factor: 2,
1570
+ minTimeoutInMs: 1e3,
1571
+ maxTimeoutInMs: 6e4,
1572
+ randomize: false
1573
+ };
1574
+ function zodfetch(schema, url, requestInit, options) {
1575
+ return new ApiPromise(_doZodFetch(schema, url, requestInit, options));
1576
+ }
1577
+ __name(zodfetch, "zodfetch");
1578
+ function zodfetchCursorPage(schema, url, params, requestInit, options) {
1579
+ const query = new URLSearchParams(params.query);
1580
+ if (params.limit) {
1581
+ query.set("page[size]", String(params.limit));
1582
+ }
1583
+ if (params.after) {
1584
+ query.set("page[after]", params.after);
1585
+ }
1586
+ if (params.before) {
1587
+ query.set("page[before]", params.before);
1588
+ }
1589
+ const cursorPageSchema = zod.z.object({
1590
+ data: zod.z.array(schema),
1591
+ pagination: zod.z.object({
1592
+ next: zod.z.string().optional(),
1593
+ previous: zod.z.string().optional()
1594
+ })
1595
+ });
1596
+ const $url = new URL(url);
1597
+ $url.search = query.toString();
1598
+ const fetchResult = _doZodFetch(cursorPageSchema, $url.href, requestInit, options);
1599
+ return new CursorPagePromise(fetchResult, schema, url, params, requestInit, options);
1600
+ }
1601
+ __name(zodfetchCursorPage, "zodfetchCursorPage");
1602
+ function zodfetchOffsetLimitPage(schema, url, params, requestInit, options) {
1603
+ const query = new URLSearchParams(params.query);
1604
+ if (params.limit) {
1605
+ query.set("perPage", String(params.limit));
1606
+ }
1607
+ if (params.page) {
1608
+ query.set("page", String(params.page));
1609
+ }
1610
+ const offsetLimitPageSchema = zod.z.object({
1611
+ data: zod.z.array(schema),
1612
+ pagination: zod.z.object({
1613
+ currentPage: zod.z.coerce.number(),
1614
+ totalPages: zod.z.coerce.number(),
1615
+ count: zod.z.coerce.number()
1616
+ })
1617
+ });
1618
+ const $url = new URL(url);
1619
+ $url.search = query.toString();
1620
+ const fetchResult = _doZodFetch(offsetLimitPageSchema, $url.href, requestInit, options);
1621
+ return new OffsetLimitPagePromise(fetchResult, schema, url, params, requestInit, options);
1622
+ }
1623
+ __name(zodfetchOffsetLimitPage, "zodfetchOffsetLimitPage");
1624
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1625
+ try {
1626
+ const $requestInit = await requestInit;
1627
+ const response = await fetch(url, requestInitWithCache($requestInit));
1628
+ const responseHeaders = createResponseHeaders(response.headers);
1629
+ if (!response.ok) {
1630
+ const retryResult = shouldRetry(response, attempt, options?.retry);
1631
+ if (retryResult.retry) {
1632
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
1633
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1634
+ } else {
1635
+ const errText = await response.text().catch((e) => castToError2(e).message);
1636
+ const errJSON = safeJsonParse(errText);
1637
+ const errMessage = errJSON ? void 0 : errText;
1638
+ throw ApiError.generate(response.status, errJSON, errMessage, responseHeaders);
1639
+ }
1640
+ }
1641
+ const jsonBody = await response.json();
1642
+ const parsedResult = schema.safeParse(jsonBody);
1643
+ if (parsedResult.success) {
1644
+ return {
1645
+ data: parsedResult.data,
1646
+ response
1647
+ };
1648
+ }
1649
+ throw zodValidationError.fromZodError(parsedResult.error);
1650
+ } catch (error) {
1651
+ if (error instanceof ApiError) {
1652
+ throw error;
1653
+ }
1654
+ if (options?.retry) {
1655
+ const retry = {
1656
+ ...defaultRetryOptions2,
1657
+ ...options.retry
1658
+ };
1659
+ const delay = calculateNextRetryDelay(retry, attempt);
1660
+ if (delay) {
1661
+ await new Promise((resolve) => setTimeout(resolve, delay));
1662
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1663
+ }
1664
+ }
1665
+ throw new ApiConnectionError({
1666
+ cause: castToError2(error)
1667
+ });
1668
+ }
1669
+ }
1670
+ __name(_doZodFetch, "_doZodFetch");
1671
+ function castToError2(err) {
1672
+ if (err instanceof Error)
1673
+ return err;
1674
+ return new Error(err);
1675
+ }
1676
+ __name(castToError2, "castToError");
1677
+ function shouldRetry(response, attempt, retryOptions) {
1678
+ function shouldRetryForOptions() {
1679
+ const retry = {
1680
+ ...defaultRetryOptions2,
1681
+ ...retryOptions
1682
+ };
1683
+ const delay = calculateNextRetryDelay(retry, attempt);
1684
+ if (delay) {
1685
+ return {
1686
+ retry: true,
1687
+ delay
1688
+ };
1689
+ } else {
1690
+ return {
1691
+ retry: false
1692
+ };
1693
+ }
1694
+ }
1695
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
1696
+ const shouldRetryHeader = response.headers.get("x-should-retry");
1697
+ if (shouldRetryHeader === "true")
1698
+ return shouldRetryForOptions();
1699
+ if (shouldRetryHeader === "false")
1700
+ return {
1701
+ retry: false
1702
+ };
1703
+ if (response.status === 408)
1704
+ return shouldRetryForOptions();
1705
+ if (response.status === 409)
1706
+ return shouldRetryForOptions();
1707
+ if (response.status === 429)
1708
+ return shouldRetryForOptions();
1709
+ if (response.status >= 500)
1710
+ return shouldRetryForOptions();
1711
+ return {
1712
+ retry: false
1713
+ };
1714
+ }
1715
+ __name(shouldRetry, "shouldRetry");
1716
+ function safeJsonParse(text) {
1717
+ try {
1718
+ return JSON.parse(text);
1719
+ } catch (e) {
1720
+ return void 0;
1721
+ }
1722
+ }
1723
+ __name(safeJsonParse, "safeJsonParse");
1724
+ function createResponseHeaders(headers) {
1725
+ return new Proxy(Object.fromEntries(
1726
+ // @ts-ignore
1727
+ headers.entries()
1728
+ ), {
1729
+ get(target, name) {
1730
+ const key = name.toString();
1731
+ return target[key.toLowerCase()] || target[key];
1732
+ }
1733
+ });
1734
+ }
1735
+ __name(createResponseHeaders, "createResponseHeaders");
1736
+ function requestInitWithCache(requestInit) {
1737
+ try {
1738
+ const withCache = {
1739
+ ...requestInit,
1740
+ cache: "no-cache"
1741
+ };
1742
+ const _ = new Request("http://localhost", withCache);
1743
+ return withCache;
1744
+ } catch (error) {
1745
+ return requestInit ?? {};
1746
+ }
1747
+ }
1748
+ __name(requestInitWithCache, "requestInitWithCache");
1749
+ var _ApiPromise = class _ApiPromise extends Promise {
1750
+ constructor(responsePromise) {
1751
+ super((resolve) => {
1752
+ resolve(null);
1753
+ });
1754
+ this.responsePromise = responsePromise;
1755
+ }
1756
+ /**
1757
+ * Gets the raw `Response` instance instead of parsing the response
1758
+ * data.
1759
+ *
1760
+ * If you want to parse the response body but still get the `Response`
1761
+ * instance, you can use {@link withResponse()}.
1762
+ */
1763
+ asResponse() {
1764
+ return this.responsePromise.then((p) => p.response);
1765
+ }
1766
+ /**
1767
+ * Gets the parsed response data and the raw `Response` instance.
1768
+ *
1769
+ * If you just want to get the raw `Response` instance without parsing it,
1770
+ * you can use {@link asResponse()}.
1771
+ */
1772
+ async withResponse() {
1773
+ const [data, response] = await Promise.all([
1774
+ this.parse(),
1775
+ this.asResponse()
1776
+ ]);
1777
+ return {
1778
+ data,
1779
+ response
1780
+ };
1781
+ }
1782
+ parse() {
1783
+ return this.responsePromise.then((result) => result.data);
1784
+ }
1785
+ then(onfulfilled, onrejected) {
1786
+ return this.parse().then(onfulfilled, onrejected);
1787
+ }
1788
+ catch(onrejected) {
1789
+ return this.parse().catch(onrejected);
1790
+ }
1791
+ finally(onfinally) {
1792
+ return this.parse().finally(onfinally);
1793
+ }
1794
+ };
1795
+ __name(_ApiPromise, "ApiPromise");
1796
+ var ApiPromise = _ApiPromise;
1797
+ var _fetchPage, fetchPage_fn;
1798
+ var _CursorPagePromise = class _CursorPagePromise extends ApiPromise {
1799
+ constructor(result, schema, url, params, requestInit, options) {
1800
+ super(result.then((result2) => ({
1801
+ data: new CursorPage(result2.data.data, result2.data.pagination, __privateMethod(this, _fetchPage, fetchPage_fn).bind(this)),
1802
+ response: result2.response
1803
+ })));
1804
+ __privateAdd(this, _fetchPage);
1805
+ this.schema = schema;
1806
+ this.url = url;
1807
+ this.params = params;
1808
+ this.requestInit = requestInit;
1809
+ this.options = options;
1810
+ }
1811
+ /**
1812
+ * Allow auto-paginating iteration on an unawaited list call, eg:
1813
+ *
1814
+ * for await (const item of client.items.list()) {
1815
+ * console.log(item)
1816
+ * }
1817
+ */
1818
+ async *[Symbol.asyncIterator]() {
1819
+ const page = await this;
1820
+ for await (const item of page) {
1821
+ yield item;
1822
+ }
1823
+ }
1824
+ };
1825
+ _fetchPage = new WeakSet();
1826
+ fetchPage_fn = /* @__PURE__ */ __name(function(params) {
1827
+ return zodfetchCursorPage(this.schema, this.url, {
1828
+ ...this.params,
1829
+ ...params
1830
+ }, this.requestInit, this.options);
1831
+ }, "#fetchPage");
1832
+ __name(_CursorPagePromise, "CursorPagePromise");
1833
+ var CursorPagePromise = _CursorPagePromise;
1834
+ var _fetchPage2, fetchPage_fn2;
1835
+ var _OffsetLimitPagePromise = class _OffsetLimitPagePromise extends ApiPromise {
1836
+ constructor(result, schema, url, params, requestInit, options) {
1837
+ super(result.then((result2) => ({
1838
+ data: new OffsetLimitPage(result2.data.data, result2.data.pagination, __privateMethod(this, _fetchPage2, fetchPage_fn2).bind(this)),
1839
+ response: result2.response
1840
+ })));
1841
+ __privateAdd(this, _fetchPage2);
1842
+ this.schema = schema;
1843
+ this.url = url;
1844
+ this.params = params;
1845
+ this.requestInit = requestInit;
1846
+ this.options = options;
1847
+ }
1848
+ /**
1849
+ * Allow auto-paginating iteration on an unawaited list call, eg:
1850
+ *
1851
+ * for await (const item of client.items.list()) {
1852
+ * console.log(item)
1853
+ * }
1854
+ */
1855
+ async *[Symbol.asyncIterator]() {
1856
+ const page = await this;
1857
+ for await (const item of page) {
1858
+ yield item;
1859
+ }
1860
+ }
1861
+ };
1862
+ _fetchPage2 = new WeakSet();
1863
+ fetchPage_fn2 = /* @__PURE__ */ __name(function(params1) {
1864
+ return zodfetchOffsetLimitPage(this.schema, this.url, {
1865
+ ...this.params,
1866
+ ...params1
1867
+ }, this.requestInit, this.options);
1868
+ }, "#fetchPage");
1869
+ __name(_OffsetLimitPagePromise, "OffsetLimitPagePromise");
1870
+ var OffsetLimitPagePromise = _OffsetLimitPagePromise;
1871
+
1872
+ // src/v3/apiClient/index.ts
1873
+ var zodFetchOptions = {
1874
+ retry: {
1875
+ maxAttempts: 3,
1876
+ minTimeoutInMs: 1e3,
1877
+ maxTimeoutInMs: 3e4,
1878
+ factor: 2,
1879
+ randomize: false
1880
+ }
1881
+ };
1882
+ var _getHeaders, getHeaders_fn;
1883
+ var _ApiClient = class _ApiClient {
1884
+ constructor(baseUrl, accessToken) {
1885
+ __privateAdd(this, _getHeaders);
1886
+ this.accessToken = accessToken;
1887
+ this.baseUrl = baseUrl.replace(/\/$/, "");
1888
+ }
1889
+ async getRunResult(runId) {
1890
+ try {
1891
+ return await zodfetch(TaskRunExecutionResult, `${this.baseUrl}/api/v1/runs/${runId}/result`, {
1892
+ method: "GET",
1893
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1894
+ }, zodFetchOptions);
1895
+ } catch (error) {
1896
+ if (error instanceof ApiError) {
1897
+ if (error.status === 404) {
1898
+ return void 0;
1899
+ }
1900
+ }
1901
+ throw error;
1902
+ }
1903
+ }
1904
+ async getBatchResults(batchId) {
1905
+ return await zodfetch(BatchTaskRunExecutionResult, `${this.baseUrl}/api/v1/batches/${batchId}/results`, {
1906
+ method: "GET",
1907
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1908
+ }, zodFetchOptions);
1909
+ }
1910
+ triggerTask(taskId, body, options) {
1911
+ const encodedTaskId = encodeURIComponent(taskId);
1912
+ return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/trigger`, {
1913
+ method: "POST",
1914
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1915
+ body: JSON.stringify(body)
1916
+ }, zodFetchOptions);
1917
+ }
1918
+ batchTriggerTask(taskId, body, options) {
1919
+ const encodedTaskId = encodeURIComponent(taskId);
1920
+ return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/batch`, {
1921
+ method: "POST",
1922
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1923
+ body: JSON.stringify(body)
1924
+ }, zodFetchOptions);
1925
+ }
1926
+ createUploadPayloadUrl(filename) {
1927
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1928
+ method: "PUT",
1929
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1930
+ }, zodFetchOptions);
1931
+ }
1932
+ getPayloadUrl(filename) {
1933
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1934
+ method: "GET",
1935
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1936
+ }, zodFetchOptions);
1937
+ }
1938
+ retrieveRun(runId) {
1939
+ return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v3/runs/${runId}`, {
1940
+ method: "GET",
1941
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1942
+ }, zodFetchOptions);
1943
+ }
1944
+ listRuns(query) {
1945
+ const searchParams = createSearchQueryForListRuns(query);
1946
+ return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/runs`, {
1947
+ query: searchParams,
1948
+ limit: query?.limit,
1949
+ after: query?.after,
1950
+ before: query?.before
1951
+ }, {
1952
+ method: "GET",
1953
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1954
+ }, zodFetchOptions);
1955
+ }
1956
+ listProjectRuns(projectRef, query) {
1957
+ const searchParams = createSearchQueryForListRuns(query);
1958
+ if (query?.env) {
1959
+ searchParams.append("filter[env]", Array.isArray(query.env) ? query.env.join(",") : query.env);
1960
+ }
1961
+ return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/projects/${projectRef}/runs`, {
1962
+ query: searchParams,
1963
+ limit: query?.limit,
1964
+ after: query?.after,
1965
+ before: query?.before
1966
+ }, {
1967
+ method: "GET",
1968
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1969
+ }, zodFetchOptions);
1970
+ }
1971
+ replayRun(runId) {
1972
+ return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
1973
+ method: "POST",
1974
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1975
+ }, zodFetchOptions);
1976
+ }
1977
+ cancelRun(runId) {
1978
+ return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
1979
+ method: "POST",
1980
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1981
+ }, zodFetchOptions);
1982
+ }
1983
+ createSchedule(options) {
1984
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
1985
+ method: "POST",
1986
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
1987
+ body: JSON.stringify(options)
1988
+ });
1989
+ }
1990
+ listSchedules(options) {
1991
+ const searchParams = new URLSearchParams();
1992
+ if (options?.page) {
1993
+ searchParams.append("page", options.page.toString());
1994
+ }
1995
+ if (options?.perPage) {
1996
+ searchParams.append("perPage", options.perPage.toString());
1997
+ }
1998
+ return zodfetchOffsetLimitPage(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
1999
+ page: options?.page,
2000
+ limit: options?.perPage
2001
+ }, {
2002
+ method: "GET",
2003
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2004
+ });
2005
+ }
2006
+ retrieveSchedule(scheduleId) {
2007
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2008
+ method: "GET",
2009
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2010
+ });
2011
+ }
2012
+ updateSchedule(scheduleId, options) {
2013
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2014
+ method: "PUT",
2015
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2016
+ body: JSON.stringify(options)
2017
+ });
2018
+ }
2019
+ deactivateSchedule(scheduleId) {
2020
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
2021
+ method: "POST",
2022
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2023
+ });
2024
+ }
2025
+ activateSchedule(scheduleId) {
2026
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
2027
+ method: "POST",
2028
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2029
+ });
2030
+ }
2031
+ deleteSchedule(scheduleId) {
2032
+ return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2033
+ method: "DELETE",
2034
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2035
+ });
2036
+ }
2037
+ listEnvVars(projectRef, slug) {
2038
+ return zodfetch(EnvironmentVariables, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2039
+ method: "GET",
2040
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2041
+ });
2042
+ }
2043
+ importEnvVars(projectRef, slug, body) {
2044
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
2045
+ method: "POST",
2046
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2047
+ body: JSON.stringify(body)
2048
+ });
2049
+ }
2050
+ retrieveEnvVar(projectRef, slug, key) {
2051
+ return zodfetch(EnvironmentVariableValue, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2052
+ method: "GET",
2053
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2054
+ });
2055
+ }
2056
+ createEnvVar(projectRef, slug, body) {
2057
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2058
+ method: "POST",
2059
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2060
+ body: JSON.stringify(body)
2061
+ });
2062
+ }
2063
+ updateEnvVar(projectRef, slug, key, body) {
2064
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2065
+ method: "PUT",
2066
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2067
+ body: JSON.stringify(body)
2068
+ });
2069
+ }
2070
+ deleteEnvVar(projectRef, slug, key) {
2071
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2072
+ method: "DELETE",
2073
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2074
+ });
2075
+ }
2076
+ };
2077
+ _getHeaders = new WeakSet();
2078
+ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2079
+ const headers = {
2080
+ "Content-Type": "application/json",
2081
+ Authorization: `Bearer ${this.accessToken}`,
2082
+ "trigger-version": version
2083
+ };
2084
+ if (taskContext.isInsideTask) {
2085
+ headers["x-trigger-worker"] = "true";
2086
+ api.propagation.inject(api.context.active(), headers);
2087
+ if (spanParentAsLink) {
2088
+ headers["x-trigger-span-parent-as-link"] = "1";
2089
+ }
2090
+ }
2091
+ return headers;
2092
+ }, "#getHeaders");
2093
+ __name(_ApiClient, "ApiClient");
2094
+ var ApiClient = _ApiClient;
2095
+ function createSearchQueryForListRuns(query) {
2096
+ const searchParams = new URLSearchParams();
2097
+ if (query) {
2098
+ if (query.status) {
2099
+ searchParams.append("filter[status]", Array.isArray(query.status) ? query.status.join(",") : query.status);
2100
+ }
2101
+ if (query.taskIdentifier) {
2102
+ searchParams.append("filter[taskIdentifier]", Array.isArray(query.taskIdentifier) ? query.taskIdentifier.join(",") : query.taskIdentifier);
2103
+ }
2104
+ if (query.version) {
2105
+ searchParams.append("filter[version]", Array.isArray(query.version) ? query.version.join(",") : query.version);
2106
+ }
2107
+ if (query.bulkAction) {
2108
+ searchParams.append("filter[bulkAction]", query.bulkAction);
2109
+ }
2110
+ if (query.schedule) {
2111
+ searchParams.append("filter[schedule]", query.schedule);
2112
+ }
2113
+ if (typeof query.isTest === "boolean") {
2114
+ searchParams.append("filter[isTest]", String(query.isTest));
2115
+ }
2116
+ if (query.from) {
2117
+ searchParams.append("filter[createdAt][from]", query.from instanceof Date ? query.from.getTime().toString() : query.from.toString());
2118
+ }
2119
+ if (query.to) {
2120
+ searchParams.append("filter[createdAt][to]", query.to instanceof Date ? query.to.getTime().toString() : query.to.toString());
2121
+ }
2122
+ if (query.period) {
2123
+ searchParams.append("filter[createdAt][period]", query.period);
2124
+ }
2125
+ }
2126
+ return searchParams;
2127
+ }
2128
+ __name(createSearchQueryForListRuns, "createSearchQueryForListRuns");
2129
+
2130
+ // src/v3/apiClientManager/index.ts
2131
+ var API_NAME2 = "api-client";
2132
+ var _getConfig, getConfig_fn;
2133
+ var _APIClientManagerAPI = class _APIClientManagerAPI {
2134
+ constructor() {
2135
+ __privateAdd(this, _getConfig);
2136
+ }
2137
+ static getInstance() {
2138
+ if (!this._instance) {
2139
+ this._instance = new _APIClientManagerAPI();
2140
+ }
2141
+ return this._instance;
2142
+ }
2143
+ disable() {
2144
+ unregisterGlobal(API_NAME2);
2145
+ }
2146
+ setGlobalAPIClientConfiguration(config) {
2147
+ return registerGlobal(API_NAME2, config);
2148
+ }
2149
+ get baseURL() {
2150
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
2151
+ return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
2152
+ }
2153
+ get accessToken() {
2154
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
2155
+ return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY") ?? getEnvVar("TRIGGER_ACCESS_TOKEN");
2156
+ }
2157
+ get client() {
2158
+ if (!this.baseURL || !this.accessToken) {
2159
+ return void 0;
2160
+ }
2161
+ return new ApiClient(this.baseURL, this.accessToken);
2162
+ }
2163
+ };
2164
+ _getConfig = new WeakSet();
2165
+ getConfig_fn = /* @__PURE__ */ __name(function() {
2166
+ return getGlobal(API_NAME2);
2167
+ }, "#getConfig");
2168
+ __name(_APIClientManagerAPI, "APIClientManagerAPI");
2169
+ var APIClientManagerAPI = _APIClientManagerAPI;
2170
+
2171
+ // src/v3/apiClientManager-api.ts
2172
+ var apiClientManager = APIClientManagerAPI.getInstance();
2173
+
2174
+ // src/v3/utils/ioSerialization.ts
2175
+ async function parsePacket(value) {
2176
+ if (!value.data) {
2177
+ return void 0;
2178
+ }
2179
+ switch (value.dataType) {
2180
+ case "application/json":
2181
+ return JSON.parse(value.data);
2182
+ case "application/super+json":
2183
+ const { parse } = await loadSuperJSON();
2184
+ return parse(value.data);
2185
+ case "text/plain":
2186
+ return value.data;
2187
+ case "application/store":
2188
+ throw new Error(`Cannot parse an application/store packet (${value.data}). Needs to be imported first.`);
2189
+ default:
2190
+ return value.data;
2191
+ }
2192
+ }
2193
+ __name(parsePacket, "parsePacket");
2194
+ async function stringifyIO(value) {
2195
+ if (value === void 0) {
2196
+ return {
2197
+ dataType: "application/json"
2198
+ };
2199
+ }
2200
+ if (typeof value === "string") {
2201
+ return {
2202
+ data: value,
2203
+ dataType: "text/plain"
2204
+ };
2205
+ }
2206
+ try {
2207
+ const { stringify } = await loadSuperJSON();
2208
+ const data = stringify(value);
2209
+ return {
2210
+ data,
2211
+ dataType: "application/super+json"
2212
+ };
2213
+ } catch {
2214
+ return {
2215
+ data: value,
2216
+ dataType: "application/json"
2217
+ };
2218
+ }
2219
+ }
2220
+ __name(stringifyIO, "stringifyIO");
2221
+ async function conditionallyExportPacket(packet, pathPrefix, tracer) {
2222
+ if (apiClientManager.client) {
2223
+ const { needsOffloading, size } = packetRequiresOffloading(packet);
2224
+ if (needsOffloading) {
2225
+ if (!tracer) {
2226
+ return await exportPacket(packet, pathPrefix);
2227
+ } else {
2228
+ const result = await tracer.startActiveSpan("store.uploadOutput", async (span) => {
2229
+ return await exportPacket(packet, pathPrefix);
2230
+ }, {
2231
+ attributes: {
2232
+ byteLength: size,
2233
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-upload"
2234
+ }
2235
+ });
2236
+ return result ?? packet;
2237
+ }
2238
+ }
2239
+ }
2240
+ return packet;
2241
+ }
2242
+ __name(conditionallyExportPacket, "conditionallyExportPacket");
2243
+ function packetRequiresOffloading(packet) {
2244
+ if (!packet.data) {
2245
+ return {
2246
+ needsOffloading: false,
2247
+ size: 0
2248
+ };
2249
+ }
2250
+ const byteSize = Buffer.byteLength(packet.data, "utf8");
2251
+ return {
2252
+ needsOffloading: byteSize >= OFFLOAD_IO_PACKET_LENGTH_LIMIT,
2253
+ size: byteSize
2254
+ };
2255
+ }
2256
+ __name(packetRequiresOffloading, "packetRequiresOffloading");
2257
+ async function exportPacket(packet, pathPrefix) {
2258
+ const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
2259
+ const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
2260
+ const uploadResponse = await fetch(presignedResponse.presignedUrl, {
2261
+ method: "PUT",
2262
+ headers: {
2263
+ "Content-Type": packet.dataType
2264
+ },
2265
+ body: packet.data
2266
+ });
2267
+ if (!uploadResponse.ok) {
2268
+ throw new Error(`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`);
2269
+ }
2270
+ return {
2271
+ data: filename,
2272
+ dataType: "application/store"
2273
+ };
2274
+ }
2275
+ __name(exportPacket, "exportPacket");
2276
+ async function conditionallyImportPacket(packet, tracer) {
2277
+ if (packet.dataType !== "application/store") {
2278
+ return packet;
2279
+ }
2280
+ if (!tracer) {
2281
+ return await importPacket(packet);
2282
+ } else {
2283
+ const result = await tracer.startActiveSpan("store.downloadPayload", async (span) => {
2284
+ return await importPacket(packet, span);
2285
+ }, {
2286
+ attributes: {
2287
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-download"
2288
+ }
2289
+ });
2290
+ return result ?? packet;
2291
+ }
2292
+ }
2293
+ __name(conditionallyImportPacket, "conditionallyImportPacket");
2294
+ async function importPacket(packet, span) {
2295
+ if (!packet.data) {
2296
+ return packet;
2297
+ }
2298
+ if (!apiClientManager.client) {
2299
+ return packet;
2300
+ }
2301
+ const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
2302
+ const response = await fetch(presignedResponse.presignedUrl);
2303
+ if (!response.ok) {
2304
+ throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
2305
+ }
2306
+ const data = await response.text();
2307
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
2308
+ return {
2309
+ data,
2310
+ dataType: response.headers.get("content-type") ?? "application/json"
2311
+ };
2312
+ }
2313
+ __name(importPacket, "importPacket");
2314
+ async function createPacketAttributes(packet, dataKey, dataTypeKey) {
2315
+ if (!packet.data) {
2316
+ return;
2317
+ }
2318
+ switch (packet.dataType) {
2319
+ case "application/json":
2320
+ return {
2321
+ ...flattenAttributes(packet, dataKey),
2322
+ [dataTypeKey]: packet.dataType
2323
+ };
2324
+ case "application/super+json":
2325
+ const { parse } = await loadSuperJSON();
2326
+ if (typeof packet.data === "undefined" || packet.data === null) {
2327
+ return;
2328
+ }
2329
+ try {
2330
+ const parsed = parse(packet.data);
2331
+ const jsonified = JSON.parse(JSON.stringify(parsed, safeReplacer));
2332
+ const result = {
2333
+ ...flattenAttributes(jsonified, dataKey),
2334
+ [dataTypeKey]: "application/json"
2335
+ };
2336
+ return result;
2337
+ } catch (e) {
2338
+ return;
2339
+ }
2340
+ case "application/store":
2341
+ return {
2342
+ [dataKey]: packet.data,
2343
+ [dataTypeKey]: packet.dataType
2344
+ };
2345
+ case "text/plain":
2346
+ return {
2347
+ [dataKey]: packet.data,
2348
+ [dataTypeKey]: packet.dataType
2349
+ };
2350
+ default:
2351
+ return;
2352
+ }
2353
+ }
2354
+ __name(createPacketAttributes, "createPacketAttributes");
2355
+ function safeReplacer(key, value) {
2356
+ if (typeof value === "bigint") {
2357
+ return value.toString();
2358
+ }
2359
+ if (value instanceof RegExp) {
2360
+ return value.toString();
2361
+ }
2362
+ if (value instanceof Set) {
2363
+ return Array.from(value);
2364
+ }
2365
+ if (value instanceof Map) {
2366
+ const obj = {};
2367
+ value.forEach((v, k) => {
2368
+ obj[k] = v;
2369
+ });
2370
+ return obj;
2371
+ }
2372
+ return value;
2373
+ }
2374
+ __name(safeReplacer, "safeReplacer");
2375
+ function getPacketExtension(outputType) {
2376
+ switch (outputType) {
2377
+ case "application/json":
2378
+ return "json";
2379
+ case "application/super+json":
2380
+ return "json";
2381
+ case "text/plain":
2382
+ return "txt";
2383
+ default:
2384
+ return "txt";
2385
+ }
2386
+ }
2387
+ __name(getPacketExtension, "getPacketExtension");
2388
+ async function loadSuperJSON() {
2389
+ return await import('superjson');
2390
+ }
2391
+ __name(loadSuperJSON, "loadSuperJSON");
2392
+
2393
+ // src/v3/utils/styleAttributes.ts
2394
+ function accessoryAttributes(accessory) {
2395
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
2396
+ }
2397
+ __name(accessoryAttributes, "accessoryAttributes");
2398
+
2399
+ // src/v3/workers/taskExecutor.ts
2400
+ var _callRun, callRun_fn, _callInitFunctions, callInitFunctions_fn, _callConfigInit, callConfigInit_fn, _callOnSuccessFunctions, callOnSuccessFunctions_fn, _callOnSuccessFunction, callOnSuccessFunction_fn, _callOnFailureFunctions, callOnFailureFunctions_fn, _callOnFailureFunction, callOnFailureFunction_fn, _callOnStartFunctions, callOnStartFunctions_fn, _callOnStartFunction, callOnStartFunction_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
2401
+ var _TaskExecutor = class _TaskExecutor {
2402
+ constructor(task, options) {
2403
+ __privateAdd(this, _callRun);
2404
+ __privateAdd(this, _callInitFunctions);
2405
+ __privateAdd(this, _callConfigInit);
2406
+ __privateAdd(this, _callOnSuccessFunctions);
2407
+ __privateAdd(this, _callOnSuccessFunction);
2408
+ __privateAdd(this, _callOnFailureFunctions);
2409
+ __privateAdd(this, _callOnFailureFunction);
2410
+ __privateAdd(this, _callOnStartFunctions);
2411
+ __privateAdd(this, _callOnStartFunction);
2412
+ __privateAdd(this, _callTaskCleanup);
2413
+ __privateAdd(this, _handleError);
2414
+ this.task = task;
2415
+ this._tracingSDK = options.tracingSDK;
2416
+ this._tracer = options.tracer;
2417
+ this._consoleInterceptor = options.consoleInterceptor;
2418
+ this._config = options.projectConfig;
2419
+ this._importedConfig = options.importedConfig;
2420
+ this._handleErrorFn = options.handleErrorFn;
2421
+ }
2422
+ async execute(execution, worker, traceContext, usage2) {
2423
+ const ctx = TaskRunContext.parse(execution);
2424
+ const attemptMessage = `Attempt ${execution.attempt.number}`;
2425
+ const originalPacket = {
2426
+ data: execution.run.payload,
2427
+ dataType: execution.run.payloadType
2428
+ };
2429
+ taskContext.setGlobalTaskContext({
2430
+ ctx,
2431
+ worker
2432
+ });
2433
+ this._tracingSDK.asyncResourceDetector.resolveWithAttributes({
2434
+ ...taskContext.attributes,
2435
+ [SemanticInternalAttributes.SDK_VERSION]: this.task.packageVersion,
2436
+ [SemanticInternalAttributes.SDK_LANGUAGE]: "typescript"
2437
+ });
2438
+ const result = await this._tracer.startActiveSpan(attemptMessage, async (span) => {
2439
+ return await this._consoleInterceptor.intercept(console, async () => {
2440
+ let parsedPayload;
2441
+ let initOutput;
2442
+ try {
2443
+ const payloadPacket = await conditionallyImportPacket(originalPacket, this._tracer);
2444
+ parsedPayload = await parsePacket(payloadPacket);
2445
+ if (execution.attempt.number === 1) {
2446
+ await __privateMethod(this, _callOnStartFunctions, callOnStartFunctions_fn).call(this, parsedPayload, ctx);
2447
+ }
2448
+ initOutput = await __privateMethod(this, _callInitFunctions, callInitFunctions_fn).call(this, parsedPayload, ctx);
2449
+ const output = await __privateMethod(this, _callRun, callRun_fn).call(this, parsedPayload, ctx, initOutput);
2450
+ await __privateMethod(this, _callOnSuccessFunctions, callOnSuccessFunctions_fn).call(this, parsedPayload, output, ctx, initOutput);
2451
+ try {
2452
+ const stringifiedOutput = await stringifyIO(output);
2453
+ const finalOutput = await conditionallyExportPacket(stringifiedOutput, `${execution.attempt.id}/output`, this._tracer);
2454
+ const attributes = await createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE);
2455
+ if (attributes) {
2456
+ span.setAttributes(attributes);
2457
+ }
2458
+ return {
2459
+ ok: true,
2460
+ id: execution.run.id,
2461
+ output: finalOutput.data,
2462
+ outputType: finalOutput.dataType
2463
+ };
2464
+ } catch (stringifyError) {
2465
+ recordSpanException(span, stringifyError);
2466
+ return {
2467
+ ok: false,
2468
+ id: execution.run.id,
2469
+ error: {
2470
+ type: "INTERNAL_ERROR",
2471
+ code: TaskRunErrorCodes.TASK_OUTPUT_ERROR,
2472
+ message: stringifyError instanceof Error ? stringifyError.message : typeof stringifyError === "string" ? stringifyError : void 0
2473
+ }
2474
+ };
2475
+ }
2476
+ } catch (runError) {
2477
+ try {
2478
+ const handleErrorResult = await __privateMethod(this, _handleError, handleError_fn).call(this, execution, runError, parsedPayload, ctx);
2479
+ recordSpanException(span, handleErrorResult.error ?? runError);
2480
+ if (handleErrorResult.status !== "retry") {
2481
+ await __privateMethod(this, _callOnFailureFunctions, callOnFailureFunctions_fn).call(this, parsedPayload, handleErrorResult.error ?? runError, ctx, initOutput);
2482
+ }
2483
+ return {
2484
+ id: execution.run.id,
2485
+ ok: false,
2486
+ error: handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError),
2487
+ retry: handleErrorResult.status === "retry" ? handleErrorResult.retry : void 0,
2488
+ skippedRetrying: handleErrorResult.status === "skipped"
2489
+ };
2490
+ } catch (handleErrorError) {
2491
+ recordSpanException(span, handleErrorError);
2492
+ return {
2493
+ ok: false,
2494
+ id: execution.run.id,
2495
+ error: {
2496
+ type: "INTERNAL_ERROR",
2497
+ code: TaskRunErrorCodes.HANDLE_ERROR_ERROR,
2498
+ message: handleErrorError instanceof Error ? handleErrorError.message : typeof handleErrorError === "string" ? handleErrorError : void 0
2499
+ }
2500
+ };
2501
+ }
2502
+ } finally {
2503
+ await __privateMethod(this, _callTaskCleanup, callTaskCleanup_fn).call(this, parsedPayload, ctx, initOutput);
2504
+ }
2505
+ });
2506
+ }, {
2507
+ kind: api.SpanKind.CONSUMER,
2508
+ attributes: {
2509
+ [SemanticInternalAttributes.STYLE_ICON]: "attempt",
2510
+ ...accessoryAttributes({
2511
+ items: [
2512
+ {
2513
+ text: ctx.task.filePath
2514
+ },
2515
+ {
2516
+ text: `${ctx.task.exportName}.run()`
2517
+ }
2518
+ ],
2519
+ style: "codepath"
2520
+ })
2521
+ }
2522
+ }, this._tracer.extractContext(traceContext));
2523
+ return {
2524
+ result
2525
+ };
2526
+ }
2527
+ };
2528
+ _callRun = new WeakSet();
2529
+ callRun_fn = /* @__PURE__ */ __name(async function(payload, ctx, init) {
2530
+ const runFn = this.task.fns.run;
2531
+ const middlewareFn = this.task.fns.middleware;
2532
+ if (!runFn) {
2533
+ throw new Error("Task does not have a run function");
2534
+ }
2535
+ if (!middlewareFn) {
2536
+ return runFn(payload, {
2537
+ ctx
2538
+ });
2539
+ }
2540
+ return middlewareFn(payload, {
2541
+ ctx,
2542
+ next: async () => runFn(payload, {
2543
+ ctx,
2544
+ init
2545
+ })
2546
+ });
2547
+ }, "#callRun");
2548
+ _callInitFunctions = new WeakSet();
2549
+ callInitFunctions_fn = /* @__PURE__ */ __name(async function(payload1, ctx1) {
2550
+ await __privateMethod(this, _callConfigInit, callConfigInit_fn).call(this, payload1, ctx1);
2551
+ const initFn = this.task.fns.init;
2552
+ if (!initFn) {
2553
+ return {};
2554
+ }
2555
+ return this._tracer.startActiveSpan("init", async (span) => {
2556
+ return await initFn(payload1, {
2557
+ ctx: ctx1
2558
+ });
2559
+ }, {
2560
+ attributes: {
2561
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2562
+ }
2563
+ });
2564
+ }, "#callInitFunctions");
2565
+ _callConfigInit = new WeakSet();
2566
+ callConfigInit_fn = /* @__PURE__ */ __name(async function(payload2, ctx2) {
2567
+ const initFn = this._importedConfig?.init;
2568
+ if (!initFn) {
2569
+ return {};
2570
+ }
2571
+ return this._tracer.startActiveSpan("config.init", async (span) => {
2572
+ return await initFn(payload2, {
2573
+ ctx: ctx2
2574
+ });
2575
+ }, {
2576
+ attributes: {
2577
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2578
+ }
2579
+ });
2580
+ }, "#callConfigInit");
2581
+ _callOnSuccessFunctions = new WeakSet();
2582
+ callOnSuccessFunctions_fn = /* @__PURE__ */ __name(async function(payload3, output, ctx3, initOutput) {
2583
+ await __privateMethod(this, _callOnSuccessFunction, callOnSuccessFunction_fn).call(this, this.task.fns.onSuccess, "task.onSuccess", payload3, output, ctx3, initOutput);
2584
+ await __privateMethod(this, _callOnSuccessFunction, callOnSuccessFunction_fn).call(this, this._importedConfig?.onSuccess, "config.onSuccess", payload3, output, ctx3, initOutput);
2585
+ }, "#callOnSuccessFunctions");
2586
+ _callOnSuccessFunction = new WeakSet();
2587
+ callOnSuccessFunction_fn = /* @__PURE__ */ __name(async function(onSuccessFn, name, payload4, output1, ctx4, initOutput1) {
2588
+ if (!onSuccessFn) {
2589
+ return;
2590
+ }
2591
+ try {
2592
+ await this._tracer.startActiveSpan(name, async (span) => {
2593
+ return await onSuccessFn(payload4, output1, {
2594
+ ctx: ctx4,
2595
+ init: initOutput1
2596
+ });
2597
+ }, {
2598
+ attributes: {
2599
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2600
+ }
2601
+ });
2602
+ } catch {
2603
+ }
2604
+ }, "#callOnSuccessFunction");
2605
+ _callOnFailureFunctions = new WeakSet();
2606
+ callOnFailureFunctions_fn = /* @__PURE__ */ __name(async function(payload5, error, ctx5, initOutput2) {
2607
+ await __privateMethod(this, _callOnFailureFunction, callOnFailureFunction_fn).call(this, this.task.fns.onFailure, "task.onFailure", payload5, error, ctx5, initOutput2);
2608
+ await __privateMethod(this, _callOnFailureFunction, callOnFailureFunction_fn).call(this, this._importedConfig?.onFailure, "config.onFailure", payload5, error, ctx5, initOutput2);
2609
+ }, "#callOnFailureFunctions");
2610
+ _callOnFailureFunction = new WeakSet();
2611
+ callOnFailureFunction_fn = /* @__PURE__ */ __name(async function(onFailureFn, name1, payload6, error1, ctx6, initOutput3) {
2612
+ if (!onFailureFn) {
2613
+ return;
2614
+ }
2615
+ try {
2616
+ return await this._tracer.startActiveSpan(name1, async (span) => {
2617
+ return await onFailureFn(payload6, error1, {
2618
+ ctx: ctx6,
2619
+ init: initOutput3
2620
+ });
2621
+ }, {
2622
+ attributes: {
2623
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2624
+ }
2625
+ });
2626
+ } catch (e) {
2627
+ }
2628
+ }, "#callOnFailureFunction");
2629
+ _callOnStartFunctions = new WeakSet();
2630
+ callOnStartFunctions_fn = /* @__PURE__ */ __name(async function(payload7, ctx7) {
2631
+ await __privateMethod(this, _callOnStartFunction, callOnStartFunction_fn).call(this, this._importedConfig?.onStart, "config.onStart", payload7, ctx7, {});
2632
+ await __privateMethod(this, _callOnStartFunction, callOnStartFunction_fn).call(this, this.task.fns.onStart, "task.onStart", payload7, ctx7, {});
2633
+ }, "#callOnStartFunctions");
2634
+ _callOnStartFunction = new WeakSet();
2635
+ callOnStartFunction_fn = /* @__PURE__ */ __name(async function(onStartFn, name2, payload8, ctx8, initOutput4) {
2636
+ if (!onStartFn) {
2637
+ return;
2638
+ }
2639
+ try {
2640
+ await this._tracer.startActiveSpan(name2, async (span) => {
2641
+ return await onStartFn(payload8, {
2642
+ ctx: ctx8
2643
+ });
2644
+ }, {
2645
+ attributes: {
2646
+ [SemanticInternalAttributes.STYLE_ICON]: "function"
2647
+ }
2648
+ });
2649
+ } catch {
2650
+ }
2651
+ }, "#callOnStartFunction");
2652
+ _callTaskCleanup = new WeakSet();
2653
+ callTaskCleanup_fn = /* @__PURE__ */ __name(async function(payload9, ctx9, init1) {
2654
+ const cleanupFn = this.task.fns.cleanup;
2655
+ if (!cleanupFn) {
2656
+ return;
2657
+ }
2658
+ return this._tracer.startActiveSpan("cleanup", async (span) => {
2659
+ return await cleanupFn(payload9, {
2660
+ ctx: ctx9,
2661
+ init: init1
2662
+ });
2663
+ });
2664
+ }, "#callTaskCleanup");
2665
+ _handleError = new WeakSet();
2666
+ handleError_fn = /* @__PURE__ */ __name(async function(execution, error2, payload10, ctx10) {
2667
+ const retriesConfig = this._importedConfig?.retries ?? this._config.retries;
2668
+ const retry = this.task.retry ?? retriesConfig?.default;
2669
+ if (!retry) {
2670
+ return {
2671
+ status: "noop"
2672
+ };
2673
+ }
2674
+ const delay = calculateNextRetryDelay(retry, execution.attempt.number);
2675
+ if (execution.environment.type === "DEVELOPMENT" && typeof retriesConfig?.enabledInDev === "boolean" && !retriesConfig.enabledInDev) {
2676
+ return {
2677
+ status: "skipped"
2678
+ };
2679
+ }
2680
+ return this._tracer.startActiveSpan("handleError()", async (span) => {
2681
+ const handleErrorResult = this.task.fns.handleError ? await this.task.fns.handleError(payload10, error2, {
2682
+ ctx: ctx10,
2683
+ retry,
2684
+ retryDelayInMs: delay,
2685
+ retryAt: delay ? new Date(Date.now() + delay) : void 0
2686
+ }) : this._importedConfig ? await this._handleErrorFn?.(payload10, error2, {
2687
+ ctx: ctx10,
2688
+ retry,
2689
+ retryDelayInMs: delay,
2690
+ retryAt: delay ? new Date(Date.now() + delay) : void 0
2691
+ }) : void 0;
2692
+ if (!handleErrorResult) {
2693
+ return typeof delay === "undefined" ? {
2694
+ status: "noop"
2695
+ } : {
2696
+ status: "retry",
2697
+ retry: {
2698
+ timestamp: Date.now() + delay,
2699
+ delay
2700
+ }
2701
+ };
2702
+ }
2703
+ if (handleErrorResult.skipRetrying) {
2704
+ return {
2705
+ status: "skipped",
2706
+ error: handleErrorResult.error
2707
+ };
2708
+ }
2709
+ if (typeof handleErrorResult.retryAt !== "undefined") {
2710
+ return {
2711
+ status: "retry",
2712
+ retry: {
2713
+ timestamp: handleErrorResult.retryAt.getTime(),
2714
+ delay: handleErrorResult.retryAt.getTime() - Date.now()
2715
+ },
2716
+ error: handleErrorResult.error
2717
+ };
2718
+ }
2719
+ if (typeof handleErrorResult.retryDelayInMs === "number") {
2720
+ return {
2721
+ status: "retry",
2722
+ retry: {
2723
+ timestamp: Date.now() + handleErrorResult.retryDelayInMs,
2724
+ delay: handleErrorResult.retryDelayInMs
2725
+ },
2726
+ error: handleErrorResult.error
2727
+ };
2728
+ }
2729
+ if (handleErrorResult.retry && typeof handleErrorResult.retry === "object") {
2730
+ const delay2 = calculateNextRetryDelay(handleErrorResult.retry, execution.attempt.number);
2731
+ return typeof delay2 === "undefined" ? {
2732
+ status: "noop",
2733
+ error: handleErrorResult.error
2734
+ } : {
2735
+ status: "retry",
2736
+ retry: {
2737
+ timestamp: Date.now() + delay2,
2738
+ delay: delay2
2739
+ },
2740
+ error: handleErrorResult.error
2741
+ };
2742
+ }
2743
+ return {
2744
+ status: "noop",
2745
+ error: handleErrorResult.error
2746
+ };
2747
+ }, {
2748
+ attributes: {
2749
+ [SemanticInternalAttributes.STYLE_ICON]: "exclamation-circle"
2750
+ }
2751
+ });
2752
+ }, "#handleError");
2753
+ __name(_TaskExecutor, "TaskExecutor");
2754
+ var TaskExecutor = _TaskExecutor;
2755
+ var _originClockTime, originClockTime_get, _originPreciseDate, originPreciseDate_get;
2756
+ var _PreciseWallClock = class _PreciseWallClock {
2757
+ constructor(options = {}) {
2758
+ __privateAdd(this, _originClockTime);
2759
+ __privateAdd(this, _originPreciseDate);
2760
+ this._origin = {
2761
+ clockTime: options.origin ?? process.hrtime(),
2762
+ preciseDate: options.now ?? new preciseDate.PreciseDate()
2763
+ };
2764
+ }
2765
+ preciseNow() {
2766
+ const elapsedHrTime = process.hrtime(__privateGet(this, _originClockTime, originClockTime_get));
2767
+ const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
2768
+ const preciseDate$1 = new preciseDate.PreciseDate(__privateGet(this, _originPreciseDate, originPreciseDate_get).getFullTime() + elapsedNanoseconds);
2769
+ const dateStruct = preciseDate$1.toStruct();
2770
+ return [
2771
+ dateStruct.seconds,
2772
+ dateStruct.nanos
2773
+ ];
2774
+ }
2775
+ reset() {
2776
+ this._origin = {
2777
+ clockTime: process.hrtime(),
2778
+ preciseDate: new preciseDate.PreciseDate()
2779
+ };
2780
+ }
2781
+ };
2782
+ _originClockTime = new WeakSet();
2783
+ originClockTime_get = /* @__PURE__ */ __name(function() {
2784
+ return this._origin.clockTime;
2785
+ }, "#originClockTime");
2786
+ _originPreciseDate = new WeakSet();
2787
+ originPreciseDate_get = /* @__PURE__ */ __name(function() {
2788
+ return this._origin.preciseDate;
2789
+ }, "#originPreciseDate");
2790
+ __name(_PreciseWallClock, "PreciseWallClock");
2791
+ var PreciseWallClock = _PreciseWallClock;
2792
+ function iconStringForSeverity(severityNumber) {
2793
+ switch (severityNumber) {
2794
+ case apiLogs.SeverityNumber.UNSPECIFIED:
2795
+ return void 0;
2796
+ case apiLogs.SeverityNumber.TRACE:
2797
+ case apiLogs.SeverityNumber.TRACE2:
2798
+ case apiLogs.SeverityNumber.TRACE3:
2799
+ case apiLogs.SeverityNumber.TRACE4:
2800
+ return "trace";
2801
+ case apiLogs.SeverityNumber.DEBUG:
2802
+ case apiLogs.SeverityNumber.DEBUG2:
2803
+ case apiLogs.SeverityNumber.DEBUG3:
2804
+ case apiLogs.SeverityNumber.DEBUG4:
2805
+ return "debug";
2806
+ case apiLogs.SeverityNumber.INFO:
2807
+ case apiLogs.SeverityNumber.INFO2:
2808
+ case apiLogs.SeverityNumber.INFO3:
2809
+ case apiLogs.SeverityNumber.INFO4:
2810
+ return "info";
2811
+ case apiLogs.SeverityNumber.WARN:
2812
+ case apiLogs.SeverityNumber.WARN2:
2813
+ case apiLogs.SeverityNumber.WARN3:
2814
+ case apiLogs.SeverityNumber.WARN4:
2815
+ return "warn";
2816
+ case apiLogs.SeverityNumber.ERROR:
2817
+ case apiLogs.SeverityNumber.ERROR2:
2818
+ case apiLogs.SeverityNumber.ERROR3:
2819
+ case apiLogs.SeverityNumber.ERROR4:
2820
+ return "error";
2821
+ case apiLogs.SeverityNumber.FATAL:
2822
+ case apiLogs.SeverityNumber.FATAL2:
2823
+ case apiLogs.SeverityNumber.FATAL3:
2824
+ case apiLogs.SeverityNumber.FATAL4:
2825
+ return "fatal";
2826
+ }
2827
+ }
2828
+ __name(iconStringForSeverity, "iconStringForSeverity");
2829
+ var _SimpleClock = class _SimpleClock {
2830
+ preciseNow() {
2831
+ const now = new preciseDate.PreciseDate();
2832
+ const nowStruct = now.toStruct();
2833
+ return [
2834
+ nowStruct.seconds,
2835
+ nowStruct.nanos
2836
+ ];
2837
+ }
2838
+ reset() {
2839
+ }
2840
+ };
2841
+ __name(_SimpleClock, "SimpleClock");
2842
+ var SimpleClock = _SimpleClock;
2843
+
2844
+ // src/v3/clock/index.ts
2845
+ var API_NAME3 = "clock";
2846
+ var SIMPLE_CLOCK = new SimpleClock();
2847
+ var _getClock, getClock_fn;
2848
+ var _ClockAPI = class _ClockAPI {
2849
+ constructor() {
2850
+ __privateAdd(this, _getClock);
2851
+ }
2852
+ static getInstance() {
2853
+ if (!this._instance) {
2854
+ this._instance = new _ClockAPI();
2855
+ }
2856
+ return this._instance;
2857
+ }
2858
+ setGlobalClock(clock2) {
2859
+ return registerGlobal(API_NAME3, clock2);
2860
+ }
2861
+ preciseNow() {
2862
+ return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2863
+ }
2864
+ reset() {
2865
+ __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2866
+ }
2867
+ };
2868
+ _getClock = new WeakSet();
2869
+ getClock_fn = /* @__PURE__ */ __name(function() {
2870
+ return getGlobal(API_NAME3) ?? SIMPLE_CLOCK;
2871
+ }, "#getClock");
2872
+ __name(_ClockAPI, "ClockAPI");
2873
+ var ClockAPI = _ClockAPI;
2874
+
2875
+ // src/v3/clock-api.ts
2876
+ var clock = ClockAPI.getInstance();
2877
+
2878
+ // src/v3/logger/taskLogger.ts
2879
+ var logLevels = [
2880
+ "none",
2881
+ "error",
2882
+ "warn",
2883
+ "info",
2884
+ "debug"
2885
+ ];
2886
+ var _emitLog, emitLog_fn, _getTimestampInHrTime, getTimestampInHrTime_fn;
2887
+ var _OtelTaskLogger = class _OtelTaskLogger {
2888
+ constructor(_config) {
2889
+ __privateAdd(this, _emitLog);
2890
+ __privateAdd(this, _getTimestampInHrTime);
2891
+ this._config = _config;
2892
+ this._level = logLevels.indexOf(_config.level);
2893
+ }
2894
+ debug(message, properties) {
2895
+ if (this._level < 4)
2896
+ return;
2897
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "debug", apiLogs.SeverityNumber.DEBUG, properties);
2898
+ }
2899
+ log(message, properties) {
2900
+ if (this._level < 3)
2901
+ return;
2902
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "log", apiLogs.SeverityNumber.INFO, properties);
2903
+ }
2904
+ info(message, properties) {
2905
+ if (this._level < 3)
2906
+ return;
2907
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "info", apiLogs.SeverityNumber.INFO, properties);
2908
+ }
2909
+ warn(message, properties) {
2910
+ if (this._level < 2)
2911
+ return;
2912
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "warn", apiLogs.SeverityNumber.WARN, properties);
2913
+ }
2914
+ error(message, properties) {
2915
+ if (this._level < 1)
2916
+ return;
2917
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "error", apiLogs.SeverityNumber.ERROR, properties);
2918
+ }
2919
+ trace(name, fn, options) {
2920
+ return this._config.tracer.startActiveSpan(name, fn, options);
2921
+ }
2922
+ };
2923
+ _emitLog = new WeakSet();
2924
+ emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
2925
+ let attributes = {
2926
+ ...flattenAttributes(safeJsonProcess(properties))
2927
+ };
2928
+ const icon = iconStringForSeverity(severityNumber);
2929
+ if (icon !== void 0) {
2930
+ attributes[SemanticInternalAttributes.STYLE_ICON] = icon;
2931
+ }
2932
+ this._config.logger.emit({
2933
+ severityNumber,
2934
+ severityText,
2935
+ body: message,
2936
+ attributes,
2937
+ timestamp
2938
+ });
2939
+ }, "#emitLog");
2940
+ _getTimestampInHrTime = new WeakSet();
2941
+ getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
2942
+ return clock.preciseNow();
2943
+ }, "#getTimestampInHrTime");
2944
+ __name(_OtelTaskLogger, "OtelTaskLogger");
2945
+ var OtelTaskLogger = _OtelTaskLogger;
2946
+ function safeJsonProcess(value) {
2947
+ try {
2948
+ return JSON.parse(JSON.stringify(value, jsonErrorReplacer));
2949
+ } catch {
2950
+ return value;
2951
+ }
2952
+ }
2953
+ __name(safeJsonProcess, "safeJsonProcess");
2954
+ function jsonErrorReplacer(key, value) {
2955
+ if (value instanceof Error) {
2956
+ return {
2957
+ name: value.name,
2958
+ message: value.message,
2959
+ stack: value.stack
2960
+ };
2961
+ }
2962
+ return value;
2963
+ }
2964
+ __name(jsonErrorReplacer, "jsonErrorReplacer");
2965
+ var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
2966
+ var _ConsoleInterceptor = class _ConsoleInterceptor {
2967
+ constructor(logger, sendToStdIO) {
2968
+ __privateAdd(this, _handleLog);
2969
+ __privateAdd(this, _getTimestampInHrTime2);
2970
+ __privateAdd(this, _getAttributes);
2971
+ this.logger = logger;
2972
+ this.sendToStdIO = sendToStdIO;
2973
+ }
2974
+ // Intercept the console and send logs to the OpenTelemetry logger
2975
+ // during the execution of the callback
2976
+ async intercept(console2, callback) {
2977
+ const originalConsole = {
2978
+ log: console2.log,
2979
+ info: console2.info,
2980
+ warn: console2.warn,
2981
+ error: console2.error,
2982
+ debug: console2.debug
2983
+ };
2984
+ console2.log = this.log.bind(this);
2985
+ console2.info = this.info.bind(this);
2986
+ console2.warn = this.warn.bind(this);
2987
+ console2.error = this.error.bind(this);
2988
+ console2.debug = this.debug.bind(this);
2989
+ try {
2990
+ return await callback();
2991
+ } finally {
2992
+ console2.log = originalConsole.log;
2993
+ console2.info = originalConsole.info;
2994
+ console2.warn = originalConsole.warn;
2995
+ console2.error = originalConsole.error;
2996
+ console2.debug = originalConsole.debug;
2997
+ }
2998
+ }
2999
+ debug(...args) {
3000
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.DEBUG, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Debug", ...args);
3001
+ }
3002
+ log(...args) {
3003
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
3004
+ }
3005
+ info(...args) {
3006
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Info", ...args);
3007
+ }
3008
+ warn(...args) {
3009
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.WARN, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Warn", ...args);
3010
+ }
3011
+ error(...args) {
3012
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.ERROR, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Error", ...args);
3013
+ }
3014
+ };
3015
+ _handleLog = new WeakSet();
3016
+ handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
3017
+ const body = util__default.default.format(...args);
3018
+ if (this.sendToStdIO) {
3019
+ if (severityNumber === apiLogs.SeverityNumber.ERROR) {
3020
+ process.stderr.write(body);
3021
+ } else {
3022
+ process.stdout.write(body);
3023
+ }
3024
+ }
3025
+ const parsed = tryParseJSON(body);
3026
+ if (parsed.ok) {
3027
+ this.logger.emit({
3028
+ severityNumber,
3029
+ severityText,
3030
+ body: getLogMessage(parsed.value, severityText),
3031
+ attributes: {
3032
+ ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3033
+ ...flattenAttributes(parsed.value)
3034
+ },
3035
+ timestamp
3036
+ });
3037
+ return;
3038
+ }
3039
+ this.logger.emit({
3040
+ severityNumber,
3041
+ severityText,
3042
+ body,
3043
+ attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3044
+ timestamp
3045
+ });
3046
+ }, "#handleLog");
3047
+ _getTimestampInHrTime2 = new WeakSet();
3048
+ getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
3049
+ return clock.preciseNow();
3050
+ }, "#getTimestampInHrTime");
3051
+ _getAttributes = new WeakSet();
3052
+ getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
3053
+ const icon = iconStringForSeverity(severityNumber1);
3054
+ let result = {};
3055
+ if (icon !== void 0) {
3056
+ result[SemanticInternalAttributes.STYLE_ICON] = icon;
3057
+ }
3058
+ return result;
3059
+ }, "#getAttributes");
3060
+ __name(_ConsoleInterceptor, "ConsoleInterceptor");
3061
+ var ConsoleInterceptor = _ConsoleInterceptor;
3062
+ function getLogMessage(value, fallback) {
3063
+ if (typeof value["message"] === "string") {
3064
+ return value["message"];
3065
+ }
3066
+ if (typeof value["msg"] === "string") {
3067
+ return value["msg"];
3068
+ }
3069
+ if (typeof value["body"] === "string") {
3070
+ return value["body"];
3071
+ }
3072
+ if (typeof value["error"] === "string") {
3073
+ return value["error"];
3074
+ }
3075
+ return fallback;
3076
+ }
3077
+ __name(getLogMessage, "getLogMessage");
3078
+ function tryParseJSON(value) {
3079
+ try {
3080
+ const parsed = JSON.parse(value);
3081
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
3082
+ return {
3083
+ ok: true,
3084
+ value: parsed
3085
+ };
3086
+ }
3087
+ return {
3088
+ ok: false,
3089
+ value
3090
+ };
3091
+ } catch (e) {
3092
+ return {
3093
+ ok: false,
3094
+ value
3095
+ };
3096
+ }
3097
+ }
3098
+ __name(tryParseJSON, "tryParseJSON");
3099
+
3100
+ // src/v3/task-catalog/standardTaskCatalog.ts
3101
+ var _StandardTaskCatalog = class _StandardTaskCatalog {
3102
+ constructor() {
3103
+ __publicField(this, "_taskMetadata", /* @__PURE__ */ new Map());
3104
+ __publicField(this, "_taskFunctions", /* @__PURE__ */ new Map());
3105
+ __publicField(this, "_taskFileMetadata", /* @__PURE__ */ new Map());
3106
+ }
3107
+ registerTaskMetadata(task) {
3108
+ const { fns, ...metadata } = task;
3109
+ this._taskMetadata.set(task.id, metadata);
3110
+ this._taskFunctions.set(task.id, fns);
3111
+ }
3112
+ updateTaskMetadata(id, updates) {
3113
+ const existingMetadata = this._taskMetadata.get(id);
3114
+ if (existingMetadata) {
3115
+ this._taskMetadata.set(id, {
3116
+ ...existingMetadata,
3117
+ ...updates
3118
+ });
3119
+ }
3120
+ if (updates.fns) {
3121
+ const existingFunctions = this._taskFunctions.get(id);
3122
+ if (existingFunctions) {
3123
+ this._taskFunctions.set(id, {
3124
+ ...existingFunctions,
3125
+ ...updates.fns
3126
+ });
3127
+ }
3128
+ }
3129
+ }
3130
+ registerTaskFileMetadata(id, metadata) {
3131
+ this._taskFileMetadata.set(id, metadata);
3132
+ }
3133
+ // Return all the tasks, without the functions
3134
+ getAllTaskMetadata() {
3135
+ const result = [];
3136
+ for (const [id, metadata] of this._taskMetadata) {
3137
+ const fileMetadata = this._taskFileMetadata.get(id);
3138
+ if (!fileMetadata) {
3139
+ continue;
3140
+ }
3141
+ result.push({
3142
+ ...metadata,
3143
+ ...fileMetadata
3144
+ });
3145
+ }
3146
+ return result;
3147
+ }
3148
+ getTaskMetadata(id) {
3149
+ const metadata = this._taskMetadata.get(id);
3150
+ const fileMetadata = this._taskFileMetadata.get(id);
3151
+ if (!metadata || !fileMetadata) {
3152
+ return void 0;
3153
+ }
3154
+ return {
3155
+ ...metadata,
3156
+ ...fileMetadata
3157
+ };
3158
+ }
3159
+ getTask(id) {
3160
+ const metadata = this._taskMetadata.get(id);
3161
+ const fileMetadata = this._taskFileMetadata.get(id);
3162
+ const fns = this._taskFunctions.get(id);
3163
+ if (!metadata || !fns || !fileMetadata) {
3164
+ return void 0;
3165
+ }
3166
+ return {
3167
+ ...metadata,
3168
+ ...fileMetadata,
3169
+ fns
3170
+ };
3171
+ }
3172
+ taskExists(id) {
3173
+ return this._taskMetadata.has(id);
3174
+ }
3175
+ disable() {
3176
+ }
3177
+ };
3178
+ __name(_StandardTaskCatalog, "StandardTaskCatalog");
3179
+ var StandardTaskCatalog = _StandardTaskCatalog;
3180
+
3181
+ // src/v3/usage/noopUsageManager.ts
3182
+ var _NoopUsageManager = class _NoopUsageManager {
3183
+ disable() {
3184
+ }
3185
+ start() {
3186
+ return {
3187
+ sample: () => ({
3188
+ cpuTime: 0,
3189
+ wallTime: 0
3190
+ })
3191
+ };
3192
+ }
3193
+ stop(measurement) {
3194
+ return measurement.sample();
3195
+ }
3196
+ pauseAsync(cb) {
3197
+ return cb();
3198
+ }
3199
+ sample() {
3200
+ return void 0;
3201
+ }
3202
+ };
3203
+ __name(_NoopUsageManager, "NoopUsageManager");
3204
+ var NoopUsageManager = _NoopUsageManager;
3205
+
3206
+ // src/v3/usage/api.ts
3207
+ var API_NAME4 = "usage";
3208
+ var NOOP_USAGE_MANAGER = new NoopUsageManager();
3209
+ var _getUsageManager, getUsageManager_fn;
3210
+ var _UsageAPI = class _UsageAPI {
3211
+ constructor() {
3212
+ __privateAdd(this, _getUsageManager);
3213
+ }
3214
+ static getInstance() {
3215
+ if (!this._instance) {
3216
+ this._instance = new _UsageAPI();
3217
+ }
3218
+ return this._instance;
3219
+ }
3220
+ setGlobalUsageManager(manager) {
3221
+ return registerGlobal(API_NAME4, manager);
3222
+ }
3223
+ disable() {
3224
+ __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).disable();
3225
+ unregisterGlobal(API_NAME4);
3226
+ }
3227
+ start() {
3228
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).start();
3229
+ }
3230
+ stop(measurement) {
3231
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).stop(measurement);
3232
+ }
3233
+ pauseAsync(cb) {
3234
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).pauseAsync(cb);
3235
+ }
3236
+ sample() {
3237
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).sample();
3238
+ }
3239
+ };
3240
+ _getUsageManager = new WeakSet();
3241
+ getUsageManager_fn = /* @__PURE__ */ __name(function() {
3242
+ return getGlobal(API_NAME4) ?? NOOP_USAGE_MANAGER;
3243
+ }, "#getUsageManager");
3244
+ __name(_UsageAPI, "UsageAPI");
3245
+ var UsageAPI = _UsageAPI;
3246
+
3247
+ // src/v3/usage-api.ts
3248
+ var usage = UsageAPI.getInstance();
3249
+
3250
+ // src/v3/clock/clock.ts
3251
+ function calculateDurationInMs(start, end) {
3252
+ const [startSeconds, startNanoseconds] = start;
3253
+ const [endSeconds, endNanoseconds] = end;
3254
+ const seconds = endSeconds - startSeconds;
3255
+ const nanoseconds = endNanoseconds - startNanoseconds;
3256
+ return Math.floor(seconds * 1e3 + nanoseconds / 1e6);
3257
+ }
3258
+ __name(calculateDurationInMs, "calculateDurationInMs");
3259
+
3260
+ // src/v3/usage/devUsageManager.ts
3261
+ var _a2;
3262
+ var DevUsageMeasurement = (_a2 = class {
3263
+ constructor(id, startedAt = clock.preciseNow()) {
3264
+ this.id = id;
3265
+ this.startedAt = startedAt;
3266
+ this._pauses = /* @__PURE__ */ new Map();
3267
+ }
3268
+ stop() {
3269
+ this._endedAt = clock.preciseNow();
3270
+ }
3271
+ sample() {
3272
+ const endedAt = this._endedAt ?? clock.preciseNow();
3273
+ const wallTime = this.startedAt ? calculateDurationInMs(this.startedAt, endedAt) : 0;
3274
+ if (wallTime === 0) {
3275
+ return {
3276
+ cpuTime: 0,
3277
+ wallTime: 0
3278
+ };
3279
+ }
3280
+ const totalPauses = Array.from(this._pauses.values()).reduce((total, pause) => {
3281
+ return total + calculateDurationInMs(pause.start, pause.end ?? endedAt);
3282
+ }, 0);
3283
+ const cpuTime = wallTime - totalPauses;
3284
+ return {
3285
+ wallTime,
3286
+ cpuTime
3287
+ };
3288
+ }
3289
+ registerPause(pauseId, start, end) {
3290
+ this._pauses.set(pauseId, {
3291
+ start,
3292
+ end
3293
+ });
3294
+ }
3295
+ }, __name(_a2, "DevUsageMeasurement"), _a2);
3296
+ var _DevUsageManager = class _DevUsageManager {
3297
+ constructor() {
3298
+ __publicField(this, "_currentMeasurements", /* @__PURE__ */ new Map());
3299
+ __publicField(this, "_pauses", /* @__PURE__ */ new Map());
3300
+ }
3301
+ disable() {
3302
+ }
3303
+ sample() {
3304
+ return this._firstMeasurement?.sample();
3305
+ }
3306
+ start() {
3307
+ const id = generateRandomString();
3308
+ const measurement = new DevUsageMeasurement(id);
3309
+ if (!this._firstMeasurement) {
3310
+ this._firstMeasurement = measurement;
3311
+ }
3312
+ this._currentMeasurements.set(id, measurement);
3313
+ return measurement;
3314
+ }
3315
+ stop(measurement) {
3316
+ measurement.stop();
3317
+ const sample = measurement.sample();
3318
+ this._currentMeasurements.delete(measurement.id);
3319
+ return sample;
3320
+ }
3321
+ async pauseAsync(cb) {
3322
+ const pauseId = generateRandomString();
3323
+ const pauseStart = clock.preciseNow();
3324
+ try {
3325
+ this._pauses.set(pauseId, {
3326
+ start: pauseStart
3327
+ });
3328
+ for (const measurement of this._currentMeasurements.values()) {
3329
+ measurement.registerPause(pauseId, pauseStart);
3330
+ }
3331
+ return await cb();
3332
+ } finally {
3333
+ const pauseEnd = clock.preciseNow();
3334
+ this._pauses.set(pauseId, {
3335
+ start: pauseStart,
3336
+ end: pauseEnd
3337
+ });
3338
+ for (const measurement of this._currentMeasurements.values()) {
3339
+ measurement.registerPause(pauseId, pauseStart, pauseEnd);
3340
+ }
3341
+ }
3342
+ }
3343
+ };
3344
+ __name(_DevUsageManager, "DevUsageManager");
3345
+ var DevUsageManager = _DevUsageManager;
3346
+ function generateRandomString() {
3347
+ let result = "";
3348
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
3349
+ const charactersLength = characters.length;
3350
+ for (var i = 0; i < 16; i++) {
3351
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
3352
+ }
3353
+ return result;
3354
+ }
3355
+ __name(generateRandomString, "generateRandomString");
3356
+
3357
+ // src/v3/usage/usageClient.ts
3358
+ var _UsageClient = class _UsageClient {
3359
+ constructor(url, jwt) {
3360
+ this.url = url;
3361
+ this.jwt = jwt;
3362
+ }
3363
+ async sendUsageEvent(event) {
3364
+ try {
3365
+ const response = await fetch(this.url, {
3366
+ method: "POST",
3367
+ body: JSON.stringify(event),
3368
+ headers: {
3369
+ "content-type": "application/json",
3370
+ "x-trigger-jwt": this.jwt,
3371
+ accept: "application/json",
3372
+ authorization: `Bearer ${apiClientManager.accessToken}`
3373
+ }
3374
+ });
3375
+ if (response.ok) {
3376
+ const renewedJwt = response.headers.get("x-trigger-jwt");
3377
+ if (renewedJwt) {
3378
+ this.jwt = renewedJwt;
3379
+ }
3380
+ }
3381
+ } catch (error) {
3382
+ console.error(`Failed to send usage event: ${error}`);
3383
+ }
3384
+ }
3385
+ };
3386
+ __name(_UsageClient, "UsageClient");
3387
+ var UsageClient = _UsageClient;
3388
+
3389
+ // src/v3/usage/prodUsageManager.ts
3390
+ var _startReportingHeartbeat, startReportingHeartbeat_fn, _reportUsage, reportUsage_fn;
3391
+ var _ProdUsageManager = class _ProdUsageManager {
3392
+ constructor(delegageUsageManager, options) {
3393
+ __privateAdd(this, _startReportingHeartbeat);
3394
+ __privateAdd(this, _reportUsage);
3395
+ this.delegageUsageManager = delegageUsageManager;
3396
+ this.options = options;
3397
+ if (this.options.url && this.options.jwt) {
3398
+ this._usageClient = new UsageClient(this.options.url, this.options.jwt);
3399
+ }
3400
+ }
3401
+ get isReportingEnabled() {
3402
+ return typeof this._usageClient !== "undefined";
3403
+ }
3404
+ disable() {
3405
+ this.delegageUsageManager.disable();
3406
+ this._abortController?.abort();
3407
+ }
3408
+ sample() {
3409
+ return this._measurement?.sample();
3410
+ }
3411
+ start() {
3412
+ if (!this.isReportingEnabled || !this.options.heartbeatIntervalMs) {
3413
+ return this.delegageUsageManager.start();
3414
+ }
3415
+ if (!this._measurement) {
3416
+ this._measurement = this.delegageUsageManager.start();
3417
+ __privateMethod(this, _startReportingHeartbeat, startReportingHeartbeat_fn).call(this).catch(console.error);
3418
+ return this._measurement;
3419
+ }
3420
+ return this.delegageUsageManager.start();
3421
+ }
3422
+ stop(measurement) {
3423
+ return this.delegageUsageManager.stop(measurement);
3424
+ }
3425
+ async pauseAsync(cb) {
3426
+ return this.delegageUsageManager.pauseAsync(cb);
3427
+ }
3428
+ async flush() {
3429
+ return await __privateMethod(this, _reportUsage, reportUsage_fn).call(this);
3430
+ }
3431
+ };
3432
+ _startReportingHeartbeat = new WeakSet();
3433
+ startReportingHeartbeat_fn = /* @__PURE__ */ __name(async function() {
3434
+ if (!this._measurement || !this.isReportingEnabled || !this.options.heartbeatIntervalMs) {
3435
+ return;
3436
+ }
3437
+ this._abortController = new AbortController();
3438
+ for await (const _ of promises.setInterval(this.options.heartbeatIntervalMs)) {
3439
+ if (this._abortController.signal.aborted) {
3440
+ break;
3441
+ }
3442
+ await __privateMethod(this, _reportUsage, reportUsage_fn).call(this);
3443
+ }
3444
+ }, "#startReportingHeartbeat");
3445
+ _reportUsage = new WeakSet();
3446
+ reportUsage_fn = /* @__PURE__ */ __name(async function() {
3447
+ if (!this._measurement) {
3448
+ return;
3449
+ }
3450
+ if (!this.isReportingEnabled) {
3451
+ return;
3452
+ }
3453
+ const client = this._usageClient;
3454
+ if (!client) {
3455
+ return;
3456
+ }
3457
+ const sample = this._measurement.sample();
3458
+ const cpuTimeSinceLastSample = this._lastSample ? sample.cpuTime - this._lastSample.cpuTime : sample.cpuTime;
3459
+ this._lastSample = sample;
3460
+ if (cpuTimeSinceLastSample <= 0) {
3461
+ return;
3462
+ }
3463
+ await client.sendUsageEvent({
3464
+ durationMs: cpuTimeSinceLastSample
3465
+ });
3466
+ }, "#reportUsage");
3467
+ __name(_ProdUsageManager, "ProdUsageManager");
3468
+ var ProdUsageManager = _ProdUsageManager;
3469
+
3470
+ exports.ConsoleInterceptor = ConsoleInterceptor;
3471
+ exports.DevUsageManager = DevUsageManager;
3472
+ exports.DurableClock = PreciseWallClock;
3473
+ exports.OtelTaskLogger = OtelTaskLogger;
3474
+ exports.ProdUsageManager = ProdUsageManager;
3475
+ exports.StandardTaskCatalog = StandardTaskCatalog;
3476
+ exports.TaskContextLogProcessor = TaskContextLogProcessor;
3477
+ exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
3478
+ exports.TaskExecutor = TaskExecutor;
3479
+ exports.TracingSDK = TracingSDK;
3480
+ exports.getEnvVar = getEnvVar;
3481
+ exports.logLevels = logLevels;
3482
+ exports.recordSpanException = recordSpanException;
3483
+ exports.usage = usage;
3484
+ //# sourceMappingURL=out.js.map
3485
+ //# sourceMappingURL=index.js.map