@trigger.dev/core 0.0.0-prerelease-20240219135254 → 0.0.0-prerelease-20240408121557

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.
package/dist/v3/index.js CHANGED
@@ -2,12 +2,27 @@
2
2
 
3
3
  var zod = require('zod');
4
4
  var api = require('@opentelemetry/api');
5
- var node_async_hooks = require('node:async_hooks');
5
+ var async_hooks = require('async_hooks');
6
+ var socket_ioClient = require('socket.io-client');
7
+ var crypto = require('crypto');
8
+ var nodePath = require('path');
6
9
  var apiLogs = require('@opentelemetry/api-logs');
7
- var util = require('node:util');
10
+ var preciseDate = require('@google-cloud/precise-date');
11
+ var humanizeDuration = require('humanize-duration');
12
+ var promises = require('timers/promises');
13
+ var util = require('util');
14
+ var exporterLogsOtlpHttp = require('@opentelemetry/exporter-logs-otlp-http');
15
+ var exporterTraceOtlpHttp = require('@opentelemetry/exporter-trace-otlp-http');
16
+ var instrumentation = require('@opentelemetry/instrumentation');
17
+ var resources = require('@opentelemetry/resources');
18
+ var sdkLogs = require('@opentelemetry/sdk-logs');
19
+ var sdkTraceNode = require('@opentelemetry/sdk-trace-node');
20
+ var semanticConventions = require('@opentelemetry/semantic-conventions');
8
21
 
9
22
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
23
 
24
+ var nodePath__default = /*#__PURE__*/_interopDefault(nodePath);
25
+ var humanizeDuration__default = /*#__PURE__*/_interopDefault(humanizeDuration);
11
26
  var util__default = /*#__PURE__*/_interopDefault(util);
12
27
 
13
28
  var __defProp = Object.defineProperty;
@@ -35,6 +50,14 @@ var __privateSet = (obj, member, value, setter) => {
35
50
  setter ? setter.call(obj, value) : member.set(obj, value);
36
51
  return value;
37
52
  };
53
+ var __privateWrapper = (obj, member, setter, getter) => ({
54
+ set _(value) {
55
+ __privateSet(obj, member, value, setter);
56
+ },
57
+ get _() {
58
+ return __privateGet(obj, member, getter);
59
+ }
60
+ });
38
61
  var __privateMethod = (obj, member, method) => {
39
62
  __accessCheck(obj, member, "access private method");
40
63
  return method;
@@ -52,48 +75,6 @@ var GetPersonalAccessTokenResponseSchema = zod.z.object({
52
75
  obfuscatedToken: zod.z.string()
53
76
  }).nullable()
54
77
  });
55
- var TaskResource = zod.z.object({
56
- id: zod.z.string(),
57
- filePath: zod.z.string(),
58
- exportName: zod.z.string()
59
- });
60
- var BackgroundWorkerMetadata = zod.z.object({
61
- packageVersion: zod.z.string(),
62
- contentHash: zod.z.string(),
63
- cliPackageVersion: zod.z.string(),
64
- tasks: zod.z.array(TaskResource)
65
- });
66
-
67
- // src/v3/schemas/api.ts
68
- var WhoAmIResponseSchema = zod.z.object({
69
- userId: zod.z.string(),
70
- email: zod.z.string().email()
71
- });
72
- var GetProjectDevResponse = zod.z.object({
73
- apiKey: zod.z.string(),
74
- name: zod.z.string()
75
- });
76
- var CreateBackgroundWorkerRequestBody = zod.z.object({
77
- localOnly: zod.z.boolean(),
78
- metadata: BackgroundWorkerMetadata
79
- });
80
- var CreateBackgroundWorkerResponse = zod.z.object({
81
- id: zod.z.string(),
82
- version: zod.z.string(),
83
- contentHash: zod.z.string()
84
- });
85
- var BackgroundWorkerRecord = CreateBackgroundWorkerResponse;
86
- var TriggerTaskRequestBody = zod.z.object({
87
- payload: zod.z.any(),
88
- context: zod.z.any(),
89
- options: zod.z.object({
90
- parentAttempt: zod.z.string().optional(),
91
- lockToCurrentVersion: zod.z.boolean().optional()
92
- }).optional()
93
- });
94
- var TriggerTaskResponse = zod.z.object({
95
- id: zod.z.string()
96
- });
97
78
  var TaskRunBuiltInError = zod.z.object({
98
79
  type: zod.z.literal("BUILT_IN_ERROR"),
99
80
  name: zod.z.string(),
@@ -109,13 +90,30 @@ var TaskRunStringError = zod.z.object({
109
90
  raw: zod.z.string()
110
91
  });
111
92
  var TaskRunErrorCodes = {
112
- COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR"
93
+ COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
94
+ CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
95
+ TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
96
+ TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
97
+ TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
98
+ TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
99
+ TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
100
+ TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
101
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR"
113
102
  };
114
103
  var TaskRunInternalError = zod.z.object({
115
104
  type: zod.z.literal("INTERNAL_ERROR"),
116
105
  code: zod.z.enum([
117
- "COULD_NOT_FIND_EXECUTOR"
118
- ])
106
+ "COULD_NOT_FIND_EXECUTOR",
107
+ "CONFIGURED_INCORRECTLY",
108
+ "TASK_ALREADY_RUNNING",
109
+ "TASK_EXECUTION_FAILED",
110
+ "TASK_EXECUTION_ABORTED",
111
+ "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
112
+ "TASK_RUN_CANCELLED",
113
+ "TASK_OUTPUT_ERROR",
114
+ "HANDLE_ERROR_ERROR"
115
+ ]),
116
+ message: zod.z.string().optional()
119
117
  });
