@trigger.dev/core 0.0.0-v3-trigger-dirs-20240422221109 → 0.0.0-v3-trigger-dirs-20240423123825

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.
Files changed (33) hide show
  1. package/dist/{consoleInterceptor-6WZo2qUS.d.ts → catalog-e2OUDZEa.d.mts} +368 -400
  2. package/dist/{consoleInterceptor-hjdjADX8.d.mts → catalog-ndN7py2b.d.ts} +368 -400
  3. package/dist/{messages-GvjBDSAA.d.mts → messages-AriaDDm0.d.mts} +439 -439
  4. package/dist/{messages-GvjBDSAA.d.ts → messages-AriaDDm0.d.ts} +439 -439
  5. package/dist/v3/dev/index.d.mts +1 -1
  6. package/dist/v3/dev/index.d.ts +1 -1
  7. package/dist/v3/index.d.mts +107 -321
  8. package/dist/v3/index.d.ts +107 -321
  9. package/dist/v3/index.js +2045 -2595
  10. package/dist/v3/index.js.map +1 -1
  11. package/dist/v3/index.mjs +2065 -2603
  12. package/dist/v3/index.mjs.map +1 -1
  13. package/dist/v3/otel/index.d.mts +34 -6
  14. package/dist/v3/otel/index.d.ts +34 -6
  15. package/dist/v3/otel/index.js +62 -38
  16. package/dist/v3/otel/index.js.map +1 -1
  17. package/dist/v3/otel/index.mjs +62 -38
  18. package/dist/v3/otel/index.mjs.map +1 -1
  19. package/dist/v3/prod/index.d.mts +2 -2
  20. package/dist/v3/prod/index.d.ts +2 -2
  21. package/dist/v3/prod/index.js.map +1 -1
  22. package/dist/v3/prod/index.mjs.map +1 -1
  23. package/dist/v3/workers/index.d.mts +57 -12
  24. package/dist/v3/workers/index.d.ts +57 -12
  25. package/dist/v3/workers/index.js +728 -124
  26. package/dist/v3/workers/index.js.map +1 -1
  27. package/dist/v3/workers/index.mjs +718 -125
  28. package/dist/v3/workers/index.mjs.map +1 -1
  29. package/package.json +3 -3
  30. package/dist/tracingSDK-XMTLzw35.d.mts +0 -35
  31. package/dist/tracingSDK-XMTLzw35.d.ts +0 -35
  32. package/dist/{manager-psJfQhBB.d.mts → manager-M9GLDnhJ.d.mts} +62 -62
  33. package/dist/{manager-psJfQhBB.d.ts → manager-M9GLDnhJ.d.ts} +62 -62
package/dist/v3/index.mjs CHANGED
@@ -1,19 +1,11 @@
1
- import { z } from 'zod';
2
- import { SpanStatusCode, propagation, context, trace, DiagLogLevel, diag, DiagConsoleLogger } from '@opentelemetry/api';
1
+ import { propagation, context, trace, SpanStatusCode } from '@opentelemetry/api';
3
2
  import { fromZodError } from 'zod-validation-error';
3
+ import { z } from 'zod';
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
5
- import nodePath from 'node:path';
6
- import { SeverityNumber, logs } from '@opentelemetry/api-logs';
7
5
  import { PreciseDate } from '@google-cloud/precise-date';
6
+ import nodePath from 'node:path';
7
+ import { logs } from '@opentelemetry/api-logs';
8
8
  import humanizeDuration from 'humanize-duration';
9
- import util from 'node:util';
10
- import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';
11
- import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
12
- import { registerInstrumentations } from '@opentelemetry/instrumentation';
13
- import { Resource, detectResourcesSync, processDetectorSync } from '@opentelemetry/resources';
14
- import { LoggerProvider, BatchLogRecordProcessor, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs';
15
- import { NodeTracerProvider, BatchSpanProcessor, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node';
16
- import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
17
9
 
18
10
  var __defProp = Object.defineProperty;
19
11
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -35,1969 +27,1888 @@ var __privateMethod = (obj, member, method) => {
35
27
  __accessCheck(obj, member, "access private method");
36
28
  return method;
37
29
  };
38
- var CreateAuthorizationCodeResponseSchema = z.object({
39
- url: z.string().url(),
40
- authorizationCode: z.string()
41
- });
42
- var GetPersonalAccessTokenRequestSchema = z.object({
43
- authorizationCode: z.string()
44
- });
45
- var GetPersonalAccessTokenResponseSchema = z.object({
46
- token: z.object({
47
- token: z.string(),
48
- obfuscatedToken: z.string()
49
- }).nullable()
50
- });
51
- var TaskRunBuiltInError = z.object({
52
- type: z.literal("BUILT_IN_ERROR"),
53
- name: z.string(),
54
- message: z.string(),
55
- stackTrace: z.string()
56
- });
57
- var TaskRunCustomErrorObject = z.object({
58
- type: z.literal("CUSTOM_ERROR"),
59
- raw: z.string()
60
- });
61
- var TaskRunStringError = z.object({
62
- type: z.literal("STRING_ERROR"),
63
- raw: z.string()
64
- });
65
- var TaskRunErrorCodes = {
66
- COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
67
- COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
68
- CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
69
- TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
70
- TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
71
- TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
72
- TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
73
- TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
74
- TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
75
- HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
76
- GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
77
- };
78
- var TaskRunInternalError = z.object({
79
- type: z.literal("INTERNAL_ERROR"),
80
- code: z.enum([
81
- "COULD_NOT_FIND_EXECUTOR",
82
- "COULD_NOT_FIND_TASK",
83
- "CONFIGURED_INCORRECTLY",
84
- "TASK_ALREADY_RUNNING",
85
- "TASK_EXECUTION_FAILED",
86
- "TASK_EXECUTION_ABORTED",
87
- "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
88
- "TASK_RUN_CANCELLED",
89
- "TASK_OUTPUT_ERROR",
90
- "HANDLE_ERROR_ERROR",
91
- "GRACEFUL_EXIT_TIMEOUT"
92
- ]),
93
- message: z.string().optional()
94
- });
95
- var TaskRunError = z.discriminatedUnion("type", [
96
- TaskRunBuiltInError,
97
- TaskRunCustomErrorObject,
98
- TaskRunStringError,
99
- TaskRunInternalError
100
- ]);
101
- var TaskRun = z.object({
102
- id: z.string(),
103
- payload: z.string(),
104
- payloadType: z.string(),
105
- context: z.any(),
106
- tags: z.array(z.string()),
107
- isTest: z.boolean().default(false),
108
- createdAt: z.coerce.date(),
109
- idempotencyKey: z.string().optional()
110
- });
111
- var TaskRunExecutionTask = z.object({
112
- id: z.string(),
113
- filePath: z.string(),
114
- exportName: z.string()
115
- });
116
- var TaskRunExecutionAttempt = z.object({
117
- id: z.string(),
118
- number: z.number(),
119
- startedAt: z.coerce.date(),
120
- backgroundWorkerId: z.string(),
121
- backgroundWorkerTaskId: z.string(),
122
- status: z.string()
123
- });
124
- var TaskRunExecutionEnvironment = z.object({
125
- id: z.string(),
126
- slug: z.string(),
127
- type: z.enum([
128
- "PRODUCTION",
129
- "STAGING",
130
- "DEVELOPMENT",
131
- "PREVIEW"
132
- ])
133
- });
134
- var TaskRunExecutionOrganization = z.object({
135
- id: z.string(),
136
- slug: z.string(),
137
- name: z.string()
138
- });
139
- var TaskRunExecutionProject = z.object({
140
- id: z.string(),
141
- ref: z.string(),
142
- slug: z.string(),
143
- name: z.string()
144
- });
145
- var TaskRunExecutionQueue = z.object({
146
- id: z.string(),
147
- name: z.string()
148
- });
149
- var TaskRunExecutionBatch = z.object({
150
- id: z.string()
151
- });
152
- var TaskRunExecution = z.object({
153
- task: TaskRunExecutionTask,
154
- attempt: TaskRunExecutionAttempt,
155
- run: TaskRun,
156
- queue: TaskRunExecutionQueue,
157
- environment: TaskRunExecutionEnvironment,
158
- organization: TaskRunExecutionOrganization,
159
- project: TaskRunExecutionProject,
160
- batch: TaskRunExecutionBatch.optional()
161
- });
162
- var TaskRunContext = z.object({
163
- task: TaskRunExecutionTask,
164
- attempt: TaskRunExecutionAttempt.omit({
165
- backgroundWorkerId: true,
166
- backgroundWorkerTaskId: true
167
- }),
168
- run: TaskRun.omit({
169
- payload: true,
170
- payloadType: true
171
- }),
172
- queue: TaskRunExecutionQueue,
173
- environment: TaskRunExecutionEnvironment,
174
- organization: TaskRunExecutionOrganization,
175
- project: TaskRunExecutionProject,
176
- batch: TaskRunExecutionBatch.optional()
177
- });
178
- var TaskRunExecutionRetry = z.object({
179
- timestamp: z.number(),
180
- delay: z.number(),
181
- error: z.unknown().optional()
182
- });
183
- var TaskRunFailedExecutionResult = z.object({
184
- ok: z.literal(false),
185
- id: z.string(),
186
- error: TaskRunError,
187
- retry: TaskRunExecutionRetry.optional(),
188
- skippedRetrying: z.boolean().optional()
189
- });
190
- var TaskRunSuccessfulExecutionResult = z.object({
191
- ok: z.literal(true),
192
- id: z.string(),
193
- output: z.string().optional(),
194
- outputType: z.string()
195
- });
196
- var TaskRunExecutionResult = z.discriminatedUnion("ok", [
197
- TaskRunSuccessfulExecutionResult,
198
- TaskRunFailedExecutionResult
199
- ]);
200
- var BatchTaskRunExecutionResult = z.object({
201
- id: z.string(),
202
- items: TaskRunExecutionResult.array()
203
- });
204
30
 
205
- // src/v3/schemas/messages.ts
206
- var EnvironmentType = z.enum([
207
- "PRODUCTION",
208
- "STAGING",
209
- "DEVELOPMENT",
210
- "PREVIEW"
211
- ]);
212
- var MachineCpu = z.union([
213
- z.literal(0.25),
214
- z.literal(0.5),
215
- z.literal(1),
216
- z.literal(2),
217
- z.literal(4)
218
- ]).default(0.5);
219
- var MachineMemory = z.union([
220
- z.literal(0.25),
221
- z.literal(0.5),
222
- z.literal(1),
223
- z.literal(2),
224
- z.literal(4),
225
- z.literal(8)
226
- ]).default(1);
227
- var Machine = z.object({
228
- version: z.literal("v1").default("v1"),
229
- cpu: MachineCpu,
230
- memory: MachineMemory
231
- });
232
- var TaskRunExecutionPayload = z.object({
233
- execution: TaskRunExecution,
234
- traceContext: z.record(z.unknown()),
235
- environment: z.record(z.string()).optional()
236
- });
237
- var ProdTaskRunExecution = TaskRunExecution.extend({
238
- worker: z.object({
239
- id: z.string(),
240
- contentHash: z.string(),
241
- version: z.string()
242
- })
243
- });
244
- var ProdTaskRunExecutionPayload = z.object({
245
- execution: ProdTaskRunExecution,
246
- traceContext: z.record(z.unknown()),
247
- environment: z.record(z.string()).optional()
248
- });
249
- var BackgroundWorkerServerMessages = z.discriminatedUnion("type", [
250
- z.object({
251
- type: z.literal("EXECUTE_RUNS"),
252
- payloads: z.array(TaskRunExecutionPayload)
253
- }),
254
- z.object({
255
- type: z.literal("CANCEL_ATTEMPT"),
256
- taskAttemptId: z.string(),
257
- taskRunId: z.string()
258
- }),
259
- z.object({
260
- type: z.literal("SCHEDULE_ATTEMPT"),
261
- image: z.string(),
262
- version: z.string(),
263
- machine: Machine,
264
- // identifiers
265
- id: z.string(),
266
- envId: z.string(),
267
- envType: EnvironmentType,
268
- orgId: z.string(),
269
- projectId: z.string(),
270
- runId: z.string()
271
- })
272
- ]);
273
- var serverWebsocketMessages = {
274
- SERVER_READY: z.object({
275
- version: z.literal("v1").default("v1"),
276
- id: z.string()
277
- }),
278
- BACKGROUND_WORKER_MESSAGE: z.object({
279
- version: z.literal("v1").default("v1"),
280
- backgroundWorkerId: z.string(),
281
- data: BackgroundWorkerServerMessages
282
- })
283
- };
284
- var BackgroundWorkerClientMessages = z.discriminatedUnion("type", [
285
- z.object({
286
- version: z.literal("v1").default("v1"),
287
- type: z.literal("TASK_RUN_COMPLETED"),
288
- completion: TaskRunExecutionResult,
289
- execution: TaskRunExecution
290
- }),
291
- z.object({
292
- version: z.literal("v1").default("v1"),
293
- type: z.literal("TASK_HEARTBEAT"),
294
- id: z.string()
295
- })
296
- ]);
297
- var BackgroundWorkerProperties = z.object({
298
- id: z.string(),
299
- version: z.string(),
300
- contentHash: z.string()
301
- });
302
- var clientWebsocketMessages = {
303
- READY_FOR_TASKS: z.object({
304
- version: z.literal("v1").default("v1"),
305
- backgroundWorkerId: z.string()
306
- }),
307
- BACKGROUND_WORKER_DEPRECATED: z.object({
308
- version: z.literal("v1").default("v1"),
309
- backgroundWorkerId: z.string()
310
- }),
311
- BACKGROUND_WORKER_MESSAGE: z.object({
312
- version: z.literal("v1").default("v1"),
313
- backgroundWorkerId: z.string(),
314
- data: BackgroundWorkerClientMessages
315
- })
316
- };
317
- var workerToChildMessages = {
318
- EXECUTE_TASK_RUN: z.object({
319
- version: z.literal("v1").default("v1"),
320
- execution: TaskRunExecution,
321
- traceContext: z.record(z.unknown()),
322
- metadata: BackgroundWorkerProperties
323
- }),
324
- TASK_RUN_COMPLETED_NOTIFICATION: z.object({
325
- version: z.literal("v1").default("v1"),
326
- completion: TaskRunExecutionResult,
327
- execution: TaskRunExecution
328
- }),
329
- CLEANUP: z.object({
330
- version: z.literal("v1").default("v1"),
331
- flush: z.boolean().default(false),
332
- kill: z.boolean().default(true)
333
- })
334
- };
335
- var FixedWindowRateLimit = z.object({
336
- type: z.literal("fixed-window"),
337
- limit: z.number(),
338
- window: z.union([
339
- z.object({
340
- seconds: z.number()
341
- }),
342
- z.object({
343
- minutes: z.number()
344
- }),
345
- z.object({
346
- hours: z.number()
347
- })
348
- ])
349
- });
350
- var SlidingWindowRateLimit = z.object({
351
- type: z.literal("sliding-window"),
352
- limit: z.number(),
353
- window: z.union([
354
- z.object({
355
- seconds: z.number()
356
- }),
357
- z.object({
358
- minutes: z.number()
359
- }),
360
- z.object({
361
- hours: z.number()
362
- })
363
- ])
364
- });
365
- var RateLimitOptions = z.discriminatedUnion("type", [
366
- FixedWindowRateLimit,
367
- SlidingWindowRateLimit
368
- ]);
369
- var RetryOptions = z.object({
370
- /** The number of attempts before giving up */
371
- maxAttempts: z.number().int().optional(),
372
- /** The exponential factor to use when calculating the next retry time.
373
- *
374
- * Each subsequent retry will be calculated as `previousTimeout * factor`
375
- */
376
- factor: z.number().optional(),
377
- /** The minimum time to wait before retrying */
378
- minTimeoutInMs: z.number().int().optional(),
379
- /** The maximum time to wait before retrying */
380
- maxTimeoutInMs: z.number().int().optional(),
381
- /** Randomize the timeout between retries.
382
- *
383
- * This can be useful to prevent the thundering herd problem where all retries happen at the same time.
384
- */
385
- randomize: z.boolean().optional()
386
- });
387
- var QueueOptions = z.object({
388
- /** You can define a shared queue and then pass the name in to your task.
389
- *
390
- * @example
391
- *
392
- * ```ts
393
- * const myQueue = queue({
394
- name: "my-queue",
395
- concurrencyLimit: 1,
396
- });
397
-
398
- export const task1 = task({
399
- id: "task-1",
400
- queue: {
401
- name: "my-queue",
402
- },
403
- run: async (payload: { message: string }) => {
404
- // ...
405
- },
406
- });
407
-
408
- export const task2 = task({
409
- id: "task-2",
410
- queue: {
411
- name: "my-queue",
412
- },
413
- run: async (payload: { message: string }) => {
414
- // ...
415
- },
31
+ // src/v3/apiErrors.ts
32
+ var _APIError = class _APIError extends Error {
33
+ constructor(status, error, message, headers) {
34
+ super(`${_APIError.makeMessage(status, error, message)}`);
35
+ this.status = status;
36
+ this.headers = headers;
37
+ const data = error;
38
+ this.error = data;
39
+ this.code = data?.["code"];
40
+ this.param = data?.["param"];
41
+ this.type = data?.["type"];
42
+ }
43
+ static makeMessage(status, error, message) {
44
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
45
+ if (status && msg) {
46
+ return `${status} ${msg}`;
47
+ }
48
+ if (status) {
49
+ return `${status} status code (no body)`;
50
+ }
51
+ if (msg) {
52
+ return msg;
53
+ }
54
+ return "(no status code or body)";
55
+ }
56
+ static generate(status, errorResponse, message, headers) {
57
+ if (!status) {
58
+ return new APIConnectionError({
59
+ cause: castToError(errorResponse)
416
60
  });
417
- * ```
418
- */
419
- name: z.string().optional(),
420
- /** An optional property that specifies the maximum number of concurrent run executions.
421
- *
422
- * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
423
- concurrencyLimit: z.number().int().min(0).max(1e3).optional(),
424
- /** @deprecated This feature is coming soon */
425
- rateLimit: RateLimitOptions.optional()
426
- });
427
- var TaskMetadata = z.object({
428
- id: z.string(),
429
- packageVersion: z.string(),
430
- queue: QueueOptions.optional(),
431
- retry: RetryOptions.optional(),
432
- machine: Machine.partial().optional(),
433
- triggerSource: z.string().optional()
434
- });
435
- var TaskFileMetadata = z.object({
436
- filePath: z.string(),
437
- exportName: z.string()
438
- });
439
- var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
440
- var UncaughtExceptionMessage = z.object({
441
- version: z.literal("v1").default("v1"),
442
- error: z.object({
443
- name: z.string(),
444
- message: z.string(),
445
- stack: z.string().optional()
446
- }),
447
- origin: z.enum([
448
- "uncaughtException",
449
- "unhandledRejection"
450
- ])
451
- });
452
- var TaskMetadataFailedToParseData = z.object({
453
- version: z.literal("v1").default("v1"),
454
- tasks: z.unknown(),
455
- zodIssues: z.custom((v) => {
456
- return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
457
- })
458
- });
459
- var childToWorkerMessages = {
460
- TASK_RUN_COMPLETED: z.object({
461
- version: z.literal("v1").default("v1"),
462
- execution: TaskRunExecution,
463
- result: TaskRunExecutionResult
464
- }),
465
- TASKS_READY: z.object({
466
- version: z.literal("v1").default("v1"),
467
- tasks: TaskMetadataWithFilePath.array()
468
- }),
469
- TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
470
- TASK_HEARTBEAT: z.object({
471
- version: z.literal("v1").default("v1"),
472
- id: z.string()
473
- }),
474
- READY_TO_DISPOSE: z.undefined(),
475
- WAIT_FOR_DURATION: z.object({
476
- version: z.literal("v1").default("v1"),
477
- ms: z.number()
478
- }),
479
- WAIT_FOR_TASK: z.object({
480
- version: z.literal("v1").default("v1"),
481
- id: z.string()
482
- }),
483
- WAIT_FOR_BATCH: z.object({
484
- version: z.literal("v1").default("v1"),
485
- id: z.string(),
486
- runs: z.string().array()
487
- }),
488
- UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
61
+ }
62
+ const error = errorResponse?.["error"];
63
+ if (status === 400) {
64
+ return new BadRequestError(status, error, message, headers);
65
+ }
66
+ if (status === 401) {
67
+ return new AuthenticationError(status, error, message, headers);
68
+ }
69
+ if (status === 403) {
70
+ return new PermissionDeniedError(status, error, message, headers);
71
+ }
72
+ if (status === 404) {
73
+ return new NotFoundError(status, error, message, headers);
74
+ }
75
+ if (status === 409) {
76
+ return new ConflictError(status, error, message, headers);
77
+ }
78
+ if (status === 422) {
79
+ return new UnprocessableEntityError(status, error, message, headers);
80
+ }
81
+ if (status === 429) {
82
+ return new RateLimitError(status, error, message, headers);
83
+ }
84
+ if (status >= 500) {
85
+ return new InternalServerError(status, error, message, headers);
86
+ }
87
+ return new _APIError(status, error, message, headers);
88
+ }
489
89
  };
