@trigger.dev/core 0.0.0-statuses-20230921210707 → 0.0.0-v3-canary-20240321105132

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