@trigger.dev/core 3.0.0-beta.46 → 3.0.0-beta.47

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 (45) hide show
  1. package/dist/{catalog-9G8AqnI9.d.ts → catalog-N-X0Te3W.d.mts} +5 -23
  2. package/dist/{catalog-Y0mRLMtJ.d.mts → catalog-NxVZnWZh.d.ts} +5 -23
  3. package/dist/{common-55Mqj8JP.d.mts → common-fIyU5pmz.d.mts} +13 -0
  4. package/dist/{common-55Mqj8JP.d.ts → common-fIyU5pmz.d.ts} +13 -0
  5. package/dist/{manager-6NRInm7C.d.ts → manager-2ZQ3_twq.d.ts} +1 -1
  6. package/dist/{manager-2AqSY67c.d.mts → manager-X_HrWQ7_.d.mts} +1 -1
  7. package/dist/{messages-nXkzt5CT.d.mts → messages-Sggr4tid.d.mts} +162 -0
  8. package/dist/{messages-nXkzt5CT.d.ts → messages-Sggr4tid.d.ts} +162 -0
  9. package/dist/{schemas-CeAee_C2.d.mts → schemas-Zy7mGFgD.d.mts} +19 -0
  10. package/dist/{schemas-CeAee_C2.d.ts → schemas-Zy7mGFgD.d.ts} +19 -0
  11. package/dist/tracer-N0p2Fuuv.d.mts +23 -0
  12. package/dist/tracer-N0p2Fuuv.d.ts +23 -0
  13. package/dist/v3/dev/index.d.mts +2 -2
  14. package/dist/v3/dev/index.d.ts +2 -2
  15. package/dist/v3/index.d.mts +50 -38
  16. package/dist/v3/index.d.ts +50 -38
  17. package/dist/v3/index.js +470 -303
  18. package/dist/v3/index.js.map +1 -1
  19. package/dist/v3/index.mjs +467 -304
  20. package/dist/v3/index.mjs.map +1 -1
  21. package/dist/v3/otel/index.js +15 -5
  22. package/dist/v3/otel/index.js.map +1 -1
  23. package/dist/v3/otel/index.mjs +15 -5
  24. package/dist/v3/otel/index.mjs.map +1 -1
  25. package/dist/v3/prod/index.d.mts +3 -3
  26. package/dist/v3/prod/index.d.ts +3 -3
  27. package/dist/v3/schemas/index.d.mts +16 -4
  28. package/dist/v3/schemas/index.d.ts +16 -4
  29. package/dist/v3/schemas/index.js +3 -1
  30. package/dist/v3/schemas/index.js.map +1 -1
  31. package/dist/v3/schemas/index.mjs +3 -1
  32. package/dist/v3/schemas/index.mjs.map +1 -1
  33. package/dist/v3/workers/index.d.mts +7 -6
  34. package/dist/v3/workers/index.d.ts +7 -6
  35. package/dist/v3/workers/index.js +250 -96
  36. package/dist/v3/workers/index.js.map +1 -1
  37. package/dist/v3/workers/index.mjs +250 -96
  38. package/dist/v3/workers/index.mjs.map +1 -1
  39. package/dist/v3/zodfetch.d.mts +15 -2
  40. package/dist/v3/zodfetch.d.ts +15 -2
  41. package/dist/v3/zodfetch.js +248 -28
  42. package/dist/v3/zodfetch.js.map +1 -1
  43. package/dist/v3/zodfetch.mjs +246 -29
  44. package/dist/v3/zodfetch.mjs.map +1 -1
  45. package/package.json +1 -1
package/dist/v3/index.mjs CHANGED
@@ -27,7 +27,7 @@ var __privateMethod = (obj, member, method) => {
27
27
  };
28
28
 
29
29
  // package.json