490
- var ProdChildToWorkerMessages = {
491
- TASK_RUN_COMPLETED: {
492
- message: z.object({
493
- version: z.literal("v1").default("v1"),
494
- execution: TaskRunExecution,
495
- result: TaskRunExecutionResult
496
- })
497
- },
498
- TASKS_READY: {
499
- message: z.object({
500
- version: z.literal("v1").default("v1"),
501
- tasks: TaskMetadataWithFilePath.array()
502
- })
503
- },
504
- TASKS_FAILED_TO_PARSE: {
505
- message: TaskMetadataFailedToParseData
506
- },
507
- TASK_HEARTBEAT: {
508
- message: z.object({
509
- version: z.literal("v1").default("v1"),
510
- id: z.string()
511
- })
512
- },
513
- READY_TO_DISPOSE: {
514
- message: z.undefined()
515
- },
516
- READY_FOR_CHECKPOINT: {
517
- message: z.object({
518
- version: z.literal("v1").default("v1")
519
- })
520
- },
521
- CANCEL_CHECKPOINT: {
522
- message: z.object({
523
- version: z.literal("v1").default("v1")
524
- })
525
- },
526
- WAIT_FOR_DURATION: {
527
- message: z.object({
528
- version: z.literal("v1").default("v1"),
529
- ms: z.number(),
530
- now: z.number()
531
- }),
532
- callback: z.object({
533
- willCheckpointAndRestore: z.boolean()
534
- })
535
- },
536
- WAIT_FOR_TASK: {
537
- message: z.object({
538
- version: z.literal("v1").default("v1"),
539
- friendlyId: z.string()
540
- })
541
- },
542
- WAIT_FOR_BATCH: {
543
- message: z.object({
544
- version: z.literal("v1").default("v1"),
545
- batchFriendlyId: z.string(),
546
- runFriendlyIds: z.string().array()
547
- })
548
- },
549
- UNCAUGHT_EXCEPTION: {
550
- message: UncaughtExceptionMessage
90
+ __name(_APIError, "APIError");
91
+ var APIError = _APIError;
92
+ var _APIConnectionError = class _APIConnectionError extends APIError {
93
+ constructor({ message, cause }) {
94
+ super(void 0, void 0, message || "Connection error.", void 0);
95
+ __publicField(this, "status");
96
+ if (cause)
97
+ this.cause = cause;
551
98
  }
552
99
  };
553
- var ProdWorkerToChildMessages = {
554
- EXECUTE_TASK_RUN: {
555
- message: z.object({
556
- version: z.literal("v1").default("v1"),
557
- execution: TaskRunExecution,
558
- traceContext: z.record(z.unknown()),
559
- metadata: BackgroundWorkerProperties
560
- })
561
- },
562
- TASK_RUN_COMPLETED_NOTIFICATION: {
563
- message: z.object({
564
- version: z.literal("v1").default("v1"),
565
- completion: TaskRunExecutionResult,
566
- execution: TaskRunExecution
567
- })
568
- },
569
- CLEANUP: {
570
- message: z.object({
571
- version: z.literal("v1").default("v1"),
572
- flush: z.boolean().default(false),
573
- kill: z.boolean().default(true)
574
- }),
575
- callback: z.void()
576
- },
577
- WAIT_COMPLETED_NOTIFICATION: {
578
- message: z.object({
579
- version: z.literal("v1").default("v1")
580
- })
100
+ __name(_APIConnectionError, "APIConnectionError");
101
+ var APIConnectionError = _APIConnectionError;
102
+ var _BadRequestError = class _BadRequestError extends APIError {
103
+ constructor() {
104
+ super(...arguments);
105
+ __publicField(this, "status", 400);
106
+ }
107
+ };
108
+ __name(_BadRequestError, "BadRequestError");
109
+ var BadRequestError = _BadRequestError;
110
+ var _AuthenticationError = class _AuthenticationError extends APIError {
111
+ constructor() {
112
+ super(...arguments);
113
+ __publicField(this, "status", 401);
114
+ }
115
+ };
116
+ __name(_AuthenticationError, "AuthenticationError");
117
+ var AuthenticationError = _AuthenticationError;
118
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
119
+ constructor() {
120
+ super(...arguments);
121
+ __publicField(this, "status", 403);
122
+ }
123
+ };
124
+ __name(_PermissionDeniedError, "PermissionDeniedError");
125
+ var PermissionDeniedError = _PermissionDeniedError;
126
+ var _NotFoundError = class _NotFoundError extends APIError {
127
+ constructor() {
128
+ super(...arguments);
129
+ __publicField(this, "status", 404);
130
+ }
131
+ };
132
+ __name(_NotFoundError, "NotFoundError");
133
+ var NotFoundError = _NotFoundError;
134
+ var _ConflictError = class _ConflictError extends APIError {
135
+ constructor() {
136
+ super(...arguments);
137
+ __publicField(this, "status", 409);
138
+ }
139
+ };
140
+ __name(_ConflictError, "ConflictError");
141
+ var ConflictError = _ConflictError;
142
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
143
+ constructor() {
144
+ super(...arguments);
145
+ __publicField(this, "status", 422);
146
+ }
147
+ };
148
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
149
+ var UnprocessableEntityError = _UnprocessableEntityError;
150
+ var _RateLimitError = class _RateLimitError extends APIError {
151
+ constructor() {
152
+ super(...arguments);
153
+ __publicField(this, "status", 429);
581
154
  }
582
155
  };
156
+ __name(_RateLimitError, "RateLimitError");
157
+ var RateLimitError = _RateLimitError;
158
+ var _InternalServerError = class _InternalServerError extends APIError {
159
+ };
160
+ __name(_InternalServerError, "InternalServerError");
161
+ var InternalServerError = _InternalServerError;
162
+ function castToError(err) {
163
+ if (err instanceof Error)
164
+ return err;
165
+ return new Error(err);
166
+ }
167
+ __name(castToError, "castToError");
583
168
 
584
- // src/v3/schemas/resources.ts
585
- var TaskResource = z.object({
586
- id: z.string(),
587
- filePath: z.string(),
588
- exportName: z.string(),
589
- queue: QueueOptions.optional(),
590
- retry: RetryOptions.optional(),
591
- machine: Machine.partial().optional(),
592
- triggerSource: z.string().optional()
593
- });
594
- var BackgroundWorkerMetadata = z.object({
595
- packageVersion: z.string(),
596
- contentHash: z.string(),
597
- cliPackageVersion: z.string().optional(),
598
- tasks: z.array(TaskResource)
599
- });
600
- var ImageDetailsMetadata = z.object({
601
- contentHash: z.string(),
602
- imageTag: z.string()
603
- });
169
+ // src/retry.ts
170
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
171
+ if (!resets)
172
+ return;
173
+ switch (format) {
174
+ case "iso_8601_duration_openai_variant": {
175
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
176
+ }
177
+ case "iso_8601": {
178
+ return calculateISO8601ResetAt(resets, now);
179
+ }
180
+ case "unix_timestamp": {
181
+ return calculateUnixTimestampResetAt(resets, now);
182
+ }
183
+ case "unix_timestamp_in_ms": {
184
+ return calculateUnixTimestampInMsResetAt(resets, now);
185
+ }
186
+ }
187
+ }
188
+ __name(calculateResetAt, "calculateResetAt");
189
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
190
+ if (!resets)
191
+ return void 0;
192
+ const resetAt = parseInt(resets, 10);
193
+ if (isNaN(resetAt))
194
+ return void 0;
195
+ return new Date(resetAt * 1e3);
196
+ }
197
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
198
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
199
+ if (!resets)
200
+ return void 0;
201
+ const resetAt = parseInt(resets, 10);
202
+ if (isNaN(resetAt))
203
+ return void 0;
204
+ return new Date(resetAt);
205
+ }
206
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
207
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
208
+ if (!resets)
209
+ return void 0;
210
+ const resetAt = new Date(resets);
211
+ if (isNaN(resetAt.getTime()))
212
+ return void 0;
213
+ return resetAt;
214
+ }
215
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
216
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
217
+ if (!resets)
218
+ return void 0;
219
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
220
+ const match = resets.match(pattern);
221
+ if (!match)
222
+ return void 0;
223
+ const days = parseInt(match[1], 10) || 0;
224
+ const hours = parseInt(match[2], 10) || 0;
225
+ const minutes = parseInt(match[3], 10) || 0;
226
+ const seconds = parseFloat(match[4]) || 0;
227
+ const milliseconds = parseInt(match[5], 10) || 0;
228
+ const resetAt = new Date(now);
229
+ resetAt.setDate(resetAt.getDate() + days);
230
+ resetAt.setHours(resetAt.getHours() + hours);
231
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
232
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
233
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
234
+ return resetAt;
235
+ }
236
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
604
237
 
