@trigger.dev/core 0.0.0-v3-schedules-beta-20240417103105 → 0.0.0-v3-schedules-beta-20240417141912

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.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  var zod = require('zod');
4
4
  var api = require('@opentelemetry/api');
5
+ var zodValidationError = require('zod-validation-error');
5
6
  var async_hooks = require('async_hooks');
6
7
  var socket_ioClient = require('socket.io-client');
7
8
  var crypto = require('crypto');
@@ -768,16 +769,50 @@ var CanceledRunResponse = zod.z.object({
768
769
  message: zod.z.string()
769
770
  });
770
771
  var ScheduledTaskPayload = zod.z.object({
772
+ /** The schedule id associated with this run (you can have many schedules for the same task).
773
+ You can use this to remove the schedule, update it, etc */
771
774
  scheduleId: zod.z.string(),
775
+ /** When the task was scheduled to run.
776
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
772
777
  timestamp: zod.z.date(),
778
+ /** When the task was last run (it has been).
779
+ This can be undefined if it's never been run */
773
780
  lastTimestamp: zod.z.date().optional(),
781
+ /** You can optionally provide an external id when creating the schedule.
782
+ Usually you would use a userId or some other unique identifier.
783
+ This defaults to undefined if you didn't provide one. */
774
784
  externalId: zod.z.string().optional(),
785
+ /** The next 5 dates this task is scheduled to run */
775
786
  upcoming: zod.z.array(zod.z.date())
776
787
  });
777
788
  var CreateScheduleOptions = zod.z.object({
789
+ /** The id of the task you want to attach to. */
778
790
  task: zod.z.string(),
791
+ /** The schedule in CRON format.
792
+ *
793
+ * ```txt
794
+ * * * * * *
795
+ ┬ ┬ ┬ ┬ ┬
796
+ │ │ │ │ |
797
+ │ │ │ │ └ day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
798
+ │ │ │ └───── month (1 - 12)
799
+ │ │ └────────── day of month (1 - 31, L)
800
+ │ └─────────────── hour (0 - 23)
801
+ └──────────────────── minute (0 - 59)
802
+ * ```
803
+
804
+ "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.
805
+
806
+ */
779
807
  cron: zod.z.string(),
808
+ /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
809
+ *
810
+ * This is useful if you don't want to create duplicate schedules for a user. */
780
811
  deduplicationKey: zod.z.string().optional(),
812
+ /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
813
+ *
814
+ * This allows you to have per-user CRON tasks.
815
+ */
781
816
  externalId: zod.z.string().optional()
782
817
  });
783
818
  var UpdateScheduleOptions = CreateScheduleOptions;
@@ -785,18 +820,18 @@ var ScheduleObject = zod.z.object({
785
820
  id: zod.z.string(),
786
821
  task: zod.z.string(),
787
822
  active: zod.z.boolean(),
788
- deduplicationKey: zod.z.string().optional(),
789
- externalId: zod.z.string().optional(),
823
+ deduplicationKey: zod.z.string().nullish(),
824
+ externalId: zod.z.string().nullish(),
790
825
  generator: zod.z.object({
791
826
  type: zod.z.literal("CRON"),
792
827
  expression: zod.z.string(),
793
828
  description: zod.z.string()
794
829
  }),
795
- nextRun: zod.z.coerce.date().optional(),
830
+ nextRun: zod.z.coerce.date().nullish(),
796
831
  environments: zod.z.array(zod.z.object({
797
832
  id: zod.z.string(),
798
833
  type: zod.z.string(),
799
- userName: zod.z.string().optional()
834
+ userName: zod.z.string().nullish()
800
835
  }))
801
836
  });
