@trigger.dev/core 0.0.0-v3-prerelease-20240703181409 → 0.0.0-v3-prerelease-20240708162325

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 +466 -303
  18. package/dist/v3/index.js.map +1 -1
  19. package/dist/v3/index.mjs +463 -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 +246 -96
  36. package/dist/v3/workers/index.js.map +1 -1
  37. package/dist/v3/workers/index.mjs +246 -96
  38. package/dist/v3/workers/index.mjs.map +1 -1
  39. package/dist/v3/zodfetch.d.mts +14 -2
  40. package/dist/v3/zodfetch.d.ts +14 -2
  41. package/dist/v3/zodfetch.js +244 -28
  42. package/dist/v3/zodfetch.js.map +1 -1
  43. package/dist/v3/zodfetch.mjs +242 -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 = "0.0.0-v3-prerelease-20240703181409";
30
+ var version = "0.0.0-v3-prerelease-20240708162325";
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,43 @@ 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
+ return await _doZodFetchWithRetries(schema, url, $requestInit, options);
2848
+ });
2849
+ }
2850
+ __name(_doZodFetch, "_doZodFetch");
2851
+ async function _doZodFetchWithRetries(schema, url, requestInit, options, attempt = 1) {
2635
2852
  try {
2636
- const $requestInit = await requestInit;
2637
- const response = await fetch(url, requestInitWithCache($requestInit));
2853
+ const response = await fetch(url, requestInitWithCache(requestInit));
2638
2854
  const responseHeaders = createResponseHeaders(response.headers);
2639
2855
  if (!response.ok) {
2640
2856
  const retryResult = shouldRetry(response, attempt, options?.retry);
2641
2857
  if (retryResult.retry) {
2642
- await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
2643
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2858
+ await waitForRetry(url, attempt + 1, retryResult.delay, options, requestInit, response);
2859
+ return await _doZodFetchWithRetries(schema, url, requestInit, options, attempt + 1);
2644
2860
  } else {
2645
2861
  const errText = await response.text().catch((e) => castToError2(e).message);
2646
2862
  const errJSON = safeJsonParse(errText);
@@ -2668,8 +2884,8 @@ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
2668
2884
  };
2669
2885
  const delay = calculateNextRetryDelay(retry, attempt);
2670
2886
  if (delay) {
2671
- await new Promise((resolve) => setTimeout(resolve, delay));
2672
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2887
+ await waitForRetry(url, attempt + 1, delay, options, requestInit);
2888
+ return await _doZodFetchWithRetries(schema, url, requestInit, options, attempt + 1);
2673
2889
  }
2674
2890
  }
2675
2891
  throw new ApiConnectionError({
@@ -2677,7 +2893,7 @@ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
2677
2893
  });
2678
2894
  }
2679
2895
  }
