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