@zapier/zapier-sdk 0.103.0 → 0.105.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.
@@ -1,6 +1,6 @@
1
1
  import { __require } from './chunk-Y6FXYEAI.mjs';
2
2
  import { z } from 'zod';
3
- import { withPositional, declareOptionalProperty, defineProperty, createDeprecationLogger, createAsyncContext, definePlugin, sendHttpRequestPlugin, declareProperty, defineMethod, coreOptionsPluginRef, createValidator, defineFormatter, declareMethod, defineResolver, concatLists, openEnum, defineHook, getRegistryPlugin, paginate, toSnakeCase, isCoreError, toTitleCase, createSdk, CORE_ERROR_SYMBOL, CoreErrorCode, CORE_SIGNAL_SYMBOL, isCoreSignal, CORE_OPTIONS_ID } from '@zapier/kitcore';
3
+ import { withPositional, declareOptionalProperty, defineProperty, createDeprecationLogger, createAsyncContext, definePlugin, sendHttpRequestPlugin, retryHttpRequestPlugin, declareProperty, defineMethod, coreOptionsPluginRef, createValidator, defineFormatter, declareMethod, defineResolver, concatLists, openEnum, defineHook, getRegistryPlugin, paginate, toSnakeCase, isCoreError, toTitleCase, createSdk, RETRY_HTTP_REQUEST_OPTIONS_ID, CORE_ERROR_SYMBOL, CoreErrorCode, CORE_SIGNAL_SYMBOL, isCoreSignal, CORE_OPTIONS_ID } from '@zapier/kitcore';
4
4
  export { CONTEXT, CORE_ERROR_SYMBOL, CORE_OPTIONS_ID, CORE_SIGNAL_SYMBOL, CoreCancelledSignal, CoreDisposeError, CoreErrorCode, CoreSignal, addPlugin, composePlugins, createController, createCorePlugin, createFunction, createPaginatedFunction, createPaginatedPluginMethod, createPluginMethod, createPluginStack, createSdk, declareMethod, declareOptionalProperty, declarePlugin, declareProperty, defineFormatter, defineLegacyMerge, defineMethod, defineMethodOverride, defineOverride, definePlugin, defineProperty, defineResolver, disposeSdk, fromFunctionPlugin, getContext, getCoreErrorCause, getCoreErrorCode, getNegatable, getRegistryPlugin, isCoreCancelledSignal, isCoreError, isCoreSignal, isPositional, omitExports, resolvePlugin, runInMethodScope, runWithTelemetryContext, selectExports, toSnakeCase, toTitleCase } from '@zapier/kitcore';
5
5
  import { buildHttpRequestContext, buildActionRunContext } from '@zapier/policy-context';
6
6
  import { ListAppsQuerySchema, AppItemSchema as AppItemSchema$1 } from '@zapier/zapier-sdk-core/v0/schemas/apps';
@@ -12,6 +12,12 @@ var ZAPIER_BASE_URL = globalThis.process?.env?.ZAPIER_BASE_URL || "https://zapie
12
12
  function getZapierSdkService() {
13
13
  return globalThis.process?.env?.ZAPIER_SDK_SERVICE;
14
14
  }
15
+ function getZapierCorrelationId() {
16
+ return globalThis.process?.env?.ZAPIER_CORRELATION_ID || void 0;
17
+ }
18
+ function getZapierCausationId() {
19
+ return globalThis.process?.env?.ZAPIER_CAUSATION_ID || void 0;
20
+ }
15
21
  var MAX_PAGE_LIMIT = 1e4;
16
22
  var DEFAULT_PAGE_SIZE = 100;
17
23
  var DEFAULT_ACTION_TIMEOUT_MILLISECONDS = 18e4;
