@trigger.dev/core 3.0.0-beta.2 → 3.0.0-beta.20

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-A-D3UC6S.d.mts +6646 -0
  2. package/dist/catalog-TAZd4-TP.d.ts +6646 -0
  3. package/dist/manager-M9GLDnhJ.d.mts +1158 -0
  4. package/dist/manager-M9GLDnhJ.d.ts +1158 -0
  5. package/dist/messages-AriaDDm0.d.mts +8696 -0
  6. package/dist/messages-AriaDDm0.d.ts +8696 -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 +808 -16920
  14. package/dist/v3/index.d.ts +808 -16920
  15. package/dist/v3/index.js +1337 -2436
  16. package/dist/v3/index.js.map +1 -1
  17. package/dist/v3/index.mjs +1195 -2294
  18. package/dist/v3/index.mjs.map +1 -1
  19. package/dist/v3/otel/index.js +69 -42
  20. package/dist/v3/otel/index.js.map +1 -1
  21. package/dist/v3/otel/index.mjs +69 -42
  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 +205 -0
  26. package/dist/v3/prod/index.js.map +1 -0
  27. package/dist/v3/prod/index.mjs +203 -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 +2664 -0
  38. package/dist/v3/workers/index.js.map +1 -0
  39. package/dist/v3/workers/index.mjs +2648 -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 +70 -5
package/dist/v3/index.js CHANGED
@@ -1,29 +1,16 @@
1
1
  'use strict';
2
2
 
3
- var zod = require('zod');
4
3
  var api = require('@opentelemetry/api');
4
+ var zodValidationError = require('zod-validation-error');
5
+ var zod = require('zod');
5
6
  var async_hooks = require('async_hooks');
6
- var socket_ioClient = require('socket.io-client');
7
- var crypto = require('crypto');
8
- var nodePath = require('path');
9
- var apiLogs = require('@opentelemetry/api-logs');
10
7
  var preciseDate = require('@google-cloud/precise-date');
8
+ var apiLogs = require('@opentelemetry/api-logs');
11
9
  var humanizeDuration = require('humanize-duration');
12
- var promises = require('timers/promises');
13
- var util = require('util');
14
- var exporterLogsOtlpHttp = require('@opentelemetry/exporter-logs-otlp-http');
15
- var exporterTraceOtlpHttp = require('@opentelemetry/exporter-trace-otlp-http');
16
- var instrumentation = require('@opentelemetry/instrumentation');
17
- var resources = require('@opentelemetry/resources');
18
- var sdkLogs = require('@opentelemetry/sdk-logs');
19
- var sdkTraceNode = require('@opentelemetry/sdk-trace-node');
20
- var semanticConventions = require('@opentelemetry/semantic-conventions');
21
10
 
22
11
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
23
12
 
24
- var nodePath__default = /*#__PURE__*/_interopDefault(nodePath);
25
13
  var humanizeDuration__default = /*#__PURE__*/_interopDefault(humanizeDuration);
26
- var util__default = /*#__PURE__*/_interopDefault(util);
27
14
 
28
15
  var __defProp = Object.defineProperty;
29
16
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -36,32 +23,394 @@ var __accessCheck = (obj, member, msg) => {
36
23
  if (!member.has(obj))
37
24
  throw TypeError("Cannot " + msg);
38
25
  };
39
- var __privateGet = (obj, member, getter) => {
40
- __accessCheck(obj, member, "read from private field");
41
- return getter ? getter.call(obj) : member.get(obj);
42
- };
43
26
  var __privateAdd = (obj, member, value) => {
44
27
  if (member.has(obj))
45
28
  throw TypeError("Cannot add the same private member more than once");
46
29
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
47
30
  };
48
- var __privateSet = (obj, member, value, setter) => {
49
- __accessCheck(obj, member, "write to private field");
50
- setter ? setter.call(obj, value) : member.set(obj, value);
51
- return value;
52
- };
53
- var __privateWrapper = (obj, member, setter, getter) => ({
54
- set _(value) {
55
- __privateSet(obj, member, value, setter);
56
- },
57
- get _() {
58
- return __privateGet(obj, member, getter);
59
- }
60
- });
61
31
  var __privateMethod = (obj, member, method) => {
62
32
  __accessCheck(obj, member, "access private method");
63
33
  return method;
64
34
  };