120
118
  var TaskRunError = zod.z.discriminatedUnion("type", [
121
119
  TaskRunBuiltInError,
@@ -129,6 +127,7 @@ var TaskRun = zod.z.object({
129
127
  payloadType: zod.z.string(),
130
128
  context: zod.z.any(),
131
129
  tags: zod.z.array(zod.z.string()),
130
+ isTest: zod.z.boolean().default(false),
132
131
  createdAt: zod.z.coerce.date()
133
132
  });
134
133
  var TaskRunExecutionTask = zod.z.object({
@@ -165,13 +164,22 @@ var TaskRunExecutionProject = zod.z.object({
165
164
  slug: zod.z.string(),
166
165
  name: zod.z.string()
167
166
  });
167
+ var TaskRunExecutionQueue = zod.z.object({
168
+ id: zod.z.string(),
169
+ name: zod.z.string()
170
+ });
171
+ var TaskRunExecutionBatch = zod.z.object({
172
+ id: zod.z.string()
173
+ });
168
174
  var TaskRunExecution = zod.z.object({
169
175
  task: TaskRunExecutionTask,
170
176
  attempt: TaskRunExecutionAttempt,
171
177
  run: TaskRun,
178
+ queue: TaskRunExecutionQueue,
172
179
  environment: TaskRunExecutionEnvironment,
173
180
  organization: TaskRunExecutionOrganization,
174
- project: TaskRunExecutionProject
181
+ project: TaskRunExecutionProject,
182
+ batch: TaskRunExecutionBatch.optional()
175
183
  });
176
184
  var TaskRunContext = zod.z.object({
177
185
  task: TaskRunExecutionTask,
@@ -183,33 +191,105 @@ var TaskRunContext = zod.z.object({
183
191
  payload: true,
184
192
  payloadType: true
185
193
  }),
194
+ queue: TaskRunExecutionQueue,
186
195
  environment: TaskRunExecutionEnvironment,
187
196
  organization: TaskRunExecutionOrganization,
188
- project: TaskRunExecutionProject
197
+ project: TaskRunExecutionProject,
198
+ batch: TaskRunExecutionBatch.optional()
199
+ });
200
+ var TaskRunExecutionRetry = zod.z.object({
201
+ timestamp: zod.z.number(),
202
+ delay: zod.z.number(),
203
+ error: zod.z.unknown().optional()
189
204
  });
190
205
  var TaskRunFailedExecutionResult = zod.z.object({
191
206
  ok: zod.z.literal(false),
192
207
  id: zod.z.string(),
193
- error: TaskRunError
208
+ error: TaskRunError,
209
+ retry: TaskRunExecutionRetry.optional(),
210
+ skippedRetrying: zod.z.boolean().optional()
194
211
  });
195
212
  var TaskRunSuccessfulExecutionResult = zod.z.object({
196
213
  ok: zod.z.literal(true),
197
214
  id: zod.z.string(),
198
- output: zod.z.string(),
215
+ output: zod.z.string().optional(),
199
216
  outputType: zod.z.string()
200
217
  });
201
218
  var TaskRunExecutionResult = zod.z.discriminatedUnion("ok", [
202
219
  TaskRunSuccessfulExecutionResult,
203
220
  TaskRunFailedExecutionResult
204
221
  ]);
222
+ var BatchTaskRunExecutionResult = zod.z.object({
223
+ id: zod.z.string(),
224
+ items: TaskRunExecutionResult.array()
225
+ });
226
+
227
+ // src/v3/schemas/messages.ts
228
+ var EnvironmentType = zod.z.enum([
229
+ "PRODUCTION",
230
+ "STAGING",
231
+ "DEVELOPMENT",
232
+ "PREVIEW"
233
+ ]);
234
+ var MachineCpu = zod.z.union([
235
+ zod.z.literal(0.25),
236
+ zod.z.literal(0.5),
237
+ zod.z.literal(1),
238
+ zod.z.literal(2),
239
+ zod.z.literal(4)
240
+ ]).default(0.5);
241
+ var MachineMemory = zod.z.union([
242
+ zod.z.literal(0.25),
243
+ zod.z.literal(0.5),
244
+ zod.z.literal(1),
245
+ zod.z.literal(2),
246
+ zod.z.literal(4),
247
+ zod.z.literal(8)
248
+ ]).default(1);
249
+ var Machine = zod.z.object({
250
+ version: zod.z.literal("v1").default("v1"),
251
+ cpu: MachineCpu,
252
+ memory: MachineMemory
253
+ });
205
254
  var TaskRunExecutionPayload = zod.z.object({
206
255
  execution: TaskRunExecution,
207
- traceContext: zod.z.record(zod.z.unknown())
256
+ traceContext: zod.z.record(zod.z.unknown()),
257
+ environment: zod.z.record(zod.z.string()).optional()
258
+ });
259
+ var ProdTaskRunExecution = TaskRunExecution.extend({
260
+ worker: zod.z.object({
261
+ id: zod.z.string(),
262
+ contentHash: zod.z.string(),
263
+ version: zod.z.string()
264
+ })
265
+ });
266
+ var ProdTaskRunExecutionPayload = zod.z.object({
267
+ execution: ProdTaskRunExecution,
268
+ traceContext: zod.z.record(zod.z.unknown()),
269
+ environment: zod.z.record(zod.z.string()).optional()
208
270
  });
209
271
  var BackgroundWorkerServerMessages = zod.z.discriminatedUnion("type", [
210
272
  zod.z.object({
211
273
  type: zod.z.literal("EXECUTE_RUNS"),
212
274
  payloads: zod.z.array(TaskRunExecutionPayload)
275
+ }),
276
+ zod.z.object({
277
+ type: zod.z.literal("CANCEL_ATTEMPT"),
278
+ taskAttemptId: zod.z.string(),
279
+ taskRunId: zod.z.string()
280
+ }),
281
+ zod.z.object({
282
+ type: zod.z.literal("SCHEDULE_ATTEMPT"),
283
+ image: zod.z.string(),
284
+ version: zod.z.string(),
285
+ machine: Machine,
286
+ // identifiers
287
+ id: zod.z.string(),
288
+ envId: zod.z.string(),
289
+ envType: EnvironmentType,
290
+ orgId: zod.z.string(),
291
+ projectId: zod.z.string(),
292
+ runId: zod.z.string()
213
293
  })
214
294
  ]);
215
295
  var serverWebsocketMessages = {
@@ -227,15 +307,26 @@ var BackgroundWorkerClientMessages = zod.z.discriminatedUnion("type", [
227
307
  zod.z.object({
228
308
  version: zod.z.literal("v1").default("v1"),
229
309
  type: zod.z.literal("TASK_RUN_COMPLETED"),
230
- completion: TaskRunExecutionResult
310
+ completion: TaskRunExecutionResult,
311
+ execution: TaskRunExecution
312
+ }),
313
+ zod.z.object({
314
+ version: zod.z.literal("v1").default("v1"),
315
+ type: zod.z.literal("TASK_HEARTBEAT"),
316
+ id: zod.z.string()
231
317
  })
232
318
  ]);
319
+ var BackgroundWorkerProperties = zod.z.object({
320
+ id: zod.z.string(),
321
+ version: zod.z.string(),
322
+ contentHash: zod.z.string()
323
+ });
233
324
  var clientWebsocketMessages = {
234
325
  READY_FOR_TASKS: zod.z.object({
235
326
  version: zod.z.literal("v1").default("v1"),
236
327
  backgroundWorkerId: zod.z.string()
237
328
  }),
238
- WORKER_DEPRECATED: zod.z.object({
329
+ BACKGROUND_WORKER_DEPRECATED: zod.z.object({
239
330
  version: zod.z.literal("v1").default("v1"),
240
331
  backgroundWorkerId: zod.z.string()
241
332
  }),
@@ -250,40 +341,1112 @@ var workerToChildMessages = {
250
341
  version: zod.z.literal("v1").default("v1"),
251
342
  execution: TaskRunExecution,
252
343
  traceContext: zod.z.record(zod.z.unknown()),
253
- metadata: BackgroundWorkerRecord
344
+ metadata: BackgroundWorkerProperties
254
345
  }),
255
- TASK_RUN_COMPLETED: zod.z.object({
346
+ TASK_RUN_COMPLETED_NOTIFICATION: zod.z.object({
256
347
  version: zod.z.literal("v1").default("v1"),
257
348
  completion: TaskRunExecutionResult,
258
349
  execution: TaskRunExecution
259
350
  }),
260
351
  CLEANUP: zod.z.object({
261
352
  version: zod.z.literal("v1").default("v1"),
262
- flush: zod.z.boolean().default(false)
353
+ flush: zod.z.boolean().default(false),
354
+ kill: zod.z.boolean().default(true)
263
355
  })
264
356
  };
357
+ var FixedWindowRateLimit = zod.z.object({
358
+ type: zod.z.literal("fixed-window"),
359
+ limit: zod.z.number(),
360
+ window: zod.z.union([
361
+ zod.z.object({
362
+ seconds: zod.z.number()
363
+ }),
364
+ zod.z.object({
365
+ minutes: zod.z.number()
366
+ }),
367
+ zod.z.object({
368
+ hours: zod.z.number()
369
+ })
370
+ ])
371
+ });
372
+ var SlidingWindowRateLimit = zod.z.object({
373
+ type: zod.z.literal("sliding-window"),
374
+ limit: zod.z.number(),
375
+ window: zod.z.union([
376
+ zod.z.object({
377
+ seconds: zod.z.number()
378
+ }),
379
+ zod.z.object({
380
+ minutes: zod.z.number()
381
+ }),
382
+ zod.z.object({
383
+ hours: zod.z.number()
384
+ })
385
+ ])
386
+ });
387
+ var RateLimitOptions = zod.z.discriminatedUnion("type", [
388
+ FixedWindowRateLimit,
389
+ SlidingWindowRateLimit
390
+ ]);
391
+ var RetryOptions = zod.z.object({
392
+ /** The number of attempts before giving up */
393
+ maxAttempts: zod.z.number().int().optional(),
394
+ /** The exponential factor to use when calculating the next retry time.
395
+ *
396
+ * Each subsequent retry will be calculated as `previousTimeout * factor`
397
+ */
398
+ factor: zod.z.number().optional(),
399
+ /** The minimum time to wait before retrying */
400
+ minTimeoutInMs: zod.z.number().int().optional(),
401
+ /** The maximum time to wait before retrying */
402
+ maxTimeoutInMs: zod.z.number().int().optional(),
403
+ /** Randomize the timeout between retries.
404
+ *
405
+ * This can be useful to prevent the thundering herd problem where all retries happen at the same time.
406
+ */
407
+ randomize: zod.z.boolean().optional()
408
+ });
409
+ var QueueOptions = zod.z.object({
410
+ /** You can define a shared queue and then pass the name in to your task.
411
+ *
412
+ * @example
413
+ *
414
+ * ```ts
415
+ * const myQueue = queue({
416
+ name: "my-queue",
417
+ concurrencyLimit: 1,
418
+ });
419
+
420
+ export const task1 = task({
421
+ id: "task-1",
422
+ queue: {
423
+ name: "my-queue",
424
+ },
425
+ run: async (payload: { message: string }) => {
426
+ // ...
427
+ },
428
+ });
429
+
430
+ export const task2 = task({
431
+ id: "task-2",
432
+ queue: {
433
+ name: "my-queue",
434
+ },
435
+ run: async (payload: { message: string }) => {
436
+ // ...
437
+ },
438
+ });
439
+ * ```
440
+ */
441
+ name: zod.z.string().optional(),
442
+ /** An optional property that specifies the maximum number of concurrent run executions.
443
+ *
444
+ * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
445
+ concurrencyLimit: zod.z.number().int().min(0).max(1e3).optional(),
446
+ /** @deprecated This feature is coming soon */
447
+ rateLimit: RateLimitOptions.optional()
448
+ });
265
449
  var TaskMetadata = zod.z.object({
266
450
  id: zod.z.string(),
267
451
  exportName: zod.z.string(),
268
- packageVersion: zod.z.string()
452
+ packageVersion: zod.z.string(),
453
+ queue: QueueOptions.optional(),
454
+ retry: RetryOptions.optional(),
455
+ machine: Machine.partial().optional()
269
456
  });
270
457
  var TaskMetadataWithFilePath = TaskMetadata.extend({
271
458
  filePath: zod.z.string()
272
459
  });
460
+ var UncaughtExceptionMessage = zod.z.object({
461
+ version: zod.z.literal("v1").default("v1"),
462
+ error: zod.z.object({
463
+ name: zod.z.string(),
464
+ message: zod.z.string(),
465
+ stack: zod.z.string().optional()
466
+ }),
467
+ origin: zod.z.enum([
468
+ "uncaughtException",
469
+ "unhandledRejection"
470
+ ])
471
+ });
472
+ var TaskMetadataFailedToParseData = zod.z.object({
473
+ version: zod.z.literal("v1").default("v1"),
474
+ tasks: zod.z.unknown(),
475
+ zodIssues: zod.z.custom((v) => {
476
+ return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
477
+ })
478
+ });
273
479
  var childToWorkerMessages = {
274
480
  TASK_RUN_COMPLETED: zod.z.object({
275
481
  version: zod.z.literal("v1").default("v1"),
482
+ execution: TaskRunExecution,
276
483
  result: TaskRunExecutionResult
277
484
  }),
278
485
  TASKS_READY: zod.z.object({
279
486
  version: zod.z.literal("v1").default("v1"),
280
487
  tasks: TaskMetadataWithFilePath.array()
281
488
  }),
282
- READY_TO_DISPOSE: zod.z.undefined()
489
+ TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
490
+ TASK_HEARTBEAT: zod.z.object({
491
+ version: zod.z.literal("v1").default("v1"),
492
+ id: zod.z.string()
493
+ }),
494
+ READY_TO_DISPOSE: zod.z.undefined(),
495
+ WAIT_FOR_DURATION: zod.z.object({
496
+ version: zod.z.literal("v1").default("v1"),
497
+ ms: zod.z.number()
498
+ }),
499
+ WAIT_FOR_TASK: zod.z.object({
500
+ version: zod.z.literal("v1").default("v1"),
501
+ id: zod.z.string()
502
+ }),
503
+ WAIT_FOR_BATCH: zod.z.object({
504
+ version: zod.z.literal("v1").default("v1"),
505
+ id: zod.z.string(),
506
+ runs: zod.z.string().array()
507
+ }),
508
+ UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
509
+ };
510
+ var ProdChildToWorkerMessages = {
511
+ TASK_RUN_COMPLETED: {
512
+ message: zod.z.object({
513
+ version: zod.z.literal("v1").default("v1"),
514
+ execution: TaskRunExecution,
515
+ result: TaskRunExecutionResult
516
+ })
517
+ },
518
+ TASKS_READY: {
519
+ message: zod.z.object({
520
+ version: zod.z.literal("v1").default("v1"),
521
+ tasks: TaskMetadataWithFilePath.array()
522
+ })
523
+ },
524
+ TASKS_FAILED_TO_PARSE: {
525
+ message: TaskMetadataFailedToParseData
526
+ },
527
+ TASK_HEARTBEAT: {
528
+ message: zod.z.object({
529
+ version: zod.z.literal("v1").default("v1"),
530
+ id: zod.z.string()
531
+ })
532
+ },
533
+ READY_TO_DISPOSE: {
534
+ message: zod.z.undefined()
535
+ },
536
+ READY_FOR_CHECKPOINT: {
537
+ message: zod.z.object({
538
+ version: zod.z.literal("v1").default("v1")
539
+ })
540
+ },
541
+ CANCEL_CHECKPOINT: {
542
+ message: zod.z.object({
543
+ version: zod.z.literal("v1").default("v1")
544
+ })
545
+ },
546
+ WAIT_FOR_DURATION: {
547
+ message: zod.z.object({
548
+ version: zod.z.literal("v1").default("v1"),
549
+ ms: zod.z.number(),
550
+ now: zod.z.number()
551
+ }),
552
+ callback: zod.z.object({
553
+ willCheckpointAndRestore: zod.z.boolean()
554
+ })
555
+ },
556
+ WAIT_FOR_TASK: {
557
+ message: zod.z.object({
558
+ version: zod.z.literal("v1").default("v1"),
559
+ friendlyId: zod.z.string()
560
+ })
561
+ },
562
+ WAIT_FOR_BATCH: {
563
+ message: zod.z.object({
564
+ version: zod.z.literal("v1").default("v1"),
565
+ batchFriendlyId: zod.z.string(),
566
+ runFriendlyIds: zod.z.string().array()
567
+ })
568
+ },
569
+ UNCAUGHT_EXCEPTION: {
570
+ message: UncaughtExceptionMessage
571
+ }
572
+ };
573
+ var ProdWorkerToChildMessages = {
574
+ EXECUTE_TASK_RUN: {
575
+ message: zod.z.object({
576
+ version: zod.z.literal("v1").default("v1"),
577
+ execution: TaskRunExecution,
578
+ traceContext: zod.z.record(zod.z.unknown()),
579
+ metadata: BackgroundWorkerProperties
580
+ })
581
+ },
582
+ TASK_RUN_COMPLETED_NOTIFICATION: {
583
+ message: zod.z.object({
584
+ version: zod.z.literal("v1").default("v1"),
585
+ completion: TaskRunExecutionResult,
586
+ execution: TaskRunExecution
587
+ })
588
+ },
589
+ CLEANUP: {
590
+ message: zod.z.object({
591
+ version: zod.z.literal("v1").default("v1"),
592
+ flush: zod.z.boolean().default(false),
593
+ kill: zod.z.boolean().default(true)
594
+ }),
595
+ callback: zod.z.void()
596
+ },
597
+ WAIT_COMPLETED_NOTIFICATION: {
598
+ message: zod.z.object({
599
+ version: zod.z.literal("v1").default("v1")
600
+ })
601
+ }
602
+ };
603
+
604
+ // src/v3/schemas/resources.ts
605
+ var TaskResource = zod.z.object({
606
+ id: zod.z.string(),
607
+ filePath: zod.z.string(),
608
+ exportName: zod.z.string(),
609
+ queue: QueueOptions.optional(),
610
+ retry: RetryOptions.optional(),
611
+ machine: Machine.partial().optional()
612
+ });
613
+ var BackgroundWorkerMetadata = zod.z.object({
614
+ packageVersion: zod.z.string(),
615
+ contentHash: zod.z.string(),
616
+ cliPackageVersion: zod.z.string().optional(),
617
+ tasks: zod.z.array(TaskResource)
618
+ });
619
+ var ImageDetailsMetadata = zod.z.object({
620
+ contentHash: zod.z.string(),
621
+ imageTag: zod.z.string()
622
+ });
623
+
624
+ // src/v3/schemas/api.ts
625
+ var WhoAmIResponseSchema = zod.z.object({
626
+ userId: zod.z.string(),
627
+ email: zod.z.string().email(),
628
+ dashboardUrl: zod.z.string()
629
+ });
630
+ var GetProjectResponseBody = zod.z.object({
631
+ id: zod.z.string(),
632
+ externalRef: zod.z.string(),
633
+ name: zod.z.string(),
634
+ slug: zod.z.string(),
635
+ createdAt: zod.z.coerce.date(),
636
+ organization: zod.z.object({
637
+ id: zod.z.string(),
638
+ title: zod.z.string(),
639
+ slug: zod.z.string(),
640
+ createdAt: zod.z.coerce.date()
641
+ })
642
+ });
643
+ var GetProjectsResponseBody = zod.z.array(GetProjectResponseBody);
644
+ var GetProjectEnvResponse = zod.z.object({
645
+ apiKey: zod.z.string(),
646
+ name: zod.z.string(),
647
+ apiUrl: zod.z.string()
648
+ });
649
+ var CreateBackgroundWorkerRequestBody = zod.z.object({
650
+ localOnly: zod.z.boolean(),
651
+ metadata: BackgroundWorkerMetadata
652
+ });
653
+ var CreateBackgroundWorkerResponse = zod.z.object({
654
+ id: zod.z.string(),
655
+ version: zod.z.string(),
656
+ contentHash: zod.z.string()
657
+ });
658
+ var TriggerTaskRequestBody = zod.z.object({
659
+ payload: zod.z.any(),
660
+ context: zod.z.any(),
661
+ options: zod.z.object({
662
+ dependentAttempt: zod.z.string().optional(),
663
+ dependentBatch: zod.z.string().optional(),
664
+ lockToVersion: zod.z.string().optional(),
665
+ queue: QueueOptions.optional(),
666
+ concurrencyKey: zod.z.string().optional(),
667
+ test: zod.z.boolean().optional()
668
+ }).optional()
669
+ });
670
+ var TriggerTaskResponse = zod.z.object({
671
+ id: zod.z.string()
672
+ });
673
+ var BatchTriggerTaskRequestBody = zod.z.object({
674
+ items: TriggerTaskRequestBody.array(),
675
+ dependentAttempt: zod.z.string().optional()
676
+ });
677
+ var BatchTriggerTaskResponse = zod.z.object({
678
+ batchId: zod.z.string(),
679
+ runs: zod.z.string().array()
680
+ });
681
+ var GetBatchResponseBody = zod.z.object({
682
+ id: zod.z.string(),
683
+ items: zod.z.array(zod.z.object({
684
+ id: zod.z.string(),
685
+ taskRunId: zod.z.string(),
686
+ status: zod.z.enum([
687
+ "PENDING",
688
+ "CANCELED",
689
+ "COMPLETED",
690
+ "FAILED"
691
+ ])
692
+ }))
693
+ });
694
+ var GetEnvironmentVariablesResponseBody = zod.z.object({
695
+ variables: zod.z.record(zod.z.string())
696
+ });
697
+ var StartDeploymentIndexingRequestBody = zod.z.object({
698
+ imageReference: zod.z.string()
699
+ });
700
+ var StartDeploymentIndexingResponseBody = zod.z.object({
701
+ id: zod.z.string(),
702
+ contentHash: zod.z.string()
703
+ });
704
+ var ExternalBuildData = zod.z.object({
705
+ buildId: zod.z.string(),
706
+ buildToken: zod.z.string(),
707
+ projectId: zod.z.string()
708
+ });
709
+ var InitializeDeploymentResponseBody = zod.z.object({
710
+ id: zod.z.string(),
711
+ contentHash: zod.z.string(),
712
+ shortCode: zod.z.string(),
713
+ version: zod.z.string(),
714
+ imageTag: zod.z.string(),
715
+ externalBuildData: ExternalBuildData.optional().nullable(),
716
+ registryHost: zod.z.string().optional()
717
+ });
718
+ var InitializeDeploymentRequestBody = zod.z.object({
719
+ contentHash: zod.z.string(),
720
+ userId: zod.z.string().optional()
721
+ });
722
+ var DeploymentErrorData = zod.z.object({
723
+ name: zod.z.string(),
724
+ message: zod.z.string(),
725
+ stack: zod.z.string().optional()
726
+ });
727
+ var GetDeploymentResponseBody = zod.z.object({
728
+ id: zod.z.string(),
729
+ status: zod.z.enum([
730
+ "PENDING",
731
+ "BUILDING",
732
+ "DEPLOYING",
733
+ "DEPLOYED",
734
+ "FAILED",
735
+ "CANCELED",
736
+ "TIMED_OUT"
737
+ ]),
738
+ contentHash: zod.z.string(),
739
+ shortCode: zod.z.string(),
740
+ version: zod.z.string(),
741
+ imageReference: zod.z.string().optional(),
742
+ errorData: DeploymentErrorData.optional().nullable(),
743
+ worker: zod.z.object({
744
+ id: zod.z.string(),
745
+ version: zod.z.string(),
746
+ tasks: zod.z.array(zod.z.object({
747
+ id: zod.z.string(),
748
+ slug: zod.z.string(),
749
+ filePath: zod.z.string(),
750
+ exportName: zod.z.string()
751
+ }))
752
+ }).optional()
753
+ });
754
+ var CreateUploadPayloadUrlResponseBody = zod.z.object({
755
+ presignedUrl: zod.z.string()
756
+ });
757
+ var PostStartCauses = zod.z.enum([
758
+ "index",
759
+ "create",
760
+ "restore"
761
+ ]);
762
+ var PreStopCauses = zod.z.enum([
763
+ "terminate"
764
+ ]);
765
+ var RegexSchema = zod.z.custom((val) => {
766
+ try {
767
+ return typeof val.test === "function";
768
+ } catch {
769
+ return false;
770
+ }
771
+ });
772
+ var Config = zod.z.object({
773
+ project: zod.z.string(),
774
+ triggerDirectories: zod.z.string().array().optional(),
775
+ triggerUrl: zod.z.string().optional(),
776
+ projectDir: zod.z.string().optional(),
777
+ tsconfigPath: zod.z.string().optional(),
778
+ retries: zod.z.object({
779
+ enabledInDev: zod.z.boolean().default(true),
780
+ default: RetryOptions.optional()
781
+ }).optional(),
782
+ additionalPackages: zod.z.string().array().optional(),
783
+ additionalFiles: zod.z.string().array().optional(),
784
+ dependenciesToBundle: zod.z.array(zod.z.union([
785
+ zod.z.string(),
786
+ RegexSchema
787
+ ])).optional(),
788
+ logLevel: zod.z.string().optional()
789
+ });
790
+ var WaitReason = zod.z.enum([
791
+ "WAIT_FOR_DURATION",
792
+ "WAIT_FOR_TASK",
793
+ "WAIT_FOR_BATCH"
794
+ ]);
795
+ var ProviderToPlatformMessages = {
796
+ LOG: {
797
+ message: zod.z.object({
798
+ version: zod.z.literal("v1").default("v1"),
799
+ data: zod.z.string()
800
+ })
801
+ },
802
+ LOG_WITH_ACK: {
803
+ message: zod.z.object({
804
+ version: zod.z.literal("v1").default("v1"),
805
+ data: zod.z.string()
806
+ }),
807
+ callback: zod.z.object({
808
+ status: zod.z.literal("ok")
809
+ })
810
+ },
811
+ WORKER_CRASHED: {
812
+ message: zod.z.object({
813
+ version: zod.z.literal("v1").default("v1"),
814
+ runId: zod.z.string(),
815
+ reason: zod.z.string().optional(),
816
+ exitCode: zod.z.number().optional(),
817
+ message: zod.z.string().optional(),
818
+ logs: zod.z.string().optional()
819
+ })
820
+ },
821
+ INDEXING_FAILED: {
822
+ message: zod.z.object({
823
+ version: zod.z.literal("v1").default("v1"),
824
+ deploymentId: zod.z.string(),
825
+ error: zod.z.object({
826
+ name: zod.z.string(),
827
+ message: zod.z.string(),
828
+ stack: zod.z.string().optional()
829
+ })
830
+ })
831
+ }
832
+ };
833
+ var PlatformToProviderMessages = {
834
+ HEALTH: {
835
+ message: zod.z.object({
836
+ version: zod.z.literal("v1").default("v1")
837
+ }),
838
+ callback: zod.z.object({
839
+ status: zod.z.literal("ok")
840
+ })
841
+ },
842
+ INDEX: {
843
+ message: zod.z.object({
844
+ version: zod.z.literal("v1").default("v1"),
845
+ imageTag: zod.z.string(),
846
+ shortCode: zod.z.string(),
847
+ apiKey: zod.z.string(),
848
+ apiUrl: zod.z.string(),
849
+ // identifiers
850
+ envId: zod.z.string(),
851
+ envType: EnvironmentType,
852
+ orgId: zod.z.string(),
853
+ projectId: zod.z.string(),
854
+ deploymentId: zod.z.string()
855
+ }),
856
+ callback: zod.z.discriminatedUnion("success", [
857
+ zod.z.object({
858
+ success: zod.z.literal(false),
859
+ error: zod.z.object({
860
+ name: zod.z.string(),
861
+ message: zod.z.string(),
862
+ stack: zod.z.string().optional()
863
+ })
864
+ }),
865
+ zod.z.object({
866
+ success: zod.z.literal(true)
867
+ })
868
+ ])
869
+ },
870
+ // TODO: this should be a shared queue message instead
871
+ RESTORE: {
872
+ message: zod.z.object({
873
+ version: zod.z.literal("v1").default("v1"),
874
+ type: zod.z.enum([
875
+ "DOCKER",
876
+ "KUBERNETES"
877
+ ]),
878
+ location: zod.z.string(),
879
+ reason: zod.z.string().optional(),
880
+ imageRef: zod.z.string(),
881
+ machine: Machine,
882
+ // identifiers
883
+ checkpointId: zod.z.string(),
884
+ envId: zod.z.string(),
885
+ envType: EnvironmentType,
886
+ orgId: zod.z.string(),
887
+ projectId: zod.z.string(),
888
+ runId: zod.z.string()
889
+ })
890
+ },
891
+ DELETE: {
892
+ message: zod.z.object({
893
+ version: zod.z.literal("v1").default("v1"),
894
+ name: zod.z.string()
895
+ }),
896
+ callback: zod.z.object({
897
+ message: zod.z.string()
898
+ })
899
+ },
900
+ GET: {
901
+ message: zod.z.object({
902
+ version: zod.z.literal("v1").default("v1"),
903
+ name: zod.z.string()
904
+ })
905
+ }
906
+ };
907
+ var CoordinatorToPlatformMessages = {
908
+ LOG: {
909
+ message: zod.z.object({
910
+ version: zod.z.literal("v1").default("v1"),
911
+ metadata: zod.z.any(),
912
+ text: zod.z.string()
913
+ })
914
+ },
915
+ CREATE_WORKER: {
916
+ message: zod.z.object({
917
+ version: zod.z.literal("v1").default("v1"),
918
+ projectRef: zod.z.string(),
919
+ envId: zod.z.string(),
920
+ deploymentId: zod.z.string(),
921
+ metadata: zod.z.object({
922
+ cliPackageVersion: zod.z.string().optional(),
923
+ contentHash: zod.z.string(),
924
+ packageVersion: zod.z.string(),
925
+ tasks: TaskResource.array()
926
+ })
927
+ }),
928
+ callback: zod.z.discriminatedUnion("success", [
929
+ zod.z.object({
930
+ success: zod.z.literal(false)
931
+ }),
932
+ zod.z.object({
933
+ success: zod.z.literal(true)
934
+ })
935
+ ])
936
+ },
937
+ READY_FOR_EXECUTION: {
938
+ message: zod.z.object({
939
+ version: zod.z.literal("v1").default("v1"),
940
+ runId: zod.z.string(),
941
+ totalCompletions: zod.z.number()
942
+ }),
943
+ callback: zod.z.discriminatedUnion("success", [
944
+ zod.z.object({
945
+ success: zod.z.literal(false)
946
+ }),
947
+ zod.z.object({
948
+ success: zod.z.literal(true),
949
+ payload: ProdTaskRunExecutionPayload
950
+ })
951
+ ])
952
+ },
953
+ READY_FOR_RESUME: {
954
+ message: zod.z.object({
955
+ version: zod.z.literal("v1").default("v1"),
956
+ attemptFriendlyId: zod.z.string(),
957
+ type: WaitReason
958
+ })
959
+ },
960
+ TASK_RUN_COMPLETED: {
961
+ message: zod.z.object({
962
+ version: zod.z.literal("v1").default("v1"),
963
+ execution: ProdTaskRunExecution,
964
+ completion: TaskRunExecutionResult,
965
+ checkpoint: zod.z.object({
966
+ docker: zod.z.boolean(),
967
+ location: zod.z.string()
968
+ }).optional()
969
+ })
970
+ },
971
+ TASK_HEARTBEAT: {
972
+ message: zod.z.object({
973
+ version: zod.z.literal("v1").default("v1"),
974
+ attemptFriendlyId: zod.z.string()
975
+ })
976
+ },
977
+ CHECKPOINT_CREATED: {
978
+ message: zod.z.object({
979
+ version: zod.z.literal("v1").default("v1"),
980
+ attemptFriendlyId: zod.z.string(),
981
+ docker: zod.z.boolean(),
982
+ location: zod.z.string(),
983
+ reason: zod.z.discriminatedUnion("type", [
984
+ zod.z.object({
985
+ type: zod.z.literal("WAIT_FOR_DURATION"),
986
+ ms: zod.z.number(),
987
+ now: zod.z.number()
988
+ }),
989
+ zod.z.object({
990
+ type: zod.z.literal("WAIT_FOR_BATCH"),
991
+ batchFriendlyId: zod.z.string(),
992
+ runFriendlyIds: zod.z.string().array()
993
+ }),
994
+ zod.z.object({
995
+ type: zod.z.literal("WAIT_FOR_TASK"),
996
+ friendlyId: zod.z.string()
997
+ }),
998
+ zod.z.object({
999
+ type: zod.z.literal("RETRYING_AFTER_FAILURE"),
1000
+ attemptNumber: zod.z.number()
1001
+ })
1002
+ ])
1003
+ })
1004
+ },
1005
+ INDEXING_FAILED: {
1006
+ message: zod.z.object({
1007
+ version: zod.z.literal("v1").default("v1"),
1008
+ deploymentId: zod.z.string(),
1009
+ error: zod.z.object({
1010
+ name: zod.z.string(),
1011
+ message: zod.z.string(),
1012
+ stack: zod.z.string().optional()
1013
+ })
1014
+ })
1015
+ }
1016
+ };
1017
+ var PlatformToCoordinatorMessages = {
1018
+ RESUME_AFTER_DEPENDENCY: {
1019
+ message: zod.z.object({
1020
+ version: zod.z.literal("v1").default("v1"),
1021
+ runId: zod.z.string(),
1022
+ attemptId: zod.z.string(),
1023
+ attemptFriendlyId: zod.z.string(),
1024
+ completions: TaskRunExecutionResult.array(),
1025
+ executions: TaskRunExecution.array()
1026
+ })
1027
+ },
1028
+ RESUME_AFTER_DURATION: {
1029
+ message: zod.z.object({
1030
+ version: zod.z.literal("v1").default("v1"),
1031
+ attemptId: zod.z.string(),
1032
+ attemptFriendlyId: zod.z.string()
1033
+ })
1034
+ },
1035
+ REQUEST_ATTEMPT_CANCELLATION: {
1036
+ message: zod.z.object({
1037
+ version: zod.z.literal("v1").default("v1"),
1038
+ attemptId: zod.z.string(),
1039
+ attemptFriendlyId: zod.z.string()
1040
+ })
1041
+ },
1042
+ READY_FOR_RETRY: {
1043
+ message: zod.z.object({
1044
+ version: zod.z.literal("v1").default("v1"),
1045
+ runId: zod.z.string()
1046
+ })
1047
+ }
1048
+ };
1049
+ var ClientToSharedQueueMessages = {
1050
+ READY_FOR_TASKS: {
1051
+ message: zod.z.object({
1052
+ version: zod.z.literal("v1").default("v1"),
1053
+ backgroundWorkerId: zod.z.string()
1054
+ })
1055
+ },
1056
+ BACKGROUND_WORKER_DEPRECATED: {
1057
+ message: zod.z.object({
1058
+ version: zod.z.literal("v1").default("v1"),
1059
+ backgroundWorkerId: zod.z.string()
1060
+ })
1061
+ },
1062
+ BACKGROUND_WORKER_MESSAGE: {
1063
+ message: zod.z.object({
1064
+ version: zod.z.literal("v1").default("v1"),
1065
+ backgroundWorkerId: zod.z.string(),
1066
+ data: BackgroundWorkerClientMessages
1067
+ })
1068
+ }
1069
+ };
1070
+ var SharedQueueToClientMessages = {
1071
+ SERVER_READY: {
1072
+ message: zod.z.object({
1073
+ version: zod.z.literal("v1").default("v1"),
1074
+ id: zod.z.string()
1075
+ })
1076
+ },
1077
+ BACKGROUND_WORKER_MESSAGE: {
1078
+ message: zod.z.object({
1079
+ version: zod.z.literal("v1").default("v1"),
1080
+ backgroundWorkerId: zod.z.string(),
1081
+ data: BackgroundWorkerServerMessages
1082
+ })
1083
+ }
1084
+ };
1085
+ var ProdWorkerToCoordinatorMessages = {
1086
+ LOG: {
1087
+ message: zod.z.object({
1088
+ version: zod.z.literal("v1").default("v1"),
1089
+ text: zod.z.string()
1090
+ }),
1091
+ callback: zod.z.void()
1092
+ },
1093
+ INDEX_TASKS: {
1094
+ message: zod.z.object({
1095
+ version: zod.z.literal("v1").default("v1"),
1096
+ deploymentId: zod.z.string(),
1097
+ tasks: TaskResource.array(),
1098
+ packageVersion: zod.z.string()
1099
+ }),
1100
+ callback: zod.z.discriminatedUnion("success", [
1101
+ zod.z.object({
1102
+ success: zod.z.literal(false)
1103
+ }),
1104
+ zod.z.object({
1105
+ success: zod.z.literal(true)
1106
+ })
1107
+ ])
1108
+ },
1109
+ READY_FOR_EXECUTION: {
1110
+ message: zod.z.object({
1111
+ version: zod.z.literal("v1").default("v1"),
1112
+ runId: zod.z.string(),
1113
+ totalCompletions: zod.z.number()
1114
+ })
1115
+ },
1116
+ READY_FOR_RESUME: {
1117
+ message: zod.z.object({
1118
+ version: zod.z.literal("v1").default("v1"),
1119
+ attemptFriendlyId: zod.z.string(),
1120
+ type: WaitReason
1121
+ })
1122
+ },
1123
+ READY_FOR_CHECKPOINT: {
1124
+ message: zod.z.object({
1125
+ version: zod.z.literal("v1").default("v1")
1126
+ })
1127
+ },
1128
+ CANCEL_CHECKPOINT: {
1129
+ message: zod.z.object({
1130
+ version: zod.z.literal("v1").default("v1")
1131
+ })
1132
+ },
1133
+ TASK_HEARTBEAT: {
1134
+ message: zod.z.object({
1135
+ version: zod.z.literal("v1").default("v1"),
1136
+ attemptFriendlyId: zod.z.string()
1137
+ })
1138
+ },
1139
+ TASK_RUN_COMPLETED: {
1140
+ message: zod.z.object({
1141
+ version: zod.z.literal("v1").default("v1"),
1142
+ execution: ProdTaskRunExecution,
1143
+ completion: TaskRunExecutionResult
1144
+ }),
1145
+ callback: zod.z.object({
1146
+ willCheckpointAndRestore: zod.z.boolean(),
1147
+ shouldExit: zod.z.boolean()
1148
+ })
1149
+ },
1150
+ WAIT_FOR_DURATION: {
1151
+ message: zod.z.object({
1152
+ version: zod.z.literal("v1").default("v1"),
1153
+ ms: zod.z.number(),
1154
+ now: zod.z.number(),
1155
+ attemptFriendlyId: zod.z.string()
1156
+ }),
1157
+ callback: zod.z.object({
1158
+ willCheckpointAndRestore: zod.z.boolean()
1159
+ })
1160
+ },
1161
+ WAIT_FOR_TASK: {
1162
+ message: zod.z.object({
1163
+ version: zod.z.literal("v1").default("v1"),
1164
+ friendlyId: zod.z.string(),
1165
+ // This is the attempt that is waiting
1166
+ attemptFriendlyId: zod.z.string()
1167
+ }),
1168
+ callback: zod.z.object({
1169
+ willCheckpointAndRestore: zod.z.boolean()
1170
+ })
1171
+ },
1172
+ WAIT_FOR_BATCH: {
1173
+ message: zod.z.object({
1174
+ version: zod.z.literal("v1").default("v1"),
1175
+ batchFriendlyId: zod.z.string(),
1176
+ runFriendlyIds: zod.z.string().array(),
1177
+ // This is the attempt that is waiting
1178
+ attemptFriendlyId: zod.z.string()
1179
+ }),
1180
+ callback: zod.z.object({
1181
+ willCheckpointAndRestore: zod.z.boolean()
1182
+ })
1183
+ },
1184
+ INDEXING_FAILED: {
1185
+ message: zod.z.object({
1186
+ version: zod.z.literal("v1").default("v1"),
1187
+ deploymentId: zod.z.string(),
1188
+ error: zod.z.object({
1189
+ name: zod.z.string(),
1190
+ message: zod.z.string(),
1191
+ stack: zod.z.string().optional()
1192
+ })
1193
+ })
1194
+ }
1195
+ };
1196
+ var CoordinatorToProdWorkerMessages = {
1197
+ RESUME_AFTER_DEPENDENCY: {
1198
+ message: zod.z.object({
1199
+ version: zod.z.literal("v1").default("v1"),
1200
+ attemptId: zod.z.string(),
1201
+ completions: TaskRunExecutionResult.array(),
1202
+ executions: TaskRunExecution.array()
1203
+ })
1204
+ },
1205
+ RESUME_AFTER_DURATION: {
1206
+ message: zod.z.object({
1207
+ version: zod.z.literal("v1").default("v1"),
1208
+ attemptId: zod.z.string()
1209
+ })
1210
+ },
1211
+ EXECUTE_TASK_RUN: {
1212
+ message: zod.z.object({
1213
+ version: zod.z.literal("v1").default("v1"),
1214
+ executionPayload: ProdTaskRunExecutionPayload
1215
+ })
1216
+ },
1217
+ REQUEST_ATTEMPT_CANCELLATION: {
1218
+ message: zod.z.object({
1219
+ version: zod.z.literal("v1").default("v1"),
1220
+ attemptId: zod.z.string()
1221
+ })
1222
+ },
1223
+ REQUEST_EXIT: {
1224
+ message: zod.z.object({
1225
+ version: zod.z.literal("v1").default("v1")
1226
+ })
1227
+ },
1228
+ READY_FOR_RETRY: {
1229
+ message: zod.z.object({
1230
+ version: zod.z.literal("v1").default("v1"),
1231
+ runId: zod.z.string()
1232
+ })
1233
+ }
283
1234
  };
1235
+ var ProdWorkerSocketData = zod.z.object({
1236
+ contentHash: zod.z.string(),
1237
+ projectRef: zod.z.string(),
1238
+ envId: zod.z.string(),
1239
+ runId: zod.z.string(),
1240
+ attemptFriendlyId: zod.z.string().optional(),
1241
+ podName: zod.z.string(),
1242
+ deploymentId: zod.z.string(),
1243
+ deploymentVersion: zod.z.string()
1244
+ });
1245
+ var PRIMARY_VARIANT = "primary";
1246
+ var Variant = zod.z.enum([
1247
+ PRIMARY_VARIANT
1248
+ ]);
1249
+ var AccessoryItem = zod.z.object({
1250
+ text: zod.z.string(),
1251
+ variant: zod.z.string().optional(),
1252
+ url: zod.z.string().optional()
1253
+ });
1254
+ var Accessory = zod.z.object({
1255
+ items: zod.z.array(AccessoryItem),
1256
+ style: zod.z.enum([
1257
+ "codepath"
1258
+ ]).optional()
1259
+ });
1260
+ var TaskEventStyle = zod.z.object({
1261
+ icon: zod.z.string().optional(),
1262
+ variant: Variant.optional(),
1263
+ accessory: Accessory.optional()
1264
+ }).default({
1265
+ icon: void 0,
1266
+ variant: void 0
1267
+ });
1268
+ var stringPatternMatchers = [
1269
+ zod.z.object({
1270
+ $endsWith: zod.z.string()
1271
+ }),
1272
+ zod.z.object({
1273
+ $startsWith: zod.z.string()
1274
+ }),
1275
+ zod.z.object({
1276
+ $ignoreCaseEquals: zod.z.string()
1277
+ })
1278
+ ];
1279
+ var EventMatcher = zod.z.union([
1280
+ /** Match against a string */
1281
+ zod.z.array(zod.z.string()),
1282
+ /** Match against a number */
1283
+ zod.z.array(zod.z.number()),
1284
+ /** Match against a boolean */
1285
+ zod.z.array(zod.z.boolean()),
1286
+ zod.z.array(zod.z.union([
1287
+ ...stringPatternMatchers,
1288
+ zod.z.object({
1289
+ $exists: zod.z.boolean()
1290
+ }),
1291
+ zod.z.object({
1292
+ $isNull: zod.z.boolean()
1293
+ }),
1294
+ zod.z.object({
1295
+ $anythingBut: zod.z.union([
1296
+ zod.z.string(),
1297
+ zod.z.number(),
1298
+ zod.z.boolean()
1299
+ ])
1300
+ }),
1301
+ zod.z.object({
1302
+ $anythingBut: zod.z.union([
1303
+ zod.z.array(zod.z.string()),
1304
+ zod.z.array(zod.z.number()),
1305
+ zod.z.array(zod.z.boolean())
1306
+ ])
1307
+ }),
1308
+ zod.z.object({
1309
+ $gt: zod.z.number()
1310
+ }),
1311
+ zod.z.object({
1312
+ $lt: zod.z.number()
1313
+ }),
1314
+ zod.z.object({
1315
+ $gte: zod.z.number()
1316
+ }),
1317
+ zod.z.object({
1318
+ $lte: zod.z.number()
1319
+ }),
1320
+ zod.z.object({
1321
+ $between: zod.z.tuple([
1322
+ zod.z.number(),
1323
+ zod.z.number()
1324
+ ])
1325
+ }),
1326
+ zod.z.object({
1327
+ $includes: zod.z.union([
1328
+ zod.z.string(),
1329
+ zod.z.number(),
1330
+ zod.z.boolean()
1331
+ ])
1332
+ }),
1333
+ zod.z.object({
1334
+ $not: zod.z.union([
1335
+ zod.z.string(),
1336
+ zod.z.number(),
1337
+ zod.z.boolean()
1338
+ ])
1339
+ })
1340
+ ]))
1341
+ ]);
1342
+ var EventFilter = zod.z.lazy(() => zod.z.record(zod.z.union([
1343
+ EventMatcher,
1344
+ EventFilter
1345
+ ])));
1346
+
1347
+ // src/v3/schemas/fetch.ts
1348
+ var FetchRetryHeadersStrategy = zod.z.object({
1349
+ /** The `headers` strategy retries the request using info from the response headers. */
1350
+ strategy: zod.z.literal("headers"),
1351
+ /** The header to use to determine the maximum number of times to retry the request. */
1352
+ limitHeader: zod.z.string(),
1353
+ /** The header to use to determine the number of remaining retries. */
1354
+ remainingHeader: zod.z.string(),
1355
+ /** The header to use to determine the time when the number of remaining retries will be reset. */
1356
+ resetHeader: zod.z.string(),
1357
+ /** The event filter to use to determine if the request should be retried. */
1358
+ bodyFilter: EventFilter.optional(),
1359
+ /** The format of the `resetHeader` value. */
1360
+ resetFormat: zod.z.enum([
1361
+ "unix_timestamp",
1362
+ "unix_timestamp_in_ms",
1363
+ "iso_8601",
1364
+ "iso_8601_duration_openai_variant"
1365
+ ]).default("unix_timestamp").optional()
1366
+ });
1367
+ var FetchRetryBackoffStrategy = RetryOptions.extend({
1368
+ /** The `backoff` strategy retries the request with an exponential backoff. */
1369
+ strategy: zod.z.literal("backoff"),
1370
+ /** The event filter to use to determine if the request should be retried. */
1371
+ bodyFilter: EventFilter.optional()
1372
+ });
1373
+ var FetchRetryStrategy = zod.z.discriminatedUnion("strategy", [
1374
+ FetchRetryHeadersStrategy,
1375
+ FetchRetryBackoffStrategy
1376
+ ]);
1377
+ var FetchRetryByStatusOptions = zod.z.record(zod.z.string(), FetchRetryStrategy);
1378
+ var FetchTimeoutOptions = zod.z.object({
1379
+ /** The maximum time to wait for the request to complete. */
1380
+ durationInMs: zod.z.number().optional(),
1381
+ retry: RetryOptions.optional()
1382
+ });
1383
+ var FetchRetryOptions = zod.z.object({
1384
+ /** The retrying strategy for specific status codes. */
1385
+ byStatus: FetchRetryByStatusOptions.optional(),
1386
+ /** The timeout options for the request. */
1387
+ timeout: RetryOptions.optional(),
1388
+ /**
1389
+ * The retrying strategy for connection errors.
1390
+ */
1391
+ connectionError: RetryOptions.optional()
1392
+ });
1393
+ var ExceptionEventProperties = zod.z.object({
1394
+ type: zod.z.string().optional(),
1395
+ message: zod.z.string().optional(),
1396
+ stacktrace: zod.z.string().optional()
1397
+ });
1398
+ var ExceptionSpanEvent = zod.z.object({
1399
+ name: zod.z.literal("exception"),
1400
+ time: zod.z.coerce.date(),
1401
+ properties: zod.z.object({
1402
+ exception: ExceptionEventProperties
1403
+ })
1404
+ });
1405
+ var CancellationSpanEvent = zod.z.object({
1406
+ name: zod.z.literal("cancellation"),
1407
+ time: zod.z.coerce.date(),
1408
+ properties: zod.z.object({
1409
+ reason: zod.z.string()
1410
+ })
1411
+ });
1412
+ var OtherSpanEvent = zod.z.object({
1413
+ name: zod.z.string(),
1414
+ time: zod.z.coerce.date(),
1415
+ properties: zod.z.record(zod.z.unknown())
1416
+ });
1417
+ var SpanEvent = zod.z.union([
1418
+ ExceptionSpanEvent,
1419
+ CancellationSpanEvent,
1420
+ OtherSpanEvent
1421
+ ]);
1422
+ var SpanEvents = zod.z.array(SpanEvent);
1423
+ function isExceptionSpanEvent(event) {
1424
+ return event.name === "exception";
1425
+ }
1426
+ __name(isExceptionSpanEvent, "isExceptionSpanEvent");
1427
+ function isCancellationSpanEvent(event) {
1428
+ return event.name === "cancellation";
1429
+ }
1430
+ __name(isCancellationSpanEvent, "isCancellationSpanEvent");
1431
+ var SpanMessagingEvent = zod.z.object({
1432
+ system: zod.z.string().optional(),
1433
+ client_id: zod.z.string().optional(),
1434
+ operation: zod.z.enum([
1435
+ "publish",
1436
+ "create",
1437
+ "receive",
1438
+ "deliver"
1439
+ ]),
1440
+ message: zod.z.any(),
1441
+ destination: zod.z.string().optional()
1442
+ });
284
1443
 
285
1444
  // src/zodfetch.ts
286
- async function zodfetch(schema, url, requestInit) {
1445
+ async function zodfetch(schema, url, requestInit, options) {
1446
+ return await _doZodFetch(schema, url, requestInit, options);
1447
+ }
1448
+ __name(zodfetch, "zodfetch");
1449
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
287
1450
  try {
288
1451
  const response = await fetch(url, requestInit);
289
1452
  if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
@@ -292,7 +1455,7 @@ async function zodfetch(schema, url, requestInit) {
292
1455
  error: `404: ${response.statusText}`
293
1456
  };
294
1457
  }
295
- if (response.status >= 400 && response.status < 500) {
1458
+ if (response.status >= 400 && response.status < 500 && response.status !== 429) {
296
1459
  const body = await response.json();
297
1460
  if (!body.error) {
298
1461
  return {
@@ -305,6 +1468,27 @@ async function zodfetch(schema, url, requestInit) {
305
1468
  error: body.error
306
1469
  };
307
1470
  }
1471
+ if (response.status === 429 || response.status >= 500) {
1472
+ if (!options?.retry) {
1473
+ return {
1474
+ ok: false,
1475
+ error: `Failed to fetch ${url}, got status code ${response.status}`
1476
+ };
1477
+ }
1478
+ const retry = {
1479
+ ...defaultRetryOptions,
1480
+ ...options.retry
1481
+ };
1482
+ if (attempt > retry.maxAttempts) {
1483
+ return {
1484
+ ok: false,
1485
+ error: `Failed to fetch ${url}, got status code ${response.status}`
1486
+ };
1487
+ }
1488
+ const delay = calculateNextRetryDelay(retry, attempt);
1489
+ await new Promise((resolve) => setTimeout(resolve, delay));
1490
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1491
+ }
308
1492
  if (response.status !== 200) {
309
1493
  return {
310
1494
  ok: false,
@@ -330,31 +1514,45 @@ async function zodfetch(schema, url, requestInit) {
330
1514
  error: parsedResult.error.message
331
1515
  };
332
1516
  } catch (error) {
1517
+ if (options?.retry) {
1518
+ const retry = {
1519
+ ...defaultRetryOptions,
1520
+ ...options.retry
1521
+ };
1522
+ if (attempt > retry.maxAttempts) {
1523
+ return {
1524
+ ok: false,
1525
+ error: error instanceof Error ? error.message : JSON.stringify(error)
1526
+ };
1527
+ }
1528
+ const delay = calculateNextRetryDelay(retry, attempt);
1529
+ await new Promise((resolve) => setTimeout(resolve, delay));
1530
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1531
+ }
333
1532
  return {
334
1533
  ok: false,
335
1534
  error: error instanceof Error ? error.message : JSON.stringify(error)
336
1535
  };
337
1536
  }
338
1537
  }
339
- __name(zodfetch, "zodfetch");
340
- var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
341
- constructor() {
342
- this.storage = new node_async_hooks.AsyncLocalStorage();
1538
+ __name(_doZodFetch, "_doZodFetch");
1539
+
1540
+ // src/v3/utils/flattenAttributes.ts
1541
+ function flattenAttributes(obj, prefix) {
1542
+ const result = {};
1543
+ if (!obj) {
1544
+ return result;
343
1545
  }
344
- runWith(context3, fn) {
345
- return this.storage.run(context3, fn);
1546
+ if (typeof obj === "string") {
1547
+ result[prefix || ""] = obj;
1548
+ return result;
346
1549
  }
347
- getStore() {
348
- return this.storage.getStore();
1550
+ if (typeof obj === "number") {
1551
+ result[prefix || ""] = obj;
1552
+ return result;
349
1553
  }
350
- };
351
- __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
352
- var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
353
-
354
- // src/v3/utils/flattenAttributes.ts
355
- function flattenAttributes(obj, prefix) {
356
- const result = {};
357
- if (obj == null) {
1554
+ if (typeof obj === "boolean") {
1555
+ result[prefix || ""] = obj;
358
1556
  return result;
359
1557
  }
360
1558
  for (const [key, value] of Object.entries(obj)) {
@@ -362,9 +1560,9 @@ function flattenAttributes(obj, prefix) {
362
1560
  if (Array.isArray(value)) {
363
1561
  for (let i = 0; i < value.length; i++) {
364
1562
  if (typeof value[i] === "object" && value[i] !== null) {
365
- Object.assign(result, flattenAttributes(value[i], `${newPrefix}.${i}`));
1563
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
366
1564
  } else {
367
- result[`${newPrefix}.${i}`] = value[i];
1565
+ result[`${newPrefix}.[${i}]`] = value[i];
368
1566
  }
369
1567
  }
370
1568
  } else if (isRecord(value)) {
@@ -382,6 +1580,115 @@ function isRecord(value) {
382
1580
  return value !== null && typeof value === "object" && !Array.isArray(value);
383
1581
  }
384
1582
  __name(isRecord, "isRecord");
1583
+ function unflattenAttributes(obj) {
1584
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
1585
+ return obj;
1586
+ }
1587
+ const result = {};
1588
+ for (const [key, value] of Object.entries(obj)) {
1589
+ const parts = key.split(".").reduce((acc, part) => {
1590
+ if (detectIsArrayIndex(part)) {
1591
+ acc.push(part);
1592
+ } else {
1593
+ acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
1594
+ }
1595
+ return acc;
1596
+ }, []);
1597
+ let current = result;
1598
+ for (let i = 0; i < parts.length - 1; i++) {
1599
+ const part = parts[i];
1600
+ const isArray = detectIsArrayIndex(part);
1601
+ const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
1602
+ const nextIsArray = detectIsArrayIndex(parts[i + 1]);
1603
+ if (!current[cleanPart]) {
1604
+ current[cleanPart] = nextIsArray ? [] : {};
1605
+ }
1606
+ current = current[cleanPart];
1607
+ }
1608
+ const lastPart = parts[parts.length - 1];
1609
+ const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
1610
+ current[cleanLastPart] = value;
1611
+ }
1612
+ return result;
1613
+ }
1614
+ __name(unflattenAttributes, "unflattenAttributes");
1615
+ function detectIsArrayIndex(key) {
1616
+ const match = key.match(/^\[(\d+)\]$/);
1617
+ if (match) {
1618
+ return true;
1619
+ }
1620
+ return false;
1621
+ }
1622
+ __name(detectIsArrayIndex, "detectIsArrayIndex");
1623
+ function primitiveValueOrflattenedAttributes(obj, prefix) {
1624
+ if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
1625
+ return obj;
1626
+ }
1627
+ const attributes = flattenAttributes(obj, prefix);
1628
+ if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
1629
+ return attributes[prefix];
1630
+ }
1631
+ return attributes;
1632
+ }
1633
+ __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
1634
+ var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
1635
+ constructor() {
1636
+ this.storage = new async_hooks.AsyncLocalStorage();
1637
+ }
1638
+ runWith(context3, fn) {
1639
+ return this.storage.run(context3, fn);
1640
+ }
1641
+ getStore() {
1642
+ return this.storage.getStore();
1643
+ }
1644
+ };
1645
+ __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
1646
+ var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
1647
+
1648
+ // src/v3/semanticInternalAttributes.ts
1649
+ var SemanticInternalAttributes = {
1650
+ ENVIRONMENT_ID: "ctx.environment.id",
1651
+ ENVIRONMENT_TYPE: "ctx.environment.type",
1652
+ ORGANIZATION_ID: "ctx.organization.id",
1653
+ ORGANIZATION_SLUG: "ctx.organization.slug",
1654
+ ORGANIZATION_NAME: "ctx.organization.name",
1655
+ PROJECT_ID: "ctx.project.id",
1656
+ PROJECT_REF: "ctx.project.ref",
1657
+ PROJECT_NAME: "ctx.project.title",
1658
+ PROJECT_DIR: "project.dir",
1659
+ ATTEMPT_ID: "ctx.attempt.id",
1660
+ ATTEMPT_NUMBER: "ctx.attempt.number",
1661
+ RUN_ID: "ctx.run.id",
1662
+ RUN_IS_TEST: "ctx.run.isTest",
1663
+ BATCH_ID: "ctx.batch.id",
1664
+ TASK_SLUG: "ctx.task.id",
1665
+ TASK_PATH: "ctx.task.filePath",
1666
+ TASK_EXPORT_NAME: "ctx.task.exportName",
1667
+ QUEUE_NAME: "ctx.queue.name",
1668
+ QUEUE_ID: "ctx.queue.id",
1669
+ SPAN_PARTIAL: "$span.partial",
1670
+ SPAN_ID: "$span.span_id",
1671
+ OUTPUT: "$output",
1672
+ OUTPUT_TYPE: "$mime_type_output",
1673
+ STYLE: "$style",
1674
+ STYLE_ICON: "$style.icon",
1675
+ STYLE_VARIANT: "$style.variant",
1676
+ STYLE_ACCESSORY: "$style.accessory",
1677
+ METADATA: "$metadata",
1678
+ TRIGGER: "$trigger",
1679
+ PAYLOAD: "$payload",
1680
+ PAYLOAD_TYPE: "$mime_type_payload",
1681
+ SHOW: "$show",
1682
+ SHOW_ACTIONS: "$show.actions",
1683
+ WORKER_ID: "worker.id",
1684
+ WORKER_VERSION: "worker.version",
1685
+ CLI_VERSION: "cli.version",
1686
+ SDK_VERSION: "sdk.version",
1687
+ SDK_LANGUAGE: "sdk.language",
1688
+ RETRY_AT: "retry.at",
1689
+ RETRY_DELAY: "retry.delay",
1690
+ RETRY_COUNT: "retry.count"
1691
+ };
385
1692
 
386
1693
  // src/v3/tasks/taskContextManager.ts
387
1694
  var _getStore, getStore_fn;
@@ -397,10 +1704,6 @@ var _TaskContextManager = class _TaskContextManager {
397
1704
  const store = __privateMethod(this, _getStore, getStore_fn).call(this);
398
1705
  return store?.ctx;
399
1706
  }
400
- get payload() {
401
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
402
- return store?.payload;
403
- }
404
1707
  get worker() {
405
1708
  const store = __privateMethod(this, _getStore, getStore_fn).call(this);
406
1709
  return store?.worker;
@@ -408,10 +1711,42 @@ var _TaskContextManager = class _TaskContextManager {
408
1711
  get attributes() {
409
1712
  if (this.ctx) {
410
1713
  return {
411
- ...flattenAttributes(this.ctx, "ctx"),
412
- ...flattenAttributes(this.payload, "payload"),
413
- ...flattenAttributes(this.worker, "worker"),
414
- "service.name": this.ctx.task.id
1714
+ ...this.contextAttributes,
1715
+ ...this.workerAttributes
1716
+ };
1717
+ }
1718
+ return {};
1719
+ }
1720
+ get workerAttributes() {
1721
+ if (this.worker) {
1722
+ return {
1723
+ [SemanticInternalAttributes.WORKER_ID]: this.worker.id,
1724
+ [SemanticInternalAttributes.WORKER_VERSION]: this.worker.version
1725
+ };
1726
+ }
1727
+ return {};
1728
+ }
1729
+ get contextAttributes() {
1730
+ if (this.ctx) {
1731
+ return {
1732
+ [SemanticInternalAttributes.ATTEMPT_ID]: this.ctx.attempt.id,
1733
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: this.ctx.attempt.number,
1734
+ [SemanticInternalAttributes.TASK_SLUG]: this.ctx.task.id,
1735
+ [SemanticInternalAttributes.TASK_PATH]: this.ctx.task.filePath,
1736
+ [SemanticInternalAttributes.TASK_EXPORT_NAME]: this.ctx.task.exportName,
1737
+ [SemanticInternalAttributes.QUEUE_NAME]: this.ctx.queue.name,
1738
+ [SemanticInternalAttributes.QUEUE_ID]: this.ctx.queue.id,
1739
+ [SemanticInternalAttributes.ENVIRONMENT_ID]: this.ctx.environment.id,
1740
+ [SemanticInternalAttributes.ENVIRONMENT_TYPE]: this.ctx.environment.type,
1741
+ [SemanticInternalAttributes.ORGANIZATION_ID]: this.ctx.organization.id,
1742
+ [SemanticInternalAttributes.PROJECT_ID]: this.ctx.project.id,
1743
+ [SemanticInternalAttributes.PROJECT_REF]: this.ctx.project.ref,
1744
+ [SemanticInternalAttributes.PROJECT_NAME]: this.ctx.project.name,
1745
+ [SemanticInternalAttributes.RUN_ID]: this.ctx.run.id,
1746
+ [SemanticInternalAttributes.RUN_IS_TEST]: this.ctx.run.isTest,
1747
+ [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
1748
+ [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
1749
+ [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id
415
1750
  };
416
1751
  }
417
1752
  return {};
@@ -427,37 +1762,165 @@ getStore_fn = /* @__PURE__ */ __name(function() {
427
1762
  __name(_TaskContextManager, "TaskContextManager");
428
1763
  var TaskContextManager = _TaskContextManager;
429
1764
  var taskContextManager = new TaskContextManager();
1765
+ var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
1766
+ constructor(innerProcessor) {
1767
+ this._innerProcessor = innerProcessor;
1768
+ }
1769
+ // Called when a span starts
1770
+ onStart(span, parentContext) {
1771
+ if (taskContextManager.ctx) {
1772
+ span.setAttributes(flattenAttributes({
1773
+ [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
1774
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
1775
+ }, SemanticInternalAttributes.METADATA));
1776
+ }
1777
+ this._innerProcessor.onStart(span, parentContext);
1778
+ }
1779
+ // Delegate the rest of the methods to the wrapped processor
1780
+ onEnd(span) {
1781
+ this._innerProcessor.onEnd(span);
1782
+ }
1783
+ shutdown() {
1784
+ return this._innerProcessor.shutdown();
1785
+ }
1786
+ forceFlush() {
1787
+ return this._innerProcessor.forceFlush();
1788
+ }
1789
+ };
1790
+ __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
1791
+ var TaskContextSpanProcessor = _TaskContextSpanProcessor;
1792
+ var _TaskContextLogProcessor = class _TaskContextLogProcessor {
1793
+ constructor(innerProcessor) {
1794
+ this._innerProcessor = innerProcessor;
1795
+ }
1796
+ forceFlush() {
1797
+ return this._innerProcessor.forceFlush();
1798
+ }
1799
+ onEmit(logRecord, context3) {
1800
+ if (taskContextManager.ctx) {
1801
+ logRecord.setAttributes(flattenAttributes({
1802
+ [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
1803
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
1804
+ }, SemanticInternalAttributes.METADATA));
1805
+ }
1806
+ this._innerProcessor.onEmit(logRecord, context3);
1807
+ }
1808
+ shutdown() {
1809
+ return this._innerProcessor.shutdown();
1810
+ }
1811
+ };
1812
+ __name(_TaskContextLogProcessor, "TaskContextLogProcessor");
1813
+ var TaskContextLogProcessor = _TaskContextLogProcessor;
1814
+
1815
+ // src/v3/utils/getEnv.ts
1816
+ function getEnvVar(name) {
1817
+ if (typeof process !== "undefined" && typeof process.env === "object" && process.env !== null) {
1818
+ return process.env[name];
1819
+ }
1820
+ }
1821
+ __name(getEnvVar, "getEnvVar");
430
1822
 
431
1823
  // src/v3/apiClient/index.ts
1824
+ var zodFetchOptions = {
1825
+ retry: {
1826
+ maxAttempts: 5,
1827
+ minTimeoutInMs: 1e3,
1828
+ maxTimeoutInMs: 3e4,
1829
+ factor: 2,
1830
+ randomize: false
1831
+ }
1832
+ };
432
1833
  var _getHeaders, getHeaders_fn;
433
1834
  var _ApiClient = class _ApiClient {
434
1835
  constructor(baseUrl, accessToken) {
435
1836
  __privateAdd(this, _getHeaders);
436
- this.baseUrl = baseUrl;
437
1837
  this.accessToken = accessToken;
1838
+ this.baseUrl = baseUrl.replace(/\/$/, "");
438
1839
  }
439
- triggerTask(taskId, options) {
1840
+ triggerTask(taskId, body, options) {
440
1841
  return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
441
1842
  method: "POST",
442
- headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this),
443
- body: JSON.stringify(options)
444
- });
1843
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1844
+ body: JSON.stringify(body)
1845
+ }, zodFetchOptions);
1846
+ }
1847
+ batchTriggerTask(taskId, body, options) {
1848
+ return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
1849
+ method: "POST",
1850
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
1851
+ body: JSON.stringify(body)
1852
+ }, zodFetchOptions);
1853
+ }
1854
+ createUploadPayloadUrl(filename) {
1855
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1856
+ method: "PUT",
1857
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1858
+ }, zodFetchOptions);
1859
+ }
1860
+ getPayloadUrl(filename) {
1861
+ return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
1862
+ method: "GET",
1863
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1864
+ }, zodFetchOptions);
445
1865
  }
446
1866
  };
447
1867
  _getHeaders = new WeakSet();
448
- getHeaders_fn = /* @__PURE__ */ __name(function() {
1868
+ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
449
1869
  const headers = {
450
1870
  "Content-Type": "application/json",
451
1871
  Authorization: `Bearer ${this.accessToken}`
452
1872
  };
453
1873
  if (taskContextManager.isInsideTask) {
454
1874
  api.propagation.inject(api.context.active(), headers);
1875
+ if (spanParentAsLink) {
1876
+ headers["x-trigger-span-parent-as-link"] = "1";
1877
+ }
455
1878
  }
456
1879
  return headers;
457
1880
  }, "#getHeaders");
458
1881
  __name(_ApiClient, "ApiClient");
459
1882
  var ApiClient = _ApiClient;
460
- var messageSchema = zod.z.object({
1883
+ var _getStore2, getStore_fn2;
1884
+ var _ApiClientManager = class _ApiClientManager {
1885
+ constructor() {
1886
+ __privateAdd(this, _getStore2);
1887
+ __publicField(this, "_storage", new SafeAsyncLocalStorage());
1888
+ }
1889
+ get baseURL() {
1890
+ const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
1891
+ return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
1892
+ }
1893
+ get accessToken() {
1894
+ const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
1895
+ return store?.accessToken ?? getEnvVar("TRIGGER_SECRET_KEY");
1896
+ }
1897
+ get client() {
1898
+ if (!this.baseURL || !this.accessToken) {
1899
+ return void 0;
1900
+ }
1901
+ return new ApiClient(this.baseURL, this.accessToken);
1902
+ }
1903
+ runWith(context3, fn) {
1904
+ return this._storage.runWith(context3, fn);
1905
+ }
1906
+ };
1907
+ _getStore2 = new WeakSet();
1908
+ getStore_fn2 = /* @__PURE__ */ __name(function() {
1909
+ return this._storage.getStore();
1910
+ }, "#getStore");
1911
+ __name(_ApiClientManager, "ApiClientManager");
1912
+ var ApiClientManager = _ApiClientManager;
1913
+ var apiClientManager = new ApiClientManager();
1914
+ var _ZodSchemaParsedError = class _ZodSchemaParsedError extends Error {
1915
+ constructor(error, payload) {
1916
+ super(error.message);
1917
+ this.error = error;
1918
+ this.payload = payload;
1919
+ }
1920
+ };
1921
+ __name(_ZodSchemaParsedError, "ZodSchemaParsedError");
1922
+ var ZodSchemaParsedError = _ZodSchemaParsedError;
1923
+ var ZodMessageSchema = zod.z.object({
461
1924
  version: zod.z.literal("v1").default("v1"),
462
1925
  type: zod.z.string(),
463
1926
  payload: zod.z.unknown()
@@ -477,12 +1940,14 @@ var _ZodMessageHandler = class _ZodMessageHandler {
477
1940
  }
478
1941
  const handler = __privateGet(this, _handlers)[parsedMessage.type];
479
1942
  if (!handler) {
480
- throw new Error(`Unknown message type: ${String(parsedMessage.type)}`);
1943
+ console.error(`No handler for message type: ${String(parsedMessage.type)}`);
1944
+ return;
481
1945
  }
482
- await handler(parsedMessage.payload);
1946
+ const ack = await handler(parsedMessage.payload);
1947
+ return ack;
483
1948
  }
484
1949
  parseMessage(message) {
485
- const parsedMessage = messageSchema.safeParse(message);
1950
+ const parsedMessage = ZodMessageSchema.safeParse(message);
486
1951
  if (!parsedMessage.success) {
487
1952
  throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
488
1953
  }
@@ -499,6 +1964,38 @@ var _ZodMessageHandler = class _ZodMessageHandler {
499
1964
  payload: parsedPayload.data
500
1965
  };
501
1966
  }
1967
+ registerHandlers(emitter, logger2) {
1968
+ const log = logger2 ?? console;
1969
+ if (!__privateGet(this, _handlers)) {
1970
+ log.info("No handlers provided");
1971
+ return;
1972
+ }
1973
+ for (const eventName of Object.keys(__privateGet(this, _schema))) {
1974
+ emitter.on(eventName, async (message, callback) => {
1975
+ log.info(`handling ${eventName}`, {
1976
+ payload: message,
1977
+ hasCallback: !!callback
1978
+ });
1979
+ let ack;
1980
+ if ("payload" in message) {
1981
+ ack = await this.handleMessage({
1982
+ type: eventName,
1983
+ ...message
1984
+ });
1985
+ } else {
1986
+ const { version, ...payload } = message;
1987
+ ack = await this.handleMessage({
1988
+ type: eventName,
1989
+ version,
1990
+ payload
1991
+ });
1992
+ }
1993
+ if (callback && typeof callback === "function") {
1994
+ callback(ack);
1995
+ }
1996
+ });
1997
+ }
1998
+ }
502
1999
  };
503
2000
  _schema = new WeakMap();
504
2001
  _handlers = new WeakMap();
@@ -519,7 +2016,7 @@ var _ZodMessageSender = class _ZodMessageSender {
519
2016
  }
520
2017
  const parsedPayload = schema.safeParse(payload);
521
2018
  if (!parsedPayload.success) {
522
- throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2019
+ throw new ZodSchemaParsedError(parsedPayload.error, payload);
523
2020
  }
524
2021
  await __privateGet(this, _sender).call(this, {
525
2022
  type,
@@ -527,82 +2024,747 @@ var _ZodMessageSender = class _ZodMessageSender {
527
2024
  version: "v1"
528
2025
  });
529
2026
  }
2027
+ async forwardMessage(message) {
2028
+ const parsedMessage = ZodMessageSchema.safeParse(message);
2029
+ if (!parsedMessage.success) {
2030
+ throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2031
+ }
2032
+ const schema = __privateGet(this, _schema2)[parsedMessage.data.type];
2033
+ if (!schema) {
2034
+ throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2035
+ }
2036
+ const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2037
+ if (!parsedPayload.success) {
2038
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2039
+ }
2040
+ await __privateGet(this, _sender).call(this, {
2041
+ type: parsedMessage.data.type,
2042
+ payload: parsedPayload.data,
2043
+ version: "v1"
2044
+ });
2045
+ }
530
2046
  };
531
2047
  _schema2 = new WeakMap();
532
2048
  _sender = new WeakMap();
533
2049
  __name(_ZodMessageSender, "ZodMessageSender");
534
2050
  var ZodMessageSender = _ZodMessageSender;
535
-
536
- // src/v3/errors.ts
537
- function parseError(error) {
538
- if (error instanceof Error) {
539
- return {
540
- type: "BUILT_IN_ERROR",
541
- name: error.name,
542
- message: error.message,
543
- stackTrace: error.stack ?? ""
544
- };
2051
+ var messageSchema = zod.z.object({
2052
+ version: zod.z.literal("v1").default("v1"),
2053
+ type: zod.z.string(),
2054
+ payload: zod.z.unknown()
2055
+ });
2056
+ var _schema3, _handlers2;
2057
+ var _ZodSocketMessageHandler = class _ZodSocketMessageHandler {
2058
+ constructor(options) {
2059
+ __privateAdd(this, _schema3, void 0);
2060
+ __privateAdd(this, _handlers2, void 0);
2061
+ __privateSet(this, _schema3, options.schema);
2062
+ __privateSet(this, _handlers2, options.handlers);
545
2063
  }
546
- if (typeof error === "string") {
547
- return {
548
- type: "STRING_ERROR",
549
- raw: error
550
- };
2064
+ async handleMessage(message) {
2065
+ const parsedMessage = this.parseMessage(message);
2066
+ if (!__privateGet(this, _handlers2)) {
2067
+ throw new Error("No handlers provided");
2068
+ }
2069
+ const handler = __privateGet(this, _handlers2)[parsedMessage.type];
2070
+ if (!handler) {
2071
+ console.error(`No handler for message type: ${String(parsedMessage.type)}`);
2072
+ return;
2073
+ }
2074
+ const ack = await handler(parsedMessage.payload);
2075
+ return ack;
551
2076
  }
552
- try {
553
- return {
554
- type: "CUSTOM_ERROR",
555
- raw: JSON.stringify(error)
556
- };
557
- } catch (e) {
2077
+ parseMessage(message) {
2078
+ const parsedMessage = messageSchema.safeParse(message);
2079
+ if (!parsedMessage.success) {
2080
+ throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2081
+ }
2082
+ const schema = __privateGet(this, _schema3)[parsedMessage.data.type]["message"];
2083
+ if (!schema) {
2084
+ throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2085
+ }
2086
+ const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2087
+ if (!parsedPayload.success) {
2088
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2089
+ }
558
2090
  return {
559
- type: "CUSTOM_ERROR",
560
- raw: String(error)
2091
+ type: parsedMessage.data.type,
2092
+ payload: parsedPayload.data
561
2093
  };
562
2094
  }
563
- }
564
- __name(parseError, "parseError");
565
- function createErrorTaskError(error) {
566
- switch (error.type) {
567
- case "BUILT_IN_ERROR": {
568
- const e = new Error(error.message);
569
- e.name = error.name;
570
- e.stack = error.stackTrace;
571
- return e;
2095
+ registerHandlers(emitter, logger2) {
2096
+ const log = logger2 ?? console;
2097
+ if (!__privateGet(this, _handlers2)) {
2098
+ log.info("No handlers provided");
2099
+ return;
572
2100
  }
573
- case "STRING_ERROR": {
574
- return error.raw;
2101
+ for (const eventName of Object.keys(__privateGet(this, _handlers2))) {
2102
+ emitter.on(eventName, async (message, callback) => {
2103
+ log.info(`handling ${eventName}`, {
2104
+ payload: message,
2105
+ hasCallback: !!callback
2106
+ });
2107
+ let ack;
2108
+ try {
2109
+ if ("payload" in message) {
2110
+ ack = await this.handleMessage({
2111
+ type: eventName,
2112
+ ...message
2113
+ });
2114
+ } else {
2115
+ const { version, ...payload } = message;
2116
+ ack = await this.handleMessage({
2117
+ type: eventName,
2118
+ version,
2119
+ payload
2120
+ });
2121
+ }
2122
+ } catch (error) {
2123
+ log.error("Error while handling message", {
2124
+ error
2125
+ });
2126
+ return;
2127
+ }
2128
+ if (callback && typeof callback === "function") {
2129
+ callback(ack);
2130
+ }
2131
+ });
575
2132
  }
576
- case "CUSTOM_ERROR": {
577
- return JSON.parse(error.raw);
2133
+ }
2134
+ };
2135
+ _schema3 = new WeakMap();
2136
+ _handlers2 = new WeakMap();
2137
+ __name(_ZodSocketMessageHandler, "ZodSocketMessageHandler");
2138
+ var ZodSocketMessageHandler = _ZodSocketMessageHandler;
2139
+ var _schema4, _socket;
2140
+ var _ZodSocketMessageSender = class _ZodSocketMessageSender {
2141
+ constructor(options) {
2142
+ __privateAdd(this, _schema4, void 0);
2143
+ __privateAdd(this, _socket, void 0);
2144
+ __privateSet(this, _schema4, options.schema);
2145
+ __privateSet(this, _socket, options.socket);
2146
+ }
2147
+ send(type, payload) {
2148
+ const schema = __privateGet(this, _schema4)[type]["message"];
2149
+ if (!schema) {
2150
+ throw new Error(`Unknown message type: ${type}`);
578
2151
  }
579
- case "INTERNAL_ERROR": {
580
- return new Error(`trigger.dev internal error (${error.code})`);
2152
+ const parsedPayload = schema.safeParse(payload);
2153
+ if (!parsedPayload.success) {
2154
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
581
2155
  }
2156
+ __privateGet(this, _socket).emit(type, {
2157
+ payload,
2158
+ version: "v1"
2159
+ });
2160
+ return;
582
2161
  }
583
- }
584
- __name(createErrorTaskError, "createErrorTaskError");
585
-
586
- // src/v3/utils/platform.ts
587
- var _globalThis = typeof globalThis === "object" ? globalThis : global;
588
-
589
- // src/v3/utils/globals.ts
590
- var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
591
- var _global = _globalThis;
592
- function registerGlobal(type, instance, allowOverride = false) {
593
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
594
- if (!allowOverride && api[type]) {
595
- return false;
2162
+ async sendWithAck(type, payload) {
2163
+ const schema = __privateGet(this, _schema4)[type]["message"];
2164
+ if (!schema) {
2165
+ throw new Error(`Unknown message type: ${type}`);
2166
+ }
2167
+ const parsedPayload = schema.safeParse(payload);
2168
+ if (!parsedPayload.success) {
2169
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2170
+ }
2171
+ const callbackResult = await __privateGet(this, _socket).emitWithAck(type, {
2172
+ payload,
2173
+ version: "v1"
2174
+ });
2175
+ return callbackResult;
596
2176
  }
597
- api[type] = instance;
598
- return true;
599
- }
600
- __name(registerGlobal, "registerGlobal");
601
- function getGlobal(type) {
602
- return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
603
- }
604
- __name(getGlobal, "getGlobal");
605
- function unregisterGlobal(type) {
2177
+ };
2178
+ _schema4 = new WeakMap();
2179
+ _socket = new WeakMap();
2180
+ __name(_ZodSocketMessageSender, "ZodSocketMessageSender");
2181
+ var ZodSocketMessageSender = _ZodSocketMessageSender;
2182
+ var _sender2, _handler, _logger;
2183
+ var _ZodSocketConnection = class _ZodSocketConnection {
2184
+ constructor(opts) {
2185
+ __privateAdd(this, _sender2, void 0);
2186
+ __privateAdd(this, _handler, void 0);
2187
+ __privateAdd(this, _logger, void 0);
2188
+ const uri = `${opts.secure ? "wss" : "ws"}://${opts.host}:${opts.port ?? (opts.secure ? "443" : "80")}/${opts.namespace}`;
2189
+ const logger2 = new SimpleStructuredLogger(opts.namespace, exports.LogLevel.info);
2190
+ logger2.log("new zod socket", {
2191
+ uri
2192
+ });
2193
+ this.socket = socket_ioClient.io(uri, {
2194
+ transports: [
2195
+ "websocket"
2196
+ ],
2197
+ auth: {
2198
+ token: opts.authToken
2199
+ },
2200
+ extraHeaders: opts.extraHeaders,
2201
+ reconnectionDelay: 500,
2202
+ reconnectionDelayMax: 1e3
2203
+ });
2204
+ __privateSet(this, _logger, logger2.child({
2205
+ socketId: this.socket.id
2206
+ }));
2207
+ __privateSet(this, _handler, new ZodSocketMessageHandler({
2208
+ schema: opts.serverMessages,
2209
+ handlers: opts.handlers
2210
+ }));
2211
+ __privateGet(this, _handler).registerHandlers(this.socket, __privateGet(this, _logger));
2212
+ __privateSet(this, _sender2, new ZodSocketMessageSender({
2213
+ schema: opts.clientMessages,
2214
+ socket: this.socket
2215
+ }));
2216
+ this.socket.on("connect_error", async (error) => {
2217
+ __privateGet(this, _logger).error(`connect_error: ${error}`);
2218
+ if (opts.onError) {
2219
+ await opts.onError(this.socket, error, __privateGet(this, _logger));
2220
+ }
2221
+ });
2222
+ this.socket.on("connect", async () => {
2223
+ __privateGet(this, _logger).info("connect");
2224
+ if (opts.onConnection) {
2225
+ await opts.onConnection(this.socket, __privateGet(this, _handler), __privateGet(this, _sender2), __privateGet(this, _logger));
2226
+ }
2227
+ });
2228
+ this.socket.on("disconnect", async (reason, description) => {
2229
+ __privateGet(this, _logger).info("disconnect", {
2230
+ reason,
2231
+ description
2232
+ });
2233
+ if (opts.onDisconnect) {
2234
+ await opts.onDisconnect(this.socket, reason, description, __privateGet(this, _logger));
2235
+ }
2236
+ });
2237
+ }
2238
+ close() {
2239
+ this.socket.close();
2240
+ }
2241
+ connect() {
2242
+ this.socket.connect();
2243
+ }
2244
+ get send() {
2245
+ return __privateGet(this, _sender2).send.bind(__privateGet(this, _sender2));
2246
+ }
2247
+ get sendWithAck() {
2248
+ return __privateGet(this, _sender2).sendWithAck.bind(__privateGet(this, _sender2));
2249
+ }
2250
+ };
2251
+ _sender2 = new WeakMap();
2252
+ _handler = new WeakMap();
2253
+ _logger = new WeakMap();
2254
+ __name(_ZodSocketConnection, "ZodSocketConnection");
2255
+ var ZodSocketConnection = _ZodSocketConnection;
2256
+
2257
+ // src/v3/zodNamespace.ts
2258
+ exports.LogLevel = void 0;
2259
+ (function(LogLevel2) {
2260
+ LogLevel2[LogLevel2["log"] = 0] = "log";
2261
+ LogLevel2[LogLevel2["error"] = 1] = "error";
2262
+ LogLevel2[LogLevel2["warn"] = 2] = "warn";
2263
+ LogLevel2[LogLevel2["info"] = 3] = "info";
2264
+ LogLevel2[LogLevel2["debug"] = 4] = "debug";
2265
+ })(exports.LogLevel || (exports.LogLevel = {}));
2266
+ var _structuredLog, structuredLog_fn;
2267
+ var _SimpleStructuredLogger = class _SimpleStructuredLogger {
2268
+ constructor(name, level = [
2269
+ "1",
2270
+ "true"
2271
+ ].includes(process.env.DEBUG ?? "") ? exports.LogLevel.debug : exports.LogLevel.info, fields) {
2272
+ __privateAdd(this, _structuredLog);
2273
+ this.name = name;
2274
+ this.level = level;
2275
+ this.fields = fields;
2276
+ }
2277
+ child(fields, level) {
2278
+ return new _SimpleStructuredLogger(this.name, level, {
2279
+ ...this.fields,
2280
+ ...fields
2281
+ });
2282
+ }
2283
+ log(message, ...args) {
2284
+ if (this.level < exports.LogLevel.log)
2285
+ return;
2286
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.log, message, "log", ...args);
2287
+ }
2288
+ error(message, ...args) {
2289
+ if (this.level < exports.LogLevel.error)
2290
+ return;
2291
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.error, message, "error", ...args);
2292
+ }
2293
+ warn(message, ...args) {
2294
+ if (this.level < exports.LogLevel.warn)
2295
+ return;
2296
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.warn, message, "warn", ...args);
2297
+ }
2298
+ info(message, ...args) {
2299
+ if (this.level < exports.LogLevel.info)
2300
+ return;
2301
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.info, message, "info", ...args);
2302
+ }
2303
+ debug(message, ...args) {
2304
+ if (this.level < exports.LogLevel.debug)
2305
+ return;
2306
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.debug, message, "debug", ...args);
2307
+ }
2308
+ };
2309
+ _structuredLog = new WeakSet();
2310
+ structuredLog_fn = /* @__PURE__ */ __name(function(loggerFunction, message, level, ...args) {
2311
+ const structuredLog = {
2312
+ ...args.length === 1 ? args[0] : args,
2313
+ ...this.fields,
2314
+ timestamp: /* @__PURE__ */ new Date(),
2315
+ name: this.name,
2316
+ message,
2317
+ level
2318
+ };
2319
+ loggerFunction(JSON.stringify(structuredLog));
2320
+ }, "#structuredLog");
2321
+ __name(_SimpleStructuredLogger, "SimpleStructuredLogger");
2322
+ var SimpleStructuredLogger = _SimpleStructuredLogger;
2323
+ var _logger2, _handler2;
2324
+ var _ZodNamespace = class _ZodNamespace {
2325
+ constructor(opts) {
2326
+ __privateAdd(this, _logger2, void 0);
2327
+ __privateAdd(this, _handler2, void 0);
2328
+ __privateSet(this, _logger2, opts.logger ?? new SimpleStructuredLogger(opts.name));
2329
+ __privateSet(this, _handler2, new ZodSocketMessageHandler({
2330
+ schema: opts.clientMessages,
2331
+ handlers: opts.handlers
2332
+ }));
2333
+ this.io = opts.io;
2334
+ this.namespace = this.io.of(opts.name);
2335
+ this.sender = new ZodMessageSender({
2336
+ schema: opts.serverMessages,
2337
+ sender: async (message) => {
2338
+ return new Promise((resolve, reject) => {
2339
+ try {
2340
+ this.namespace.emit(message.type, message.payload);
2341
+ resolve();
2342
+ } catch (err) {
2343
+ reject(err);
2344
+ }
2345
+ });
2346
+ }
2347
+ });
2348
+ if (opts.preAuth) {
2349
+ this.namespace.use(async (socket, next) => {
2350
+ const logger2 = __privateGet(this, _logger2).child({
2351
+ socketId: socket.id,
2352
+ socketStage: "preAuth"
2353
+ });
2354
+ if (typeof opts.preAuth === "function") {
2355
+ await opts.preAuth(socket, next, logger2);
2356
+ }
2357
+ });
2358
+ }
2359
+ if (opts.authToken) {
2360
+ this.namespace.use((socket, next) => {
2361
+ const logger2 = __privateGet(this, _logger2).child({
2362
+ socketId: socket.id,
2363
+ socketStage: "auth"
2364
+ });
2365
+ const { auth } = socket.handshake;
2366
+ if (!("token" in auth)) {
2367
+ logger2.error("no token");
2368
+ return socket.disconnect(true);
2369
+ }
2370
+ if (auth.token !== opts.authToken) {
2371
+ logger2.error("invalid token");
2372
+ return socket.disconnect(true);
2373
+ }
2374
+ logger2.info("success");
2375
+ next();
2376
+ });
2377
+ }
2378
+ if (opts.postAuth) {
2379
+ this.namespace.use(async (socket, next) => {
2380
+ const logger2 = __privateGet(this, _logger2).child({
2381
+ socketId: socket.id,
2382
+ socketStage: "auth"
2383
+ });
2384
+ if (typeof opts.postAuth === "function") {
2385
+ await opts.postAuth(socket, next, logger2);
2386
+ }
2387
+ });
2388
+ }
2389
+ this.namespace.on("connection", async (socket) => {
2390
+ const logger2 = __privateGet(this, _logger2).child({
2391
+ socketId: socket.id,
2392
+ socketStage: "connection"
2393
+ });
2394
+ logger2.info("connected");
2395
+ __privateGet(this, _handler2).registerHandlers(socket, logger2);
2396
+ socket.on("disconnect", async (reason, description) => {
2397
+ logger2.info("disconnect", {
2398
+ reason,
2399
+ description
2400
+ });
2401
+ if (opts.onDisconnect) {
2402
+ await opts.onDisconnect(socket, reason, description, logger2);
2403
+ }
2404
+ });
2405
+ socket.on("error", async (error) => {
2406
+ logger2.error("error", {
2407
+ error
2408
+ });
2409
+ if (opts.onError) {
2410
+ await opts.onError(socket, error, logger2);
2411
+ }
2412
+ });
2413
+ if (opts.onConnection) {
2414
+ await opts.onConnection(socket, __privateGet(this, _handler2), this.sender, logger2);
2415
+ }
2416
+ });
2417
+ }
2418
+ fetchSockets() {
2419
+ return this.namespace.fetchSockets();
2420
+ }
2421
+ };
2422
+ _logger2 = new WeakMap();
2423
+ _handler2 = new WeakMap();
2424
+ __name(_ZodNamespace, "ZodNamespace");
2425
+ var ZodNamespace = _ZodNamespace;
2426
+ var messageSchema2 = zod.z.object({
2427
+ version: zod.z.literal("v1").default("v1"),
2428
+ type: zod.z.string(),
2429
+ payload: zod.z.unknown()
2430
+ });
2431
+ var _schema5, _handlers3, _sender3, _a;
2432
+ var ZodIpcMessageHandler = (_a = class {
2433
+ constructor(options) {
2434
+ __privateAdd(this, _schema5, void 0);
2435
+ __privateAdd(this, _handlers3, void 0);
2436
+ __privateAdd(this, _sender3, void 0);
2437
+ __privateSet(this, _schema5, options.schema);
2438
+ __privateSet(this, _handlers3, options.handlers);
2439
+ __privateSet(this, _sender3, options.sender);
2440
+ }
2441
+ async handleMessage(message) {
2442
+ const parsedMessage = this.parseMessage(message);
2443
+ if (!__privateGet(this, _handlers3)) {
2444
+ throw new Error("No handlers provided");
2445
+ }
2446
+ const handler = __privateGet(this, _handlers3)[parsedMessage.type];
2447
+ if (!handler) {
2448
+ return;
2449
+ }
2450
+ const ack = await handler(parsedMessage.payload, __privateGet(this, _sender3));
2451
+ return ack;
2452
+ }
2453
+ parseMessage(message) {
2454
+ const parsedMessage = messageSchema2.safeParse(message);
2455
+ if (!parsedMessage.success) {
2456
+ throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2457
+ }
2458
+ const schema = __privateGet(this, _schema5)[parsedMessage.data.type]["message"];
2459
+ if (!schema) {
2460
+ throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2461
+ }
2462
+ const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2463
+ if (!parsedPayload.success) {
2464
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2465
+ }
2466
+ return {
2467
+ type: parsedMessage.data.type,
2468
+ payload: parsedPayload.data
2469
+ };
2470
+ }
2471
+ }, _schema5 = new WeakMap(), _handlers3 = new WeakMap(), _sender3 = new WeakMap(), __name(_a, "ZodIpcMessageHandler"), _a);
2472
+ var Packet = zod.z.discriminatedUnion("type", [
2473
+ zod.z.object({
2474
+ type: zod.z.literal("CONNECT"),
2475
+ sessionId: zod.z.string().optional()
2476
+ }),
2477
+ zod.z.object({
2478
+ type: zod.z.literal("ACK"),
2479
+ message: zod.z.any(),
2480
+ id: zod.z.number()
2481
+ }),
2482
+ zod.z.object({
2483
+ type: zod.z.literal("EVENT"),
2484
+ message: zod.z.any(),
2485
+ id: zod.z.number().optional()
2486
+ })
2487
+ ]);
2488
+ var _sessionId, _messageCounter, _handler3, _acks, _registerHandlers, registerHandlers_fn, _handlePacket, handlePacket_fn, _sendPacket, sendPacket_fn;
2489
+ var _ZodIpcConnection = class _ZodIpcConnection {
2490
+ constructor(opts) {
2491
+ __privateAdd(this, _registerHandlers);
2492
+ __privateAdd(this, _handlePacket);
2493
+ __privateAdd(this, _sendPacket);
2494
+ __privateAdd(this, _sessionId, void 0);
2495
+ __privateAdd(this, _messageCounter, void 0);
2496
+ __privateAdd(this, _handler3, void 0);
2497
+ __privateAdd(this, _acks, void 0);
2498
+ this.opts = opts;
2499
+ __privateSet(this, _messageCounter, 0);
2500
+ __privateSet(this, _acks, /* @__PURE__ */ new Map());
2501
+ __privateSet(this, _handler3, new ZodIpcMessageHandler({
2502
+ schema: opts.listenSchema,
2503
+ handlers: opts.handlers,
2504
+ sender: {
2505
+ send: this.send.bind(this),
2506
+ sendWithAck: this.sendWithAck.bind(this)
2507
+ }
2508
+ }));
2509
+ __privateMethod(this, _registerHandlers, registerHandlers_fn).call(this);
2510
+ }
2511
+ async connect() {
2512
+ __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2513
+ type: "CONNECT"
2514
+ });
2515
+ }
2516
+ async send(type, payload) {
2517
+ const schema = this.opts.emitSchema[type]["message"];
2518
+ if (!schema) {
2519
+ throw new Error(`Unknown message type: ${type}`);
2520
+ }
2521
+ const parsedPayload = schema.safeParse(payload);
2522
+ if (!parsedPayload.success) {
2523
+ throw new ZodSchemaParsedError(parsedPayload.error, payload);
2524
+ }
2525
+ await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2526
+ type: "EVENT",
2527
+ message: {
2528
+ type,
2529
+ payload,
2530
+ version: "v1"
2531
+ }
2532
+ });
2533
+ }
2534
+ async sendWithAck(type, payload, timeoutInMs) {
2535
+ const currentId = __privateWrapper(this, _messageCounter)._++;
2536
+ return new Promise(async (resolve, reject) => {
2537
+ const defaultTimeoutInMs = 2e3;
2538
+ const timeout = setTimeout(() => {
2539
+ reject(JSON.stringify({
2540
+ reason: "sendWithAck() timeout",
2541
+ timeoutInMs: timeoutInMs ?? defaultTimeoutInMs,
2542
+ type,
2543
+ payload
2544
+ }));
2545
+ }, timeoutInMs ?? defaultTimeoutInMs);
2546
+ __privateGet(this, _acks).set(currentId, {
2547
+ resolve,
2548
+ reject,
2549
+ timeout
2550
+ });
2551
+ const schema = this.opts.emitSchema[type]["message"];
2552
+ if (!schema) {
2553
+ clearTimeout(timeout);
2554
+ return reject(`Unknown message type: ${type}`);
2555
+ }
2556
+ const parsedPayload = schema.safeParse(payload);
2557
+ if (!parsedPayload.success) {
2558
+ clearTimeout(timeout);
2559
+ return reject(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2560
+ }
2561
+ await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2562
+ type: "EVENT",
2563
+ message: {
2564
+ type,
2565
+ payload,
2566
+ version: "v1"
2567
+ },
2568
+ id: currentId
2569
+ });
2570
+ });
2571
+ }
2572
+ };
2573
+ _sessionId = new WeakMap();
2574
+ _messageCounter = new WeakMap();
2575
+ _handler3 = new WeakMap();
2576
+ _acks = new WeakMap();
2577
+ _registerHandlers = new WeakSet();
2578
+ registerHandlers_fn = /* @__PURE__ */ __name(async function() {
2579
+ if (!this.opts.process.on) {
2580
+ return;
2581
+ }
2582
+ this.opts.process.on("message", async (message) => {
2583
+ __privateMethod(this, _handlePacket, handlePacket_fn).call(this, message);
2584
+ });
2585
+ }, "#registerHandlers");
2586
+ _handlePacket = new WeakSet();
2587
+ handlePacket_fn = /* @__PURE__ */ __name(async function(packet) {
2588
+ const parsedPacket = Packet.safeParse(packet);
2589
+ if (!parsedPacket.success) {
2590
+ return;
2591
+ }
2592
+ switch (parsedPacket.data.type) {
2593
+ case "ACK": {
2594
+ const ack = __privateGet(this, _acks).get(parsedPacket.data.id);
2595
+ if (!ack) {
2596
+ return;
2597
+ }
2598
+ clearTimeout(ack.timeout);
2599
+ ack.resolve(parsedPacket.data.message);
2600
+ break;
2601
+ }
2602
+ case "CONNECT": {
2603
+ if (!parsedPacket.data.sessionId) {
2604
+ const id = crypto.randomUUID();
2605
+ await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2606
+ type: "CONNECT",
2607
+ sessionId: id
2608
+ });
2609
+ return;
2610
+ }
2611
+ if (__privateGet(this, _sessionId)) {
2612
+ return;
2613
+ }
2614
+ __privateSet(this, _sessionId, parsedPacket.data.sessionId);
2615
+ break;
2616
+ }
2617
+ case "EVENT": {
2618
+ const result = await __privateGet(this, _handler3).handleMessage(parsedPacket.data.message);
2619
+ if (typeof parsedPacket.data.id === "undefined") {
2620
+ return;
2621
+ }
2622
+ await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2623
+ type: "ACK",
2624
+ id: parsedPacket.data.id,
2625
+ message: result
2626
+ });
2627
+ break;
2628
+ }
2629
+ }
2630
+ }, "#handlePacket");
2631
+ _sendPacket = new WeakSet();
2632
+ sendPacket_fn = /* @__PURE__ */ __name(async function(packet1) {
2633
+ await this.opts.process.send?.(packet1);
2634
+ }, "#sendPacket");
2635
+ __name(_ZodIpcConnection, "ZodIpcConnection");
2636
+ var ZodIpcConnection = _ZodIpcConnection;
2637
+ function parseError(error) {
2638
+ if (error instanceof Error) {
2639
+ return {
2640
+ type: "BUILT_IN_ERROR",
2641
+ name: error.name,
2642
+ message: error.message,
2643
+ stackTrace: error.stack ?? ""
2644
+ };
2645
+ }
2646
+ if (typeof error === "string") {
2647
+ return {
2648
+ type: "STRING_ERROR",
2649
+ raw: error
2650
+ };
2651
+ }
2652
+ try {
2653
+ return {
2654
+ type: "CUSTOM_ERROR",
2655
+ raw: JSON.stringify(error)
2656
+ };
2657
+ } catch (e) {
2658
+ return {
2659
+ type: "CUSTOM_ERROR",
2660
+ raw: String(error)
2661
+ };
2662
+ }
2663
+ }
2664
+ __name(parseError, "parseError");
2665
+ function createErrorTaskError(error) {
2666
+ switch (error.type) {
2667
+ case "BUILT_IN_ERROR": {
2668
+ const e = new Error(error.message);
2669
+ e.name = error.name;
2670
+ e.stack = error.stackTrace;
2671
+ return e;
2672
+ }
2673
+ case "STRING_ERROR": {
2674
+ return error.raw;
2675
+ }
2676
+ case "CUSTOM_ERROR": {
2677
+ return JSON.parse(error.raw);
2678
+ }
2679
+ case "INTERNAL_ERROR": {
2680
+ return new Error(`trigger.dev internal error (${error.code})`);
2681
+ }
2682
+ }
2683
+ }
2684
+ __name(createErrorTaskError, "createErrorTaskError");
2685
+ function correctErrorStackTrace(stackTrace, projectDir, options) {
2686
+ const [errorLine, ...traceLines] = stackTrace.split("\n");
2687
+ return [
2688
+ options?.removeFirstLine ? void 0 : errorLine,
2689
+ ...traceLines.map((line) => correctStackTraceLine(line, projectDir))
2690
+ ].filter(Boolean).join("\n");
2691
+ }
2692
+ __name(correctErrorStackTrace, "correctErrorStackTrace");
2693
+ function correctStackTraceLine(line, projectDir) {
2694
+ const regex = /at (.*?) \(?file:\/\/(\/.*?\.ts):(\d+):(\d+)\)?/;
2695
+ const match = regex.exec(line);
2696
+ if (!match) {
2697
+ return;
2698
+ }
2699
+ const [_, identifier, path, lineNum, colNum] = match;
2700
+ if (!path) {
2701
+ return;
2702
+ }
2703
+ if (nodePath__default.default.basename(path) === "__entryPoint.ts") {
2704
+ return;
2705
+ }
2706
+ if (projectDir && !path.includes(projectDir)) {
2707
+ return;
2708
+ }
2709
+ return line;
2710
+ }
2711
+ __name(correctStackTraceLine, "correctStackTraceLine");
2712
+ function groupTaskMetadataIssuesByTask(tasks, issues) {
2713
+ return issues.reduce((acc, issue) => {
2714
+ if (issue.path.length === 0) {
2715
+ return acc;
2716
+ }
2717
+ const taskIndex = issue.path[1];
2718
+ if (typeof taskIndex !== "number") {
2719
+ return acc;
2720
+ }
2721
+ const task = tasks[taskIndex];
2722
+ if (!task) {
2723
+ return acc;
2724
+ }
2725
+ const restOfPath = issue.path.slice(2);
2726
+ const taskId = task.id;
2727
+ const taskName = task.exportName;
2728
+ const filePath = task.filePath;
2729
+ const key = taskIndex;
2730
+ const existing = acc[key] ?? {
2731
+ id: taskId,
2732
+ exportName: taskName,
2733
+ filePath,
2734
+ issues: []
2735
+ };
2736
+ existing.issues.push({
2737
+ message: issue.message,
2738
+ path: restOfPath.length === 0 ? void 0 : restOfPath.join(".")
2739
+ });
2740
+ return {
2741
+ ...acc,
2742
+ [key]: existing
2743
+ };
2744
+ }, {});
2745
+ }
2746
+ __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
2747
+
2748
+ // src/v3/utils/platform.ts
2749
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
2750
+
2751
+ // src/v3/utils/globals.ts
2752
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
2753
+ var _global = _globalThis;
2754
+ function registerGlobal(type, instance, allowOverride = false) {
2755
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
2756
+ if (!allowOverride && api[type]) {
2757
+ return false;
2758
+ }
2759
+ api[type] = instance;
2760
+ return true;
2761
+ }
2762
+ __name(registerGlobal, "registerGlobal");
2763
+ function getGlobal(type) {
2764
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
2765
+ }
2766
+ __name(getGlobal, "getGlobal");
2767
+ function unregisterGlobal(type) {
606
2768
  const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
607
2769
  if (api) {
608
2770
  delete api[type];
@@ -614,6 +2776,11 @@ __name(unregisterGlobal, "unregisterGlobal");
614
2776
  var _NoopRuntimeManager = class _NoopRuntimeManager {
615
2777
  disable() {
616
2778
  }
2779
+ registerTasks() {
2780
+ }
2781
+ getTaskMetadata(id) {
2782
+ return void 0;
2783
+ }
617
2784
  waitForDuration(ms) {
618
2785
  return Promise.resolve();
619
2786
  }
@@ -621,7 +2788,20 @@ var _NoopRuntimeManager = class _NoopRuntimeManager {
621
2788
  return Promise.resolve();
622
2789
  }
623
2790
  waitForTask(params) {
624
- throw new Error("Method not implemented.");
2791
+ return Promise.resolve({
2792
+ ok: false,
2793
+ id: params.id,
2794
+ error: {
2795
+ type: "INTERNAL_ERROR",
2796
+ code: "CONFIGURED_INCORRECTLY"
2797
+ }
2798
+ });
2799
+ }
2800
+ waitForBatch(params) {
2801
+ return Promise.resolve({
2802
+ id: params.id,
2803
+ items: []
2804
+ });
625
2805
  }
626
2806
  };
627
2807
  __name(_NoopRuntimeManager, "NoopRuntimeManager");
@@ -650,6 +2830,9 @@ var _RuntimeAPI = class _RuntimeAPI {
650
2830
  waitForTask(params) {
651
2831
  return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
652
2832
  }
2833
+ waitForBatch(params) {
2834
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
2835
+ }
653
2836
  setGlobalRuntimeManager(runtimeManager) {
654
2837
  return registerGlobal(API_NAME, runtimeManager);
655
2838
  }
@@ -657,6 +2840,12 @@ var _RuntimeAPI = class _RuntimeAPI {
657
2840
  __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
658
2841
  unregisterGlobal(API_NAME);
659
2842
  }
2843
+ registerTasks(tasks) {
2844
+ __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).registerTasks(tasks);
2845
+ }
2846
+ getTaskMetadata(id) {
2847
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).getTaskMetadata(id);
2848
+ }
660
2849
  };
661
2850
  _getRuntimeManager = new WeakSet();
662
2851
  getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
@@ -667,58 +2856,159 @@ var RuntimeAPI = _RuntimeAPI;
667
2856
 
668
2857
  // src/v3/runtime-api.ts
669
2858
  var runtime = RuntimeAPI.getInstance();
2859
+ function iconStringForSeverity(severityNumber) {
2860
+ switch (severityNumber) {
2861
+ case apiLogs.SeverityNumber.UNSPECIFIED:
2862
+ return void 0;
2863
+ case apiLogs.SeverityNumber.TRACE:
2864
+ case apiLogs.SeverityNumber.TRACE2:
2865
+ case apiLogs.SeverityNumber.TRACE3:
2866
+ case apiLogs.SeverityNumber.TRACE4:
2867
+ return "trace";
2868
+ case apiLogs.SeverityNumber.DEBUG:
2869
+ case apiLogs.SeverityNumber.DEBUG2:
2870
+ case apiLogs.SeverityNumber.DEBUG3:
2871
+ case apiLogs.SeverityNumber.DEBUG4:
2872
+ return "debug";
2873
+ case apiLogs.SeverityNumber.INFO:
2874
+ case apiLogs.SeverityNumber.INFO2:
2875
+ case apiLogs.SeverityNumber.INFO3:
2876
+ case apiLogs.SeverityNumber.INFO4:
2877
+ return "info";
2878
+ case apiLogs.SeverityNumber.WARN:
2879
+ case apiLogs.SeverityNumber.WARN2:
2880
+ case apiLogs.SeverityNumber.WARN3:
2881
+ case apiLogs.SeverityNumber.WARN4:
2882
+ return "warn";
2883
+ case apiLogs.SeverityNumber.ERROR:
2884
+ case apiLogs.SeverityNumber.ERROR2:
2885
+ case apiLogs.SeverityNumber.ERROR3:
2886
+ case apiLogs.SeverityNumber.ERROR4:
2887
+ return "error";
2888
+ case apiLogs.SeverityNumber.FATAL:
2889
+ case apiLogs.SeverityNumber.FATAL2:
2890
+ case apiLogs.SeverityNumber.FATAL3:
2891
+ case apiLogs.SeverityNumber.FATAL4:
2892
+ return "fatal";
2893
+ }
2894
+ }
2895
+ __name(iconStringForSeverity, "iconStringForSeverity");
2896
+ var _SimpleClock = class _SimpleClock {
2897
+ preciseNow() {
2898
+ const now = new preciseDate.PreciseDate();
2899
+ const nowStruct = now.toStruct();
2900
+ return [
2901
+ nowStruct.seconds,
2902
+ nowStruct.nanos
2903
+ ];
2904
+ }
2905
+ reset() {
2906
+ }
2907
+ };
2908
+ __name(_SimpleClock, "SimpleClock");
2909
+ var SimpleClock = _SimpleClock;
2910
+
2911
+ // src/v3/clock/index.ts
2912
+ var API_NAME2 = "clock";
2913
+ var SIMPLE_CLOCK = new SimpleClock();
2914
+ var _getClock, getClock_fn;
2915
+ var _ClockAPI = class _ClockAPI {
2916
+ constructor() {
2917
+ __privateAdd(this, _getClock);
2918
+ }
2919
+ static getInstance() {
2920
+ if (!this._instance) {
2921
+ this._instance = new _ClockAPI();
2922
+ }
2923
+ return this._instance;
2924
+ }
2925
+ setGlobalClock(clock2) {
2926
+ return registerGlobal(API_NAME2, clock2);
2927
+ }
2928
+ preciseNow() {
2929
+ return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2930
+ }
2931
+ reset() {
2932
+ __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2933
+ }
2934
+ };
2935
+ _getClock = new WeakSet();
2936
+ getClock_fn = /* @__PURE__ */ __name(function() {
2937
+ return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2938
+ }, "#getClock");
2939
+ __name(_ClockAPI, "ClockAPI");
2940
+ var ClockAPI = _ClockAPI;
2941
+
2942
+ // src/v3/clock-api.ts
2943
+ var clock = ClockAPI.getInstance();
2944
+
2945
+ // src/v3/logger/taskLogger.ts
670
2946
  var logLevels = [
2947
+ "none",
671
2948
  "error",
672
2949
  "warn",
673
2950
  "log",
674
2951
  "info",
675
2952
  "debug"
676
2953
  ];
677
- var _emitLog, emitLog_fn;
2954
+ var _emitLog, emitLog_fn, _getTimestampInHrTime, getTimestampInHrTime_fn;
678
2955
  var _OtelTaskLogger = class _OtelTaskLogger {
679
2956
  constructor(_config) {
680
2957
  __privateAdd(this, _emitLog);
2958
+ __privateAdd(this, _getTimestampInHrTime);
681
2959
  this._config = _config;
682
2960
  this._level = logLevels.indexOf(_config.level);
683
2961
  }
684
2962
  debug(message, properties) {
685
- if (this._level < 4)
2963
+ if (this._level < 5)
686
2964
  return;
687
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "debug", apiLogs.SeverityNumber.DEBUG, properties);
2965
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "debug", apiLogs.SeverityNumber.DEBUG, properties);
688
2966
  }
689
2967
  log(message, properties) {
690
- if (this._level < 2)
2968
+ if (this._level < 3)
691
2969
  return;
692
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "log", apiLogs.SeverityNumber.INFO, properties);
2970
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "log", apiLogs.SeverityNumber.INFO, properties);
693
2971
  }
694
2972
  info(message, properties) {
695
- if (this._level < 3)
2973
+ if (this._level < 4)
696
2974
  return;
697
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "info", apiLogs.SeverityNumber.INFO, properties);
2975
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "info", apiLogs.SeverityNumber.INFO, properties);
698
2976
  }
699
2977
  warn(message, properties) {
700
- if (this._level < 1)
2978
+ if (this._level < 2)
701
2979
  return;
702
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "warn", apiLogs.SeverityNumber.WARN, properties);
2980
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "warn", apiLogs.SeverityNumber.WARN, properties);
703
2981
  }
704
2982
  error(message, properties) {
705
- if (this._level < 0)
2983
+ if (this._level < 1)
706
2984
  return;
707
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, "error", apiLogs.SeverityNumber.ERROR, properties);
2985
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "error", apiLogs.SeverityNumber.ERROR, properties);
2986
+ }
2987
+ trace(name, fn, options) {
2988
+ return this._config.tracer.startActiveSpan(name, fn, options);
708
2989
  }
709
2990
  };
710
2991
  _emitLog = new WeakSet();
711
- emitLog_fn = /* @__PURE__ */ __name(function(message, severityText, severityNumber, properties) {
2992
+ emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
2993
+ let attributes = {
2994
+ ...flattenAttributes(properties)
2995
+ };
2996
+ const icon = iconStringForSeverity(severityNumber);
2997
+ if (icon !== void 0) {
2998
+ attributes[SemanticInternalAttributes.STYLE_ICON] = icon;
2999
+ }
712
3000
  this._config.logger.emit({
713
3001
  severityNumber,
714
3002
  severityText,
715
3003
  body: message,
716
- attributes: {
717
- ...flattenAttributes(properties),
718
- "log.type": "logger"
719
- }
3004
+ attributes,
3005
+ timestamp
720
3006
  });
721
3007
  }, "#emitLog");
3008
+ _getTimestampInHrTime = new WeakSet();
3009
+ getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
3010
+ return clock.preciseNow();
3011
+ }, "#getTimestampInHrTime");
722
3012
  __name(_OtelTaskLogger, "OtelTaskLogger");
