@trigger.dev/core 0.0.0-prerelease-20240418145424 → 0.0.0-prerelease-20240528152213

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/catalog-BUwiuDbt.d.mts +202 -0
  2. package/dist/catalog-eKgqBHUA.d.ts +202 -0
  3. package/dist/index.d.mts +60 -1
  4. package/dist/index.d.ts +60 -1
  5. package/dist/index.js +7 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +7 -1
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/manager-uPyMRN8k.d.mts +1159 -0
  10. package/dist/manager-uPyMRN8k.d.ts +1159 -0
  11. package/dist/messages-l9PdIyKF.d.mts +16741 -0
  12. package/dist/messages-l9PdIyKF.d.ts +16741 -0
  13. package/dist/schemas-b8tRw8dX.d.mts +2331 -0
  14. package/dist/schemas-b8tRw8dX.d.ts +2331 -0
  15. package/dist/v3/dev/index.d.mts +28 -0
  16. package/dist/v3/dev/index.d.ts +28 -0
  17. package/dist/v3/dev/index.js +93 -0
  18. package/dist/v3/dev/index.js.map +1 -0
  19. package/dist/v3/dev/index.mjs +91 -0
  20. package/dist/v3/dev/index.mjs.map +1 -0
  21. package/dist/v3/index.d.mts +517 -17166
  22. package/dist/v3/index.d.ts +517 -17166
  23. package/dist/v3/index.js +1591 -2828
  24. package/dist/v3/index.js.map +1 -1
  25. package/dist/v3/index.mjs +1580 -2802
  26. package/dist/v3/index.mjs.map +1 -1
  27. package/dist/v3/otel/index.js +85 -44
  28. package/dist/v3/otel/index.js.map +1 -1
  29. package/dist/v3/otel/index.mjs +85 -44
  30. package/dist/v3/otel/index.mjs.map +1 -1
  31. package/dist/v3/prod/index.d.mts +45 -0
  32. package/dist/v3/prod/index.d.ts +45 -0
  33. package/dist/v3/prod/index.js +304 -0
  34. package/dist/v3/prod/index.js.map +1 -0
  35. package/dist/v3/prod/index.mjs +302 -0
  36. package/dist/v3/prod/index.mjs.map +1 -0
  37. package/dist/v3/utils/structuredLogger.d.mts +31 -0
  38. package/dist/v3/utils/structuredLogger.d.ts +31 -0
  39. package/dist/v3/utils/structuredLogger.js +88 -0
  40. package/dist/v3/utils/structuredLogger.js.map +1 -0
  41. package/dist/v3/utils/structuredLogger.mjs +86 -0
  42. package/dist/v3/utils/structuredLogger.mjs.map +1 -0
  43. package/dist/v3/workers/index.d.mts +96 -0
  44. package/dist/v3/workers/index.d.ts +96 -0
  45. package/dist/v3/workers/index.js +2831 -0
  46. package/dist/v3/workers/index.js.map +1 -0
  47. package/dist/v3/workers/index.mjs +2815 -0
  48. package/dist/v3/workers/index.mjs.map +1 -0
  49. package/dist/v3/zodIpc.d.mts +32 -0
  50. package/dist/v3/zodIpc.d.ts +32 -0
  51. package/dist/v3/zodIpc.js +268 -0
  52. package/dist/v3/zodIpc.js.map +1 -0
  53. package/dist/v3/zodIpc.mjs +266 -0
  54. package/dist/v3/zodIpc.mjs.map +1 -0
  55. package/dist/v3/zodMessageHandler.d.mts +69 -0
  56. package/dist/v3/zodMessageHandler.d.ts +69 -0
  57. package/dist/v3/zodMessageHandler.js +168 -0
  58. package/dist/v3/zodMessageHandler.js.map +1 -0
  59. package/dist/v3/zodMessageHandler.mjs +163 -0
  60. package/dist/v3/zodMessageHandler.mjs.map +1 -0
  61. package/dist/v3/zodNamespace.d.mts +3663 -0
  62. package/dist/v3/zodNamespace.d.ts +3663 -0
  63. package/dist/v3/zodNamespace.js +366 -0
  64. package/dist/v3/zodNamespace.js.map +1 -0
  65. package/dist/v3/zodNamespace.mjs +364 -0
  66. package/dist/v3/zodNamespace.mjs.map +1 -0
  67. package/dist/v3/zodSocket.d.mts +88 -0
  68. package/dist/v3/zodSocket.d.ts +88 -0
  69. package/dist/v3/zodSocket.js +319 -0
  70. package/dist/v3/zodSocket.js.map +1 -0
  71. package/dist/v3/zodSocket.mjs +315 -0
  72. package/dist/v3/zodSocket.mjs.map +1 -0
  73. package/dist/v3/zodfetch.d.mts +78 -0
  74. package/dist/v3/zodfetch.d.ts +78 -0
  75. package/dist/v3/zodfetch.js +446 -0
  76. package/dist/v3/zodfetch.js.map +1 -0
  77. package/dist/v3/zodfetch.mjs +433 -0
  78. package/dist/v3/zodfetch.mjs.map +1 -0
  79. package/package.json +77 -4
package/dist/v3/index.mjs CHANGED
@@ -1,22 +1,11 @@
1
+ import { propagation, context, trace, SpanStatusCode } from '@opentelemetry/api';
1
2
  import { z } from 'zod';
2
- import { SpanStatusCode, trace, propagation, context, DiagLogLevel, diag, DiagConsoleLogger, SpanKind } from '@opentelemetry/api';
3
3
  import { fromZodError } from 'zod-validation-error';
4
- import { AsyncLocalStorage } from 'node:async_hooks';
5
- import { io } from 'socket.io-client';
6
- import { randomUUID } from 'crypto';
7
- import nodePath from 'node:path';
8
- import { SeverityNumber, logs } from '@opentelemetry/api-logs';
4
+ import { FormDataEncoder } from 'form-data-encoder';
5
+ import { Readable } from 'node:stream';
9
6
  import { PreciseDate } from '@google-cloud/precise-date';
7
+ import { logs } from '@opentelemetry/api-logs';
10
8
  import humanizeDuration from 'humanize-duration';
