@zapier/zapier-sdk 0.42.1 → 0.44.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +75 -73
  3. package/dist/api/client.d.ts.map +1 -1
  4. package/dist/api/client.js +309 -35
  5. package/dist/api/types.d.ts +29 -0
  6. package/dist/api/types.d.ts.map +1 -1
  7. package/dist/constants.d.ts +25 -0
  8. package/dist/constants.d.ts.map +1 -1
  9. package/dist/constants.js +32 -0
  10. package/dist/index.cjs +441 -44
  11. package/dist/index.d.mts +82 -4
  12. package/dist/index.mjs +437 -45
  13. package/dist/plugins/api/index.d.ts.map +1 -1
  14. package/dist/plugins/api/index.js +5 -1
  15. package/dist/plugins/createClientCredentials/index.d.ts.map +1 -1
  16. package/dist/plugins/createClientCredentials/index.js +1 -0
  17. package/dist/plugins/createClientCredentials/schemas.d.ts +1 -0
  18. package/dist/plugins/createClientCredentials/schemas.d.ts.map +1 -1
  19. package/dist/plugins/createClientCredentials/schemas.js +6 -0
  20. package/dist/plugins/fetch/index.d.ts.map +1 -1
  21. package/dist/plugins/fetch/index.js +15 -1
  22. package/dist/plugins/getInputFieldsSchema/schemas.js +1 -1
  23. package/dist/plugins/listInputFieldChoices/schemas.js +1 -1
  24. package/dist/plugins/listInputFields/schemas.js +1 -1
  25. package/dist/plugins/manifest/schemas.d.ts +2 -2
  26. package/dist/plugins/runAction/index.d.ts.map +1 -1
  27. package/dist/plugins/runAction/index.js +12 -1
  28. package/dist/plugins/runAction/schemas.js +1 -1
  29. package/dist/types/connections.d.ts +2 -2
  30. package/dist/types/connections.d.ts.map +1 -1
  31. package/dist/types/connections.js +5 -3
  32. package/dist/types/errors.d.ts +37 -0
  33. package/dist/types/errors.d.ts.map +1 -1
  34. package/dist/types/errors.js +18 -0
  35. package/dist/types/properties.js +1 -1
  36. package/dist/types/sdk.d.ts +7 -0
  37. package/dist/types/sdk.d.ts.map +1 -1
  38. package/dist/types/sdk.js +20 -0
  39. package/dist/utils/open-approval.d.ts +2 -0
  40. package/dist/utils/open-approval.d.ts.map +1 -0
  41. package/dist/utils/open-approval.js +13 -0
  42. package/dist/utils/open-url.d.ts +3 -0
  43. package/dist/utils/open-url.d.ts.map +1 -0
  44. package/dist/utils/open-url.js +72 -0
  45. package/package.json +3 -1
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import { buildHttpRequestContext, buildActionRunContext } from '@zapier/policy-context';
2
3
  import { ListAppsQuerySchema, AppItemSchema as AppItemSchema$1 } from '@zapier/zapier-sdk-core/v0/schemas/apps';
3
4
  import { ListConnectionsQuerySchema as ListConnectionsQuerySchema$1, ConnectionItemSchema as ConnectionItemSchema$1 } from '@zapier/zapier-sdk-core/v0/schemas/connections';
4
5
  import { ListClientCredentialsQuerySchema as ListClientCredentialsQuerySchema$1, CreateClientCredentialsRequestSchema, ClientCredentialsItemSchema as ClientCredentialsItemSchema$1, ClientCredentialsCreatedItemSchema as ClientCredentialsCreatedItemSchema$1 } from '@zapier/zapier-sdk-core/v0/schemas/client-credentials';
@@ -56,6 +57,16 @@ function parseIntEnvVar(name) {
56
57
  }
57
58
  var ZAPIER_MAX_NETWORK_RETRIES = parseIntEnvVar("ZAPIER_MAX_NETWORK_RETRIES") ?? 3;
58
59
  var ZAPIER_MAX_NETWORK_RETRY_DELAY_MS = parseIntEnvVar("ZAPIER_MAX_NETWORK_RETRY_DELAY_MS") ?? 6e4;
60
+ function getZapierIsInteractive() {
61
+ return globalThis.process?.env?.ZAPIER_IS_INTERACTIVE === "true";
62
+ }
63
+ function getZapierApprovalMode() {
64
+ const value = globalThis.process?.env?.ZAPIER_APPROVAL_MODE;
65
+ if (value === "poll" || value === "fail") return value;
66
+ return void 0;
67
+ }
68
+ var DEFAULT_APPROVAL_TIMEOUT_MS = 10 * 60 * 1e3;
69
+ var DEFAULT_MAX_APPROVAL_RETRIES = 2;
59
70
 
60
71
  // src/types/properties.ts
61
72
  var AppKeyPropertySchema = withPositional(
@@ -88,7 +99,7 @@ var AuthenticationIdPropertySchema = ConnectionIdPropertySchema.meta({
88
99
  deprecated: true
89
100
  });
90
101
  var ConnectionPropertySchema = z.union([z.string(), z.number().int().positive()]).describe(
91
- "Connection alias (string) or numeric connectionId. Strings are resolved from the connections map; numbers are used directly."
102
+ "Connection alias or connection ID (UUID or positive integer). Strings that match a key in the connections map are resolved against it; otherwise the value is used as a connection ID directly."
92
103
  );
93
104
  var InputsPropertySchema = z.record(z.string(), z.unknown()).describe("Input parameters for the action");
94
105
  var LimitPropertySchema = z.number().int().min(1).max(MAX_PAGE_LIMIT).default(50).describe("Maximum number of items to return");
@@ -224,6 +235,17 @@ var ZapierRateLimitError = class extends ZapierError {
224
235
  this.retries = options.retries ?? 0;
225
236
  }
226
237
  };