723
3013
  var OtelTaskLogger = _OtelTaskLogger;
724
3014
  var _NoopTaskLogger = class _NoopTaskLogger {
@@ -732,12 +3022,15 @@ var _NoopTaskLogger = class _NoopTaskLogger {
732
3022
  }
733
3023
  error() {
734
3024
  }
3025
+ trace(name, fn) {
3026
+ return fn({});
3027
+ }
735
3028
  };
736
3029
  __name(_NoopTaskLogger, "NoopTaskLogger");
737
3030
  var NoopTaskLogger = _NoopTaskLogger;
738
3031
 
739
3032
  // src/v3/logger/index.ts
740
- var API_NAME2 = "logger";
3033
+ var API_NAME3 = "logger";
741
3034
  var NOOP_TASK_LOGGER = new NoopTaskLogger();
742
3035
  var _getTaskLogger, getTaskLogger_fn;
743
3036
  var _LoggerAPI = class _LoggerAPI {
@@ -751,10 +3044,10 @@ var _LoggerAPI = class _LoggerAPI {
751
3044
  return this._instance;
752
3045
  }
753
3046
  disable() {
754
- unregisterGlobal(API_NAME2);
3047
+ unregisterGlobal(API_NAME3);
755
3048
  }
756
3049
  setGlobalTaskLogger(taskLogger) {
757
- return registerGlobal(API_NAME2, taskLogger);
3050
+ return registerGlobal(API_NAME3, taskLogger);
758
3051
  }
759
3052
  debug(message, metadata) {
760
3053
  __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).debug(message, metadata);
@@ -771,10 +3064,13 @@ var _LoggerAPI = class _LoggerAPI {
771
3064
  error(message, metadata) {
772
3065
  __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).error(message, metadata);
773
3066
  }
3067
+ trace(name, fn) {
3068
+ return __privateMethod(this, _getTaskLogger, getTaskLogger_fn).call(this).trace(name, fn);
3069
+ }
774
3070
  };