35
+
36
+ // src/v3/apiErrors.ts
37
+ var _APIError = class _APIError extends Error {
38
+ constructor(status, error, message, headers) {
39
+ super(`${_APIError.makeMessage(status, error, message)}`);
40
+ this.status = status;
41
+ this.headers = headers;
42
+ const data = error;
43
+ this.error = data;
44
+ this.code = data?.["code"];
45
+ this.param = data?.["param"];
46
+ this.type = data?.["type"];
47
+ }
48
+ static makeMessage(status, error, message) {
49
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
50
+ if (status && msg) {
51
+ return `${status} ${msg}`;
52
+ }
53
+ if (status) {
54
+ return `${status} status code (no body)`;
55
+ }
56
+ if (msg) {
57
+ return msg;
58
+ }
59
+ return "(no status code or body)";
60
+ }
61
+ static generate(status, errorResponse, message, headers) {
62
+ if (!status) {
63
+ return new APIConnectionError({
64
+ cause: castToError(errorResponse)
65
+ });
66
+ }
67
+ const error = errorResponse?.["error"];
68
+ if (status === 400) {
69
+ return new BadRequestError(status, error, message, headers);
70
+ }
71
+ if (status === 401) {
72
+ return new AuthenticationError(status, error, message, headers);
73
+ }
74
+ if (status === 403) {
75
+ return new PermissionDeniedError(status, error, message, headers);
76
+ }
77
+ if (status === 404) {
78
+ return new NotFoundError(status, error, message, headers);
79
+ }
80
+ if (status === 409) {
81
+ return new ConflictError(status, error, message, headers);
82
+ }
83
+ if (status === 422) {
84
+ return new UnprocessableEntityError(status, error, message, headers);
85
+ }
86
+ if (status === 429) {
87
+ return new RateLimitError(status, error, message, headers);
88
+ }
89
+ if (status >= 500) {
90
+ return new InternalServerError(status, error, message, headers);
91
+ }
92
+ return new _APIError(status, error, message, headers);
93
+ }
94
+ };
95
+ __name(_APIError, "APIError");
96
+ var APIError = _APIError;
97
+ var _APIConnectionError = class _APIConnectionError extends APIError {
98
+ constructor({ message, cause }) {
99
+ super(void 0, void 0, message || "Connection error.", void 0);
100
+ __publicField(this, "status");
101
+ if (cause)
102
+ this.cause = cause;
103
+ }
104
+ };
105
+ __name(_APIConnectionError, "APIConnectionError");
106
+ var APIConnectionError = _APIConnectionError;
107
+ var _BadRequestError = class _BadRequestError extends APIError {
108
+ constructor() {
109
+ super(...arguments);
110
+ __publicField(this, "status", 400);
111
+ }
112
+ };
113
+ __name(_BadRequestError, "BadRequestError");
114
+ var BadRequestError = _BadRequestError;
115
+ var _AuthenticationError = class _AuthenticationError extends APIError {
116
+ constructor() {
117
+ super(...arguments);
118
+ __publicField(this, "status", 401);
119
+ }
120
+ };
121
+ __name(_AuthenticationError, "AuthenticationError");
122
+ var AuthenticationError = _AuthenticationError;
123
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
124
+ constructor() {
125
+ super(...arguments);
126
+ __publicField(this, "status", 403);
127
+ }
128
+ };
129
+ __name(_PermissionDeniedError, "PermissionDeniedError");
130
+ var PermissionDeniedError = _PermissionDeniedError;
131
+ var _NotFoundError = class _NotFoundError extends APIError {
132
+ constructor() {
133
+ super(...arguments);
134
+ __publicField(this, "status", 404);
135
+ }
136
+ };
137
+ __name(_NotFoundError, "NotFoundError");
138
+ var NotFoundError = _NotFoundError;
139
+ var _ConflictError = class _ConflictError extends APIError {
140
+ constructor() {
141
+ super(...arguments);
142
+ __publicField(this, "status", 409);
143
+ }
144
+ };
145
+ __name(_ConflictError, "ConflictError");
146
+ var ConflictError = _ConflictError;
147
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
148
+ constructor() {
149
+ super(...arguments);
150
+ __publicField(this, "status", 422);
151
+ }
152
+ };
153
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
154
+ var UnprocessableEntityError = _UnprocessableEntityError;
155
+ var _RateLimitError = class _RateLimitError extends APIError {
156
+ constructor() {
157
+ super(...arguments);
158
+ __publicField(this, "status", 429);
159
+ }
160
+ };
161
+ __name(_RateLimitError, "RateLimitError");
162
+ var RateLimitError = _RateLimitError;
163
+ var _InternalServerError = class _InternalServerError extends APIError {
164
+ };
165
+ __name(_InternalServerError, "InternalServerError");
166
+ var InternalServerError = _InternalServerError;
167
+ function castToError(err) {
168
+ if (err instanceof Error)
169
+ return err;
170
+ return new Error(err);
171
+ }
172
+ __name(castToError, "castToError");
173
+
174
+ // src/retry.ts
175
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
176
+ if (!resets)
177
+ return;
178
+ switch (format) {
179
+ case "iso_8601_duration_openai_variant": {
180
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
181
+ }
182
+ case "iso_8601": {
183
+ return calculateISO8601ResetAt(resets, now);
184
+ }
185
+ case "unix_timestamp": {
186
+ return calculateUnixTimestampResetAt(resets, now);
187
+ }
188
+ case "unix_timestamp_in_ms": {
189
+ return calculateUnixTimestampInMsResetAt(resets, now);
190
+ }
191
+ }
192
+ }
193
+ __name(calculateResetAt, "calculateResetAt");
194
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
195
+ if (!resets)
196
+ return void 0;
197
+ const resetAt = parseInt(resets, 10);
198
+ if (isNaN(resetAt))
199
+ return void 0;
200
+ return new Date(resetAt * 1e3);
201
+ }
202
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
203
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
204
+ if (!resets)
205
+ return void 0;
206
+ const resetAt = parseInt(resets, 10);
207
+ if (isNaN(resetAt))
208
+ return void 0;
209
+ return new Date(resetAt);
210
+ }
211
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
212
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
213
+ if (!resets)
214
+ return void 0;
215
+ const resetAt = new Date(resets);
216
+ if (isNaN(resetAt.getTime()))
217
+ return void 0;
218
+ return resetAt;
219
+ }
220
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
221
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
222
+ if (!resets)
223
+ return void 0;
224
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
225
+ const match = resets.match(pattern);
226
+ if (!match)
227
+ return void 0;
228
+ const days = parseInt(match[1], 10) || 0;
229
+ const hours = parseInt(match[2], 10) || 0;
230
+ const minutes = parseInt(match[3], 10) || 0;
231
+ const seconds = parseFloat(match[4]) || 0;
232
+ const milliseconds = parseInt(match[5], 10) || 0;
233
+ const resetAt = new Date(now);
234
+ resetAt.setDate(resetAt.getDate() + days);
235
+ resetAt.setHours(resetAt.getHours() + hours);
236
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
237
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
238
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
239
+ return resetAt;
240
+ }
241
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
242
+
243
+ // src/v3/utils/retries.ts
244
+ var defaultRetryOptions = {
245
+ maxAttempts: 3,
246
+ factor: 2,
247
+ minTimeoutInMs: 1e3,
248
+ maxTimeoutInMs: 6e4,
249
+ randomize: true
250
+ };
251
+ var defaultFetchRetryOptions = {
252
+ byStatus: {
253
+ "429,408,409,5xx": {
254
+ strategy: "backoff",
255
+ ...defaultRetryOptions
256
+ }
257
+ },
258
+ connectionError: defaultRetryOptions,
259
+ timeout: defaultRetryOptions
260
+ };
261
+ function calculateNextRetryDelay(options, attempt) {
262
+ const opts = {
263
+ ...defaultRetryOptions,
264
+ ...options
265
+ };
266
+ if (attempt >= opts.maxAttempts) {
267
+ return;
268
+ }
269
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
270
+ const random = randomize ? Math.random() + 1 : 1;
271
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
272
+ return Math.round(timeout);
273
+ }
274
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
275
+ function calculateResetAt2(resets, format, now = Date.now()) {
276
+ const resetAt = calculateResetAt(resets, format, new Date(now));
277
+ return resetAt?.getTime();
278
+ }
279
+ __name(calculateResetAt2, "calculateResetAt");
280
+
281
+ // src/v3/zodfetch.ts
282
+ var defaultRetryOptions2 = {
283
+ maxAttempts: 3,
284
+ factor: 2,
285
+ minTimeoutInMs: 1e3,
286
+ maxTimeoutInMs: 6e4,
287
+ randomize: false
288
+ };
289
+ async function zodfetch(schema, url, requestInit, options) {
290
+ return await _doZodFetch(schema, url, requestInit, options);
291
+ }
292
+ __name(zodfetch, "zodfetch");
293
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
294
+ try {
295
+ const response = await fetch(url, requestInitWithCache(requestInit));
296
+ const responseHeaders = createResponseHeaders(response.headers);
297
+ if (!response.ok) {
298
+ const retryResult = shouldRetry(response, attempt, options?.retry);
299
+ if (retryResult.retry) {
300
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
301
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
302
+ } else {
303
+ const errText = await response.text().catch((e) => castToError2(e).message);
304
+ const errJSON = safeJsonParse(errText);
305
+ const errMessage = errJSON ? void 0 : errText;
306
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
307
+ }
308
+ }
309
+ const jsonBody = await response.json();
310
+ const parsedResult = schema.safeParse(jsonBody);
311
+ if (parsedResult.success) {
312
+ return parsedResult.data;
313
+ }
314
+ throw zodValidationError.fromZodError(parsedResult.error);
315
+ } catch (error) {
316
+ if (error instanceof APIError) {
317
+ throw error;
318
+ }
319
+ if (options?.retry) {
320
+ const retry = {
321
+ ...defaultRetryOptions2,
322
+ ...options.retry
323
+ };
324
+ const delay = calculateNextRetryDelay(retry, attempt);
325
+ if (delay) {
326
+ await new Promise((resolve) => setTimeout(resolve, delay));
327
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
328
+ }
329
+ }
330
+ throw new APIConnectionError({
331
+ cause: castToError2(error)
332
+ });
333
+ }
334
+ }
335
+ __name(_doZodFetch, "_doZodFetch");
336
+ function castToError2(err) {
337
+ if (err instanceof Error)
338
+ return err;
339
+ return new Error(err);
340
+ }
341
+ __name(castToError2, "castToError");
342
+ function shouldRetry(response, attempt, retryOptions) {
343
+ function shouldRetryForOptions() {
344
+ const retry = {
345
+ ...defaultRetryOptions2,
346
+ ...retryOptions
347
+ };
348
+ const delay = calculateNextRetryDelay(retry, attempt);
349
+ if (delay) {
350
+ return {
351
+ retry: true,
352
+ delay
353
+ };
354
+ } else {
355
+ return {
356
+ retry: false
357
+ };
358
+ }
359
+ }
360
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
361
+ const shouldRetryHeader = response.headers.get("x-should-retry");
362
+ if (shouldRetryHeader === "true")
363
+ return shouldRetryForOptions();
364
+ if (shouldRetryHeader === "false")
365
+ return {
366
+ retry: false
367
+ };
368
+ if (response.status === 408)
369
+ return shouldRetryForOptions();
370
+ if (response.status === 409)
371
+ return shouldRetryForOptions();
372
+ if (response.status === 429)
373
+ return shouldRetryForOptions();
374
+ if (response.status >= 500)
375
+ return shouldRetryForOptions();
376
+ return {
377
+ retry: false
378
+ };
379
+ }
380
+ __name(shouldRetry, "shouldRetry");
381
+ function safeJsonParse(text) {
382
+ try {
383
+ return JSON.parse(text);
384
+ } catch (e) {
385
+ return void 0;
386
+ }
387
+ }
388
+ __name(safeJsonParse, "safeJsonParse");
389
+ function createResponseHeaders(headers) {
390
+ return new Proxy(Object.fromEntries(
391
+ // @ts-ignore
392
+ headers.entries()
393
+ ), {
394
+ get(target, name) {
395
+ const key = name.toString();
396
+ return target[key.toLowerCase()] || target[key];
397
+ }
398
+ });
399
+ }
400
+ __name(createResponseHeaders, "createResponseHeaders");
401
+ function requestInitWithCache(requestInit) {
402
+ try {
403
+ const withCache = {
404
+ ...requestInit,
405
+ cache: "no-cache"
406
+ };
407
+ const _ = new Request("http://localhost", withCache);
408
+ return withCache;
409
+ } catch (error) {
410
+ return requestInit ?? {};
411
+ }
412
+ }
413
+ __name(requestInitWithCache, "requestInitWithCache");
65
414
  var CreateAuthorizationCodeResponseSchema = zod.z.object({
66
415
  url: zod.z.string().url(),
67
416
  authorizationCode: zod.z.string()
@@ -91,6 +440,7 @@ var TaskRunStringError = zod.z.object({
91
440
  });
92
441
  var TaskRunErrorCodes = {
93
442
  COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
443
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
94
444
  CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
95
445
  TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
96
446
  TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
@@ -98,12 +448,14 @@ var TaskRunErrorCodes = {
98
448
  TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
99
449
  TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
100
450
  TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
101
- HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR"
451
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
452
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
102
453
  };
103
454
  var TaskRunInternalError = zod.z.object({
104
455
  type: zod.z.literal("INTERNAL_ERROR"),
105
456
  code: zod.z.enum([
106
457
  "COULD_NOT_FIND_EXECUTOR",
458
+ "COULD_NOT_FIND_TASK",
107
459
  "CONFIGURED_INCORRECTLY",
108
460
  "TASK_ALREADY_RUNNING",
109
461
  "TASK_EXECUTION_FAILED",
@@ -111,7 +463,8 @@ var TaskRunInternalError = zod.z.object({
111
463
  "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
112
464
  "TASK_RUN_CANCELLED",
113
465
  "TASK_OUTPUT_ERROR",
114
- "HANDLE_ERROR_ERROR"
466
+ "HANDLE_ERROR_ERROR",
467
+ "GRACEFUL_EXIT_TIMEOUT"
115
468
  ]),
116
469
  message: zod.z.string().optional()
117
470
  });
@@ -128,7 +481,8 @@ var TaskRun = zod.z.object({
128
481
  context: zod.z.any(),
129
482
  tags: zod.z.array(zod.z.string()),
130
483
  isTest: zod.z.boolean().default(false),
131
- createdAt: zod.z.coerce.date()
484
+ createdAt: zod.z.coerce.date(),
485
+ idempotencyKey: zod.z.string().optional()
132
486
  });
133
487
  var TaskRunExecutionTask = zod.z.object({
134
488
  id: zod.z.string(),
@@ -442,21 +796,23 @@ var QueueOptions = zod.z.object({
442
796
  /** An optional property that specifies the maximum number of concurrent run executions.
443
797
  *
444
798
  * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
445
- concurrencyLimit: zod.z.number().int().min(1).max(1e3).optional(),
799
+ concurrencyLimit: zod.z.number().int().min(0).max(1e3).optional(),
446
800
  /** @deprecated This feature is coming soon */
447
801
  rateLimit: RateLimitOptions.optional()
448
802
  });
449
803
  var TaskMetadata = zod.z.object({
450
804
  id: zod.z.string(),
451
- exportName: zod.z.string(),
452
805
  packageVersion: zod.z.string(),
453
806
  queue: QueueOptions.optional(),
454
807
  retry: RetryOptions.optional(),
455
- machine: Machine.partial().optional()
808
+ machine: Machine.partial().optional(),
809
+ triggerSource: zod.z.string().optional()
456
810
  });
457
- var TaskMetadataWithFilePath = TaskMetadata.extend({
458
- filePath: zod.z.string()
811
+ var TaskFileMetadata = zod.z.object({
812
+ filePath: zod.z.string(),
813
+ exportName: zod.z.string()
459
814
  });
815
+ var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
460
816
  var UncaughtExceptionMessage = zod.z.object({
461
817
  version: zod.z.literal("v1").default("v1"),
462
818
  error: zod.z.object({
@@ -469,6 +825,13 @@ var UncaughtExceptionMessage = zod.z.object({
469
825
  "unhandledRejection"
470
826
  ])
471
827
  });
828
+ var TaskMetadataFailedToParseData = zod.z.object({
829
+ version: zod.z.literal("v1").default("v1"),
830
+ tasks: zod.z.unknown(),
831
+ zodIssues: zod.z.custom((v) => {
832
+ return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
833
+ })
834
+ });
472
835
  var childToWorkerMessages = {
473
836
  TASK_RUN_COMPLETED: zod.z.object({
474
837
  version: zod.z.literal("v1").default("v1"),
@@ -479,6 +842,7 @@ var childToWorkerMessages = {
479
842
  version: zod.z.literal("v1").default("v1"),
480
843
  tasks: TaskMetadataWithFilePath.array()
481
844
  }),
845
+ TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
482
846
  TASK_HEARTBEAT: zod.z.object({
483
847
  version: zod.z.literal("v1").default("v1"),
484
848
  id: zod.z.string()
@@ -513,6 +877,9 @@ var ProdChildToWorkerMessages = {
513
877
  tasks: TaskMetadataWithFilePath.array()
514
878
  })
515
879
  },
880
+ TASKS_FAILED_TO_PARSE: {
881
+ message: TaskMetadataFailedToParseData
882
+ },
516
883
  TASK_HEARTBEAT: {
517
884
  message: zod.z.object({
518
885
  version: zod.z.literal("v1").default("v1"),
@@ -597,7 +964,8 @@ var TaskResource = zod.z.object({
597
964
  exportName: zod.z.string(),
598
965
  queue: QueueOptions.optional(),
599
966
  retry: RetryOptions.optional(),
600
- machine: Machine.partial().optional()
967
+ machine: Machine.partial().optional(),
968
+ triggerSource: zod.z.string().optional()
601
969
  });
602
970
  var BackgroundWorkerMetadata = zod.z.object({
603
971
  packageVersion: zod.z.string(),
@@ -653,7 +1021,9 @@ var TriggerTaskRequestBody = zod.z.object({
653
1021
  lockToVersion: zod.z.string().optional(),
654
1022
  queue: QueueOptions.optional(),
655
1023
  concurrencyKey: zod.z.string().optional(),
656
- test: zod.z.boolean().optional()
1024
+ idempotencyKey: zod.z.string().optional(),
1025
+ test: zod.z.boolean().optional(),
1026
+ payloadType: zod.z.string().optional()
657
1027
  }).optional()
658
1028
  });
659
1029
  var TriggerTaskResponse = zod.z.object({
@@ -708,6 +1078,11 @@ var InitializeDeploymentRequestBody = zod.z.object({
708
1078
  contentHash: zod.z.string(),
709
1079
  userId: zod.z.string().optional()
710
1080
  });
1081
+ var DeploymentErrorData = zod.z.object({
1082
+ name: zod.z.string(),
1083
+ message: zod.z.string(),
1084
+ stack: zod.z.string().optional()
1085
+ });
711
1086
  var GetDeploymentResponseBody = zod.z.object({
712
1087
  id: zod.z.string(),
713
1088
  status: zod.z.enum([
@@ -723,11 +1098,7 @@ var GetDeploymentResponseBody = zod.z.object({
723
1098
  shortCode: zod.z.string(),
724
1099
  version: zod.z.string(),
725
1100
  imageReference: zod.z.string().optional(),
726
- errorData: zod.z.object({
727
- name: zod.z.string(),
728
- message: zod.z.string(),
729
- stack: zod.z.string().optional()
730
- }).optional().nullable(),
1101
+ errorData: DeploymentErrorData.optional().nullable(),
731
1102
  worker: zod.z.object({
732
1103
  id: zod.z.string(),
733
1104
  version: zod.z.string(),
@@ -742,6 +1113,93 @@ var GetDeploymentResponseBody = zod.z.object({
742
1113
  var CreateUploadPayloadUrlResponseBody = zod.z.object({
743
1114
  presignedUrl: zod.z.string()
744
1115
  });
1116
+ var ReplayRunResponse = zod.z.object({
1117
+ id: zod.z.string()
1118
+ });
1119
+ var CanceledRunResponse = zod.z.object({
1120
+ message: zod.z.string()
1121
+ });
1122
+ var ScheduledTaskPayload = zod.z.object({
1123
+ /** The schedule id associated with this run (you can have many schedules for the same task).
1124
+ You can use this to remove the schedule, update it, etc */
1125
+ scheduleId: zod.z.string(),
1126
+ /** When the task was scheduled to run.
1127
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
1128
+ timestamp: zod.z.date(),
1129
+ /** When the task was last run (it has been).
1130
+ This can be undefined if it's never been run */
1131
+ lastTimestamp: zod.z.date().optional(),
1132
+ /** You can optionally provide an external id when creating the schedule.
1133
+ Usually you would use a userId or some other unique identifier.
1134
+ This defaults to undefined if you didn't provide one. */
1135
+ externalId: zod.z.string().optional(),
1136
+ /** The next 5 dates this task is scheduled to run */
1137
+ upcoming: zod.z.array(zod.z.date())
1138
+ });
1139
+ var CreateScheduleOptions = zod.z.object({
1140
+ /** The id of the task you want to attach to. */
1141
+ task: zod.z.string(),
1142
+ /** The schedule in CRON format.
1143
+ *
1144
+ * ```txt
1145
+ * * * * * *
1146
+ ┬ ┬ ┬ ┬ ┬
1147
+ │ │ │ │ |
1148
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
1149
+ │ │ │ └───── month (1 - 12)
1150
+ │ │ └────────── day of month (1 - 31, L)
1151
+ │ └─────────────── hour (0 - 23)
1152
+ └──────────────────── minute (0 - 59)
1153
+ * ```
1154
+
1155
+ "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.
1156
+
1157
+ */
1158
+ cron: zod.z.string(),
1159
+ /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1160
+ *
1161
+ * This is useful if you don't want to create duplicate schedules for a user. */
1162
+ deduplicationKey: zod.z.string().optional(),
1163
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
1164
+ *
1165
+ * This allows you to have per-user CRON tasks.
1166
+ */
1167
+ externalId: zod.z.string().optional()
1168
+ });
1169
+ var UpdateScheduleOptions = CreateScheduleOptions;
1170
+ var ScheduleObject = zod.z.object({
1171
+ id: zod.z.string(),
1172
+ task: zod.z.string(),
1173
+ active: zod.z.boolean(),
1174
+ deduplicationKey: zod.z.string().nullish(),
1175
+ externalId: zod.z.string().nullish(),
1176
+ generator: zod.z.object({
1177
+ type: zod.z.literal("CRON"),
1178
+ expression: zod.z.string(),
1179
+ description: zod.z.string()
1180
+ }),
1181
+ nextRun: zod.z.coerce.date().nullish(),
1182
+ environments: zod.z.array(zod.z.object({
1183
+ id: zod.z.string(),
1184
+ type: zod.z.string(),
1185
+ userName: zod.z.string().nullish()
1186
+ }))
1187
+ });
1188
+ var DeletedScheduleObject = zod.z.object({
1189
+ id: zod.z.string()
1190
+ });
1191
+ var ListSchedulesResult = zod.z.object({
1192
+ data: zod.z.array(ScheduleObject),
1193
+ pagination: zod.z.object({
1194
+ currentPage: zod.z.number(),
1195
+ totalPages: zod.z.number(),
1196
+ count: zod.z.number()
1197
+ })
1198
+ });
1199
+ var ListScheduleOptions = zod.z.object({
1200
+ page: zod.z.number().optional(),
1201
+ perPage: zod.z.number().optional()
1202
+ });
745
1203
  var PostStartCauses = zod.z.enum([
746
1204
  "index",
747
1205
  "create",
@@ -772,7 +1230,9 @@ var Config = zod.z.object({
772
1230
  dependenciesToBundle: zod.z.array(zod.z.union([
773
1231
  zod.z.string(),
774
1232
  RegexSchema
775
- ])).optional()
1233
+ ])).optional(),
1234
+ logLevel: zod.z.string().optional(),
1235
+ enableConsoleLogging: zod.z.boolean().optional()
776
1236
  });
777
1237
  var WaitReason = zod.z.enum([
778
1238
  "WAIT_FOR_DURATION",
@@ -794,29 +1254,51 @@ var ProviderToPlatformMessages = {
794
1254
  callback: zod.z.object({
795
1255
  status: zod.z.literal("ok")
796
1256
  })
797
- }
798
- };
799
- var PlatformToProviderMessages = {
800
- HEALTH: {
801
- message: zod.z.object({
802
- version: zod.z.literal("v1").default("v1")
803
- }),
804
- callback: zod.z.object({
805
- status: zod.z.literal("ok")
806
- })
807
1257
  },
808
- INDEX: {
1258
+ WORKER_CRASHED: {
809
1259
  message: zod.z.object({
810
1260
  version: zod.z.literal("v1").default("v1"),
811
- imageTag: zod.z.string(),
812
- shortCode: zod.z.string(),
1261
+ runId: zod.z.string(),
1262
+ reason: zod.z.string().optional(),
1263
+ exitCode: zod.z.number().optional(),
1264
+ message: zod.z.string().optional(),
1265
+ logs: zod.z.string().optional()
1266
+ })
1267
+ },
1268
+ INDEXING_FAILED: {
1269
+ message: zod.z.object({
1270
+ version: zod.z.literal("v1").default("v1"),
1271
+ deploymentId: zod.z.string(),
1272
+ error: zod.z.object({
1273
+ name: zod.z.string(),
1274
+ message: zod.z.string(),
1275
+ stack: zod.z.string().optional()
1276
+ })
1277
+ })
1278
+ }
1279
+ };
1280
+ var PlatformToProviderMessages = {
1281
+ HEALTH: {
1282
+ message: zod.z.object({
1283
+ version: zod.z.literal("v1").default("v1")
1284
+ }),
1285
+ callback: zod.z.object({
1286
+ status: zod.z.literal("ok")
1287
+ })
1288
+ },
1289
+ INDEX: {
1290
+ message: zod.z.object({
1291
+ version: zod.z.literal("v1").default("v1"),
1292
+ imageTag: zod.z.string(),
1293
+ shortCode: zod.z.string(),
813
1294
  apiKey: zod.z.string(),
814
1295
  apiUrl: zod.z.string(),
815
1296
  // identifiers
816
1297
  envId: zod.z.string(),
817
1298
  envType: EnvironmentType,
818
1299
  orgId: zod.z.string(),
819
- projectId: zod.z.string()
1300
+ projectId: zod.z.string(),
1301
+ deploymentId: zod.z.string()
820
1302
  }),
821
1303
  callback: zod.z.discriminatedUnion("success", [
822
1304
  zod.z.object({
@@ -1406,169 +1888,32 @@ var SpanMessagingEvent = zod.z.object({
1406
1888
  destination: zod.z.string().optional()
1407
1889
  });
1408
1890
 
1409
- // src/zodfetch.ts
1410
- async function zodfetch(schema, url, requestInit) {
1411
- try {
1412
- const response = await fetch(url, requestInit);
1413
- if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
1414
- return {
1415
- ok: false,
1416
- error: `404: ${response.statusText}`
1417
- };
1418
- }
1419
- if (response.status >= 400 && response.status < 500) {
1420
- const body = await response.json();
1421
- if (!body.error) {
1422
- return {
1423
- ok: false,
1424
- error: "Something went wrong"
1425
- };
1426
- }
1427
- return {
1428
- ok: false,
1429
- error: body.error
1430
- };
1431
- }
1432
- if (response.status !== 200) {
1433
- return {
1434
- ok: false,
1435
- error: `Failed to fetch ${url}, got status code ${response.status}`
1436
- };
1437
- }
1438
- const jsonBody = await response.json();
1439
- const parsedResult = schema.safeParse(jsonBody);
1440
- if (parsedResult.success) {
1441
- return {
1442
- ok: true,
1443
- data: parsedResult.data
1444
- };
1445
- }
1446
- if ("error" in jsonBody) {
1447
- return {
1448
- ok: false,
1449
- error: typeof jsonBody.error === "string" ? jsonBody.error : JSON.stringify(jsonBody.error)
1450
- };
1451
- }
1452
- return {
1453
- ok: false,
1454
- error: parsedResult.error.message
1455
- };
1456
- } catch (error) {
1457
- return {
1458
- ok: false,
1459
- error: error instanceof Error ? error.message : JSON.stringify(error)
1460
- };
1461
- }
1462
- }
1463
- __name(zodfetch, "zodfetch");
1891
+ // src/v3/utils/platform.ts
1892
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
1464
1893
 
1465
- // src/v3/utils/flattenAttributes.ts
1466
- function flattenAttributes(obj, prefix) {
1467
- const result = {};
1468
- if (!obj) {
1469
- return result;
1470
- }
1471
- if (typeof obj === "string") {
1472
- result[prefix || ""] = obj;
1473
- return result;
1474
- }
1475
- if (typeof obj === "number") {
1476
- result[prefix || ""] = obj;
1477
- return result;
1478
- }
1479
- if (typeof obj === "boolean") {
1480
- result[prefix || ""] = obj;
1481
- return result;
1482
- }
1483
- for (const [key, value] of Object.entries(obj)) {
1484
- const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
1485
- if (Array.isArray(value)) {
1486
- for (let i = 0; i < value.length; i++) {
1487
- if (typeof value[i] === "object" && value[i] !== null) {
1488
- Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
1489
- } else {
1490
- result[`${newPrefix}.[${i}]`] = value[i];
1491
- }
1492
- }
1493
- } else if (isRecord(value)) {
1494
- Object.assign(result, flattenAttributes(value, newPrefix));
1495
- } else {
1496
- if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
1497
- result[newPrefix] = value;
1498
- }
1499
- }
1500
- }
1501
- return result;
1502
- }
1503
- __name(flattenAttributes, "flattenAttributes");
1504
- function isRecord(value) {
1505
- return value !== null && typeof value === "object" && !Array.isArray(value);
1506
- }
1507
- __name(isRecord, "isRecord");
1508
- function unflattenAttributes(obj) {
1509
- if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
1510
- return obj;
1511
- }
1512
- const result = {};
1513
- for (const [key, value] of Object.entries(obj)) {
1514
- const parts = key.split(".").reduce((acc, part) => {
1515
- if (detectIsArrayIndex(part)) {
1516
- acc.push(part);
1517
- } else {
1518
- acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
1519
- }
1520
- return acc;
1521
- }, []);
1522
- let current = result;
1523
- for (let i = 0; i < parts.length - 1; i++) {
1524
- const part = parts[i];
1525
- const isArray = detectIsArrayIndex(part);
1526
- const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
1527
- const nextIsArray = detectIsArrayIndex(parts[i + 1]);
1528
- if (!current[cleanPart]) {
1529
- current[cleanPart] = nextIsArray ? [] : {};
1530
- }
1531
- current = current[cleanPart];
1532
- }
1533
- const lastPart = parts[parts.length - 1];
1534
- const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
1535
- current[cleanLastPart] = value;
1894
+ // src/v3/utils/globals.ts
1895
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
1896
+ var _global = _globalThis;
1897
+ function registerGlobal(type, instance, allowOverride = false) {
1898
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
1899
+ if (!allowOverride && api[type]) {
1900
+ return false;
1536
1901
  }
1537
- return result;
1902
+ api[type] = instance;
1903
+ return true;
1538
1904
  }
1539
- __name(unflattenAttributes, "unflattenAttributes");
1540
- function detectIsArrayIndex(key) {
1541
- const match = key.match(/^\[(\d+)\]$/);
1542
- if (match) {
1543
- return true;
1544
- }
1545
- return false;
1905
+ __name(registerGlobal, "registerGlobal");
1906
+ function getGlobal(type) {
1907
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
1546
1908
  }
1547
- __name(detectIsArrayIndex, "detectIsArrayIndex");
1548
- function primitiveValueOrflattenedAttributes(obj, prefix) {
1549
- if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
1550
- return obj;
1551
- }
1552
- const attributes = flattenAttributes(obj, prefix);
1553
- if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
1554
- return attributes[prefix];
1909
+ __name(getGlobal, "getGlobal");
1910
+ function unregisterGlobal(type) {
1911
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
1912
+ if (api) {
1913
+ delete api[type];
1555
1914
  }
1556
- return attributes;
1557
1915
  }
1558
- __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
1559
- var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
1560
- constructor() {
1561
- this.storage = new async_hooks.AsyncLocalStorage();
1562
- }
1563
- runWith(context3, fn) {
1564
- return this.storage.run(context3, fn);
1565
- }
1566
- getStore() {
1567
- return this.storage.getStore();
1568
- }
1569
- };
1570
- __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
1571
- var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
1916
+ __name(unregisterGlobal, "unregisterGlobal");
1572
1917
 
1573
1918
  // src/v3/semanticInternalAttributes.ts
1574
1919
  var SemanticInternalAttributes = {
@@ -1612,26 +1957,32 @@ var SemanticInternalAttributes = {
1612
1957
  SDK_LANGUAGE: "sdk.language",
1613
1958
  RETRY_AT: "retry.at",
1614
1959
  RETRY_DELAY: "retry.delay",
1615
- RETRY_COUNT: "retry.count"
1960
+ RETRY_COUNT: "retry.count",
1961
+ LINK_TITLE: "$link.title",
1962
+ IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
1616
1963
  };
1617
1964
 
1618
- // src/v3/tasks/taskContextManager.ts
1619
- var _getStore, getStore_fn;
1620
- var _TaskContextManager = class _TaskContextManager {
1965
+ // src/v3/taskContext/index.ts
1966
+ var API_NAME = "task-context";
1967
+ var _getTaskContext, getTaskContext_fn;
1968
+ var _TaskContextAPI = class _TaskContextAPI {
1621
1969
  constructor() {
1622
- __privateAdd(this, _getStore);
1623
- __publicField(this, "_storage", new SafeAsyncLocalStorage());
1970
+ __privateAdd(this, _getTaskContext);
1971
+ }
1972
+ static getInstance() {
1973
+ if (!this._instance) {
1974
+ this._instance = new _TaskContextAPI();
1975
+ }
1976
+ return this._instance;
1624
1977
  }
1625
1978
  get isInsideTask() {
1626
- return __privateMethod(this, _getStore, getStore_fn).call(this) !== void 0;
1979
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
1627
1980
  }
1628
1981
  get ctx() {
1629
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
1630
- return store?.ctx;
1982
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
1631
1983
  }
1632
1984
  get worker() {
1633
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
1634
- return store?.worker;
1985
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
1635
1986
  }
1636
1987
  get attributes() {
1637
1988
  if (this.ctx) {
@@ -1671,71 +2022,28 @@ var _TaskContextManager = class _TaskContextManager {
1671
2022
  [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
1672
2023
  [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
1673
2024
  [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
1674
- [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id
2025
+ [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
2026
+ [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
1675
2027
  };
1676
2028
  }
1677
2029
  return {};
1678
2030
  }
1679
- runWith(context3, fn) {
1680
- return this._storage.runWith(context3, fn);
1681
- }
1682
- };
1683
- _getStore = new WeakSet();
1684
- getStore_fn = /* @__PURE__ */ __name(function() {
1685
- return this._storage.getStore();
1686
- }, "#getStore");
1687
- __name(_TaskContextManager, "TaskContextManager");
1688
- var TaskContextManager = _TaskContextManager;
1689
- var taskContextManager = new TaskContextManager();
1690
- var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
1691
- constructor(innerProcessor) {
1692
- this._innerProcessor = innerProcessor;
1693
- }
1694
- // Called when a span starts
1695
- onStart(span, parentContext) {
1696
- if (taskContextManager.ctx) {
1697
- span.setAttributes(flattenAttributes({
1698
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
1699
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
1700
- }, SemanticInternalAttributes.METADATA));
1701
- }
1702
- this._innerProcessor.onStart(span, parentContext);
1703
- }
1704
- // Delegate the rest of the methods to the wrapped processor
1705
- onEnd(span) {
1706
- this._innerProcessor.onEnd(span);
1707
- }
1708
- shutdown() {
1709
- return this._innerProcessor.shutdown();
1710
- }
1711
- forceFlush() {
1712
- return this._innerProcessor.forceFlush();
1713
- }
1714
- };
1715
- __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
1716
- var TaskContextSpanProcessor = _TaskContextSpanProcessor;
1717
- var _TaskContextLogProcessor = class _TaskContextLogProcessor {
1718
- constructor(innerProcessor) {
1719
- this._innerProcessor = innerProcessor;
1720
- }
1721
- forceFlush() {
1722
- return this._innerProcessor.forceFlush();
1723
- }
1724
- onEmit(logRecord, context3) {
1725
- if (taskContextManager.ctx) {
1726
- logRecord.setAttributes(flattenAttributes({
1727
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
1728
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
1729
- }, SemanticInternalAttributes.METADATA));
1730
- }
1731
- this._innerProcessor.onEmit(logRecord, context3);
2031
+ disable() {
2032
+ unregisterGlobal(API_NAME);
1732
2033
  }
1733
- shutdown() {
1734
- return this._innerProcessor.shutdown();
2034
+ setGlobalTaskContext(taskContext2) {
2035
+ return registerGlobal(API_NAME, taskContext2);
1735
2036
  }
1736
2037
  };
1737
- __name(_TaskContextLogProcessor, "TaskContextLogProcessor");
1738
- var TaskContextLogProcessor = _TaskContextLogProcessor;
2038
+ _getTaskContext = new WeakSet();
2039
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
2040
+ return getGlobal(API_NAME);
2041
+ }, "#getTaskContext");
2042
+ __name(_TaskContextAPI, "TaskContextAPI");
2043
+ var TaskContextAPI = _TaskContextAPI;
2044
+
2045
+ // src/v3/task-context-api.ts
2046
+ var taskContext = TaskContextAPI.getInstance();
1739
2047
 
1740
2048
  // src/v3/utils/getEnv.ts
1741
2049
  function getEnvVar(name) {
@@ -1744,8 +2052,30 @@ function getEnvVar(name) {
1744
2052
  }
1745
2053
  }
1746
2054
  __name(getEnvVar, "getEnvVar");
2055
+ var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
2056
+ constructor() {
2057
+ this.storage = new async_hooks.AsyncLocalStorage();
2058
+ }
2059
+ runWith(context3, fn) {
2060
+ return this.storage.run(context3, fn);
2061
+ }
2062
+ getStore() {
2063
+ return this.storage.getStore();
2064
+ }
2065
+ };
2066
+ __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
2067
+ var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
1747
2068
 
1748
2069
  // src/v3/apiClient/index.ts
2070
+ var zodFetchOptions = {
2071
+ retry: {
2072
+ maxAttempts: 3,
2073
+ minTimeoutInMs: 1e3,
2074
+ maxTimeoutInMs: 3e4,
2075
+ factor: 2,
2076
+ randomize: false
2077
+ }
2078
+ };
1749
2079
  var _getHeaders, getHeaders_fn;
1750
2080
  var _ApiClient = class _ApiClient {
1751
2081
  constructor(baseUrl, accessToken) {
@@ -1753,61 +2083,145 @@ var _ApiClient = class _ApiClient {
1753
2083
  this.accessToken = accessToken;
1754
2084
  this.baseUrl = baseUrl.replace(/\/$/, "");
1755
2085
  }
2086
+ async getRunResult(runId) {
2087
+ try {
2088
+ return await zodfetch(TaskRunExecutionResult, `${this.baseUrl}/api/v1/runs/${runId}/result`, {
2089
+ method: "GET",
2090
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2091
+ }, zodFetchOptions);
2092
+ } catch (error) {
2093
+ if (error instanceof APIError) {
2094
+ if (error.status === 404) {
2095
+ return void 0;
2096
+ }
2097
+ }
2098
+ throw error;
2099
+ }
2100
+ }
2101
+ async getBatchResults(batchId) {
2102
+ return await zodfetch(BatchTaskRunExecutionResult, `${this.baseUrl}/api/v1/batches/${batchId}/results`, {
2103
+ method: "GET",
2104
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2105
+ }, zodFetchOptions);
2106
+ }
1756
2107
  triggerTask(taskId, body, options) {
1757
2108
  return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
1758
2109
  method: "POST",
1759
2110
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1760
2111
  body: JSON.stringify(body)
1761
- });
2112
+ }, zodFetchOptions);
1762
2113
  }
1763
2114
  batchTriggerTask(taskId, body, options) {
1764
2115
  return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
1765
2116
  method: "POST",
1766
2117
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1767
2118
  body: JSON.stringify(body)
1768
- });
2119
+ }, zodFetchOptions);
1769
2120
  }
1770
2121
  createUploadPayloadUrl(filename) {
1771
2122
  return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1772
2123
  method: "PUT",
1773
2124
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1774
- });
2125
+ }, zodFetchOptions);
1775
2126
  }
1776
2127
  getPayloadUrl(filename) {
1777
2128
  return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1778
2129
  method: "GET",
1779
2130
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1780
- });
2131
+ }, zodFetchOptions);
1781
2132
  }
1782
- };
1783
- _getHeaders = new WeakSet();
1784
- getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
1785
- const headers = {
1786
- "Content-Type": "application/json",
1787
- Authorization: `Bearer ${this.accessToken}`
1788
- };
1789
- if (taskContextManager.isInsideTask) {
1790
- api.propagation.inject(api.context.active(), headers);
1791
- if (spanParentAsLink) {
1792
- headers["x-trigger-span-parent-as-link"] = "1";
1793
- }
2133
+ replayRun(runId) {
2134
+ return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2135
+ method: "POST",
2136
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2137
+ }, zodFetchOptions);
1794
2138
  }
1795
- return headers;
1796
- }, "#getHeaders");
1797
- __name(_ApiClient, "ApiClient");
2139
+ cancelRun(runId) {
2140
+ return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
2141
+ method: "POST",
2142
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2143
+ }, zodFetchOptions);
2144
+ }
2145
+ createSchedule(options) {
2146
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
2147
+ method: "POST",
2148
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2149
+ body: JSON.stringify(options)
2150
+ });
2151
+ }
2152
+ listSchedules(options) {
2153
+ const searchParams = new URLSearchParams();
2154
+ if (options?.page) {
2155
+ searchParams.append("page", options.page.toString());
2156
+ }
2157
+ if (options?.perPage) {
2158
+ searchParams.append("perPage", options.perPage.toString());
2159
+ }
2160
+ return zodfetch(ListSchedulesResult, `${this.baseUrl}/api/v1/schedules${searchParams.size > 0 ? `?${searchParams}` : ""}`, {
2161
+ method: "GET",
2162
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2163
+ });
2164
+ }
2165
+ retrieveSchedule(scheduleId) {
2166
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2167
+ method: "GET",
2168
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2169
+ });
2170
+ }
2171
+ updateSchedule(scheduleId, options) {
2172
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2173
+ method: "PUT",
2174
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2175
+ body: JSON.stringify(options)
2176
+ });
2177
+ }
2178
+ deactivateSchedule(scheduleId) {
2179
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
2180
+ method: "POST",
2181
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2182
+ });
2183
+ }
2184
+ activateSchedule(scheduleId) {
2185
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
2186
+ method: "POST",
2187
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2188
+ });
2189
+ }
2190
+ deleteSchedule(scheduleId) {
2191
+ return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2192
+ method: "DELETE",
2193
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2194
+ });
2195
+ }
2196
+ };
2197
+ _getHeaders = new WeakSet();
2198
+ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2199
+ const headers = {
2200
+ "Content-Type": "application/json",
2201
+ Authorization: `Bearer ${this.accessToken}`
2202
+ };
2203
+ if (taskContext.isInsideTask) {
2204
+ api.propagation.inject(api.context.active(), headers);
2205
+ if (spanParentAsLink) {
2206
+ headers["x-trigger-span-parent-as-link"] = "1";
2207
+ }
2208
+ }
2209
+ return headers;
2210
+ }, "#getHeaders");
2211
+ __name(_ApiClient, "ApiClient");
1798
2212
  var ApiClient = _ApiClient;
1799
- var _getStore2, getStore_fn2;
2213
+ var _getStore, getStore_fn;
1800
2214
  var _ApiClientManager = class _ApiClientManager {
1801
2215
  constructor() {
1802
- __privateAdd(this, _getStore2);
2216
+ __privateAdd(this, _getStore);
1803
2217
  __publicField(this, "_storage", new SafeAsyncLocalStorage());
1804
2218
  }
1805
2219
  get baseURL() {
1806
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
2220
+ const store = __privateMethod(this, _getStore, getStore_fn).call(this);
1807
2221
  return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
1808
2222
  }
1809
2223
  get accessToken() {
1810
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
2224
+ const store = __privateMethod(this, _getStore, getStore_fn).call(this);
1811
2225
  return store?.accessToken ?? getEnvVar("TRIGGER_SECRET_KEY");
1812
2226
  }
1813
2227
  get client() {
@@ -1820,1068 +2234,314 @@ var _ApiClientManager = class _ApiClientManager {
1820
2234
  return this._storage.runWith(context3, fn);
1821
2235
  }
1822
2236
  };
1823
- _getStore2 = new WeakSet();
1824
- getStore_fn2 = /* @__PURE__ */ __name(function() {
2237
+ _getStore = new WeakSet();
2238
+ getStore_fn = /* @__PURE__ */ __name(function() {
1825
2239
  return this._storage.getStore();
1826
2240
  }, "#getStore");
1827
2241
  __name(_ApiClientManager, "ApiClientManager");
1828
2242
  var ApiClientManager = _ApiClientManager;
1829
2243
  var apiClientManager = new ApiClientManager();
1830
- var ZodMessageSchema = zod.z.object({
1831
- version: zod.z.literal("v1").default("v1"),
1832
- type: zod.z.string(),
1833
- payload: zod.z.unknown()
1834
- });
1835
- var _schema, _handlers;
1836
- var _ZodMessageHandler = class _ZodMessageHandler {
1837
- constructor(options) {
1838
- __privateAdd(this, _schema, void 0);
1839
- __privateAdd(this, _handlers, void 0);
1840
- __privateSet(this, _schema, options.schema);
1841
- __privateSet(this, _handlers, options.messages);
1842
- }
1843
- async handleMessage(message) {
1844
- const parsedMessage = this.parseMessage(message);
1845
- if (!__privateGet(this, _handlers)) {
1846
- throw new Error("No handlers provided");
1847
- }
1848
- const handler = __privateGet(this, _handlers)[parsedMessage.type];
1849
- if (!handler) {
1850
- console.error(`No handler for message type: ${String(parsedMessage.type)}`);
1851
- return;
1852
- }
1853
- const ack = await handler(parsedMessage.payload);
1854
- return ack;
1855
- }
1856
- parseMessage(message) {
1857
- const parsedMessage = ZodMessageSchema.safeParse(message);
1858
- if (!parsedMessage.success) {
1859
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
1860
- }
1861
- const schema = __privateGet(this, _schema)[parsedMessage.data.type];
1862
- if (!schema) {
1863
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
1864
- }
1865
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
1866
- if (!parsedPayload.success) {
1867
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
1868
- }
1869
- return {
1870
- type: parsedMessage.data.type,
1871
- payload: parsedPayload.data
1872
- };
2244
+ var _SimpleClock = class _SimpleClock {
2245
+ preciseNow() {
2246
+ const now = new preciseDate.PreciseDate();
2247
+ const nowStruct = now.toStruct();
2248
+ return [
2249
+ nowStruct.seconds,
2250
+ nowStruct.nanos
2251
+ ];
1873
2252
  }
1874
- registerHandlers(emitter, logger2) {
1875
- const log = logger2 ?? console;
1876
- if (!__privateGet(this, _handlers)) {
1877
- log.info("No handlers provided");
1878
- return;
1879
- }
1880
- for (const eventName of Object.keys(__privateGet(this, _schema))) {
1881
- emitter.on(eventName, async (message, callback) => {
1882
- log.info(`handling ${eventName}`, {
1883
- payload: message,
1884
- hasCallback: !!callback
1885
- });
1886
- let ack;
1887
- if ("payload" in message) {
1888
- ack = await this.handleMessage({
1889
- type: eventName,
1890
- ...message
1891
- });
1892
- } else {
1893
- const { version, ...payload } = message;
1894
- ack = await this.handleMessage({
1895
- type: eventName,
1896
- version,
1897
- payload
1898
- });
1899
- }
1900
- if (callback && typeof callback === "function") {
1901
- callback(ack);
1902
- }
1903
- });
1904
- }
2253
+ reset() {
1905
2254
  }
1906
2255
  };
1907
- _schema = new WeakMap();
1908
- _handlers = new WeakMap();
1909
- __name(_ZodMessageHandler, "ZodMessageHandler");
1910
- var ZodMessageHandler = _ZodMessageHandler;
1911
- var _schema2, _sender;
1912
- var _ZodMessageSender = class _ZodMessageSender {
1913
- constructor(options) {
1914
- __privateAdd(this, _schema2, void 0);
1915
- __privateAdd(this, _sender, void 0);
1916
- __privateSet(this, _schema2, options.schema);
1917
- __privateSet(this, _sender, options.sender);
1918
- }
1919
- async send(type, payload) {
1920
- const schema = __privateGet(this, _schema2)[type];
1921
- if (!schema) {
1922
- throw new Error(`Unknown message type: ${type}`);
1923
- }
1924
- const parsedPayload = schema.safeParse(payload);
1925
- if (!parsedPayload.success) {
1926
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
1927
- }
1928
- await __privateGet(this, _sender).call(this, {
1929
- type,
1930
- payload,
1931
- version: "v1"
1932
- });
2256
+ __name(_SimpleClock, "SimpleClock");
2257
+ var SimpleClock = _SimpleClock;
2258
+
2259
+ // src/v3/clock/index.ts
2260
+ var API_NAME2 = "clock";
2261
+ var SIMPLE_CLOCK = new SimpleClock();
2262
+ var _getClock, getClock_fn;
2263
+ var _ClockAPI = class _ClockAPI {
2264
+ constructor() {
2265
+ __privateAdd(this, _getClock);
1933
2266
  }
1934
- async forwardMessage(message) {
1935
- const parsedMessage = ZodMessageSchema.safeParse(message);
1936
- if (!parsedMessage.success) {
1937
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
1938
- }
1939
- const schema = __privateGet(this, _schema2)[parsedMessage.data.type];
1940
- if (!schema) {
1941
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
1942
- }
1943
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
1944
- if (!parsedPayload.success) {
1945
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2267
+ static getInstance() {
2268
+ if (!this._instance) {
2269
+ this._instance = new _ClockAPI();
1946
2270
  }
1947
- await __privateGet(this, _sender).call(this, {
1948
- type: parsedMessage.data.type,
1949
- payload: parsedPayload.data,
1950
- version: "v1"
1951
- });
2271
+ return this._instance;
2272
+ }
2273
+ setGlobalClock(clock2) {
2274
+ return registerGlobal(API_NAME2, clock2);
2275
+ }
2276
+ preciseNow() {
2277
+ return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2278
+ }
2279
+ reset() {
2280
+ __privateMethod(this, _getClock, getClock_fn).call(this).reset();
1952
2281
  }
1953
2282
  };
1954
- _schema2 = new WeakMap();
1955
- _sender = new WeakMap();
1956
- __name(_ZodMessageSender, "ZodMessageSender");
1957
- var ZodMessageSender = _ZodMessageSender;
1958
- var messageSchema = zod.z.object({
1959
- version: zod.z.literal("v1").default("v1"),
1960
- type: zod.z.string(),
1961
- payload: zod.z.unknown()
1962
- });
1963
- var _schema3, _handlers2;
1964
- var _ZodSocketMessageHandler = class _ZodSocketMessageHandler {
1965
- constructor(options) {
1966
- __privateAdd(this, _schema3, void 0);
1967
- __privateAdd(this, _handlers2, void 0);
1968
- __privateSet(this, _schema3, options.schema);
1969
- __privateSet(this, _handlers2, options.handlers);
1970
- }
1971
- async handleMessage(message) {
1972
- const parsedMessage = this.parseMessage(message);
1973
- if (!__privateGet(this, _handlers2)) {
1974
- throw new Error("No handlers provided");
1975
- }
1976
- const handler = __privateGet(this, _handlers2)[parsedMessage.type];
1977
- if (!handler) {
1978
- console.error(`No handler for message type: ${String(parsedMessage.type)}`);
1979
- return;
1980
- }
1981
- const ack = await handler(parsedMessage.payload);
1982
- return ack;
2283
+ _getClock = new WeakSet();
2284
+ getClock_fn = /* @__PURE__ */ __name(function() {
2285
+ return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2286
+ }, "#getClock");
2287
+ __name(_ClockAPI, "ClockAPI");
2288
+ var ClockAPI = _ClockAPI;
2289
+
2290
+ // src/v3/clock-api.ts
2291
+ var clock = ClockAPI.getInstance();
2292
+
2293
+ // src/v3/errors.ts
2294
+ function parseError(error) {
2295
+ if (error instanceof Error) {
2296
+ return {
2297
+ type: "BUILT_IN_ERROR",
2298
+ name: error.name,
2299
+ message: error.message,
2300
+ stackTrace: error.stack ?? ""
2301
+ };
1983
2302
  }
1984
- parseMessage(message) {
1985
- const parsedMessage = messageSchema.safeParse(message);
1986
- if (!parsedMessage.success) {
1987
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
1988
- }
1989
- const schema = __privateGet(this, _schema3)[parsedMessage.data.type]["message"];
1990
- if (!schema) {
1991
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
1992
- }
1993
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
1994
- if (!parsedPayload.success) {
1995
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
1996
- }
2303
+ if (typeof error === "string") {
1997
2304
  return {
1998
- type: parsedMessage.data.type,
1999
- payload: parsedPayload.data
2305
+ type: "STRING_ERROR",
2306
+ raw: error
2000
2307
  };
2001
2308
  }
2002
- registerHandlers(emitter, logger2) {
2003
- const log = logger2 ?? console;
2004
- if (!__privateGet(this, _handlers2)) {
2005
- log.info("No handlers provided");
2006
- return;
2309
+ try {
2310
+ return {
2311
+ type: "CUSTOM_ERROR",
2312
+ raw: JSON.stringify(error)
2313
+ };
2314
+ } catch (e) {
2315
+ return {
2316
+ type: "CUSTOM_ERROR",
2317
+ raw: String(error)
2318
+ };
2319
+ }
2320
+ }
2321
+ __name(parseError, "parseError");
2322
+ function createErrorTaskError(error) {
2323
+ switch (error.type) {
2324
+ case "BUILT_IN_ERROR": {
2325
+ const e = new Error(error.message);
2326
+ e.name = error.name;
2327
+ e.stack = error.stackTrace;
2328
+ return e;
2007
2329
  }
2008
- for (const eventName of Object.keys(__privateGet(this, _handlers2))) {
2009
- emitter.on(eventName, async (message, callback) => {
2010
- log.info(`handling ${eventName}`, {
2011
- payload: message,
2012
- hasCallback: !!callback
2013
- });
2014
- let ack;
2015
- try {
2016
- if ("payload" in message) {
2017
- ack = await this.handleMessage({
2018
- type: eventName,
2019
- ...message
2020
- });
2021
- } else {
2022
- const { version, ...payload } = message;
2023
- ack = await this.handleMessage({
2024
- type: eventName,
2025
- version,
2026
- payload
2027
- });
2028
- }
2029
- } catch (error) {
2030
- log.error("Error while handling message", {
2031
- error
2032
- });
2033
- return;
2034
- }
2035
- if (callback && typeof callback === "function") {
2036
- callback(ack);
2037
- }
2038
- });
2330
+ case "STRING_ERROR": {
2331
+ return error.raw;
2039
2332
  }
2040
- }
2041
- };
2042
- _schema3 = new WeakMap();
2043
- _handlers2 = new WeakMap();
2044
- __name(_ZodSocketMessageHandler, "ZodSocketMessageHandler");
2045
- var ZodSocketMessageHandler = _ZodSocketMessageHandler;
2046
- var _schema4, _socket;
2047
- var _ZodSocketMessageSender = class _ZodSocketMessageSender {
2048
- constructor(options) {
2049
- __privateAdd(this, _schema4, void 0);
2050
- __privateAdd(this, _socket, void 0);
2051
- __privateSet(this, _schema4, options.schema);
2052
- __privateSet(this, _socket, options.socket);
2053
- }
2054
- send(type, payload) {
2055
- const schema = __privateGet(this, _schema4)[type]["message"];
2056
- if (!schema) {
2057
- throw new Error(`Unknown message type: ${type}`);
2333
+ case "CUSTOM_ERROR": {
2334
+ return JSON.parse(error.raw);
2058
2335
  }
2059
- const parsedPayload = schema.safeParse(payload);
2060
- if (!parsedPayload.success) {
2061
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2336
+ case "INTERNAL_ERROR": {
2337
+ return new Error(`trigger.dev internal error (${error.code})`);
2062
2338
  }
2063
- __privateGet(this, _socket).emit(type, {
2064
- payload,
2065
- version: "v1"
2066
- });
2339
+ }
2340
+ }
2341
+ __name(createErrorTaskError, "createErrorTaskError");
2342
+ function correctErrorStackTrace(stackTrace, projectDir, options) {
2343
+ const [errorLine, ...traceLines] = stackTrace.split("\n");
2344
+ return [
2345
+ options?.removeFirstLine ? void 0 : errorLine,
2346
+ ...traceLines.map((line) => correctStackTraceLine(line, projectDir))
2347
+ ].filter(Boolean).join("\n");
2348
+ }
2349
+ __name(correctErrorStackTrace, "correctErrorStackTrace");
2350
+ var LINES_TO_IGNORE = [
2351
+ /ConsoleInterceptor/,
2352
+ /TriggerTracer/,
2353
+ /TaskExecutor/,
2354
+ /EXECUTE_TASK_RUN/,
2355
+ /@trigger.dev\/core/,
2356
+ /safeJsonProcess/,
2357
+ /__entryPoint.ts/
2358
+ ];
2359
+ function correctStackTraceLine(line, projectDir) {
2360
+ if (LINES_TO_IGNORE.some((regex) => regex.test(line))) {
2361
+ return;
2362
+ }
2363
+ if (projectDir && !line.includes(projectDir)) {
2067
2364
  return;
2068
2365
  }
2069
- async sendWithAck(type, payload) {
2070
- const schema = __privateGet(this, _schema4)[type]["message"];
2071
- if (!schema) {
2072
- throw new Error(`Unknown message type: ${type}`);
2366
+ return line.trim();
2367
+ }
2368
+ __name(correctStackTraceLine, "correctStackTraceLine");
2369
+ function groupTaskMetadataIssuesByTask(tasks, issues) {
2370
+ return issues.reduce((acc, issue) => {
2371
+ if (issue.path.length === 0) {
2372
+ return acc;
2373
+ }
2374
+ const taskIndex = issue.path[1];
2375
+ if (typeof taskIndex !== "number") {
2376
+ return acc;
2073
2377
  }
2074
- const parsedPayload = schema.safeParse(payload);
2075
- if (!parsedPayload.success) {
2076
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2378
+ const task = tasks[taskIndex];
2379
+ if (!task) {
2380
+ return acc;
2077
2381
  }
2078
- const callbackResult = await __privateGet(this, _socket).emitWithAck(type, {
2079
- payload,
2080
- version: "v1"
2382
+ const restOfPath = issue.path.slice(2);
2383
+ const taskId = task.id;
2384
+ const taskName = task.exportName;
2385
+ const filePath = task.filePath;
2386
+ const key = taskIndex;
2387
+ const existing = acc[key] ?? {
2388
+ id: taskId,
2389
+ exportName: taskName,
2390
+ filePath,
2391
+ issues: []
2392
+ };
2393
+ existing.issues.push({
2394
+ message: issue.message,
2395
+ path: restOfPath.length === 0 ? void 0 : restOfPath.join(".")
2081
2396
  });
2082
- return callbackResult;
2397
+ return {
2398
+ ...acc,
2399
+ [key]: existing
2400
+ };
2401
+ }, {});
2402
+ }
2403
+ __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
2404
+
2405
+ // src/v3/limits.ts
2406
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2407
+ var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
2408
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2409
+ var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2410
+ var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
2411
+ var OTEL_LINK_COUNT_LIMIT = 2;
2412
+ var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
2413
+ var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
2414
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
2415
+ function imposeAttributeLimits(attributes) {
2416
+ const newAttributes = {};
2417
+ for (const [key, value] of Object.entries(attributes)) {
2418
+ if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
2419
+ continue;
2420
+ }
2421
+ if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
2422
+ break;
2423
+ }
2424
+ newAttributes[key] = value;
2083
2425
  }
2084
- };
2085
- _schema4 = new WeakMap();
2086
- _socket = new WeakMap();
2087
- __name(_ZodSocketMessageSender, "ZodSocketMessageSender");
2088
- var ZodSocketMessageSender = _ZodSocketMessageSender;
2089
- var _sender2, _handler, _logger;
2090
- var _ZodSocketConnection = class _ZodSocketConnection {
2091
- constructor(opts) {
2092
- __privateAdd(this, _sender2, void 0);
2093
- __privateAdd(this, _handler, void 0);
2094
- __privateAdd(this, _logger, void 0);
2095
- const uri = `${opts.secure ? "wss" : "ws"}://${opts.host}:${opts.port ?? (opts.secure ? "443" : "80")}/${opts.namespace}`;
2096
- const logger2 = new SimpleStructuredLogger(opts.namespace, exports.LogLevel.info);
2097
- logger2.log("new zod socket", {
2098
- uri
2099
- });
2100
- this.socket = socket_ioClient.io(uri, {
2101
- transports: [
2102
- "websocket"
2103
- ],
2104
- auth: {
2105
- token: opts.authToken
2106
- },
2107
- extraHeaders: opts.extraHeaders,
2108
- reconnectionDelay: 500,
2109
- reconnectionDelayMax: 1e3
2110
- });
2111
- __privateSet(this, _logger, logger2.child({
2112
- socketId: this.socket.id
2113
- }));
2114
- __privateSet(this, _handler, new ZodSocketMessageHandler({
2115
- schema: opts.serverMessages,
2116
- handlers: opts.handlers
2117
- }));
2118
- __privateGet(this, _handler).registerHandlers(this.socket, __privateGet(this, _logger));
2119
- __privateSet(this, _sender2, new ZodSocketMessageSender({
2120
- schema: opts.clientMessages,
2121
- socket: this.socket
2122
- }));
2123
- this.socket.on("connect_error", async (error) => {
2124
- __privateGet(this, _logger).error(`connect_error: ${error}`);
2125
- if (opts.onError) {
2126
- await opts.onError(this.socket, error, __privateGet(this, _logger));
2127
- }
2128
- });
2129
- this.socket.on("connect", async () => {
2130
- __privateGet(this, _logger).info("connect");
2131
- if (opts.onConnection) {
2132
- await opts.onConnection(this.socket, __privateGet(this, _handler), __privateGet(this, _sender2), __privateGet(this, _logger));
2133
- }
2134
- });
2135
- this.socket.on("disconnect", async (reason, description) => {
2136
- __privateGet(this, _logger).info("disconnect", {
2137
- reason,
2138
- description
2139
- });
2140
- if (opts.onDisconnect) {
2141
- await opts.onDisconnect(this.socket, reason, description, __privateGet(this, _logger));
2142
- }
2143
- });
2426
+ return newAttributes;
2427
+ }
2428
+ __name(imposeAttributeLimits, "imposeAttributeLimits");
2429
+ function calculateAttributeValueLength(value) {
2430
+ if (value === void 0 || value === null) {
2431
+ return 0;
2144
2432
  }
2145
- close() {
2146
- this.socket.close();
2433
+ if (typeof value === "string") {
2434
+ return value.length;
2147
2435
  }
2148
- connect() {
2149
- this.socket.connect();
2436
+ if (typeof value === "number") {
2437
+ return 8;
2150
2438
  }
2151
- get send() {
2152
- return __privateGet(this, _sender2).send.bind(__privateGet(this, _sender2));
2439
+ if (typeof value === "boolean") {
2440
+ return 4;
2153
2441
  }
2154
- get sendWithAck() {
2155
- return __privateGet(this, _sender2).sendWithAck.bind(__privateGet(this, _sender2));
2442
+ if (Array.isArray(value)) {
2443
+ return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
2156
2444
  }
2157
- };
2158
- _sender2 = new WeakMap();
2159
- _handler = new WeakMap();
2160
- _logger = new WeakMap();
2161
- __name(_ZodSocketConnection, "ZodSocketConnection");
2162
- var ZodSocketConnection = _ZodSocketConnection;
2445
+ return 0;
2446
+ }
2447
+ __name(calculateAttributeValueLength, "calculateAttributeValueLength");
2163
2448
 
2164
- // src/v3/zodNamespace.ts
2165
- exports.LogLevel = void 0;
2166
- (function(LogLevel2) {
2167
- LogLevel2[LogLevel2["log"] = 0] = "log";
2168
- LogLevel2[LogLevel2["error"] = 1] = "error";
2169
- LogLevel2[LogLevel2["warn"] = 2] = "warn";
2170
- LogLevel2[LogLevel2["info"] = 3] = "info";
2171
- LogLevel2[LogLevel2["debug"] = 4] = "debug";
2172
- })(exports.LogLevel || (exports.LogLevel = {}));
2173
- var _structuredLog, structuredLog_fn;
2174
- var _SimpleStructuredLogger = class _SimpleStructuredLogger {
2175
- constructor(name, level = [
2176
- "1",
2177
- "true"
2178
- ].includes(process.env.DEBUG ?? "") ? exports.LogLevel.debug : exports.LogLevel.info, fields) {
2179
- __privateAdd(this, _structuredLog);
2180
- this.name = name;
2181
- this.level = level;
2182
- this.fields = fields;
2183
- }
2184
- child(fields, level) {
2185
- return new _SimpleStructuredLogger(this.name, level, {
2186
- ...this.fields,
2187
- ...fields
2188
- });
2449
+ // src/v3/utils/flattenAttributes.ts
2450
+ function flattenAttributes(obj, prefix) {
2451
+ const result = {};
2452
+ if (!obj) {
2453
+ return result;
2189
2454
  }
2190
- log(message, ...args) {
2191
- if (this.level < exports.LogLevel.log)
2192
- return;
2193
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.log, message, "log", ...args);
2455
+ if (typeof obj === "string") {
2456
+ result[prefix || ""] = obj;
2457
+ return result;
2194
2458
  }
2195
- error(message, ...args) {
2196
- if (this.level < exports.LogLevel.error)
2197
- return;
2198
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.error, message, "error", ...args);
2199
- }
2200
- warn(message, ...args) {
2201
- if (this.level < exports.LogLevel.warn)
2202
- return;
2203
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.warn, message, "warn", ...args);
2204
- }
2205
- info(message, ...args) {
2206
- if (this.level < exports.LogLevel.info)
2207
- return;
2208
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.info, message, "info", ...args);
2459
+ if (typeof obj === "number") {
2460
+ result[prefix || ""] = obj;
2461
+ return result;
2209
2462
  }
2210
- debug(message, ...args) {
2211
- if (this.level < exports.LogLevel.debug)
2212
- return;
2213
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.debug, message, "debug", ...args);
2463
+ if (typeof obj === "boolean") {
2464
+ result[prefix || ""] = obj;
2465
+ return result;
2214
2466
  }
2215
- };
2216
- _structuredLog = new WeakSet();
2217
- structuredLog_fn = /* @__PURE__ */ __name(function(loggerFunction, message, level, ...args) {
2218
- const structuredLog = {
2219
- ...args.length === 1 ? args[0] : args,
2220
- ...this.fields,
2221
- timestamp: /* @__PURE__ */ new Date(),
2222
- name: this.name,
2223
- message,
2224
- level
2225
- };
2226
- loggerFunction(JSON.stringify(structuredLog));
2227
- }, "#structuredLog");
2228
- __name(_SimpleStructuredLogger, "SimpleStructuredLogger");
2229
- var SimpleStructuredLogger = _SimpleStructuredLogger;
2230
- var _logger2, _handler2;
2231
- var _ZodNamespace = class _ZodNamespace {
2232
- constructor(opts) {
2233
- __privateAdd(this, _logger2, void 0);
2234
- __privateAdd(this, _handler2, void 0);
2235
- __privateSet(this, _logger2, opts.logger ?? new SimpleStructuredLogger(opts.name));
2236
- __privateSet(this, _handler2, new ZodSocketMessageHandler({
2237
- schema: opts.clientMessages,
2238
- handlers: opts.handlers
2239
- }));
2240
- this.io = opts.io;
2241
- this.namespace = this.io.of(opts.name);
2242
- this.sender = new ZodMessageSender({
2243
- schema: opts.serverMessages,
2244
- sender: async (message) => {
2245
- return new Promise((resolve, reject) => {
2246
- try {
2247
- this.namespace.emit(message.type, message.payload);
2248
- resolve();
2249
- } catch (err) {
2250
- reject(err);
2251
- }
2252
- });
2253
- }
2254
- });
2255
- if (opts.preAuth) {
2256
- this.namespace.use(async (socket, next) => {
2257
- const logger2 = __privateGet(this, _logger2).child({
2258
- socketId: socket.id,
2259
- socketStage: "preAuth"
2260
- });
2261
- if (typeof opts.preAuth === "function") {
2262
- await opts.preAuth(socket, next, logger2);
2263
- }
2264
- });
2265
- }
2266
- if (opts.authToken) {
2267
- this.namespace.use((socket, next) => {
2268
- const logger2 = __privateGet(this, _logger2).child({
2269
- socketId: socket.id,
2270
- socketStage: "auth"
2271
- });
2272
- const { auth } = socket.handshake;
2273
- if (!("token" in auth)) {
2274
- logger2.error("no token");
2275
- return socket.disconnect(true);
2276
- }
2277
- if (auth.token !== opts.authToken) {
2278
- logger2.error("invalid token");
2279
- return socket.disconnect(true);
2280
- }
2281
- logger2.info("success");
2282
- next();
2283
- });
2284
- }
2285
- if (opts.postAuth) {
2286
- this.namespace.use(async (socket, next) => {
2287
- const logger2 = __privateGet(this, _logger2).child({
2288
- socketId: socket.id,
2289
- socketStage: "auth"
2290
- });
2291
- if (typeof opts.postAuth === "function") {
2292
- await opts.postAuth(socket, next, logger2);
2293
- }
2294
- });
2295
- }
2296
- this.namespace.on("connection", async (socket) => {
2297
- const logger2 = __privateGet(this, _logger2).child({
2298
- socketId: socket.id,
2299
- socketStage: "connection"
2300
- });
2301
- logger2.info("connected");
2302
- __privateGet(this, _handler2).registerHandlers(socket, logger2);
2303
- socket.on("disconnect", async (reason, description) => {
2304
- logger2.info("disconnect", {
2305
- reason,
2306
- description
2307
- });
2308
- if (opts.onDisconnect) {
2309
- await opts.onDisconnect(socket, reason, description, logger2);
2310
- }
2311
- });
2312
- socket.on("error", async (error) => {
2313
- logger2.error("error", {
2314
- error
2315
- });
2316
- if (opts.onError) {
2317
- await opts.onError(socket, error, logger2);
2467
+ for (const [key, value] of Object.entries(obj)) {
2468
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
2469
+ if (Array.isArray(value)) {
2470
+ for (let i = 0; i < value.length; i++) {
2471
+ if (typeof value[i] === "object" && value[i] !== null) {
2472
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
2473
+ } else {
2474
+ result[`${newPrefix}.[${i}]`] = value[i];
2318
2475
  }
2319
- });
2320
- if (opts.onConnection) {
2321
- await opts.onConnection(socket, __privateGet(this, _handler2), this.sender, logger2);
2322
- }
2323
- });
2324
- }
2325
- fetchSockets() {
2326
- return this.namespace.fetchSockets();
2327
- }
2328
- };
2329
- _logger2 = new WeakMap();
2330
- _handler2 = new WeakMap();
2331
- __name(_ZodNamespace, "ZodNamespace");
2332
- var ZodNamespace = _ZodNamespace;
2333
- var messageSchema2 = zod.z.object({
2334
- version: zod.z.literal("v1").default("v1"),
2335
- type: zod.z.string(),
2336
- payload: zod.z.unknown()
2337
- });
2338
- var _schema5, _handlers3, _sender3, _a;
2339
- var ZodIpcMessageHandler = (_a = class {
2340
- constructor(options) {
2341
- __privateAdd(this, _schema5, void 0);
2342
- __privateAdd(this, _handlers3, void 0);
2343
- __privateAdd(this, _sender3, void 0);
2344
- __privateSet(this, _schema5, options.schema);
2345
- __privateSet(this, _handlers3, options.handlers);
2346
- __privateSet(this, _sender3, options.sender);
2347
- }
2348
- async handleMessage(message) {
2349
- const parsedMessage = this.parseMessage(message);
2350
- if (!__privateGet(this, _handlers3)) {
2351
- throw new Error("No handlers provided");
2352
- }
2353
- const handler = __privateGet(this, _handlers3)[parsedMessage.type];
2354
- if (!handler) {
2355
- return;
2356
- }
2357
- const ack = await handler(parsedMessage.payload, __privateGet(this, _sender3));
2358
- return ack;
2359
- }
2360
- parseMessage(message) {
2361
- const parsedMessage = messageSchema2.safeParse(message);
2362
- if (!parsedMessage.success) {
2363
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2364
- }
2365
- const schema = __privateGet(this, _schema5)[parsedMessage.data.type]["message"];
2366
- if (!schema) {
2367
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2368
- }
2369
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2370
- if (!parsedPayload.success) {
2371
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2372
- }
2373
- return {
2374
- type: parsedMessage.data.type,
2375
- payload: parsedPayload.data
2376
- };
2377
- }
2378
- }, _schema5 = new WeakMap(), _handlers3 = new WeakMap(), _sender3 = new WeakMap(), __name(_a, "ZodIpcMessageHandler"), _a);
2379
- var Packet = zod.z.discriminatedUnion("type", [
2380
- zod.z.object({
2381
- type: zod.z.literal("CONNECT"),
2382
- sessionId: zod.z.string().optional()
2383
- }),
2384
- zod.z.object({
2385
- type: zod.z.literal("ACK"),
2386
- message: zod.z.any(),
2387
- id: zod.z.number()
2388
- }),
2389
- zod.z.object({
2390
- type: zod.z.literal("EVENT"),
2391
- message: zod.z.any(),
2392
- id: zod.z.number().optional()
2393
- })
2394
- ]);
2395
- var _sessionId, _messageCounter, _handler3, _acks, _registerHandlers, registerHandlers_fn, _handlePacket, handlePacket_fn, _sendPacket, sendPacket_fn;
2396
- var _ZodIpcConnection = class _ZodIpcConnection {
2397
- constructor(opts) {
2398
- __privateAdd(this, _registerHandlers);
2399
- __privateAdd(this, _handlePacket);
2400
- __privateAdd(this, _sendPacket);
2401
- __privateAdd(this, _sessionId, void 0);
2402
- __privateAdd(this, _messageCounter, void 0);
2403
- __privateAdd(this, _handler3, void 0);
2404
- __privateAdd(this, _acks, void 0);
2405
- this.opts = opts;
2406
- __privateSet(this, _messageCounter, 0);
2407
- __privateSet(this, _acks, /* @__PURE__ */ new Map());
2408
- __privateSet(this, _handler3, new ZodIpcMessageHandler({
2409
- schema: opts.listenSchema,
2410
- handlers: opts.handlers,
2411
- sender: {
2412
- send: this.send.bind(this),
2413
- sendWithAck: this.sendWithAck.bind(this)
2414
- }
2415
- }));
2416
- __privateMethod(this, _registerHandlers, registerHandlers_fn).call(this);
2417
- }
2418
- async connect() {
2419
- __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2420
- type: "CONNECT"
2421
- });
2422
- }
2423
- async send(type, payload) {
2424
- const schema = this.opts.emitSchema[type]["message"];
2425
- if (!schema) {
2426
- throw new Error(`Unknown message type: ${type}`);
2427
- }
2428
- const parsedPayload = schema.safeParse(payload);
2429
- if (!parsedPayload.success) {
2430
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2431
- }
2432
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2433
- type: "EVENT",
2434
- message: {
2435
- type,
2436
- payload,
2437
- version: "v1"
2438
- }
2439
- });
2440
- }
2441
- async sendWithAck(type, payload, timeoutInMs) {
2442
- const currentId = __privateWrapper(this, _messageCounter)._++;
2443
- return new Promise(async (resolve, reject) => {
2444
- const defaultTimeoutInMs = 2e3;
2445
- const timeout = setTimeout(() => {
2446
- reject(JSON.stringify({
2447
- reason: "sendWithAck() timeout",
2448
- timeoutInMs: timeoutInMs ?? defaultTimeoutInMs,
2449
- type,
2450
- payload
2451
- }));
2452
- }, timeoutInMs ?? defaultTimeoutInMs);
2453
- __privateGet(this, _acks).set(currentId, {
2454
- resolve,
2455
- reject,
2456
- timeout
2457
- });
2458
- const schema = this.opts.emitSchema[type]["message"];
2459
- if (!schema) {
2460
- clearTimeout(timeout);
2461
- return reject(`Unknown message type: ${type}`);
2462
- }
2463
- const parsedPayload = schema.safeParse(payload);
2464
- if (!parsedPayload.success) {
2465
- clearTimeout(timeout);
2466
- return reject(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2467
- }
2468
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2469
- type: "EVENT",
2470
- message: {
2471
- type,
2472
- payload,
2473
- version: "v1"
2474
- },
2475
- id: currentId
2476
- });
2477
- });
2478
- }
2479
- };
2480
- _sessionId = new WeakMap();
2481
- _messageCounter = new WeakMap();
2482
- _handler3 = new WeakMap();
2483
- _acks = new WeakMap();
2484
- _registerHandlers = new WeakSet();
2485
- registerHandlers_fn = /* @__PURE__ */ __name(async function() {
2486
- if (!this.opts.process.on) {
2487
- return;
2488
- }
2489
- this.opts.process.on("message", async (message) => {
2490
- __privateMethod(this, _handlePacket, handlePacket_fn).call(this, message);
2491
- });
2492
- }, "#registerHandlers");
2493
- _handlePacket = new WeakSet();
2494
- handlePacket_fn = /* @__PURE__ */ __name(async function(packet) {
2495
- const parsedPacket = Packet.safeParse(packet);
2496
- if (!parsedPacket.success) {
2497
- return;
2498
- }
2499
- switch (parsedPacket.data.type) {
2500
- case "ACK": {
2501
- const ack = __privateGet(this, _acks).get(parsedPacket.data.id);
2502
- if (!ack) {
2503
- return;
2504
- }
2505
- clearTimeout(ack.timeout);
2506
- ack.resolve(parsedPacket.data.message);
2507
- break;
2508
- }
2509
- case "CONNECT": {
2510
- if (!parsedPacket.data.sessionId) {
2511
- const id = crypto.randomUUID();
2512
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2513
- type: "CONNECT",
2514
- sessionId: id
2515
- });
2516
- return;
2517
- }
2518
- if (__privateGet(this, _sessionId)) {
2519
- return;
2520
2476
  }
2521
- __privateSet(this, _sessionId, parsedPacket.data.sessionId);
2522
- break;
2523
- }
2524
- case "EVENT": {
2525
- const result = await __privateGet(this, _handler3).handleMessage(parsedPacket.data.message);
2526
- if (typeof parsedPacket.data.id === "undefined") {
2527
- return;
2477
+ } else if (isRecord(value)) {
2478
+ Object.assign(result, flattenAttributes(value, newPrefix));
2479
+ } else {
2480
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
2481
+ result[newPrefix] = value;
2528
2482
  }
2529
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2530
- type: "ACK",
2531
- id: parsedPacket.data.id,
2532
- message: result
2533
- });
2534
- break;
2535
- }
2536
- }
2537
- }, "#handlePacket");
2538
- _sendPacket = new WeakSet();
2539
- sendPacket_fn = /* @__PURE__ */ __name(async function(packet1) {
2540
- await this.opts.process.send?.(packet1);
2541
- }, "#sendPacket");
2542
- __name(_ZodIpcConnection, "ZodIpcConnection");
2543
- var ZodIpcConnection = _ZodIpcConnection;
2544
- function parseError(error) {
2545
- if (error instanceof Error) {
2546
- return {
2547
- type: "BUILT_IN_ERROR",
2548
- name: error.name,
2549
- message: error.message,
2550
- stackTrace: error.stack ?? ""
2551
- };
2552
- }
2553
- if (typeof error === "string") {
2554
- return {
2555
- type: "STRING_ERROR",
2556
- raw: error
2557
- };
2558
- }
2559
- try {
2560
- return {
2561
- type: "CUSTOM_ERROR",
2562
- raw: JSON.stringify(error)
2563
- };
2564
- } catch (e) {
2565
- return {
2566
- type: "CUSTOM_ERROR",
2567
- raw: String(error)
2568
- };
2569
- }
2570
- }
2571
- __name(parseError, "parseError");
2572
- function createErrorTaskError(error) {
2573
- switch (error.type) {
2574
- case "BUILT_IN_ERROR": {
2575
- const e = new Error(error.message);
2576
- e.name = error.name;
2577
- e.stack = error.stackTrace;
2578
- return e;
2579
- }
2580
- case "STRING_ERROR": {
2581
- return error.raw;
2582
- }
2583
- case "CUSTOM_ERROR": {
2584
- return JSON.parse(error.raw);
2585
- }
2586
- case "INTERNAL_ERROR": {
2587
- return new Error(`trigger.dev internal error (${error.code})`);
2588
2483
  }
2589
2484
  }
2485
+ return result;
2590
2486
  }
2591
- __name(createErrorTaskError, "createErrorTaskError");
2592
- function correctErrorStackTrace(stackTrace, projectDir, options) {
2593
- const [errorLine, ...traceLines] = stackTrace.split("\n");
2594
- return [
2595
- options?.removeFirstLine ? void 0 : errorLine,
2596
- ...traceLines.map((line) => correctStackTraceLine(line, projectDir))
2597
- ].filter(Boolean).join("\n");
2598
- }
2599
- __name(correctErrorStackTrace, "correctErrorStackTrace");
2600
- function correctStackTraceLine(line, projectDir) {
2601
- const regex = /at (.*?) \(?file:\/\/(\/.*?\.ts):(\d+):(\d+)\)?/;
2602
- const match = regex.exec(line);
2603
- if (!match) {
2604
- return;
2605
- }
2606
- const [_, identifier, path, lineNum, colNum] = match;
2607
- if (!path) {
2608
- return;
2609
- }
2610
- if (nodePath__default.default.basename(path) === "__entryPoint.ts") {
2611
- return;
2612
- }
2613
- if (projectDir && !path.includes(projectDir)) {
2614
- return;
2615
- }
2616
- return line;
2617
- }
2618
- __name(correctStackTraceLine, "correctStackTraceLine");
2619
-
2620
- // src/v3/utils/platform.ts
2621
- var _globalThis = typeof globalThis === "object" ? globalThis : global;
2622
-
2623
- // src/v3/utils/globals.ts
2624
- var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
2625
- var _global = _globalThis;
2626
- function registerGlobal(type, instance, allowOverride = false) {
2627
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
2628
- if (!allowOverride && api[type]) {
2629
- return false;
2630
- }
2631
- api[type] = instance;
2632
- return true;
2633
- }
2634
- __name(registerGlobal, "registerGlobal");
2635
- function getGlobal(type) {
2636
- return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
2637
- }
2638
- __name(getGlobal, "getGlobal");
2639
- function unregisterGlobal(type) {
2640
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
2641
- if (api) {
2642
- delete api[type];
2643
- }
2487
+ __name(flattenAttributes, "flattenAttributes");
2488
+ function isRecord(value) {
2489
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2644
2490
  }
2645
- __name(unregisterGlobal, "unregisterGlobal");
2646
-
2647
- // src/v3/runtime/noopRuntimeManager.ts
2648
- var _NoopRuntimeManager = class _NoopRuntimeManager {
2649
- disable() {
2650
- }
2651
- registerTasks() {
2652
- }
2653
- getTaskMetadata(id) {
2654
- return void 0;
2655
- }
2656
- waitForDuration(ms) {
2657
- return Promise.resolve();
2658
- }
2659
- waitUntil(date) {
2660
- return Promise.resolve();
2491
+ __name(isRecord, "isRecord");
2492
+ function unflattenAttributes(obj) {
2493
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
2494
+ return obj;
2661
2495
  }
2662
- waitForTask(params) {
2663
- return Promise.resolve({
2664
- ok: false,
2665
- id: params.id,
2666
- error: {
2667
- type: "INTERNAL_ERROR",
2668
- code: "CONFIGURED_INCORRECTLY"
2496
+ const result = {};
2497
+ for (const [key, value] of Object.entries(obj)) {
2498
+ const parts = key.split(".").reduce((acc, part) => {
2499
+ if (detectIsArrayIndex(part)) {
2500
+ acc.push(part);
2501
+ } else {
2502
+ acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
2669
2503
  }
2670
- });
2671
- }
2672
- waitForBatch(params) {
2673
- return Promise.resolve({
2674
- id: params.id,
2675
- items: []
2676
- });
2677
- }
2678
- };
2679
- __name(_NoopRuntimeManager, "NoopRuntimeManager");
2680
- var NoopRuntimeManager = _NoopRuntimeManager;
2681
-
2682
- // src/v3/runtime/index.ts
2683
- var API_NAME = "runtime";
2684
- var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
2685
- var _getRuntimeManager, getRuntimeManager_fn;
2686
- var _RuntimeAPI = class _RuntimeAPI {
2687
- constructor() {
2688
- __privateAdd(this, _getRuntimeManager);
2689
- }
2690
- static getInstance() {
2691
- if (!this._instance) {
2692
- this._instance = new _RuntimeAPI();
2504
+ return acc;
2505
+ }, []);
2506
+ let current = result;
2507
+ for (let i = 0; i < parts.length - 1; i++) {
2508
+ const part = parts[i];
2509
+ const isArray = detectIsArrayIndex(part);
2510
+ const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
2511
+ const nextIsArray = detectIsArrayIndex(parts[i + 1]);
2512
+ if (!current[cleanPart]) {
2513
+ current[cleanPart] = nextIsArray ? [] : {};
2514
+ }
2515
+ current = current[cleanPart];
2693
2516
  }
2694
- return this._instance;
2695
- }
2696
- waitForDuration(ms) {
2697
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
2698
- }
2699
- waitUntil(date) {
2700
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
2701
- }
2702
- waitForTask(params) {
2703
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
2704
- }
2705
- waitForBatch(params) {
2706
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
2707
- }
2708
- setGlobalRuntimeManager(runtimeManager) {
2709
- return registerGlobal(API_NAME, runtimeManager);
2710
- }
2711
- disable() {
2712
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2713
- unregisterGlobal(API_NAME);
2714
- }
2715
- registerTasks(tasks) {
2716
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).registerTasks(tasks);
2717
- }
2718
- getTaskMetadata(id) {
2719
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).getTaskMetadata(id);
2720
- }
2721
- };
2722
- _getRuntimeManager = new WeakSet();
2723
- getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
2724
- return getGlobal(API_NAME) ?? NOOP_RUNTIME_MANAGER;
2725
- }, "#getRuntimeManager");
2726
- __name(_RuntimeAPI, "RuntimeAPI");
2727
- var RuntimeAPI = _RuntimeAPI;
2728
-
2729
- // src/v3/runtime-api.ts
2730
- var runtime = RuntimeAPI.getInstance();
2731
- function iconStringForSeverity(severityNumber) {
2732
- switch (severityNumber) {
2733
- case apiLogs.SeverityNumber.UNSPECIFIED:
2734
- return void 0;
2735
- case apiLogs.SeverityNumber.TRACE:
2736
- case apiLogs.SeverityNumber.TRACE2:
2737
- case apiLogs.SeverityNumber.TRACE3:
2738
- case apiLogs.SeverityNumber.TRACE4:
2739
- return "trace";
2740
- case apiLogs.SeverityNumber.DEBUG:
2741
- case apiLogs.SeverityNumber.DEBUG2:
2742
- case apiLogs.SeverityNumber.DEBUG3:
2743
- case apiLogs.SeverityNumber.DEBUG4:
2744
- return "debug";
2745
- case apiLogs.SeverityNumber.INFO:
2746
- case apiLogs.SeverityNumber.INFO2:
2747
- case apiLogs.SeverityNumber.INFO3:
2748
- case apiLogs.SeverityNumber.INFO4:
2749
- return "info";
2750
- case apiLogs.SeverityNumber.WARN:
2751
- case apiLogs.SeverityNumber.WARN2:
2752
- case apiLogs.SeverityNumber.WARN3:
2753
- case apiLogs.SeverityNumber.WARN4:
2754
- return "warn";
2755
- case apiLogs.SeverityNumber.ERROR:
2756
- case apiLogs.SeverityNumber.ERROR2:
2757
- case apiLogs.SeverityNumber.ERROR3:
2758
- case apiLogs.SeverityNumber.ERROR4:
2759
- return "error";
2760
- case apiLogs.SeverityNumber.FATAL:
2761
- case apiLogs.SeverityNumber.FATAL2:
2762
- case apiLogs.SeverityNumber.FATAL3:
2763
- case apiLogs.SeverityNumber.FATAL4:
2764
- return "fatal";
2517
+ const lastPart = parts[parts.length - 1];
2518
+ const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
2519
+ current[cleanLastPart] = value;
2765
2520
  }
2521
+ return result;
2766
2522
  }
2767
- __name(iconStringForSeverity, "iconStringForSeverity");
2768
- var _SimpleClock = class _SimpleClock {
2769
- preciseNow() {
2770
- const now = new preciseDate.PreciseDate();
2771
- const nowStruct = now.toStruct();
2772
- return [
2773
- nowStruct.seconds,
2774
- nowStruct.nanos
2775
- ];
2776
- }
2777
- reset() {
2778
- }
2779
- };
2780
- __name(_SimpleClock, "SimpleClock");
2781
- var SimpleClock = _SimpleClock;
2782
-
2783
- // src/v3/clock/index.ts
2784
- var API_NAME2 = "clock";
2785
- var SIMPLE_CLOCK = new SimpleClock();
2786
- var _getClock, getClock_fn;
2787
- var _ClockAPI = class _ClockAPI {
2788
- constructor() {
2789
- __privateAdd(this, _getClock);
2790
- }
2791
- static getInstance() {
2792
- if (!this._instance) {
2793
- this._instance = new _ClockAPI();
2794
- }
2795
- return this._instance;
2796
- }
2797
- setGlobalClock(clock2) {
2798
- return registerGlobal(API_NAME2, clock2);
2799
- }
2800
- preciseNow() {
2801
- return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2802
- }
2803
- reset() {
2804
- __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2805
- }
2806
- };
2807
- _getClock = new WeakSet();
2808
- getClock_fn = /* @__PURE__ */ __name(function() {
2809
- return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2810
- }, "#getClock");
2811
- __name(_ClockAPI, "ClockAPI");
2812
- var ClockAPI = _ClockAPI;
2813
-
2814
- // src/v3/clock-api.ts
2815
- var clock = ClockAPI.getInstance();
2816
-
2817
- // src/v3/logger/taskLogger.ts
2818
- var logLevels = [
2819
- "error",
2820
- "warn",
2821
- "log",
2822
- "info",
2823
- "debug"
2824
- ];
2825
- var _emitLog, emitLog_fn, _getTimestampInHrTime, getTimestampInHrTime_fn;
2826
- var _OtelTaskLogger = class _OtelTaskLogger {
2827
- constructor(_config) {
2828
- __privateAdd(this, _emitLog);
2829
- __privateAdd(this, _getTimestampInHrTime);
2830
- this._config = _config;
2831
- this._level = logLevels.indexOf(_config.level);
2832
- }
2833
- debug(message, properties) {
2834
- if (this._level < 4)
2835
- return;
2836
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "debug", apiLogs.SeverityNumber.DEBUG, properties);
2837
- }
2838
- log(message, properties) {
2839
- if (this._level < 2)
2840
- return;
2841
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "log", apiLogs.SeverityNumber.INFO, properties);
2842
- }
2843
- info(message, properties) {
2844
- if (this._level < 3)
2845
- return;
2846
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "info", apiLogs.SeverityNumber.INFO, properties);
2847
- }
2848
- warn(message, properties) {
2849
- if (this._level < 1)
2850
- return;
2851
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "warn", apiLogs.SeverityNumber.WARN, properties);
2523
+ __name(unflattenAttributes, "unflattenAttributes");
2524
+ function detectIsArrayIndex(key) {
2525
+ const match = key.match(/^\[(\d+)\]$/);
2526
+ if (match) {
2527
+ return true;
2852
2528
  }
2853
- error(message, properties) {
2854
- if (this._level < 0)
2855
- return;
2856
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "error", apiLogs.SeverityNumber.ERROR, properties);
2529
+ return false;
2530
+ }
2531
+ __name(detectIsArrayIndex, "detectIsArrayIndex");
2532
+ function primitiveValueOrflattenedAttributes(obj, prefix) {
2533
+ if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
2534
+ return obj;
2857
2535
  }
2858
- trace(name, fn, options) {
2859
- return this._config.tracer.startActiveSpan(name, fn, options);
2536
+ const attributes = flattenAttributes(obj, prefix);
2537
+ if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
2538
+ return attributes[prefix];
2860
2539
  }
2861
- };
2862
- _emitLog = new WeakSet();
2863
- emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
2864
- let attributes = {
2865
- ...flattenAttributes(properties)
2866
- };
2867
- const icon = iconStringForSeverity(severityNumber);
2868
- if (icon !== void 0) {
2869
- attributes[SemanticInternalAttributes.STYLE_ICON] = icon;
2870
- }
2871
- this._config.logger.emit({
2872
- severityNumber,
2873
- severityText,
2874
- body: message,
2875
- attributes,
2876
- timestamp
2877
- });
2878
- }, "#emitLog");
2879
- _getTimestampInHrTime = new WeakSet();
2880
- getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
2881
- return clock.preciseNow();
2882
- }, "#getTimestampInHrTime");
2883
- __name(_OtelTaskLogger, "OtelTaskLogger");
2884
- var OtelTaskLogger = _OtelTaskLogger;
2540
+ return attributes;
2541
+ }
2542
+ __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
2543
+
2544
+ // src/v3/logger/taskLogger.ts
2885
2545
  var _NoopTaskLogger = class _NoopTaskLogger {
2886
2546
  debug() {
2887
2547
  }
@@ -2949,666 +2609,302 @@ var LoggerAPI = _LoggerAPI;
2949
2609
  // src/v3/logger-api.ts
2950
2610
  var logger = LoggerAPI.getInstance();
2951
2611
 
2952
- // src/v3/limits.ts
2953
- var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2954
- var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
2955
- var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2956
- var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2957
- var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
2958
- var OTEL_LINK_COUNT_LIMIT = 2;
2959
- var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
2960
- var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
2961
- var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
2962
- function imposeAttributeLimits(attributes) {
2963
- const newAttributes = {};
2964
- for (const [key, value] of Object.entries(attributes)) {
2965
- if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
2966
- continue;
2967
- }
2968
- if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
2969
- break;
2970
- }
2971
- newAttributes[key] = value;
2972
- }
2973
- return newAttributes;
2974
- }
2975
- __name(imposeAttributeLimits, "imposeAttributeLimits");
2976
- function calculateAttributeValueLength(value) {
2977
- if (value === void 0 || value === null) {
2978
- return 0;
2979
- }
2980
- if (typeof value === "string") {
2981
- return value.length;
2982
- }
2983
- if (typeof value === "number") {
2984
- return 8;
2985
- }
2986
- if (typeof value === "boolean") {
2987
- return 4;
2988
- }
2989
- if (Array.isArray(value)) {
2990
- return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
2991
- }
2992
- return 0;
2993
- }
2994
- __name(calculateAttributeValueLength, "calculateAttributeValueLength");
2995
- function dateDifference(date1, date2) {
2996
- return Math.abs(date1.getTime() - date2.getTime());
2997
- }
2998
- __name(dateDifference, "dateDifference");
2999
- function formatDuration(start, end, options) {
3000
- if (!start || !end) {
3001
- return "\u2013";
3002
- }
3003
- return formatDurationMilliseconds(dateDifference(start, end), options);
3004
- }
3005
- __name(formatDuration, "formatDuration");
3006
- function nanosecondsToMilliseconds(nanoseconds) {
3007
- return nanoseconds / 1e6;
3008
- }
3009
- __name(nanosecondsToMilliseconds, "nanosecondsToMilliseconds");
3010
- function millisecondsToNanoseconds(milliseconds) {
3011
- return milliseconds * 1e6;
3012
- }
3013
- __name(millisecondsToNanoseconds, "millisecondsToNanoseconds");
3014
- function formatDurationNanoseconds(nanoseconds, options) {
3015
- return formatDurationMilliseconds(nanosecondsToMilliseconds(nanoseconds), options);
3016
- }
3017
- __name(formatDurationNanoseconds, "formatDurationNanoseconds");
3018
- var aboveOneSecondUnits = [
3019
- "d",
3020
- "h",
3021
- "m",
3022
- "s"
3023
- ];
3024
- var belowOneSecondUnits = [
3025
- "ms"
3026
- ];
3027
- function formatDurationMilliseconds(milliseconds, options) {
3028
- let duration = humanizeDuration__default.default(milliseconds, {
3029
- units: options?.units ? options.units : milliseconds < 1e3 ? belowOneSecondUnits : aboveOneSecondUnits,
3030
- maxDecimalPoints: options?.maxDecimalPoints ?? 1,
3031
- largest: 2
3032
- });
3033
- if (!options) {
3034
- return duration;
3035
- }
3036
- switch (options.style) {
3037
- case "short":
3038
- duration = duration.replace(" milliseconds", "ms");
3039
- duration = duration.replace(" millisecond", "ms");
3040
- duration = duration.replace(" seconds", "s");
3041
- duration = duration.replace(" second", "s");
3042
- duration = duration.replace(" minutes", "m");
3043
- duration = duration.replace(" minute", "m");
3044
- duration = duration.replace(" hours", "h");
3045
- duration = duration.replace(" hour", "h");
3046
- duration = duration.replace(" days", "d");
3047
- duration = duration.replace(" day", "d");
3048
- duration = duration.replace(" weeks", "w");
3049
- duration = duration.replace(" week", "w");
3050
- duration = duration.replace(" months", "mo");
3051
- duration = duration.replace(" month", "mo");
3052
- duration = duration.replace(" years", "y");
3053
- duration = duration.replace(" year", "y");
3054
- }
3055
- return duration;
3056
- }
3057
- __name(formatDurationMilliseconds, "formatDurationMilliseconds");
3058
- function formatDurationInDays(milliseconds) {
3059
- let duration = humanizeDuration__default.default(milliseconds, {
3060
- maxDecimalPoints: 0,
3061
- largest: 2,
3062
- units: [
3063
- "d"
3064
- ]
3065
- });
3066
- return duration;
3067
- }
3068
- __name(formatDurationInDays, "formatDurationInDays");
3069
-
3070
- // src/v3/runtime/devRuntimeManager.ts
3071
- var _DevRuntimeManager = class _DevRuntimeManager {
3072
- constructor() {
3073
- __publicField(this, "_taskWaits", /* @__PURE__ */ new Map());
3074
- __publicField(this, "_batchWaits", /* @__PURE__ */ new Map());
3075
- __publicField(this, "_tasks", /* @__PURE__ */ new Map());
3076
- __publicField(this, "_pendingCompletionNotifications", /* @__PURE__ */ new Map());
3077
- }
3078
- disable() {
3079
- }
3080
- registerTasks(tasks) {
3081
- for (const task of tasks) {
3082
- this._tasks.set(task.id, task);
3083
- }
3084
- }
3085
- getTaskMetadata(id) {
3086
- return this._tasks.get(id);
3087
- }
3088
- async waitForDuration(ms) {
3089
- return new Promise((resolve) => {
3090
- setTimeout(resolve, ms);
3091
- });
3092
- }
3093
- async waitUntil(date) {
3094
- return new Promise((resolve) => {
3095
- setTimeout(resolve, date.getTime() - Date.now());
3096
- });
3097
- }
3098
- async waitForTask(params) {
3099
- const pendingCompletion = this._pendingCompletionNotifications.get(params.id);
3100
- if (pendingCompletion) {
3101
- this._pendingCompletionNotifications.delete(params.id);
3102
- return pendingCompletion;
3103
- }
3104
- const promise = new Promise((resolve, reject) => {
3105
- this._taskWaits.set(params.id, {
3106
- resolve,
3107
- reject
3108
- });
3109
- });
3110
- return await promise;
3111
- }
3112
- async waitForBatch(params) {
3113
- if (!params.runs.length) {
3114
- return Promise.resolve({
3115
- id: params.id,
3116
- items: []
3117
- });
3118
- }
3119
- const promise = Promise.all(params.runs.map((runId) => {
3120
- return new Promise((resolve, reject) => {
3121
- const pendingCompletion = this._pendingCompletionNotifications.get(runId);
3122
- if (pendingCompletion) {
3123
- this._pendingCompletionNotifications.delete(runId);
3124
- if (pendingCompletion.ok) {
3125
- resolve(pendingCompletion);
3126
- } else {
3127
- reject(pendingCompletion);
3128
- }
3129
- return;
3130
- }
3131
- this._taskWaits.set(runId, {
3132
- resolve,
3133
- reject
3134
- });
3135
- });
3136
- }));
3137
- const results = await promise;
3138
- return {
3139
- id: params.id,
3140
- items: results
3141
- };
3142
- }
3143
- resumeTask(completion, execution) {
3144
- const wait = this._taskWaits.get(execution.run.id);
3145
- if (!wait) {
3146
- this._pendingCompletionNotifications.set(execution.run.id, completion);
3147
- return;
3148
- }
3149
- if (completion.ok) {
3150
- wait.resolve(completion);
3151
- } else {
3152
- wait.reject(completion);
3153
- }
3154
- this._taskWaits.delete(execution.run.id);
3155
- }
3156
- };
3157
- __name(_DevRuntimeManager, "DevRuntimeManager");
3158
- var DevRuntimeManager = _DevRuntimeManager;
3159
- var _ProdRuntimeManager = class _ProdRuntimeManager {
3160
- constructor(ipc, options = {}) {
3161
- this.ipc = ipc;
3162
- this.options = options;
3163
- this._taskWaits = /* @__PURE__ */ new Map();
3164
- this._batchWaits = /* @__PURE__ */ new Map();
3165
- this._tasks = /* @__PURE__ */ new Map();
3166
- }
2612
+ // src/v3/runtime/noopRuntimeManager.ts
2613
+ var _NoopRuntimeManager = class _NoopRuntimeManager {
3167
2614
  disable() {
3168
- }
3169
- registerTasks(tasks) {
3170
- for (const task of tasks) {
3171
- this._tasks.set(task.id, task);
3172
- }
3173
- }
3174
- getTaskMetadata(id) {
3175
- return this._tasks.get(id);
3176
- }
3177
- async waitForDuration(ms) {
3178
- const now = Date.now();
3179
- const resolveAfterDuration = promises.setTimeout(ms, "duration");
3180
- if (ms <= this.waitThresholdInMs) {
3181
- await resolveAfterDuration;
3182
- return;
3183
- }
3184
- const waitForRestore = new Promise((resolve, reject) => {
3185
- this._waitForRestore = {
3186
- resolve,
3187
- reject
3188
- };
3189
- });
3190
- const { willCheckpointAndRestore } = await this.ipc.sendWithAck("WAIT_FOR_DURATION", {
3191
- ms,
3192
- now
3193
- });
3194
- if (!willCheckpointAndRestore) {
3195
- await resolveAfterDuration;
3196
- return;
3197
- }
3198
- this.ipc.send("READY_FOR_CHECKPOINT", {});
3199
- await Promise.race([
3200
- waitForRestore,
3201
- resolveAfterDuration
3202
- ]);
3203
- this.ipc.send("CANCEL_CHECKPOINT", {});
3204
- }
3205
- resumeAfterRestore() {
3206
- if (!this._waitForRestore) {
3207
- return;
3208
- }
3209
- clock.reset();
3210
- this._waitForRestore.resolve("restore");
3211
- this._waitForRestore = void 0;
3212
- }
3213
- async waitUntil(date) {
3214
- return this.waitForDuration(date.getTime() - Date.now());
3215
- }
3216
- async waitForTask(params) {
3217
- const promise = new Promise((resolve, reject) => {
3218
- this._taskWaits.set(params.id, {
3219
- resolve,
3220
- reject
3221
- });
3222
- });
3223
- await this.ipc.send("WAIT_FOR_TASK", {
3224
- friendlyId: params.id
3225
- });
3226
- return await promise;
3227
- }
3228
- async waitForBatch(params) {
3229
- if (!params.runs.length) {
3230
- return Promise.resolve({
3231
- id: params.id,
3232
- items: []
3233
- });
3234
- }
3235
- const promise = Promise.all(params.runs.map((runId) => {
3236
- return new Promise((resolve, reject) => {
3237
- this._taskWaits.set(runId, {
3238
- resolve,
3239
- reject
3240
- });
3241
- });
3242
- }));
3243
- await this.ipc.send("WAIT_FOR_BATCH", {
3244
- batchFriendlyId: params.id,
3245
- runFriendlyIds: params.runs
3246
- });
3247
- const results = await promise;
3248
- return {
3249
- id: params.id,
3250
- items: results
3251
- };
3252
- }
3253
- resumeTask(completion, execution) {
3254
- const wait = this._taskWaits.get(execution.run.id);
3255
- if (!wait) {
3256
- return;
3257
- }
3258
- if (completion.ok) {
3259
- wait.resolve(completion);
3260
- } else {
3261
- wait.reject(completion);
3262
- }
3263
- this._taskWaits.delete(execution.run.id);
3264
- }
3265
- get waitThresholdInMs() {
3266
- return this.options.waitThresholdInMs ?? 3e4;
3267
- }
3268
- };
3269
- __name(_ProdRuntimeManager, "ProdRuntimeManager");
3270
- var ProdRuntimeManager = _ProdRuntimeManager;
3271
- var _originClockTime, originClockTime_get, _originPreciseDate, originPreciseDate_get;
3272
- var _PreciseWallClock = class _PreciseWallClock {
3273
- constructor(options = {}) {
3274
- __privateAdd(this, _originClockTime);
3275
- __privateAdd(this, _originPreciseDate);
3276
- this._origin = {
3277
- clockTime: options.origin ?? process.hrtime(),
3278
- preciseDate: options.now ?? new preciseDate.PreciseDate()
3279
- };
3280
- }
3281
- preciseNow() {
3282
- const elapsedHrTime = process.hrtime(__privateGet(this, _originClockTime, originClockTime_get));
3283
- const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
3284
- const preciseDate$1 = new preciseDate.PreciseDate(__privateGet(this, _originPreciseDate, originPreciseDate_get).getFullTime() + elapsedNanoseconds);
3285
- const dateStruct = preciseDate$1.toStruct();
3286
- return [
3287
- dateStruct.seconds,
3288
- dateStruct.nanos
3289
- ];
3290
- }
3291
- reset() {
3292
- this._origin = {
3293
- clockTime: process.hrtime(),
3294
- preciseDate: new preciseDate.PreciseDate()
3295
- };
3296
- }
3297
- };
3298
- _originClockTime = new WeakSet();
3299
- originClockTime_get = /* @__PURE__ */ __name(function() {
3300
- return this._origin.clockTime;
3301
- }, "#originClockTime");
3302
- _originPreciseDate = new WeakSet();
3303
- originPreciseDate_get = /* @__PURE__ */ __name(function() {
3304
- return this._origin.preciseDate;
3305
- }, "#originPreciseDate");
3306
- __name(_PreciseWallClock, "PreciseWallClock");
3307
- var PreciseWallClock = _PreciseWallClock;
3308
- var _TriggerTracer = class _TriggerTracer {
3309
- constructor(_config) {
3310
- this._config = _config;
3311
- }
3312
- get tracer() {
3313
- if (!this._tracer) {
3314
- if ("tracer" in this._config)
3315
- return this._config.tracer;
3316
- this._tracer = api.trace.getTracer(this._config.name, this._config.version);
3317
- }
3318
- return this._tracer;
3319
- }
3320
- get logger() {
3321
- if (!this._logger) {
3322
- if ("logger" in this._config)
3323
- return this._config.logger;
3324
- this._logger = apiLogs.logs.getLogger(this._config.name, this._config.version);
3325
- }
3326
- return this._logger;
3327
- }
3328
- extractContext(traceContext) {
3329
- return api.propagation.extract(api.context.active(), traceContext ?? {});
3330
- }
3331
- startActiveSpan(name, fn, options, ctx) {
3332
- const parentContext = ctx ?? api.context.active();
3333
- const attributes = options?.attributes ?? {};
3334
- return this.tracer.startActiveSpan(name, {
3335
- ...options,
3336
- attributes,
3337
- startTime: clock.preciseNow()
3338
- }, parentContext, async (span) => {
3339
- this.tracer.startSpan(name, {
3340
- ...options,
3341
- attributes: {
3342
- ...attributes,
3343
- [SemanticInternalAttributes.SPAN_PARTIAL]: true,
3344
- [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
3345
- }
3346
- }, parentContext).end();
3347
- try {
3348
- return await fn(span);
3349
- } catch (e) {
3350
- if (typeof e === "string" || e instanceof Error) {
3351
- span.recordException(e);
3352
- }
3353
- span.setStatus({
3354
- code: api.SpanStatusCode.ERROR
3355
- });
3356
- throw e;
3357
- } finally {
3358
- span.end(clock.preciseNow());
2615
+ }
2616
+ waitForDuration(ms) {
2617
+ return Promise.resolve();
2618
+ }
2619
+ waitUntil(date) {
2620
+ return Promise.resolve();
2621
+ }
2622
+ waitForTask(params) {
2623
+ return Promise.resolve({
2624
+ ok: false,
2625
+ id: params.id,
2626
+ error: {
2627
+ type: "INTERNAL_ERROR",
2628
+ code: "CONFIGURED_INCORRECTLY"
3359
2629
  }
3360
2630
  });
3361
2631
  }
3362
- startSpan(name, options, ctx) {
3363
- const parentContext = ctx ?? api.context.active();
3364
- const attributes = options?.attributes ?? {};
3365
- const span = this.tracer.startSpan(name, options, ctx);
3366
- this.tracer.startSpan(name, {
3367
- ...options,
3368
- attributes: {
3369
- ...attributes,
3370
- [SemanticInternalAttributes.SPAN_PARTIAL]: true,
3371
- [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
3372
- }
3373
- }, parentContext).end();
3374
- return span;
2632
+ waitForBatch(params) {
2633
+ return Promise.resolve({
2634
+ id: params.id,
2635
+ items: []
2636
+ });
3375
2637
  }
3376
2638
  };
3377
- __name(_TriggerTracer, "TriggerTracer");
3378
- var TriggerTracer = _TriggerTracer;
3379
- var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
3380
- var _ConsoleInterceptor = class _ConsoleInterceptor {
3381
- constructor(logger2) {
3382
- __privateAdd(this, _handleLog);
3383
- __privateAdd(this, _getTimestampInHrTime2);
3384
- __privateAdd(this, _getAttributes);
3385
- this.logger = logger2;
3386
- }
3387
- // Intercept the console and send logs to the OpenTelemetry logger
3388
- // during the execution of the callback
3389
- async intercept(console2, callback) {
3390
- const originalConsole = {
3391
- log: console2.log,
3392
- info: console2.info,
3393
- warn: console2.warn,
3394
- error: console2.error
3395
- };
3396
- console2.log = this.log.bind(this);
3397
- console2.info = this.info.bind(this);
3398
- console2.warn = this.warn.bind(this);
3399
- console2.error = this.error.bind(this);
3400
- try {
3401
- return await callback();
3402
- } finally {
3403
- console2.log = originalConsole.log;
3404
- console2.info = originalConsole.info;
3405
- console2.warn = originalConsole.warn;
3406
- console2.error = originalConsole.error;
2639
+ __name(_NoopRuntimeManager, "NoopRuntimeManager");
2640
+ var NoopRuntimeManager = _NoopRuntimeManager;
2641
+
2642
+ // src/v3/runtime/index.ts
2643
+ var API_NAME4 = "runtime";
2644
+ var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
2645
+ var _getRuntimeManager, getRuntimeManager_fn;
2646
+ var _RuntimeAPI = class _RuntimeAPI {
2647
+ constructor() {
2648
+ __privateAdd(this, _getRuntimeManager);
2649
+ }
2650
+ static getInstance() {
2651
+ if (!this._instance) {
2652
+ this._instance = new _RuntimeAPI();
3407
2653
  }
2654
+ return this._instance;
2655
+ }
2656
+ waitForDuration(ms) {
2657
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
2658
+ }
2659
+ waitUntil(date) {
2660
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
3408
2661
  }
3409
- log(...args) {
3410
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
2662
+ waitForTask(params) {
2663
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
3411
2664
  }
3412
- info(...args) {
3413
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Info", ...args);
2665
+ waitForBatch(params) {
2666
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
3414
2667
  }
3415
- warn(...args) {
3416
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.WARN, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Warn", ...args);
2668
+ setGlobalRuntimeManager(runtimeManager) {
2669
+ return registerGlobal(API_NAME4, runtimeManager);
3417
2670
  }
3418
- error(...args) {
3419
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.ERROR, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Error", ...args);
2671
+ disable() {
2672
+ __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2673
+ unregisterGlobal(API_NAME4);
3420
2674
  }
3421
2675
  };
3422
- _handleLog = new WeakSet();
3423
- handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
3424
- const body = util__default.default.format(...args);
3425
- const parsed = tryParseJSON(body);
3426
- if (parsed.ok) {
3427
- this.logger.emit({
3428
- severityNumber,
3429
- severityText,
3430
- body: getLogMessage(parsed.value, severityText),
3431
- attributes: {
3432
- ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3433
- ...flattenAttributes(parsed.value)
3434
- },
3435
- timestamp
3436
- });
3437
- return;
2676
+ _getRuntimeManager = new WeakSet();
2677
+ getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
2678
+ return getGlobal(API_NAME4) ?? NOOP_RUNTIME_MANAGER;
2679
+ }, "#getRuntimeManager");
2680
+ __name(_RuntimeAPI, "RuntimeAPI");
2681
+ var RuntimeAPI = _RuntimeAPI;
2682
+
2683
+ // src/v3/runtime-api.ts
2684
+ var runtime = RuntimeAPI.getInstance();
2685
+
2686
+ // src/v3/task-catalog/noopTaskCatalog.ts
2687
+ var _NoopTaskCatalog = class _NoopTaskCatalog {
2688
+ registerTaskMetadata(task) {
3438
2689
  }
3439
- this.logger.emit({
3440
- severityNumber,
3441
- severityText,
3442
- body,
3443
- attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3444
- timestamp
3445
- });
3446
- }, "#handleLog");
3447
- _getTimestampInHrTime2 = new WeakSet();
3448
- getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
3449
- return clock.preciseNow();
3450
- }, "#getTimestampInHrTime");
3451
- _getAttributes = new WeakSet();
3452
- getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
3453
- const icon = iconStringForSeverity(severityNumber1);
3454
- let result = {};
3455
- if (icon !== void 0) {
3456
- result[SemanticInternalAttributes.STYLE_ICON] = icon;
2690
+ registerTaskFileMetadata(id, metadata) {
3457
2691
  }
3458
- return result;
3459
- }, "#getAttributes");
3460
- __name(_ConsoleInterceptor, "ConsoleInterceptor");
3461
- var ConsoleInterceptor = _ConsoleInterceptor;
3462
- function getLogMessage(value, fallback) {
3463
- if (typeof value["message"] === "string") {
3464
- return value["message"];
2692
+ updateTaskMetadata(id, updates) {
2693
+ }
2694
+ getAllTaskMetadata() {
2695
+ return [];
3465
2696
  }
3466
- if (typeof value["msg"] === "string") {
3467
- return value["msg"];
2697
+ getTaskMetadata(id) {
2698
+ return void 0;
3468
2699
  }
3469
- if (typeof value["body"] === "string") {
3470
- return value["body"];
2700
+ getTask(id) {
2701
+ return void 0;
3471
2702
  }
3472
- if (typeof value["error"] === "string") {
3473
- return value["error"];
2703
+ taskExists(id) {
2704
+ return false;
3474
2705
  }
3475
- return fallback;
3476
- }
3477
- __name(getLogMessage, "getLogMessage");
3478
- function tryParseJSON(value) {
3479
- try {
3480
- const parsed = JSON.parse(value);
3481
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
3482
- return {
3483
- ok: true,
3484
- value: parsed
3485
- };
3486
- }
3487
- return {
3488
- ok: false,
3489
- value
3490
- };
3491
- } catch (e) {
3492
- return {
3493
- ok: false,
3494
- value
3495
- };
2706
+ disable() {
3496
2707
  }
3497
- }
3498
- __name(tryParseJSON, "tryParseJSON");
2708
+ };
2709
+ __name(_NoopTaskCatalog, "NoopTaskCatalog");
2710
+ var NoopTaskCatalog = _NoopTaskCatalog;
3499
2711
 
3500
- // src/retry.ts
3501
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
3502
- if (!resets)
3503
- return;
3504
- switch (format) {
3505
- case "iso_8601_duration_openai_variant": {
3506
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
3507
- }
3508
- case "iso_8601": {
3509
- return calculateISO8601ResetAt(resets, now);
3510
- }
3511
- case "unix_timestamp": {
3512
- return calculateUnixTimestampResetAt(resets, now);
3513
- }
3514
- case "unix_timestamp_in_ms": {
3515
- return calculateUnixTimestampInMsResetAt(resets, now);
2712
+ // src/v3/task-catalog/index.ts
2713
+ var API_NAME5 = "task-catalog";
2714
+ var NOOP_TASK_CATALOG = new NoopTaskCatalog();
2715
+ var _getCatalog, getCatalog_fn;
2716
+ var _TaskCatalogAPI = class _TaskCatalogAPI {
2717
+ constructor() {
2718
+ __privateAdd(this, _getCatalog);
2719
+ }
2720
+ static getInstance() {
2721
+ if (!this._instance) {
2722
+ this._instance = new _TaskCatalogAPI();
3516
2723
  }
2724
+ return this._instance;
2725
+ }
2726
+ setGlobalTaskCatalog(taskCatalog2) {
2727
+ return registerGlobal(API_NAME5, taskCatalog2);
2728
+ }
2729
+ disable() {
2730
+ unregisterGlobal(API_NAME5);
2731
+ }
2732
+ registerTaskMetadata(task) {
2733
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskMetadata(task);
2734
+ }
2735
+ updateTaskMetadata(id, updates) {
2736
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).updateTaskMetadata(id, updates);
2737
+ }
2738
+ registerTaskFileMetadata(id, metadata) {
2739
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskFileMetadata(id, metadata);
2740
+ }
2741
+ getAllTaskMetadata() {
2742
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getAllTaskMetadata();
2743
+ }
2744
+ getTaskMetadata(id) {
2745
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTaskMetadata(id);
2746
+ }
2747
+ getTask(id) {
2748
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTask(id);
3517
2749
  }
2750
+ taskExists(id) {
2751
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).taskExists(id);
2752
+ }
2753
+ };
2754
+ _getCatalog = new WeakSet();
2755
+ getCatalog_fn = /* @__PURE__ */ __name(function() {
2756
+ return getGlobal(API_NAME5) ?? NOOP_TASK_CATALOG;
2757
+ }, "#getCatalog");
2758
+ __name(_TaskCatalogAPI, "TaskCatalogAPI");
2759
+ var TaskCatalogAPI = _TaskCatalogAPI;
2760
+
2761
+ // src/v3/task-catalog-api.ts
2762
+ var taskCatalog = TaskCatalogAPI.getInstance();
2763
+ function dateDifference(date1, date2) {
2764
+ return Math.abs(date1.getTime() - date2.getTime());
3518
2765
  }
3519
- __name(calculateResetAt, "calculateResetAt");
3520
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
3521
- if (!resets)
3522
- return void 0;
3523
- const resetAt = parseInt(resets, 10);
3524
- if (isNaN(resetAt))
3525
- return void 0;
3526
- return new Date(resetAt * 1e3);
2766
+ __name(dateDifference, "dateDifference");
2767
+ function formatDuration(start, end, options) {
2768
+ if (!start || !end) {
2769
+ return "\u2013";
2770
+ }
2771
+ return formatDurationMilliseconds(dateDifference(start, end), options);
3527
2772
  }
3528
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
3529
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
3530
- if (!resets)
3531
- return void 0;
3532
- const resetAt = parseInt(resets, 10);
3533
- if (isNaN(resetAt))
3534
- return void 0;
3535
- return new Date(resetAt);
2773
+ __name(formatDuration, "formatDuration");
2774
+ function nanosecondsToMilliseconds(nanoseconds) {
2775
+ return nanoseconds / 1e6;
3536
2776
  }
3537
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
3538
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
3539
- if (!resets)
3540
- return void 0;
3541
- const resetAt = new Date(resets);
3542
- if (isNaN(resetAt.getTime()))
3543
- return void 0;
3544
- return resetAt;
2777
+ __name(nanosecondsToMilliseconds, "nanosecondsToMilliseconds");
2778
+ function millisecondsToNanoseconds(milliseconds) {
2779
+ return milliseconds * 1e6;
3545
2780
  }
3546
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
3547
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
3548
- if (!resets)
3549
- return void 0;
3550
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
3551
- const match = resets.match(pattern);
3552
- if (!match)
3553
- return void 0;
3554
- const days = parseInt(match[1], 10) || 0;
3555
- const hours = parseInt(match[2], 10) || 0;
3556
- const minutes = parseInt(match[3], 10) || 0;
3557
- const seconds = parseFloat(match[4]) || 0;
3558
- const milliseconds = parseInt(match[5], 10) || 0;
3559
- const resetAt = new Date(now);
3560
- resetAt.setDate(resetAt.getDate() + days);
3561
- resetAt.setHours(resetAt.getHours() + hours);
3562
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
3563
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
3564
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
3565
- return resetAt;
2781
+ __name(millisecondsToNanoseconds, "millisecondsToNanoseconds");
2782
+ function formatDurationNanoseconds(nanoseconds, options) {
2783
+ return formatDurationMilliseconds(nanosecondsToMilliseconds(nanoseconds), options);
3566
2784
  }
3567
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
3568
-
3569
- // src/v3/utils/retries.ts
3570
- var defaultRetryOptions = {
3571
- maxAttempts: 3,
3572
- factor: 2,
3573
- minTimeoutInMs: 1e3,
3574
- maxTimeoutInMs: 6e4,
3575
- randomize: true
3576
- };
3577
- var defaultFetchRetryOptions = {
3578
- byStatus: {
3579
- "429,408,409,5xx": {
3580
- strategy: "backoff",
3581
- ...defaultRetryOptions
3582
- }
3583
- },
3584
- connectionError: defaultRetryOptions,
3585
- timeout: defaultRetryOptions
3586
- };
3587
- function calculateNextRetryDelay(options, attempt) {
3588
- const opts = {
3589
- ...defaultRetryOptions,
3590
- ...options
3591
- };
3592
- if (attempt >= opts.maxAttempts) {
3593
- return;
2785
+ __name(formatDurationNanoseconds, "formatDurationNanoseconds");
2786
+ var aboveOneSecondUnits = [
2787
+ "d",
2788
+ "h",
2789
+ "m",
2790
+ "s"
2791
+ ];
2792
+ var belowOneSecondUnits = [
2793
+ "ms"
2794
+ ];
2795
+ function formatDurationMilliseconds(milliseconds, options) {
2796
+ let duration = humanizeDuration__default.default(milliseconds, {
2797
+ units: options?.units ? options.units : milliseconds < 1e3 ? belowOneSecondUnits : aboveOneSecondUnits,
2798
+ maxDecimalPoints: options?.maxDecimalPoints ?? 1,
2799
+ largest: 2
2800
+ });
2801
+ if (!options) {
2802
+ return duration;
2803
+ }
2804
+ switch (options.style) {
2805
+ case "short":
2806
+ duration = duration.replace(" milliseconds", "ms");
2807
+ duration = duration.replace(" millisecond", "ms");
2808
+ duration = duration.replace(" seconds", "s");
2809
+ duration = duration.replace(" second", "s");
2810
+ duration = duration.replace(" minutes", "m");
2811
+ duration = duration.replace(" minute", "m");
2812
+ duration = duration.replace(" hours", "h");
2813
+ duration = duration.replace(" hour", "h");
2814
+ duration = duration.replace(" days", "d");
2815
+ duration = duration.replace(" day", "d");
2816
+ duration = duration.replace(" weeks", "w");
2817
+ duration = duration.replace(" week", "w");
2818
+ duration = duration.replace(" months", "mo");
2819
+ duration = duration.replace(" month", "mo");
2820
+ duration = duration.replace(" years", "y");
2821
+ duration = duration.replace(" year", "y");
3594
2822
  }
3595
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
3596
- const random = randomize ? Math.random() + 1 : 1;
3597
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
3598
- return Math.round(timeout);
3599
- }
3600
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
3601
- function calculateResetAt2(resets, format, now = Date.now()) {
3602
- const resetAt = calculateResetAt(resets, format, new Date(now));
3603
- return resetAt?.getTime();
2823
+ return duration;
3604
2824
  }
3605
- __name(calculateResetAt2, "calculateResetAt");
3606
-
3607
- // src/v3/utils/styleAttributes.ts
3608
- function accessoryAttributes(accessory) {
3609
- return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
2825
+ __name(formatDurationMilliseconds, "formatDurationMilliseconds");
2826
+ function formatDurationInDays(milliseconds) {
2827
+ let duration = humanizeDuration__default.default(milliseconds, {
2828
+ maxDecimalPoints: 0,
2829
+ largest: 2,
2830
+ units: [
2831
+ "d"
2832
+ ]
2833
+ });
2834
+ return duration;
3610
2835
  }
3611
- __name(accessoryAttributes, "accessoryAttributes");
2836
+ __name(formatDurationInDays, "formatDurationInDays");
2837
+ var _TriggerTracer = class _TriggerTracer {
2838
+ constructor(_config) {
2839
+ this._config = _config;
2840
+ }
2841
+ get tracer() {
2842
+ if (!this._tracer) {
2843
+ if ("tracer" in this._config)
2844
+ return this._config.tracer;
2845
+ this._tracer = api.trace.getTracer(this._config.name, this._config.version);
2846
+ }
2847
+ return this._tracer;
2848
+ }
2849
+ get logger() {
2850
+ if (!this._logger) {
2851
+ if ("logger" in this._config)
2852
+ return this._config.logger;
2853
+ this._logger = apiLogs.logs.getLogger(this._config.name, this._config.version);
2854
+ }
2855
+ return this._logger;
2856
+ }
2857
+ extractContext(traceContext) {
2858
+ return api.propagation.extract(api.context.active(), traceContext ?? {});
2859
+ }
2860
+ startActiveSpan(name, fn, options, ctx) {
2861
+ const parentContext = ctx ?? api.context.active();
2862
+ const attributes = options?.attributes ?? {};
2863
+ return this.tracer.startActiveSpan(name, {
2864
+ ...options,
2865
+ attributes,
2866
+ startTime: clock.preciseNow()
2867
+ }, parentContext, async (span) => {
2868
+ this.tracer.startSpan(name, {
2869
+ ...options,
2870
+ attributes: {
2871
+ ...attributes,
2872
+ [SemanticInternalAttributes.SPAN_PARTIAL]: true,
2873
+ [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
2874
+ }
2875
+ }, parentContext).end();
2876
+ try {
2877
+ return await fn(span);
2878
+ } catch (e) {
2879
+ if (typeof e === "string" || e instanceof Error) {
2880
+ span.recordException(e);
2881
+ }
2882
+ span.setStatus({
2883
+ code: api.SpanStatusCode.ERROR
2884
+ });
2885
+ throw e;
2886
+ } finally {
2887
+ span.end(clock.preciseNow());
2888
+ }
2889
+ });
2890
+ }
2891
+ startSpan(name, options, ctx) {
2892
+ const parentContext = ctx ?? api.context.active();
2893
+ const attributes = options?.attributes ?? {};
2894
+ const span = this.tracer.startSpan(name, options, ctx);
2895
+ this.tracer.startSpan(name, {
2896
+ ...options,
2897
+ attributes: {
2898
+ ...attributes,
2899
+ [SemanticInternalAttributes.SPAN_PARTIAL]: true,
2900
+ [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
2901
+ }
2902
+ }, parentContext).end();
2903
+ return span;
2904
+ }
2905
+ };
2906
+ __name(_TriggerTracer, "TriggerTracer");
2907
+ var TriggerTracer = _TriggerTracer;
3612
2908
 
3613
2909
  // src/eventFilterMatches.ts
3614
2910
  function eventFilterMatches(payload, filter) {
@@ -3778,150 +3074,41 @@ function omit(obj, ...keys) {
3778
3074
  return result;
3779
3075
  }
3780
3076
  __name(omit, "omit");
3781
- var _a2;
3782
- var AsyncResourceDetector = (_a2 = class {
3783
- constructor() {
3784
- __publicField(this, "_resolved", false);
3785
- this._promise = new Promise((resolver) => {
3786
- this._resolver = resolver;
3787
- });
3788
- }
3789
- detect(_config) {
3790
- return new resources.Resource({}, this._promise);
3791
- }
3792
- resolveWithAttributes(attributes) {
3793
- if (!this._resolver) {
3794
- throw new Error("Resolver not available");
3795
- }
3796
- if (this._resolved) {
3797
- return;
3798
- }
3799
- this._resolved = true;
3800
- this._resolver(attributes);
3801
- }
3802
- }, __name(_a2, "AsyncResourceDetector"), _a2);
3803
- var _TracingSDK = class _TracingSDK {
3804
- constructor(config) {
3805
- this.config = config;
3806
- this.asyncResourceDetector = new AsyncResourceDetector();
3807
- setLogLevel(config.diagLogLevel ?? "none");
3808
- const envResourceAttributesSerialized = getEnvVar("OTEL_RESOURCE_ATTRIBUTES");
3809
- const envResourceAttributes = envResourceAttributesSerialized ? JSON.parse(envResourceAttributesSerialized) : {};
3810
- const commonResources = resources.detectResourcesSync({
3811
- detectors: [
3812
- this.asyncResourceDetector,
3813
- resources.processDetectorSync
3814
- ]
3815
- }).merge(new resources.Resource({
3816
- [semanticConventions.SemanticResourceAttributes.CLOUD_PROVIDER]: "trigger.dev",
3817
- [SemanticInternalAttributes.TRIGGER]: true
3818
- })).merge(config.resource ?? new resources.Resource({})).merge(new resources.Resource(envResourceAttributes));
3819
- const traceProvider = new sdkTraceNode.NodeTracerProvider({
3820
- forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
3821
- resource: commonResources,
3822
- spanLimits: {
3823
- attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
3824
- attributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
3825
- eventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT,
3826
- attributePerEventCountLimit: OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
3827
- linkCountLimit: OTEL_LINK_COUNT_LIMIT,
3828
- attributePerLinkCountLimit: OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT
3829
- }
3830
- });
3831
- const spanExporter = new exporterTraceOtlpHttp.OTLPTraceExporter({
3832
- url: `${config.url}/v1/traces`,
3833
- timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
3834
- });
3835
- traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkTraceNode.BatchSpanProcessor(spanExporter, {
3836
- maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
3837
- scheduledDelayMillis: parseInt(getEnvVar("OTEL_SPAN_SCHEDULED_DELAY_MILLIS") ?? "200"),
3838
- exportTimeoutMillis: parseInt(getEnvVar("OTEL_SPAN_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
3839
- maxQueueSize: parseInt(getEnvVar("OTEL_SPAN_MAX_QUEUE_SIZE") ?? "512")
3840
- }) : new sdkTraceNode.SimpleSpanProcessor(spanExporter)));
3841
- traceProvider.register();
3842
- instrumentation.registerInstrumentations({
3843
- instrumentations: config.instrumentations ?? [],
3844
- tracerProvider: traceProvider
3845
- });
3846
- const logExporter = new exporterLogsOtlpHttp.OTLPLogExporter({
3847
- url: `${config.url}/v1/logs`
3848
- });
3849
- const loggerProvider = new sdkLogs.LoggerProvider({
3850
- resource: commonResources,
3851
- logRecordLimits: {
3852
- attributeCountLimit: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
3853
- attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
3854
- }
3855
- });
3856
- loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkLogs.BatchLogRecordProcessor(logExporter, {
3857
- maxExportBatchSize: parseInt(getEnvVar("OTEL_LOG_MAX_EXPORT_BATCH_SIZE") ?? "64"),
3858
- scheduledDelayMillis: parseInt(getEnvVar("OTEL_LOG_SCHEDULED_DELAY_MILLIS") ?? "200"),
3859
- exportTimeoutMillis: parseInt(getEnvVar("OTEL_LOG_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
3860
- maxQueueSize: parseInt(getEnvVar("OTEL_LOG_MAX_QUEUE_SIZE") ?? "512")
3861
- }) : new sdkLogs.SimpleLogRecordProcessor(logExporter)));
3862
- this._logProvider = loggerProvider;
3863
- this._spanExporter = spanExporter;
3864
- this._traceProvider = traceProvider;
3865
- apiLogs.logs.setGlobalLoggerProvider(loggerProvider);
3866
- this.getLogger = loggerProvider.getLogger.bind(loggerProvider);
3867
- this.getTracer = traceProvider.getTracer.bind(traceProvider);
3868
- }
3869
- async flush() {
3870
- await this._spanExporter.forceFlush?.();
3871
- await this._logProvider.forceFlush();
3872
- }
3873
- async shutdown() {
3874
- await this._spanExporter.shutdown();
3875
- await this._logProvider.shutdown();
3876
- }
3877
- };
3878
- __name(_TracingSDK, "TracingSDK");
3879
- var TracingSDK = _TracingSDK;
3880
- function setLogLevel(level) {
3881
- let diagLogLevel;
3882
- switch (level) {
3883
- case "none":
3884
- diagLogLevel = api.DiagLogLevel.NONE;
3885
- break;
3886
- case "error":
3887
- diagLogLevel = api.DiagLogLevel.ERROR;
3888
- break;
3889
- case "warn":
3890
- diagLogLevel = api.DiagLogLevel.WARN;
3891
- break;
3892
- case "info":
3893
- diagLogLevel = api.DiagLogLevel.INFO;
3894
- break;
3895
- case "debug":
3896
- diagLogLevel = api.DiagLogLevel.DEBUG;
3897
- break;
3898
- case "verbose":
3899
- diagLogLevel = api.DiagLogLevel.VERBOSE;
3900
- break;
3901
- case "all":
3902
- diagLogLevel = api.DiagLogLevel.ALL;
3903
- break;
3904
- default:
3905
- diagLogLevel = api.DiagLogLevel.NONE;
3906
- }
3907
- api.diag.setLogger(new api.DiagConsoleLogger(), diagLogLevel);
3077
+
3078
+ // src/v3/utils/styleAttributes.ts
3079
+ function accessoryAttributes(accessory) {
3080
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
3908
3081
  }
3909
- __name(setLogLevel, "setLogLevel");
3082
+ __name(accessoryAttributes, "accessoryAttributes");
3910
3083
 
3911
- // src/v3/otel/index.ts
3912
- function recordSpanException(span, error) {
3913
- if (error instanceof Error) {
3914
- span.recordException(error);
3915
- } else if (typeof error === "string") {
3916
- span.recordException(new Error(error));
3917
- } else {
3918
- span.recordException(new Error(JSON.stringify(error)));
3919
- }
3920
- span.setStatus({
3921
- code: api.SpanStatusCode.ERROR
3922
- });
3084
+ // package.json
3085
+ var dependencies = {
3086
+ "@google-cloud/precise-date": "^4.0.0",
3087
+ "@opentelemetry/api": "^1.8.0",
3088
+ "@opentelemetry/api-logs": "^0.48.0",
3089
+ "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
3090
+ "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
3091
+ "@opentelemetry/instrumentation": "^0.49.1",
3092
+ "@opentelemetry/resources": "^1.22.0",
3093
+ "@opentelemetry/sdk-logs": "^0.49.1",
3094
+ "@opentelemetry/sdk-node": "^0.49.1",
3095
+ "@opentelemetry/sdk-trace-base": "^1.22.0",
3096
+ "@opentelemetry/sdk-trace-node": "^1.22.0",
3097
+ "@opentelemetry/semantic-conventions": "^1.22.0",
3098
+ "humanize-duration": "^3.27.3",
3099
+ superjson: "^2.2.1",
3100
+ ulidx: "^2.2.1",
3101
+ zod: "3.22.3",
3102
+ "zod-error": "1.5.0",
3103
+ "zod-validation-error": "^1.5.0",
3104
+ "socket.io-client": "4.7.4"
3105
+ };
3106
+
3107
+ // src/v3/utils/detectDependencyVersion.ts
3108
+ function detectDependencyVersion(dependency) {
3109
+ return dependencies[dependency];
3923
3110
  }
3924
- __name(recordSpanException, "recordSpanException");
3111
+ __name(detectDependencyVersion, "detectDependencyVersion");
3925
3112
 
3926
3113
  // src/v3/utils/ioSerialization.ts
3927
3114
  async function parsePacket(value) {
@@ -3964,6 +3151,7 @@ async function stringifyIO(value) {
3964
3151
  };
3965
3152
  } catch {
3966
3153
  return {
3154
+ data: value,
3967
3155
  dataType: "application/json"
3968
3156
  };
3969
3157
  }
@@ -4008,23 +3196,20 @@ __name(packetRequiresOffloading, "packetRequiresOffloading");
4008
3196
  async function exportPacket(packet, pathPrefix) {
4009
3197
  const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
4010
3198
  const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
4011
- if (presignedResponse.ok) {
4012
- const uploadResponse = await fetch(presignedResponse.data.presignedUrl, {
4013
- method: "PUT",
4014
- headers: {
4015
- "Content-Type": packet.dataType
4016
- },
4017
- body: packet.data
4018
- });
4019
- if (!uploadResponse.ok) {
4020
- throw new Error(`Failed to upload output to ${presignedResponse.data.presignedUrl}: ${uploadResponse.statusText}`);
4021
- }
4022
- return {
4023
- data: filename,
4024
- dataType: "application/store"
4025
- };
3199
+ const uploadResponse = await fetch(presignedResponse.presignedUrl, {
3200
+ method: "PUT",
3201
+ headers: {
3202
+ "Content-Type": packet.dataType
3203
+ },
3204
+ body: packet.data
3205
+ });
3206
+ if (!uploadResponse.ok) {
3207
+ throw new Error(`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`);
4026
3208
  }
4027
- return packet;
3209
+ return {
3210
+ data: filename,
3211
+ dataType: "application/store"
3212
+ };
4028
3213
  }
4029
3214
  __name(exportPacket, "exportPacket");
4030
3215
  async function conditionallyImportPacket(packet, tracer) {
@@ -4053,19 +3238,16 @@ async function importPacket(packet, span) {
4053
3238
  return packet;
4054
3239
  }
4055
3240
  const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
4056
- if (presignedResponse.ok) {
4057
- const response = await fetch(presignedResponse.data.presignedUrl);
4058
- if (!response.ok) {
4059
- throw new Error(`Failed to import packet ${presignedResponse.data.presignedUrl}: ${response.statusText}`);
4060
- }
4061
- const data = await response.text();
4062
- span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4063
- return {
4064
- data,
4065
- dataType: response.headers.get("content-type") ?? "application/json"
4066
- };
3241
+ const response = await fetch(presignedResponse.presignedUrl);
3242
+ if (!response.ok) {
3243
+ throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
4067
3244
  }
4068
- return packet;
3245
+ const data = await response.text();
3246
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
3247
+ return {
3248
+ data,
3249
+ dataType: response.headers.get("content-type") ?? "application/json"
3250
+ };
4069
3251
  }
4070
3252
  __name(importPacket, "importPacket");
4071
3253
  async function createPacketAttributes(packet, dataKey, dataTypeKey) {
@@ -4118,7 +3300,7 @@ async function createPacketAttributesAsJson(data, dataType) {
4118
3300
  case "application/super+json":
4119
3301
  const { deserialize } = await loadSuperJSON();
4120
3302
  const deserialized = deserialize(data);
4121
- const jsonify = safeJsonParse(JSON.stringify(deserialized, safeReplacer));
3303
+ const jsonify = safeJsonParse2(JSON.stringify(deserialized, safeReplacer));
4122
3304
  return imposeAttributeLimits(flattenAttributes(jsonify, void 0));
4123
3305
  case "application/store":
4124
3306
  return data;
@@ -4132,10 +3314,16 @@ async function prettyPrintPacket(rawData, dataType) {
4132
3314
  return "";
4133
3315
  }
4134
3316
  if (dataType === "application/super+json") {
3317
+ if (typeof rawData === "string") {
3318
+ rawData = safeJsonParse2(rawData);
3319
+ }
4135
3320
  const { deserialize } = await loadSuperJSON();
4136
3321
  return await prettyPrintPacket(deserialize(rawData), "application/json");
4137
3322
  }
4138
3323
  if (dataType === "application/json") {
3324
+ if (typeof rawData === "string") {
3325
+ rawData = safeJsonParse2(rawData);
3326
+ }
4139
3327
  return JSON.stringify(rawData, safeReplacer, 2);
4140
3328
  }
4141
3329
  if (typeof rawData === "string") {
@@ -4181,325 +3369,42 @@ async function loadSuperJSON() {
4181
3369
  return await import('superjson');
4182
3370
  }
4183
3371
  __name(loadSuperJSON, "loadSuperJSON");
4184
- function safeJsonParse(value) {
3372
+ function safeJsonParse2(value) {
4185
3373
  try {
4186
3374
  return JSON.parse(value);
4187
3375
  } catch {
4188
3376
  return;
4189
3377
  }
4190
3378
  }
4191
- __name(safeJsonParse, "safeJsonParse");
4192
-
4193
- // src/v3/workers/taskExecutor.ts
4194
- var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
4195
- var _TaskExecutor = class _TaskExecutor {
4196
- constructor(task, options) {
4197
- __privateAdd(this, _callRun);
4198
- __privateAdd(this, _callTaskInit);
4199
- __privateAdd(this, _callTaskCleanup);
4200
- __privateAdd(this, _handleError);
4201
- this.task = task;
4202
- this._tracingSDK = options.tracingSDK;
4203
- this._tracer = options.tracer;
4204
- this._consoleInterceptor = options.consoleInterceptor;
4205
- this._config = options.projectConfig;
4206
- this._importedConfig = options.importedConfig;
4207
- this._handleErrorFn = options.handleErrorFn;
4208
- }
4209
- async execute(execution, worker, traceContext) {
4210
- const ctx = TaskRunContext.parse(execution);
4211
- const attemptMessage = `Attempt ${execution.attempt.number}`;
4212
- const originalPacket = {
4213
- data: execution.run.payload,
4214
- dataType: execution.run.payloadType
4215
- };
4216
- const result = await taskContextManager.runWith({
4217
- ctx,
4218
- worker
4219
- }, async () => {
4220
- this._tracingSDK.asyncResourceDetector.resolveWithAttributes({
4221
- ...taskContextManager.attributes,
4222
- [SemanticInternalAttributes.SDK_VERSION]: this.task.packageVersion,
4223
- [SemanticInternalAttributes.SDK_LANGUAGE]: "typescript"
4224
- });
4225
- return await this._tracer.startActiveSpan(attemptMessage, async (span) => {
4226
- return await this._consoleInterceptor.intercept(console, async () => {
4227
- let parsedPayload;
4228
- let initOutput;
4229
- try {
4230
- const payloadPacket = await conditionallyImportPacket(originalPacket, this._tracer);
4231
- parsedPayload = await parsePacket(payloadPacket);
4232
- initOutput = await __privateMethod(this, _callTaskInit, callTaskInit_fn).call(this, parsedPayload, ctx);
4233
- const output = await __privateMethod(this, _callRun, callRun_fn).call(this, parsedPayload, ctx, initOutput);
4234
- try {
4235
- const stringifiedOutput = await stringifyIO(output);
4236
- const finalOutput = await conditionallyExportPacket(stringifiedOutput, `${execution.attempt.id}/output`, this._tracer);
4237
- const attributes = await createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE);
4238
- if (attributes) {
4239
- span.setAttributes(attributes);
4240
- }
4241
- return {
4242
- ok: true,
4243
- id: execution.attempt.id,
4244
- output: finalOutput.data,
4245
- outputType: finalOutput.dataType
4246
- };
4247
- } catch (stringifyError) {
4248
- recordSpanException(span, stringifyError);
4249
- return {
4250
- ok: false,
4251
- id: execution.attempt.id,
4252
- error: {
4253
- type: "INTERNAL_ERROR",
4254
- code: TaskRunErrorCodes.TASK_OUTPUT_ERROR,
4255
- message: stringifyError instanceof Error ? stringifyError.message : typeof stringifyError === "string" ? stringifyError : void 0
4256
- }
4257
- };
4258
- }
4259
- } catch (runError) {
4260
- try {
4261
- const handleErrorResult = await __privateMethod(this, _handleError, handleError_fn).call(this, execution, runError, parsedPayload, ctx);
4262
- recordSpanException(span, handleErrorResult.error ?? runError);
4263
- return {
4264
- id: execution.attempt.id,
4265
- ok: false,
4266
- error: handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError),
4267
- retry: handleErrorResult.status === "retry" ? handleErrorResult.retry : void 0,
4268
- skippedRetrying: handleErrorResult.status === "skipped"
4269
- };
4270
- } catch (handleErrorError) {
4271
- recordSpanException(span, handleErrorError);
4272
- return {
4273
- ok: false,
4274
- id: execution.attempt.id,
4275
- error: {
4276
- type: "INTERNAL_ERROR",
4277
- code: TaskRunErrorCodes.HANDLE_ERROR_ERROR,
4278
- message: handleErrorError instanceof Error ? handleErrorError.message : typeof handleErrorError === "string" ? handleErrorError : void 0
4279
- }
4280
- };
4281
- }
4282
- } finally {
4283
- await __privateMethod(this, _callTaskCleanup, callTaskCleanup_fn).call(this, parsedPayload, ctx, initOutput);
4284
- }
4285
- });
4286
- }, {
4287
- kind: api.SpanKind.CONSUMER,
4288
- attributes: {
4289
- [SemanticInternalAttributes.STYLE_ICON]: "attempt",
4290
- ...accessoryAttributes({
4291
- items: [
4292
- {
4293
- text: ctx.task.filePath
4294
- },
4295
- {
4296
- text: `${ctx.task.exportName}.run()`
4297
- }
4298
- ],
4299
- style: "codepath"
4300
- })
4301
- }
4302
- }, this._tracer.extractContext(traceContext));
4303
- });
4304
- return result;
4305
- }
4306
- };
4307
- _callRun = new WeakSet();
4308
- callRun_fn = /* @__PURE__ */ __name(async function(payload, ctx, init) {
4309
- const runFn = this.task.fns.run;
4310
- const middlewareFn = this.task.fns.middleware;
4311
- if (!runFn) {
4312
- throw new Error("Task does not have a run function");
4313
- }
4314
- if (!middlewareFn) {
4315
- return runFn(payload, {
4316
- ctx
4317
- });
4318
- }
4319
- return middlewareFn(payload, {
4320
- ctx,
4321
- next: async () => runFn(payload, {
4322
- ctx,
4323
- init
4324
- })
4325
- });
4326
- }, "#callRun");
4327
- _callTaskInit = new WeakSet();
4328
- callTaskInit_fn = /* @__PURE__ */ __name(async function(payload1, ctx1) {
4329
- const initFn = this.task.fns.init;
4330
- if (!initFn) {
4331
- return {};
4332
- }
4333
- return this._tracer.startActiveSpan("init", async (span) => {
4334
- return await initFn(payload1, {
4335
- ctx: ctx1
4336
- });
4337
- });
4338
- }, "#callTaskInit");
4339
- _callTaskCleanup = new WeakSet();
4340
- callTaskCleanup_fn = /* @__PURE__ */ __name(async function(payload2, ctx2, init1) {
4341
- const cleanupFn = this.task.fns.cleanup;
4342
- if (!cleanupFn) {
4343
- return;
4344
- }
4345
- return this._tracer.startActiveSpan("cleanup", async (span) => {
4346
- return await cleanupFn(payload2, {
4347
- ctx: ctx2,
4348
- init: init1
4349
- });
4350
- });
4351
- }, "#callTaskCleanup");
4352
- _handleError = new WeakSet();
4353
- handleError_fn = /* @__PURE__ */ __name(async function(execution, error, payload3, ctx3) {
4354
- const retriesConfig = this._importedConfig?.retries ?? this._config.retries;
4355
- const retry = this.task.retry ?? retriesConfig?.default;
4356
- if (!retry) {
4357
- return {
4358
- status: "noop"
4359
- };
4360
- }
4361
- const delay = calculateNextRetryDelay(retry, execution.attempt.number);
4362
- if (execution.environment.type === "DEVELOPMENT" && typeof retriesConfig?.enabledInDev === "boolean" && !retriesConfig.enabledInDev) {
4363
- return {
4364
- status: "skipped"
4365
- };
4366
- }
4367
- return this._tracer.startActiveSpan("handleError()", async (span) => {
4368
- const handleErrorResult = this.task.fns.handleError ? await this.task.fns.handleError(payload3, error, {
4369
- ctx: ctx3,
4370
- retry,
4371
- retryDelayInMs: delay,
4372
- retryAt: delay ? new Date(Date.now() + delay) : void 0
4373
- }) : this._importedConfig ? await this._handleErrorFn?.(payload3, error, {
4374
- ctx: ctx3,
4375
- retry,
4376
- retryDelayInMs: delay,
4377
- retryAt: delay ? new Date(Date.now() + delay) : void 0
4378
- }) : void 0;
4379
- if (!handleErrorResult) {
4380
- return typeof delay === "undefined" ? {
4381
- status: "noop"
4382
- } : {
4383
- status: "retry",
4384
- retry: {
4385
- timestamp: Date.now() + delay,
4386
- delay
4387
- }
4388
- };
4389
- }
4390
- if (handleErrorResult.skipRetrying) {
4391
- return {
4392
- status: "skipped",
4393
- error: handleErrorResult.error
4394
- };
4395
- }
4396
- if (typeof handleErrorResult.retryAt !== "undefined") {
4397
- return {
4398
- status: "retry",
4399
- retry: {
4400
- timestamp: handleErrorResult.retryAt.getTime(),
4401
- delay: handleErrorResult.retryAt.getTime() - Date.now()
4402
- },
4403
- error: handleErrorResult.error
4404
- };
4405
- }
4406
- if (typeof handleErrorResult.retryDelayInMs === "number") {
4407
- return {
4408
- status: "retry",
4409
- retry: {
4410
- timestamp: Date.now() + handleErrorResult.retryDelayInMs,
4411
- delay: handleErrorResult.retryDelayInMs
4412
- },
4413
- error: handleErrorResult.error
4414
- };
4415
- }
4416
- if (handleErrorResult.retry && typeof handleErrorResult.retry === "object") {
4417
- const delay2 = calculateNextRetryDelay(handleErrorResult.retry, execution.attempt.number);
4418
- return typeof delay2 === "undefined" ? {
4419
- status: "noop",
4420
- error: handleErrorResult.error
4421
- } : {
4422
- status: "retry",
4423
- retry: {
4424
- timestamp: Date.now() + delay2,
4425
- delay: delay2
4426
- },
4427
- error: handleErrorResult.error
4428
- };
4429
- }
4430
- return {
4431
- status: "noop",
4432
- error: handleErrorResult.error
4433
- };
4434
- }, {
4435
- attributes: {
4436
- [SemanticInternalAttributes.STYLE_ICON]: "exclamation-circle"
4437
- }
4438
- });
4439
- }, "#handleError");
4440
- __name(_TaskExecutor, "TaskExecutor");
4441
- var TaskExecutor = _TaskExecutor;
4442
-
4443
- // package.json
4444
- var dependencies = {
4445
- "@google-cloud/precise-date": "^4.0.0",
4446
- "@opentelemetry/api": "^1.8.0",
4447
- "@opentelemetry/api-logs": "^0.48.0",
4448
- "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
4449
- "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
4450
- "@opentelemetry/instrumentation": "^0.49.1",
4451
- "@opentelemetry/resources": "^1.22.0",
4452
- "@opentelemetry/sdk-logs": "^0.49.1",
4453
- "@opentelemetry/sdk-node": "^0.49.1",
4454
- "@opentelemetry/sdk-trace-base": "^1.22.0",
4455
- "@opentelemetry/sdk-trace-node": "^1.22.0",
4456
- "@opentelemetry/semantic-conventions": "^1.22.0",
4457
- "humanize-duration": "^3.27.3",
4458
- "socket.io": "^4.7.4",
4459
- "socket.io-client": "^4.7.4",
4460
- superjson: "^2.2.1",
4461
- ulidx: "^2.2.1",
4462
- zod: "3.22.3",
4463
- "zod-error": "1.5.0"
4464
- };
4465
-
4466
- // src/v3/utils/detectDependencyVersion.ts
4467
- function detectDependencyVersion(dependency) {
4468
- return dependencies[dependency];
4469
- }
4470
- __name(detectDependencyVersion, "detectDependencyVersion");
4471
-
4472
- // src/v3/index.ts
4473
- function parseTriggerTaskRequestBody(body) {
4474
- return TriggerTaskRequestBody.safeParse(body);
4475
- }
4476
- __name(parseTriggerTaskRequestBody, "parseTriggerTaskRequestBody");
4477
- function parseBatchTriggerTaskRequestBody(body) {
4478
- return BatchTriggerTaskRequestBody.safeParse(body);
4479
- }
4480
- __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
3379
+ __name(safeJsonParse2, "safeJsonParse");
4481
3380
 
3381
+ exports.APIConnectionError = APIConnectionError;
3382
+ exports.APIError = APIError;
4482
3383
  exports.ApiClient = ApiClient;
4483
3384
  exports.ApiClientManager = ApiClientManager;
3385
+ exports.AuthenticationError = AuthenticationError;
4484
3386
  exports.BackgroundWorkerClientMessages = BackgroundWorkerClientMessages;
4485
3387
  exports.BackgroundWorkerMetadata = BackgroundWorkerMetadata;
4486
3388
  exports.BackgroundWorkerProperties = BackgroundWorkerProperties;
4487
3389
  exports.BackgroundWorkerServerMessages = BackgroundWorkerServerMessages;
3390
+ exports.BadRequestError = BadRequestError;
4488
3391
  exports.BatchTaskRunExecutionResult = BatchTaskRunExecutionResult;
4489
3392
  exports.BatchTriggerTaskRequestBody = BatchTriggerTaskRequestBody;
4490
3393
  exports.BatchTriggerTaskResponse = BatchTriggerTaskResponse;
3394
+ exports.CanceledRunResponse = CanceledRunResponse;
4491
3395
  exports.CancellationSpanEvent = CancellationSpanEvent;
4492
3396
  exports.ClientToSharedQueueMessages = ClientToSharedQueueMessages;
4493
3397
  exports.Config = Config;
4494
- exports.ConsoleInterceptor = ConsoleInterceptor;
3398
+ exports.ConflictError = ConflictError;
4495
3399
  exports.CoordinatorToPlatformMessages = CoordinatorToPlatformMessages;
4496
3400
  exports.CoordinatorToProdWorkerMessages = CoordinatorToProdWorkerMessages;
4497
3401
  exports.CreateAuthorizationCodeResponseSchema = CreateAuthorizationCodeResponseSchema;
4498
3402
  exports.CreateBackgroundWorkerRequestBody = CreateBackgroundWorkerRequestBody;
4499
3403
  exports.CreateBackgroundWorkerResponse = CreateBackgroundWorkerResponse;
3404
+ exports.CreateScheduleOptions = CreateScheduleOptions;
4500
3405
  exports.CreateUploadPayloadUrlResponseBody = CreateUploadPayloadUrlResponseBody;
4501
- exports.DevRuntimeManager = DevRuntimeManager;
4502
- exports.DurableClock = PreciseWallClock;
3406
+ exports.DeletedScheduleObject = DeletedScheduleObject;
3407
+ exports.DeploymentErrorData = DeploymentErrorData;
4503
3408
  exports.EnvironmentType = EnvironmentType;
4504
3409
  exports.EventFilter = EventFilter;
4505
3410
  exports.ExceptionEventProperties = ExceptionEventProperties;
@@ -4523,9 +3428,13 @@ exports.GetProjectsResponseBody = GetProjectsResponseBody;
4523
3428
  exports.ImageDetailsMetadata = ImageDetailsMetadata;
4524
3429
  exports.InitializeDeploymentRequestBody = InitializeDeploymentRequestBody;
4525
3430
  exports.InitializeDeploymentResponseBody = InitializeDeploymentResponseBody;
3431
+ exports.InternalServerError = InternalServerError;
3432
+ exports.ListScheduleOptions = ListScheduleOptions;
3433
+ exports.ListSchedulesResult = ListSchedulesResult;
4526
3434
  exports.Machine = Machine;
4527
3435
  exports.MachineCpu = MachineCpu;
4528
3436
  exports.MachineMemory = MachineMemory;
3437
+ exports.NotFoundError = NotFoundError;
4529
3438
  exports.OFFLOAD_IO_PACKET_LENGTH_LIMIT = OFFLOAD_IO_PACKET_LENGTH_LIMIT;
4530
3439
  exports.OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT;
4531
3440
  exports.OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT;
@@ -4535,15 +3444,14 @@ exports.OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_
4535
3444
  exports.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT;
4536
3445
  exports.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT;
4537
3446
  exports.OTEL_SPAN_EVENT_COUNT_LIMIT = OTEL_SPAN_EVENT_COUNT_LIMIT;
4538
- exports.OtelTaskLogger = OtelTaskLogger;
4539
3447
  exports.OtherSpanEvent = OtherSpanEvent;
4540
3448
  exports.PRIMARY_VARIANT = PRIMARY_VARIANT;
3449
+ exports.PermissionDeniedError = PermissionDeniedError;
4541
3450
  exports.PlatformToCoordinatorMessages = PlatformToCoordinatorMessages;
4542
3451
  exports.PlatformToProviderMessages = PlatformToProviderMessages;
4543
3452
  exports.PostStartCauses = PostStartCauses;
4544
3453
  exports.PreStopCauses = PreStopCauses;
4545
3454
  exports.ProdChildToWorkerMessages = ProdChildToWorkerMessages;
4546
- exports.ProdRuntimeManager = ProdRuntimeManager;
4547
3455
  exports.ProdTaskRunExecution = ProdTaskRunExecution;
4548
3456
  exports.ProdTaskRunExecutionPayload = ProdTaskRunExecutionPayload;
4549
3457
  exports.ProdWorkerSocketData = ProdWorkerSocketData;
@@ -4551,21 +3459,24 @@ exports.ProdWorkerToChildMessages = ProdWorkerToChildMessages;
4551
3459
  exports.ProdWorkerToCoordinatorMessages = ProdWorkerToCoordinatorMessages;
4552
3460
  exports.ProviderToPlatformMessages = ProviderToPlatformMessages;
4553
3461
  exports.QueueOptions = QueueOptions;
3462
+ exports.RateLimitError = RateLimitError;
4554
3463
  exports.RateLimitOptions = RateLimitOptions;
3464
+ exports.ReplayRunResponse = ReplayRunResponse;
4555
3465
  exports.RetryOptions = RetryOptions;
3466
+ exports.ScheduleObject = ScheduleObject;
3467
+ exports.ScheduledTaskPayload = ScheduledTaskPayload;
4556
3468
  exports.SemanticInternalAttributes = SemanticInternalAttributes;
4557
3469
  exports.SharedQueueToClientMessages = SharedQueueToClientMessages;
4558
- exports.SimpleStructuredLogger = SimpleStructuredLogger;
4559
3470
  exports.SlidingWindowRateLimit = SlidingWindowRateLimit;
4560
3471
  exports.SpanEvent = SpanEvent;
4561
3472
  exports.SpanEvents = SpanEvents;
4562
3473
  exports.SpanMessagingEvent = SpanMessagingEvent;
4563
3474
  exports.StartDeploymentIndexingRequestBody = StartDeploymentIndexingRequestBody;
4564
3475
  exports.StartDeploymentIndexingResponseBody = StartDeploymentIndexingResponseBody;
4565
- exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
4566
3476
  exports.TaskEventStyle = TaskEventStyle;
4567
- exports.TaskExecutor = TaskExecutor;
3477
+ exports.TaskFileMetadata = TaskFileMetadata;
4568
3478
  exports.TaskMetadata = TaskMetadata;
3479
+ exports.TaskMetadataFailedToParseData = TaskMetadataFailedToParseData;
4569
3480
  exports.TaskMetadataWithFilePath = TaskMetadataWithFilePath;
4570
3481
  exports.TaskResource = TaskResource;
4571
3482
  exports.TaskRun = TaskRun;
@@ -4589,21 +3500,14 @@ exports.TaskRunFailedExecutionResult = TaskRunFailedExecutionResult;
4589
3500
  exports.TaskRunInternalError = TaskRunInternalError;
4590
3501
  exports.TaskRunStringError = TaskRunStringError;
4591
3502
  exports.TaskRunSuccessfulExecutionResult = TaskRunSuccessfulExecutionResult;
4592
- exports.TracingSDK = TracingSDK;
4593
3503
  exports.TriggerTaskRequestBody = TriggerTaskRequestBody;
4594
3504
  exports.TriggerTaskResponse = TriggerTaskResponse;
4595
3505
  exports.TriggerTracer = TriggerTracer;
4596
3506
  exports.UncaughtExceptionMessage = UncaughtExceptionMessage;
3507
+ exports.UnprocessableEntityError = UnprocessableEntityError;
3508
+ exports.UpdateScheduleOptions = UpdateScheduleOptions;
4597
3509
  exports.WaitReason = WaitReason;
4598
3510
  exports.WhoAmIResponseSchema = WhoAmIResponseSchema;
4599
- exports.ZodIpcConnection = ZodIpcConnection;
4600
- exports.ZodMessageHandler = ZodMessageHandler;
4601
- exports.ZodMessageSchema = ZodMessageSchema;
4602
- exports.ZodMessageSender = ZodMessageSender;
4603
- exports.ZodNamespace = ZodNamespace;
4604
- exports.ZodSocketConnection = ZodSocketConnection;
4605
- exports.ZodSocketMessageHandler = ZodSocketMessageHandler;
4606
- exports.ZodSocketMessageSender = ZodSocketMessageSender;
4607
3511
  exports.accessoryAttributes = accessoryAttributes;
4608
3512
  exports.apiClientManager = apiClientManager;
4609
3513
  exports.calculateNextRetryDelay = calculateNextRetryDelay;
@@ -4626,8 +3530,7 @@ exports.formatDuration = formatDuration;
4626
3530
  exports.formatDurationInDays = formatDurationInDays;
4627
3531
  exports.formatDurationMilliseconds = formatDurationMilliseconds;
4628
3532
  exports.formatDurationNanoseconds = formatDurationNanoseconds;
4629
- exports.getEnvVar = getEnvVar;
4630
- exports.iconStringForSeverity = iconStringForSeverity;
3533
+ exports.groupTaskMetadataIssuesByTask = groupTaskMetadataIssuesByTask;
4631
3534
  exports.imposeAttributeLimits = imposeAttributeLimits;
4632
3535
  exports.isCancellationSpanEvent = isCancellationSpanEvent;
4633
3536
  exports.isExceptionSpanEvent = isExceptionSpanEvent;
@@ -4636,18 +3539,16 @@ exports.millisecondsToNanoseconds = millisecondsToNanoseconds;
4636
3539
  exports.nanosecondsToMilliseconds = nanosecondsToMilliseconds;
4637
3540
  exports.omit = omit;
4638
3541
  exports.packetRequiresOffloading = packetRequiresOffloading;
4639
- exports.parseBatchTriggerTaskRequestBody = parseBatchTriggerTaskRequestBody;
4640
3542
  exports.parseError = parseError;
4641
3543
  exports.parsePacket = parsePacket;
4642
- exports.parseTriggerTaskRequestBody = parseTriggerTaskRequestBody;
4643
3544
  exports.prettyPrintPacket = prettyPrintPacket;
4644
3545
  exports.primitiveValueOrflattenedAttributes = primitiveValueOrflattenedAttributes;
4645
- exports.recordSpanException = recordSpanException;
4646
3546
  exports.runtime = runtime;
4647
3547
  exports.serverWebsocketMessages = serverWebsocketMessages;
4648
3548
  exports.stringPatternMatchers = stringPatternMatchers;
4649
3549
  exports.stringifyIO = stringifyIO;
4650
- exports.taskContextManager = taskContextManager;
3550
+ exports.taskCatalog = taskCatalog;
3551
+ exports.taskContext = taskContext;
4651
3552
  exports.unflattenAttributes = unflattenAttributes;
4652
3553
  exports.workerToChildMessages = workerToChildMessages;
4653
3554
  //# sourceMappingURL=out.js.map