@zapier/zapier-sdk 0.3.1 → 0.4.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 (158) hide show
  1. package/dist/index.cjs +2001 -0
  2. package/dist/index.d.mts +840 -0
  3. package/dist/index.d.ts +840 -20
  4. package/dist/index.mjs +1955 -0
  5. package/package.json +19 -7
  6. package/src/api/client.ts +84 -16
  7. package/src/api/types.ts +9 -1
  8. package/src/auth.ts +19 -287
  9. package/src/functions/fetch/index.ts +180 -0
  10. package/src/functions/fetch/info.ts +8 -0
  11. package/src/functions/fetch/schemas.ts +46 -0
  12. package/src/functions/findFirstAuthentication/schemas.ts +3 -13
  13. package/src/functions/findUniqueAuthentication/schemas.ts +3 -13
  14. package/src/functions/generateTypes/index.ts +15 -0
  15. package/src/functions/generateTypes/schemas.ts +3 -10
  16. package/src/functions/getAction/schemas.ts +3 -13
  17. package/src/functions/getApp/schemas.ts +2 -13
  18. package/src/functions/getAuthentication/index.ts +0 -1
  19. package/src/functions/getAuthentication/schemas.ts +3 -17
  20. package/src/functions/listActions/schemas.ts +3 -13
  21. package/src/functions/listApps/schemas.ts +2 -13
  22. package/src/functions/listAuthentications/index.ts +0 -1
  23. package/src/functions/listAuthentications/schemas.ts +3 -15
  24. package/src/functions/listFields/schemas.ts +3 -13
  25. package/src/functions/runAction/index.ts +0 -1
  26. package/src/functions/runAction/schemas.ts +6 -15
  27. package/src/index.ts +4 -2
  28. package/src/plugins/apps/index.ts +35 -9
  29. package/src/sdk.ts +20 -22
  30. package/src/types/domain.ts +16 -0
  31. package/src/types/sdk.ts +13 -1
  32. package/tsconfig.json +2 -2
  33. package/tsup.config.ts +21 -0
  34. package/dist/api/auth.d.ts +0 -8
  35. package/dist/api/auth.js +0 -29
  36. package/dist/api/client.d.ts +0 -8
  37. package/dist/api/client.js +0 -119
  38. package/dist/api/debug.d.ts +0 -12
  39. package/dist/api/debug.js +0 -50
  40. package/dist/api/index.d.ts +0 -28
  41. package/dist/api/index.js +0 -52
  42. package/dist/api/polling.d.ts +0 -17
  43. package/dist/api/polling.js +0 -34
  44. package/dist/api/types.d.ts +0 -147
  45. package/dist/api/types.js +0 -9
  46. package/dist/auth.d.ts +0 -59
  47. package/dist/auth.js +0 -261
  48. package/dist/functions/bundleCode/index.d.ts +0 -11
  49. package/dist/functions/bundleCode/index.js +0 -91
  50. package/dist/functions/bundleCode/info.d.ts +0 -27
  51. package/dist/functions/bundleCode/info.js +0 -11
  52. package/dist/functions/bundleCode/schemas.d.ts +0 -27
  53. package/dist/functions/bundleCode/schemas.js +0 -22
  54. package/dist/functions/findFirstAuthentication/index.d.ts +0 -12
  55. package/dist/functions/findFirstAuthentication/index.js +0 -21
  56. package/dist/functions/findFirstAuthentication/info.d.ts +0 -30
  57. package/dist/functions/findFirstAuthentication/info.js +0 -11
  58. package/dist/functions/findFirstAuthentication/schemas.d.ts +0 -42
  59. package/dist/functions/findFirstAuthentication/schemas.js +0 -25
  60. package/dist/functions/findUniqueAuthentication/index.d.ts +0 -13
  61. package/dist/functions/findUniqueAuthentication/index.js +0 -28
  62. package/dist/functions/findUniqueAuthentication/info.d.ts +0 -30
  63. package/dist/functions/findUniqueAuthentication/info.js +0 -11
  64. package/dist/functions/findUniqueAuthentication/schemas.d.ts +0 -42
  65. package/dist/functions/findUniqueAuthentication/schemas.js +0 -25
  66. package/dist/functions/generateTypes/index.d.ts +0 -11
  67. package/dist/functions/generateTypes/index.js +0 -305
  68. package/dist/functions/generateTypes/info.d.ts +0 -21
  69. package/dist/functions/generateTypes/info.js +0 -11
  70. package/dist/functions/generateTypes/schemas.d.ts +0 -30
  71. package/dist/functions/generateTypes/schemas.js +0 -14
  72. package/dist/functions/getAction/index.d.ts +0 -12
  73. package/dist/functions/getAction/index.js +0 -26
  74. package/dist/functions/getAction/info.d.ts +0 -18
  75. package/dist/functions/getAction/info.js +0 -11
  76. package/dist/functions/getAction/schemas.d.ts +0 -30
  77. package/dist/functions/getAction/schemas.js +0 -13
  78. package/dist/functions/getApp/index.d.ts +0 -12
  79. package/dist/functions/getApp/index.js +0 -37
  80. package/dist/functions/getApp/info.d.ts +0 -12
  81. package/dist/functions/getApp/info.js +0 -11
  82. package/dist/functions/getApp/schemas.d.ts +0 -24
  83. package/dist/functions/getApp/schemas.js +0 -11
  84. package/dist/functions/getAuthentication/index.d.ts +0 -13
  85. package/dist/functions/getAuthentication/index.js +0 -38
  86. package/dist/functions/getAuthentication/info.d.ts +0 -12
  87. package/dist/functions/getAuthentication/info.js +0 -11
  88. package/dist/functions/getAuthentication/schemas.d.ts +0 -26
  89. package/dist/functions/getAuthentication/schemas.js +0 -16
  90. package/dist/functions/listActions/index.d.ts +0 -12
  91. package/dist/functions/listActions/index.js +0 -128
  92. package/dist/functions/listActions/info.d.ts +0 -15
  93. package/dist/functions/listActions/info.js +0 -11
  94. package/dist/functions/listActions/schemas.d.ts +0 -27
  95. package/dist/functions/listActions/schemas.js +0 -14
  96. package/dist/functions/listApps/index.d.ts +0 -12
  97. package/dist/functions/listApps/index.js +0 -50
  98. package/dist/functions/listApps/info.d.ts +0 -18
  99. package/dist/functions/listApps/info.js +0 -11
  100. package/dist/functions/listApps/schemas.d.ts +0 -30
  101. package/dist/functions/listApps/schemas.js +0 -15
  102. package/dist/functions/listAuthentications/index.d.ts +0 -12
  103. package/dist/functions/listAuthentications/index.js +0 -131
  104. package/dist/functions/listAuthentications/info.d.ts +0 -30
  105. package/dist/functions/listAuthentications/info.js +0 -11
  106. package/dist/functions/listAuthentications/schemas.d.ts +0 -44
  107. package/dist/functions/listAuthentications/schemas.js +0 -25
  108. package/dist/functions/listFields/index.d.ts +0 -12
  109. package/dist/functions/listFields/index.js +0 -65
  110. package/dist/functions/listFields/info.d.ts +0 -24
  111. package/dist/functions/listFields/info.js +0 -11
  112. package/dist/functions/listFields/schemas.d.ts +0 -36
  113. package/dist/functions/listFields/schemas.js +0 -17
  114. package/dist/functions/runAction/index.d.ts +0 -12
  115. package/dist/functions/runAction/index.js +0 -86
  116. package/dist/functions/runAction/info.d.ts +0 -24
  117. package/dist/functions/runAction/info.js +0 -11
  118. package/dist/functions/runAction/schemas.d.ts +0 -38
  119. package/dist/functions/runAction/schemas.js +0 -15
  120. package/dist/index.js +0 -57
  121. package/dist/plugins/apps/index.d.ts +0 -8
  122. package/dist/plugins/apps/index.js +0 -77
  123. package/dist/plugins/apps/info.d.ts +0 -6
  124. package/dist/plugins/apps/info.js +0 -13
  125. package/dist/plugins/apps/types.d.ts +0 -21
  126. package/dist/plugins/apps/types.js +0 -2
  127. package/dist/resolvers/actionKey.d.ts +0 -8
  128. package/dist/resolvers/actionKey.js +0 -20
  129. package/dist/resolvers/actionType.d.ts +0 -8
  130. package/dist/resolvers/actionType.js +0 -21
  131. package/dist/resolvers/appKey.d.ts +0 -6
  132. package/dist/resolvers/appKey.js +0 -8
  133. package/dist/resolvers/authenticationId.d.ts +0 -8
  134. package/dist/resolvers/authenticationId.js +0 -29
  135. package/dist/resolvers/index.d.ts +0 -39
  136. package/dist/resolvers/index.js +0 -105
  137. package/dist/resolvers/inputs.d.ts +0 -7
  138. package/dist/resolvers/inputs.js +0 -15
  139. package/dist/schema-utils.d.ts +0 -44
  140. package/dist/schema-utils.js +0 -76
  141. package/dist/schemas/Action.d.ts +0 -21
  142. package/dist/schemas/Action.js +0 -31
  143. package/dist/schemas/App.d.ts +0 -19
  144. package/dist/schemas/App.js +0 -32
  145. package/dist/schemas/Auth.d.ts +0 -27
  146. package/dist/schemas/Auth.js +0 -42
  147. package/dist/schemas/Field.d.ts +0 -15
  148. package/dist/schemas/Field.js +0 -25
  149. package/dist/sdk.d.ts +0 -6
  150. package/dist/sdk.js +0 -90
  151. package/dist/types/domain.d.ts +0 -25
  152. package/dist/types/domain.js +0 -21
  153. package/dist/types/events.d.ts +0 -37
  154. package/dist/types/events.js +0 -8
  155. package/dist/types/properties.d.ts +0 -21
  156. package/dist/types/properties.js +0 -52
  157. package/dist/types/sdk.d.ts +0 -24
  158. package/dist/types/sdk.js +0 -2
