@trigger.dev/core 3.0.0-beta.3 → 3.0.0-beta.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/catalog-KbyTBoap.d.ts +2496 -0
  2. package/dist/catalog-ck7x04PV.d.mts +2496 -0
  3. package/dist/manager-WNMVbgHf.d.mts +1158 -0
  4. package/dist/manager-WNMVbgHf.d.ts +1158 -0
  5. package/dist/messages-vq7Bk4Ap.d.mts +12838 -0
  6. package/dist/messages-vq7Bk4Ap.d.ts +12838 -0
  7. package/dist/v3/dev/index.d.mts +28 -0
  8. package/dist/v3/dev/index.d.ts +28 -0
  9. package/dist/v3/dev/index.js +93 -0
  10. package/dist/v3/dev/index.js.map +1 -0
  11. package/dist/v3/dev/index.mjs +91 -0
  12. package/dist/v3/dev/index.mjs.map +1 -0
  13. package/dist/v3/index.d.mts +850 -16919
  14. package/dist/v3/index.d.ts +850 -16919
  15. package/dist/v3/index.js +1676 -2763
  16. package/dist/v3/index.js.map +1 -1
  17. package/dist/v3/index.mjs +1681 -2767
  18. package/dist/v3/index.mjs.map +1 -1
  19. package/dist/v3/otel/index.js +83 -45
  20. package/dist/v3/otel/index.js.map +1 -1
  21. package/dist/v3/otel/index.mjs +83 -45
  22. package/dist/v3/otel/index.mjs.map +1 -1
  23. package/dist/v3/prod/index.d.mts +45 -0
  24. package/dist/v3/prod/index.d.ts +45 -0
  25. package/dist/v3/prod/index.js +229 -0
  26. package/dist/v3/prod/index.js.map +1 -0
  27. package/dist/v3/prod/index.mjs +227 -0
  28. package/dist/v3/prod/index.mjs.map +1 -0
  29. package/dist/v3/utils/structuredLogger.d.mts +31 -0
  30. package/dist/v3/utils/structuredLogger.d.ts +31 -0
  31. package/dist/v3/utils/structuredLogger.js +88 -0
  32. package/dist/v3/utils/structuredLogger.js.map +1 -0
  33. package/dist/v3/utils/structuredLogger.mjs +86 -0
  34. package/dist/v3/utils/structuredLogger.mjs.map +1 -0
  35. package/dist/v3/workers/index.d.mts +95 -0
  36. package/dist/v3/workers/index.d.ts +95 -0
  37. package/dist/v3/workers/index.js +2631 -0
  38. package/dist/v3/workers/index.js.map +1 -0
  39. package/dist/v3/workers/index.mjs +2615 -0
  40. package/dist/v3/workers/index.mjs.map +1 -0
  41. package/dist/v3/zodIpc.d.mts +32 -0
  42. package/dist/v3/zodIpc.d.ts +32 -0
  43. package/dist/v3/zodIpc.js +268 -0
  44. package/dist/v3/zodIpc.js.map +1 -0
  45. package/dist/v3/zodIpc.mjs +266 -0
  46. package/dist/v3/zodIpc.mjs.map +1 -0
  47. package/dist/v3/zodMessageHandler.d.mts +69 -0
  48. package/dist/v3/zodMessageHandler.d.ts +69 -0
  49. package/dist/v3/zodMessageHandler.js +168 -0
  50. package/dist/v3/zodMessageHandler.js.map +1 -0
  51. package/dist/v3/zodMessageHandler.mjs +163 -0
  52. package/dist/v3/zodMessageHandler.mjs.map +1 -0
  53. package/dist/v3/zodNamespace.d.mts +3663 -0
  54. package/dist/v3/zodNamespace.d.ts +3663 -0
  55. package/dist/v3/zodNamespace.js +356 -0
  56. package/dist/v3/zodNamespace.js.map +1 -0
  57. package/dist/v3/zodNamespace.mjs +354 -0
  58. package/dist/v3/zodNamespace.mjs.map +1 -0
  59. package/dist/v3/zodSocket.d.mts +88 -0
  60. package/dist/v3/zodSocket.d.ts +88 -0
  61. package/dist/v3/zodSocket.js +309 -0
  62. package/dist/v3/zodSocket.js.map +1 -0
  63. package/dist/v3/zodSocket.mjs +305 -0
  64. package/dist/v3/zodSocket.mjs.map +1 -0
  65. package/package.json +72 -7
package/dist/v3/index.mjs CHANGED
@@ -1,21 +1,9 @@
1
+ import { propagation, context, trace, SpanStatusCode } from '@opentelemetry/api';
2
+ import { fromZodError } from 'zod-validation-error';
1
3
  import { z } from 'zod';
2
- import { SpanStatusCode, trace, propagation, context, DiagLogLevel, diag, DiagConsoleLogger, SpanKind } from '@opentelemetry/api';
3
- import { AsyncLocalStorage } from 'node:async_hooks';
4
- import { io } from 'socket.io-client';
5
- import { randomUUID } from 'crypto';
6
- import nodePath from 'node:path';
7
- import { SeverityNumber, logs } from '@opentelemetry/api-logs';
8
4
  import { PreciseDate } from '@google-cloud/precise-date';
5
+ import { logs } from '@opentelemetry/api-logs';
9
6
  import humanizeDuration from 'humanize-duration';
