@zapier/zapier-sdk 0.103.0 → 0.104.0

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.
@@ -706,7 +706,6 @@ function createDebugFetch(options) {
706
706
  // src/utils/retry-utils.ts
707
707
  var MAX_CONSECUTIVE_ERRORS = 3;
708
708
  var BASE_ERROR_BACKOFF_MILLISECONDS = 1e3;
709
- var BASE_EXPONENTIAL_BACKOFF_MILLISECONDS = 1e3;
710
709
  var JITTER_FACTOR = 0.5;
711
710
  function calculateErrorBackoffMs(baseInterval, errorCount) {
712
711
  const jitter = Math.random() * JITTER_FACTOR * baseInterval;
@@ -717,11 +716,6 @@ function calculateErrorBackoffMs(baseInterval, errorCount) {
717
716
  );
718
717
  return Math.floor(baseInterval + jitter + errorBackoff);
719
718
  }
720
- function calculateExponentialBackoffMs(attempt, baseDelayMs = BASE_EXPONENTIAL_BACKOFF_MILLISECONDS) {
721
- const baseDelay = baseDelayMs * Math.pow(2, attempt - 1);
722
- const jitter = Math.random() * JITTER_FACTOR * baseDelay;
723
- return Math.floor(baseDelay + jitter);
724
- }
725
719
  function sleep(ms, signal) {
726
720
  if (!signal) {
727
721
  return new Promise((resolve2) => setTimeout(resolve2, ms));
@@ -1076,7 +1070,114 @@ var sdkOptionsPluginRef = kitcore.declareOptionalProperty({
1076
1070
  id: SDK_OPTIONS_ID
1077
1071
  });
1078
1072
 
1073
+ // src/api/rate-limit.ts
1074
+ var EPOCH_THRESHOLD_SECONDS = 1e9;
1075
+ function parseRateLimitHeaders(response) {
1076
+ const info = {};
1077
+ const retryAfter = response.headers.get("retry-after");
1078
+ if (retryAfter) {
1079
+ const seconds = parseInt(retryAfter, 10);
1080
+ if (!isNaN(seconds)) {
1081
+ info.retryAfterMs = Math.max(0, seconds * 1e3);
1082
+ } else {
1083
+ const date = Date.parse(retryAfter);
1084
+ if (!isNaN(date)) {
1085
+ info.retryAfterMs = Math.max(0, date - Date.now());
1086
+ }
1087
+ }
1088
+ }
1089
+ const reset = response.headers.get("x-ratelimit-reset");
1090
+ if (reset) {
1091
+ const resetValue = parseInt(reset, 10);
1092
+ if (!isNaN(resetValue)) {
1093
+ const isEpoch = resetValue >= EPOCH_THRESHOLD_SECONDS;
1094
+ info.resetMs = isEpoch ? resetValue * 1e3 : Date.now() + resetValue * 1e3;
1095
+ if (info.retryAfterMs === void 0) {
1096
+ info.retryAfterMs = isEpoch ? Math.max(0, info.resetMs - Date.now()) : Math.max(0, resetValue * 1e3);
1097
+ }
1098
+ }
1099
+ }
1100
+ const limit = response.headers.get("x-ratelimit-limit");
1101
+ if (limit) {
1102
+ const limitNum = parseInt(limit, 10);
1103
+ if (!isNaN(limitNum)) {
1104
+ info.limit = limitNum;
1105
+ }
1106
+ }
1107
+ const remaining = response.headers.get("x-ratelimit-remaining");
1108
+ if (remaining) {
1109
+ const remainingNum = parseInt(remaining, 10);
1110
+ if (!isNaN(remainingNum)) {
1111
+ info.remaining = remainingNum;
1112
+ }
1113
+ }
1114
+ return info;
1115
+ }
1116
+
1117
+ // src/utils/type-guard-utils.ts
1118
+ function isPlainObject(value) {
1119
+ if (typeof value !== "object" || value === null) return false;
1120
+ const proto = Object.getPrototypeOf(value);
1121
+ return proto === Object.prototype || proto === null;
1122
+ }
1123
+ function isPromiseLike(value) {
1124
+ return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
1125
+ }
1126
+
1127
+ // src/plugins/transport/retry-events.ts
1128
+ var retryCounts = /* @__PURE__ */ new WeakMap();
1129
+ function retriesFor(request) {
1130
+ return retryCounts.get(request) ?? 0;
1131
+ }
1132
+ function createRetryObserver({
1133
+ onEvent,
1134
+ maxNetworkRetries
1135
+ }) {
1136
+ return ({ request, attemptNumber, delayMilliseconds, response }) => {
1137
+ retryCounts.set(request, attemptNumber);
1138
+ if (!onEvent || response?.status !== 429) return;
1139
+ const observed = onEvent({
1140
+ type: "api:rate_limit_retry",
1141
+ payload: {
1142
+ retry: attemptNumber,
1143
+ maxNetworkRetries,
1144
+ delayMs: delayMilliseconds,
1145
+ path: request.url,
1146
+ method: request.method ?? "GET",
1147
+ rateLimit: parseRateLimitHeaders(response)
1148
+ },
1149
+ timestamp: Date.now()
1150
+ });
1151
+ if (isPromiseLike(observed)) {
1152
+ void Promise.resolve(observed).catch(() => {
1153
+ });
1154
+ }
1155
+ };
1156
+ }
1157
+
1079
1158
  // src/plugins/transport/options.ts
1159
+ var RETRYABLE_STATUSES = [429, 500, 502, 503, 504];
1160
+ var NON_IDEMPOTENT_RETRYABLE_STATUSES = [429];
1161
+ function resolveRetryHttpRequestOptions({
1162
+ maxNetworkRetries,
1163
+ maxNetworkRetryDelayMilliseconds,
1164
+ onEvent
1165
+ }) {
1166
+ const retries = maxNetworkRetries ?? ZAPIER_MAX_NETWORK_RETRIES;
1167
+ return {
1168
+ maxAttempts: retries + 1,
1169
+ maxDelayMilliseconds: maxNetworkRetryDelayMilliseconds ?? ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS,
1170
+ retryStatuses: RETRYABLE_STATUSES,
1171
+ nonIdempotentRetryStatuses: NON_IDEMPOTENT_RETRYABLE_STATUSES,
1172
+ onRetry: createRetryObserver({ onEvent, maxNetworkRetries: retries })
1173
+ };
1174
+ }
1175
+ function resolveNetworkRetryDelayMilliseconds({
1176
+ maxNetworkRetryDelaySeconds,
1177
+ maxNetworkRetryDelayMs
1178
+ }) {
1179
+ return maxNetworkRetryDelaySeconds != null ? maxNetworkRetryDelaySeconds * 1e3 : maxNetworkRetryDelayMs;
1180
+ }
1080
1181
  function resolveTransportFetch({
1081
1182
  fetch: customFetch,
1082
1183
  debug = false
@@ -1104,15 +1205,29 @@ var httpFetchPlugin = kitcore.defineProperty({
1104
1205
  // src/plugins/transport/standalone.ts
1105
1206
  function createZapierSendHttpRequest({
1106
1207
  fetch: customFetch,
1107
- debug
1208
+ debug,
1209
+ maxNetworkRetries,
1210
+ maxNetworkRetryDelayMilliseconds,
1211
+ onEvent
1108
1212
  }) {
1109
1213
  const sdk = kitcore.createSdk(
1110
1214
  kitcore.definePlugin({
1111
1215
  name: "zapierStandaloneHttpTransport",
1112
- imports: [kitcore.sendHttpRequestPlugin, httpFetchPlugin],
1216
+ imports: [kitcore.sendHttpRequestPlugin, kitcore.retryHttpRequestPlugin, httpFetchPlugin],
1113
1217
  exports: [kitcore.sendHttpRequestPlugin]
1114
1218
  }),
1115
- { configuration: { [SDK_OPTIONS_ID]: { fetch: customFetch, debug } } }
1219
+ {
1220
+ configuration: {
1221
+ [SDK_OPTIONS_ID]: { fetch: customFetch, debug },
1222
+ // Filled by configuration rather than the graph's property plugin: the
1223
+ // caller here holds client-shaped ms options, not SDK options.
1224
+ [kitcore.RETRY_HTTP_REQUEST_OPTIONS_ID]: resolveRetryHttpRequestOptions({
1225
+ maxNetworkRetries,
1226
+ maxNetworkRetryDelayMilliseconds,
1227
+ onEvent
1228
+ })
1229
+ }
1230
+ }
1116
1231
  );
1117
1232
  return sdk.sendHttpRequest;
1118
1233
  }
@@ -1770,13 +1885,6 @@ async function invalidateCredentialsToken(options) {
1770
1885
  });
1771
1886
  }
1772
1887
  }
1773
-
1774
- // src/utils/type-guard-utils.ts
1775
- function isPlainObject(value) {
1776
- if (typeof value !== "object" || value === null) return false;
1777
- const proto = Object.getPrototypeOf(value);
1778
- return proto === Object.prototype || proto === null;
1779
- }
1780
1888
  var callerContext = kitcore.createAsyncContext();
1781
1889
  function runWithCallerContext(context, fn) {
1782
1890
  let parent;
@@ -2022,9 +2130,6 @@ function sniffDeprecationNotice({
2022
2130
  }
2023
2131
  }
2024
2132
  }
2025
- function isPromiseLike(value) {
2026
- return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
2027
- }
2028
2133
  function parseDeprecationDate(value) {
2029
2134
  if (!value) return void 0;
2030
2135
  const match = /^@(-?\d+)$/.exec(value.trim());
@@ -2553,7 +2658,7 @@ function logRouteOverride({
2553
2658
  }
2554
2659
 
2555
2660
  // src/sdk-version.ts
2556
- var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.103.0" : void 0) || "unknown";
2661
+ var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.104.0" : void 0) || "unknown";
2557
2662
 
2558
2663
  // src/utils/open-url.ts
2559
2664
  var nodePrefix = "node:";
@@ -2669,7 +2774,6 @@ var PollApprovalResponseSchema = zod.z.object({
2669
2774
  approval_url: zod.z.string().optional()
2670
2775
  });
2671
2776
  var APPROVAL_MAX_POLLING_INTERVAL_MILLISECONDS = 5e3;
2672
- var EPOCH_THRESHOLD_SECONDS = 1e9;
2673
2777
  function validateSdkPath(path) {
2674
2778
  if (!path.startsWith("/") || path.startsWith("//")) {
2675
2779
  throw new ZapierValidationError(
@@ -2677,57 +2781,17 @@ function validateSdkPath(path) {
2677
2781
  );
2678
2782
  }
2679
2783
  }
2680
- function parseRateLimitHeaders(response) {
2681
- const info = {};
2682
- const retryAfter = response.headers.get("retry-after");
2683
- if (retryAfter) {
2684
- const seconds = parseInt(retryAfter, 10);
2685
- if (!isNaN(seconds)) {
2686
- info.retryAfterMs = seconds * 1e3;
2687
- } else {
2688
- const date = Date.parse(retryAfter);
2689
- if (!isNaN(date)) {
2690
- info.retryAfterMs = Math.max(0, date - Date.now());
2691
- }
2692
- }
2693
- }
2694
- const reset = response.headers.get("x-ratelimit-reset");
2695
- if (reset) {
2696
- const resetValue = parseInt(reset, 10);
2697
- if (!isNaN(resetValue)) {
2698
- const isEpoch = resetValue >= EPOCH_THRESHOLD_SECONDS;
2699
- info.resetMs = isEpoch ? resetValue * 1e3 : Date.now() + resetValue * 1e3;
2700
- if (info.retryAfterMs === void 0) {
2701
- info.retryAfterMs = isEpoch ? Math.max(0, info.resetMs - Date.now()) : Math.max(0, resetValue * 1e3);
2702
- }
2703
- }
2704
- }
2705
- const limit = response.headers.get("x-ratelimit-limit");
2706
- if (limit) {
2707
- const limitNum = parseInt(limit, 10);
2708
- if (!isNaN(limitNum)) {
2709
- info.limit = limitNum;
2710
- }
2711
- }
2712
- const remaining = response.headers.get("x-ratelimit-remaining");
2713
- if (remaining) {
2714
- const remainingNum = parseInt(remaining, 10);
2715
- if (!isNaN(remainingNum)) {
2716
- info.remaining = remainingNum;
2717
- }
2718
- }
2719
- return info;
2720
- }
2721
2784
  var ZapierApiClient = class {
2722
2785
  constructor(options) {
2723
2786
  this.options = options;
2724
2787
  /**
2725
2788
  * Perform a request against an already-resolved URL.
2726
2789
  *
2727
- * Does auth, header merging, and 429 retry all the cross-cutting
2728
- * concerns that every Zapier-bound HTTP call needs. Callers that have a
2729
- * path (e.g. `/relay/...`) should use `rawFetch` instead, which does
2730
- * path URL resolution and delegates here.
2790
+ * Does auth and header merging, and converts a terminal 429 into
2791
+ * `ZapierRateLimitError` the cross-cutting concerns that every
2792
+ * Zapier-bound HTTP call needs and that the transport does not own. Callers
2793
+ * that have a path (e.g. `/relay/...`) should use `rawFetch` instead, which
2794
+ * does path → URL resolution and delegates here.
2731
2795
  *
2732
2796
  * Exposed as a separate helper so call sites with a server-supplied
2733
2797
  * absolute URL (e.g. an approval poll URL) can still share the same
@@ -2761,47 +2825,30 @@ var ZapierApiClient = class {
2761
2825
  resource: _resource,
2762
2826
  ...wireInit
2763
2827
  } = fetchInit;
2764
- let retries = 0;
2765
- while (true) {
2766
- const response = await this.options.sendHttpRequest({
2767
- ...wireInit,
2768
- // Set the resolved URL and merged headers after the spread so caller
2769
- // values cannot override them.
2770
- url,
2771
- headers: Object.fromEntries(mergedHeaders)
2772
- });
2773
- if (response.status !== 429) {
2774
- return response;
2775
- }
2776
- const rateLimitInfo = parseRateLimitHeaders(response);
2777
- const delayMs = rateLimitInfo.retryAfterMs ?? calculateExponentialBackoffMs(retries + 1);
2778
- if (delayMs > this.maxNetworkRetryDelayMilliseconds || retries >= this.maxNetworkRetries) {
2779
- throw new ZapierRateLimitError(
2780
- await this.readRateLimitErrorMessage(response),
2781
- {
2782
- statusCode: 429,
2783
- rateLimit: rateLimitInfo,
2784
- retries
2785
- }
2786
- );
2787
- }
2788
- retries++;
2789
- this.emitEvent("api:rate_limit_retry", {
2790
- retry: retries,
2791
- maxNetworkRetries: this.maxNetworkRetries,
2792
- delayMs,
2793
- path: url,
2794
- method: init?.method ?? "GET",
2795
- rateLimit: rateLimitInfo
2796
- });
2797
- await sleep(delayMs, init?.signal ?? void 0);
2828
+ const request = {
2829
+ ...wireInit,
2830
+ url,
2831
+ headers: Object.fromEntries(mergedHeaders)
2832
+ };
2833
+ const response = await this.options.sendHttpRequest(request);
2834
+ if (response.status !== 429) {
2835
+ return response;
2798
2836
  }
2837
+ throw new ZapierRateLimitError(
2838
+ await this.readRateLimitErrorMessage(response),
2839
+ {
2840
+ statusCode: 429,
2841
+ rateLimit: parseRateLimitHeaders(response),
2842
+ retries: retriesFor(request)
2843
+ }
2844
+ );
2799
2845
  };
2800
2846
  /**
2801
2847
  * Wrap an outbound HTTP call with the concurrency semaphore. Used by both
2802
2848
  * `rawFetch` (path-based) and the approval-poll path (absolute URL); each
2803
- * caller acquires per-attempt, so 429 retry sleep is held but the gap
2804
- * between approval polls and the human-approval wait are not.
2849
+ * caller acquires per request, so the transport's retry sleeps are held
2850
+ * inside the permit but the gap between approval polls and the
2851
+ * human-approval wait are not.
2805
2852
  *
2806
2853
  * The release is registered in a finally that wraps the entire post-
2807
2854
  * acquire flow — including the `wait_end` event emission — so a throwing
@@ -3051,8 +3098,6 @@ var ZapierApiClient = class {
3051
3098
  signal: options.signal
3052
3099
  });
3053
3100
  };
3054
- this.maxNetworkRetries = options.maxNetworkRetries ?? ZAPIER_MAX_NETWORK_RETRIES;
3055
- this.maxNetworkRetryDelayMilliseconds = options.maxNetworkRetryDelayMilliseconds ?? options.maxNetworkRetryDelayMs ?? ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS;
3056
3101
  const requested = options.maxConcurrentRequests;
3057
3102
  const limit = requested === void 0 || Number.isNaN(requested) ? ZAPIER_MAX_CONCURRENT_REQUESTS : requested;
3058
3103
  if (limit !== Infinity && (!Number.isInteger(limit) || limit < 1 || limit > MAX_CONCURRENCY_LIMIT)) {
@@ -3808,7 +3853,13 @@ var createZapierApi = (options) => {
3808
3853
  fetch: debugFetch,
3809
3854
  // Built from the caller's own `fetch`, not `debugFetch`: the pipeline wraps
3810
3855
  // for debug itself, and passing the wrapped one would log twice.
3811
- sendHttpRequest: options.sendHttpRequest ?? createZapierSendHttpRequest({ fetch: options.fetch, debug }),
3856
+ sendHttpRequest: options.sendHttpRequest ?? createZapierSendHttpRequest({
3857
+ fetch: options.fetch,
3858
+ debug,
3859
+ onEvent: options.onEvent,
3860
+ maxNetworkRetries: options.maxNetworkRetries,
3861
+ maxNetworkRetryDelayMilliseconds: options.maxNetworkRetryDelayMilliseconds ?? options.maxNetworkRetryDelayMs
3862
+ }),
3812
3863
  debugLog,
3813
3864
  routingOptions
3814
3865
  });
@@ -3847,10 +3898,30 @@ function getOrCreateApiClient(config) {
3847
3898
  callerPackage
3848
3899
  });
3849
3900
  }
3901
+ var retryHttpRequestOptionsPlugin = kitcore.defineProperty({
3902
+ namespace: "kitcore",
3903
+ name: "retryHttpRequestOptions",
3904
+ imports: [sdkOptionsPluginRef],
3905
+ setup: ({ imports }) => resolveRetryHttpRequestOptions({
3906
+ maxNetworkRetries: imports.sdkOptions?.maxNetworkRetries,
3907
+ maxNetworkRetryDelayMilliseconds: resolveNetworkRetryDelayMilliseconds(
3908
+ imports.sdkOptions ?? {}
3909
+ ),
3910
+ onEvent: imports.sdkOptions?.onEvent
3911
+ }),
3912
+ get: ({ state }) => state
3913
+ });
3914
+
3915
+ // src/plugins/transport/index.ts
3850
3916
  var zapierHttpTransportPlugin = kitcore.definePlugin({
3851
3917
  namespace: "zapier",
3852
3918
  name: "httpTransport",
3853
- imports: [kitcore.sendHttpRequestPlugin, httpFetchPlugin],
3919
+ imports: [
3920
+ kitcore.sendHttpRequestPlugin,
3921
+ kitcore.retryHttpRequestPlugin,
3922
+ retryHttpRequestOptionsPlugin,
3923
+ httpFetchPlugin
3924
+ ],
3854
3925
  exports: [kitcore.sendHttpRequestPlugin]
3855
3926
  });
3856
3927
 
@@ -3910,7 +3981,10 @@ var apiPlugin = kitcore.defineProperty({
3910
3981
  fetch: customFetch,
3911
3982
  onEvent,
3912
3983
  maxNetworkRetries,
3913
- maxNetworkRetryDelayMilliseconds: (maxNetworkRetryDelaySeconds != null ? maxNetworkRetryDelaySeconds * 1e3 : maxNetworkRetryDelayMs) ?? ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS,
3984
+ maxNetworkRetryDelayMilliseconds: resolveNetworkRetryDelayMilliseconds({
3985
+ maxNetworkRetryDelaySeconds,
3986
+ maxNetworkRetryDelayMs
3987
+ }) ?? ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS,
3914
3988
  maxConcurrentRequests,
3915
3989
  approvalTimeoutMilliseconds: approvalTimeoutSeconds != null ? approvalTimeoutSeconds * 1e3 : approvalTimeoutMs,
3916
3990
  maxApprovalRetries,
@@ -12315,17 +12389,20 @@ var BaseSdkOptionsSchema = zod.z.object({
12315
12389
  routeOverrides: zod.z.record(zod.z.string(), zod.z.string()).optional().describe("Maps SDK route prefixes to direct origins.").meta({ internal: true }),
12316
12390
  trackingBaseUrl: zod.z.string().optional().describe("Base URL for Zapier tracking endpoints.").meta({ valueHint: "url" }),
12317
12391
  /**
12318
- * Maximum number of retries for rate-limited requests (429 responses).
12392
+ * Maximum number of retries for rate-limited requests (429 responses) and,
12393
+ * on idempotent methods, retryable server errors (500, 502, 503, 504).
12319
12394
  * Set to 0 to disable retries. Default is 3.
12320
12395
  */
12321
- maxNetworkRetries: zod.z.number().optional().describe("Max retries for rate-limited requests (default: 3).").meta({ valueHint: "count" }),
12396
+ maxNetworkRetries: zod.z.number().optional().describe(
12397
+ "Max retries for rate-limited and server-error responses (default: 3)."
12398
+ ).meta({ valueHint: "count" }),
12322
12399
  /**
12323
- * Maximum delay in seconds to wait for a rate-limit retry.
12400
+ * Maximum delay in seconds to wait between network retries.
12324
12401
  * If the server requests a longer delay, the request fails immediately.
12325
12402
  * Default is 60 (60 seconds).
12326
12403
  */
12327
12404
  maxNetworkRetryDelaySeconds: zod.z.number().optional().describe(
12328
- "Max delay in seconds to wait for a rate-limit retry (default: 60)."
12405
+ "Max delay in seconds to wait between network retries (default: 60)."
12329
12406
  ).meta({ valueHint: "seconds" }),
12330
12407
  /** @deprecated Use `maxNetworkRetryDelaySeconds` instead. */
12331
12408
  maxNetworkRetryDelayMs: zod.z.number().optional().describe("Max delay in ms to wait for retry (default: 60000).").meta({ valueHint: "ms", deprecated: true }),