30
- var version = "3.0.0-beta.46";
30
+ var version = "3.0.0-beta.47";
31
31
  var dependencies = {
32
32
  "@google-cloud/precise-date": "^4.0.0",
33
33
  "@opentelemetry/api": "^1.8.0",
@@ -161,6 +161,7 @@ var TaskRun = z.object({
161
161
  createdAt: z.coerce.date(),
162
162
  startedAt: z.coerce.date().default(() => /* @__PURE__ */ new Date()),
163
163
  idempotencyKey: z.string().optional(),
164
+ maxAttempts: z.number().optional(),
164
165
  durationMs: z.number().default(0),
165
166
  costInCents: z.number().default(0),
166
167
  baseCostInCents: z.number().default(0)
@@ -479,6 +480,14 @@ var ImageDetailsMetadata = z.object({
479
480
  contentHash: z.string(),
480
481
  imageTag: z.string()
481
482
  });
483
+ var _AbortTaskRunError = class _AbortTaskRunError extends Error {
484
+ constructor(message) {
485
+ super(message);
486
+ this.name = "AbortTaskRunError";
487
+ }
488
+ };
489
+ __name(_AbortTaskRunError, "AbortTaskRunError");
490
+ var AbortTaskRunError = _AbortTaskRunError;
482
491
  function parseError(error) {
483
492
  if (error instanceof Error) {
484
493
  return {
@@ -559,6 +568,39 @@ function createJsonErrorObject(error) {
559
568
  }
560
569
  }
561
570
  __name(createJsonErrorObject, "createJsonErrorObject");
571
+ function sanitizeError(error) {
572
+ switch (error.type) {
573
+ case "BUILT_IN_ERROR": {
574
+ return {
575
+ type: "BUILT_IN_ERROR",
576
+ message: error.message?.replace(/\0/g, ""),
577
+ name: error.name?.replace(/\0/g, ""),
578
+ stackTrace: error.stackTrace?.replace(/\0/g, "")
579
+ };
580
+ }
581
+ case "STRING_ERROR": {
582
+ return {
583
+ type: "STRING_ERROR",
584
+ raw: error.raw.replace(/\0/g, "")
585
+ };
586
+ }
587
+ case "CUSTOM_ERROR": {
588
+ return {
589
+ type: "CUSTOM_ERROR",
590
+ raw: error.raw.replace(/\0/g, "")
591
+ };
592
+ }
593
+ case "INTERNAL_ERROR": {
594
+ return {
595
+ type: "INTERNAL_ERROR",
596
+ code: error.code,
597
+ message: error.message?.replace(/\0/g, ""),
598
+ stackTrace: error.stackTrace?.replace(/\0/g, "")
599
+ };
600
+ }
601
+ }
602
+ }
603
+ __name(sanitizeError, "sanitizeError");
562
604
  function correctErrorStackTrace(stackTrace, projectDir, options) {
563
605
  const [errorLine, ...traceLines] = stackTrace.split("\n");
564
606
  return [
@@ -674,7 +716,8 @@ var TriggerTaskRequestBody = z.object({
674
716
  test: z.boolean().optional(),
675
717
  payloadType: z.string().optional(),
676
718
  delay: z.string().or(z.coerce.date()).optional(),
677
- ttl: z.string().or(z.number().nonnegative().int()).optional()
719
+ ttl: z.string().or(z.number().nonnegative().int()).optional(),
720
+ maxAttempts: z.number().int().optional()
678
721
  }).optional()
679
722
  });
680
723
  var TriggerTaskResponse = z.object({
@@ -2138,7 +2181,10 @@ var SemanticInternalAttributes = {
2138
2181
  LINK_TITLE: "$link.title",
2139
2182
  IDEMPOTENCY_KEY: "ctx.run.idempotencyKey",
2140
2183
  USAGE_DURATION_MS: "$usage.durationMs",
2141
- USAGE_COST_IN_CENTS: "$usage.costInCents"
2184
+ USAGE_COST_IN_CENTS: "$usage.costInCents",
2185
+ RATE_LIMIT_LIMIT: "response.rateLimit.limit",
2186
+ RATE_LIMIT_REMAINING: "response.rateLimit.remaining",
2187
+ RATE_LIMIT_RESET: "response.rateLimit.reset"
2142
2188
  };
2143
2189
 
2144
2190
  // src/v3/taskContext/index.ts
@@ -2228,10 +2274,118 @@ var TaskContextAPI = _TaskContextAPI;
2228
2274
  // src/v3/task-context-api.ts
2229
2275
  var taskContext = TaskContextAPI.getInstance();
2230
2276
 
2277
+ // src/retry.ts
2278
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
2279
+ if (!resets)
2280
+ return;
2281
+ switch (format) {
2282
+ case "iso_8601_duration_openai_variant": {
2283
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
2284
+ }
2285
+ case "iso_8601": {
2286
+ return calculateISO8601ResetAt(resets, now);
2287
+ }
2288
+ case "unix_timestamp": {
2289
+ return calculateUnixTimestampResetAt(resets, now);
2290
+ }
2291
+ case "unix_timestamp_in_ms": {
2292
+ return calculateUnixTimestampInMsResetAt(resets, now);
2293
+ }
2294
+ }
2295
+ }
2296
+ __name(calculateResetAt, "calculateResetAt");
2297
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
2298
+ if (!resets)
2299
+ return void 0;
2300
+ const resetAt = parseInt(resets, 10);
2301
+ if (isNaN(resetAt))
2302
+ return void 0;
2303
+ return new Date(resetAt * 1e3);
2304
+ }
2305
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
2306
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
2307
+ if (!resets)
2308
+ return void 0;
2309
+ const resetAt = parseInt(resets, 10);
2310
+ if (isNaN(resetAt))
2311
+ return void 0;
2312
+ return new Date(resetAt);
2313
+ }
2314
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
2315
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
2316
+ if (!resets)
2317
+ return void 0;
2318
+ const resetAt = new Date(resets);
2319
+ if (isNaN(resetAt.getTime()))
2320
+ return void 0;
2321
+ return resetAt;
2322
+ }
2323
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
2324
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
2325
+ if (!resets)
2326
+ return void 0;
2327
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
2328
+ const match = resets.match(pattern);
2329
+ if (!match)
2330
+ return void 0;
2331
+ const days = parseInt(match[1], 10) || 0;
2332
+ const hours = parseInt(match[2], 10) || 0;
2333
+ const minutes = parseInt(match[3], 10) || 0;
2334
+ const seconds = parseFloat(match[4]) || 0;
2335
+ const milliseconds = parseInt(match[5], 10) || 0;
2336
+ const resetAt = new Date(now);
2337
+ resetAt.setDate(resetAt.getDate() + days);
2338
+ resetAt.setHours(resetAt.getHours() + hours);
2339
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
2340
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
2341
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
2342
+ return resetAt;
2343
+ }
2344
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
2345
+
2346
+ // src/v3/utils/retries.ts
2347
+ var defaultRetryOptions = {
2348
+ maxAttempts: 3,
2349
+ factor: 2,
2350
+ minTimeoutInMs: 1e3,
2351
+ maxTimeoutInMs: 6e4,
2352
+ randomize: true
2353
+ };
2354
+ var defaultFetchRetryOptions = {
2355
+ byStatus: {
2356
+ "429,408,409,5xx": {
2357
+ strategy: "backoff",
2358
+ ...defaultRetryOptions
2359
+ }
2360
+ },
2361
+ connectionError: defaultRetryOptions,
2362
+ timeout: defaultRetryOptions
2363
+ };
2364
+ function calculateNextRetryDelay(options, attempt) {
2365
+ const opts = {
2366
+ ...defaultRetryOptions,
2367
+ ...options
2368
+ };
2369
+ if (attempt >= opts.maxAttempts) {
2370
+ return;
2371
+ }
2372
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
2373
+ const random = randomize ? Math.random() + 1 : 1;
2374
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
2375
+ return Math.round(timeout);
2376
+ }
2377
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
2378
+ function calculateResetAt2(resets, format, now = Date.now()) {
2379
+ const resetAt = calculateResetAt(resets, format, new Date(now));
2380
+ return resetAt?.getTime();
2381
+ }
2382
+ __name(calculateResetAt2, "calculateResetAt");
2383
+
2231
2384
  // src/v3/apiClient/errors.ts
2232
2385
  var _ApiError = class _ApiError extends Error {
2233
2386
  constructor(status, error, message, headers) {
2234
2387
  super(`${_ApiError.makeMessage(status, error, message)}`);
2388
+ this.name = "TriggerApiError";
2235
2389
  this.status = status;
2236
2390
  this.headers = headers;
2237
2391
  const data = error;
@@ -2352,6 +2506,16 @@ var _RateLimitError = class _RateLimitError extends ApiError {
2352
2506
  super(...arguments);
2353
2507
  __publicField(this, "status", 429);
2354
2508
  }
2509
+ get millisecondsUntilReset() {
2510
+ const resetAtUnixEpochMs = (this.headers ?? {})["x-ratelimit-reset"];
2511
+ if (typeof resetAtUnixEpochMs === "string") {
2512
+ const resetAtUnixEpoch = parseInt(resetAtUnixEpochMs, 10);
2513
+ if (isNaN(resetAtUnixEpoch)) {
2514
+ return;
2515
+ }
2516
+ return Math.max(resetAtUnixEpoch - Date.now() + Math.floor(Math.random() * 2e3), 0);
2517
+ }
2518
+ }
2355
2519
  };
2356
2520
  __name(_RateLimitError, "RateLimitError");
2357
2521
  var RateLimitError = _RateLimitError;
@@ -2366,112 +2530,131 @@ function castToError(err) {
2366
2530
  }
2367
2531
  __name(castToError, "castToError");
2368
2532
 
2369
- // src/retry.ts
2370
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
2371
- if (!resets)
2372
- return;
2373
- switch (format) {
2374
- case "iso_8601_duration_openai_variant": {
2375
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
2376
- }
2377
- case "iso_8601": {
2378
- return calculateISO8601ResetAt(resets, now);
2533
+ // src/v3/utils/flattenAttributes.ts
2534
+ var NULL_SENTINEL = "$@null((";
2535
+ function flattenAttributes(obj, prefix) {
2536
+ const result = {};
2537
+ if (obj === void 0) {
2538
+ return result;
2539
+ }
2540
+ if (obj === null) {
2541
+ result[prefix || ""] = NULL_SENTINEL;
2542
+ return result;
2543
+ }
2544
+ if (typeof obj === "string") {
2545
+ result[prefix || ""] = obj;
2546
+ return result;
2547
+ }
2548
+ if (typeof obj === "number") {
2549
+ result[prefix || ""] = obj;
2550
+ return result;
2551
+ }
2552
+ if (typeof obj === "boolean") {
2553
+ result[prefix || ""] = obj;
2554
+ return result;
2555
+ }
2556
+ for (const [key, value] of Object.entries(obj)) {
2557
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${Array.isArray(obj) ? `[${key}]` : key}`;
2558
+ if (Array.isArray(value)) {
2559
+ for (let i = 0; i < value.length; i++) {
2560
+ if (typeof value[i] === "object" && value[i] !== null) {
2561
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
2562
+ } else {
2563
+ if (value[i] === null) {
2564
+ result[`${newPrefix}.[${i}]`] = NULL_SENTINEL;
2565
+ } else {
2566
+ result[`${newPrefix}.[${i}]`] = value[i];
2567
+ }
2568
+ }
2569
+ }
2570
+ } else if (isRecord(value)) {
2571
+ Object.assign(result, flattenAttributes(value, newPrefix));
2572
+ } else {
2573
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
2574
+ result[newPrefix] = value;
2575
+ } else if (value === null) {
2576
+ result[newPrefix] = NULL_SENTINEL;
2577
+ }
2379
2578
  }
2380
- case "unix_timestamp": {
2381
- return calculateUnixTimestampResetAt(resets, now);
2579
+ }
2580
+ return result;
2581
+ }
2582
+ __name(flattenAttributes, "flattenAttributes");
2583
+ function isRecord(value) {
2584
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2585
+ }
2586
+ __name(isRecord, "isRecord");
2587
+ function unflattenAttributes(obj) {
2588
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
2589
+ return obj;
2590
+ }
2591
+ if (typeof obj === "object" && obj !== null && Object.keys(obj).length === 1 && Object.keys(obj)[0] === "") {
2592
+ return rehydrateNull(obj[""]);
2593
+ }
2594
+ if (Object.keys(obj).length === 0) {
2595
+ return;
2596
+ }
2597
+ const result = {};
2598
+ for (const [key, value] of Object.entries(obj)) {
2599
+ const parts = key.split(".").reduce((acc, part) => {
2600
+ if (part.includes("[")) {
2601
+ const subparts = part.split(/\[|\]/).filter((p) => p !== "");
2602
+ acc.push(...subparts);
2603
+ } else {
2604
+ acc.push(part);
2605
+ }
2606
+ return acc;
2607
+ }, []);
2608
+ let current = result;
2609
+ for (let i = 0; i < parts.length - 1; i++) {
2610
+ const part = parts[i];
2611
+ const nextPart = parts[i + 1];
2612
+ const isArray = /^\d+$/.test(nextPart);
2613
+ if (isArray && !Array.isArray(current[part])) {
2614
+ current[part] = [];
2615
+ } else if (!isArray && current[part] === void 0) {
2616
+ current[part] = {};
2617
+ }
2618
+ current = current[part];
2382
2619
  }
2383
- case "unix_timestamp_in_ms": {
2384
- return calculateUnixTimestampInMsResetAt(resets, now);
2620
+ const lastPart = parts[parts.length - 1];
2621
+ current[lastPart] = rehydrateNull(value);
2622
+ }
2623
+ if (Object.keys(result).every((k) => /^\d+$/.test(k))) {
2624
+ const maxIndex = Math.max(...Object.keys(result).map((k) => parseInt(k)));
2625
+ const arrayResult = Array(maxIndex + 1);
2626
+ for (const key in result) {
2627
+ arrayResult[parseInt(key)] = result[key];
2385
2628
  }
2629
+ return arrayResult;
2386
2630
  }
2631
+ return result;
2387
2632
  }
2388
- __name(calculateResetAt, "calculateResetAt");
2389
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
2390
- if (!resets)
2391
- return void 0;
2392
- const resetAt = parseInt(resets, 10);
2393
- if (isNaN(resetAt))
2394
- return void 0;
2395
- return new Date(resetAt * 1e3);
2396
- }
2397
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
2398
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
2399
- if (!resets)
2400
- return void 0;
2401
- const resetAt = parseInt(resets, 10);
2402
- if (isNaN(resetAt))
2403
- return void 0;
2404
- return new Date(resetAt);
2405
- }
2406
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
2407
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
2408
- if (!resets)
2409
- return void 0;
2410
- const resetAt = new Date(resets);
2411
- if (isNaN(resetAt.getTime()))
2412
- return void 0;
2413
- return resetAt;
2414
- }
2415
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
2416
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
2417
- if (!resets)
2418
- return void 0;
2419
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
2420
- const match = resets.match(pattern);
2421
- if (!match)
2422
- return void 0;
2423
- const days = parseInt(match[1], 10) || 0;
2424
- const hours = parseInt(match[2], 10) || 0;
2425
- const minutes = parseInt(match[3], 10) || 0;
2426
- const seconds = parseFloat(match[4]) || 0;
2427
- const milliseconds = parseInt(match[5], 10) || 0;
2428
- const resetAt = new Date(now);
2429
- resetAt.setDate(resetAt.getDate() + days);
2430
- resetAt.setHours(resetAt.getHours() + hours);
2431
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
2432
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
2433
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
2434
- return resetAt;
2633
+ __name(unflattenAttributes, "unflattenAttributes");
2634
+ function primitiveValueOrflattenedAttributes(obj, prefix) {
2635
+ if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
2636
+ return obj;
2637
+ }
2638
+ const attributes = flattenAttributes(obj, prefix);
2639
+ if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
2640
+ return attributes[prefix];
2641
+ }
2642
+ return attributes;
2435
2643
  }
2436
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
2437
-
2438
- // src/v3/utils/retries.ts
2439
- var defaultRetryOptions = {
2440
- maxAttempts: 3,
2441
- factor: 2,
2442
- minTimeoutInMs: 1e3,
2443
- maxTimeoutInMs: 6e4,
2444
- randomize: true
2445
- };
2446
- var defaultFetchRetryOptions = {
2447
- byStatus: {
2448
- "429,408,409,5xx": {
2449
- strategy: "backoff",
2450
- ...defaultRetryOptions
2451
- }
2452
- },
2453
- connectionError: defaultRetryOptions,
2454
- timeout: defaultRetryOptions
2455
- };
2456
- function calculateNextRetryDelay(options, attempt) {
2457
- const opts = {
2458
- ...defaultRetryOptions,
2459
- ...options
2460
- };
2461
- if (attempt >= opts.maxAttempts) {
2462
- return;
2644
+ __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
2645
+ function rehydrateNull(value) {
2646
+ if (value === NULL_SENTINEL) {
2647
+ return null;
2463
2648
  }
2464
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
2465
- const random = randomize ? Math.random() + 1 : 1;
2466
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
2467
- return Math.round(timeout);
2649
+ return value;
2468
2650
  }
2469
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
2470
- function calculateResetAt2(resets, format, now = Date.now()) {
2471
- const resetAt = calculateResetAt(resets, format, new Date(now));
2472
- return resetAt?.getTime();
2651
+ __name(rehydrateNull, "rehydrateNull");
2652
+
2653
+ // src/v3/utils/styleAttributes.ts
2654
+ function accessoryAttributes(accessory) {
2655
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
2473
2656
  }
2474
- __name(calculateResetAt2, "calculateResetAt");
2657
+ __name(accessoryAttributes, "accessoryAttributes");
2475
2658
 
2476
2659
  // src/v3/apiClient/pagination.ts
2477
2660
  var _CursorPage = class _CursorPage {
@@ -2581,6 +2764,12 @@ var defaultRetryOptions2 = {
2581
2764
  maxTimeoutInMs: 6e4,
2582
2765
  randomize: false
2583
2766
  };
2767
+ var requestOptionsKeys = {
2768
+ retry: true
2769
+ };
2770
+ var isRequestOptions = /* @__PURE__ */ __name((obj) => {
2771
+ return typeof obj === "object" && obj !== null && !isEmptyObj(obj) && Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k));
2772
+ }, "isRequestOptions");
2584
2773
  function zodfetch(schema, url, requestInit, options) {
2585
2774
  return new ApiPromise(_doZodFetch(schema, url, requestInit, options));
2586
2775
  }
@@ -2631,16 +2820,47 @@ function zodfetchOffsetLimitPage(schema, url, params, requestInit, options) {
2631
2820
  return new OffsetLimitPagePromise(fetchResult, schema, url, params, requestInit, options);
2632
2821
  }
2633
2822
  __name(zodfetchOffsetLimitPage, "zodfetchOffsetLimitPage");
2634
- async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
2823
+ async function traceZodFetch(params, callback) {
2824
+ if (!params.options?.tracer) {
2825
+ return callback();
2826
+ }
2827
+ const url = new URL(params.url);
2828
+ const method = params.requestInit?.method ?? "GET";
2829
+ const name = params.options.name ?? `${method} ${url.pathname}`;
2830
+ return await params.options.tracer.startActiveSpan(name, async (span) => {
2831
+ return await callback(span);
2832
+ }, {
2833
+ attributes: {
2834
+ [SemanticInternalAttributes.STYLE_ICON]: params.options?.icon ?? "api",
2835
+ ...params.options.attributes
2836
+ }
2837
+ });
2838
+ }
2839
+ __name(traceZodFetch, "traceZodFetch");
2840
+ async function _doZodFetch(schema, url, requestInit, options) {
2841
+ const $requestInit = await requestInit;
2842
+ return traceZodFetch({
2843
+ url,
2844
+ requestInit: $requestInit,
2845
+ options
2846
+ }, async (span) => {
2847
+ const result = await _doZodFetchWithRetries(schema, url, $requestInit, options);
2848
+ if (options?.onResponseBody && span) {
2849
+ options.onResponseBody(result.data, span);
2850
+ }
2851
+ return result;
2852
+ });
2853
+ }
2854
+ __name(_doZodFetch, "_doZodFetch");
2855
+ async function _doZodFetchWithRetries(schema, url, requestInit, options, attempt = 1) {
2635
2856
  try {
2636
- const $requestInit = await requestInit;
2637
- const response = await fetch(url, requestInitWithCache($requestInit));
2857
+ const response = await fetch(url, requestInitWithCache(requestInit));
2638
2858
  const responseHeaders = createResponseHeaders(response.headers);
2639
2859
  if (!response.ok) {
2640
2860
  const retryResult = shouldRetry(response, attempt, options?.retry);
2641
2861
  if (retryResult.retry) {
2642
- await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
2643
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2862
+ await waitForRetry(url, attempt + 1, retryResult.delay, options, requestInit, response);
2863
+ return await _doZodFetchWithRetries(schema, url, requestInit, options, attempt + 1);
2644
2864
  } else {
2645
2865
  const errText = await response.text().catch((e) => castToError2(e).message);
2646
2866
  const errJSON = safeJsonParse(errText);
@@ -2668,8 +2888,8 @@ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
2668
2888
  };
2669
2889
  const delay = calculateNextRetryDelay(retry, attempt);
2670
2890
  if (delay) {
2671
- await new Promise((resolve) => setTimeout(resolve, delay));
2672
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2891
+ await waitForRetry(url, attempt + 1, delay, options, requestInit);
2892
+ return await _doZodFetchWithRetries(schema, url, requestInit, options, attempt + 1);
2673
2893
  }
2674
2894
  }
2675
2895
  throw new ApiConnectionError({
@@ -2677,7 +2897,7 @@ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
2677
2897
  });
2678
2898
  }
2679
2899
  }
2680
- __name(_doZodFetch, "_doZodFetch");
2900
+ __name(_doZodFetchWithRetries, "_doZodFetchWithRetries");
2681
2901
  function castToError2(err) {
2682
2902
  if (err instanceof Error)
2683
2903
  return err;
@@ -2714,8 +2934,25 @@ function shouldRetry(response, attempt, retryOptions) {
2714
2934
  return shouldRetryForOptions();
2715
2935
  if (response.status === 409)
2716
2936
  return shouldRetryForOptions();
2717
- if (response.status === 429)
2937
+ if (response.status === 429) {
2938
+ if (attempt >= (typeof retryOptions?.maxAttempts === "number" ? retryOptions?.maxAttempts : 3)) {
2939
+ return {
2940
+ retry: false
2941
+ };
2942
+ }
2943
+ const resetAtUnixEpochMs = response.headers.get("x-ratelimit-reset");
2944
+ if (resetAtUnixEpochMs) {
2945
+ const resetAtUnixEpoch = parseInt(resetAtUnixEpochMs, 10);
2946
+ const delay = resetAtUnixEpoch - Date.now() + Math.floor(Math.random() * 1e3);
2947
+ if (delay > 0) {
2948
+ return {
2949
+ retry: true,
2950
+ delay
2951
+ };
2952
+ }
2953
+ }
2718
2954
  return shouldRetryForOptions();
2955
+ }
2719
2956
  if (response.status >= 500)
2720
2957
  return shouldRetryForOptions();
2721
2958
  return {
@@ -2878,9 +3115,44 @@ fetchPage_fn2 = /* @__PURE__ */ __name(function(params1) {
2878
3115
  }, "#fetchPage");
2879
3116
  __name(_OffsetLimitPagePromise, "OffsetLimitPagePromise");
2880
3117
  var OffsetLimitPagePromise = _OffsetLimitPagePromise;
3118
+ async function waitForRetry(url, attempt, delay, options, requestInit, response) {
3119
+ if (options?.tracer) {
3120
+ const method = requestInit?.method ?? "GET";
3121
+ return options.tracer.startActiveSpan(response ? `wait after ${response.status}` : `wait after error`, async (span) => {
3122
+ await new Promise((resolve) => setTimeout(resolve, delay));
3123
+ }, {
3124
+ attributes: {
3125
+ [SemanticInternalAttributes.STYLE_ICON]: "wait",
3126
+ ...accessoryAttributes({
3127
+ items: [
3128
+ {
3129
+ text: `retrying ${options?.name ?? method.toUpperCase()} in ${delay}ms`,
3130
+ variant: "normal"
3131
+ }
3132
+ ],
3133
+ style: "codepath"
3134
+ })
3135
+ }
3136
+ });
3137
+ }
3138
+ await new Promise((resolve) => setTimeout(resolve, delay));
3139
+ }
3140
+ __name(waitForRetry, "waitForRetry");
3141
+ function isEmptyObj(obj) {
3142
+ if (!obj)
3143
+ return true;
3144
+ for (const _k in obj)
3145
+ return false;
3146
+ return true;
3147
+ }
3148
+ __name(isEmptyObj, "isEmptyObj");
3149
+ function hasOwn(obj, key) {
3150
+ return Object.prototype.hasOwnProperty.call(obj, key);
3151
+ }
3152
+ __name(hasOwn, "hasOwn");
2881
3153
 
2882
3154
  // src/v3/apiClient/index.ts
2883
- var zodFetchOptions = {
3155
+ var DEFAULT_ZOD_FETCH_OPTIONS = {
2884
3156
  retry: {
2885
3157
  maxAttempts: 3,
2886
3158
  minTimeoutInMs: 1e3,
@@ -2891,17 +3163,18 @@ var zodFetchOptions = {
2891
3163
  };
2892
3164
  var _getHeaders, getHeaders_fn;
2893
3165
  var _ApiClient = class _ApiClient {
2894
- constructor(baseUrl, accessToken) {
3166
+ constructor(baseUrl, accessToken, requestOptions = {}) {
2895
3167
  __privateAdd(this, _getHeaders);
2896
3168
  this.accessToken = accessToken;
2897
3169
  this.baseUrl = baseUrl.replace(/\/$/, "");
3170
+ this.defaultRequestOptions = mergeRequestOptions(DEFAULT_ZOD_FETCH_OPTIONS, requestOptions);
2898
3171
  }
2899
- async getRunResult(runId) {
3172
+ async getRunResult(runId, requestOptions) {
2900
3173
  try {
2901
3174
  return await zodfetch(TaskRunExecutionResult, `${this.baseUrl}/api/v1/runs/${runId}/result`, {
2902
3175
  method: "GET",
2903
3176
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2904
- }, zodFetchOptions);
3177
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2905
3178
  } catch (error) {
2906
3179
  if (error instanceof ApiError) {
2907
3180
  if (error.status === 404) {
@@ -2911,47 +3184,47 @@ var _ApiClient = class _ApiClient {
2911
3184
  throw error;
2912
3185
  }
2913
3186
  }
2914
- async getBatchResults(batchId) {
3187
+ async getBatchResults(batchId, requestOptions) {
2915
3188
  return await zodfetch(BatchTaskRunExecutionResult, `${this.baseUrl}/api/v1/batches/${batchId}/results`, {
2916
3189
  method: "GET",
2917
3190
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2918
- }, zodFetchOptions);
3191
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2919
3192
  }
2920
- triggerTask(taskId, body, options) {
3193
+ triggerTask(taskId, body, options, requestOptions) {
2921
3194
  const encodedTaskId = encodeURIComponent(taskId);
2922
3195
  return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/trigger`, {
2923
3196
  method: "POST",
2924
3197
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2925
3198
  body: JSON.stringify(body)
2926
- }, zodFetchOptions);
3199
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2927
3200
  }
2928
- batchTriggerTask(taskId, body, options) {
3201
+ batchTriggerTask(taskId, body, options, requestOptions) {
2929
3202
  const encodedTaskId = encodeURIComponent(taskId);
2930
3203
  return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/batch`, {
2931
3204
  method: "POST",
2932
3205
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2933
3206
  body: JSON.stringify(body)
2934
- }, zodFetchOptions);
3207
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2935
3208
  }
2936
- createUploadPayloadUrl(filename) {
3209
+ createUploadPayloadUrl(filename, requestOptions) {
2937
3210
  return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2938
3211
  method: "PUT",
2939
3212
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2940
- }, zodFetchOptions);
3213
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2941
3214
  }
2942
- getPayloadUrl(filename) {
3215
+ getPayloadUrl(filename, requestOptions) {
2943
3216
  return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2944
3217
  method: "GET",
2945
3218
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2946
- }, zodFetchOptions);
3219
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2947
3220
  }
2948
- retrieveRun(runId) {
3221
+ retrieveRun(runId, requestOptions) {
2949
3222
  return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v3/runs/${runId}`, {
2950
3223
  method: "GET",
2951
3224
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2952
- }, zodFetchOptions);
3225
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2953
3226
  }
2954
- listRuns(query) {
3227
+ listRuns(query, requestOptions) {
2955
3228
  const searchParams = createSearchQueryForListRuns(query);
2956
3229
  return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/runs`, {
2957
3230
  query: searchParams,
@@ -2961,9 +3234,9 @@ var _ApiClient = class _ApiClient {
2961
3234
  }, {
2962
3235
  method: "GET",
2963
3236
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2964
- }, zodFetchOptions);
3237
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2965
3238
  }
2966
- listProjectRuns(projectRef, query) {
3239
+ listProjectRuns(projectRef, query, requestOptions) {
2967
3240
  const searchParams = createSearchQueryForListRuns(query);
2968
3241
  if (query?.env) {
2969
3242
  searchParams.append("filter[env]", Array.isArray(query.env) ? query.env.join(",") : query.env);
@@ -2976,35 +3249,35 @@ var _ApiClient = class _ApiClient {
2976
3249
  }, {
2977
3250
  method: "GET",
2978
3251
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2979
- }, zodFetchOptions);
3252
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2980
3253
  }
2981
- replayRun(runId) {
3254
+ replayRun(runId, requestOptions) {
2982
3255
  return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2983
3256
  method: "POST",
2984
3257
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2985
- }, zodFetchOptions);
3258
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2986
3259
  }
2987
- cancelRun(runId) {
3260
+ cancelRun(runId, requestOptions) {
2988
3261
  return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
2989
3262
  method: "POST",
2990
3263
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2991
- }, zodFetchOptions);
3264
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2992
3265
  }
2993
- rescheduleRun(runId, body) {
3266
+ rescheduleRun(runId, body, requestOptions) {
2994
3267
  return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/reschedule`, {
2995
3268
  method: "POST",
2996
3269
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2997
3270
  body: JSON.stringify(body)
2998
- }, zodFetchOptions);
3271
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2999
3272
  }
3000
- createSchedule(options) {
3273
+ createSchedule(options, requestOptions) {
3001
3274
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
3002
3275
  method: "POST",
3003
3276
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3004
3277
  body: JSON.stringify(options)
3005
- });
3278
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3006
3279
  }
3007
- listSchedules(options) {
3280
+ listSchedules(options, requestOptions) {
3008
3281
  const searchParams = new URLSearchParams();
3009
3282
  if (options?.page) {
3010
3283
  searchParams.append("page", options.page.toString());
@@ -3018,77 +3291,77 @@ var _ApiClient = class _ApiClient {
3018
3291
  }, {
3019
3292
  method: "GET",
3020
3293
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3021
- });
3294
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3022
3295
  }
3023
- retrieveSchedule(scheduleId) {
3296
+ retrieveSchedule(scheduleId, requestOptions) {
3024
3297
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
3025
3298
  method: "GET",
3026
3299
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3027
- });
3300
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3028
3301
  }
3029
- updateSchedule(scheduleId, options) {
3302
+ updateSchedule(scheduleId, options, requestOptions) {
3030
3303
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
3031
3304
  method: "PUT",
3032
3305
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3033
3306
  body: JSON.stringify(options)
3034
- });
3307
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3035
3308
  }
3036
- deactivateSchedule(scheduleId) {
3309
+ deactivateSchedule(scheduleId, requestOptions) {
3037
3310
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
3038
3311
  method: "POST",
3039
3312
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3040
- });
3313
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3041
3314
  }
3042
- activateSchedule(scheduleId) {
3315
+ activateSchedule(scheduleId, requestOptions) {
3043
3316
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
3044
3317
  method: "POST",
3045
3318
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3046
- });
3319
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3047
3320
  }
3048
- deleteSchedule(scheduleId) {
3321
+ deleteSchedule(scheduleId, requestOptions) {
3049
3322
  return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
3050
3323
  method: "DELETE",
3051
3324
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3052
- });
3325
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3053
3326
  }