775
3071
  _getTaskLogger = new WeakSet();
776
3072
  getTaskLogger_fn = /* @__PURE__ */ __name(function() {
777
- return getGlobal(API_NAME2) ?? NOOP_TASK_LOGGER;
3073
+ return getGlobal(API_NAME3) ?? NOOP_TASK_LOGGER;
778
3074
  }, "#getTaskLogger");
779
3075
  __name(_LoggerAPI, "LoggerAPI");
780
3076
  var LoggerAPI = _LoggerAPI;
@@ -782,47 +3078,145 @@ var LoggerAPI = _LoggerAPI;
782
3078
  // src/v3/logger-api.ts
783
3079
  var logger = LoggerAPI.getInstance();
784
3080
 
785
- // src/v3/semanticInternalAttributes.ts
786
- var SemanticInternalAttributes = {
787
- ENVIRONMENT_ID: "ctx.environment.id",
788
- ENVIRONMENT_TYPE: "ctx.environment.type",
789
- ORGANIZATION_ID: "ctx.organization.id",
790
- PROJECT_ID: "ctx.project.id",
791
- PROJECT_REF: "ctx.project.ref",
792
- ATTEMPT_ID: "ctx.attempt.id",
793
- ATTEMP_NUMBER: "ctx.attempt.number",
794
- RUN_ID: "ctx.run.id",
795
- TASK_SLUG: "ctx.task.id",
796
- TASK_PATH: "ctx.task.filePath",
797
- TASK_EXPORT_NAME: "ctx.task.exportName",
798
- SPAN_PARTIAL: "$span.partial",
799
- SPAN_ID: "$span.span_id",
800
- OUTPUT: "$output",
801
- STYLE: "$style",
802
- STYLE_ICON: "$style.icon",
803
- METADATA: "$metadata",
804
- TRIGGER: "$trigger",
805
- PAYLOAD: "$payload",
806
- WORKER_ID: "worker.id",
807
- WORKER_VERSION: "worker.version",
808
- CLI_VERSION: "cli.version",
809
- SDK_VERSION: "sdk.version",
810
- SDK_LANGUAGE: "sdk.language"
811
- };
3081
+ // src/v3/limits.ts
3082
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
3083
+ var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
3084
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
3085
+ var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
3086
+ var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
3087
+ var OTEL_LINK_COUNT_LIMIT = 2;
3088
+ var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
3089
+ var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
3090
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
3091
+ function imposeAttributeLimits(attributes) {
3092
+ const newAttributes = {};
3093
+ for (const [key, value] of Object.entries(attributes)) {
3094
+ if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
3095
+ continue;
3096
+ }
3097
+ if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
3098
+ break;
3099
+ }
3100
+ newAttributes[key] = value;
3101
+ }
3102
+ return newAttributes;
3103
+ }
3104
+ __name(imposeAttributeLimits, "imposeAttributeLimits");
3105
+ function calculateAttributeValueLength(value) {
3106
+ if (value === void 0 || value === null) {
3107
+ return 0;
3108
+ }
3109
+ if (typeof value === "string") {
3110
+ return value.length;
3111
+ }
3112
+ if (typeof value === "number") {
3113
+ return 8;
3114
+ }
3115
+ if (typeof value === "boolean") {
3116
+ return 4;
3117
+ }
3118
+ if (Array.isArray(value)) {
3119
+ return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
3120
+ }
3121
+ return 0;
3122
+ }
3123
+ __name(calculateAttributeValueLength, "calculateAttributeValueLength");
3124
+ function dateDifference(date1, date2) {
3125
+ return Math.abs(date1.getTime() - date2.getTime());
3126
+ }
3127
+ __name(dateDifference, "dateDifference");
3128
+ function formatDuration(start, end, options) {
3129
+ if (!start || !end) {
3130
+ return "\u2013";
3131
+ }
3132
+ return formatDurationMilliseconds(dateDifference(start, end), options);
3133
+ }
3134
+ __name(formatDuration, "formatDuration");
3135
+ function nanosecondsToMilliseconds(nanoseconds) {
3136
+ return nanoseconds / 1e6;
3137
+ }
3138
+ __name(nanosecondsToMilliseconds, "nanosecondsToMilliseconds");
3139
+ function millisecondsToNanoseconds(milliseconds) {
3140
+ return milliseconds * 1e6;
3141
+ }
3142
+ __name(millisecondsToNanoseconds, "millisecondsToNanoseconds");
3143
+ function formatDurationNanoseconds(nanoseconds, options) {
3144
+ return formatDurationMilliseconds(nanosecondsToMilliseconds(nanoseconds), options);
3145
+ }
3146
+ __name(formatDurationNanoseconds, "formatDurationNanoseconds");
3147
+ var aboveOneSecondUnits = [
3148
+ "d",
3149
+ "h",
3150
+ "m",
3151
+ "s"
3152
+ ];
3153
+ var belowOneSecondUnits = [
3154
+ "ms"
3155
+ ];
3156
+ function formatDurationMilliseconds(milliseconds, options) {
3157
+ let duration = humanizeDuration__default.default(milliseconds, {
3158
+ units: options?.units ? options.units : milliseconds < 1e3 ? belowOneSecondUnits : aboveOneSecondUnits,
3159
+ maxDecimalPoints: options?.maxDecimalPoints ?? 1,
3160
+ largest: 2
3161
+ });
3162
+ if (!options) {
3163
+ return duration;
3164
+ }
3165
+ switch (options.style) {
3166
+ case "short":
3167
+ duration = duration.replace(" milliseconds", "ms");
3168
+ duration = duration.replace(" millisecond", "ms");
3169
+ duration = duration.replace(" seconds", "s");
3170
+ duration = duration.replace(" second", "s");
3171
+ duration = duration.replace(" minutes", "m");
3172
+ duration = duration.replace(" minute", "m");
3173
+ duration = duration.replace(" hours", "h");
3174
+ duration = duration.replace(" hour", "h");
3175
+ duration = duration.replace(" days", "d");
3176
+ duration = duration.replace(" day", "d");
3177
+ duration = duration.replace(" weeks", "w");
3178
+ duration = duration.replace(" week", "w");
3179
+ duration = duration.replace(" months", "mo");
3180
+ duration = duration.replace(" month", "mo");
3181
+ duration = duration.replace(" years", "y");
3182
+ duration = duration.replace(" year", "y");
3183
+ }
3184
+ return duration;
3185
+ }
3186
+ __name(formatDurationMilliseconds, "formatDurationMilliseconds");
3187
+ function formatDurationInDays(milliseconds) {
3188
+ let duration = humanizeDuration__default.default(milliseconds, {
3189
+ maxDecimalPoints: 0,
3190
+ largest: 2,
3191
+ units: [
3192
+ "d"
3193
+ ]
3194
+ });
3195
+ return duration;
3196
+ }
3197
+ __name(formatDurationInDays, "formatDurationInDays");
812
3198
 