package/dist/index.cjs ADDED
@@ -0,0 +1,2001 @@
1
+ 'use strict';
2
+
3
+ var zod = require('zod');
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+
15
+ // src/auth.ts
16
+ var auth_exports = {};
17
+ __export(auth_exports, {
18
+ getTokenFromCliLogin: () => getTokenFromCliLogin,
19
+ getTokenFromEnv: () => getTokenFromEnv,
20
+ getTokenFromEnvOrConfig: () => getTokenFromEnvOrConfig
21
+ });
22
+ function getTokenFromEnv() {
23
+ return process.env.ZAPIER_TOKEN;
24
+ }
25
+ async function getTokenFromCliLogin(options = {}) {
26
+ try {
27
+ const { getToken } = await import('@zapier/zapier-sdk-cli-login');
28
+ return await getToken(options);
29
+ } catch {
30
+ return void 0;
31
+ }
32
+ }
33
+ async function getTokenFromEnvOrConfig(options = {}) {
34
+ const envToken = getTokenFromEnv();
35
+ if (envToken) {
36
+ return envToken;
37
+ }
38
+ return getTokenFromCliLogin(options);
39
+ }
40
+ var init_auth = __esm({
41
+ "src/auth.ts"() {
42
+ }
43
+ });
44
+
45
+ // src/api/auth.ts
46
+ var auth_exports2 = {};
47
+ __export(auth_exports2, {
48
+ getAuthorizationHeader: () => getAuthorizationHeader,
49
+ isJwt: () => isJwt
50
+ });
51
+ function isJwt(token) {
52
+ const parts = token.split(".");
53
+ if (parts.length !== 3) {
54
+ return false;
55
+ }
56
+ const base64UrlPattern = /^[A-Za-z0-9_-]+$/;
57
+ return parts.every((part) => part.length > 0 && base64UrlPattern.test(part));
58
+ }
59
+ function getAuthorizationHeader(token) {
60
+ if (isJwt(token)) {
61
+ return `JWT ${token}`;
62
+ }
63
+ return `Bearer ${token}`;
64
+ }
65
+ var init_auth2 = __esm({
66
+ "src/api/auth.ts"() {
67
+ }
68
+ });
69
+
70
+ // src/types/domain.ts
71
+ var ZapierSdkError = class extends Error {
72
+ constructor(message, code) {
73
+ super(message);
74
+ this.code = code;
75
+ this.name = "ZapierSdkError";
76
+ }
77
+ };
78
+ var AppNotFoundError = class extends ZapierSdkError {
79
+ constructor(appKey) {
80
+ super(`App "${appKey}" not found`);
81
+ this.name = "AppNotFoundError";
82
+ this.code = "APP_NOT_FOUND";
83
+ this.appKey = appKey;
84
+ }
85
+ };
86
+ function withFormatter(schema, formatMeta) {
87
+ schema._def.formatMeta = formatMeta;
88
+ return schema;
89
+ }
90
+ function withOutputSchema(inputSchema, outputSchema) {
91
+ inputSchema._def.outputSchema = outputSchema;
92
+ return inputSchema;
93
+ }
94
+ function withPositional(schema) {
95
+ schema._def.positionalMeta = { positional: true };
96
+ return schema;
97
+ }
98
+ function isPositional(schema) {
99
+ if (schema._def.positionalMeta?.positional) {
100
+ return true;
101
+ }
102
+ if (schema instanceof zod.z.ZodOptional) {
103
+ return isPositional(schema._def.innerType);
104
+ }
105
+ if (schema instanceof zod.z.ZodDefault) {
106
+ return isPositional(schema._def.innerType);
107
+ }
108
+ return false;
109
+ }
110
+
111
+ // src/types/properties.ts
112
+ var AppKeyPropertySchema = withPositional(
113
+ zod.z.string().min(1).describe("App slug (e.g., 'slack', 'github')")
114
+ );
115
+ var ActionTypePropertySchema = zod.z.enum([
116
+ "read",
117
+ "read_bulk",
118
+ "write",
119
+ "run",
120
+ "search",
121
+ "search_or_write",
122
+ "search_and_write",
123
+ "filter"
124
+ ]).describe("Action type that matches the action's defined type");
125
+ var ActionKeyPropertySchema = zod.z.string().min(1).describe("Action key to execute");
126
+ var AuthenticationIdPropertySchema = zod.z.number().int().describe("Authentication ID to use for this action");
127
+ var InputsPropertySchema = zod.z.record(zod.z.any()).describe("Input parameters for the action");
128
+ var LimitPropertySchema = zod.z.number().int().min(1).max(1e3).default(50).describe("Maximum number of items to return");
129
+ var OffsetPropertySchema = zod.z.number().int().min(0).default(0).describe("Number of items to skip for pagination");
130
+ var OutputPropertySchema = zod.z.string().describe("Output file path");
131
+ var DebugPropertySchema = zod.z.boolean().default(false).describe("Enable debug logging");
132
+ var ParamsPropertySchema = zod.z.record(zod.z.any()).describe("Additional parameters");
133
+
134
+ // src/plugins/apps/index.ts
135
+ function createActionFunction(appKey, actionType, actionKey, options, pinnedAuthId) {
136
+ return async (actionOptions = {}) => {
137
+ const { sdk } = options;
138
+ const { inputs, authenticationId: providedAuthenticationId } = actionOptions;
139
+ const authenticationId = pinnedAuthId || providedAuthenticationId;
140
+ if (!authenticationId) {
141
+ throw new Error(
142
+ `Authentication ID is required. Either use the factory pattern: sdk.apps.${appKey}({ authenticationId }) or provide authenticationId in the action call.`
143
+ );
144
+ }
145
+ return sdk.runAction({
146
+ appKey,
147
+ actionType,
148
+ actionKey,
149
+ inputs,
150
+ authenticationId
151
+ });
152
+ };
153
+ }
154
+ function createActionTypeProxy(appKey, actionType, options, pinnedAuthId) {
155
+ if (actionType === "fetch") {
156
+ return async (fetchOptions) => {
157
+ const { sdk } = options;
158
+ const authenticationId = pinnedAuthId || fetchOptions.authenticationId;
159
+ if (!authenticationId) {
160
+ throw new Error(
161
+ `Authentication ID is required for fetch. Either use the factory pattern: sdk.apps.${appKey}({ authenticationId }).fetch(...) or provide authenticationId in the fetch call.`
162
+ );
163
+ }
164
+ return sdk.fetch({
165
+ ...fetchOptions,
166
+ authenticationId
167
+ });
168
+ };
169
+ }
170
+ return new Proxy(
171
+ {},
172
+ {
173
+ get(_, actionKey) {
174
+ if (typeof actionKey === "string") {
175
+ return createActionFunction(
176
+ appKey,
177
+ actionType,
178
+ actionKey,
179
+ options,
180
+ pinnedAuthId
181
+ );
182
+ }
183
+ return void 0;
184
+ }
185
+ }
186
+ );
187
+ }
188
+ function createPinnedAppProxy(appKey, options, pinnedAuthId) {
189
+ return new Proxy(
190
+ {},
191
+ {
192
+ get(_, actionType) {
193
+ if (typeof actionType === "string") {
194
+ return createActionTypeProxy(
195
+ appKey,
196
+ actionType,
197
+ options,
198
+ pinnedAuthId
199
+ );
200
+ }
201
+ return void 0;
202
+ }
203
+ }
204
+ );
205
+ }
206
+ function createAppProxy(appKey, options) {
207
+ const appFactory = (factoryOptions) => {
208
+ return createPinnedAppProxy(
209
+ appKey,
210
+ options,
211
+ factoryOptions.authenticationId
212
+ );
213
+ };
214
+ return new Proxy(appFactory, {
215
+ get(_, actionType) {
216
+ if (typeof actionType === "string") {
217
+ return createActionTypeProxy(appKey, actionType, options);
218
+ }
219
+ return void 0;
220
+ }
221
+ });
222
+ }
223
+ function createAppsProxy(options) {
224
+ const appsProxy = new Proxy({}, {
225
+ get(_, prop) {
226
+ if (typeof prop === "string") {
227
+ return createAppProxy(prop, options);
228
+ }
229
+ return void 0;
230
+ }
231
+ });
232
+ return appsProxy;
233
+ }
234
+ function createAppsPlugin(options) {
235
+ return createAppsProxy(options);
236
+ }
237
+
238
+ // src/index.ts
239
+ init_auth();
240
+
241
+ // src/resolvers/appKey.ts
242
+ var appKeyResolver = {
243
+ type: "static",
244
+ inputType: "text",
245
+ placeholder: "Enter app slug (e.g., 'slack', 'github')"
246
+ };
247
+
248
+ // src/resolvers/actionType.ts
249
+ var actionTypeResolver = {
250
+ type: "dynamic",
251
+ depends: ["appKey"],
252
+ fetch: async (sdk, resolvedParams) => {
253
+ const actions = await sdk.listActions({ appKey: resolvedParams.appKey });
254
+ const types = [...new Set(actions.map((action) => action.type))];
255
+ return types.map((type) => ({ key: type, name: type }));
256
+ },
257
+ prompt: (types) => ({
258
+ type: "list",
259
+ name: "actionType",
260
+ message: "Select action type:",
261
+ choices: types.map((type) => ({
262
+ name: type.name,
263
+ value: type.key
264
+ }))
265
+ })
266
+ };
267
+
268
+ // src/resolvers/actionKey.ts
269
+ var actionKeyResolver = {
270
+ type: "dynamic",
271
+ depends: ["appKey", "actionType"],
272
+ fetch: async (sdk, resolvedParams) => {
273
+ const actions = await sdk.listActions({ appKey: resolvedParams.appKey });
274
+ return actions.filter(
275
+ (action) => action.type === resolvedParams.actionType
276
+ );
277
+ },
278
+ prompt: (actions) => ({
279
+ type: "list",
280
+ name: "actionKey",
281
+ message: "Select action:",
282
+ choices: actions.map((action) => ({
283
+ name: `${action.name || action.key} - ${action.description || "No description"}`,
284
+ value: action.key
285
+ }))
286
+ })
287
+ };
288
+
289
+ // src/resolvers/authenticationId.ts
290
+ var authenticationIdResolver = {
291
+ type: "dynamic",
292
+ depends: ["appKey"],
293
+ fetch: async (sdk, resolvedParams) => {
294
+ return await sdk.listAuthentications({
295
+ appKey: resolvedParams.appKey,
296
+ limit: 1e3
297
+ });
298
+ },
299
+ prompt: (auths, params) => ({
300
+ type: "list",
301
+ name: "authenticationId",
302
+ message: `Select authentication for ${params.appKey}:`,
303
+ choices: [
304
+ ...auths.map((auth) => ({
305
+ name: `${auth.title || auth.label || "Authentication"} (ID: ${auth.id})`,
306
+ value: auth.id
307
+ })),
308
+ {
309
+ name: "\u2197 Skip authentication (may fail)",
310
+ value: null
311
+ }
312
+ ]
313
+ })
314
+ };
315
+
316
+ // src/resolvers/inputs.ts
317
+ var inputsResolver = {
318
+ type: "fields",
319
+ depends: ["appKey", "actionKey", "actionType", "authenticationId"],
320
+ fetch: async (sdk, resolvedParams) => {
321
+ return await sdk.listFields({
322
+ appKey: resolvedParams.appKey,
323
+ actionKey: resolvedParams.actionKey,
324
+ actionType: resolvedParams.actionType,
325
+ authenticationId: resolvedParams.authenticationId
326
+ });
327
+ }
328
+ };
329
+
330
+ // src/resolvers/index.ts
331
+ var resolverRegistry = {
332
+ appKey: appKeyResolver,
333
+ actionType: actionTypeResolver,
334
+ actionKey: actionKeyResolver,
335
+ authenticationId: authenticationIdResolver,
336
+ inputs: inputsResolver
337
+ };
338
+ function getResolver(name) {
339
+ return resolverRegistry[name];
340
+ }
341
+ function getResolversForMissingParams(missingParams) {
342
+ const resolvers = {};
343
+ for (const param of missingParams) {
344
+ const resolver = resolverRegistry[param];
345
+ if (resolver) {
346
+ resolvers[param] = resolver;
347
+ }
348
+ }
349
+ return resolvers;
350
+ }
351
+ function hasResolver(paramName) {
352
+ return paramName in resolverRegistry;
353
+ }
354
+ function getResolvableParams() {
355
+ return Object.keys(resolverRegistry);
356
+ }
357
+ function getResolutionOrder(paramName, resolved = /* @__PURE__ */ new Set()) {
358
+ const resolver = getResolver(paramName);
359
+ if (!resolver || resolver.type === "static") {
360
+ return [paramName];
361
+ }
362
+ const order = [];
363
+ if ("depends" in resolver && resolver.depends) {
364
+ for (const dependency of resolver.depends) {
365
+ if (!resolved.has(dependency)) {
366
+ order.push(...getResolutionOrder(dependency, resolved));
367
+ resolved.add(dependency);
368
+ }
369
+ }
370
+ }
371
+ if (!resolved.has(paramName)) {
372
+ order.push(paramName);
373
+ resolved.add(paramName);
374
+ }
375
+ return order;
376
+ }
377
+ function getResolutionOrderForParams(paramNames) {
378
+ const resolved = /* @__PURE__ */ new Set();
379
+ const order = [];
380
+ for (const paramName of paramNames) {
381
+ const paramOrder = getResolutionOrder(paramName, resolved);
382
+ for (const param of paramOrder) {
383
+ if (!order.includes(param)) {
384
+ order.push(param);
385
+ }
386
+ }
387
+ }
388
+ return order;
389
+ }
390
+
391
+ // src/api/index.ts
392
+ init_auth2();
393
+
394
+ // src/api/debug.ts
395
+ function createDebugLogger(enabled) {
396
+ if (!enabled) {
397
+ return () => {
398
+ };
399
+ }
400
+ return (message, data) => {
401
+ console.log(`[Zapier SDK] ${message}`, data || "");
402
+ };
403
+ }
404
+ function createDebugFetch(options) {
405
+ const { originalFetch, debugLog } = options;
406
+ return async (input, options2) => {
407
+ const startTime = Date.now();
408
+ const url = typeof input === "string" ? input : input.toString();
409
+ const method = options2?.method || "GET";
410
+ debugLog(`\u2192 ${method} ${url}`, {
411
+ headers: options2?.headers,
412
+ body: options2?.body ? JSON.parse(options2.body) : void 0
413
+ });
414
+ try {
415
+ const response = await originalFetch(input, options2);
416
+ const duration = Date.now() - startTime;
417
+ debugLog(`\u2190 ${response.status} ${response.statusText} (${duration}ms)`, {
418
+ url,
419
+ method,
420
+ status: response.status
421
+ });
422
+ return response;
423
+ } catch (error) {
424
+ const duration = Date.now() - startTime;
425
+ debugLog(`\u2716 Request failed (${duration}ms)`, {
426
+ url,
427
+ method,
428
+ error: error instanceof Error ? error.message : error
429
+ });
430
+ throw error;
431
+ }
432
+ };
433
+ }
434
+
435
+ // src/api/polling.ts
436
+ async function pollUntilComplete(options) {
437
+ const {
438
+ fetch: fetch2,
439
+ url,
440
+ headers = {},
441
+ maxAttempts = 30,
442
+ initialDelay = 50,
443
+ maxDelay = 1e3,
444
+ successStatus = 200,
445
+ pendingStatus = 202,
446
+ resultExtractor = (response) => response
447
+ } = options;
448
+ let delay = initialDelay;
449
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
450
+ const response = await fetch2(url, { headers });
451
+ if (response.status === successStatus) {
452
+ const result = await response.json();
453
+ return resultExtractor(result);
454
+ } else if (response.status === pendingStatus) {
455
+ if (attempt < maxAttempts - 1) {
456
+ await new Promise((resolve) => setTimeout(resolve, delay));
457
+ delay = Math.min(delay * 2, maxDelay);
458
+ continue;
459
+ }
460
+ } else {
461
+ throw new Error(
462
+ `Request failed: GET ${url} - ${response.status} ${response.statusText}`
463
+ );
464
+ }
465
+ }
466
+ throw new Error(`Operation timed out after ${maxAttempts} attempts`);
467
+ }
468
+
469
+ // src/api/client.ts
470
+ init_auth2();
471
+ init_auth();
472
+ var SUBDOMAIN_PREFIXES = /* @__PURE__ */ new Set(["relay"]);
473
+ function createZapierApi(options) {
474
+ const {
475
+ baseUrl,
476
+ token,
477
+ getToken,
478
+ debug = false,
479
+ fetch: originalFetch = globalThis.fetch,
480
+ onEvent
481
+ } = options;
482
+ const debugLog = createDebugLogger(debug);
483
+ const fetch2 = createDebugFetch({ originalFetch, debugLog });
484
+ function buildUrl(path, searchParams) {
485
+ const pathSegments = path.split("/").filter(Boolean);
486
+ let finalBaseUrl = baseUrl;
487
+ if (pathSegments.length > 0 && SUBDOMAIN_PREFIXES.has(pathSegments[0])) {
488
+ const subdomain = pathSegments[0];
489
+ const baseUrlObj = new URL(baseUrl);
490
+ baseUrlObj.hostname = `${subdomain}.${baseUrlObj.hostname}`;
491
+ finalBaseUrl = baseUrlObj.toString();
492
+ path = "/" + pathSegments.slice(1).join("/");
493
+ }
494
+ const url = new URL(path, finalBaseUrl);
495
+ if (searchParams) {
496
+ Object.entries(searchParams).forEach(([key, value]) => {
497
+ url.searchParams.set(key, value);
498
+ });
499
+ }
500
+ return url.toString();
501
+ }
502
+ async function buildHeaders(options2 = {}) {
503
+ const headers = {
504
+ ...options2.headers
505
+ };
506
+ if (options2.authRequired !== false) {
507
+ let resolvedToken = token;
508
+ if (!resolvedToken && getToken) {
509
+ resolvedToken = await getToken();
510
+ }
511
+ if (!resolvedToken) {
512
+ resolvedToken = await getTokenFromEnvOrConfig({
513
+ onEvent,
514
+ fetch: originalFetch
515
+ });
516
+ }
517
+ if (resolvedToken) {
518
+ headers.Authorization = getAuthorizationHeader(resolvedToken);
519
+ }
520
+ }
521
+ return headers;
522
+ }
523
+ async function handleResponse(response, customErrorHandler, hadAuthToken) {
524
+ if (!response.ok) {
525
+ if (customErrorHandler) {
526
+ const customError = customErrorHandler(response);
527
+ if (customError) {
528
+ throw customError;
529
+ }
530
+ }
531
+ if (response.status >= 400 && response.status < 500 && !hadAuthToken) {
532
+ throw new Error(
533
+ `Authentication required (HTTP ${response.status}). Please provide a token in options or set ZAPIER_TOKEN environment variable.`
534
+ );
535
+ }
536
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
537
+ }
538
+ try {
539
+ return await response.json();
540
+ } catch {
541
+ return await response.text();
542
+ }
543
+ }
544
+ async function plainFetch(input, init) {
545
+ const url = typeof input === "string" && !input.startsWith("http") ? buildUrl(input, init?.searchParams) : input.toString();
546
+ const headers = await buildHeaders(init);
547
+ const finalHeaders = {
548
+ ...headers,
549
+ ...init?.headers ? init.headers instanceof Headers ? Object.fromEntries(init.headers.entries()) : init.headers : {}
550
+ };
551
+ return await fetch2(url, {
552
+ ...init,
553
+ headers: finalHeaders
554
+ });
555
+ }
556
+ async function fetchJson(method, path, data, options2 = {}) {
557
+ const headers = { ...options2.headers };
558
+ if (data && typeof data === "object") {
559
+ headers["Content-Type"] = "application/json";
560
+ }
561
+ const response = await plainFetch(path, {
562
+ method,
563
+ body: data ? JSON.stringify(data) : void 0,
564
+ headers,
565
+ searchParams: options2.searchParams,
566
+ authRequired: options2.authRequired,
567
+ customErrorHandler: options2.customErrorHandler
568
+ });
569
+ const hadAuthToken = !!(await buildHeaders(options2)).Authorization;
570
+ return handleResponse(response, options2.customErrorHandler, hadAuthToken);
571
+ }
572
+ return {
573
+ async get(path, options2 = {}) {
574
+ return fetchJson("GET", path, void 0, options2);
575
+ },
576
+ async post(path, data, options2 = {}) {
577
+ return fetchJson("POST", path, data, options2);
578
+ },
579
+ async put(path, data, options2 = {}) {
580
+ return fetchJson("PUT", path, data, options2);
581
+ },
582
+ async delete(path, options2 = {}) {
583
+ return fetchJson("DELETE", path, void 0, options2);
584
+ },
585
+ async poll(path, options2 = {}) {
586
+ const url = buildUrl(path, options2.searchParams);
587
+ const headers = await buildHeaders(options2);
588
+ return pollUntilComplete({
589
+ fetch: fetch2,
590
+ url,
591
+ headers,
592
+ maxAttempts: options2.maxAttempts,
593
+ initialDelay: options2.initialDelay,
594
+ maxDelay: options2.maxDelay,
595
+ successStatus: options2.successStatus,
596
+ pendingStatus: options2.pendingStatus,
597
+ resultExtractor: options2.resultExtractor
598
+ });
599
+ },
600
+ async fetch(input, init) {
601
+ return plainFetch(input, init);
602
+ }
603
+ };
604
+ }
605
+
606
+ // src/api/index.ts
607
+ function generateRequestId() {
608
+ return Math.random().toString(36).substring(2) + Date.now().toString(36);
609
+ }
610
+ function getOrCreateApiClient(config) {
611
+ const {
612
+ baseUrl = "https://zapier.com",
613
+ token,
614
+ getToken,
615
+ api: providedApi,
616
+ debug = false,
617
+ fetch: customFetch
618
+ } = config;
619
+ if (providedApi) {
620
+ return providedApi;
621
+ }
622
+ return createZapierApi({
623
+ baseUrl,
624
+ token,
625
+ getToken,
626
+ debug,
627
+ fetch: customFetch
628
+ });
629
+ }
630
+
631
+ // src/functions/getApp/index.ts
632
+ async function getApp(options) {
633
+ const api = getOrCreateApiClient(options);
634
+ const { appKey } = options;
635
+ const app = await api.get(`/api/v4/apps/${appKey}/`, {
636
+ customErrorHandler: (response) => {
637
+ if (response.status === 404) {
638
+ return new AppNotFoundError(appKey);
639
+ }
640
+ return void 0;
641
+ }
642
+ });
643
+ return {
644
+ key: app.slug,
645
+ name: app.name,
646
+ description: app.description,
647
+ version: "1.0.0",
648
+ category: app.category?.name,
649
+ actions: [],
650
+ triggers: [],
651
+ current_implementation_id: app.current_implementation_id
652
+ };
653
+ }
654
+
655
+ // src/functions/listAuthentications/index.ts
656
+ async function listAuthentications(options = {}) {
657
+ const api = getOrCreateApiClient(options);
658
+ const listAuthenticationsInternal = async (options2 = {}) => {
659
+ const searchParams = {};
660
+ if (options2.appKey) {
661
+ try {
662
+ const app = await getApp({
663
+ appKey: options2.appKey,
664
+ api,
665
+ token: options2.token,
666
+ baseUrl: options2.baseUrl,
667
+ debug: options2.debug,
668
+ fetch: options2.fetch
669
+ });
670
+ const selectedApi = app.current_implementation_id;
671
+ if (selectedApi) {
672
+ const versionlessApi = selectedApi.split("@")[0];
673
+ searchParams.versionless_selected_api = versionlessApi;
674
+ }
675
+ } catch (error) {
676
+ if (error instanceof Error && error.name === "AppNotFoundError") {
677
+ throw error;
678
+ }
679
+ console.warn(
680
+ `Warning: Could not filter by app ${options2.appKey}:`,
681
+ error instanceof Error ? error.message : "Unknown error"
682
+ );
683
+ }
684
+ }
685
+ if (options2.search) {
686
+ searchParams.search = options2.search;
687
+ } else if (options2.title) {
688
+ searchParams.search = options2.title;
689
+ }
690
+ if (options2.account_id) {
691
+ searchParams.account_id = options2.account_id;
692
+ }
693
+ if (options2.owner) {
694
+ searchParams.owner = options2.owner;
695
+ }
696
+ if (options2.limit) {
697
+ searchParams.limit = options2.limit.toString();
698
+ }
699
+ if (options2.offset) {
700
+ searchParams.offset = options2.offset.toString();
701
+ }
702
+ const data = await api.get(
703
+ "/api/v4/authentications/",
704
+ {
705
+ searchParams,
706
+ customErrorHandler: (response) => {
707
+ if (response.status === 401) {
708
+ return new Error(
709
+ `Authentication failed. Your token may not have permission to access authentications or may be expired. (HTTP ${response.status})`
710
+ );
711
+ }
712
+ if (response.status === 403) {
713
+ return new Error(
714
+ `Access forbidden. Your token may not have the required scopes to list authentications. (HTTP ${response.status})`
715
+ );
716
+ }
717
+ return void 0;
718
+ }
719
+ }
720
+ );
721
+ let auths = data.results || [];
722
+ auths = auths.map((auth) => ({
723
+ ...auth,
724
+ title: auth.title || auth.label || void 0
725
+ }));
726
+ if (options2.title) {
727
+ auths = auths.filter((auth) => auth.title === options2.title);
728
+ }
729
+ if (auths.length > 0) {
730
+ auths.__pagination = {
731
+ count: data.count,
732
+ hasNext: !!data.next,
733
+ hasPrevious: !!data.previous,
734
+ nextUrl: data.next,
735
+ previousUrl: data.previous
736
+ };
737
+ }
738
+ return auths;
739
+ };
740
+ if (options.limit && options.owner === void 0) {
741
+ const ownedAuths = await listAuthenticationsInternal({
742
+ ...options,
743
+ owner: "me"
744
+ });
745
+ if (ownedAuths.length >= options.limit) {
746
+ return ownedAuths.slice(0, options.limit);
747
+ }
748
+ const allAuths = await listAuthenticationsInternal({
749
+ ...options,
750
+ owner: void 0
751
+ });
752
+ const ownedAuthenticationIds = new Set(ownedAuths.map((auth) => auth.id));
753
+ const additionalAuths = allAuths.filter(
754
+ (auth) => !ownedAuthenticationIds.has(auth.id)
755
+ );
756
+ const combined = [...ownedAuths, ...additionalAuths];
757
+ return combined.slice(0, options.limit);
758
+ }
759
+ return listAuthenticationsInternal(options);
760
+ }
761
+
762
+ // src/functions/getAuthentication/index.ts
763
+ async function getAuthentication(options) {
764
+ const { authenticationId } = options;
765
+ const api = getOrCreateApiClient(options);
766
+ const data = await api.get(
767
+ `/api/v4/authentications/${authenticationId}/`,
768
+ {
769
+ customErrorHandler: (response) => {
770
+ if (response.status === 401) {
771
+ return new Error(
772
+ `Authentication failed. Your token may not have permission to access authentications or may be expired. (HTTP ${response.status})`
773
+ );
774
+ }
775
+ if (response.status === 403) {
776
+ return new Error(
777
+ `Access forbidden. Your token may not have the required scopes to get authentication ${authenticationId}. (HTTP ${response.status})`
778
+ );
779
+ }
780
+ if (response.status === 404) {
781
+ return new Error(
782
+ `Authentication ${authenticationId} not found. It may not exist or you may not have access to it. (HTTP ${response.status})`
783
+ );
784
+ }
785
+ return void 0;
786
+ }
787
+ }
788
+ );
789
+ return {
790
+ ...data,
791
+ title: data.title || data.label || void 0
792
+ };
793
+ }
794
+
795
+ // src/functions/findFirstAuthentication/index.ts
796
+ async function findFirstAuthentication(options = {}) {
797
+ const auths = await listAuthentications({
798
+ ...options,
799
+ limit: 1
800
+ });
801
+ return auths.length > 0 ? auths[0] : null;
802
+ }
803
+
804
+ // src/functions/findUniqueAuthentication/index.ts
805
+ async function findUniqueAuthentication(options = {}) {
806
+ const auths = await listAuthentications({
807
+ ...options,
808
+ limit: 2
809
+ // Get up to 2 to check for uniqueness
810
+ });
811
+ if (auths.length === 0) {
812
+ throw new Error("No authentication found matching the specified criteria");
813
+ }
814
+ if (auths.length > 1) {
815
+ throw new Error(
816
+ "Multiple authentications found matching the specified criteria. Expected exactly one."
817
+ );
818
+ }
819
+ return auths[0];
820
+ }
821
+
822
+ // src/functions/listApps/index.ts
823
+ async function listApps(options = {}) {
824
+ const api = getOrCreateApiClient(options);
825
+ const searchParams = {};
826
+ if (options.category) {
827
+ searchParams.category = options.category;
828
+ }
829
+ if (options.limit) {
830
+ searchParams.limit = options.limit.toString();
831
+ }
832
+ if (options.offset) {
833
+ searchParams.offset = options.offset.toString();
834
+ }
835
+ const data = await api.get("/api/v4/apps/", { searchParams });
836
+ const apps = data.results?.map(
837
+ (app) => ({
838
+ key: app.slug,
839
+ name: app.name,
840
+ description: app.description,
841
+ version: "1.0.0",
842
+ // API doesn't provide version
843
+ category: app.category?.name,
844
+ actions: [],
845
+ // Will be populated separately
846
+ triggers: [],
847
+ current_implementation_id: app.current_implementation_id
848
+ })
849
+ ) || [];
850
+ if (apps.length > 0) {
851
+ apps.__pagination = {
852
+ count: data.count,
853
+ hasNext: !!data.next,
854
+ hasPrevious: !!data.previous,
855
+ nextUrl: data.next,
856
+ previousUrl: data.previous
857
+ };
858
+ }
859
+ return apps;
860
+ }
861
+
862
+ // src/functions/listActions/index.ts
863
+ async function listActions(options = {}) {
864
+ const api = getOrCreateApiClient(options);
865
+ if (options.appKey) {
866
+ try {
867
+ const appData = await getApp({
868
+ appKey: options.appKey,
869
+ api,
870
+ token: options.token,
871
+ baseUrl: options.baseUrl,
872
+ debug: options.debug,
873
+ fetch: options.fetch
874
+ });
875
+ const implementationId = appData.current_implementation_id?.split("@")[0];
876
+ if (!implementationId) {
877
+ throw new Error("No current_implementation_id found for app");
878
+ }
879
+ const searchParams2 = {
880
+ global: "true",
881
+ public_only: "true",
882
+ selected_apis: implementationId
883
+ };
884
+ const data2 = await api.get("/api/v4/implementations/", {
885
+ searchParams: searchParams2
886
+ });
887
+ const actions2 = [];
888
+ for (const implementation of data2.results || []) {
889
+ if (implementation.actions) {
890
+ for (const action of implementation.actions) {
891
+ const transformedAction = {
892
+ key: action.key,
893
+ name: action.name || action.label,
894
+ description: action.description || "",
895
+ appKey: implementation.slug || "",
896
+ type: action.type || action.type_of || "read",
897
+ inputFields: [],
898
+ // Would need additional API call for detailed fields
899
+ outputFields: []
900
+ };
901
+ if (options?.type && transformedAction.type !== options.type) {
902
+ continue;
903
+ }
904
+ actions2.push(transformedAction);
905
+ }
906
+ }
907
+ }
908
+ if (actions2.length > 0) {
909
+ actions2.__pagination = {
910
+ count: data2.count,
911
+ hasNext: !!data2.next,
912
+ hasPrevious: !!data2.previous,
913
+ nextUrl: data2.next,
914
+ previousUrl: data2.previous
915
+ };
916
+ }
917
+ return actions2;
918
+ } catch (error) {
919
+ if (error instanceof Error && error.name === "AppNotFoundError") {
920
+ throw error;
921
+ }
922
+ console.warn(
923
+ "Optimized app lookup failed, falling back to full scan:",
924
+ error
925
+ );
926
+ }
927
+ }
928
+ const searchParams = {
929
+ global: "true",
930
+ public_only: "true"
931
+ };
932
+ const data = await api.get("/api/v4/implementations/", { searchParams });
933
+ const actions = [];
934
+ for (const implementation of data.results || []) {
935
+ if (implementation.actions) {
936
+ for (const action of implementation.actions) {
937
+ const transformedAction = {
938
+ key: action.key,
939
+ name: action.name || action.label,
940
+ description: action.description || "",
941
+ appKey: implementation.slug || "",
942
+ type: action.type || action.type_of || "read",
943
+ inputFields: [],
944
+ // Would need additional API call for detailed fields
945
+ outputFields: []
946
+ };
947
+ if (options?.appKey && transformedAction.appKey !== options.appKey) {
948
+ continue;
949
+ }
950
+ if (options?.type && transformedAction.type !== options.type) {
951
+ continue;
952
+ }
953
+ actions.push(transformedAction);
954
+ }
955
+ }
956
+ }
957
+ if (actions.length > 0) {
958
+ actions.__pagination = {
959
+ count: data.count,
960
+ hasNext: !!data.next,
961
+ hasPrevious: !!data.previous,
962
+ nextUrl: data.next,
963
+ previousUrl: data.previous
964
+ };
965
+ }
966
+ return actions;
967
+ }
968
+
969
+ // src/functions/getAction/index.ts
970
+ async function getAction(options) {
971
+ const { appKey, actionKey, actionType } = options;
972
+ const actions = await listActions({
973
+ ...options,
974
+ appKey
975
+ });
976
+ const action = actions.find(
977
+ (a) => a.key === actionKey && a.type === actionType
978
+ );
979
+ if (!action) {
980
+ throw new Error(`Action not found: ${actionKey} with type ${actionType}`);
981
+ }
982
+ return action;
983
+ }
984
+
985
+ // src/functions/runAction/index.ts
986
+ async function runAction(options) {
987
+ const {
988
+ appKey,
989
+ actionType,
990
+ actionKey,
991
+ inputs,
992
+ authenticationId: providedAuthenticationId
993
+ } = options;
994
+ const api = getOrCreateApiClient(options);
995
+ const actionData = await getAction({
996
+ ...options,
997
+ appKey,
998
+ actionKey,
999
+ actionType
1000
+ });
1001
+ if (actionData.type !== actionType) {
1002
+ throw new Error(
1003
+ `Action type mismatch: expected ${actionType}, got ${actionData.type}`
1004
+ );
1005
+ }
1006
+ const startTime = Date.now();
1007
+ const result = await executeAction({
1008
+ api,
1009
+ appSlug: appKey,
1010
+ actionKey,
1011
+ actionType: actionData.type,
1012
+ executionOptions: { inputs: inputs || {} },
1013
+ authenticationId: providedAuthenticationId,
1014
+ options
1015
+ });
1016
+ const executionTime = Date.now() - startTime;
1017
+ return {
1018
+ success: true,
1019
+ data: result,
1020
+ metadata: {
1021
+ executionTime,
1022
+ requestId: generateRequestId()
1023
+ }
1024
+ };
1025
+ }
1026
+ async function executeAction(actionOptions) {
1027
+ const {
1028
+ api,
1029
+ appSlug,
1030
+ actionKey,
1031
+ actionType,
1032
+ executionOptions,
1033
+ authenticationId,
1034
+ options
1035
+ } = actionOptions;
1036
+ const appData = await getApp({
1037
+ appKey: appSlug,
1038
+ api,
1039
+ token: options.token,
1040
+ baseUrl: options.baseUrl,
1041
+ debug: options.debug,
1042
+ fetch: options.fetch
1043
+ });
1044
+ const selectedApi = appData.current_implementation_id;
1045
+ if (!selectedApi) {
1046
+ throw new Error("No current_implementation_id found for app");
1047
+ }
1048
+ const runRequest = {
1049
+ data: {
1050
+ authentication_id: authenticationId || 1,
1051
+ selected_api: selectedApi,
1052
+ action_key: actionKey,
1053
+ action_type: actionType,
1054
+ inputs: executionOptions.inputs || {}
1055
+ }
1056
+ };
1057
+ const runData = await api.post("/api/actions/v1/runs", runRequest);
1058
+ const runId = runData.data.id;
1059
+ return await api.poll(`/api/actions/v1/runs/${runId}`, {
1060
+ successStatus: 200,
1061
+ pendingStatus: 202,
1062
+ resultExtractor: (result) => result.data
1063
+ });
1064
+ }
1065
+
1066
+ // src/functions/listFields/index.ts
1067
+ async function listFields(options) {
1068
+ const api = getOrCreateApiClient(options);
1069
+ const { appKey, actionKey, actionType, authenticationId, params } = options;
1070
+ const appData = await getApp({
1071
+ appKey,
1072
+ api,
1073
+ token: options.token,
1074
+ baseUrl: options.baseUrl,
1075
+ debug: options.debug,
1076
+ fetch: options.fetch
1077
+ });
1078
+ const selectedApi = appData.current_implementation_id;
1079
+ if (!selectedApi) {
1080
+ throw new Error("No current_implementation_id found for app");
1081
+ }
1082
+ const needsRequest = {
1083
+ selected_api: selectedApi,
1084
+ action: actionKey,
1085
+ type_of: actionType,
1086
+ authentication_id: authenticationId,
1087
+ params: params || {}
1088
+ };
1089
+ const needsData = await api.post(
1090
+ "/api/v4/implementations/needs/",
1091
+ needsRequest
1092
+ );
1093
+ if (!needsData.success) {
1094
+ throw new Error(
1095
+ `Failed to get action fields: ${needsData.errors?.join(", ") || "Unknown error"}`
1096
+ );
1097
+ }
1098
+ return (needsData.needs || []).map((need) => ({
1099
+ key: need.key,
1100
+ label: need.label,
1101
+ required: need.required || false,
1102
+ type: need.type,
1103
+ helpText: need.help_text,
1104
+ helpTextHtml: need.help_text_html,
1105
+ choices: need.choices?.map((choice) => ({
1106
+ value: choice.value,
1107
+ label: choice.label
1108
+ })),
1109
+ default: need.default,
1110
+ placeholder: need.placeholder,
1111
+ computed: need.computed,
1112
+ customField: need.custom_field,
1113
+ dependsOn: need.depends_on,
1114
+ format: need.format,
1115
+ inputFormat: need.input_format
1116
+ }));
1117
+ }
1118
+
1119
+ // src/functions/generateTypes/index.ts
1120
+ function generateFetchMethodSignature() {
1121
+ return ` /** Make authenticated HTTP requests through Zapier's Relay service */
1122
+ fetch: (options: Omit<z.infer<typeof RelayFetchSchema>, 'authenticationId'>) => Promise<Response>`;
1123
+ }
1124
+ async function generateTypes(options) {
1125
+ const {
1126
+ appKey,
1127
+ authenticationId,
1128
+ output = `./types/${appKey}.d.ts`
1129
+ } = options;
1130
+ const { app, version } = parseAppIdentifier(appKey);
1131
+ const actions = await listActions({
1132
+ ...options,
1133
+ appKey: app
1134
+ });
1135
+ if (actions.length === 0) {
1136
+ const typeDefinitions2 = generateEmptyTypesFile(app, version);
1137
+ if (output) {
1138
+ const fs = await import('fs');
1139
+ const path = await import('path');
1140
+ fs.mkdirSync(path.dirname(output), { recursive: true });
1141
+ fs.writeFileSync(output, typeDefinitions2, "utf8");
1142
+ }
1143
+ return typeDefinitions2;
1144
+ }
1145
+ const actionsWithFields = [];
1146
+ if (authenticationId) {
1147
+ for (const action of actions) {
1148
+ try {
1149
+ const fields = await listFields({
1150
+ ...options,
1151
+ appKey: action.appKey,
1152
+ actionKey: action.key,
1153
+ actionType: action.type,
1154
+ authenticationId
1155
+ });
1156
+ actionsWithFields.push({ ...action, inputFields: fields });
1157
+ } catch {
1158
+ actionsWithFields.push({ ...action, inputFields: [] });
1159
+ }
1160
+ }
1161
+ } else {
1162
+ actions.forEach((action) => {
1163
+ actionsWithFields.push({ ...action, inputFields: [] });
1164
+ });
1165
+ }
1166
+ const typeDefinitions = generateTypeDefinitions(
1167
+ app,
1168
+ actionsWithFields,
1169
+ version
1170
+ );
1171
+ if (output) {
1172
+ const fs = await import('fs');
1173
+ const path = await import('path');
1174
+ fs.mkdirSync(path.dirname(output), { recursive: true });
1175
+ fs.writeFileSync(output, typeDefinitions, "utf8");
1176
+ }
1177
+ return typeDefinitions;
1178
+ }
1179
+ function parseAppIdentifier(identifier) {
1180
+ const parts = identifier.split("@");
1181
+ return {
1182
+ app: parts[0],
1183
+ version: parts[1]
1184
+ };
1185
+ }
1186
+ function generateTypeDefinitions(appKey, actions, version) {
1187
+ if (actions.length === 0) {
1188
+ return generateEmptyTypesFile(appKey, version);
1189
+ }
1190
+ const actionsByType = actions.reduce(
1191
+ (acc, action) => {
1192
+ if (!acc[action.type]) {
1193
+ acc[action.type] = [];
1194
+ }
1195
+ acc[action.type].push(action);
1196
+ return acc;
1197
+ },
1198
+ {}
1199
+ );
1200
+ const appName = capitalize(appKey);
1201
+ const versionComment = version ? ` * Generated for ${appKey}@${version}` : ` * Generated for ${appKey}`;
1202
+ let output = `/* eslint-disable @typescript-eslint/naming-convention */
1203
+ /**
1204
+ * Auto-generated TypeScript types for Zapier ${appKey} actions
1205
+ ${versionComment}
1206
+ * Generated on: ${(/* @__PURE__ */ new Date()).toISOString()}
1207
+ *
1208
+ * Usage:
1209
+ * import type { ${appName}Sdk } from './path/to/this/file'
1210
+ * const sdk = createZapierSdk() as unknown as ${appName}Sdk
1211
+ *
1212
+ * // Direct usage (per-call auth):
1213
+ * await sdk.apps.${appKey}.search.user_by_email({ authenticationId: 123, inputs: { email } })
1214
+ *
1215
+ * // Factory usage (pinned auth):
1216
+ * const my${appName} = sdk.apps.${appKey}({ authenticationId: 123 })
1217
+ * await my${appName}.search.user_by_email({ inputs: { email } })
1218
+ */
1219
+
1220
+ import type { ActionExecutionOptions, ActionExecutionResult } from '@zapier/zapier-sdk'
1221
+ import { z } from 'zod'
1222
+ import { RelayFetchSchema } from '@zapier/zapier-sdk'
1223
+
1224
+ `;
1225
+ actions.forEach((action) => {
1226
+ if (action.inputFields.length > 0) {
1227
+ const inputTypeName = `${appName}${capitalize(action.type)}${capitalize(
1228
+ sanitizeActionName(action.key)
1229
+ )}Inputs`;
1230
+ output += `interface ${inputTypeName} {
1231
+ `;
1232
+ action.inputFields.forEach((field) => {
1233
+ const isOptional = !field.required;
1234
+ const fieldType = mapFieldTypeToTypeScript(field);
1235
+ const description = field.helpText ? ` /** ${escapeComment(field.helpText)} */
1236
+ ` : "";
1237
+ output += `${description} ${sanitizeFieldName(field.key)}${isOptional ? "?" : ""}: ${fieldType}
1238
+ `;
1239
+ });
1240
+ output += `}
1241
+
1242
+ `;
1243
+ }
1244
+ });
1245
+ Object.entries(actionsByType).forEach(([actionType, typeActions]) => {
1246
+ const typeName = `${appName}${capitalize(actionType)}Actions`;
1247
+ output += `interface ${typeName} {
1248
+ `;
1249
+ typeActions.forEach((action) => {
1250
+ const actionName = sanitizeActionName(action.key);
1251
+ const description = action.description ? ` /** ${escapeComment(action.description)} */
1252
+ ` : "";
1253
+ if (action.inputFields.length > 0) {
1254
+ const inputTypeName = `${appName}${capitalize(action.type)}${capitalize(
1255
+ sanitizeActionName(action.key)
1256
+ )}Inputs`;
1257
+ output += `${description} ${actionName}: (options: { inputs: ${inputTypeName} } & Omit<ActionExecutionOptions, 'inputs'>) => Promise<ActionExecutionResult>
1258
+ `;
1259
+ } else {
1260
+ output += `${description} ${actionName}: (options?: { inputs?: Record<string, any> } & ActionExecutionOptions) => Promise<ActionExecutionResult>
1261
+ `;
1262
+ }
1263
+ });
1264
+ output += `}
1265
+
1266
+ `;
1267
+ });
1268
+ output += `interface ${appName}AppProxy {
1269
+ `;
1270
+ Object.keys(actionsByType).forEach((actionType) => {
1271
+ const typeName = `${appName}${capitalize(actionType)}Actions`;
1272
+ output += ` ${actionType}: ${typeName}
1273
+ `;
1274
+ });
1275
+ output += generateFetchMethodSignature() + "\n";
1276
+ output += `}
1277
+
1278
+ `;
1279
+ output += `interface ${appName}AppFactory {
1280
+ `;
1281
+ output += ` (options: { authenticationId: number }): ${appName}AppProxy
1282
+ `;
1283
+ output += `}
1284
+
1285
+ `;
1286
+ output += `type ${appName}AppWithFactory = ${appName}AppFactory & ${appName}AppProxy
1287
+
1288
+ `;
1289
+ output += `export interface ${appName}Sdk {
1290
+ `;
1291
+ output += ` apps: {
1292
+ `;
1293
+ output += ` ${appKey}: ${appName}AppWithFactory
1294
+ `;
1295
+ output += ` }
1296
+ `;
1297
+ output += `}
1298
+ `;
1299
+ return output;
1300
+ }
1301
+ function generateEmptyTypesFile(appKey, version) {
1302
+ const appName = capitalize(appKey);
1303
+ const versionComment = version ? ` * Generated for ${appKey}@${version}` : ` * Generated for ${appKey}`;
1304
+ return `/* eslint-disable @typescript-eslint/naming-convention */
1305
+ /**
1306
+ * Auto-generated TypeScript types for Zapier ${appKey} actions
1307
+ ${versionComment}
1308
+ * Generated on: ${(/* @__PURE__ */ new Date()).toISOString()}
1309
+ *
1310
+ * No actions found for this app.
1311
+ */
1312
+
1313
+ import type { ActionExecutionOptions, ActionExecutionResult } from '@zapier/zapier-sdk'
1314
+ import { z } from 'zod'
1315
+ import { RelayFetchSchema } from '@zapier/zapier-sdk'
1316
+
1317
+ interface ${appName}AppProxy {
1318
+ // No actions available
1319
+ ${generateFetchMethodSignature()}
1320
+ }
1321
+
1322
+ interface ${appName}AppFactory {
1323
+ (options: { authenticationId: number }): ${appName}AppProxy
1324
+ }
1325
+
1326
+ type ${appName}AppWithFactory = ${appName}AppFactory & ${appName}AppProxy
1327
+
1328
+ export interface ${appName}Sdk {
1329
+ apps: {
1330
+ ${appKey}: ${appName}AppWithFactory
1331
+ }
1332
+ }
1333
+ `;
1334
+ }
1335
+ function capitalize(str) {
1336
+ return str.charAt(0).toUpperCase() + str.slice(1).replace(/[-_]/g, "");
1337
+ }
1338
+ function sanitizeActionName(actionKey) {
1339
+ let sanitized = actionKey.replace(/[^a-zA-Z0-9_$]/g, "_");
1340
+ if (/^[0-9]/.test(sanitized)) {
1341
+ sanitized = "_" + sanitized;
1342
+ }
1343
+ return sanitized;
1344
+ }
1345
+ function sanitizeFieldName(fieldKey) {
1346
+ let sanitized = fieldKey.replace(/[^a-zA-Z0-9_$]/g, "_");
1347
+ if (/^[0-9]/.test(sanitized)) {
1348
+ sanitized = "_" + sanitized;
1349
+ }
1350
+ return sanitized;
1351
+ }
1352
+ function escapeComment(comment) {
1353
+ return comment.replace(/\*\//g, "*\\/").replace(/\r?\n/g, " ");
1354
+ }
1355
+ function mapFieldTypeToTypeScript(field) {
1356
+ if (field.choices && field.choices.length > 0) {
1357
+ const choiceValues = field.choices.filter(
1358
+ (choice) => choice.value !== void 0 && choice.value !== null && choice.value !== ""
1359
+ ).map(
1360
+ (choice) => typeof choice.value === "string" ? `"${choice.value}"` : choice.value
1361
+ );
1362
+ if (choiceValues.length > 0) {
1363
+ return choiceValues.join(" | ");
1364
+ }
1365
+ }
1366
+ switch (field.type?.toLowerCase()) {
1367
+ case "string":
1368
+ case "text":
1369
+ case "email":
1370
+ case "url":
1371
+ case "password":
1372
+ return "string";
1373
+ case "integer":
1374
+ case "number":
1375
+ return "number";
1376
+ case "boolean":
1377
+ return "boolean";
1378
+ case "datetime":
1379
+ case "date":
1380
+ return "string";
1381
+ // ISO date strings
1382
+ case "file":
1383
+ return "string";
1384
+ // File URL or content
1385
+ case "array":
1386
+ return "any[]";
1387
+ case "object":
1388
+ return "Record<string, any>";
1389
+ default:
1390
+ return "string | number | boolean";
1391
+ }
1392
+ }
1393
+
1394
+ // src/functions/bundleCode/index.ts
1395
+ async function bundleCode(options) {
1396
+ const {
1397
+ input,
1398
+ output,
1399
+ target = "es2020",
1400
+ cjs = false,
1401
+ minify = false,
1402
+ string: returnString = false
1403
+ } = options;
1404
+ const { buildSync } = await import('esbuild');
1405
+ const fs = await import('fs');
1406
+ const path = await import('path');
1407
+ const resolvedInput = path.resolve(process.cwd(), input);
1408
+ try {
1409
+ const result = buildSync({
1410
+ entryPoints: [resolvedInput],
1411
+ bundle: true,
1412
+ platform: "node",
1413
+ target,
1414
+ format: cjs ? "cjs" : "esm",
1415
+ minify,
1416
+ write: false,
1417
+ external: [],
1418
+ // Bundle everything
1419
+ banner: {
1420
+ js: "#!/usr/bin/env node"
1421
+ }
1422
+ });
1423
+ if (result.errors.length > 0) {
1424
+ throw new Error(
1425
+ `Bundle failed: ${result.errors.map((e) => e.text).join(", ")}`
1426
+ );
1427
+ }
1428
+ const bundledCode = result.outputFiles?.[0]?.text;
1429
+ if (!bundledCode) {
1430
+ throw new Error("No output generated");
1431
+ }
1432
+ let finalOutput = bundledCode;
1433
+ if (returnString) {
1434
+ finalOutput = JSON.stringify(bundledCode);
1435
+ }
1436
+ if (output) {
1437
+ fs.mkdirSync(path.dirname(output), { recursive: true });
1438
+ fs.writeFileSync(output, finalOutput, "utf8");
1439
+ }
1440
+ return finalOutput;
1441
+ } catch (error) {
1442
+ throw new Error(
1443
+ `Bundle failed: ${error instanceof Error ? error.message : "Unknown error"}`
1444
+ );
1445
+ }
1446
+ }
1447
+
1448
+ // src/functions/fetch/index.ts
1449
+ function transformUrlToRelayPath(url) {
1450
+ const targetUrl = new URL(url);
1451
+ const relayPath = `/relay/${targetUrl.hostname}${targetUrl.pathname}${targetUrl.search}${targetUrl.hash}`;
1452
+ return relayPath;
1453
+ }
1454
+ async function fetch(options) {
1455
+ const {
1456
+ url,
1457
+ method = "GET",
1458
+ body,
1459
+ headers,
1460
+ authenticationId,
1461
+ callbackUrl,
1462
+ authenticationTemplate,
1463
+ ...config
1464
+ } = options;
1465
+ return relayFetch(
1466
+ url,
1467
+ {
1468
+ method,
1469
+ body,
1470
+ headers,
1471
+ authenticationId,
1472
+ callbackUrl,
1473
+ authenticationTemplate
1474
+ },
1475
+ config
1476
+ );
1477
+ }
1478
+ async function relayFetch(url, options = {}, config = {}) {
1479
+ const api = getOrCreateApiClient(config);
1480
+ const {
1481
+ authenticationId,
1482
+ callbackUrl,
1483
+ authenticationTemplate,
1484
+ method = "GET",
1485
+ body,
1486
+ ...fetchOptions
1487
+ } = options;
1488
+ const relayPath = transformUrlToRelayPath(url);
1489
+ const headers = {};
1490
+ if (fetchOptions.headers) {
1491
+ const headerEntries = fetchOptions.headers instanceof Headers ? Array.from(fetchOptions.headers.entries()) : Object.entries(fetchOptions.headers);
1492
+ for (const [key, value] of headerEntries) {
1493
+ headers[key] = value;
1494
+ }
1495
+ }
1496
+ if (authenticationId) {
1497
+ headers["X-Relay-Authentication-Id"] = authenticationId.toString();
1498
+ }
1499
+ if (callbackUrl) {
1500
+ headers["X-Relay-Callback-Url"] = callbackUrl;
1501
+ }
1502
+ if (authenticationTemplate) {
1503
+ headers["X-Authentication-Template"] = authenticationTemplate;
1504
+ }
1505
+ const requestOptions = {
1506
+ headers,
1507
+ authRequired: false,
1508
+ // Disable automatic Authorization header
1509
+ customErrorHandler: (response) => {
1510
+ if (!response.ok) {
1511
+ return new Error(
1512
+ `Relay request failed: ${response.status} ${response.statusText}`
1513
+ );
1514
+ }
1515
+ return void 0;
1516
+ }
1517
+ };
1518
+ let token = config.token;
1519
+ if (!token && config.getToken) {
1520
+ token = await config.getToken();
1521
+ }
1522
+ if (!token) {
1523
+ const { getTokenFromEnvOrConfig: getTokenFromEnvOrConfig2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
1524
+ token = await getTokenFromEnvOrConfig2({
1525
+ onEvent: config.onEvent,
1526
+ fetch: config.fetch
1527
+ });
1528
+ }
1529
+ if (token) {
1530
+ const { getAuthorizationHeader: getAuthorizationHeader2 } = await Promise.resolve().then(() => (init_auth2(), auth_exports2));
1531
+ headers["X-Relay-Authorization"] = getAuthorizationHeader2(token);
1532
+ }
1533
+ return await api.fetch(relayPath, {
1534
+ method,
1535
+ body,
1536
+ headers: requestOptions.headers,
1537
+ authRequired: requestOptions.authRequired,
1538
+ customErrorHandler: requestOptions.customErrorHandler
1539
+ });
1540
+ }
1541
+ var RelayFetchSchema = zod.z.object({
1542
+ url: zod.z.string().url().describe("The URL to fetch (will be proxied through Relay)"),
1543
+ method: zod.z.enum(["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]).optional().describe("HTTP method"),
1544
+ body: zod.z.string().optional().describe("Request body as a string"),
1545
+ authenticationId: zod.z.number().int().optional().describe("Zapier authentication ID to use for the request"),
1546
+ callbackUrl: zod.z.string().url().optional().describe("URL to send async response to (makes request async)"),
1547
+ authenticationTemplate: zod.z.string().optional().describe(
1548
+ "Optional JSON string authentication template to bypass Notary lookup"
1549
+ ),
1550
+ headers: zod.z.record(zod.z.string()).optional().describe("Request headers")
1551
+ }).describe("Make authenticated HTTP requests through Zapier's Relay service");
1552
+ var AppItemSchema = withFormatter(
1553
+ zod.z.object({
1554
+ key: zod.z.string(),
1555
+ name: zod.z.string().optional(),
1556
+ description: zod.z.string().optional(),
1557
+ category: zod.z.string().optional()
1558
+ }),
1559
+ {
1560
+ format: (item) => {
1561
+ const details = [];
1562
+ if (item.description) {
1563
+ details.push({ text: item.description, style: "dim" });
1564
+ }
1565
+ if (item.category) {
1566
+ details.push({
1567
+ text: `Category: ${item.category}`,
1568
+ style: "accent"
1569
+ });
1570
+ }
1571
+ return {
1572
+ title: item.name || item.key,
1573
+ subtitle: `(${item.key})`,
1574
+ details
1575
+ };
1576
+ }
1577
+ }
1578
+ );
1579
+
1580
+ // src/functions/listApps/schemas.ts
1581
+ var ListAppsSchema = withOutputSchema(
1582
+ zod.z.object({
1583
+ category: zod.z.string().optional().describe("Filter apps by category"),
1584
+ limit: LimitPropertySchema.optional().describe(
1585
+ "Maximum number of items to return (1-200)"
1586
+ ),
1587
+ offset: OffsetPropertySchema.optional().describe(
1588
+ "Number of items to skip for pagination"
1589
+ )
1590
+ }).describe("List all available apps with optional filtering"),
1591
+ AppItemSchema
1592
+ );
1593
+
1594
+ // src/functions/listApps/info.ts
1595
+ var listAppsInfo = {
1596
+ name: listApps.name,
1597
+ inputSchema: ListAppsSchema,
1598
+ implementation: listApps
1599
+ };
1600
+ var GetAppSchema = zod.z.object({
1601
+ appKey: AppKeyPropertySchema.describe(
1602
+ "App key or slug to fetch (e.g., google-sheets, slack, github)"
1603
+ )
1604
+ }).describe("Get detailed information about a specific app");
1605
+
1606
+ // src/functions/getApp/info.ts
1607
+ var getAppInfo = {
1608
+ name: getApp.name,
1609
+ inputSchema: GetAppSchema,
1610
+ implementation: getApp
1611
+ };
1612
+ var ActionItemSchema = withFormatter(
1613
+ zod.z.object({
1614
+ key: zod.z.string(),
1615
+ name: zod.z.string().optional(),
1616
+ type: zod.z.string(),
1617
+ appKey: zod.z.string().optional(),
1618
+ description: zod.z.string().optional()
1619
+ }),
1620
+ {
1621
+ format: (item) => {
1622
+ const details = [];
1623
+ details.push({ text: `Type: ${item.type}`, style: "accent" });
1624
+ if (item.appKey) {
1625
+ details.push({ text: `App: ${item.appKey}`, style: "normal" });
1626
+ }
1627
+ if (item.description) {
1628
+ details.push({ text: item.description, style: "dim" });
1629
+ }
1630
+ return {
1631
+ title: item.name || item.key,
1632
+ subtitle: `(${item.key})`,
1633
+ details
1634
+ };
1635
+ }
1636
+ }
1637
+ );
1638
+
1639
+ // src/functions/listActions/schemas.ts
1640
+ var ListActionsSchema = withOutputSchema(
1641
+ zod.z.object({
1642
+ appKey: AppKeyPropertySchema.optional(),
1643
+ type: ActionTypePropertySchema.optional().describe(
1644
+ "Filter actions by type"
1645
+ )
1646
+ }).describe("List all actions for a specific app"),
1647
+ ActionItemSchema
1648
+ );
1649
+
1650
+ // src/functions/listActions/info.ts
1651
+ var listActionsInfo = {
1652
+ name: listActions.name,
1653
+ inputSchema: ListActionsSchema,
1654
+ implementation: listActions
1655
+ };
1656
+ var GetActionSchema = zod.z.object({
1657
+ appKey: AppKeyPropertySchema,
1658
+ actionType: ActionTypePropertySchema,
1659
+ actionKey: ActionKeyPropertySchema
1660
+ }).describe("Get detailed information about a specific action");
1661
+
1662
+ // src/functions/getAction/info.ts
1663
+ var getActionInfo = {
1664
+ name: getAction.name,
1665
+ inputSchema: GetActionSchema,
1666
+ implementation: getAction
1667
+ };
1668
+ var RunActionSchema = zod.z.object({
1669
+ appKey: AppKeyPropertySchema,
1670
+ actionType: ActionTypePropertySchema,
1671
+ actionKey: ActionKeyPropertySchema,
1672
+ inputs: InputsPropertySchema.optional().describe(
1673
+ "Input parameters for the action"
1674
+ ),
1675
+ authenticationId: AuthenticationIdPropertySchema.optional()
1676
+ }).describe("Execute an action with the given inputs");
1677
+
1678
+ // src/functions/runAction/info.ts
1679
+ var runActionInfo = {
1680
+ name: runAction.name,
1681
+ inputSchema: RunActionSchema,
1682
+ implementation: runAction
1683
+ };
1684
+ var AuthItemSchema = withFormatter(
1685
+ zod.z.object({
1686
+ id: zod.z.number(),
1687
+ title: zod.z.string().optional(),
1688
+ identifier: zod.z.string().optional(),
1689
+ account_id: zod.z.string().optional(),
1690
+ is_private: zod.z.boolean().optional(),
1691
+ shared_with_all: zod.z.boolean().optional(),
1692
+ marked_stale_at: zod.z.string().optional()
1693
+ }),
1694
+ {
1695
+ format: (item) => {
1696
+ const details = [];
1697
+ if (item.identifier) {
1698
+ details.push({
1699
+ text: `Identifier: ${item.identifier}`,
1700
+ style: "accent"
1701
+ });
1702
+ }
1703
+ details.push({
1704
+ text: `Account: ${item.account_id || "unknown"} | Private: ${item.is_private || false} | Shared: ${item.shared_with_all || false}`,
1705
+ style: "dim"
1706
+ });
1707
+ if (item.marked_stale_at) {
1708
+ details.push({
1709
+ text: `\u26A0\uFE0F Marked stale: ${new Date(item.marked_stale_at).toLocaleDateString()}`,
1710
+ style: "warning"
1711
+ });
1712
+ }
1713
+ return {
1714
+ title: item.title || `Authentication ${item.id}`,
1715
+ subtitle: `(ID: ${item.id})`,
1716
+ details
1717
+ };
1718
+ }
1719
+ }
1720
+ );
1721
+
1722
+ // src/functions/listAuthentications/schemas.ts
1723
+ var ListAuthenticationsSchema = withOutputSchema(
1724
+ zod.z.object({
1725
+ appKey: AppKeyPropertySchema.optional().describe(
1726
+ "App slug to get authentications for (e.g., 'slack', 'github')"
1727
+ ),
1728
+ search: zod.z.string().optional().describe("Search term to filter authentications by title"),
1729
+ title: zod.z.string().optional().describe("Filter authentications by exact title match"),
1730
+ account_id: zod.z.string().optional().describe("Filter by account ID"),
1731
+ owner: zod.z.string().optional().describe("Filter by owner"),
1732
+ limit: LimitPropertySchema.optional().describe(
1733
+ "Maximum number of items to return (1-200)"
1734
+ ),
1735
+ offset: OffsetPropertySchema.optional().describe(
1736
+ "Number of items to skip for pagination"
1737
+ )
1738
+ }).describe("List available authentications with optional filtering"),
1739
+ AuthItemSchema
1740
+ );
1741
+
1742
+ // src/functions/listAuthentications/info.ts
1743
+ var listAuthenticationsInfo = {
1744
+ name: listAuthentications.name,
1745
+ inputSchema: ListAuthenticationsSchema,
1746
+ implementation: listAuthentications
1747
+ };
1748
+ var GetAuthenticationSchema = withOutputSchema(
1749
+ zod.z.object({
1750
+ authenticationId: zod.z.number().int().positive().describe("Authentication ID to retrieve")
1751
+ }).describe("Get a specific authentication by ID"),
1752
+ AuthItemSchema
1753
+ );
1754
+
1755
+ // src/functions/getAuthentication/info.ts
1756
+ var getAuthenticationInfo = {
1757
+ name: getAuthentication.name,
1758
+ inputSchema: GetAuthenticationSchema,
1759
+ implementation: getAuthentication
1760
+ };
1761
+ var FindFirstAuthenticationSchema = withOutputSchema(
1762
+ zod.z.object({
1763
+ appKey: AppKeyPropertySchema.optional().describe(
1764
+ "App slug to get authentications for (e.g., 'slack', 'github')"
1765
+ ),
1766
+ search: zod.z.string().optional().describe("Search term to filter authentications by title"),
1767
+ title: zod.z.string().optional().describe("Filter authentications by exact title match"),
1768
+ account_id: zod.z.string().optional().describe("Filter by account ID"),
1769
+ owner: zod.z.string().optional().describe("Filter by owner"),
1770
+ limit: LimitPropertySchema.optional().describe(
1771
+ "Maximum number of items to return (1-200)"
1772
+ ),
1773
+ offset: OffsetPropertySchema.optional().describe(
1774
+ "Number of items to skip for pagination"
1775
+ )
1776
+ }).describe("Find the first authentication matching the criteria"),
1777
+ AuthItemSchema
1778
+ );
1779
+
1780
+ // src/functions/findFirstAuthentication/info.ts
1781
+ var findFirstAuthenticationInfo = {
1782
+ name: findFirstAuthentication.name,
1783
+ inputSchema: FindFirstAuthenticationSchema,
1784
+ implementation: findFirstAuthentication
1785
+ };
1786
+ var FindUniqueAuthenticationSchema = withOutputSchema(
1787
+ zod.z.object({
1788
+ appKey: AppKeyPropertySchema.optional().describe(
1789
+ "App slug to get authentications for (e.g., 'slack', 'github')"
1790
+ ),
1791
+ search: zod.z.string().optional().describe("Search term to filter authentications by title"),
1792
+ title: zod.z.string().optional().describe("Filter authentications by exact title match"),
1793
+ account_id: zod.z.string().optional().describe("Filter by account ID"),
1794
+ owner: zod.z.string().optional().describe("Filter by owner"),
1795
+ limit: LimitPropertySchema.optional().describe(
1796
+ "Maximum number of items to return (1-200)"
1797
+ ),
1798
+ offset: OffsetPropertySchema.optional().describe(
1799
+ "Number of items to skip for pagination"
1800
+ )
1801
+ }).describe("Find a unique authentication matching the criteria"),
1802
+ AuthItemSchema
1803
+ );
1804
+
1805
+ // src/functions/findUniqueAuthentication/info.ts
1806
+ var findUniqueAuthenticationInfo = {
1807
+ name: findUniqueAuthentication.name,
1808
+ inputSchema: FindUniqueAuthenticationSchema,
1809
+ implementation: findUniqueAuthentication
1810
+ };
1811
+ var FieldItemSchema = withFormatter(
1812
+ zod.z.object({
1813
+ key: zod.z.string(),
1814
+ name: zod.z.string().optional(),
1815
+ description: zod.z.string().optional()
1816
+ }),
1817
+ {
1818
+ format: (item) => {
1819
+ const details = [];
1820
+ if (item.description) {
1821
+ details.push({ text: item.description, style: "dim" });
1822
+ }
1823
+ return {
1824
+ title: item.name || item.key,
1825
+ subtitle: `(${item.key})`,
1826
+ details
1827
+ };
1828
+ }
1829
+ }
1830
+ );
1831
+
1832
+ // src/functions/listFields/schemas.ts
1833
+ var ListFieldsSchema = withOutputSchema(
1834
+ zod.z.object({
1835
+ appKey: AppKeyPropertySchema,
1836
+ actionType: ActionTypePropertySchema,
1837
+ actionKey: ActionKeyPropertySchema,
1838
+ authenticationId: AuthenticationIdPropertySchema.optional(),
1839
+ params: ParamsPropertySchema.optional().describe(
1840
+ "Additional parameters that may affect available fields"
1841
+ )
1842
+ }).describe("Get the input fields required for a specific action"),
1843
+ FieldItemSchema
1844
+ );
1845
+
1846
+ // src/functions/listFields/info.ts
1847
+ var listFieldsInfo = {
1848
+ name: listFields.name,
1849
+ inputSchema: ListFieldsSchema,
1850
+ implementation: listFields
1851
+ };
1852
+ var GenerateTypesSchema = zod.z.object({
1853
+ appKey: AppKeyPropertySchema.describe("App key to generate SDK code for"),
1854
+ authenticationId: AuthenticationIdPropertySchema.optional(),
1855
+ output: OutputPropertySchema.optional().describe(
1856
+ "Output file path (defaults to generated/<appKey>.ts)"
1857
+ ),
1858
+ debug: DebugPropertySchema.describe(
1859
+ "Enable debug logging during generation"
1860
+ )
1861
+ }).describe("Generate TypeScript SDK code for a specific app");
1862
+
1863
+ // src/functions/generateTypes/info.ts
1864
+ var generateTypesInfo = {
1865
+ name: generateTypes.name,
1866
+ inputSchema: GenerateTypesSchema,
1867
+ implementation: generateTypes
1868
+ };
1869
+ var BundleCodeSchema = zod.z.object({
1870
+ input: zod.z.string().min(1).describe("Input TypeScript file path to bundle"),
1871
+ output: OutputPropertySchema.optional().describe(
1872
+ "Output file path (defaults to input with .js extension)"
1873
+ ),
1874
+ string: zod.z.boolean().default(false).describe("Return bundled code as string instead of writing to file"),
1875
+ minify: zod.z.boolean().default(false).describe("Minify the bundled output"),
1876
+ target: zod.z.string().default("es2017").describe("ECMAScript target version"),
1877
+ cjs: zod.z.boolean().default(false).describe("Output CommonJS format instead of ESM")
1878
+ }).describe("Bundle TypeScript code into executable JavaScript");
1879
+
1880
+ // src/functions/bundleCode/info.ts
1881
+ var bundleCodeInfo = {
1882
+ name: bundleCode.name,
1883
+ inputSchema: BundleCodeSchema,
1884
+ implementation: bundleCode
1885
+ };
1886
+
1887
+ // src/functions/fetch/info.ts
1888
+ var fetchInfo = {
1889
+ name: "fetch",
1890
+ inputSchema: RelayFetchSchema,
1891
+ implementation: fetch
1892
+ };
1893
+
1894
+ // src/sdk.ts
1895
+ var functionRegistry = [
1896
+ listAppsInfo,
1897
+ getAppInfo,
1898
+ listActionsInfo,
1899
+ getActionInfo,
1900
+ runActionInfo,
1901
+ listAuthenticationsInfo,
1902
+ getAuthenticationInfo,
1903
+ findFirstAuthenticationInfo,
1904
+ findUniqueAuthenticationInfo,
1905
+ listFieldsInfo,
1906
+ generateTypesInfo,
1907
+ bundleCodeInfo,
1908
+ fetchInfo
1909
+ ];
1910
+ function createZapierSdk(options = {}) {
1911
+ const {
1912
+ fetch: customFetch = globalThis.fetch,
1913
+ baseUrl = "https://zapier.com",
1914
+ token,
1915
+ getToken,
1916
+ onEvent,
1917
+ debug = false
1918
+ } = options;
1919
+ const api = createZapierApi({
1920
+ baseUrl,
1921
+ token,
1922
+ getToken,
1923
+ debug,
1924
+ fetch: customFetch,
1925
+ onEvent
1926
+ });
1927
+ const baseSdk = {
1928
+ // Registry for CLI
1929
+ __registry: functionRegistry,
1930
+ // Function implementations with API config injection
1931
+ listApps: (options2 = {}) => listApps({ ...options2, api }),
1932
+ getApp: (options2) => getApp({ ...options2, api }),
1933
+ listActions: (options2 = {}) => listActions({ ...options2, api }),
1934
+ getAction: (options2) => getAction({ ...options2, api }),
1935
+ runAction: (options2) => runAction({ ...options2, api }),
1936
+ listAuthentications: (options2 = {}) => listAuthentications({ ...options2, api }),
1937
+ getAuthentication: (options2) => getAuthentication({ ...options2, api }),
1938
+ findFirstAuthentication: (options2 = {}) => findFirstAuthentication({ ...options2, api }),
1939
+ findUniqueAuthentication: (options2 = {}) => findUniqueAuthentication({ ...options2, api }),
1940
+ listFields: (options2) => listFields({ ...options2, api }),
1941
+ generateTypes: (options2) => generateTypes({ ...options2, api }),
1942
+ bundleCode: (options2) => bundleCode(options2),
1943
+ // No API config needed
1944
+ fetch: (options2) => fetch({ ...options2, api })
1945
+ };
1946
+ const fullSdk = {
1947
+ ...baseSdk,
1948
+ // Add plugins - apps plugin gets the base SDK cast as full ZapierSdk type
1949
+ // This is safe because by the time plugin functions are called, fullSdk will be complete
1950
+ apps: createAppsPlugin({
1951
+ sdk: baseSdk
1952
+ })
1953
+ };
1954
+ return fullSdk;
1955
+ }
1956
+
1957
+ exports.ActionKeyPropertySchema = ActionKeyPropertySchema;
1958
+ exports.ActionTypePropertySchema = ActionTypePropertySchema;
1959
+ exports.AppKeyPropertySchema = AppKeyPropertySchema;
1960
+ exports.AppNotFoundError = AppNotFoundError;
1961
+ exports.AuthenticationIdPropertySchema = AuthenticationIdPropertySchema;
1962
+ exports.DebugPropertySchema = DebugPropertySchema;
1963
+ exports.InputsPropertySchema = InputsPropertySchema;
1964
+ exports.LimitPropertySchema = LimitPropertySchema;
1965
+ exports.OffsetPropertySchema = OffsetPropertySchema;
1966
+ exports.OutputPropertySchema = OutputPropertySchema;
1967
+ exports.ParamsPropertySchema = ParamsPropertySchema;
1968
+ exports.RelayFetchSchema = RelayFetchSchema;
1969
+ exports.ZapierSdkError = ZapierSdkError;
1970
+ exports.actionKeyResolver = actionKeyResolver;
1971
+ exports.actionTypeResolver = actionTypeResolver;
1972
+ exports.appKeyResolver = appKeyResolver;
1973
+ exports.authenticationIdResolver = authenticationIdResolver;
1974
+ exports.bundleCode = bundleCode;
1975
+ exports.createAppsPlugin = createAppsPlugin;
1976
+ exports.createZapierSdk = createZapierSdk;
1977
+ exports.fetch = fetch;
1978
+ exports.findFirstAuthentication = findFirstAuthentication;
1979
+ exports.findUniqueAuthentication = findUniqueAuthentication;
1980
+ exports.generateTypes = generateTypes;
1981
+ exports.getAction = getAction;
1982
+ exports.getApp = getApp;
1983
+ exports.getAuthentication = getAuthentication;
1984
+ exports.getResolutionOrder = getResolutionOrder;
1985
+ exports.getResolutionOrderForParams = getResolutionOrderForParams;
1986
+ exports.getResolvableParams = getResolvableParams;
1987
+ exports.getResolver = getResolver;
1988
+ exports.getResolversForMissingParams = getResolversForMissingParams;
1989
+ exports.getTokenFromCliLogin = getTokenFromCliLogin;
1990
+ exports.getTokenFromEnv = getTokenFromEnv;
1991
+ exports.getTokenFromEnvOrConfig = getTokenFromEnvOrConfig;
1992
+ exports.hasResolver = hasResolver;
1993
+ exports.inputsResolver = inputsResolver;
1994
+ exports.isPositional = isPositional;
1995
+ exports.listActions = listActions;
1996
+ exports.listApps = listApps;
1997
+ exports.listAuthentications = listAuthentications;
1998
+ exports.listFields = listFields;
1999
+ exports.relayFetch = relayFetch;
2000
+ exports.resolverRegistry = resolverRegistry;
2001
+ exports.runAction = runAction;