11
- import { setTimeout as setTimeout$1 } from 'node:timers/promises';
12
- import util from 'node:util';
13
- import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';
14
- import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
15
- import { registerInstrumentations } from '@opentelemetry/instrumentation';
16
- import { Resource, detectResourcesSync, processDetectorSync } from '@opentelemetry/resources';
17
- import { LoggerProvider, BatchLogRecordProcessor, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs';
18
- import { NodeTracerProvider, BatchSpanProcessor, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node';
19
- import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
20
9
 
21
10
  var __defProp = Object.defineProperty;
22
11
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -29,32 +18,178 @@ var __accessCheck = (obj, member, msg) => {
29
18
  if (!member.has(obj))
30
19
  throw TypeError("Cannot " + msg);
31
20
  };
32
- var __privateGet = (obj, member, getter) => {
33
- __accessCheck(obj, member, "read from private field");
34
- return getter ? getter.call(obj) : member.get(obj);
35
- };
36
21
  var __privateAdd = (obj, member, value) => {
37
22
  if (member.has(obj))
38
23
  throw TypeError("Cannot add the same private member more than once");
39
24
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
40
25
  };
41
- var __privateSet = (obj, member, value, setter) => {
42
- __accessCheck(obj, member, "write to private field");
43
- setter ? setter.call(obj, value) : member.set(obj, value);
44
- return value;
45
- };
46
- var __privateWrapper = (obj, member, setter, getter) => ({
47
- set _(value) {
48
- __privateSet(obj, member, value, setter);
49
- },
50
- get _() {
51
- return __privateGet(obj, member, getter);
52
- }
53
- });
54
26
  var __privateMethod = (obj, member, method) => {
55
27
  __accessCheck(obj, member, "access private method");
56
28
  return method;
57
29
  };
30
+
31
+ // package.json
32
+ var version = "0.0.0-prerelease-20240528152213";
33
+ var dependencies = {
34
+ "@google-cloud/precise-date": "^4.0.0",
35
+ "@opentelemetry/api": "^1.8.0",
36
+ "@opentelemetry/api-logs": "^0.48.0",
37
+ "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
38
+ "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
39
+ "@opentelemetry/instrumentation": "^0.49.1",
40
+ "@opentelemetry/resources": "^1.22.0",
41
+ "@opentelemetry/sdk-logs": "^0.49.1",
42
+ "@opentelemetry/sdk-node": "^0.49.1",
43
+ "@opentelemetry/sdk-trace-base": "^1.22.0",
44
+ "@opentelemetry/sdk-trace-node": "^1.22.0",
45
+ "@opentelemetry/semantic-conventions": "^1.22.0",
46
+ "form-data-encoder": "^4.0.2",
47
+ "humanize-duration": "^3.27.3",
48
+ "socket.io-client": "4.7.4",
49
+ superjson: "^2.2.1",
50
+ ulidx: "^2.2.1",
51
+ zod: "3.22.3",
52
+ "zod-error": "1.5.0",
53
+ "zod-validation-error": "^1.5.0"
54
+ };
55
+
56
+ // src/v3/apiErrors.ts
57
+ var _APIError = class _APIError extends Error {
58
+ constructor(status, error, message, headers) {
59
+ super(`${_APIError.makeMessage(status, error, message)}`);
60
+ this.status = status;
61
+ this.headers = headers;
62
+ const data = error;
63
+ this.error = data;
64
+ this.code = data?.["code"];
65
+ this.param = data?.["param"];
66
+ this.type = data?.["type"];
67
+ }
68
+ static makeMessage(status, error, message) {
69
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
70
+ if (status && msg) {
71
+ return `${status} ${msg}`;
72
+ }
73
+ if (status) {
74
+ return `${status} status code (no body)`;
75
+ }
76
+ if (msg) {
77
+ return msg;
78
+ }
79
+ return "(no status code or body)";
80
+ }
81
+ static generate(status, errorResponse, message, headers) {
82
+ if (!status) {
83
+ return new APIConnectionError({
84
+ cause: castToError(errorResponse)
85
+ });
86
+ }
87
+ const error = errorResponse?.["error"];
88
+ if (status === 400) {
89
+ return new BadRequestError(status, error, message, headers);
90
+ }
91
+ if (status === 401) {
92
+ return new AuthenticationError(status, error, message, headers);
93
+ }
94
+ if (status === 403) {
95
+ return new PermissionDeniedError(status, error, message, headers);
96
+ }
97
+ if (status === 404) {
98
+ return new NotFoundError(status, error, message, headers);
99
+ }
100
+ if (status === 409) {
101
+ return new ConflictError(status, error, message, headers);
102
+ }
103
+ if (status === 422) {
104
+ return new UnprocessableEntityError(status, error, message, headers);
105
+ }
106
+ if (status === 429) {
107
+ return new RateLimitError(status, error, message, headers);
108
+ }
109
+ if (status >= 500) {
110
+ return new InternalServerError(status, error, message, headers);
111
+ }
112
+ return new _APIError(status, error, message, headers);
113
+ }
114
+ };
115
+ __name(_APIError, "APIError");
116
+ var APIError = _APIError;
117
+ var _APIConnectionError = class _APIConnectionError extends APIError {
118
+ constructor({ message, cause }) {
119
+ super(void 0, void 0, message || "Connection error.", void 0);
120
+ __publicField(this, "status");
121
+ if (cause)
122
+ this.cause = cause;
123
+ }
124
+ };
125
+ __name(_APIConnectionError, "APIConnectionError");
126
+ var APIConnectionError = _APIConnectionError;
127
+ var _BadRequestError = class _BadRequestError extends APIError {
128
+ constructor() {
129
+ super(...arguments);
130
+ __publicField(this, "status", 400);
131
+ }
132
+ };
133
+ __name(_BadRequestError, "BadRequestError");
134
+ var BadRequestError = _BadRequestError;
135
+ var _AuthenticationError = class _AuthenticationError extends APIError {
136
+ constructor() {
137
+ super(...arguments);
138
+ __publicField(this, "status", 401);
139
+ }
140
+ };
141
+ __name(_AuthenticationError, "AuthenticationError");
142
+ var AuthenticationError = _AuthenticationError;
143
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
144
+ constructor() {
145
+ super(...arguments);
146
+ __publicField(this, "status", 403);
147
+ }
148
+ };
149
+ __name(_PermissionDeniedError, "PermissionDeniedError");
150
+ var PermissionDeniedError = _PermissionDeniedError;
151
+ var _NotFoundError = class _NotFoundError extends APIError {
152
+ constructor() {
153
+ super(...arguments);
154
+ __publicField(this, "status", 404);
155
+ }
156
+ };
157
+ __name(_NotFoundError, "NotFoundError");
158
+ var NotFoundError = _NotFoundError;
159
+ var _ConflictError = class _ConflictError extends APIError {
160
+ constructor() {
161
+ super(...arguments);
162
+ __publicField(this, "status", 409);
163
+ }
164
+ };
165
+ __name(_ConflictError, "ConflictError");
166
+ var ConflictError = _ConflictError;
167
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
168
+ constructor() {
169
+ super(...arguments);
170
+ __publicField(this, "status", 422);
171
+ }
172
+ };
173
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
174
+ var UnprocessableEntityError = _UnprocessableEntityError;
175
+ var _RateLimitError = class _RateLimitError extends APIError {
176
+ constructor() {
177
+ super(...arguments);
178
+ __publicField(this, "status", 429);
179
+ }
180
+ };
181
+ __name(_RateLimitError, "RateLimitError");
182
+ var RateLimitError = _RateLimitError;
183
+ var _InternalServerError = class _InternalServerError extends APIError {
184
+ };
185
+ __name(_InternalServerError, "InternalServerError");
186
+ var InternalServerError = _InternalServerError;
187
+ function castToError(err) {
188
+ if (err instanceof Error)
189
+ return err;
190
+ return new Error(err);
191
+ }
192
+ __name(castToError, "castToError");
58
193
  var CreateAuthorizationCodeResponseSchema = z.object({
59
194
  url: z.string().url(),
60
195
  authorizationCode: z.string()
@@ -90,6 +225,7 @@ var TaskRunErrorCodes = {
90
225
  TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
91
226
  TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
92
227
  TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
228
+ TASK_PROCESS_SIGKILL_TIMEOUT: "TASK_PROCESS_SIGKILL_TIMEOUT",
93
229
  TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
94
230
  TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
95
231
  HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
@@ -105,10 +241,12 @@ var TaskRunInternalError = z.object({
105
241
  "TASK_EXECUTION_FAILED",
106
242
  "TASK_EXECUTION_ABORTED",
107
243
  "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
244
+ "TASK_PROCESS_SIGKILL_TIMEOUT",
108
245
  "TASK_RUN_CANCELLED",
109
246
  "TASK_OUTPUT_ERROR",
110
247
  "HANDLE_ERROR_ERROR",
111
- "GRACEFUL_EXIT_TIMEOUT"
248
+ "GRACEFUL_EXIT_TIMEOUT",
249
+ "TASK_RUN_HEARTBEAT_TIMEOUT"
112
250
  ]),
113
251
  message: z.string().optional()
114
252
  });
@@ -125,7 +263,8 @@ var TaskRun = z.object({
125
263
  context: z.any(),
126
264
  tags: z.array(z.string()),
127
265
  isTest: z.boolean().default(false),
128
- createdAt: z.coerce.date()
266
+ createdAt: z.coerce.date(),
267
+ idempotencyKey: z.string().optional()
129
268
  });
130
269
  var TaskRunExecutionTask = z.object({
131
270
  id: z.string(),
@@ -221,7 +360,7 @@ var BatchTaskRunExecutionResult = z.object({
221
360
  items: TaskRunExecutionResult.array()
222
361
  });
223
362
 
224
- // src/v3/schemas/messages.ts
363
+ // src/v3/schemas/schemas.ts
225
364
  var EnvironmentType = z.enum([
226
365
  "PRODUCTION",
227
366
  "STAGING",
@@ -265,92 +404,6 @@ var ProdTaskRunExecutionPayload = z.object({
265
404
  traceContext: z.record(z.unknown()),
266
405
  environment: z.record(z.string()).optional()
267
406
  });
268
- var BackgroundWorkerServerMessages = z.discriminatedUnion("type", [
269
- z.object({
270
- type: z.literal("EXECUTE_RUNS"),
271
- payloads: z.array(TaskRunExecutionPayload)
272
- }),
273
- z.object({
274
- type: z.literal("CANCEL_ATTEMPT"),
275
- taskAttemptId: z.string(),
276
- taskRunId: z.string()
277
- }),
278
- z.object({
279
- type: z.literal("SCHEDULE_ATTEMPT"),
280
- image: z.string(),
281
- version: z.string(),
282
- machine: Machine,
283
- // identifiers
284
- id: z.string(),
285
- envId: z.string(),
286
- envType: EnvironmentType,
287
- orgId: z.string(),
288
- projectId: z.string(),
289
- runId: z.string()
290
- })
291
- ]);
292
- var serverWebsocketMessages = {
293
- SERVER_READY: z.object({
294
- version: z.literal("v1").default("v1"),
295
- id: z.string()
296
- }),
297
- BACKGROUND_WORKER_MESSAGE: z.object({
298
- version: z.literal("v1").default("v1"),
299
- backgroundWorkerId: z.string(),
300
- data: BackgroundWorkerServerMessages
301
- })
302
- };
303
- var BackgroundWorkerClientMessages = z.discriminatedUnion("type", [
304
- z.object({
305
- version: z.literal("v1").default("v1"),
306
- type: z.literal("TASK_RUN_COMPLETED"),
307
- completion: TaskRunExecutionResult,
308
- execution: TaskRunExecution
309
- }),
310
- z.object({
311
- version: z.literal("v1").default("v1"),
312
- type: z.literal("TASK_HEARTBEAT"),
313
- id: z.string()
314
- })
315
- ]);
316
- var BackgroundWorkerProperties = z.object({
317
- id: z.string(),
318
- version: z.string(),
319
- contentHash: z.string()
320
- });
321
- var clientWebsocketMessages = {
322
- READY_FOR_TASKS: z.object({
323
- version: z.literal("v1").default("v1"),
324
- backgroundWorkerId: z.string()
325
- }),
326
- BACKGROUND_WORKER_DEPRECATED: z.object({
327
- version: z.literal("v1").default("v1"),
328
- backgroundWorkerId: z.string()
329
- }),
330
- BACKGROUND_WORKER_MESSAGE: z.object({
331
- version: z.literal("v1").default("v1"),
332
- backgroundWorkerId: z.string(),
333
- data: BackgroundWorkerClientMessages
334
- })
335
- };
336
- var workerToChildMessages = {
337
- EXECUTE_TASK_RUN: z.object({
338
- version: z.literal("v1").default("v1"),
339
- execution: TaskRunExecution,
340
- traceContext: z.record(z.unknown()),
341
- metadata: BackgroundWorkerProperties
342
- }),
343
- TASK_RUN_COMPLETED_NOTIFICATION: z.object({
344
- version: z.literal("v1").default("v1"),
345
- completion: TaskRunExecutionResult,
346
- execution: TaskRunExecution
347
- }),
348
- CLEANUP: z.object({
349
- version: z.literal("v1").default("v1"),
350
- flush: z.boolean().default(false),
351
- kill: z.boolean().default(true)
352
- })
353
- };
354
407
  var FixedWindowRateLimit = z.object({
355
408
  type: z.literal("fixed-window"),
356
409
  limit: z.number(),
@@ -456,149 +509,53 @@ var TaskFileMetadata = z.object({
456
509
  exportName: z.string()
457
510
  });
458
511
  var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
459
- var UncaughtExceptionMessage = z.object({
460
- version: z.literal("v1").default("v1"),
461
- error: z.object({
462
- name: z.string(),
463
- message: z.string(),
464
- stack: z.string().optional()
465
- }),
466
- origin: z.enum([
467
- "uncaughtException",
468
- "unhandledRejection"
469
- ])
512
+ var PostStartCauses = z.enum([
513
+ "index",
514
+ "create",
515
+ "restore"
516
+ ]);
517
+ var PreStopCauses = z.enum([
518
+ "terminate"
519
+ ]);
520
+ var RegexSchema = z.custom((val) => {
521
+ try {
522
+ return typeof val.test === "function";
523
+ } catch {
524
+ return false;
525
+ }
470
526
  });
471
- var TaskMetadataFailedToParseData = z.object({
472
- version: z.literal("v1").default("v1"),
473
- tasks: z.unknown(),
474
- zodIssues: z.custom((v) => {
475
- return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
476
- })
527
+ var Config = z.object({
528
+ project: z.string(),
529
+ triggerDirectories: z.string().array().optional(),
530
+ triggerUrl: z.string().optional(),
531
+ projectDir: z.string().optional(),
532
+ tsconfigPath: z.string().optional(),
533
+ retries: z.object({
534
+ enabledInDev: z.boolean().default(true),
535
+ default: RetryOptions.optional()
536
+ }).optional(),
537
+ additionalPackages: z.string().array().optional(),
538
+ additionalFiles: z.string().array().optional(),
539
+ dependenciesToBundle: z.array(z.union([
540
+ z.string(),
541
+ RegexSchema
542
+ ])).optional(),
543
+ logLevel: z.string().optional(),
544
+ enableConsoleLogging: z.boolean().optional(),
545
+ postInstall: z.string().optional()
546
+ });
547
+ var WaitReason = z.enum([
548
+ "WAIT_FOR_DURATION",
549
+ "WAIT_FOR_TASK",
550
+ "WAIT_FOR_BATCH"
551
+ ]);
552
+ var TaskRunExecutionLazyAttemptPayload = z.object({
553
+ runId: z.string(),
554
+ messageId: z.string(),
555
+ isTest: z.boolean(),
556
+ traceContext: z.record(z.unknown()),
557
+ environment: z.record(z.string()).optional()
477
558
  });
478
- var childToWorkerMessages = {
479
- TASK_RUN_COMPLETED: z.object({
480
- version: z.literal("v1").default("v1"),
481
- execution: TaskRunExecution,
482
- result: TaskRunExecutionResult
483
- }),
484
- TASKS_READY: z.object({
485
- version: z.literal("v1").default("v1"),
486
- tasks: TaskMetadataWithFilePath.array()
487
- }),
488
- TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
489
- TASK_HEARTBEAT: z.object({
490
- version: z.literal("v1").default("v1"),
491
- id: z.string()
492
- }),
493
- READY_TO_DISPOSE: z.undefined(),
494
- WAIT_FOR_DURATION: z.object({
495
- version: z.literal("v1").default("v1"),
496
- ms: z.number()
497
- }),
498
- WAIT_FOR_TASK: z.object({
499
- version: z.literal("v1").default("v1"),
500
- id: z.string()
501
- }),
502
- WAIT_FOR_BATCH: z.object({
503
- version: z.literal("v1").default("v1"),
504
- id: z.string(),
505
- runs: z.string().array()
506
- }),
507
- UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
508
- };
509
- var ProdChildToWorkerMessages = {
510
- TASK_RUN_COMPLETED: {
511
- message: z.object({
512
- version: z.literal("v1").default("v1"),
513
- execution: TaskRunExecution,
514
- result: TaskRunExecutionResult
515
- })
516
- },
517
- TASKS_READY: {
518
- message: z.object({
519
- version: z.literal("v1").default("v1"),
520
- tasks: TaskMetadataWithFilePath.array()
521
- })
522
- },
523
- TASKS_FAILED_TO_PARSE: {
524
- message: TaskMetadataFailedToParseData
525
- },
526
- TASK_HEARTBEAT: {
527
- message: z.object({
528
- version: z.literal("v1").default("v1"),
529
- id: z.string()
530
- })
531
- },
532
- READY_TO_DISPOSE: {
533
- message: z.undefined()
534
- },
535
- READY_FOR_CHECKPOINT: {
536
- message: z.object({
537
- version: z.literal("v1").default("v1")
538
- })
539
- },
540
- CANCEL_CHECKPOINT: {
541
- message: z.object({
542
- version: z.literal("v1").default("v1")
543
- })
544
- },
545
- WAIT_FOR_DURATION: {
546
- message: z.object({
547
- version: z.literal("v1").default("v1"),
548
- ms: z.number(),
549
- now: z.number()
550
- }),
551
- callback: z.object({
552
- willCheckpointAndRestore: z.boolean()
553
- })
554
- },
555
- WAIT_FOR_TASK: {
556
- message: z.object({
557
- version: z.literal("v1").default("v1"),
558
- friendlyId: z.string()
559
- })
560
- },
561
- WAIT_FOR_BATCH: {
562
- message: z.object({
563
- version: z.literal("v1").default("v1"),
564
- batchFriendlyId: z.string(),
565
- runFriendlyIds: z.string().array()
566
- })
567
- },
568
- UNCAUGHT_EXCEPTION: {
569
- message: UncaughtExceptionMessage
570
- }
571
- };
572
- var ProdWorkerToChildMessages = {
573
- EXECUTE_TASK_RUN: {
574
- message: z.object({
575
- version: z.literal("v1").default("v1"),
576
- execution: TaskRunExecution,
577
- traceContext: z.record(z.unknown()),
578
- metadata: BackgroundWorkerProperties
579
- })
580
- },
581
- TASK_RUN_COMPLETED_NOTIFICATION: {
582
- message: z.object({
583
- version: z.literal("v1").default("v1"),
584
- completion: TaskRunExecutionResult,
585
- execution: TaskRunExecution
586
- })
587
- },
588
- CLEANUP: {
589
- message: z.object({
590
- version: z.literal("v1").default("v1"),
591
- flush: z.boolean().default(false),
592
- kill: z.boolean().default(true)
593
- }),
594
- callback: z.void()
595
- },
596
- WAIT_COMPLETED_NOTIFICATION: {
597
- message: z.object({
598
- version: z.literal("v1").default("v1")
599
- })
600
- }
601
- };
602
559
 
603
560
  // src/v3/schemas/resources.ts
604
561
  var TaskResource = z.object({
@@ -648,7 +605,8 @@ var GetProjectEnvResponse = z.object({
648
605
  });
649
606
  var CreateBackgroundWorkerRequestBody = z.object({
650
607
  localOnly: z.boolean(),
651
- metadata: BackgroundWorkerMetadata
608
+ metadata: BackgroundWorkerMetadata,
609
+ supportsLazyAttempts: z.boolean().optional()
652
610
  });
653
611
  var CreateBackgroundWorkerResponse = z.object({
654
612
  id: z.string(),
@@ -697,7 +655,8 @@ var GetEnvironmentVariablesResponseBody = z.object({
697
655
  variables: z.record(z.string())
698
656
  });
699
657
  var StartDeploymentIndexingRequestBody = z.object({
700
- imageReference: z.string()
658
+ imageReference: z.string(),
659
+ selfHosted: z.boolean().optional()
701
660
  });
702
661
  var StartDeploymentIndexingResponseBody = z.object({
703
662
  id: z.string(),
@@ -843,58 +802,354 @@ var ListScheduleOptions = z.object({
843
802
  page: z.number().optional(),
844
803
  perPage: z.number().optional()
845
804
  });
846
- var PostStartCauses = z.enum([
847
- "index",
848
- "create",
849
- "restore"
805
+ var RunStatus = z.enum([
806
+ "PENDING",
807
+ "EXECUTING",
808
+ "PAUSED",
809
+ "COMPLETED",
810
+ "FAILED",
811
+ "CANCELED"
850
812
  ]);
851
- var PreStopCauses = z.enum([
852
- "terminate"
813
+ var AttemptStatus = z.enum([
814
+ "PENDING",
815
+ "EXECUTING",
816
+ "PAUSED",
817
+ "COMPLETED",
818
+ "FAILED",
819
+ "CANCELED"
853
820
  ]);
854
- var RegexSchema = z.custom((val) => {
855
- try {
856
- return typeof val.test === "function";
857
- } catch {
858
- return false;
859
- }
821
+ var RetrieveRunResponse = z.object({
822
+ id: z.string(),
823
+ status: RunStatus,
824
+ taskIdentifier: z.string(),
825
+ idempotencyKey: z.string().optional(),
826
+ version: z.string().optional(),
827
+ createdAt: z.coerce.date(),
828
+ updatedAt: z.coerce.date(),
829
+ attempts: z.array(z.object({
830
+ id: z.string(),
831
+ status: AttemptStatus,
832
+ createdAt: z.coerce.date(),
833
+ updatedAt: z.coerce.date(),
834
+ startedAt: z.coerce.date().optional(),
835
+ completedAt: z.coerce.date().optional()
836
+ }).optional())
837
+ });
838
+ var CreateEnvironmentVariableRequestBody = z.object({
839
+ name: z.string(),
840
+ value: z.string()
860
841
  });
861
- var Config = z.object({
862
- project: z.string(),
863
- triggerDirectories: z.string().array().optional(),
864
- triggerUrl: z.string().optional(),
865
- projectDir: z.string().optional(),
866
- tsconfigPath: z.string().optional(),
867
- retries: z.object({
868
- enabledInDev: z.boolean().default(true),
869
- default: RetryOptions.optional()
870
- }).optional(),
871
- additionalPackages: z.string().array().optional(),
872
- additionalFiles: z.string().array().optional(),
873
- dependenciesToBundle: z.array(z.union([
874
- z.string(),
875
- RegexSchema
876
- ])).optional(),
877
- logLevel: z.string().optional(),
878
- enableConsoleLogging: z.boolean().optional()
842
+ var UpdateEnvironmentVariableRequestBody = z.object({
843
+ value: z.string()
879
844
  });
880
- var WaitReason = z.enum([
881
- "WAIT_FOR_DURATION",
882
- "WAIT_FOR_TASK",
883
- "WAIT_FOR_BATCH"
845
+ var ImportEnvironmentVariablesRequestBody = z.object({
846
+ variables: z.record(z.string()),
847
+ override: z.boolean().optional()
848
+ });
849
+ var EnvironmentVariableResponseBody = z.object({
850
+ success: z.boolean()
851
+ });
852
+ var EnvironmentVariableValue = z.object({
853
+ value: z.string()
854
+ });
855
+ var EnvironmentVariable = z.object({
856
+ name: z.string(),
857
+ value: z.string()
858
+ });
859
+ var EnvironmentVariables = z.array(EnvironmentVariable);
860
+ var BackgroundWorkerServerMessages = z.discriminatedUnion("type", [
861
+ z.object({
862
+ type: z.literal("EXECUTE_RUNS"),
863
+ payloads: z.array(TaskRunExecutionPayload)
864
+ }),
865
+ z.object({
866
+ type: z.literal("CANCEL_ATTEMPT"),
867
+ taskAttemptId: z.string(),
868
+ taskRunId: z.string()
869
+ }),
870
+ z.object({
871
+ type: z.literal("SCHEDULE_ATTEMPT"),
872
+ image: z.string(),
873
+ version: z.string(),
874
+ machine: Machine,
875
+ // identifiers
876
+ id: z.string().optional(),
877
+ envId: z.string(),
878
+ envType: EnvironmentType,
879
+ orgId: z.string(),
880
+ projectId: z.string(),
881
+ runId: z.string()
882
+ }),
883
+ z.object({
884
+ type: z.literal("EXECUTE_RUN_LAZY_ATTEMPT"),
885
+ payload: TaskRunExecutionLazyAttemptPayload
886
+ })
884
887
  ]);
885
- var ProviderToPlatformMessages = {
886
- LOG: {
887
- message: z.object({
888
- version: z.literal("v1").default("v1"),
889
- data: z.string()
890
- })
891
- },
892
- LOG_WITH_ACK: {
893
- message: z.object({
894
- version: z.literal("v1").default("v1"),
895
- data: z.string()
896
- }),
897
- callback: z.object({
888
+ var serverWebsocketMessages = {
889
+ SERVER_READY: z.object({
890
+ version: z.literal("v1").default("v1"),
891
+ id: z.string()
892
+ }),
893
+ BACKGROUND_WORKER_MESSAGE: z.object({
894
+ version: z.literal("v1").default("v1"),
895
+ backgroundWorkerId: z.string(),
896
+ data: BackgroundWorkerServerMessages
897
+ })
898
+ };
899
+ var BackgroundWorkerClientMessages = z.discriminatedUnion("type", [
900
+ z.object({
901
+ version: z.literal("v1").default("v1"),
902
+ type: z.literal("TASK_RUN_COMPLETED"),
903
+ completion: TaskRunExecutionResult,
904
+ execution: TaskRunExecution
905
+ }),
906
+ z.object({
907
+ version: z.literal("v1").default("v1"),
908
+ type: z.literal("TASK_RUN_FAILED_TO_RUN"),
909
+ completion: TaskRunFailedExecutionResult
910
+ }),
911
+ z.object({
912
+ version: z.literal("v1").default("v1"),
913
+ type: z.literal("TASK_HEARTBEAT"),
914
+ id: z.string()
915
+ }),
916
+ z.object({
917
+ version: z.literal("v1").default("v1"),
918
+ type: z.literal("TASK_RUN_HEARTBEAT"),
919
+ id: z.string()
920
+ })
921
+ ]);
922
+ var BackgroundWorkerProperties = z.object({
923
+ id: z.string(),
924
+ version: z.string(),
925
+ contentHash: z.string()
926
+ });
927
+ var clientWebsocketMessages = {
928
+ READY_FOR_TASKS: z.object({
929
+ version: z.literal("v1").default("v1"),
930
+ backgroundWorkerId: z.string(),
931
+ inProgressRuns: z.string().array().optional()
932
+ }),
933
+ BACKGROUND_WORKER_DEPRECATED: z.object({
934
+ version: z.literal("v1").default("v1"),
935
+ backgroundWorkerId: z.string()
936
+ }),
937
+ BACKGROUND_WORKER_MESSAGE: z.object({
938
+ version: z.literal("v1").default("v1"),
939
+ backgroundWorkerId: z.string(),
940
+ data: BackgroundWorkerClientMessages
941
+ })
942
+ };
943
+ var workerToChildMessages = {
944
+ EXECUTE_TASK_RUN: z.object({
945
+ version: z.literal("v1").default("v1"),
946
+ execution: TaskRunExecution,
947
+ traceContext: z.record(z.unknown()),
948
+ metadata: BackgroundWorkerProperties
949
+ }),
950
+ TASK_RUN_COMPLETED_NOTIFICATION: z.discriminatedUnion("version", [
951
+ z.object({
952
+ version: z.literal("v1"),
953
+ completion: TaskRunExecutionResult,
954
+ execution: TaskRunExecution
955
+ }),
956
+ z.object({
957
+ version: z.literal("v2"),
958
+ completion: TaskRunExecutionResult
959
+ })
960
+ ]),
961
+ CLEANUP: z.object({
962
+ version: z.literal("v1").default("v1"),
963
+ flush: z.boolean().default(false),
964
+ kill: z.boolean().default(true)
965
+ })
966
+ };
967
+ var UncaughtExceptionMessage = z.object({
968
+ version: z.literal("v1").default("v1"),
969
+ error: z.object({
970
+ name: z.string(),
971
+ message: z.string(),
972
+ stack: z.string().optional()
973
+ }),
974
+ origin: z.enum([
975
+ "uncaughtException",
976
+ "unhandledRejection"
977
+ ])
978
+ });
979
+ var TaskMetadataFailedToParseData = z.object({
980
+ version: z.literal("v1").default("v1"),
981
+ tasks: z.unknown(),
982
+ zodIssues: z.custom((v) => {
983
+ return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
984
+ })
985
+ });
986
+ var childToWorkerMessages = {
987
+ TASK_RUN_COMPLETED: z.object({
988
+ version: z.literal("v1").default("v1"),
989
+ execution: TaskRunExecution,
990
+ result: TaskRunExecutionResult
991
+ }),
992
+ TASKS_READY: z.object({
993
+ version: z.literal("v1").default("v1"),
994
+ tasks: TaskMetadataWithFilePath.array()
995
+ }),
996
+ TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
997
+ TASK_HEARTBEAT: z.object({
998
+ version: z.literal("v1").default("v1"),
999
+ id: z.string()
1000
+ }),
1001
+ TASK_RUN_HEARTBEAT: z.object({
1002
+ version: z.literal("v1").default("v1"),
1003
+ id: z.string()
1004
+ }),
1005
+ READY_TO_DISPOSE: z.undefined(),
1006
+ WAIT_FOR_DURATION: z.object({
1007
+ version: z.literal("v1").default("v1"),
1008
+ ms: z.number()
1009
+ }),
1010
+ WAIT_FOR_TASK: z.object({
1011
+ version: z.literal("v1").default("v1"),
1012
+ id: z.string()
1013
+ }),
1014
+ WAIT_FOR_BATCH: z.object({
1015
+ version: z.literal("v1").default("v1"),
1016
+ id: z.string(),
1017
+ runs: z.string().array()
1018
+ }),
1019
+ UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
1020
+ };
1021
+ var ProdChildToWorkerMessages = {
1022
+ TASK_RUN_COMPLETED: {
1023
+ message: z.object({
1024
+ version: z.literal("v1").default("v1"),
1025
+ execution: TaskRunExecution,
1026
+ result: TaskRunExecutionResult
1027
+ })
1028
+ },
1029
+ TASKS_READY: {
1030
+ message: z.object({
1031
+ version: z.literal("v1").default("v1"),
1032
+ tasks: TaskMetadataWithFilePath.array()
1033
+ })
1034
+ },
1035
+ TASKS_FAILED_TO_PARSE: {
1036
+ message: TaskMetadataFailedToParseData
1037
+ },
1038
+ TASK_HEARTBEAT: {
1039
+ message: z.object({
1040
+ version: z.literal("v1").default("v1"),
1041
+ id: z.string()
1042
+ })
1043
+ },
1044
+ TASK_RUN_HEARTBEAT: {
1045
+ message: z.object({
1046
+ version: z.literal("v1").default("v1"),
1047
+ id: z.string()
1048
+ })
1049
+ },
1050
+ READY_TO_DISPOSE: {
1051
+ message: z.undefined()
1052
+ },
1053
+ READY_FOR_CHECKPOINT: {
1054
+ message: z.object({
1055
+ version: z.literal("v1").default("v1")
1056
+ })
1057
+ },
1058
+ CANCEL_CHECKPOINT: {
1059
+ message: z.discriminatedUnion("version", [
1060
+ z.object({
1061
+ version: z.literal("v1")
1062
+ }),
1063
+ z.object({
1064
+ version: z.literal("v2"),
1065
+ reason: WaitReason.optional()
1066
+ })
1067
+ ]).default({
1068
+ version: "v1"
1069
+ }),
1070
+ callback: z.object({
1071
+ // TODO: Figure out how best to handle callback schema parsing in zod IPC
1072
+ version: z.literal("v2"),
1073
+ checkpointCanceled: z.boolean(),
1074
+ reason: WaitReason.optional()
1075
+ })
1076
+ },
1077
+ WAIT_FOR_DURATION: {
1078
+ message: z.object({
1079
+ version: z.literal("v1").default("v1"),
1080
+ ms: z.number(),
1081
+ now: z.number()
1082
+ }),
1083
+ callback: z.object({
1084
+ willCheckpointAndRestore: z.boolean()
1085
+ })
1086
+ },
1087
+ WAIT_FOR_TASK: {
1088
+ message: z.object({
1089
+ version: z.literal("v1").default("v1"),
1090
+ friendlyId: z.string()
1091
+ })
1092
+ },
1093
+ WAIT_FOR_BATCH: {
1094
+ message: z.object({
1095
+ version: z.literal("v1").default("v1"),
1096
+ batchFriendlyId: z.string(),
1097
+ runFriendlyIds: z.string().array()
1098
+ })
1099
+ },
1100
+ UNCAUGHT_EXCEPTION: {
1101
+ message: UncaughtExceptionMessage
1102
+ }
1103
+ };
1104
+ var ProdWorkerToChildMessages = {
1105
+ EXECUTE_TASK_RUN: {
1106
+ message: z.object({
1107
+ version: z.literal("v1").default("v1"),
1108
+ execution: TaskRunExecution,
1109
+ traceContext: z.record(z.unknown()),
1110
+ metadata: BackgroundWorkerProperties
1111
+ })
1112
+ },
1113
+ TASK_RUN_COMPLETED_NOTIFICATION: {
1114
+ message: z.discriminatedUnion("version", [
1115
+ z.object({
1116
+ version: z.literal("v1"),
1117
+ completion: TaskRunExecutionResult,
1118
+ execution: TaskRunExecution
1119
+ }),
1120
+ z.object({
1121
+ version: z.literal("v2"),
1122
+ completion: TaskRunExecutionResult
1123
+ })
1124
+ ])
1125
+ },
1126
+ CLEANUP: {
1127
+ message: z.object({
1128
+ version: z.literal("v1").default("v1"),
1129
+ flush: z.boolean().default(false),
1130
+ kill: z.boolean().default(true)
1131
+ }),
1132
+ callback: z.void()
1133
+ },
1134
+ WAIT_COMPLETED_NOTIFICATION: {
1135
+ message: z.object({
1136
+ version: z.literal("v1").default("v1")
1137
+ })
1138
+ }
1139
+ };
1140
+ var ProviderToPlatformMessages = {
1141
+ LOG: {
1142
+ message: z.object({
1143
+ version: z.literal("v1").default("v1"),
1144
+ data: z.string()
1145
+ })
1146
+ },
1147
+ LOG_WITH_ACK: {
1148
+ message: z.object({
1149
+ version: z.literal("v1").default("v1"),
1150
+ data: z.string()
1151
+ }),
1152
+ callback: z.object({
898
1153
  status: z.literal("ok")
899
1154
  })
900
1155
  },
@@ -994,6 +1249,17 @@ var PlatformToProviderMessages = {
994
1249
  })
995
1250
  }
996
1251
  };
1252
+ var CreateWorkerMessage = z.object({
1253
+ projectRef: z.string(),
1254
+ envId: z.string(),
1255
+ deploymentId: z.string(),
1256
+ metadata: z.object({
1257
+ cliPackageVersion: z.string().optional(),
1258
+ contentHash: z.string(),
1259
+ packageVersion: z.string(),
1260
+ tasks: TaskResource.array()
1261
+ })
1262
+ });
997
1263
  var CoordinatorToPlatformMessages = {
998
1264
  LOG: {
999
1265
  message: z.object({
@@ -1003,18 +1269,15 @@ var CoordinatorToPlatformMessages = {
1003
1269
  })
1004
1270
  },
1005
1271
  CREATE_WORKER: {
1006
- message: z.object({
1007
- version: z.literal("v1").default("v1"),
1008
- projectRef: z.string(),
1009
- envId: z.string(),
1010
- deploymentId: z.string(),
1011
- metadata: z.object({
1012
- cliPackageVersion: z.string().optional(),
1013
- contentHash: z.string(),
1014
- packageVersion: z.string(),
1015
- tasks: TaskResource.array()
1272
+ message: z.discriminatedUnion("version", [
1273
+ CreateWorkerMessage.extend({
1274
+ version: z.literal("v1")
1275
+ }),
1276
+ CreateWorkerMessage.extend({
1277
+ version: z.literal("v2"),
1278
+ supportsLazyAttempts: z.boolean()
1016
1279
  })
1017
- }),
1280
+ ]),
1018
1281
  callback: z.discriminatedUnion("success", [
1019
1282
  z.object({
1020
1283
  success: z.literal(false)
@@ -1024,15 +1287,32 @@ var CoordinatorToPlatformMessages = {
1024
1287
  })
1025
1288
  ])
1026
1289
  },
1027
- READY_FOR_EXECUTION: {
1290
+ CREATE_TASK_RUN_ATTEMPT: {
1028
1291
  message: z.object({
1029
1292
  version: z.literal("v1").default("v1"),
1030
1293
  runId: z.string(),
1031
- totalCompletions: z.number()
1294
+ envId: z.string()
1032
1295
  }),
1033
1296
  callback: z.discriminatedUnion("success", [
1034
1297
  z.object({
1035
- success: z.literal(false)
1298
+ success: z.literal(false),
1299
+ reason: z.string().optional()
1300
+ }),
1301
+ z.object({
1302
+ success: z.literal(true),
1303
+ executionPayload: ProdTaskRunExecutionPayload
1304
+ })
1305
+ ])
1306
+ },
1307
+ READY_FOR_EXECUTION: {
1308
+ message: z.object({
1309
+ version: z.literal("v1").default("v1"),
1310
+ runId: z.string(),
1311
+ totalCompletions: z.number()
1312
+ }),
1313
+ callback: z.discriminatedUnion("success", [
1314
+ z.object({
1315
+ success: z.literal(false)
1036
1316
  }),
1037
1317
  z.object({
1038
1318
  success: z.literal(true),
@@ -1040,6 +1320,24 @@ var CoordinatorToPlatformMessages = {
1040
1320
  })
1041
1321
  ])
1042
1322
  },
1323
+ READY_FOR_LAZY_ATTEMPT: {
1324
+ message: z.object({
1325
+ version: z.literal("v1").default("v1"),
1326
+ runId: z.string(),
1327
+ envId: z.string(),
1328
+ totalCompletions: z.number()
1329
+ }),
1330
+ callback: z.discriminatedUnion("success", [
1331
+ z.object({
1332
+ success: z.literal(false),
1333
+ reason: z.string().optional()
1334
+ }),
1335
+ z.object({
1336
+ success: z.literal(true),
1337
+ lazyPayload: TaskRunExecutionLazyAttemptPayload
1338
+ })
1339
+ ])
1340
+ },
1043
1341
  READY_FOR_RESUME: {
1044
1342
  message: z.object({
1045
1343
  version: z.literal("v1").default("v1"),
@@ -1058,12 +1356,24 @@ var CoordinatorToPlatformMessages = {
1058
1356
  }).optional()
1059
1357
  })
1060
1358
  },
1359
+ TASK_RUN_FAILED_TO_RUN: {
1360
+ message: z.object({
1361
+ version: z.literal("v1").default("v1"),
1362
+ completion: TaskRunFailedExecutionResult
1363
+ })
1364
+ },
1061
1365
  TASK_HEARTBEAT: {
1062
1366
  message: z.object({
1063
1367
  version: z.literal("v1").default("v1"),
1064
1368
  attemptFriendlyId: z.string()
1065
1369
  })
1066
1370
  },
1371
+ TASK_RUN_HEARTBEAT: {
1372
+ message: z.object({
1373
+ version: z.literal("v1").default("v1"),
1374
+ runId: z.string()
1375
+ })
1376
+ },
1067
1377
  CHECKPOINT_CREATED: {
1068
1378
  message: z.object({
1069
1379
  version: z.literal("v1").default("v1"),
@@ -1102,6 +1412,17 @@ var CoordinatorToPlatformMessages = {
1102
1412
  stack: z.string().optional()
1103
1413
  })
1104
1414
  })
1415
+ },
1416
+ RUN_CRASHED: {
1417
+ message: z.object({
1418
+ version: z.literal("v1").default("v1"),
1419
+ runId: z.string(),
1420
+ error: z.object({
1421
+ name: z.string(),
1422
+ message: z.string(),
1423
+ stack: z.string().optional()
1424
+ })
1425
+ })
1105
1426
  }
1106
1427
  };
1107
1428
  var PlatformToCoordinatorMessages = {
@@ -1129,6 +1450,13 @@ var PlatformToCoordinatorMessages = {
1129
1450
  attemptFriendlyId: z.string()
1130
1451
  })
1131
1452
  },
1453
+ REQUEST_RUN_CANCELLATION: {
1454
+ message: z.object({
1455
+ version: z.literal("v1").default("v1"),
1456
+ runId: z.string(),
1457
+ delayInMs: z.number().optional()
1458
+ })
1459
+ },
1132
1460
  READY_FOR_RETRY: {
1133
1461
  message: z.object({
1134
1462
  version: z.literal("v1").default("v1"),
@@ -1172,6 +1500,12 @@ var SharedQueueToClientMessages = {
1172
1500
  })
1173
1501
  }
1174
1502
  };
1503
+ var IndexTasksMessage = z.object({
1504
+ version: z.literal("v1"),
1505
+ deploymentId: z.string(),
1506
+ tasks: TaskResource.array(),
1507
+ packageVersion: z.string()
1508
+ });
1175
1509
  var ProdWorkerToCoordinatorMessages = {
1176
1510
  LOG: {
1177
1511
  message: z.object({
@@ -1181,12 +1515,15 @@ var ProdWorkerToCoordinatorMessages = {
1181
1515
  callback: z.void()
1182
1516
  },
1183
1517
  INDEX_TASKS: {
1184
- message: z.object({
1185
- version: z.literal("v1").default("v1"),
1186
- deploymentId: z.string(),
1187
- tasks: TaskResource.array(),
1188
- packageVersion: z.string()
1189
- }),
1518
+ message: z.discriminatedUnion("version", [
1519
+ IndexTasksMessage.extend({
1520
+ version: z.literal("v1")
1521
+ }),
1522
+ IndexTasksMessage.extend({
1523
+ version: z.literal("v2"),
1524
+ supportsLazyAttempts: z.boolean()
1525
+ })
1526
+ ]),
1190
1527
  callback: z.discriminatedUnion("success", [
1191
1528
  z.object({
1192
1529
  success: z.literal(false)
@@ -1203,6 +1540,13 @@ var ProdWorkerToCoordinatorMessages = {
1203
1540
  totalCompletions: z.number()
1204
1541
  })
1205
1542
  },
1543
+ READY_FOR_LAZY_ATTEMPT: {
1544
+ message: z.object({
1545
+ version: z.literal("v1").default("v1"),
1546
+ runId: z.string(),
1547
+ totalCompletions: z.number()
1548
+ })
1549
+ },
1206
1550
  READY_FOR_RESUME: {
1207
1551
  message: z.object({
1208
1552
  version: z.literal("v1").default("v1"),
@@ -1216,8 +1560,21 @@ var ProdWorkerToCoordinatorMessages = {
1216
1560
  })
1217
1561
  },
1218
1562
  CANCEL_CHECKPOINT: {
1219
- message: z.object({
1220
- version: z.literal("v1").default("v1")
1563
+ message: z.discriminatedUnion("version", [
1564
+ z.object({
1565
+ version: z.literal("v1")
1566
+ }),
1567
+ z.object({
1568
+ version: z.literal("v2"),
1569
+ reason: WaitReason.optional()
1570
+ })
1571
+ ]).default({
1572
+ version: "v1"
1573
+ }),
1574
+ callback: z.object({
1575
+ version: z.literal("v2").default("v2"),
1576
+ checkpointCanceled: z.boolean(),
1577
+ reason: WaitReason.optional()
1221
1578
  })
1222
1579
  },
1223
1580
  TASK_HEARTBEAT: {
@@ -1226,6 +1583,12 @@ var ProdWorkerToCoordinatorMessages = {
1226
1583
  attemptFriendlyId: z.string()
1227
1584
  })
1228
1585
  },
1586
+ TASK_RUN_HEARTBEAT: {
1587
+ message: z.object({
1588
+ version: z.literal("v1").default("v1"),
1589
+ runId: z.string()
1590
+ })
1591
+ },
1229
1592
  TASK_RUN_COMPLETED: {
1230
1593
  message: z.object({
1231
1594
  version: z.literal("v1").default("v1"),
@@ -1237,6 +1600,12 @@ var ProdWorkerToCoordinatorMessages = {
1237
1600
  shouldExit: z.boolean()
1238
1601
  })
1239
1602
  },
1603
+ TASK_RUN_FAILED_TO_RUN: {
1604
+ message: z.object({
1605
+ version: z.literal("v1").default("v1"),
1606
+ completion: TaskRunFailedExecutionResult
1607
+ })
1608
+ },
1240
1609
  WAIT_FOR_DURATION: {
1241
1610
  message: z.object({
1242
1611
  version: z.literal("v1").default("v1"),
@@ -1281,6 +1650,32 @@ var ProdWorkerToCoordinatorMessages = {
1281
1650
  stack: z.string().optional()
1282
1651
  })
1283
1652
  })
1653
+ },
1654
+ CREATE_TASK_RUN_ATTEMPT: {
1655
+ message: z.object({
1656
+ version: z.literal("v1").default("v1"),
1657
+ runId: z.string()
1658
+ }),
1659
+ callback: z.discriminatedUnion("success", [
1660
+ z.object({
1661
+ success: z.literal(false),
1662
+ reason: z.string().optional()
1663
+ }),
1664
+ z.object({
1665
+ success: z.literal(true),
1666
+ executionPayload: ProdTaskRunExecutionPayload
1667
+ })
1668
+ ])
1669
+ },
1670
+ UNRECOVERABLE_ERROR: {
1671
+ message: z.object({
1672
+ version: z.literal("v1").default("v1"),
1673
+ error: z.object({
1674
+ name: z.string(),
1675
+ message: z.string(),
1676
+ stack: z.string().optional()
1677
+ })
1678
+ })
1284
1679
  }
1285
1680
  };
1286
1681
  var CoordinatorToProdWorkerMessages = {
@@ -1304,6 +1699,12 @@ var CoordinatorToProdWorkerMessages = {
1304
1699
  executionPayload: ProdTaskRunExecutionPayload
1305
1700
  })
1306
1701
  },
1702
+ EXECUTE_TASK_RUN_LAZY_ATTEMPT: {
1703
+ message: z.object({
1704
+ version: z.literal("v1").default("v1"),
1705
+ lazyPayload: TaskRunExecutionLazyAttemptPayload
1706
+ })
1707
+ },
1307
1708
  REQUEST_ATTEMPT_CANCELLATION: {
1308
1709
  message: z.object({
1309
1710
  version: z.literal("v1").default("v1"),
@@ -1311,9 +1712,15 @@ var CoordinatorToProdWorkerMessages = {
1311
1712
  })
1312
1713
  },
1313
1714
  REQUEST_EXIT: {
1314
- message: z.object({
1315
- version: z.literal("v1").default("v1")
1316
- })
1715
+ message: z.discriminatedUnion("version", [
1716
+ z.object({
1717
+ version: z.literal("v1")
1718
+ }),
1719
+ z.object({
1720
+ version: z.literal("v2"),
1721
+ delayInMs: z.number().optional()
1722
+ })
1723
+ ])
1317
1724
  },
1318
1725
  READY_FOR_RETRY: {
1319
1726
  message: z.object({
@@ -1531,143 +1938,162 @@ var SpanMessagingEvent = z.object({
1531
1938
  destination: z.string().optional()
1532
1939
  });
1533
1940
 
1534
- // src/v3/apiErrors.ts
1535
- var _APIError = class _APIError extends Error {
1536
- constructor(status, error, message, headers) {
1537
- super(`${_APIError.makeMessage(status, error, message)}`);
1538
- this.status = status;
1539
- this.headers = headers;
1540
- const data = error;
1541
- this.error = data;
1542
- this.code = data?.["code"];
1543
- this.param = data?.["param"];
1544
- this.type = data?.["type"];
1941
+ // src/v3/utils/platform.ts
1942
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
1943
+
1944
+ // src/v3/utils/globals.ts
1945
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
1946
+ var _global = _globalThis;
1947
+ function registerGlobal(type, instance, allowOverride = false) {
1948
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
1949
+ if (!allowOverride && api[type]) {
1950
+ return false;
1545
1951
  }
1546
- static makeMessage(status, error, message) {
1547
- const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1548
- if (status && msg) {
1549
- return `${status} ${msg}`;
1550
- }
1551
- if (status) {
1552
- return `${status} status code (no body)`;
1553
- }
1554
- if (msg) {
1555
- return msg;
1556
- }
1557
- return "(no status code or body)";
1952
+ api[type] = instance;
1953
+ return true;
1954
+ }
1955
+ __name(registerGlobal, "registerGlobal");
1956
+ function getGlobal(type) {
1957
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
1958
+ }
1959
+ __name(getGlobal, "getGlobal");
1960
+ function unregisterGlobal(type) {
1961
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
1962
+ if (api) {
1963
+ delete api[type];
1558
1964
  }
1559
- static generate(status, errorResponse, message, headers) {
1560
- if (!status) {
1561
- return new APIConnectionError({
1562
- cause: castToError(errorResponse)
1563
- });
1564
- }
1565
- const error = errorResponse?.["error"];
1566
- if (status === 400) {
1567
- return new BadRequestError(status, error, message, headers);
1568
- }
1569
- if (status === 401) {
1570
- return new AuthenticationError(status, error, message, headers);
1965
+ }
1966
+ __name(unregisterGlobal, "unregisterGlobal");
1967
+
1968
+ // src/v3/semanticInternalAttributes.ts
1969
+ var SemanticInternalAttributes = {
1970
+ ENVIRONMENT_ID: "ctx.environment.id",
1971
+ ENVIRONMENT_TYPE: "ctx.environment.type",
1972
+ ORGANIZATION_ID: "ctx.organization.id",
1973
+ ORGANIZATION_SLUG: "ctx.organization.slug",
1974
+ ORGANIZATION_NAME: "ctx.organization.name",
1975
+ PROJECT_ID: "ctx.project.id",
1976
+ PROJECT_REF: "ctx.project.ref",
1977
+ PROJECT_NAME: "ctx.project.title",
1978
+ PROJECT_DIR: "project.dir",
1979
+ ATTEMPT_ID: "ctx.attempt.id",
1980
+ ATTEMPT_NUMBER: "ctx.attempt.number",
1981
+ RUN_ID: "ctx.run.id",
1982
+ RUN_IS_TEST: "ctx.run.isTest",
1983
+ BATCH_ID: "ctx.batch.id",
1984
+ TASK_SLUG: "ctx.task.id",
1985
+ TASK_PATH: "ctx.task.filePath",
1986
+ TASK_EXPORT_NAME: "ctx.task.exportName",
1987
+ QUEUE_NAME: "ctx.queue.name",
1988
+ QUEUE_ID: "ctx.queue.id",
1989
+ SPAN_PARTIAL: "$span.partial",
1990
+ SPAN_ID: "$span.span_id",
1991
+ OUTPUT: "$output",
1992
+ OUTPUT_TYPE: "$mime_type_output",
1993
+ STYLE: "$style",
1994
+ STYLE_ICON: "$style.icon",
1995
+ STYLE_VARIANT: "$style.variant",
1996
+ STYLE_ACCESSORY: "$style.accessory",
1997
+ METADATA: "$metadata",
1998
+ TRIGGER: "$trigger",
1999
+ PAYLOAD: "$payload",
2000
+ PAYLOAD_TYPE: "$mime_type_payload",
2001
+ SHOW: "$show",
2002
+ SHOW_ACTIONS: "$show.actions",
2003
+ WORKER_ID: "worker.id",
2004
+ WORKER_VERSION: "worker.version",
2005
+ CLI_VERSION: "cli.version",
2006
+ SDK_VERSION: "sdk.version",
2007
+ SDK_LANGUAGE: "sdk.language",
2008
+ RETRY_AT: "retry.at",
2009
+ RETRY_DELAY: "retry.delay",
2010
+ RETRY_COUNT: "retry.count",
2011
+ LINK_TITLE: "$link.title",
2012
+ IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
2013
+ };
2014
+
2015
+ // src/v3/taskContext/index.ts
2016
+ var API_NAME = "task-context";
2017
+ var _getTaskContext, getTaskContext_fn;
2018
+ var _TaskContextAPI = class _TaskContextAPI {
2019
+ constructor() {
2020
+ __privateAdd(this, _getTaskContext);
2021
+ }
2022
+ static getInstance() {
2023
+ if (!this._instance) {
2024
+ this._instance = new _TaskContextAPI();
1571
2025
  }
1572
- if (status === 403) {
1573
- return new PermissionDeniedError(status, error, message, headers);
2026
+ return this._instance;
2027
+ }
2028
+ get isInsideTask() {
2029
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
2030
+ }
2031
+ get ctx() {
2032
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
2033
+ }
2034
+ get worker() {
2035
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
2036
+ }
2037
+ get attributes() {
2038
+ if (this.ctx) {
2039
+ return {
2040
+ ...this.contextAttributes,
2041
+ ...this.workerAttributes
2042
+ };
1574
2043
  }
1575
- if (status === 404) {
1576
- return new NotFoundError(status, error, message, headers);
2044
+ return {};
2045
+ }
2046
+ get workerAttributes() {
2047
+ if (this.worker) {
2048
+ return {
2049
+ [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
2050
+ [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
2051
+ };
1577
2052
  }
1578
- if (status === 409) {
1579
- return new ConflictError(status, error, message, headers);
1580
- }
1581
- if (status === 422) {
1582
- return new UnprocessableEntityError(status, error, message, headers);
1583
- }
1584
- if (status === 429) {
1585
- return new RateLimitError(status, error, message, headers);
1586
- }
1587
- if (status >= 500) {
1588
- return new InternalServerError(status, error, message, headers);
1589
- }
1590
- return new _APIError(status, error, message, headers);
1591
- }
1592
- };
1593
- __name(_APIError, "APIError");
1594
- var APIError = _APIError;
1595
- var _APIConnectionError = class _APIConnectionError extends APIError {
1596
- constructor({ message, cause }) {
1597
- super(void 0, void 0, message || "Connection error.", void 0);
1598
- __publicField(this, "status");
1599
- if (cause)
1600
- this.cause = cause;
1601
- }
1602
- };
1603
- __name(_APIConnectionError, "APIConnectionError");
1604
- var APIConnectionError = _APIConnectionError;
1605
- var _BadRequestError = class _BadRequestError extends APIError {
1606
- constructor() {
1607
- super(...arguments);
1608
- __publicField(this, "status", 400);
1609
- }
1610
- };
1611
- __name(_BadRequestError, "BadRequestError");
1612
- var BadRequestError = _BadRequestError;
1613
- var _AuthenticationError = class _AuthenticationError extends APIError {
1614
- constructor() {
1615
- super(...arguments);
1616
- __publicField(this, "status", 401);
1617
- }
1618
- };
1619
- __name(_AuthenticationError, "AuthenticationError");
1620
- var AuthenticationError = _AuthenticationError;
1621
- var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
1622
- constructor() {
1623
- super(...arguments);
1624
- __publicField(this, "status", 403);
1625
- }
1626
- };
1627
- __name(_PermissionDeniedError, "PermissionDeniedError");
1628
- var PermissionDeniedError = _PermissionDeniedError;
1629
- var _NotFoundError = class _NotFoundError extends APIError {
1630
- constructor() {
1631
- super(...arguments);
1632
- __publicField(this, "status", 404);
2053
+ return {};
1633
2054
  }
1634
- };
1635
- __name(_NotFoundError, "NotFoundError");
1636
- var NotFoundError = _NotFoundError;
1637
- var _ConflictError = class _ConflictError extends APIError {
1638
- constructor() {
1639
- super(...arguments);
1640
- __publicField(this, "status", 409);
2055
+ get contextAttributes() {
2056
+ if (this.ctx) {
2057
+ return {
2058
+ [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
2059
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
2060
+ [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
2061
+ [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
2062
+ [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
2063
+ [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
2064
+ [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
2065
+ [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
2066
+ [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
2067
+ [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
2068
+ [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
2069
+ [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
2070
+ [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
2071
+ [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
2072
+ [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
2073
+ [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
2074
+ [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
2075
+ [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
2076
+ [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
2077
+ };
2078
+ }
2079
+ return {};
1641
2080
  }
1642
- };
1643
- __name(_ConflictError, "ConflictError");
1644
- var ConflictError = _ConflictError;
1645
- var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
1646
- constructor() {
1647
- super(...arguments);
1648
- __publicField(this, "status", 422);
2081
+ disable() {
2082
+ unregisterGlobal(API_NAME);
1649
2083
  }
1650
- };
1651
- __name(_UnprocessableEntityError, "UnprocessableEntityError");
1652
- var UnprocessableEntityError = _UnprocessableEntityError;
1653
- var _RateLimitError = class _RateLimitError extends APIError {
1654
- constructor() {
1655
- super(...arguments);
1656
- __publicField(this, "status", 429);
2084
+ setGlobalTaskContext(taskContext2) {
2085
+ return registerGlobal(API_NAME, taskContext2);
1657
2086
  }
1658
2087
  };
1659
- __name(_RateLimitError, "RateLimitError");
1660
- var RateLimitError = _RateLimitError;
1661
- var _InternalServerError = class _InternalServerError extends APIError {
1662
- };
1663
- __name(_InternalServerError, "InternalServerError");
1664
- var InternalServerError = _InternalServerError;
1665
- function castToError(err) {
1666
- if (err instanceof Error)
1667
- return err;
1668
- return new Error(err);
1669
- }
1670
- __name(castToError, "castToError");
2088
+ _getTaskContext = new WeakSet();
2089
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
2090
+ return getGlobal(API_NAME);
2091
+ }, "#getTaskContext");
2092
+ __name(_TaskContextAPI, "TaskContextAPI");
2093
+ var TaskContextAPI = _TaskContextAPI;
2094
+
2095
+ // src/v3/task-context-api.ts
2096
+ var taskContext = TaskContextAPI.getInstance();
1671
2097
 
1672
2098
  // src/retry.ts
1673
2099
  function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
@@ -1775,8 +2201,6 @@ function calculateResetAt2(resets, format, now = Date.now()) {
1775
2201
  return resetAt?.getTime();
1776
2202
  }
1777
2203
  __name(calculateResetAt2, "calculateResetAt");
1778
-
1779
- // src/v3/zodfetch.ts
1780
2204
  var defaultRetryOptions2 = {
1781
2205
  maxAttempts: 3,
1782
2206
  factor: 2,
@@ -1788,6 +2212,32 @@ async function zodfetch(schema, url, requestInit, options) {
1788
2212
  return await _doZodFetch(schema, url, requestInit, options);
1789
2213
  }
1790
2214
  __name(zodfetch, "zodfetch");
2215
+ async function zodupload(schema, url, body, requestInit, options) {
2216
+ const form = await createForm(body);
2217
+ const encoder = new FormDataEncoder(form);
2218
+ const finalHeaders = {};
2219
+ for (const [key, value] of Object.entries(requestInit?.headers || {})) {
2220
+ finalHeaders[key] = value;
2221
+ }
2222
+ for (const [key, value] of Object.entries(encoder.headers)) {
2223
+ finalHeaders[key] = value;
2224
+ }
2225
+ finalHeaders["Content-Length"] = String(encoder.contentLength);
2226
+ const finalRequestInit = {
2227
+ ...requestInit,
2228
+ headers: finalHeaders,
2229
+ body: Readable.from(encoder),
2230
+ // @ts-expect-error
2231
+ duplex: "half"
2232
+ };
2233
+ return await _doZodFetch(schema, url, finalRequestInit, options);
2234
+ }
2235
+ __name(zodupload, "zodupload");
2236
+ var createForm = /* @__PURE__ */ __name(async (body) => {
2237
+ const form = new FormData();
2238
+ await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
2239
+ return form;
2240
+ }, "createForm");
1791
2241
  async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1792
2242
  try {
1793
2243
  const response = await fetch(url, requestInitWithCache(requestInit));
@@ -1909,345 +2359,177 @@ function requestInitWithCache(requestInit) {
1909
2359
  }
1910
2360
  }
1911
2361
  __name(requestInitWithCache, "requestInitWithCache");
1912
-
1913
- // src/v3/utils/flattenAttributes.ts
1914
- function flattenAttributes(obj, prefix) {
1915
- const result = {};
1916
- if (!obj) {
1917
- return result;
1918
- }
1919
- if (typeof obj === "string") {
1920
- result[prefix || ""] = obj;
1921
- return result;
2362
+ var addFormValue = /* @__PURE__ */ __name(async (form, key, value) => {
2363
+ if (value === void 0)
2364
+ return;
2365
+ if (value == null) {
2366
+ throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
2367
+ }
2368
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
2369
+ form.append(key, String(value));
2370
+ } else if (isUploadable(value) || isBlobLike(value) || value instanceof Buffer || value instanceof ArrayBuffer) {
2371
+ const file = await toFile(value);
2372
+ form.append(key, file);
2373
+ } else if (Array.isArray(value)) {
2374
+ await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry)));
2375
+ } else if (typeof value === "object") {
2376
+ await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));
2377
+ } else {
2378
+ throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
2379
+ }
2380
+ }, "addFormValue");
2381
+ async function toFile(value, name, options) {
2382
+ value = await value;
2383
+ options ??= isFileLike(value) ? {
2384
+ lastModified: value.lastModified,
2385
+ type: value.type
2386
+ } : {};
2387
+ if (isResponseLike(value)) {
2388
+ const blob = await value.blob();
2389
+ name ||= new URL(value.url).pathname.split(/[\\/]/).pop() ?? "unknown_file";
2390
+ return new File([
2391
+ blob
2392
+ ], name, options);
2393
+ }
2394
+ const bits = await getBytes(value);
2395
+ name ||= getName(value) ?? "unknown_file";
2396
+ if (!options.type) {
2397
+ const type = bits[0]?.type;
2398
+ if (typeof type === "string") {
2399
+ options = {
2400
+ ...options,
2401
+ type
2402
+ };
2403
+ }
1922
2404
  }
1923
- if (typeof obj === "number") {
1924
- result[prefix || ""] = obj;
1925
- return result;
2405
+ return new File(bits, name, options);
2406
+ }
2407
+ __name(toFile, "toFile");
2408
+ function getName(value) {
2409
+ return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream
2410
+ getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop();
2411
+ }
2412
+ __name(getName, "getName");
2413
+ var getStringFromMaybeBuffer = /* @__PURE__ */ __name((x) => {
2414
+ if (typeof x === "string")
2415
+ return x;
2416
+ if (typeof Buffer !== "undefined" && x instanceof Buffer)
2417
+ return String(x);
2418
+ return void 0;
2419
+ }, "getStringFromMaybeBuffer");
2420
+ async function getBytes(value) {
2421
+ let parts = [];
2422
+ if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
2423
+ value instanceof ArrayBuffer) {
2424
+ parts.push(value);
2425
+ } else if (isBlobLike(value)) {
2426
+ parts.push(await value.arrayBuffer());
2427
+ } else if (isAsyncIterableIterator(value)) {
2428
+ for await (const chunk of value) {
2429
+ parts.push(chunk);
2430
+ }
2431
+ } else {
2432
+ throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor?.name}; props: ${propsForError(value)}`);
2433
+ }
2434
+ return parts;
2435
+ }
2436
+ __name(getBytes, "getBytes");
2437
+ function propsForError(value) {
2438
+ const props = Object.getOwnPropertyNames(value);
2439
+ return `[${props.map((p) => `"${p}"`).join(", ")}]`;
2440
+ }
2441
+ __name(propsForError, "propsForError");
2442
+ var isAsyncIterableIterator = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function", "isAsyncIterableIterator");
2443
+ var isResponseLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function", "isResponseLike");
2444
+ var isFileLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value), "isFileLike");
2445
+ var isBlobLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function", "isBlobLike");
2446
+ var isFsReadStream = /* @__PURE__ */ __name((value) => value instanceof Readable, "isFsReadStream");
2447
+ var isUploadable = /* @__PURE__ */ __name((value) => {
2448
+ return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);
2449
+ }, "isUploadable");
2450
+ var isRecordLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => typeof key === "string" && typeof value[key] === "string"), "isRecordLike");
2451
+
2452
+ // src/v3/apiClient/index.ts
2453
+ var zodFetchOptions = {
2454
+ retry: {
2455
+ maxAttempts: 3,
2456
+ minTimeoutInMs: 1e3,
2457
+ maxTimeoutInMs: 3e4,
2458
+ factor: 2,
2459
+ randomize: false
1926
2460
  }
1927
- if (typeof obj === "boolean") {
1928
- result[prefix || ""] = obj;
1929
- return result;
2461
+ };
2462
+ var _getHeaders, getHeaders_fn;
2463
+ var _ApiClient = class _ApiClient {
2464
+ constructor(baseUrl, accessToken) {
2465
+ __privateAdd(this, _getHeaders);
2466
+ this.accessToken = accessToken;
2467
+ this.baseUrl = baseUrl.replace(/\/$/, "");
1930
2468
  }
1931
- for (const [key, value] of Object.entries(obj)) {
1932
- const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
1933
- if (Array.isArray(value)) {
1934
- for (let i = 0; i < value.length; i++) {
1935
- if (typeof value[i] === "object" && value[i] !== null) {
1936
- Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
1937
- } else {
1938
- result[`${newPrefix}.[${i}]`] = value[i];
2469
+ async getRunResult(runId) {
2470
+ try {
2471
+ return await zodfetch(TaskRunExecutionResult, `${this.baseUrl}/api/v1/runs/${runId}/result`, {
2472
+ method: "GET",
2473
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2474
+ }, zodFetchOptions);
2475
+ } catch (error) {
2476
+ if (error instanceof APIError) {
2477
+ if (error.status === 404) {
2478
+ return void 0;
1939
2479
  }
1940
2480
  }
1941
- } else if (isRecord(value)) {
1942
- Object.assign(result, flattenAttributes(value, newPrefix));
1943
- } else {
1944
- if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
1945
- result[newPrefix] = value;
1946
- }
2481
+ throw error;
1947
2482
  }
1948
2483
  }
1949
- return result;
1950
- }
1951
- __name(flattenAttributes, "flattenAttributes");
1952
- function isRecord(value) {
1953
- return value !== null && typeof value === "object" && !Array.isArray(value);
1954
- }
1955
- __name(isRecord, "isRecord");
1956
- function unflattenAttributes(obj) {
1957
- if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
1958
- return obj;
2484
+ async getBatchResults(batchId) {
2485
+ return await zodfetch(BatchTaskRunExecutionResult, `${this.baseUrl}/api/v1/batches/${batchId}/results`, {
2486
+ method: "GET",
2487
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2488
+ }, zodFetchOptions);
1959
2489
  }
1960
- const result = {};
1961
- for (const [key, value] of Object.entries(obj)) {
1962
- const parts = key.split(".").reduce((acc, part) => {
1963
- if (detectIsArrayIndex(part)) {
1964
- acc.push(part);
1965
- } else {
1966
- acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
1967
- }
1968
- return acc;
1969
- }, []);
1970
- let current = result;
1971
- for (let i = 0; i < parts.length - 1; i++) {
1972
- const part = parts[i];
1973
- const isArray = detectIsArrayIndex(part);
1974
- const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
1975
- const nextIsArray = detectIsArrayIndex(parts[i + 1]);
1976
- if (!current[cleanPart]) {
1977
- current[cleanPart] = nextIsArray ? [] : {};
1978
- }
1979
- current = current[cleanPart];
1980
- }
1981
- const lastPart = parts[parts.length - 1];
1982
- const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
1983
- current[cleanLastPart] = value;
2490
+ triggerTask(taskId, body, options) {
2491
+ return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
2492
+ method: "POST",
2493
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2494
+ body: JSON.stringify(body)
2495
+ }, zodFetchOptions);
1984
2496
  }
1985
- return result;
1986
- }
1987
- __name(unflattenAttributes, "unflattenAttributes");
1988
- function detectIsArrayIndex(key) {
1989
- const match = key.match(/^\[(\d+)\]$/);
1990
- if (match) {
1991
- return true;
2497
+ batchTriggerTask(taskId, body, options) {
2498
+ return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
2499
+ method: "POST",
2500
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2501
+ body: JSON.stringify(body)
2502
+ }, zodFetchOptions);
1992
2503
  }
1993
- return false;
1994
- }
1995
- __name(detectIsArrayIndex, "detectIsArrayIndex");
1996
- function primitiveValueOrflattenedAttributes(obj, prefix) {
1997
- if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
1998
- return obj;
2504
+ createUploadPayloadUrl(filename) {
2505
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2506
+ method: "PUT",
2507
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2508
+ }, zodFetchOptions);
1999
2509
  }
2000
- const attributes = flattenAttributes(obj, prefix);
2001
- if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
2002
- return attributes[prefix];
2510
+ getPayloadUrl(filename) {
2511
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2512
+ method: "GET",
2513
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2514
+ }, zodFetchOptions);
2003
2515
  }
2004
- return attributes;
2005
- }
2006
- __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
2007
- var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
2008
- constructor() {
2009
- this.storage = new AsyncLocalStorage();
2516
+ retrieveRun(runId) {
2517
+ return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v3/runs/${runId}`, {
2518
+ method: "GET",
2519
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2520
+ }, zodFetchOptions);
2010
2521
  }
2011
- runWith(context3, fn) {
2012
- return this.storage.run(context3, fn);
2522
+ replayRun(runId) {
2523
+ return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2524
+ method: "POST",
2525
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2526
+ }, zodFetchOptions);
2013
2527
  }
2014
- getStore() {
2015
- return this.storage.getStore();
2016
- }
2017
- };
2018
- __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
2019
- var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
2020
-
2021
- // src/v3/semanticInternalAttributes.ts
2022
- var SemanticInternalAttributes = {
2023
- ENVIRONMENT_ID: "ctx.environment.id",
2024
- ENVIRONMENT_TYPE: "ctx.environment.type",
2025
- ORGANIZATION_ID: "ctx.organization.id",
2026
- ORGANIZATION_SLUG: "ctx.organization.slug",
2027
- ORGANIZATION_NAME: "ctx.organization.name",
2028
- PROJECT_ID: "ctx.project.id",
2029
- PROJECT_REF: "ctx.project.ref",
2030
- PROJECT_NAME: "ctx.project.title",
2031
- PROJECT_DIR: "project.dir",
2032
- ATTEMPT_ID: "ctx.attempt.id",
2033
- ATTEMPT_NUMBER: "ctx.attempt.number",
2034
- RUN_ID: "ctx.run.id",
2035
- RUN_IS_TEST: "ctx.run.isTest",
2036
- BATCH_ID: "ctx.batch.id",
2037
- TASK_SLUG: "ctx.task.id",
2038
- TASK_PATH: "ctx.task.filePath",
2039
- TASK_EXPORT_NAME: "ctx.task.exportName",
2040
- QUEUE_NAME: "ctx.queue.name",
2041
- QUEUE_ID: "ctx.queue.id",
2042
- SPAN_PARTIAL: "$span.partial",
2043
- SPAN_ID: "$span.span_id",
2044
- OUTPUT: "$output",
2045
- OUTPUT_TYPE: "$mime_type_output",
2046
- STYLE: "$style",
2047
- STYLE_ICON: "$style.icon",
2048
- STYLE_VARIANT: "$style.variant",
2049
- STYLE_ACCESSORY: "$style.accessory",
2050
- METADATA: "$metadata",
2051
- TRIGGER: "$trigger",
2052
- PAYLOAD: "$payload",
2053
- PAYLOAD_TYPE: "$mime_type_payload",
2054
- SHOW: "$show",
2055
- SHOW_ACTIONS: "$show.actions",
2056
- WORKER_ID: "worker.id",
2057
- WORKER_VERSION: "worker.version",
2058
- CLI_VERSION: "cli.version",
2059
- SDK_VERSION: "sdk.version",
2060
- SDK_LANGUAGE: "sdk.language",
2061
- RETRY_AT: "retry.at",
2062
- RETRY_DELAY: "retry.delay",
2063
- RETRY_COUNT: "retry.count",
2064
- LINK_TITLE: "$link.title"
2065
- };
2066
-
2067
- // src/v3/tasks/taskContextManager.ts
2068
- var _getStore, getStore_fn;
2069
- var _TaskContextManager = class _TaskContextManager {
2070
- constructor() {
2071
- __privateAdd(this, _getStore);
2072
- __publicField(this, "_storage", new SafeAsyncLocalStorage());
2073
- }
2074
- get isInsideTask() {
2075
- return __privateMethod(this, _getStore, getStore_fn).call(this) !== void 0;
2076
- }
2077
- get ctx() {
2078
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2079
- return store?.ctx;
2080
- }
2081
- get worker() {
2082
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2083
- return store?.worker;
2084
- }
2085
- get attributes() {
2086
- if (this.ctx) {
2087
- return {
2088
- ...this.contextAttributes,
2089
- ...this.workerAttributes
2090
- };
2091
- }
2092
- return {};
2093
- }
2094
- get workerAttributes() {
2095
- if (this.worker) {
2096
- return {
2097
- [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
2098
- [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
2099
- };
2100
- }
2101
- return {};
2102
- }
2103
- get contextAttributes() {
2104
- if (this.ctx) {
2105
- return {
2106
- [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
2107
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
2108
- [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
2109
- [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
2110
- [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
2111
- [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
2112
- [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
2113
- [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
2114
- [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
2115
- [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
2116
- [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
2117
- [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
2118
- [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
2119
- [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
2120
- [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
2121
- [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
2122
- [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
2123
- [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id
2124
- };
2125
- }
2126
- return {};
2127
- }
2128
- runWith(context3, fn) {
2129
- return this._storage.runWith(context3, fn);
2130
- }
2131
- };
2132
- _getStore = new WeakSet();
2133
- getStore_fn = /* @__PURE__ */ __name(function() {
2134
- return this._storage.getStore();
2135
- }, "#getStore");
2136
- __name(_TaskContextManager, "TaskContextManager");
2137
- var TaskContextManager = _TaskContextManager;
2138
- var taskContextManager = new TaskContextManager();
2139
- var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
2140
- constructor(innerProcessor) {
2141
- this._innerProcessor = innerProcessor;
2142
- }
2143
- // Called when a span starts
2144
- onStart(span, parentContext) {
2145
- if (taskContextManager.ctx) {
2146
- span.setAttributes(flattenAttributes({
2147
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
2148
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
2149
- }, SemanticInternalAttributes.METADATA));
2150
- }
2151
- this._innerProcessor.onStart(span, parentContext);
2152
- }
2153
- // Delegate the rest of the methods to the wrapped processor
2154
- onEnd(span) {
2155
- this._innerProcessor.onEnd(span);
2156
- }
2157
- shutdown() {
2158
- return this._innerProcessor.shutdown();
2159
- }
2160
- forceFlush() {
2161
- return this._innerProcessor.forceFlush();
2162
- }
2163
- };
2164
- __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
2165
- var TaskContextSpanProcessor = _TaskContextSpanProcessor;
2166
- var _TaskContextLogProcessor = class _TaskContextLogProcessor {
2167
- constructor(innerProcessor) {
2168
- this._innerProcessor = innerProcessor;
2169
- }
2170
- forceFlush() {
2171
- return this._innerProcessor.forceFlush();
2172
- }
2173
- onEmit(logRecord, context3) {
2174
- if (taskContextManager.ctx) {
2175
- logRecord.setAttributes(flattenAttributes({
2176
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
2177
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
2178
- }, SemanticInternalAttributes.METADATA));
2179
- }
2180
- this._innerProcessor.onEmit(logRecord, context3);
2181
- }
2182
- shutdown() {
2183
- return this._innerProcessor.shutdown();
2184
- }
2185
- };
2186
- __name(_TaskContextLogProcessor, "TaskContextLogProcessor");
2187
- var TaskContextLogProcessor = _TaskContextLogProcessor;
2188
-
2189
- // src/v3/utils/getEnv.ts
2190
- function getEnvVar(name) {
2191
- if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
2192
- return process.env[name];
2193
- }
2194
- }
2195
- __name(getEnvVar, "getEnvVar");
2196
-
2197
- // src/v3/apiClient/index.ts
2198
- var zodFetchOptions = {
2199
- retry: {
2200
- maxAttempts: 3,
2201
- minTimeoutInMs: 1e3,
2202
- maxTimeoutInMs: 3e4,
2203
- factor: 2,
2204
- randomize: false
2205
- }
2206
- };
2207
- var _getHeaders, getHeaders_fn;
2208
- var _ApiClient = class _ApiClient {
2209
- constructor(baseUrl, accessToken) {
2210
- __privateAdd(this, _getHeaders);
2211
- this.accessToken = accessToken;
2212
- this.baseUrl = baseUrl.replace(/\/$/, "");
2213
- }
2214
- triggerTask(taskId, body, options) {
2215
- return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
2216
- method: "POST",
2217
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2218
- body: JSON.stringify(body)
2219
- }, zodFetchOptions);
2220
- }
2221
- batchTriggerTask(taskId, body, options) {
2222
- return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
2223
- method: "POST",
2224
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2225
- body: JSON.stringify(body)
2226
- }, zodFetchOptions);
2227
- }
2228
- createUploadPayloadUrl(filename) {
2229
- return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2230
- method: "PUT",
2231
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2232
- }, zodFetchOptions);
2233
- }
2234
- getPayloadUrl(filename) {
2235
- return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2236
- method: "GET",
2237
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2238
- }, zodFetchOptions);
2239
- }
2240
- replayRun(runId) {
2241
- return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2242
- method: "POST",
2243
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2244
- }, zodFetchOptions);
2245
- }
2246
- cancelRun(runId) {
2247
- return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
2248
- method: "POST",
2249
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2250
- }, zodFetchOptions);
2528
+ cancelRun(runId) {
2529
+ return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
2530
+ method: "POST",
2531
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2532
+ }, zodFetchOptions);
2251
2533
  }
2252
2534
  createSchedule(options) {
2253
2535
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
@@ -2300,14 +2582,62 @@ var _ApiClient = class _ApiClient {
2300
2582
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2301
2583
  });
2302
2584
  }
2585
+ listEnvVars(projectRef, slug) {
2586
+ return zodfetch(EnvironmentVariables, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2587
+ method: "GET",
2588
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2589
+ });
2590
+ }
2591
+ importEnvVars(projectRef, slug, body) {
2592
+ if (isRecordLike(body.variables)) {
2593
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
2594
+ method: "POST",
2595
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2596
+ body: JSON.stringify(body)
2597
+ });
2598
+ } else {
2599
+ return zodupload(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, body, {
2600
+ method: "POST",
2601
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2602
+ });
2603
+ }
2604
+ }
2605
+ retrieveEnvVar(projectRef, slug, key) {
2606
+ return zodfetch(EnvironmentVariableValue, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2607
+ method: "GET",
2608
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2609
+ });
2610
+ }
2611
+ createEnvVar(projectRef, slug, body) {
2612
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
2613
+ method: "POST",
2614
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2615
+ body: JSON.stringify(body)
2616
+ });
2617
+ }
2618
+ updateEnvVar(projectRef, slug, key, body) {
2619
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2620
+ method: "PUT",
2621
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2622
+ body: JSON.stringify(body)
2623
+ });
2624
+ }
2625
+ deleteEnvVar(projectRef, slug, key) {
2626
+ return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
2627
+ method: "DELETE",
2628
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2629
+ });
2630
+ }
2303
2631
  };
2304
2632
  _getHeaders = new WeakSet();
2305
2633
  getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2306
2634
  const headers = {
2307
2635
  "Content-Type": "application/json",
2308
- Authorization: `Bearer ${this.accessToken}`
2636
+ Authorization: `Bearer ${this.accessToken}`,
2637
+ "trigger-version": version
2309
2638
  };
2310
- if (taskContextManager.isInsideTask) {
2639
+ if (taskContext.isInsideTask) {
2640
+ headers["x-trigger-worker"] = "true";
2311
2641
  propagation.inject(context.active(), headers);
2312
2642
  if (spanParentAsLink) {
2313
2643
  headers["x-trigger-span-parent-as-link"] = "1";
@@ -2317,767 +2647,63 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2317
2647
  }, "#getHeaders");
2318
2648
  __name(_ApiClient, "ApiClient");
2319
2649
  var ApiClient = _ApiClient;
2320
- var _getStore2, getStore_fn2;
2321
- var _ApiClientManager = class _ApiClientManager {
2322
- constructor() {
2323
- __privateAdd(this, _getStore2);
2324
- __publicField(this, "_storage", new SafeAsyncLocalStorage());
2650
+ var _SimpleClock = class _SimpleClock {
2651
+ preciseNow() {
2652
+ const now = new PreciseDate();
2653
+ const nowStruct = now.toStruct();
2654
+ return [
2655
+ nowStruct.seconds,
2656
+ nowStruct.nanos
2657
+ ];
2325
2658
  }
2326
- get baseURL() {
2327
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
2328
- return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
2659
+ reset() {
2329
2660
  }
2330
- get accessToken() {
2331
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
2332
- return store?.accessToken ?? getEnvVar("TRIGGER_SECRET_KEY");
2661
+ };
2662
+ __name(_SimpleClock, "SimpleClock");
2663
+ var SimpleClock = _SimpleClock;
2664
+
2665
+ // src/v3/clock/index.ts
2666
+ var API_NAME2 = "clock";
2667
+ var SIMPLE_CLOCK = new SimpleClock();
2668
+ var _getClock, getClock_fn;
2669
+ var _ClockAPI = class _ClockAPI {
2670
+ constructor() {
2671
+ __privateAdd(this, _getClock);
2333
2672
  }
2334
- get client() {
2335
- if (!this.baseURL || !this.accessToken) {
2336
- return void 0;
2673
+ static getInstance() {
2674
+ if (!this._instance) {
2675
+ this._instance = new _ClockAPI();
2337
2676
  }
2338
- return new ApiClient(this.baseURL, this.accessToken);
2677
+ return this._instance;
2678
+ }
2679
+ setGlobalClock(clock2) {
2680
+ return registerGlobal(API_NAME2, clock2);
2339
2681
  }
2340
- runWith(context3, fn) {
2341
- return this._storage.runWith(context3, fn);
2682
+ preciseNow() {
2683
+ return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2342
2684
  }
2343
- };
2344
- _getStore2 = new WeakSet();
2345
- getStore_fn2 = /* @__PURE__ */ __name(function() {
2346
- return this._storage.getStore();
2347
- }, "#getStore");
2348
- __name(_ApiClientManager, "ApiClientManager");
2349
- var ApiClientManager = _ApiClientManager;
2350
- var apiClientManager = new ApiClientManager();
2351
- var _ZodSchemaParsedError = class _ZodSchemaParsedError extends Error {
2352
- constructor(error, payload) {
2353
- super(error.message);
2354
- this.error = error;
2355
- this.payload = payload;
2685
+ reset() {
2686
+ __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2356
2687
  }
2357
2688
  };
2358
- __name(_ZodSchemaParsedError, "ZodSchemaParsedError");
2359
- var ZodSchemaParsedError = _ZodSchemaParsedError;
2360
- var ZodMessageSchema = z.object({
2361
- version: z.literal("v1").default("v1"),
2362
- type: z.string(),
2363
- payload: z.unknown()
2364
- });
2365
- var _schema, _handlers;
2366
- var _ZodMessageHandler = class _ZodMessageHandler {
2367
- constructor(options) {
2368
- __privateAdd(this, _schema, void 0);
2369
- __privateAdd(this, _handlers, void 0);
2370
- __privateSet(this, _schema, options.schema);
2371
- __privateSet(this, _handlers, options.messages);
2372
- }
2373
- async handleMessage(message) {
2374
- const parsedMessage = this.parseMessage(message);
2375
- if (!__privateGet(this, _handlers)) {
2376
- throw new Error("No handlers provided");
2377
- }
2378
- const handler = __privateGet(this, _handlers)[parsedMessage.type];
2379
- if (!handler) {
2380
- console.error(`No handler for message type: ${String(parsedMessage.type)}`);
2381
- return;
2382
- }
2383
- const ack = await handler(parsedMessage.payload);
2384
- return ack;
2385
- }
2386
- parseMessage(message) {
2387
- const parsedMessage = ZodMessageSchema.safeParse(message);
2388
- if (!parsedMessage.success) {
2389
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2390
- }
2391
- const schema = __privateGet(this, _schema)[parsedMessage.data.type];
2392
- if (!schema) {
2393
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2394
- }
2395
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2396
- if (!parsedPayload.success) {
2397
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2398
- }
2689
+ _getClock = new WeakSet();
2690
+ getClock_fn = /* @__PURE__ */ __name(function() {
2691
+ return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2692
+ }, "#getClock");
2693
+ __name(_ClockAPI, "ClockAPI");
2694
+ var ClockAPI = _ClockAPI;
2695
+
2696
+ // src/v3/clock-api.ts
2697
+ var clock = ClockAPI.getInstance();
2698
+
2699
+ // src/v3/errors.ts
2700
+ function parseError(error) {
2701
+ if (error instanceof Error) {
2399
2702
  return {
2400
- type: parsedMessage.data.type,
2401
- payload: parsedPayload.data
2402
- };
2403
- }
2404
- registerHandlers(emitter, logger2) {
2405
- const log = logger2 ?? console;
2406
- if (!__privateGet(this, _handlers)) {
2407
- log.info("No handlers provided");
2408
- return;
2409
- }
2410
- for (const eventName of Object.keys(__privateGet(this, _schema))) {
2411
- emitter.on(eventName, async (message, callback) => {
2412
- log.info(`handling ${eventName}`, {
2413
- payload: message,
2414
- hasCallback: !!callback
2415
- });
2416
- let ack;
2417
- if ("payload" in message) {
2418
- ack = await this.handleMessage({
2419
- type: eventName,
2420
- ...message
2421
- });
2422
- } else {
2423
- const { version, ...payload } = message;
2424
- ack = await this.handleMessage({
2425
- type: eventName,
2426
- version,
2427
- payload
2428
- });
2429
- }
2430
- if (callback && typeof callback === "function") {
2431
- callback(ack);
2432
- }
2433
- });
2434
- }
2435
- }
2436
- };
2437
- _schema = new WeakMap();
2438
- _handlers = new WeakMap();
2439
- __name(_ZodMessageHandler, "ZodMessageHandler");
2440
- var ZodMessageHandler = _ZodMessageHandler;
2441
- var _schema2, _sender;
2442
- var _ZodMessageSender = class _ZodMessageSender {
2443
- constructor(options) {
2444
- __privateAdd(this, _schema2, void 0);
2445
- __privateAdd(this, _sender, void 0);
2446
- __privateSet(this, _schema2, options.schema);
2447
- __privateSet(this, _sender, options.sender);
2448
- }
2449
- async send(type, payload) {
2450
- const schema = __privateGet(this, _schema2)[type];
2451
- if (!schema) {
2452
- throw new Error(`Unknown message type: ${type}`);
2453
- }
2454
- const parsedPayload = schema.safeParse(payload);
2455
- if (!parsedPayload.success) {
2456
- throw new ZodSchemaParsedError(parsedPayload.error, payload);
2457
- }
2458
- await __privateGet(this, _sender).call(this, {
2459
- type,
2460
- payload,
2461
- version: "v1"
2462
- });
2463
- }
2464
- async forwardMessage(message) {
2465
- const parsedMessage = ZodMessageSchema.safeParse(message);
2466
- if (!parsedMessage.success) {
2467
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2468
- }
2469
- const schema = __privateGet(this, _schema2)[parsedMessage.data.type];
2470
- if (!schema) {
2471
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2472
- }
2473
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2474
- if (!parsedPayload.success) {
2475
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2476
- }
2477
- await __privateGet(this, _sender).call(this, {
2478
- type: parsedMessage.data.type,
2479
- payload: parsedPayload.data,
2480
- version: "v1"
2481
- });
2482
- }
2483
- };
2484
- _schema2 = new WeakMap();
2485
- _sender = new WeakMap();
2486
- __name(_ZodMessageSender, "ZodMessageSender");
2487
- var ZodMessageSender = _ZodMessageSender;
2488
- var messageSchema = z.object({
2489
- version: z.literal("v1").default("v1"),
2490
- type: z.string(),
2491
- payload: z.unknown()
2492
- });
2493
- var _schema3, _handlers2;
2494
- var _ZodSocketMessageHandler = class _ZodSocketMessageHandler {
2495
- constructor(options) {
2496
- __privateAdd(this, _schema3, void 0);
2497
- __privateAdd(this, _handlers2, void 0);
2498
- __privateSet(this, _schema3, options.schema);
2499
- __privateSet(this, _handlers2, options.handlers);
2500
- }
2501
- async handleMessage(message) {
2502
- const parsedMessage = this.parseMessage(message);
2503
- if (!__privateGet(this, _handlers2)) {
2504
- throw new Error("No handlers provided");
2505
- }
2506
- const handler = __privateGet(this, _handlers2)[parsedMessage.type];
2507
- if (!handler) {
2508
- console.error(`No handler for message type: ${String(parsedMessage.type)}`);
2509
- return;
2510
- }
2511
- const ack = await handler(parsedMessage.payload);
2512
- return ack;
2513
- }
2514
- parseMessage(message) {
2515
- const parsedMessage = messageSchema.safeParse(message);
2516
- if (!parsedMessage.success) {
2517
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2518
- }
2519
- const schema = __privateGet(this, _schema3)[parsedMessage.data.type]["message"];
2520
- if (!schema) {
2521
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2522
- }
2523
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2524
- if (!parsedPayload.success) {
2525
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2526
- }
2527
- return {
2528
- type: parsedMessage.data.type,
2529
- payload: parsedPayload.data
2530
- };
2531
- }
2532
- registerHandlers(emitter, logger2) {
2533
- const log = logger2 ?? console;
2534
- if (!__privateGet(this, _handlers2)) {
2535
- log.info("No handlers provided");
2536
- return;
2537
- }
2538
- for (const eventName of Object.keys(__privateGet(this, _handlers2))) {
2539
- emitter.on(eventName, async (message, callback) => {
2540
- log.info(`handling ${eventName}`, {
2541
- payload: message,
2542
- hasCallback: !!callback
2543
- });
2544
- let ack;
2545
- try {
2546
- if ("payload" in message) {
2547
- ack = await this.handleMessage({
2548
- type: eventName,
2549
- ...message
2550
- });
2551
- } else {
2552
- const { version, ...payload } = message;
2553
- ack = await this.handleMessage({
2554
- type: eventName,
2555
- version,
2556
- payload
2557
- });
2558
- }
2559
- } catch (error) {
2560
- log.error("Error while handling message", {
2561
- error
2562
- });
2563
- return;
2564
- }
2565
- if (callback && typeof callback === "function") {
2566
- callback(ack);
2567
- }
2568
- });
2569
- }
2570
- }
2571
- };
2572
- _schema3 = new WeakMap();
2573
- _handlers2 = new WeakMap();
2574
- __name(_ZodSocketMessageHandler, "ZodSocketMessageHandler");
2575
- var ZodSocketMessageHandler = _ZodSocketMessageHandler;
2576
- var _schema4, _socket;
2577
- var _ZodSocketMessageSender = class _ZodSocketMessageSender {
2578
- constructor(options) {
2579
- __privateAdd(this, _schema4, void 0);
2580
- __privateAdd(this, _socket, void 0);
2581
- __privateSet(this, _schema4, options.schema);
2582
- __privateSet(this, _socket, options.socket);
2583
- }
2584
- send(type, payload) {
2585
- const schema = __privateGet(this, _schema4)[type]["message"];
2586
- if (!schema) {
2587
- throw new Error(`Unknown message type: ${type}`);
2588
- }
2589
- const parsedPayload = schema.safeParse(payload);
2590
- if (!parsedPayload.success) {
2591
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2592
- }
2593
- __privateGet(this, _socket).emit(type, {
2594
- payload,
2595
- version: "v1"
2596
- });
2597
- return;
2598
- }
2599
- async sendWithAck(type, payload) {
2600
- const schema = __privateGet(this, _schema4)[type]["message"];
2601
- if (!schema) {
2602
- throw new Error(`Unknown message type: ${type}`);
2603
- }
2604
- const parsedPayload = schema.safeParse(payload);
2605
- if (!parsedPayload.success) {
2606
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2607
- }
2608
- const callbackResult = await __privateGet(this, _socket).emitWithAck(type, {
2609
- payload,
2610
- version: "v1"
2611
- });
2612
- return callbackResult;
2613
- }
2614
- };
2615
- _schema4 = new WeakMap();
2616
- _socket = new WeakMap();
2617
- __name(_ZodSocketMessageSender, "ZodSocketMessageSender");
2618
- var ZodSocketMessageSender = _ZodSocketMessageSender;
2619
- var _sender2, _handler, _logger;
2620
- var _ZodSocketConnection = class _ZodSocketConnection {
2621
- constructor(opts) {
2622
- __privateAdd(this, _sender2, void 0);
2623
- __privateAdd(this, _handler, void 0);
2624
- __privateAdd(this, _logger, void 0);
2625
- const uri = `${opts.secure ? "wss" : "ws"}://${opts.host}:${opts.port ?? (opts.secure ? "443" : "80")}/${opts.namespace}`;
2626
- const logger2 = new SimpleStructuredLogger(opts.namespace, LogLevel.info);
2627
- logger2.log("new zod socket", {
2628
- uri
2629
- });
2630
- this.socket = io(uri, {
2631
- transports: [
2632
- "websocket"
2633
- ],
2634
- auth: {
2635
- token: opts.authToken
2636
- },
2637
- extraHeaders: opts.extraHeaders,
2638
- reconnectionDelay: 500,
2639
- reconnectionDelayMax: 1e3
2640
- });
2641
- __privateSet(this, _logger, logger2.child({
2642
- socketId: this.socket.id
2643
- }));
2644
- __privateSet(this, _handler, new ZodSocketMessageHandler({
2645
- schema: opts.serverMessages,
2646
- handlers: opts.handlers
2647
- }));
2648
- __privateGet(this, _handler).registerHandlers(this.socket, __privateGet(this, _logger));
2649
- __privateSet(this, _sender2, new ZodSocketMessageSender({
2650
- schema: opts.clientMessages,
2651
- socket: this.socket
2652
- }));
2653
- this.socket.on("connect_error", async (error) => {
2654
- __privateGet(this, _logger).error(`connect_error: ${error}`);
2655
- if (opts.onError) {
2656
- await opts.onError(this.socket, error, __privateGet(this, _logger));
2657
- }
2658
- });
2659
- this.socket.on("connect", async () => {
2660
- __privateGet(this, _logger).info("connect");
2661
- if (opts.onConnection) {
2662
- await opts.onConnection(this.socket, __privateGet(this, _handler), __privateGet(this, _sender2), __privateGet(this, _logger));
2663
- }
2664
- });
2665
- this.socket.on("disconnect", async (reason, description) => {
2666
- __privateGet(this, _logger).info("disconnect", {
2667
- reason,
2668
- description
2669
- });
2670
- if (opts.onDisconnect) {
2671
- await opts.onDisconnect(this.socket, reason, description, __privateGet(this, _logger));
2672
- }
2673
- });
2674
- }
2675
- close() {
2676
- this.socket.close();
2677
- }
2678
- connect() {
2679
- this.socket.connect();
2680
- }
2681
- get send() {
2682
- return __privateGet(this, _sender2).send.bind(__privateGet(this, _sender2));
2683
- }
2684
- get sendWithAck() {
2685
- return __privateGet(this, _sender2).sendWithAck.bind(__privateGet(this, _sender2));
2686
- }
2687
- };
2688
- _sender2 = new WeakMap();
2689
- _handler = new WeakMap();
2690
- _logger = new WeakMap();
2691
- __name(_ZodSocketConnection, "ZodSocketConnection");
2692
- var ZodSocketConnection = _ZodSocketConnection;
2693
-
2694
- // src/v3/zodNamespace.ts
2695
- var LogLevel;
2696
- (function(LogLevel2) {
2697
- LogLevel2[LogLevel2["log"] = 0] = "log";
2698
- LogLevel2[LogLevel2["error"] = 1] = "error";
2699
- LogLevel2[LogLevel2["warn"] = 2] = "warn";
2700
- LogLevel2[LogLevel2["info"] = 3] = "info";
2701
- LogLevel2[LogLevel2["debug"] = 4] = "debug";
2702
- })(LogLevel || (LogLevel = {}));
2703
- var _structuredLog, structuredLog_fn;
2704
- var _SimpleStructuredLogger = class _SimpleStructuredLogger {
2705
- constructor(name, level = [
2706
- "1",
2707
- "true"
2708
- ].includes(process.env.DEBUG ?? "") ? LogLevel.debug : LogLevel.info, fields) {
2709
- __privateAdd(this, _structuredLog);
2710
- this.name = name;
2711
- this.level = level;
2712
- this.fields = fields;
2713
- }
2714
- child(fields, level) {
2715
- return new _SimpleStructuredLogger(this.name, level, {
2716
- ...this.fields,
2717
- ...fields
2718
- });
2719
- }
2720
- log(message, ...args) {
2721
- if (this.level < LogLevel.log)
2722
- return;
2723
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.log, message, "log", ...args);
2724
- }
2725
- error(message, ...args) {
2726
- if (this.level < LogLevel.error)
2727
- return;
2728
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.error, message, "error", ...args);
2729
- }
2730
- warn(message, ...args) {
2731
- if (this.level < LogLevel.warn)
2732
- return;
2733
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.warn, message, "warn", ...args);
2734
- }
2735
- info(message, ...args) {
2736
- if (this.level < LogLevel.info)
2737
- return;
2738
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.info, message, "info", ...args);
2739
- }
2740
- debug(message, ...args) {
2741
- if (this.level < LogLevel.debug)
2742
- return;
2743
- __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.debug, message, "debug", ...args);
2744
- }
2745
- };
2746
- _structuredLog = new WeakSet();
2747
- structuredLog_fn = /* @__PURE__ */ __name(function(loggerFunction, message, level, ...args) {
2748
- const structuredLog = {
2749
- ...args.length === 1 ? args[0] : args,
2750
- ...this.fields,
2751
- timestamp: /* @__PURE__ */ new Date(),
2752
- name: this.name,
2753
- message,
2754
- level
2755
- };
2756
- loggerFunction(JSON.stringify(structuredLog));
2757
- }, "#structuredLog");
2758
- __name(_SimpleStructuredLogger, "SimpleStructuredLogger");
2759
- var SimpleStructuredLogger = _SimpleStructuredLogger;
2760
- var _logger2, _handler2;
2761
- var _ZodNamespace = class _ZodNamespace {
2762
- constructor(opts) {
2763
- __privateAdd(this, _logger2, void 0);
2764
- __privateAdd(this, _handler2, void 0);
2765
- __privateSet(this, _logger2, opts.logger ?? new SimpleStructuredLogger(opts.name));
2766
- __privateSet(this, _handler2, new ZodSocketMessageHandler({
2767
- schema: opts.clientMessages,
2768
- handlers: opts.handlers
2769
- }));
2770
- this.io = opts.io;
2771
- this.namespace = this.io.of(opts.name);
2772
- this.sender = new ZodMessageSender({
2773
- schema: opts.serverMessages,
2774
- sender: async (message) => {
2775
- return new Promise((resolve, reject) => {
2776
- try {
2777
- this.namespace.emit(message.type, message.payload);
2778
- resolve();
2779
- } catch (err) {
2780
- reject(err);
2781
- }
2782
- });
2783
- }
2784
- });
2785
- if (opts.preAuth) {
2786
- this.namespace.use(async (socket, next) => {
2787
- const logger2 = __privateGet(this, _logger2).child({
2788
- socketId: socket.id,
2789
- socketStage: "preAuth"
2790
- });
2791
- if (typeof opts.preAuth === "function") {
2792
- await opts.preAuth(socket, next, logger2);
2793
- }
2794
- });
2795
- }
2796
- if (opts.authToken) {
2797
- this.namespace.use((socket, next) => {
2798
- const logger2 = __privateGet(this, _logger2).child({
2799
- socketId: socket.id,
2800
- socketStage: "auth"
2801
- });
2802
- const { auth } = socket.handshake;
2803
- if (!("token" in auth)) {
2804
- logger2.error("no token");
2805
- return socket.disconnect(true);
2806
- }
2807
- if (auth.token !== opts.authToken) {
2808
- logger2.error("invalid token");
2809
- return socket.disconnect(true);
2810
- }
2811
- logger2.info("success");
2812
- next();
2813
- });
2814
- }
2815
- if (opts.postAuth) {
2816
- this.namespace.use(async (socket, next) => {
2817
- const logger2 = __privateGet(this, _logger2).child({
2818
- socketId: socket.id,
2819
- socketStage: "auth"
2820
- });
2821
- if (typeof opts.postAuth === "function") {
2822
- await opts.postAuth(socket, next, logger2);
2823
- }
2824
- });
2825
- }
2826
- this.namespace.on("connection", async (socket) => {
2827
- const logger2 = __privateGet(this, _logger2).child({
2828
- socketId: socket.id,
2829
- socketStage: "connection"
2830
- });
2831
- logger2.info("connected");
2832
- __privateGet(this, _handler2).registerHandlers(socket, logger2);
2833
- socket.on("disconnect", async (reason, description) => {
2834
- logger2.info("disconnect", {
2835
- reason,
2836
- description
2837
- });
2838
- if (opts.onDisconnect) {
2839
- await opts.onDisconnect(socket, reason, description, logger2);
2840
- }
2841
- });
2842
- socket.on("error", async (error) => {
2843
- logger2.error("error", {
2844
- error
2845
- });
2846
- if (opts.onError) {
2847
- await opts.onError(socket, error, logger2);
2848
- }
2849
- });
2850
- if (opts.onConnection) {
2851
- await opts.onConnection(socket, __privateGet(this, _handler2), this.sender, logger2);
2852
- }
2853
- });
2854
- }
2855
- fetchSockets() {
2856
- return this.namespace.fetchSockets();
2857
- }
2858
- };
2859
- _logger2 = new WeakMap();
2860
- _handler2 = new WeakMap();
2861
- __name(_ZodNamespace, "ZodNamespace");
2862
- var ZodNamespace = _ZodNamespace;
2863
- var messageSchema2 = z.object({
2864
- version: z.literal("v1").default("v1"),
2865
- type: z.string(),
2866
- payload: z.unknown()
2867
- });
2868
- var _schema5, _handlers3, _sender3, _a;
2869
- var ZodIpcMessageHandler = (_a = class {
2870
- constructor(options) {
2871
- __privateAdd(this, _schema5, void 0);
2872
- __privateAdd(this, _handlers3, void 0);
2873
- __privateAdd(this, _sender3, void 0);
2874
- __privateSet(this, _schema5, options.schema);
2875
- __privateSet(this, _handlers3, options.handlers);
2876
- __privateSet(this, _sender3, options.sender);
2877
- }
2878
- async handleMessage(message) {
2879
- const parsedMessage = this.parseMessage(message);
2880
- if (!__privateGet(this, _handlers3)) {
2881
- throw new Error("No handlers provided");
2882
- }
2883
- const handler = __privateGet(this, _handlers3)[parsedMessage.type];
2884
- if (!handler) {
2885
- return;
2886
- }
2887
- const ack = await handler(parsedMessage.payload, __privateGet(this, _sender3));
2888
- return ack;
2889
- }
2890
- parseMessage(message) {
2891
- const parsedMessage = messageSchema2.safeParse(message);
2892
- if (!parsedMessage.success) {
2893
- throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2894
- }
2895
- const schema = __privateGet(this, _schema5)[parsedMessage.data.type]["message"];
2896
- if (!schema) {
2897
- throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2898
- }
2899
- const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2900
- if (!parsedPayload.success) {
2901
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2902
- }
2903
- return {
2904
- type: parsedMessage.data.type,
2905
- payload: parsedPayload.data
2906
- };
2907
- }
2908
- }, _schema5 = new WeakMap(), _handlers3 = new WeakMap(), _sender3 = new WeakMap(), __name(_a, "ZodIpcMessageHandler"), _a);
2909
- var Packet = z.discriminatedUnion("type", [
2910
- z.object({
2911
- type: z.literal("CONNECT"),
2912
- sessionId: z.string().optional()
2913
- }),
2914
- z.object({
2915
- type: z.literal("ACK"),
2916
- message: z.any(),
2917
- id: z.number()
2918
- }),
2919
- z.object({
2920
- type: z.literal("EVENT"),
2921
- message: z.any(),
2922
- id: z.number().optional()
2923
- })
2924
- ]);
2925
- var _sessionId, _messageCounter, _handler3, _acks, _registerHandlers, registerHandlers_fn, _handlePacket, handlePacket_fn, _sendPacket, sendPacket_fn;
2926
- var _ZodIpcConnection = class _ZodIpcConnection {
2927
- constructor(opts) {
2928
- __privateAdd(this, _registerHandlers);
2929
- __privateAdd(this, _handlePacket);
2930
- __privateAdd(this, _sendPacket);
2931
- __privateAdd(this, _sessionId, void 0);
2932
- __privateAdd(this, _messageCounter, void 0);
2933
- __privateAdd(this, _handler3, void 0);
2934
- __privateAdd(this, _acks, void 0);
2935
- this.opts = opts;
2936
- __privateSet(this, _messageCounter, 0);
2937
- __privateSet(this, _acks, /* @__PURE__ */ new Map());
2938
- __privateSet(this, _handler3, new ZodIpcMessageHandler({
2939
- schema: opts.listenSchema,
2940
- handlers: opts.handlers,
2941
- sender: {
2942
- send: this.send.bind(this),
2943
- sendWithAck: this.sendWithAck.bind(this)
2944
- }
2945
- }));
2946
- __privateMethod(this, _registerHandlers, registerHandlers_fn).call(this);
2947
- }
2948
- async connect() {
2949
- __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2950
- type: "CONNECT"
2951
- });
2952
- }
2953
- async send(type, payload) {
2954
- const schema = this.opts.emitSchema[type]["message"];
2955
- if (!schema) {
2956
- throw new Error(`Unknown message type: ${type}`);
2957
- }
2958
- const parsedPayload = schema.safeParse(payload);
2959
- if (!parsedPayload.success) {
2960
- throw new ZodSchemaParsedError(parsedPayload.error, payload);
2961
- }
2962
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2963
- type: "EVENT",
2964
- message: {
2965
- type,
2966
- payload,
2967
- version: "v1"
2968
- }
2969
- });
2970
- }
2971
- async sendWithAck(type, payload, timeoutInMs) {
2972
- const currentId = __privateWrapper(this, _messageCounter)._++;
2973
- return new Promise(async (resolve, reject) => {
2974
- const defaultTimeoutInMs = 2e3;
2975
- const timeout = setTimeout(() => {
2976
- reject(JSON.stringify({
2977
- reason: "sendWithAck() timeout",
2978
- timeoutInMs: timeoutInMs ?? defaultTimeoutInMs,
2979
- type,
2980
- payload
2981
- }));
2982
- }, timeoutInMs ?? defaultTimeoutInMs);
2983
- __privateGet(this, _acks).set(currentId, {
2984
- resolve,
2985
- reject,
2986
- timeout
2987
- });
2988
- const schema = this.opts.emitSchema[type]["message"];
2989
- if (!schema) {
2990
- clearTimeout(timeout);
2991
- return reject(`Unknown message type: ${type}`);
2992
- }
2993
- const parsedPayload = schema.safeParse(payload);
2994
- if (!parsedPayload.success) {
2995
- clearTimeout(timeout);
2996
- return reject(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2997
- }
2998
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2999
- type: "EVENT",
3000
- message: {
3001
- type,
3002
- payload,
3003
- version: "v1"
3004
- },
3005
- id: currentId
3006
- });
3007
- });
3008
- }
3009
- };
3010
- _sessionId = new WeakMap();
3011
- _messageCounter = new WeakMap();
3012
- _handler3 = new WeakMap();
3013
- _acks = new WeakMap();
3014
- _registerHandlers = new WeakSet();
3015
- registerHandlers_fn = /* @__PURE__ */ __name(async function() {
3016
- if (!this.opts.process.on) {
3017
- return;
3018
- }
3019
- this.opts.process.on("message", async (message) => {
3020
- __privateMethod(this, _handlePacket, handlePacket_fn).call(this, message);
3021
- });
3022
- }, "#registerHandlers");
3023
- _handlePacket = new WeakSet();
3024
- handlePacket_fn = /* @__PURE__ */ __name(async function(packet) {
3025
- const parsedPacket = Packet.safeParse(packet);
3026
- if (!parsedPacket.success) {
3027
- return;
3028
- }
3029
- switch (parsedPacket.data.type) {
3030
- case "ACK": {
3031
- const ack = __privateGet(this, _acks).get(parsedPacket.data.id);
3032
- if (!ack) {
3033
- return;
3034
- }
3035
- clearTimeout(ack.timeout);
3036
- ack.resolve(parsedPacket.data.message);
3037
- break;
3038
- }
3039
- case "CONNECT": {
3040
- if (!parsedPacket.data.sessionId) {
3041
- const id = randomUUID();
3042
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
3043
- type: "CONNECT",
3044
- sessionId: id
3045
- });
3046
- return;
3047
- }
3048
- if (__privateGet(this, _sessionId)) {
3049
- return;
3050
- }
3051
- __privateSet(this, _sessionId, parsedPacket.data.sessionId);
3052
- break;
3053
- }
3054
- case "EVENT": {
3055
- const result = await __privateGet(this, _handler3).handleMessage(parsedPacket.data.message);
3056
- if (typeof parsedPacket.data.id === "undefined") {
3057
- return;
3058
- }
3059
- await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
3060
- type: "ACK",
3061
- id: parsedPacket.data.id,
3062
- message: result
3063
- });
3064
- break;
3065
- }
3066
- }
3067
- }, "#handlePacket");
3068
- _sendPacket = new WeakSet();
3069
- sendPacket_fn = /* @__PURE__ */ __name(async function(packet1) {
3070
- await this.opts.process.send?.(packet1);
3071
- }, "#sendPacket");
3072
- __name(_ZodIpcConnection, "ZodIpcConnection");
3073
- var ZodIpcConnection = _ZodIpcConnection;
3074
- function parseError(error) {
3075
- if (error instanceof Error) {
3076
- return {
3077
- type: "BUILT_IN_ERROR",
3078
- name: error.name,
3079
- message: error.message,
3080
- stackTrace: error.stack ?? ""
2703
+ type: "BUILT_IN_ERROR",
2704
+ name: error.name,
2705
+ message: error.message,
2706
+ stackTrace: error.stack ?? ""
3081
2707
  };
3082
2708
  }
3083
2709
  if (typeof error === "string") {
@@ -3119,31 +2745,62 @@ function createErrorTaskError(error) {
3119
2745
  }
3120
2746
  }
3121
2747
  __name(createErrorTaskError, "createErrorTaskError");
2748
+ function createJsonErrorObject(error) {
2749
+ switch (error.type) {
2750
+ case "BUILT_IN_ERROR": {
2751
+ return {
2752
+ name: error.name,
2753
+ message: error.message,
2754
+ stackTrace: error.stackTrace
2755
+ };
2756
+ }
2757
+ case "STRING_ERROR": {
2758
+ return {
2759
+ message: error.raw
2760
+ };
2761
+ }
2762
+ case "CUSTOM_ERROR": {
2763
+ return {
2764
+ message: error.raw
2765
+ };
2766
+ }
2767
+ case "INTERNAL_ERROR": {
2768
+ return {
2769
+ message: `trigger.dev internal error (${error.code})`
2770
+ };
2771
+ }
2772
+ }
2773
+ }
2774
+ __name(createJsonErrorObject, "createJsonErrorObject");
3122
2775
  function correctErrorStackTrace(stackTrace, projectDir, options) {
3123
2776
  const [errorLine, ...traceLines] = stackTrace.split("\n");
3124
2777
  return [
3125
2778
  options?.removeFirstLine ? void 0 : errorLine,
3126
- ...traceLines.map((line) => correctStackTraceLine(line, projectDir))
2779
+ ...traceLines.map((line) => correctStackTraceLine(line, projectDir, options?.isDev))
3127
2780
  ].filter(Boolean).join("\n");
3128
2781
  }
3129
2782
  __name(correctErrorStackTrace, "correctErrorStackTrace");
3130
- function correctStackTraceLine(line, projectDir) {
3131
- const regex = /at (.*?) \(?file:\/\/(\/.*?\.ts):(\d+):(\d+)\)?/;
3132
- const match = regex.exec(line);
3133
- if (!match) {
3134
- return;
3135
- }
3136
- const [_, identifier, path, lineNum, colNum] = match;
3137
- if (!path) {
3138
- return;
3139
- }
3140
- if (nodePath.basename(path) === "__entryPoint.ts") {
2783
+ var LINES_TO_IGNORE = [
2784
+ /ConsoleInterceptor/,
2785
+ /TriggerTracer/,
2786
+ /TaskExecutor/,
2787
+ /EXECUTE_TASK_RUN/,
2788
+ /@trigger.dev\/core/,
2789
+ /packages\/core\/src\/v3/,
2790
+ /safeJsonProcess/,
2791
+ /__entryPoint.ts/,
2792
+ /ZodIpc/,
2793
+ /startActiveSpan/,
2794
+ /processTicksAndRejections/
2795
+ ];
2796
+ function correctStackTraceLine(line, projectDir, isDev) {
2797
+ if (LINES_TO_IGNORE.some((regex) => regex.test(line))) {
3141
2798
  return;
3142
2799
  }
3143
- if (projectDir && !path.includes(projectDir)) {
2800
+ if (isDev && projectDir && !line.includes(projectDir)) {
3144
2801
  return;
3145
2802
  }
3146
- return line;
2803
+ return line.trim();
3147
2804
  }
3148
2805
  __name(correctStackTraceLine, "correctStackTraceLine");
3149
2806
  function groupTaskMetadataIssuesByTask(tasks, issues) {
@@ -3182,335 +2839,363 @@ function groupTaskMetadataIssuesByTask(tasks, issues) {
3182
2839
  }
3183
2840
  __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
3184
2841
 
3185
- // src/v3/utils/platform.ts
3186
- var _globalThis = typeof globalThis === "object" ? globalThis : global;
3187
-
3188
- // src/v3/utils/globals.ts
3189
- var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
3190
- var _global = _globalThis;
3191
- function registerGlobal(type, instance, allowOverride = false) {
3192
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
3193
- if (!allowOverride && api[type]) {
3194
- return false;
2842
+ // src/v3/limits.ts
2843
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2844
+ var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
2845
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2846
+ var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2847
+ var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
2848
+ var OTEL_LINK_COUNT_LIMIT = 2;
2849
+ var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
2850
+ var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
2851
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
2852
+ function imposeAttributeLimits(attributes) {
2853
+ const newAttributes = {};
2854
+ for (const [key, value] of Object.entries(attributes)) {
2855
+ if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
2856
+ continue;
2857
+ }
2858
+ if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
2859
+ break;
2860
+ }
2861
+ newAttributes[key] = value;
3195
2862
  }
3196
- api[type] = instance;
3197
- return true;
3198
- }
3199
- __name(registerGlobal, "registerGlobal");
3200
- function getGlobal(type) {
3201
- return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
2863
+ return newAttributes;
3202
2864
  }
3203
- __name(getGlobal, "getGlobal");
3204
- function unregisterGlobal(type) {
3205
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
3206
- if (api) {
3207
- delete api[type];
2865
+ __name(imposeAttributeLimits, "imposeAttributeLimits");
2866
+ function calculateAttributeValueLength(value) {
2867
+ if (value === void 0 || value === null) {
2868
+ return 0;
3208
2869
  }
3209
- }
3210
- __name(unregisterGlobal, "unregisterGlobal");
3211
-
3212
- // src/v3/runtime/noopRuntimeManager.ts
3213
- var _NoopRuntimeManager = class _NoopRuntimeManager {
3214
- disable() {
3215
- }
3216
- waitForDuration(ms) {
3217
- return Promise.resolve();
2870
+ if (typeof value === "string") {
2871
+ return value.length;
3218
2872
  }
3219
- waitUntil(date) {
3220
- return Promise.resolve();
2873
+ if (typeof value === "number") {
2874
+ return 8;
3221
2875
  }
3222
- waitForTask(params) {
3223
- return Promise.resolve({
3224
- ok: false,
3225
- id: params.id,
3226
- error: {
3227
- type: "INTERNAL_ERROR",
3228
- code: "CONFIGURED_INCORRECTLY"
3229
- }
3230
- });
2876
+ if (typeof value === "boolean") {
2877
+ return 4;
3231
2878
  }
3232
- waitForBatch(params) {
3233
- return Promise.resolve({
3234
- id: params.id,
3235
- items: []
3236
- });
2879
+ if (Array.isArray(value)) {
2880
+ return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
3237
2881
  }
3238
- };
3239
- __name(_NoopRuntimeManager, "NoopRuntimeManager");
3240
- var NoopRuntimeManager = _NoopRuntimeManager;
2882
+ return 0;
2883
+ }
2884
+ __name(calculateAttributeValueLength, "calculateAttributeValueLength");
3241
2885
 
3242
- // src/v3/runtime/index.ts
3243
- var API_NAME = "runtime";
3244
- var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
3245
- var _getRuntimeManager, getRuntimeManager_fn;
3246
- var _RuntimeAPI = class _RuntimeAPI {
3247
- constructor() {
3248
- __privateAdd(this, _getRuntimeManager);
2886
+ // src/v3/utils/flattenAttributes.ts
2887
+ var NULL_SENTINEL = "$@null((";
2888
+ function flattenAttributes(obj, prefix) {
2889
+ const result = {};
2890
+ if (obj === void 0) {
2891
+ return result;
3249
2892
  }
3250
- static getInstance() {
3251
- if (!this._instance) {
3252
- this._instance = new _RuntimeAPI();
2893
+ if (obj === null) {
2894
+ result[prefix || ""] = NULL_SENTINEL;
2895
+ return result;
2896
+ }
2897
+ if (typeof obj === "string") {
2898
+ result[prefix || ""] = obj;
2899
+ return result;
2900
+ }
2901
+ if (typeof obj === "number") {
2902
+ result[prefix || ""] = obj;
2903
+ return result;
2904
+ }
2905
+ if (typeof obj === "boolean") {
2906
+ result[prefix || ""] = obj;
2907
+ return result;
2908
+ }
2909
+ for (const [key, value] of Object.entries(obj)) {
2910
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${Array.isArray(obj) ? `[${key}]` : key}`;
2911
+ if (Array.isArray(value)) {
2912
+ for (let i = 0; i < value.length; i++) {
2913
+ if (typeof value[i] === "object" && value[i] !== null) {
2914
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
2915
+ } else {
2916
+ if (value[i] === null) {
2917
+ result[`${newPrefix}.[${i}]`] = NULL_SENTINEL;
2918
+ } else {
2919
+ result[`${newPrefix}.[${i}]`] = value[i];
2920
+ }
2921
+ }
2922
+ }
2923
+ } else if (isRecord(value)) {
2924
+ Object.assign(result, flattenAttributes(value, newPrefix));
2925
+ } else {
2926
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
2927
+ result[newPrefix] = value;
2928
+ } else if (value === null) {
2929
+ result[newPrefix] = NULL_SENTINEL;
2930
+ }
3253
2931
  }
3254
- return this._instance;
3255
2932
  }
3256
- waitForDuration(ms) {
3257
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
2933
+ return result;
2934
+ }
2935
+ __name(flattenAttributes, "flattenAttributes");
2936
+ function isRecord(value) {
2937
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2938
+ }
2939
+ __name(isRecord, "isRecord");
2940
+ function unflattenAttributes(obj) {
2941
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
2942
+ return obj;
3258
2943
  }
3259
- waitUntil(date) {
3260
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
2944
+ if (typeof obj === "object" && obj !== null && Object.keys(obj).length === 1 && Object.keys(obj)[0] === "") {
2945
+ return rehydrateNull(obj[""]);
3261
2946
  }
3262
- waitForTask(params) {
3263
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
2947
+ if (Object.keys(obj).length === 0) {
2948
+ return;
3264
2949
  }
3265
- waitForBatch(params) {
3266
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
2950
+ const result = {};
2951
+ for (const [key, value] of Object.entries(obj)) {
2952
+ const parts = key.split(".").reduce((acc, part) => {
2953
+ if (part.includes("[")) {
2954
+ const subparts = part.split(/\[|\]/).filter((p) => p !== "");
2955
+ acc.push(...subparts);
2956
+ } else {
2957
+ acc.push(part);
2958
+ }
2959
+ return acc;
2960
+ }, []);
2961
+ let current = result;
2962
+ for (let i = 0; i < parts.length - 1; i++) {
2963
+ const part = parts[i];
2964
+ const nextPart = parts[i + 1];
2965
+ const isArray = /^\d+$/.test(nextPart);
2966
+ if (isArray && !Array.isArray(current[part])) {
2967
+ current[part] = [];
2968
+ } else if (!isArray && current[part] === void 0) {
2969
+ current[part] = {};
2970
+ }
2971
+ current = current[part];
2972
+ }
2973
+ const lastPart = parts[parts.length - 1];
2974
+ current[lastPart] = rehydrateNull(value);
3267
2975
  }
3268
- setGlobalRuntimeManager(runtimeManager) {
3269
- return registerGlobal(API_NAME, runtimeManager);
2976
+ if (Object.keys(result).every((k) => /^\d+$/.test(k))) {
2977
+ const maxIndex = Math.max(...Object.keys(result).map((k) => parseInt(k)));
2978
+ const arrayResult = Array(maxIndex + 1);
2979
+ for (const key in result) {
2980
+ arrayResult[parseInt(key)] = result[key];
2981
+ }
2982
+ return arrayResult;
3270
2983
  }
3271
- disable() {
3272
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
3273
- unregisterGlobal(API_NAME);
2984
+ return result;
2985
+ }
2986
+ __name(unflattenAttributes, "unflattenAttributes");
2987
+ function primitiveValueOrflattenedAttributes(obj, prefix) {
2988
+ if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
2989
+ return obj;
3274
2990
  }
3275
- };
3276
- _getRuntimeManager = new WeakSet();
3277
- getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
3278
- return getGlobal(API_NAME) ?? NOOP_RUNTIME_MANAGER;
3279
- }, "#getRuntimeManager");
3280
- __name(_RuntimeAPI, "RuntimeAPI");
3281
- var RuntimeAPI = _RuntimeAPI;
3282
-
3283
- // src/v3/runtime-api.ts
3284
- var runtime = RuntimeAPI.getInstance();
3285
- function iconStringForSeverity(severityNumber) {
3286
- switch (severityNumber) {
3287
- case SeverityNumber.UNSPECIFIED:
3288
- return void 0;
3289
- case SeverityNumber.TRACE:
3290
- case SeverityNumber.TRACE2:
3291
- case SeverityNumber.TRACE3:
3292
- case SeverityNumber.TRACE4:
3293
- return "trace";
3294
- case SeverityNumber.DEBUG:
3295
- case SeverityNumber.DEBUG2:
3296
- case SeverityNumber.DEBUG3:
3297
- case SeverityNumber.DEBUG4:
3298
- return "debug";
3299
- case SeverityNumber.INFO:
3300
- case SeverityNumber.INFO2:
3301
- case SeverityNumber.INFO3:
3302
- case SeverityNumber.INFO4:
3303
- return "info";
3304
- case SeverityNumber.WARN:
3305
- case SeverityNumber.WARN2:
3306
- case SeverityNumber.WARN3:
3307
- case SeverityNumber.WARN4:
3308
- return "warn";
3309
- case SeverityNumber.ERROR:
3310
- case SeverityNumber.ERROR2:
3311
- case SeverityNumber.ERROR3:
3312
- case SeverityNumber.ERROR4:
3313
- return "error";
3314
- case SeverityNumber.FATAL:
3315
- case SeverityNumber.FATAL2:
3316
- case SeverityNumber.FATAL3:
3317
- case SeverityNumber.FATAL4:
3318
- return "fatal";
2991
+ const attributes = flattenAttributes(obj, prefix);
2992
+ if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
2993
+ return attributes[prefix];
3319
2994
  }
2995
+ return attributes;
3320
2996
  }
3321
- __name(iconStringForSeverity, "iconStringForSeverity");
3322
- var _SimpleClock = class _SimpleClock {
3323
- preciseNow() {
3324
- const now = new PreciseDate();
3325
- const nowStruct = now.toStruct();
3326
- return [
3327
- nowStruct.seconds,
3328
- nowStruct.nanos
3329
- ];
2997
+ __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
2998
+ function rehydrateNull(value) {
2999
+ if (value === NULL_SENTINEL) {
3000
+ return null;
3330
3001
  }
3331
- reset() {
3002
+ return value;
3003
+ }
3004
+ __name(rehydrateNull, "rehydrateNull");
3005
+
3006
+ // src/v3/logger/taskLogger.ts
3007
+ var _NoopTaskLogger = class _NoopTaskLogger {
3008
+ debug() {
3009
+ }
3010
+ log() {
3011
+ }
3012
+ info() {
3013
+ }
3014
+ warn() {
3015
+ }
3016
+ error() {
3017
+ }
3018
+ trace(name, fn) {
3019
+ return fn({});
3332
3020
  }
3333
3021
  };
3334
- __name(_SimpleClock, "SimpleClock");
3335
- var SimpleClock = _SimpleClock;
3022
+ __name(_NoopTaskLogger, "NoopTaskLogger");
3023
+ var NoopTaskLogger = _NoopTaskLogger;
3336
3024
 
3337
- // src/v3/clock/index.ts
3338
- var API_NAME2 = "clock";
3339
- var SIMPLE_CLOCK = new SimpleClock();
3340
- var _getClock, getClock_fn;
3341
- var _ClockAPI = class _ClockAPI {
3025
+ // src/v3/logger/index.ts
3026
+ var API_NAME3 = "logger";
3027
+ var NOOP_TASK_LOGGER = new NoopTaskLogger();
3028
+ var _getTaskLogger, getTaskLogger_fn;
3029
+ var _LoggerAPI = class _LoggerAPI {
3342
3030
  constructor() {
3343
- __privateAdd(this, _getClock);
3031
+ __privateAdd(this, _getTaskLogger);
3344
3032
  }
3345
3033
  static getInstance() {
3346
3034
  if (!this._instance) {
3347
- this._instance = new _ClockAPI();
3035
+ this._instance = new _LoggerAPI();
3348
3036
  }
3349
3037
  return this._instance;
3350
3038
  }
3351
- setGlobalClock(clock2) {
3352
- return registerGlobal(API_NAME2, clock2);
3039
+ disable() {
3040
+ unregisterGlobal(API_NAME3);
3353
3041
  }
3354
- preciseNow() {
3355
- return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
3042
+ setGlobalTaskLogger(taskLogger) {
3043
+ return registerGlobal(API_NAME3, taskLogger);
3356
3044
  }
3357
- reset() {
3358
- __privateMethod(this, _getClock, getClock_fn).call(this).reset();
3045
+ debug(message, metadata) {
3046
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).debug(message, metadata);
3047
+ }
3048
+ log(message, metadata) {
3049
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).log(message, metadata);
3050
+ }
3051
+ info(message, metadata) {
3052
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).info(message, metadata);
3053
+ }
3054
+ warn(message, metadata) {
3055
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).warn(message, metadata);
3056
+ }
3057
+ error(message, metadata) {
3058
+ __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).error(message, metadata);
3059
+ }
3060
+ trace(name, fn) {
3061
+ return __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).trace(name, fn);
3359
3062
  }
3360
3063
  };
3361
- _getClock = new WeakSet();
3362
- getClock_fn = /* @__PURE__ */ __name(function() {
3363
- return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
3364
- }, "#getClock");
3365
- __name(_ClockAPI, "ClockAPI");
3366
- var ClockAPI = _ClockAPI;
3064
+ _getTaskLogger = new WeakSet();
3065
+ getTaskLogger_fn = /* @__PURE__ */ __name(function() {
3066
+ return getGlobal(API_NAME3) ?? NOOP_TASK_LOGGER;
3067
+ }, "#getTaskLogger");
3068
+ __name(_LoggerAPI, "LoggerAPI");
3069
+ var LoggerAPI = _LoggerAPI;
3367
3070
 
3368
- // src/v3/clock-api.ts
3369
- var clock = ClockAPI.getInstance();
3071
+ // src/v3/logger-api.ts
3072
+ var logger = LoggerAPI.getInstance();
3370
3073
 
3371
- // src/v3/logger/taskLogger.ts
3372
- var logLevels = [
3373
- "none",
3374
- "error",
3375
- "warn",
3376
- "log",
3377
- "info",
3378
- "debug"
3379
- ];
3380
- var _emitLog, emitLog_fn, _getTimestampInHrTime, getTimestampInHrTime_fn;
3381
- var _OtelTaskLogger = class _OtelTaskLogger {
3382
- constructor(_config) {
3383
- __privateAdd(this, _emitLog);
3384
- __privateAdd(this, _getTimestampInHrTime);
3385
- this._config = _config;
3386
- this._level = logLevels.indexOf(_config.level);
3074
+ // src/v3/runtime/noopRuntimeManager.ts
3075
+ var _NoopRuntimeManager = class _NoopRuntimeManager {
3076
+ disable() {
3387
3077
  }
3388
- debug(message, properties) {
3389
- if (this._level < 5)
3390
- return;
3391
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "debug", SeverityNumber.DEBUG, properties);
3078
+ waitForDuration(ms) {
3079
+ return Promise.resolve();
3392
3080
  }
3393
- log(message, properties) {
3394
- if (this._level < 3)
3395
- return;
3396
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "log", SeverityNumber.INFO, properties);
3081
+ waitUntil(date) {
3082
+ return Promise.resolve();
3397
3083
  }
3398
- info(message, properties) {
3399
- if (this._level < 4)
3400
- return;
3401
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "info", SeverityNumber.INFO, properties);
3084
+ waitForTask(params) {
3085
+ return Promise.resolve({
3086
+ ok: false,
3087
+ id: params.id,
3088
+ error: {
3089
+ type: "INTERNAL_ERROR",
3090
+ code: "CONFIGURED_INCORRECTLY"
3091
+ }
3092
+ });
3402
3093
  }
3403
- warn(message, properties) {
3404
- if (this._level < 2)
3405
- return;
3406
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "warn", SeverityNumber.WARN, properties);
3094
+ waitForBatch(params) {
3095
+ return Promise.resolve({
3096
+ id: params.id,
3097
+ items: []
3098
+ });
3407
3099
  }
3408
- error(message, properties) {
3409
- if (this._level < 1)
3410
- return;
3411
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "error", SeverityNumber.ERROR, properties);
3100
+ };
3101
+ __name(_NoopRuntimeManager, "NoopRuntimeManager");
3102
+ var NoopRuntimeManager = _NoopRuntimeManager;
3103
+
3104
+ // src/v3/runtime/index.ts
3105
+ var API_NAME4 = "runtime";
3106
+ var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
3107
+ var _getRuntimeManager, getRuntimeManager_fn;
3108
+ var _RuntimeAPI = class _RuntimeAPI {
3109
+ constructor() {
3110
+ __privateAdd(this, _getRuntimeManager);
3412
3111
  }
3413
- trace(name, fn, options) {
3414
- return this._config.tracer.startActiveSpan(name, fn, options);
3112
+ static getInstance() {
3113
+ if (!this._instance) {
3114
+ this._instance = new _RuntimeAPI();
3115
+ }
3116
+ return this._instance;
3415
3117
  }
3416
- };
3417
- _emitLog = new WeakSet();
3418
- emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
3419
- let attributes = {
3420
- ...flattenAttributes(safeJsonProcess(properties))
3421
- };
3422
- const icon = iconStringForSeverity(severityNumber);
3423
- if (icon !== void 0) {
3424
- attributes[SemanticInternalAttributes.STYLE_ICON] = icon;
3425
- }
3426
- this._config.logger.emit({
3427
- severityNumber,
3428
- severityText,
3429
- body: message,
3430
- attributes,
3431
- timestamp
3432
- });
3433
- }, "#emitLog");
3434
- _getTimestampInHrTime = new WeakSet();
3435
- getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
3436
- return clock.preciseNow();
3437
- }, "#getTimestampInHrTime");
3438
- __name(_OtelTaskLogger, "OtelTaskLogger");
3439
- var OtelTaskLogger = _OtelTaskLogger;
3440
- var _NoopTaskLogger = class _NoopTaskLogger {
3441
- debug() {
3118
+ waitForDuration(ms) {
3119
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
3442
3120
  }
3443
- log() {
3121
+ waitUntil(date) {
3122
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
3444
3123
  }
3445
- info() {
3124
+ waitForTask(params) {
3125
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
3446
3126
  }
3447
- warn() {
3127
+ waitForBatch(params) {
3128
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
3448
3129
  }
3449
- error() {
3130
+ setGlobalRuntimeManager(runtimeManager) {
3131
+ return registerGlobal(API_NAME4, runtimeManager);
3450
3132
  }
3451
- trace(name, fn) {
3452
- return fn({});
3133
+ disable() {
3134
+ __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
3135
+ unregisterGlobal(API_NAME4);
3453
3136
  }
3454
3137
  };
3455
- __name(_NoopTaskLogger, "NoopTaskLogger");
3456
- var NoopTaskLogger = _NoopTaskLogger;
3457
- function safeJsonProcess(value) {
3458
- try {
3459
- return JSON.parse(JSON.stringify(value));
3460
- } catch {
3461
- return value;
3138
+ _getRuntimeManager = new WeakSet();
3139
+ getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
3140
+ return getGlobal(API_NAME4) ?? NOOP_RUNTIME_MANAGER;
3141
+ }, "#getRuntimeManager");
3142
+ __name(_RuntimeAPI, "RuntimeAPI");
3143
+ var RuntimeAPI = _RuntimeAPI;
3144
+
3145
+ // src/v3/runtime-api.ts
3146
+ var runtime = RuntimeAPI.getInstance();
3147
+
3148
+ // src/v3/utils/getEnv.ts
3149
+ function getEnvVar(name) {
3150
+ if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
3151
+ return process.env[name];
3462
3152
  }
3463
3153
  }
3464
- __name(safeJsonProcess, "safeJsonProcess");
3154
+ __name(getEnvVar, "getEnvVar");
3465
3155
 
3466
- // src/v3/logger/index.ts
3467
- var API_NAME3 = "logger";
3468
- var NOOP_TASK_LOGGER = new NoopTaskLogger();
3469
- var _getTaskLogger, getTaskLogger_fn;
3470
- var _LoggerAPI = class _LoggerAPI {
3156
+ // src/v3/apiClientManager/index.ts
3157
+ var API_NAME5 = "api-client";
3158
+ var _getConfig, getConfig_fn;
3159
+ var _APIClientManagerAPI = class _APIClientManagerAPI {
3471
3160
  constructor() {
3472
- __privateAdd(this, _getTaskLogger);
3161
+ __privateAdd(this, _getConfig);
3473
3162
  }
3474
3163
  static getInstance() {
3475
3164
  if (!this._instance) {
3476
- this._instance = new _LoggerAPI();
3165
+ this._instance = new _APIClientManagerAPI();
3477
3166
  }
3478
3167
  return this._instance;
3479
3168
  }
3480
3169
  disable() {
3481
- unregisterGlobal(API_NAME3);
3482
- }
3483
- setGlobalTaskLogger(taskLogger) {
3484
- return registerGlobal(API_NAME3, taskLogger);
3170
+ unregisterGlobal(API_NAME5);
3485
3171
  }
3486
- debug(message, metadata) {
3487
- __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).debug(message, metadata);
3488
- }
3489
- log(message, metadata) {
3490
- __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).log(message, metadata);
3491
- }
3492
- info(message, metadata) {
3493
- __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).info(message, metadata);
3172
+ setGlobalAPIClientConfiguration(config) {
3173
+ return registerGlobal(API_NAME5, config);
3494
3174
  }
3495
- warn(message, metadata) {
3496
- __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).warn(message, metadata);
3175
+ get baseURL() {
3176
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
3177
+ return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
3497
3178
  }
3498
- error(message, metadata) {
3499
- __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).error(message, metadata);
3179
+ get accessToken() {
3180
+ const store = __privateMethod(this, _getConfig, getConfig_fn).call(this);
3181
+ return store?.secretKey ?? getEnvVar("TRIGGER_SECRET_KEY") ?? getEnvVar("TRIGGER_ACCESS_TOKEN");
3500
3182
  }
3501
- trace(name, fn) {
3502
- return __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).trace(name, fn);
3183
+ get client() {
3184
+ if (!this.baseURL || !this.accessToken) {
3185
+ return void 0;
3186
+ }
3187
+ return new ApiClient(this.baseURL, this.accessToken);
3503
3188
  }
3504
3189
  };
3505
- _getTaskLogger = new WeakSet();
3506
- getTaskLogger_fn = /* @__PURE__ */ __name(function() {
3507
- return getGlobal(API_NAME3) ?? NOOP_TASK_LOGGER;
3508
- }, "#getTaskLogger");
3509
- __name(_LoggerAPI, "LoggerAPI");
3510
- var LoggerAPI = _LoggerAPI;
3190
+ _getConfig = new WeakSet();
3191
+ getConfig_fn = /* @__PURE__ */ __name(function() {
3192
+ return getGlobal(API_NAME5);
3193
+ }, "#getConfig");
3194
+ __name(_APIClientManagerAPI, "APIClientManagerAPI");
3195
+ var APIClientManagerAPI = _APIClientManagerAPI;
3511
3196
 
3512
- // src/v3/logger-api.ts
3513
- var logger = LoggerAPI.getInstance();
3197
+ // src/v3/apiClientManager-api.ts
3198
+ var apiClientManager = APIClientManagerAPI.getInstance();
3514
3199
 
3515
3200
  // src/v3/task-catalog/noopTaskCatalog.ts
3516
3201
  var _NoopTaskCatalog = class _NoopTaskCatalog {
@@ -3529,6 +3214,9 @@ var _NoopTaskCatalog = class _NoopTaskCatalog {
3529
3214
  getTask(id) {
3530
3215
  return void 0;
3531
3216
  }
3217
+ taskExists(id) {
3218
+ return false;
3219
+ }
3532
3220
  disable() {
3533
3221
  }
3534
3222
  };
@@ -3536,7 +3224,7 @@ __name(_NoopTaskCatalog, "NoopTaskCatalog");
3536
3224
  var NoopTaskCatalog = _NoopTaskCatalog;
3537
3225
 
3538
3226
  // src/v3/task-catalog/index.ts
3539
- var API_NAME4 = "task-catalog";
3227
+ var API_NAME6 = "task-catalog";
3540
3228
  var NOOP_TASK_CATALOG = new NoopTaskCatalog();
3541
3229
  var _getCatalog, getCatalog_fn;
3542
3230
  var _TaskCatalogAPI = class _TaskCatalogAPI {
@@ -3550,10 +3238,10 @@ var _TaskCatalogAPI = class _TaskCatalogAPI {
3550
3238
  return this._instance;
3551
3239
  }
3552
3240
  setGlobalTaskCatalog(taskCatalog2) {
3553
- return registerGlobal(API_NAME4, taskCatalog2);
3241
+ return registerGlobal(API_NAME6, taskCatalog2);
3554
3242
  }
3555
3243
  disable() {
3556
- unregisterGlobal(API_NAME4);
3244
+ unregisterGlobal(API_NAME6);
3557
3245
  }
3558
3246
  registerTaskMetadata(task) {
3559
3247
  __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskMetadata(task);
@@ -3573,60 +3261,19 @@ var _TaskCatalogAPI = class _TaskCatalogAPI {
3573
3261
  getTask(id) {
3574
3262
  return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTask(id);
3575
3263
  }
3264
+ taskExists(id) {
3265
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).taskExists(id);
3266
+ }
3576
3267
  };
3577
3268
  _getCatalog = new WeakSet();
3578
3269
  getCatalog_fn = /* @__PURE__ */ __name(function() {
3579
- return getGlobal(API_NAME4) ?? NOOP_TASK_CATALOG;
3270
+ return getGlobal(API_NAME6) ?? NOOP_TASK_CATALOG;
3580
3271
  }, "#getCatalog");
3581
3272
  __name(_TaskCatalogAPI, "TaskCatalogAPI");
3582
3273
  var TaskCatalogAPI = _TaskCatalogAPI;
3583
3274
 
3584
3275
  // src/v3/task-catalog-api.ts
3585
3276
  var taskCatalog = TaskCatalogAPI.getInstance();
3586
-
3587
- // src/v3/limits.ts
3588
- var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
3589
- var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
3590
- var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
3591
- var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
3592
- var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
3593
- var OTEL_LINK_COUNT_LIMIT = 2;
3594
- var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
3595
- var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
3596
- var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
3597
- function imposeAttributeLimits(attributes) {
3598
- const newAttributes = {};
3599
- for (const [key, value] of Object.entries(attributes)) {
3600
- if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
3601
- continue;
3602
- }
3603
- if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
3604
- break;
3605
- }
3606
- newAttributes[key] = value;
3607
- }
3608
- return newAttributes;
3609
- }
3610
- __name(imposeAttributeLimits, "imposeAttributeLimits");
3611
- function calculateAttributeValueLength(value) {
3612
- if (value === void 0 || value === null) {
3613
- return 0;
3614
- }
3615
- if (typeof value === "string") {
3616
- return value.length;
3617
- }
3618
- if (typeof value === "number") {
3619
- return 8;
3620
- }
3621
- if (typeof value === "boolean") {
3622
- return 4;
3623
- }
3624
- if (Array.isArray(value)) {
3625
- return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
3626
- }
3627
- return 0;
3628
- }
3629
- __name(calculateAttributeValueLength, "calculateAttributeValueLength");
3630
3277
  function dateDifference(date1, date2) {
3631
3278
  return Math.abs(date1.getTime() - date2.getTime());
3632
3279
  }
@@ -3646,291 +3293,61 @@ function millisecondsToNanoseconds(milliseconds) {
3646
3293
  return milliseconds * 1e6;
3647
3294
  }
3648
3295
  __name(millisecondsToNanoseconds, "millisecondsToNanoseconds");
3649
- function formatDurationNanoseconds(nanoseconds, options) {
3650
- return formatDurationMilliseconds(nanosecondsToMilliseconds(nanoseconds), options);
3651
- }
3652
- __name(formatDurationNanoseconds, "formatDurationNanoseconds");
3653
- var aboveOneSecondUnits = [
3654
- "d",
3655
- "h",
3656
- "m",
3657
- "s"
3658
- ];
3659
- var belowOneSecondUnits = [
3660
- "ms"
3661
- ];
3662
- function formatDurationMilliseconds(milliseconds, options) {
3663
- let duration = humanizeDuration(milliseconds, {
3664
- units: options?.units ? options.units : milliseconds < 1e3 ? belowOneSecondUnits : aboveOneSecondUnits,
3665
- maxDecimalPoints: options?.maxDecimalPoints ?? 1,
3666
- largest: 2
3667
- });
3668
- if (!options) {
3669
- return duration;
3670
- }
3671
- switch (options.style) {
3672
- case "short":
3673
- duration = duration.replace(" milliseconds", "ms");
3674
- duration = duration.replace(" millisecond", "ms");
3675
- duration = duration.replace(" seconds", "s");
3676
- duration = duration.replace(" second", "s");
3677
- duration = duration.replace(" minutes", "m");
3678
- duration = duration.replace(" minute", "m");
3679
- duration = duration.replace(" hours", "h");
3680
- duration = duration.replace(" hour", "h");
3681
- duration = duration.replace(" days", "d");
3682
- duration = duration.replace(" day", "d");
3683
- duration = duration.replace(" weeks", "w");
3684
- duration = duration.replace(" week", "w");
3685
- duration = duration.replace(" months", "mo");
3686
- duration = duration.replace(" month", "mo");
3687
- duration = duration.replace(" years", "y");
3688
- duration = duration.replace(" year", "y");
3689
- }
3690
- return duration;
3691
- }
3692
- __name(formatDurationMilliseconds, "formatDurationMilliseconds");
3693
- function formatDurationInDays(milliseconds) {
3694
- let duration = humanizeDuration(milliseconds, {
3695
- maxDecimalPoints: 0,
3696
- largest: 2,
3697
- units: [
3698
- "d"
3699
- ]
3700
- });
3701
- return duration;
3702
- }
3703
- __name(formatDurationInDays, "formatDurationInDays");
3704
- async function unboundedTimeout(delay = 0, value, options) {
3705
- const maxDelay = 2147483647;
3706
- const fullTimeouts = Math.floor(delay / maxDelay);
3707
- const remainingDelay = delay % maxDelay;
3708
- let lastTimeoutResult = await setTimeout$1(remainingDelay, value, options);
3709
- for (let i = 0; i < fullTimeouts; i++) {
3710
- lastTimeoutResult = await setTimeout$1(maxDelay, value, options);
3711
- }
3712
- return lastTimeoutResult;
3713
- }
3714
- __name(unboundedTimeout, "unboundedTimeout");
3715
-
3716
- // src/v3/runtime/devRuntimeManager.ts
3717
- var _DevRuntimeManager = class _DevRuntimeManager {
3718
- constructor() {
3719
- __publicField(this, "_taskWaits", /* @__PURE__ */ new Map());
3720
- __publicField(this, "_batchWaits", /* @__PURE__ */ new Map());
3721
- __publicField(this, "_pendingCompletionNotifications", /* @__PURE__ */ new Map());
3722
- }
3723
- disable() {
3724
- }
3725
- async waitForDuration(ms) {
3726
- await unboundedTimeout(ms);
3727
- }
3728
- async waitUntil(date) {
3729
- return this.waitForDuration(date.getTime() - Date.now());
3730
- }
3731
- async waitForTask(params) {
3732
- const pendingCompletion = this._pendingCompletionNotifications.get(params.id);
3733
- if (pendingCompletion) {
3734
- this._pendingCompletionNotifications.delete(params.id);
3735
- return pendingCompletion;
3736
- }
3737
- const promise = new Promise((resolve, reject) => {
3738
- this._taskWaits.set(params.id, {
3739
- resolve,
3740
- reject
3741
- });
3742
- });
3743
- return await promise;
3744
- }
3745
- async waitForBatch(params) {
3746
- if (!params.runs.length) {
3747
- return Promise.resolve({
3748
- id: params.id,
3749
- items: []
3750
- });
3751
- }
3752
- const promise = Promise.all(params.runs.map((runId) => {
3753
- return new Promise((resolve, reject) => {
3754
- const pendingCompletion = this._pendingCompletionNotifications.get(runId);
3755
- if (pendingCompletion) {
3756
- this._pendingCompletionNotifications.delete(runId);
3757
- if (pendingCompletion.ok) {
3758
- resolve(pendingCompletion);
3759
- } else {
3760
- reject(pendingCompletion);
3761
- }
3762
- return;
3763
- }
3764
- this._taskWaits.set(runId, {
3765
- resolve,
3766
- reject
3767
- });
3768
- });
3769
- }));
3770
- const results = await promise;
3771
- return {
3772
- id: params.id,
3773
- items: results
3774
- };
3775
- }
3776
- resumeTask(completion, execution) {
3777
- const wait = this._taskWaits.get(execution.run.id);
3778
- if (!wait) {
3779
- this._pendingCompletionNotifications.set(execution.run.id, completion);
3780
- return;
3781
- }
3782
- if (completion.ok) {
3783
- wait.resolve(completion);
3784
- } else {
3785
- wait.reject(completion);
3786
- }
3787
- this._taskWaits.delete(execution.run.id);
3788
- }
3789
- };
3790
- __name(_DevRuntimeManager, "DevRuntimeManager");
3791
- var DevRuntimeManager = _DevRuntimeManager;
3792
-
3793
- // src/v3/runtime/prodRuntimeManager.ts
3794
- var _ProdRuntimeManager = class _ProdRuntimeManager {
3795
- constructor(ipc, options = {}) {
3796
- this.ipc = ipc;
3797
- this.options = options;
3798
- this._taskWaits = /* @__PURE__ */ new Map();
3799
- this._batchWaits = /* @__PURE__ */ new Map();
3800
- }
3801
- disable() {
3802
- }
3803
- async waitForDuration(ms) {
3804
- const now = Date.now();
3805
- const resolveAfterDuration = unboundedTimeout(ms, "duration");
3806
- if (ms <= this.waitThresholdInMs) {
3807
- await resolveAfterDuration;
3808
- return;
3809
- }
3810
- const waitForRestore = new Promise((resolve, reject) => {
3811
- this._waitForRestore = {
3812
- resolve,
3813
- reject
3814
- };
3815
- });
3816
- const { willCheckpointAndRestore } = await this.ipc.sendWithAck("WAIT_FOR_DURATION", {
3817
- ms,
3818
- now
3819
- });
3820
- if (!willCheckpointAndRestore) {
3821
- await resolveAfterDuration;
3822
- return;
3823
- }
3824
- this.ipc.send("READY_FOR_CHECKPOINT", {});
3825
- await Promise.race([
3826
- waitForRestore,
3827
- resolveAfterDuration
3828
- ]);
3829
- this.ipc.send("CANCEL_CHECKPOINT", {});
3830
- }
3831
- resumeAfterRestore() {
3832
- if (!this._waitForRestore) {
3833
- return;
3834
- }
3835
- clock.reset();
3836
- this._waitForRestore.resolve("restore");
3837
- this._waitForRestore = void 0;
3838
- }
3839
- async waitUntil(date) {
3840
- return this.waitForDuration(date.getTime() - Date.now());
3841
- }
3842
- async waitForTask(params) {
3843
- const promise = new Promise((resolve, reject) => {
3844
- this._taskWaits.set(params.id, {
3845
- resolve,
3846
- reject
3847
- });
3848
- });
3849
- await this.ipc.send("WAIT_FOR_TASK", {
3850
- friendlyId: params.id
3851
- });
3852
- return await promise;
3853
- }
3854
- async waitForBatch(params) {
3855
- if (!params.runs.length) {
3856
- return Promise.resolve({
3857
- id: params.id,
3858
- items: []
3859
- });
3860
- }
3861
- const promise = Promise.all(params.runs.map((runId) => {
3862
- return new Promise((resolve, reject) => {
3863
- this._taskWaits.set(runId, {
3864
- resolve,
3865
- reject
3866
- });
3867
- });
3868
- }));
3869
- await this.ipc.send("WAIT_FOR_BATCH", {
3870
- batchFriendlyId: params.id,
3871
- runFriendlyIds: params.runs
3872
- });
3873
- const results = await promise;
3874
- return {
3875
- id: params.id,
3876
- items: results
3877
- };
3878
- }
3879
- resumeTask(completion, execution) {
3880
- const wait = this._taskWaits.get(execution.run.id);
3881
- if (!wait) {
3882
- return;
3883
- }
3884
- if (completion.ok) {
3885
- wait.resolve(completion);
3886
- } else {
3887
- wait.reject(completion);
3888
- }
3889
- this._taskWaits.delete(execution.run.id);
3890
- }
3891
- get waitThresholdInMs() {
3892
- return this.options.waitThresholdInMs ?? 3e4;
3893
- }
3894
- };
3895
- __name(_ProdRuntimeManager, "ProdRuntimeManager");
3896
- var ProdRuntimeManager = _ProdRuntimeManager;
3897
- var _originClockTime, originClockTime_get, _originPreciseDate, originPreciseDate_get;
3898
- var _PreciseWallClock = class _PreciseWallClock {
3899
- constructor(options = {}) {
3900
- __privateAdd(this, _originClockTime);
3901
- __privateAdd(this, _originPreciseDate);
3902
- this._origin = {
3903
- clockTime: options.origin ?? process.hrtime(),
3904
- preciseDate: options.now ?? new PreciseDate()
3905
- };
3906
- }
3907
- preciseNow() {
3908
- const elapsedHrTime = process.hrtime(__privateGet(this, _originClockTime, originClockTime_get));
3909
- const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
3910
- const preciseDate = new PreciseDate(__privateGet(this, _originPreciseDate, originPreciseDate_get).getFullTime() + elapsedNanoseconds);
3911
- const dateStruct = preciseDate.toStruct();
3912
- return [
3913
- dateStruct.seconds,
3914
- dateStruct.nanos
3915
- ];
3296
+ function formatDurationNanoseconds(nanoseconds, options) {
3297
+ return formatDurationMilliseconds(nanosecondsToMilliseconds(nanoseconds), options);
3298
+ }
3299
+ __name(formatDurationNanoseconds, "formatDurationNanoseconds");
3300
+ var aboveOneSecondUnits = [
3301
+ "d",
3302
+ "h",
3303
+ "m",
3304
+ "s"
3305
+ ];
3306
+ var belowOneSecondUnits = [
3307
+ "ms"
3308
+ ];
3309
+ function formatDurationMilliseconds(milliseconds, options) {
3310
+ let duration = humanizeDuration(milliseconds, {
3311
+ units: options?.units ? options.units : milliseconds < 1e3 ? belowOneSecondUnits : aboveOneSecondUnits,
3312
+ maxDecimalPoints: options?.maxDecimalPoints ?? 1,
3313
+ largest: 2
3314
+ });
3315
+ if (!options) {
3316
+ return duration;
3916
3317
  }
3917
- reset() {
3918
- this._origin = {
3919
- clockTime: process.hrtime(),
3920
- preciseDate: new PreciseDate()
3921
- };
3318
+ switch (options.style) {
3319
+ case "short":
3320
+ duration = duration.replace(" milliseconds", "ms");
3321
+ duration = duration.replace(" millisecond", "ms");
3322
+ duration = duration.replace(" seconds", "s");
3323
+ duration = duration.replace(" second", "s");
3324
+ duration = duration.replace(" minutes", "m");
3325
+ duration = duration.replace(" minute", "m");
3326
+ duration = duration.replace(" hours", "h");
3327
+ duration = duration.replace(" hour", "h");
3328
+ duration = duration.replace(" days", "d");
3329
+ duration = duration.replace(" day", "d");
3330
+ duration = duration.replace(" weeks", "w");
3331
+ duration = duration.replace(" week", "w");
3332
+ duration = duration.replace(" months", "mo");
3333
+ duration = duration.replace(" month", "mo");
3334
+ duration = duration.replace(" years", "y");
3335
+ duration = duration.replace(" year", "y");
3922
3336
  }
3923
- };
3924
- _originClockTime = new WeakSet();
3925
- originClockTime_get = /* @__PURE__ */ __name(function() {
3926
- return this._origin.clockTime;
3927
- }, "#originClockTime");
3928
- _originPreciseDate = new WeakSet();
3929
- originPreciseDate_get = /* @__PURE__ */ __name(function() {
3930
- return this._origin.preciseDate;
3931
- }, "#originPreciseDate");
3932
- __name(_PreciseWallClock, "PreciseWallClock");
3933
- var PreciseWallClock = _PreciseWallClock;
3337
+ return duration;
3338
+ }
3339
+ __name(formatDurationMilliseconds, "formatDurationMilliseconds");
3340
+ function formatDurationInDays(milliseconds) {
3341
+ let duration = humanizeDuration(milliseconds, {
3342
+ maxDecimalPoints: 0,
3343
+ largest: 2,
3344
+ units: [
3345
+ "d"
3346
+ ]
3347
+ });
3348
+ return duration;
3349
+ }
3350
+ __name(formatDurationInDays, "formatDurationInDays");
3934
3351
  var _TriggerTracer = class _TriggerTracer {
3935
3352
  constructor(_config) {
3936
3353
  this._config = _config;
@@ -4002,146 +3419,6 @@ var _TriggerTracer = class _TriggerTracer {
4002
3419
  };
4003
3420
  __name(_TriggerTracer, "TriggerTracer");
4004
3421
  var TriggerTracer = _TriggerTracer;
4005
- var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
4006
- var _ConsoleInterceptor = class _ConsoleInterceptor {
4007
- constructor(logger2, sendToStdIO) {
4008
- __privateAdd(this, _handleLog);
4009
- __privateAdd(this, _getTimestampInHrTime2);
4010
- __privateAdd(this, _getAttributes);
4011
- this.logger = logger2;
4012
- this.sendToStdIO = sendToStdIO;
4013
- }
4014
- // Intercept the console and send logs to the OpenTelemetry logger
4015
- // during the execution of the callback
4016
- async intercept(console2, callback) {
4017
- const originalConsole = {
4018
- log: console2.log,
4019
- info: console2.info,
4020
- warn: console2.warn,
4021
- error: console2.error,
4022
- debug: console2.debug
4023
- };
4024
- console2.log = this.log.bind(this);
4025
- console2.info = this.info.bind(this);
4026
- console2.warn = this.warn.bind(this);
4027
- console2.error = this.error.bind(this);
4028
- console2.debug = this.debug.bind(this);
4029
- try {
4030
- return await callback();
4031
- } finally {
4032
- console2.log = originalConsole.log;
4033
- console2.info = originalConsole.info;
4034
- console2.warn = originalConsole.warn;
4035
- console2.error = originalConsole.error;
4036
- console2.debug = originalConsole.debug;
4037
- }
4038
- }
4039
- debug(...args) {
4040
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.DEBUG, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Debug", ...args);
4041
- }
4042
- log(...args) {
4043
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
4044
- }
4045
- info(...args) {
4046
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Info", ...args);
4047
- }
4048
- warn(...args) {
4049
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.WARN, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Warn", ...args);
4050
- }
4051
- error(...args) {
4052
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.ERROR, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Error", ...args);
4053
- }
4054
- };
4055
- _handleLog = new WeakSet();
4056
- handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
4057
- const body = util.format(...args);
4058
- if (this.sendToStdIO) {
4059
- if (severityNumber === SeverityNumber.ERROR) {
4060
- process.stderr.write(body);
4061
- } else {
4062
- process.stdout.write(body);
4063
- }
4064
- }
4065
- const parsed = tryParseJSON(body);
4066
- if (parsed.ok) {
4067
- this.logger.emit({
4068
- severityNumber,
4069
- severityText,
4070
- body: getLogMessage(parsed.value, severityText),
4071
- attributes: {
4072
- ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
4073
- ...flattenAttributes(parsed.value)
4074
- },
4075
- timestamp
4076
- });
4077
- return;
4078
- }
4079
- this.logger.emit({
4080
- severityNumber,
4081
- severityText,
4082
- body,
4083
- attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
4084
- timestamp
4085
- });
4086
- }, "#handleLog");
4087
- _getTimestampInHrTime2 = new WeakSet();
4088
- getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
4089
- return clock.preciseNow();
4090
- }, "#getTimestampInHrTime");
4091
- _getAttributes = new WeakSet();
4092
- getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
4093
- const icon = iconStringForSeverity(severityNumber1);
4094
- let result = {};
4095
- if (icon !== void 0) {
4096
- result[SemanticInternalAttributes.STYLE_ICON] = icon;
4097
- }
4098
- return result;
4099
- }, "#getAttributes");
4100
- __name(_ConsoleInterceptor, "ConsoleInterceptor");
4101
- var ConsoleInterceptor = _ConsoleInterceptor;
4102
- function getLogMessage(value, fallback) {
4103
- if (typeof value["message"] === "string") {
4104
- return value["message"];
4105
- }
4106
- if (typeof value["msg"] === "string") {
4107
- return value["msg"];
4108
- }
4109
- if (typeof value["body"] === "string") {
4110
- return value["body"];
4111
- }
4112
- if (typeof value["error"] === "string") {
4113
- return value["error"];
4114
- }
4115
- return fallback;
4116
- }
4117
- __name(getLogMessage, "getLogMessage");
4118
- function tryParseJSON(value) {
4119
- try {
4120
- const parsed = JSON.parse(value);
4121
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
4122
- return {
4123
- ok: true,
4124
- value: parsed
4125
- };
4126
- }
4127
- return {
4128
- ok: false,
4129
- value
4130
- };
4131
- } catch (e) {
4132
- return {
4133
- ok: false,
4134
- value
4135
- };
4136
- }
4137
- }
4138
- __name(tryParseJSON, "tryParseJSON");
4139
-
4140
- // src/v3/utils/styleAttributes.ts
4141
- function accessoryAttributes(accessory) {
4142
- return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
4143
- }
4144
- __name(accessoryAttributes, "accessoryAttributes");
4145
3422
 
4146
3423
  // src/eventFilterMatches.ts
4147
3424
  function eventFilterMatches(payload, filter) {
@@ -4311,150 +3588,18 @@ function omit(obj, ...keys) {
4311
3588
  return result;
4312
3589
  }
4313
3590
  __name(omit, "omit");
4314
- var _a2;
4315
- var AsyncResourceDetector = (_a2 = class {
4316
- constructor() {
4317
- __publicField(this, "_resolved", false);
4318
- this._promise = new Promise((resolver) => {
4319
- this._resolver = resolver;
4320
- });
4321
- }
4322
- detect(_config) {
4323
- return new Resource({}, this._promise);
4324
- }
4325
- resolveWithAttributes(attributes) {
4326
- if (!this._resolver) {
4327
- throw new Error("Resolver not available");
4328
- }
4329
- if (this._resolved) {
4330
- return;
4331
- }
4332
- this._resolved = true;
4333
- this._resolver(attributes);
4334
- }
4335
- }, __name(_a2, "AsyncResourceDetector"), _a2);
4336
- var _TracingSDK = class _TracingSDK {
4337
- constructor(config) {
4338
- this.config = config;
4339
- this.asyncResourceDetector = new AsyncResourceDetector();
4340
- setLogLevel(config.diagLogLevel ?? "none");
4341
- const envResourceAttributesSerialized = getEnvVar("OTEL_RESOURCE_ATTRIBUTES");
4342
- const envResourceAttributes = envResourceAttributesSerialized ? JSON.parse(envResourceAttributesSerialized) : {};
4343
- const commonResources = detectResourcesSync({
4344
- detectors: [
4345
- this.asyncResourceDetector,
4346
- processDetectorSync
4347
- ]
4348
- }).merge(new Resource({
4349
- [SemanticResourceAttributes.CLOUD_PROVIDER]: "trigger.dev",
4350
- [SemanticInternalAttributes.TRIGGER]: true
4351
- })).merge(config.resource ?? new Resource({})).merge(new Resource(envResourceAttributes));
4352
- const traceProvider = new NodeTracerProvider({
4353
- forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
4354
- resource: commonResources,
4355
- spanLimits: {
4356
- attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
4357
- attributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
4358
- eventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT,
4359
- attributePerEventCountLimit: OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
4360
- linkCountLimit: OTEL_LINK_COUNT_LIMIT,
4361
- attributePerLinkCountLimit: OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT
4362
- }
4363
- });
4364
- const spanExporter = new OTLPTraceExporter({
4365
- url: `${config.url}/v1/traces`,
4366
- timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
4367
- });
4368
- traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new BatchSpanProcessor(spanExporter, {
4369
- maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
4370
- scheduledDelayMillis: parseInt(getEnvVar("OTEL_SPAN_SCHEDULED_DELAY_MILLIS") ?? "200"),
4371
- exportTimeoutMillis: parseInt(getEnvVar("OTEL_SPAN_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
4372
- maxQueueSize: parseInt(getEnvVar("OTEL_SPAN_MAX_QUEUE_SIZE") ?? "512")
4373
- }) : new SimpleSpanProcessor(spanExporter)));
4374
- traceProvider.register();
4375
- registerInstrumentations({
4376
- instrumentations: config.instrumentations ?? [],
4377
- tracerProvider: traceProvider
4378
- });
4379
- const logExporter = new OTLPLogExporter({
4380
- url: `${config.url}/v1/logs`
4381
- });
4382
- const loggerProvider = new LoggerProvider({
4383
- resource: commonResources,
4384
- logRecordLimits: {
4385
- attributeCountLimit: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
4386
- attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
4387
- }
4388
- });
4389
- loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new BatchLogRecordProcessor(logExporter, {
4390
- maxExportBatchSize: parseInt(getEnvVar("OTEL_LOG_MAX_EXPORT_BATCH_SIZE") ?? "64"),
4391
- scheduledDelayMillis: parseInt(getEnvVar("OTEL_LOG_SCHEDULED_DELAY_MILLIS") ?? "200"),
4392
- exportTimeoutMillis: parseInt(getEnvVar("OTEL_LOG_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
4393
- maxQueueSize: parseInt(getEnvVar("OTEL_LOG_MAX_QUEUE_SIZE") ?? "512")
4394
- }) : new SimpleLogRecordProcessor(logExporter)));
4395
- this._logProvider = loggerProvider;
4396
- this._spanExporter = spanExporter;
4397
- this._traceProvider = traceProvider;
4398
- logs.setGlobalLoggerProvider(loggerProvider);
4399
- this.getLogger = loggerProvider.getLogger.bind(loggerProvider);
4400
- this.getTracer = traceProvider.getTracer.bind(traceProvider);
4401
- }
4402
- async flush() {
4403
- await this._traceProvider.forceFlush();
4404
- await this._logProvider.forceFlush();
4405
- }
4406
- async shutdown() {
4407
- await this._traceProvider.shutdown();
4408
- await this._logProvider.shutdown();
4409
- }
4410
- };
4411
- __name(_TracingSDK, "TracingSDK");
4412
- var TracingSDK = _TracingSDK;
4413
- function setLogLevel(level) {
4414
- let diagLogLevel;
4415
- switch (level) {
4416
- case "none":
4417
- diagLogLevel = DiagLogLevel.NONE;
4418
- break;
4419
- case "error":
4420
- diagLogLevel = DiagLogLevel.ERROR;
4421
- break;
4422
- case "warn":
4423
- diagLogLevel = DiagLogLevel.WARN;
4424
- break;
4425
- case "info":
4426
- diagLogLevel = DiagLogLevel.INFO;
4427
- break;
4428
- case "debug":
4429
- diagLogLevel = DiagLogLevel.DEBUG;
4430
- break;
4431
- case "verbose":
4432
- diagLogLevel = DiagLogLevel.VERBOSE;
4433
- break;
4434
- case "all":
4435
- diagLogLevel = DiagLogLevel.ALL;
4436
- break;
4437
- default:
4438
- diagLogLevel = DiagLogLevel.NONE;
4439
- }
4440
- diag.setLogger(new DiagConsoleLogger(), diagLogLevel);
3591
+
3592
+ // src/v3/utils/styleAttributes.ts
3593
+ function accessoryAttributes(accessory) {
3594
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
4441
3595
  }
4442
- __name(setLogLevel, "setLogLevel");
3596
+ __name(accessoryAttributes, "accessoryAttributes");
4443
3597
 
4444
- // src/v3/otel/index.ts
4445
- function recordSpanException(span, error) {
4446
- if (error instanceof Error) {
4447
- span.recordException(error);
4448
- } else if (typeof error === "string") {
4449
- span.recordException(new Error(error));
4450
- } else {
4451
- span.recordException(new Error(JSON.stringify(error)));
4452
- }
4453
- span.setStatus({
4454
- code: SpanStatusCode.ERROR
4455
- });
3598
+ // src/v3/utils/detectDependencyVersion.ts
3599
+ function detectDependencyVersion(dependency) {
3600
+ return dependencies[dependency];
4456
3601
  }
4457
- __name(recordSpanException, "recordSpanException");
3602
+ __name(detectDependencyVersion, "detectDependencyVersion");
4458
3603
 
4459
3604
  // src/v3/utils/ioSerialization.ts
4460
3605
  async function parsePacket(value) {
@@ -4614,11 +3759,12 @@ async function createPacketAttributes(packet, dataKey, dataTypeKey) {
4614
3759
  try {
4615
3760
  const parsed = parse(packet.data);
4616
3761
  const jsonified = JSON.parse(JSON.stringify(parsed, safeReplacer));
4617
- return {
3762
+ const result = {
4618
3763
  ...flattenAttributes(jsonified, dataKey),
4619
3764
  [dataTypeKey]: "application/json"
4620
3765
  };
4621
- } catch {
3766
+ return result;
3767
+ } catch (e) {
4622
3768
  return;
4623
3769
  }
4624
3770
  case "application/store":
@@ -4724,374 +3870,6 @@ function safeJsonParse2(value) {
4724
3870
  }
4725
3871
  __name(safeJsonParse2, "safeJsonParse");
4726
3872
 
4727
- // src/v3/workers/taskExecutor.ts
4728
- var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
4729
- var _TaskExecutor = class _TaskExecutor {
4730
- constructor(task, options) {
4731
- __privateAdd(this, _callRun);
4732
- __privateAdd(this, _callTaskInit);
4733
- __privateAdd(this, _callTaskCleanup);
4734
- __privateAdd(this, _handleError);
4735
- this.task = task;
4736
- this._tracingSDK = options.tracingSDK;
4737
- this._tracer = options.tracer;
4738
- this._consoleInterceptor = options.consoleInterceptor;
4739
- this._config = options.projectConfig;
4740
- this._importedConfig = options.importedConfig;
4741
- this._handleErrorFn = options.handleErrorFn;
4742
- }
4743
- async execute(execution, worker, traceContext) {
4744
- const ctx = TaskRunContext.parse(execution);
4745
- const attemptMessage = `Attempt ${execution.attempt.number}`;
4746
- const originalPacket = {
4747
- data: execution.run.payload,
4748
- dataType: execution.run.payloadType
4749
- };
4750
- const result = await taskContextManager.runWith({
4751
- ctx,
4752
- worker
4753
- }, async () => {
4754
- this._tracingSDK.asyncResourceDetector.resolveWithAttributes({
4755
- ...taskContextManager.attributes,
4756
- [SemanticInternalAttributes.SDK_VERSION]: this.task.packageVersion,
4757
- [SemanticInternalAttributes.SDK_LANGUAGE]: "typescript"
4758
- });
4759
- return await this._tracer.startActiveSpan(attemptMessage, async (span) => {
4760
- return await this._consoleInterceptor.intercept(console, async () => {
4761
- let parsedPayload;
4762
- let initOutput;
4763
- try {
4764
- const payloadPacket = await conditionallyImportPacket(originalPacket, this._tracer);
4765
- parsedPayload = await parsePacket(payloadPacket);
4766
- initOutput = await __privateMethod(this, _callTaskInit, callTaskInit_fn).call(this, parsedPayload, ctx);
4767
- const output = await __privateMethod(this, _callRun, callRun_fn).call(this, parsedPayload, ctx, initOutput);
4768
- try {
4769
- const stringifiedOutput = await stringifyIO(output);
4770
- const finalOutput = await conditionallyExportPacket(stringifiedOutput, `${execution.attempt.id}/output`, this._tracer);
4771
- const attributes = await createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE);
4772
- if (attributes) {
4773
- span.setAttributes(attributes);
4774
- }
4775
- return {
4776
- ok: true,
4777
- id: execution.attempt.id,
4778
- output: finalOutput.data,
4779
- outputType: finalOutput.dataType
4780
- };
4781
- } catch (stringifyError) {
4782
- recordSpanException(span, stringifyError);
4783
- return {
4784
- ok: false,
4785
- id: execution.attempt.id,
4786
- error: {
4787
- type: "INTERNAL_ERROR",
4788
- code: TaskRunErrorCodes.TASK_OUTPUT_ERROR,
4789
- message: stringifyError instanceof Error ? stringifyError.message : typeof stringifyError === "string" ? stringifyError : void 0
4790
- }
4791
- };
4792
- }
4793
- } catch (runError) {
4794
- try {
4795
- const handleErrorResult = await __privateMethod(this, _handleError, handleError_fn).call(this, execution, runError, parsedPayload, ctx);
4796
- recordSpanException(span, handleErrorResult.error ?? runError);
4797
- return {
4798
- id: execution.attempt.id,
4799
- ok: false,
4800
- error: handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError),
4801
- retry: handleErrorResult.status === "retry" ? handleErrorResult.retry : void 0,
4802
- skippedRetrying: handleErrorResult.status === "skipped"
4803
- };
4804
- } catch (handleErrorError) {
4805
- recordSpanException(span, handleErrorError);
4806
- return {
4807
- ok: false,
4808
- id: execution.attempt.id,
4809
- error: {
4810
- type: "INTERNAL_ERROR",
4811
- code: TaskRunErrorCodes.HANDLE_ERROR_ERROR,
4812
- message: handleErrorError instanceof Error ? handleErrorError.message : typeof handleErrorError === "string" ? handleErrorError : void 0
4813
- }
4814
- };
4815
- }
4816
- } finally {
4817
- await __privateMethod(this, _callTaskCleanup, callTaskCleanup_fn).call(this, parsedPayload, ctx, initOutput);
4818
- }
4819
- });
4820
- }, {
4821
- kind: SpanKind.CONSUMER,
4822
- attributes: {
4823
- [SemanticInternalAttributes.STYLE_ICON]: "attempt",
4824
- ...accessoryAttributes({
4825
- items: [
4826
- {
4827
- text: ctx.task.filePath
4828
- },
4829
- {
4830
- text: `${ctx.task.exportName}.run()`
4831
- }
4832
- ],
4833
- style: "codepath"
4834
- })
4835
- }
4836
- }, this._tracer.extractContext(traceContext));
4837
- });
4838
- return result;
4839
- }
4840
- };
4841
- _callRun = new WeakSet();
4842
- callRun_fn = /* @__PURE__ */ __name(async function(payload, ctx, init) {
4843
- const runFn = this.task.fns.run;
4844
- const middlewareFn = this.task.fns.middleware;
4845
- if (!runFn) {
4846
- throw new Error("Task does not have a run function");
4847
- }
4848
- if (!middlewareFn) {
4849
- return runFn(payload, {
4850
- ctx
4851
- });
4852
- }
4853
- return middlewareFn(payload, {
4854
- ctx,
4855
- next: async () => runFn(payload, {
4856
- ctx,
4857
- init
4858
- })
4859
- });
4860
- }, "#callRun");
4861
- _callTaskInit = new WeakSet();
4862
- callTaskInit_fn = /* @__PURE__ */ __name(async function(payload1, ctx1) {
4863
- const initFn = this.task.fns.init;
4864
- if (!initFn) {
4865
- return {};
4866
- }
4867
- return this._tracer.startActiveSpan("init", async (span) => {
4868
- return await initFn(payload1, {
4869
- ctx: ctx1
4870
- });
4871
- });
4872
- }, "#callTaskInit");
4873
- _callTaskCleanup = new WeakSet();
4874
- callTaskCleanup_fn = /* @__PURE__ */ __name(async function(payload2, ctx2, init1) {
4875
- const cleanupFn = this.task.fns.cleanup;
4876
- if (!cleanupFn) {
4877
- return;
4878
- }
4879
- return this._tracer.startActiveSpan("cleanup", async (span) => {
4880
- return await cleanupFn(payload2, {
4881
- ctx: ctx2,
4882
- init: init1
4883
- });
4884
- });
4885
- }, "#callTaskCleanup");
4886
- _handleError = new WeakSet();
4887
- handleError_fn = /* @__PURE__ */ __name(async function(execution, error, payload3, ctx3) {
4888
- const retriesConfig = this._importedConfig?.retries ?? this._config.retries;
4889
- const retry = this.task.retry ?? retriesConfig?.default;
4890
- if (!retry) {
4891
- return {
4892
- status: "noop"
4893
- };
4894
- }
4895
- const delay = calculateNextRetryDelay(retry, execution.attempt.number);
4896
- if (execution.environment.type === "DEVELOPMENT" && typeof retriesConfig?.enabledInDev === "boolean" && !retriesConfig.enabledInDev) {
4897
- return {
4898
- status: "skipped"
4899
- };
4900
- }
4901
- return this._tracer.startActiveSpan("handleError()", async (span) => {
4902
- const handleErrorResult = this.task.fns.handleError ? await this.task.fns.handleError(payload3, error, {
4903
- ctx: ctx3,
4904
- retry,
4905
- retryDelayInMs: delay,
4906
- retryAt: delay ? new Date(Date.now() + delay) : void 0
4907
- }) : this._importedConfig ? await this._handleErrorFn?.(payload3, error, {
4908
- ctx: ctx3,
4909
- retry,
4910
- retryDelayInMs: delay,
4911
- retryAt: delay ? new Date(Date.now() + delay) : void 0
4912
- }) : void 0;
4913
- if (!handleErrorResult) {
4914
- return typeof delay === "undefined" ? {
4915
- status: "noop"
4916
- } : {
4917
- status: "retry",
4918
- retry: {
4919
- timestamp: Date.now() + delay,
4920
- delay
4921
- }
4922
- };
4923
- }
4924
- if (handleErrorResult.skipRetrying) {
4925
- return {
4926
- status: "skipped",
4927
- error: handleErrorResult.error
4928
- };
4929
- }
4930
- if (typeof handleErrorResult.retryAt !== "undefined") {
4931
- return {
4932
- status: "retry",
4933
- retry: {
4934
- timestamp: handleErrorResult.retryAt.getTime(),
4935
- delay: handleErrorResult.retryAt.getTime() - Date.now()
4936
- },
4937
- error: handleErrorResult.error
4938
- };
4939
- }
4940
- if (typeof handleErrorResult.retryDelayInMs === "number") {
4941
- return {
4942
- status: "retry",
4943
- retry: {
4944
- timestamp: Date.now() + handleErrorResult.retryDelayInMs,
4945
- delay: handleErrorResult.retryDelayInMs
4946
- },
4947
- error: handleErrorResult.error
4948
- };
4949
- }
4950
- if (handleErrorResult.retry && typeof handleErrorResult.retry === "object") {
4951
- const delay2 = calculateNextRetryDelay(handleErrorResult.retry, execution.attempt.number);
4952
- return typeof delay2 === "undefined" ? {
4953
- status: "noop",
4954
- error: handleErrorResult.error
4955
- } : {
4956
- status: "retry",
4957
- retry: {
4958
- timestamp: Date.now() + delay2,
4959
- delay: delay2
4960
- },
4961
- error: handleErrorResult.error
4962
- };
4963
- }
4964
- return {
4965
- status: "noop",
4966
- error: handleErrorResult.error
4967
- };
4968
- }, {
4969
- attributes: {
4970
- [SemanticInternalAttributes.STYLE_ICON]: "exclamation-circle"
4971
- }
4972
- });
4973
- }, "#handleError");
4974
- __name(_TaskExecutor, "TaskExecutor");
4975
- var TaskExecutor = _TaskExecutor;
4976
-
4977
- // package.json
4978
- var dependencies = {
4979
- "@google-cloud/precise-date": "^4.0.0",
4980
- "@opentelemetry/api": "^1.8.0",
4981
- "@opentelemetry/api-logs": "^0.48.0",
4982
- "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
4983
- "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
4984
- "@opentelemetry/instrumentation": "^0.49.1",
4985
- "@opentelemetry/resources": "^1.22.0",
4986
- "@opentelemetry/sdk-logs": "^0.49.1",
4987
- "@opentelemetry/sdk-node": "^0.49.1",
4988
- "@opentelemetry/sdk-trace-base": "^1.22.0",
4989
- "@opentelemetry/sdk-trace-node": "^1.22.0",
4990
- "@opentelemetry/semantic-conventions": "^1.22.0",
4991
- "humanize-duration": "^3.27.3",
4992
- "socket.io": "^4.7.4",
4993
- "socket.io-client": "^4.7.4",
4994
- superjson: "^2.2.1",
4995
- ulidx: "^2.2.1",
4996
- zod: "3.22.3",
4997
- "zod-error": "1.5.0",
4998
- "zod-validation-error": "^1.5.0"
4999
- };
5000
-
5001
- // src/v3/utils/detectDependencyVersion.ts
5002
- function detectDependencyVersion(dependency) {
5003
- return dependencies[dependency];
5004
- }
5005
- __name(detectDependencyVersion, "detectDependencyVersion");
5006
-
5007
- // src/v3/task-catalog/standardTaskCatalog.ts
5008
- var _StandardTaskCatalog = class _StandardTaskCatalog {
5009
- constructor() {
5010
- __publicField(this, "_taskMetadata", /* @__PURE__ */ new Map());
5011
- __publicField(this, "_taskFunctions", /* @__PURE__ */ new Map());
5012
- __publicField(this, "_taskFileMetadata", /* @__PURE__ */ new Map());
5013
- }
5014
- registerTaskMetadata(task) {
5015
- const { fns, ...metadata } = task;
5016
- this._taskMetadata.set(task.id, metadata);
5017
- this._taskFunctions.set(task.id, fns);
5018
- }
5019
- updateTaskMetadata(id, updates) {
5020
- const existingMetadata = this._taskMetadata.get(id);
5021
- if (existingMetadata) {
5022
- this._taskMetadata.set(id, {
5023
- ...existingMetadata,
5024
- ...updates
5025
- });
5026
- }
5027
- if (updates.fns) {
5028
- const existingFunctions = this._taskFunctions.get(id);
5029
- if (existingFunctions) {
5030
- this._taskFunctions.set(id, {
5031
- ...existingFunctions,
5032
- ...updates.fns
5033
- });
5034
- }
5035
- }
5036
- }
5037
- registerTaskFileMetadata(id, metadata) {
5038
- this._taskFileMetadata.set(id, metadata);
5039
- }
5040
- // Return all the tasks, without the functions
5041
- getAllTaskMetadata() {
5042
- const result = [];
5043
- for (const [id, metadata] of this._taskMetadata) {
5044
- const fileMetadata = this._taskFileMetadata.get(id);
5045
- if (!fileMetadata) {
5046
- continue;
5047
- }
5048
- result.push({
5049
- ...metadata,
5050
- ...fileMetadata
5051
- });
5052
- }
5053
- return result;
5054
- }
5055
- getTaskMetadata(id) {
5056
- const metadata = this._taskMetadata.get(id);
5057
- const fileMetadata = this._taskFileMetadata.get(id);
5058
- if (!metadata || !fileMetadata) {
5059
- return void 0;
5060
- }
5061
- return {
5062
- ...metadata,
5063
- ...fileMetadata
5064
- };
5065
- }
5066
- getTask(id) {
5067
- const metadata = this._taskMetadata.get(id);
5068
- const fileMetadata = this._taskFileMetadata.get(id);
5069
- const fns = this._taskFunctions.get(id);
5070
- if (!metadata || !fns || !fileMetadata) {
5071
- return void 0;
5072
- }
5073
- return {
5074
- ...metadata,
5075
- ...fileMetadata,
5076
- fns
5077
- };
5078
- }
5079
- disable() {
5080
- }
5081
- };
5082
- __name(_StandardTaskCatalog, "StandardTaskCatalog");
5083
- var StandardTaskCatalog = _StandardTaskCatalog;
5084
-
5085
- // src/v3/index.ts
5086
- function parseTriggerTaskRequestBody(body) {
5087
- return TriggerTaskRequestBody.safeParse(body);
5088
- }
5089
- __name(parseTriggerTaskRequestBody, "parseTriggerTaskRequestBody");
5090
- function parseBatchTriggerTaskRequestBody(body) {
5091
- return BatchTriggerTaskRequestBody.safeParse(body);
5092
- }
5093
- __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
5094
-
5095
- export { APIConnectionError, APIError, ApiClient, ApiClientManager, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, ConsoleInterceptor, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, DeletedScheduleObject, DeploymentErrorData, DevRuntimeManager, PreciseWallClock as DurableClock, EnvironmentType, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListScheduleOptions, ListSchedulesResult, LogLevel, Machine, MachineCpu, MachineMemory, NotFoundError, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OtelTaskLogger, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdRuntimeManager, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RetryOptions, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SharedQueueToClientMessages, SimpleStructuredLogger, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StandardTaskCatalog, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskContextSpanProcessor, TaskEventStyle, TaskExecutor, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TracingSDK, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, ZodIpcConnection, ZodMessageHandler, ZodMessageSchema, ZodMessageSender, ZodNamespace, ZodSchemaParsedError, ZodSocketConnection, ZodSocketMessageHandler, ZodSocketMessageSender, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, getEnvVar, groupTaskMetadataIssuesByTask, iconStringForSeverity, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logLevels, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseBatchTriggerTaskRequestBody, parseError, parsePacket, parseTriggerTaskRequestBody, prettyPrintPacket, primitiveValueOrflattenedAttributes, recordSpanException, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContextManager, unflattenAttributes, workerToChildMessages };
3873
+ export { APIConnectionError, APIError, ApiClient, AttemptStatus, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateEnvironmentVariableRequestBody, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, DeletedScheduleObject, DeploymentErrorData, EnvironmentType, EnvironmentVariable, EnvironmentVariableResponseBody, EnvironmentVariableValue, EnvironmentVariables, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, ImportEnvironmentVariablesRequestBody, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListScheduleOptions, ListSchedulesResult, Machine, MachineCpu, MachineMemory, NULL_SENTINEL, NotFoundError, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RetrieveRunResponse, RetryOptions, RunStatus, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SharedQueueToClientMessages, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskEventStyle, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionLazyAttemptPayload, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateEnvironmentVariableRequestBody, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createJsonErrorObject, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, groupTaskMetadataIssuesByTask, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseError, parsePacket, prettyPrintPacket, primitiveValueOrflattenedAttributes, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContext, unflattenAttributes, workerToChildMessages };
5096
3874
  //# sourceMappingURL=out.js.map
5097
3875
  //# sourceMappingURL=index.mjs.map