10
- import { setTimeout as setTimeout$1 } from 'node:timers/promises';
11
- import util from 'node:util';
12
- import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';
13
- import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
14
- import { registerInstrumentations } from '@opentelemetry/instrumentation';
15
- import { Resource, detectResourcesSync, processDetectorSync } from '@opentelemetry/resources';
16
- import { LoggerProvider, BatchLogRecordProcessor, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs';
17
- import { NodeTracerProvider, BatchSpanProcessor, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node';
18
- import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
19
7
 
20
8
  var __defProp = Object.defineProperty;
21
9
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -28,32 +16,394 @@ var __accessCheck = (obj, member, msg) => {
28
16
  if (!member.has(obj))
29
17
  throw TypeError("Cannot " + msg);
30
18
  };
31
- var __privateGet = (obj, member, getter) => {
32
- __accessCheck(obj, member, "read from private field");
33
- return getter ? getter.call(obj) : member.get(obj);
34
- };
35
19
  var __privateAdd = (obj, member, value) => {
36
20
  if (member.has(obj))
37
21
  throw TypeError("Cannot add the same private member more than once");
38
22
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
39
23
  };
40
- var __privateSet = (obj, member, value, setter) => {
41
- __accessCheck(obj, member, "write to private field");
42
- setter ? setter.call(obj, value) : member.set(obj, value);
43
- return value;
44
- };
45
- var __privateWrapper = (obj, member, setter, getter) => ({
46
- set _(value) {
47
- __privateSet(obj, member, value, setter);
48
- },
49
- get _() {
50
- return __privateGet(obj, member, getter);
51
- }
52
- });
53
24
  var __privateMethod = (obj, member, method) => {
54
25
  __accessCheck(obj, member, "access private method");
55
26
  return method;
56
27
  };
28
+
29
+ // src/v3/apiErrors.ts
30
+ var _APIError = class _APIError extends Error {
31
+ constructor(status, error, message, headers) {
32
+ super(`${_APIError.makeMessage(status, error, message)}`);
33
+ this.status = status;
34
+ this.headers = headers;
35
+ const data = error;
36
+ this.error = data;
37
+ this.code = data?.["code"];
38
+ this.param = data?.["param"];
39
+ this.type = data?.["type"];
40
+ }
41
+ static makeMessage(status, error, message) {
42
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
43
+ if (status && msg) {
44
+ return `${status} ${msg}`;
45
+ }
46
+ if (status) {
47
+ return `${status} status code (no body)`;
48
+ }
49
+ if (msg) {
50
+ return msg;
51
+ }
52
+ return "(no status code or body)";
53
+ }
54
+ static generate(status, errorResponse, message, headers) {
55
+ if (!status) {
56
+ return new APIConnectionError({
57
+ cause: castToError(errorResponse)
58
+ });
59
+ }
60
+ const error = errorResponse?.["error"];
61
+ if (status === 400) {
62
+ return new BadRequestError(status, error, message, headers);
63
+ }
64
+ if (status === 401) {
65
+ return new AuthenticationError(status, error, message, headers);
66
+ }
67
+ if (status === 403) {
68
+ return new PermissionDeniedError(status, error, message, headers);
69
+ }
70
+ if (status === 404) {
71
+ return new NotFoundError(status, error, message, headers);
72
+ }
73
+ if (status === 409) {
74
+ return new ConflictError(status, error, message, headers);
75
+ }
76
+ if (status === 422) {
77
+ return new UnprocessableEntityError(status, error, message, headers);
78
+ }
79
+ if (status === 429) {
80
+ return new RateLimitError(status, error, message, headers);
81
+ }
82
+ if (status >= 500) {
83
+ return new InternalServerError(status, error, message, headers);
84
+ }
85
+ return new _APIError(status, error, message, headers);
86
+ }
87
+ };
88
+ __name(_APIError, "APIError");
89
+ var APIError = _APIError;
90
+ var _APIConnectionError = class _APIConnectionError extends APIError {
91
+ constructor({ message, cause }) {
92
+ super(void 0, void 0, message || "Connection error.", void 0);
93
+ __publicField(this, "status");
94
+ if (cause)
95
+ this.cause = cause;
96
+ }
97
+ };
98
+ __name(_APIConnectionError, "APIConnectionError");
99
+ var APIConnectionError = _APIConnectionError;
100
+ var _BadRequestError = class _BadRequestError extends APIError {
101
+ constructor() {
102
+ super(...arguments);
103
+ __publicField(this, "status", 400);
104
+ }
105
+ };
106
+ __name(_BadRequestError, "BadRequestError");
107
+ var BadRequestError = _BadRequestError;
108
+ var _AuthenticationError = class _AuthenticationError extends APIError {
109
+ constructor() {
110
+ super(...arguments);
111
+ __publicField(this, "status", 401);
112
+ }
113
+ };
114
+ __name(_AuthenticationError, "AuthenticationError");
115
+ var AuthenticationError = _AuthenticationError;
116
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
117
+ constructor() {
118
+ super(...arguments);
119
+ __publicField(this, "status", 403);
120
+ }
121
+ };
122
+ __name(_PermissionDeniedError, "PermissionDeniedError");
123
+ var PermissionDeniedError = _PermissionDeniedError;
124
+ var _NotFoundError = class _NotFoundError extends APIError {
125
+ constructor() {
126
+ super(...arguments);
127
+ __publicField(this, "status", 404);
128
+ }
129
+ };
130
+ __name(_NotFoundError, "NotFoundError");
131
+ var NotFoundError = _NotFoundError;
132
+ var _ConflictError = class _ConflictError extends APIError {
133
+ constructor() {
134
+ super(...arguments);
135
+ __publicField(this, "status", 409);
136
+ }
137
+ };
138
+ __name(_ConflictError, "ConflictError");
139
+ var ConflictError = _ConflictError;
140
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
141
+ constructor() {
142
+ super(...arguments);
143
+ __publicField(this, "status", 422);
144
+ }
145
+ };
146
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
147
+ var UnprocessableEntityError = _UnprocessableEntityError;
148
+ var _RateLimitError = class _RateLimitError extends APIError {
149
+ constructor() {
150
+ super(...arguments);
151
+ __publicField(this, "status", 429);
152
+ }
153
+ };
154
+ __name(_RateLimitError, "RateLimitError");
155
+ var RateLimitError = _RateLimitError;
156
+ var _InternalServerError = class _InternalServerError extends APIError {
157
+ };
158
+ __name(_InternalServerError, "InternalServerError");
159
+ var InternalServerError = _InternalServerError;
160
+ function castToError(err) {
161
+ if (err instanceof Error)
162
+ return err;
163
+ return new Error(err);
164
+ }
165
+ __name(castToError, "castToError");
166
+
167
+ // src/retry.ts
168
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
169
+ if (!resets)
170
+ return;
171
+ switch (format) {
172
+ case "iso_8601_duration_openai_variant": {
173
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
174
+ }
175
+ case "iso_8601": {
176
+ return calculateISO8601ResetAt(resets, now);
177
+ }
178
+ case "unix_timestamp": {
179
+ return calculateUnixTimestampResetAt(resets, now);
180
+ }
181
+ case "unix_timestamp_in_ms": {
182
+ return calculateUnixTimestampInMsResetAt(resets, now);
183
+ }
184
+ }
185
+ }
186
+ __name(calculateResetAt, "calculateResetAt");
187
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
188
+ if (!resets)
189
+ return void 0;
190
+ const resetAt = parseInt(resets, 10);
191
+ if (isNaN(resetAt))
192
+ return void 0;
193
+ return new Date(resetAt * 1e3);
194
+ }
195
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
196
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
197
+ if (!resets)
198
+ return void 0;
199
+ const resetAt = parseInt(resets, 10);
200
+ if (isNaN(resetAt))
201
+ return void 0;
202
+ return new Date(resetAt);
203
+ }
204
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
205
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
206
+ if (!resets)
207
+ return void 0;
208
+ const resetAt = new Date(resets);
209
+ if (isNaN(resetAt.getTime()))
210
+ return void 0;
211
+ return resetAt;
212
+ }
213
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
214
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
215
+ if (!resets)
216
+ return void 0;
217
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
218
+ const match = resets.match(pattern);
219
+ if (!match)
220
+ return void 0;
221
+ const days = parseInt(match[1], 10) || 0;
222
+ const hours = parseInt(match[2], 10) || 0;
223
+ const minutes = parseInt(match[3], 10) || 0;
224
+ const seconds = parseFloat(match[4]) || 0;
225
+ const milliseconds = parseInt(match[5], 10) || 0;
226
+ const resetAt = new Date(now);
227
+ resetAt.setDate(resetAt.getDate() + days);
228
+ resetAt.setHours(resetAt.getHours() + hours);
229
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
230
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
231
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
232
+ return resetAt;
233
+ }
234
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
235
+
236
+ // src/v3/utils/retries.ts
237
+ var defaultRetryOptions = {
238
+ maxAttempts: 3,
239
+ factor: 2,
240
+ minTimeoutInMs: 1e3,
241
+ maxTimeoutInMs: 6e4,
242
+ randomize: true
243
+ };
244
+ var defaultFetchRetryOptions = {
245
+ byStatus: {
246
+ "429,408,409,5xx": {
247
+ strategy: "backoff",
248
+ ...defaultRetryOptions
249
+ }
250
+ },
251
+ connectionError: defaultRetryOptions,
252
+ timeout: defaultRetryOptions
253
+ };
254
+ function calculateNextRetryDelay(options, attempt) {
255
+ const opts = {
256
+ ...defaultRetryOptions,
257
+ ...options
258
+ };
259
+ if (attempt >= opts.maxAttempts) {
260
+ return;
261
+ }
262
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
263
+ const random = randomize ? Math.random() + 1 : 1;
264
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
265
+ return Math.round(timeout);
266
+ }
267
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
268
+ function calculateResetAt2(resets, format, now = Date.now()) {
269
+ const resetAt = calculateResetAt(resets, format, new Date(now));
270
+ return resetAt?.getTime();
271
+ }
272
+ __name(calculateResetAt2, "calculateResetAt");
273
+
274
+ // src/v3/zodfetch.ts
275
+ var defaultRetryOptions2 = {
276
+ maxAttempts: 3,
277
+ factor: 2,
278
+ minTimeoutInMs: 1e3,
279
+ maxTimeoutInMs: 6e4,
280
+ randomize: false
281
+ };
282
+ async function zodfetch(schema, url, requestInit, options) {
283
+ return await _doZodFetch(schema, url, requestInit, options);
284
+ }
285
+ __name(zodfetch, "zodfetch");
286
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
287
+ try {
288
+ const response = await fetch(url, requestInitWithCache(requestInit));
289
+ const responseHeaders = createResponseHeaders(response.headers);
290
+ if (!response.ok) {
291
+ const retryResult = shouldRetry(response, attempt, options?.retry);
292
+ if (retryResult.retry) {
293
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
294
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
295
+ } else {
296
+ const errText = await response.text().catch((e) => castToError2(e).message);
297
+ const errJSON = safeJsonParse(errText);
298
+ const errMessage = errJSON ? void 0 : errText;
299
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
300
+ }
301
+ }
302
+ const jsonBody = await response.json();
303
+ const parsedResult = schema.safeParse(jsonBody);
304
+ if (parsedResult.success) {
305
+ return parsedResult.data;
306
+ }
307
+ throw fromZodError(parsedResult.error);
308
+ } catch (error) {
309
+ if (error instanceof APIError) {
310
+ throw error;
311
+ }
312
+ if (options?.retry) {
313
+ const retry = {
314
+ ...defaultRetryOptions2,
315
+ ...options.retry
316
+ };
317
+ const delay = calculateNextRetryDelay(retry, attempt);
318
+ if (delay) {
319
+ await new Promise((resolve) => setTimeout(resolve, delay));
320
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
321
+ }
322
+ }
323
+ throw new APIConnectionError({
324
+ cause: castToError2(error)
325
+ });
326
+ }
327
+ }
328
+ __name(_doZodFetch, "_doZodFetch");
329
+ function castToError2(err) {
330
+ if (err instanceof Error)
331
+ return err;
332
+ return new Error(err);
333
+ }
334
+ __name(castToError2, "castToError");
335
+ function shouldRetry(response, attempt, retryOptions) {
336
+ function shouldRetryForOptions() {
337
+ const retry = {
338
+ ...defaultRetryOptions2,
339
+ ...retryOptions
340
+ };
341
+ const delay = calculateNextRetryDelay(retry, attempt);
342
+ if (delay) {
343
+ return {
344
+ retry: true,
345
+ delay
346
+ };
347
+ } else {
348
+ return {
349
+ retry: false
350
+ };
351
+ }
352
+ }
353
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
354
+ const shouldRetryHeader = response.headers.get("x-should-retry");
355
+ if (shouldRetryHeader === "true")
356
+ return shouldRetryForOptions();
357
+ if (shouldRetryHeader === "false")
358
+ return {
359
+ retry: false
360
+ };
361
+ if (response.status === 408)
362
+ return shouldRetryForOptions();
363
+ if (response.status === 409)
364
+ return shouldRetryForOptions();
365
+ if (response.status === 429)
366
+ return shouldRetryForOptions();
367
+ if (response.status >= 500)
368
+ return shouldRetryForOptions();
369
+ return {
370
+ retry: false
371
+ };
372
+ }
373
+ __name(shouldRetry, "shouldRetry");
374
+ function safeJsonParse(text) {
375
+ try {
376
+ return JSON.parse(text);
377
+ } catch (e) {
378
+ return void 0;
379
+ }
380
+ }
381
+ __name(safeJsonParse, "safeJsonParse");
382
+ function createResponseHeaders(headers) {
383
+ return new Proxy(Object.fromEntries(
384
+ // @ts-ignore
385
+ headers.entries()
386
+ ), {
387
+ get(target, name) {
388
+ const key = name.toString();
389
+ return target[key.toLowerCase()] || target[key];
390
+ }
391
+ });
392
+ }
393
+ __name(createResponseHeaders, "createResponseHeaders");
394
+ function requestInitWithCache(requestInit) {
395
+ try {
396
+ const withCache = {
397
+ ...requestInit,
398
+ cache: "no-cache"
399
+ };
400
+ const _ = new Request("http://localhost", withCache);
401
+ return withCache;
402
+ } catch (error) {
403
+ return requestInit ?? {};
404
+ }
405
+ }
406
+ __name(requestInitWithCache, "requestInitWithCache");
57
407
  var CreateAuthorizationCodeResponseSchema = z.object({
58
408
  url: z.string().url(),
59
409
  authorizationCode: z.string()
@@ -83,6 +433,7 @@ var TaskRunStringError = z.object({
83
433
  });
84
434
  var TaskRunErrorCodes = {
85
435
  COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
436
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
86
437
  CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
87
438
  TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
88
439
  TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
@@ -90,12 +441,14 @@ var TaskRunErrorCodes = {
90
441
  TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
91
442
  TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
92
443
  TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
93
- HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR"
444
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
445
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
94
446
  };
95
447
  var TaskRunInternalError = z.object({
96
448
  type: z.literal("INTERNAL_ERROR"),
97
449
  code: z.enum([
98
450
  "COULD_NOT_FIND_EXECUTOR",
451
+ "COULD_NOT_FIND_TASK",
99
452
  "CONFIGURED_INCORRECTLY",
100
453
  "TASK_ALREADY_RUNNING",
101
454
  "TASK_EXECUTION_FAILED",
@@ -103,7 +456,8 @@ var TaskRunInternalError = z.object({
103
456
  "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
104
457
  "TASK_RUN_CANCELLED",
105
458
  "TASK_OUTPUT_ERROR",
106
- "HANDLE_ERROR_ERROR"
459
+ "HANDLE_ERROR_ERROR",
460
+ "GRACEFUL_EXIT_TIMEOUT"
107
461
  ]),
108
462
  message: z.string().optional()
109
463
  });
@@ -120,7 +474,8 @@ var TaskRun = z.object({
120
474
  context: z.any(),
121
475
  tags: z.array(z.string()),
122
476
  isTest: z.boolean().default(false),
123
- createdAt: z.coerce.date()
477
+ createdAt: z.coerce.date(),
478
+ idempotencyKey: z.string().optional()
124
479
  });
125
480
  var TaskRunExecutionTask = z.object({
126
481
  id: z.string(),
@@ -216,7 +571,7 @@ var BatchTaskRunExecutionResult = z.object({
216
571
  items: TaskRunExecutionResult.array()
217
572
  });
218
573
 
219
- // src/v3/schemas/messages.ts
574
+ // src/v3/schemas/schemas.ts
220
575
  var EnvironmentType = z.enum([
221
576
  "PRODUCTION",
222
577
  "STAGING",
@@ -260,92 +615,6 @@ var ProdTaskRunExecutionPayload = z.object({
260
615
  traceContext: z.record(z.unknown()),
261
616
  environment: z.record(z.string()).optional()
262
617
  });
263
- var BackgroundWorkerServerMessages = z.discriminatedUnion("type", [
264
- z.object({
265
- type: z.literal("EXECUTE_RUNS"),
266
- payloads: z.array(TaskRunExecutionPayload)
267
- }),
268
- z.object({
269
- type: z.literal("CANCEL_ATTEMPT"),
270
- taskAttemptId: z.string(),
271
- taskRunId: z.string()
272
- }),
273
- z.object({
274
- type: z.literal("SCHEDULE_ATTEMPT"),
275
- image: z.string(),
276
- version: z.string(),
277
- machine: Machine,
278
- // identifiers
279
- id: z.string(),
280
- envId: z.string(),
281
- envType: EnvironmentType,
282
- orgId: z.string(),
283
- projectId: z.string(),
284
- runId: z.string()
285
- })
286
- ]);
287
- var serverWebsocketMessages = {
288
- SERVER_READY: z.object({
289
- version: z.literal("v1").default("v1"),
290
- id: z.string()
291
- }),
292
- BACKGROUND_WORKER_MESSAGE: z.object({
293
- version: z.literal("v1").default("v1"),
294
- backgroundWorkerId: z.string(),
295
- data: BackgroundWorkerServerMessages
296
- })
297
- };
298
- var BackgroundWorkerClientMessages = z.discriminatedUnion("type", [
299
- z.object({
300
- version: z.literal("v1").default("v1"),
301
- type: z.literal("TASK_RUN_COMPLETED"),
302
- completion: TaskRunExecutionResult,
303
- execution: TaskRunExecution
304
- }),
305
- z.object({
306
- version: z.literal("v1").default("v1"),
307
- type: z.literal("TASK_HEARTBEAT"),
308
- id: z.string()
309
- })
310
- ]);
311
- var BackgroundWorkerProperties = z.object({
312
- id: z.string(),
313
- version: z.string(),
314
- contentHash: z.string()
315
- });
316
- var clientWebsocketMessages = {
317
- READY_FOR_TASKS: z.object({
318
- version: z.literal("v1").default("v1"),
319
- backgroundWorkerId: z.string()
320
- }),
321
- BACKGROUND_WORKER_DEPRECATED: z.object({
322
- version: z.literal("v1").default("v1"),
323
- backgroundWorkerId: z.string()
324
- }),
325
- BACKGROUND_WORKER_MESSAGE: z.object({
326
- version: z.literal("v1").default("v1"),
327
- backgroundWorkerId: z.string(),
328
- data: BackgroundWorkerClientMessages
329
- })
330
- };
331
- var workerToChildMessages = {
332
- EXECUTE_TASK_RUN: z.object({
333
- version: z.literal("v1").default("v1"),
334
- execution: TaskRunExecution,
335
- traceContext: z.record(z.unknown()),
336
- metadata: BackgroundWorkerProperties
337
- }),
338
- TASK_RUN_COMPLETED_NOTIFICATION: z.object({
339
- version: z.literal("v1").default("v1"),
340
- completion: TaskRunExecutionResult,
341
- execution: TaskRunExecution
342
- }),
343
- CLEANUP: z.object({
344
- version: z.literal("v1").default("v1"),
345
- flush: z.boolean().default(false),
346
- kill: z.boolean().default(true)
347
- })
348
- };
349
618
  var FixedWindowRateLimit = z.object({
350
619
  type: z.literal("fixed-window"),
351
620
  limit: z.number(),
@@ -440,158 +709,57 @@ var QueueOptions = z.object({
440
709
  });
441
710
  var TaskMetadata = z.object({
442
711
  id: z.string(),
443
- exportName: z.string(),
444
712
  packageVersion: z.string(),
445
713
  queue: QueueOptions.optional(),
446
714
  retry: RetryOptions.optional(),
447
- machine: Machine.partial().optional()
715
+ machine: Machine.partial().optional(),
716
+ triggerSource: z.string().optional()
448
717
  });
449
- var TaskMetadataWithFilePath = TaskMetadata.extend({
450
- filePath: z.string()
718
+ var TaskFileMetadata = z.object({
719
+ filePath: z.string(),
720
+ exportName: z.string()
451
721
  });
452
- var UncaughtExceptionMessage = z.object({
453
- version: z.literal("v1").default("v1"),
454
- error: z.object({
455
- name: z.string(),
456
- message: z.string(),
457
- stack: z.string().optional()
458
- }),
459
- origin: z.enum([
460
- "uncaughtException",
461
- "unhandledRejection"
462
- ])
722
+ var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
723
+ var PostStartCauses = z.enum([
724
+ "index",
725
+ "create",
726
+ "restore"
727
+ ]);
728
+ var PreStopCauses = z.enum([
729
+ "terminate"
730
+ ]);
731
+ var RegexSchema = z.custom((val) => {
732
+ try {
733
+ return typeof val.test === "function";
734
+ } catch {
735
+ return false;
736
+ }
463
737
  });
464
- var TaskMetadataFailedToParseData = z.object({
465
- version: z.literal("v1").default("v1"),
466
- tasks: z.unknown(),
467
- zodIssues: z.custom((v) => {
468
- return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
469
- })
738
+ var Config = z.object({
739
+ project: z.string(),
740
+ triggerDirectories: z.string().array().optional(),
741
+ triggerUrl: z.string().optional(),
742
+ projectDir: z.string().optional(),
743
+ tsconfigPath: z.string().optional(),
744
+ retries: z.object({
745
+ enabledInDev: z.boolean().default(true),
746
+ default: RetryOptions.optional()
747
+ }).optional(),
748
+ additionalPackages: z.string().array().optional(),
749
+ additionalFiles: z.string().array().optional(),
750
+ dependenciesToBundle: z.array(z.union([
751
+ z.string(),
752
+ RegexSchema
753
+ ])).optional(),
754
+ logLevel: z.string().optional(),
755
+ enableConsoleLogging: z.boolean().optional(),
756
+ postInstall: z.string().optional()
470
757
  });
471
- var childToWorkerMessages = {
472
- TASK_RUN_COMPLETED: z.object({
473
- version: z.literal("v1").default("v1"),
474
- execution: TaskRunExecution,
475
- result: TaskRunExecutionResult
476
- }),
477
- TASKS_READY: z.object({
478
- version: z.literal("v1").default("v1"),
479
- tasks: TaskMetadataWithFilePath.array()
480
- }),
481
- TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
482
- TASK_HEARTBEAT: z.object({
483
- version: z.literal("v1").default("v1"),
484
- id: z.string()
485
- }),
486
- READY_TO_DISPOSE: z.undefined(),
487
- WAIT_FOR_DURATION: z.object({
488
- version: z.literal("v1").default("v1"),
489
- ms: z.number()
490
- }),
491
- WAIT_FOR_TASK: z.object({
492
- version: z.literal("v1").default("v1"),
493
- id: z.string()
494
- }),
495
- WAIT_FOR_BATCH: z.object({
496
- version: z.literal("v1").default("v1"),
497
- id: z.string(),
498
- runs: z.string().array()
499
- }),
500
- UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
501
- };
502
- var ProdChildToWorkerMessages = {
503
- TASK_RUN_COMPLETED: {
504
- message: z.object({
505
- version: z.literal("v1").default("v1"),
506
- execution: TaskRunExecution,
507
- result: TaskRunExecutionResult
508
- })
509
- },
510
- TASKS_READY: {
511
- message: z.object({
512
- version: z.literal("v1").default("v1"),
513
- tasks: TaskMetadataWithFilePath.array()
514
- })
515
- },
516
- TASKS_FAILED_TO_PARSE: {
517
- message: TaskMetadataFailedToParseData
518
- },
519
- TASK_HEARTBEAT: {
520
- message: z.object({
521
- version: z.literal("v1").default("v1"),
522
- id: z.string()
523
- })
524
- },
525
- READY_TO_DISPOSE: {
526
- message: z.undefined()
527
- },
528
- READY_FOR_CHECKPOINT: {
529
- message: z.object({
530
- version: z.literal("v1").default("v1")
531
- })
532
- },
533
- CANCEL_CHECKPOINT: {
534
- message: z.object({
535
- version: z.literal("v1").default("v1")
536
- })
537
- },
538
- WAIT_FOR_DURATION: {
539
- message: z.object({
540
- version: z.literal("v1").default("v1"),
541
- ms: z.number(),
542
- now: z.number()
543
- }),
544
- callback: z.object({
545
- willCheckpointAndRestore: z.boolean()
546
- })
547
- },
548
- WAIT_FOR_TASK: {
549
- message: z.object({
550
- version: z.literal("v1").default("v1"),
551
- friendlyId: z.string()
552
- })
553
- },
554
- WAIT_FOR_BATCH: {
555
- message: z.object({
556
- version: z.literal("v1").default("v1"),
557
- batchFriendlyId: z.string(),
558
- runFriendlyIds: z.string().array()
559
- })
560
- },
561
- UNCAUGHT_EXCEPTION: {
562
- message: UncaughtExceptionMessage
563
- }
564
- };
565
- var ProdWorkerToChildMessages = {
566
- EXECUTE_TASK_RUN: {
567
- message: z.object({
568
- version: z.literal("v1").default("v1"),
569
- execution: TaskRunExecution,
570
- traceContext: z.record(z.unknown()),
571
- metadata: BackgroundWorkerProperties
572
- })
573
- },
574
- TASK_RUN_COMPLETED_NOTIFICATION: {
575
- message: z.object({
576
- version: z.literal("v1").default("v1"),
577
- completion: TaskRunExecutionResult,
578
- execution: TaskRunExecution
579
- })
580
- },
581
- CLEANUP: {
582
- message: z.object({
583
- version: z.literal("v1").default("v1"),
584
- flush: z.boolean().default(false),
585
- kill: z.boolean().default(true)
586
- }),
587
- callback: z.void()
588
- },
589
- WAIT_COMPLETED_NOTIFICATION: {
590
- message: z.object({
591
- version: z.literal("v1").default("v1")
592
- })
593
- }
594
- };
758
+ var WaitReason = z.enum([
759
+ "WAIT_FOR_DURATION",
760
+ "WAIT_FOR_TASK",
761
+ "WAIT_FOR_BATCH"
762
+ ]);
595
763
 
596
764
  // src/v3/schemas/resources.ts
597
765
  var TaskResource = z.object({
@@ -600,7 +768,8 @@ var TaskResource = z.object({
600
768
  exportName: z.string(),
601
769
  queue: QueueOptions.optional(),
602
770
  retry: RetryOptions.optional(),
603
- machine: Machine.partial().optional()
771
+ machine: Machine.partial().optional(),
772
+ triggerSource: z.string().optional()
604
773
  });
605
774
  var BackgroundWorkerMetadata = z.object({
606
775
  packageVersion: z.string(),
@@ -656,7 +825,9 @@ var TriggerTaskRequestBody = z.object({
656
825
  lockToVersion: z.string().optional(),
657
826
  queue: QueueOptions.optional(),
658
827
  concurrencyKey: z.string().optional(),
659
- test: z.boolean().optional()
828
+ idempotencyKey: z.string().optional(),
829
+ test: z.boolean().optional(),
830
+ payloadType: z.string().optional()
660
831
  }).optional()
661
832
  });
662
833
  var TriggerTaskResponse = z.object({
@@ -687,7 +858,8 @@ var GetEnvironmentVariablesResponseBody = z.object({
687
858
  variables: z.record(z.string())
688
859
  });
689
860
  var StartDeploymentIndexingRequestBody = z.object({
690
- imageReference: z.string()
861
+ imageReference: z.string(),
862
+ selfHosted: z.boolean().optional()
691
863
  });
692
864
  var StartDeploymentIndexingResponseBody = z.object({
693
865
  id: z.string(),
@@ -746,131 +918,478 @@ var GetDeploymentResponseBody = z.object({
746
918
  var CreateUploadPayloadUrlResponseBody = z.object({
747
919
  presignedUrl: z.string()
748
920
  });
749
- var PostStartCauses = z.enum([
750
- "index",
751
- "create",
752
- "restore"
921
+ var ReplayRunResponse = z.object({
922
+ id: z.string()
923
+ });
924
+ var CanceledRunResponse = z.object({
925
+ message: z.string()
926
+ });
927
+ var ScheduledTaskPayload = z.object({
928
+ /** The schedule id associated with this run (you can have many schedules for the same task).
929
+ You can use this to remove the schedule, update it, etc */
930
+ scheduleId: z.string(),
931
+ /** When the task was scheduled to run.
932
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
933
+ timestamp: z.date(),
934
+ /** When the task was last run (it has been).
935
+ This can be undefined if it's never been run */
936
+ lastTimestamp: z.date().optional(),
937
+ /** You can optionally provide an external id when creating the schedule.
938
+ Usually you would use a userId or some other unique identifier.
939
+ This defaults to undefined if you didn't provide one. */
940
+ externalId: z.string().optional(),
941
+ /** The next 5 dates this task is scheduled to run */
942
+ upcoming: z.array(z.date())
943
+ });
944
+ var CreateScheduleOptions = z.object({
945
+ /** The id of the task you want to attach to. */
946
+ task: z.string(),
947
+ /** The schedule in CRON format.
948
+ *
949
+ * ```txt
950
+ * * * * * *
951
+ ┬ ┬ ┬ ┬ ┬
952
+ │ │ │ │ |
953
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
954
+ │ │ │ └───── month (1 - 12)
955
+ │ │ └────────── day of month (1 - 31, L)
956
+ │ └─────────────── hour (0 - 23)
957
+ └──────────────────── minute (0 - 59)
958
+ * ```
959
+
960
+ "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.
961
+
962
+ */
963
+ cron: z.string(),
964
+ /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
965
+ *
966
+ * This is useful if you don't want to create duplicate schedules for a user. */
967
+ deduplicationKey: z.string().optional(),
968
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
969
+ *
970
+ * This allows you to have per-user CRON tasks.
971
+ */
972
+ externalId: z.string().optional()
973
+ });
974
+ var UpdateScheduleOptions = CreateScheduleOptions;
975
+ var ScheduleObject = z.object({
976
+ id: z.string(),
977
+ task: z.string(),
978
+ active: z.boolean(),
979
+ deduplicationKey: z.string().nullish(),
980
+ externalId: z.string().nullish(),
981
+ generator: z.object({
982
+ type: z.literal("CRON"),
983
+ expression: z.string(),
984
+ description: z.string()
985
+ }),
986
+ nextRun: z.coerce.date().nullish(),
987
+ environments: z.array(z.object({
988
+ id: z.string(),
989
+ type: z.string(),
990
+ userName: z.string().nullish()
991
+ }))
992
+ });
993
+ var DeletedScheduleObject = z.object({
994
+ id: z.string()
995
+ });
996
+ var ListSchedulesResult = z.object({
997
+ data: z.array(ScheduleObject),
998
+ pagination: z.object({
999
+ currentPage: z.number(),
1000
+ totalPages: z.number(),
1001
+ count: z.number()
1002
+ })
1003
+ });
1004
+ var ListScheduleOptions = z.object({
1005
+ page: z.number().optional(),
1006
+ perPage: z.number().optional()
1007
+ });
1008
+ var RunStatus = z.enum([
1009
+ "PENDING",
1010
+ "EXECUTING",
1011
+ "PAUSED",
1012
+ "COMPLETED",
1013
+ "FAILED",
1014
+ "CANCELED"
753
1015
  ]);
754
- var PreStopCauses = z.enum([
755
- "terminate"
1016
+ var AttemptStatus = z.enum([
1017
+ "PENDING",
1018
+ "EXECUTING",
1019
+ "PAUSED",
1020
+ "COMPLETED",
1021
+ "FAILED",
1022
+ "CANCELED"
756
1023
  ]);
757
- var RegexSchema = z.custom((val) => {
758
- try {
759
- return typeof val.test === "function";
760
- } catch {
761
- return false;
762
- }
763
- });
764
- var Config = z.object({
765
- project: z.string(),
766
- triggerDirectories: z.string().array().optional(),
767
- triggerUrl: z.string().optional(),
768
- projectDir: z.string().optional(),
769
- tsconfigPath: z.string().optional(),
770
- retries: z.object({
771
- enabledInDev: z.boolean().default(true),
772
- default: RetryOptions.optional()
773
- }).optional(),
774
- additionalPackages: z.string().array().optional(),
775
- additionalFiles: z.string().array().optional(),
776
- dependenciesToBundle: z.array(z.union([
777
- z.string(),
778
- RegexSchema
779
- ])).optional(),
780
- logLevel: z.string().optional()
1024
+ var RetrieveRunResponse = z.object({
1025
+ id: z.string(),
1026
+ status: RunStatus,
1027
+ taskIdentifier: z.string(),
1028
+ idempotencyKey: z.string().optional(),
1029
+ version: z.string().optional(),
1030
+ createdAt: z.coerce.date(),
1031
+ updatedAt: z.coerce.date(),
1032
+ attempts: z.array(z.object({
1033
+ id: z.string(),
1034
+ status: AttemptStatus,
1035
+ createdAt: z.coerce.date(),
1036
+ updatedAt: z.coerce.date(),
1037
+ startedAt: z.coerce.date().optional(),
1038
+ completedAt: z.coerce.date().optional()
1039
+ }).optional())
781
1040
  });
782
- var WaitReason = z.enum([
783
- "WAIT_FOR_DURATION",
784
- "WAIT_FOR_TASK",
785
- "WAIT_FOR_BATCH"
1041
+ var BackgroundWorkerServerMessages = z.discriminatedUnion("type", [
1042
+ z.object({
1043
+ type: z.literal("EXECUTE_RUNS"),
1044
+ payloads: z.array(TaskRunExecutionPayload)
1045
+ }),
1046
+ z.object({
1047
+ type: z.literal("CANCEL_ATTEMPT"),
1048
+ taskAttemptId: z.string(),
1049
+ taskRunId: z.string()
1050
+ }),
1051
+ z.object({
1052
+ type: z.literal("SCHEDULE_ATTEMPT"),
1053
+ image: z.string(),
1054
+ version: z.string(),
1055
+ machine: Machine,
1056
+ // identifiers
1057
+ id: z.string(),
1058
+ envId: z.string(),
1059
+ envType: EnvironmentType,
1060
+ orgId: z.string(),
1061
+ projectId: z.string(),
1062
+ runId: z.string()
1063
+ })
786
1064
  ]);
787
- var ProviderToPlatformMessages = {
788
- LOG: {
1065
+ var serverWebsocketMessages = {
1066
+ SERVER_READY: z.object({
1067
+ version: z.literal("v1").default("v1"),
1068
+ id: z.string()
1069
+ }),
1070
+ BACKGROUND_WORKER_MESSAGE: z.object({
1071
+ version: z.literal("v1").default("v1"),
1072
+ backgroundWorkerId: z.string(),
1073
+ data: BackgroundWorkerServerMessages
1074
+ })
1075
+ };
1076
+ var BackgroundWorkerClientMessages = z.discriminatedUnion("type", [
1077
+ z.object({
1078
+ version: z.literal("v1").default("v1"),
1079
+ type: z.literal("TASK_RUN_COMPLETED"),
1080
+ completion: TaskRunExecutionResult,
1081
+ execution: TaskRunExecution
1082
+ }),
1083
+ z.object({
1084
+ version: z.literal("v1").default("v1"),
1085
+ type: z.literal("TASK_HEARTBEAT"),
1086
+ id: z.string()
1087
+ })
1088
+ ]);
1089
+ var BackgroundWorkerProperties = z.object({
1090
+ id: z.string(),
1091
+ version: z.string(),
1092
+ contentHash: z.string()
1093
+ });
1094
+ var clientWebsocketMessages = {
1095
+ READY_FOR_TASKS: z.object({
1096
+ version: z.literal("v1").default("v1"),
1097
+ backgroundWorkerId: z.string()
1098
+ }),
1099
+ BACKGROUND_WORKER_DEPRECATED: z.object({
1100
+ version: z.literal("v1").default("v1"),
1101
+ backgroundWorkerId: z.string()
1102
+ }),
1103
+ BACKGROUND_WORKER_MESSAGE: z.object({
1104
+ version: z.literal("v1").default("v1"),
1105
+ backgroundWorkerId: z.string(),
1106
+ data: BackgroundWorkerClientMessages
1107
+ })
1108
+ };
1109
+ var workerToChildMessages = {
1110
+ EXECUTE_TASK_RUN: z.object({
1111
+ version: z.literal("v1").default("v1"),
1112
+ execution: TaskRunExecution,
1113
+ traceContext: z.record(z.unknown()),
1114
+ metadata: BackgroundWorkerProperties
1115
+ }),
1116
+ TASK_RUN_COMPLETED_NOTIFICATION: z.object({
1117
+ version: z.literal("v1").default("v1"),
1118
+ completion: TaskRunExecutionResult,
1119
+ execution: TaskRunExecution
1120
+ }),
1121
+ CLEANUP: z.object({
1122
+ version: z.literal("v1").default("v1"),
1123
+ flush: z.boolean().default(false),
1124
+ kill: z.boolean().default(true)
1125
+ })
1126
+ };
1127
+ var UncaughtExceptionMessage = z.object({
1128
+ version: z.literal("v1").default("v1"),
1129
+ error: z.object({
1130
+ name: z.string(),
1131
+ message: z.string(),
1132
+ stack: z.string().optional()
1133
+ }),
1134
+ origin: z.enum([
1135
+ "uncaughtException",
1136
+ "unhandledRejection"
1137
+ ])
1138
+ });
1139
+ var TaskMetadataFailedToParseData = z.object({
1140
+ version: z.literal("v1").default("v1"),
1141
+ tasks: z.unknown(),
1142
+ zodIssues: z.custom((v) => {
1143
+ return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
1144
+ })
1145
+ });
1146
+ var childToWorkerMessages = {
1147
+ TASK_RUN_COMPLETED: z.object({
1148
+ version: z.literal("v1").default("v1"),
1149
+ execution: TaskRunExecution,
1150
+ result: TaskRunExecutionResult
1151
+ }),
1152
+ TASKS_READY: z.object({
1153
+ version: z.literal("v1").default("v1"),
1154
+ tasks: TaskMetadataWithFilePath.array()
1155
+ }),
1156
+ TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
1157
+ TASK_HEARTBEAT: z.object({
1158
+ version: z.literal("v1").default("v1"),
1159
+ id: z.string()
1160
+ }),
1161
+ READY_TO_DISPOSE: z.undefined(),
1162
+ WAIT_FOR_DURATION: z.object({
1163
+ version: z.literal("v1").default("v1"),
1164
+ ms: z.number()
1165
+ }),
1166
+ WAIT_FOR_TASK: z.object({
1167
+ version: z.literal("v1").default("v1"),
1168
+ id: z.string()
1169
+ }),
1170
+ WAIT_FOR_BATCH: z.object({
1171
+ version: z.literal("v1").default("v1"),
1172
+ id: z.string(),
1173
+ runs: z.string().array()
1174
+ }),
1175
+ UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
1176
+ };
1177
+ var ProdChildToWorkerMessages = {
1178
+ TASK_RUN_COMPLETED: {
789
1179
  message: z.object({
790
1180
  version: z.literal("v1").default("v1"),
791
- data: z.string()
1181
+ execution: TaskRunExecution,
1182
+ result: TaskRunExecutionResult
792
1183
  })
793
1184
  },
794
- LOG_WITH_ACK: {
1185
+ TASKS_READY: {
795
1186
  message: z.object({
796
1187
  version: z.literal("v1").default("v1"),
797
- data: z.string()
798
- }),
799
- callback: z.object({
800
- status: z.literal("ok")
1188
+ tasks: TaskMetadataWithFilePath.array()
801
1189
  })
802
- }
803
- };
804
- var PlatformToProviderMessages = {
805
- HEALTH: {
1190
+ },
1191
+ TASKS_FAILED_TO_PARSE: {
1192
+ message: TaskMetadataFailedToParseData
1193
+ },
1194
+ TASK_HEARTBEAT: {
806
1195
  message: z.object({
807
- version: z.literal("v1").default("v1")
808
- }),
809
- callback: z.object({
810
- status: z.literal("ok")
1196
+ version: z.literal("v1").default("v1"),
1197
+ id: z.string()
811
1198
  })
812
1199
  },
813
- INDEX: {
1200
+ READY_TO_DISPOSE: {
1201
+ message: z.undefined()
1202
+ },
1203
+ READY_FOR_CHECKPOINT: {
814
1204
  message: z.object({
815
- version: z.literal("v1").default("v1"),
816
- imageTag: z.string(),
817
- shortCode: z.string(),
818
- apiKey: z.string(),
819
- apiUrl: z.string(),
820
- // identifiers
821
- envId: z.string(),
822
- envType: EnvironmentType,
823
- orgId: z.string(),
824
- projectId: z.string()
825
- }),
826
- callback: z.discriminatedUnion("success", [
1205
+ version: z.literal("v1").default("v1")
1206
+ })
1207
+ },
1208
+ CANCEL_CHECKPOINT: {
1209
+ message: z.discriminatedUnion("version", [
827
1210
  z.object({
828
- success: z.literal(false),
829
- error: z.object({
830
- name: z.string(),
831
- message: z.string(),
832
- stack: z.string().optional()
833
- })
1211
+ version: z.literal("v1")
834
1212
  }),
835
1213
  z.object({
836
- success: z.literal(true)
1214
+ version: z.literal("v2"),
1215
+ reason: WaitReason.optional()
837
1216
  })
838
- ])
1217
+ ]).default({
1218
+ version: "v1"
1219
+ }),
1220
+ callback: z.object({
1221
+ // TODO: Figure out how best to handle callback schema parsing in zod IPC
1222
+ version: z.literal("v2"),
1223
+ checkpointCanceled: z.boolean(),
1224
+ reason: WaitReason.optional()
1225
+ })
839
1226
  },
840
- // TODO: this should be a shared queue message instead
841
- RESTORE: {
1227
+ WAIT_FOR_DURATION: {
842
1228
  message: z.object({
843
1229
  version: z.literal("v1").default("v1"),
844
- type: z.enum([
845
- "DOCKER",
846
- "KUBERNETES"
847
- ]),
848
- location: z.string(),
849
- reason: z.string().optional(),
850
- imageRef: z.string(),
851
- machine: Machine,
852
- // identifiers
853
- checkpointId: z.string(),
854
- envId: z.string(),
855
- envType: EnvironmentType,
856
- orgId: z.string(),
857
- projectId: z.string(),
858
- runId: z.string()
1230
+ ms: z.number(),
1231
+ now: z.number()
1232
+ }),
1233
+ callback: z.object({
1234
+ willCheckpointAndRestore: z.boolean()
859
1235
  })
860
1236
  },
861
- DELETE: {
1237
+ WAIT_FOR_TASK: {
862
1238
  message: z.object({
863
1239
  version: z.literal("v1").default("v1"),
864
- name: z.string()
865
- }),
866
- callback: z.object({
867
- message: z.string()
1240
+ friendlyId: z.string()
868
1241
  })
869
1242
  },
870
- GET: {
1243
+ WAIT_FOR_BATCH: {
871
1244
  message: z.object({
872
1245
  version: z.literal("v1").default("v1"),
873
- name: z.string()
1246
+ batchFriendlyId: z.string(),
1247
+ runFriendlyIds: z.string().array()
1248
+ })
1249
+ },
1250
+ UNCAUGHT_EXCEPTION: {
1251
+ message: UncaughtExceptionMessage
1252
+ }
1253
+ };
1254
+ var ProdWorkerToChildMessages = {
1255
+ EXECUTE_TASK_RUN: {
1256
+ message: z.object({
1257
+ version: z.literal("v1").default("v1"),
1258
+ execution: TaskRunExecution,
1259
+ traceContext: z.record(z.unknown()),
1260
+ metadata: BackgroundWorkerProperties
1261
+ })
1262
+ },
1263
+ TASK_RUN_COMPLETED_NOTIFICATION: {
1264
+ message: z.object({
1265
+ version: z.literal("v1").default("v1"),
1266
+ completion: TaskRunExecutionResult,
1267
+ execution: TaskRunExecution
1268
+ })
1269
+ },
1270
+ CLEANUP: {
1271
+ message: z.object({
1272
+ version: z.literal("v1").default("v1"),
1273
+ flush: z.boolean().default(false),
1274
+ kill: z.boolean().default(true)
1275
+ }),
1276
+ callback: z.void()
1277
+ },
1278
+ WAIT_COMPLETED_NOTIFICATION: {
1279
+ message: z.object({
1280
+ version: z.literal("v1").default("v1")
1281
+ })
1282
+ }
1283
+ };
1284
+ var ProviderToPlatformMessages = {
1285
+ LOG: {
1286
+ message: z.object({
1287
+ version: z.literal("v1").default("v1"),
1288
+ data: z.string()
1289
+ })
1290
+ },
1291
+ LOG_WITH_ACK: {
1292
+ message: z.object({
1293
+ version: z.literal("v1").default("v1"),
1294
+ data: z.string()
1295
+ }),
1296
+ callback: z.object({
1297
+ status: z.literal("ok")
1298
+ })
1299
+ },
1300
+ WORKER_CRASHED: {
1301
+ message: z.object({
1302
+ version: z.literal("v1").default("v1"),
1303
+ runId: z.string(),
1304
+ reason: z.string().optional(),
1305
+ exitCode: z.number().optional(),
1306
+ message: z.string().optional(),
1307
+ logs: z.string().optional()
1308
+ })
1309
+ },
1310
+ INDEXING_FAILED: {
1311
+ message: z.object({
1312
+ version: z.literal("v1").default("v1"),
1313
+ deploymentId: z.string(),
1314
+ error: z.object({
1315
+ name: z.string(),
1316
+ message: z.string(),
1317
+ stack: z.string().optional()
1318
+ })
1319
+ })
1320
+ }
1321
+ };
1322
+ var PlatformToProviderMessages = {
1323
+ HEALTH: {
1324
+ message: z.object({
1325
+ version: z.literal("v1").default("v1")
1326
+ }),
1327
+ callback: z.object({
1328
+ status: z.literal("ok")
1329
+ })
1330
+ },
1331
+ INDEX: {
1332
+ message: z.object({
1333
+ version: z.literal("v1").default("v1"),
1334
+ imageTag: z.string(),
1335
+ shortCode: z.string(),
1336
+ apiKey: z.string(),
1337
+ apiUrl: z.string(),
1338
+ // identifiers
1339
+ envId: z.string(),
1340
+ envType: EnvironmentType,
1341
+ orgId: z.string(),
1342
+ projectId: z.string(),
1343
+ deploymentId: z.string()
1344
+ }),
1345
+ callback: z.discriminatedUnion("success", [
1346
+ z.object({
1347
+ success: z.literal(false),
1348
+ error: z.object({
1349
+ name: z.string(),
1350
+ message: z.string(),
1351
+ stack: z.string().optional()
1352
+ })
1353
+ }),
1354
+ z.object({
1355
+ success: z.literal(true)
1356
+ })
1357
+ ])
1358
+ },
1359
+ // TODO: this should be a shared queue message instead
1360
+ RESTORE: {
1361
+ message: z.object({
1362
+ version: z.literal("v1").default("v1"),
1363
+ type: z.enum([
1364
+ "DOCKER",
1365
+ "KUBERNETES"
1366
+ ]),
1367
+ location: z.string(),
1368
+ reason: z.string().optional(),
1369
+ imageRef: z.string(),
1370
+ machine: Machine,
1371
+ // identifiers
1372
+ checkpointId: z.string(),
1373
+ envId: z.string(),
1374
+ envType: EnvironmentType,
1375
+ orgId: z.string(),
1376
+ projectId: z.string(),
1377
+ runId: z.string()
1378
+ })
1379
+ },
1380
+ DELETE: {
1381
+ message: z.object({
1382
+ version: z.literal("v1").default("v1"),
1383
+ name: z.string()
1384
+ }),
1385
+ callback: z.object({
1386
+ message: z.string()
1387
+ })
1388
+ },
1389
+ GET: {
1390
+ message: z.object({
1391
+ version: z.literal("v1").default("v1"),
1392
+ name: z.string()
874
1393
  })
875
1394
  }
876
1395
  };
@@ -1096,8 +1615,21 @@ var ProdWorkerToCoordinatorMessages = {
1096
1615
  })
1097
1616
  },
1098
1617
  CANCEL_CHECKPOINT: {
1099
- message: z.object({
1100
- version: z.literal("v1").default("v1")
1618
+ message: z.discriminatedUnion("version", [
1619
+ z.object({
1620
+ version: z.literal("v1")
1621
+ }),
1622
+ z.object({
1623
+ version: z.literal("v2"),
1624
+ reason: WaitReason.optional()
1625
+ })
1626
+ ]).default({
1627
+ version: "v1"
1628
+ }),
1629
+ callback: z.object({
1630
+ version: z.literal("v2").default("v2"),
1631
+ checkpointCanceled: z.boolean(),
1632
+ reason: WaitReason.optional()
1101
1633
  })
1102
1634
  },
1103
1635
  TASK_HEARTBEAT: {
@@ -1411,287 +1943,116 @@ var SpanMessagingEvent = z.object({
1411
1943
  destination: z.string().optional()
1412
1944
  });
1413
1945
 
1414
- // src/zodfetch.ts
1415
- async function zodfetch(schema, url, requestInit, options) {
1416
- return await _doZodFetch(schema, url, requestInit, options);
1946
+ // src/v3/utils/platform.ts
1947
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
1948
+
1949
+ // src/v3/utils/globals.ts
1950
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
1951
+ var _global = _globalThis;
1952
+ function registerGlobal(type, instance, allowOverride = false) {
1953
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
1954
+ if (!allowOverride && api[type]) {
1955
+ return false;
1956
+ }
1957
+ api[type] = instance;
1958
+ return true;
1417
1959
  }
1418
- __name(zodfetch, "zodfetch");
1419
- async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1420
- try {
1421
- const response = await fetch(url, requestInit);
1422
- if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
1423
- return {
1424
- ok: false,
1425
- error: `404: ${response.statusText}`
1426
- };
1960
+ __name(registerGlobal, "registerGlobal");
1961
+ function getGlobal(type) {
1962
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
1963
+ }
1964
+ __name(getGlobal, "getGlobal");
1965
+ function unregisterGlobal(type) {
1966
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
1967
+ if (api) {
1968
+ delete api[type];
1969
+ }
1970
+ }
1971
+ __name(unregisterGlobal, "unregisterGlobal");
1972
+
1973
+ // src/v3/semanticInternalAttributes.ts
1974
+ var SemanticInternalAttributes = {
1975
+ ENVIRONMENT_ID: "ctx.environment.id",
1976
+ ENVIRONMENT_TYPE: "ctx.environment.type",
1977
+ ORGANIZATION_ID: "ctx.organization.id",
1978
+ ORGANIZATION_SLUG: "ctx.organization.slug",
1979
+ ORGANIZATION_NAME: "ctx.organization.name",
1980
+ PROJECT_ID: "ctx.project.id",
1981
+ PROJECT_REF: "ctx.project.ref",
1982
+ PROJECT_NAME: "ctx.project.title",
1983
+ PROJECT_DIR: "project.dir",
1984
+ ATTEMPT_ID: "ctx.attempt.id",
1985
+ ATTEMPT_NUMBER: "ctx.attempt.number",
1986
+ RUN_ID: "ctx.run.id",
1987
+ RUN_IS_TEST: "ctx.run.isTest",
1988
+ BATCH_ID: "ctx.batch.id",
1989
+ TASK_SLUG: "ctx.task.id",
1990
+ TASK_PATH: "ctx.task.filePath",
1991
+ TASK_EXPORT_NAME: "ctx.task.exportName",
1992
+ QUEUE_NAME: "ctx.queue.name",
1993
+ QUEUE_ID: "ctx.queue.id",
1994
+ SPAN_PARTIAL: "$span.partial",
1995
+ SPAN_ID: "$span.span_id",
1996
+ OUTPUT: "$output",
1997
+ OUTPUT_TYPE: "$mime_type_output",
1998
+ STYLE: "$style",
1999
+ STYLE_ICON: "$style.icon",
2000
+ STYLE_VARIANT: "$style.variant",
2001
+ STYLE_ACCESSORY: "$style.accessory",
2002
+ METADATA: "$metadata",
2003
+ TRIGGER: "$trigger",
2004
+ PAYLOAD: "$payload",
2005
+ PAYLOAD_TYPE: "$mime_type_payload",
2006
+ SHOW: "$show",
2007
+ SHOW_ACTIONS: "$show.actions",
2008
+ WORKER_ID: "worker.id",
2009
+ WORKER_VERSION: "worker.version",
2010
+ CLI_VERSION: "cli.version",
2011
+ SDK_VERSION: "sdk.version",
2012
+ SDK_LANGUAGE: "sdk.language",
2013
+ RETRY_AT: "retry.at",
2014
+ RETRY_DELAY: "retry.delay",
2015
+ RETRY_COUNT: "retry.count",
2016
+ LINK_TITLE: "$link.title",
2017
+ IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
2018
+ };
2019
+
2020
+ // src/v3/taskContext/index.ts
2021
+ var API_NAME = "task-context";
2022
+ var _getTaskContext, getTaskContext_fn;
2023
+ var _TaskContextAPI = class _TaskContextAPI {
2024
+ constructor() {
2025
+ __privateAdd(this, _getTaskContext);
2026
+ }
2027
+ static getInstance() {
2028
+ if (!this._instance) {
2029
+ this._instance = new _TaskContextAPI();
1427
2030
  }
1428
- if (response.status >= 400 && response.status < 500 && response.status !== 429) {
1429
- const body = await response.json();
1430
- if (!body.error) {
1431
- return {
1432
- ok: false,
1433
- error: "Something went wrong"
1434
- };
1435
- }
2031
+ return this._instance;
2032
+ }
2033
+ get isInsideTask() {
2034
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
2035
+ }
2036
+ get ctx() {
2037
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
2038
+ }
2039
+ get worker() {
2040
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
2041
+ }
2042
+ get attributes() {
2043
+ if (this.ctx) {
1436
2044
  return {
1437
- ok: false,
1438
- error: body.error
1439
- };
1440
- }
1441
- if (response.status === 429 || response.status >= 500) {
1442
- if (!options?.retry) {
1443
- return {
1444
- ok: false,
1445
- error: `Failed to fetch ${url}, got status code ${response.status}`
1446
- };
1447
- }
1448
- const retry = {
1449
- ...defaultRetryOptions,
1450
- ...options.retry
2045
+ ...this.contextAttributes,
2046
+ ...this.workerAttributes
1451
2047
  };
1452
- if (attempt > retry.maxAttempts) {
1453
- return {
1454
- ok: false,
1455
- error: `Failed to fetch ${url}, got status code ${response.status}`
1456
- };
1457
- }
1458
- const delay = calculateNextRetryDelay(retry, attempt);
1459
- await new Promise((resolve) => setTimeout(resolve, delay));
1460
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1461
2048
  }
1462
- if (response.status !== 200) {
2049
+ return {};
2050
+ }
2051
+ get workerAttributes() {
2052
+ if (this.worker) {
1463
2053
  return {
1464
- ok: false,
1465
- error: `Failed to fetch ${url}, got status code ${response.status}`
1466
- };
1467
- }
1468
- const jsonBody = await response.json();
1469
- const parsedResult = schema.safeParse(jsonBody);
1470
- if (parsedResult.success) {
1471
- return {
1472
- ok: true,
1473
- data: parsedResult.data
1474
- };
1475
- }
1476
- if ("error" in jsonBody) {
1477
- return {
1478
- ok: false,
1479
- error: typeof jsonBody.error === "string" ? jsonBody.error : JSON.stringify(jsonBody.error)
1480
- };
1481
- }
1482
- return {
1483
- ok: false,
1484
- error: parsedResult.error.message
1485
- };
1486
- } catch (error) {
1487
- if (options?.retry) {
1488
- const retry = {
1489
- ...defaultRetryOptions,
1490
- ...options.retry
1491
- };
1492
- if (attempt > retry.maxAttempts) {
1493
- return {
1494
- ok: false,
1495
- error: error instanceof Error ? error.message : JSON.stringify(error)
1496
- };
1497
- }
1498
- const delay = calculateNextRetryDelay(retry, attempt);
1499
- await new Promise((resolve) => setTimeout(resolve, delay));
1500
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1501
- }
1502
- return {
1503
- ok: false,
1504
- error: error instanceof Error ? error.message : JSON.stringify(error)
1505
- };
1506
- }
1507
- }
1508
- __name(_doZodFetch, "_doZodFetch");
1509
-
1510
- // src/v3/utils/flattenAttributes.ts
1511
- function flattenAttributes(obj, prefix) {
1512
- const result = {};
1513
- if (!obj) {
1514
- return result;
1515
- }
1516
- if (typeof obj === "string") {
1517
- result[prefix || ""] = obj;
1518
- return result;
1519
- }
1520
- if (typeof obj === "number") {
1521
- result[prefix || ""] = obj;
1522
- return result;
1523
- }
1524
- if (typeof obj === "boolean") {
1525
- result[prefix || ""] = obj;
1526
- return result;
1527
- }
1528
- for (const [key, value] of Object.entries(obj)) {
1529
- const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
1530
- if (Array.isArray(value)) {
1531
- for (let i = 0; i < value.length; i++) {
1532
- if (typeof value[i] === "object" && value[i] !== null) {
1533
- Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
1534
- } else {
1535
- result[`${newPrefix}.[${i}]`] = value[i];
1536
- }
1537
- }
1538
- } else if (isRecord(value)) {
1539
- Object.assign(result, flattenAttributes(value, newPrefix));
1540
- } else {
1541
- if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
1542
- result[newPrefix] = value;
1543
- }
1544
- }
1545
- }
1546
- return result;
1547
- }
1548
- __name(flattenAttributes, "flattenAttributes");
1549
- function isRecord(value) {
1550
- return value !== null && typeof value === "object" && !Array.isArray(value);
1551
- }
1552
- __name(isRecord, "isRecord");
1553
- function unflattenAttributes(obj) {
1554
- if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
1555
- return obj;
1556
- }
1557
- const result = {};
1558
- for (const [key, value] of Object.entries(obj)) {
1559
- const parts = key.split(".").reduce((acc, part) => {
1560
- if (detectIsArrayIndex(part)) {
1561
- acc.push(part);
1562
- } else {
1563
- acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
1564
- }
1565
- return acc;
1566
- }, []);
1567
- let current = result;
1568
- for (let i = 0; i < parts.length - 1; i++) {
1569
- const part = parts[i];
1570
- const isArray = detectIsArrayIndex(part);
1571
- const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
1572
- const nextIsArray = detectIsArrayIndex(parts[i + 1]);
1573
- if (!current[cleanPart]) {
1574
- current[cleanPart] = nextIsArray ? [] : {};
1575
- }
1576
- current = current[cleanPart];
1577
- }
1578
- const lastPart = parts[parts.length - 1];
1579
- const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
1580
- current[cleanLastPart] = value;
1581
- }
1582
- return result;
1583
- }
1584
- __name(unflattenAttributes, "unflattenAttributes");
1585
- function detectIsArrayIndex(key) {
1586
- const match = key.match(/^\[(\d+)\]$/);
1587
- if (match) {
1588
- return true;
1589
- }
1590
- return false;
1591
- }
1592
- __name(detectIsArrayIndex, "detectIsArrayIndex");
1593
- function primitiveValueOrflattenedAttributes(obj, prefix) {
1594
- if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
1595
- return obj;
1596
- }
1597
- const attributes = flattenAttributes(obj, prefix);
1598
- if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
1599
- return attributes[prefix];
1600
- }
1601
- return attributes;
1602
- }
1603
- __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
1604
- var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
1605
- constructor() {
1606
- this.storage = new AsyncLocalStorage();
1607
- }
1608
- runWith(context3, fn) {
1609
- return this.storage.run(context3, fn);
1610
- }
1611
- getStore() {
1612
- return this.storage.getStore();
1613
- }
1614
- };
1615
- __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
1616
- var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
1617
-
1618
- // src/v3/semanticInternalAttributes.ts
1619
- var SemanticInternalAttributes = {
1620
- ENVIRONMENT_ID: "ctx.environment.id",
1621
- ENVIRONMENT_TYPE: "ctx.environment.type",
1622
- ORGANIZATION_ID: "ctx.organization.id",
1623
- ORGANIZATION_SLUG: "ctx.organization.slug",
1624
- ORGANIZATION_NAME: "ctx.organization.name",
1625
- PROJECT_ID: "ctx.project.id",
1626
- PROJECT_REF: "ctx.project.ref",
1627
- PROJECT_NAME: "ctx.project.title",
1628
- PROJECT_DIR: "project.dir",
1629
- ATTEMPT_ID: "ctx.attempt.id",
1630
- ATTEMPT_NUMBER: "ctx.attempt.number",
1631
- RUN_ID: "ctx.run.id",
1632
- RUN_IS_TEST: "ctx.run.isTest",
1633
- BATCH_ID: "ctx.batch.id",
1634
- TASK_SLUG: "ctx.task.id",
1635
- TASK_PATH: "ctx.task.filePath",
1636
- TASK_EXPORT_NAME: "ctx.task.exportName",
1637
- QUEUE_NAME: "ctx.queue.name",
1638
- QUEUE_ID: "ctx.queue.id",
1639
- SPAN_PARTIAL: "$span.partial",
1640
- SPAN_ID: "$span.span_id",
1641
- OUTPUT: "$output",
1642
- OUTPUT_TYPE: "$mime_type_output",
1643
- STYLE: "$style",
1644
- STYLE_ICON: "$style.icon",
1645
- STYLE_VARIANT: "$style.variant",
1646
- STYLE_ACCESSORY: "$style.accessory",
1647
- METADATA: "$metadata",
1648
- TRIGGER: "$trigger",
1649
- PAYLOAD: "$payload",
1650
- PAYLOAD_TYPE: "$mime_type_payload",
1651
- SHOW: "$show",
1652
- SHOW_ACTIONS: "$show.actions",
1653
- WORKER_ID: "worker.id",
1654
- WORKER_VERSION: "worker.version",
1655
- CLI_VERSION: "cli.version",
1656
- SDK_VERSION: "sdk.version",
1657
- SDK_LANGUAGE: "sdk.language",
1658
- RETRY_AT: "retry.at",
1659
- RETRY_DELAY: "retry.delay",
1660
- RETRY_COUNT: "retry.count"
1661
- };
1662
-
1663
- // src/v3/tasks/taskContextManager.ts
1664
- var _getStore, getStore_fn;
1665
- var _TaskContextManager = class _TaskContextManager {
1666
- constructor() {
1667
- __privateAdd(this, _getStore);
1668
- __publicField(this, "_storage", new SafeAsyncLocalStorage());
1669
- }
1670
- get isInsideTask() {
1671
- return __privateMethod(this, _getStore, getStore_fn).call(this) !== void 0;
1672
- }
1673
- get ctx() {
1674
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
1675
- return store?.ctx;
1676
- }
1677
- get worker() {
1678
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
1679
- return store?.worker;
1680
- }
1681
- get attributes() {
1682
- if (this.ctx) {
1683
- return {
1684
- ...this.contextAttributes,
1685
- ...this.workerAttributes
1686
- };
1687
- }
1688
- return {};
1689
- }
1690
- get workerAttributes() {
1691
- if (this.worker) {
1692
- return {
1693
- [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
1694
- [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
2054
+ [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
2055
+ [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
1695
2056
  };
1696
2057
  }
1697
2058
  return {};
@@ -1716,84 +2077,33 @@ var _TaskContextManager = class _TaskContextManager {
1716
2077
  [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
1717
2078
  [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
1718
2079
  [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
1719
- [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id
2080
+ [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
2081
+ [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
1720
2082
  };
1721
2083
  }
1722
2084
  return {};
1723
2085
  }
1724
- runWith(context3, fn) {
1725
- return this._storage.runWith(context3, fn);
1726
- }
1727
- };
1728
- _getStore = new WeakSet();
1729
- getStore_fn = /* @__PURE__ */ __name(function() {
1730
- return this._storage.getStore();
1731
- }, "#getStore");
1732
- __name(_TaskContextManager, "TaskContextManager");
1733
- var TaskContextManager = _TaskContextManager;
1734
- var taskContextManager = new TaskContextManager();
1735
- var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
1736
- constructor(innerProcessor) {
1737
- this._innerProcessor = innerProcessor;
1738
- }
1739
- // Called when a span starts
1740
- onStart(span, parentContext) {
1741
- if (taskContextManager.ctx) {
1742
- span.setAttributes(flattenAttributes({
1743
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
1744
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
1745
- }, SemanticInternalAttributes.METADATA));
1746
- }
1747
- this._innerProcessor.onStart(span, parentContext);
1748
- }
1749
- // Delegate the rest of the methods to the wrapped processor
1750
- onEnd(span) {
1751
- this._innerProcessor.onEnd(span);
1752
- }
1753
- shutdown() {
1754
- return this._innerProcessor.shutdown();
1755
- }
1756
- forceFlush() {
1757
- return this._innerProcessor.forceFlush();
1758
- }
1759
- };
1760
- __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
1761
- var TaskContextSpanProcessor = _TaskContextSpanProcessor;
1762
- var _TaskContextLogProcessor = class _TaskContextLogProcessor {
1763
- constructor(innerProcessor) {
1764
- this._innerProcessor = innerProcessor;
1765
- }
1766
- forceFlush() {
1767
- return this._innerProcessor.forceFlush();
1768
- }
1769
- onEmit(logRecord, context3) {
1770
- if (taskContextManager.ctx) {
1771
- logRecord.setAttributes(flattenAttributes({
1772
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
1773
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
1774
- }, SemanticInternalAttributes.METADATA));
1775
- }
1776
- this._innerProcessor.onEmit(logRecord, context3);
2086
+ disable() {
2087
+ unregisterGlobal(API_NAME);
1777
2088
  }
1778
- shutdown() {
1779
- return this._innerProcessor.shutdown();
2089
+ setGlobalTaskContext(taskContext2) {
2090
+ return registerGlobal(API_NAME, taskContext2);
1780
2091
  }
1781
2092
  };
1782
- __name(_TaskContextLogProcessor, "TaskContextLogProcessor");
1783
- var TaskContextLogProcessor = _TaskContextLogProcessor;
2093
+ _getTaskContext = new WeakSet();
2094
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
2095
+ return getGlobal(API_NAME);
2096
+ }, "#getTaskContext");
2097
+ __name(_TaskContextAPI, "TaskContextAPI");
2098
+ var TaskContextAPI = _TaskContextAPI;
1784
2099
 
1785
- // src/v3/utils/getEnv.ts
1786
- function getEnvVar(name) {
1787
- if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
1788
- return process.env[name];
1789
- }
1790
- }
1791
- __name(getEnvVar, "getEnvVar");
2100
+ // src/v3/task-context-api.ts
2101
+ var taskContext = TaskContextAPI.getInstance();
1792
2102
 
1793
2103
  // src/v3/apiClient/index.ts
1794
2104
  var zodFetchOptions = {
1795
2105
  retry: {
1796
- maxAttempts: 5,
2106
+ maxAttempts: 3,
1797
2107
  minTimeoutInMs: 1e3,
1798
2108
  maxTimeoutInMs: 3e4,
1799
2109
  factor: 2,
@@ -1807,6 +2117,27 @@ var _ApiClient = class _ApiClient {
1807
2117
  this.accessToken = accessToken;
1808
2118
  this.baseUrl = baseUrl.replace(/\/$/, "");
1809
2119
  }
2120
+ async getRunResult(runId) {
2121
+ try {
2122
+ return await zodfetch(TaskRunExecutionResult, `${this.baseUrl}/api/v1/runs/${runId}/result`, {
2123
+ method: "GET",
2124
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2125
+ }, zodFetchOptions);
2126
+ } catch (error) {
2127
+ if (error instanceof APIError) {
2128
+ if (error.status === 404) {
2129
+ return void 0;
2130
+ }
2131
+ }
2132
+ throw error;
2133
+ }
2134
+ }
2135
+ async getBatchResults(batchId) {
2136
+ return await zodfetch(BatchTaskRunExecutionResult, `${this.baseUrl}/api/v1/batches/${batchId}/results`, {
2137
+ method: "GET",
2138
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2139
+ }, zodFetchOptions);
2140
+ }
1810
2141
  triggerTask(taskId, body, options) {
1811
2142
  return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
1812
2143
  method: "POST",
@@ -1833,6 +2164,75 @@ var _ApiClient = class _ApiClient {
1833
2164
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1834
2165
  }, zodFetchOptions);
1835
2166
  }
2167
+ retrieveRun(runId) {
2168
+ return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v3/runs/${runId}`, {
2169
+ method: "GET",
2170
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2171
+ }, zodFetchOptions);
2172
+ }
2173
+ replayRun(runId) {
2174
+ return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2175
+ method: "POST",
2176
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2177
+ }, zodFetchOptions);
2178
+ }
2179
+ cancelRun(runId) {
2180
+ return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
2181
+ method: "POST",
2182
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2183
+ }, zodFetchOptions);
2184
+ }
2185
+ createSchedule(options) {
2186
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
2187
+ method: "POST",
2188
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2189
+ body: JSON.stringify(options)
2190
+ });
2191
+ }
2192
+ listSchedules(options) {
2193
+ const searchParams = new URLSearchParams();
2194
+ if (options?.page) {
2195
+ searchParams.append("page", options.page.toString());
2196
+ }
2197
+ if (options?.perPage) {
2198
+ searchParams.append("perPage", options.perPage.toString());
2199
+ }
2200
+ return zodfetch(ListSchedulesResult, `${this.baseUrl}/api/v1/schedules${searchParams.size > 0 ? `?${searchParams}` : ""}`, {
2201
+ method: "GET",
2202
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2203
+ });
2204
+ }
2205
+ retrieveSchedule(scheduleId) {
2206
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2207
+ method: "GET",
2208
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2209
+ });
2210
+ }
2211
+ updateSchedule(scheduleId, options) {
2212
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2213
+ method: "PUT",
2214
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2215
+ body: JSON.stringify(options)
2216
+ });
2217
+ }
2218
+ deactivateSchedule(scheduleId) {
2219
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
2220
+ method: "POST",
2221
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2222
+ });
2223
+ }
2224
+ activateSchedule(scheduleId) {
2225
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
2226
+ method: "POST",
2227
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2228
+ });
2229
+ }
2230
+ deleteSchedule(scheduleId) {
2231
+ return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2232
+ method: "DELETE",
2233
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2234
+ });
2235
+ }
1836
2236
  };
1837
2237
  _getHeaders = new WeakSet();
1838
2238
  getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
@@ -1840,7 +2240,7 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
1840
2240
  "Content-Type": "application/json",
1841
2241
  Authorization: `Bearer ${this.accessToken}`
1842
2242
  };
1843
- if (taskContextManager.isInsideTask) {
2243
+ if (taskContext.isInsideTask) {
1844
2244
  propagation.inject(context.active(), headers);
1845
2245
  if (spanParentAsLink) {
1846
2246
  headers["x-trigger-span-parent-as-link"] = "1";
@@ -1850,760 +2250,56 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
1850
2250
  }, "#getHeaders");
1851
2251
  __name(_ApiClient, "ApiClient");
1852
2252
  var ApiClient = _ApiClient;
1853
- var _getStore2, getStore_fn2;
1854
- var _ApiClientManager = class _ApiClientManager {
1855
- constructor() {
1856
- __privateAdd(this, _getStore2);
1857
- __publicField(this, "_storage", new SafeAsyncLocalStorage());
2253
+ var _SimpleClock = class _SimpleClock {
2254
+ preciseNow() {
2255
+ const now = new PreciseDate();
2256
+ const nowStruct = now.toStruct();
2257
+ return [
2258
+ nowStruct.seconds,
2259
+ nowStruct.nanos
2260
+ ];
1858
2261
  }
1859
- get baseURL() {
1860
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
1861
- return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
1862
- }
1863
- get accessToken() {
1864
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
1865
- return store?.accessToken ?? getEnvVar("TRIGGER_SECRET_KEY");
1866
- }
1867
- get client() {
1868
- if (!this.baseURL || !this.accessToken) {
1869
- return void 0;
1870
- }
1871
- return new ApiClient(this.baseURL, this.accessToken);
1872
- }
1873
- runWith(context3, fn) {
1874
- return this._storage.runWith(context3, fn);
1875
- }
1876
- };
1877
- _getStore2 = new WeakSet();
1878
- getStore_fn2 = /* @__PURE__ */ __name(function() {
1879
- return this._storage.getStore();
1880
- }, "#getStore");
1881
- __name(_ApiClientManager, "ApiClientManager");
1882
- var ApiClientManager = _ApiClientManager;
1883
- var apiClientManager = new ApiClientManager();
1884
- var _ZodSchemaParsedError = class _ZodSchemaParsedError extends Error {
1885
- constructor(error, payload) {
1886
- super(error.message);
1887
- this.error = error;
1888
- this.payload = payload;
1889
- }
1890
- };
1891
- __name(_ZodSchemaParsedError, "ZodSchemaParsedError");
1892
- var ZodSchemaParsedError = _ZodSchemaParsedError;
1893
- var ZodMessageSchema = z.object({
1894
- version: z.literal("v1").default("v1"),
1895
- type: z.string(),
1896
- payload: z.unknown()
1897
- });
1898
- var _schema, _handlers;
1899
- var _ZodMessageHandler = class _ZodMessageHandler {
1900
- constructor(options) {
1901
- __privateAdd(this, _schema, void 0);
1902
- __privateAdd(this, _handlers, void 0);
1903
- __privateSet(this, _schema, options.schema);
1904
- __privateSet(this, _handlers, options.messages);
1905
- }
1906
- async handleMessage(message) {
1907
- const parsedMessage = this.parseMessage(message);
1908
- if (!__privateGet(this, _handlers)) {
1909
- throw new Error("No handlers provided");
1910
- }
1911
- const handler = __privateGet(this, _handlers)[parsedMessage.type];
1912
- if (!handler) {
1913
- console.error(`No handler for message type: ${String(parsedMessage.type)}`);
1914
- return;
1915
- }
1916
- const ack = await handler(parsedMessage.payload);
1917
- return ack;
1918
- }
1919
- parseMessage(message) {
1920
- const parsedMessage = ZodMessageSchema.safeParse(message);
1921
- if (!parsedMessage.success) {
1922
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
1923
- }
1924
- const schema = __privateGet(this, _schema)[parsedMessage.data.type];
1925
- if (!schema) {
1926
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
1927
- }
1928
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
1929
- if (!parsedPayload.success) {
1930
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
1931
- }
1932
- return {
1933
- type: parsedMessage.data.type,
1934
- payload: parsedPayload.data
1935
- };
1936
- }
1937
- registerHandlers(emitter, logger2) {
1938
- const log = logger2 ?? console;
1939
- if (!__privateGet(this, _handlers)) {
1940
- log.info("No handlers provided");
1941
- return;
1942
- }
1943
- for (const eventName of Object.keys(__privateGet(this, _schema))) {
1944
- emitter.on(eventName, async (message, callback) => {
1945
- log.info(`handling ${eventName}`, {
1946
- payload: message,
1947
- hasCallback: !!callback
1948
- });
1949
- let ack;
1950
- if ("payload" in message) {
1951
- ack = await this.handleMessage({
1952
- type: eventName,
1953
- ...message
1954
- });
1955
- } else {
1956
- const { version, ...payload } = message;
1957
- ack = await this.handleMessage({
1958
- type: eventName,
1959
- version,
1960
- payload
1961
- });
1962
- }
1963
- if (callback && typeof callback === "function") {
1964
- callback(ack);
1965
- }
1966
- });
1967
- }
1968
- }
1969
- };
1970
- _schema = new WeakMap();
1971
- _handlers = new WeakMap();
1972
- __name(_ZodMessageHandler, "ZodMessageHandler");
1973
- var ZodMessageHandler = _ZodMessageHandler;
1974
- var _schema2, _sender;
1975
- var _ZodMessageSender = class _ZodMessageSender {
1976
- constructor(options) {
1977
- __privateAdd(this, _schema2, void 0);
1978
- __privateAdd(this, _sender, void 0);
1979
- __privateSet(this, _schema2, options.schema);
1980
- __privateSet(this, _sender, options.sender);
1981
- }
1982
- async send(type, payload) {
1983
- const schema = __privateGet(this, _schema2)[type];
1984
- if (!schema) {
1985
- throw new Error(`Unknown message type: ${type}`);
1986
- }
1987
- const parsedPayload = schema.safeParse(payload);
1988
- if (!parsedPayload.success) {
1989
- throw new ZodSchemaParsedError(parsedPayload.error, payload);
1990
- }
1991
- await __privateGet(this, _sender).call(this, {
1992
- type,
1993
- payload,
1994
- version: "v1"
1995
- });
1996
- }
1997
- async forwardMessage(message) {
1998
- const parsedMessage = ZodMessageSchema.safeParse(message);
1999
- if (!parsedMessage.success) {
2000
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2001
- }
2002
- const schema = __privateGet(this, _schema2)[parsedMessage.data.type];
2003
- if (!schema) {
2004
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2005
- }
2006
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2007
- if (!parsedPayload.success) {
2008
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2009
- }
2010
- await __privateGet(this, _sender).call(this, {
2011
- type: parsedMessage.data.type,
2012
- payload: parsedPayload.data,
2013
- version: "v1"
2014
- });
2015
- }
2016
- };
2017
- _schema2 = new WeakMap();
2018
- _sender = new WeakMap();
2019
- __name(_ZodMessageSender, "ZodMessageSender");
2020
- var ZodMessageSender = _ZodMessageSender;
2021
- var messageSchema = z.object({
2022
- version: z.literal("v1").default("v1"),
2023
- type: z.string(),
2024
- payload: z.unknown()
2025
- });
2026
- var _schema3, _handlers2;
2027
- var _ZodSocketMessageHandler = class _ZodSocketMessageHandler {
2028
- constructor(options) {
2029
- __privateAdd(this, _schema3, void 0);
2030
- __privateAdd(this, _handlers2, void 0);
2031
- __privateSet(this, _schema3, options.schema);
2032
- __privateSet(this, _handlers2, options.handlers);
2033
- }
2034
- async handleMessage(message) {
2035
- const parsedMessage = this.parseMessage(message);
2036
- if (!__privateGet(this, _handlers2)) {
2037
- throw new Error("No handlers provided");
2038
- }
2039
- const handler = __privateGet(this, _handlers2)[parsedMessage.type];
2040
- if (!handler) {
2041
- console.error(`No handler for message type: ${String(parsedMessage.type)}`);
2042
- return;
2043
- }
2044
- const ack = await handler(parsedMessage.payload);
2045
- return ack;
2046
- }
2047
- parseMessage(message) {
2048
- const parsedMessage = messageSchema.safeParse(message);
2049
- if (!parsedMessage.success) {
2050
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2051
- }
2052
- const schema = __privateGet(this, _schema3)[parsedMessage.data.type]["message"];
2053
- if (!schema) {
2054
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2055
- }
2056
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2057
- if (!parsedPayload.success) {
2058
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2059
- }
2060
- return {
2061
- type: parsedMessage.data.type,
2062
- payload: parsedPayload.data
2063
- };
2064
- }
2065
- registerHandlers(emitter, logger2) {
2066
- const log = logger2 ?? console;
2067
- if (!__privateGet(this, _handlers2)) {
2068
- log.info("No handlers provided");
2069
- return;
2070
- }
2071
- for (const eventName of Object.keys(__privateGet(this, _handlers2))) {
2072
- emitter.on(eventName, async (message, callback) => {
2073
- log.info(`handling ${eventName}`, {
2074
- payload: message,
2075
- hasCallback: !!callback
2076
- });
2077
- let ack;
2078
- try {
2079
- if ("payload" in message) {
2080
- ack = await this.handleMessage({
2081
- type: eventName,
2082
- ...message
2083
- });
2084
- } else {
2085
- const { version, ...payload } = message;
2086
- ack = await this.handleMessage({
2087
- type: eventName,
2088
- version,
2089
- payload
2090
- });
2091
- }
2092
- } catch (error) {
2093
- log.error("Error while handling message", {
2094
- error
2095
- });
2096
- return;
2097
- }
2098
- if (callback && typeof callback === "function") {
2099
- callback(ack);
2100
- }
2101
- });
2102
- }
2103
- }
2104
- };
2105
- _schema3 = new WeakMap();
2106
- _handlers2 = new WeakMap();
2107
- __name(_ZodSocketMessageHandler, "ZodSocketMessageHandler");
2108
- var ZodSocketMessageHandler = _ZodSocketMessageHandler;
2109
- var _schema4, _socket;
2110
- var _ZodSocketMessageSender = class _ZodSocketMessageSender {
2111
- constructor(options) {
2112
- __privateAdd(this, _schema4, void 0);
2113
- __privateAdd(this, _socket, void 0);
2114
- __privateSet(this, _schema4, options.schema);
2115
- __privateSet(this, _socket, options.socket);
2116
- }
2117
- send(type, payload) {
2118
- const schema = __privateGet(this, _schema4)[type]["message"];
2119
- if (!schema) {
2120
- throw new Error(`Unknown message type: ${type}`);
2121
- }
2122
- const parsedPayload = schema.safeParse(payload);
2123
- if (!parsedPayload.success) {
2124
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2125
- }
2126
- __privateGet(this, _socket).emit(type, {
2127
- payload,
2128
- version: "v1"
2129
- });
2130
- return;
2131
- }
2132
- async sendWithAck(type, payload) {
2133
- const schema = __privateGet(this, _schema4)[type]["message"];
2134
- if (!schema) {
2135
- throw new Error(`Unknown message type: ${type}`);
2136
- }
2137
- const parsedPayload = schema.safeParse(payload);
2138
- if (!parsedPayload.success) {
2139
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2140
- }
2141
- const callbackResult = await __privateGet(this, _socket).emitWithAck(type, {
2142
- payload,
2143
- version: "v1"
2144
- });
2145
- return callbackResult;
2262
+ reset() {
2146
2263
  }
2147
2264
  };
2148
- _schema4 = new WeakMap();
2149
- _socket = new WeakMap();
2150
- __name(_ZodSocketMessageSender, "ZodSocketMessageSender");
2151
- var ZodSocketMessageSender = _ZodSocketMessageSender;
2152
- var _sender2, _handler, _logger;
2153
- var _ZodSocketConnection = class _ZodSocketConnection {
2154
- constructor(opts) {
2155
- __privateAdd(this, _sender2, void 0);
2156
- __privateAdd(this, _handler, void 0);
2157
- __privateAdd(this, _logger, void 0);
2158
- const uri = `${opts.secure ? "wss" : "ws"}://${opts.host}:${opts.port ?? (opts.secure ? "443" : "80")}/${opts.namespace}`;
2159
- const logger2 = new SimpleStructuredLogger(opts.namespace, LogLevel.info);
2160
- logger2.log("new zod socket", {
2161
- uri
2162
- });
2163
- this.socket = io(uri, {
2164
- transports: [
2165
- "websocket"
2166
- ],
2167
- auth: {
2168
- token: opts.authToken
2169
- },
2170
- extraHeaders: opts.extraHeaders,
2171
- reconnectionDelay: 500,
2172
- reconnectionDelayMax: 1e3
2173
- });
2174
- __privateSet(this, _logger, logger2.child({
2175
- socketId: this.socket.id
2176
- }));
2177
- __privateSet(this, _handler, new ZodSocketMessageHandler({
2178
- schema: opts.serverMessages,
2179
- handlers: opts.handlers
2180
- }));
2181
- __privateGet(this, _handler).registerHandlers(this.socket, __privateGet(this, _logger));
2182
- __privateSet(this, _sender2, new ZodSocketMessageSender({
2183
- schema: opts.clientMessages,
2184
- socket: this.socket
2185
- }));
2186
- this.socket.on("connect_error", async (error) => {
2187
- __privateGet(this, _logger).error(`connect_error: ${error}`);
2188
- if (opts.onError) {
2189
- await opts.onError(this.socket, error, __privateGet(this, _logger));
2190
- }
2191
- });
2192
- this.socket.on("connect", async () => {
2193
- __privateGet(this, _logger).info("connect");
2194
- if (opts.onConnection) {
2195
- await opts.onConnection(this.socket, __privateGet(this, _handler), __privateGet(this, _sender2), __privateGet(this, _logger));
2196
- }
2197
- });
2198
- this.socket.on("disconnect", async (reason, description) => {
2199
- __privateGet(this, _logger).info("disconnect", {
2200
- reason,
2201
- description
2202
- });
2203
- if (opts.onDisconnect) {
2204
- await opts.onDisconnect(this.socket, reason, description, __privateGet(this, _logger));
2205
- }
2206
- });
2207
- }
2208
- close() {
2209
- this.socket.close();
2210
- }
2211
- connect() {
2212
- this.socket.connect();
2213
- }
2214
- get send() {
2215
- return __privateGet(this, _sender2).send.bind(__privateGet(this, _sender2));
2216
- }
2217
- get sendWithAck() {
2218
- return __privateGet(this, _sender2).sendWithAck.bind(__privateGet(this, _sender2));
2219
- }
2220
- };
2221
- _sender2 = new WeakMap();
2222
- _handler = new WeakMap();
2223
- _logger = new WeakMap();
2224
- __name(_ZodSocketConnection, "ZodSocketConnection");
2225
- var ZodSocketConnection = _ZodSocketConnection;
2265
+ __name(_SimpleClock, "SimpleClock");
2266
+ var SimpleClock = _SimpleClock;
2226
2267
 
2227
- // src/v3/zodNamespace.ts
2228
- var LogLevel;
2229
- (function(LogLevel2) {
2230
- LogLevel2[LogLevel2["log"] = 0] = "log";
2231
- LogLevel2[LogLevel2["error"] = 1] = "error";
2232
- LogLevel2[LogLevel2["warn"] = 2] = "warn";
2233
- LogLevel2[LogLevel2["info"] = 3] = "info";
2234
- LogLevel2[LogLevel2["debug"] = 4] = "debug";
2235
- })(LogLevel || (LogLevel = {}));
2236
- var _structuredLog, structuredLog_fn;
2237
- var _SimpleStructuredLogger = class _SimpleStructuredLogger {
2238
- constructor(name, level = [
2239
- "1",
2240
- "true"
2241
- ].includes(process.env.DEBUG ?? "") ? LogLevel.debug : LogLevel.info, fields) {
2242
- __privateAdd(this, _structuredLog);
2243
- this.name = name;
2244
- this.level = level;
2245
- this.fields = fields;
2246
- }
2247
- child(fields, level) {
2248
- return new _SimpleStructuredLogger(this.name, level, {
2249
- ...this.fields,
2250
- ...fields
2251
- });
2252
- }
2253
- log(message, ...args) {
2254
- if (this.level < LogLevel.log)
2255
- return;
2256
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.log, message, "log", ...args);
2257
- }
2258
- error(message, ...args) {
2259
- if (this.level < LogLevel.error)
2260
- return;
2261
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.error, message, "error", ...args);
2262
- }
2263
- warn(message, ...args) {
2264
- if (this.level < LogLevel.warn)
2265
- return;
2266
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.warn, message, "warn", ...args);
2267
- }
2268
- info(message, ...args) {
2269
- if (this.level < LogLevel.info)
2270
- return;
2271
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.info, message, "info", ...args);
2272
- }
2273
- debug(message, ...args) {
2274
- if (this.level < LogLevel.debug)
2275
- return;
2276
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.debug, message, "debug", ...args);
2277
- }
2278
- };
2279
- _structuredLog = new WeakSet();
2280
- structuredLog_fn = /* @__PURE__ */ __name(function(loggerFunction, message, level, ...args) {
2281
- const structuredLog = {
2282
- ...args.length === 1 ? args[0] : args,
2283
- ...this.fields,
2284
- timestamp: /* @__PURE__ */ new Date(),
2285
- name: this.name,
2286
- message,
2287
- level
2288
- };
2289
- loggerFunction(JSON.stringify(structuredLog));
2290
- }, "#structuredLog");
2291
- __name(_SimpleStructuredLogger, "SimpleStructuredLogger");
2292
- var SimpleStructuredLogger = _SimpleStructuredLogger;
2293
- var _logger2, _handler2;
2294
- var _ZodNamespace = class _ZodNamespace {
2295
- constructor(opts) {
2296
- __privateAdd(this, _logger2, void 0);
2297
- __privateAdd(this, _handler2, void 0);
2298
- __privateSet(this, _logger2, opts.logger ?? new SimpleStructuredLogger(opts.name));
2299
- __privateSet(this, _handler2, new ZodSocketMessageHandler({
2300
- schema: opts.clientMessages,
2301
- handlers: opts.handlers
2302
- }));
2303
- this.io = opts.io;
2304
- this.namespace = this.io.of(opts.name);
2305
- this.sender = new ZodMessageSender({
2306
- schema: opts.serverMessages,
2307
- sender: async (message) => {
2308
- return new Promise((resolve, reject) => {
2309
- try {
2310
- this.namespace.emit(message.type, message.payload);
2311
- resolve();
2312
- } catch (err) {
2313
- reject(err);
2314
- }
2315
- });
2316
- }
2317
- });
2318
- if (opts.preAuth) {
2319
- this.namespace.use(async (socket, next) => {
2320
- const logger2 = __privateGet(this, _logger2).child({
2321
- socketId: socket.id,
2322
- socketStage: "preAuth"
2323
- });
2324
- if (typeof opts.preAuth === "function") {
2325
- await opts.preAuth(socket, next, logger2);
2326
- }
2327
- });
2328
- }
2329
- if (opts.authToken) {
2330
- this.namespace.use((socket, next) => {
2331
- const logger2 = __privateGet(this, _logger2).child({
2332
- socketId: socket.id,
2333
- socketStage: "auth"
2334
- });
2335
- const { auth } = socket.handshake;
2336
- if (!("token" in auth)) {
2337
- logger2.error("no token");
2338
- return socket.disconnect(true);
2339
- }
2340
- if (auth.token !== opts.authToken) {
2341
- logger2.error("invalid token");
2342
- return socket.disconnect(true);
2343
- }
2344
- logger2.info("success");
2345
- next();
2346
- });
2347
- }
2348
- if (opts.postAuth) {
2349
- this.namespace.use(async (socket, next) => {
2350
- const logger2 = __privateGet(this, _logger2).child({
2351
- socketId: socket.id,
2352
- socketStage: "auth"
2353
- });
2354
- if (typeof opts.postAuth === "function") {
2355
- await opts.postAuth(socket, next, logger2);
2356
- }
2357
- });
2358
- }
2359
- this.namespace.on("connection", async (socket) => {
2360
- const logger2 = __privateGet(this, _logger2).child({
2361
- socketId: socket.id,
2362
- socketStage: "connection"
2363
- });
2364
- logger2.info("connected");
2365
- __privateGet(this, _handler2).registerHandlers(socket, logger2);
2366
- socket.on("disconnect", async (reason, description) => {
2367
- logger2.info("disconnect", {
2368
- reason,
2369
- description
2370
- });
2371
- if (opts.onDisconnect) {
2372
- await opts.onDisconnect(socket, reason, description, logger2);
2373
- }
2374
- });
2375
- socket.on("error", async (error) => {
2376
- logger2.error("error", {
2377
- error
2378
- });
2379
- if (opts.onError) {
2380
- await opts.onError(socket, error, logger2);
2381
- }
2382
- });
2383
- if (opts.onConnection) {
2384
- await opts.onConnection(socket, __privateGet(this, _handler2), this.sender, logger2);
2385
- }
2386
- });
2387
- }
2388
- fetchSockets() {
2389
- return this.namespace.fetchSockets();
2390
- }
2391
- };
2392
- _logger2 = new WeakMap();
2393
- _handler2 = new WeakMap();
2394
- __name(_ZodNamespace, "ZodNamespace");
2395
- var ZodNamespace = _ZodNamespace;
2396
- var messageSchema2 = z.object({
2397
- version: z.literal("v1").default("v1"),
2398
- type: z.string(),
2399
- payload: z.unknown()
2400
- });
2401
- var _schema5, _handlers3, _sender3, _a;
2402
- var ZodIpcMessageHandler = (_a = class {
2403
- constructor(options) {
2404
- __privateAdd(this, _schema5, void 0);
2405
- __privateAdd(this, _handlers3, void 0);
2406
- __privateAdd(this, _sender3, void 0);
2407
- __privateSet(this, _schema5, options.schema);
2408
- __privateSet(this, _handlers3, options.handlers);
2409
- __privateSet(this, _sender3, options.sender);
2410
- }
2411
- async handleMessage(message) {
2412
- const parsedMessage = this.parseMessage(message);
2413
- if (!__privateGet(this, _handlers3)) {
2414
- throw new Error("No handlers provided");
2415
- }
2416
- const handler = __privateGet(this, _handlers3)[parsedMessage.type];
2417
- if (!handler) {
2418
- return;
2419
- }
2420
- const ack = await handler(parsedMessage.payload, __privateGet(this, _sender3));
2421
- return ack;
2268
+ // src/v3/clock/index.ts
2269
+ var API_NAME2 = "clock";
2270
+ var SIMPLE_CLOCK = new SimpleClock();
2271
+ var _getClock, getClock_fn;
2272
+ var _ClockAPI = class _ClockAPI {
2273
+ constructor() {
2274
+ __privateAdd(this, _getClock);
2422
2275
  }
2423
- parseMessage(message) {
2424
- const parsedMessage = messageSchema2.safeParse(message);
2425
- if (!parsedMessage.success) {
2426
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2427
- }
2428
- const schema = __privateGet(this, _schema5)[parsedMessage.data.type]["message"];
2429
- if (!schema) {
2430
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2431
- }
2432
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2433
- if (!parsedPayload.success) {
2434
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2276
+ static getInstance() {
2277
+ if (!this._instance) {
2278
+ this._instance = new _ClockAPI();
2435
2279
  }
2436
- return {
2437
- type: parsedMessage.data.type,
2438
- payload: parsedPayload.data
2439
- };
2440
- }
2441
- }, _schema5 = new WeakMap(), _handlers3 = new WeakMap(), _sender3 = new WeakMap(), __name(_a, "ZodIpcMessageHandler"), _a);
2442
- var Packet = z.discriminatedUnion("type", [
2443
- z.object({
2444
- type: z.literal("CONNECT"),
2445
- sessionId: z.string().optional()
2446
- }),
2447
- z.object({
2448
- type: z.literal("ACK"),
2449
- message: z.any(),
2450
- id: z.number()
2451
- }),
2452
- z.object({
2453
- type: z.literal("EVENT"),
2454
- message: z.any(),
2455
- id: z.number().optional()
2456
- })
2457
- ]);
2458
- var _sessionId, _messageCounter, _handler3, _acks, _registerHandlers, registerHandlers_fn, _handlePacket, handlePacket_fn, _sendPacket, sendPacket_fn;
2459
- var _ZodIpcConnection = class _ZodIpcConnection {
2460
- constructor(opts) {
2461
- __privateAdd(this, _registerHandlers);
2462
- __privateAdd(this, _handlePacket);
2463
- __privateAdd(this, _sendPacket);
2464
- __privateAdd(this, _sessionId, void 0);
2465
- __privateAdd(this, _messageCounter, void 0);
2466
- __privateAdd(this, _handler3, void 0);
2467
- __privateAdd(this, _acks, void 0);
2468
- this.opts = opts;
2469
- __privateSet(this, _messageCounter, 0);
2470
- __privateSet(this, _acks, /* @__PURE__ */ new Map());
2471
- __privateSet(this, _handler3, new ZodIpcMessageHandler({
2472
- schema: opts.listenSchema,
2473
- handlers: opts.handlers,
2474
- sender: {
2475
- send: this.send.bind(this),
2476
- sendWithAck: this.sendWithAck.bind(this)
2477
- }
2478
- }));
2479
- __privateMethod(this, _registerHandlers, registerHandlers_fn).call(this);
2280
+ return this._instance;
2480
2281
  }
2481
- async connect() {
2482
- __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2483
- type: "CONNECT"
2484
- });
2282
+ setGlobalClock(clock2) {
2283
+ return registerGlobal(API_NAME2, clock2);
2485
2284
  }
2486
- async send(type, payload) {
2487
- const schema = this.opts.emitSchema[type]["message"];
2488
- if (!schema) {
2489
- throw new Error(`Unknown message type: ${type}`);
2490
- }
2491
- const parsedPayload = schema.safeParse(payload);
2492
- if (!parsedPayload.success) {
2493
- throw new ZodSchemaParsedError(parsedPayload.error, payload);
2494
- }
2495
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2496
- type: "EVENT",
2497
- message: {
2498
- type,
2499
- payload,
2500
- version: "v1"
2501
- }
2502
- });
2285
+ preciseNow() {
2286
+ return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2503
2287
  }
2504
- async sendWithAck(type, payload, timeoutInMs) {
2505
- const currentId = __privateWrapper(this, _messageCounter)._++;
2506
- return new Promise(async (resolve, reject) => {
2507
- const defaultTimeoutInMs = 2e3;
2508
- const timeout = setTimeout(() => {
2509
- reject(JSON.stringify({
2510
- reason: "sendWithAck() timeout",
2511
- timeoutInMs: timeoutInMs ?? defaultTimeoutInMs,
2512
- type,
2513
- payload
2514
- }));
2515
- }, timeoutInMs ?? defaultTimeoutInMs);
2516
- __privateGet(this, _acks).set(currentId, {
2517
- resolve,
2518
- reject,
2519
- timeout
2520
- });
2521
- const schema = this.opts.emitSchema[type]["message"];
2522
- if (!schema) {
2523
- clearTimeout(timeout);
2524
- return reject(`Unknown message type: ${type}`);
2525
- }
2526
- const parsedPayload = schema.safeParse(payload);
2527
- if (!parsedPayload.success) {
2528
- clearTimeout(timeout);
2529
- return reject(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2530
- }
2531
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2532
- type: "EVENT",
2533
- message: {
2534
- type,
2535
- payload,
2536
- version: "v1"
2537
- },
2538
- id: currentId
2539
- });
2540
- });
2288
+ reset() {
2289
+ __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2541
2290
  }
2542
2291
  };
2543
- _sessionId = new WeakMap();
2544
- _messageCounter = new WeakMap();
2545
- _handler3 = new WeakMap();
2546
- _acks = new WeakMap();
2547
- _registerHandlers = new WeakSet();
2548
- registerHandlers_fn = /* @__PURE__ */ __name(async function() {
2549
- if (!this.opts.process.on) {
2550
- return;
2551
- }
2552
- this.opts.process.on("message", async (message) => {
2553
- __privateMethod(this, _handlePacket, handlePacket_fn).call(this, message);
2554
- });
2555
- }, "#registerHandlers");
2556
- _handlePacket = new WeakSet();
2557
- handlePacket_fn = /* @__PURE__ */ __name(async function(packet) {
2558
- const parsedPacket = Packet.safeParse(packet);
2559
- if (!parsedPacket.success) {
2560
- return;
2561
- }
2562
- switch (parsedPacket.data.type) {
2563
- case "ACK": {
2564
- const ack = __privateGet(this, _acks).get(parsedPacket.data.id);
2565
- if (!ack) {
2566
- return;
2567
- }
2568
- clearTimeout(ack.timeout);
2569
- ack.resolve(parsedPacket.data.message);
2570
- break;
2571
- }
2572
- case "CONNECT": {
2573
- if (!parsedPacket.data.sessionId) {
2574
- const id = randomUUID();
2575
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2576
- type: "CONNECT",
2577
- sessionId: id
2578
- });
2579
- return;
2580
- }
2581
- if (__privateGet(this, _sessionId)) {
2582
- return;
2583
- }
2584
- __privateSet(this, _sessionId, parsedPacket.data.sessionId);
2585
- break;
2586
- }
2587
- case "EVENT": {
2588
- const result = await __privateGet(this, _handler3).handleMessage(parsedPacket.data.message);
2589
- if (typeof parsedPacket.data.id === "undefined") {
2590
- return;
2591
- }
2592
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2593
- type: "ACK",
2594
- id: parsedPacket.data.id,
2595
- message: result
2596
- });
2597
- break;
2598
- }
2599
- }
2600
- }, "#handlePacket");
2601
- _sendPacket = new WeakSet();
2602
- sendPacket_fn = /* @__PURE__ */ __name(async function(packet1) {
2603
- await this.opts.process.send?.(packet1);
2604
- }, "#sendPacket");
2605
- __name(_ZodIpcConnection, "ZodIpcConnection");
2606
- var ZodIpcConnection = _ZodIpcConnection;
2292
+ _getClock = new WeakSet();
2293
+ getClock_fn = /* @__PURE__ */ __name(function() {
2294
+ return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2295
+ }, "#getClock");
2296
+ __name(_ClockAPI, "ClockAPI");
2297
+ var ClockAPI = _ClockAPI;
2298
+
2299
+ // src/v3/clock-api.ts
2300
+ var clock = ClockAPI.getInstance();
2301
+
2302
+ // src/v3/errors.ts
2607
2303
  function parseError(error) {
2608
2304
  if (error instanceof Error) {
2609
2305
  return {
@@ -2652,6 +2348,33 @@ function createErrorTaskError(error) {
2652
2348
  }
2653
2349
  }
2654
2350
  __name(createErrorTaskError, "createErrorTaskError");
2351
+ function createJsonErrorObject(error) {
2352
+ switch (error.type) {
2353
+ case "BUILT_IN_ERROR": {
2354
+ return {
2355
+ name: error.name,
2356
+ message: error.message,
2357
+ stackTrace: error.stackTrace
2358
+ };
2359
+ }
2360
+ case "STRING_ERROR": {
2361
+ return {
2362
+ message: error.raw
2363
+ };
2364
+ }
2365
+ case "CUSTOM_ERROR": {
2366
+ return {
2367
+ message: error.raw
2368
+ };
2369
+ }
2370
+ case "INTERNAL_ERROR": {
2371
+ return {
2372
+ message: `trigger.dev internal error (${error.code})`
2373
+ };
2374
+ }
2375
+ }
2376
+ }
2377
+ __name(createJsonErrorObject, "createJsonErrorObject");
2655
2378
  function correctErrorStackTrace(stackTrace, projectDir, options) {
2656
2379
  const [errorLine, ...traceLines] = stackTrace.split("\n");
2657
2380
  return [
@@ -2660,23 +2383,23 @@ function correctErrorStackTrace(stackTrace, projectDir, options) {
2660
2383
  ].filter(Boolean).join("\n");
2661
2384
  }
2662
2385
  __name(correctErrorStackTrace, "correctErrorStackTrace");
2386
+ var LINES_TO_IGNORE = [
2387
+ /ConsoleInterceptor/,
2388
+ /TriggerTracer/,
2389
+ /TaskExecutor/,
2390
+ /EXECUTE_TASK_RUN/,
2391
+ /@trigger.dev\/core/,
2392
+ /safeJsonProcess/,
2393
+ /__entryPoint.ts/
2394
+ ];
2663
2395
  function correctStackTraceLine(line, projectDir) {
2664
- const regex = /at (.*?) \(?file:\/\/(\/.*?\.ts):(\d+):(\d+)\)?/;
2665
- const match = regex.exec(line);
2666
- if (!match) {
2667
- return;
2668
- }
2669
- const [_, identifier, path, lineNum, colNum] = match;
2670
- if (!path) {
2396
+ if (LINES_TO_IGNORE.some((regex) => regex.test(line))) {
2671
2397
  return;
2672
2398
  }
2673
- if (nodePath.basename(path) === "__entryPoint.ts") {
2399
+ if (projectDir && !line.includes(projectDir)) {
2674
2400
  return;
2675
2401
  }
2676
- if (projectDir && !path.includes(projectDir)) {
2677
- return;
2678
- }
2679
- return line;
2402
+ return line.trim();
2680
2403
  }
2681
2404
  __name(correctStackTraceLine, "correctStackTraceLine");
2682
2405
  function groupTaskMetadataIssuesByTask(tasks, issues) {
@@ -2715,272 +2438,171 @@ function groupTaskMetadataIssuesByTask(tasks, issues) {
2715
2438
  }
2716
2439
  __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
2717
2440
 
2718
- // src/v3/utils/platform.ts
2719
- var _globalThis = typeof globalThis === "object" ? globalThis : global;
2720
-
2721
- // src/v3/utils/globals.ts
2722
- var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
2723
- var _global = _globalThis;
2724
- function registerGlobal(type, instance, allowOverride = false) {
2725
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
2726
- if (!allowOverride && api[type]) {
2727
- return false;
2728
- }
2729
- api[type] = instance;
2730
- return true;
2731
- }
2732
- __name(registerGlobal, "registerGlobal");
2733
- function getGlobal(type) {
2734
- return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
2735
- }
2736
- __name(getGlobal, "getGlobal");
2737
- function unregisterGlobal(type) {
2738
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
2739
- if (api) {
2740
- delete api[type];
2441
+ // src/v3/limits.ts
2442
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2443
+ var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
2444
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2445
+ var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2446
+ var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
2447
+ var OTEL_LINK_COUNT_LIMIT = 2;
2448
+ var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
2449
+ var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
2450
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
2451
+ function imposeAttributeLimits(attributes) {
2452
+ const newAttributes = {};
2453
+ for (const [key, value] of Object.entries(attributes)) {
2454
+ if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
2455
+ continue;
2456
+ }
2457
+ if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
2458
+ break;
2459
+ }
2460
+ newAttributes[key] = value;
2741
2461
  }
2462
+ return newAttributes;
2742
2463
  }
2743
- __name(unregisterGlobal, "unregisterGlobal");
2744
-
2745
- // src/v3/runtime/noopRuntimeManager.ts
2746
- var _NoopRuntimeManager = class _NoopRuntimeManager {
2747
- disable() {
2748
- }
2749
- registerTasks() {
2750
- }
2751
- getTaskMetadata(id) {
2752
- return void 0;
2464
+ __name(imposeAttributeLimits, "imposeAttributeLimits");
2465
+ function calculateAttributeValueLength(value) {
2466
+ if (value === void 0 || value === null) {
2467
+ return 0;
2753
2468
  }
2754
- waitForDuration(ms) {
2755
- return Promise.resolve();
2469
+ if (typeof value === "string") {
2470
+ return value.length;
2756
2471
  }
2757
- waitUntil(date) {
2758
- return Promise.resolve();
2472
+ if (typeof value === "number") {
2473
+ return 8;
2759
2474
  }
2760
- waitForTask(params) {
2761
- return Promise.resolve({
2762
- ok: false,
2763
- id: params.id,
2764
- error: {
2765
- type: "INTERNAL_ERROR",
2766
- code: "CONFIGURED_INCORRECTLY"
2767
- }
2768
- });
2475
+ if (typeof value === "boolean") {
2476
+ return 4;
2769
2477
  }
2770
- waitForBatch(params) {
2771
- return Promise.resolve({
2772
- id: params.id,
2773
- items: []
2774
- });
2478
+ if (Array.isArray(value)) {
2479
+ return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
2775
2480
  }
2776
- };
2777
- __name(_NoopRuntimeManager, "NoopRuntimeManager");
2778
- var NoopRuntimeManager = _NoopRuntimeManager;
2481
+ return 0;
2482
+ }
2483
+ __name(calculateAttributeValueLength, "calculateAttributeValueLength");
2779
2484
 
2780
- // src/v3/runtime/index.ts
2781
- var API_NAME = "runtime";
2782
- var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
2783
- var _getRuntimeManager, getRuntimeManager_fn;
2784
- var _RuntimeAPI = class _RuntimeAPI {
2785
- constructor() {
2786
- __privateAdd(this, _getRuntimeManager);
2787
- }
2788
- static getInstance() {
2789
- if (!this._instance) {
2790
- this._instance = new _RuntimeAPI();
2791
- }
2792
- return this._instance;
2793
- }
2794
- waitForDuration(ms) {
2795
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
2796
- }
2797
- waitUntil(date) {
2798
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
2799
- }
2800
- waitForTask(params) {
2801
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
2802
- }
2803
- waitForBatch(params) {
2804
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
2485
+ // src/v3/utils/flattenAttributes.ts
2486
+ var NULL_SENTINEL = "$@null((";
2487
+ function flattenAttributes(obj, prefix) {
2488
+ const result = {};
2489
+ if (obj === void 0) {
2490
+ return result;
2805
2491
  }
2806
- setGlobalRuntimeManager(runtimeManager) {
2807
- return registerGlobal(API_NAME, runtimeManager);
2492
+ if (obj === null) {
2493
+ result[prefix || ""] = NULL_SENTINEL;
2494
+ return result;
2808
2495
  }
2809
- disable() {
2810
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2811
- unregisterGlobal(API_NAME);
2496
+ if (typeof obj === "string") {
2497
+ result[prefix || ""] = obj;
2498
+ return result;
2812
2499
  }
2813
- registerTasks(tasks) {
2814
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).registerTasks(tasks);
2500
+ if (typeof obj === "number") {
2501
+ result[prefix || ""] = obj;
2502
+ return result;
2815
2503
  }
2816
- getTaskMetadata(id) {
2817
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).getTaskMetadata(id);
2504
+ if (typeof obj === "boolean") {
2505
+ result[prefix || ""] = obj;
2506
+ return result;
2818
2507
  }
2819
- };
2820
- _getRuntimeManager = new WeakSet();
2821
- getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
2822
- return getGlobal(API_NAME) ?? NOOP_RUNTIME_MANAGER;
2823
- }, "#getRuntimeManager");
2824
- __name(_RuntimeAPI, "RuntimeAPI");
2825
- var RuntimeAPI = _RuntimeAPI;
2826
-
2827
- // src/v3/runtime-api.ts
2828
- var runtime = RuntimeAPI.getInstance();
2829
- function iconStringForSeverity(severityNumber) {
2830
- switch (severityNumber) {
2831
- case SeverityNumber.UNSPECIFIED:
2832
- return void 0;
2833
- case SeverityNumber.TRACE:
2834
- case SeverityNumber.TRACE2:
2835
- case SeverityNumber.TRACE3:
2836
- case SeverityNumber.TRACE4:
2837
- return "trace";
2838
- case SeverityNumber.DEBUG:
2839
- case SeverityNumber.DEBUG2:
2840
- case SeverityNumber.DEBUG3:
2841
- case SeverityNumber.DEBUG4:
2842
- return "debug";
2843
- case SeverityNumber.INFO:
2844
- case SeverityNumber.INFO2:
2845
- case SeverityNumber.INFO3:
2846
- case SeverityNumber.INFO4:
2847
- return "info";
2848
- case SeverityNumber.WARN:
2849
- case SeverityNumber.WARN2:
2850
- case SeverityNumber.WARN3:
2851
- case SeverityNumber.WARN4:
2852
- return "warn";
2853
- case SeverityNumber.ERROR:
2854
- case SeverityNumber.ERROR2:
2855
- case SeverityNumber.ERROR3:
2856
- case SeverityNumber.ERROR4:
2857
- return "error";
2858
- case SeverityNumber.FATAL:
2859
- case SeverityNumber.FATAL2:
2860
- case SeverityNumber.FATAL3:
2861
- case SeverityNumber.FATAL4:
2862
- return "fatal";
2508
+ for (const [key, value] of Object.entries(obj)) {
2509
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${Array.isArray(obj) ? `[${key}]` : key}`;
2510
+ if (Array.isArray(value)) {
2511
+ for (let i = 0; i < value.length; i++) {
2512
+ if (typeof value[i] === "object" && value[i] !== null) {
2513
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
2514
+ } else {
2515
+ if (value[i] === null) {
2516
+ result[`${newPrefix}.[${i}]`] = NULL_SENTINEL;
2517
+ } else {
2518
+ result[`${newPrefix}.[${i}]`] = value[i];
2519
+ }
2520
+ }
2521
+ }
2522
+ } else if (isRecord(value)) {
2523
+ Object.assign(result, flattenAttributes(value, newPrefix));
2524
+ } else {
2525
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
2526
+ result[newPrefix] = value;
2527
+ } else if (value === null) {
2528
+ result[newPrefix] = NULL_SENTINEL;
2529
+ }
2530
+ }
2863
2531
  }
2532
+ return result;
2864
2533
  }
2865
- __name(iconStringForSeverity, "iconStringForSeverity");
2866
- var _SimpleClock = class _SimpleClock {
2867
- preciseNow() {
2868
- const now = new PreciseDate();
2869
- const nowStruct = now.toStruct();
2870
- return [
2871
- nowStruct.seconds,
2872
- nowStruct.nanos
2873
- ];
2534
+ __name(flattenAttributes, "flattenAttributes");
2535
+ function isRecord(value) {
2536
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2537
+ }
2538
+ __name(isRecord, "isRecord");
2539
+ function unflattenAttributes(obj) {
2540
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
2541
+ return obj;
2874
2542
  }
2875
- reset() {
2543
+ if (typeof obj === "object" && obj !== null && Object.keys(obj).length === 1 && Object.keys(obj)[0] === "") {
2544
+ return rehydrateNull(obj[""]);
2876
2545
  }
2877
- };
2878
- __name(_SimpleClock, "SimpleClock");
2879
- var SimpleClock = _SimpleClock;
2880
-
2881
- // src/v3/clock/index.ts
2882
- var API_NAME2 = "clock";
2883
- var SIMPLE_CLOCK = new SimpleClock();
2884
- var _getClock, getClock_fn;
2885
- var _ClockAPI = class _ClockAPI {
2886
- constructor() {
2887
- __privateAdd(this, _getClock);
2546
+ if (Object.keys(obj).length === 0) {
2547
+ return;
2888
2548
  }
2889
- static getInstance() {
2890
- if (!this._instance) {
2891
- this._instance = new _ClockAPI();
2549
+ const result = {};
2550
+ for (const [key, value] of Object.entries(obj)) {
2551
+ const parts = key.split(".").reduce((acc, part) => {
2552
+ if (part.includes("[")) {
2553
+ const subparts = part.split(/\[|\]/).filter((p) => p !== "");
2554
+ acc.push(...subparts);
2555
+ } else {
2556
+ acc.push(part);
2557
+ }
2558
+ return acc;
2559
+ }, []);
2560
+ let current = result;
2561
+ for (let i = 0; i < parts.length - 1; i++) {
2562
+ const part = parts[i];
2563
+ const nextPart = parts[i + 1];
2564
+ const isArray = /^\d+$/.test(nextPart);
2565
+ if (isArray && !Array.isArray(current[part])) {
2566
+ current[part] = [];
2567
+ } else if (!isArray && current[part] === void 0) {
2568
+ current[part] = {};
2569
+ }
2570
+ current = current[part];
2892
2571
  }
2893
- return this._instance;
2572
+ const lastPart = parts[parts.length - 1];
2573
+ current[lastPart] = rehydrateNull(value);
2894
2574
  }
2895
- setGlobalClock(clock2) {
2896
- return registerGlobal(API_NAME2, clock2);
2575
+ if (Object.keys(result).every((k) => /^\d+$/.test(k))) {
2576
+ const maxIndex = Math.max(...Object.keys(result).map((k) => parseInt(k)));
2577
+ const arrayResult = Array(maxIndex + 1);
2578
+ for (const key in result) {
2579
+ arrayResult[parseInt(key)] = result[key];
2580
+ }
2581
+ return arrayResult;
2897
2582
  }
2898
- preciseNow() {
2899
- return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2583
+ return result;
2584
+ }
2585
+ __name(unflattenAttributes, "unflattenAttributes");
2586
+ function primitiveValueOrflattenedAttributes(obj, prefix) {
2587
+ if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
2588
+ return obj;
2900
2589
  }
2901
- reset() {
2902
- __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2590
+ const attributes = flattenAttributes(obj, prefix);
2591
+ if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
2592
+ return attributes[prefix];
2903
2593
  }
2904
- };
2905
- _getClock = new WeakSet();
2906
- getClock_fn = /* @__PURE__ */ __name(function() {
2907
- return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2908
- }, "#getClock");
2909
- __name(_ClockAPI, "ClockAPI");
2910
- var ClockAPI = _ClockAPI;
2911
-
2912
- // src/v3/clock-api.ts
2913
- var clock = ClockAPI.getInstance();
2594
+ return attributes;
2595
+ }
2596
+ __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
2597
+ function rehydrateNull(value) {
2598
+ if (value === NULL_SENTINEL) {
2599
+ return null;
2600
+ }
2601
+ return value;
2602
+ }
2603
+ __name(rehydrateNull, "rehydrateNull");
2914
2604
 
2915
2605
  // src/v3/logger/taskLogger.ts
2916
- var logLevels = [
2917
- "none",
2918
- "error",
2919
- "warn",
2920
- "log",
2921
- "info",
2922
- "debug"
2923
- ];
2924
- var _emitLog, emitLog_fn, _getTimestampInHrTime, getTimestampInHrTime_fn;
2925
- var _OtelTaskLogger = class _OtelTaskLogger {
2926
- constructor(_config) {
2927
- __privateAdd(this, _emitLog);
2928
- __privateAdd(this, _getTimestampInHrTime);
2929
- this._config = _config;
2930
- this._level = logLevels.indexOf(_config.level);
2931
- }
2932
- debug(message, properties) {
2933
- if (this._level < 5)
2934
- return;
2935
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "debug", SeverityNumber.DEBUG, properties);
2936
- }
2937
- log(message, properties) {
2938
- if (this._level < 3)
2939
- return;
2940
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "log", SeverityNumber.INFO, properties);
2941
- }
2942
- info(message, properties) {
2943
- if (this._level < 4)
2944
- return;
2945
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "info", SeverityNumber.INFO, properties);
2946
- }
2947
- warn(message, properties) {
2948
- if (this._level < 2)
2949
- return;
2950
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "warn", SeverityNumber.WARN, properties);
2951
- }
2952
- error(message, properties) {
2953
- if (this._level < 1)
2954
- return;
2955
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "error", SeverityNumber.ERROR, properties);
2956
- }
2957
- trace(name, fn, options) {
2958
- return this._config.tracer.startActiveSpan(name, fn, options);
2959
- }
2960
- };
2961
- _emitLog = new WeakSet();
2962
- emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
2963
- let attributes = {
2964
- ...flattenAttributes(properties)
2965
- };
2966
- const icon = iconStringForSeverity(severityNumber);
2967
- if (icon !== void 0) {
2968
- attributes[SemanticInternalAttributes.STYLE_ICON] = icon;
2969
- }
2970
- this._config.logger.emit({
2971
- severityNumber,
2972
- severityText,
2973
- body: message,
2974
- attributes,
2975
- timestamp
2976
- });
2977
- }, "#emitLog");
2978
- _getTimestampInHrTime = new WeakSet();
2979
- getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
2980
- return clock.preciseNow();
2981
- }, "#getTimestampInHrTime");
2982
- __name(_OtelTaskLogger, "OtelTaskLogger");
2983
- var OtelTaskLogger = _OtelTaskLogger;
2984
2606
  var _NoopTaskLogger = class _NoopTaskLogger {
2985
2607
  debug() {
2986
2608
  }
@@ -3048,49 +2670,209 @@ var LoggerAPI = _LoggerAPI;
3048
2670
  // src/v3/logger-api.ts
3049
2671
  var logger = LoggerAPI.getInstance();
3050
2672
 
3051
- // src/v3/limits.ts
3052
- var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
3053
- var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
3054
- var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
3055
- var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
3056
- var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
3057
- var OTEL_LINK_COUNT_LIMIT = 2;
3058
- var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
3059
- var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
3060
- var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
3061
- function imposeAttributeLimits(attributes) {
3062
- const newAttributes = {};
3063
- for (const [key, value] of Object.entries(attributes)) {
3064
- if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
3065
- continue;
3066
- }
3067
- if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
3068
- break;
2673
+ // src/v3/runtime/noopRuntimeManager.ts
2674
+ var _NoopRuntimeManager = class _NoopRuntimeManager {
2675
+ disable() {
2676
+ }
2677
+ waitForDuration(ms) {
2678
+ return Promise.resolve();
2679
+ }
2680
+ waitUntil(date) {
2681
+ return Promise.resolve();
2682
+ }
2683
+ waitForTask(params) {
2684
+ return Promise.resolve({
2685
+ ok: false,
2686
+ id: params.id,
2687
+ error: {
2688
+ type: "INTERNAL_ERROR",
2689
+ code: "CONFIGURED_INCORRECTLY"
2690
+ }
2691
+ });
2692
+ }
2693
+ waitForBatch(params) {
2694
+ return Promise.resolve({
2695
+ id: params.id,
2696
+ items: []
2697
+ });
2698
+ }
2699
+ };
2700
+ __name(_NoopRuntimeManager, "NoopRuntimeManager");
2701
+ var NoopRuntimeManager = _NoopRuntimeManager;
2702
+
2703
+ // src/v3/runtime/index.ts
2704
+ var API_NAME4 = "runtime";
2705
+ var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
2706
+ var _getRuntimeManager, getRuntimeManager_fn;
2707
+ var _RuntimeAPI = class _RuntimeAPI {
2708
+ constructor() {
2709
+ __privateAdd(this, _getRuntimeManager);
2710
+ }
2711
+ static getInstance() {
2712
+ if (!this._instance) {
2713
+ this._instance = new _RuntimeAPI();
3069
2714
  }
3070
- newAttributes[key] = value;
2715
+ return this._instance;
3071
2716
  }
3072
- return newAttributes;
3073
- }
3074
- __name(imposeAttributeLimits, "imposeAttributeLimits");
3075
- function calculateAttributeValueLength(value) {
3076
- if (value === void 0 || value === null) {
3077
- return 0;
2717
+ waitForDuration(ms) {
2718
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
3078
2719
  }
3079
- if (typeof value === "string") {
3080
- return value.length;
2720
+ waitUntil(date) {
2721
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
3081
2722
  }
3082
- if (typeof value === "number") {
3083
- return 8;
2723
+ waitForTask(params) {
2724
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
3084
2725
  }
3085
- if (typeof value === "boolean") {
3086
- return 4;
2726
+ waitForBatch(params) {
2727
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
3087
2728
  }
3088
- if (Array.isArray(value)) {
3089
- return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
2729
+ setGlobalRuntimeManager(runtimeManager) {
2730
+ return registerGlobal(API_NAME4, runtimeManager);
2731
+ }
2732
+ disable() {
2733
+ __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2734
+ unregisterGlobal(API_NAME4);
2735
+ }
2736
+ };
2737
+ _getRuntimeManager = new WeakSet();
2738
+ getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
2739
+ return getGlobal(API_NAME4) ?? NOOP_RUNTIME_MANAGER;
2740
+ }, "#getRuntimeManager");
2741
+ __name(_RuntimeAPI, "RuntimeAPI");
2742
+ var RuntimeAPI = _RuntimeAPI;
2743
+
2744
+ // src/v3/runtime-api.ts
2745
+ var runtime = RuntimeAPI.getInstance();
2746
+
2747
+ // src/v3/utils/getEnv.ts
2748
+ function getEnvVar(name) {
2749
+ if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
2750
+ return process.env[name];
3090
2751
  }
3091
- return 0;
3092
2752
  }
3093
- __name(calculateAttributeValueLength, "calculateAttributeValueLength");
2753
+ __name(getEnvVar, "getEnvVar");
2754
+
2755
+ // src/v3/apiClientManager/index.ts
2756
+ var API_NAME5 = "api-client";
2757
+ var _getConfig, getConfig_fn;
2758
+ var _APIClientManagerAPI = class _APIClientManagerAPI {
2759
+ constructor() {
2760
+ __privateAdd(this, _getConfig);
2761
+ }
2762
+ static getInstance() {
2763
+ if (!this._instance) {
2764
+ this._instance = new _APIClientManagerAPI();
2765
+ }
2766
+ return this._instance;
2767
+ }
2768
+ disable() {
2769
+ unregisterGlobal(API_NAME5);
2770
+ }
2771
+ setGlobalAPIClientConfiguration(config) {
2772
+ return registerGlobal(API_NAME5, config);
2773
+ }
2774
+ get baseURL() {
2775
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
2776
+ return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
2777
+ }
2778
+ get accessToken() {
2779
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
2780
+ return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY");
2781
+ }
2782
+ get client() {
2783
+ if (!this.baseURL || !this.accessToken) {
2784
+ return void 0;
2785
+ }
2786
+ return new ApiClient(this.baseURL, this.accessToken);
2787
+ }
2788
+ };
2789
+ _getConfig = new WeakSet();
2790
+ getConfig_fn = /* @__PURE__ */ __name(function() {
2791
+ return getGlobal(API_NAME5);
2792
+ }, "#getConfig");
2793
+ __name(_APIClientManagerAPI, "APIClientManagerAPI");
2794
+ var APIClientManagerAPI = _APIClientManagerAPI;
2795
+
2796
+ // src/v3/apiClientManager-api.ts
2797
+ var apiClientManager = APIClientManagerAPI.getInstance();
2798
+
2799
+ // src/v3/task-catalog/noopTaskCatalog.ts
2800
+ var _NoopTaskCatalog = class _NoopTaskCatalog {
2801
+ registerTaskMetadata(task) {
2802
+ }
2803
+ registerTaskFileMetadata(id, metadata) {
2804
+ }
2805
+ updateTaskMetadata(id, updates) {
2806
+ }
2807
+ getAllTaskMetadata() {
2808
+ return [];
2809
+ }
2810
+ getTaskMetadata(id) {
2811
+ return void 0;
2812
+ }
2813
+ getTask(id) {
2814
+ return void 0;
2815
+ }
2816
+ taskExists(id) {
2817
+ return false;
2818
+ }
2819
+ disable() {
2820
+ }
2821
+ };
2822
+ __name(_NoopTaskCatalog, "NoopTaskCatalog");
2823
+ var NoopTaskCatalog = _NoopTaskCatalog;
2824
+
2825
+ // src/v3/task-catalog/index.ts
2826
+ var API_NAME6 = "task-catalog";
2827
+ var NOOP_TASK_CATALOG = new NoopTaskCatalog();
2828
+ var _getCatalog, getCatalog_fn;
2829
+ var _TaskCatalogAPI = class _TaskCatalogAPI {
2830
+ constructor() {
2831
+ __privateAdd(this, _getCatalog);
2832
+ }
2833
+ static getInstance() {
2834
+ if (!this._instance) {
2835
+ this._instance = new _TaskCatalogAPI();
2836
+ }
2837
+ return this._instance;
2838
+ }
2839
+ setGlobalTaskCatalog(taskCatalog2) {
2840
+ return registerGlobal(API_NAME6, taskCatalog2);
2841
+ }
2842
+ disable() {
2843
+ unregisterGlobal(API_NAME6);
2844
+ }
2845
+ registerTaskMetadata(task) {
2846
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskMetadata(task);
2847
+ }
2848
+ updateTaskMetadata(id, updates) {
2849
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).updateTaskMetadata(id, updates);
2850
+ }
2851
+ registerTaskFileMetadata(id, metadata) {
2852
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskFileMetadata(id, metadata);
2853
+ }
2854
+ getAllTaskMetadata() {
2855
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getAllTaskMetadata();
2856
+ }
2857
+ getTaskMetadata(id) {
2858
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTaskMetadata(id);
2859
+ }
2860
+ getTask(id) {
2861
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTask(id);
2862
+ }
2863
+ taskExists(id) {
2864
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).taskExists(id);
2865
+ }
2866
+ };
2867
+ _getCatalog = new WeakSet();
2868
+ getCatalog_fn = /* @__PURE__ */ __name(function() {
2869
+ return getGlobal(API_NAME6) ?? NOOP_TASK_CATALOG;
2870
+ }, "#getCatalog");
2871
+ __name(_TaskCatalogAPI, "TaskCatalogAPI");
2872
+ var TaskCatalogAPI = _TaskCatalogAPI;
2873
+
2874
+ // src/v3/task-catalog-api.ts
2875
+ var taskCatalog = TaskCatalogAPI.getInstance();
3094
2876
  function dateDifference(date1, date2) {
3095
2877
  return Math.abs(date1.getTime() - date2.getTime());
3096
2878
  }
@@ -3143,571 +2925,99 @@ function formatDurationMilliseconds(milliseconds, options) {
3143
2925
  duration = duration.replace(" hours", "h");
3144
2926
  duration = duration.replace(" hour", "h");
3145
2927
  duration = duration.replace(" days", "d");
3146
- duration = duration.replace(" day", "d");
3147
- duration = duration.replace(" weeks", "w");
3148
- duration = duration.replace(" week", "w");
3149
- duration = duration.replace(" months", "mo");
3150
- duration = duration.replace(" month", "mo");
3151
- duration = duration.replace(" years", "y");
3152
- duration = duration.replace(" year", "y");
3153
- }
3154
- return duration;
3155
- }
3156
- __name(formatDurationMilliseconds, "formatDurationMilliseconds");
3157
- function formatDurationInDays(milliseconds) {
3158
- let duration = humanizeDuration(milliseconds, {
3159
- maxDecimalPoints: 0,
3160
- largest: 2,
3161
- units: [
3162
- "d"
3163
- ]
3164
- });
3165
- return duration;
3166
- }
3167
- __name(formatDurationInDays, "formatDurationInDays");
3168
-
3169
- // src/v3/runtime/devRuntimeManager.ts
3170
- var _DevRuntimeManager = class _DevRuntimeManager {
3171
- constructor() {
3172
- __publicField(this, "_taskWaits", /* @__PURE__ */ new Map());
3173
- __publicField(this, "_batchWaits", /* @__PURE__ */ new Map());
3174
- __publicField(this, "_tasks", /* @__PURE__ */ new Map());
3175
- __publicField(this, "_pendingCompletionNotifications", /* @__PURE__ */ new Map());
3176
- }
3177
- disable() {
3178
- }
3179
- registerTasks(tasks) {
3180
- for (const task of tasks) {
3181
- this._tasks.set(task.id, task);
3182
- }
3183
- }
3184
- getTaskMetadata(id) {
3185
- return this._tasks.get(id);
3186
- }
3187
- async waitForDuration(ms) {
3188
- return new Promise((resolve) => {
3189
- setTimeout(resolve, ms);
3190
- });
3191
- }
3192
- async waitUntil(date) {
3193
- return new Promise((resolve) => {
3194
- setTimeout(resolve, date.getTime() - Date.now());
3195
- });
3196
- }
3197
- async waitForTask(params) {
3198
- const pendingCompletion = this._pendingCompletionNotifications.get(params.id);
3199
- if (pendingCompletion) {
3200
- this._pendingCompletionNotifications.delete(params.id);
3201
- return pendingCompletion;
3202
- }
3203
- const promise = new Promise((resolve, reject) => {
3204
- this._taskWaits.set(params.id, {
3205
- resolve,
3206
- reject
3207
- });
3208
- });
3209
- return await promise;
3210
- }
3211
- async waitForBatch(params) {
3212
- if (!params.runs.length) {
3213
- return Promise.resolve({
3214
- id: params.id,
3215
- items: []
3216
- });
3217
- }
3218
- const promise = Promise.all(params.runs.map((runId) => {
3219
- return new Promise((resolve, reject) => {
3220
- const pendingCompletion = this._pendingCompletionNotifications.get(runId);
3221
- if (pendingCompletion) {
3222
- this._pendingCompletionNotifications.delete(runId);
3223
- if (pendingCompletion.ok) {
3224
- resolve(pendingCompletion);
3225
- } else {
3226
- reject(pendingCompletion);
3227
- }
3228
- return;
3229
- }
3230
- this._taskWaits.set(runId, {
3231
- resolve,
3232
- reject
3233
- });
3234
- });
3235
- }));
3236
- const results = await promise;
3237
- return {
3238
- id: params.id,
3239
- items: results
3240
- };
3241
- }
3242
- resumeTask(completion, execution) {
3243
- const wait = this._taskWaits.get(execution.run.id);
3244
- if (!wait) {
3245
- this._pendingCompletionNotifications.set(execution.run.id, completion);
3246
- return;
3247
- }
3248
- if (completion.ok) {
3249
- wait.resolve(completion);
3250
- } else {
3251
- wait.reject(completion);
3252
- }
3253
- this._taskWaits.delete(execution.run.id);
3254
- }
3255
- };
3256
- __name(_DevRuntimeManager, "DevRuntimeManager");
3257
- var DevRuntimeManager = _DevRuntimeManager;
3258
- var _ProdRuntimeManager = class _ProdRuntimeManager {
3259
- constructor(ipc, options = {}) {
3260
- this.ipc = ipc;
3261
- this.options = options;
3262
- this._taskWaits = /* @__PURE__ */ new Map();
3263
- this._batchWaits = /* @__PURE__ */ new Map();
3264
- this._tasks = /* @__PURE__ */ new Map();
3265
- }
3266
- disable() {
3267
- }
3268
- registerTasks(tasks) {
3269
- for (const task of tasks) {
3270
- this._tasks.set(task.id, task);
3271
- }
3272
- }
3273
- getTaskMetadata(id) {
3274
- return this._tasks.get(id);
3275
- }
3276
- async waitForDuration(ms) {
3277
- const now = Date.now();
3278
- const resolveAfterDuration = setTimeout$1(ms, "duration");
3279
- if (ms <= this.waitThresholdInMs) {
3280
- await resolveAfterDuration;
3281
- return;
3282
- }
3283
- const waitForRestore = new Promise((resolve, reject) => {
3284
- this._waitForRestore = {
3285
- resolve,
3286
- reject
3287
- };
3288
- });
3289
- const { willCheckpointAndRestore } = await this.ipc.sendWithAck("WAIT_FOR_DURATION", {
3290
- ms,
3291
- now
3292
- });
3293
- if (!willCheckpointAndRestore) {
3294
- await resolveAfterDuration;
3295
- return;
3296
- }
3297
- this.ipc.send("READY_FOR_CHECKPOINT", {});
3298
- await Promise.race([
3299
- waitForRestore,
3300
- resolveAfterDuration
3301
- ]);
3302
- this.ipc.send("CANCEL_CHECKPOINT", {});
3303
- }
3304
- resumeAfterRestore() {
3305
- if (!this._waitForRestore) {
3306
- return;
3307
- }
3308
- clock.reset();
3309
- this._waitForRestore.resolve("restore");
3310
- this._waitForRestore = void 0;
3311
- }
3312
- async waitUntil(date) {
3313
- return this.waitForDuration(date.getTime() - Date.now());
3314
- }
3315
- async waitForTask(params) {
3316
- const promise = new Promise((resolve, reject) => {
3317
- this._taskWaits.set(params.id, {
3318
- resolve,
3319
- reject
3320
- });
3321
- });
3322
- await this.ipc.send("WAIT_FOR_TASK", {
3323
- friendlyId: params.id
3324
- });
3325
- return await promise;
3326
- }
3327
- async waitForBatch(params) {
3328
- if (!params.runs.length) {
3329
- return Promise.resolve({
3330
- id: params.id,
3331
- items: []
3332
- });
3333
- }
3334
- const promise = Promise.all(params.runs.map((runId) => {
3335
- return new Promise((resolve, reject) => {
3336
- this._taskWaits.set(runId, {
3337
- resolve,
3338
- reject
3339
- });
3340
- });
3341
- }));
3342
- await this.ipc.send("WAIT_FOR_BATCH", {
3343
- batchFriendlyId: params.id,
3344
- runFriendlyIds: params.runs
3345
- });
3346
- const results = await promise;
3347
- return {
3348
- id: params.id,
3349
- items: results
3350
- };
3351
- }
3352
- resumeTask(completion, execution) {
3353
- const wait = this._taskWaits.get(execution.run.id);
3354
- if (!wait) {
3355
- return;
3356
- }
3357
- if (completion.ok) {
3358
- wait.resolve(completion);
3359
- } else {
3360
- wait.reject(completion);
3361
- }
3362
- this._taskWaits.delete(execution.run.id);
3363
- }
3364
- get waitThresholdInMs() {
3365
- return this.options.waitThresholdInMs ?? 3e4;
3366
- }
3367
- };
3368
- __name(_ProdRuntimeManager, "ProdRuntimeManager");
3369
- var ProdRuntimeManager = _ProdRuntimeManager;
3370
- var _originClockTime, originClockTime_get, _originPreciseDate, originPreciseDate_get;
3371
- var _PreciseWallClock = class _PreciseWallClock {
3372
- constructor(options = {}) {
3373
- __privateAdd(this, _originClockTime);
3374
- __privateAdd(this, _originPreciseDate);
3375
- this._origin = {
3376
- clockTime: options.origin ?? process.hrtime(),
3377
- preciseDate: options.now ?? new PreciseDate()
3378
- };
3379
- }
3380
- preciseNow() {
3381
- const elapsedHrTime = process.hrtime(__privateGet(this, _originClockTime, originClockTime_get));
3382
- const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
3383
- const preciseDate = new PreciseDate(__privateGet(this, _originPreciseDate, originPreciseDate_get).getFullTime() + elapsedNanoseconds);
3384
- const dateStruct = preciseDate.toStruct();
3385
- return [
3386
- dateStruct.seconds,
3387
- dateStruct.nanos
3388
- ];
3389
- }
3390
- reset() {
3391
- this._origin = {
3392
- clockTime: process.hrtime(),
3393
- preciseDate: new PreciseDate()
3394
- };
3395
- }
3396
- };
3397
- _originClockTime = new WeakSet();
3398
- originClockTime_get = /* @__PURE__ */ __name(function() {
3399
- return this._origin.clockTime;
3400
- }, "#originClockTime");
3401
- _originPreciseDate = new WeakSet();
3402
- originPreciseDate_get = /* @__PURE__ */ __name(function() {
3403
- return this._origin.preciseDate;
3404
- }, "#originPreciseDate");
3405
- __name(_PreciseWallClock, "PreciseWallClock");
3406
- var PreciseWallClock = _PreciseWallClock;
3407
- var _TriggerTracer = class _TriggerTracer {
3408
- constructor(_config) {
3409
- this._config = _config;
3410
- }
3411
- get tracer() {
3412
- if (!this._tracer) {
3413
- if ("tracer" in this._config)
3414
- return this._config.tracer;
3415
- this._tracer = trace.getTracer(this._config.name, this._config.version);
3416
- }
3417
- return this._tracer;
3418
- }
3419
- get logger() {
3420
- if (!this._logger) {
3421
- if ("logger" in this._config)
3422
- return this._config.logger;
3423
- this._logger = logs.getLogger(this._config.name, this._config.version);
3424
- }
3425
- return this._logger;
3426
- }
3427
- extractContext(traceContext) {
3428
- return propagation.extract(context.active(), traceContext ?? {});
3429
- }
3430
- startActiveSpan(name, fn, options, ctx) {
3431
- const parentContext = ctx ?? context.active();
3432
- const attributes = options?.attributes ?? {};
3433
- return this.tracer.startActiveSpan(name, {
3434
- ...options,
3435
- attributes,
3436
- startTime: clock.preciseNow()
3437
- }, parentContext, async (span) => {
3438
- this.tracer.startSpan(name, {
3439
- ...options,
3440
- attributes: {
3441
- ...attributes,
3442
- [SemanticInternalAttributes.SPAN_PARTIAL]: true,
3443
- [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
3444
- }
3445
- }, parentContext).end();
3446
- try {
3447
- return await fn(span);
3448
- } catch (e) {
3449
- if (typeof e === "string" || e instanceof Error) {
3450
- span.recordException(e);
3451
- }
3452
- span.setStatus({
3453
- code: SpanStatusCode.ERROR
3454
- });
3455
- throw e;
3456
- } finally {
3457
- span.end(clock.preciseNow());
3458
- }
3459
- });
3460
- }
3461
- startSpan(name, options, ctx) {
3462
- const parentContext = ctx ?? context.active();
3463
- const attributes = options?.attributes ?? {};
3464
- const span = this.tracer.startSpan(name, options, ctx);
3465
- this.tracer.startSpan(name, {
3466
- ...options,
3467
- attributes: {
3468
- ...attributes,
3469
- [SemanticInternalAttributes.SPAN_PARTIAL]: true,
3470
- [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
3471
- }
3472
- }, parentContext).end();
3473
- return span;
3474
- }
3475
- };
3476
- __name(_TriggerTracer, "TriggerTracer");
3477
- var TriggerTracer = _TriggerTracer;
3478
- var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
3479
- var _ConsoleInterceptor = class _ConsoleInterceptor {
3480
- constructor(logger2) {
3481
- __privateAdd(this, _handleLog);
3482
- __privateAdd(this, _getTimestampInHrTime2);
3483
- __privateAdd(this, _getAttributes);
3484
- this.logger = logger2;
3485
- }
3486
- // Intercept the console and send logs to the OpenTelemetry logger
3487
- // during the execution of the callback
3488
- async intercept(console2, callback) {
3489
- const originalConsole = {
3490
- log: console2.log,
3491
- info: console2.info,
3492
- warn: console2.warn,
3493
- error: console2.error
3494
- };
3495
- console2.log = this.log.bind(this);
3496
- console2.info = this.info.bind(this);
3497
- console2.warn = this.warn.bind(this);
3498
- console2.error = this.error.bind(this);
3499
- try {
3500
- return await callback();
3501
- } finally {
3502
- console2.log = originalConsole.log;
3503
- console2.info = originalConsole.info;
3504
- console2.warn = originalConsole.warn;
3505
- console2.error = originalConsole.error;
3506
- }
3507
- }
3508
- log(...args) {
3509
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
3510
- }
3511
- info(...args) {
3512
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Info", ...args);
3513
- }
3514
- warn(...args) {
3515
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.WARN, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Warn", ...args);
3516
- }
3517
- error(...args) {
3518
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.ERROR, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Error", ...args);
3519
- }
3520
- };
3521
- _handleLog = new WeakSet();
3522
- handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
3523
- const body = util.format(...args);
3524
- const parsed = tryParseJSON(body);
3525
- if (parsed.ok) {
3526
- this.logger.emit({
3527
- severityNumber,
3528
- severityText,
3529
- body: getLogMessage(parsed.value, severityText),
3530
- attributes: {
3531
- ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3532
- ...flattenAttributes(parsed.value)
3533
- },
3534
- timestamp
3535
- });
3536
- return;
3537
- }
3538
- this.logger.emit({
3539
- severityNumber,
3540
- severityText,
3541
- body,
3542
- attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3543
- timestamp
3544
- });
3545
- }, "#handleLog");
3546
- _getTimestampInHrTime2 = new WeakSet();
3547
- getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
3548
- return clock.preciseNow();
3549
- }, "#getTimestampInHrTime");
3550
- _getAttributes = new WeakSet();
3551
- getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
3552
- const icon = iconStringForSeverity(severityNumber1);
3553
- let result = {};
3554
- if (icon !== void 0) {
3555
- result[SemanticInternalAttributes.STYLE_ICON] = icon;
3556
- }
3557
- return result;
3558
- }, "#getAttributes");
3559
- __name(_ConsoleInterceptor, "ConsoleInterceptor");
3560
- var ConsoleInterceptor = _ConsoleInterceptor;
3561
- function getLogMessage(value, fallback) {
3562
- if (typeof value["message"] === "string") {
3563
- return value["message"];
3564
- }
3565
- if (typeof value["msg"] === "string") {
3566
- return value["msg"];
3567
- }
3568
- if (typeof value["body"] === "string") {
3569
- return value["body"];
3570
- }
3571
- if (typeof value["error"] === "string") {
3572
- return value["error"];
3573
- }
3574
- return fallback;
3575
- }
3576
- __name(getLogMessage, "getLogMessage");
3577
- function tryParseJSON(value) {
3578
- try {
3579
- const parsed = JSON.parse(value);
3580
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
3581
- return {
3582
- ok: true,
3583
- value: parsed
3584
- };
3585
- }
3586
- return {
3587
- ok: false,
3588
- value
3589
- };
3590
- } catch (e) {
3591
- return {
3592
- ok: false,
3593
- value
3594
- };
3595
- }
3596
- }
3597
- __name(tryParseJSON, "tryParseJSON");
3598
-
3599
- // src/retry.ts
3600
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
3601
- if (!resets)
3602
- return;
3603
- switch (format) {
3604
- case "iso_8601_duration_openai_variant": {
3605
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
3606
- }
3607
- case "iso_8601": {
3608
- return calculateISO8601ResetAt(resets, now);
3609
- }
3610
- case "unix_timestamp": {
3611
- return calculateUnixTimestampResetAt(resets, now);
3612
- }
3613
- case "unix_timestamp_in_ms": {
3614
- return calculateUnixTimestampInMsResetAt(resets, now);
3615
- }
3616
- }
3617
- }
3618
- __name(calculateResetAt, "calculateResetAt");
3619
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
3620
- if (!resets)
3621
- return void 0;
3622
- const resetAt = parseInt(resets, 10);
3623
- if (isNaN(resetAt))
3624
- return void 0;
3625
- return new Date(resetAt * 1e3);
3626
- }
3627
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
3628
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
3629
- if (!resets)
3630
- return void 0;
3631
- const resetAt = parseInt(resets, 10);
3632
- if (isNaN(resetAt))
3633
- return void 0;
3634
- return new Date(resetAt);
3635
- }
3636
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
3637
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
3638
- if (!resets)
3639
- return void 0;
3640
- const resetAt = new Date(resets);
3641
- if (isNaN(resetAt.getTime()))
3642
- return void 0;
3643
- return resetAt;
3644
- }
3645
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
3646
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
3647
- if (!resets)
3648
- return void 0;
3649
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
3650
- const match = resets.match(pattern);
3651
- if (!match)
3652
- return void 0;
3653
- const days = parseInt(match[1], 10) || 0;
3654
- const hours = parseInt(match[2], 10) || 0;
3655
- const minutes = parseInt(match[3], 10) || 0;
3656
- const seconds = parseFloat(match[4]) || 0;
3657
- const milliseconds = parseInt(match[5], 10) || 0;
3658
- const resetAt = new Date(now);
3659
- resetAt.setDate(resetAt.getDate() + days);
3660
- resetAt.setHours(resetAt.getHours() + hours);
3661
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
3662
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
3663
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
3664
- return resetAt;
3665
- }
3666
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
3667
-
3668
- // src/v3/utils/retries.ts
3669
- var defaultRetryOptions = {
3670
- maxAttempts: 3,
3671
- factor: 2,
3672
- minTimeoutInMs: 1e3,
3673
- maxTimeoutInMs: 6e4,
3674
- randomize: true
3675
- };
3676
- var defaultFetchRetryOptions = {
3677
- byStatus: {
3678
- "429,408,409,5xx": {
3679
- strategy: "backoff",
3680
- ...defaultRetryOptions
3681
- }
3682
- },
3683
- connectionError: defaultRetryOptions,
3684
- timeout: defaultRetryOptions
3685
- };
3686
- function calculateNextRetryDelay(options, attempt) {
3687
- const opts = {
3688
- ...defaultRetryOptions,
3689
- ...options
3690
- };
3691
- if (attempt >= opts.maxAttempts) {
3692
- return;
3693
- }
3694
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
3695
- const random = randomize ? Math.random() + 1 : 1;
3696
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
3697
- return Math.round(timeout);
3698
- }
3699
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
3700
- function calculateResetAt2(resets, format, now = Date.now()) {
3701
- const resetAt = calculateResetAt(resets, format, new Date(now));
3702
- return resetAt?.getTime();
2928
+ duration = duration.replace(" day", "d");
2929
+ duration = duration.replace(" weeks", "w");
2930
+ duration = duration.replace(" week", "w");
2931
+ duration = duration.replace(" months", "mo");
2932
+ duration = duration.replace(" month", "mo");
2933
+ duration = duration.replace(" years", "y");
2934
+ duration = duration.replace(" year", "y");
2935
+ }
2936
+ return duration;
3703
2937
  }
3704
- __name(calculateResetAt2, "calculateResetAt");
3705
-
3706
- // src/v3/utils/styleAttributes.ts
3707
- function accessoryAttributes(accessory) {
3708
- return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
2938
+ __name(formatDurationMilliseconds, "formatDurationMilliseconds");
2939
+ function formatDurationInDays(milliseconds) {
2940
+ let duration = humanizeDuration(milliseconds, {
2941
+ maxDecimalPoints: 0,
2942
+ largest: 2,
2943
+ units: [
2944
+ "d"
2945
+ ]
2946
+ });
2947
+ return duration;
3709
2948
  }
3710
- __name(accessoryAttributes, "accessoryAttributes");
2949
+ __name(formatDurationInDays, "formatDurationInDays");
2950
+ var _TriggerTracer = class _TriggerTracer {
2951
+ constructor(_config) {
2952
+ this._config = _config;
2953
+ }
2954
+ get tracer() {
2955
+ if (!this._tracer) {
2956
+ if ("tracer" in this._config)
2957
+ return this._config.tracer;
2958
+ this._tracer = trace.getTracer(this._config.name, this._config.version);
2959
+ }
2960
+ return this._tracer;
2961
+ }
2962
+ get logger() {
2963
+ if (!this._logger) {
2964
+ if ("logger" in this._config)
2965
+ return this._config.logger;
2966
+ this._logger = logs.getLogger(this._config.name, this._config.version);
2967
+ }
2968
+ return this._logger;
2969
+ }
2970
+ extractContext(traceContext) {
2971
+ return propagation.extract(context.active(), traceContext ?? {});
2972
+ }
2973
+ startActiveSpan(name, fn, options, ctx) {
2974
+ const parentContext = ctx ?? context.active();
2975
+ const attributes = options?.attributes ?? {};
2976
+ return this.tracer.startActiveSpan(name, {
2977
+ ...options,
2978
+ attributes,
2979
+ startTime: clock.preciseNow()
2980
+ }, parentContext, async (span) => {
2981
+ this.tracer.startSpan(name, {
2982
+ ...options,
2983
+ attributes: {
2984
+ ...attributes,
2985
+ [SemanticInternalAttributes.SPAN_PARTIAL]: true,
2986
+ [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
2987
+ }
2988
+ }, parentContext).end();
2989
+ try {
2990
+ return await fn(span);
2991
+ } catch (e) {
2992
+ if (typeof e === "string" || e instanceof Error) {
2993
+ span.recordException(e);
2994
+ }
2995
+ span.setStatus({
2996
+ code: SpanStatusCode.ERROR
2997
+ });
2998
+ throw e;
2999
+ } finally {
3000
+ span.end(clock.preciseNow());
3001
+ }
3002
+ });
3003
+ }
3004
+ startSpan(name, options, ctx) {
3005
+ const parentContext = ctx ?? context.active();
3006
+ const attributes = options?.attributes ?? {};
3007
+ const span = this.tracer.startSpan(name, options, ctx);
3008
+ this.tracer.startSpan(name, {
3009
+ ...options,
3010
+ attributes: {
3011
+ ...attributes,
3012
+ [SemanticInternalAttributes.SPAN_PARTIAL]: true,
3013
+ [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
3014
+ }
3015
+ }, parentContext).end();
3016
+ return span;
3017
+ }
3018
+ };
3019
+ __name(_TriggerTracer, "TriggerTracer");
3020
+ var TriggerTracer = _TriggerTracer;
3711
3021
 
3712
3022
  // src/eventFilterMatches.ts
3713
3023
  function eventFilterMatches(payload, filter) {
@@ -3877,150 +3187,41 @@ function omit(obj, ...keys) {
3877
3187
  return result;
3878
3188
  }
3879
3189
  __name(omit, "omit");
3880
- var _a2;
3881
- var AsyncResourceDetector = (_a2 = class {
3882
- constructor() {
3883
- __publicField(this, "_resolved", false);
3884
- this._promise = new Promise((resolver) => {
3885
- this._resolver = resolver;
3886
- });
3887
- }
3888
- detect(_config) {
3889
- return new Resource({}, this._promise);
3890
- }
3891
- resolveWithAttributes(attributes) {
3892
- if (!this._resolver) {
3893
- throw new Error("Resolver not available");
3894
- }
3895
- if (this._resolved) {
3896
- return;
3897
- }
3898
- this._resolved = true;
3899
- this._resolver(attributes);
3900
- }
3901
- }, __name(_a2, "AsyncResourceDetector"), _a2);
3902
- var _TracingSDK = class _TracingSDK {
3903
- constructor(config) {
3904
- this.config = config;
3905
- this.asyncResourceDetector = new AsyncResourceDetector();
3906
- setLogLevel(config.diagLogLevel ?? "none");
3907
- const envResourceAttributesSerialized = getEnvVar("OTEL_RESOURCE_ATTRIBUTES");
3908
- const envResourceAttributes = envResourceAttributesSerialized ? JSON.parse(envResourceAttributesSerialized) : {};
3909
- const commonResources = detectResourcesSync({
3910
- detectors: [
3911
- this.asyncResourceDetector,
3912
- processDetectorSync
3913
- ]
3914
- }).merge(new Resource({
3915
- [SemanticResourceAttributes.CLOUD_PROVIDER]: "trigger.dev",
3916
- [SemanticInternalAttributes.TRIGGER]: true
3917
- })).merge(config.resource ?? new Resource({})).merge(new Resource(envResourceAttributes));
3918
- const traceProvider = new NodeTracerProvider({
3919
- forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
3920
- resource: commonResources,
3921
- spanLimits: {
3922
- attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
3923
- attributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
3924
- eventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT,
3925
- attributePerEventCountLimit: OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
3926
- linkCountLimit: OTEL_LINK_COUNT_LIMIT,
3927
- attributePerLinkCountLimit: OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT
3928
- }
3929
- });
3930
- const spanExporter = new OTLPTraceExporter({
3931
- url: `${config.url}/v1/traces`,
3932
- timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
3933
- });
3934
- traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new BatchSpanProcessor(spanExporter, {
3935
- maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
3936
- scheduledDelayMillis: parseInt(getEnvVar("OTEL_SPAN_SCHEDULED_DELAY_MILLIS") ?? "200"),
3937
- exportTimeoutMillis: parseInt(getEnvVar("OTEL_SPAN_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
3938
- maxQueueSize: parseInt(getEnvVar("OTEL_SPAN_MAX_QUEUE_SIZE") ?? "512")
3939
- }) : new SimpleSpanProcessor(spanExporter)));
3940
- traceProvider.register();
3941
- registerInstrumentations({
3942
- instrumentations: config.instrumentations ?? [],
3943
- tracerProvider: traceProvider
3944
- });
3945
- const logExporter = new OTLPLogExporter({
3946
- url: `${config.url}/v1/logs`
3947
- });
3948
- const loggerProvider = new LoggerProvider({
3949
- resource: commonResources,
3950
- logRecordLimits: {
3951
- attributeCountLimit: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
3952
- attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
3953
- }
3954
- });
3955
- loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new BatchLogRecordProcessor(logExporter, {
3956
- maxExportBatchSize: parseInt(getEnvVar("OTEL_LOG_MAX_EXPORT_BATCH_SIZE") ?? "64"),
3957
- scheduledDelayMillis: parseInt(getEnvVar("OTEL_LOG_SCHEDULED_DELAY_MILLIS") ?? "200"),
3958
- exportTimeoutMillis: parseInt(getEnvVar("OTEL_LOG_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
3959
- maxQueueSize: parseInt(getEnvVar("OTEL_LOG_MAX_QUEUE_SIZE") ?? "512")
3960
- }) : new SimpleLogRecordProcessor(logExporter)));
3961
- this._logProvider = loggerProvider;
3962
- this._spanExporter = spanExporter;
3963
- this._traceProvider = traceProvider;
3964
- logs.setGlobalLoggerProvider(loggerProvider);
3965
- this.getLogger = loggerProvider.getLogger.bind(loggerProvider);
3966
- this.getTracer = traceProvider.getTracer.bind(traceProvider);
3967
- }
3968
- async flush() {
3969
- await this._spanExporter.forceFlush?.();
3970
- await this._logProvider.forceFlush();
3971
- }
3972
- async shutdown() {
3973
- await this._spanExporter.shutdown();
3974
- await this._logProvider.shutdown();
3975
- }
3976
- };
3977
- __name(_TracingSDK, "TracingSDK");
3978
- var TracingSDK = _TracingSDK;
3979
- function setLogLevel(level) {
3980
- let diagLogLevel;
3981
- switch (level) {
3982
- case "none":
3983
- diagLogLevel = DiagLogLevel.NONE;
3984
- break;
3985
- case "error":
3986
- diagLogLevel = DiagLogLevel.ERROR;
3987
- break;
3988
- case "warn":
3989
- diagLogLevel = DiagLogLevel.WARN;
3990
- break;
3991
- case "info":
3992
- diagLogLevel = DiagLogLevel.INFO;
3993
- break;
3994
- case "debug":
3995
- diagLogLevel = DiagLogLevel.DEBUG;
3996
- break;
3997
- case "verbose":
3998
- diagLogLevel = DiagLogLevel.VERBOSE;
3999
- break;
4000
- case "all":
4001
- diagLogLevel = DiagLogLevel.ALL;
4002
- break;
4003
- default:
4004
- diagLogLevel = DiagLogLevel.NONE;
4005
- }
4006
- diag.setLogger(new DiagConsoleLogger(), diagLogLevel);
3190
+
3191
+ // src/v3/utils/styleAttributes.ts
3192
+ function accessoryAttributes(accessory) {
3193
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
4007
3194
  }
4008
- __name(setLogLevel, "setLogLevel");
3195
+ __name(accessoryAttributes, "accessoryAttributes");
4009
3196
 
4010
- // src/v3/otel/index.ts
4011
- function recordSpanException(span, error) {
4012
- if (error instanceof Error) {
4013
- span.recordException(error);
4014
- } else if (typeof error === "string") {
4015
- span.recordException(new Error(error));
4016
- } else {
4017
- span.recordException(new Error(JSON.stringify(error)));
4018
- }
4019
- span.setStatus({
4020
- code: SpanStatusCode.ERROR
4021
- });
3197
+ // package.json
3198
+ var dependencies = {
3199
+ "@google-cloud/precise-date": "^4.0.0",
3200
+ "@opentelemetry/api": "^1.8.0",
3201
+ "@opentelemetry/api-logs": "^0.48.0",
3202
+ "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
3203
+ "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
3204
+ "@opentelemetry/instrumentation": "^0.49.1",
3205
+ "@opentelemetry/resources": "^1.22.0",
3206
+ "@opentelemetry/sdk-logs": "^0.49.1",
3207
+ "@opentelemetry/sdk-node": "^0.49.1",
3208
+ "@opentelemetry/sdk-trace-base": "^1.22.0",
3209
+ "@opentelemetry/sdk-trace-node": "^1.22.0",
3210
+ "@opentelemetry/semantic-conventions": "^1.22.0",
3211
+ "humanize-duration": "^3.27.3",
3212
+ superjson: "^2.2.1",
3213
+ ulidx: "^2.2.1",
3214
+ zod: "3.22.3",
3215
+ "zod-error": "1.5.0",
3216
+ "zod-validation-error": "^1.5.0",
3217
+ "socket.io-client": "4.7.4"
3218
+ };
3219
+
3220
+ // src/v3/utils/detectDependencyVersion.ts
3221
+ function detectDependencyVersion(dependency) {
3222
+ return dependencies[dependency];
4022
3223
  }
4023
- __name(recordSpanException, "recordSpanException");
3224
+ __name(detectDependencyVersion, "detectDependencyVersion");
4024
3225
 
4025
3226
  // src/v3/utils/ioSerialization.ts
4026
3227
  async function parsePacket(value) {
@@ -4063,6 +3264,7 @@ async function stringifyIO(value) {
4063
3264
  };
4064
3265
  } catch {
4065
3266
  return {
3267
+ data: value,
4066
3268
  dataType: "application/json"
4067
3269
  };
4068
3270
  }
@@ -4107,23 +3309,20 @@ __name(packetRequiresOffloading, "packetRequiresOffloading");
4107
3309
  async function exportPacket(packet, pathPrefix) {
4108
3310
  const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
4109
3311
  const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
4110
- if (presignedResponse.ok) {
4111
- const uploadResponse = await fetch(presignedResponse.data.presignedUrl, {
4112
- method: "PUT",
4113
- headers: {
4114
- "Content-Type": packet.dataType
4115
- },
4116
- body: packet.data
4117
- });
4118
- if (!uploadResponse.ok) {
4119
- throw new Error(`Failed to upload output to ${presignedResponse.data.presignedUrl}: ${uploadResponse.statusText}`);
4120
- }
4121
- return {
4122
- data: filename,
4123
- dataType: "application/store"
4124
- };
3312
+ const uploadResponse = await fetch(presignedResponse.presignedUrl, {
3313
+ method: "PUT",
3314
+ headers: {
3315
+ "Content-Type": packet.dataType
3316
+ },
3317
+ body: packet.data
3318
+ });
3319
+ if (!uploadResponse.ok) {
3320
+ throw new Error(`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`);
4125
3321
  }
4126
- return packet;
3322
+ return {
3323
+ data: filename,
3324
+ dataType: "application/store"
3325
+ };
4127
3326
  }
4128
3327
  __name(exportPacket, "exportPacket");
4129
3328
  async function conditionallyImportPacket(packet, tracer) {
@@ -4152,19 +3351,16 @@ async function importPacket(packet, span) {
4152
3351
  return packet;
4153
3352
  }
4154
3353
  const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
4155
- if (presignedResponse.ok) {
4156
- const response = await fetch(presignedResponse.data.presignedUrl);
4157
- if (!response.ok) {
4158
- throw new Error(`Failed to import packet ${presignedResponse.data.presignedUrl}: ${response.statusText}`);
4159
- }
4160
- const data = await response.text();
4161
- span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4162
- return {
4163
- data,
4164
- dataType: response.headers.get("content-type") ?? "application/json"
4165
- };
3354
+ const response = await fetch(presignedResponse.presignedUrl);
3355
+ if (!response.ok) {
3356
+ throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
4166
3357
  }
4167
- return packet;
3358
+ const data = await response.text();
3359
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
3360
+ return {
3361
+ data,
3362
+ dataType: response.headers.get("content-type") ?? "application/json"
3363
+ };
4168
3364
  }
4169
3365
  __name(importPacket, "importPacket");
4170
3366
  async function createPacketAttributes(packet, dataKey, dataTypeKey) {
@@ -4185,11 +3381,12 @@ async function createPacketAttributes(packet, dataKey, dataTypeKey) {
4185
3381
  try {
4186
3382
  const parsed = parse(packet.data);
4187
3383
  const jsonified = JSON.parse(JSON.stringify(parsed, safeReplacer));
4188
- return {
3384
+ const result = {
4189
3385
  ...flattenAttributes(jsonified, dataKey),
4190
3386
  [dataTypeKey]: "application/json"
4191
3387
  };
4192
- } catch {
3388
+ return result;
3389
+ } catch (e) {
4193
3390
  return;
4194
3391
  }
4195
3392
  case "application/store":
@@ -4217,7 +3414,7 @@ async function createPacketAttributesAsJson(data, dataType) {
4217
3414
  case "application/super+json":
4218
3415
  const { deserialize } = await loadSuperJSON();
4219
3416
  const deserialized = deserialize(data);
4220
- const jsonify = safeJsonParse(JSON.stringify(deserialized, safeReplacer));
3417
+ const jsonify = safeJsonParse2(JSON.stringify(deserialized, safeReplacer));
4221
3418
  return imposeAttributeLimits(flattenAttributes(jsonify, void 0));
4222
3419
  case "application/store":
4223
3420
  return data;
@@ -4231,10 +3428,16 @@ async function prettyPrintPacket(rawData, dataType) {
4231
3428
  return "";
4232
3429
  }
4233
3430
  if (dataType === "application/super+json") {
3431
+ if (typeof rawData === "string") {
3432
+ rawData = safeJsonParse2(rawData);
3433
+ }
4234
3434
  const { deserialize } = await loadSuperJSON();
4235
3435
  return await prettyPrintPacket(deserialize(rawData), "application/json");
4236
3436
  }
4237
3437
  if (dataType === "application/json") {
3438
+ if (typeof rawData === "string") {
3439
+ rawData = safeJsonParse2(rawData);
3440
+ }
4238
3441
  return JSON.stringify(rawData, safeReplacer, 2);
4239
3442
  }
4240
3443
  if (typeof rawData === "string") {
@@ -4280,304 +3483,15 @@ async function loadSuperJSON() {
4280
3483
  return await import('superjson');
4281
3484
  }
4282
3485
  __name(loadSuperJSON, "loadSuperJSON");
4283
- function safeJsonParse(value) {
3486
+ function safeJsonParse2(value) {
4284
3487
  try {
4285
3488
  return JSON.parse(value);
4286
3489
  } catch {
4287
3490
  return;
4288
3491
  }
4289
3492
  }
4290
- __name(safeJsonParse, "safeJsonParse");
4291
-
4292
- // src/v3/workers/taskExecutor.ts
4293
- var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
4294
- var _TaskExecutor = class _TaskExecutor {
4295
- constructor(task, options) {
4296
- __privateAdd(this, _callRun);
4297
- __privateAdd(this, _callTaskInit);
4298
- __privateAdd(this, _callTaskCleanup);
4299
- __privateAdd(this, _handleError);
4300
- this.task = task;
4301
- this._tracingSDK = options.tracingSDK;
4302
- this._tracer = options.tracer;
4303
- this._consoleInterceptor = options.consoleInterceptor;
4304
- this._config = options.projectConfig;
4305
- this._importedConfig = options.importedConfig;
4306
- this._handleErrorFn = options.handleErrorFn;
4307
- }
4308
- async execute(execution, worker, traceContext) {
4309
- const ctx = TaskRunContext.parse(execution);
4310
- const attemptMessage = `Attempt ${execution.attempt.number}`;
4311
- const originalPacket = {
4312
- data: execution.run.payload,
4313
- dataType: execution.run.payloadType
4314
- };
4315
- const result = await taskContextManager.runWith({
4316
- ctx,
4317
- worker
4318
- }, async () => {
4319
- this._tracingSDK.asyncResourceDetector.resolveWithAttributes({
4320
- ...taskContextManager.attributes,
4321
- [SemanticInternalAttributes.SDK_VERSION]: this.task.packageVersion,
4322
- [SemanticInternalAttributes.SDK_LANGUAGE]: "typescript"
4323
- });
4324
- return await this._tracer.startActiveSpan(attemptMessage, async (span) => {
4325
- return await this._consoleInterceptor.intercept(console, async () => {
4326
- let parsedPayload;
4327
- let initOutput;
4328
- try {
4329
- const payloadPacket = await conditionallyImportPacket(originalPacket, this._tracer);
4330
- parsedPayload = await parsePacket(payloadPacket);
4331
- initOutput = await __privateMethod(this, _callTaskInit, callTaskInit_fn).call(this, parsedPayload, ctx);
4332
- const output = await __privateMethod(this, _callRun, callRun_fn).call(this, parsedPayload, ctx, initOutput);
4333
- try {
4334
- const stringifiedOutput = await stringifyIO(output);
4335
- const finalOutput = await conditionallyExportPacket(stringifiedOutput, `${execution.attempt.id}/output`, this._tracer);
4336
- const attributes = await createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE);
4337
- if (attributes) {
4338
- span.setAttributes(attributes);
4339
- }
4340
- return {
4341
- ok: true,
4342
- id: execution.attempt.id,
4343
- output: finalOutput.data,
4344
- outputType: finalOutput.dataType
4345
- };
4346
- } catch (stringifyError) {
4347
- recordSpanException(span, stringifyError);
4348
- return {
4349
- ok: false,
4350
- id: execution.attempt.id,
4351
- error: {
4352
- type: "INTERNAL_ERROR",
4353
- code: TaskRunErrorCodes.TASK_OUTPUT_ERROR,
4354
- message: stringifyError instanceof Error ? stringifyError.message : typeof stringifyError === "string" ? stringifyError : void 0
4355
- }
4356
- };
4357
- }
4358
- } catch (runError) {
4359
- try {
4360
- const handleErrorResult = await __privateMethod(this, _handleError, handleError_fn).call(this, execution, runError, parsedPayload, ctx);
4361
- recordSpanException(span, handleErrorResult.error ?? runError);
4362
- return {
4363
- id: execution.attempt.id,
4364
- ok: false,
4365
- error: handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError),
4366
- retry: handleErrorResult.status === "retry" ? handleErrorResult.retry : void 0,
4367
- skippedRetrying: handleErrorResult.status === "skipped"
4368
- };
4369
- } catch (handleErrorError) {
4370
- recordSpanException(span, handleErrorError);
4371
- return {
4372
- ok: false,
4373
- id: execution.attempt.id,
4374
- error: {
4375
- type: "INTERNAL_ERROR",
4376
- code: TaskRunErrorCodes.HANDLE_ERROR_ERROR,
4377
- message: handleErrorError instanceof Error ? handleErrorError.message : typeof handleErrorError === "string" ? handleErrorError : void 0
4378
- }
4379
- };
4380
- }
4381
- } finally {
4382
- await __privateMethod(this, _callTaskCleanup, callTaskCleanup_fn).call(this, parsedPayload, ctx, initOutput);
4383
- }
4384
- });
4385
- }, {
4386
- kind: SpanKind.CONSUMER,
4387
- attributes: {
4388
- [SemanticInternalAttributes.STYLE_ICON]: "attempt",
4389
- ...accessoryAttributes({
4390
- items: [
4391
- {
4392
- text: ctx.task.filePath
4393
- },
4394
- {
4395
- text: `${ctx.task.exportName}.run()`
4396
- }
4397
- ],
4398
- style: "codepath"
4399
- })
4400
- }
4401
- }, this._tracer.extractContext(traceContext));
4402
- });
4403
- return result;
4404
- }
4405
- };
4406
- _callRun = new WeakSet();
4407
- callRun_fn = /* @__PURE__ */ __name(async function(payload, ctx, init) {
4408
- const runFn = this.task.fns.run;
4409
- const middlewareFn = this.task.fns.middleware;
4410
- if (!runFn) {
4411
- throw new Error("Task does not have a run function");
4412
- }
4413
- if (!middlewareFn) {
4414
- return runFn(payload, {
4415
- ctx
4416
- });
4417
- }
4418
- return middlewareFn(payload, {
4419
- ctx,
4420
- next: async () => runFn(payload, {
4421
- ctx,
4422
- init
4423
- })
4424
- });
4425
- }, "#callRun");
4426
- _callTaskInit = new WeakSet();
4427
- callTaskInit_fn = /* @__PURE__ */ __name(async function(payload1, ctx1) {
4428
- const initFn = this.task.fns.init;
4429
- if (!initFn) {
4430
- return {};
4431
- }
4432
- return this._tracer.startActiveSpan("init", async (span) => {
4433
- return await initFn(payload1, {
4434
- ctx: ctx1
4435
- });
4436
- });
4437
- }, "#callTaskInit");
4438
- _callTaskCleanup = new WeakSet();
4439
- callTaskCleanup_fn = /* @__PURE__ */ __name(async function(payload2, ctx2, init1) {
4440
- const cleanupFn = this.task.fns.cleanup;
4441
- if (!cleanupFn) {
4442
- return;
4443
- }
4444
- return this._tracer.startActiveSpan("cleanup", async (span) => {
4445
- return await cleanupFn(payload2, {
4446
- ctx: ctx2,
4447
- init: init1
4448
- });
4449
- });
4450
- }, "#callTaskCleanup");
4451
- _handleError = new WeakSet();
4452
- handleError_fn = /* @__PURE__ */ __name(async function(execution, error, payload3, ctx3) {
4453
- const retriesConfig = this._importedConfig?.retries ?? this._config.retries;
4454
- const retry = this.task.retry ?? retriesConfig?.default;
4455
- if (!retry) {
4456
- return {
4457
- status: "noop"
4458
- };
4459
- }
4460
- const delay = calculateNextRetryDelay(retry, execution.attempt.number);
4461
- if (execution.environment.type === "DEVELOPMENT" && typeof retriesConfig?.enabledInDev === "boolean" && !retriesConfig.enabledInDev) {
4462
- return {
4463
- status: "skipped"
4464
- };
4465
- }
4466
- return this._tracer.startActiveSpan("handleError()", async (span) => {
4467
- const handleErrorResult = this.task.fns.handleError ? await this.task.fns.handleError(payload3, error, {
4468
- ctx: ctx3,
4469
- retry,
4470
- retryDelayInMs: delay,
4471
- retryAt: delay ? new Date(Date.now() + delay) : void 0
4472
- }) : this._importedConfig ? await this._handleErrorFn?.(payload3, error, {
4473
- ctx: ctx3,
4474
- retry,
4475
- retryDelayInMs: delay,
4476
- retryAt: delay ? new Date(Date.now() + delay) : void 0
4477
- }) : void 0;
4478
- if (!handleErrorResult) {
4479
- return typeof delay === "undefined" ? {
4480
- status: "noop"
4481
- } : {
4482
- status: "retry",
4483
- retry: {
4484
- timestamp: Date.now() + delay,
4485
- delay
4486
- }
4487
- };
4488
- }
4489
- if (handleErrorResult.skipRetrying) {
4490
- return {
4491
- status: "skipped",
4492
- error: handleErrorResult.error
4493
- };
4494
- }
4495
- if (typeof handleErrorResult.retryAt !== "undefined") {
4496
- return {
4497
- status: "retry",
4498
- retry: {
4499
- timestamp: handleErrorResult.retryAt.getTime(),
4500
- delay: handleErrorResult.retryAt.getTime() - Date.now()
4501
- },
4502
- error: handleErrorResult.error
4503
- };
4504
- }
4505
- if (typeof handleErrorResult.retryDelayInMs === "number") {
4506
- return {
4507
- status: "retry",
4508
- retry: {
4509
- timestamp: Date.now() + handleErrorResult.retryDelayInMs,
4510
- delay: handleErrorResult.retryDelayInMs
4511
- },
4512
- error: handleErrorResult.error
4513
- };
4514
- }
4515
- if (handleErrorResult.retry && typeof handleErrorResult.retry === "object") {
4516
- const delay2 = calculateNextRetryDelay(handleErrorResult.retry, execution.attempt.number);
4517
- return typeof delay2 === "undefined" ? {
4518
- status: "noop",
4519
- error: handleErrorResult.error
4520
- } : {
4521
- status: "retry",
4522
- retry: {
4523
- timestamp: Date.now() + delay2,
4524
- delay: delay2
4525
- },
4526
- error: handleErrorResult.error
4527
- };
4528
- }
4529
- return {
4530
- status: "noop",
4531
- error: handleErrorResult.error
4532
- };
4533
- }, {
4534
- attributes: {
4535
- [SemanticInternalAttributes.STYLE_ICON]: "exclamation-circle"
4536
- }
4537
- });
4538
- }, "#handleError");
4539
- __name(_TaskExecutor, "TaskExecutor");
4540
- var TaskExecutor = _TaskExecutor;
4541
-
4542
- // package.json
4543
- var dependencies = {
4544
- "@google-cloud/precise-date": "^4.0.0",
4545
- "@opentelemetry/api": "^1.8.0",
4546
- "@opentelemetry/api-logs": "^0.48.0",
4547
- "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
4548
- "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
4549
- "@opentelemetry/instrumentation": "^0.49.1",
4550
- "@opentelemetry/resources": "^1.22.0",
4551
- "@opentelemetry/sdk-logs": "^0.49.1",
4552
- "@opentelemetry/sdk-node": "^0.49.1",
4553
- "@opentelemetry/sdk-trace-base": "^1.22.0",
4554
- "@opentelemetry/sdk-trace-node": "^1.22.0",
4555
- "@opentelemetry/semantic-conventions": "^1.22.0",
4556
- "humanize-duration": "^3.27.3",
4557
- "socket.io": "^4.7.4",
4558
- "socket.io-client": "^4.7.4",
4559
- superjson: "^2.2.1",
4560
- ulidx: "^2.2.1",
4561
- zod: "3.22.3",
4562
- "zod-error": "1.5.0"
4563
- };
4564
-
4565
- // src/v3/utils/detectDependencyVersion.ts
4566
- function detectDependencyVersion(dependency) {
4567
- return dependencies[dependency];
4568
- }
4569
- __name(detectDependencyVersion, "detectDependencyVersion");
4570
-
4571
- // src/v3/index.ts
4572
- function parseTriggerTaskRequestBody(body) {
4573
- return TriggerTaskRequestBody.safeParse(body);
4574
- }
4575
- __name(parseTriggerTaskRequestBody, "parseTriggerTaskRequestBody");
4576
- function parseBatchTriggerTaskRequestBody(body) {
4577
- return BatchTriggerTaskRequestBody.safeParse(body);
4578
- }
4579
- __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
3493
+ __name(safeJsonParse2, "safeJsonParse");
4580
3494
 
4581
- export { ApiClient, ApiClientManager, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConsoleInterceptor, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateUploadPayloadUrlResponseBody, DeploymentErrorData, DevRuntimeManager, PreciseWallClock as DurableClock, EnvironmentType, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, LogLevel, Machine, MachineCpu, MachineMemory, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OtelTaskLogger, OtherSpanEvent, PRIMARY_VARIANT, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdRuntimeManager, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitOptions, RetryOptions, SemanticInternalAttributes, SharedQueueToClientMessages, SimpleStructuredLogger, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskContextSpanProcessor, TaskEventStyle, TaskExecutor, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TracingSDK, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, WaitReason, WhoAmIResponseSchema, ZodIpcConnection, ZodMessageHandler, ZodMessageSchema, ZodMessageSender, ZodNamespace, ZodSchemaParsedError, ZodSocketConnection, ZodSocketMessageHandler, ZodSocketMessageSender, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, getEnvVar, groupTaskMetadataIssuesByTask, iconStringForSeverity, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logLevels, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseBatchTriggerTaskRequestBody, parseError, parsePacket, parseTriggerTaskRequestBody, prettyPrintPacket, primitiveValueOrflattenedAttributes, recordSpanException, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskContextManager, unflattenAttributes, workerToChildMessages };
3495
+ export { APIConnectionError, APIError, ApiClient, AttemptStatus, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, DeletedScheduleObject, DeploymentErrorData, EnvironmentType, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListScheduleOptions, ListSchedulesResult, Machine, MachineCpu, MachineMemory, NULL_SENTINEL, NotFoundError, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RetrieveRunResponse, RetryOptions, RunStatus, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SharedQueueToClientMessages, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskEventStyle, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createJsonErrorObject, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, groupTaskMetadataIssuesByTask, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseError, parsePacket, prettyPrintPacket, primitiveValueOrflattenedAttributes, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContext, unflattenAttributes, workerToChildMessages };
4582
3496
  //# sourceMappingURL=out.js.map
4583
3497
  //# sourceMappingURL=index.mjs.map