813
3199
  // src/v3/runtime/devRuntimeManager.ts
814
3200
  var _DevRuntimeManager = class _DevRuntimeManager {
815
- constructor(options) {
816
- this.options = options;
817
- this._taskWaits = /* @__PURE__ */ new Map();
3201
+ constructor() {
3202
+ __publicField(this, "_taskWaits", /* @__PURE__ */ new Map());
3203
+ __publicField(this, "_batchWaits", /* @__PURE__ */ new Map());
3204
+ __publicField(this, "_tasks", /* @__PURE__ */ new Map());
3205
+ __publicField(this, "_pendingCompletionNotifications", /* @__PURE__ */ new Map());
818
3206
  }
819
3207
  disable() {
820
3208
  }
3209
+ registerTasks(tasks) {
3210
+ for (const task of tasks) {
3211
+ this._tasks.set(task.id, task);
3212
+ }
3213
+ }
3214
+ getTaskMetadata(id) {
3215
+ return this._tasks.get(id);
3216
+ }
821
3217
  async waitForDuration(ms) {
822
- return this.options.tracer.startActiveSpan("wait for duration", async (span) => {
823
- return new Promise((resolve) => {
824
- setTimeout(resolve, ms);
825
- });
3218
+ return new Promise((resolve) => {
3219
+ setTimeout(resolve, ms);
826
3220
  });
827
3221
  }
828
3222
  async waitUntil(date) {
@@ -831,27 +3225,215 @@ var _DevRuntimeManager = class _DevRuntimeManager {
831
3225
  });
832
3226
  }
833
3227
  async waitForTask(params) {
834
- return this.options.tracer.startActiveSpan("wait for task", async (span) => {
835
- span.setAttribute("trigger.task.run.id", params.id);
836
- const promise = new Promise((resolve, reject) => {
837
- this._taskWaits.set(params.id, {
3228
+ const pendingCompletion = this._pendingCompletionNotifications.get(params.id);
3229
+ if (pendingCompletion) {
3230
+ this._pendingCompletionNotifications.delete(params.id);
3231
+ return pendingCompletion;
3232
+ }
3233
+ const promise = new Promise((resolve, reject) => {
3234
+ this._taskWaits.set(params.id, {
3235
+ resolve,
3236
+ reject
3237
+ });
3238
+ });
3239
+ return await promise;
3240
+ }
3241
+ async waitForBatch(params) {
3242
+ if (!params.runs.length) {
3243
+ return Promise.resolve({
3244
+ id: params.id,
3245
+ items: []
3246
+ });
3247
+ }
3248
+ const promise = Promise.all(params.runs.map((runId) => {
3249
+ return new Promise((resolve, reject) => {
3250
+ const pendingCompletion = this._pendingCompletionNotifications.get(runId);
3251
+ if (pendingCompletion) {
3252
+ this._pendingCompletionNotifications.delete(runId);
3253
+ if (pendingCompletion.ok) {
3254
+ resolve(pendingCompletion);
3255
+ } else {
3256
+ reject(pendingCompletion);
3257
+ }
3258
+ return;
3259
+ }
3260
+ this._taskWaits.set(runId, {
838
3261
  resolve,
839
3262
  reject
840
3263
  });
841
3264
  });
842
- return await promise;
843
- });
3265
+ }));
3266
+ const results = await promise;
3267
+ return {
3268
+ id: params.id,
3269
+ items: results
3270
+ };
844
3271
  }
845
3272
  resumeTask(completion, execution) {
846
3273
  const wait = this._taskWaits.get(execution.run.id);
847
- if (wait) {
3274
+ if (!wait) {
3275
+ this._pendingCompletionNotifications.set(execution.run.id, completion);
3276
+ return;
3277
+ }
3278
+ if (completion.ok) {
848
3279
  wait.resolve(completion);
849
- this._taskWaits.delete(execution.run.id);
3280
+ } else {
3281
+ wait.reject(completion);
850
3282
  }
3283
+ this._taskWaits.delete(execution.run.id);
851
3284
  }
852
3285
  };
853
3286
  __name(_DevRuntimeManager, "DevRuntimeManager");
854
3287
  var DevRuntimeManager = _DevRuntimeManager;
3288
+ var _ProdRuntimeManager = class _ProdRuntimeManager {
3289
+ constructor(ipc, options = {}) {
3290
+ this.ipc = ipc;
3291
+ this.options = options;
3292
+ this._taskWaits = /* @__PURE__ */ new Map();
3293
+ this._batchWaits = /* @__PURE__ */ new Map();
3294
+ this._tasks = /* @__PURE__ */ new Map();
3295
+ }
3296
+ disable() {
3297
+ }
3298
+ registerTasks(tasks) {
3299
+ for (const task of tasks) {
3300
+ this._tasks.set(task.id, task);
3301
+ }
3302
+ }
3303
+ getTaskMetadata(id) {
3304
+ return this._tasks.get(id);
3305
+ }
3306
+ async waitForDuration(ms) {
3307
+ const now = Date.now();
3308
+ const resolveAfterDuration = promises.setTimeout(ms, "duration");
3309
+ if (ms <= this.waitThresholdInMs) {
3310
+ await resolveAfterDuration;
3311
+ return;
3312
+ }
3313
+ const waitForRestore = new Promise((resolve, reject) => {
3314
+ this._waitForRestore = {
3315
+ resolve,
3316
+ reject
3317
+ };
3318
+ });
3319
+ const { willCheckpointAndRestore } = await this.ipc.sendWithAck("WAIT_FOR_DURATION", {
3320
+ ms,
3321
+ now
3322
+ });
3323
+ if (!willCheckpointAndRestore) {
3324
+ await resolveAfterDuration;
3325
+ return;
3326
+ }
3327
+ this.ipc.send("READY_FOR_CHECKPOINT", {});
3328
+ await Promise.race([
3329
+ waitForRestore,
3330
+ resolveAfterDuration
3331
+ ]);
3332
+ this.ipc.send("CANCEL_CHECKPOINT", {});
3333
+ }
3334
+ resumeAfterRestore() {
3335
+ if (!this._waitForRestore) {
3336
+ return;
3337
+ }
3338
+ clock.reset();
3339
+ this._waitForRestore.resolve("restore");
3340
+ this._waitForRestore = void 0;
3341
+ }
3342
+ async waitUntil(date) {
3343
+ return this.waitForDuration(date.getTime() - Date.now());
3344
+ }
3345
+ async waitForTask(params) {
3346
+ const promise = new Promise((resolve, reject) => {
3347
+ this._taskWaits.set(params.id, {
3348
+ resolve,
3349
+ reject
3350
+ });
3351
+ });
3352
+ await this.ipc.send("WAIT_FOR_TASK", {
3353
+ friendlyId: params.id
3354
+ });
3355
+ return await promise;
3356
+ }
3357
+ async waitForBatch(params) {
3358
+ if (!params.runs.length) {
3359
+ return Promise.resolve({
3360
+ id: params.id,
3361
+ items: []
3362
+ });
3363
+ }
3364
+ const promise = Promise.all(params.runs.map((runId) => {
3365
+ return new Promise((resolve, reject) => {
3366
+ this._taskWaits.set(runId, {
3367
+ resolve,
3368
+ reject
3369
+ });
3370
+ });
3371
+ }));
3372
+ await this.ipc.send("WAIT_FOR_BATCH", {
3373
+ batchFriendlyId: params.id,
3374
+ runFriendlyIds: params.runs
3375
+ });
3376
+ const results = await promise;
3377
+ return {
3378
+ id: params.id,
3379
+ items: results
3380
+ };
3381
+ }
3382
+ resumeTask(completion, execution) {
3383
+ const wait = this._taskWaits.get(execution.run.id);
3384
+ if (!wait) {
3385
+ return;
3386
+ }
3387
+ if (completion.ok) {
3388
+ wait.resolve(completion);
3389
+ } else {
3390
+ wait.reject(completion);
3391
+ }
3392
+ this._taskWaits.delete(execution.run.id);
3393
+ }
3394
+ get waitThresholdInMs() {
3395
+ return this.options.waitThresholdInMs ?? 3e4;
3396
+ }
3397
+ };
3398
+ __name(_ProdRuntimeManager, "ProdRuntimeManager");
3399
+ var ProdRuntimeManager = _ProdRuntimeManager;
3400
+ var _originClockTime, originClockTime_get, _originPreciseDate, originPreciseDate_get;
3401
+ var _PreciseWallClock = class _PreciseWallClock {
3402
+ constructor(options = {}) {
3403
+ __privateAdd(this, _originClockTime);
3404
+ __privateAdd(this, _originPreciseDate);
3405
+ this._origin = {
3406
+ clockTime: options.origin ?? process.hrtime(),
3407
+ preciseDate: options.now ?? new preciseDate.PreciseDate()
3408
+ };
3409
+ }
3410
+ preciseNow() {
3411
+ const elapsedHrTime = process.hrtime(__privateGet(this, _originClockTime, originClockTime_get));
3412
+ const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
3413
+ const preciseDate$1 = new preciseDate.PreciseDate(__privateGet(this, _originPreciseDate, originPreciseDate_get).getFullTime() + elapsedNanoseconds);
3414
+ const dateStruct = preciseDate$1.toStruct();
3415
+ return [
3416
+ dateStruct.seconds,
3417
+ dateStruct.nanos
3418
+ ];
3419
+ }
3420
+ reset() {
3421
+ this._origin = {
3422
+ clockTime: process.hrtime(),
3423
+ preciseDate: new preciseDate.PreciseDate()
3424
+ };
3425
+ }
3426
+ };
3427
+ _originClockTime = new WeakSet();
3428
+ originClockTime_get = /* @__PURE__ */ __name(function() {
3429
+ return this._origin.clockTime;
3430
+ }, "#originClockTime");
3431
+ _originPreciseDate = new WeakSet();
3432
+ originPreciseDate_get = /* @__PURE__ */ __name(function() {
3433
+ return this._origin.preciseDate;
3434
+ }, "#originPreciseDate");
3435
+ __name(_PreciseWallClock, "PreciseWallClock");
3436
+ var PreciseWallClock = _PreciseWallClock;
855
3437
  var _TriggerTracer = class _TriggerTracer {
856
3438
  constructor(_config) {
857
3439
  this._config = _config;
@@ -880,7 +3462,8 @@ var _TriggerTracer = class _TriggerTracer {
880
3462
  const attributes = options?.attributes ?? {};
881
3463
  return this.tracer.startActiveSpan(name, {
882
3464
  ...options,
883
- attributes
3465
+ attributes,
3466
+ startTime: clock.preciseNow()
884
3467
  }, parentContext, async (span) => {
885
3468
  this.tracer.startSpan(name, {
886
3469
  ...options,
@@ -901,57 +3484,72 @@ var _TriggerTracer = class _TriggerTracer {
901
3484
  });
902
3485
  throw e;
903
3486
  } finally {
904
- span.end();
3487
+ span.end(clock.preciseNow());
3488
+ }
3489
+ });
3490
+ }
3491
+ startSpan(name, options, ctx) {
3492
+ const parentContext = ctx ?? api.context.active();
3493
+ const attributes = options?.attributes ?? {};
3494
+ const span = this.tracer.startSpan(name, options, ctx);
3495
+ this.tracer.startSpan(name, {
3496
+ ...options,
3497
+ attributes: {
3498
+ ...attributes,
3499
+ [SemanticInternalAttributes.SPAN_PARTIAL]: true,
3500
+ [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
905
3501
  }
906
- });
3502
+ }, parentContext).end();
3503
+ return span;
907
3504
  }
908
3505
  };
909
3506
  __name(_TriggerTracer, "TriggerTracer");
910
3507
  var TriggerTracer = _TriggerTracer;
911
- var _handleLog, handleLog_fn, _getAttributes, getAttributes_fn;
3508
+ var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
912
3509
  var _ConsoleInterceptor = class _ConsoleInterceptor {
913
3510
  constructor(logger2) {
914
3511
  __privateAdd(this, _handleLog);
3512
+ __privateAdd(this, _getTimestampInHrTime2);
915
3513
  __privateAdd(this, _getAttributes);
916
3514
  this.logger = logger2;
917
3515
  }
918
3516
  // Intercept the console and send logs to the OpenTelemetry logger
919
3517
  // during the execution of the callback
920
- async intercept(console, callback) {
3518
+ async intercept(console2, callback) {
921
3519
  const originalConsole = {
922
- log: console.log,
923
- info: console.info,
924
- warn: console.warn,
925
- error: console.error
3520
+ log: console2.log,
3521
+ info: console2.info,
3522
+ warn: console2.warn,
3523
+ error: console2.error
926
3524
  };
927
- console.log = this.log.bind(this);
928
- console.info = this.info.bind(this);
929
- console.warn = this.warn.bind(this);
930
- console.error = this.error.bind(this);
3525
+ console2.log = this.log.bind(this);
3526
+ console2.info = this.info.bind(this);
3527
+ console2.warn = this.warn.bind(this);
3528
+ console2.error = this.error.bind(this);
931
3529
  try {
932
3530
  return await callback();
933
3531
  } finally {
934
- console.log = originalConsole.log;
935
- console.info = originalConsole.info;
936
- console.warn = originalConsole.warn;
937
- console.error = originalConsole.error;
3532
+ console2.log = originalConsole.log;
3533
+ console2.info = originalConsole.info;
3534
+ console2.warn = originalConsole.warn;
3535
+ console2.error = originalConsole.error;
938
3536
  }
939
3537
  }
940
3538
  log(...args) {
941
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, "Log", ...args);
3539
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
942
3540
  }
943
3541
  info(...args) {
944
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, "Info", ...args);
3542
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Info", ...args);
945
3543
  }
946
3544
  warn(...args) {
947
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.WARN, "Warn", ...args);
3545
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.WARN, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Warn", ...args);
948
3546
  }
949
3547
  error(...args) {
950
- __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.ERROR, "Error", ...args);
3548
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, apiLogs.SeverityNumber.ERROR, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Error", ...args);
951
3549
  }
952
3550
  };
953
3551
  _handleLog = new WeakSet();
954
- handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, severityText, ...args) {
3552
+ handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
955
3553
  const body = util__default.default.format(...args);
956
3554
  const parsed = tryParseJSON(body);
957
3555
  if (parsed.ok) {
@@ -960,9 +3558,10 @@ handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, severityText, ...
960
3558
  severityText,
961
3559
  body: getLogMessage(parsed.value, severityText),
962
3560
  attributes: {
963
- ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this),
3561
+ ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
964
3562
  ...flattenAttributes(parsed.value)
965
- }
3563
+ },
3564
+ timestamp
966
3565
  });
967
3566
  return;
968
3567
  }