605
- // src/v3/schemas/api.ts
606
- var WhoAmIResponseSchema = z.object({
607
- userId: z.string(),
608
- email: z.string().email(),
609
- dashboardUrl: z.string()
610
- });
611
- var GetProjectResponseBody = z.object({
612
- id: z.string(),
613
- externalRef: z.string(),
614
- name: z.string(),
615
- slug: z.string(),
616
- createdAt: z.coerce.date(),
617
- organization: z.object({
618
- id: z.string(),
619
- title: z.string(),
620
- slug: z.string(),
621
- createdAt: z.coerce.date()
622
- })
623
- });
624
- var GetProjectsResponseBody = z.array(GetProjectResponseBody);
625
- var GetProjectEnvResponse = z.object({
626
- apiKey: z.string(),
627
- name: z.string(),
628
- apiUrl: z.string()
629
- });
630
- var CreateBackgroundWorkerRequestBody = z.object({
631
- localOnly: z.boolean(),
632
- metadata: BackgroundWorkerMetadata
633
- });
634
- var CreateBackgroundWorkerResponse = z.object({
635
- id: z.string(),
636
- version: z.string(),
637
- contentHash: z.string()
638
- });
639
- var TriggerTaskRequestBody = z.object({
640
- payload: z.any(),
641
- context: z.any(),
642
- options: z.object({
643
- dependentAttempt: z.string().optional(),
644
- dependentBatch: z.string().optional(),
645
- lockToVersion: z.string().optional(),
646
- queue: QueueOptions.optional(),
647
- concurrencyKey: z.string().optional(),
648
- idempotencyKey: z.string().optional(),
649
- test: z.boolean().optional(),
650
- payloadType: z.string().optional()
651
- }).optional()
238
+ // src/v3/utils/retries.ts
239
+ var defaultRetryOptions = {
240
+ maxAttempts: 3,
241
+ factor: 2,
242
+ minTimeoutInMs: 1e3,
243
+ maxTimeoutInMs: 6e4,
244
+ randomize: true
245
+ };
246
+ var defaultFetchRetryOptions = {
247
+ byStatus: {
248
+ "429,408,409,5xx": {
249
+ strategy: "backoff",
250
+ ...defaultRetryOptions
251
+ }
252
+ },
253
+ connectionError: defaultRetryOptions,
254
+ timeout: defaultRetryOptions
255
+ };
256
+ function calculateNextRetryDelay(options, attempt) {
257
+ const opts = {
258
+ ...defaultRetryOptions,
259
+ ...options
260
+ };
261
+ if (attempt >= opts.maxAttempts) {
262
+ return;
263
+ }
264
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
265
+ const random = randomize ? Math.random() + 1 : 1;
266
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
267
+ return Math.round(timeout);
268
+ }
269
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
270
+ function calculateResetAt2(resets, format, now = Date.now()) {
271
+ const resetAt = calculateResetAt(resets, format, new Date(now));
272
+ return resetAt?.getTime();
273
+ }
274
+ __name(calculateResetAt2, "calculateResetAt");
275
+
276
+ // src/v3/zodfetch.ts
277
+ var defaultRetryOptions2 = {
278
+ maxAttempts: 3,
279
+ factor: 2,
280
+ minTimeoutInMs: 1e3,
281
+ maxTimeoutInMs: 6e4,
282
+ randomize: false
283
+ };
284
+ async function zodfetch(schema, url, requestInit, options) {
285
+ return await _doZodFetch(schema, url, requestInit, options);
286
+ }
287
+ __name(zodfetch, "zodfetch");
288
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
289
+ try {
290
+ const response = await fetch(url, requestInitWithCache(requestInit));
291
+ const responseHeaders = createResponseHeaders(response.headers);
292
+ if (!response.ok) {
293
+ const retryResult = shouldRetry(response, attempt, options?.retry);
294
+ if (retryResult.retry) {
295
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
296
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
297
+ } else {
298
+ const errText = await response.text().catch((e) => castToError2(e).message);
299
+ const errJSON = safeJsonParse(errText);
300
+ const errMessage = errJSON ? void 0 : errText;
301
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
302
+ }
303
+ }
304
+ const jsonBody = await response.json();
305
+ const parsedResult = schema.safeParse(jsonBody);
306
+ if (parsedResult.success) {
307
+ return parsedResult.data;
308
+ }
309
+ throw fromZodError(parsedResult.error);
310
+ } catch (error) {
311
+ if (error instanceof APIError) {
312
+ throw error;
313
+ }
314
+ if (options?.retry) {
315
+ const retry = {
316
+ ...defaultRetryOptions2,
317
+ ...options.retry
318
+ };
319
+ const delay = calculateNextRetryDelay(retry, attempt);
320
+ if (delay) {
321
+ await new Promise((resolve) => setTimeout(resolve, delay));
322
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
323
+ }
324
+ }
325
+ throw new APIConnectionError({
326
+ cause: castToError2(error)
327
+ });
328
+ }
329
+ }
330
+ __name(_doZodFetch, "_doZodFetch");
331
+ function castToError2(err) {
332
+ if (err instanceof Error)
333
+ return err;
334
+ return new Error(err);
335
+ }
336
+ __name(castToError2, "castToError");
337
+ function shouldRetry(response, attempt, retryOptions) {
338
+ function shouldRetryForOptions() {
339
+ const retry = {
340
+ ...defaultRetryOptions2,
341
+ ...retryOptions
342
+ };
343
+ const delay = calculateNextRetryDelay(retry, attempt);
344
+ if (delay) {
345
+ return {
346
+ retry: true,
347
+ delay
348
+ };
349
+ } else {
350
+ return {
351
+ retry: false
352
+ };
353
+ }
354
+ }
355
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
356
+ const shouldRetryHeader = response.headers.get("x-should-retry");
357
+ if (shouldRetryHeader === "true")
358
+ return shouldRetryForOptions();
359
+ if (shouldRetryHeader === "false")
360
+ return {
361
+ retry: false
362
+ };
363
+ if (response.status === 408)
364
+ return shouldRetryForOptions();
365
+ if (response.status === 409)
366
+ return shouldRetryForOptions();
367
+ if (response.status === 429)
368
+ return shouldRetryForOptions();
369
+ if (response.status >= 500)
370
+ return shouldRetryForOptions();
371
+ return {
372
+ retry: false
373
+ };
374
+ }
375
+ __name(shouldRetry, "shouldRetry");
376
+ function safeJsonParse(text) {
377
+ try {
378
+ return JSON.parse(text);
379
+ } catch (e) {
380
+ return void 0;
381
+ }
382
+ }
383
+ __name(safeJsonParse, "safeJsonParse");
384
+ function createResponseHeaders(headers) {
385
+ return new Proxy(Object.fromEntries(
386
+ // @ts-ignore
387
+ headers.entries()
388
+ ), {
389
+ get(target, name) {
390
+ const key = name.toString();
391
+ return target[key.toLowerCase()] || target[key];
392
+ }
393
+ });
394
+ }
395
+ __name(createResponseHeaders, "createResponseHeaders");
396
+ function requestInitWithCache(requestInit) {
397
+ try {
398
+ const withCache = {
399
+ ...requestInit,
400
+ cache: "no-cache"
401
+ };
402
+ const _ = new Request("http://localhost", withCache);
403
+ return withCache;
404
+ } catch (error) {
405
+ return requestInit ?? {};
406
+ }
407
+ }
408
+ __name(requestInitWithCache, "requestInitWithCache");
409
+ var CreateAuthorizationCodeResponseSchema = z.object({
410
+ url: z.string().url(),
411
+ authorizationCode: z.string()
652
412
  });
653
- var TriggerTaskResponse = z.object({
654
- id: z.string()
413
+ var GetPersonalAccessTokenRequestSchema = z.object({
414
+ authorizationCode: z.string()
655
415
  });
656
- var BatchTriggerTaskRequestBody = z.object({
657
- items: TriggerTaskRequestBody.array(),
658
- dependentAttempt: z.string().optional()
416
+ var GetPersonalAccessTokenResponseSchema = z.object({
417
+ token: z.object({
418
+ token: z.string(),
419
+ obfuscatedToken: z.string()
420
+ }).nullable()
659
421
  });
660
- var BatchTriggerTaskResponse = z.object({
661
- batchId: z.string(),
662
- runs: z.string().array()
422
+ var TaskRunBuiltInError = z.object({
423
+ type: z.literal("BUILT_IN_ERROR"),
424
+ name: z.string(),
425
+ message: z.string(),
426
+ stackTrace: z.string()
663
427
  });
664
- var GetBatchResponseBody = z.object({
665
- id: z.string(),
666
- items: z.array(z.object({
667
- id: z.string(),
668
- taskRunId: z.string(),
669
- status: z.enum([
670
- "PENDING",
671
- "CANCELED",
672
- "COMPLETED",
673
- "FAILED"
674
- ])
675
- }))
428
+ var TaskRunCustomErrorObject = z.object({
429
+ type: z.literal("CUSTOM_ERROR"),
430
+ raw: z.string()
676
431
  });
677
- var GetEnvironmentVariablesResponseBody = z.object({
678
- variables: z.record(z.string())
432
+ var TaskRunStringError = z.object({
433
+ type: z.literal("STRING_ERROR"),
434
+ raw: z.string()
679
435
  });
680
- var StartDeploymentIndexingRequestBody = z.object({
681
- imageReference: z.string()
436
+ var TaskRunErrorCodes = {
437
+ COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
438
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
439
+ CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
440
+ TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
441
+ TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
442
+ TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
443
+ TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
444
+ TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
445
+ TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
446
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
447
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
448
+ };
449
+ var TaskRunInternalError = z.object({
450
+ type: z.literal("INTERNAL_ERROR"),
451
+ code: z.enum([
452
+ "COULD_NOT_FIND_EXECUTOR",
453
+ "COULD_NOT_FIND_TASK",
454
+ "CONFIGURED_INCORRECTLY",
455
+ "TASK_ALREADY_RUNNING",
456
+ "TASK_EXECUTION_FAILED",
457
+ "TASK_EXECUTION_ABORTED",
458
+ "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
459
+ "TASK_RUN_CANCELLED",
460
+ "TASK_OUTPUT_ERROR",
461
+ "HANDLE_ERROR_ERROR",
462
+ "GRACEFUL_EXIT_TIMEOUT"
463
+ ]),
464
+ message: z.string().optional()
682
465
  });
683
- var StartDeploymentIndexingResponseBody = z.object({
466
+ var TaskRunError = z.discriminatedUnion("type", [
467
+ TaskRunBuiltInError,
468
+ TaskRunCustomErrorObject,
469
+ TaskRunStringError,
470
+ TaskRunInternalError
471
+ ]);
472
+ var TaskRun = z.object({
684
473
  id: z.string(),
685
- contentHash: z.string()
474
+ payload: z.string(),
475
+ payloadType: z.string(),
476
+ context: z.any(),
477
+ tags: z.array(z.string()),
478
+ isTest: z.boolean().default(false),
479
+ createdAt: z.coerce.date(),
480
+ idempotencyKey: z.string().optional()
686
481
  });
687
- var ExternalBuildData = z.object({
688
- buildId: z.string(),
689
- buildToken: z.string(),
690
- projectId: z.string()
482
+ var TaskRunExecutionTask = z.object({
483
+ id: z.string(),
484
+ filePath: z.string(),
485
+ exportName: z.string()
691
486
  });
692
- var InitializeDeploymentResponseBody = z.object({
487
+ var TaskRunExecutionAttempt = z.object({
693
488
  id: z.string(),
694
- contentHash: z.string(),
695
- shortCode: z.string(),
696
- version: z.string(),
697
- imageTag: z.string(),
698
- externalBuildData: ExternalBuildData.optional().nullable(),
699
- registryHost: z.string().optional()
489
+ number: z.number(),
490
+ startedAt: z.coerce.date(),
491
+ backgroundWorkerId: z.string(),
492
+ backgroundWorkerTaskId: z.string(),
493
+ status: z.string()
700
494
  });
701
- var InitializeDeploymentRequestBody = z.object({
702
- contentHash: z.string(),
703
- userId: z.string().optional()
495
+ var TaskRunExecutionEnvironment = z.object({
496
+ id: z.string(),
497
+ slug: z.string(),
498
+ type: z.enum([
499
+ "PRODUCTION",
500
+ "STAGING",
501
+ "DEVELOPMENT",
502
+ "PREVIEW"
503
+ ])
704
504
  });
705
- var DeploymentErrorData = z.object({
706
- name: z.string(),
707
- message: z.string(),
708
- stack: z.string().optional()
505
+ var TaskRunExecutionOrganization = z.object({
506
+ id: z.string(),
507
+ slug: z.string(),
508
+ name: z.string()
709
509
  });
710
- var GetDeploymentResponseBody = z.object({
510
+ var TaskRunExecutionProject = z.object({
711
511
  id: z.string(),
712
- status: z.enum([
713
- "PENDING",
714
- "BUILDING",
715
- "DEPLOYING",
716
- "DEPLOYED",
717
- "FAILED",
718
- "CANCELED",
719
- "TIMED_OUT"
720
- ]),
721
- contentHash: z.string(),
722
- shortCode: z.string(),
723
- version: z.string(),
724
- imageReference: z.string().optional(),
725
- errorData: DeploymentErrorData.optional().nullable(),
726
- worker: z.object({
727
- id: z.string(),
728
- version: z.string(),
729
- tasks: z.array(z.object({
730
- id: z.string(),
731
- slug: z.string(),
732
- filePath: z.string(),
733
- exportName: z.string()
734
- }))
735
- }).optional()
512
+ ref: z.string(),
513
+ slug: z.string(),
514
+ name: z.string()
736
515
  });
737
- var CreateUploadPayloadUrlResponseBody = z.object({
738
- presignedUrl: z.string()
516
+ var TaskRunExecutionQueue = z.object({
517
+ id: z.string(),
518
+ name: z.string()
739
519
  });
740
- var ReplayRunResponse = z.object({
520
+ var TaskRunExecutionBatch = z.object({
741
521
  id: z.string()
742
522
  });
743
- var CanceledRunResponse = z.object({
744
- message: z.string()
523
+ var TaskRunExecution = z.object({
524
+ task: TaskRunExecutionTask,
525
+ attempt: TaskRunExecutionAttempt,
526
+ run: TaskRun,
527
+ queue: TaskRunExecutionQueue,
528
+ environment: TaskRunExecutionEnvironment,
529
+ organization: TaskRunExecutionOrganization,
530
+ project: TaskRunExecutionProject,
531
+ batch: TaskRunExecutionBatch.optional()
745
532
  });
746
- var ScheduledTaskPayload = z.object({
747
- /** The schedule id associated with this run (you can have many schedules for the same task).
748
- You can use this to remove the schedule, update it, etc */
749
- scheduleId: z.string(),
750
- /** When the task was scheduled to run.
751
- * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
752
- timestamp: z.date(),
753
- /** When the task was last run (it has been).
754
- This can be undefined if it's never been run */
755
- lastTimestamp: z.date().optional(),
756
- /** You can optionally provide an external id when creating the schedule.
757
- Usually you would use a userId or some other unique identifier.
758
- This defaults to undefined if you didn't provide one. */
759
- externalId: z.string().optional(),
760
- /** The next 5 dates this task is scheduled to run */
761
- upcoming: z.array(z.date())
533
+ var TaskRunContext = z.object({
534
+ task: TaskRunExecutionTask,
535
+ attempt: TaskRunExecutionAttempt.omit({
536
+ backgroundWorkerId: true,
537
+ backgroundWorkerTaskId: true
538
+ }),
539
+ run: TaskRun.omit({
540
+ payload: true,
541
+ payloadType: true
542
+ }),
543
+ queue: TaskRunExecutionQueue,
544
+ environment: TaskRunExecutionEnvironment,
545
+ organization: TaskRunExecutionOrganization,
546
+ project: TaskRunExecutionProject,
547
+ batch: TaskRunExecutionBatch.optional()
762
548
  });
763
- var CreateScheduleOptions = z.object({
764
- /** The id of the task you want to attach to. */
765
- task: z.string(),
766
- /** The schedule in CRON format.
767
- *
768
- * ```txt
769
- * * * * * *
770
- ┬ ┬ ┬ ┬ ┬
771
- │ │ │ │ |
772
- │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
773
- │ │ │ └───── month (1 - 12)
774
- │ │ └────────── day of month (1 - 31, L)
775
- │ └─────────────── hour (0 - 23)
776
- └──────────────────── minute (0 - 59)
777
- * ```
778
-
779
- "L" means the last. In the "day of week" field, 1L means the last Monday of the month. In the day of month field, L means the last day of the month.
780
-
781
- */
782
- cron: z.string(),
783
- /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
784
- *
785
- * This is useful if you don't want to create duplicate schedules for a user. */
786
- deduplicationKey: z.string().optional(),
787
- /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
788
- *
789
- * This allows you to have per-user CRON tasks.
790
- */
791
- externalId: z.string().optional()
549
+ var TaskRunExecutionRetry = z.object({
550
+ timestamp: z.number(),
551
+ delay: z.number(),
552
+ error: z.unknown().optional()
792
553
  });
793
- var UpdateScheduleOptions = CreateScheduleOptions;
794
- var ScheduleObject = z.object({
554
+ var TaskRunFailedExecutionResult = z.object({
555
+ ok: z.literal(false),
795
556
  id: z.string(),
796
- task: z.string(),
797
- active: z.boolean(),
798
- deduplicationKey: z.string().nullish(),
799
- externalId: z.string().nullish(),
800
- generator: z.object({
801
- type: z.literal("CRON"),
802
- expression: z.string(),
803
- description: z.string()
804
- }),
805
- nextRun: z.coerce.date().nullish(),
806
- environments: z.array(z.object({
807
- id: z.string(),
808
- type: z.string(),
809
- userName: z.string().nullish()
810
- }))
811
- });
812
- var DeletedScheduleObject = z.object({
813
- id: z.string()
557
+ error: TaskRunError,
558
+ retry: TaskRunExecutionRetry.optional(),
559
+ skippedRetrying: z.boolean().optional()
814
560
  });
815
- var ListSchedulesResult = z.object({
816
- data: z.array(ScheduleObject),
817
- pagination: z.object({
818
- currentPage: z.number(),
819
- totalPages: z.number(),
820
- count: z.number()
821
- })
561
+ var TaskRunSuccessfulExecutionResult = z.object({
562
+ ok: z.literal(true),
563
+ id: z.string(),
564
+ output: z.string().optional(),
565
+ outputType: z.string()
822
566
  });
823
- var ListScheduleOptions = z.object({
824
- page: z.number().optional(),
825
- perPage: z.number().optional()
567
+ var TaskRunExecutionResult = z.discriminatedUnion("ok", [
568
+ TaskRunSuccessfulExecutionResult,
569
+ TaskRunFailedExecutionResult
570
+ ]);
571
+ var BatchTaskRunExecutionResult = z.object({
572
+ id: z.string(),
573
+ items: TaskRunExecutionResult.array()
826
574
  });
827
- var PostStartCauses = z.enum([
828
- "index",
829
- "create",
830
- "restore"
575
+
576
+ // src/v3/schemas/messages.ts
577
+ var EnvironmentType = z.enum([
578
+ "PRODUCTION",
579
+ "STAGING",
580
+ "DEVELOPMENT",
581
+ "PREVIEW"
831
582
  ]);
832
- var PreStopCauses = z.enum([
833
- "terminate"
834
- ]);
835
- var RegexSchema = z.custom((val) => {
836
- try {
837
- return typeof val.test === "function";
838
- } catch {
839
- return false;
840
- }
583
+ var MachineCpu = z.union([
584
+ z.literal(0.25),
585
+ z.literal(0.5),
586
+ z.literal(1),
587
+ z.literal(2),
588
+ z.literal(4)
589
+ ]).default(0.5);
590
+ var MachineMemory = z.union([
591
+ z.literal(0.25),
592
+ z.literal(0.5),
593
+ z.literal(1),
594
+ z.literal(2),
595
+ z.literal(4),
596
+ z.literal(8)
597
+ ]).default(1);
598
+ var Machine = z.object({
599
+ version: z.literal("v1").default("v1"),
600
+ cpu: MachineCpu,
601
+ memory: MachineMemory
841
602
  });
842
- var Config = z.object({
843
- project: z.string(),
844
- triggerDirectories: z.string().array().optional(),
845
- triggerUrl: z.string().optional(),
846
- projectDir: z.string().optional(),
847
- tsconfigPath: z.string().optional(),
848
- retries: z.object({
849
- enabledInDev: z.boolean().default(true),
850
- default: RetryOptions.optional()
851
- }).optional(),
852
- additionalPackages: z.string().array().optional(),
853
- additionalFiles: z.string().array().optional(),
854
- dependenciesToBundle: z.array(z.union([
855
- z.string(),
856
- RegexSchema
857
- ])).optional(),
858
- logLevel: z.string().optional(),
859
- enableConsoleLogging: z.boolean().optional()
603
+ var TaskRunExecutionPayload = z.object({
604
+ execution: TaskRunExecution,
605
+ traceContext: z.record(z.unknown()),
606
+ environment: z.record(z.string()).optional()
860
607
  });
861
- var WaitReason = z.enum([
862
- "WAIT_FOR_DURATION",
863
- "WAIT_FOR_TASK",
864
- "WAIT_FOR_BATCH"
608
+ var ProdTaskRunExecution = TaskRunExecution.extend({
609
+ worker: z.object({
610
+ id: z.string(),
611
+ contentHash: z.string(),
612
+ version: z.string()
613
+ })
614
+ });
615
+ var ProdTaskRunExecutionPayload = z.object({
616
+ execution: ProdTaskRunExecution,
617
+ traceContext: z.record(z.unknown()),
618
+ environment: z.record(z.string()).optional()
619
+ });
620
+ var BackgroundWorkerServerMessages = z.discriminatedUnion("type", [
621
+ z.object({
622
+ type: z.literal("EXECUTE_RUNS"),
623
+ payloads: z.array(TaskRunExecutionPayload)
624
+ }),
625
+ z.object({
626
+ type: z.literal("CANCEL_ATTEMPT"),
627
+ taskAttemptId: z.string(),
628
+ taskRunId: z.string()
629
+ }),
630
+ z.object({
631
+ type: z.literal("SCHEDULE_ATTEMPT"),
632
+ image: z.string(),
633
+ version: z.string(),
634
+ machine: Machine,
635
+ // identifiers
636
+ id: z.string(),
637
+ envId: z.string(),
638
+ envType: EnvironmentType,
639
+ orgId: z.string(),
640
+ projectId: z.string(),
641
+ runId: z.string()
642
+ })
865
643
  ]);
866
- var ProviderToPlatformMessages = {
867
- LOG: {
868
- message: z.object({
869
- version: z.literal("v1").default("v1"),
870
- data: z.string()
871
- })
872
- },
873
- LOG_WITH_ACK: {
874
- message: z.object({
875
- version: z.literal("v1").default("v1"),
876
- data: z.string()
877
- }),
878
- callback: z.object({
879
- status: z.literal("ok")
880
- })
881
- },
882
- WORKER_CRASHED: {
883
- message: z.object({
884
- version: z.literal("v1").default("v1"),
885
- runId: z.string(),
886
- reason: z.string().optional(),
887
- exitCode: z.number().optional(),
888
- message: z.string().optional(),
889
- logs: z.string().optional()
890
- })
891
- },
892
- INDEXING_FAILED: {
893
- message: z.object({
894
- version: z.literal("v1").default("v1"),
895
- deploymentId: z.string(),
896
- error: z.object({
897
- name: z.string(),
898
- message: z.string(),
899
- stack: z.string().optional()
900
- })
901
- })
902
- }
644
+ var serverWebsocketMessages = {
645
+ SERVER_READY: z.object({
646
+ version: z.literal("v1").default("v1"),
647
+ id: z.string()
648
+ }),
649
+ BACKGROUND_WORKER_MESSAGE: z.object({
650
+ version: z.literal("v1").default("v1"),
651
+ backgroundWorkerId: z.string(),
652
+ data: BackgroundWorkerServerMessages
653
+ })
903
654
  };
904
- var PlatformToProviderMessages = {
905
- HEALTH: {
906
- message: z.object({
907
- version: z.literal("v1").default("v1")
655
+ var BackgroundWorkerClientMessages = z.discriminatedUnion("type", [
656
+ z.object({
657
+ version: z.literal("v1").default("v1"),
658
+ type: z.literal("TASK_RUN_COMPLETED"),
659
+ completion: TaskRunExecutionResult,
660
+ execution: TaskRunExecution
661
+ }),
662
+ z.object({
663
+ version: z.literal("v1").default("v1"),
664
+ type: z.literal("TASK_HEARTBEAT"),
665
+ id: z.string()
666
+ })
667
+ ]);
668
+ var BackgroundWorkerProperties = z.object({
669
+ id: z.string(),
670
+ version: z.string(),
671
+ contentHash: z.string()
672
+ });
673
+ var clientWebsocketMessages = {
674
+ READY_FOR_TASKS: z.object({
675
+ version: z.literal("v1").default("v1"),
676
+ backgroundWorkerId: z.string()
677
+ }),
678
+ BACKGROUND_WORKER_DEPRECATED: z.object({
679
+ version: z.literal("v1").default("v1"),
680
+ backgroundWorkerId: z.string()
681
+ }),
682
+ BACKGROUND_WORKER_MESSAGE: z.object({
683
+ version: z.literal("v1").default("v1"),
684
+ backgroundWorkerId: z.string(),
685
+ data: BackgroundWorkerClientMessages
686
+ })
687
+ };
688
+ var workerToChildMessages = {
689
+ EXECUTE_TASK_RUN: z.object({
690
+ version: z.literal("v1").default("v1"),
691
+ execution: TaskRunExecution,
692
+ traceContext: z.record(z.unknown()),
693
+ metadata: BackgroundWorkerProperties
694
+ }),
695
+ TASK_RUN_COMPLETED_NOTIFICATION: z.object({
696
+ version: z.literal("v1").default("v1"),
697
+ completion: TaskRunExecutionResult,
698
+ execution: TaskRunExecution
699
+ }),
700
+ CLEANUP: z.object({
701
+ version: z.literal("v1").default("v1"),
702
+ flush: z.boolean().default(false),
703
+ kill: z.boolean().default(true)
704
+ })
705
+ };
706
+ var FixedWindowRateLimit = z.object({
707
+ type: z.literal("fixed-window"),
708
+ limit: z.number(),
709
+ window: z.union([
710
+ z.object({
711
+ seconds: z.number()
908
712
  }),
909
- callback: z.object({
910
- status: z.literal("ok")
911
- })
912
- },
913
- INDEX: {
914
- message: z.object({
915
- version: z.literal("v1").default("v1"),
916
- imageTag: z.string(),
917
- shortCode: z.string(),
918
- apiKey: z.string(),
919
- apiUrl: z.string(),
920
- // identifiers
921
- envId: z.string(),
922
- envType: EnvironmentType,
923
- orgId: z.string(),
924
- projectId: z.string(),
925
- deploymentId: z.string()
713
+ z.object({
714
+ minutes: z.number()
926
715
  }),
927
- callback: z.discriminatedUnion("success", [
928
- z.object({
929
- success: z.literal(false),
930
- error: z.object({
931
- name: z.string(),
932
- message: z.string(),
933
- stack: z.string().optional()
934
- })
935
- }),
936
- z.object({
937
- success: z.literal(true)
938
- })
939
- ])
940
- },
941
- // TODO: this should be a shared queue message instead
942
- RESTORE: {
943
- message: z.object({
944
- version: z.literal("v1").default("v1"),
945
- type: z.enum([
946
- "DOCKER",
947
- "KUBERNETES"
948
- ]),
949
- location: z.string(),
950
- reason: z.string().optional(),
951
- imageRef: z.string(),
952
- machine: Machine,
953
- // identifiers
954
- checkpointId: z.string(),
955
- envId: z.string(),
956
- envType: EnvironmentType,
957
- orgId: z.string(),
958
- projectId: z.string(),
959
- runId: z.string()
716
+ z.object({
717
+ hours: z.number()
960
718
  })
961
- },
962
- DELETE: {
963
- message: z.object({
964
- version: z.literal("v1").default("v1"),
965
- name: z.string()
966
- }),
967
- callback: z.object({
968
- message: z.string()
719
+ ])
720
+ });
721
+ var SlidingWindowRateLimit = z.object({
722
+ type: z.literal("sliding-window"),
723
+ limit: z.number(),
724
+ window: z.union([
725
+ z.object({
726
+ seconds: z.number()
727
+ }),
728
+ z.object({
729
+ minutes: z.number()
730
+ }),
731
+ z.object({
732
+ hours: z.number()
733
+ })
734
+ ])
735
+ });
736
+ var RateLimitOptions = z.discriminatedUnion("type", [
737
+ FixedWindowRateLimit,
738
+ SlidingWindowRateLimit
739
+ ]);
740
+ var RetryOptions = z.object({
741
+ /** The number of attempts before giving up */
742
+ maxAttempts: z.number().int().optional(),
743
+ /** The exponential factor to use when calculating the next retry time.
744
+ *
745
+ * Each subsequent retry will be calculated as `previousTimeout * factor`
746
+ */
747
+ factor: z.number().optional(),
748
+ /** The minimum time to wait before retrying */
749
+ minTimeoutInMs: z.number().int().optional(),
750
+ /** The maximum time to wait before retrying */
751
+ maxTimeoutInMs: z.number().int().optional(),
752
+ /** Randomize the timeout between retries.
753
+ *
754
+ * This can be useful to prevent the thundering herd problem where all retries happen at the same time.
755
+ */
756
+ randomize: z.boolean().optional()
757
+ });
758
+ var QueueOptions = z.object({
759
+ /** You can define a shared queue and then pass the name in to your task.
760
+ *
761
+ * @example
762
+ *
763
+ * ```ts
764
+ * const myQueue = queue({
765
+ name: "my-queue",
766
+ concurrencyLimit: 1,
767
+ });
768
+
769
+ export const task1 = task({
770
+ id: "task-1",
771
+ queue: {
772
+ name: "my-queue",
773
+ },
774
+ run: async (payload: { message: string }) => {
775
+ // ...
776
+ },
777
+ });
778
+
779
+ export const task2 = task({
780
+ id: "task-2",
781
+ queue: {
782
+ name: "my-queue",
783
+ },
784
+ run: async (payload: { message: string }) => {
785
+ // ...
786
+ },
787
+ });
788
+ * ```
789
+ */
790
+ name: z.string().optional(),
791
+ /** An optional property that specifies the maximum number of concurrent run executions.
792
+ *
793
+ * If this property is omitted, the task can potentially use up the full concurrency of an environment. */
794
+ concurrencyLimit: z.number().int().min(0).max(1e3).optional(),
795
+ /** @deprecated This feature is coming soon */
796
+ rateLimit: RateLimitOptions.optional()
797
+ });
798
+ var TaskMetadata = z.object({
799
+ id: z.string(),
800
+ packageVersion: z.string(),
801
+ queue: QueueOptions.optional(),
802
+ retry: RetryOptions.optional(),
803
+ machine: Machine.partial().optional(),
804
+ triggerSource: z.string().optional()
805
+ });
806
+ var TaskFileMetadata = z.object({
807
+ filePath: z.string(),
808
+ exportName: z.string()
809
+ });
810
+ var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
811
+ var UncaughtExceptionMessage = z.object({
812
+ version: z.literal("v1").default("v1"),
813
+ error: z.object({
814
+ name: z.string(),
815
+ message: z.string(),
816
+ stack: z.string().optional()
817
+ }),
818
+ origin: z.enum([
819
+ "uncaughtException",
820
+ "unhandledRejection"
821
+ ])
822
+ });
823
+ var TaskMetadataFailedToParseData = z.object({
824
+ version: z.literal("v1").default("v1"),
825
+ tasks: z.unknown(),
826
+ zodIssues: z.custom((v) => {
827
+ return Array.isArray(v) && v.every((issue) => typeof issue === "object" && "message" in issue);
828
+ })
829
+ });
830
+ var childToWorkerMessages = {
831
+ TASK_RUN_COMPLETED: z.object({
832
+ version: z.literal("v1").default("v1"),
833
+ execution: TaskRunExecution,
834
+ result: TaskRunExecutionResult
835
+ }),
836
+ TASKS_READY: z.object({
837
+ version: z.literal("v1").default("v1"),
838
+ tasks: TaskMetadataWithFilePath.array()
839
+ }),
840
+ TASKS_FAILED_TO_PARSE: TaskMetadataFailedToParseData,
841
+ TASK_HEARTBEAT: z.object({
842
+ version: z.literal("v1").default("v1"),
843
+ id: z.string()
844
+ }),
845
+ READY_TO_DISPOSE: z.undefined(),
846
+ WAIT_FOR_DURATION: z.object({
847
+ version: z.literal("v1").default("v1"),
848
+ ms: z.number()
849
+ }),
850
+ WAIT_FOR_TASK: z.object({
851
+ version: z.literal("v1").default("v1"),
852
+ id: z.string()
853
+ }),
854
+ WAIT_FOR_BATCH: z.object({
855
+ version: z.literal("v1").default("v1"),
856
+ id: z.string(),
857
+ runs: z.string().array()
858
+ }),
859
+ UNCAUGHT_EXCEPTION: UncaughtExceptionMessage
860
+ };
861
+ var ProdChildToWorkerMessages = {
862
+ TASK_RUN_COMPLETED: {
863
+ message: z.object({
864
+ version: z.literal("v1").default("v1"),
865
+ execution: TaskRunExecution,
866
+ result: TaskRunExecutionResult
969
867
  })
970
868
  },
971
- GET: {
869
+ TASKS_READY: {
972
870
  message: z.object({
973
871
  version: z.literal("v1").default("v1"),
974
- name: z.string()
872
+ tasks: TaskMetadataWithFilePath.array()
975
873
  })
976
- }
977
- };
978
- var CoordinatorToPlatformMessages = {
979
- LOG: {
874
+ },
875
+ TASKS_FAILED_TO_PARSE: {
876
+ message: TaskMetadataFailedToParseData
877
+ },
878
+ TASK_HEARTBEAT: {
980
879
  message: z.object({
981
880
  version: z.literal("v1").default("v1"),
982
- metadata: z.any(),
983
- text: z.string()
881
+ id: z.string()
984
882
  })
985
883
  },
986
- CREATE_WORKER: {
884
+ READY_TO_DISPOSE: {
885
+ message: z.undefined()
886
+ },
887
+ READY_FOR_CHECKPOINT: {
888
+ message: z.object({
889
+ version: z.literal("v1").default("v1")
890
+ })
891
+ },
892
+ CANCEL_CHECKPOINT: {
893
+ message: z.object({
894
+ version: z.literal("v1").default("v1")
895
+ })
896
+ },
897
+ WAIT_FOR_DURATION: {
987
898
  message: z.object({
988
899
  version: z.literal("v1").default("v1"),
989
- projectRef: z.string(),
990
- envId: z.string(),
991
- deploymentId: z.string(),
992
- metadata: z.object({
993
- cliPackageVersion: z.string().optional(),
994
- contentHash: z.string(),
995
- packageVersion: z.string(),
996
- tasks: TaskResource.array()
997
- })
900
+ ms: z.number(),
901
+ now: z.number()
998
902
  }),
999
- callback: z.discriminatedUnion("success", [
1000
- z.object({
1001
- success: z.literal(false)
1002
- }),
1003
- z.object({
1004
- success: z.literal(true)
1005
- })
1006
- ])
903
+ callback: z.object({
904
+ willCheckpointAndRestore: z.boolean()
905
+ })
1007
906
  },
1008
- READY_FOR_EXECUTION: {
907
+ WAIT_FOR_TASK: {
1009
908
  message: z.object({
1010
909
  version: z.literal("v1").default("v1"),
1011
- runId: z.string(),
1012
- totalCompletions: z.number()
1013
- }),
1014
- callback: z.discriminatedUnion("success", [
1015
- z.object({
1016
- success: z.literal(false)
1017
- }),
1018
- z.object({
1019
- success: z.literal(true),
1020
- payload: ProdTaskRunExecutionPayload
1021
- })
1022
- ])
910
+ friendlyId: z.string()
911
+ })
1023
912
  },
1024
- READY_FOR_RESUME: {
913
+ WAIT_FOR_BATCH: {
1025
914
  message: z.object({
1026
915
  version: z.literal("v1").default("v1"),
1027
- attemptFriendlyId: z.string(),
1028
- type: WaitReason
916
+ batchFriendlyId: z.string(),
917
+ runFriendlyIds: z.string().array()
1029
918
  })
1030
919
  },
1031
- TASK_RUN_COMPLETED: {
920
+ UNCAUGHT_EXCEPTION: {
921
+ message: UncaughtExceptionMessage
922
+ }
923
+ };
924
+ var ProdWorkerToChildMessages = {
925
+ EXECUTE_TASK_RUN: {
1032
926
  message: z.object({
1033
927
  version: z.literal("v1").default("v1"),
1034
- execution: ProdTaskRunExecution,
1035
- completion: TaskRunExecutionResult,
1036
- checkpoint: z.object({
1037
- docker: z.boolean(),
1038
- location: z.string()
1039
- }).optional()
928
+ execution: TaskRunExecution,
929
+ traceContext: z.record(z.unknown()),
930
+ metadata: BackgroundWorkerProperties
1040
931
  })
1041
932
  },
1042
- TASK_HEARTBEAT: {
933
+ TASK_RUN_COMPLETED_NOTIFICATION: {
1043
934
  message: z.object({
1044
935
  version: z.literal("v1").default("v1"),
1045
- attemptFriendlyId: z.string()
936
+ completion: TaskRunExecutionResult,
937
+ execution: TaskRunExecution
1046
938
  })
1047
939
  },
1048
- CHECKPOINT_CREATED: {
940
+ CLEANUP: {
1049
941
  message: z.object({
1050
942
  version: z.literal("v1").default("v1"),
1051
- attemptFriendlyId: z.string(),
1052
- docker: z.boolean(),
1053
- location: z.string(),
1054
- reason: z.discriminatedUnion("type", [
1055
- z.object({
1056
- type: z.literal("WAIT_FOR_DURATION"),
1057
- ms: z.number(),
1058
- now: z.number()
1059
- }),
1060
- z.object({
1061
- type: z.literal("WAIT_FOR_BATCH"),
1062
- batchFriendlyId: z.string(),
1063
- runFriendlyIds: z.string().array()
1064
- }),
1065
- z.object({
1066
- type: z.literal("WAIT_FOR_TASK"),
1067
- friendlyId: z.string()
1068
- }),
1069
- z.object({
1070
- type: z.literal("RETRYING_AFTER_FAILURE"),
1071
- attemptNumber: z.number()
1072
- })
1073
- ])
1074
- })
1075
- },
1076
- INDEXING_FAILED: {
1077
- message: z.object({
1078
- version: z.literal("v1").default("v1"),
1079
- deploymentId: z.string(),
1080
- error: z.object({
1081
- name: z.string(),
1082
- message: z.string(),
1083
- stack: z.string().optional()
1084
- })
1085
- })
1086
- }
1087
- };
1088
- var PlatformToCoordinatorMessages = {
1089
- RESUME_AFTER_DEPENDENCY: {
1090
- message: z.object({
1091
- version: z.literal("v1").default("v1"),
1092
- runId: z.string(),
1093
- attemptId: z.string(),
1094
- attemptFriendlyId: z.string(),
1095
- completions: TaskRunExecutionResult.array(),
1096
- executions: TaskRunExecution.array()
1097
- })
1098
- },
1099
- RESUME_AFTER_DURATION: {
1100
- message: z.object({
1101
- version: z.literal("v1").default("v1"),
1102
- attemptId: z.string(),
1103
- attemptFriendlyId: z.string()
1104
- })
1105
- },
1106
- REQUEST_ATTEMPT_CANCELLATION: {
1107
- message: z.object({
1108
- version: z.literal("v1").default("v1"),
1109
- attemptId: z.string(),
1110
- attemptFriendlyId: z.string()
1111
- })
1112
- },
1113
- READY_FOR_RETRY: {
1114
- message: z.object({
1115
- version: z.literal("v1").default("v1"),
1116
- runId: z.string()
1117
- })
1118
- }
1119
- };
1120
- var ClientToSharedQueueMessages = {
1121
- READY_FOR_TASKS: {
1122
- message: z.object({
1123
- version: z.literal("v1").default("v1"),
1124
- backgroundWorkerId: z.string()
1125
- })
1126
- },
1127
- BACKGROUND_WORKER_DEPRECATED: {
1128
- message: z.object({
1129
- version: z.literal("v1").default("v1"),
1130
- backgroundWorkerId: z.string()
1131
- })
1132
- },
1133
- BACKGROUND_WORKER_MESSAGE: {
1134
- message: z.object({
1135
- version: z.literal("v1").default("v1"),
1136
- backgroundWorkerId: z.string(),
1137
- data: BackgroundWorkerClientMessages
1138
- })
1139
- }
1140
- };
1141
- var SharedQueueToClientMessages = {
1142
- SERVER_READY: {
1143
- message: z.object({
1144
- version: z.literal("v1").default("v1"),
1145
- id: z.string()
1146
- })
1147
- },
1148
- BACKGROUND_WORKER_MESSAGE: {
1149
- message: z.object({
1150
- version: z.literal("v1").default("v1"),
1151
- backgroundWorkerId: z.string(),
1152
- data: BackgroundWorkerServerMessages
1153
- })
1154
- }
1155
- };
1156
- var ProdWorkerToCoordinatorMessages = {
1157
- LOG: {
1158
- message: z.object({
1159
- version: z.literal("v1").default("v1"),
1160
- text: z.string()
943
+ flush: z.boolean().default(false),
944
+ kill: z.boolean().default(true)
1161
945
  }),
1162
946
  callback: z.void()
1163
947
  },
1164
- INDEX_TASKS: {
1165
- message: z.object({
1166
- version: z.literal("v1").default("v1"),
1167
- deploymentId: z.string(),
1168
- tasks: TaskResource.array(),
1169
- packageVersion: z.string()
1170
- }),
1171
- callback: z.discriminatedUnion("success", [
1172
- z.object({
1173
- success: z.literal(false)
1174
- }),
1175
- z.object({
1176
- success: z.literal(true)
1177
- })
1178
- ])
1179
- },
1180
- READY_FOR_EXECUTION: {
1181
- message: z.object({
1182
- version: z.literal("v1").default("v1"),
1183
- runId: z.string(),
1184
- totalCompletions: z.number()
1185
- })
1186
- },
1187
- READY_FOR_RESUME: {
1188
- message: z.object({
1189
- version: z.literal("v1").default("v1"),
1190
- attemptFriendlyId: z.string(),
1191
- type: WaitReason
1192
- })
1193
- },
1194
- READY_FOR_CHECKPOINT: {
1195
- message: z.object({
1196
- version: z.literal("v1").default("v1")
1197
- })
1198
- },
1199
- CANCEL_CHECKPOINT: {
1200
- message: z.object({
1201
- version: z.literal("v1").default("v1")
1202
- })
1203
- },
1204
- TASK_HEARTBEAT: {
1205
- message: z.object({
1206
- version: z.literal("v1").default("v1"),
1207
- attemptFriendlyId: z.string()
1208
- })
1209
- },
1210
- TASK_RUN_COMPLETED: {
1211
- message: z.object({
1212
- version: z.literal("v1").default("v1"),
1213
- execution: ProdTaskRunExecution,
1214
- completion: TaskRunExecutionResult
1215
- }),
1216
- callback: z.object({
1217
- willCheckpointAndRestore: z.boolean(),
1218
- shouldExit: z.boolean()
1219
- })
1220
- },
1221
- WAIT_FOR_DURATION: {
1222
- message: z.object({
1223
- version: z.literal("v1").default("v1"),
1224
- ms: z.number(),
1225
- now: z.number(),
1226
- attemptFriendlyId: z.string()
1227
- }),
1228
- callback: z.object({
1229
- willCheckpointAndRestore: z.boolean()
1230
- })
1231
- },
1232
- WAIT_FOR_TASK: {
1233
- message: z.object({
1234
- version: z.literal("v1").default("v1"),
1235
- friendlyId: z.string(),
1236
- // This is the attempt that is waiting
1237
- attemptFriendlyId: z.string()
1238
- }),
1239
- callback: z.object({
1240
- willCheckpointAndRestore: z.boolean()
1241
- })
1242
- },
1243
- WAIT_FOR_BATCH: {
1244
- message: z.object({
1245
- version: z.literal("v1").default("v1"),
1246
- batchFriendlyId: z.string(),
1247
- runFriendlyIds: z.string().array(),
1248
- // This is the attempt that is waiting
1249
- attemptFriendlyId: z.string()
1250
- }),
1251
- callback: z.object({
1252
- willCheckpointAndRestore: z.boolean()
1253
- })
1254
- },
1255
- INDEXING_FAILED: {
1256
- message: z.object({
1257
- version: z.literal("v1").default("v1"),
1258
- deploymentId: z.string(),
1259
- error: z.object({
1260
- name: z.string(),
1261
- message: z.string(),
1262
- stack: z.string().optional()
1263
- })
1264
- })
1265
- }
1266
- };
1267
- var CoordinatorToProdWorkerMessages = {
1268
- RESUME_AFTER_DEPENDENCY: {
1269
- message: z.object({
1270
- version: z.literal("v1").default("v1"),
1271
- attemptId: z.string(),
1272
- completions: TaskRunExecutionResult.array(),
1273
- executions: TaskRunExecution.array()
1274
- })
1275
- },
1276
- RESUME_AFTER_DURATION: {
1277
- message: z.object({
1278
- version: z.literal("v1").default("v1"),
1279
- attemptId: z.string()
1280
- })
1281
- },
1282
- EXECUTE_TASK_RUN: {
1283
- message: z.object({
1284
- version: z.literal("v1").default("v1"),
1285
- executionPayload: ProdTaskRunExecutionPayload
1286
- })
1287
- },
1288
- REQUEST_ATTEMPT_CANCELLATION: {
1289
- message: z.object({
1290
- version: z.literal("v1").default("v1"),
1291
- attemptId: z.string()
1292
- })
1293
- },
1294
- REQUEST_EXIT: {
948
+ WAIT_COMPLETED_NOTIFICATION: {
1295
949
  message: z.object({
1296
950
  version: z.literal("v1").default("v1")
1297
951
  })
1298
- },
1299
- READY_FOR_RETRY: {
1300
- message: z.object({
1301
- version: z.literal("v1").default("v1"),
1302
- runId: z.string()
1303
- })
1304
952
  }
1305
953
  };
1306
- var ProdWorkerSocketData = z.object({
954
+
955
+ // src/v3/schemas/resources.ts
956
+ var TaskResource = z.object({
957
+ id: z.string(),
958
+ filePath: z.string(),
959
+ exportName: z.string(),
960
+ queue: QueueOptions.optional(),
961
+ retry: RetryOptions.optional(),
962
+ machine: Machine.partial().optional(),
963
+ triggerSource: z.string().optional()
964
+ });
965
+ var BackgroundWorkerMetadata = z.object({
966
+ packageVersion: z.string(),
1307
967
  contentHash: z.string(),
1308
- projectRef: z.string(),
1309
- envId: z.string(),
1310
- runId: z.string(),
1311
- attemptFriendlyId: z.string().optional(),
1312
- podName: z.string(),
1313
- deploymentId: z.string(),
1314
- deploymentVersion: z.string()
1315
- });
1316
- var PRIMARY_VARIANT = "primary";
1317
- var Variant = z.enum([
1318
- PRIMARY_VARIANT
1319
- ]);
1320
- var AccessoryItem = z.object({
1321
- text: z.string(),
1322
- variant: z.string().optional(),
1323
- url: z.string().optional()
1324
- });
1325
- var Accessory = z.object({
1326
- items: z.array(AccessoryItem),
1327
- style: z.enum([
1328
- "codepath"
1329
- ]).optional()
968
+ cliPackageVersion: z.string().optional(),
969
+ tasks: z.array(TaskResource)
1330
970
  });
1331
- var TaskEventStyle = z.object({
1332
- icon: z.string().optional(),
1333
- variant: Variant.optional(),
1334
- accessory: Accessory.optional()
1335
- }).default({
1336
- icon: void 0,
1337
- variant: void 0
971
+ var ImageDetailsMetadata = z.object({
972
+ contentHash: z.string(),
973
+ imageTag: z.string()
1338
974
  });
1339
- var stringPatternMatchers = [
1340
- z.object({
1341
- $endsWith: z.string()
1342
- }),
1343
- z.object({
1344
- $startsWith: z.string()
1345
- }),
1346
- z.object({
1347
- $ignoreCaseEquals: z.string()
1348
- })
1349
- ];
1350
- var EventMatcher = z.union([
1351
- /** Match against a string */
1352
- z.array(z.string()),
1353
- /** Match against a number */
1354
- z.array(z.number()),
1355
- /** Match against a boolean */
1356
- z.array(z.boolean()),
1357
- z.array(z.union([
1358
- ...stringPatternMatchers,
1359
- z.object({
1360
- $exists: z.boolean()
1361
- }),
1362
- z.object({
1363
- $isNull: z.boolean()
1364
- }),
1365
- z.object({
1366
- $anythingBut: z.union([
1367
- z.string(),
1368
- z.number(),
1369
- z.boolean()
1370
- ])
1371
- }),
1372
- z.object({
1373
- $anythingBut: z.union([
1374
- z.array(z.string()),
1375
- z.array(z.number()),
1376
- z.array(z.boolean())
1377
- ])
1378
- }),
1379
- z.object({
1380
- $gt: z.number()
1381
- }),
1382
- z.object({
1383
- $lt: z.number()
1384
- }),
1385
- z.object({
1386
- $gte: z.number()
1387
- }),
1388
- z.object({
1389
- $lte: z.number()
1390
- }),
1391
- z.object({
1392
- $between: z.tuple([
1393
- z.number(),
1394
- z.number()
1395
- ])
1396
- }),
1397
- z.object({
1398
- $includes: z.union([
1399
- z.string(),
1400
- z.number(),
1401
- z.boolean()
1402
- ])
1403
- }),
1404
- z.object({
1405
- $not: z.union([
1406
- z.string(),
1407
- z.number(),
1408
- z.boolean()
1409
- ])
1410
- })
1411
- ]))
1412
- ]);
1413
- var EventFilter = z.lazy(() => z.record(z.union([
1414
- EventMatcher,
1415
- EventFilter
1416
- ])));
1417
975
 
1418
- // src/v3/schemas/fetch.ts
1419
- var FetchRetryHeadersStrategy = z.object({
1420
- /** The `headers` strategy retries the request using info from the response headers. */
1421
- strategy: z.literal("headers"),
1422
- /** The header to use to determine the maximum number of times to retry the request. */
1423
- limitHeader: z.string(),
1424
- /** The header to use to determine the number of remaining retries. */
1425
- remainingHeader: z.string(),
1426
- /** The header to use to determine the time when the number of remaining retries will be reset. */
1427
- resetHeader: z.string(),
1428
- /** The event filter to use to determine if the request should be retried. */
1429
- bodyFilter: EventFilter.optional(),
1430
- /** The format of the `resetHeader` value. */
1431
- resetFormat: z.enum([
1432
- "unix_timestamp",
1433
- "unix_timestamp_in_ms",
1434
- "iso_8601",
1435
- "iso_8601_duration_openai_variant"
1436
- ]).default("unix_timestamp").optional()
976
+ // src/v3/schemas/api.ts
977
+ var WhoAmIResponseSchema = z.object({
978
+ userId: z.string(),
979
+ email: z.string().email(),
980
+ dashboardUrl: z.string()
1437
981
  });
1438
- var FetchRetryBackoffStrategy = RetryOptions.extend({
1439
- /** The `backoff` strategy retries the request with an exponential backoff. */
1440
- strategy: z.literal("backoff"),
1441
- /** The event filter to use to determine if the request should be retried. */
1442
- bodyFilter: EventFilter.optional()
982
+ var GetProjectResponseBody = z.object({
983
+ id: z.string(),
984
+ externalRef: z.string(),
985
+ name: z.string(),
986
+ slug: z.string(),
987
+ createdAt: z.coerce.date(),
988
+ organization: z.object({
989
+ id: z.string(),
990
+ title: z.string(),
991
+ slug: z.string(),
992
+ createdAt: z.coerce.date()
993
+ })
1443
994
  });
1444
- var FetchRetryStrategy = z.discriminatedUnion("strategy", [
1445
- FetchRetryHeadersStrategy,
1446
- FetchRetryBackoffStrategy
1447
- ]);
1448
- var FetchRetryByStatusOptions = z.record(z.string(), FetchRetryStrategy);
1449
- var FetchTimeoutOptions = z.object({
1450
- /** The maximum time to wait for the request to complete. */
1451
- durationInMs: z.number().optional(),
1452
- retry: RetryOptions.optional()
995
+ var GetProjectsResponseBody = z.array(GetProjectResponseBody);
996
+ var GetProjectEnvResponse = z.object({
997
+ apiKey: z.string(),
998
+ name: z.string(),
999
+ apiUrl: z.string()
1453
1000
  });
1454
- var FetchRetryOptions = z.object({
1455
- /** The retrying strategy for specific status codes. */
1456
- byStatus: FetchRetryByStatusOptions.optional(),
1457
- /** The timeout options for the request. */
1458
- timeout: RetryOptions.optional(),
1459
- /**
1460
- * The retrying strategy for connection errors.
1461
- */
1462
- connectionError: RetryOptions.optional()
1001
+ var CreateBackgroundWorkerRequestBody = z.object({
1002
+ localOnly: z.boolean(),
1003
+ metadata: BackgroundWorkerMetadata
1463
1004
  });
1464
- var ExceptionEventProperties = z.object({
1465
- type: z.string().optional(),
1466
- message: z.string().optional(),
1467
- stacktrace: z.string().optional()
1005
+ var CreateBackgroundWorkerResponse = z.object({
1006
+ id: z.string(),
1007
+ version: z.string(),
1008
+ contentHash: z.string()
1468
1009
  });
1469
- var ExceptionSpanEvent = z.object({
1470
- name: z.literal("exception"),
1471
- time: z.coerce.date(),
1472
- properties: z.object({
1473
- exception: ExceptionEventProperties
1474
- })
1010
+ var TriggerTaskRequestBody = z.object({
1011
+ payload: z.any(),
1012
+ context: z.any(),
1013
+ options: z.object({
1014
+ dependentAttempt: z.string().optional(),
1015
+ dependentBatch: z.string().optional(),
1016
+ lockToVersion: z.string().optional(),
1017
+ queue: QueueOptions.optional(),
1018
+ concurrencyKey: z.string().optional(),
1019
+ idempotencyKey: z.string().optional(),
1020
+ test: z.boolean().optional(),
1021
+ payloadType: z.string().optional()
1022
+ }).optional()
1475
1023
  });
1476
- var CancellationSpanEvent = z.object({
1477
- name: z.literal("cancellation"),
1478
- time: z.coerce.date(),
1479
- properties: z.object({
1480
- reason: z.string()
1481
- })
1024
+ var TriggerTaskResponse = z.object({
1025
+ id: z.string()
1482
1026
  });
1483
- var OtherSpanEvent = z.object({
1484
- name: z.string(),
1485
- time: z.coerce.date(),
1486
- properties: z.record(z.unknown())
1027
+ var BatchTriggerTaskRequestBody = z.object({
1028
+ items: TriggerTaskRequestBody.array(),
1029
+ dependentAttempt: z.string().optional()
1487
1030
  });
1488
- var SpanEvent = z.union([
1489
- ExceptionSpanEvent,
1490
- CancellationSpanEvent,
1491
- OtherSpanEvent
1492
- ]);
1493
- var SpanEvents = z.array(SpanEvent);
1494
- function isExceptionSpanEvent(event) {
1495
- return event.name === "exception";
1496
- }
1497
- __name(isExceptionSpanEvent, "isExceptionSpanEvent");
1498
- function isCancellationSpanEvent(event) {
1499
- return event.name === "cancellation";
1500
- }
1501
- __name(isCancellationSpanEvent, "isCancellationSpanEvent");
1502
- var SpanMessagingEvent = z.object({
1503
- system: z.string().optional(),
1504
- client_id: z.string().optional(),
1505
- operation: z.enum([
1506
- "publish",
1507
- "create",
1508
- "receive",
1509
- "deliver"
1510
- ]),
1511
- message: z.any(),
1512
- destination: z.string().optional()
1031
+ var BatchTriggerTaskResponse = z.object({
1032
+ batchId: z.string(),
1033
+ runs: z.string().array()
1513
1034
  });
1514
-
1515
- // src/v3/apiErrors.ts
1516
- var _APIError = class _APIError extends Error {
1517
- constructor(status, error, message, headers) {
1518
- super(`${_APIError.makeMessage(status, error, message)}`);
1519
- this.status = status;
1520
- this.headers = headers;
1521
- const data = error;
1522
- this.error = data;
1523
- this.code = data?.["code"];
1524
- this.param = data?.["param"];
1525
- this.type = data?.["type"];
1035
+ var GetBatchResponseBody = z.object({
1036
+ id: z.string(),
1037
+ items: z.array(z.object({
1038
+ id: z.string(),
1039
+ taskRunId: z.string(),
1040
+ status: z.enum([
1041
+ "PENDING",
1042
+ "CANCELED",
1043
+ "COMPLETED",
1044
+ "FAILED"
1045
+ ])
1046
+ }))
1047
+ });
1048
+ var GetEnvironmentVariablesResponseBody = z.object({
1049
+ variables: z.record(z.string())
1050
+ });
1051
+ var StartDeploymentIndexingRequestBody = z.object({
1052
+ imageReference: z.string()
1053
+ });
1054
+ var StartDeploymentIndexingResponseBody = z.object({
1055
+ id: z.string(),
1056
+ contentHash: z.string()
1057
+ });
1058
+ var ExternalBuildData = z.object({
1059
+ buildId: z.string(),
1060
+ buildToken: z.string(),
1061
+ projectId: z.string()
1062
+ });
1063
+ var InitializeDeploymentResponseBody = z.object({
1064
+ id: z.string(),
1065
+ contentHash: z.string(),
1066
+ shortCode: z.string(),
1067
+ version: z.string(),
1068
+ imageTag: z.string(),
1069
+ externalBuildData: ExternalBuildData.optional().nullable(),
1070
+ registryHost: z.string().optional()
1071
+ });
1072
+ var InitializeDeploymentRequestBody = z.object({
1073
+ contentHash: z.string(),
1074
+ userId: z.string().optional()
1075
+ });
1076
+ var DeploymentErrorData = z.object({
1077
+ name: z.string(),
1078
+ message: z.string(),
1079
+ stack: z.string().optional()
1080
+ });
1081
+ var GetDeploymentResponseBody = z.object({
1082
+ id: z.string(),
1083
+ status: z.enum([
1084
+ "PENDING",
1085
+ "BUILDING",
1086
+ "DEPLOYING",
1087
+ "DEPLOYED",
1088
+ "FAILED",
1089
+ "CANCELED",
1090
+ "TIMED_OUT"
1091
+ ]),
1092
+ contentHash: z.string(),
1093
+ shortCode: z.string(),
1094
+ version: z.string(),
1095
+ imageReference: z.string().optional(),
1096
+ errorData: DeploymentErrorData.optional().nullable(),
1097
+ worker: z.object({
1098
+ id: z.string(),
1099
+ version: z.string(),
1100
+ tasks: z.array(z.object({
1101
+ id: z.string(),
1102
+ slug: z.string(),
1103
+ filePath: z.string(),
1104
+ exportName: z.string()
1105
+ }))
1106
+ }).optional()
1107
+ });
1108
+ var CreateUploadPayloadUrlResponseBody = z.object({
1109
+ presignedUrl: z.string()
1110
+ });
1111
+ var ReplayRunResponse = z.object({
1112
+ id: z.string()
1113
+ });
1114
+ var CanceledRunResponse = z.object({
1115
+ message: z.string()
1116
+ });
1117
+ var ScheduledTaskPayload = z.object({
1118
+ /** The schedule id associated with this run (you can have many schedules for the same task).
1119
+ You can use this to remove the schedule, update it, etc */
1120
+ scheduleId: z.string(),
1121
+ /** When the task was scheduled to run.
1122
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
1123
+ timestamp: z.date(),
1124
+ /** When the task was last run (it has been).
1125
+ This can be undefined if it's never been run */
1126
+ lastTimestamp: z.date().optional(),
1127
+ /** You can optionally provide an external id when creating the schedule.
1128
+ Usually you would use a userId or some other unique identifier.
1129
+ This defaults to undefined if you didn't provide one. */
1130
+ externalId: z.string().optional(),
1131
+ /** The next 5 dates this task is scheduled to run */
1132
+ upcoming: z.array(z.date())
1133
+ });
1134
+ var CreateScheduleOptions = z.object({
1135
+ /** The id of the task you want to attach to. */
1136
+ task: z.string(),
1137
+ /** The schedule in CRON format.
1138
+ *
1139
+ * ```txt
1140
+ * * * * * *
1141
+ ┬ ┬ ┬ ┬ ┬
1142
+ │ │ │ │ |
1143
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
1144
+ │ │ │ └───── month (1 - 12)
1145
+ │ │ └────────── day of month (1 - 31, L)
1146
+ │ └─────────────── hour (0 - 23)
1147
+ └──────────────────── minute (0 - 59)
1148
+ * ```
1149
+
1150
+ "L" means the last. In the "day of week" field, 1L means the last Monday of the month. In the day of month field, L means the last day of the month.
1151
+
1152
+ */
1153
+ cron: z.string(),
1154
+ /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1155
+ *
1156
+ * This is useful if you don't want to create duplicate schedules for a user. */
1157
+ deduplicationKey: z.string().optional(),
1158
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
1159
+ *
1160
+ * This allows you to have per-user CRON tasks.
1161
+ */
1162
+ externalId: z.string().optional()
1163
+ });
1164
+ var UpdateScheduleOptions = CreateScheduleOptions;
1165
+ var ScheduleObject = z.object({
1166
+ id: z.string(),
1167
+ task: z.string(),
1168
+ active: z.boolean(),
1169
+ deduplicationKey: z.string().nullish(),
1170
+ externalId: z.string().nullish(),
1171
+ generator: z.object({
1172
+ type: z.literal("CRON"),
1173
+ expression: z.string(),
1174
+ description: z.string()
1175
+ }),
1176
+ nextRun: z.coerce.date().nullish(),
1177
+ environments: z.array(z.object({
1178
+ id: z.string(),
1179
+ type: z.string(),
1180
+ userName: z.string().nullish()
1181
+ }))
1182
+ });
1183
+ var DeletedScheduleObject = z.object({
1184
+ id: z.string()
1185
+ });
1186
+ var ListSchedulesResult = z.object({
1187
+ data: z.array(ScheduleObject),
1188
+ pagination: z.object({
1189
+ currentPage: z.number(),
1190
+ totalPages: z.number(),
1191
+ count: z.number()
1192
+ })
1193
+ });
1194
+ var ListScheduleOptions = z.object({
1195
+ page: z.number().optional(),
1196
+ perPage: z.number().optional()
1197
+ });
1198
+ var PostStartCauses = z.enum([
1199
+ "index",
1200
+ "create",
1201
+ "restore"
1202
+ ]);
1203
+ var PreStopCauses = z.enum([
1204
+ "terminate"
1205
+ ]);
1206
+ var RegexSchema = z.custom((val) => {
1207
+ try {
1208
+ return typeof val.test === "function";
1209
+ } catch {
1210
+ return false;
1526
1211
  }
1527
- static makeMessage(status, error, message) {
1528
- const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1529
- if (status && msg) {
1530
- return `${status} ${msg}`;
1531
- }
1532
- if (status) {
1533
- return `${status} status code (no body)`;
1534
- }
1535
- if (msg) {
1536
- return msg;
1537
- }
1538
- return "(no status code or body)";
1212
+ });
1213
+ var Config = z.object({
1214
+ project: z.string(),
1215
+ triggerDirectories: z.string().array().optional(),
1216
+ triggerUrl: z.string().optional(),
1217
+ projectDir: z.string().optional(),
1218
+ tsconfigPath: z.string().optional(),
1219
+ retries: z.object({
1220
+ enabledInDev: z.boolean().default(true),
1221
+ default: RetryOptions.optional()
1222
+ }).optional(),
1223
+ additionalPackages: z.string().array().optional(),
1224
+ additionalFiles: z.string().array().optional(),
1225
+ dependenciesToBundle: z.array(z.union([
1226
+ z.string(),
1227
+ RegexSchema
1228
+ ])).optional(),
1229
+ logLevel: z.string().optional(),
1230
+ enableConsoleLogging: z.boolean().optional()
1231
+ });
1232
+ var WaitReason = z.enum([
1233
+ "WAIT_FOR_DURATION",
1234
+ "WAIT_FOR_TASK",
1235
+ "WAIT_FOR_BATCH"
1236
+ ]);
1237
+ var ProviderToPlatformMessages = {
1238
+ LOG: {
1239
+ message: z.object({
1240
+ version: z.literal("v1").default("v1"),
1241
+ data: z.string()
1242
+ })
1243
+ },
1244
+ LOG_WITH_ACK: {
1245
+ message: z.object({
1246
+ version: z.literal("v1").default("v1"),
1247
+ data: z.string()
1248
+ }),
1249
+ callback: z.object({
1250
+ status: z.literal("ok")
1251
+ })
1252
+ },
1253
+ WORKER_CRASHED: {
1254
+ message: z.object({
1255
+ version: z.literal("v1").default("v1"),
1256
+ runId: z.string(),
1257
+ reason: z.string().optional(),
1258
+ exitCode: z.number().optional(),
1259
+ message: z.string().optional(),
1260
+ logs: z.string().optional()
1261
+ })
1262
+ },
1263
+ INDEXING_FAILED: {
1264
+ message: z.object({
1265
+ version: z.literal("v1").default("v1"),
1266
+ deploymentId: z.string(),
1267
+ error: z.object({
1268
+ name: z.string(),
1269
+ message: z.string(),
1270
+ stack: z.string().optional()
1271
+ })
1272
+ })
1539
1273
  }
1540
- static generate(status, errorResponse, message, headers) {
1541
- if (!status) {
1542
- return new APIConnectionError({
1543
- cause: castToError(errorResponse)
1544
- });
1545
- }
1546
- const error = errorResponse?.["error"];
1547
- if (status === 400) {
1548
- return new BadRequestError(status, error, message, headers);
1549
- }
1550
- if (status === 401) {
1551
- return new AuthenticationError(status, error, message, headers);
1552
- }
1553
- if (status === 403) {
1554
- return new PermissionDeniedError(status, error, message, headers);
1555
- }
1556
- if (status === 404) {
1557
- return new NotFoundError(status, error, message, headers);
1558
- }
1559
- if (status === 409) {
1560
- return new ConflictError(status, error, message, headers);
1561
- }
1562
- if (status === 422) {
1563
- return new UnprocessableEntityError(status, error, message, headers);
1564
- }
1565
- if (status === 429) {
1566
- return new RateLimitError(status, error, message, headers);
1567
- }
1568
- if (status >= 500) {
1569
- return new InternalServerError(status, error, message, headers);
1570
- }
1571
- return new _APIError(status, error, message, headers);
1274
+ };
1275
+ var PlatformToProviderMessages = {
1276
+ HEALTH: {
1277
+ message: z.object({
1278
+ version: z.literal("v1").default("v1")
1279
+ }),
1280
+ callback: z.object({
1281
+ status: z.literal("ok")
1282
+ })
1283
+ },
1284
+ INDEX: {
1285
+ message: z.object({
1286
+ version: z.literal("v1").default("v1"),
1287
+ imageTag: z.string(),
1288
+ shortCode: z.string(),
1289
+ apiKey: z.string(),
1290
+ apiUrl: z.string(),
1291
+ // identifiers
1292
+ envId: z.string(),
1293
+ envType: EnvironmentType,
1294
+ orgId: z.string(),
1295
+ projectId: z.string(),
1296
+ deploymentId: z.string()
1297
+ }),
1298
+ callback: z.discriminatedUnion("success", [
1299
+ z.object({
1300
+ success: z.literal(false),
1301
+ error: z.object({
1302
+ name: z.string(),
1303
+ message: z.string(),
1304
+ stack: z.string().optional()
1305
+ })
1306
+ }),
1307
+ z.object({
1308
+ success: z.literal(true)
1309
+ })
1310
+ ])
1311
+ },
1312
+ // TODO: this should be a shared queue message instead
1313
+ RESTORE: {
1314
+ message: z.object({
1315
+ version: z.literal("v1").default("v1"),
1316
+ type: z.enum([
1317
+ "DOCKER",
1318
+ "KUBERNETES"
1319
+ ]),
1320
+ location: z.string(),
1321
+ reason: z.string().optional(),
1322
+ imageRef: z.string(),
1323
+ machine: Machine,
1324
+ // identifiers
1325
+ checkpointId: z.string(),
1326
+ envId: z.string(),
1327
+ envType: EnvironmentType,
1328
+ orgId: z.string(),
1329
+ projectId: z.string(),
1330
+ runId: z.string()
1331
+ })
1332
+ },
1333
+ DELETE: {
1334
+ message: z.object({
1335
+ version: z.literal("v1").default("v1"),
1336
+ name: z.string()
1337
+ }),
1338
+ callback: z.object({
1339
+ message: z.string()
1340
+ })
1341
+ },
1342
+ GET: {
1343
+ message: z.object({
1344
+ version: z.literal("v1").default("v1"),
1345
+ name: z.string()
1346
+ })
1572
1347
  }
1573
1348
  };
1574
- __name(_APIError, "APIError");
1575
- var APIError = _APIError;
1576
- var _APIConnectionError = class _APIConnectionError extends APIError {
1577
- constructor({ message, cause }) {
1578
- super(void 0, void 0, message || "Connection error.", void 0);
1579
- __publicField(this, "status");
1580
- if (cause)
1581
- this.cause = cause;
1349
+ var CoordinatorToPlatformMessages = {
1350
+ LOG: {
1351
+ message: z.object({
1352
+ version: z.literal("v1").default("v1"),
1353
+ metadata: z.any(),
1354
+ text: z.string()
1355
+ })
1356
+ },
1357
+ CREATE_WORKER: {
1358
+ message: z.object({
1359
+ version: z.literal("v1").default("v1"),
1360
+ projectRef: z.string(),
1361
+ envId: z.string(),
1362
+ deploymentId: z.string(),
1363
+ metadata: z.object({
1364
+ cliPackageVersion: z.string().optional(),
1365
+ contentHash: z.string(),
1366
+ packageVersion: z.string(),
1367
+ tasks: TaskResource.array()
1368
+ })
1369
+ }),
1370
+ callback: z.discriminatedUnion("success", [
1371
+ z.object({
1372
+ success: z.literal(false)
1373
+ }),
1374
+ z.object({
1375
+ success: z.literal(true)
1376
+ })
1377
+ ])
1378
+ },
1379
+ READY_FOR_EXECUTION: {
1380
+ message: z.object({
1381
+ version: z.literal("v1").default("v1"),
1382
+ runId: z.string(),
1383
+ totalCompletions: z.number()
1384
+ }),
1385
+ callback: z.discriminatedUnion("success", [
1386
+ z.object({
1387
+ success: z.literal(false)
1388
+ }),
1389
+ z.object({
1390
+ success: z.literal(true),
1391
+ payload: ProdTaskRunExecutionPayload
1392
+ })
1393
+ ])
1394
+ },
1395
+ READY_FOR_RESUME: {
1396
+ message: z.object({
1397
+ version: z.literal("v1").default("v1"),
1398
+ attemptFriendlyId: z.string(),
1399
+ type: WaitReason
1400
+ })
1401
+ },
1402
+ TASK_RUN_COMPLETED: {
1403
+ message: z.object({
1404
+ version: z.literal("v1").default("v1"),
1405
+ execution: ProdTaskRunExecution,
1406
+ completion: TaskRunExecutionResult,
1407
+ checkpoint: z.object({
1408
+ docker: z.boolean(),
1409
+ location: z.string()
1410
+ }).optional()
1411
+ })
1412
+ },
1413
+ TASK_HEARTBEAT: {
1414
+ message: z.object({
1415
+ version: z.literal("v1").default("v1"),
1416
+ attemptFriendlyId: z.string()
1417
+ })
1418
+ },
1419
+ CHECKPOINT_CREATED: {
1420
+ message: z.object({
1421
+ version: z.literal("v1").default("v1"),
1422
+ attemptFriendlyId: z.string(),
1423
+ docker: z.boolean(),
1424
+ location: z.string(),
1425
+ reason: z.discriminatedUnion("type", [
1426
+ z.object({
1427
+ type: z.literal("WAIT_FOR_DURATION"),
1428
+ ms: z.number(),
1429
+ now: z.number()
1430
+ }),
1431
+ z.object({
1432
+ type: z.literal("WAIT_FOR_BATCH"),
1433
+ batchFriendlyId: z.string(),
1434
+ runFriendlyIds: z.string().array()
1435
+ }),
1436
+ z.object({
1437
+ type: z.literal("WAIT_FOR_TASK"),
1438
+ friendlyId: z.string()
1439
+ }),
1440
+ z.object({
1441
+ type: z.literal("RETRYING_AFTER_FAILURE"),
1442
+ attemptNumber: z.number()
1443
+ })
1444
+ ])
1445
+ })
1446
+ },
1447
+ INDEXING_FAILED: {
1448
+ message: z.object({
1449
+ version: z.literal("v1").default("v1"),
1450
+ deploymentId: z.string(),
1451
+ error: z.object({
1452
+ name: z.string(),
1453
+ message: z.string(),
1454
+ stack: z.string().optional()
1455
+ })
1456
+ })
1582
1457
  }
1583
1458
  };
1584
- __name(_APIConnectionError, "APIConnectionError");
1585
- var APIConnectionError = _APIConnectionError;
1586
- var _BadRequestError = class _BadRequestError extends APIError {
1587
- constructor() {
1588
- super(...arguments);
1589
- __publicField(this, "status", 400);
1459
+ var PlatformToCoordinatorMessages = {
1460
+ RESUME_AFTER_DEPENDENCY: {
1461
+ message: z.object({
1462
+ version: z.literal("v1").default("v1"),
1463
+ runId: z.string(),
1464
+ attemptId: z.string(),
1465
+ attemptFriendlyId: z.string(),
1466
+ completions: TaskRunExecutionResult.array(),
1467
+ executions: TaskRunExecution.array()
1468
+ })
1469
+ },
1470
+ RESUME_AFTER_DURATION: {
1471
+ message: z.object({
1472
+ version: z.literal("v1").default("v1"),
1473
+ attemptId: z.string(),
1474
+ attemptFriendlyId: z.string()
1475
+ })
1476
+ },
1477
+ REQUEST_ATTEMPT_CANCELLATION: {
1478
+ message: z.object({
1479
+ version: z.literal("v1").default("v1"),
1480
+ attemptId: z.string(),
1481
+ attemptFriendlyId: z.string()
1482
+ })
1483
+ },
1484
+ READY_FOR_RETRY: {
1485
+ message: z.object({
1486
+ version: z.literal("v1").default("v1"),
1487
+ runId: z.string()
1488
+ })
1590
1489
  }
1591
1490
  };
1592
- __name(_BadRequestError, "BadRequestError");
1593
- var BadRequestError = _BadRequestError;
1594
- var _AuthenticationError = class _AuthenticationError extends APIError {
1595
- constructor() {
1596
- super(...arguments);
1597
- __publicField(this, "status", 401);
1598
- }
1599
- };
1600
- __name(_AuthenticationError, "AuthenticationError");
1601
- var AuthenticationError = _AuthenticationError;
1602
- var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
1603
- constructor() {
1604
- super(...arguments);
1605
- __publicField(this, "status", 403);
1606
- }
1607
- };
1608
- __name(_PermissionDeniedError, "PermissionDeniedError");
1609
- var PermissionDeniedError = _PermissionDeniedError;
1610
- var _NotFoundError = class _NotFoundError extends APIError {
1611
- constructor() {
1612
- super(...arguments);
1613
- __publicField(this, "status", 404);
1491
+ var ClientToSharedQueueMessages = {
1492
+ READY_FOR_TASKS: {
1493
+ message: z.object({
1494
+ version: z.literal("v1").default("v1"),
1495
+ backgroundWorkerId: z.string()
1496
+ })
1497
+ },
1498
+ BACKGROUND_WORKER_DEPRECATED: {
1499
+ message: z.object({
1500
+ version: z.literal("v1").default("v1"),
1501
+ backgroundWorkerId: z.string()
1502
+ })
1503
+ },
1504
+ BACKGROUND_WORKER_MESSAGE: {
1505
+ message: z.object({
1506
+ version: z.literal("v1").default("v1"),
1507
+ backgroundWorkerId: z.string(),
1508
+ data: BackgroundWorkerClientMessages
1509
+ })
1614
1510
  }
1615
1511
  };
1616
- __name(_NotFoundError, "NotFoundError");
1617
- var NotFoundError = _NotFoundError;
1618
- var _ConflictError = class _ConflictError extends APIError {
1619
- constructor() {
1620
- super(...arguments);
1621
- __publicField(this, "status", 409);
1512
+ var SharedQueueToClientMessages = {
1513
+ SERVER_READY: {
1514
+ message: z.object({
1515
+ version: z.literal("v1").default("v1"),
1516
+ id: z.string()
1517
+ })
1518
+ },
1519
+ BACKGROUND_WORKER_MESSAGE: {
1520
+ message: z.object({
1521
+ version: z.literal("v1").default("v1"),
1522
+ backgroundWorkerId: z.string(),
1523
+ data: BackgroundWorkerServerMessages
1524
+ })
1622
1525
  }
1623
1526
  };
1624
- __name(_ConflictError, "ConflictError");
1625
- var ConflictError = _ConflictError;
1626
- var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
1627
- constructor() {
1628
- super(...arguments);
1629
- __publicField(this, "status", 422);
1527
+ var ProdWorkerToCoordinatorMessages = {
1528
+ LOG: {
1529
+ message: z.object({
1530
+ version: z.literal("v1").default("v1"),
1531
+ text: z.string()
1532
+ }),
1533
+ callback: z.void()
1534
+ },
1535
+ INDEX_TASKS: {
1536
+ message: z.object({
1537
+ version: z.literal("v1").default("v1"),
1538
+ deploymentId: z.string(),
1539
+ tasks: TaskResource.array(),
1540
+ packageVersion: z.string()
1541
+ }),
1542
+ callback: z.discriminatedUnion("success", [
1543
+ z.object({
1544
+ success: z.literal(false)
1545
+ }),
1546
+ z.object({
1547
+ success: z.literal(true)
1548
+ })
1549
+ ])
1550
+ },
1551
+ READY_FOR_EXECUTION: {
1552
+ message: z.object({
1553
+ version: z.literal("v1").default("v1"),
1554
+ runId: z.string(),
1555
+ totalCompletions: z.number()
1556
+ })
1557
+ },
1558
+ READY_FOR_RESUME: {
1559
+ message: z.object({
1560
+ version: z.literal("v1").default("v1"),
1561
+ attemptFriendlyId: z.string(),
1562
+ type: WaitReason
1563
+ })
1564
+ },
1565
+ READY_FOR_CHECKPOINT: {
1566
+ message: z.object({
1567
+ version: z.literal("v1").default("v1")
1568
+ })
1569
+ },
1570
+ CANCEL_CHECKPOINT: {
1571
+ message: z.object({
1572
+ version: z.literal("v1").default("v1")
1573
+ })
1574
+ },
1575
+ TASK_HEARTBEAT: {
1576
+ message: z.object({
1577
+ version: z.literal("v1").default("v1"),
1578
+ attemptFriendlyId: z.string()
1579
+ })
1580
+ },
1581
+ TASK_RUN_COMPLETED: {
1582
+ message: z.object({
1583
+ version: z.literal("v1").default("v1"),
1584
+ execution: ProdTaskRunExecution,
1585
+ completion: TaskRunExecutionResult
1586
+ }),
1587
+ callback: z.object({
1588
+ willCheckpointAndRestore: z.boolean(),
1589
+ shouldExit: z.boolean()
1590
+ })
1591
+ },
1592
+ WAIT_FOR_DURATION: {
1593
+ message: z.object({
1594
+ version: z.literal("v1").default("v1"),
1595
+ ms: z.number(),
1596
+ now: z.number(),
1597
+ attemptFriendlyId: z.string()
1598
+ }),
1599
+ callback: z.object({
1600
+ willCheckpointAndRestore: z.boolean()
1601
+ })
1602
+ },
1603
+ WAIT_FOR_TASK: {
1604
+ message: z.object({
1605
+ version: z.literal("v1").default("v1"),
1606
+ friendlyId: z.string(),
1607
+ // This is the attempt that is waiting
1608
+ attemptFriendlyId: z.string()
1609
+ }),
1610
+ callback: z.object({
1611
+ willCheckpointAndRestore: z.boolean()
1612
+ })
1613
+ },
1614
+ WAIT_FOR_BATCH: {
1615
+ message: z.object({
1616
+ version: z.literal("v1").default("v1"),
1617
+ batchFriendlyId: z.string(),
1618
+ runFriendlyIds: z.string().array(),
1619
+ // This is the attempt that is waiting
1620
+ attemptFriendlyId: z.string()
1621
+ }),
1622
+ callback: z.object({
1623
+ willCheckpointAndRestore: z.boolean()
1624
+ })
1625
+ },
1626
+ INDEXING_FAILED: {
1627
+ message: z.object({
1628
+ version: z.literal("v1").default("v1"),
1629
+ deploymentId: z.string(),
1630
+ error: z.object({
1631
+ name: z.string(),
1632
+ message: z.string(),
1633
+ stack: z.string().optional()
1634
+ })
1635
+ })
1630
1636
  }
1631
1637
  };
1632
- __name(_UnprocessableEntityError, "UnprocessableEntityError");
1633
- var UnprocessableEntityError = _UnprocessableEntityError;
1634
- var _RateLimitError = class _RateLimitError extends APIError {
1635
- constructor() {
1636
- super(...arguments);
1637
- __publicField(this, "status", 429);
1638
+ var CoordinatorToProdWorkerMessages = {
1639
+ RESUME_AFTER_DEPENDENCY: {
1640
+ message: z.object({
1641
+ version: z.literal("v1").default("v1"),
1642
+ attemptId: z.string(),
1643
+ completions: TaskRunExecutionResult.array(),
1644
+ executions: TaskRunExecution.array()
1645
+ })
1646
+ },
1647
+ RESUME_AFTER_DURATION: {
1648
+ message: z.object({
1649
+ version: z.literal("v1").default("v1"),
1650
+ attemptId: z.string()
1651
+ })
1652
+ },
1653
+ EXECUTE_TASK_RUN: {
1654
+ message: z.object({
1655
+ version: z.literal("v1").default("v1"),
1656
+ executionPayload: ProdTaskRunExecutionPayload
1657
+ })
1658
+ },
1659
+ REQUEST_ATTEMPT_CANCELLATION: {
1660
+ message: z.object({
1661
+ version: z.literal("v1").default("v1"),
1662
+ attemptId: z.string()
1663
+ })
1664
+ },
1665
+ REQUEST_EXIT: {
1666
+ message: z.object({
1667
+ version: z.literal("v1").default("v1")
1668
+ })
1669
+ },
1670
+ READY_FOR_RETRY: {
1671
+ message: z.object({
1672
+ version: z.literal("v1").default("v1"),
1673
+ runId: z.string()
1674
+ })
1638
1675
  }
1639
1676
  };
1640
- __name(_RateLimitError, "RateLimitError");
1641
- var RateLimitError = _RateLimitError;
1642
- var _InternalServerError = class _InternalServerError extends APIError {
1643
- };
1644
- __name(_InternalServerError, "InternalServerError");
1645
- var InternalServerError = _InternalServerError;
1646
- function castToError(err) {
1647
- if (err instanceof Error)
1648
- return err;
1649
- return new Error(err);
1650
- }
1651
- __name(castToError, "castToError");
1652
-
1653
- // src/retry.ts
1654
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
1655
- if (!resets)
1656
- return;
1657
- switch (format) {
1658
- case "iso_8601_duration_openai_variant": {
1659
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
1660
- }
1661
- case "iso_8601": {
1662
- return calculateISO8601ResetAt(resets, now);
1663
- }
1664
- case "unix_timestamp": {
1665
- return calculateUnixTimestampResetAt(resets, now);
1666
- }
1667
- case "unix_timestamp_in_ms": {
1668
- return calculateUnixTimestampInMsResetAt(resets, now);
1669
- }
1670
- }
1671
- }
1672
- __name(calculateResetAt, "calculateResetAt");
1673
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
1674
- if (!resets)
1675
- return void 0;
1676
- const resetAt = parseInt(resets, 10);
1677
- if (isNaN(resetAt))
1678
- return void 0;
1679
- return new Date(resetAt * 1e3);
1680
- }
1681
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
1682
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
1683
- if (!resets)
1684
- return void 0;
1685
- const resetAt = parseInt(resets, 10);
1686
- if (isNaN(resetAt))
1687
- return void 0;
1688
- return new Date(resetAt);
1689
- }
1690
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
1691
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
1692
- if (!resets)
1693
- return void 0;
1694
- const resetAt = new Date(resets);
1695
- if (isNaN(resetAt.getTime()))
1696
- return void 0;
1697
- return resetAt;
1698
- }
1699
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
1700
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
1701
- if (!resets)
1702
- return void 0;
1703
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
1704
- const match = resets.match(pattern);
1705
- if (!match)
1706
- return void 0;
1707
- const days = parseInt(match[1], 10) || 0;
1708
- const hours = parseInt(match[2], 10) || 0;
1709
- const minutes = parseInt(match[3], 10) || 0;
1710
- const seconds = parseFloat(match[4]) || 0;
1711
- const milliseconds = parseInt(match[5], 10) || 0;
1712
- const resetAt = new Date(now);
1713
- resetAt.setDate(resetAt.getDate() + days);
1714
- resetAt.setHours(resetAt.getHours() + hours);
1715
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
1716
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
1717
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
1718
- return resetAt;
1719
- }
1720
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
1721
-
1722
- // src/v3/utils/retries.ts
1723
- var defaultRetryOptions = {
1724
- maxAttempts: 3,
1725
- factor: 2,
1726
- minTimeoutInMs: 1e3,
1727
- maxTimeoutInMs: 6e4,
1728
- randomize: true
1729
- };
1730
- var defaultFetchRetryOptions = {
1731
- byStatus: {
1732
- "429,408,409,5xx": {
1733
- strategy: "backoff",
1734
- ...defaultRetryOptions
1735
- }
1736
- },
1737
- connectionError: defaultRetryOptions,
1738
- timeout: defaultRetryOptions
1739
- };
1740
- function calculateNextRetryDelay(options, attempt) {
1741
- const opts = {
1742
- ...defaultRetryOptions,
1743
- ...options
1744
- };
1745
- if (attempt >= opts.maxAttempts) {
1746
- return;
1747
- }
1748
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1749
- const random = randomize ? Math.random() + 1 : 1;
1750
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1751
- return Math.round(timeout);
1752
- }
1753
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1754
- function calculateResetAt2(resets, format, now = Date.now()) {
1755
- const resetAt = calculateResetAt(resets, format, new Date(now));
1756
- return resetAt?.getTime();
1757
- }
1758
- __name(calculateResetAt2, "calculateResetAt");
1677
+ var ProdWorkerSocketData = z.object({
1678
+ contentHash: z.string(),
1679
+ projectRef: z.string(),
1680
+ envId: z.string(),
1681
+ runId: z.string(),
1682
+ attemptFriendlyId: z.string().optional(),
1683
+ podName: z.string(),
1684
+ deploymentId: z.string(),
1685
+ deploymentVersion: z.string()
1686
+ });
1687
+ var PRIMARY_VARIANT = "primary";
1688
+ var Variant = z.enum([
1689
+ PRIMARY_VARIANT
1690
+ ]);
1691
+ var AccessoryItem = z.object({
1692
+ text: z.string(),
1693
+ variant: z.string().optional(),
1694
+ url: z.string().optional()
1695
+ });
1696
+ var Accessory = z.object({
1697
+ items: z.array(AccessoryItem),
1698
+ style: z.enum([
1699
+ "codepath"
1700
+ ]).optional()
1701
+ });
1702
+ var TaskEventStyle = z.object({
1703
+ icon: z.string().optional(),
1704
+ variant: Variant.optional(),
1705
+ accessory: Accessory.optional()
1706
+ }).default({
1707
+ icon: void 0,
1708
+ variant: void 0
1709
+ });
1710
+ var stringPatternMatchers = [
1711
+ z.object({
1712
+ $endsWith: z.string()
1713
+ }),
1714
+ z.object({
1715
+ $startsWith: z.string()
1716
+ }),
1717
+ z.object({
1718
+ $ignoreCaseEquals: z.string()
1719
+ })
1720
+ ];
1721
+ var EventMatcher = z.union([
1722
+ /** Match against a string */
1723
+ z.array(z.string()),
1724
+ /** Match against a number */
1725
+ z.array(z.number()),
1726
+ /** Match against a boolean */
1727
+ z.array(z.boolean()),
1728
+ z.array(z.union([
1729
+ ...stringPatternMatchers,
1730
+ z.object({
1731
+ $exists: z.boolean()
1732
+ }),
1733
+ z.object({
1734
+ $isNull: z.boolean()
1735
+ }),
1736
+ z.object({
1737
+ $anythingBut: z.union([
1738
+ z.string(),
1739
+ z.number(),
1740
+ z.boolean()
1741
+ ])
1742
+ }),
1743
+ z.object({
1744
+ $anythingBut: z.union([
1745
+ z.array(z.string()),
1746
+ z.array(z.number()),
1747
+ z.array(z.boolean())
1748
+ ])
1749
+ }),
1750
+ z.object({
1751
+ $gt: z.number()
1752
+ }),
1753
+ z.object({
1754
+ $lt: z.number()
1755
+ }),
1756
+ z.object({
1757
+ $gte: z.number()
1758
+ }),
1759
+ z.object({
1760
+ $lte: z.number()
1761
+ }),
1762
+ z.object({
1763
+ $between: z.tuple([
1764
+ z.number(),
1765
+ z.number()
1766
+ ])
1767
+ }),
1768
+ z.object({
1769
+ $includes: z.union([
1770
+ z.string(),
1771
+ z.number(),
1772
+ z.boolean()
1773
+ ])
1774
+ }),
1775
+ z.object({
1776
+ $not: z.union([
1777
+ z.string(),
1778
+ z.number(),
1779
+ z.boolean()
1780
+ ])
1781
+ })
1782
+ ]))
1783
+ ]);
1784
+ var EventFilter = z.lazy(() => z.record(z.union([
1785
+ EventMatcher,
1786
+ EventFilter
1787
+ ])));
1759
1788
 
1760
- // src/v3/zodfetch.ts
1761
- var defaultRetryOptions2 = {
1762
- maxAttempts: 3,
1763
- factor: 2,
1764
- minTimeoutInMs: 1e3,
1765
- maxTimeoutInMs: 6e4,
1766
- randomize: false
1767
- };
1768
- async function zodfetch(schema, url, requestInit, options) {
1769
- return await _doZodFetch(schema, url, requestInit, options);
1770
- }
1771
- __name(zodfetch, "zodfetch");
1772
- async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1773
- try {
1774
- const response = await fetch(url, requestInitWithCache(requestInit));
1775
- const responseHeaders = createResponseHeaders(response.headers);
1776
- if (!response.ok) {
1777
- const retryResult = shouldRetry(response, attempt, options?.retry);
1778
- if (retryResult.retry) {
1779
- await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
1780
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1781
- } else {
1782
- const errText = await response.text().catch((e) => castToError2(e).message);
1783
- const errJSON = safeJsonParse(errText);
1784
- const errMessage = errJSON ? void 0 : errText;
1785
- throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
1786
- }
1787
- }
1788
- const jsonBody = await response.json();
1789
- const parsedResult = schema.safeParse(jsonBody);
1790
- if (parsedResult.success) {
1791
- return parsedResult.data;
1792
- }
1793
- throw fromZodError(parsedResult.error);
1794
- } catch (error) {
1795
- if (error instanceof APIError) {
1796
- throw error;
1797
- }
1798
- if (options?.retry) {
1799
- const retry = {
1800
- ...defaultRetryOptions2,
1801
- ...options.retry
1802
- };
1803
- const delay = calculateNextRetryDelay(retry, attempt);
1804
- if (delay) {
1805
- await new Promise((resolve) => setTimeout(resolve, delay));
1806
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1807
- }
1808
- }
1809
- throw new APIConnectionError({
1810
- cause: castToError2(error)
1811
- });
1812
- }
1813
- }
1814
- __name(_doZodFetch, "_doZodFetch");
1815
- function castToError2(err) {
1816
- if (err instanceof Error)
1817
- return err;
1818
- return new Error(err);
1819
- }
1820
- __name(castToError2, "castToError");
1821
- function shouldRetry(response, attempt, retryOptions) {
1822
- function shouldRetryForOptions() {
1823
- const retry = {
1824
- ...defaultRetryOptions2,
1825
- ...retryOptions
1826
- };
1827
- const delay = calculateNextRetryDelay(retry, attempt);
1828
- if (delay) {
1829
- return {
1830
- retry: true,
1831
- delay
1832
- };
1833
- } else {
1834
- return {
1835
- retry: false
1836
- };
1837
- }
1838
- }
1839
- __name(shouldRetryForOptions, "shouldRetryForOptions");
1840
- const shouldRetryHeader = response.headers.get("x-should-retry");
1841
- if (shouldRetryHeader === "true")
1842
- return shouldRetryForOptions();
1843
- if (shouldRetryHeader === "false")
1844
- return {
1845
- retry: false
1846
- };
1847
- if (response.status === 408)
1848
- return shouldRetryForOptions();
1849
- if (response.status === 409)
1850
- return shouldRetryForOptions();
1851
- if (response.status === 429)
1852
- return shouldRetryForOptions();
1853
- if (response.status >= 500)
1854
- return shouldRetryForOptions();
1855
- return {
1856
- retry: false
1857
- };
1858
- }
1859
- __name(shouldRetry, "shouldRetry");
1860
- function safeJsonParse(text) {
1861
- try {
1862
- return JSON.parse(text);
1863
- } catch (e) {
1864
- return void 0;
1865
- }
1866
- }
1867
- __name(safeJsonParse, "safeJsonParse");
1868
- function createResponseHeaders(headers) {
1869
- return new Proxy(Object.fromEntries(
1870
- // @ts-ignore
1871
- headers.entries()
1872
- ), {
1873
- get(target, name) {
1874
- const key = name.toString();
1875
- return target[key.toLowerCase()] || target[key];
1876
- }
1877
- });
1789
+ // src/v3/schemas/fetch.ts
1790
+ var FetchRetryHeadersStrategy = z.object({
1791
+ /** The `headers` strategy retries the request using info from the response headers. */
1792
+ strategy: z.literal("headers"),
1793
+ /** The header to use to determine the maximum number of times to retry the request. */
1794
+ limitHeader: z.string(),
1795
+ /** The header to use to determine the number of remaining retries. */
1796
+ remainingHeader: z.string(),
1797
+ /** The header to use to determine the time when the number of remaining retries will be reset. */
1798
+ resetHeader: z.string(),
1799
+ /** The event filter to use to determine if the request should be retried. */
1800
+ bodyFilter: EventFilter.optional(),
1801
+ /** The format of the `resetHeader` value. */
1802
+ resetFormat: z.enum([
1803
+ "unix_timestamp",
1804
+ "unix_timestamp_in_ms",
1805
+ "iso_8601",
1806
+ "iso_8601_duration_openai_variant"
1807
+ ]).default("unix_timestamp").optional()
1808
+ });
1809
+ var FetchRetryBackoffStrategy = RetryOptions.extend({
1810
+ /** The `backoff` strategy retries the request with an exponential backoff. */
1811
+ strategy: z.literal("backoff"),
1812
+ /** The event filter to use to determine if the request should be retried. */
1813
+ bodyFilter: EventFilter.optional()
1814
+ });
1815
+ var FetchRetryStrategy = z.discriminatedUnion("strategy", [
1816
+ FetchRetryHeadersStrategy,
1817
+ FetchRetryBackoffStrategy
1818
+ ]);
1819
+ var FetchRetryByStatusOptions = z.record(z.string(), FetchRetryStrategy);
1820
+ var FetchTimeoutOptions = z.object({
1821
+ /** The maximum time to wait for the request to complete. */
1822
+ durationInMs: z.number().optional(),
1823
+ retry: RetryOptions.optional()
1824
+ });
1825
+ var FetchRetryOptions = z.object({
1826
+ /** The retrying strategy for specific status codes. */
1827
+ byStatus: FetchRetryByStatusOptions.optional(),
1828
+ /** The timeout options for the request. */
1829
+ timeout: RetryOptions.optional(),
1830
+ /**
1831
+ * The retrying strategy for connection errors.
1832
+ */
1833
+ connectionError: RetryOptions.optional()
1834
+ });
1835
+ var ExceptionEventProperties = z.object({
1836
+ type: z.string().optional(),
1837
+ message: z.string().optional(),
1838
+ stacktrace: z.string().optional()
1839
+ });
1840
+ var ExceptionSpanEvent = z.object({
1841
+ name: z.literal("exception"),
1842
+ time: z.coerce.date(),
1843
+ properties: z.object({
1844
+ exception: ExceptionEventProperties
1845
+ })
1846
+ });
1847
+ var CancellationSpanEvent = z.object({
1848
+ name: z.literal("cancellation"),
1849
+ time: z.coerce.date(),
1850
+ properties: z.object({
1851
+ reason: z.string()
1852
+ })
1853
+ });
1854
+ var OtherSpanEvent = z.object({
1855
+ name: z.string(),
1856
+ time: z.coerce.date(),
1857
+ properties: z.record(z.unknown())
1858
+ });
1859
+ var SpanEvent = z.union([
1860
+ ExceptionSpanEvent,
1861
+ CancellationSpanEvent,
1862
+ OtherSpanEvent
1863
+ ]);
1864
+ var SpanEvents = z.array(SpanEvent);
1865
+ function isExceptionSpanEvent(event) {
1866
+ return event.name === "exception";
1878
1867
  }
1879
- __name(createResponseHeaders, "createResponseHeaders");
1880
- function requestInitWithCache(requestInit) {
1881
- try {
1882
- const withCache = {
1883
- ...requestInit,
1884
- cache: "no-cache"
1885
- };
1886
- const _ = new Request("http://localhost", withCache);
1887
- return withCache;
1888
- } catch (error) {
1889
- return requestInit ?? {};
1890
- }
1868
+ __name(isExceptionSpanEvent, "isExceptionSpanEvent");
1869
+ function isCancellationSpanEvent(event) {
1870
+ return event.name === "cancellation";
1891
1871
  }
1892
- __name(requestInitWithCache, "requestInitWithCache");
1872
+ __name(isCancellationSpanEvent, "isCancellationSpanEvent");
1873
+ var SpanMessagingEvent = z.object({
1874
+ system: z.string().optional(),
1875
+ client_id: z.string().optional(),
1876
+ operation: z.enum([
1877
+ "publish",
1878
+ "create",
1879
+ "receive",
1880
+ "deliver"
1881
+ ]),
1882
+ message: z.any(),
1883
+ destination: z.string().optional()
1884
+ });
1893
1885
 
1894
- // src/v3/utils/flattenAttributes.ts
1895
- function flattenAttributes(obj, prefix) {
1896
- const result = {};
1897
- if (!obj) {
1898
- return result;
1899
- }
1900
- if (typeof obj === "string") {
1901
- result[prefix || ""] = obj;
1902
- return result;
1903
- }
1904
- if (typeof obj === "number") {
1905
- result[prefix || ""] = obj;
1906
- return result;
1907
- }
1908
- if (typeof obj === "boolean") {
1909
- result[prefix || ""] = obj;
1910
- return result;
1911
- }
1912
- for (const [key, value] of Object.entries(obj)) {
1913
- const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
1914
- if (Array.isArray(value)) {
1915
- for (let i = 0; i < value.length; i++) {
1916
- if (typeof value[i] === "object" && value[i] !== null) {
1917
- Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
1918
- } else {
1919
- result[`${newPrefix}.[${i}]`] = value[i];
1920
- }
1921
- }
1922
- } else if (isRecord(value)) {
1923
- Object.assign(result, flattenAttributes(value, newPrefix));
1924
- } else {
1925
- if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
1926
- result[newPrefix] = value;
1927
- }
1928
- }
1929
- }
1930
- return result;
1931
- }
1932
- __name(flattenAttributes, "flattenAttributes");
1933
- function isRecord(value) {
1934
- return value !== null && typeof value === "object" && !Array.isArray(value);
1935
- }
1936
- __name(isRecord, "isRecord");
1937
- function unflattenAttributes(obj) {
1938
- if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
1939
- return obj;
1940
- }
1941
- const result = {};
1942
- for (const [key, value] of Object.entries(obj)) {
1943
- const parts = key.split(".").reduce((acc, part) => {
1944
- if (detectIsArrayIndex(part)) {
1945
- acc.push(part);
1946
- } else {
1947
- acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
1948
- }
1949
- return acc;
1950
- }, []);
1951
- let current = result;
1952
- for (let i = 0; i < parts.length - 1; i++) {
1953
- const part = parts[i];
1954
- const isArray = detectIsArrayIndex(part);
1955
- const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
1956
- const nextIsArray = detectIsArrayIndex(parts[i + 1]);
1957
- if (!current[cleanPart]) {
1958
- current[cleanPart] = nextIsArray ? [] : {};
1959
- }
1960
- current = current[cleanPart];
1961
- }
1962
- const lastPart = parts[parts.length - 1];
1963
- const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
1964
- current[cleanLastPart] = value;
1886
+ // src/v3/utils/platform.ts
1887
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
1888
+
1889
+ // src/v3/utils/globals.ts
1890
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
1891
+ var _global = _globalThis;
1892
+ function registerGlobal(type, instance, allowOverride = false) {
1893
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
1894
+ if (!allowOverride && api[type]) {
1895
+ return false;
1965
1896
  }
1966
- return result;
1897
+ api[type] = instance;
1898
+ return true;
1967
1899
  }
1968
- __name(unflattenAttributes, "unflattenAttributes");
1969
- function detectIsArrayIndex(key) {
1970
- const match = key.match(/^\[(\d+)\]$/);
1971
- if (match) {
1972
- return true;
1973
- }
1974
- return false;
1900
+ __name(registerGlobal, "registerGlobal");
1901
+ function getGlobal(type) {
1902
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
1975
1903
  }
1976
- __name(detectIsArrayIndex, "detectIsArrayIndex");
1977
- function primitiveValueOrflattenedAttributes(obj, prefix) {
1978
- if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
1979
- return obj;
1980
- }
1981
- const attributes = flattenAttributes(obj, prefix);
1982
- if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
1983
- return attributes[prefix];
1904
+ __name(getGlobal, "getGlobal");
1905
+ function unregisterGlobal(type) {
1906
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
1907
+ if (api) {
1908
+ delete api[type];
1984
1909
  }
1985
- return attributes;
1986
1910
  }
1987
- __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
1988
- var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
1989
- constructor() {
1990
- this.storage = new AsyncLocalStorage();
1991
- }
1992
- runWith(context3, fn) {
1993
- return this.storage.run(context3, fn);
1994
- }
1995
- getStore() {
1996
- return this.storage.getStore();
1997
- }
1998
- };
1999
- __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
2000
- var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
1911
+ __name(unregisterGlobal, "unregisterGlobal");
2001
1912
 
2002
1913
  // src/v3/semanticInternalAttributes.ts
2003
1914
  var SemanticInternalAttributes = {
@@ -2046,23 +1957,27 @@ var SemanticInternalAttributes = {
2046
1957
  IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
2047
1958
  };
2048
1959
 
2049
- // src/v3/tasks/taskContextManager.ts
2050
- var _getStore, getStore_fn;
2051
- var _TaskContextManager = class _TaskContextManager {
1960
+ // src/v3/taskContext/index.ts
1961
+ var API_NAME = "task-context";
1962
+ var _getTaskContext, getTaskContext_fn;
1963
+ var _TaskContextAPI = class _TaskContextAPI {
2052
1964
  constructor() {
2053
- __privateAdd(this, _getStore);
2054
- __publicField(this, "_storage", new SafeAsyncLocalStorage());
1965
+ __privateAdd(this, _getTaskContext);
1966
+ }
1967
+ static getInstance() {
1968
+ if (!this._instance) {
1969
+ this._instance = new _TaskContextAPI();
1970
+ }
1971
+ return this._instance;
2055
1972
  }
2056
1973
  get isInsideTask() {
2057
- return __privateMethod(this, _getStore, getStore_fn).call(this) !== void 0;
1974
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
2058
1975
  }
2059
1976
  get ctx() {
2060
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2061
- return store?.ctx;
1977
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
2062
1978
  }
2063
1979
  get worker() {
2064
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2065
- return store?.worker;
1980
+ return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
2066
1981
  }
2067
1982
  get attributes() {
2068
1983
  if (this.ctx) {
@@ -2108,66 +2023,22 @@ var _TaskContextManager = class _TaskContextManager {
2108
2023
  }
2109
2024
  return {};
2110
2025
  }
2111
- runWith(context3, fn) {
2112
- return this._storage.runWith(context3, fn);
2113
- }
2114
- };
2115
- _getStore = new WeakSet();
2116
- getStore_fn = /* @__PURE__ */ __name(function() {
2117
- return this._storage.getStore();
2118
- }, "#getStore");
2119
- __name(_TaskContextManager, "TaskContextManager");
2120
- var TaskContextManager = _TaskContextManager;
2121
- var taskContextManager = new TaskContextManager();
2122
- var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
2123
- constructor(innerProcessor) {
2124
- this._innerProcessor = innerProcessor;
2125
- }
2126
- // Called when a span starts
2127
- onStart(span, parentContext) {
2128
- if (taskContextManager.ctx) {
2129
- span.setAttributes(flattenAttributes({
2130
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
2131
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
2132
- }, SemanticInternalAttributes.METADATA));
2133
- }
2134
- this._innerProcessor.onStart(span, parentContext);
2135
- }
2136
- // Delegate the rest of the methods to the wrapped processor
2137
- onEnd(span) {
2138
- this._innerProcessor.onEnd(span);
2139
- }
2140
- shutdown() {
2141
- return this._innerProcessor.shutdown();
2142
- }
2143
- forceFlush() {
2144
- return this._innerProcessor.forceFlush();
2145
- }
2146
- };
2147
- __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
2148
- var TaskContextSpanProcessor = _TaskContextSpanProcessor;
2149
- var _TaskContextLogProcessor = class _TaskContextLogProcessor {
2150
- constructor(innerProcessor) {
2151
- this._innerProcessor = innerProcessor;
2152
- }
2153
- forceFlush() {
2154
- return this._innerProcessor.forceFlush();
2155
- }
2156
- onEmit(logRecord, context3) {
2157
- if (taskContextManager.ctx) {
2158
- logRecord.setAttributes(flattenAttributes({
2159
- [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
2160
- [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
2161
- }, SemanticInternalAttributes.METADATA));
2162
- }
2163
- this._innerProcessor.onEmit(logRecord, context3);
2026
+ disable() {
2027
+ unregisterGlobal(API_NAME);
2164
2028
  }
2165
- shutdown() {
2166
- return this._innerProcessor.shutdown();
2029
+ setGlobalTaskContext(taskContext2) {
2030
+ return registerGlobal(API_NAME, taskContext2);
2167
2031
  }
2168
2032
  };
2169
- __name(_TaskContextLogProcessor, "TaskContextLogProcessor");
2170
- var TaskContextLogProcessor = _TaskContextLogProcessor;
2033
+ _getTaskContext = new WeakSet();
2034
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
2035
+ return getGlobal(API_NAME);
2036
+ }, "#getTaskContext");
2037
+ __name(_TaskContextAPI, "TaskContextAPI");
2038
+ var TaskContextAPI = _TaskContextAPI;
2039
+
2040
+ // src/v3/task-context-api.ts
2041
+ var taskContext = TaskContextAPI.getInstance();
2171
2042
 
2172
2043
  // src/v3/utils/getEnv.ts
2173
2044
  function getEnvVar(name) {
@@ -2176,6 +2047,19 @@ function getEnvVar(name) {
2176
2047
  }
2177
2048
  }
2178
2049
  __name(getEnvVar, "getEnvVar");
2050
+ var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
2051
+ constructor() {
2052
+ this.storage = new AsyncLocalStorage();
2053
+ }
2054
+ runWith(context3, fn) {
2055
+ return this.storage.run(context3, fn);
2056
+ }
2057
+ getStore() {
2058
+ return this.storage.getStore();
2059
+ }
2060
+ };
2061
+ __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
2062
+ var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
2179
2063
 
2180
2064
  // src/v3/apiClient/index.ts
2181
2065
  var zodFetchOptions = {
@@ -2311,7 +2195,7 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2311
2195
  "Content-Type": "application/json",
2312
2196
  Authorization: `Bearer ${this.accessToken}`
2313
2197
  };
2314
- if (taskContextManager.isInsideTask) {
2198
+ if (taskContext.isInsideTask) {
2315
2199
  propagation.inject(context.active(), headers);
2316
2200
  if (spanParentAsLink) {
2317
2201
  headers["x-trigger-span-parent-as-link"] = "1";
@@ -2321,18 +2205,18 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2321
2205
  }, "#getHeaders");
2322
2206
  __name(_ApiClient, "ApiClient");
2323
2207
  var ApiClient = _ApiClient;
2324
- var _getStore2, getStore_fn2;
2208
+ var _getStore, getStore_fn;
2325
2209
  var _ApiClientManager = class _ApiClientManager {
2326
2210
  constructor() {
2327
- __privateAdd(this, _getStore2);
2211
+ __privateAdd(this, _getStore);
2328
2212
  __publicField(this, "_storage", new SafeAsyncLocalStorage());
2329
2213
  }
2330
2214
  get baseURL() {
2331
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
2215
+ const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2332
2216
  return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
2333
2217
  }
2334
2218
  get accessToken() {
2335
- const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
2219
+ const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2336
2220
  return store?.accessToken ?? getEnvVar("TRIGGER_SECRET_KEY");
2337
2221
  }
2338
2222
  get client() {
@@ -2345,13 +2229,61 @@ var _ApiClientManager = class _ApiClientManager {
2345
2229
  return this._storage.runWith(context3, fn);
2346
2230
  }
2347
2231
  };
2348
- _getStore2 = new WeakSet();
2349
- getStore_fn2 = /* @__PURE__ */ __name(function() {
2232
+ _getStore = new WeakSet();
2233
+ getStore_fn = /* @__PURE__ */ __name(function() {
2350
2234
  return this._storage.getStore();
2351
2235
  }, "#getStore");
2352
2236
  __name(_ApiClientManager, "ApiClientManager");
2353
2237
  var ApiClientManager = _ApiClientManager;
2354
2238
  var apiClientManager = new ApiClientManager();
2239
+ var _SimpleClock = class _SimpleClock {
2240
+ preciseNow() {
2241
+ const now = new PreciseDate();
2242
+ const nowStruct = now.toStruct();
2243
+ return [
2244
+ nowStruct.seconds,
2245
+ nowStruct.nanos
2246
+ ];
2247
+ }
2248
+ reset() {
2249
+ }
2250
+ };
2251
+ __name(_SimpleClock, "SimpleClock");
2252
+ var SimpleClock = _SimpleClock;
2253
+
2254
+ // src/v3/clock/index.ts
2255
+ var API_NAME2 = "clock";
2256
+ var SIMPLE_CLOCK = new SimpleClock();
2257
+ var _getClock, getClock_fn;
2258
+ var _ClockAPI = class _ClockAPI {
2259
+ constructor() {
2260
+ __privateAdd(this, _getClock);
2261
+ }
2262
+ static getInstance() {
2263
+ if (!this._instance) {
2264
+ this._instance = new _ClockAPI();
2265
+ }
2266
+ return this._instance;
2267
+ }
2268
+ setGlobalClock(clock2) {
2269
+ return registerGlobal(API_NAME2, clock2);
2270
+ }
2271
+ preciseNow() {
2272
+ return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2273
+ }
2274
+ reset() {
2275
+ __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2276
+ }
2277
+ };
2278
+ _getClock = new WeakSet();
2279
+ getClock_fn = /* @__PURE__ */ __name(function() {
2280
+ return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2281
+ }, "#getClock");
2282
+ __name(_ClockAPI, "ClockAPI");
2283
+ var ClockAPI = _ClockAPI;
2284
+
2285
+ // src/v3/clock-api.ts
2286
+ var clock = ClockAPI.getInstance();
2355
2287
  function parseError(error) {
2356
2288
  if (error instanceof Error) {
2357
2289
  return {
@@ -2463,261 +2395,146 @@ function groupTaskMetadataIssuesByTask(tasks, issues) {
2463
2395
  }
2464
2396
  __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
2465
2397
 
2466
- // src/v3/utils/platform.ts
2467
- var _globalThis = typeof globalThis === "object" ? globalThis : global;
2468
-
2469
- // src/v3/utils/globals.ts
2470
- var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
2471
- var _global = _globalThis;
2472
- function registerGlobal(type, instance, allowOverride = false) {
2473
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
2474
- if (!allowOverride && api[type]) {
2475
- return false;
2476
- }
2477
- api[type] = instance;
2478
- return true;
2479
- }
2480
- __name(registerGlobal, "registerGlobal");
2481
- function getGlobal(type) {
2482
- return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
2483
- }
2484
- __name(getGlobal, "getGlobal");
2485
- function unregisterGlobal(type) {
2486
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
2487
- if (api) {
2488
- delete api[type];
2398
+ // src/v3/limits.ts
2399
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2400
+ var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
2401
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2402
+ var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2403
+ var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
2404
+ var OTEL_LINK_COUNT_LIMIT = 2;
2405
+ var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
2406
+ var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
2407
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
2408
+ function imposeAttributeLimits(attributes) {
2409
+ const newAttributes = {};
2410
+ for (const [key, value] of Object.entries(attributes)) {
2411
+ if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
2412
+ continue;
2413
+ }
2414
+ if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
2415
+ break;
2416
+ }
2417
+ newAttributes[key] = value;
2489
2418
  }
2419
+ return newAttributes;
2490
2420
  }
2491
- __name(unregisterGlobal, "unregisterGlobal");
2492
-
2493
- // src/v3/runtime/noopRuntimeManager.ts
2494
- var _NoopRuntimeManager = class _NoopRuntimeManager {
2495
- disable() {
2421
+ __name(imposeAttributeLimits, "imposeAttributeLimits");
2422
+ function calculateAttributeValueLength(value) {
2423
+ if (value === void 0 || value === null) {
2424
+ return 0;
2496
2425
  }
2497
- waitForDuration(ms) {
2498
- return Promise.resolve();
2426
+ if (typeof value === "string") {
2427
+ return value.length;
2499
2428
  }
2500
- waitUntil(date) {
2501
- return Promise.resolve();
2429
+ if (typeof value === "number") {
2430
+ return 8;
2502
2431
  }
2503
- waitForTask(params) {
2504
- return Promise.resolve({
2505
- ok: false,
2506
- id: params.id,
2507
- error: {
2508
- type: "INTERNAL_ERROR",
2509
- code: "CONFIGURED_INCORRECTLY"
2510
- }
2511
- });
2432
+ if (typeof value === "boolean") {
2433
+ return 4;
2512
2434
  }
2513
- waitForBatch(params) {
2514
- return Promise.resolve({
2515
- id: params.id,
2516
- items: []
2517
- });
2435
+ if (Array.isArray(value)) {
2436
+ return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
2518
2437
  }
2519
- };
2520
- __name(_NoopRuntimeManager, "NoopRuntimeManager");
2521
- var NoopRuntimeManager = _NoopRuntimeManager;
2438
+ return 0;
2439
+ }
2440
+ __name(calculateAttributeValueLength, "calculateAttributeValueLength");
2522
2441
 
2523
- // src/v3/runtime/index.ts
2524
- var API_NAME = "runtime";
2525
- var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
2526
- var _getRuntimeManager, getRuntimeManager_fn;
2527
- var _RuntimeAPI = class _RuntimeAPI {
2528
- constructor() {
2529
- __privateAdd(this, _getRuntimeManager);
2530
- }
2531
- static getInstance() {
2532
- if (!this._instance) {
2533
- this._instance = new _RuntimeAPI();
2534
- }
2535
- return this._instance;
2536
- }
2537
- waitForDuration(ms) {
2538
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
2539
- }
2540
- waitUntil(date) {
2541
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
2542
- }
2543
- waitForTask(params) {
2544
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
2442
+ // src/v3/utils/flattenAttributes.ts
2443
+ function flattenAttributes(obj, prefix) {
2444
+ const result = {};
2445
+ if (!obj) {
2446
+ return result;
2545
2447
  }
2546
- waitForBatch(params) {
2547
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
2448
+ if (typeof obj === "string") {
2449
+ result[prefix || ""] = obj;
2450
+ return result;
2548
2451
  }
2549
- setGlobalRuntimeManager(runtimeManager) {
2550
- return registerGlobal(API_NAME, runtimeManager);
2452
+ if (typeof obj === "number") {
2453
+ result[prefix || ""] = obj;
2454
+ return result;
2551
2455
  }
2552
- disable() {
2553
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2554
- unregisterGlobal(API_NAME);
2456
+ if (typeof obj === "boolean") {
2457
+ result[prefix || ""] = obj;
2458
+ return result;
2555
2459
  }
2556
- };
2557
- _getRuntimeManager = new WeakSet();
2558
- getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
2559
- return getGlobal(API_NAME) ?? NOOP_RUNTIME_MANAGER;
2560
- }, "#getRuntimeManager");
2561
- __name(_RuntimeAPI, "RuntimeAPI");
2562
- var RuntimeAPI = _RuntimeAPI;
2563
-
2564
- // src/v3/runtime-api.ts
2565
- var runtime = RuntimeAPI.getInstance();
2566
- function iconStringForSeverity(severityNumber) {
2567
- switch (severityNumber) {
2568
- case SeverityNumber.UNSPECIFIED:
2569
- return void 0;
2570
- case SeverityNumber.TRACE:
2571
- case SeverityNumber.TRACE2:
2572
- case SeverityNumber.TRACE3:
2573
- case SeverityNumber.TRACE4:
2574
- return "trace";
2575
- case SeverityNumber.DEBUG:
2576
- case SeverityNumber.DEBUG2:
2577
- case SeverityNumber.DEBUG3:
2578
- case SeverityNumber.DEBUG4:
2579
- return "debug";
2580
- case SeverityNumber.INFO:
2581
- case SeverityNumber.INFO2:
2582
- case SeverityNumber.INFO3:
2583
- case SeverityNumber.INFO4:
2584
- return "info";
2585
- case SeverityNumber.WARN:
2586
- case SeverityNumber.WARN2:
2587
- case SeverityNumber.WARN3:
2588
- case SeverityNumber.WARN4:
2589
- return "warn";
2590
- case SeverityNumber.ERROR:
2591
- case SeverityNumber.ERROR2:
2592
- case SeverityNumber.ERROR3:
2593
- case SeverityNumber.ERROR4:
2594
- return "error";
2595
- case SeverityNumber.FATAL:
2596
- case SeverityNumber.FATAL2:
2597
- case SeverityNumber.FATAL3:
2598
- case SeverityNumber.FATAL4:
2599
- return "fatal";
2460
+ for (const [key, value] of Object.entries(obj)) {
2461
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
2462
+ if (Array.isArray(value)) {
2463
+ for (let i = 0; i < value.length; i++) {
2464
+ if (typeof value[i] === "object" && value[i] !== null) {
2465
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
2466
+ } else {
2467
+ result[`${newPrefix}.[${i}]`] = value[i];
2468
+ }
2469
+ }
2470
+ } else if (isRecord(value)) {
2471
+ Object.assign(result, flattenAttributes(value, newPrefix));
2472
+ } else {
2473
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
2474
+ result[newPrefix] = value;
2475
+ }
2476
+ }
2600
2477
  }
2478
+ return result;
2601
2479
  }
2602
- __name(iconStringForSeverity, "iconStringForSeverity");
2603
- var _SimpleClock = class _SimpleClock {
2604
- preciseNow() {
2605
- const now = new PreciseDate();
2606
- const nowStruct = now.toStruct();
2607
- return [
2608
- nowStruct.seconds,
2609
- nowStruct.nanos
2610
- ];
2611
- }
2612
- reset() {
2613
- }
2614
- };
2615
- __name(_SimpleClock, "SimpleClock");
2616
- var SimpleClock = _SimpleClock;
2617
-
2618
- // src/v3/clock/index.ts
2619
- var API_NAME2 = "clock";
2620
- var SIMPLE_CLOCK = new SimpleClock();
2621
- var _getClock, getClock_fn;
2622
- var _ClockAPI = class _ClockAPI {
2623
- constructor() {
2624
- __privateAdd(this, _getClock);
2480
+ __name(flattenAttributes, "flattenAttributes");
2481
+ function isRecord(value) {
2482
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2483
+ }
2484
+ __name(isRecord, "isRecord");
2485
+ function unflattenAttributes(obj) {
2486
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
2487
+ return obj;
2625
2488
  }
2626
- static getInstance() {
2627
- if (!this._instance) {
2628
- this._instance = new _ClockAPI();
2489
+ const result = {};
2490
+ for (const [key, value] of Object.entries(obj)) {
2491
+ const parts = key.split(".").reduce((acc, part) => {
2492
+ if (detectIsArrayIndex(part)) {
2493
+ acc.push(part);
2494
+ } else {
2495
+ acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
2496
+ }
2497
+ return acc;
2498
+ }, []);
2499
+ let current = result;
2500
+ for (let i = 0; i < parts.length - 1; i++) {
2501
+ const part = parts[i];
2502
+ const isArray = detectIsArrayIndex(part);
2503
+ const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
2504
+ const nextIsArray = detectIsArrayIndex(parts[i + 1]);
2505
+ if (!current[cleanPart]) {
2506
+ current[cleanPart] = nextIsArray ? [] : {};
2507
+ }
2508
+ current = current[cleanPart];
2629
2509
  }
2630
- return this._instance;
2631
- }
2632
- setGlobalClock(clock2) {
2633
- return registerGlobal(API_NAME2, clock2);
2634
- }
2635
- preciseNow() {
2636
- return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2637
- }
2638
- reset() {
2639
- __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2640
- }
2641
- };
2642
- _getClock = new WeakSet();
2643
- getClock_fn = /* @__PURE__ */ __name(function() {
2644
- return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2645
- }, "#getClock");
2646
- __name(_ClockAPI, "ClockAPI");
2647
- var ClockAPI = _ClockAPI;
2648
-
2649
- // src/v3/clock-api.ts
2650
- var clock = ClockAPI.getInstance();
2651
-
2652
- // src/v3/logger/taskLogger.ts
2653
- var logLevels = [
2654
- "none",
2655
- "error",
2656
- "warn",
2657
- "log",
2658
- "info",
2659
- "debug"
2660
- ];
2661
- var _emitLog, emitLog_fn, _getTimestampInHrTime, getTimestampInHrTime_fn;
2662
- var _OtelTaskLogger = class _OtelTaskLogger {
2663
- constructor(_config) {
2664
- __privateAdd(this, _emitLog);
2665
- __privateAdd(this, _getTimestampInHrTime);
2666
- this._config = _config;
2667
- this._level = logLevels.indexOf(_config.level);
2668
- }
2669
- debug(message, properties) {
2670
- if (this._level < 5)
2671
- return;
2672
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "debug", SeverityNumber.DEBUG, properties);
2673
- }
2674
- log(message, properties) {
2675
- if (this._level < 3)
2676
- return;
2677
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "log", SeverityNumber.INFO, properties);
2678
- }
2679
- info(message, properties) {
2680
- if (this._level < 4)
2681
- return;
2682
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "info", SeverityNumber.INFO, properties);
2510
+ const lastPart = parts[parts.length - 1];
2511
+ const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
2512
+ current[cleanLastPart] = value;
2683
2513
  }
2684
- warn(message, properties) {
2685
- if (this._level < 2)
2686
- return;
2687
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "warn", SeverityNumber.WARN, properties);
2514
+ return result;
2515
+ }
2516
+ __name(unflattenAttributes, "unflattenAttributes");
2517
+ function detectIsArrayIndex(key) {
2518
+ const match = key.match(/^\[(\d+)\]$/);
2519
+ if (match) {
2520
+ return true;
2688
2521
  }
2689
- error(message, properties) {
2690
- if (this._level < 1)
2691
- return;
2692
- __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "error", SeverityNumber.ERROR, properties);
2522
+ return false;
2523
+ }
2524
+ __name(detectIsArrayIndex, "detectIsArrayIndex");
2525
+ function primitiveValueOrflattenedAttributes(obj, prefix) {
2526
+ if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
2527
+ return obj;
2693
2528
  }
2694
- trace(name, fn, options) {
2695
- return this._config.tracer.startActiveSpan(name, fn, options);
2529
+ const attributes = flattenAttributes(obj, prefix);
2530
+ if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
2531
+ return attributes[prefix];
2696
2532
  }
2697
- };
2698
- _emitLog = new WeakSet();
2699
- emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
2700
- let attributes = {
2701
- ...flattenAttributes(safeJsonProcess(properties))
2702
- };
2703
- const icon = iconStringForSeverity(severityNumber);
2704
- if (icon !== void 0) {
2705
- attributes[SemanticInternalAttributes.STYLE_ICON] = icon;
2706
- }
2707
- this._config.logger.emit({
2708
- severityNumber,
2709
- severityText,
2710
- body: message,
2711
- attributes,
2712
- timestamp
2713
- });
2714
- }, "#emitLog");
2715
- _getTimestampInHrTime = new WeakSet();
2716
- getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
2717
- return clock.preciseNow();
2718
- }, "#getTimestampInHrTime");
2719
- __name(_OtelTaskLogger, "OtelTaskLogger");
2720
- var OtelTaskLogger = _OtelTaskLogger;
2533
+ return attributes;
2534
+ }
2535
+ __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
2536
+
2537
+ // src/v3/logger/taskLogger.ts
2721
2538
  var _NoopTaskLogger = class _NoopTaskLogger {
2722
2539
  debug() {
2723
2540
  }
@@ -2735,25 +2552,6 @@ var _NoopTaskLogger = class _NoopTaskLogger {
2735
2552
  };
2736
2553
  __name(_NoopTaskLogger, "NoopTaskLogger");
2737
2554
  var NoopTaskLogger = _NoopTaskLogger;
2738
- function safeJsonProcess(value) {
2739
- try {
2740
- return JSON.parse(JSON.stringify(value, jsonErrorReplacer));
2741
- } catch {
2742
- return value;
2743
- }
2744
- }
2745
- __name(safeJsonProcess, "safeJsonProcess");
2746
- function jsonErrorReplacer(key, value) {
2747
- if (value instanceof Error) {
2748
- return {
2749
- name: value.name,
2750
- message: value.message,
2751
- stack: value.stack
2752
- };
2753
- }
2754
- return value;
2755
- }
2756
- __name(jsonErrorReplacer, "jsonErrorReplacer");
2757
2555
 
2758
2556
  // src/v3/logger/index.ts
2759
2557
  var API_NAME3 = "logger";
@@ -2804,6 +2602,80 @@ var LoggerAPI = _LoggerAPI;
2804
2602
  // src/v3/logger-api.ts
2805
2603
  var logger = LoggerAPI.getInstance();
2806
2604
 
2605
+ // src/v3/runtime/noopRuntimeManager.ts
2606
+ var _NoopRuntimeManager = class _NoopRuntimeManager {
2607
+ disable() {
2608
+ }
2609
+ waitForDuration(ms) {
2610
+ return Promise.resolve();
2611
+ }
2612
+ waitUntil(date) {
2613
+ return Promise.resolve();
2614
+ }
2615
+ waitForTask(params) {
2616
+ return Promise.resolve({
2617
+ ok: false,
2618
+ id: params.id,
2619
+ error: {
2620
+ type: "INTERNAL_ERROR",
2621
+ code: "CONFIGURED_INCORRECTLY"
2622
+ }
2623
+ });
2624
+ }
2625
+ waitForBatch(params) {
2626
+ return Promise.resolve({
2627
+ id: params.id,
2628
+ items: []
2629
+ });
2630
+ }
2631
+ };
2632
+ __name(_NoopRuntimeManager, "NoopRuntimeManager");
2633
+ var NoopRuntimeManager = _NoopRuntimeManager;
2634
+
2635
+ // src/v3/runtime/index.ts
2636
+ var API_NAME4 = "runtime";
2637
+ var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
2638
+ var _getRuntimeManager, getRuntimeManager_fn;
2639
+ var _RuntimeAPI = class _RuntimeAPI {
2640
+ constructor() {
2641
+ __privateAdd(this, _getRuntimeManager);
2642
+ }
2643
+ static getInstance() {
2644
+ if (!this._instance) {
2645
+ this._instance = new _RuntimeAPI();
2646
+ }
2647
+ return this._instance;
2648
+ }
2649
+ waitForDuration(ms) {
2650
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
2651
+ }
2652
+ waitUntil(date) {
2653
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
2654
+ }
2655
+ waitForTask(params) {
2656
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
2657
+ }
2658
+ waitForBatch(params) {
2659
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
2660
+ }
2661
+ setGlobalRuntimeManager(runtimeManager) {
2662
+ return registerGlobal(API_NAME4, runtimeManager);
2663
+ }
2664
+ disable() {
2665
+ __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2666
+ unregisterGlobal(API_NAME4);
2667
+ }
2668
+ };
2669
+ _getRuntimeManager = new WeakSet();
2670
+ getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
2671
+ return getGlobal(API_NAME4) ?? NOOP_RUNTIME_MANAGER;
2672
+ }, "#getRuntimeManager");
2673
+ __name(_RuntimeAPI, "RuntimeAPI");
2674
+ var RuntimeAPI = _RuntimeAPI;
2675
+
2676
+ // src/v3/runtime-api.ts
2677
+ var runtime = RuntimeAPI.getInstance();
2678
+
2807
2679
  // src/v3/task-catalog/noopTaskCatalog.ts
2808
2680
  var _NoopTaskCatalog = class _NoopTaskCatalog {
2809
2681
  registerTaskMetadata(task) {
@@ -2828,7 +2700,7 @@ __name(_NoopTaskCatalog, "NoopTaskCatalog");
2828
2700
  var NoopTaskCatalog = _NoopTaskCatalog;
2829
2701
 
2830
2702
  // src/v3/task-catalog/index.ts
2831
- var API_NAME4 = "task-catalog";
2703
+ var API_NAME5 = "task-catalog";
2832
2704
  var NOOP_TASK_CATALOG = new NoopTaskCatalog();
2833
2705
  var _getCatalog, getCatalog_fn;
2834
2706
  var _TaskCatalogAPI = class _TaskCatalogAPI {
@@ -2842,10 +2714,10 @@ var _TaskCatalogAPI = class _TaskCatalogAPI {
2842
2714
  return this._instance;
2843
2715
  }
2844
2716
  setGlobalTaskCatalog(taskCatalog2) {
2845
- return registerGlobal(API_NAME4, taskCatalog2);
2717
+ return registerGlobal(API_NAME5, taskCatalog2);
2846
2718
  }
2847
2719
  disable() {
2848
- unregisterGlobal(API_NAME4);
2720
+ unregisterGlobal(API_NAME5);
2849
2721
  }
2850
2722
  registerTaskMetadata(task) {
2851
2723
  __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskMetadata(task);
@@ -2868,57 +2740,13 @@ var _TaskCatalogAPI = class _TaskCatalogAPI {
2868
2740
  };
2869
2741
  _getCatalog = new WeakSet();
2870
2742
  getCatalog_fn = /* @__PURE__ */ __name(function() {
2871
- return getGlobal(API_NAME4) ?? NOOP_TASK_CATALOG;
2743
+ return getGlobal(API_NAME5) ?? NOOP_TASK_CATALOG;
2872
2744
  }, "#getCatalog");
2873
2745
  __name(_TaskCatalogAPI, "TaskCatalogAPI");
2874
2746
  var TaskCatalogAPI = _TaskCatalogAPI;
2875
2747
 
2876
2748
  // src/v3/task-catalog-api.ts
2877
2749
  var taskCatalog = TaskCatalogAPI.getInstance();
2878
-
2879
- // src/v3/limits.ts
2880
- var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2881
- var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
2882
- var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2883
- var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2884
- var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
2885
- var OTEL_LINK_COUNT_LIMIT = 2;
2886
- var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
2887
- var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
2888
- var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
2889
- function imposeAttributeLimits(attributes) {
2890
- const newAttributes = {};
2891
- for (const [key, value] of Object.entries(attributes)) {
2892
- if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
2893
- continue;
2894
- }
2895
- if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
2896
- break;
2897
- }
2898
- newAttributes[key] = value;
2899
- }
2900
- return newAttributes;
2901
- }
2902
- __name(imposeAttributeLimits, "imposeAttributeLimits");
2903
- function calculateAttributeValueLength(value) {
2904
- if (value === void 0 || value === null) {
2905
- return 0;
2906
- }
2907
- if (typeof value === "string") {
2908
- return value.length;
2909
- }
2910
- if (typeof value === "number") {
2911
- return 8;
2912
- }
2913
- if (typeof value === "boolean") {
2914
- return 4;
2915
- }
2916
- if (Array.isArray(value)) {
2917
- return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
2918
- }
2919
- return 0;
2920
- }
2921
- __name(calculateAttributeValueLength, "calculateAttributeValueLength");
2922
2750
  function dateDifference(date1, date2) {
2923
2751
  return Math.abs(date1.getTime() - date2.getTime());
2924
2752
  }
@@ -3064,146 +2892,6 @@ var _TriggerTracer = class _TriggerTracer {
3064
2892
  };
3065
2893
  __name(_TriggerTracer, "TriggerTracer");
3066
2894
  var TriggerTracer = _TriggerTracer;
3067
- var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
3068
- var _ConsoleInterceptor = class _ConsoleInterceptor {
3069
- constructor(logger2, sendToStdIO) {
3070
- __privateAdd(this, _handleLog);
3071
- __privateAdd(this, _getTimestampInHrTime2);
3072
- __privateAdd(this, _getAttributes);
3073
- this.logger = logger2;
3074
- this.sendToStdIO = sendToStdIO;
3075
- }
3076
- // Intercept the console and send logs to the OpenTelemetry logger
3077
- // during the execution of the callback
3078
- async intercept(console, callback) {
3079
- const originalConsole = {
3080
- log: console.log,
3081
- info: console.info,
3082
- warn: console.warn,
3083
- error: console.error,
3084
- debug: console.debug
3085
- };
3086
- console.log = this.log.bind(this);
3087
- console.info = this.info.bind(this);
3088
- console.warn = this.warn.bind(this);
3089
- console.error = this.error.bind(this);
3090
- console.debug = this.debug.bind(this);
3091
- try {
3092
- return await callback();
3093
- } finally {
3094
- console.log = originalConsole.log;
3095
- console.info = originalConsole.info;
3096
- console.warn = originalConsole.warn;
3097
- console.error = originalConsole.error;
3098
- console.debug = originalConsole.debug;
3099
- }
3100
- }
3101
- debug(...args) {
3102
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.DEBUG, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Debug", ...args);
3103
- }
3104
- log(...args) {
3105
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
3106
- }
3107
- info(...args) {
3108
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Info", ...args);
3109
- }
3110
- warn(...args) {
3111
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.WARN, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Warn", ...args);
3112
- }
3113
- error(...args) {
3114
- __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.ERROR, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Error", ...args);
3115
- }
3116
- };
3117
- _handleLog = new WeakSet();
3118
- handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
3119
- const body = util.format(...args);
3120
- if (this.sendToStdIO) {
3121
- if (severityNumber === SeverityNumber.ERROR) {
3122
- process.stderr.write(body);
3123
- } else {
3124
- process.stdout.write(body);
3125
- }
3126
- }
3127
- const parsed = tryParseJSON(body);
3128
- if (parsed.ok) {
3129
- this.logger.emit({
3130
- severityNumber,
3131
- severityText,
3132
- body: getLogMessage(parsed.value, severityText),
3133
- attributes: {
3134
- ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3135
- ...flattenAttributes(parsed.value)
3136
- },
3137
- timestamp
3138
- });
3139
- return;
3140
- }
3141
- this.logger.emit({
3142
- severityNumber,
3143
- severityText,
3144
- body,
3145
- attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
3146
- timestamp
3147
- });
3148
- }, "#handleLog");
3149
- _getTimestampInHrTime2 = new WeakSet();
3150
- getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
3151
- return clock.preciseNow();
3152
- }, "#getTimestampInHrTime");
3153
- _getAttributes = new WeakSet();
3154
- getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
3155
- const icon = iconStringForSeverity(severityNumber1);
3156
- let result = {};
3157
- if (icon !== void 0) {
3158
- result[SemanticInternalAttributes.STYLE_ICON] = icon;
3159
- }
3160
- return result;
3161
- }, "#getAttributes");
3162
- __name(_ConsoleInterceptor, "ConsoleInterceptor");
3163
- var ConsoleInterceptor = _ConsoleInterceptor;
3164
- function getLogMessage(value, fallback) {
3165
- if (typeof value["message"] === "string") {
3166
- return value["message"];
3167
- }
3168
- if (typeof value["msg"] === "string") {
3169
- return value["msg"];
3170
- }
3171
- if (typeof value["body"] === "string") {
3172
- return value["body"];
3173
- }
3174
- if (typeof value["error"] === "string") {
3175
- return value["error"];
3176
- }
3177
- return fallback;
3178
- }
3179
- __name(getLogMessage, "getLogMessage");
3180
- function tryParseJSON(value) {
3181
- try {
3182
- const parsed = JSON.parse(value);
3183
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
3184
- return {
3185
- ok: true,
3186
- value: parsed
3187
- };
3188
- }
3189
- return {
3190
- ok: false,
3191
- value
3192
- };
3193
- } catch (e) {
3194
- return {
3195
- ok: false,
3196
- value
3197
- };
3198
- }
3199
- }
3200
- __name(tryParseJSON, "tryParseJSON");
3201
-
3202
- // src/v3/utils/styleAttributes.ts
3203
- function accessoryAttributes(accessory) {
3204
- return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
3205
- }
3206
- __name(accessoryAttributes, "accessoryAttributes");
3207
2895
 
3208
2896
  // src/eventFilterMatches.ts
3209
2897
  function eventFilterMatches(payload, filter) {
@@ -3373,150 +3061,12 @@ function omit(obj, ...keys) {
3373
3061
  return result;
3374
3062
  }
3375
3063
  __name(omit, "omit");
3376
- var _a;
3377
- var AsyncResourceDetector = (_a = class {
3378
- constructor() {
3379
- __publicField(this, "_resolved", false);
3380
- this._promise = new Promise((resolver) => {
3381
- this._resolver = resolver;
3382
- });
3383
- }
3384
- detect(_config) {
3385
- return new Resource({}, this._promise);
3386
- }
3387
- resolveWithAttributes(attributes) {
3388
- if (!this._resolver) {
3389
- throw new Error("Resolver not available");
3390
- }
3391
- if (this._resolved) {
3392
- return;
3393
- }
3394
- this._resolved = true;
3395
- this._resolver(attributes);
3396
- }
3397
- }, __name(_a, "AsyncResourceDetector"), _a);
3398
- var _TracingSDK = class _TracingSDK {
3399
- constructor(config) {
3400
- this.config = config;
3401
- this.asyncResourceDetector = new AsyncResourceDetector();
3402
- setLogLevel(config.diagLogLevel ?? "none");
3403
- const envResourceAttributesSerialized = getEnvVar("OTEL_RESOURCE_ATTRIBUTES");
3404
- const envResourceAttributes = envResourceAttributesSerialized ? JSON.parse(envResourceAttributesSerialized) : {};
3405
- const commonResources = detectResourcesSync({
3406
- detectors: [
3407
- this.asyncResourceDetector,
3408
- processDetectorSync
3409
- ]
3410
- }).merge(new Resource({
3411
- [SemanticResourceAttributes.CLOUD_PROVIDER]: "trigger.dev",
3412
- [SemanticInternalAttributes.TRIGGER]: true
3413
- })).merge(config.resource ?? new Resource({})).merge(new Resource(envResourceAttributes));
3414
- const traceProvider = new NodeTracerProvider({
3415
- forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
3416
- resource: commonResources,
3417
- spanLimits: {
3418
- attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
3419
- attributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
3420
- eventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT,
3421
- attributePerEventCountLimit: OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
3422
- linkCountLimit: OTEL_LINK_COUNT_LIMIT,
3423
- attributePerLinkCountLimit: OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT
3424
- }
3425
- });
3426
- const spanExporter = new OTLPTraceExporter({
3427
- url: `${config.url}/v1/traces`,
3428
- timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
3429
- });
3430
- traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new BatchSpanProcessor(spanExporter, {
3431
- maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
3432
- scheduledDelayMillis: parseInt(getEnvVar("OTEL_SPAN_SCHEDULED_DELAY_MILLIS") ?? "200"),
3433
- exportTimeoutMillis: parseInt(getEnvVar("OTEL_SPAN_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
3434
- maxQueueSize: parseInt(getEnvVar("OTEL_SPAN_MAX_QUEUE_SIZE") ?? "512")
3435
- }) : new SimpleSpanProcessor(spanExporter)));
3436
- traceProvider.register();
3437
- registerInstrumentations({
3438
- instrumentations: config.instrumentations ?? [],
3439
- tracerProvider: traceProvider
3440
- });
3441
- const logExporter = new OTLPLogExporter({
3442
- url: `${config.url}/v1/logs`
3443
- });
3444
- const loggerProvider = new LoggerProvider({
3445
- resource: commonResources,
3446
- logRecordLimits: {
3447
- attributeCountLimit: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
3448
- attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
3449
- }
3450
- });
3451
- loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new BatchLogRecordProcessor(logExporter, {
3452
- maxExportBatchSize: parseInt(getEnvVar("OTEL_LOG_MAX_EXPORT_BATCH_SIZE") ?? "64"),
3453
- scheduledDelayMillis: parseInt(getEnvVar("OTEL_LOG_SCHEDULED_DELAY_MILLIS") ?? "200"),
3454
- exportTimeoutMillis: parseInt(getEnvVar("OTEL_LOG_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
3455
- maxQueueSize: parseInt(getEnvVar("OTEL_LOG_MAX_QUEUE_SIZE") ?? "512")
3456
- }) : new SimpleLogRecordProcessor(logExporter)));
3457
- this._logProvider = loggerProvider;
3458
- this._spanExporter = spanExporter;
3459
- this._traceProvider = traceProvider;
3460
- logs.setGlobalLoggerProvider(loggerProvider);
3461
- this.getLogger = loggerProvider.getLogger.bind(loggerProvider);
3462
- this.getTracer = traceProvider.getTracer.bind(traceProvider);
3463
- }
3464
- async flush() {
3465
- await this._traceProvider.forceFlush();
3466
- await this._logProvider.forceFlush();
3467
- }
3468
- async shutdown() {
3469
- await this._traceProvider.shutdown();
3470
- await this._logProvider.shutdown();
3471
- }
3472
- };
3473
- __name(_TracingSDK, "TracingSDK");
3474
- var TracingSDK = _TracingSDK;
3475
- function setLogLevel(level) {
3476
- let diagLogLevel;
3477
- switch (level) {
3478
- case "none":
3479
- diagLogLevel = DiagLogLevel.NONE;
3480
- break;
3481
- case "error":
3482
- diagLogLevel = DiagLogLevel.ERROR;
3483
- break;
3484
- case "warn":
3485
- diagLogLevel = DiagLogLevel.WARN;
3486
- break;
3487
- case "info":
3488
- diagLogLevel = DiagLogLevel.INFO;
3489
- break;
3490
- case "debug":
3491
- diagLogLevel = DiagLogLevel.DEBUG;
3492
- break;
3493
- case "verbose":
3494
- diagLogLevel = DiagLogLevel.VERBOSE;
3495
- break;
3496
- case "all":
3497
- diagLogLevel = DiagLogLevel.ALL;
3498
- break;
3499
- default:
3500
- diagLogLevel = DiagLogLevel.NONE;
3501
- }
3502
- diag.setLogger(new DiagConsoleLogger(), diagLogLevel);
3503
- }
3504
- __name(setLogLevel, "setLogLevel");
3505
3064
 
3506
- // src/v3/otel/index.ts
3507
- function recordSpanException(span, error) {
3508
- if (error instanceof Error) {
3509
- span.recordException(error);
3510
- } else if (typeof error === "string") {
3511
- span.recordException(new Error(error));
3512
- } else {
3513
- span.recordException(new Error(JSON.stringify(error)));
3514
- }
3515
- span.setStatus({
3516
- code: SpanStatusCode.ERROR
3517
- });
3065
+ // src/v3/utils/styleAttributes.ts
3066
+ function accessoryAttributes(accessory) {
3067
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
3518
3068
  }
3519
- __name(recordSpanException, "recordSpanException");
3069
+ __name(accessoryAttributes, "accessoryAttributes");
3520
3070
 
3521
3071
  // package.json
3522
3072
  var dependencies = {
@@ -3815,94 +3365,6 @@ function safeJsonParse2(value) {
3815
3365
  }
3816
3366
  __name(safeJsonParse2, "safeJsonParse");
3817
3367
 
3818
- // src/v3/task-catalog/standardTaskCatalog.ts
3819
- var _StandardTaskCatalog = class _StandardTaskCatalog {
3820
- constructor() {
3821
- __publicField(this, "_taskMetadata", /* @__PURE__ */ new Map());
3822
- __publicField(this, "_taskFunctions", /* @__PURE__ */ new Map());
3823
- __publicField(this, "_taskFileMetadata", /* @__PURE__ */ new Map());
3824
- }
3825
- registerTaskMetadata(task) {
3826
- const { fns, ...metadata } = task;
3827
- this._taskMetadata.set(task.id, metadata);
3828
- this._taskFunctions.set(task.id, fns);
3829
- }
3830
- updateTaskMetadata(id, updates) {
3831
- const existingMetadata = this._taskMetadata.get(id);
3832
- if (existingMetadata) {
3833
- this._taskMetadata.set(id, {
3834
- ...existingMetadata,
3835
- ...updates
3836
- });
3837
- }
3838
- if (updates.fns) {
3839
- const existingFunctions = this._taskFunctions.get(id);
3840
- if (existingFunctions) {
3841
- this._taskFunctions.set(id, {
3842
- ...existingFunctions,
3843
- ...updates.fns
3844
- });
3845
- }
3846
- }
3847
- }
3848
- registerTaskFileMetadata(id, metadata) {
3849
- this._taskFileMetadata.set(id, metadata);
3850
- }
3851
- // Return all the tasks, without the functions
3852
- getAllTaskMetadata() {
3853
- const result = [];
3854
- for (const [id, metadata] of this._taskMetadata) {
3855
- const fileMetadata = this._taskFileMetadata.get(id);
3856
- if (!fileMetadata) {
3857
- continue;
3858
- }
3859
- result.push({
3860
- ...metadata,
3861
- ...fileMetadata
3862
- });
3863
- }
3864
- return result;
3865
- }
3866
- getTaskMetadata(id) {
3867
- const metadata = this._taskMetadata.get(id);
3868
- const fileMetadata = this._taskFileMetadata.get(id);
3869
- if (!metadata || !fileMetadata) {
3870
- return void 0;
3871
- }
3872
- return {
3873
- ...metadata,
3874
- ...fileMetadata
3875
- };
3876
- }
3877
- getTask(id) {
3878
- const metadata = this._taskMetadata.get(id);
3879
- const fileMetadata = this._taskFileMetadata.get(id);
3880
- const fns = this._taskFunctions.get(id);
3881
- if (!metadata || !fns || !fileMetadata) {
3882
- return void 0;
3883
- }
3884
- return {
3885
- ...metadata,
3886
- ...fileMetadata,
3887
- fns
3888
- };
3889
- }
3890
- disable() {
3891
- }
3892
- };
3893
- __name(_StandardTaskCatalog, "StandardTaskCatalog");
3894
- var StandardTaskCatalog = _StandardTaskCatalog;
3895
-
3896
- // src/v3/index.ts
3897
- function parseTriggerTaskRequestBody(body) {
3898
- return TriggerTaskRequestBody.safeParse(body);
3899
- }
3900
- __name(parseTriggerTaskRequestBody, "parseTriggerTaskRequestBody");
3901
- function parseBatchTriggerTaskRequestBody(body) {
3902
- return BatchTriggerTaskRequestBody.safeParse(body);
3903
- }
3904
- __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
3905
-
3906
- export { APIConnectionError, APIError, ApiClient, ApiClientManager, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, ConsoleInterceptor, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, DeletedScheduleObject, DeploymentErrorData, EnvironmentType, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListScheduleOptions, ListSchedulesResult, Machine, MachineCpu, MachineMemory, NotFoundError, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OtelTaskLogger, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RetryOptions, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SharedQueueToClientMessages, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StandardTaskCatalog, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskContextSpanProcessor, TaskEventStyle, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TracingSDK, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, getEnvVar, groupTaskMetadataIssuesByTask, iconStringForSeverity, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logLevels, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseBatchTriggerTaskRequestBody, parseError, parsePacket, parseTriggerTaskRequestBody, prettyPrintPacket, primitiveValueOrflattenedAttributes, recordSpanException, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContextManager, unflattenAttributes, workerToChildMessages };
3368
+ export { APIConnectionError, APIError, ApiClient, ApiClientManager, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, DeletedScheduleObject, DeploymentErrorData, EnvironmentType, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListScheduleOptions, ListSchedulesResult, Machine, MachineCpu, MachineMemory, NotFoundError, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RetryOptions, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SharedQueueToClientMessages, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskEventStyle, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, groupTaskMetadataIssuesByTask, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseError, parsePacket, prettyPrintPacket, primitiveValueOrflattenedAttributes, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContext, unflattenAttributes, workerToChildMessages };
3907
3369
  //# sourceMappingURL=out.js.map
3908
3370
  //# sourceMappingURL=index.mjs.map