2680
- __name(_doZodFetch, "_doZodFetch");
2896
+ __name(_doZodFetchWithRetries, "_doZodFetchWithRetries");
2681
2897
  function castToError2(err) {
2682
2898
  if (err instanceof Error)
2683
2899
  return err;
@@ -2714,8 +2930,25 @@ function shouldRetry(response, attempt, retryOptions) {
2714
2930
  return shouldRetryForOptions();
2715
2931
  if (response.status === 409)
2716
2932
  return shouldRetryForOptions();
2717
- if (response.status === 429)
2933
+ if (response.status === 429) {
2934
+ if (attempt >= (typeof retryOptions?.maxAttempts === "number" ? retryOptions?.maxAttempts : 3)) {
2935
+ return {
2936
+ retry: false
2937
+ };
2938
+ }
2939
+ const resetAtUnixEpochMs = response.headers.get("x-ratelimit-reset");
2940
+ if (resetAtUnixEpochMs) {
2941
+ const resetAtUnixEpoch = parseInt(resetAtUnixEpochMs, 10);
2942
+ const delay = resetAtUnixEpoch - Date.now() + Math.floor(Math.random() * 1e3);
2943
+ if (delay > 0) {
2944
+ return {
2945
+ retry: true,
2946
+ delay
2947
+ };
2948
+ }
2949
+ }
2718
2950
  return shouldRetryForOptions();
2951
+ }
2719
2952
  if (response.status >= 500)
2720
2953
  return shouldRetryForOptions();
2721
2954
  return {
@@ -2878,9 +3111,44 @@ fetchPage_fn2 = /* @__PURE__ */ __name(function(params1) {
2878
3111
  }, "#fetchPage");
2879
3112
  __name(_OffsetLimitPagePromise, "OffsetLimitPagePromise");
2880
3113
  var OffsetLimitPagePromise = _OffsetLimitPagePromise;
3114
+ async function waitForRetry(url, attempt, delay, options, requestInit, response) {
3115
+ if (options?.tracer) {
3116
+ const method = requestInit?.method ?? "GET";
3117
+ return options.tracer.startActiveSpan(response ? `wait after ${response.status}` : `wait after error`, async (span) => {
3118
+ await new Promise((resolve) => setTimeout(resolve, delay));
3119
+ }, {
3120
+ attributes: {
3121
+ [SemanticInternalAttributes.STYLE_ICON]: "wait",
3122
+ ...accessoryAttributes({
3123
+ items: [
3124
+ {
3125
+ text: `retrying ${options?.name ?? method.toUpperCase()} in ${delay}ms`,
3126
+ variant: "normal"
3127
+ }
3128
+ ],
3129
+ style: "codepath"
3130
+ })
3131
+ }
3132
+ });
3133
+ }
3134
+ await new Promise((resolve) => setTimeout(resolve, delay));
3135
+ }
3136
+ __name(waitForRetry, "waitForRetry");
3137
+ function isEmptyObj(obj) {
3138
+ if (!obj)
3139
+ return true;
3140
+ for (const _k in obj)
3141
+ return false;
3142
+ return true;
3143
+ }
3144
+ __name(isEmptyObj, "isEmptyObj");
3145
+ function hasOwn(obj, key) {
3146
+ return Object.prototype.hasOwnProperty.call(obj, key);
3147
+ }
3148
+ __name(hasOwn, "hasOwn");
2881
3149
 
2882
3150
  // src/v3/apiClient/index.ts
2883
- var zodFetchOptions = {
3151
+ var DEFAULT_ZOD_FETCH_OPTIONS = {
2884
3152
  retry: {
2885
3153
  maxAttempts: 3,
2886
3154
  minTimeoutInMs: 1e3,
@@ -2891,17 +3159,18 @@ var zodFetchOptions = {
2891
3159
  };
2892
3160
  var _getHeaders, getHeaders_fn;
2893
3161
  var _ApiClient = class _ApiClient {
2894
- constructor(baseUrl, accessToken) {
3162
+ constructor(baseUrl, accessToken, requestOptions = {}) {
2895
3163
  __privateAdd(this, _getHeaders);
2896
3164
  this.accessToken = accessToken;
2897
3165
  this.baseUrl = baseUrl.replace(/\/$/, "");
3166
+ this.defaultRequestOptions = mergeRequestOptions(DEFAULT_ZOD_FETCH_OPTIONS, requestOptions);
2898
3167
  }
2899
- async getRunResult(runId) {
3168
+ async getRunResult(runId, requestOptions) {
2900
3169
  try {
2901
3170
  return await zodfetch(TaskRunExecutionResult, `${this.baseUrl}/api/v1/runs/${runId}/result`, {
2902
3171
  method: "GET",
2903
3172
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2904
- }, zodFetchOptions);
3173
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2905
3174
  } catch (error) {
2906
3175
  if (error instanceof ApiError) {
2907
3176
  if (error.status === 404) {
@@ -2911,47 +3180,47 @@ var _ApiClient = class _ApiClient {
2911
3180
  throw error;
2912
3181
  }
2913
3182
  }
2914
- async getBatchResults(batchId) {
3183
+ async getBatchResults(batchId, requestOptions) {
2915
3184
  return await zodfetch(BatchTaskRunExecutionResult, `${this.baseUrl}/api/v1/batches/${batchId}/results`, {
2916
3185
  method: "GET",
2917
3186
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2918
- }, zodFetchOptions);
3187
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2919
3188
  }
2920
- triggerTask(taskId, body, options) {
3189
+ triggerTask(taskId, body, options, requestOptions) {
2921
3190
  const encodedTaskId = encodeURIComponent(taskId);
2922
3191
  return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/trigger`, {
2923
3192
  method: "POST",
2924
3193
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2925
3194
  body: JSON.stringify(body)
2926
- }, zodFetchOptions);
3195
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2927
3196
  }
2928
- batchTriggerTask(taskId, body, options) {
3197
+ batchTriggerTask(taskId, body, options, requestOptions) {
2929
3198
  const encodedTaskId = encodeURIComponent(taskId);
2930
3199
  return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/batch`, {
2931
3200
  method: "POST",
2932
3201
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2933
3202
  body: JSON.stringify(body)
2934
- }, zodFetchOptions);
3203
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2935
3204
  }
2936
- createUploadPayloadUrl(filename) {
3205
+ createUploadPayloadUrl(filename, requestOptions) {
2937
3206
  return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2938
3207
  method: "PUT",
2939
3208
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2940
- }, zodFetchOptions);
3209
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2941
3210
  }
2942
- getPayloadUrl(filename) {
3211
+ getPayloadUrl(filename, requestOptions) {
2943
3212
  return zodfetch(CreateUploadPayloadUrlResponseBody, `${this.baseUrl}/api/v1/packets/${filename}`, {
2944
3213
  method: "GET",
2945
3214
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2946
- }, zodFetchOptions);
3215
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2947
3216
  }
2948
- retrieveRun(runId) {
3217
+ retrieveRun(runId, requestOptions) {
2949
3218
  return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v3/runs/${runId}`, {
2950
3219
  method: "GET",
2951
3220
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2952
- }, zodFetchOptions);
3221
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2953
3222
  }
2954
- listRuns(query) {
3223
+ listRuns(query, requestOptions) {
2955
3224
  const searchParams = createSearchQueryForListRuns(query);
2956
3225
  return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/runs`, {
2957
3226
  query: searchParams,
@@ -2961,9 +3230,9 @@ var _ApiClient = class _ApiClient {
2961
3230
  }, {
2962
3231
  method: "GET",
2963
3232
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2964
- }, zodFetchOptions);
3233
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2965
3234
  }
2966
- listProjectRuns(projectRef, query) {
3235
+ listProjectRuns(projectRef, query, requestOptions) {
2967
3236
  const searchParams = createSearchQueryForListRuns(query);
2968
3237
  if (query?.env) {
2969
3238
  searchParams.append("filter[env]", Array.isArray(query.env) ? query.env.join(",") : query.env);
@@ -2976,35 +3245,35 @@ var _ApiClient = class _ApiClient {
2976
3245
  }, {
2977
3246
  method: "GET",
2978
3247
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2979
- }, zodFetchOptions);
3248
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2980
3249
  }
2981
- replayRun(runId) {
3250
+ replayRun(runId, requestOptions) {
2982
3251
  return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2983
3252
  method: "POST",
2984
3253
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2985
- }, zodFetchOptions);
3254
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2986
3255
  }
2987
- cancelRun(runId) {
3256
+ cancelRun(runId, requestOptions) {
2988
3257
  return zodfetch(CanceledRunResponse, `${this.baseUrl}/api/v2/runs/${runId}/cancel`, {
2989
3258
  method: "POST",
2990
3259
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2991
- }, zodFetchOptions);
3260
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2992
3261
  }
2993
- rescheduleRun(runId, body) {
3262
+ rescheduleRun(runId, body, requestOptions) {
2994
3263
  return zodfetch(RetrieveRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/reschedule`, {
2995
3264
  method: "POST",
2996
3265
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2997
3266
  body: JSON.stringify(body)
2998
- }, zodFetchOptions);
3267
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
2999
3268
  }
3000
- createSchedule(options) {
3269
+ createSchedule(options, requestOptions) {
3001
3270
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
3002
3271
  method: "POST",
3003
3272
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3004
3273
  body: JSON.stringify(options)
3005
- });
3274
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3006
3275
  }
3007
- listSchedules(options) {
3276
+ listSchedules(options, requestOptions) {
3008
3277
  const searchParams = new URLSearchParams();
3009
3278
  if (options?.page) {
3010
3279
  searchParams.append("page", options.page.toString());
@@ -3018,77 +3287,77 @@ var _ApiClient = class _ApiClient {
3018
3287
  }, {
3019
3288
  method: "GET",
3020
3289
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3021
- });
3290
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3022
3291
  }
3023
- retrieveSchedule(scheduleId) {
3292
+ retrieveSchedule(scheduleId, requestOptions) {
3024
3293
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
3025
3294
  method: "GET",
3026
3295
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3027
- });
3296
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3028
3297
  }
3029
- updateSchedule(scheduleId, options) {
3298
+ updateSchedule(scheduleId, options, requestOptions) {
3030
3299
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
3031
3300
  method: "PUT",
3032
3301
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3033
3302
  body: JSON.stringify(options)
3034
- });
3303
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3035
3304
  }
3036
- deactivateSchedule(scheduleId) {
3305
+ deactivateSchedule(scheduleId, requestOptions) {
3037
3306
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
3038
3307
  method: "POST",
3039
3308
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3040
- });
3309
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3041
3310
  }
3042
- activateSchedule(scheduleId) {
3311
+ activateSchedule(scheduleId, requestOptions) {
3043
3312
  return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
3044
3313
  method: "POST",
3045
3314
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3046
- });
3315
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3047
3316
  }
3048
- deleteSchedule(scheduleId) {
3317
+ deleteSchedule(scheduleId, requestOptions) {
3049
3318
  return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
3050
3319
  method: "DELETE",
3051
3320
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3052
- });
3321
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3053
3322
  }
3054
- listEnvVars(projectRef, slug) {
3323
+ listEnvVars(projectRef, slug, requestOptions) {
3055
3324
  return zodfetch(EnvironmentVariables, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
3056
3325
  method: "GET",
3057
3326
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3058
- });
3327
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3059
3328
  }
3060
- importEnvVars(projectRef, slug, body) {
3329
+ importEnvVars(projectRef, slug, body, requestOptions) {
3061
3330
  return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/import`, {
3062
3331
  method: "POST",
3063
3332
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3064
3333
  body: JSON.stringify(body)
3065
- });
3334
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3066
3335
  }
3067
- retrieveEnvVar(projectRef, slug, key) {
3336
+ retrieveEnvVar(projectRef, slug, key, requestOptions) {
3068
3337
  return zodfetch(EnvironmentVariableValue, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
3069
3338
  method: "GET",
3070
3339
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3071
- });
3340
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3072
3341
  }
3073
- createEnvVar(projectRef, slug, body) {
3342
+ createEnvVar(projectRef, slug, body, requestOptions) {
3074
3343
  return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}`, {
3075
3344
  method: "POST",
3076
3345
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3077
3346
  body: JSON.stringify(body)
3078
- });
3347
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3079
3348
  }
3080
- updateEnvVar(projectRef, slug, key, body) {
3349
+ updateEnvVar(projectRef, slug, key, body, requestOptions) {
3081
3350
  return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
3082
3351
  method: "PUT",
3083
3352
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
3084
3353
  body: JSON.stringify(body)
3085
- });
3354
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3086
3355
  }
3087
- deleteEnvVar(projectRef, slug, key) {
3356
+ deleteEnvVar(projectRef, slug, key, requestOptions) {
3088
3357
  return zodfetch(EnvironmentVariableResponseBody, `${this.baseUrl}/api/v1/projects/${projectRef}/envvars/${slug}/${key}`, {
3089
3358
  method: "DELETE",
3090
3359
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3091
- });
3360
+ }, mergeRequestOptions(this.defaultRequestOptions, requestOptions));
3092
3361
  }
3093
3362
  };
3094
3363
  _getHeaders = new WeakSet();
@@ -3143,6 +3412,20 @@ function createSearchQueryForListRuns(query) {
3143
3412
  return searchParams;
3144
3413
  }
3145
3414
  __name(createSearchQueryForListRuns, "createSearchQueryForListRuns");
3415
+ function mergeRequestOptions(defaultOptions, options) {
3416
+ if (!options) {
3417
+ return defaultOptions;
3418
+ }
3419
+ return {
3420
+ ...defaultOptions,
3421
+ ...options,
3422
+ retry: {
3423
+ ...defaultOptions.retry,
3424
+ ...options.retry
3425
+ }
3426
+ };
3427
+ }
3428
+ __name(mergeRequestOptions, "mergeRequestOptions");
3146
3429
  var _SimpleClock = class _SimpleClock {
3147
3430
  preciseNow() {
3148
3431
  const now = new PreciseDate();
@@ -3235,128 +3518,6 @@ function calculateAttributeValueLength(value) {
3235
3518
  return 0;
3236
3519
  }
3237
3520
  __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
3521
  var _NoopTaskLogger = class _NoopTaskLogger {
3361
3522
  debug() {
3362
3523
  }
@@ -3801,14 +3962,16 @@ var _TriggerTracer = class _TriggerTracer {
3801
3962
  attributes,
3802
3963
  startTime: clock.preciseNow()
3803
3964
  }, 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();
3965
+ if (taskContext.ctx) {
3966
+ this.tracer.startSpan(name, {
3967
+ ...options,
3968
+ attributes: {
3969
+ ...attributes,
3970
+ [SemanticInternalAttributes.SPAN_PARTIAL]: true,
3971
+ [SemanticInternalAttributes.SPAN_ID]: span.spanContext().spanId
3972
+ }
3973
+ }, parentContext).end();
3974
+ }
3812
3975
  const usageMeasurement = usage.start();
3813
3976
  try {
3814
3977
  return await fn(span);
@@ -3821,12 +3984,14 @@ var _TriggerTracer = class _TriggerTracer {
3821
3984
  });
3822
3985
  throw e;
3823
3986
  } 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
- });
3987
+ if (taskContext.ctx) {
3988
+ const usageSample = usage.stop(usageMeasurement);
3989
+ const machine = taskContext.ctx.machine;
3990
+ span.setAttributes({
3991
+ [SemanticInternalAttributes.USAGE_DURATION_MS]: usageSample.cpuTime,
3992
+ [SemanticInternalAttributes.USAGE_COST_IN_CENTS]: machine?.centsPerMs ? usageSample.cpuTime * machine.centsPerMs : 0
3993
+ });
3994
+ }
3830
3995
  span.end(clock.preciseNow());
3831
3996
  }
3832
3997
  });
@@ -4018,12 +4183,6 @@ function omit(obj, ...keys) {
4018
4183
  }
4019
4184
  __name(omit, "omit");
4020
4185
 
4021
- // src/v3/utils/styleAttributes.ts
4022
- function accessoryAttributes(accessory) {
4023
- return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
4024
- }
4025
- __name(accessoryAttributes, "accessoryAttributes");
4026
-
4027
4186
  // src/v3/utils/detectDependencyVersion.ts
4028
4187
  function detectDependencyVersion(dependency) {
4029
4188
  return dependencies[dependency];
@@ -4299,6 +4458,6 @@ function safeJsonParse2(value) {
4299
4458
  }
4300
4459
  __name(safeJsonParse2, "safeJsonParse");
4301
4460
 
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 };
4461
+ 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
4462
  //# sourceMappingURL=out.js.map
4304
4463
  //# sourceMappingURL=index.mjs.map