3054
- listEnvVars(projectRef, slug) {
3327
+ listEnvVars(projectRef, slug, requestOptions) {
3055
3328
  return zodfetch(EnvironmentVariables, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
3056
3329
  method: "GET",
3057
3330
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3058
- });
3331
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3059
3332
  }
3060
- importEnvVars(projectRef, slug, body) {
3333
+ importEnvVars(projectRef, slug, body, requestOptions) {
3061
3334
  return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
3062
3335
  method: "POST",
3063
3336
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3064
3337
  body: JSON.stringify(body)
3065
- });
3338
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3066
3339
  }
3067
- retrieveEnvVar(projectRef, slug, key) {
3340
+ retrieveEnvVar(projectRef, slug, key, requestOptions) {
3068
3341
  return zodfetch(EnvironmentVariableValue, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
3069
3342
  method: "GET",
3070
3343
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3071
- });
3344
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3072
3345
  }
3073
- createEnvVar(projectRef, slug, body) {
3346
+ createEnvVar(projectRef, slug, body, requestOptions) {
3074
3347
  return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
3075
3348
  method: "POST",
3076
3349
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3077
3350
  body: JSON.stringify(body)
3078
- });
3351
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3079
3352
  }
3080
- updateEnvVar(projectRef, slug, key, body) {
3353
+ updateEnvVar(projectRef, slug, key, body, requestOptions) {
3081
3354
  return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
3082
3355
  method: "PUT",
3083
3356
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3084
3357
  body: JSON.stringify(body)
3085
- });
3358
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3086
3359
  }
