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

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