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

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