802
837
  var DeletedScheduleObject = zod.z.object({
@@ -1502,101 +1537,384 @@ var SpanMessagingEvent = zod.z.object({
1502
1537
  destination: zod.z.string().optional()
1503
1538
  });
1504
1539
 
1505
- // src/zodfetch.ts
1540
+ // src/v3/apiErrors.ts
1541
+ var _APIError = class _APIError extends Error {
1542
+ constructor(status, error, message, headers) {
1543
+ super(`${_APIError.makeMessage(status, error, message)}`);
1544
+ this.status = status;
1545
+ this.headers = headers;
1546
+ const data = error;
1547
+ this.error = data;
1548
+ this.code = data?.["code"];
1549
+ this.param = data?.["param"];
1550
+ this.type = data?.["type"];
1551
+ }
1552
+ static makeMessage(status, error, message) {
1553
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1554
+ if (status && msg) {
1555
+ return `${status} ${msg}`;
1556
+ }
1557
+ if (status) {
1558
+ return `${status} status code (no body)`;
1559
+ }
1560
+ if (msg) {
1561
+ return msg;
1562
+ }
1563
+ return "(no status code or body)";
1564
+ }
1565
+ static generate(status, errorResponse, message, headers) {
1566
+ if (!status) {
1567
+ return new APIConnectionError({
1568
+ cause: castToError(errorResponse)
1569
+ });
1570
+ }
1571
+ const error = errorResponse?.["error"];
1572
+ if (status === 400) {
1573
+ return new BadRequestError(status, error, message, headers);
1574
+ }
1575
+ if (status === 401) {
1576
+ return new AuthenticationError(status, error, message, headers);
1577
+ }
1578
+ if (status === 403) {
1579
+ return new PermissionDeniedError(status, error, message, headers);
1580
+ }
1581
+ if (status === 404) {
1582
+ return new NotFoundError(status, error, message, headers);
1583
+ }
1584
+ if (status === 409) {
1585
+ return new ConflictError(status, error, message, headers);
1586
+ }
1587
+ if (status === 422) {
1588
+ return new UnprocessableEntityError(status, error, message, headers);
1589
+ }
1590
+ if (status === 429) {
1591
+ return new RateLimitError(status, error, message, headers);
1592
+ }
1593
+ if (status >= 500) {
1594
+ return new InternalServerError(status, error, message, headers);
1595
+ }
1596
+ return new _APIError(status, error, message, headers);
1597
+ }
1598
+ };
1599
+ __name(_APIError, "APIError");
1600
+ var APIError = _APIError;
1601
+ var _APIConnectionError = class _APIConnectionError extends APIError {
1602
+ constructor({ message, cause }) {
1603
+ super(void 0, void 0, message || "Connection error.", void 0);
1604
+ __publicField(this, "status");
1605
+ if (cause)
1606
+ this.cause = cause;
1607
+ }
1608
+ };
1609
+ __name(_APIConnectionError, "APIConnectionError");
1610
+ var APIConnectionError = _APIConnectionError;
1611
+ var _BadRequestError = class _BadRequestError extends APIError {
1612
+ constructor() {
1613
+ super(...arguments);
1614
+ __publicField(this, "status", 400);
1615
+ }
1616
+ };
1617
+ __name(_BadRequestError, "BadRequestError");
1618
+ var BadRequestError = _BadRequestError;
1619
+ var _AuthenticationError = class _AuthenticationError extends APIError {
1620
+ constructor() {
1621
+ super(...arguments);
1622
+ __publicField(this, "status", 401);
1623
+ }
1624
+ };
1625
+ __name(_AuthenticationError, "AuthenticationError");
1626
+ var AuthenticationError = _AuthenticationError;
1627
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
1628
+ constructor() {
1629
+ super(...arguments);
1630
+ __publicField(this, "status", 403);
1631
+ }
1632
+ };
1633
+ __name(_PermissionDeniedError, "PermissionDeniedError");
1634
+ var PermissionDeniedError = _PermissionDeniedError;
1635
+ var _NotFoundError = class _NotFoundError extends APIError {
1636
+ constructor() {
1637
+ super(...arguments);
1638
+ __publicField(this, "status", 404);
1639
+ }
1640
+ };
1641
+ __name(_NotFoundError, "NotFoundError");
1642
+ var NotFoundError = _NotFoundError;
1643
+ var _ConflictError = class _ConflictError extends APIError {
1644
+ constructor() {
1645
+ super(...arguments);
1646
+ __publicField(this, "status", 409);
1647
+ }
1648
+ };
1649
+ __name(_ConflictError, "ConflictError");
1650
+ var ConflictError = _ConflictError;
1651
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
1652
+ constructor() {
1653
+ super(...arguments);
1654
+ __publicField(this, "status", 422);
1655
+ }
1656
+ };
1657
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
1658
+ var UnprocessableEntityError = _UnprocessableEntityError;
1659
+ var _RateLimitError = class _RateLimitError extends APIError {
1660
+ constructor() {
1661
+ super(...arguments);
1662
+ __publicField(this, "status", 429);
1663
+ }
1664
+ };
1665
+ __name(_RateLimitError, "RateLimitError");
1666
+ var RateLimitError = _RateLimitError;
1667
+ var _InternalServerError = class _InternalServerError extends APIError {
1668
+ };
1669
+ __name(_InternalServerError, "InternalServerError");
1670
+ var InternalServerError = _InternalServerError;
1671
+ function castToError(err) {
1672
+ if (err instanceof Error)
1673
+ return err;
1674
+ return new Error(err);
1675
+ }
1676
+ __name(castToError, "castToError");
1677
+
1678
+ // src/retry.ts
1679
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
1680
+ if (!resets)
1681
+ return;
1682
+ switch (format) {
1683
+ case "iso_8601_duration_openai_variant": {
1684
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
1685
+ }
1686
+ case "iso_8601": {
1687
+ return calculateISO8601ResetAt(resets, now);
1688
+ }
1689
+ case "unix_timestamp": {
1690
+ return calculateUnixTimestampResetAt(resets, now);
1691
+ }
1692
+ case "unix_timestamp_in_ms": {
1693
+ return calculateUnixTimestampInMsResetAt(resets, now);
1694
+ }
1695
+ }
1696
+ }
1697
+ __name(calculateResetAt, "calculateResetAt");
1698
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
1699
+ if (!resets)
1700
+ return void 0;
1701
+ const resetAt = parseInt(resets, 10);
1702
+ if (isNaN(resetAt))
1703
+ return void 0;
1704
+ return new Date(resetAt * 1e3);
1705
+ }
1706
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
1707
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
1708
+ if (!resets)
1709
+ return void 0;
1710
+ const resetAt = parseInt(resets, 10);
1711
+ if (isNaN(resetAt))
1712
+ return void 0;
1713
+ return new Date(resetAt);
1714
+ }
1715
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
1716
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
1717
+ if (!resets)
1718
+ return void 0;
1719
+ const resetAt = new Date(resets);
1720
+ if (isNaN(resetAt.getTime()))
1721
+ return void 0;
1722
+ return resetAt;
1723
+ }
1724
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
1725
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
1726
+ if (!resets)
1727
+ return void 0;
1728
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
1729
+ const match = resets.match(pattern);
1730
+ if (!match)
1731
+ return void 0;
1732
+ const days = parseInt(match[1], 10) || 0;
1733
+ const hours = parseInt(match[2], 10) || 0;
1734
+ const minutes = parseInt(match[3], 10) || 0;
1735
+ const seconds = parseFloat(match[4]) || 0;
1736
+ const milliseconds = parseInt(match[5], 10) || 0;
1737
+ const resetAt = new Date(now);
1738
+ resetAt.setDate(resetAt.getDate() + days);
1739
+ resetAt.setHours(resetAt.getHours() + hours);
1740
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
1741
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
1742
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
1743
+ return resetAt;
1744
+ }
1745
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
1746
+
1747
+ // src/v3/utils/retries.ts
1748
+ var defaultRetryOptions = {
1749
+ maxAttempts: 3,
1750
+ factor: 2,
1751
+ minTimeoutInMs: 1e3,
1752
+ maxTimeoutInMs: 6e4,
1753
+ randomize: true
1754
+ };
1755
+ var defaultFetchRetryOptions = {
1756
+ byStatus: {
1757
+ "429,408,409,5xx": {
1758
+ strategy: "backoff",
1759
+ ...defaultRetryOptions
1760
+ }
1761
+ },
1762
+ connectionError: defaultRetryOptions,
1763
+ timeout: defaultRetryOptions
1764
+ };
1765
+ function calculateNextRetryDelay(options, attempt) {
1766
+ const opts = {
1767
+ ...defaultRetryOptions,
1768
+ ...options
1769
+ };
1770
+ if (attempt >= opts.maxAttempts) {
1771
+ return;
1772
+ }
1773
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1774
+ const random = randomize ? Math.random() + 1 : 1;
1775
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1776
+ return Math.round(timeout);
1777
+ }
1778
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1779
+ function calculateResetAt2(resets, format, now = Date.now()) {
1780
+ const resetAt = calculateResetAt(resets, format, new Date(now));
1781
+ return resetAt?.getTime();
1782
+ }
1783
+ __name(calculateResetAt2, "calculateResetAt");
1784
+
1785
+ // src/v3/zodfetch.ts
1786
+ var defaultRetryOptions2 = {
1787
+ maxAttempts: 3,
1788
+ factor: 2,
1789
+ minTimeoutInMs: 1e3,
1790
+ maxTimeoutInMs: 6e4,
1791
+ randomize: false
1792
+ };
1506
1793
  async function zodfetch(schema, url, requestInit, options) {
1507
1794
  return await _doZodFetch(schema, url, requestInit, options);
1508
1795
  }