3087
- deleteEnvVar(projectRef, slug, key) {
3360
+ deleteEnvVar(projectRef, slug, key, requestOptions) {
3088
3361
  return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
3089
3362
  method: "DELETE",
3090
3363
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3091
- });
3364
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3092
3365
  }
3093
3366
  };
3094
3367
  _getHeaders = new WeakSet();
@@ -3143,6 +3416,20 @@ function createSearchQueryForListRuns(query) {
3143
3416
  return searchParams;
3144
3417
  }
3145
3418
  __name(createSearchQueryForListRuns, "createSearchQueryForListRuns");
3419
+ function mergeRequestOptions(defaultOptions, options) {
3420
+ if (!options) {
3421
+ return defaultOptions;
3422
+ }
3423
+ return {
3424
+ ...defaultOptions,
3425
+ ...options,
3426
+ retry: {
3427
+ ...defaultOptions.retry,
3428
+ ...options.retry
3429
+ }
3430
+ };
3431
+ }
3432
+ __name(mergeRequestOptions, "mergeRequestOptions");
3146
3433
  var _SimpleClock = class _SimpleClock {
3147
3434
  preciseNow() {
3148
3435
  const now = new PreciseDate();
@@ -3235,128 +3522,6 @@ function calculateAttributeValueLength(value) {
3235
3522
  return 0;
3236
3523
  }
3237
3524
  __name(calculateAttributeValueLength, "calculateAttributeValueLength");
3238
-
3239
- // src/v3/utils/flattenAttributes.ts
3240
- var NULL_SENTINEL = "$@null((";
3241
- function flattenAttributes(obj, prefix) {
3242
- const result = {};
3243
- if (obj === void 0) {
3244
- return result;
3245
- }
3246
- if (obj === null) {
3247
- result[prefix || ""] = NULL_SENTINEL;
3248
- return result;
3249
- }
3250
- if (typeof obj === "string") {
3251
- result[prefix || ""] = obj;
3252
- return result;
3253
- }
3254
- if (typeof obj === "number") {
3255
- result[prefix || ""] = obj;
3256
- return result;
3257
- }
3258
- if (typeof obj === "boolean") {
3259
- result[prefix || ""] = obj;
3260
- return result;
3261
- }
3262
- for (const [key, value] of Object.entries(obj)) {
3263
- const newPrefix = `${prefix ? `${prefix}.` : ""}${Array.isArray(obj) ? `[${key}]` : key}`;
3264
- if (Array.isArray(value)) {
3265
- for (let i = 0; i < value.length; i++) {
3266
- if (typeof value[i] === "object" && value[i] !== null) {
3267
- Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
3268
- } else {
3269
- if (value[i] === null) {
3270
- result[`${newPrefix}.[${i}]`] = NULL_SENTINEL;
3271
- } else {
3272
- result[`${newPrefix}.[${i}]`] = value[i];
3273
- }
3274
- }
3275
- }
3276
- } else if (isRecord(value)) {
3277
- Object.assign(result, flattenAttributes(value, newPrefix));
3278
- } else {
3279
- if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
3280
- result[newPrefix] = value;
3281
- } else if (value === null) {
3282
- result[newPrefix] = NULL_SENTINEL;
3283
- }
3284
- }
3285
- }
3286
- return result;
3287
- }
3288
- __name(flattenAttributes, "flattenAttributes");
3289
- function isRecord(value) {
3290
- return value !== null && typeof value === "object" && !Array.isArray(value);
3291
- }
3292
- __name(isRecord, "isRecord");
3293
- function unflattenAttributes(obj) {
3294
- if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
3295
- return obj;
3296
- }
3297
- if (typeof obj === "object" && obj !== null && Object.keys(obj).length === 1 && Object.keys(obj)[0] === "") {
3298
- return rehydrateNull(obj[""]);
3299
- }
3300
- if (Object.keys(obj).length === 0) {
3301
- return;
3302
- }
3303
- const result = {};
3304
- for (const [key, value] of Object.entries(obj)) {
3305
- const parts = key.split(".").reduce((acc, part) => {
3306
- if (part.includes("[")) {
3307
- const subparts = part.split(/\[|\]/).filter((p) => p !== "");
3308
- acc.push(...subparts);
3309
- } else {
3310
- acc.push(part);
3311
- }
3312
- return acc;
3313
- }, []);
3314
- let current = result;
3315
- for (let i = 0; i < parts.length - 1; i++) {
3316
- const part = parts[i];
3317
- const nextPart = parts[i + 1];
3318
- const isArray = /^\d+$/.test(nextPart);
3319
- if (isArray && !Array.isArray(current[part])) {
3320
- current[part] = [];
3321
- } else if (!isArray && current[part] === void 0) {
3322
- current[part] = {};
3323
- }
3324
- current = current[part];
3325
- }
3326
- const lastPart = parts[parts.length - 1];
3327
- current[lastPart] = rehydrateNull(value);
3328
- }
3329
- if (Object.keys(result).every((k) => /^\d+$/.test(k))) {
3330
- const maxIndex = Math.max(...Object.keys(result).map((k) => parseInt(k)));
3331
- const arrayResult = Array(maxIndex + 1);
3332
- for (const key in result) {
3333
- arrayResult[parseInt(key)] = result[key];
3334
- }
3335
- return arrayResult;
3336
- }
3337
- return result;
3338
- }
3339
- __name(unflattenAttributes, "unflattenAttributes");
3340
- function primitiveValueOrflattenedAttributes(obj, prefix) {
3341
- if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
3342
- return obj;
3343
- }
3344
- const attributes = flattenAttributes(obj, prefix);
3345
- if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
3346
- return attributes[prefix];
3347
- }
3348
- return attributes;
3349
- }
3350
- __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
3351
- function rehydrateNull(value) {
3352
- if (value === NULL_SENTINEL) {
3353
- return null;
3354
- }
3355
- return value;
3356
- }
3357
- __name(rehydrateNull, "rehydrateNull");
3358
-
3359
- // src/v3/logger/taskLogger.ts
3360
3525
  var _NoopTaskLogger = class _NoopTaskLogger {
3361
3526
  debug() {
3362
3527
  }
@@ -3801,14 +3966,16 @@ var _TriggerTracer = class _TriggerTracer {
3801
3966
  attributes,
3802
3967
  startTime: clock.preciseNow()
3803
3968
  }, parentContext, async (span) => {
3804
- this.tracer.startSpan(name, {
3805
- ...options,
3806
- attributes: {
3807
- ...attributes,
3808
- [SemanticInternalAttributes.SPAN_PARTIAL]: true,
3809
- [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
3810
- }
3811
- }, parentContext).end();
3969
+ if (taskContext.ctx) {
3970
+ this.tracer.startSpan(name, {
3971
+ ...options,
3972
+ attributes: {
3973
+ ...attributes,
3974
+ [SemanticInternalAttributes.SPAN_PARTIAL]: true,
3975
+ [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
3976
+ }
3977
+ }, parentContext).end();
3978
+ }
3812
3979
  const usageMeasurement = usage.start();
3813
3980
  try {
3814
3981
  return await fn(span);
@@ -3821,12 +3988,14 @@ var _TriggerTracer = class _TriggerTracer {
3821
3988
  });
3822
3989
  throw e;
3823
3990
  } finally {
3824
- const usageSample = usage.stop(usageMeasurement);
3825
- const machine = taskContext.ctx?.machine;
3826
- span.setAttributes({
3827
- [SemanticInternalAttributes.USAGE_DURATION_MS]: usageSample.cpuTime,
3828
- [SemanticInternalAttributes.USAGE_COST_IN_CENTS]: machine?.centsPerMs ? usageSample.cpuTime * machine.centsPerMs : 0
3829
- });
3991
+ if (taskContext.ctx) {
3992
+ const usageSample = usage.stop(usageMeasurement);
3993
+ const machine = taskContext.ctx.machine;
3994
+ span.setAttributes({
3995
+ [SemanticInternalAttributes.USAGE_DURATION_MS]: usageSample.cpuTime,
3996
+ [SemanticInternalAttributes.USAGE_COST_IN_CENTS]: machine?.centsPerMs ? usageSample.cpuTime * machine.centsPerMs : 0
3997
+ });
3998
+ }
3830
3999
  span.end(clock.preciseNow());
3831
4000
  }
3832
4001
  });
@@ -4018,12 +4187,6 @@ function omit(obj, ...keys) {
4018
4187
  }
4019
4188
  __name(omit, "omit");
4020
4189
 
4021
- // src/v3/utils/styleAttributes.ts
4022
- function accessoryAttributes(accessory) {
4023
- return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
4024
- }
4025
- __name(accessoryAttributes, "accessoryAttributes");
4026
-
4027
4190
  // src/v3/utils/detectDependencyVersion.ts
4028
4191
  function detectDependencyVersion(dependency) {
4029
4192
  return dependencies[dependency];
@@ -4299,6 +4462,6 @@ function safeJsonParse2(value) {
4299
4462
  }
4300
4463
  __name(safeJsonParse2, "safeJsonParse");
4301
4464
 
4302
- export { ApiClient, ApiConnectionError, ApiError, AttemptStatus, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, CoordinatorSocketData, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateEnvironmentVariableRequestBody, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, CursorPage, DeletedScheduleObject, DeploymentErrorData, EnvironmentType, EnvironmentVariable, EnvironmentVariableResponseBody, EnvironmentVariableValue, EnvironmentVariables, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, ImportEnvironmentVariablesRequestBody, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListRunResponse, ListRunResponseItem, ListScheduleOptions, ListSchedulesResult, MachineConfig, MachineCpu, MachineMemory, MachinePreset, MachinePresetName, NULL_SENTINEL, 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, OffsetLimitPage, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RescheduleRunRequestBody, RetrieveRunResponse, RetryOptions, RunEnvironmentDetails, RunScheduleDetails, RunStatus, ScheduleGenerator, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SerializedError, SharedQueueToClientMessages, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskEventStyle, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionLazyAttemptPayload, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunExecutionUsage, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TimezonesResult, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateEnvironmentVariableRequestBody, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createJsonErrorObject, 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, usage, workerToChildMessages };
4465
+ export { AbortTaskRunError, ApiClient, ApiConnectionError, ApiError, AttemptStatus, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, CoordinatorSocketData, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateEnvironmentVariableRequestBody, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, CursorPage, DeletedScheduleObject, DeploymentErrorData, EnvironmentType, EnvironmentVariable, EnvironmentVariableResponseBody, EnvironmentVariableValue, EnvironmentVariables, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, ImportEnvironmentVariablesRequestBody, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListRunResponse, ListRunResponseItem, ListScheduleOptions, ListSchedulesResult, MachineConfig, MachineCpu, MachineMemory, MachinePreset, MachinePresetName, NULL_SENTINEL, 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, OffsetLimitPage, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RescheduleRunRequestBody, RetrieveRunResponse, RetryOptions, RunEnvironmentDetails, RunScheduleDetails, RunStatus, ScheduleGenerator, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SerializedError, SharedQueueToClientMessages, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskEventStyle, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionLazyAttemptPayload, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunExecutionUsage, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TimezonesResult, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateEnvironmentVariableRequestBody, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createJsonErrorObject, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, groupTaskMetadataIssuesByTask, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, isRequestOptions, logger, mergeRequestOptions, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseError, parsePacket, prettyPrintPacket, primitiveValueOrflattenedAttributes, runtime, sanitizeError, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContext, unflattenAttributes, usage, workerToChildMessages };
4303
4466
  //# sourceMappingURL=out.js.map
4304
4467
  //# sourceMappingURL=index.mjs.map