@trigger.dev/core 3.0.0-beta.12 → 3.0.0-beta.14

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.
package/dist/v3/index.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { SpanStatusCode, trace, propagation, context, DiagLogLevel, diag, DiagConsoleLogger, SpanKind } from '@opentelemetry/api';
3
+ import { fromZodError } from 'zod-validation-error';
3
4
  import { AsyncLocalStorage } from 'node:async_hooks';
4
5
  import { io } from 'socket.io-client';
5
6
  import { randomUUID } from 'crypto';
@@ -83,6 +84,7 @@ var TaskRunStringError = z.object({
83
84
  });
84
85
  var TaskRunErrorCodes = {
85
86
  COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
87
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
86
88
  CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
87
89
  TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
88
90
  TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
@@ -90,12 +92,14 @@ var TaskRunErrorCodes = {
90
92
  TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
91
93
  TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
92
94
  TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
93
- HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR"
95
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
96
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
94
97
  };
95
98
  var TaskRunInternalError = z.object({
96
99
  type: z.literal("INTERNAL_ERROR"),
97
100
  code: z.enum([
98
101
  "COULD_NOT_FIND_EXECUTOR",
102
+ "COULD_NOT_FIND_TASK",
99
103
  "CONFIGURED_INCORRECTLY",
100
104
  "TASK_ALREADY_RUNNING",
101
105
  "TASK_EXECUTION_FAILED",
@@ -103,7 +107,8 @@ var TaskRunInternalError = z.object({
103
107
  "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
104
108
  "TASK_RUN_CANCELLED",
105
109
  "TASK_OUTPUT_ERROR",
106
- "HANDLE_ERROR_ERROR"
110
+ "HANDLE_ERROR_ERROR",
111
+ "GRACEFUL_EXIT_TIMEOUT"
107
112
  ]),
108
113
  message: z.string().optional()
109
114
  });
@@ -440,15 +445,17 @@ var QueueOptions = z.object({
440
445
  });
441
446
  var TaskMetadata = z.object({
442
447
  id: z.string(),
443
- exportName: z.string(),
444
448
  packageVersion: z.string(),
445
449
  queue: QueueOptions.optional(),
446
450
  retry: RetryOptions.optional(),
447
- machine: Machine.partial().optional()
451
+ machine: Machine.partial().optional(),
452
+ triggerSource: z.string().optional()
448
453
  });
449
- var TaskMetadataWithFilePath = TaskMetadata.extend({
450
- filePath: z.string()
454
+ var TaskFileMetadata = z.object({
455
+ filePath: z.string(),
456
+ exportName: z.string()
451
457
  });
458
+ var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
452
459
  var UncaughtExceptionMessage = z.object({
453
460
  version: z.literal("v1").default("v1"),
454
461
  error: z.object({
@@ -600,7 +607,8 @@ var TaskResource = z.object({
600
607
  exportName: z.string(),
601
608
  queue: QueueOptions.optional(),
602
609
  retry: RetryOptions.optional(),
603
- machine: Machine.partial().optional()
610
+ machine: Machine.partial().optional(),
611
+ triggerSource: z.string().optional()
604
612
  });
605
613
  var BackgroundWorkerMetadata = z.object({
606
614
  packageVersion: z.string(),
@@ -656,7 +664,9 @@ var TriggerTaskRequestBody = z.object({
656
664
  lockToVersion: z.string().optional(),
657
665
  queue: QueueOptions.optional(),
658
666
  concurrencyKey: z.string().optional(),
659
- test: z.boolean().optional()
667
+ idempotencyKey: z.string().optional(),
668
+ test: z.boolean().optional(),
669
+ payloadType: z.string().optional()
660
670
  }).optional()
661
671
  });
662
672
  var TriggerTaskResponse = z.object({
@@ -752,6 +762,87 @@ var ReplayRunResponse = z.object({
752
762
  var CanceledRunResponse = z.object({
753
763
  message: z.string()
754
764
  });
765
+ var ScheduledTaskPayload = z.object({
766
+ /** The schedule id associated with this run (you can have many schedules for the same task).
767
+ You can use this to remove the schedule, update it, etc */
768
+ scheduleId: z.string(),
769
+ /** When the task was scheduled to run.
770
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
771
+ timestamp: z.date(),
772
+ /** When the task was last run (it has been).
773
+ This can be undefined if it's never been run */
774
+ lastTimestamp: z.date().optional(),
775
+ /** You can optionally provide an external id when creating the schedule.
776
+ Usually you would use a userId or some other unique identifier.
777
+ This defaults to undefined if you didn't provide one. */
778
+ externalId: z.string().optional(),
779
+ /** The next 5 dates this task is scheduled to run */
780
+ upcoming: z.array(z.date())
781
+ });
782
+ var CreateScheduleOptions = z.object({
783
+ /** The id of the task you want to attach to. */
784
+ task: z.string(),
785
+ /** The schedule in CRON format.
786
+ *
787
+ * ```txt
788
+ * * * * * *
789
+ ┬ ┬ ┬ ┬ ┬
790
+ │ │ │ │ |
791
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
792
+ │ │ │ └───── month (1 - 12)
793
+ │ │ └────────── day of month (1 - 31, L)
794
+ │ └─────────────── hour (0 - 23)
795
+ └──────────────────── minute (0 - 59)
796
+ * ```
797
+
798
+ "L" means the last. In the "day of week" field, 1L means the last Monday of the month. In the day of month field, L means the last day of the month.
799
+
800
+ */
801
+ cron: z.string(),
802
+ /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
803
+ *
804
+ * This is useful if you don't want to create duplicate schedules for a user. */
805
+ deduplicationKey: z.string().optional(),
806
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
807
+ *
808
+ * This allows you to have per-user CRON tasks.
809
+ */
810
+ externalId: z.string().optional()
811
+ });
812
+ var UpdateScheduleOptions = CreateScheduleOptions;
813
+ var ScheduleObject = z.object({
814
+ id: z.string(),
815
+ task: z.string(),
816
+ active: z.boolean(),
817
+ deduplicationKey: z.string().nullish(),
818
+ externalId: z.string().nullish(),
819
+ generator: z.object({
820
+ type: z.literal("CRON"),
821
+ expression: z.string(),
822
+ description: z.string()
823
+ }),
824
+ nextRun: z.coerce.date().nullish(),
825
+ environments: z.array(z.object({
826
+ id: z.string(),
827
+ type: z.string(),
828
+ userName: z.string().nullish()
829
+ }))
830
+ });
831
+ var DeletedScheduleObject = z.object({
832
+ id: z.string()
833
+ });
834
+ var ListSchedulesResult = z.object({
835
+ data: z.array(ScheduleObject),
836
+ pagination: z.object({
837
+ currentPage: z.number(),
838
+ totalPages: z.number(),
839
+ count: z.number()
840
+ })
841
+ });
842
+ var ListScheduleOptions = z.object({
843
+ page: z.number().optional(),
844
+ perPage: z.number().optional()
845
+ });
755
846
  var PostStartCauses = z.enum([
756
847
  "index",
757
848
  "create",
@@ -783,7 +874,8 @@ var Config = z.object({
783
874
  z.string(),
784
875
  RegexSchema
785
876
  ])).optional(),
786
- logLevel: z.string().optional()
877
+ logLevel: z.string().optional(),
878
+ enableConsoleLogging: z.boolean().optional()
787
879
  });
788
880
  var WaitReason = z.enum([
789
881
  "WAIT_FOR_DURATION",
@@ -1439,101 +1531,384 @@ var SpanMessagingEvent = z.object({
1439
1531
  destination: z.string().optional()
1440
1532
  });
1441
1533
 
1442
- // src/zodfetch.ts
1534
+ // src/v3/apiErrors.ts
1535
+ var _APIError = class _APIError extends Error {
1536
+ constructor(status, error, message, headers) {
1537
+ super(`${_APIError.makeMessage(status, error, message)}`);
1538
+ this.status = status;
1539
+ this.headers = headers;
1540
+ const data = error;
1541
+ this.error = data;
1542
+ this.code = data?.["code"];
1543
+ this.param = data?.["param"];
1544
+ this.type = data?.["type"];
1545
+ }
1546
+ static makeMessage(status, error, message) {
1547
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1548
+ if (status && msg) {
1549
+ return `${status} ${msg}`;
1550
+ }
1551
+ if (status) {
1552
+ return `${status} status code (no body)`;
1553
+ }
1554
+ if (msg) {
1555
+ return msg;
1556
+ }
1557
+ return "(no status code or body)";
1558
+ }
1559
+ static generate(status, errorResponse, message, headers) {
1560
+ if (!status) {
1561
+ return new APIConnectionError({
1562
+ cause: castToError(errorResponse)
1563
+ });
1564
+ }
1565
+ const error = errorResponse?.["error"];
1566
+ if (status === 400) {
1567
+ return new BadRequestError(status, error, message, headers);
1568
+ }
1569
+ if (status === 401) {
1570
+ return new AuthenticationError(status, error, message, headers);
1571
+ }
1572
+ if (status === 403) {
1573
+ return new PermissionDeniedError(status, error, message, headers);
1574
+ }
1575
+ if (status === 404) {
1576
+ return new NotFoundError(status, error, message, headers);
1577
+ }
1578
+ if (status === 409) {
1579
+ return new ConflictError(status, error, message, headers);
1580
+ }
1581
+ if (status === 422) {
1582
+ return new UnprocessableEntityError(status, error, message, headers);
1583
+ }
1584
+ if (status === 429) {
1585
+ return new RateLimitError(status, error, message, headers);
1586
+ }
1587
+ if (status >= 500) {
1588
+ return new InternalServerError(status, error, message, headers);
1589
+ }
1590
+ return new _APIError(status, error, message, headers);
1591
+ }
1592
+ };
1593
+ __name(_APIError, "APIError");
1594
+ var APIError = _APIError;
1595
+ var _APIConnectionError = class _APIConnectionError extends APIError {
1596
+ constructor({ message, cause }) {
1597
+ super(void 0, void 0, message || "Connection error.", void 0);
1598
+ __publicField(this, "status");
1599
+ if (cause)
1600
+ this.cause = cause;
1601
+ }
1602
+ };
1603
+ __name(_APIConnectionError, "APIConnectionError");
1604
+ var APIConnectionError = _APIConnectionError;
1605
+ var _BadRequestError = class _BadRequestError extends APIError {
1606
+ constructor() {
1607
+ super(...arguments);
1608
+ __publicField(this, "status", 400);
1609
+ }
1610
+ };
1611
+ __name(_BadRequestError, "BadRequestError");
1612
+ var BadRequestError = _BadRequestError;
1613
+ var _AuthenticationError = class _AuthenticationError extends APIError {
1614
+ constructor() {
1615
+ super(...arguments);
1616
+ __publicField(this, "status", 401);
1617
+ }
1618
+ };
1619
+ __name(_AuthenticationError, "AuthenticationError");
1620
+ var AuthenticationError = _AuthenticationError;
1621
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
1622
+ constructor() {
1623
+ super(...arguments);
1624
+ __publicField(this, "status", 403);
1625
+ }
1626
+ };
1627
+ __name(_PermissionDeniedError, "PermissionDeniedError");
1628
+ var PermissionDeniedError = _PermissionDeniedError;
1629
+ var _NotFoundError = class _NotFoundError extends APIError {
1630
+ constructor() {
1631
+ super(...arguments);
1632
+ __publicField(this, "status", 404);
1633
+ }
1634
+ };
1635
+ __name(_NotFoundError, "NotFoundError");
1636
+ var NotFoundError = _NotFoundError;
1637
+ var _ConflictError = class _ConflictError extends APIError {
1638
+ constructor() {
1639
+ super(...arguments);
1640
+ __publicField(this, "status", 409);
1641
+ }
1642
+ };
1643
+ __name(_ConflictError, "ConflictError");
1644
+ var ConflictError = _ConflictError;
1645
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
1646
+ constructor() {
1647
+ super(...arguments);
1648
+ __publicField(this, "status", 422);
1649
+ }
1650
+ };
1651
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
1652
+ var UnprocessableEntityError = _UnprocessableEntityError;
1653
+ var _RateLimitError = class _RateLimitError extends APIError {
1654
+ constructor() {
1655
+ super(...arguments);
1656
+ __publicField(this, "status", 429);
1657
+ }
1658
+ };
1659
+ __name(_RateLimitError, "RateLimitError");
1660
+ var RateLimitError = _RateLimitError;
1661
+ var _InternalServerError = class _InternalServerError extends APIError {
1662
+ };
1663
+ __name(_InternalServerError, "InternalServerError");
1664
+ var InternalServerError = _InternalServerError;
1665
+ function castToError(err) {
1666
+ if (err instanceof Error)
1667
+ return err;
1668
+ return new Error(err);
1669
+ }
1670
+ __name(castToError, "castToError");
1671
+
1672
+ // src/retry.ts
1673
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
1674
+ if (!resets)
1675
+ return;
1676
+ switch (format) {
1677
+ case "iso_8601_duration_openai_variant": {
1678
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
1679
+ }
1680
+ case "iso_8601": {
1681
+ return calculateISO8601ResetAt(resets, now);
1682
+ }
1683
+ case "unix_timestamp": {
1684
+ return calculateUnixTimestampResetAt(resets, now);
1685
+ }
1686
+ case "unix_timestamp_in_ms": {
1687
+ return calculateUnixTimestampInMsResetAt(resets, now);
1688
+ }
1689
+ }
1690
+ }
1691
+ __name(calculateResetAt, "calculateResetAt");
1692
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
1693
+ if (!resets)
1694
+ return void 0;
1695
+ const resetAt = parseInt(resets, 10);
1696
+ if (isNaN(resetAt))
1697
+ return void 0;
1698
+ return new Date(resetAt * 1e3);
1699
+ }
1700
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
1701
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
1702
+ if (!resets)
1703
+ return void 0;
1704
+ const resetAt = parseInt(resets, 10);
1705
+ if (isNaN(resetAt))
1706
+ return void 0;
1707
+ return new Date(resetAt);
1708
+ }
1709
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
1710
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
1711
+ if (!resets)
1712
+ return void 0;
1713
+ const resetAt = new Date(resets);
1714
+ if (isNaN(resetAt.getTime()))
1715
+ return void 0;
1716
+ return resetAt;
1717
+ }
1718
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
1719
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
1720
+ if (!resets)
1721
+ return void 0;
1722
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
1723
+ const match = resets.match(pattern);
1724
+ if (!match)
1725
+ return void 0;
1726
+ const days = parseInt(match[1], 10) || 0;
1727
+ const hours = parseInt(match[2], 10) || 0;
1728
+ const minutes = parseInt(match[3], 10) || 0;
1729
+ const seconds = parseFloat(match[4]) || 0;
1730
+ const milliseconds = parseInt(match[5], 10) || 0;
1731
+ const resetAt = new Date(now);
1732
+ resetAt.setDate(resetAt.getDate() + days);
1733
+ resetAt.setHours(resetAt.getHours() + hours);
1734
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
1735
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
1736
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
1737
+ return resetAt;
1738
+ }
1739
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
1740
+
1741
+ // src/v3/utils/retries.ts
1742
+ var defaultRetryOptions = {
1743
+ maxAttempts: 3,
1744
+ factor: 2,
1745
+ minTimeoutInMs: 1e3,
1746
+ maxTimeoutInMs: 6e4,
1747
+ randomize: true
1748
+ };
1749
+ var defaultFetchRetryOptions = {
1750
+ byStatus: {
1751
+ "429,408,409,5xx": {
1752
+ strategy: "backoff",
1753
+ ...defaultRetryOptions
1754
+ }
1755
+ },
1756
+ connectionError: defaultRetryOptions,
1757
+ timeout: defaultRetryOptions
1758
+ };
1759
+ function calculateNextRetryDelay(options, attempt) {
1760
+ const opts = {
1761
+ ...defaultRetryOptions,
1762
+ ...options
1763
+ };
1764
+ if (attempt >= opts.maxAttempts) {
1765
+ return;
1766
+ }
1767
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1768
+ const random = randomize ? Math.random() + 1 : 1;
1769
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1770
+ return Math.round(timeout);
1771
+ }
1772
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1773
+ function calculateResetAt2(resets, format, now = Date.now()) {
1774
+ const resetAt = calculateResetAt(resets, format, new Date(now));
1775
+ return resetAt?.getTime();
1776
+ }
1777
+ __name(calculateResetAt2, "calculateResetAt");
1778
+
1779
+ // src/v3/zodfetch.ts
1780
+ var defaultRetryOptions2 = {
1781
+ maxAttempts: 3,
1782
+ factor: 2,
1783
+ minTimeoutInMs: 1e3,
1784
+ maxTimeoutInMs: 6e4,
1785
+ randomize: false
1786
+ };
1443
1787
  async function zodfetch(schema, url, requestInit, options) {
1444
1788
  return await _doZodFetch(schema, url, requestInit, options);
1445
1789
  }
1446
1790
  __name(zodfetch, "zodfetch");
1447
1791
  async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1448
1792
  try {
1449
- const response = await fetch(url, requestInit);
1450
- if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
1451
- return {
1452
- ok: false,
1453
- error: `404: ${response.statusText}`
1454
- };
1455
- }
1456
- if (response.status >= 400 && response.status < 500 && response.status !== 429) {
1457
- const body = await response.json();
1458
- if (!body.error) {
1459
- return {
1460
- ok: false,
1461
- error: "Something went wrong"
1462
- };
1793
+ const response = await fetch(url, requestInitWithCache(requestInit));
1794
+ const responseHeaders = createResponseHeaders(response.headers);
1795
+ if (!response.ok) {
1796
+ const retryResult = shouldRetry(response, attempt, options?.retry);
1797
+ if (retryResult.retry) {
1798
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
1799
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1800
+ } else {
1801
+ const errText = await response.text().catch((e) => castToError2(e).message);
1802
+ const errJSON = safeJsonParse(errText);
1803
+ const errMessage = errJSON ? void 0 : errText;
1804
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
1463
1805
  }
1464
- return {
1465
- ok: false,
1466
- error: body.error
1467
- };
1468
1806
  }
1469
- if (response.status === 429 || response.status >= 500) {
1470
- if (!options?.retry) {
1471
- return {
1472
- ok: false,
1473
- error: `Failed to fetch ${url}, got status code ${response.status}`
1474
- };
1475
- }
1807
+ const jsonBody = await response.json();
1808
+ const parsedResult = schema.safeParse(jsonBody);
1809
+ if (parsedResult.success) {
1810
+ return parsedResult.data;
1811
+ }
1812
+ throw fromZodError(parsedResult.error);
1813
+ } catch (error) {
1814
+ if (error instanceof APIError) {
1815
+ throw error;
1816
+ }
1817
+ if (options?.retry) {
1476
1818
  const retry = {
1477
- ...defaultRetryOptions,
1819
+ ...defaultRetryOptions2,
1478
1820
  ...options.retry
1479
1821
  };
1480
- if (attempt > retry.maxAttempts) {
1481
- return {
1482
- ok: false,
1483
- error: `Failed to fetch ${url}, got status code ${response.status}`
1484
- };
1485
- }
1486
1822
  const delay = calculateNextRetryDelay(retry, attempt);
1487
- await new Promise((resolve) => setTimeout(resolve, delay));
1488
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1489
- }
1490
- if (response.status !== 200) {
1491
- return {
1492
- ok: false,
1493
- error: `Failed to fetch ${url}, got status code ${response.status}`
1494
- };
1823
+ if (delay) {
1824
+ await new Promise((resolve) => setTimeout(resolve, delay));
1825
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1826
+ }
1495
1827
  }
1496
- const jsonBody = await response.json();
1497
- const parsedResult = schema.safeParse(jsonBody);
1498
- if (parsedResult.success) {
1828
+ throw new APIConnectionError({
1829
+ cause: castToError2(error)
1830
+ });
1831
+ }
1832
+ }
1833
+ __name(_doZodFetch, "_doZodFetch");
1834
+ function castToError2(err) {
1835
+ if (err instanceof Error)
1836
+ return err;
1837
+ return new Error(err);
1838
+ }
1839
+ __name(castToError2, "castToError");
1840
+ function shouldRetry(response, attempt, retryOptions) {
1841
+ function shouldRetryForOptions() {
1842
+ const retry = {
1843
+ ...defaultRetryOptions2,
1844
+ ...retryOptions
1845
+ };
1846
+ const delay = calculateNextRetryDelay(retry, attempt);
1847
+ if (delay) {
1499
1848
  return {
1500
- ok: true,
1501
- data: parsedResult.data
1849
+ retry: true,
1850
+ delay
1502
1851
  };
1503
- }
1504
- if ("error" in jsonBody) {
1852
+ } else {
1505
1853
  return {
1506
- ok: false,
1507
- error: typeof jsonBody.error === "string" ? jsonBody.error : JSON.stringify(jsonBody.error)
1854
+ retry: false
1508
1855
  };
1509
1856
  }
1857
+ }
1858
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
1859
+ const shouldRetryHeader = response.headers.get("x-should-retry");
1860
+ if (shouldRetryHeader === "true")
1861
+ return shouldRetryForOptions();
1862
+ if (shouldRetryHeader === "false")
1510
1863
  return {
1511
- ok: false,
1512
- error: parsedResult.error.message
1864
+ retry: false
1513
1865
  };
1514
- } catch (error) {
1515
- if (options?.retry) {
1516
- const retry = {
1517
- ...defaultRetryOptions,
1518
- ...options.retry
1519
- };
1520
- if (attempt > retry.maxAttempts) {
1521
- return {
1522
- ok: false,
1523
- error: error instanceof Error ? error.message : JSON.stringify(error)
1524
- };
1525
- }
1526
- const delay = calculateNextRetryDelay(retry, attempt);
1527
- await new Promise((resolve) => setTimeout(resolve, delay));
1528
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1866
+ if (response.status === 408)
1867
+ return shouldRetryForOptions();
1868
+ if (response.status === 409)
1869
+ return shouldRetryForOptions();
1870
+ if (response.status === 429)
1871
+ return shouldRetryForOptions();
1872
+ if (response.status >= 500)
1873
+ return shouldRetryForOptions();
1874
+ return {
1875
+ retry: false
1876
+ };
1877
+ }
1878
+ __name(shouldRetry, "shouldRetry");
1879
+ function safeJsonParse(text) {
1880
+ try {
1881
+ return JSON.parse(text);
1882
+ } catch (e) {
1883
+ return void 0;
1884
+ }
1885
+ }
1886
+ __name(safeJsonParse, "safeJsonParse");
1887
+ function createResponseHeaders(headers) {
1888
+ return new Proxy(Object.fromEntries(
1889
+ // @ts-ignore
1890
+ headers.entries()
1891
+ ), {
1892
+ get(target, name) {
1893
+ const key = name.toString();
1894
+ return target[key.toLowerCase()] || target[key];
1529
1895
  }
1530
- return {
1531
- ok: false,
1532
- error: error instanceof Error ? error.message : JSON.stringify(error)
1896
+ });
1897
+ }
1898
+ __name(createResponseHeaders, "createResponseHeaders");
1899
+ function requestInitWithCache(requestInit) {
1900
+ try {
1901
+ const withCache = {
1902
+ ...requestInit,
1903
+ cache: "no-cache"
1533
1904
  };
1905
+ const _ = new Request("http://localhost", withCache);
1906
+ return withCache;
1907
+ } catch (error) {
1908
+ return requestInit ?? {};
1534
1909
  }
1535
1910
  }
1536
- __name(_doZodFetch, "_doZodFetch");
1911
+ __name(requestInitWithCache, "requestInitWithCache");
1537
1912
 
1538
1913
  // src/v3/utils/flattenAttributes.ts
1539
1914
  function flattenAttributes(obj, prefix) {
@@ -1685,7 +2060,8 @@ var SemanticInternalAttributes = {
1685
2060
  SDK_LANGUAGE: "sdk.language",
1686
2061
  RETRY_AT: "retry.at",
1687
2062
  RETRY_DELAY: "retry.delay",
1688
- RETRY_COUNT: "retry.count"
2063
+ RETRY_COUNT: "retry.count",
2064
+ LINK_TITLE: "$link.title"
1689
2065
  };
1690
2066
 
1691
2067
  // src/v3/tasks/taskContextManager.ts
@@ -1821,7 +2197,7 @@ __name(getEnvVar, "getEnvVar");
1821
2197
  // src/v3/apiClient/index.ts
1822
2198
  var zodFetchOptions = {
1823
2199
  retry: {
1824
- maxAttempts: 5,
2200
+ maxAttempts: 3,
1825
2201
  minTimeoutInMs: 1e3,
1826
2202
  maxTimeoutInMs: 3e4,
1827
2203
  factor: 2,
@@ -1873,6 +2249,57 @@ var _ApiClient = class _ApiClient {
1873
2249
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
1874
2250
  }, zodFetchOptions);
1875
2251
  }
2252
+ createSchedule(options) {
2253
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
2254
+ method: "POST",
2255
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2256
+ body: JSON.stringify(options)
2257
+ });
2258
+ }
2259
+ listSchedules(options) {
2260
+ const searchParams = new URLSearchParams();
2261
+ if (options?.page) {
2262
+ searchParams.append("page", options.page.toString());
2263
+ }
2264
+ if (options?.perPage) {
2265
+ searchParams.append("perPage", options.perPage.toString());
2266
+ }
2267
+ return zodfetch(ListSchedulesResult, `${this.baseUrl}/api/v1/schedules${searchParams.size > 0 ? `?${searchParams}` : ""}`, {
2268
+ method: "GET",
2269
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2270
+ });
2271
+ }
2272
+ retrieveSchedule(scheduleId) {
2273
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2274
+ method: "GET",
2275
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2276
+ });
2277
+ }
2278
+ updateSchedule(scheduleId, options) {
2279
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2280
+ method: "PUT",
2281
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false),
2282
+ body: JSON.stringify(options)
2283
+ });
2284
+ }
2285
+ deactivateSchedule(scheduleId) {
2286
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/deactivate`, {
2287
+ method: "POST",
2288
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2289
+ });
2290
+ }
2291
+ activateSchedule(scheduleId) {
2292
+ return zodfetch(ScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}/activate`, {
2293
+ method: "POST",
2294
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2295
+ });
2296
+ }
2297
+ deleteSchedule(scheduleId) {
2298
+ return zodfetch(DeletedScheduleObject, `${this.baseUrl}/api/v1/schedules/${scheduleId}`, {
2299
+ method: "DELETE",
2300
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2301
+ });
2302
+ }
1876
2303
  };
1877
2304
  _getHeaders = new WeakSet();
1878
2305
  getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
@@ -2786,11 +3213,6 @@ __name(unregisterGlobal, "unregisterGlobal");
2786
3213
  var _NoopRuntimeManager = class _NoopRuntimeManager {
2787
3214
  disable() {
2788
3215
  }
2789
- registerTasks() {
2790
- }
2791
- getTaskMetadata(id) {
2792
- return void 0;
2793
- }
2794
3216
  waitForDuration(ms) {
2795
3217
  return Promise.resolve();
2796
3218
  }
@@ -2850,12 +3272,6 @@ var _RuntimeAPI = class _RuntimeAPI {
2850
3272
  __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2851
3273
  unregisterGlobal(API_NAME);
2852
3274
  }
2853
- registerTasks(tasks) {
2854
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).registerTasks(tasks);
2855
- }
2856
- getTaskMetadata(id) {
2857
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).getTaskMetadata(id);
2858
- }
2859
3275
  };
2860
3276
  _getRuntimeManager = new WeakSet();
2861
3277
  getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
@@ -3001,7 +3417,7 @@ var _OtelTaskLogger = class _OtelTaskLogger {
3001
3417
  _emitLog = new WeakSet();
3002
3418
  emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
3003
3419
  let attributes = {
3004
- ...flattenAttributes(properties)
3420
+ ...flattenAttributes(safeJsonProcess(properties))
3005
3421
  };
3006
3422
  const icon = iconStringForSeverity(severityNumber);
3007
3423
  if (icon !== void 0) {
@@ -3038,6 +3454,14 @@ var _NoopTaskLogger = class _NoopTaskLogger {
3038
3454
  };
3039
3455
  __name(_NoopTaskLogger, "NoopTaskLogger");
3040
3456
  var NoopTaskLogger = _NoopTaskLogger;
3457
+ function safeJsonProcess(value) {
3458
+ try {
3459
+ return JSON.parse(JSON.stringify(value));
3460
+ } catch {
3461
+ return value;
3462
+ }
3463
+ }
3464
+ __name(safeJsonProcess, "safeJsonProcess");
3041
3465
 
3042
3466
  // src/v3/logger/index.ts
3043
3467
  var API_NAME3 = "logger";
@@ -3088,6 +3512,78 @@ var LoggerAPI = _LoggerAPI;
3088
3512
  // src/v3/logger-api.ts
3089
3513
  var logger = LoggerAPI.getInstance();
3090
3514
 
3515
+ // src/v3/task-catalog/noopTaskCatalog.ts
3516
+ var _NoopTaskCatalog = class _NoopTaskCatalog {
3517
+ registerTaskMetadata(task) {
3518
+ }
3519
+ registerTaskFileMetadata(id, metadata) {
3520
+ }
3521
+ updateTaskMetadata(id, updates) {
3522
+ }
3523
+ getAllTaskMetadata() {
3524
+ return [];
3525
+ }
3526
+ getTaskMetadata(id) {
3527
+ return void 0;
3528
+ }
3529
+ getTask(id) {
3530
+ return void 0;
3531
+ }
3532
+ disable() {
3533
+ }
3534
+ };
3535
+ __name(_NoopTaskCatalog, "NoopTaskCatalog");
3536
+ var NoopTaskCatalog = _NoopTaskCatalog;
3537
+
3538
+ // src/v3/task-catalog/index.ts
3539
+ var API_NAME4 = "task-catalog";
3540
+ var NOOP_TASK_CATALOG = new NoopTaskCatalog();
3541
+ var _getCatalog, getCatalog_fn;
3542
+ var _TaskCatalogAPI = class _TaskCatalogAPI {
3543
+ constructor() {
3544
+ __privateAdd(this, _getCatalog);
3545
+ }
3546
+ static getInstance() {
3547
+ if (!this._instance) {
3548
+ this._instance = new _TaskCatalogAPI();
3549
+ }
3550
+ return this._instance;
3551
+ }
3552
+ setGlobalTaskCatalog(taskCatalog2) {
3553
+ return registerGlobal(API_NAME4, taskCatalog2);
3554
+ }
3555
+ disable() {
3556
+ unregisterGlobal(API_NAME4);
3557
+ }
3558
+ registerTaskMetadata(task) {
3559
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskMetadata(task);
3560
+ }
3561
+ updateTaskMetadata(id, updates) {
3562
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).updateTaskMetadata(id, updates);
3563
+ }
3564
+ registerTaskFileMetadata(id, metadata) {
3565
+ __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskFileMetadata(id, metadata);
3566
+ }
3567
+ getAllTaskMetadata() {
3568
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getAllTaskMetadata();
3569
+ }
3570
+ getTaskMetadata(id) {
3571
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTaskMetadata(id);
3572
+ }
3573
+ getTask(id) {
3574
+ return __privateMethod(this, _getCatalog, getCatalog_fn).call(this).getTask(id);
3575
+ }
3576
+ };
3577
+ _getCatalog = new WeakSet();
3578
+ getCatalog_fn = /* @__PURE__ */ __name(function() {
3579
+ return getGlobal(API_NAME4) ?? NOOP_TASK_CATALOG;
3580
+ }, "#getCatalog");
3581
+ __name(_TaskCatalogAPI, "TaskCatalogAPI");
3582
+ var TaskCatalogAPI = _TaskCatalogAPI;
3583
+
3584
+ // src/v3/task-catalog-api.ts
3585
+ var taskCatalog = TaskCatalogAPI.getInstance();
3586
+
3091
3587
  // src/v3/limits.ts
3092
3588
  var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
3093
3589
  var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
@@ -3205,34 +3701,32 @@ function formatDurationInDays(milliseconds) {
3205
3701
  return duration;
3206
3702
  }
3207
3703
  __name(formatDurationInDays, "formatDurationInDays");
3704
+ async function unboundedTimeout(delay = 0, value, options) {
3705
+ const maxDelay = 2147483647;
3706
+ const fullTimeouts = Math.floor(delay / maxDelay);
3707
+ const remainingDelay = delay % maxDelay;
3708
+ let lastTimeoutResult = await setTimeout$1(remainingDelay, value, options);
3709
+ for (let i = 0; i < fullTimeouts; i++) {
3710
+ lastTimeoutResult = await setTimeout$1(maxDelay, value, options);
3711
+ }
3712
+ return lastTimeoutResult;
3713
+ }
3714
+ __name(unboundedTimeout, "unboundedTimeout");
3208
3715
 
3209
3716
  // src/v3/runtime/devRuntimeManager.ts
3210
3717
  var _DevRuntimeManager = class _DevRuntimeManager {
3211
3718
  constructor() {
3212
3719
  __publicField(this, "_taskWaits", /* @__PURE__ */ new Map());
3213
3720
  __publicField(this, "_batchWaits", /* @__PURE__ */ new Map());
3214
- __publicField(this, "_tasks", /* @__PURE__ */ new Map());
3215
3721
  __publicField(this, "_pendingCompletionNotifications", /* @__PURE__ */ new Map());
3216
3722
  }
3217
3723
  disable() {
3218
3724
  }
3219
- registerTasks(tasks) {
3220
- for (const task of tasks) {
3221
- this._tasks.set(task.id, task);
3222
- }
3223
- }
3224
- getTaskMetadata(id) {
3225
- return this._tasks.get(id);
3226
- }
3227
3725
  async waitForDuration(ms) {
3228
- return new Promise((resolve) => {
3229
- setTimeout(resolve, ms);
3230
- });
3726
+ await unboundedTimeout(ms);
3231
3727
  }
3232
3728
  async waitUntil(date) {
3233
- return new Promise((resolve) => {
3234
- setTimeout(resolve, date.getTime() - Date.now());
3235
- });
3729
+ return this.waitForDuration(date.getTime() - Date.now());
3236
3730
  }
3237
3731
  async waitForTask(params) {
3238
3732
  const pendingCompletion = this._pendingCompletionNotifications.get(params.id);
@@ -3295,27 +3789,20 @@ var _DevRuntimeManager = class _DevRuntimeManager {
3295
3789
  };
3296
3790
  __name(_DevRuntimeManager, "DevRuntimeManager");
3297
3791
  var DevRuntimeManager = _DevRuntimeManager;
3792
+
3793
+ // src/v3/runtime/prodRuntimeManager.ts
3298
3794
  var _ProdRuntimeManager = class _ProdRuntimeManager {
3299
3795
  constructor(ipc, options = {}) {
3300
3796
  this.ipc = ipc;
3301
3797
  this.options = options;
3302
3798
  this._taskWaits = /* @__PURE__ */ new Map();
3303
3799
  this._batchWaits = /* @__PURE__ */ new Map();
3304
- this._tasks = /* @__PURE__ */ new Map();
3305
3800
  }
3306
3801
  disable() {
3307
3802
  }
3308
- registerTasks(tasks) {
3309
- for (const task of tasks) {
3310
- this._tasks.set(task.id, task);
3311
- }
3312
- }
3313
- getTaskMetadata(id) {
3314
- return this._tasks.get(id);
3315
- }
3316
3803
  async waitForDuration(ms) {
3317
3804
  const now = Date.now();
3318
- const resolveAfterDuration = setTimeout$1(ms, "duration");
3805
+ const resolveAfterDuration = unboundedTimeout(ms, "duration");
3319
3806
  if (ms <= this.waitThresholdInMs) {
3320
3807
  await resolveAfterDuration;
3321
3808
  return;
@@ -3517,11 +4004,12 @@ __name(_TriggerTracer, "TriggerTracer");
3517
4004
  var TriggerTracer = _TriggerTracer;
3518
4005
  var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
3519
4006
  var _ConsoleInterceptor = class _ConsoleInterceptor {
3520
- constructor(logger2) {
4007
+ constructor(logger2, sendToStdIO) {
3521
4008
  __privateAdd(this, _handleLog);
3522
4009
  __privateAdd(this, _getTimestampInHrTime2);
3523
4010
  __privateAdd(this, _getAttributes);
3524
4011
  this.logger = logger2;
4012
+ this.sendToStdIO = sendToStdIO;
3525
4013
  }
3526
4014
  // Intercept the console and send logs to the OpenTelemetry logger
3527
4015
  // during the execution of the callback
@@ -3530,12 +4018,14 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3530
4018
  log: console2.log,
3531
4019
  info: console2.info,
3532
4020
  warn: console2.warn,
3533
- error: console2.error
4021
+ error: console2.error,
4022
+ debug: console2.debug
3534
4023
  };
3535
4024
  console2.log = this.log.bind(this);
3536
4025
  console2.info = this.info.bind(this);
3537
4026
  console2.warn = this.warn.bind(this);
3538
4027
  console2.error = this.error.bind(this);
4028
+ console2.debug = this.debug.bind(this);
3539
4029
  try {
3540
4030
  return await callback();
3541
4031
  } finally {
@@ -3543,8 +4033,12 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3543
4033
  console2.info = originalConsole.info;
3544
4034
  console2.warn = originalConsole.warn;
3545
4035
  console2.error = originalConsole.error;
4036
+ console2.debug = originalConsole.debug;
3546
4037
  }
3547
4038
  }
4039
+ debug(...args) {
4040
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.DEBUG, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Debug", ...args);
4041
+ }
3548
4042
  log(...args) {
3549
4043
  __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
3550
4044
  }
@@ -3561,6 +4055,13 @@ var _ConsoleInterceptor = class _ConsoleInterceptor {
3561
4055
  _handleLog = new WeakSet();
3562
4056
  handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
3563
4057
  const body = util.format(...args);
4058
+ if (this.sendToStdIO) {
4059
+ if (severityNumber === SeverityNumber.ERROR) {
4060
+ process.stderr.write(body);
4061
+ } else {
4062
+ process.stdout.write(body);
4063
+ }
4064
+ }
3564
4065
  const parsed = tryParseJSON(body);
3565
4066
  if (parsed.ok) {
3566
4067
  this.logger.emit({
@@ -3636,113 +4137,6 @@ function tryParseJSON(value) {
3636
4137
  }
3637
4138
  __name(tryParseJSON, "tryParseJSON");
3638
4139
 
3639
- // src/retry.ts
3640
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
3641
- if (!resets)
3642
- return;
3643
- switch (format) {
3644
- case "iso_8601_duration_openai_variant": {
3645
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
3646
- }
3647
- case "iso_8601": {
3648
- return calculateISO8601ResetAt(resets, now);
3649
- }
3650
- case "unix_timestamp": {
3651
- return calculateUnixTimestampResetAt(resets, now);
3652
- }
3653
- case "unix_timestamp_in_ms": {
3654
- return calculateUnixTimestampInMsResetAt(resets, now);
3655
- }
3656
- }
3657
- }
3658
- __name(calculateResetAt, "calculateResetAt");
3659
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
3660
- if (!resets)
3661
- return void 0;
3662
- const resetAt = parseInt(resets, 10);
3663
- if (isNaN(resetAt))
3664
- return void 0;
3665
- return new Date(resetAt * 1e3);
3666
- }
3667
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
3668
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
3669
- if (!resets)
3670
- return void 0;
3671
- const resetAt = parseInt(resets, 10);
3672
- if (isNaN(resetAt))
3673
- return void 0;
3674
- return new Date(resetAt);
3675
- }
3676
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
3677
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
3678
- if (!resets)
3679
- return void 0;
3680
- const resetAt = new Date(resets);
3681
- if (isNaN(resetAt.getTime()))
3682
- return void 0;
3683
- return resetAt;
3684
- }
3685
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
3686
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
3687
- if (!resets)
3688
- return void 0;
3689
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
3690
- const match = resets.match(pattern);
3691
- if (!match)
3692
- return void 0;
3693
- const days = parseInt(match[1], 10) || 0;
3694
- const hours = parseInt(match[2], 10) || 0;
3695
- const minutes = parseInt(match[3], 10) || 0;
3696
- const seconds = parseFloat(match[4]) || 0;
3697
- const milliseconds = parseInt(match[5], 10) || 0;
3698
- const resetAt = new Date(now);
3699
- resetAt.setDate(resetAt.getDate() + days);
3700
- resetAt.setHours(resetAt.getHours() + hours);
3701
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
3702
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
3703
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
3704
- return resetAt;
3705
- }
3706
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
3707
-
3708
- // src/v3/utils/retries.ts
3709
- var defaultRetryOptions = {
3710
- maxAttempts: 3,
3711
- factor: 2,
3712
- minTimeoutInMs: 1e3,
3713
- maxTimeoutInMs: 6e4,
3714
- randomize: true
3715
- };
3716
- var defaultFetchRetryOptions = {
3717
- byStatus: {
3718
- "429,408,409,5xx": {
3719
- strategy: "backoff",
3720
- ...defaultRetryOptions
3721
- }
3722
- },
3723
- connectionError: defaultRetryOptions,
3724
- timeout: defaultRetryOptions
3725
- };
3726
- function calculateNextRetryDelay(options, attempt) {
3727
- const opts = {
3728
- ...defaultRetryOptions,
3729
- ...options
3730
- };
3731
- if (attempt >= opts.maxAttempts) {
3732
- return;
3733
- }
3734
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
3735
- const random = randomize ? Math.random() + 1 : 1;
3736
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
3737
- return Math.round(timeout);
3738
- }
3739
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
3740
- function calculateResetAt2(resets, format, now = Date.now()) {
3741
- const resetAt = calculateResetAt(resets, format, new Date(now));
3742
- return resetAt?.getTime();
3743
- }
3744
- __name(calculateResetAt2, "calculateResetAt");
3745
-
3746
4140
  // src/v3/utils/styleAttributes.ts
3747
4141
  function accessoryAttributes(accessory) {
3748
4142
  return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
@@ -4103,6 +4497,7 @@ async function stringifyIO(value) {
4103
4497
  };
4104
4498
  } catch {
4105
4499
  return {
4500
+ data: value,
4106
4501
  dataType: "application/json"
4107
4502
  };
4108
4503
  }
@@ -4147,23 +4542,20 @@ __name(packetRequiresOffloading, "packetRequiresOffloading");
4147
4542
  async function exportPacket(packet, pathPrefix) {
4148
4543
  const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
4149
4544
  const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
4150
- if (presignedResponse.ok) {
4151
- const uploadResponse = await fetch(presignedResponse.data.presignedUrl, {
4152
- method: "PUT",
4153
- headers: {
4154
- "Content-Type": packet.dataType
4155
- },
4156
- body: packet.data
4157
- });
4158
- if (!uploadResponse.ok) {
4159
- throw new Error(`Failed to upload output to ${presignedResponse.data.presignedUrl}: ${uploadResponse.statusText}`);
4160
- }
4161
- return {
4162
- data: filename,
4163
- dataType: "application/store"
4164
- };
4545
+ const uploadResponse = await fetch(presignedResponse.presignedUrl, {
4546
+ method: "PUT",
4547
+ headers: {
4548
+ "Content-Type": packet.dataType
4549
+ },
4550
+ body: packet.data
4551
+ });
4552
+ if (!uploadResponse.ok) {
4553
+ throw new Error(`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`);
4165
4554
  }
4166
- return packet;
4555
+ return {
4556
+ data: filename,
4557
+ dataType: "application/store"
4558
+ };
4167
4559
  }
4168
4560
  __name(exportPacket, "exportPacket");
4169
4561
  async function conditionallyImportPacket(packet, tracer) {
@@ -4192,19 +4584,16 @@ async function importPacket(packet, span) {
4192
4584
  return packet;
4193
4585
  }
4194
4586
  const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
4195
- if (presignedResponse.ok) {
4196
- const response = await fetch(presignedResponse.data.presignedUrl);
4197
- if (!response.ok) {
4198
- throw new Error(`Failed to import packet ${presignedResponse.data.presignedUrl}: ${response.statusText}`);
4199
- }
4200
- const data = await response.text();
4201
- span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4202
- return {
4203
- data,
4204
- dataType: response.headers.get("content-type") ?? "application/json"
4205
- };
4587
+ const response = await fetch(presignedResponse.presignedUrl);
4588
+ if (!response.ok) {
4589
+ throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
4206
4590
  }
4207
- return packet;
4591
+ const data = await response.text();
4592
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4593
+ return {
4594
+ data,
4595
+ dataType: response.headers.get("content-type") ?? "application/json"
4596
+ };
4208
4597
  }
4209
4598
  __name(importPacket, "importPacket");
4210
4599
  async function createPacketAttributes(packet, dataKey, dataTypeKey) {
@@ -4257,7 +4646,7 @@ async function createPacketAttributesAsJson(data, dataType) {
4257
4646
  case "application/super+json":
4258
4647
  const { deserialize } = await loadSuperJSON();
4259
4648
  const deserialized = deserialize(data);
4260
- const jsonify = safeJsonParse(JSON.stringify(deserialized, safeReplacer));
4649
+ const jsonify = safeJsonParse2(JSON.stringify(deserialized, safeReplacer));
4261
4650
  return imposeAttributeLimits(flattenAttributes(jsonify, void 0));
4262
4651
  case "application/store":
4263
4652
  return data;
@@ -4271,10 +4660,16 @@ async function prettyPrintPacket(rawData, dataType) {
4271
4660
  return "";
4272
4661
  }
4273
4662
  if (dataType === "application/super+json") {
4663
+ if (typeof rawData === "string") {
4664
+ rawData = safeJsonParse2(rawData);
4665
+ }
4274
4666
  const { deserialize } = await loadSuperJSON();
4275
4667
  return await prettyPrintPacket(deserialize(rawData), "application/json");
4276
4668
  }
4277
4669
  if (dataType === "application/json") {
4670
+ if (typeof rawData === "string") {
4671
+ rawData = safeJsonParse2(rawData);
4672
+ }
4278
4673
  return JSON.stringify(rawData, safeReplacer, 2);
4279
4674
  }
4280
4675
  if (typeof rawData === "string") {
@@ -4320,14 +4715,14 @@ async function loadSuperJSON() {
4320
4715
  return await import('superjson');
4321
4716
  }
4322
4717
  __name(loadSuperJSON, "loadSuperJSON");
4323
- function safeJsonParse(value) {
4718
+ function safeJsonParse2(value) {
4324
4719
  try {
4325
4720
  return JSON.parse(value);
4326
4721
  } catch {
4327
4722
  return;
4328
4723
  }
4329
4724
  }
4330
- __name(safeJsonParse, "safeJsonParse");
4725
+ __name(safeJsonParse2, "safeJsonParse");
4331
4726
 
4332
4727
  // src/v3/workers/taskExecutor.ts
4333
4728
  var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
@@ -4599,7 +4994,8 @@ var dependencies = {
4599
4994
  superjson: "^2.2.1",
4600
4995
  ulidx: "^2.2.1",
4601
4996
  zod: "3.22.3",
4602
- "zod-error": "1.5.0"
4997
+ "zod-error": "1.5.0",
4998
+ "zod-validation-error": "^1.5.0"
4603
4999
  };
4604
5000
 
4605
5001
  // src/v3/utils/detectDependencyVersion.ts
@@ -4608,6 +5004,84 @@ function detectDependencyVersion(dependency) {
4608
5004
  }
4609
5005
  __name(detectDependencyVersion, "detectDependencyVersion");
4610
5006
 
5007
+ // src/v3/task-catalog/standardTaskCatalog.ts
5008
+ var _StandardTaskCatalog = class _StandardTaskCatalog {
5009
+ constructor() {
5010
+ __publicField(this, "_taskMetadata", /* @__PURE__ */ new Map());
5011
+ __publicField(this, "_taskFunctions", /* @__PURE__ */ new Map());
5012
+ __publicField(this, "_taskFileMetadata", /* @__PURE__ */ new Map());
5013
+ }
5014
+ registerTaskMetadata(task) {
5015
+ const { fns, ...metadata } = task;
5016
+ this._taskMetadata.set(task.id, metadata);
5017
+ this._taskFunctions.set(task.id, fns);
5018
+ }
5019
+ updateTaskMetadata(id, updates) {
5020
+ const existingMetadata = this._taskMetadata.get(id);
5021
+ if (existingMetadata) {
5022
+ this._taskMetadata.set(id, {
5023
+ ...existingMetadata,
5024
+ ...updates
5025
+ });
5026
+ }
5027
+ if (updates.fns) {
5028
+ const existingFunctions = this._taskFunctions.get(id);
5029
+ if (existingFunctions) {
5030
+ this._taskFunctions.set(id, {
5031
+ ...existingFunctions,
5032
+ ...updates.fns
5033
+ });
5034
+ }
5035
+ }
5036
+ }
5037
+ registerTaskFileMetadata(id, metadata) {
5038
+ this._taskFileMetadata.set(id, metadata);
5039
+ }
5040
+ // Return all the tasks, without the functions
5041
+ getAllTaskMetadata() {
5042
+ const result = [];
5043
+ for (const [id, metadata] of this._taskMetadata) {
5044
+ const fileMetadata = this._taskFileMetadata.get(id);
5045
+ if (!fileMetadata) {
5046
+ continue;
5047
+ }
5048
+ result.push({
5049
+ ...metadata,
5050
+ ...fileMetadata
5051
+ });
5052
+ }
5053
+ return result;
5054
+ }
5055
+ getTaskMetadata(id) {
5056
+ const metadata = this._taskMetadata.get(id);
5057
+ const fileMetadata = this._taskFileMetadata.get(id);
5058
+ if (!metadata || !fileMetadata) {
5059
+ return void 0;
5060
+ }
5061
+ return {
5062
+ ...metadata,
5063
+ ...fileMetadata
5064
+ };
5065
+ }
5066
+ getTask(id) {
5067
+ const metadata = this._taskMetadata.get(id);
5068
+ const fileMetadata = this._taskFileMetadata.get(id);
5069
+ const fns = this._taskFunctions.get(id);
5070
+ if (!metadata || !fns || !fileMetadata) {
5071
+ return void 0;
5072
+ }
5073
+ return {
5074
+ ...metadata,
5075
+ ...fileMetadata,
5076
+ fns
5077
+ };
5078
+ }
5079
+ disable() {
5080
+ }
5081
+ };
5082
+ __name(_StandardTaskCatalog, "StandardTaskCatalog");
5083
+ var StandardTaskCatalog = _StandardTaskCatalog;
5084
+
4611
5085
  // src/v3/index.ts
4612
5086
  function parseTriggerTaskRequestBody(body) {
4613
5087
  return TriggerTaskRequestBody.safeParse(body);
@@ -4618,6 +5092,6 @@ function parseBatchTriggerTaskRequestBody(body) {
4618
5092
  }
4619
5093
  __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
4620
5094
 
4621
- export { ApiClient, ApiClientManager, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConsoleInterceptor, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateUploadPayloadUrlResponseBody, DeploymentErrorData, DevRuntimeManager, PreciseWallClock as DurableClock, EnvironmentType, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, LogLevel, Machine, MachineCpu, MachineMemory, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OtelTaskLogger, OtherSpanEvent, PRIMARY_VARIANT, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdRuntimeManager, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitOptions, ReplayRunResponse, RetryOptions, SemanticInternalAttributes, SharedQueueToClientMessages, SimpleStructuredLogger, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskContextSpanProcessor, TaskEventStyle, TaskExecutor, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TracingSDK, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, WaitReason, WhoAmIResponseSchema, ZodIpcConnection, ZodMessageHandler, ZodMessageSchema, ZodMessageSender, ZodNamespace, ZodSchemaParsedError, ZodSocketConnection, ZodSocketMessageHandler, ZodSocketMessageSender, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, getEnvVar, groupTaskMetadataIssuesByTask, iconStringForSeverity, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logLevels, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseBatchTriggerTaskRequestBody, parseError, parsePacket, parseTriggerTaskRequestBody, prettyPrintPacket, primitiveValueOrflattenedAttributes, recordSpanException, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskContextManager, unflattenAttributes, workerToChildMessages };
5095
+ export { APIConnectionError, APIError, ApiClient, ApiClientManager, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, ConsoleInterceptor, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, DeletedScheduleObject, DeploymentErrorData, DevRuntimeManager, PreciseWallClock as DurableClock, EnvironmentType, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListScheduleOptions, ListSchedulesResult, LogLevel, Machine, MachineCpu, MachineMemory, NotFoundError, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OtelTaskLogger, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdRuntimeManager, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RetryOptions, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SharedQueueToClientMessages, SimpleStructuredLogger, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StandardTaskCatalog, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskContextSpanProcessor, TaskEventStyle, TaskExecutor, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TracingSDK, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, ZodIpcConnection, ZodMessageHandler, ZodMessageSchema, ZodMessageSender, ZodNamespace, ZodSchemaParsedError, ZodSocketConnection, ZodSocketMessageHandler, ZodSocketMessageSender, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, getEnvVar, groupTaskMetadataIssuesByTask, iconStringForSeverity, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logLevels, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseBatchTriggerTaskRequestBody, parseError, parsePacket, parseTriggerTaskRequestBody, prettyPrintPacket, primitiveValueOrflattenedAttributes, recordSpanException, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContextManager, unflattenAttributes, workerToChildMessages };
4622
5096
  //# sourceMappingURL=out.js.map
4623
5097
  //# sourceMappingURL=index.mjs.map