@@ -970,14 +3569,22 @@ handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, severityText, ...
970
3569
  severityNumber,
971
3570
  severityText,
972
3571
  body,
973
- attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this)
3572
+ attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3573
+ timestamp
974
3574
  });
975
3575
  }, "#handleLog");
3576
+ _getTimestampInHrTime2 = new WeakSet();
3577
+ getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
3578
+ return clock.preciseNow();
3579
+ }, "#getTimestampInHrTime");
976
3580
  _getAttributes = new WeakSet();
977
- getAttributes_fn = /* @__PURE__ */ __name(function() {
978
- return {
979
- "log.type": "console"
980
- };
3581
+ getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
3582
+ const icon = iconStringForSeverity(severityNumber1);
3583
+ let result = {};
3584
+ if (icon !== void 0) {
3585
+ result[SemanticInternalAttributes.STYLE_ICON] = icon;
3586
+ }
3587
+ return result;
981
3588
  }, "#getAttributes");
982
3589
  __name(_ConsoleInterceptor, "ConsoleInterceptor");
983
3590
  var ConsoleInterceptor = _ConsoleInterceptor;
@@ -1019,28 +3626,1077 @@ function tryParseJSON(value) {
1019
3626
  }
1020
3627
  __name(tryParseJSON, "tryParseJSON");
1021
3628
 