@@ -705,7 +711,6 @@ function createDebugFetch(options) {
705
711
  // src/utils/retry-utils.ts
706
712
  var MAX_CONSECUTIVE_ERRORS = 3;
707
713
  var BASE_ERROR_BACKOFF_MILLISECONDS = 1e3;
708
- var BASE_EXPONENTIAL_BACKOFF_MILLISECONDS = 1e3;
709
714
  var JITTER_FACTOR = 0.5;
710
715
  function calculateErrorBackoffMs(baseInterval, errorCount) {
711
716
  const jitter = Math.random() * JITTER_FACTOR * baseInterval;
@@ -716,11 +721,6 @@ function calculateErrorBackoffMs(baseInterval, errorCount) {
716
721
  );
717
722
  return Math.floor(baseInterval + jitter + errorBackoff);
718
723
  }
719
- function calculateExponentialBackoffMs(attempt, baseDelayMs = BASE_EXPONENTIAL_BACKOFF_MILLISECONDS) {
720
- const baseDelay = baseDelayMs * Math.pow(2, attempt - 1);
721
- const jitter = Math.random() * JITTER_FACTOR * baseDelay;
722
- return Math.floor(baseDelay + jitter);
723
- }
724
724
  function sleep(ms, signal) {
725
725
  if (!signal) {
726
726
  return new Promise((resolve2) => setTimeout(resolve2, ms));
@@ -1075,7 +1075,114 @@ var sdkOptionsPluginRef = declareOptionalProperty({
1075
1075
  id: SDK_OPTIONS_ID
1076
1076
  });
1077
1077
 
1078
+ // src/api/rate-limit.ts
1079
+ var EPOCH_THRESHOLD_SECONDS = 1e9;
1080
+ function parseRateLimitHeaders(response) {
1081
+ const info = {};
1082
+ const retryAfter = response.headers.get("retry-after");
1083
+ if (retryAfter) {
1084
+ const seconds = parseInt(retryAfter, 10);
1085
+ if (!isNaN(seconds)) {
1086
+ info.retryAfterMs = Math.max(0, seconds * 1e3);
1087
+ } else {
1088
+ const date = Date.parse(retryAfter);
1089
+ if (!isNaN(date)) {
1090
+ info.retryAfterMs = Math.max(0, date - Date.now());
1091
+ }
1092
+ }
1093
+ }
1094
+ const reset = response.headers.get("x-ratelimit-reset");
1095
+ if (reset) {
1096
+ const resetValue = parseInt(reset, 10);
1097
+ if (!isNaN(resetValue)) {
1098
+ const isEpoch = resetValue >= EPOCH_THRESHOLD_SECONDS;
1099
+ info.resetMs = isEpoch ? resetValue * 1e3 : Date.now() + resetValue * 1e3;
1100
+ if (info.retryAfterMs === void 0) {
1101
+ info.retryAfterMs = isEpoch ? Math.max(0, info.resetMs - Date.now()) : Math.max(0, resetValue * 1e3);
1102
+ }
1103
+ }
1104
+ }
1105
+ const limit = response.headers.get("x-ratelimit-limit");
1106
+ if (limit) {
1107
+ const limitNum = parseInt(limit, 10);
1108
+ if (!isNaN(limitNum)) {
1109
+ info.limit = limitNum;
1110
+ }
1111
+ }
1112
+ const remaining = response.headers.get("x-ratelimit-remaining");
1113
+ if (remaining) {
1114
+ const remainingNum = parseInt(remaining, 10);
1115
+ if (!isNaN(remainingNum)) {
1116
+ info.remaining = remainingNum;
1117
+ }
1118
+ }
1119
+ return info;
1120
+ }
1121
+
1122
+ // src/utils/type-guard-utils.ts
1123
+ function isPlainObject(value) {
1124
+ if (typeof value !== "object" || value === null) return false;
1125
+ const proto = Object.getPrototypeOf(value);
1126
+ return proto === Object.prototype || proto === null;
1127
+ }
1128
+ function isPromiseLike(value) {
1129
+ return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
1130
+ }
1131
+
1132
+ // src/plugins/transport/retry-events.ts
1133
+ var retryCounts = /* @__PURE__ */ new WeakMap();
1134
+ function retriesFor(request) {
1135
+ return retryCounts.get(request) ?? 0;
1136
+ }
1137
+ function createRetryObserver({
1138
+ onEvent,
1139
+ maxNetworkRetries
1140
+ }) {
1141
+ return ({ request, attemptNumber, delayMilliseconds, response }) => {
1142
+ retryCounts.set(request, attemptNumber);
1143
+ if (!onEvent || response?.status !== 429) return;
1144
+ const observed = onEvent({
1145
+ type: "api:rate_limit_retry",
1146
+ payload: {
1147
+ retry: attemptNumber,
1148
+ maxNetworkRetries,
1149
+ delayMs: delayMilliseconds,
1150
+ path: request.url,
1151
+ method: request.method ?? "GET",
1152
+ rateLimit: parseRateLimitHeaders(response)
1153
+ },
1154
+ timestamp: Date.now()
1155
+ });
1156
+ if (isPromiseLike(observed)) {
1157
+ void Promise.resolve(observed).catch(() => {
1158
+ });
1159
+ }
1160
+ };
1161
+ }
1162
+
1078
1163
  // src/plugins/transport/options.ts
1164
+ var RETRYABLE_STATUSES = [429, 500, 502, 503, 504];
1165
+ var NON_IDEMPOTENT_RETRYABLE_STATUSES = [429];
1166
+ function resolveRetryHttpRequestOptions({
1167
+ maxNetworkRetries,
1168
+ maxNetworkRetryDelayMilliseconds,
1169
+ onEvent
1170
+ }) {
1171
+ const retries = maxNetworkRetries ?? ZAPIER_MAX_NETWORK_RETRIES;
1172
+ return {
1173
+ maxAttempts: retries + 1,
1174
+ maxDelayMilliseconds: maxNetworkRetryDelayMilliseconds ?? ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS,
1175
+ retryStatuses: RETRYABLE_STATUSES,
1176
+ nonIdempotentRetryStatuses: NON_IDEMPOTENT_RETRYABLE_STATUSES,
1177
+ onRetry: createRetryObserver({ onEvent, maxNetworkRetries: retries })
1178
+ };
1179
+ }
1180
+ function resolveNetworkRetryDelayMilliseconds({
1181
+ maxNetworkRetryDelaySeconds,
1182
+ maxNetworkRetryDelayMs
1183
+ }) {
1184
+ return maxNetworkRetryDelaySeconds != null ? maxNetworkRetryDelaySeconds * 1e3 : maxNetworkRetryDelayMs;
1185
+ }
1079
1186
  function resolveTransportFetch({
1080
1187
  fetch: customFetch,
1081
1188
  debug = false
@@ -1103,15 +1210,29 @@ var httpFetchPlugin = defineProperty({
1103
1210
  // src/plugins/transport/standalone.ts
1104
1211
  function createZapierSendHttpRequest({
1105
1212
  fetch: customFetch,
1106
- debug
1213
+ debug,
1214
+ maxNetworkRetries,
1215
+ maxNetworkRetryDelayMilliseconds,
1216
+ onEvent
1107
1217
  }) {
1108
1218
  const sdk = createSdk(
1109
1219
  definePlugin({
1110
1220
  name: "zapierStandaloneHttpTransport",
1111
- imports: [sendHttpRequestPlugin, httpFetchPlugin],
1221
+ imports: [sendHttpRequestPlugin, retryHttpRequestPlugin, httpFetchPlugin],
1112
1222
  exports: [sendHttpRequestPlugin]
1113
1223
  }),
1114
- { configuration: { [SDK_OPTIONS_ID]: { fetch: customFetch, debug } } }
1224
+ {
1225
+ configuration: {
1226
+ [SDK_OPTIONS_ID]: { fetch: customFetch, debug },
1227
+ // Filled by configuration rather than the graph's property plugin: the
1228
+ // caller here holds client-shaped ms options, not SDK options.
1229
+ [RETRY_HTTP_REQUEST_OPTIONS_ID]: resolveRetryHttpRequestOptions({
1230
+ maxNetworkRetries,
1231
+ maxNetworkRetryDelayMilliseconds,
1232
+ onEvent
1233
+ })
1234
+ }
1235
+ }
1115
1236
  );
1116
1237
  return sdk.sendHttpRequest;
1117
1238
  }
@@ -1120,6 +1241,17 @@ function createZapierSendHttpRequest({
1120
1241
  var CORRELATION_CALL_ID = Symbol(
1121
1242
  "zapier.correlationCallId"
1122
1243
  );
1244
+ function resolveCorrelationId({
1245
+ options,
1246
+ callId
1247
+ }) {
1248
+ return options?.correlationId || getZapierCorrelationId() || callId || void 0;
1249
+ }
1250
+ function resolveCausationId({
1251
+ options
1252
+ }) {
1253
+ return options?.causationId || getZapierCausationId();
1254
+ }
1123
1255
  var ClientCredentialsObjectSchema = z.object({
1124
1256
  type: z.enum(["client_credentials"]).optional().meta({ internal: true }),
1125
1257
  clientId: z.string().describe("OAuth client ID for authentication.").meta({ valueHint: "id" }),
@@ -1769,13 +1901,6 @@ async function invalidateCredentialsToken(options) {
1769
1901
  });
1770
1902
  }
1771
1903
  }
1772
-
1773
- // src/utils/type-guard-utils.ts
1774
- function isPlainObject(value) {
1775
- if (typeof value !== "object" || value === null) return false;
1776
- const proto = Object.getPrototypeOf(value);
1777
- return proto === Object.prototype || proto === null;
1778
- }
1779
1904
  var callerContext = createAsyncContext();
1780
1905
  function runWithCallerContext(context, fn) {
1781
1906
  let parent;
@@ -2021,9 +2146,6 @@ function sniffDeprecationNotice({
2021
2146
  }
2022
2147
  }
2023
2148
  }
2024
- function isPromiseLike(value) {
2025
- return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
2026
- }
2027
2149
  function parseDeprecationDate(value) {
2028
2150
  if (!value) return void 0;
2029
2151
  const match = /^@(-?\d+)$/.exec(value.trim());
@@ -2552,7 +2674,7 @@ function logRouteOverride({
2552
2674
  }
2553
2675
 
2554
2676
  // src/sdk-version.ts
2555
- var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.103.0" : void 0) || "unknown";
2677
+ var SDK_VERSION = (typeof process !== "undefined" && process.env ? "0.105.0" : void 0) || "unknown";
2556
2678
 
2557
2679
  // src/utils/open-url.ts
2558
2680
  var nodePrefix = "node:";
@@ -2668,7 +2790,6 @@ var PollApprovalResponseSchema = z.object({
2668
2790
  approval_url: z.string().optional()
2669
2791
  });
2670
2792
  var APPROVAL_MAX_POLLING_INTERVAL_MILLISECONDS = 5e3;
2671
- var EPOCH_THRESHOLD_SECONDS = 1e9;
2672
2793
  function validateSdkPath(path) {
2673
2794
  if (!path.startsWith("/") || path.startsWith("//")) {
2674
2795
  throw new ZapierValidationError(
@@ -2676,57 +2797,17 @@ function validateSdkPath(path) {
2676
2797
  );
2677
2798
  }
2678
2799
  }
2679
- function parseRateLimitHeaders(response) {
2680
- const info = {};
2681
- const retryAfter = response.headers.get("retry-after");
2682
- if (retryAfter) {
2683
- const seconds = parseInt(retryAfter, 10);
2684
- if (!isNaN(seconds)) {
2685
- info.retryAfterMs = seconds * 1e3;
2686
- } else {
2687
- const date = Date.parse(retryAfter);
2688
- if (!isNaN(date)) {
2689
- info.retryAfterMs = Math.max(0, date - Date.now());
2690
- }
2691
- }
2692
- }
2693
- const reset = response.headers.get("x-ratelimit-reset");
2694
- if (reset) {
2695
- const resetValue = parseInt(reset, 10);
2696
- if (!isNaN(resetValue)) {
2697
- const isEpoch = resetValue >= EPOCH_THRESHOLD_SECONDS;
2698
- info.resetMs = isEpoch ? resetValue * 1e3 : Date.now() + resetValue * 1e3;
2699
- if (info.retryAfterMs === void 0) {
2700
- info.retryAfterMs = isEpoch ? Math.max(0, info.resetMs - Date.now()) : Math.max(0, resetValue * 1e3);
2701
- }
2702
- }
2703
- }
2704
- const limit = response.headers.get("x-ratelimit-limit");
2705
- if (limit) {
2706
- const limitNum = parseInt(limit, 10);
2707
- if (!isNaN(limitNum)) {
2708
- info.limit = limitNum;
2709
- }
2710
- }
2711
- const remaining = response.headers.get("x-ratelimit-remaining");
2712
- if (remaining) {
2713
- const remainingNum = parseInt(remaining, 10);
2714
- if (!isNaN(remainingNum)) {
2715
- info.remaining = remainingNum;
2716
- }
2717
- }
2718
- return info;
2719
- }
2720
2800
  var ZapierApiClient = class {
2721
2801
  constructor(options) {
2722
2802
  this.options = options;
2723
2803
  /**
2724
2804
  * Perform a request against an already-resolved URL.
2725
2805
  *
2726
- * Does auth, header merging, and 429 retry all the cross-cutting
2727
- * concerns that every Zapier-bound HTTP call needs. Callers that have a
2728
- * path (e.g. `/relay/...`) should use `rawFetch` instead, which does
2729
- * path URL resolution and delegates here.
2806
+ * Does auth and header merging, and converts a terminal 429 into
2807
+ * `ZapierRateLimitError` the cross-cutting concerns that every
2808
+ * Zapier-bound HTTP call needs and that the transport does not own. Callers
2809
+ * that have a path (e.g. `/relay/...`) should use `rawFetch` instead, which
2810
+ * does path → URL resolution and delegates here.
2730
2811
  *
2731
2812
  * Exposed as a separate helper so call sites with a server-supplied
2732
2813
  * absolute URL (e.g. an approval poll URL) can still share the same
@@ -2760,47 +2841,30 @@ var ZapierApiClient = class {
2760
2841
  resource: _resource,
2761
2842
  ...wireInit
2762
2843
  } = fetchInit;
2763
- let retries = 0;
2764
- while (true) {
2765
- const response = await this.options.sendHttpRequest({
2766
- ...wireInit,
2767
- // Set the resolved URL and merged headers after the spread so caller
2768
- // values cannot override them.
2769
- url,
2770
- headers: Object.fromEntries(mergedHeaders)
2771
- });
2772
- if (response.status !== 429) {
2773
- return response;
2774
- }
2775
- const rateLimitInfo = parseRateLimitHeaders(response);
2776
- const delayMs = rateLimitInfo.retryAfterMs ?? calculateExponentialBackoffMs(retries + 1);
2777
- if (delayMs > this.maxNetworkRetryDelayMilliseconds || retries >= this.maxNetworkRetries) {
2778
- throw new ZapierRateLimitError(
2779
- await this.readRateLimitErrorMessage(response),
2780
- {
2781
- statusCode: 429,
2782
- rateLimit: rateLimitInfo,
2783
- retries
2784
- }
2785
- );
2786
- }
2787
- retries++;
2788
- this.emitEvent("api:rate_limit_retry", {
2789
- retry: retries,
2790
- maxNetworkRetries: this.maxNetworkRetries,
2791
- delayMs,
2792
- path: url,
2793
- method: init?.method ?? "GET",
2794
- rateLimit: rateLimitInfo
2795
- });
2796
- await sleep(delayMs, init?.signal ?? void 0);
2844
+ const request = {
2845
+ ...wireInit,
2846
+ url,
2847
+ headers: Object.fromEntries(mergedHeaders)
2848
+ };
2849
+ const response = await this.options.sendHttpRequest(request);
2850
+ if (response.status !== 429) {
2851
+ return response;
2797
2852
  }
2853
+ throw new ZapierRateLimitError(
2854
+ await this.readRateLimitErrorMessage(response),
2855
+ {
2856
+ statusCode: 429,
2857
+ rateLimit: parseRateLimitHeaders(response),
2858
+ retries: retriesFor(request)
2859
+ }
2860
+ );
2798
2861
  };
2799
2862
  /**
2800
2863
  * Wrap an outbound HTTP call with the concurrency semaphore. Used by both
2801
2864
  * `rawFetch` (path-based) and the approval-poll path (absolute URL); each
2802
- * caller acquires per-attempt, so 429 retry sleep is held but the gap
2803
- * between approval polls and the human-approval wait are not.
2865
+ * caller acquires per request, so the transport's retry sleeps are held
2866
+ * inside the permit but the gap between approval polls and the
2867
+ * human-approval wait are not.
2804
2868
  *
2805
2869
  * The release is registered in a finally that wraps the entire post-
2806
2870
  * acquire flow — including the `wait_end` event emission — so a throwing
@@ -3050,8 +3114,6 @@ var ZapierApiClient = class {
3050
3114
  signal: options.signal
3051
3115
  });
3052
3116
  };
3053
- this.maxNetworkRetries = options.maxNetworkRetries ?? ZAPIER_MAX_NETWORK_RETRIES;
3054
- this.maxNetworkRetryDelayMilliseconds = options.maxNetworkRetryDelayMilliseconds ?? options.maxNetworkRetryDelayMs ?? ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS;
3055
3117
  const requested = options.maxConcurrentRequests;
3056
3118
  const limit = requested === void 0 || Number.isNaN(requested) ? ZAPIER_MAX_CONCURRENT_REQUESTS : requested;
3057
3119
  if (limit !== Infinity && (!Number.isInteger(limit) || limit < 1 || limit > MAX_CONCURRENCY_LIMIT)) {
@@ -3341,11 +3403,21 @@ var ZapierApiClient = class {
3341
3403
  headers.set("zapier-sdk-package-operation", packageOperation);
3342
3404
  }
3343
3405
  }
3344
- if (callId) {
3345
- headers.set("zapier-correlation-id", callId);
3406
+ const correlationId = resolveCorrelationId({
3407
+ options: this.options,
3408
+ callId
3409
+ });
3410
+ if (correlationId) {
3411
+ headers.set("zapier-correlation-id", correlationId);
3346
3412
  } else {
3347
3413
  headers.delete("zapier-correlation-id");
3348
3414
  }
3415
+ const causationId = resolveCausationId({ options: this.options });
3416
+ if (causationId) {
3417
+ headers.set("zapier-causation-id", causationId);
3418
+ } else {
3419
+ headers.delete("zapier-causation-id");
3420
+ }
3349
3421
  }
3350
3422
  // Helper to perform HTTP requests with JSON handling
3351
3423
  async fetchJson(method, path, data, options = {}) {
@@ -3807,7 +3879,13 @@ var createZapierApi = (options) => {
3807
3879
  fetch: debugFetch,
3808
3880
  // Built from the caller's own `fetch`, not `debugFetch`: the pipeline wraps
3809
3881
  // for debug itself, and passing the wrapped one would log twice.
3810
- sendHttpRequest: options.sendHttpRequest ?? createZapierSendHttpRequest({ fetch: options.fetch, debug }),
3882
+ sendHttpRequest: options.sendHttpRequest ?? createZapierSendHttpRequest({
3883
+ fetch: options.fetch,
3884
+ debug,
3885
+ onEvent: options.onEvent,
3886
+ maxNetworkRetries: options.maxNetworkRetries,
3887
+ maxNetworkRetryDelayMilliseconds: options.maxNetworkRetryDelayMilliseconds ?? options.maxNetworkRetryDelayMs
3888
+ }),
3811
3889
  debugLog,
3812
3890
  routingOptions
3813
3891
  });
@@ -3846,10 +3924,30 @@ function getOrCreateApiClient(config) {
3846
3924
  callerPackage
3847
3925
  });
3848
3926
  }
3927
+ var retryHttpRequestOptionsPlugin = defineProperty({
3928
+ namespace: "kitcore",
3929
+ name: "retryHttpRequestOptions",
3930
+ imports: [sdkOptionsPluginRef],
3931
+ setup: ({ imports }) => resolveRetryHttpRequestOptions({
3932
+ maxNetworkRetries: imports.sdkOptions?.maxNetworkRetries,
3933
+ maxNetworkRetryDelayMilliseconds: resolveNetworkRetryDelayMilliseconds(
3934
+ imports.sdkOptions ?? {}
3935
+ ),
3936
+ onEvent: imports.sdkOptions?.onEvent
3937
+ }),
3938
+ get: ({ state }) => state
3939
+ });
3940
+
3941
+ // src/plugins/transport/index.ts
3849
3942
  var zapierHttpTransportPlugin = definePlugin({
3850
3943
  namespace: "zapier",
3851
3944
  name: "httpTransport",
3852
- imports: [sendHttpRequestPlugin, httpFetchPlugin],
3945
+ imports: [
3946
+ sendHttpRequestPlugin,
3947
+ retryHttpRequestPlugin,
3948
+ retryHttpRequestOptionsPlugin,
3949
+ httpFetchPlugin
3950
+ ],
3853
3951
  exports: [sendHttpRequestPlugin]
3854
3952
  });
3855
3953
 
@@ -3899,7 +3997,9 @@ var apiPlugin = defineProperty({
3899
3997
  approvalMode,
3900
3998
  openAutoModeApprovalsInBrowser,
3901
3999
  callerPackage,
3902
- routeOverrides
4000
+ routeOverrides,
4001
+ correlationId,
4002
+ causationId
3903
4003
  } = imports.sdkOptions ?? {};
3904
4004
  return createZapierApi({
3905
4005
  baseUrl,
@@ -3909,7 +4009,10 @@ var apiPlugin = defineProperty({
3909
4009
  fetch: customFetch,
3910
4010
  onEvent,
3911
4011
  maxNetworkRetries,
3912
- maxNetworkRetryDelayMilliseconds: (maxNetworkRetryDelaySeconds != null ? maxNetworkRetryDelaySeconds * 1e3 : maxNetworkRetryDelayMs) ?? ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS,
4012
+ maxNetworkRetryDelayMilliseconds: resolveNetworkRetryDelayMilliseconds({
4013
+ maxNetworkRetryDelaySeconds,
4014
+ maxNetworkRetryDelayMs
4015
+ }) ?? ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS,
3913
4016
  maxConcurrentRequests,
3914
4017
  approvalTimeoutMilliseconds: approvalTimeoutSeconds != null ? approvalTimeoutSeconds * 1e3 : approvalTimeoutMs,
3915
4018
  maxApprovalRetries,
@@ -3919,7 +4022,12 @@ var apiPlugin = defineProperty({
3919
4022
  routeOverrides,
3920
4023
  // Inject the graph-composed transport so host `dispatchHttpRequest` wraps
3921
4024
  // apply.
3922
- sendHttpRequest: imports.sendHttpRequest
4025
+ sendHttpRequest: imports.sendHttpRequest,
4026
+ // Pass through unresolved so `resolveCorrelationId` / `resolveCausationId`
4027
+ // do the option-then-env-var chain at request time — the same helper the
4028
+ // event-emission hook calls, so header and MethodCalledEvent stay aligned.
4029
+ correlationId,
4030
+ causationId
3923
4031
  });
3924
4032
  },
3925
4033
  get: ({ state, callContext }) => callContext?.callId ? withCorrelationId({ client: state, callId: callContext.callId }) : state
@@ -11678,7 +11786,7 @@ function computeArgumentCount(args) {
11678
11786
  }
11679
11787
  return args.filter((a) => a !== void 0).length;
11680
11788
  }
11681
- function makeMethodEndHook(emitMethodCalled) {
11789
+ function makeMethodEndHook(emitMethodCalled, { sdkOptions } = {}) {
11682
11790
  return ({
11683
11791
  methodName,
11684
11792
  args,
@@ -11694,9 +11802,9 @@ function makeMethodEndHook(emitMethodCalled) {
11694
11802
  const metadata = readMethodMetadata(annotations);
11695
11803
  emitMethodCalled({
11696
11804
  method_name: methodName,
11697
- // The per-call correlation id (also the `zapier-correlation-id` header on
11698
- // this call's requests). Not the `call_context` surface label.
11699
- correlation_id: callId ?? null,
11805
+ // Same resolution as the `zapier-correlation-id` header: SDK option >
11806
+ // env var > per-call kitcore id. Not the `call_context` surface label.
11807
+ correlation_id: resolveCorrelationId({ options: sdkOptions, callId }) ?? null,
11700
11808
  execution_duration_ms: durationMs,
11701
11809
  success_flag: !error,
11702
11810
  error_message: error?.message ?? null,
@@ -12090,17 +12198,20 @@ var eventEmissionPlugin = defineProperty({
12090
12198
  var eventEmissionHookPlugin = defineHook({
12091
12199
  namespace: "zapier",
12092
12200
  name: "eventEmissionHook",
12093
- imports: [eventEmissionPlugin],
12201
+ imports: [eventEmissionPlugin, sdkOptionsPluginRef],
12094
12202
  observe: {
12095
12203
  onMethodEnd: ({ imports, input }) => {
12096
12204
  if (input.methodName === "getRegistry") return;
12097
- const emitter = imports.eventEmission;
12098
- makeMethodEndHook((data) => {
12099
- emitter.emit(METHOD_CALLED_EVENT_SUBJECT, {
12100
- ...buildMethodCalledEvent(data),
12101
- call_context: emitter.config.callContext ?? "sdk"
12102
- });
12103
- })(input);
12205
+ const { eventEmission: emitter, sdkOptions } = imports;
12206
+ makeMethodEndHook(
12207
+ (data) => {
12208
+ emitter.emit(METHOD_CALLED_EVENT_SUBJECT, {
12209
+ ...buildMethodCalledEvent(data),
12210
+ call_context: emitter.config.callContext ?? "sdk"
12211
+ });
12212
+ },
12213
+ { sdkOptions }
12214
+ )(input);
12104
12215
  }
12105
12216
  }
12106
12217
  });
@@ -12314,17 +12425,20 @@ var BaseSdkOptionsSchema = z.object({
12314
12425
  routeOverrides: z.record(z.string(), z.string()).optional().describe("Maps SDK route prefixes to direct origins.").meta({ internal: true }),
12315
12426
  trackingBaseUrl: z.string().optional().describe("Base URL for Zapier tracking endpoints.").meta({ valueHint: "url" }),
12316
12427
  /**
12317
- * Maximum number of retries for rate-limited requests (429 responses).
12428
+ * Maximum number of retries for rate-limited requests (429 responses) and,
12429
+ * on idempotent methods, retryable server errors (500, 502, 503, 504).
12318
12430
  * Set to 0 to disable retries. Default is 3.
12319
12431
  */
12320
- maxNetworkRetries: z.number().optional().describe("Max retries for rate-limited requests (default: 3).").meta({ valueHint: "count" }),
12432
+ maxNetworkRetries: z.number().optional().describe(
12433
+ "Max retries for rate-limited and server-error responses (default: 3)."
12434
+ ).meta({ valueHint: "count" }),
12321
12435
  /**
12322
- * Maximum delay in seconds to wait for a rate-limit retry.
12436
+ * Maximum delay in seconds to wait between network retries.
12323
12437
  * If the server requests a longer delay, the request fails immediately.
12324
12438
  * Default is 60 (60 seconds).
12325
12439
  */
12326
12440
  maxNetworkRetryDelaySeconds: z.number().optional().describe(
12327
- "Max delay in seconds to wait for a rate-limit retry (default: 60)."
12441
+ "Max delay in seconds to wait between network retries (default: 60)."
12328
12442
  ).meta({ valueHint: "seconds" }),
12329
12443
  /** @deprecated Use `maxNetworkRetryDelaySeconds` instead. */
12330
12444
  maxNetworkRetryDelayMs: z.number().optional().describe("Max delay in ms to wait for retry (default: 60000).").meta({ valueHint: "ms", deprecated: true }),
@@ -12358,6 +12472,12 @@ var BaseSdkOptionsSchema = z.object({
12358
12472
  openAutoModeApprovalsInBrowser: z.boolean().optional().describe(
12359
12473
  "By default, auto-mode approvals do not open in a browser. Enable this option to open the approval URL and watch the approval process. Resolution order is: explicit option, then ZAPIER_OPEN_AUTO_MODE_APPROVALS_IN_BROWSER, then false."
12360
12474
  ),
12475
+ correlationId: z.string().optional().describe(
12476
+ "Correlation ID for request tracing. When set, emitted as the `zapier-correlation-id` header on every outbound request. Falls back to the ZAPIER_CORRELATION_ID environment variable."
12477
+ ).meta({ valueHint: "id" }),
12478
+ causationId: z.string().optional().describe(
12479
+ "Causation ID for request tracing. When set, emitted as the `zapier-causation-id` header on every outbound request. Falls back to the ZAPIER_CAUSATION_ID environment variable."
12480
+ ).meta({ valueHint: "id" }),
12361
12481
  // Internal
12362
12482
  manifestPath: z.string().optional().describe("Path to a .zapierrc manifest file for app version locking.").meta({ internal: true }),
12363
12483
  manifest: z.custom().optional().describe("Manifest for app version locking.").meta({ internal: true }),
@@ -12382,4 +12502,4 @@ var registryPlugin = (_sdk) => {
12382
12502
  return {};
12383
12503
  };
12384
12504
 
12385
- export { ACTION_RUNS_PATH, API_ID, ActionKeyPropertySchema, ActionPropertySchema, ActionTimeoutMillisecondsPropertySchema, ActionTimeoutSecondsPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppPropertySchema, AppsPropertySchema, AuthMechanism, AuthenticationIdPropertySchema, BaseSdkOptionsSchema, CONNECTIONS_ID, CONTEXT_CACHE_MAX_SIZE, CONTEXT_CACHE_TTL_MILLISECONDS, ClientCredentialsObjectSchema, ConnectionEntrySchema, ConnectionIdPropertySchema, ConnectionPropertySchema, ConnectionsMapSchema, ConnectionsPropertySchema, CredentialsFunctionSchema, CredentialsObjectSchema, CredentialsSchema, DEFAULT_ACTION_TIMEOUT_MILLISECONDS, DEFAULT_APPROVAL_TIMEOUT_MILLISECONDS, DEFAULT_CONFIG_PATH, DEFAULT_MAX_APPROVAL_RETRIES, DEFAULT_PAGE_SIZE, DEPRECATION_NOTICE_EVENT, DebugPropertySchema, DrainTriggerInboxSchema, EVENT_EMISSION_ID, FieldsPropertySchema, InputFieldPropertySchema, InputsPropertySchema, LeaseLimitPropertySchema, LeasePropertySchema, LeaseSecondsPropertySchema, LimitPropertySchema, MANIFEST_ID, MAX_CONCURRENCY_LIMIT, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, PkceCredentialsObjectSchema, RESOLVE_CREDENTIALS_ID, RecordPropertySchema, RecordsPropertySchema, RelayFetchSchema, RelayRequestSchema, ResolvedCredentialsSchema, SDK_OPTIONS_ID, TablePropertySchema, TablesPropertySchema, TriggerInboxKeyPropertySchema, TriggerInboxNamePropertySchema, TriggerInboxPropertySchema, WatchTriggerInboxSchema, ZAPIER_BASE_URL, ZAPIER_MAX_CONCURRENT_REQUESTS, ZAPIER_MAX_NETWORK_RETRIES, ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS, ZapierAbortDrainSignal, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierApprovalError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierConflictError, ZapierError, ZapierNotFoundError, ZapierRateLimitError, ZapierRelayError, ZapierReleaseTriggerMessageSignal, ZapierResourceNotFoundError, ZapierSignal, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, apiPlugin, apiPluginRef, appKeyResolver, appsPlugin, batch, buildApplicationLifecycleEvent, buildCapabilityMessage, buildErrorEvent, buildErrorEventWithContext, buildMethodCalledEvent, cleanupEventListeners, clearTokenCache, clientCredentialsNameResolver, clientIdResolver, connectionIdGenericResolver, connectionIdResolver, connectionsPlugin, connectionsPluginRef, createActionRunPlugin, createBaseEvent, createClientCredentialsPlugin, createMemoryCache, createTableFieldsPlugin, createTablePlugin, createTableRecordsPlugin, createZapierApi, createZapierSdk, createZapierSdkWithoutRegistry, deleteClientCredentialsPlugin, deleteTableFieldsPlugin, deleteTablePlugin, deleteTableRecordsPlugin, durableRunIdResolver, eventEmissionHookPlugin, eventEmissionPlugin, eventEmissionPluginRef, extractErrorDetail, fetchPlugin, findFirstConnectionPlugin, findManifestEntry, findUniqueConnectionPlugin, formatErrorMessage, generateEventId, getActionInputFieldsSchemaPlugin, getActionPlugin, getActionRunPlugin, getAgent, getAppPlugin, getBaseUrlFromCredentials, getCallerContext, getCiPlatform, getClientIdFromCredentials, getConnectionPlugin, getCpuTime, getCurrentTimestamp, getMemoryUsage, getOrCreateApiClient, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getReleaseId, getTablePlugin, getTableRecordPlugin, getTokenFromCliLogin, getTtyContext, getZapierApprovalMode, getZapierDefaultApprovalMode, getZapierOpenAutoModeApprovalsInBrowser, getZapierSdkService, injectCliLogin, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, invalidateCachedToken, invalidateCredentialsToken, isCi, isCliLoginAvailable, isClientCredentials, isCredentialsFunction, isCredentialsObject, isPermanentHttpError, isPkceCredentials, isZapierAbortDrainSignal, isZapierActionError, isZapierAppNotFoundError, isZapierApprovalError, isZapierAuthenticationError, isZapierBundleError, isZapierConflictError, isZapierError, isZapierNotFoundError, isZapierRateLimitError, isZapierReleaseTriggerMessageSignal, isZapierResourceNotFoundError, isZapierSignal, isZapierTimeoutError, isZapierValidationError, listActionInputFieldChoicesPlugin, listActionInputFieldsPlugin, listActionsPlugin, listAppsPlugin, listClientCredentialsPlugin, listConnectionsPlugin, listTableFieldsPlugin, listTableRecordsPlugin, listTablesPlugin, logDeprecation, manifestPlugin, manifestPluginRef, operationAnnotatorPlugin, parseConcurrencyEnvVar, readManifestFromFile, registryPlugin, requestPlugin, resetDeprecationWarnings, resolveAuth, resolveAuthToken, resolveCredentials, resolveCredentialsFromEnv, resolveCredentialsPlugin, resolveCredentialsPluginRef, runActionPlugin, runWithCallerContext, sdkOptionsPluginRef, tableFieldIdsResolver, tableFieldsResolver, tableFiltersResolver, tableIdResolver, tableNameResolver, tableRecordIdResolver, tableRecordIdsResolver, tableRecordsResolver, tableSortResolver, tableUpdateRecordsResolver, triggerInboxResolver, triggerMessagesResolver, updateTableRecordsPlugin, workflowDraftIdResolver, workflowIdResolver, workflowRunIdResolver, workflowVersionIdResolver, zapierAdaptError, zapierCoreOptions, zapierSdkPlugin };
12505
+ export { ACTION_RUNS_PATH, API_ID, ActionKeyPropertySchema, ActionPropertySchema, ActionTimeoutMillisecondsPropertySchema, ActionTimeoutSecondsPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppPropertySchema, AppsPropertySchema, AuthMechanism, AuthenticationIdPropertySchema, BaseSdkOptionsSchema, CONNECTIONS_ID, CONTEXT_CACHE_MAX_SIZE, CONTEXT_CACHE_TTL_MILLISECONDS, ClientCredentialsObjectSchema, ConnectionEntrySchema, ConnectionIdPropertySchema, ConnectionPropertySchema, ConnectionsMapSchema, ConnectionsPropertySchema, CredentialsFunctionSchema, CredentialsObjectSchema, CredentialsSchema, DEFAULT_ACTION_TIMEOUT_MILLISECONDS, DEFAULT_APPROVAL_TIMEOUT_MILLISECONDS, DEFAULT_CONFIG_PATH, DEFAULT_MAX_APPROVAL_RETRIES, DEFAULT_PAGE_SIZE, DEPRECATION_NOTICE_EVENT, DebugPropertySchema, DrainTriggerInboxSchema, EVENT_EMISSION_ID, FieldsPropertySchema, InputFieldPropertySchema, InputsPropertySchema, LeaseLimitPropertySchema, LeasePropertySchema, LeaseSecondsPropertySchema, LimitPropertySchema, MANIFEST_ID, MAX_CONCURRENCY_LIMIT, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, PkceCredentialsObjectSchema, RESOLVE_CREDENTIALS_ID, RecordPropertySchema, RecordsPropertySchema, RelayFetchSchema, RelayRequestSchema, ResolvedCredentialsSchema, SDK_OPTIONS_ID, TablePropertySchema, TablesPropertySchema, TriggerInboxKeyPropertySchema, TriggerInboxNamePropertySchema, TriggerInboxPropertySchema, WatchTriggerInboxSchema, ZAPIER_BASE_URL, ZAPIER_MAX_CONCURRENT_REQUESTS, ZAPIER_MAX_NETWORK_RETRIES, ZAPIER_MAX_NETWORK_RETRY_DELAY_MILLISECONDS, ZapierAbortDrainSignal, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierApprovalError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierConflictError, ZapierError, ZapierNotFoundError, ZapierRateLimitError, ZapierRelayError, ZapierReleaseTriggerMessageSignal, ZapierResourceNotFoundError, ZapierSignal, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, apiPlugin, apiPluginRef, appKeyResolver, appsPlugin, batch, buildApplicationLifecycleEvent, buildCapabilityMessage, buildErrorEvent, buildErrorEventWithContext, buildMethodCalledEvent, cleanupEventListeners, clearTokenCache, clientCredentialsNameResolver, clientIdResolver, connectionIdGenericResolver, connectionIdResolver, connectionsPlugin, connectionsPluginRef, createActionRunPlugin, createBaseEvent, createClientCredentialsPlugin, createMemoryCache, createTableFieldsPlugin, createTablePlugin, createTableRecordsPlugin, createZapierApi, createZapierSdk, createZapierSdkWithoutRegistry, deleteClientCredentialsPlugin, deleteTableFieldsPlugin, deleteTablePlugin, deleteTableRecordsPlugin, durableRunIdResolver, eventEmissionHookPlugin, eventEmissionPlugin, eventEmissionPluginRef, extractErrorDetail, fetchPlugin, findFirstConnectionPlugin, findManifestEntry, findUniqueConnectionPlugin, formatErrorMessage, generateEventId, getActionInputFieldsSchemaPlugin, getActionPlugin, getActionRunPlugin, getAgent, getAppPlugin, getBaseUrlFromCredentials, getCallerContext, getCiPlatform, getClientIdFromCredentials, getConnectionPlugin, getCpuTime, getCurrentTimestamp, getMemoryUsage, getOrCreateApiClient, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getReleaseId, getTablePlugin, getTableRecordPlugin, getTokenFromCliLogin, getTtyContext, getZapierApprovalMode, getZapierCausationId, getZapierCorrelationId, getZapierDefaultApprovalMode, getZapierOpenAutoModeApprovalsInBrowser, getZapierSdkService, injectCliLogin, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, invalidateCachedToken, invalidateCredentialsToken, isCi, isCliLoginAvailable, isClientCredentials, isCredentialsFunction, isCredentialsObject, isPermanentHttpError, isPkceCredentials, isZapierAbortDrainSignal, isZapierActionError, isZapierAppNotFoundError, isZapierApprovalError, isZapierAuthenticationError, isZapierBundleError, isZapierConflictError, isZapierError, isZapierNotFoundError, isZapierRateLimitError, isZapierReleaseTriggerMessageSignal, isZapierResourceNotFoundError, isZapierSignal, isZapierTimeoutError, isZapierValidationError, listActionInputFieldChoicesPlugin, listActionInputFieldsPlugin, listActionsPlugin, listAppsPlugin, listClientCredentialsPlugin, listConnectionsPlugin, listTableFieldsPlugin, listTableRecordsPlugin, listTablesPlugin, logDeprecation, manifestPlugin, manifestPluginRef, operationAnnotatorPlugin, parseConcurrencyEnvVar, readManifestFromFile, registryPlugin, requestPlugin, resetDeprecationWarnings, resolveAuth, resolveAuthToken, resolveCredentials, resolveCredentialsFromEnv, resolveCredentialsPlugin, resolveCredentialsPluginRef, runActionPlugin, runWithCallerContext, sdkOptionsPluginRef, tableFieldIdsResolver, tableFieldsResolver, tableFiltersResolver, tableIdResolver, tableNameResolver, tableRecordIdResolver, tableRecordIdsResolver, tableRecordsResolver, tableSortResolver, tableUpdateRecordsResolver, triggerInboxResolver, triggerMessagesResolver, updateTableRecordsPlugin, workflowDraftIdResolver, workflowIdResolver, workflowRunIdResolver, workflowVersionIdResolver, zapierAdaptError, zapierCoreOptions, zapierSdkPlugin };