238
+ var ZapierApprovalError = class extends ZapierError {
239
+ constructor(message, options = {}) {
240
+ super(message, options);
241
+ this.name = "ZapierApprovalError";
242
+ this.code = "ZAPIER_APPROVAL_ERROR";
243
+ this.approvalId = options.approvalId;
244
+ this.approvalStatus = options.status;
245
+ this.approvalUrl = options.approvalUrl;
246
+ this.pollUrl = options.pollUrl;
247
+ }
248
+ };
227
249
  var ZapierRelayError = class extends ZapierError {
228
250
  constructor(message, options = {}) {
229
251
  super(message, options);
@@ -268,6 +290,10 @@ ${context.join(", ")}`;
268
290
  if (error instanceof ZapierBundleError && error.buildErrors && error.buildErrors.length > 0) {
269
291
  message += "\n\nBuild errors:\n" + error.buildErrors.map((err) => ` \u2022 ${err}`).join("\n");
270
292
  }
293
+ if (error instanceof ZapierApprovalError && error.approvalUrl) {
294
+ message += `
295
+ Approval URL: ${error.approvalUrl}`;
296
+ }
271
297
  if (error instanceof ZapierRateLimitError) {
272
298
  const { limit, remaining, retryAfterMs } = error.rateLimit;
273
299
  const parts = [];
@@ -975,18 +1001,27 @@ var fetchPlugin = (sdk) => {
975
1001
  if (maxTime !== void 0) {
976
1002
  headers["X-Zapier-Sdk-Max-Time"] = String(maxTime);
977
1003
  }
1004
+ const upstreamUrl = new URL(url).toString();
1005
+ const method = (fetchInit.method ?? "GET").toUpperCase();
978
1006
  const abortHandle = buildAbortHandle({
979
1007
  maxTimeSeconds: maxTime,
980
1008
  callerSignal: fetchInit.signal
981
1009
  });
982
1010
  try {
983
1011
  const result = await api.fetch(relayPath, {
984
- method: fetchInit.method ?? "GET",
1012
+ method,
985
1013
  body: fetchInit.body,
986
1014
  headers,
987
1015
  redirect: fetchInit.redirect,
988
1016
  signal: abortHandle?.signal,
989
- authRequired: true
1017
+ authRequired: true,
1018
+ approvalContext: () => buildHttpRequestContext({
1019
+ method,
1020
+ url: upstreamUrl,
1021
+ headers,
1022
+ body: typeof fetchInit.body === "string" ? fetchInit.body : void 0,
1023
+ connection_id: resolvedConnectionId ? String(resolvedConnectionId) : void 0
1024
+ })
990
1025
  });
991
1026
  const relayError = result.headers.get("x-relay-error");
992
1027
  if (relayError) {
@@ -2976,7 +3011,7 @@ var listActionsPlugin = (sdk) => {
2976
3011
  var ListInputFieldsDescription = "Get the input fields required for a specific action";
2977
3012
  var ListInputFieldsBaseSchema = z.object({
2978
3013
  connection: ConnectionPropertySchema.optional().describe(
2979
- "Connection alias (string) or numeric connectionId. Strings are resolved from the connections map; numbers are used directly. Mutually exclusive with connectionId."
3014
+ "Connection alias or connection ID (UUID or positive integer). Strings that match a key in the connections map are resolved against it; otherwise the value is used as a connection ID directly. Mutually exclusive with connectionId."
2980
3015
  ),
2981
3016
  connectionId: ConnectionIdPropertySchema.nullable().optional().describe(
2982
3017
  "Connection ID to use when listing input fields. Required if the action needs a connection to determine available fields."
@@ -3672,7 +3707,9 @@ var listClientCredentialsPlugin = (sdk) => {
3672
3707
  };
3673
3708
  };
3674
3709
  var CreateClientCredentialsSchema = CreateClientCredentialsRequestSchema.omit({ allowed_scopes: true }).extend({
3675
- allowedScopes: z.array(z.enum(["credentials", "external"])).default(["external"]).describe("Scopes to allow for these credentials")
3710
+ allowedScopes: z.array(z.enum(["credentials", "external"])).default(["external"]).describe("Scopes to allow for these credentials"),
3711
+ // Temporarily hidden while we finalise work to make approvals/policies customer-facing.
3712
+ policy: z.record(z.string(), z.unknown()).optional().describe("Policy document (JSON) to attach to the credentials").meta({ deprecated: true })
3676
3713
  }).describe("Create new client credentials for the authenticated user");
3677
3714
 
3678
3715
  // src/plugins/createClientCredentials/index.ts
@@ -3683,7 +3720,8 @@ var createClientCredentialsPlugin = (sdk) => {
3683
3720
  "/api/v0/client-credentials",
3684
3721
  {
3685
3722
  name: options.name,
3686
- allowed_scopes: options.allowedScopes
3723
+ allowed_scopes: options.allowedScopes,
3724
+ ...options.policy && { policy: options.policy }
3687
3725
  },
3688
3726
  {
3689
3727
  customErrorHandler: ({ status }) => {
@@ -4073,7 +4111,7 @@ var findUniqueConnectionPlugin = (sdk) => {
4073
4111
  var RunActionDescription = "Execute an action with the given inputs";
4074
4112
  var RunActionBaseSchema = z.object({
4075
4113
  connection: ConnectionPropertySchema.optional().describe(
4076
- "Connection alias (string) or numeric connectionId. Strings are resolved from the connections map; numbers are used directly. Mutually exclusive with connectionId."
4114
+ "Connection alias or connection ID (UUID or positive integer). Strings that match a key in the connections map are resolved against it; otherwise the value is used as a connection ID directly. Mutually exclusive with connectionId."
4077
4115
  ),
4078
4116
  connectionId: ConnectionIdPropertySchema.nullable().optional().describe(
4079
4117
  "Connection ID to use when running the action. Required if the action needs a connection to authenticate and interact with the service."
@@ -4106,8 +4144,6 @@ var RunActionSchemaDeprecated = z.object({
4106
4144
  actionKey: ActionKeyPropertySchema
4107
4145
  }).merge(RunActionBaseSchema);
4108
4146
  var RunActionInputSchema = z.union([RunActionSchema, RunActionSchemaDeprecated]).describe(RunActionDescription);
4109
-
4110
- // src/plugins/runAction/index.ts
4111
4147
  async function executeAction(actionOptions) {
4112
4148
  const {
4113
4149
  api,
@@ -4138,7 +4174,18 @@ async function executeAction(actionOptions) {
4138
4174
  };
4139
4175
  const runData = await api.post(
4140
4176
  "/zapier/api/actions/v1/runs",
4141
- runRequest
4177
+ runRequest,
4178
+ {
4179
+ approvalContext: () => buildActionRunContext({
4180
+ selected_api: selectedApi,
4181
+ action_type: actionType,
4182
+ action_key: actionKey,
4183
+ connection_id: connectionId != null ? String(connectionId) : void 0,
4184
+ // Cast: inputs is Record<string, unknown> at the SDK surface, but
4185
+ // buildActionRunContext coerces to JsonValue at runtime via zod.
4186
+ inputs: executionOptions.inputs ?? {}
4187
+ })
4188
+ }
4142
4189
  );
4143
4190
  const runId = runData.data.id;
4144
4191
  return await api.poll(`/zapier/api/actions/v1/runs/${runId}`, {
@@ -4443,8 +4490,12 @@ async function readFile(filePath) {
4443
4490
  }
4444
4491
  throw new Error(`File not found: ${filePath}`);
4445
4492
  }
4493
+ var POSITIVE_INTEGER_OR_UUID = /^([1-9][0-9]*|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
4446
4494
  var ConnectionEntrySchema = z.object({
4447
- connectionId: z.number().int().positive().describe("Zapier connection ID for the third-party service.")
4495
+ connectionId: z.union([
4496
+ z.string().regex(POSITIVE_INTEGER_OR_UUID),
4497
+ z.number().int().positive()
4498
+ ]).describe("Zapier connection ID for the third-party service.")
4448
4499
  });
4449
4500
  var ConnectionsMapSchema = z.record(z.string(), ConnectionEntrySchema);
4450
4501
 
@@ -5687,7 +5738,89 @@ async function invalidateCredentialsToken(options) {
5687
5738
  }
5688
5739
  }
5689
5740
 
5690
- // src/api/client.ts
5741
+ // src/utils/open-url.ts
5742
+ var nodePrefix = "node:";
5743
+ async function loadChildProcess() {
5744
+ return import(`${nodePrefix}child_process`);
5745
+ }
5746
+ async function loadProcess() {
5747
+ return import(`${nodePrefix}process`);
5748
+ }
5749
+ var openUrl = async (url) => {
5750
+ if (typeof url !== "string") {
5751
+ throw new TypeError("Expected `url` to be a string");
5752
+ }
5753
+ let parsed;
5754
+ try {
5755
+ parsed = new URL(url);
5756
+ } catch {
5757
+ throw new Error(`Invalid URL: ${url}`);
5758
+ }
5759
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
5760
+ throw new Error(`Refusing to open non-http(s) URL: ${parsed.protocol}`);
5761
+ }
5762
+ const target = parsed.toString();
5763
+ if (typeof globalThis.window !== "undefined" && typeof globalThis.window.open === "function") {
5764
+ globalThis.window.open(target, "_blank", "noopener");
5765
+ return;
5766
+ }
5767
+ let spawn;
5768
+ let platform;
5769
+ try {
5770
+ const [cp, proc] = await Promise.all([loadChildProcess(), loadProcess()]);
5771
+ spawn = cp.spawn;
5772
+ platform = proc.platform;
5773
+ } catch {
5774
+ throw new Error(
5775
+ "openUrl: no supported runtime. window.open is unavailable and node:child_process could not be loaded."
5776
+ );
5777
+ }
5778
+ if (typeof spawn !== "function") {
5779
+ throw new Error(
5780
+ "openUrl: child_process.spawn is not available in this runtime"
5781
+ );
5782
+ }
5783
+ let command;
5784
+ let args;
5785
+ if (platform === "darwin") {
5786
+ command = "open";
5787
+ args = [target];
5788
+ } else if (platform === "win32") {
5789
+ command = "rundll32";
5790
+ args = ["url.dll,FileProtocolHandler", target];
5791
+ } else {
5792
+ throw new Error(`Unsupported platform: ${platform}`);
5793
+ }
5794
+ const child = spawn(command, args, {
5795
+ stdio: "ignore",
5796
+ detached: true,
5797
+ windowsHide: true
5798
+ });
5799
+ child.once("error", () => {
5800
+ });
5801
+ child.unref();
5802
+ };
5803
+ var open_url_default = openUrl;
5804
+
5805
+ // src/utils/open-approval.ts
5806
+ async function openApproval(url) {
5807
+ console.error(`Approval required. Opening browser: ${url}`);
5808
+ try {
5809
+ await open_url_default(url);
5810
+ } catch {
5811
+ }
5812
+ }
5813
+ var ApprovalStatusSchema = z.enum(["pending_approval", "approved", "denied"]);
5814
+ var CreateApprovalResponseSchema = z.object({
5815
+ status: ApprovalStatusSchema,
5816
+ approval_id: z.string(),
5817
+ approval_url: z.string().url(),
5818
+ poll_url: z.string().url()
5819
+ });
5820
+ var PollApprovalResponseSchema = z.object({
5821
+ status: ApprovalStatusSchema,
5822
+ approval_id: z.string()
5823
+ });
5691
5824
  function parseRateLimitHeaders(response) {
5692
5825
  const info = {};
5693
5826
  const retryAfter = response.headers.get("retry-after");
@@ -5748,16 +5881,23 @@ var pathConfig = {
5748
5881
  var ZapierApiClient = class {
5749
5882
  constructor(options) {
5750
5883
  this.options = options;
5751
- this.fetch = async (path, init) => {
5752
- if (!path.startsWith("/")) {
5753
- throw new ZapierValidationError(
5754
- `fetch expects a path starting with '/', got: ${path}`
5755
- );
5756
- }
5884
+ /**
5885
+ * Perform a request against an already-resolved URL.
5886
+ *
5887
+ * Does auth, header merging, and 429 retry — all the cross-cutting
5888
+ * concerns that every Zapier-bound HTTP call needs. Callers that have a
5889
+ * path (e.g. `/relay/...`) should use `rawFetch` instead, which does
5890
+ * path → URL resolution and delegates here.
5891
+ *
5892
+ * Exposed as a separate helper so call sites with a server-supplied
5893
+ * absolute URL (e.g. an approval poll URL) can still share the same
5894
+ * auth/retry pipeline instead of reaching for `this.options.fetch`
5895
+ * directly and drifting.
5896
+ */
5897
+ this.rawFetchUrl = async (url, init, pathConfig2) => {
5757
5898
  if (init?.body && (isPlainObject(init.body) || Array.isArray(init.body))) {
5758
5899
  init.body = JSON.stringify(init.body);
5759
5900
  }
5760
- const { url, pathConfig: pathConfig2 } = this.buildUrl(path, init?.searchParams);
5761
5901
  const builtHeaders = await this.buildHeaders(
5762
5902
  init,
5763
5903
  pathConfig2
@@ -5776,30 +5916,114 @@ var ZapierApiClient = class {
5776
5916
  ...init,
5777
5917
  headers: mergedHeaders
5778
5918
  });
5779
- if (response.status === 429) {
5780
- const rateLimitInfo = parseRateLimitHeaders(response);
5781
- const delayMs = rateLimitInfo.retryAfterMs ?? calculateExponentialBackoffMs(retries + 1);
5782
- if (delayMs > this.maxNetworkRetryDelayMs || retries >= this.maxNetworkRetries) {
5783
- throw new ZapierRateLimitError("Rate limited", {
5784
- statusCode: 429,
5785
- rateLimit: rateLimitInfo,
5786
- retries
5787
- });
5788
- }
5789
- retries++;
5790
- this.emitEvent("api:rate_limit_retry", {
5791
- retry: retries,
5792
- maxNetworkRetries: this.maxNetworkRetries,
5793
- delayMs,
5794
- path,
5795
- method: init?.method ?? "GET",
5796
- rateLimit: rateLimitInfo
5919
+ if (response.status !== 429) {
5920
+ return response;
5921
+ }
5922
+ const rateLimitInfo = parseRateLimitHeaders(response);
5923
+ const delayMs = rateLimitInfo.retryAfterMs ?? calculateExponentialBackoffMs(retries + 1);
5924
+ if (delayMs > this.maxNetworkRetryDelayMs || retries >= this.maxNetworkRetries) {
5925
+ throw new ZapierRateLimitError("Rate limited", {
5926
+ statusCode: 429,
5927
+ rateLimit: rateLimitInfo,
5928
+ retries
5929
+ });
5930
+ }
5931
+ retries++;
5932
+ this.emitEvent("api:rate_limit_retry", {
5933
+ retry: retries,
5934
+ maxNetworkRetries: this.maxNetworkRetries,
5935
+ delayMs,
5936
+ path: url,
5937
+ method: init?.method ?? "GET",
5938
+ rateLimit: rateLimitInfo
5939
+ });
5940
+ await sleep(delayMs);
5941
+ }
5942
+ };
5943
+ /**
5944
+ * Perform a request with auth, header merging, and rate-limit (429) retries.
5945
+ * Does NOT handle 403 approval_required — that's routed by `fetch`.
5946
+ */
5947
+ this.rawFetch = async (path, init) => {
5948
+ if (!path.startsWith("/")) {
5949
+ throw new ZapierValidationError(
5950
+ `fetch expects a path starting with '/', got: ${path}`
5951
+ );
5952
+ }
5953
+ const { url, pathConfig: pathConfig2 } = this.buildUrl(path, init?.searchParams);
5954
+ return this.rawFetchUrl(url, init, pathConfig2);
5955
+ };
5956
+ /**
5957
+ * Approval-aware HTTP fetch.
5958
+ *
5959
+ * Wraps `rawFetch` with the backend's just-in-time approval protocol. The
5960
+ * backend signals approval state via a 403 response with an
5961
+ * `x-zapier-error-type` header:
5962
+ *
5963
+ * - `request_denied_by_policy` → a policy rule permanently blocks the
5964
+ * request; no human can approve it. Throw.
5965
+ * - `approval_required` → the request needs human approval; the
5966
+ * SDK creates an approval, opens the URL
5967
+ * (poll mode), waits for resolution, and
5968
+ * retries the original request.
5969
+ * - anything else → not our concern, pass through.
5970
+ *
5971
+ * The retry loop exists because a single user action can legitimately
5972
+ * require multiple sequential approvals (e.g. policies that approve one
5973
+ * step at a time). Each iteration is either a first attempt or a post-
5974
+ * approval retry; `maxApprovalRetries` bounds the loop as a runaway-loop
5975
+ * safeguard.
5976
+ *
5977
+ * Loop accounting: `attempt` counts rawFetch calls, not approval rounds.
5978
+ * With `maxRetries = N` we perform up to `N + 1` rawFetch calls and at
5979
+ * most `N` approval rounds. The `attempt === maxRetries` guard ensures we
5980
+ * don't run an (N+1)th approval round we'll never consume — if the final
5981
+ * retry still returns `approval_required`, we break out and throw
5982
+ * `max_retries_exceeded` instead.
5983
+ */
5984
+ this.fetch = async (path, init) => {
5985
+ const maxRetries = this.options.maxApprovalRetries ?? DEFAULT_MAX_APPROVAL_RETRIES;
5986
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
5987
+ const response = await this.rawFetch(path, init);
5988
+ if (response.status !== 403) return response;
5989
+ const errorType = response.headers.get("x-zapier-error-type");
5990
+ if (errorType === "request_denied_by_policy") {
5991
+ const { data } = await this.parseResult(response);
5992
+ const { message, errors } = this.parseErrorResponse({
5993
+ status: response.status,
5994
+ statusText: response.statusText,
5995
+ data
5797
5996
  });
5798
- await sleep(delayMs);
5799
- continue;
5997
+ throw new ZapierApprovalError(
5998
+ message || "Request explicitly denied by policy",
5999
+ {
6000
+ status: "policy_denied",
6001
+ statusCode: response.status,
6002
+ errors
6003
+ }
6004
+ );
6005
+ }
6006
+ if (errorType !== "approval_required") return response;
6007
+ if (attempt === maxRetries) break;
6008
+ const isInteractive = this.options.isInteractive ?? getZapierIsInteractive();
6009
+ if (!isInteractive) {
6010
+ throw new ZapierApprovalError(
6011
+ "Approval required but session is not interactive",
6012
+ { status: "approval_required" }
6013
+ );
6014
+ }
6015
+ if (!init?.approvalContext) {
6016
+ throw new ZapierApiError(
6017
+ `Received 403 approval_required for ${path}, but the caller did not provide an approvalContext builder. Every approval-capable request must pass approvalContext so the SDK can create the approval with the correct policy context.`,
6018
+ { statusCode: 403 }
6019
+ );
5800
6020
  }
5801
- return response;
6021
+ await this.runOneApprovalRound(init.approvalContext);
5802
6022
  }
6023
+ throw new ZapierApprovalError(
6024
+ `Exceeded maximum approval retries (${maxRetries}) for ${path}`,
6025
+ { status: "max_retries_exceeded" }
6026
+ );
5803
6027
  };
5804
6028
  this.get = async (path, options = {}) => {
5805
6029
  return this.fetchJson("GET", path, void 0, options);
@@ -6084,6 +6308,156 @@ var ZapierApiClient = class {
6084
6308
  }
6085
6309
  return result;
6086
6310
  }
6311
+ /**
6312
+ * Run a single approval round: create the approval, open the URL (poll mode)
6313
+ * or throw (fail mode), poll until resolved, and emit events. Throws on
6314
+ * denied/timeout/unexpected status. Returns on approved.
6315
+ */
6316
+ async runOneApprovalRound(buildContext) {
6317
+ const context = buildContext();
6318
+ let approvalResponse;
6319
+ try {
6320
+ approvalResponse = await this.rawFetch("/api/v0/approvals", {
6321
+ method: "POST",
6322
+ headers: {
6323
+ "Content-Type": "application/json",
6324
+ Accept: "application/json"
6325
+ },
6326
+ body: JSON.stringify({ context })
6327
+ });
6328
+ } catch (err) {
6329
+ throw new ZapierApiError("Failed to create approval request", {
6330
+ statusCode: 0,
6331
+ cause: err
6332
+ });
6333
+ }
6334
+ if (!approvalResponse.ok) {
6335
+ const body2 = await approvalResponse.text().catch(() => void 0);
6336
+ throw new ZapierApiError(
6337
+ `Failed to create approval request: ${approvalResponse.status}`,
6338
+ { statusCode: approvalResponse.status, response: body2 }
6339
+ );
6340
+ }
6341
+ let body;
6342
+ try {
6343
+ body = await approvalResponse.text();
6344
+ } catch (err) {
6345
+ throw new ZapierApiError("Failed to read approval response body", {
6346
+ statusCode: approvalResponse.status,
6347
+ cause: err
6348
+ });
6349
+ }
6350
+ let approval;
6351
+ try {
6352
+ approval = CreateApprovalResponseSchema.parse(JSON.parse(body));
6353
+ } catch (err) {
6354
+ throw new ZapierApiError(`Failed to parse approval response: ${body}`, {
6355
+ statusCode: approvalResponse.status,
6356
+ cause: err,
6357
+ response: body
6358
+ });
6359
+ }
6360
+ const sdkapiOrigin = new URL(this.buildUrl("/api/v0/approvals").url).origin;
6361
+ const browserOrigin = getZapierBaseUrl(this.options.baseUrl) ?? sdkapiOrigin;
6362
+ const assertApprovalOrigin = (url, expectedOrigin, label) => {
6363
+ let parsed;
6364
+ try {
6365
+ parsed = new URL(url);
6366
+ } catch {
6367
+ throw new ZapierApiError(`Invalid approval ${label}: ${url}`, {
6368
+ statusCode: approvalResponse.status,
6369
+ response: body
6370
+ });
6371
+ }
6372
+ if (parsed.origin !== expectedOrigin) {
6373
+ throw new ZapierApiError(
6374
+ `Approval ${label} origin ${parsed.origin} does not match expected ${expectedOrigin}`,
6375
+ { statusCode: approvalResponse.status, response: body }
6376
+ );
6377
+ }
6378
+ };
6379
+ assertApprovalOrigin(approval.poll_url, sdkapiOrigin, "poll_url");
6380
+ assertApprovalOrigin(approval.approval_url, browserOrigin, "approval_url");
6381
+ this.emitEvent("approval:required", {
6382
+ approvalId: approval.approval_id,
6383
+ approvalUrl: approval.approval_url
6384
+ });
6385
+ const approvalMode = this.options.approvalMode ?? getZapierApprovalMode();
6386
+ if (approvalMode === "fail") {
6387
+ throw new ZapierApprovalError("This request requires approval.", {
6388
+ approvalId: approval.approval_id,
6389
+ approvalUrl: approval.approval_url,
6390
+ pollUrl: approval.poll_url,
6391
+ status: "pending"
6392
+ });
6393
+ }
6394
+ await openApproval(approval.approval_url);
6395
+ const timeoutMs = this.options.approvalTimeoutMs ?? DEFAULT_APPROVAL_TIMEOUT_MS;
6396
+ let rawPollResult;
6397
+ try {
6398
+ rawPollResult = await pollUntilComplete({
6399
+ // poll_url is an absolute URL supplied by the server, so we use
6400
+ // rawFetchUrl directly (skipping path resolution) but still share
6401
+ // auth + interactive-header + 429-retry with the rest of the SDK.
6402
+ fetchPoll: () => this.rawFetchUrl(approval.poll_url, {
6403
+ method: "GET",
6404
+ headers: { Accept: "application/json" }
6405
+ }),
6406
+ timeoutMs,
6407
+ isPending: (body2) => {
6408
+ const parsed = PollApprovalResponseSchema.safeParse(body2);
6409
+ return parsed.success && parsed.data.status === "pending_approval";
6410
+ }
6411
+ });
6412
+ } catch (err) {
6413
+ if (!(err instanceof ZapierTimeoutError)) {
6414
+ throw err;
6415
+ }
6416
+ this.emitEvent("approval:timeout", {
6417
+ approvalId: approval.approval_id
6418
+ });
6419
+ throw new ZapierApprovalError(
6420
+ `Approval timed out after ${timeoutMs / 1e3} seconds`,
6421
+ {
6422
+ approvalId: approval.approval_id,
6423
+ approvalUrl: approval.approval_url,
6424
+ pollUrl: approval.poll_url,
6425
+ status: "timeout",
6426
+ cause: err
6427
+ }
6428
+ );
6429
+ }
6430
+ const pollParse = PollApprovalResponseSchema.safeParse(rawPollResult);
6431
+ if (!pollParse.success) {
6432
+ const bodyPreview = typeof rawPollResult === "string" ? rawPollResult : JSON.stringify(rawPollResult);
6433
+ throw new ZapierApiError(
6434
+ `Failed to parse approval poll response: ${bodyPreview}`,
6435
+ {
6436
+ statusCode: 0,
6437
+ cause: pollParse.error,
6438
+ response: rawPollResult
6439
+ }
6440
+ );
6441
+ }
6442
+ const pollResult = pollParse.data;
6443
+ if (pollResult.status === "denied") {
6444
+ this.emitEvent("approval:denied", {
6445
+ approvalId: approval.approval_id
6446
+ });
6447
+ throw new ZapierApprovalError("Request denied by user", {
6448
+ approvalId: approval.approval_id,
6449
+ status: "denied"
6450
+ });
6451
+ }
6452
+ if (pollResult.status !== "approved") {
6453
+ throw new ZapierApiError(
6454
+ `Unexpected approval status received: ${pollResult.status}`
6455
+ );
6456
+ }
6457
+ this.emitEvent("approval:approved", {
6458
+ approvalId: approval.approval_id
6459
+ });
6460
+ }
6087
6461
  };
6088
6462
  var createZapierApi = (options) => {
6089
6463
  const { debug = false, fetch: originalFetch = globalThis.fetch } = options;
@@ -6106,7 +6480,11 @@ var apiPlugin = (sdk) => {
6106
6480
  onEvent,
6107
6481
  debug = false,
6108
6482
  maxNetworkRetries = ZAPIER_MAX_NETWORK_RETRIES,
6109
- maxNetworkRetryDelayMs = ZAPIER_MAX_NETWORK_RETRY_DELAY_MS
6483
+ maxNetworkRetryDelayMs = ZAPIER_MAX_NETWORK_RETRY_DELAY_MS,
6484
+ isInteractive,
6485
+ approvalTimeoutMs,
6486
+ maxApprovalRetries,
6487
+ approvalMode
6110
6488
  } = sdk.context.options;
6111
6489
  const api = createZapierApi({
6112
6490
  baseUrl,
@@ -6116,7 +6494,11 @@ var apiPlugin = (sdk) => {
6116
6494
  fetch: customFetch,
6117
6495
  onEvent,
6118
6496
  maxNetworkRetries,
6119
- maxNetworkRetryDelayMs
6497
+ maxNetworkRetryDelayMs,
6498
+ isInteractive,
6499
+ approvalTimeoutMs,
6500
+ maxApprovalRetries,
6501
+ approvalMode
6120
6502
  });
6121
6503
  return {
6122
6504
  context: {
@@ -7671,7 +8053,7 @@ var findUniqueAuthenticationPlugin = (sdk) => ({
7671
8053
  var GetInputFieldsSchemaDescription = "Get the JSON Schema representation of input fields for an action. Returns a JSON Schema object describing the structure, types, and validation rules for the action's input parameters.";
7672
8054
  var GetInputFieldsSchemaBaseSchema = z.object({
7673
8055
  connection: ConnectionPropertySchema.optional().describe(
7674
- "Connection alias (string) or numeric connectionId. Strings are resolved from the connections map; numbers are used directly. Mutually exclusive with connectionId."
8056
+ "Connection alias or connection ID (UUID or positive integer). Strings that match a key in the connections map are resolved against it; otherwise the value is used as a connection ID directly. Mutually exclusive with connectionId."
7675
8057
  ),
7676
8058
  connectionId: ConnectionIdPropertySchema.nullable().optional().describe(
7677
8059
  "Connection ID to use when fetching the schema. Required if the action needs a connection to determine available fields."
@@ -7809,7 +8191,7 @@ var InputFieldChoiceItemSchema = withFormatter(NeedChoicesSchema, {
7809
8191
  var ListInputFieldChoicesDescription = "Get the available choices for a dynamic dropdown input field";
7810
8192
  var ListInputFieldChoicesBaseSchema = z.object({
7811
8193
  connection: ConnectionPropertySchema.optional().describe(
7812
- "Connection alias (string) or numeric connectionId. Strings are resolved from the connections map; numbers are used directly. Mutually exclusive with connectionId."
8194
+ "Connection alias or connection ID (UUID or positive integer). Strings that match a key in the connections map are resolved against it; otherwise the value is used as a connection ID directly. Mutually exclusive with connectionId."
7813
8195
  ),
7814
8196
  connectionId: ConnectionIdPropertySchema.nullable().optional().describe(
7815
8197
  "Connection ID to use when listing available field choices. Required if the action needs a connection to populate dynamic dropdown options."
@@ -8668,6 +9050,16 @@ var BaseSdkOptionsSchema = z.object({
8668
9050
  * Default is 60000 (60 seconds).
8669
9051
  */
8670
9052
  maxNetworkRetryDelayMs: z.number().optional().describe("Max delay in ms to wait for retry (default: 60000).").meta({ valueHint: "ms" }),
9053
+ isInteractive: z.boolean().optional().describe(
9054
+ "Whether this session is interactive (user can visit approval URLs). Defaults to ZAPIER_IS_INTERACTIVE env var."
9055
+ ).meta({ internal: true }),
9056
+ approvalTimeoutMs: z.number().optional().describe("Timeout in ms for approval polling. Default: 600000 (10 min).").meta({ valueHint: "ms", internal: true }),
9057
+ maxApprovalRetries: z.number().optional().describe(
9058
+ "Maximum number of sequential approval rounds per request (one per gating policy) before giving up. Default: 2."
9059
+ ).meta({ internal: true }),
9060
+ approvalMode: z.enum(["poll", "fail"]).optional().describe(
9061
+ 'Approval flow behavior. "poll" opens browser and polls (default). "fail" creates the approval and throws immediately with the approval URL.'
9062
+ ).meta({ internal: true }),
8671
9063
  // Internal
8672
9064
  manifestPath: z.string().optional().describe("Path to a .zapierrc manifest file for app version locking.").meta({ internal: true }),
8673
9065
  manifest: z.custom().optional().describe("Manifest for app version locking.").meta({ internal: true }),
@@ -8682,4 +9074,4 @@ var BaseSdkOptionsSchema = z.object({
8682
9074
  // Use credentials instead
8683
9075
  });
8684
9076
 
8685
- export { ActionKeyPropertySchema, ActionPropertySchema, ActionTimeoutMsPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppPropertySchema, AppsPropertySchema, AuthenticationIdPropertySchema, BaseSdkOptionsSchema, CONTEXT_CACHE_MAX_SIZE, CONTEXT_CACHE_TTL_MS, ClientCredentialsObjectSchema, ConnectionEntrySchema, ConnectionIdPropertySchema, ConnectionPropertySchema, ConnectionsMapSchema, ConnectionsPropertySchema, CredentialsFunctionSchema, CredentialsObjectSchema, CredentialsSchema, DEFAULT_ACTION_TIMEOUT_MS, DEFAULT_CONFIG_PATH, DEFAULT_PAGE_SIZE, DebugPropertySchema, FieldsPropertySchema, InputFieldPropertySchema, InputsPropertySchema, LimitPropertySchema, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, PkceCredentialsObjectSchema, RecordPropertySchema, RecordsPropertySchema, RelayFetchSchema, RelayRequestSchema, ResolvedCredentialsSchema, TablePropertySchema, TablesPropertySchema, ZAPIER_BASE_URL, ZAPIER_MAX_NETWORK_RETRIES, ZAPIER_MAX_NETWORK_RETRY_DELAY_MS, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierError, ZapierNotFoundError, ZapierRateLimitError, ZapierRelayError, ZapierResourceNotFoundError, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, apiPlugin, appKeyResolver, appsPlugin, connectionIdGenericResolver as authenticationIdGenericResolver, connectionIdResolver as authenticationIdResolver, batch, buildApplicationLifecycleEvent, buildCapabilityMessage, buildErrorEvent, buildErrorEventWithContext, buildMethodCalledEvent, clearTokenCache, clientCredentialsNameResolver, clientIdResolver, connectionIdGenericResolver, connectionIdResolver, connectionsPlugin, createBaseEvent, createClientCredentialsPlugin, createFunction, createOptionsPlugin, createSdk, createTableFieldsPlugin, createTablePlugin, createTableRecordsPlugin, createZapierSdk, createZapierSdkWithoutRegistry, deleteClientCredentialsPlugin, deleteTableFieldsPlugin, deleteTablePlugin, deleteTableRecordsPlugin, fetchPlugin, findFirstConnectionPlugin, findManifestEntry, findUniqueConnectionPlugin, formatErrorMessage, generateEventId, getActionPlugin, getAppPlugin, getBaseUrlFromCredentials, getCiPlatform, getClientIdFromCredentials, getConnectionPlugin, getCpuTime, getCurrentTimestamp, getMemoryUsage, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getReleaseId, getTablePlugin, getTableRecordPlugin, getTokenFromCliLogin, injectCliLogin, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, invalidateCachedToken, invalidateCredentialsToken, isCi, isCliLoginAvailable, isClientCredentials, isCredentialsFunction, isCredentialsObject, isPkceCredentials, isPositional, listActionsPlugin, listAppsPlugin, listClientCredentialsPlugin, listConnectionsPlugin, listInputFieldsPlugin, listTableFieldsPlugin, listTableRecordsPlugin, listTablesPlugin, logDeprecation, manifestPlugin, readManifestFromFile, registryPlugin, requestPlugin, resetDeprecationWarnings, resolveAuthToken, resolveCredentials, resolveCredentialsFromEnv, runActionPlugin, runWithTelemetryContext, tableFieldIdsResolver, tableFieldsResolver, tableFiltersResolver, tableIdResolver, tableNameResolver, tableRecordIdResolver, tableRecordIdsResolver, tableRecordsResolver, tableSortResolver, tableUpdateRecordsResolver, toSnakeCase, toTitleCase, updateTableRecordsPlugin };
9077
+ export { ActionKeyPropertySchema, ActionPropertySchema, ActionTimeoutMsPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AppPropertySchema, AppsPropertySchema, AuthenticationIdPropertySchema, BaseSdkOptionsSchema, CONTEXT_CACHE_MAX_SIZE, CONTEXT_CACHE_TTL_MS, ClientCredentialsObjectSchema, ConnectionEntrySchema, ConnectionIdPropertySchema, ConnectionPropertySchema, ConnectionsMapSchema, ConnectionsPropertySchema, CredentialsFunctionSchema, CredentialsObjectSchema, CredentialsSchema, DEFAULT_ACTION_TIMEOUT_MS, DEFAULT_APPROVAL_TIMEOUT_MS, DEFAULT_CONFIG_PATH, DEFAULT_MAX_APPROVAL_RETRIES, DEFAULT_PAGE_SIZE, DebugPropertySchema, FieldsPropertySchema, InputFieldPropertySchema, InputsPropertySchema, LimitPropertySchema, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, PkceCredentialsObjectSchema, RecordPropertySchema, RecordsPropertySchema, RelayFetchSchema, RelayRequestSchema, ResolvedCredentialsSchema, TablePropertySchema, TablesPropertySchema, ZAPIER_BASE_URL, ZAPIER_MAX_NETWORK_RETRIES, ZAPIER_MAX_NETWORK_RETRY_DELAY_MS, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierApprovalError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierError, ZapierNotFoundError, ZapierRateLimitError, ZapierRelayError, ZapierResourceNotFoundError, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, apiPlugin, appKeyResolver, appsPlugin, connectionIdGenericResolver as authenticationIdGenericResolver, connectionIdResolver as authenticationIdResolver, batch, buildApplicationLifecycleEvent, buildCapabilityMessage, buildErrorEvent, buildErrorEventWithContext, buildMethodCalledEvent, clearTokenCache, clientCredentialsNameResolver, clientIdResolver, connectionIdGenericResolver, connectionIdResolver, connectionsPlugin, createBaseEvent, createClientCredentialsPlugin, createFunction, createOptionsPlugin, createSdk, createTableFieldsPlugin, createTablePlugin, createTableRecordsPlugin, createZapierSdk, createZapierSdkWithoutRegistry, deleteClientCredentialsPlugin, deleteTableFieldsPlugin, deleteTablePlugin, deleteTableRecordsPlugin, fetchPlugin, findFirstConnectionPlugin, findManifestEntry, findUniqueConnectionPlugin, formatErrorMessage, generateEventId, getActionPlugin, getAppPlugin, getBaseUrlFromCredentials, getCiPlatform, getClientIdFromCredentials, getConnectionPlugin, getCpuTime, getCurrentTimestamp, getMemoryUsage, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getReleaseId, getTablePlugin, getTableRecordPlugin, getTokenFromCliLogin, getZapierApprovalMode, getZapierIsInteractive, injectCliLogin, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, invalidateCachedToken, invalidateCredentialsToken, isCi, isCliLoginAvailable, isClientCredentials, isCredentialsFunction, isCredentialsObject, isPkceCredentials, isPositional, listActionsPlugin, listAppsPlugin, listClientCredentialsPlugin, listConnectionsPlugin, listInputFieldsPlugin, listTableFieldsPlugin, listTableRecordsPlugin, listTablesPlugin, logDeprecation, manifestPlugin, readManifestFromFile, registryPlugin, requestPlugin, resetDeprecationWarnings, resolveAuthToken, resolveCredentials, resolveCredentialsFromEnv, runActionPlugin, runWithTelemetryContext, tableFieldIdsResolver, tableFieldsResolver, tableFiltersResolver, tableIdResolver, tableNameResolver, tableRecordIdResolver, tableRecordIdsResolver, tableRecordsResolver, tableSortResolver, tableUpdateRecordsResolver, toSnakeCase, toTitleCase, updateTableRecordsPlugin };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/plugins/api/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAQnE,MAAM,WAAW,gBAAiB,SAAQ,cAAc;CAAG;AAG3D,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE;QACP,GAAG,EAAE,SAAS,CAAC;QACf,kBAAkB,EAAE,MAAM,OAAO,CAAC,mBAAmB,GAAG,SAAS,CAAC,CAAC;KACpE,CAAC;CACH;AAED,eAAO,MAAM,SAAS,EAAE,MAAM,CAC5B;IAAE,OAAO,EAAE;QAAE,OAAO,EAAE,cAAc,CAAA;KAAE,CAAA;CAAE,EACxC,iBAAiB,CAsClB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/plugins/api/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAQnE,MAAM,WAAW,gBAAiB,SAAQ,cAAc;CAAG;AAG3D,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE;QACP,GAAG,EAAE,SAAS,CAAC;QACf,kBAAkB,EAAE,MAAM,OAAO,CAAC,mBAAmB,GAAG,SAAS,CAAC,CAAC;KACpE,CAAC;CACH;AAED,eAAO,MAAM,SAAS,EAAE,MAAM,CAC5B;IAAE,OAAO,EAAE;QAAE,OAAO,EAAE,cAAc,CAAA;KAAE,CAAA;CAAE,EACxC,iBAAiB,CA8ClB,CAAC"}