3629
+ // src/retry.ts
3630
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
3631
+ if (!resets)
3632
+ return;
3633
+ switch (format) {
3634
+ case "iso_8601_duration_openai_variant": {
3635
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
3636
+ }
3637
+ case "iso_8601": {
3638
+ return calculateISO8601ResetAt(resets, now);
3639
+ }
3640
+ case "unix_timestamp": {
3641
+ return calculateUnixTimestampResetAt(resets, now);
3642
+ }
3643
+ case "unix_timestamp_in_ms": {
3644
+ return calculateUnixTimestampInMsResetAt(resets, now);
3645
+ }
3646
+ }
3647
+ }
3648
+ __name(calculateResetAt, "calculateResetAt");
3649
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
3650
+ if (!resets)
3651
+ return void 0;
3652
+ const resetAt = parseInt(resets, 10);
3653
+ if (isNaN(resetAt))
3654
+ return void 0;
3655
+ return new Date(resetAt * 1e3);
3656
+ }
3657
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
3658
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
3659
+ if (!resets)
3660
+ return void 0;
3661
+ const resetAt = parseInt(resets, 10);
3662
+ if (isNaN(resetAt))
3663
+ return void 0;
3664
+ return new Date(resetAt);
3665
+ }
3666
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
3667
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
3668
+ if (!resets)
3669
+ return void 0;
3670
+ const resetAt = new Date(resets);
3671
+ if (isNaN(resetAt.getTime()))
3672
+ return void 0;
3673
+ return resetAt;
3674
+ }
3675
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
3676
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
3677
+ if (!resets)
3678
+ return void 0;
3679
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
3680
+ const match = resets.match(pattern);
3681
+ if (!match)
3682
+ return void 0;
3683
+ const days = parseInt(match[1], 10) || 0;
3684
+ const hours = parseInt(match[2], 10) || 0;
3685
+ const minutes = parseInt(match[3], 10) || 0;
3686
+ const seconds = parseFloat(match[4]) || 0;
3687
+ const milliseconds = parseInt(match[5], 10) || 0;
3688
+ const resetAt = new Date(now);
3689
+ resetAt.setDate(resetAt.getDate() + days);
3690
+ resetAt.setHours(resetAt.getHours() + hours);
3691
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
3692
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
3693
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
3694
+ return resetAt;
3695
+ }
3696
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
3697
+
3698
+ // src/v3/utils/retries.ts
3699
+ var defaultRetryOptions = {
3700
+ maxAttempts: 3,
3701
+ factor: 2,
3702
+ minTimeoutInMs: 1e3,
3703
+ maxTimeoutInMs: 6e4,
3704
+ randomize: true
3705
+ };
3706
+ var defaultFetchRetryOptions = {
3707
+ byStatus: {
3708
+ "429,408,409,5xx": {
3709
+ strategy: "backoff",
3710
+ ...defaultRetryOptions
3711
+ }
3712
+ },
3713
+ connectionError: defaultRetryOptions,
3714
+ timeout: defaultRetryOptions
3715
+ };
3716
+ function calculateNextRetryDelay(options, attempt) {
3717
+ const opts = {
3718
+ ...defaultRetryOptions,
3719
+ ...options
3720
+ };
3721
+ if (attempt >= opts.maxAttempts) {
3722
+ return;
3723
+ }
3724
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
3725
+ const random = randomize ? Math.random() + 1 : 1;
3726
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
3727
+ return Math.round(timeout);
3728
+ }
3729
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
3730
+ function calculateResetAt2(resets, format, now = Date.now()) {
3731
+ const resetAt = calculateResetAt(resets, format, new Date(now));
3732
+ return resetAt?.getTime();
3733
+ }
3734
+ __name(calculateResetAt2, "calculateResetAt");
3735
+
3736
+ // src/v3/utils/styleAttributes.ts
3737
+ function accessoryAttributes(accessory) {
3738
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
3739
+ }
3740
+ __name(accessoryAttributes, "accessoryAttributes");
3741
+
3742
+ // src/eventFilterMatches.ts
3743
+ function eventFilterMatches(payload, filter) {
3744
+ if (payload === void 0 || payload === null) {
3745
+ if (Object.entries(filter).length === 0) {
3746
+ return true;
3747
+ } else {
3748
+ return false;
3749
+ }
3750
+ }
3751
+ for (const [patternKey, patternValue] of Object.entries(filter)) {
3752
+ const payloadValue = payload[patternKey];
3753
+ if (Array.isArray(patternValue)) {
3754
+ if (patternValue.length === 0) {
3755
+ continue;
3756
+ }
3757
+ if (patternValue.every((item) => typeof item === "string")) {
3758
+ if (patternValue.includes(payloadValue)) {
3759
+ continue;
3760
+ }
3761
+ return false;
3762
+ }
3763
+ if (patternValue.every((item) => typeof item === "number")) {
3764
+ if (patternValue.includes(payloadValue)) {
3765
+ continue;
3766
+ }
3767
+ return false;
3768
+ }
3769
+ if (patternValue.every((item) => typeof item === "boolean")) {
3770
+ if (patternValue.includes(payloadValue)) {
3771
+ continue;
3772
+ }
3773
+ return false;
3774
+ }
3775
+ const objectArray = patternValue;
3776
+ if (!contentFiltersMatches(payloadValue, objectArray)) {
3777
+ return false;
3778
+ }
3779
+ continue;
3780
+ } else if (typeof patternValue === "object") {
3781
+ if (Array.isArray(payloadValue)) {
3782
+ if (!payloadValue.some((item) => eventFilterMatches(item, patternValue))) {
3783
+ return false;
3784
+ }
3785
+ } else {
3786
+ if (!eventFilterMatches(payloadValue, patternValue)) {
3787
+ return false;
3788
+ }
3789
+ }
3790
+ }
3791
+ }
3792
+ return true;
3793
+ }
3794
+ __name(eventFilterMatches, "eventFilterMatches");
3795
+ function contentFiltersMatches(actualValue, contentFilters) {
3796
+ for (const contentFilter of contentFilters) {
3797
+ if (typeof contentFilter === "object") {
3798
+ Object.entries(contentFilter)[0];
3799
+ if (!contentFilterMatches(actualValue, contentFilter)) {
3800
+ return false;
3801
+ }
3802
+ }
3803
+ }
3804
+ return true;
3805
+ }
3806
+ __name(contentFiltersMatches, "contentFiltersMatches");
3807
+ function contentFilterMatches(actualValue, contentFilter) {
3808
+ if ("$endsWith" in contentFilter) {
3809
+ if (typeof actualValue !== "string") {
3810
+ return false;
3811
+ }
3812
+ return actualValue.endsWith(contentFilter.$endsWith);
3813
+ }
3814
+ if ("$startsWith" in contentFilter) {
3815
+ if (typeof actualValue !== "string") {
3816
+ return false;
3817
+ }
3818
+ return actualValue.startsWith(contentFilter.$startsWith);
3819
+ }
3820
+ if ("$anythingBut" in contentFilter) {
3821
+ if (Array.isArray(contentFilter.$anythingBut)) {
3822
+ if (contentFilter.$anythingBut.includes(actualValue)) {
3823
+ return false;
3824
+ }
3825
+ }
3826
+ if (contentFilter.$anythingBut === actualValue) {
3827
+ return false;
3828
+ }
3829
+ return true;
3830
+ }
3831
+ if ("$exists" in contentFilter) {
3832
+ if (contentFilter.$exists) {
3833
+ return actualValue !== void 0;
3834
+ }
3835
+ return actualValue === void 0;
3836
+ }
3837
+ if ("$gt" in contentFilter) {
3838
+ if (typeof actualValue !== "number") {
3839
+ return false;
3840
+ }
3841
+ return actualValue > contentFilter.$gt;
3842
+ }
3843
+ if ("$lt" in contentFilter) {
3844
+ if (typeof actualValue !== "number") {
3845
+ return false;
3846
+ }
3847
+ return actualValue < contentFilter.$lt;
3848
+ }
3849
+ if ("$gte" in contentFilter) {
3850
+ if (typeof actualValue !== "number") {
3851
+ return false;
3852
+ }
3853
+ return actualValue >= contentFilter.$gte;
3854
+ }
3855
+ if ("$lte" in contentFilter) {
3856
+ if (typeof actualValue !== "number") {
3857
+ return false;
3858
+ }
3859
+ return actualValue <= contentFilter.$lte;
3860
+ }
3861
+ if ("$between" in contentFilter) {
3862
+ if (typeof actualValue !== "number") {
3863
+ return false;
3864
+ }
3865
+ return actualValue >= contentFilter.$between[0] && actualValue <= contentFilter.$between[1];
3866
+ }
3867
+ if ("$includes" in contentFilter) {
3868
+ if (Array.isArray(actualValue)) {
3869
+ return actualValue.includes(contentFilter.$includes);
3870
+ }
3871
+ return false;
3872
+ }
3873
+ if ("$ignoreCaseEquals" in contentFilter) {
3874
+ if (typeof actualValue !== "string") {
3875
+ return false;
3876
+ }
3877
+ return actualValue.localeCompare(contentFilter.$ignoreCaseEquals, void 0, {
3878
+ sensitivity: "accent"
3879
+ }) === 0;
3880
+ }
3881
+ if ("$isNull" in contentFilter) {
3882
+ if (contentFilter.$isNull) {
3883
+ return actualValue === null;
3884
+ }
3885
+ return actualValue !== null;
3886
+ }
3887
+ if ("$not" in contentFilter) {
3888
+ if (Array.isArray(actualValue)) {
3889
+ return !actualValue.includes(contentFilter.$not);
3890
+ } else if (typeof actualValue === "number" || typeof actualValue === "boolean" || typeof actualValue === "string") {
3891
+ return actualValue !== contentFilter.$not;
3892
+ }
3893
+ return false;
3894
+ }
3895
+ return true;
3896
+ }
3897
+ __name(contentFilterMatches, "contentFilterMatches");
3898
+
3899
+ // src/v3/utils/omit.ts
3900
+ function omit(obj, ...keys) {
3901
+ const result = {};
3902
+ for (const key in obj) {
3903
+ if (!keys.includes(key)) {
3904
+ result[key] = obj[key];
3905
+ }
3906
+ }
3907
+ return result;
3908
+ }
3909
+ __name(omit, "omit");
3910
+ var _a2;
3911
+ var AsyncResourceDetector = (_a2 = class {
3912
+ constructor() {
3913
+ __publicField(this, "_resolved", false);
3914
+ this._promise = new Promise((resolver) => {
3915
+ this._resolver = resolver;
3916
+ });
3917
+ }
3918
+ detect(_config) {
3919
+ return new resources.Resource({}, this._promise);
3920
+ }
3921
+ resolveWithAttributes(attributes) {
3922
+ if (!this._resolver) {
3923
+ throw new Error("Resolver not available");
3924
+ }
3925
+ if (this._resolved) {
3926
+ return;
3927
+ }
3928
+ this._resolved = true;
3929
+ this._resolver(attributes);
3930
+ }
3931
+ }, __name(_a2, "AsyncResourceDetector"), _a2);
3932
+ var _TracingSDK = class _TracingSDK {
3933
+ constructor(config) {
3934
+ this.config = config;
3935
+ this.asyncResourceDetector = new AsyncResourceDetector();
3936
+ setLogLevel(config.diagLogLevel ?? "none");
3937
+ const envResourceAttributesSerialized = getEnvVar("OTEL_RESOURCE_ATTRIBUTES");
3938
+ const envResourceAttributes = envResourceAttributesSerialized ? JSON.parse(envResourceAttributesSerialized) : {};
3939
+ const commonResources = resources.detectResourcesSync({
3940
+ detectors: [
3941
+ this.asyncResourceDetector,
3942
+ resources.processDetectorSync
3943
+ ]
3944
+ }).merge(new resources.Resource({
3945
+ [semanticConventions.SemanticResourceAttributes.CLOUD_PROVIDER]: "trigger.dev",
3946
+ [SemanticInternalAttributes.TRIGGER]: true
3947
+ })).merge(config.resource ?? new resources.Resource({})).merge(new resources.Resource(envResourceAttributes));
3948
+ const traceProvider = new sdkTraceNode.NodeTracerProvider({
3949
+ forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
3950
+ resource: commonResources,
3951
+ spanLimits: {
3952
+ attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
3953
+ attributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
3954
+ eventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT,
3955
+ attributePerEventCountLimit: OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
3956
+ linkCountLimit: OTEL_LINK_COUNT_LIMIT,
3957
+ attributePerLinkCountLimit: OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT
3958
+ }
3959
+ });
3960
+ const spanExporter = new exporterTraceOtlpHttp.OTLPTraceExporter({
3961
+ url: `${config.url}/v1/traces`,
3962
+ timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
3963
+ });
3964
+ traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkTraceNode.BatchSpanProcessor(spanExporter, {
3965
+ maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
3966
+ scheduledDelayMillis: parseInt(getEnvVar("OTEL_SPAN_SCHEDULED_DELAY_MILLIS") ?? "200"),
3967
+ exportTimeoutMillis: parseInt(getEnvVar("OTEL_SPAN_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
3968
+ maxQueueSize: parseInt(getEnvVar("OTEL_SPAN_MAX_QUEUE_SIZE") ?? "512")
3969
+ }) : new sdkTraceNode.SimpleSpanProcessor(spanExporter)));
3970
+ traceProvider.register();
3971
+ instrumentation.registerInstrumentations({
3972
+ instrumentations: config.instrumentations ?? [],
3973
+ tracerProvider: traceProvider
3974
+ });
3975
+ const logExporter = new exporterLogsOtlpHttp.OTLPLogExporter({
3976
+ url: `${config.url}/v1/logs`
3977
+ });
3978
+ const loggerProvider = new sdkLogs.LoggerProvider({
3979
+ resource: commonResources,
3980
+ logRecordLimits: {
3981
+ attributeCountLimit: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
3982
+ attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
3983
+ }
3984
+ });
3985
+ loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkLogs.BatchLogRecordProcessor(logExporter, {
3986
+ maxExportBatchSize: parseInt(getEnvVar("OTEL_LOG_MAX_EXPORT_BATCH_SIZE") ?? "64"),
3987
+ scheduledDelayMillis: parseInt(getEnvVar("OTEL_LOG_SCHEDULED_DELAY_MILLIS") ?? "200"),
3988
+ exportTimeoutMillis: parseInt(getEnvVar("OTEL_LOG_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
3989
+ maxQueueSize: parseInt(getEnvVar("OTEL_LOG_MAX_QUEUE_SIZE") ?? "512")
3990
+ }) : new sdkLogs.SimpleLogRecordProcessor(logExporter)));
3991
+ this._logProvider = loggerProvider;
3992
+ this._spanExporter = spanExporter;
3993
+ this._traceProvider = traceProvider;
3994
+ apiLogs.logs.setGlobalLoggerProvider(loggerProvider);
3995
+ this.getLogger = loggerProvider.getLogger.bind(loggerProvider);
3996
+ this.getTracer = traceProvider.getTracer.bind(traceProvider);
3997
+ }
3998
+ async flush() {
3999
+ await this._traceProvider.forceFlush();
4000
+ await this._logProvider.forceFlush();
4001
+ }
4002
+ async shutdown() {
4003
+ await this._traceProvider.shutdown();
4004
+ await this._logProvider.shutdown();
4005
+ }
4006
+ };
4007
+ __name(_TracingSDK, "TracingSDK");
4008
+ var TracingSDK = _TracingSDK;
4009
+ function setLogLevel(level) {
4010
+ let diagLogLevel;
4011
+ switch (level) {
4012
+ case "none":
4013
+ diagLogLevel = api.DiagLogLevel.NONE;
4014
+ break;
4015
+ case "error":
4016
+ diagLogLevel = api.DiagLogLevel.ERROR;
4017
+ break;
4018
+ case "warn":
4019
+ diagLogLevel = api.DiagLogLevel.WARN;
4020
+ break;
4021
+ case "info":
4022
+ diagLogLevel = api.DiagLogLevel.INFO;
4023
+ break;
4024
+ case "debug":
4025
+ diagLogLevel = api.DiagLogLevel.DEBUG;
4026
+ break;
4027
+ case "verbose":
4028
+ diagLogLevel = api.DiagLogLevel.VERBOSE;
4029
+ break;
4030
+ case "all":
4031
+ diagLogLevel = api.DiagLogLevel.ALL;
4032
+ break;
4033
+ default:
4034
+ diagLogLevel = api.DiagLogLevel.NONE;
4035
+ }
4036
+ api.diag.setLogger(new api.DiagConsoleLogger(), diagLogLevel);
4037
+ }
4038
+ __name(setLogLevel, "setLogLevel");
4039
+
4040
+ // src/v3/otel/index.ts
4041
+ function recordSpanException(span, error) {
4042
+ if (error instanceof Error) {
4043
+ span.recordException(error);
4044
+ } else if (typeof error === "string") {
4045
+ span.recordException(new Error(error));
4046
+ } else {
4047
+ span.recordException(new Error(JSON.stringify(error)));
4048
+ }
4049
+ span.setStatus({
4050
+ code: api.SpanStatusCode.ERROR
4051
+ });
4052
+ }
4053
+ __name(recordSpanException, "recordSpanException");
4054
+
4055
+ // src/v3/utils/ioSerialization.ts
4056
+ async function parsePacket(value) {
4057
+ if (!value.data) {
4058
+ return void 0;
4059
+ }
4060
+ switch (value.dataType) {
4061
+ case "application/json":
4062
+ return JSON.parse(value.data);
4063
+ case "application/super+json":
4064
+ const { parse } = await loadSuperJSON();
4065
+ return parse(value.data);
4066
+ case "text/plain":
4067
+ return value.data;
4068
+ case "application/store":
4069
+ throw new Error(`Cannot parse an application/store packet (${value.data}). Needs to be imported first.`);
4070
+ default:
4071
+ return value.data;
4072
+ }
4073
+ }
4074
+ __name(parsePacket, "parsePacket");
4075
+ async function stringifyIO(value) {
4076
+ if (value === void 0) {
4077
+ return {
4078
+ dataType: "application/json"
4079
+ };
4080
+ }
4081
+ if (typeof value === "string") {
4082
+ return {
4083
+ data: value,
4084
+ dataType: "text/plain"
4085
+ };
4086
+ }
4087
+ try {
4088
+ const { stringify } = await loadSuperJSON();
4089
+ const data = stringify(value);
4090
+ return {
4091
+ data,
4092
+ dataType: "application/super+json"
4093
+ };
4094
+ } catch {
4095
+ return {
4096
+ dataType: "application/json"
4097
+ };
4098
+ }
4099
+ }
4100
+ __name(stringifyIO, "stringifyIO");
4101
+ async function conditionallyExportPacket(packet, pathPrefix, tracer) {
4102
+ if (apiClientManager.client) {
4103
+ const { needsOffloading, size } = packetRequiresOffloading(packet);
4104
+ if (needsOffloading) {
4105
+ if (!tracer) {
4106
+ return await exportPacket(packet, pathPrefix);
4107
+ } else {
4108
+ const result = await tracer.startActiveSpan("store.uploadOutput", async (span) => {
4109
+ return await exportPacket(packet, pathPrefix);
4110
+ }, {
4111
+ attributes: {
4112
+ byteLength: size,
4113
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-upload"
4114
+ }
4115
+ });
4116
+ return result ?? packet;
4117
+ }
4118
+ }
4119
+ }
4120
+ return packet;
4121
+ }
4122
+ __name(conditionallyExportPacket, "conditionallyExportPacket");
4123
+ function packetRequiresOffloading(packet) {
4124
+ if (!packet.data) {
4125
+ return {
4126
+ needsOffloading: false,
4127
+ size: 0
4128
+ };
4129
+ }
4130
+ const byteSize = Buffer.byteLength(packet.data, "utf8");
4131
+ return {
4132
+ needsOffloading: byteSize >= OFFLOAD_IO_PACKET_LENGTH_LIMIT,
4133
+ size: byteSize
4134
+ };
4135
+ }
4136
+ __name(packetRequiresOffloading, "packetRequiresOffloading");
4137
+ async function exportPacket(packet, pathPrefix) {
4138
+ const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
4139
+ const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
4140
+ if (presignedResponse.ok) {
4141
+ const uploadResponse = await fetch(presignedResponse.data.presignedUrl, {
4142
+ method: "PUT",
4143
+ headers: {
4144
+ "Content-Type": packet.dataType
4145
+ },
4146
+ body: packet.data
4147
+ });
4148
+ if (!uploadResponse.ok) {
4149
+ throw new Error(`Failed to upload output to ${presignedResponse.data.presignedUrl}: ${uploadResponse.statusText}`);
4150
+ }
4151
+ return {
4152
+ data: filename,
4153
+ dataType: "application/store"
4154
+ };
4155
+ }
4156
+ return packet;
4157
+ }
4158
+ __name(exportPacket, "exportPacket");
4159
+ async function conditionallyImportPacket(packet, tracer) {
4160
+ if (packet.dataType !== "application/store") {
4161
+ return packet;
4162
+ }
4163
+ if (!tracer) {
4164
+ return await importPacket(packet);
4165
+ } else {
4166
+ const result = await tracer.startActiveSpan("store.downloadPayload", async (span) => {
4167
+ return await importPacket(packet, span);
4168
+ }, {
4169
+ attributes: {
4170
+ [SemanticInternalAttributes.STYLE_ICON]: "cloud-download"
4171
+ }
4172
+ });
4173
+ return result ?? packet;
4174
+ }
4175
+ }
4176
+ __name(conditionallyImportPacket, "conditionallyImportPacket");
4177
+ async function importPacket(packet, span) {
4178
+ if (!packet.data) {
4179
+ return packet;
4180
+ }
4181
+ if (!apiClientManager.client) {
4182
+ return packet;
4183
+ }
4184
+ const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
4185
+ if (presignedResponse.ok) {
4186
+ const response = await fetch(presignedResponse.data.presignedUrl);
4187
+ if (!response.ok) {
4188
+ throw new Error(`Failed to import packet ${presignedResponse.data.presignedUrl}: ${response.statusText}`);
4189
+ }
4190
+ const data = await response.text();
4191
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4192
+ return {
4193
+ data,
4194
+ dataType: response.headers.get("content-type") ?? "application/json"
4195
+ };
4196
+ }
4197
+ return packet;
4198
+ }
4199
+ __name(importPacket, "importPacket");
4200
+ async function createPacketAttributes(packet, dataKey, dataTypeKey) {
4201
+ if (!packet.data) {
4202
+ return;
4203
+ }
4204
+ switch (packet.dataType) {
4205
+ case "application/json":
4206
+ return {
4207
+ ...flattenAttributes(packet, dataKey),
4208
+ [dataTypeKey]: packet.dataType
4209
+ };
4210
+ case "application/super+json":
4211
+ const { parse } = await loadSuperJSON();
4212
+ if (typeof packet.data === "undefined" || packet.data === null) {
4213
+ return;
4214
+ }
4215
+ try {
4216
+ const parsed = parse(packet.data);
4217
+ const jsonified = JSON.parse(JSON.stringify(parsed, safeReplacer));
4218
+ return {
4219
+ ...flattenAttributes(jsonified, dataKey),
4220
+ [dataTypeKey]: "application/json"
4221
+ };
4222
+ } catch {
4223
+ return;
4224
+ }
4225
+ case "application/store":
4226
+ return {
4227
+ [dataKey]: packet.data,
4228
+ [dataTypeKey]: packet.dataType
4229
+ };
4230
+ case "text/plain":
4231
+ return {
4232
+ [dataKey]: packet.data,
4233
+ [dataTypeKey]: packet.dataType
4234
+ };
4235
+ default:
4236
+ return;
4237
+ }
4238
+ }
4239
+ __name(createPacketAttributes, "createPacketAttributes");
4240
+ async function createPacketAttributesAsJson(data, dataType) {
4241
+ if (typeof data === "string" || typeof data === "number" || typeof data === "boolean" || data === null || data === void 0) {
4242
+ return data;
4243
+ }
4244
+ switch (dataType) {
4245
+ case "application/json":
4246
+ return imposeAttributeLimits(flattenAttributes(data, void 0));
4247
+ case "application/super+json":
4248
+ const { deserialize } = await loadSuperJSON();
4249
+ const deserialized = deserialize(data);
4250
+ const jsonify = safeJsonParse(JSON.stringify(deserialized, safeReplacer));
4251
+ return imposeAttributeLimits(flattenAttributes(jsonify, void 0));
4252
+ case "application/store":
4253
+ return data;
4254
+ default:
4255
+ return {};
4256
+ }
4257
+ }
4258
+ __name(createPacketAttributesAsJson, "createPacketAttributesAsJson");
4259
+ async function prettyPrintPacket(rawData, dataType) {
4260
+ if (rawData === void 0) {
4261
+ return "";
4262
+ }
4263
+ if (dataType === "application/super+json") {
4264
+ const { deserialize } = await loadSuperJSON();
4265
+ return await prettyPrintPacket(deserialize(rawData), "application/json");
4266
+ }
4267
+ if (dataType === "application/json") {
4268
+ return JSON.stringify(rawData, safeReplacer, 2);
4269
+ }
4270
+ if (typeof rawData === "string") {
4271
+ return rawData;
4272
+ }
4273
+ return JSON.stringify(rawData, safeReplacer, 2);
4274
+ }
4275
+ __name(prettyPrintPacket, "prettyPrintPacket");
4276
+ function safeReplacer(key, value) {
4277
+ if (typeof value === "bigint") {
4278
+ return value.toString();
4279
+ }
4280
+ if (value instanceof RegExp) {
4281
+ return value.toString();
4282
+ }
4283
+ if (value instanceof Set) {
4284
+ return Array.from(value);
4285
+ }
4286
+ if (value instanceof Map) {
4287
+ const obj = {};
4288
+ value.forEach((v, k) => {
4289
+ obj[k] = v;
4290
+ });
4291
+ return obj;
4292
+ }
4293
+ return value;
4294
+ }
4295
+ __name(safeReplacer, "safeReplacer");
4296
+ function getPacketExtension(outputType) {
4297
+ switch (outputType) {
4298
+ case "application/json":
4299
+ return "json";
4300
+ case "application/super+json":
4301
+ return "json";
4302
+ case "text/plain":
4303
+ return "txt";
4304
+ default:
4305
+ return "txt";
4306
+ }
4307
+ }
4308
+ __name(getPacketExtension, "getPacketExtension");
4309
+ async function loadSuperJSON() {
4310
+ return await import('superjson');
4311
+ }
4312
+ __name(loadSuperJSON, "loadSuperJSON");
4313
+ function safeJsonParse(value) {
4314
+ try {
4315
+ return JSON.parse(value);
4316
+ } catch {
4317
+ return;
4318
+ }
4319
+ }
4320
+ __name(safeJsonParse, "safeJsonParse");
4321
+
4322
+ // src/v3/workers/taskExecutor.ts
4323
+ var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
4324
+ var _TaskExecutor = class _TaskExecutor {
4325
+ constructor(task, options) {
4326
+ __privateAdd(this, _callRun);
4327
+ __privateAdd(this, _callTaskInit);
4328
+ __privateAdd(this, _callTaskCleanup);
4329
+ __privateAdd(this, _handleError);
4330
+ this.task = task;
4331
+ this._tracingSDK = options.tracingSDK;
4332
+ this._tracer = options.tracer;
4333
+ this._consoleInterceptor = options.consoleInterceptor;
4334
+ this._config = options.projectConfig;
4335
+ this._importedConfig = options.importedConfig;
4336
+ this._handleErrorFn = options.handleErrorFn;
4337
+ }
4338
+ async execute(execution, worker, traceContext) {
4339
+ const ctx = TaskRunContext.parse(execution);
4340
+ const attemptMessage = `Attempt ${execution.attempt.number}`;
4341
+ const originalPacket = {
4342
+ data: execution.run.payload,
4343
+ dataType: execution.run.payloadType
4344
+ };
4345
+ const result = await taskContextManager.runWith({
4346
+ ctx,
4347
+ worker
4348
+ }, async () => {
4349
+ this._tracingSDK.asyncResourceDetector.resolveWithAttributes({
4350
+ ...taskContextManager.attributes,
4351
+ [SemanticInternalAttributes.SDK_VERSION]: this.task.packageVersion,
4352
+ [SemanticInternalAttributes.SDK_LANGUAGE]: "typescript"
4353
+ });
4354
+ return await this._tracer.startActiveSpan(attemptMessage, async (span) => {
4355
+ return await this._consoleInterceptor.intercept(console, async () => {
4356
+ let parsedPayload;
4357
+ let initOutput;
4358
+ try {
4359
+ const payloadPacket = await conditionallyImportPacket(originalPacket, this._tracer);
4360
+ parsedPayload = await parsePacket(payloadPacket);
4361
+ initOutput = await __privateMethod(this, _callTaskInit, callTaskInit_fn).call(this, parsedPayload, ctx);
4362
+ const output = await __privateMethod(this, _callRun, callRun_fn).call(this, parsedPayload, ctx, initOutput);
4363
+ try {
4364
+ const stringifiedOutput = await stringifyIO(output);
4365
+ const finalOutput = await conditionallyExportPacket(stringifiedOutput, `${execution.attempt.id}/output`, this._tracer);
4366
+ const attributes = await createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE);
4367
+ if (attributes) {
4368
+ span.setAttributes(attributes);
4369
+ }
4370
+ return {
4371
+ ok: true,
4372
+ id: execution.attempt.id,
4373
+ output: finalOutput.data,
4374
+ outputType: finalOutput.dataType
4375
+ };
4376
+ } catch (stringifyError) {
4377
+ recordSpanException(span, stringifyError);
4378
+ return {
4379
+ ok: false,
4380
+ id: execution.attempt.id,
4381
+ error: {
4382
+ type: "INTERNAL_ERROR",
4383
+ code: TaskRunErrorCodes.TASK_OUTPUT_ERROR,
4384
+ message: stringifyError instanceof Error ? stringifyError.message : typeof stringifyError === "string" ? stringifyError : void 0
4385
+ }
4386
+ };
4387
+ }
4388
+ } catch (runError) {
4389
+ try {
4390
+ const handleErrorResult = await __privateMethod(this, _handleError, handleError_fn).call(this, execution, runError, parsedPayload, ctx);
4391
+ recordSpanException(span, handleErrorResult.error ?? runError);
4392
+ return {
4393
+ id: execution.attempt.id,
4394
+ ok: false,
4395
+ error: handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError),
4396
+ retry: handleErrorResult.status === "retry" ? handleErrorResult.retry : void 0,
4397
+ skippedRetrying: handleErrorResult.status === "skipped"
4398
+ };
4399
+ } catch (handleErrorError) {
4400
+ recordSpanException(span, handleErrorError);
4401
+ return {
4402
+ ok: false,
4403
+ id: execution.attempt.id,
4404
+ error: {
4405
+ type: "INTERNAL_ERROR",
4406
+ code: TaskRunErrorCodes.HANDLE_ERROR_ERROR,
4407
+ message: handleErrorError instanceof Error ? handleErrorError.message : typeof handleErrorError === "string" ? handleErrorError : void 0
4408
+ }
4409
+ };
4410
+ }
4411
+ } finally {
4412
+ await __privateMethod(this, _callTaskCleanup, callTaskCleanup_fn).call(this, parsedPayload, ctx, initOutput);
4413
+ }
4414
+ });
4415
+ }, {
4416
+ kind: api.SpanKind.CONSUMER,
4417
+ attributes: {
4418
+ [SemanticInternalAttributes.STYLE_ICON]: "attempt",
4419
+ ...accessoryAttributes({
4420
+ items: [
4421
+ {
4422
+ text: ctx.task.filePath
4423
+ },
4424
+ {
4425
+ text: `${ctx.task.exportName}.run()`
4426
+ }
4427
+ ],
4428
+ style: "codepath"
4429
+ })
4430
+ }
4431
+ }, this._tracer.extractContext(traceContext));
4432
+ });
4433
+ return result;
4434
+ }
4435
+ };
4436
+ _callRun = new WeakSet();
4437
+ callRun_fn = /* @__PURE__ */ __name(async function(payload, ctx, init) {
4438
+ const runFn = this.task.fns.run;
4439
+ const middlewareFn = this.task.fns.middleware;
4440
+ if (!runFn) {
4441
+ throw new Error("Task does not have a run function");
4442
+ }
4443
+ if (!middlewareFn) {
4444
+ return runFn(payload, {
4445
+ ctx
4446
+ });
4447
+ }
4448
+ return middlewareFn(payload, {
4449
+ ctx,
4450
+ next: async () => runFn(payload, {
4451
+ ctx,
4452
+ init
4453
+ })
4454
+ });
4455
+ }, "#callRun");
4456
+ _callTaskInit = new WeakSet();
4457
+ callTaskInit_fn = /* @__PURE__ */ __name(async function(payload1, ctx1) {
4458
+ const initFn = this.task.fns.init;
4459
+ if (!initFn) {
4460
+ return {};
4461
+ }
4462
+ return this._tracer.startActiveSpan("init", async (span) => {
4463
+ return await initFn(payload1, {
4464
+ ctx: ctx1
4465
+ });
4466
+ });
4467
+ }, "#callTaskInit");
4468
+ _callTaskCleanup = new WeakSet();
4469
+ callTaskCleanup_fn = /* @__PURE__ */ __name(async function(payload2, ctx2, init1) {
4470
+ const cleanupFn = this.task.fns.cleanup;
4471
+ if (!cleanupFn) {
4472
+ return;
4473
+ }
4474
+ return this._tracer.startActiveSpan("cleanup", async (span) => {
4475
+ return await cleanupFn(payload2, {
4476
+ ctx: ctx2,
4477
+ init: init1
4478
+ });
4479
+ });
4480
+ }, "#callTaskCleanup");
4481
+ _handleError = new WeakSet();
4482
+ handleError_fn = /* @__PURE__ */ __name(async function(execution, error, payload3, ctx3) {
4483
+ const retriesConfig = this._importedConfig?.retries ?? this._config.retries;
4484
+ const retry = this.task.retry ?? retriesConfig?.default;
4485
+ if (!retry) {
4486
+ return {
4487
+ status: "noop"
4488
+ };
4489
+ }
4490
+ const delay = calculateNextRetryDelay(retry, execution.attempt.number);
4491
+ if (execution.environment.type === "DEVELOPMENT" && typeof retriesConfig?.enabledInDev === "boolean" && !retriesConfig.enabledInDev) {
4492
+ return {
4493
+ status: "skipped"
4494
+ };
4495
+ }
4496
+ return this._tracer.startActiveSpan("handleError()", async (span) => {
4497
+ const handleErrorResult = this.task.fns.handleError ? await this.task.fns.handleError(payload3, error, {
4498
+ ctx: ctx3,
4499
+ retry,
4500
+ retryDelayInMs: delay,
4501
+ retryAt: delay ? new Date(Date.now() + delay) : void 0
4502
+ }) : this._importedConfig ? await this._handleErrorFn?.(payload3, error, {
4503
+ ctx: ctx3,
4504
+ retry,
4505
+ retryDelayInMs: delay,
4506
+ retryAt: delay ? new Date(Date.now() + delay) : void 0
4507
+ }) : void 0;
4508
+ if (!handleErrorResult) {
4509
+ return typeof delay === "undefined" ? {
4510
+ status: "noop"
4511
+ } : {
4512
+ status: "retry",
4513
+ retry: {
4514
+ timestamp: Date.now() + delay,
4515
+ delay
4516
+ }
4517
+ };
4518
+ }
4519
+ if (handleErrorResult.skipRetrying) {
4520
+ return {
4521
+ status: "skipped",
4522
+ error: handleErrorResult.error
4523
+ };
4524
+ }
4525
+ if (typeof handleErrorResult.retryAt !== "undefined") {
4526
+ return {
4527
+ status: "retry",
4528
+ retry: {
4529
+ timestamp: handleErrorResult.retryAt.getTime(),
4530
+ delay: handleErrorResult.retryAt.getTime() - Date.now()
4531
+ },
4532
+ error: handleErrorResult.error
4533
+ };
4534
+ }
4535
+ if (typeof handleErrorResult.retryDelayInMs === "number") {
4536
+ return {
4537
+ status: "retry",
4538
+ retry: {
4539
+ timestamp: Date.now() + handleErrorResult.retryDelayInMs,
4540
+ delay: handleErrorResult.retryDelayInMs
4541
+ },
4542
+ error: handleErrorResult.error
4543
+ };
4544
+ }
4545
+ if (handleErrorResult.retry && typeof handleErrorResult.retry === "object") {
4546
+ const delay2 = calculateNextRetryDelay(handleErrorResult.retry, execution.attempt.number);
4547
+ return typeof delay2 === "undefined" ? {
4548
+ status: "noop",
4549
+ error: handleErrorResult.error
4550
+ } : {
4551
+ status: "retry",
4552
+ retry: {
4553
+ timestamp: Date.now() + delay2,
4554
+ delay: delay2
4555
+ },
4556
+ error: handleErrorResult.error
4557
+ };
4558
+ }
4559
+ return {
4560
+ status: "noop",
4561
+ error: handleErrorResult.error
4562
+ };
4563
+ }, {
4564
+ attributes: {
4565
+ [SemanticInternalAttributes.STYLE_ICON]: "exclamation-circle"
4566
+ }
4567
+ });
4568
+ }, "#handleError");
4569
+ __name(_TaskExecutor, "TaskExecutor");
4570
+ var TaskExecutor = _TaskExecutor;
4571
+
4572
+ // package.json
4573
+ var dependencies = {
4574
+ "@google-cloud/precise-date": "^4.0.0",
4575
+ "@opentelemetry/api": "^1.8.0",
4576
+ "@opentelemetry/api-logs": "^0.48.0",
4577
+ "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
4578
+ "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
4579
+ "@opentelemetry/instrumentation": "^0.49.1",
4580
+ "@opentelemetry/resources": "^1.22.0",
4581
+ "@opentelemetry/sdk-logs": "^0.49.1",
4582
+ "@opentelemetry/sdk-node": "^0.49.1",
4583
+ "@opentelemetry/sdk-trace-base": "^1.22.0",
4584
+ "@opentelemetry/sdk-trace-node": "^1.22.0",
4585
+ "@opentelemetry/semantic-conventions": "^1.22.0",
4586
+ "humanize-duration": "^3.27.3",
4587
+ "socket.io": "^4.7.4",
4588
+ "socket.io-client": "^4.7.4",
4589
+ superjson: "^2.2.1",
4590
+ ulidx: "^2.2.1",
4591
+ zod: "3.22.3",
4592
+ "zod-error": "1.5.0"
4593
+ };
4594
+
4595
+ // src/v3/utils/detectDependencyVersion.ts
4596
+ function detectDependencyVersion(dependency) {
4597
+ return dependencies[dependency];
4598
+ }
4599
+ __name(detectDependencyVersion, "detectDependencyVersion");
4600
+
1022
4601
  // src/v3/index.ts
