@trigger.dev/core 2.3.18 → 3.0.0-beta.1

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