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

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