1023
4602
  function parseTriggerTaskRequestBody(body) {
1024
4603
  return TriggerTaskRequestBody.safeParse(body);
1025
4604
  }
1026
4605
  __name(parseTriggerTaskRequestBody, "parseTriggerTaskRequestBody");
4606
+ function parseBatchTriggerTaskRequestBody(body) {
4607
+ return BatchTriggerTaskRequestBody.safeParse(body);
4608
+ }
4609
+ __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
1027
4610
 
1028
4611
  exports.ApiClient = ApiClient;
4612
+ exports.ApiClientManager = ApiClientManager;
1029
4613
  exports.BackgroundWorkerClientMessages = BackgroundWorkerClientMessages;
1030
4614
  exports.BackgroundWorkerMetadata = BackgroundWorkerMetadata;
1031
- exports.BackgroundWorkerRecord = BackgroundWorkerRecord;
4615
+ exports.BackgroundWorkerProperties = BackgroundWorkerProperties;
1032
4616
  exports.BackgroundWorkerServerMessages = BackgroundWorkerServerMessages;
4617
+ exports.BatchTaskRunExecutionResult = BatchTaskRunExecutionResult;
4618
+ exports.BatchTriggerTaskRequestBody = BatchTriggerTaskRequestBody;
4619
+ exports.BatchTriggerTaskResponse = BatchTriggerTaskResponse;
4620
+ exports.CancellationSpanEvent = CancellationSpanEvent;
4621
+ exports.ClientToSharedQueueMessages = ClientToSharedQueueMessages;
4622
+ exports.Config = Config;
1033
4623
  exports.ConsoleInterceptor = ConsoleInterceptor;
4624
+ exports.CoordinatorToPlatformMessages = CoordinatorToPlatformMessages;
4625
+ exports.CoordinatorToProdWorkerMessages = CoordinatorToProdWorkerMessages;
1034
4626
  exports.CreateAuthorizationCodeResponseSchema = CreateAuthorizationCodeResponseSchema;
1035
4627
  exports.CreateBackgroundWorkerRequestBody = CreateBackgroundWorkerRequestBody;
1036
4628
  exports.CreateBackgroundWorkerResponse = CreateBackgroundWorkerResponse;
4629
+ exports.CreateUploadPayloadUrlResponseBody = CreateUploadPayloadUrlResponseBody;
4630
+ exports.DeploymentErrorData = DeploymentErrorData;
1037
4631
  exports.DevRuntimeManager = DevRuntimeManager;
4632
+ exports.DurableClock = PreciseWallClock;
4633
+ exports.EnvironmentType = EnvironmentType;
4634
+ exports.EventFilter = EventFilter;
4635
+ exports.ExceptionEventProperties = ExceptionEventProperties;
4636
+ exports.ExceptionSpanEvent = ExceptionSpanEvent;
4637
+ exports.ExternalBuildData = ExternalBuildData;
4638
+ exports.FetchRetryBackoffStrategy = FetchRetryBackoffStrategy;
4639
+ exports.FetchRetryByStatusOptions = FetchRetryByStatusOptions;
4640
+ exports.FetchRetryHeadersStrategy = FetchRetryHeadersStrategy;
4641
+ exports.FetchRetryOptions = FetchRetryOptions;
4642
+ exports.FetchRetryStrategy = FetchRetryStrategy;
4643
+ exports.FetchTimeoutOptions = FetchTimeoutOptions;
4644
+ exports.FixedWindowRateLimit = FixedWindowRateLimit;
4645
+ exports.GetBatchResponseBody = GetBatchResponseBody;
4646
+ exports.GetDeploymentResponseBody = GetDeploymentResponseBody;
4647
+ exports.GetEnvironmentVariablesResponseBody = GetEnvironmentVariablesResponseBody;
1038
4648
  exports.GetPersonalAccessTokenRequestSchema = GetPersonalAccessTokenRequestSchema;
1039
4649
  exports.GetPersonalAccessTokenResponseSchema = GetPersonalAccessTokenResponseSchema;
1040
- exports.GetProjectDevResponse = GetProjectDevResponse;
4650
+ exports.GetProjectEnvResponse = GetProjectEnvResponse;
4651
+ exports.GetProjectResponseBody = GetProjectResponseBody;
4652
+ exports.GetProjectsResponseBody = GetProjectsResponseBody;
4653
+ exports.ImageDetailsMetadata = ImageDetailsMetadata;
4654
+ exports.InitializeDeploymentRequestBody = InitializeDeploymentRequestBody;
4655
+ exports.InitializeDeploymentResponseBody = InitializeDeploymentResponseBody;
4656
+ exports.Machine = Machine;
4657
+ exports.MachineCpu = MachineCpu;
4658
+ exports.MachineMemory = MachineMemory;
4659
+ exports.OFFLOAD_IO_PACKET_LENGTH_LIMIT = OFFLOAD_IO_PACKET_LENGTH_LIMIT;
4660
+ exports.OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT;
4661
+ exports.OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT;
4662
+ exports.OTEL_LINK_COUNT_LIMIT = OTEL_LINK_COUNT_LIMIT;
4663
+ exports.OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = OTEL_LOG_ATTRIBUTE_COUNT_LIMIT;
4664
+ exports.OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT;
4665
+ exports.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT;
4666
+ exports.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT;
4667
+ exports.OTEL_SPAN_EVENT_COUNT_LIMIT = OTEL_SPAN_EVENT_COUNT_LIMIT;
1041
4668
  exports.OtelTaskLogger = OtelTaskLogger;
4669
+ exports.OtherSpanEvent = OtherSpanEvent;
4670
+ exports.PRIMARY_VARIANT = PRIMARY_VARIANT;
4671
+ exports.PlatformToCoordinatorMessages = PlatformToCoordinatorMessages;
4672
+ exports.PlatformToProviderMessages = PlatformToProviderMessages;
4673
+ exports.PostStartCauses = PostStartCauses;
4674
+ exports.PreStopCauses = PreStopCauses;
4675
+ exports.ProdChildToWorkerMessages = ProdChildToWorkerMessages;
4676
+ exports.ProdRuntimeManager = ProdRuntimeManager;
4677
+ exports.ProdTaskRunExecution = ProdTaskRunExecution;
4678
+ exports.ProdTaskRunExecutionPayload = ProdTaskRunExecutionPayload;
4679
+ exports.ProdWorkerSocketData = ProdWorkerSocketData;
4680
+ exports.ProdWorkerToChildMessages = ProdWorkerToChildMessages;
4681
+ exports.ProdWorkerToCoordinatorMessages = ProdWorkerToCoordinatorMessages;
4682
+ exports.ProviderToPlatformMessages = ProviderToPlatformMessages;
4683
+ exports.QueueOptions = QueueOptions;
4684
+ exports.RateLimitOptions = RateLimitOptions;
4685
+ exports.RetryOptions = RetryOptions;
1042
4686
  exports.SemanticInternalAttributes = SemanticInternalAttributes;
4687
+ exports.SharedQueueToClientMessages = SharedQueueToClientMessages;
4688
+ exports.SimpleStructuredLogger = SimpleStructuredLogger;
4689
+ exports.SlidingWindowRateLimit = SlidingWindowRateLimit;
4690
+ exports.SpanEvent = SpanEvent;
4691
+ exports.SpanEvents = SpanEvents;
4692
+ exports.SpanMessagingEvent = SpanMessagingEvent;
4693
+ exports.StartDeploymentIndexingRequestBody = StartDeploymentIndexingRequestBody;
4694
+ exports.StartDeploymentIndexingResponseBody = StartDeploymentIndexingResponseBody;
4695
+ exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
4696
+ exports.TaskEventStyle = TaskEventStyle;
4697
+ exports.TaskExecutor = TaskExecutor;
1043
4698
  exports.TaskMetadata = TaskMetadata;
4699
+ exports.TaskMetadataFailedToParseData = TaskMetadataFailedToParseData;
1044
4700
  exports.TaskMetadataWithFilePath = TaskMetadataWithFilePath;
1045
4701
  exports.TaskResource = TaskResource;
1046
4702
  exports.TaskRun = TaskRun;
@@ -1051,32 +4707,82 @@ exports.TaskRunError = TaskRunError;
1051
4707
  exports.TaskRunErrorCodes = TaskRunErrorCodes;
1052
4708
  exports.TaskRunExecution = TaskRunExecution;
1053
4709
  exports.TaskRunExecutionAttempt = TaskRunExecutionAttempt;
4710
+ exports.TaskRunExecutionBatch = TaskRunExecutionBatch;
1054
4711
  exports.TaskRunExecutionEnvironment = TaskRunExecutionEnvironment;
1055
4712
  exports.TaskRunExecutionOrganization = TaskRunExecutionOrganization;
1056
4713
  exports.TaskRunExecutionPayload = TaskRunExecutionPayload;
1057
4714
  exports.TaskRunExecutionProject = TaskRunExecutionProject;
4715
+ exports.TaskRunExecutionQueue = TaskRunExecutionQueue;
1058
4716
  exports.TaskRunExecutionResult = TaskRunExecutionResult;
4717
+ exports.TaskRunExecutionRetry = TaskRunExecutionRetry;
1059
4718
  exports.TaskRunExecutionTask = TaskRunExecutionTask;
1060
4719
  exports.TaskRunFailedExecutionResult = TaskRunFailedExecutionResult;
1061
4720
  exports.TaskRunInternalError = TaskRunInternalError;
1062
4721
  exports.TaskRunStringError = TaskRunStringError;
1063
4722
  exports.TaskRunSuccessfulExecutionResult = TaskRunSuccessfulExecutionResult;
4723
+ exports.TracingSDK = TracingSDK;
1064
4724
  exports.TriggerTaskRequestBody = TriggerTaskRequestBody;
1065
4725
  exports.TriggerTaskResponse = TriggerTaskResponse;
1066
4726
  exports.TriggerTracer = TriggerTracer;
4727
+ exports.UncaughtExceptionMessage = UncaughtExceptionMessage;
4728
+ exports.WaitReason = WaitReason;
1067
4729
  exports.WhoAmIResponseSchema = WhoAmIResponseSchema;
4730
+ exports.ZodIpcConnection = ZodIpcConnection;
1068
4731
  exports.ZodMessageHandler = ZodMessageHandler;
4732
+ exports.ZodMessageSchema = ZodMessageSchema;
1069
4733
  exports.ZodMessageSender = ZodMessageSender;
4734
+ exports.ZodNamespace = ZodNamespace;
4735
+ exports.ZodSchemaParsedError = ZodSchemaParsedError;
4736
+ exports.ZodSocketConnection = ZodSocketConnection;
4737
+ exports.ZodSocketMessageHandler = ZodSocketMessageHandler;
4738
+ exports.ZodSocketMessageSender = ZodSocketMessageSender;
4739
+ exports.accessoryAttributes = accessoryAttributes;
4740
+ exports.apiClientManager = apiClientManager;
4741
+ exports.calculateNextRetryDelay = calculateNextRetryDelay;
4742
+ exports.calculateResetAt = calculateResetAt2;
1070
4743
  exports.childToWorkerMessages = childToWorkerMessages;
1071
4744
  exports.clientWebsocketMessages = clientWebsocketMessages;
4745
+ exports.clock = clock;
4746
+ exports.conditionallyExportPacket = conditionallyExportPacket;
4747
+ exports.conditionallyImportPacket = conditionallyImportPacket;
4748
+ exports.correctErrorStackTrace = correctErrorStackTrace;
1072
4749
  exports.createErrorTaskError = createErrorTaskError;
4750
+ exports.createPacketAttributes = createPacketAttributes;
4751
+ exports.createPacketAttributesAsJson = createPacketAttributesAsJson;
4752
+ exports.defaultFetchRetryOptions = defaultFetchRetryOptions;
4753
+ exports.defaultRetryOptions = defaultRetryOptions;
4754
+ exports.detectDependencyVersion = detectDependencyVersion;
4755
+ exports.eventFilterMatches = eventFilterMatches;
1073
4756
  exports.flattenAttributes = flattenAttributes;
4757
+ exports.formatDuration = formatDuration;
4758
+ exports.formatDurationInDays = formatDurationInDays;
4759
+ exports.formatDurationMilliseconds = formatDurationMilliseconds;
4760
+ exports.formatDurationNanoseconds = formatDurationNanoseconds;
4761
+ exports.getEnvVar = getEnvVar;
4762
+ exports.groupTaskMetadataIssuesByTask = groupTaskMetadataIssuesByTask;
4763
+ exports.iconStringForSeverity = iconStringForSeverity;
4764
+ exports.imposeAttributeLimits = imposeAttributeLimits;
4765
+ exports.isCancellationSpanEvent = isCancellationSpanEvent;
4766
+ exports.isExceptionSpanEvent = isExceptionSpanEvent;
4767
+ exports.logLevels = logLevels;
1074
4768
  exports.logger = logger;
4769
+ exports.millisecondsToNanoseconds = millisecondsToNanoseconds;
4770
+ exports.nanosecondsToMilliseconds = nanosecondsToMilliseconds;
4771
+ exports.omit = omit;
4772
+ exports.packetRequiresOffloading = packetRequiresOffloading;
4773
+ exports.parseBatchTriggerTaskRequestBody = parseBatchTriggerTaskRequestBody;
1075
4774
  exports.parseError = parseError;
4775
+ exports.parsePacket = parsePacket;
1076
4776
  exports.parseTriggerTaskRequestBody = parseTriggerTaskRequestBody;
4777
+ exports.prettyPrintPacket = prettyPrintPacket;
4778
+ exports.primitiveValueOrflattenedAttributes = primitiveValueOrflattenedAttributes;
4779
+ exports.recordSpanException = recordSpanException;
1077
4780
  exports.runtime = runtime;
1078
4781
  exports.serverWebsocketMessages = serverWebsocketMessages;
4782
+ exports.stringPatternMatchers = stringPatternMatchers;
4783
+ exports.stringifyIO = stringifyIO;
1079
4784
  exports.taskContextManager = taskContextManager;
4785
+ exports.unflattenAttributes = unflattenAttributes;
1080
4786
  exports.workerToChildMessages = workerToChildMessages;
1081
4787
  //# sourceMappingURL=out.js.map
1082
4788
  //# sourceMappingURL=index.js.map