1509
1796
  __name(zodfetch, "zodfetch");
1510
1797
  async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1511
1798
  try {
1512
- const response = await fetch(url, requestInit);
1513
- if ((!requestInit || requestInit.method === "GET") && response.status === 404) {
1514
- return {
1515
- ok: false,
1516
- error: `404: ${response.statusText}`
1517
- };
1518
- }
1519
- if (response.status >= 400 && response.status < 500 && response.status !== 429) {
1520
- const body = await response.json();
1521
- if (!body.error) {
1522
- return {
1523
- ok: false,
1524
- error: "Something went wrong"
1525
- };
1799
+ const response = await fetch(url, requestInitWithCache(requestInit));
1800
+ const responseHeaders = createResponseHeaders(response.headers);
1801
+ if (!response.ok) {
1802
+ const retryResult = shouldRetry(response, attempt, options?.retry);
1803
+ if (retryResult.retry) {
1804
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
1805
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1806
+ } else {
1807
+ const errText = await response.text().catch((e) => castToError2(e).message);
1808
+ const errJSON = safeJsonParse(errText);
1809
+ const errMessage = errJSON ? void 0 : errText;
1810
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
1526
1811
  }
1527
- return {
1528
- ok: false,
1529
- error: body.error
1530
- };
1531
1812
  }
1532
- if (response.status === 429 || response.status >= 500) {
1533
- if (!options?.retry) {
1534
- return {
1535
- ok: false,
1536
- error: `Failed to fetch ${url}, got status code ${response.status}`
1537
- };
1538
- }
1813
+ const jsonBody = await response.json();
1814
+ const parsedResult = schema.safeParse(jsonBody);
1815
+ if (parsedResult.success) {
1816
+ return parsedResult.data;
1817
+ }
1818
+ throw zodValidationError.fromZodError(parsedResult.error);
1819
+ } catch (error) {
1820
+ if (error instanceof APIError) {
1821
+ throw error;
1822
+ }
1823
+ if (options?.retry) {
1539
1824
  const retry = {
1540
- ...defaultRetryOptions,
1825
+ ...defaultRetryOptions2,
1541
1826
  ...options.retry
1542
1827
  };
1543
- if (attempt > retry.maxAttempts) {
1544
- return {
1545
- ok: false,
1546
- error: `Failed to fetch ${url}, got status code ${response.status}`
1547
- };
1548
- }
1549
1828
  const delay = calculateNextRetryDelay(retry, attempt);
1550
- await new Promise((resolve) => setTimeout(resolve, delay));
1551
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1552
- }
1553
- if (response.status !== 200) {
1554
- return {
1555
- ok: false,
1556
- error: `Failed to fetch ${url}, got status code ${response.status}`
1557
- };
1829
+ if (delay) {
1830
+ await new Promise((resolve) => setTimeout(resolve, delay));
1831
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1832
+ }
1558
1833
  }
1559
- const jsonBody = await response.json();
1560
- const parsedResult = schema.safeParse(jsonBody);
1561
- if (parsedResult.success) {
1834
+ throw new APIConnectionError({
1835
+ cause: castToError2(error)
1836
+ });
1837
+ }
1838
+ }
1839
+ __name(_doZodFetch, "_doZodFetch");
1840
+ function castToError2(err) {
1841
+ if (err instanceof Error)
1842
+ return err;
1843
+ return new Error(err);
1844
+ }
1845
+ __name(castToError2, "castToError");
1846
+ function shouldRetry(response, attempt, retryOptions) {
1847
+ function shouldRetryForOptions() {
1848
+ const retry = {
1849
+ ...defaultRetryOptions2,
1850
+ ...retryOptions
1851
+ };
1852
+ const delay = calculateNextRetryDelay(retry, attempt);
1853
+ if (delay) {
1562
1854
  return {
1563
- ok: true,
1564
- data: parsedResult.data
1855
+ retry: true,
1856
+ delay
1565
1857
  };
1566
- }
1567
- if ("error" in jsonBody) {
1858
+ } else {
1568
1859
  return {
1569
- ok: false,
1570
- error: typeof jsonBody.error === "string" ? jsonBody.error : JSON.stringify(jsonBody.error)
1860
+ retry: false
1571
1861
  };
1572
1862
  }
1863
+ }
1864
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
1865
+ const shouldRetryHeader = response.headers.get("x-should-retry");
1866
+ if (shouldRetryHeader === "true")
1867
+ return shouldRetryForOptions();
1868
+ if (shouldRetryHeader === "false")
1573
1869
  return {
1574
- ok: false,
1575
- error: parsedResult.error.message
1870
+ retry: false
1576
1871
  };
1577
- } catch (error) {
1578
- if (options?.retry) {
1579
- const retry = {
1580
- ...defaultRetryOptions,
1581
- ...options.retry
1582
- };
1583
- if (attempt > retry.maxAttempts) {
1584
- return {
1585
- ok: false,
1586
- error: error instanceof Error ? error.message : JSON.stringify(error)
1587
- };
1588
- }
1589
- const delay = calculateNextRetryDelay(retry, attempt);
1590
- await new Promise((resolve) => setTimeout(resolve, delay));
1591
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1872
+ if (response.status === 408)
1873
+ return shouldRetryForOptions();
1874
+ if (response.status === 409)
1875
+ return shouldRetryForOptions();
1876
+ if (response.status === 429)
1877
+ return shouldRetryForOptions();
1878
+ if (response.status >= 500)
1879
+ return shouldRetryForOptions();
1880
+ return {
1881
+ retry: false
1882
+ };
1883
+ }
1884
+ __name(shouldRetry, "shouldRetry");
1885
+ function safeJsonParse(text) {
1886
+ try {
1887
+ return JSON.parse(text);
1888
+ } catch (e) {
1889
+ return void 0;
1890
+ }
1891
+ }
1892
+ __name(safeJsonParse, "safeJsonParse");
1893
+ function createResponseHeaders(headers) {
1894
+ return new Proxy(Object.fromEntries(
1895
+ // @ts-ignore
1896
+ headers.entries()
1897
+ ), {
1898
+ get(target, name) {
1899
+ const key = name.toString();
1900
+ return target[key.toLowerCase()] || target[key];
1592
1901
  }
1593
- return {
1594
- ok: false,
1595
- error: error instanceof Error ? error.message : JSON.stringify(error)
1902
+ });
1903
+ }
1904
+ __name(createResponseHeaders, "createResponseHeaders");
1905
+ function requestInitWithCache(requestInit) {
1906
+ try {
1907
+ const withCache = {
1908
+ ...requestInit,
1909
+ cache: "no-cache"
1596
1910
  };
1911
+ const _ = new Request("http://localhost", withCache);
1912
+ return withCache;
1913
+ } catch (error) {
1914
+ return requestInit ?? {};
1597
1915
  }
1598
1916
  }
1599
- __name(_doZodFetch, "_doZodFetch");
1917
+ __name(requestInitWithCache, "requestInitWithCache");
1600
1918
 
1601
1919
  // src/v3/utils/flattenAttributes.ts
1602
1920
  function flattenAttributes(obj, prefix) {
@@ -1885,7 +2203,7 @@ __name(getEnvVar, "getEnvVar");
1885
2203
  // src/v3/apiClient/index.ts
1886
2204
  var zodFetchOptions = {
1887
2205
  retry: {
1888
- maxAttempts: 5,
2206
+ maxAttempts: 3,
1889
2207
  minTimeoutInMs: 1e3,
1890
2208
  maxTimeoutInMs: 3e4,
1891
2209
  factor: 2,
@@ -3816,113 +4134,6 @@ function tryParseJSON(value) {
3816
4134
  }
3817
4135
  __name(tryParseJSON, "tryParseJSON");
3818
4136
 
3819
- // src/retry.ts
3820
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
3821
- if (!resets)
3822
- return;
3823
- switch (format) {
3824
- case "iso_8601_duration_openai_variant": {
3825
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
3826
- }
3827
- case "iso_8601": {
3828
- return calculateISO8601ResetAt(resets, now);
3829
- }
3830
- case "unix_timestamp": {
3831
- return calculateUnixTimestampResetAt(resets, now);
3832
- }
3833
- case "unix_timestamp_in_ms": {
3834
- return calculateUnixTimestampInMsResetAt(resets, now);
3835
- }
3836
- }
3837
- }
3838
- __name(calculateResetAt, "calculateResetAt");
3839
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
3840
- if (!resets)
3841
- return void 0;
3842
- const resetAt = parseInt(resets, 10);
3843
- if (isNaN(resetAt))
3844
- return void 0;
3845
- return new Date(resetAt * 1e3);
3846
- }
3847
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
3848
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
3849
- if (!resets)
3850
- return void 0;
3851
- const resetAt = parseInt(resets, 10);
3852
- if (isNaN(resetAt))
3853
- return void 0;
3854
- return new Date(resetAt);
3855
- }
3856
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
3857
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
3858
- if (!resets)
3859
- return void 0;
3860
- const resetAt = new Date(resets);
3861
- if (isNaN(resetAt.getTime()))
3862
- return void 0;
3863
- return resetAt;
3864
- }
3865
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
3866
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
3867
- if (!resets)
3868
- return void 0;
3869
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
3870
- const match = resets.match(pattern);
3871
- if (!match)
3872
- return void 0;
3873
- const days = parseInt(match[1], 10) || 0;
3874
- const hours = parseInt(match[2], 10) || 0;
3875
- const minutes = parseInt(match[3], 10) || 0;
3876
- const seconds = parseFloat(match[4]) || 0;
3877
- const milliseconds = parseInt(match[5], 10) || 0;
3878
- const resetAt = new Date(now);
3879
- resetAt.setDate(resetAt.getDate() + days);
3880
- resetAt.setHours(resetAt.getHours() + hours);
3881
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
3882
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
3883
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
3884
- return resetAt;
3885
- }
3886
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
3887
-
3888
- // src/v3/utils/retries.ts
3889
- var defaultRetryOptions = {
3890
- maxAttempts: 3,
3891
- factor: 2,
3892
- minTimeoutInMs: 1e3,
3893
- maxTimeoutInMs: 6e4,
3894
- randomize: true
3895
- };
3896
- var defaultFetchRetryOptions = {
3897
- byStatus: {
3898
- "429,408,409,5xx": {
3899
- strategy: "backoff",
3900
- ...defaultRetryOptions
3901
- }
3902
- },
3903
- connectionError: defaultRetryOptions,
3904
- timeout: defaultRetryOptions
3905
- };
3906
- function calculateNextRetryDelay(options, attempt) {
3907
- const opts = {
3908
- ...defaultRetryOptions,
3909
- ...options
3910
- };
3911
- if (attempt >= opts.maxAttempts) {
3912
- return;
3913
- }
3914
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
3915
- const random = randomize ? Math.random() + 1 : 1;
3916
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
3917
- return Math.round(timeout);
3918
- }
3919
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
3920
- function calculateResetAt2(resets, format, now = Date.now()) {
3921
- const resetAt = calculateResetAt(resets, format, new Date(now));
3922
- return resetAt?.getTime();
3923
- }
3924
- __name(calculateResetAt2, "calculateResetAt");
3925
-
3926
4137
  // src/v3/utils/styleAttributes.ts
3927
4138
  function accessoryAttributes(accessory) {
3928
4139
  return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
@@ -4328,23 +4539,20 @@ __name(packetRequiresOffloading, "packetRequiresOffloading");
4328
4539
  async function exportPacket(packet, pathPrefix) {
4329
4540
  const filename = `${pathPrefix}.${getPacketExtension(packet.dataType)}`;
4330
4541
  const presignedResponse = await apiClientManager.client.createUploadPayloadUrl(filename);
4331
- if (presignedResponse.ok) {
4332
- const uploadResponse = await fetch(presignedResponse.data.presignedUrl, {
4333
- method: "PUT",
4334
- headers: {
4335
- "Content-Type": packet.dataType
4336
- },
4337
- body: packet.data
4338
- });
4339
- if (!uploadResponse.ok) {
4340
- throw new Error(`Failed to upload output to ${presignedResponse.data.presignedUrl}: ${uploadResponse.statusText}`);
4341
- }
4342
- return {
4343
- data: filename,
4344
- dataType: "application/store"
4345
- };
4542
+ const uploadResponse = await fetch(presignedResponse.presignedUrl, {
4543
+ method: "PUT",
4544
+ headers: {
4545
+ "Content-Type": packet.dataType
4546
+ },
4547
+ body: packet.data
4548
+ });
4549
+ if (!uploadResponse.ok) {
4550
+ throw new Error(`Failed to upload output to ${presignedResponse.presignedUrl}: ${uploadResponse.statusText}`);
4346
4551
  }
4347
- return packet;
4552
+ return {
4553
+ data: filename,
4554
+ dataType: "application/store"
4555
+ };
4348
4556
  }
4349
4557
  __name(exportPacket, "exportPacket");
4350
4558
  async function conditionallyImportPacket(packet, tracer) {
@@ -4373,19 +4581,16 @@ async function importPacket(packet, span) {
4373
4581
  return packet;
4374
4582
  }
4375
4583
  const presignedResponse = await apiClientManager.client.getPayloadUrl(packet.data);
4376
- if (presignedResponse.ok) {
4377
- const response = await fetch(presignedResponse.data.presignedUrl);
4378
- if (!response.ok) {
4379
- throw new Error(`Failed to import packet ${presignedResponse.data.presignedUrl}: ${response.statusText}`);
4380
- }
4381
- const data = await response.text();
4382
- span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4383
- return {
4384
- data,
4385
- dataType: response.headers.get("content-type") ?? "application/json"
4386
- };
4584
+ const response = await fetch(presignedResponse.presignedUrl);
4585
+ if (!response.ok) {
4586
+ throw new Error(`Failed to import packet ${presignedResponse.presignedUrl}: ${response.statusText}`);
4387
4587
  }
4388
- return packet;
4588
+ const data = await response.text();
4589
+ span?.setAttribute("size", Buffer.byteLength(data, "utf8"));
4590
+ return {
4591
+ data,
4592
+ dataType: response.headers.get("content-type") ?? "application/json"
4593
+ };
4389
4594
  }
4390
4595
  __name(importPacket, "importPacket");
4391
4596
  async function createPacketAttributes(packet, dataKey, dataTypeKey) {
@@ -4438,7 +4643,7 @@ async function createPacketAttributesAsJson(data, dataType) {
4438
4643
  case "application/super+json":
4439
4644
  const { deserialize } = await loadSuperJSON();
4440
4645
  const deserialized = deserialize(data);
4441
- const jsonify = safeJsonParse(JSON.stringify(deserialized, safeReplacer));
4646
+ const jsonify = safeJsonParse2(JSON.stringify(deserialized, safeReplacer));
4442
4647
  return imposeAttributeLimits(flattenAttributes(jsonify, void 0));
4443
4648
  case "application/store":
4444
4649
  return data;
@@ -4453,14 +4658,14 @@ async function prettyPrintPacket(rawData, dataType) {
4453
4658
  }
4454
4659
  if (dataType === "application/super+json") {
4455
4660
  if (typeof rawData === "string") {
4456
- rawData = safeJsonParse(rawData);
4661
+ rawData = safeJsonParse2(rawData);
4457
4662
  }
4458
4663
  const { deserialize } = await loadSuperJSON();
4459
4664
  return await prettyPrintPacket(deserialize(rawData), "application/json");
4460
4665
  }
4461
4666
  if (dataType === "application/json") {
4462
4667
  if (typeof rawData === "string") {
4463
- rawData = safeJsonParse(rawData);
4668
+ rawData = safeJsonParse2(rawData);
4464
4669
  }
4465
4670
  return JSON.stringify(rawData, safeReplacer, 2);
4466
4671
  }
@@ -4507,14 +4712,14 @@ async function loadSuperJSON() {
4507
4712
  return await import('superjson');
4508
4713
  }
4509
4714
  __name(loadSuperJSON, "loadSuperJSON");
4510
- function safeJsonParse(value) {
4715
+ function safeJsonParse2(value) {
4511
4716
  try {
4512
4717
  return JSON.parse(value);
4513
4718
  } catch {
4514
4719
  return;
4515
4720
  }
4516
4721
  }
4517
- __name(safeJsonParse, "safeJsonParse");
4722
+ __name(safeJsonParse2, "safeJsonParse");
4518
4723
 
4519
4724
  // src/v3/workers/taskExecutor.ts
4520
4725
  var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
@@ -4786,7 +4991,8 @@ var dependencies = {
4786
4991
  superjson: "^2.2.1",
4787
4992
  ulidx: "^2.2.1",
4788
4993
  zod: "3.22.3",
4789
- "zod-error": "1.5.0"
4994
+ "zod-error": "1.5.0",
4995
+ "zod-validation-error": "^1.5.0"
4790
4996
  };
4791
4997
 
4792
4998
  // src/v3/utils/detectDependencyVersion.ts
@@ -4883,12 +5089,16 @@ function parseBatchTriggerTaskRequestBody(body) {
4883
5089
  }
4884
5090
  __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
4885
5091
 
5092
+ exports.APIConnectionError = APIConnectionError;
5093
+ exports.APIError = APIError;
4886
5094
  exports.ApiClient = ApiClient;
4887
5095
  exports.ApiClientManager = ApiClientManager;
5096
+ exports.AuthenticationError = AuthenticationError;
4888
5097
  exports.BackgroundWorkerClientMessages = BackgroundWorkerClientMessages;
4889
5098
  exports.BackgroundWorkerMetadata = BackgroundWorkerMetadata;
4890
5099
  exports.BackgroundWorkerProperties = BackgroundWorkerProperties;
4891
5100
  exports.BackgroundWorkerServerMessages = BackgroundWorkerServerMessages;
5101
+ exports.BadRequestError = BadRequestError;
4892
5102
  exports.BatchTaskRunExecutionResult = BatchTaskRunExecutionResult;
4893
5103
  exports.BatchTriggerTaskRequestBody = BatchTriggerTaskRequestBody;
4894
5104
  exports.BatchTriggerTaskResponse = BatchTriggerTaskResponse;
@@ -4896,6 +5106,7 @@ exports.CanceledRunResponse = CanceledRunResponse;
4896
5106
  exports.CancellationSpanEvent = CancellationSpanEvent;
4897
5107
  exports.ClientToSharedQueueMessages = ClientToSharedQueueMessages;
4898
5108
  exports.Config = Config;
5109
+ exports.ConflictError = ConflictError;
4899
5110
  exports.ConsoleInterceptor = ConsoleInterceptor;
4900
5111
  exports.CoordinatorToPlatformMessages = CoordinatorToPlatformMessages;
4901
5112
  exports.CoordinatorToProdWorkerMessages = CoordinatorToProdWorkerMessages;
@@ -4931,11 +5142,13 @@ exports.GetProjectsResponseBody = GetProjectsResponseBody;
4931
5142
  exports.ImageDetailsMetadata = ImageDetailsMetadata;
4932
5143
  exports.InitializeDeploymentRequestBody = InitializeDeploymentRequestBody;
4933
5144
  exports.InitializeDeploymentResponseBody = InitializeDeploymentResponseBody;
5145
+ exports.InternalServerError = InternalServerError;
4934
5146
  exports.ListScheduleOptions = ListScheduleOptions;
4935
5147
  exports.ListSchedulesResult = ListSchedulesResult;
4936
5148
  exports.Machine = Machine;
4937
5149
  exports.MachineCpu = MachineCpu;
4938
5150
  exports.MachineMemory = MachineMemory;
5151
+ exports.NotFoundError = NotFoundError;
4939
5152
  exports.OFFLOAD_IO_PACKET_LENGTH_LIMIT = OFFLOAD_IO_PACKET_LENGTH_LIMIT;
4940
5153
  exports.OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT;
4941
5154
  exports.OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT;
@@ -4948,6 +5161,7 @@ exports.OTEL_SPAN_EVENT_COUNT_LIMIT = OTEL_SPAN_EVENT_COUNT_LIMIT;
4948
5161
  exports.OtelTaskLogger = OtelTaskLogger;
4949
5162
  exports.OtherSpanEvent = OtherSpanEvent;
4950
5163
  exports.PRIMARY_VARIANT = PRIMARY_VARIANT;
5164
+ exports.PermissionDeniedError = PermissionDeniedError;
4951
5165
  exports.PlatformToCoordinatorMessages = PlatformToCoordinatorMessages;
4952
5166
  exports.PlatformToProviderMessages = PlatformToProviderMessages;
4953
5167
  exports.PostStartCauses = PostStartCauses;
@@ -4961,6 +5175,7 @@ exports.ProdWorkerToChildMessages = ProdWorkerToChildMessages;
4961
5175
  exports.ProdWorkerToCoordinatorMessages = ProdWorkerToCoordinatorMessages;
4962
5176
  exports.ProviderToPlatformMessages = ProviderToPlatformMessages;
4963
5177
  exports.QueueOptions = QueueOptions;
5178
+ exports.RateLimitError = RateLimitError;
4964
5179
  exports.RateLimitOptions = RateLimitOptions;
4965
5180
  exports.ReplayRunResponse = ReplayRunResponse;
4966
5181
  exports.RetryOptions = RetryOptions;
@@ -5010,6 +5225,7 @@ exports.TriggerTaskRequestBody = TriggerTaskRequestBody;
5010
5225
  exports.TriggerTaskResponse = TriggerTaskResponse;
5011
5226
  exports.TriggerTracer = TriggerTracer;
5012
5227
  exports.UncaughtExceptionMessage = UncaughtExceptionMessage;
5228
+ exports.UnprocessableEntityError = UnprocessableEntityError;
5013
5229
  exports.UpdateScheduleOptions = UpdateScheduleOptions;
5014
5230
  exports.WaitReason = WaitReason;
5015
5231
  exports.WhoAmIResponseSchema = WhoAmIResponseSchema;