@zapier/zapier-sdk 0.4.0 → 0.5.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 (374) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/api/auth.d.ts +9 -0
  3. package/dist/api/auth.d.ts.map +1 -0
  4. package/dist/api/auth.js +25 -0
  5. package/dist/api/client.d.ts +9 -0
  6. package/dist/api/client.d.ts.map +1 -0
  7. package/dist/api/client.js +322 -0
  8. package/dist/api/debug.d.ts +13 -0
  9. package/dist/api/debug.d.ts.map +1 -0
  10. package/dist/api/debug.js +55 -0
  11. package/dist/api/index.d.ts +29 -0
  12. package/dist/api/index.d.ts.map +1 -0
  13. package/dist/api/index.js +41 -0
  14. package/dist/api/polling.d.ts +16 -0
  15. package/dist/api/polling.d.ts.map +1 -0
  16. package/dist/api/polling.js +45 -0
  17. package/dist/api/schemas.d.ts +2473 -0
  18. package/dist/api/schemas.d.ts.map +1 -0
  19. package/dist/api/schemas.js +355 -0
  20. package/dist/api/types.d.ts +75 -0
  21. package/dist/api/types.d.ts.map +1 -0
  22. package/dist/api/types.js +11 -0
  23. package/dist/auth.d.ts +34 -0
  24. package/dist/auth.d.ts.map +1 -0
  25. package/dist/auth.js +47 -0
  26. package/dist/constants.d.ts +10 -0
  27. package/dist/constants.d.ts.map +1 -0
  28. package/dist/constants.js +9 -0
  29. package/dist/index.cjs +2134 -1444
  30. package/dist/index.d.mts +2456 -584
  31. package/dist/index.d.ts +17 -840
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +20 -0
  34. package/dist/index.mjs +2118 -1428
  35. package/dist/plugins/api/index.d.ts +14 -0
  36. package/dist/plugins/api/index.d.ts.map +1 -0
  37. package/dist/plugins/api/index.js +21 -0
  38. package/dist/plugins/apps/index.d.ts +11 -0
  39. package/dist/plugins/apps/index.d.ts.map +1 -0
  40. package/dist/plugins/apps/index.js +91 -0
  41. package/dist/plugins/apps/types.d.ts +30 -0
  42. package/dist/plugins/apps/types.d.ts.map +1 -0
  43. package/dist/plugins/apps/types.js +2 -0
  44. package/dist/plugins/fetch/index.d.ts +21 -0
  45. package/dist/plugins/fetch/index.d.ts.map +1 -0
  46. package/dist/plugins/fetch/index.js +20 -0
  47. package/dist/plugins/findFirstAuthentication/index.d.ts +20 -0
  48. package/dist/plugins/findFirstAuthentication/index.d.ts.map +1 -0
  49. package/dist/plugins/findFirstAuthentication/index.js +24 -0
  50. package/dist/plugins/findFirstAuthentication/index.test.d.ts +2 -0
  51. package/dist/plugins/findFirstAuthentication/index.test.d.ts.map +1 -0
  52. package/dist/plugins/findFirstAuthentication/index.test.js +171 -0
  53. package/dist/plugins/findFirstAuthentication/schemas.d.ts +29 -0
  54. package/dist/plugins/findFirstAuthentication/schemas.d.ts.map +1 -0
  55. package/dist/plugins/findFirstAuthentication/schemas.js +18 -0
  56. package/dist/plugins/findUniqueAuthentication/index.d.ts +20 -0
  57. package/dist/plugins/findUniqueAuthentication/index.d.ts.map +1 -0
  58. package/dist/plugins/findUniqueAuthentication/index.js +31 -0
  59. package/dist/plugins/findUniqueAuthentication/index.test.d.ts +2 -0
  60. package/dist/plugins/findUniqueAuthentication/index.test.d.ts.map +1 -0
  61. package/dist/plugins/findUniqueAuthentication/index.test.js +152 -0
  62. package/dist/plugins/findUniqueAuthentication/schemas.d.ts +29 -0
  63. package/dist/plugins/findUniqueAuthentication/schemas.d.ts.map +1 -0
  64. package/dist/plugins/findUniqueAuthentication/schemas.js +18 -0
  65. package/dist/plugins/getAction/index.d.ts +23 -0
  66. package/dist/plugins/getAction/index.d.ts.map +1 -0
  67. package/dist/plugins/getAction/index.js +28 -0
  68. package/dist/plugins/getAction/index.test.d.ts +2 -0
  69. package/dist/plugins/getAction/index.test.d.ts.map +1 -0
  70. package/dist/plugins/getAction/index.test.js +186 -0
  71. package/dist/plugins/getAction/schemas.d.ts +23 -0
  72. package/dist/plugins/getAction/schemas.d.ts.map +1 -0
  73. package/dist/plugins/getAction/schemas.js +10 -0
  74. package/dist/plugins/getApp/index.d.ts +22 -0
  75. package/dist/plugins/getApp/index.d.ts.map +1 -0
  76. package/dist/plugins/getApp/index.js +39 -0
  77. package/dist/plugins/getApp/index.test.d.ts +2 -0
  78. package/dist/plugins/getApp/index.test.d.ts.map +1 -0
  79. package/dist/plugins/getApp/index.test.js +100 -0
  80. package/dist/plugins/getApp/schemas.d.ts +18 -0
  81. package/dist/plugins/getApp/schemas.d.ts.map +1 -0
  82. package/dist/plugins/getApp/schemas.js +10 -0
  83. package/dist/plugins/getAuthentication/index.d.ts +22 -0
  84. package/dist/plugins/getAuthentication/index.d.ts.map +1 -0
  85. package/dist/plugins/getAuthentication/index.js +41 -0
  86. package/dist/plugins/getAuthentication/index.test.d.ts +2 -0
  87. package/dist/plugins/getAuthentication/index.test.d.ts.map +1 -0
  88. package/dist/plugins/getAuthentication/index.test.js +205 -0
  89. package/dist/plugins/getAuthentication/schemas.d.ts +17 -0
  90. package/dist/plugins/getAuthentication/schemas.d.ts.map +1 -0
  91. package/dist/plugins/getAuthentication/schemas.js +11 -0
  92. package/dist/plugins/getProfile/index.d.ts +23 -0
  93. package/dist/plugins/getProfile/index.d.ts.map +1 -0
  94. package/dist/plugins/getProfile/index.js +29 -0
  95. package/dist/plugins/getProfile/schemas.d.ts +13 -0
  96. package/dist/plugins/getProfile/schemas.d.ts.map +1 -0
  97. package/dist/plugins/getProfile/schemas.js +5 -0
  98. package/dist/plugins/listActions/index.d.ts +28 -0
  99. package/dist/plugins/listActions/index.d.ts.map +1 -0
  100. package/dist/plugins/listActions/index.js +61 -0
  101. package/dist/plugins/listActions/index.test.d.ts +2 -0
  102. package/dist/plugins/listActions/index.test.d.ts.map +1 -0
  103. package/dist/plugins/listActions/index.test.js +467 -0
  104. package/dist/plugins/listActions/schemas.d.ts +29 -0
  105. package/dist/plugins/listActions/schemas.d.ts.map +1 -0
  106. package/dist/plugins/listActions/schemas.js +21 -0
  107. package/dist/plugins/listApps/index.d.ts +28 -0
  108. package/dist/plugins/listApps/index.d.ts.map +1 -0
  109. package/dist/plugins/listApps/index.js +62 -0
  110. package/dist/plugins/listApps/index.test.d.ts +2 -0
  111. package/dist/plugins/listApps/index.test.d.ts.map +1 -0
  112. package/dist/plugins/listApps/index.test.js +313 -0
  113. package/dist/plugins/listApps/schemas.d.ts +30 -0
  114. package/dist/plugins/listApps/schemas.d.ts.map +1 -0
  115. package/dist/plugins/listApps/schemas.js +23 -0
  116. package/dist/plugins/listAuthentications/index.d.ts +28 -0
  117. package/dist/plugins/listAuthentications/index.d.ts.map +1 -0
  118. package/dist/plugins/listAuthentications/index.js +77 -0
  119. package/dist/plugins/listAuthentications/index.test.d.ts +2 -0
  120. package/dist/plugins/listAuthentications/index.test.d.ts.map +1 -0
  121. package/dist/plugins/listAuthentications/index.test.js +564 -0
  122. package/dist/plugins/listAuthentications/schemas.d.ts +38 -0
  123. package/dist/plugins/listAuthentications/schemas.d.ts.map +1 -0
  124. package/dist/plugins/listAuthentications/schemas.js +28 -0
  125. package/dist/plugins/listInputFields/index.d.ts +28 -0
  126. package/dist/plugins/listInputFields/index.d.ts.map +1 -0
  127. package/dist/plugins/listInputFields/index.js +133 -0
  128. package/dist/plugins/listInputFields/index.test.d.ts +2 -0
  129. package/dist/plugins/listInputFields/index.test.d.ts.map +1 -0
  130. package/dist/plugins/listInputFields/index.test.js +325 -0
  131. package/dist/plugins/listInputFields/schemas.d.ts +38 -0
  132. package/dist/plugins/listInputFields/schemas.d.ts.map +1 -0
  133. package/dist/plugins/listInputFields/schemas.js +22 -0
  134. package/dist/plugins/registry/index.d.ts +11 -0
  135. package/dist/plugins/registry/index.d.ts.map +1 -0
  136. package/dist/plugins/registry/index.js +14 -0
  137. package/dist/plugins/request/index.d.ts +19 -0
  138. package/dist/plugins/request/index.d.ts.map +1 -0
  139. package/dist/plugins/request/index.js +62 -0
  140. package/dist/plugins/request/index.test.d.ts +2 -0
  141. package/dist/plugins/request/index.test.d.ts.map +1 -0
  142. package/dist/plugins/request/index.test.js +256 -0
  143. package/dist/plugins/request/schemas.d.ts +69 -0
  144. package/dist/plugins/request/schemas.d.ts.map +1 -0
  145. package/dist/plugins/request/schemas.js +42 -0
  146. package/dist/plugins/runAction/index.d.ts +28 -0
  147. package/dist/plugins/runAction/index.d.ts.map +1 -0
  148. package/dist/plugins/runAction/index.js +86 -0
  149. package/dist/plugins/runAction/index.test.d.ts +2 -0
  150. package/dist/plugins/runAction/index.test.d.ts.map +1 -0
  151. package/dist/plugins/runAction/index.test.js +320 -0
  152. package/dist/plugins/runAction/schemas.d.ts +37 -0
  153. package/dist/plugins/runAction/schemas.d.ts.map +1 -0
  154. package/dist/plugins/runAction/schemas.js +22 -0
  155. package/dist/resolvers/actionKey.d.ts +9 -0
  156. package/dist/resolvers/actionKey.d.ts.map +1 -0
  157. package/dist/resolvers/actionKey.js +19 -0
  158. package/dist/resolvers/actionType.d.ts +9 -0
  159. package/dist/resolvers/actionType.d.ts.map +1 -0
  160. package/dist/resolvers/actionType.js +22 -0
  161. package/dist/resolvers/appKey.d.ts +7 -0
  162. package/dist/resolvers/appKey.d.ts.map +1 -0
  163. package/dist/resolvers/appKey.js +5 -0
  164. package/dist/resolvers/authenticationId.d.ts +9 -0
  165. package/dist/resolvers/authenticationId.d.ts.map +1 -0
  166. package/dist/resolvers/authenticationId.js +33 -0
  167. package/dist/resolvers/index.d.ts +40 -0
  168. package/dist/resolvers/index.d.ts.map +1 -0
  169. package/dist/resolvers/index.js +91 -0
  170. package/dist/resolvers/inputs.d.ts +8 -0
  171. package/dist/resolvers/inputs.d.ts.map +1 -0
  172. package/dist/resolvers/inputs.js +14 -0
  173. package/dist/schemas/Action.d.ts +243 -0
  174. package/dist/schemas/Action.d.ts.map +1 -0
  175. package/dist/schemas/Action.js +34 -0
  176. package/dist/schemas/App.d.ts +26 -0
  177. package/dist/schemas/App.d.ts.map +1 -0
  178. package/dist/schemas/App.js +22 -0
  179. package/dist/schemas/Auth.d.ts +161 -0
  180. package/dist/schemas/Auth.d.ts.map +1 -0
  181. package/dist/schemas/Auth.js +41 -0
  182. package/dist/schemas/Field.d.ts +144 -0
  183. package/dist/schemas/Field.d.ts.map +1 -0
  184. package/dist/schemas/Field.js +105 -0
  185. package/dist/schemas/UserProfile.d.ts +163 -0
  186. package/dist/schemas/UserProfile.d.ts.map +1 -0
  187. package/dist/schemas/UserProfile.js +29 -0
  188. package/dist/sdk.d.ts +10 -0
  189. package/dist/sdk.d.ts.map +1 -0
  190. package/dist/sdk.js +94 -0
  191. package/dist/sdk.test.d.ts +2 -0
  192. package/dist/sdk.test.d.ts.map +1 -0
  193. package/dist/sdk.test.js +135 -0
  194. package/dist/types/domain.d.ts +36 -0
  195. package/dist/types/domain.d.ts.map +1 -0
  196. package/dist/types/domain.js +1 -0
  197. package/dist/types/domain.test.d.ts +2 -0
  198. package/dist/types/domain.test.d.ts.map +1 -0
  199. package/dist/types/domain.test.js +39 -0
  200. package/dist/types/errors.d.ts +143 -0
  201. package/dist/types/errors.d.ts.map +1 -0
  202. package/dist/types/errors.js +187 -0
  203. package/dist/types/events.d.ts +38 -0
  204. package/dist/types/events.d.ts.map +1 -0
  205. package/dist/types/events.js +7 -0
  206. package/dist/types/functions.d.ts +26 -0
  207. package/dist/types/functions.d.ts.map +1 -0
  208. package/dist/types/functions.js +4 -0
  209. package/dist/types/plugin.d.ts +61 -0
  210. package/dist/types/plugin.d.ts.map +1 -0
  211. package/dist/types/plugin.js +9 -0
  212. package/dist/types/properties.d.ts +22 -0
  213. package/dist/types/properties.d.ts.map +1 -0
  214. package/dist/types/properties.js +50 -0
  215. package/dist/types/sdk.d.ts +43 -0
  216. package/dist/types/sdk.d.ts.map +1 -0
  217. package/dist/types/sdk.js +4 -0
  218. package/dist/utils/array-utils.d.ts +31 -0
  219. package/dist/utils/array-utils.d.ts.map +1 -0
  220. package/dist/utils/array-utils.js +36 -0
  221. package/dist/utils/array-utils.test.d.ts +2 -0
  222. package/dist/utils/array-utils.test.d.ts.map +1 -0
  223. package/dist/utils/array-utils.test.js +107 -0
  224. package/dist/utils/domain-utils.d.ts +78 -0
  225. package/dist/utils/domain-utils.d.ts.map +1 -0
  226. package/dist/utils/domain-utils.js +218 -0
  227. package/dist/utils/domain-utils.test.d.ts +2 -0
  228. package/dist/utils/domain-utils.test.d.ts.map +1 -0
  229. package/dist/utils/domain-utils.test.js +192 -0
  230. package/dist/utils/function-utils.d.ts +45 -0
  231. package/dist/utils/function-utils.d.ts.map +1 -0
  232. package/dist/utils/function-utils.js +158 -0
  233. package/dist/utils/function-utils.test.d.ts +2 -0
  234. package/dist/utils/function-utils.test.d.ts.map +1 -0
  235. package/dist/utils/function-utils.test.js +110 -0
  236. package/dist/utils/pagination-utils.d.ts +37 -0
  237. package/dist/utils/pagination-utils.d.ts.map +1 -0
  238. package/dist/utils/pagination-utils.js +165 -0
  239. package/dist/utils/pagination-utils.test.d.ts +17 -0
  240. package/dist/utils/pagination-utils.test.d.ts.map +1 -0
  241. package/dist/utils/pagination-utils.test.js +461 -0
  242. package/dist/utils/schema-utils.d.ts +45 -0
  243. package/dist/utils/schema-utils.d.ts.map +1 -0
  244. package/dist/utils/schema-utils.js +65 -0
  245. package/dist/utils/validation.d.ts +4 -0
  246. package/dist/utils/validation.d.ts.map +1 -0
  247. package/dist/utils/validation.js +30 -0
  248. package/dist/utils/validation.test.d.ts +2 -0
  249. package/dist/utils/validation.test.d.ts.map +1 -0
  250. package/dist/utils/validation.test.js +43 -0
  251. package/package.json +12 -3
  252. package/src/api/client.ts +403 -167
  253. package/src/api/debug.ts +10 -1
  254. package/src/api/index.ts +0 -2
  255. package/src/api/polling.ts +31 -14
  256. package/src/api/schemas.ts +387 -0
  257. package/src/api/types.ts +73 -138
  258. package/src/constants.ts +10 -0
  259. package/src/index.ts +45 -20
  260. package/src/plugins/api/index.ts +47 -0
  261. package/src/plugins/apps/index.ts +36 -31
  262. package/src/plugins/apps/types.ts +24 -12
  263. package/src/plugins/fetch/index.ts +58 -0
  264. package/src/plugins/findFirstAuthentication/index.test.ts +206 -0
  265. package/src/plugins/findFirstAuthentication/index.ts +55 -0
  266. package/src/plugins/findFirstAuthentication/schemas.ts +41 -0
  267. package/src/plugins/findUniqueAuthentication/index.test.ts +197 -0
  268. package/src/plugins/findUniqueAuthentication/index.ts +72 -0
  269. package/src/plugins/findUniqueAuthentication/schemas.ts +42 -0
  270. package/src/plugins/getAction/index.test.ts +239 -0
  271. package/src/plugins/getAction/index.ts +57 -0
  272. package/src/plugins/getAction/schemas.ts +33 -0
  273. package/src/plugins/getApp/index.test.ts +127 -0
  274. package/src/plugins/getApp/index.ts +66 -0
  275. package/src/plugins/getApp/schemas.ts +38 -0
  276. package/src/plugins/getAuthentication/index.test.ts +284 -0
  277. package/src/plugins/getAuthentication/index.ts +86 -0
  278. package/src/plugins/getAuthentication/schemas.ts +31 -0
  279. package/src/plugins/getProfile/index.ts +55 -0
  280. package/src/plugins/getProfile/schemas.ts +26 -0
  281. package/src/plugins/listActions/index.test.ts +582 -0
  282. package/src/plugins/listActions/index.ts +115 -0
  283. package/src/plugins/listActions/schemas.ts +54 -0
  284. package/src/plugins/listApps/index.test.ts +357 -0
  285. package/src/plugins/listApps/index.ts +121 -0
  286. package/src/plugins/listApps/schemas.ts +49 -0
  287. package/src/plugins/listAuthentications/index.test.ts +709 -0
  288. package/src/plugins/listAuthentications/index.ts +136 -0
  289. package/src/plugins/listAuthentications/schemas.ts +60 -0
  290. package/src/plugins/listInputFields/index.test.ts +408 -0
  291. package/src/plugins/listInputFields/index.ts +204 -0
  292. package/src/plugins/listInputFields/schemas.ts +56 -0
  293. package/src/plugins/registry/index.ts +30 -0
  294. package/src/plugins/request/index.test.ts +329 -0
  295. package/src/plugins/request/index.ts +103 -0
  296. package/src/plugins/request/schemas.ts +64 -0
  297. package/src/plugins/runAction/index.test.ts +387 -0
  298. package/src/plugins/runAction/index.ts +176 -0
  299. package/src/plugins/runAction/schemas.ts +53 -0
  300. package/src/resolvers/actionKey.ts +6 -4
  301. package/src/resolvers/actionType.ts +7 -2
  302. package/src/resolvers/appKey.ts +1 -1
  303. package/src/resolvers/authenticationId.ts +12 -3
  304. package/src/resolvers/inputs.ts +3 -1
  305. package/src/schemas/Action.ts +18 -12
  306. package/src/schemas/App.ts +11 -19
  307. package/src/schemas/Auth.ts +18 -13
  308. package/src/schemas/Field.ts +106 -11
  309. package/src/schemas/UserProfile.ts +43 -0
  310. package/src/sdk.test.ts +212 -0
  311. package/src/sdk.ts +133 -105
  312. package/src/types/domain.test.ts +50 -0
  313. package/src/types/domain.ts +43 -75
  314. package/src/types/errors.ts +275 -0
  315. package/src/types/functions.ts +27 -0
  316. package/src/types/optional-zapier-sdk-cli-login.d.ts +37 -0
  317. package/src/types/plugin.ts +105 -0
  318. package/src/types/properties.ts +4 -3
  319. package/src/types/sdk.ts +71 -46
  320. package/src/utils/array-utils.test.ts +131 -0
  321. package/src/utils/array-utils.ts +41 -0
  322. package/src/utils/domain-utils.test.ts +239 -0
  323. package/src/utils/domain-utils.ts +283 -0
  324. package/src/utils/function-utils.test.ts +141 -0
  325. package/src/utils/function-utils.ts +245 -0
  326. package/src/utils/pagination-utils.test.ts +620 -0
  327. package/src/utils/pagination-utils.ts +242 -0
  328. package/src/utils/validation.test.ts +50 -0
  329. package/src/utils/validation.ts +44 -0
  330. package/tsconfig.build.json +16 -2
  331. package/tsconfig.json +3 -1
  332. package/tsconfig.tsbuildinfo +1 -0
  333. package/tsup.config.ts +2 -0
  334. package/src/functions/bundleCode/index.ts +0 -78
  335. package/src/functions/bundleCode/info.ts +0 -9
  336. package/src/functions/bundleCode/schemas.ts +0 -30
  337. package/src/functions/fetch/index.ts +0 -180
  338. package/src/functions/fetch/info.ts +0 -8
  339. package/src/functions/fetch/schemas.ts +0 -46
  340. package/src/functions/findFirstAuthentication/index.ts +0 -24
  341. package/src/functions/findFirstAuthentication/info.ts +0 -9
  342. package/src/functions/findFirstAuthentication/schemas.ts +0 -50
  343. package/src/functions/findUniqueAuthentication/index.ts +0 -35
  344. package/src/functions/findUniqueAuthentication/info.ts +0 -9
  345. package/src/functions/findUniqueAuthentication/schemas.ts +0 -50
  346. package/src/functions/generateTypes/index.ts +0 -363
  347. package/src/functions/generateTypes/info.ts +0 -9
  348. package/src/functions/generateTypes/schemas.ts +0 -31
  349. package/src/functions/getAction/index.ts +0 -33
  350. package/src/functions/getAction/info.ts +0 -9
  351. package/src/functions/getAction/schemas.ts +0 -25
  352. package/src/functions/getApp/index.ts +0 -41
  353. package/src/functions/getApp/info.ts +0 -9
  354. package/src/functions/getApp/schemas.ts +0 -20
  355. package/src/functions/getAuthentication/index.ts +0 -50
  356. package/src/functions/getAuthentication/info.ts +0 -9
  357. package/src/functions/getAuthentication/schemas.ts +0 -29
  358. package/src/functions/listActions/index.ts +0 -149
  359. package/src/functions/listActions/info.ts +0 -9
  360. package/src/functions/listActions/schemas.ts +0 -30
  361. package/src/functions/listApps/index.ts +0 -60
  362. package/src/functions/listApps/info.ts +0 -9
  363. package/src/functions/listApps/schemas.ts +0 -32
  364. package/src/functions/listAuthentications/index.ts +0 -162
  365. package/src/functions/listAuthentications/info.ts +0 -9
  366. package/src/functions/listAuthentications/schemas.ts +0 -50
  367. package/src/functions/listFields/index.ts +0 -86
  368. package/src/functions/listFields/info.ts +0 -9
  369. package/src/functions/listFields/schemas.ts +0 -36
  370. package/src/functions/runAction/index.ts +0 -127
  371. package/src/functions/runAction/info.ts +0 -9
  372. package/src/functions/runAction/schemas.ts +0 -34
  373. package/src/plugins/apps/info.ts +0 -12
  374. /package/src/{schema-utils.ts → utils/schema-utils.ts} +0 -0
package/dist/index.cjs CHANGED
@@ -2,87 +2,7 @@
2
2
 
3
3
  var zod = require('zod');
4
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
- };
5
+ // src/types/properties.ts
86
6
  function withFormatter(schema, formatMeta) {
87
7
  schema._def.formatMeta = formatMeta;
88
8
  return schema;
@@ -108,9 +28,12 @@ function isPositional(schema) {
108
28
  return false;
109
29
  }
110
30
 
31
+ // src/constants.ts
32
+ var MAX_PAGE_LIMIT = 1e4;
33
+
111
34
  // src/types/properties.ts
112
35
  var AppKeyPropertySchema = withPositional(
113
- zod.z.string().min(1).describe("App slug (e.g., 'slack', 'github')")
36
+ zod.z.string().min(1).describe("App key (e.g., 'SlackCLIAPI')")
114
37
  );
115
38
  var ActionTypePropertySchema = zod.z.enum([
116
39
  "read",
@@ -125,20 +48,155 @@ var ActionTypePropertySchema = zod.z.enum([
125
48
  var ActionKeyPropertySchema = zod.z.string().min(1).describe("Action key to execute");
126
49
  var AuthenticationIdPropertySchema = zod.z.number().int().describe("Authentication ID to use for this action");
127
50
  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");
51
+ var LimitPropertySchema = zod.z.number().int().min(1).max(MAX_PAGE_LIMIT).default(50).describe("Maximum number of items to return");
129
52
  var OffsetPropertySchema = zod.z.number().int().min(0).default(0).describe("Number of items to skip for pagination");
130
53
  var OutputPropertySchema = zod.z.string().describe("Output file path");
131
54
  var DebugPropertySchema = zod.z.boolean().default(false).describe("Enable debug logging");
132
55
  var ParamsPropertySchema = zod.z.record(zod.z.any()).describe("Additional parameters");
133
56
 
57
+ // src/types/errors.ts
58
+ var ZapierError = class extends Error {
59
+ constructor(message, options = {}) {
60
+ super(message);
61
+ this.statusCode = options.statusCode;
62
+ this.errors = options.errors;
63
+ this.cause = options.cause;
64
+ this.response = options.response;
65
+ Object.setPrototypeOf(this, new.target.prototype);
66
+ }
67
+ };
68
+ var ZapierApiError = class extends ZapierError {
69
+ constructor(message, options = {}) {
70
+ super(message, options);
71
+ this.name = "ZapierApiError";
72
+ }
73
+ };
74
+ var ZapierAppNotFoundError = class extends ZapierError {
75
+ constructor(message, options = {}) {
76
+ super(message, options);
77
+ this.name = "ZapierAppNotFoundError";
78
+ this.appKey = options.appKey;
79
+ }
80
+ };
81
+ var ZapierValidationError = class extends ZapierError {
82
+ constructor(message, options = {}) {
83
+ super(message, options);
84
+ this.name = "ZapierValidationError";
85
+ this.details = options.details;
86
+ }
87
+ };
88
+ var ZapierUnknownError = class extends ZapierError {
89
+ constructor(message, options = {}) {
90
+ super(message, options);
91
+ this.name = "ZapierUnknownError";
92
+ }
93
+ };
94
+ var ZapierAuthenticationError = class extends ZapierError {
95
+ constructor(message, options = {}) {
96
+ super(message, options);
97
+ this.name = "ZapierAuthenticationError";
98
+ }
99
+ };
100
+ var ZapierResourceNotFoundError = class extends ZapierError {
101
+ constructor(message, options = {}) {
102
+ super(message, options);
103
+ this.name = "ZapierResourceNotFoundError";
104
+ this.resourceType = options.resourceType;
105
+ this.resourceId = options.resourceId;
106
+ }
107
+ };
108
+ var ZapierConfigurationError = class extends ZapierError {
109
+ constructor(message, options = {}) {
110
+ super(message, options);
111
+ this.name = "ZapierConfigurationError";
112
+ this.configType = options.configType;
113
+ }
114
+ };
115
+ var ZapierBundleError = class extends ZapierError {
116
+ constructor(message, options = {}) {
117
+ super(message, options);
118
+ this.name = "ZapierBundleError";
119
+ this.buildErrors = options.buildErrors;
120
+ }
121
+ };
122
+ var ZapierTimeoutError = class extends ZapierError {
123
+ constructor(message, options = {}) {
124
+ super(message, options);
125
+ this.name = "ZapierTimeoutError";
126
+ this.attempts = options.attempts;
127
+ this.maxAttempts = options.maxAttempts;
128
+ }
129
+ };
130
+ var ZapierActionError = class extends ZapierError {
131
+ constructor(message, options = {}) {
132
+ super(message, options);
133
+ this.name = "ZapierActionError";
134
+ this.appKey = options.appKey;
135
+ this.actionKey = options.actionKey;
136
+ }
137
+ // Legacy accessor for backward compatibility
138
+ get actionErrors() {
139
+ return this.errors;
140
+ }
141
+ };
142
+ var ZapierNotFoundError = class extends ZapierError {
143
+ constructor(message, options = {}) {
144
+ super(message, options);
145
+ this.name = "ZapierNotFoundError";
146
+ }
147
+ };
148
+ function formatErrorMessage(error) {
149
+ let message = error.message;
150
+ if (error.errors && error.errors.length > 0) {
151
+ const additionalErrors = error.errors.slice(1);
152
+ if (additionalErrors.length > 0) {
153
+ const errorDetails = additionalErrors.map((err) => ` \u2022 ${err.detail || err.title || err.code}`).join("\n");
154
+ message += "\n\nAdditional errors:\n" + errorDetails;
155
+ }
156
+ }
157
+ if (error instanceof ZapierAppNotFoundError && error.appKey) {
158
+ message += `
159
+ App key: ${error.appKey}`;
160
+ }
161
+ if (error instanceof ZapierActionError && (error.appKey || error.actionKey)) {
162
+ const context = [];
163
+ if (error.appKey) context.push(`App: ${error.appKey}`);
164
+ if (error.actionKey) context.push(`Action: ${error.actionKey}`);
165
+ message += `
166
+ ${context.join(", ")}`;
167
+ }
168
+ if (error instanceof ZapierResourceNotFoundError && (error.resourceType || error.resourceId)) {
169
+ const context = [];
170
+ if (error.resourceType) context.push(`Type: ${error.resourceType}`);
171
+ if (error.resourceId) context.push(`ID: ${error.resourceId}`);
172
+ message += `
173
+ ${context.join(", ")}`;
174
+ }
175
+ if (error instanceof ZapierTimeoutError && (error.attempts || error.maxAttempts)) {
176
+ const context = [];
177
+ if (error.attempts) context.push(`Attempts: ${error.attempts}`);
178
+ if (error.maxAttempts) context.push(`Max attempts: ${error.maxAttempts}`);
179
+ message += `
180
+ ${context.join(", ")}`;
181
+ }
182
+ if (error instanceof ZapierBundleError && error.buildErrors && error.buildErrors.length > 0) {
183
+ message += "\n\nBuild errors:\n" + error.buildErrors.map((err) => ` \u2022 ${err}`).join("\n");
184
+ }
185
+ if (error.statusCode && !message.includes(`${error.statusCode}`)) {
186
+ message += `
187
+ HTTP Status: ${error.statusCode}`;
188
+ }
189
+ return message;
190
+ }
191
+
134
192
  // src/plugins/apps/index.ts
135
193
  function createActionFunction(appKey, actionType, actionKey, options, pinnedAuthId) {
136
- return async (actionOptions = {}) => {
194
+ return (actionOptions = {}) => {
137
195
  const { sdk } = options;
138
196
  const { inputs, authenticationId: providedAuthenticationId } = actionOptions;
139
197
  const authenticationId = pinnedAuthId || providedAuthenticationId;
140
198
  if (!authenticationId) {
141
- throw new Error(
199
+ throw new ZapierValidationError(
142
200
  `Authentication ID is required. Either use the factory pattern: sdk.apps.${appKey}({ authenticationId }) or provide authenticationId in the action call.`
143
201
  );
144
202
  }
@@ -153,16 +211,16 @@ function createActionFunction(appKey, actionType, actionKey, options, pinnedAuth
153
211
  }
154
212
  function createActionTypeProxy(appKey, actionType, options, pinnedAuthId) {
155
213
  if (actionType === "fetch") {
156
- return async (fetchOptions) => {
214
+ return async (url, init) => {
157
215
  const { sdk } = options;
158
- const authenticationId = pinnedAuthId || fetchOptions.authenticationId;
216
+ const authenticationId = pinnedAuthId || init?.authenticationId;
159
217
  if (!authenticationId) {
160
- throw new Error(
218
+ throw new ZapierValidationError(
161
219
  `Authentication ID is required for fetch. Either use the factory pattern: sdk.apps.${appKey}({ authenticationId }).fetch(...) or provide authenticationId in the fetch call.`
162
220
  );
163
221
  }
164
- return sdk.fetch({
165
- ...fetchOptions,
222
+ return sdk.fetch(url, {
223
+ ...init,
166
224
  authenticationId
167
225
  });
168
226
  };
@@ -231,18 +289,40 @@ function createAppsProxy(options) {
231
289
  });
232
290
  return appsProxy;
233
291
  }
234
- function createAppsPlugin(options) {
235
- return createAppsProxy(options);
236
- }
292
+ var appsPlugin = ({ sdk }) => {
293
+ return {
294
+ apps: createAppsProxy({ sdk })
295
+ };
296
+ };
237
297
 
238
- // src/index.ts
239
- init_auth();
298
+ // src/plugins/fetch/index.ts
299
+ var fetchPlugin = ({ sdk }) => {
300
+ return {
301
+ fetch: async function fetch(url, init) {
302
+ const {
303
+ authenticationId,
304
+ callbackUrl,
305
+ authenticationTemplate,
306
+ ...fetchInit
307
+ } = init || {};
308
+ return sdk.request({
309
+ url: url.toString(),
310
+ method: fetchInit.method,
311
+ body: fetchInit.body,
312
+ headers: fetchInit.headers,
313
+ authenticationId,
314
+ callbackUrl,
315
+ authenticationTemplate
316
+ });
317
+ }
318
+ };
319
+ };
240
320
 
241
321
  // src/resolvers/appKey.ts
242
322
  var appKeyResolver = {
243
323
  type: "static",
244
324
  inputType: "text",
245
- placeholder: "Enter app slug (e.g., 'slack', 'github')"
325
+ placeholder: "Enter app key (e.g., 'SlackCLIAPI' or slug like 'github')"
246
326
  };
247
327
 
248
328
  // src/resolvers/actionType.ts
@@ -250,8 +330,12 @@ var actionTypeResolver = {
250
330
  type: "dynamic",
251
331
  depends: ["appKey"],
252
332
  fetch: async (sdk, resolvedParams) => {
253
- const actions = await sdk.listActions({ appKey: resolvedParams.appKey });
254
- const types = [...new Set(actions.map((action) => action.type))];
333
+ const actionsResponse = await sdk.listActions({
334
+ appKey: resolvedParams.appKey
335
+ });
336
+ const types = [
337
+ ...new Set(actionsResponse.data.map((action) => action.action_type))
338
+ ];
255
339
  return types.map((type) => ({ key: type, name: type }));
256
340
  },
257
341
  prompt: (types) => ({
@@ -270,9 +354,11 @@ var actionKeyResolver = {
270
354
  type: "dynamic",
271
355
  depends: ["appKey", "actionType"],
272
356
  fetch: async (sdk, resolvedParams) => {
273
- const actions = await sdk.listActions({ appKey: resolvedParams.appKey });
274
- return actions.filter(
275
- (action) => action.type === resolvedParams.actionType
357
+ const actionsResponse = await sdk.listActions({
358
+ appKey: resolvedParams.appKey
359
+ });
360
+ return actionsResponse.data.filter(
361
+ (action) => action.action_type === resolvedParams.actionType
276
362
  );
277
363
  },
278
364
  prompt: (actions) => ({
@@ -280,7 +366,7 @@ var actionKeyResolver = {
280
366
  name: "actionKey",
281
367
  message: "Select action:",
282
368
  choices: actions.map((action) => ({
283
- name: `${action.name || action.key} - ${action.description || "No description"}`,
369
+ name: `${action.title || action.name || action.key} - ${action.description || "No description"}`,
284
370
  value: action.key
285
371
  }))
286
372
  })
@@ -291,10 +377,19 @@ var authenticationIdResolver = {
291
377
  type: "dynamic",
292
378
  depends: ["appKey"],
293
379
  fetch: async (sdk, resolvedParams) => {
294
- return await sdk.listAuthentications({
380
+ const myAuths = await sdk.listAuthentications({
295
381
  appKey: resolvedParams.appKey,
296
- limit: 1e3
382
+ maxItems: 1e3,
383
+ owner: "me"
384
+ });
385
+ const allAuths = await sdk.listAuthentications({
386
+ appKey: resolvedParams.appKey,
387
+ maxItems: 1e3
297
388
  });
389
+ const otherAuths = allAuths.data.filter(
390
+ (auth) => !myAuths.data.some((myAuth) => myAuth.id === auth.id)
391
+ );
392
+ return [...myAuths.data, ...otherAuths];
298
393
  },
299
394
  prompt: (auths, params) => ({
300
395
  type: "list",
@@ -318,12 +413,15 @@ var inputsResolver = {
318
413
  type: "fields",
319
414
  depends: ["appKey", "actionKey", "actionType", "authenticationId"],
320
415
  fetch: async (sdk, resolvedParams) => {
321
- return await sdk.listFields({
416
+ const fieldsResponse = await sdk.listInputFields({
322
417
  appKey: resolvedParams.appKey,
323
418
  actionKey: resolvedParams.actionKey,
324
419
  actionType: resolvedParams.actionType,
325
- authenticationId: resolvedParams.authenticationId
420
+ authenticationId: resolvedParams.authenticationId,
421
+ inputs: resolvedParams.inputs
422
+ // Pass along currently resolved inputs
326
423
  });
424
+ return fieldsResponse.data;
327
425
  }
328
426
  };
329
427
 
@@ -388,8 +486,74 @@ function getResolutionOrderForParams(paramNames) {
388
486
  return order;
389
487
  }
390
488
 
391
- // src/api/index.ts
392
- init_auth2();
489
+ // src/auth.ts
490
+ function getTokenFromEnv() {
491
+ return process.env.ZAPIER_TOKEN;
492
+ }
493
+ async function getTokenFromCliLogin(options = {}) {
494
+ try {
495
+ const { getToken } = await import('@zapier/zapier-sdk-cli-login');
496
+ return await getToken(options);
497
+ } catch {
498
+ return void 0;
499
+ }
500
+ }
501
+ async function getTokenFromEnvOrConfig(options = {}) {
502
+ const envToken = getTokenFromEnv();
503
+ if (envToken) {
504
+ return envToken;
505
+ }
506
+ return getTokenFromCliLogin(options);
507
+ }
508
+ var RelayRequestSchema = zod.z.object({
509
+ url: zod.z.string().url().describe("The URL to request (will be proxied through Relay)"),
510
+ method: zod.z.enum(["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]).optional().describe("HTTP method"),
511
+ body: zod.z.any().optional().describe("Request body as a string"),
512
+ authenticationId: zod.z.number().int().optional().describe("Zapier authentication ID to use for the request"),
513
+ callbackUrl: zod.z.string().url().optional().describe("URL to send async response to (makes request async)"),
514
+ authenticationTemplate: zod.z.string().optional().describe(
515
+ "Optional JSON string authentication template to bypass Notary lookup"
516
+ ),
517
+ headers: zod.z.union([
518
+ zod.z.record(zod.z.string()),
519
+ zod.z.instanceof(Headers),
520
+ zod.z.array(zod.z.tuple([zod.z.string(), zod.z.string()]))
521
+ ]).optional().describe("Request headers")
522
+ }).extend({
523
+ relayBaseUrl: zod.z.string().optional().describe("Base URL for Relay service")
524
+ }).describe("Make authenticated HTTP requests through Zapier's Relay service");
525
+ var RelayFetchSchema = RelayRequestSchema;
526
+
527
+ // src/plugins/registry/index.ts
528
+ var registryPlugin = ({ sdk, context }) => {
529
+ const metaKeys = Object.keys(context.meta || {});
530
+ const registryEntries = metaKeys.map((key) => {
531
+ return {
532
+ ...context.meta[key],
533
+ name: key,
534
+ implementation: sdk[key]
535
+ };
536
+ });
537
+ return {
538
+ __registry: registryEntries
539
+ };
540
+ };
541
+
542
+ // src/api/auth.ts
543
+ function isJwt(token) {
544
+ const parts = token.split(".");
545
+ if (parts.length !== 3) {
546
+ return false;
547
+ }
548
+ const base64UrlPattern = /^[A-Za-z0-9_-]+$/;
549
+ return parts.every((part) => part.length > 0 && base64UrlPattern.test(part));
550
+ }
551
+ function getAuthorizationHeader(token) {
552
+ if (isJwt(token)) {
553
+ return `JWT ${token}`;
554
+ }
555
+ return `Bearer ${token}`;
556
+ }
393
557
 
394
558
  // src/api/debug.ts
395
559
  function createDebugLogger(enabled) {
@@ -409,7 +573,13 @@ function createDebugFetch(options) {
409
573
  const method = options2?.method || "GET";
410
574
  debugLog(`\u2192 ${method} ${url}`, {
411
575
  headers: options2?.headers,
412
- body: options2?.body ? JSON.parse(options2.body) : void 0
576
+ body: options2?.body && typeof options2.body === "string" ? (() => {
577
+ try {
578
+ return JSON.parse(options2.body);
579
+ } catch {
580
+ return options2.body;
581
+ }
582
+ })() : options2?.body
413
583
  });
414
584
  try {
415
585
  const response = await originalFetch(input, options2);
@@ -435,9 +605,7 @@ function createDebugFetch(options) {
435
605
  // src/api/polling.ts
436
606
  async function pollUntilComplete(options) {
437
607
  const {
438
- fetch: fetch2,
439
- url,
440
- headers = {},
608
+ fetchPoll,
441
609
  maxAttempts = 30,
442
610
  initialDelay = 50,
443
611
  maxDelay = 1e3,
@@ -446,1189 +614,1360 @@ async function pollUntilComplete(options) {
446
614
  resultExtractor = (response) => response
447
615
  } = options;
448
616
  let delay = initialDelay;
617
+ let errorCount = 0;
449
618
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
450
- const response = await fetch2(url, { headers });
619
+ const response = await fetchPoll();
451
620
  if (response.status === successStatus) {
621
+ errorCount = 0;
452
622
  const result = await response.json();
453
623
  return resultExtractor(result);
454
624
  } else if (response.status === pendingStatus) {
625
+ errorCount = 0;
455
626
  if (attempt < maxAttempts - 1) {
456
627
  await new Promise((resolve) => setTimeout(resolve, delay));
457
628
  delay = Math.min(delay * 2, maxDelay);
458
629
  continue;
459
630
  }
460
631
  } else {
461
- throw new Error(
462
- `Request failed: GET ${url} - ${response.status} ${response.statusText}`
463
- );
632
+ errorCount++;
633
+ if (errorCount >= 3) {
634
+ throw new ZapierApiError(
635
+ `Poll request failed: ${response.status} ${response.statusText}`,
636
+ { statusCode: response.status }
637
+ );
638
+ }
639
+ if (attempt < maxAttempts - 1) {
640
+ await new Promise((resolve) => setTimeout(resolve, delay));
641
+ delay = Math.min(delay * 2, maxDelay);
642
+ continue;
643
+ }
464
644
  }
465
645
  }
466
- throw new Error(`Operation timed out after ${maxAttempts} attempts`);
646
+ throw new ZapierTimeoutError(
647
+ `Operation timed out after ${maxAttempts} attempts`,
648
+ { attempts: maxAttempts, maxAttempts }
649
+ );
467
650
  }
468
651
 
469
652
  // 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);
653
+ var SubdomainConfigMap = {
654
+ // e.g. https://relay.zapier.com
655
+ relay: {
656
+ authHeader: "X-Relay-Authorization"
657
+ }
658
+ };
659
+ var ZapierApiClient = class {
660
+ constructor(options) {
661
+ this.options = options;
662
+ this.fetch = async (path, init) => {
663
+ return this.plainFetch(path, init);
664
+ };
665
+ this.get = async (path, options = {}) => {
666
+ return this.fetchJson("GET", path, void 0, options);
667
+ };
668
+ this.post = async (path, data, options = {}) => {
669
+ return this.fetchJson("POST", path, data, options);
670
+ };
671
+ this.put = async (path, data, options = {}) => {
672
+ return this.fetchJson("PUT", path, data, options);
673
+ };
674
+ this.delete = async (path, options = {}) => {
675
+ return this.fetchJson("DELETE", path, void 0, options);
676
+ };
677
+ this.poll = async (path, options = {}) => {
678
+ return pollUntilComplete({
679
+ fetchPoll: () => this.plainFetch(path, {
680
+ method: "GET",
681
+ searchParams: options.searchParams,
682
+ authRequired: options.authRequired
683
+ }),
684
+ maxAttempts: options.maxAttempts,
685
+ initialDelay: options.initialDelay,
686
+ maxDelay: options.maxDelay,
687
+ successStatus: options.successStatus,
688
+ pendingStatus: options.pendingStatus,
689
+ resultExtractor: options.resultExtractor
498
690
  });
691
+ };
692
+ }
693
+ // Helper to parse response data
694
+ async parseResult(response) {
695
+ try {
696
+ return { type: "json", data: await response.json() };
697
+ } catch {
698
+ return { type: "text", data: await response.text() };
499
699
  }
500
- return url.toString();
501
700
  }
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);
701
+ // Helper to get a token from the different places it could be gotten
702
+ async getAuthToken() {
703
+ if (this.options.token) {
704
+ return this.options.token;
705
+ }
706
+ if (this.options.getToken) {
707
+ const token = await this.options.getToken();
708
+ if (token) {
709
+ return token;
519
710
  }
520
711
  }
521
- return headers;
712
+ return getTokenFromEnvOrConfig({
713
+ onEvent: this.options.onEvent,
714
+ fetch: this.options.fetch
715
+ });
522
716
  }
523
- async function handleResponse(response, customErrorHandler, hadAuthToken) {
524
- if (!response.ok) {
525
- if (customErrorHandler) {
526
- const customError = customErrorHandler(response);
527
- if (customError) {
717
+ // Helper to handle responses
718
+ async handleResponse(params) {
719
+ const { response, customErrorHandler, wasMissingAuthToken } = params;
720
+ const { data: responseData } = await this.parseResult(response);
721
+ if (response.ok) {
722
+ return responseData;
723
+ }
724
+ const errorInfo = {
725
+ status: response.status,
726
+ statusText: response.statusText,
727
+ data: responseData
728
+ };
729
+ if (customErrorHandler) {
730
+ const customError = customErrorHandler(errorInfo);
731
+ if (customError) {
732
+ if (customError instanceof Error) {
528
733
  throw customError;
734
+ } else {
735
+ throw new Error(
736
+ `customErrorHandler returned a non-Error: ${JSON.stringify(customError)}`
737
+ );
529
738
  }
530
739
  }
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.`
740
+ }
741
+ const { message, errors } = this.parseErrorResponse(errorInfo);
742
+ const errorOptions = {
743
+ statusCode: response.status,
744
+ errors
745
+ };
746
+ if (response.status === 404) {
747
+ throw new ZapierNotFoundError(message, errorOptions);
748
+ }
749
+ if (response.status === 401 || response.status === 403) {
750
+ if (wasMissingAuthToken) {
751
+ throw new ZapierAuthenticationError(
752
+ `Authentication required (HTTP ${response.status}). Please provide a token in options or set ZAPIER_TOKEN environment variable.`,
753
+ errorOptions
534
754
  );
535
755
  }
536
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
756
+ throw new ZapierAuthenticationError(message, errorOptions);
757
+ }
758
+ if (response.status === 400) {
759
+ throw new ZapierValidationError(message, errorOptions);
760
+ }
761
+ throw new ZapierApiError(message, errorOptions);
762
+ }
763
+ hasErrorArray(data) {
764
+ return typeof data === "object" && data !== null && "errors" in data && Array.isArray(data.errors);
765
+ }
766
+ // Helper to check if data has API errors
767
+ isApiErrorArray(dataArray) {
768
+ const data = dataArray[0];
769
+ return typeof data === "object" && data !== null && "message" in data && "code" in data && "title" in data && "detail" in data;
770
+ }
771
+ // Do our best to extract an error message from the response data
772
+ extractErrorMessage(data) {
773
+ if (typeof data === "string") {
774
+ return data;
775
+ }
776
+ if (typeof data === "object" && data !== null) {
777
+ if ("message" in data && typeof data.message === "string") {
778
+ return data.message;
779
+ }
780
+ if ("error" in data) {
781
+ if (typeof data.error === "string") {
782
+ return data.error;
783
+ }
784
+ if (typeof data.error === "object" && data.error !== null) {
785
+ if ("message" in data.error && typeof data.error.message === "string") {
786
+ return data.error.message;
787
+ }
788
+ }
789
+ try {
790
+ return JSON.stringify(data.error);
791
+ } catch {
792
+ }
793
+ }
794
+ if ("errors" in data && Array.isArray(data.errors)) {
795
+ if (this.isApiErrorArray(data.errors)) {
796
+ return data.errors[0].detail || data.errors[0].title;
797
+ }
798
+ }
537
799
  }
800
+ return void 0;
801
+ }
802
+ // Helper to parse API error response
803
+ parseErrorResponse(errorInfo) {
804
+ const fallbackMessage = `HTTP ${errorInfo.status}: ${errorInfo.statusText}`;
538
805
  try {
539
- return await response.json();
806
+ if (typeof errorInfo.data === "string") {
807
+ return { message: `${fallbackMessage}: ${errorInfo.data}` };
808
+ }
809
+ const errorMessage = this.extractErrorMessage(errorInfo.data) || fallbackMessage;
810
+ if (this.hasErrorArray(errorInfo.data)) {
811
+ if (this.isApiErrorArray(errorInfo.data.errors)) {
812
+ return {
813
+ message: errorMessage,
814
+ errors: errorInfo.data.errors
815
+ };
816
+ } else {
817
+ return {
818
+ message: errorMessage,
819
+ errors: errorInfo.data.errors.map((e) => ({
820
+ status: errorInfo.status,
821
+ code: String(errorInfo.status),
822
+ title: errorInfo.statusText,
823
+ detail: JSON.stringify(e)
824
+ }))
825
+ };
826
+ }
827
+ }
828
+ return { message: errorMessage };
540
829
  } catch {
541
- return await response.text();
830
+ return { message: fallbackMessage };
542
831
  }
543
832
  }
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 : {}
833
+ // Check if this is a path that needs subdomain routing
834
+ // e.g. /relay/workflows -> relay.zapier.com/workflows
835
+ applySubdomainBehavior(path) {
836
+ const pathSegments = path.split("/").filter(Boolean);
837
+ if (pathSegments.length > 0 && pathSegments[0] in SubdomainConfigMap) {
838
+ const domainPrefix = pathSegments[0];
839
+ const subdomainConfig = SubdomainConfigMap[domainPrefix];
840
+ const originalBaseUrl = new URL(this.options.baseUrl);
841
+ const finalBaseUrl = `https://${domainPrefix}.${originalBaseUrl.hostname}`;
842
+ const pathWithoutPrefix = "/" + pathSegments.slice(1).join("/");
843
+ return { url: new URL(pathWithoutPrefix, finalBaseUrl), subdomainConfig };
844
+ }
845
+ return {
846
+ url: new URL(path, this.options.baseUrl),
847
+ subdomainConfig: void 0
550
848
  };
551
- return await fetch2(url, {
552
- ...init,
553
- headers: finalHeaders
554
- });
555
849
  }
556
- async function fetchJson(method, path, data, options2 = {}) {
557
- const headers = { ...options2.headers };
850
+ // Helper to build full URLs and return routing info
851
+ buildUrl(path, searchParams) {
852
+ const { url, subdomainConfig } = this.applySubdomainBehavior(path);
853
+ if (searchParams) {
854
+ Object.entries(searchParams).forEach(([key, value]) => {
855
+ url.searchParams.set(key, value);
856
+ });
857
+ }
858
+ return { url: url.toString(), subdomainConfig };
859
+ }
860
+ // Helper to build headers
861
+ async buildHeaders(options = {}, subdomainConfig) {
862
+ const headers = new Headers(options.headers ?? {});
863
+ const authToken = await this.getAuthToken();
864
+ if (authToken) {
865
+ const authHeaderName = subdomainConfig?.authHeader || "Authorization";
866
+ headers.set(authHeaderName, getAuthorizationHeader(authToken));
867
+ }
868
+ if (options.authRequired) {
869
+ if (headers.get("Authorization") == null && authToken == null) {
870
+ throw new ZapierAuthenticationError(
871
+ `Authentication required but no token available. Please set ZAPIER_TOKEN, or run the 'login' command with the CLI.`
872
+ );
873
+ }
874
+ }
875
+ return headers;
876
+ }
877
+ // Helper to perform HTTP requests with JSON handling
878
+ async fetchJson(method, path, data, options = {}) {
879
+ const headers = { ...options.headers };
558
880
  if (data && typeof data === "object") {
559
881
  headers["Content-Type"] = "application/json";
560
882
  }
561
- const response = await plainFetch(path, {
883
+ const wasMissingAuthToken = options.authRequired && await this.getAuthToken() == null;
884
+ const response = await this.plainFetch(path, {
885
+ ...options,
562
886
  method,
563
- body: data ? JSON.stringify(data) : void 0,
564
- headers,
565
- searchParams: options2.searchParams,
566
- authRequired: options2.authRequired,
567
- customErrorHandler: options2.customErrorHandler
887
+ body: data != null ? JSON.stringify(data) : void 0,
888
+ headers
568
889
  });
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);
890
+ const result = await this.handleResponse({
891
+ response,
892
+ customErrorHandler: options.customErrorHandler,
893
+ wasMissingAuthToken
894
+ });
895
+ if (typeof result === "string") {
896
+ throw new ZapierValidationError(
897
+ `Response could not be parsed as JSON: ${result}`
898
+ );
602
899
  }
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;
900
+ return result;
621
901
  }
622
- return createZapierApi({
902
+ // Plain fetch method for API paths (must start with /)
903
+ async plainFetch(path, fetchOptions) {
904
+ if (!path.startsWith("/")) {
905
+ throw new ZapierValidationError(
906
+ `plainFetch expects a path starting with '/', got: ${path}`
907
+ );
908
+ }
909
+ if (fetchOptions?.body && typeof fetchOptions.body === "object") {
910
+ fetchOptions.body = JSON.stringify(fetchOptions.body);
911
+ }
912
+ const { url, subdomainConfig } = this.buildUrl(
913
+ path,
914
+ fetchOptions?.searchParams
915
+ );
916
+ const builtHeaders = await this.buildHeaders(
917
+ fetchOptions,
918
+ subdomainConfig
919
+ );
920
+ const inputHeaders = new Headers(fetchOptions?.headers ?? {});
921
+ const mergedHeaders = new Headers();
922
+ builtHeaders.forEach((value, key) => {
923
+ mergedHeaders.set(key, value);
924
+ });
925
+ inputHeaders.forEach((value, key) => {
926
+ mergedHeaders.set(key, value);
927
+ });
928
+ return await this.options.fetch(url, {
929
+ ...fetchOptions,
930
+ headers: mergedHeaders
931
+ });
932
+ }
933
+ };
934
+ var createZapierApi = (options) => {
935
+ const {
936
+ baseUrl,
937
+ token,
938
+ getToken,
939
+ debug = false,
940
+ fetch: originalFetch = globalThis.fetch,
941
+ onEvent
942
+ } = options;
943
+ const debugLog = createDebugLogger(debug);
944
+ const debugFetch = createDebugFetch({ originalFetch, debugLog });
945
+ return new ZapierApiClient({
623
946
  baseUrl,
624
947
  token,
625
948
  getToken,
626
949
  debug,
627
- fetch: customFetch
950
+ fetch: debugFetch,
951
+ onEvent
628
952
  });
629
- }
953
+ };
630
954
 
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
- }
955
+ // src/plugins/api/index.ts
956
+ var apiPlugin = (params) => {
957
+ const {
958
+ fetch: customFetch = globalThis.fetch,
959
+ baseUrl = "https://zapier.com",
960
+ token,
961
+ getToken,
962
+ onEvent,
963
+ debug = false
964
+ } = params;
965
+ const api = createZapierApi({
966
+ baseUrl,
967
+ token,
968
+ getToken,
969
+ debug,
970
+ fetch: customFetch,
971
+ onEvent
642
972
  });
643
973
  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
974
+ context: {
975
+ api
976
+ // Provide API client in context for other plugins to use
977
+ }
652
978
  };
653
- }
979
+ };
654
980
 
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
- }
981
+ // src/utils/pagination-utils.ts
982
+ var offsetCursorMarker = "$$offset$$";
983
+ function splitOffsetCursor(cursor) {
984
+ if (!cursor) {
985
+ return [0, cursor];
986
+ }
987
+ try {
988
+ const parsedCursor = JSON.parse(cursor);
989
+ if (!Array.isArray(parsedCursor)) {
990
+ return [0, cursor];
684
991
  }
685
- if (options2.search) {
686
- searchParams.search = options2.search;
687
- } else if (options2.title) {
688
- searchParams.search = options2.title;
992
+ const [marker, offset, currentCursor] = parsedCursor;
993
+ if (marker !== offsetCursorMarker) {
994
+ return [0, cursor];
689
995
  }
690
- if (options2.account_id) {
691
- searchParams.account_id = options2.account_id;
996
+ if (typeof offset !== "number") {
997
+ return [0, cursor];
692
998
  }
693
- if (options2.owner) {
694
- searchParams.owner = options2.owner;
999
+ return [offset, currentCursor];
1000
+ } catch {
1001
+ return [0, cursor];
1002
+ }
1003
+ }
1004
+ function createOffsetCursor(offset, currentCursor) {
1005
+ return JSON.stringify([offsetCursorMarker, offset, currentCursor]);
1006
+ }
1007
+ async function* paginateMaxItems(pageFunction, pageOptions) {
1008
+ let cursor = pageOptions?.cursor;
1009
+ let totalItemsYielded = 0;
1010
+ const maxItems = pageOptions?.maxItems;
1011
+ const pageSize = pageOptions?.pageSize;
1012
+ do {
1013
+ const options = {
1014
+ ...pageOptions || {},
1015
+ cursor,
1016
+ pageSize: maxItems !== void 0 && pageSize !== void 0 ? Math.min(pageSize, maxItems) : pageSize
1017
+ };
1018
+ const page = await pageFunction(options);
1019
+ if (maxItems !== void 0) {
1020
+ const remainingItems = maxItems - totalItemsYielded;
1021
+ if (page.data.length >= remainingItems) {
1022
+ const yieldedPage = {
1023
+ ...page,
1024
+ data: page.data.slice(0, remainingItems),
1025
+ nextCursor: void 0
1026
+ };
1027
+ yield yieldedPage;
1028
+ break;
1029
+ }
695
1030
  }
696
- if (options2.limit) {
697
- searchParams.limit = options2.limit.toString();
1031
+ yield page;
1032
+ totalItemsYielded += page.data.length;
1033
+ cursor = page.nextCursor;
1034
+ } while (cursor);
1035
+ }
1036
+ async function* paginateBuffered(pageFunction, pageOptions) {
1037
+ const pageSize = pageOptions?.pageSize;
1038
+ const [cursorOffset, currentCursor] = splitOffsetCursor(pageOptions?.cursor);
1039
+ const options = {
1040
+ ...pageOptions || {},
1041
+ cursor: currentCursor
1042
+ };
1043
+ const iterator = paginateMaxItems(pageFunction, options);
1044
+ let bufferedPages = [];
1045
+ let isFirstPage = true;
1046
+ let cursor;
1047
+ for await (let page of iterator) {
1048
+ if (isFirstPage) {
1049
+ isFirstPage = false;
1050
+ if (cursorOffset) {
1051
+ page = {
1052
+ ...page,
1053
+ data: page.data.slice(cursorOffset)
1054
+ };
1055
+ }
698
1056
  }
699
- if (options2.offset) {
700
- searchParams.offset = options2.offset.toString();
1057
+ if (!pageSize) {
1058
+ yield page;
1059
+ cursor = page.nextCursor;
1060
+ continue;
701
1061
  }
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
- }
1062
+ const bufferedLength = bufferedPages.reduce(
1063
+ (acc, page2) => acc + page2.data.length,
1064
+ 0
720
1065
  );
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
1066
+ if (bufferedLength + page.data.length < pageSize) {
1067
+ bufferedPages.push(page);
1068
+ cursor = page.nextCursor;
1069
+ continue;
1070
+ }
1071
+ const bufferedItems = bufferedPages.map((p) => p.data).flat();
1072
+ const allItems = [...bufferedItems, ...page.data];
1073
+ const pageItems = allItems.slice(0, pageSize);
1074
+ const remainingItems = allItems.slice(pageItems.length);
1075
+ if (remainingItems.length === 0) {
1076
+ yield {
1077
+ ...page,
1078
+ data: pageItems,
1079
+ nextCursor: page.nextCursor
736
1080
  };
1081
+ bufferedPages = [];
1082
+ cursor = page.nextCursor;
1083
+ continue;
737
1084
  }
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);
1085
+ yield {
1086
+ ...page,
1087
+ data: pageItems,
1088
+ nextCursor: createOffsetCursor(
1089
+ page.data.length - remainingItems.length,
1090
+ cursor
1091
+ )
1092
+ };
1093
+ while (remainingItems.length > pageSize) {
1094
+ const pageItems2 = remainingItems.splice(0, pageSize);
1095
+ yield {
1096
+ ...page,
1097
+ data: pageItems2,
1098
+ nextCursor: createOffsetCursor(
1099
+ page.data.length - remainingItems.length,
1100
+ cursor
1101
+ )
1102
+ };
747
1103
  }
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);
1104
+ bufferedPages = [
1105
+ {
1106
+ ...page,
1107
+ data: remainingItems
1108
+ }
1109
+ ];
1110
+ cursor = page.nextCursor;
1111
+ }
1112
+ if (bufferedPages.length > 0) {
1113
+ const lastBufferedPage = bufferedPages.slice(-1)[0];
1114
+ const bufferedItems = bufferedPages.map((p) => p.data).flat();
1115
+ yield {
1116
+ ...lastBufferedPage,
1117
+ data: bufferedItems
1118
+ };
758
1119
  }
759
- return listAuthenticationsInternal(options);
760
1120
  }
1121
+ var paginate = paginateBuffered;
761
1122
 
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;
1123
+ // src/utils/validation.ts
1124
+ var validate = (schema, input) => {
1125
+ const result = schema.safeParse(input);
1126
+ if (!result.success) {
1127
+ const errorMessages = result.error.errors.map((error) => {
1128
+ const path = error.path.length > 0 ? error.path.join(".") : "input";
1129
+ return `${path}: ${error.message}`;
1130
+ });
1131
+ const message = `Validation failed:
1132
+ ${errorMessages.join("\n ")}`;
1133
+ throw new ZapierValidationError(message, {
1134
+ details: {
1135
+ zodErrors: result.error.errors,
1136
+ input
786
1137
  }
787
- }
788
- );
789
- return {
790
- ...data,
791
- title: data.title || data.label || void 0
1138
+ });
1139
+ }
1140
+ return result.data;
1141
+ };
1142
+ function createValidator(schema) {
1143
+ return function validateFn(input) {
1144
+ return validate(schema, input);
792
1145
  };
793
1146
  }
1147
+ var validateOptions = (schema, options) => {
1148
+ return validate(schema, options);
1149
+ };
794
1150
 
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");
1151
+ // src/utils/function-utils.ts
1152
+ function extractCursor(data) {
1153
+ if (!data?.next) {
1154
+ return void 0;
813
1155
  }
814
- if (auths.length > 1) {
815
- throw new Error(
816
- "Multiple authentications found matching the specified criteria. Expected exactly one."
817
- );
1156
+ try {
1157
+ const urlObj = new URL(data.next);
1158
+ const offset = urlObj.searchParams.get("offset");
1159
+ return offset || void 0;
1160
+ } catch {
1161
+ return void 0;
818
1162
  }
819
- return auths[0];
820
1163
  }
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
- };
1164
+ function normalizeError(error) {
1165
+ if (error instanceof ZapierError) {
1166
+ return error;
858
1167
  }
859
- return apps;
1168
+ const message = error instanceof Error ? error.message : String(error);
1169
+ return new ZapierUnknownError(`Unknown error: ${message}`, { cause: error });
860
1170
  }
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
- }
1171
+ function createFunction(coreFn, schema) {
1172
+ const functionName = coreFn.name;
1173
+ const namedFunctions = {
1174
+ [functionName]: async function(options) {
1175
+ try {
1176
+ const normalizedOptions = options ?? {};
1177
+ if (schema) {
1178
+ const validatedOptions = validateOptions(schema, normalizedOptions);
1179
+ return await coreFn({
1180
+ ...normalizedOptions,
1181
+ ...validatedOptions
1182
+ });
906
1183
  }
1184
+ return await coreFn(normalizedOptions);
1185
+ } catch (error) {
1186
+ throw normalizeError(error);
907
1187
  }
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;
1188
+ }
1189
+ };
1190
+ return namedFunctions[functionName];
1191
+ }
1192
+ function createPageFunction(coreFn) {
1193
+ const functionName = coreFn.name + "Page";
1194
+ const namedFunctions = {
1195
+ [functionName]: async function(options) {
1196
+ try {
1197
+ const result = await coreFn(options);
1198
+ if (result && typeof result === "object" && "data" in result) {
1199
+ const data = result.data;
1200
+ return {
1201
+ data: Array.isArray(data) ? data : [data],
1202
+ nextCursor: result.nextCursor
1203
+ };
1204
+ }
1205
+ if (Array.isArray(result)) {
1206
+ return { data: result };
1207
+ }
1208
+ return { data: [result] };
1209
+ } catch (error) {
1210
+ throw normalizeError(error);
921
1211
  }
922
- console.warn(
923
- "Optimized app lookup failed, falling back to full scan:",
924
- error
925
- );
926
1212
  }
927
- }
928
- const searchParams = {
929
- global: "true",
930
- public_only: "true"
931
1213
  };
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;
1214
+ return namedFunctions[functionName];
1215
+ }
1216
+ function createPaginatedFunction(coreFn, schema) {
1217
+ const pageFunction = createPageFunction(coreFn);
1218
+ const functionName = coreFn.name;
1219
+ const validator = schema ? createValidator(schema) : null;
1220
+ const namedFunctions = {
1221
+ [functionName]: function(options) {
1222
+ const normalizedOptions = options ?? {};
1223
+ const validatedOptions = {
1224
+ ...normalizedOptions,
1225
+ ...validator ? validator(normalizedOptions) : normalizedOptions
1226
+ };
1227
+ const pageSize = validatedOptions.pageSize || 100;
1228
+ const optimizedOptions = {
1229
+ ...validatedOptions,
1230
+ pageSize
1231
+ };
1232
+ const iterator = paginate(pageFunction, optimizedOptions);
1233
+ const firstPagePromise = iterator.next().then((result) => {
1234
+ if (result.done) {
1235
+ throw new Error("Paginate should always iterate at least once");
949
1236
  }
950
- if (options?.type && transformedAction.type !== options.type) {
951
- continue;
1237
+ return result.value;
1238
+ });
1239
+ return Object.assign(firstPagePromise, {
1240
+ [Symbol.asyncIterator]: async function* () {
1241
+ yield await firstPagePromise;
1242
+ for await (const page of iterator) {
1243
+ yield page;
1244
+ }
1245
+ },
1246
+ items: function() {
1247
+ return {
1248
+ [Symbol.asyncIterator]: async function* () {
1249
+ const firstPage = await firstPagePromise;
1250
+ for (const item of firstPage.data) {
1251
+ yield item;
1252
+ }
1253
+ for await (const page of iterator) {
1254
+ for (const item of page.data) {
1255
+ yield item;
1256
+ }
1257
+ }
1258
+ }
1259
+ };
952
1260
  }
953
- actions.push(transformedAction);
1261
+ });
1262
+ }
1263
+ };
1264
+ return namedFunctions[functionName];
1265
+ }
1266
+ var NeedChoicesSchema = zod.z.object({
1267
+ key: zod.z.string().optional(),
1268
+ label: zod.z.string().optional(),
1269
+ sample: zod.z.string().optional(),
1270
+ value: zod.z.string().optional()
1271
+ });
1272
+ var NeedSchema = zod.z.object({
1273
+ key: zod.z.string(),
1274
+ alters_custom_fields: zod.z.boolean().nullable().optional(),
1275
+ capabilities: zod.z.array(zod.z.string()).optional(),
1276
+ choices: zod.z.array(NeedChoicesSchema).optional(),
1277
+ computed: zod.z.boolean().nullable().optional(),
1278
+ custom_field: zod.z.boolean().optional(),
1279
+ default: zod.z.string().optional(),
1280
+ depends_on: zod.z.array(zod.z.string()).optional(),
1281
+ format: zod.z.literal("SELECT").optional(),
1282
+ from_search: zod.z.boolean().optional(),
1283
+ from_write: zod.z.boolean().optional(),
1284
+ help_text: zod.z.string().optional(),
1285
+ help_text_html: zod.z.string().optional(),
1286
+ input_format: zod.z.array(zod.z.string()).optional(),
1287
+ label: zod.z.string().optional(),
1288
+ language: zod.z.string().optional(),
1289
+ parent_key: zod.z.string().optional(),
1290
+ placeholder: zod.z.string().optional(),
1291
+ prefill: zod.z.string().optional(),
1292
+ required: zod.z.boolean().optional(),
1293
+ searchfill: zod.z.string().optional(),
1294
+ send_in_json: zod.z.boolean().optional(),
1295
+ regex: zod.z.string().optional(),
1296
+ type: zod.z.enum([
1297
+ "integer",
1298
+ "string",
1299
+ "text",
1300
+ "datetime",
1301
+ "boolean",
1302
+ "file",
1303
+ "decimal",
1304
+ "copy",
1305
+ "password",
1306
+ "dict",
1307
+ "code",
1308
+ "filter",
1309
+ "json"
1310
+ ]).optional(),
1311
+ list: zod.z.boolean().optional()
1312
+ });
1313
+ var ActionLinksSchema = zod.z.object({
1314
+ action_url: zod.z.string().optional()
1315
+ });
1316
+ var ActionPermissionsSchema = zod.z.object({
1317
+ can_use: zod.z.boolean().optional()
1318
+ });
1319
+ var ActionSchema = zod.z.object({
1320
+ id: zod.z.string().optional(),
1321
+ type: zod.z.enum([
1322
+ "filter",
1323
+ "read",
1324
+ "read_bulk",
1325
+ "run",
1326
+ "search",
1327
+ "search_and_write",
1328
+ "search_or_write",
1329
+ "write"
1330
+ ]),
1331
+ key: zod.z.string(),
1332
+ name: zod.z.string(),
1333
+ noun: zod.z.string().optional(),
1334
+ description: zod.z.string(),
1335
+ description_html: zod.z.string().optional(),
1336
+ is_important: zod.z.boolean().optional(),
1337
+ is_hidden: zod.z.boolean().optional(),
1338
+ needs: zod.z.array(NeedSchema).optional(),
1339
+ meta: zod.z.string().optional(),
1340
+ selected_api: zod.z.string().optional(),
1341
+ links: ActionLinksSchema.optional(),
1342
+ permissions: ActionPermissionsSchema.optional()
1343
+ });
1344
+ var ChoiceSchema = zod.z.object({
1345
+ value: zod.z.union([zod.z.string(), zod.z.number()]),
1346
+ label: zod.z.string()
1347
+ });
1348
+ zod.z.object({
1349
+ key: zod.z.string(),
1350
+ label: zod.z.string(),
1351
+ type: zod.z.enum([
1352
+ "string",
1353
+ "number",
1354
+ "boolean",
1355
+ "datetime",
1356
+ "file",
1357
+ "object",
1358
+ "array"
1359
+ ]),
1360
+ required: zod.z.boolean(),
1361
+ description: zod.z.string().optional(),
1362
+ choices: zod.z.array(ChoiceSchema).optional()
1363
+ });
1364
+ zod.z.object({
1365
+ data: zod.z.array(zod.z.any())
1366
+ });
1367
+ var ActionFieldChoiceSchema = zod.z.object({
1368
+ value: zod.z.union([zod.z.string(), zod.z.number()]),
1369
+ label: zod.z.string()
1370
+ });
1371
+ zod.z.object({
1372
+ key: zod.z.string(),
1373
+ label: zod.z.string().optional(),
1374
+ required: zod.z.boolean(),
1375
+ type: zod.z.string().optional(),
1376
+ helpText: zod.z.string().optional(),
1377
+ helpTextHtml: zod.z.string().optional(),
1378
+ choices: zod.z.array(ActionFieldChoiceSchema).optional(),
1379
+ default: zod.z.string().optional(),
1380
+ placeholder: zod.z.string().optional(),
1381
+ computed: zod.z.boolean().optional(),
1382
+ customField: zod.z.boolean().optional(),
1383
+ dependsOn: zod.z.array(zod.z.string()).optional(),
1384
+ format: zod.z.string().optional(),
1385
+ inputFormat: zod.z.array(zod.z.string()).optional()
1386
+ });
1387
+ var AuthenticationSchema = zod.z.object({
1388
+ id: zod.z.number(),
1389
+ date: zod.z.string(),
1390
+ lastchanged: zod.z.string().optional(),
1391
+ account_id: zod.z.number(),
1392
+ customuser_id: zod.z.number().optional(),
1393
+ selected_api: zod.z.string(),
1394
+ destination_selected_api: zod.z.string().nullable().optional(),
1395
+ is_invite_only: zod.z.boolean(),
1396
+ is_private: zod.z.boolean(),
1397
+ shared_with_all: zod.z.boolean(),
1398
+ is_stale: zod.z.string().optional(),
1399
+ is_shared: zod.z.string().optional(),
1400
+ marked_stale_at: zod.z.string().nullable().optional(),
1401
+ label: zod.z.string().nullable().optional(),
1402
+ identifier: zod.z.string().nullable().optional(),
1403
+ title: zod.z.string().nullable().optional(),
1404
+ url: zod.z.string().optional(),
1405
+ groups: zod.z.string().optional(),
1406
+ members: zod.z.string().optional(),
1407
+ permissions: zod.z.record(zod.z.boolean()).optional()
1408
+ });
1409
+ zod.z.object({
1410
+ count: zod.z.number(),
1411
+ next: zod.z.string().nullable().optional(),
1412
+ previous: zod.z.string().nullable().optional(),
1413
+ results: zod.z.array(AuthenticationSchema)
1414
+ });
1415
+ var UserProfileSchema = zod.z.object({
1416
+ id: zod.z.number(),
1417
+ code: zod.z.string(),
1418
+ user_id: zod.z.number(),
1419
+ auto_provisioned: zod.z.boolean(),
1420
+ first_name: zod.z.string(),
1421
+ last_name: zod.z.string(),
1422
+ username: zod.z.string(),
1423
+ personas: zod.z.string(),
1424
+ user_generated_personas: zod.z.string(),
1425
+ last_login: zod.z.string(),
1426
+ email: zod.z.string(),
1427
+ email_hash: zod.z.string(),
1428
+ email_confirmed: zod.z.boolean(),
1429
+ timezone: zod.z.string(),
1430
+ photo_url: zod.z.string(),
1431
+ has_seen_notifications: zod.z.record(zod.z.boolean().nullable()),
1432
+ signup: zod.z.string(),
1433
+ since_signup: zod.z.string(),
1434
+ has_activated: zod.z.boolean(),
1435
+ enable_gz_creator: zod.z.boolean(),
1436
+ should_see_nps_survey: zod.z.boolean(),
1437
+ is_developer: zod.z.boolean(),
1438
+ is_expert: zod.z.boolean(),
1439
+ tos_agreement: zod.z.boolean(),
1440
+ should_renew_tos: zod.z.boolean(),
1441
+ is_gdpr_consented: zod.z.boolean(),
1442
+ disable_ssl_check: zod.z.boolean(),
1443
+ identity: zod.z.number(),
1444
+ summary_schedule: zod.z.string(),
1445
+ alert_triggers: zod.z.string(),
1446
+ alert_actions: zod.z.string(),
1447
+ is_staff: zod.z.boolean(),
1448
+ is_zt_reviewer: zod.z.boolean(),
1449
+ is_high_value: zod.z.boolean(),
1450
+ is_temporary: zod.z.boolean(),
1451
+ banner_message: zod.z.string(),
1452
+ enable_totp_2fa: zod.z.boolean(),
1453
+ viewed_help: zod.z.record(zod.z.boolean()),
1454
+ show_editor_migration_mesaging: zod.z.boolean(),
1455
+ switches: zod.z.record(zod.z.any()),
1456
+ organizations: zod.z.array(zod.z.any().nullable()),
1457
+ primary_organization: zod.z.any().nullable(),
1458
+ has_active_zaps: zod.z.boolean(),
1459
+ has_google_sso: zod.z.boolean(),
1460
+ auth_realm: zod.z.string(),
1461
+ roles: zod.z.array(
1462
+ zod.z.object({
1463
+ account_id: zod.z.number(),
1464
+ role: zod.z.string()
1465
+ })
1466
+ )
1467
+ });
1468
+ zod.z.object({
1469
+ age_in_days: zod.z.string().optional(),
1470
+ api_docs_url: zod.z.string().nullable().optional(),
1471
+ app_profile_url: zod.z.string(),
1472
+ banner: zod.z.string().optional(),
1473
+ categories: zod.z.array(zod.z.any()).optional(),
1474
+ // TODO: Define proper service_category type
1475
+ canonical_id: zod.z.string().optional(),
1476
+ current_implementation_id: zod.z.string(),
1477
+ days_since_last_update: zod.z.string().optional(),
1478
+ description: zod.z.string(),
1479
+ external_url: zod.z.string(),
1480
+ hashtag: zod.z.string().optional(),
1481
+ id: zod.z.number().optional(),
1482
+ image: zod.z.string().optional(),
1483
+ images: zod.z.string().optional(),
1484
+ integration_overview_html: zod.z.string().nullable().optional(),
1485
+ internal_id: zod.z.string(),
1486
+ invite_url: zod.z.string().nullable().optional(),
1487
+ is_beta: zod.z.string().optional(),
1488
+ is_built_in: zod.z.string().optional(),
1489
+ is_featured: zod.z.string().optional(),
1490
+ is_premium: zod.z.boolean().optional(),
1491
+ is_public: zod.z.string().optional(),
1492
+ is_upcoming: zod.z.string().optional(),
1493
+ learn_more_url: zod.z.string(),
1494
+ name: zod.z.string(),
1495
+ popularity: zod.z.number(),
1496
+ primary_color: zod.z.string(),
1497
+ request_count: zod.z.string().optional(),
1498
+ slug: zod.z.string(),
1499
+ zap_usage_count: zod.z.number().nullable().optional()
1500
+ });
1501
+ var ServiceSchema = zod.z.object({
1502
+ id: zod.z.number().optional(),
1503
+ canonical_id: zod.z.string().optional(),
1504
+ current_implementation_id: zod.z.string(),
1505
+ name: zod.z.string(),
1506
+ slug: zod.z.string(),
1507
+ app_url: zod.z.string().optional(),
1508
+ learn_more_url: zod.z.string().optional(),
1509
+ description: zod.z.string(),
1510
+ primary_color: zod.z.string(),
1511
+ popularity: zod.z.number(),
1512
+ image: zod.z.string().optional(),
1513
+ images: zod.z.string().optional()
1514
+ });
1515
+ zod.z.object({
1516
+ results: zod.z.array(ServiceSchema),
1517
+ next: zod.z.string().nullable().optional(),
1518
+ previous: zod.z.string().nullable().optional()
1519
+ });
1520
+ zod.z.object({
1521
+ selected_api: zod.z.string(),
1522
+ action: zod.z.string(),
1523
+ type_of: zod.z.string(),
1524
+ authentication_id: zod.z.number().optional(),
1525
+ params: zod.z.record(zod.z.any()).optional()
1526
+ });
1527
+ zod.z.object({
1528
+ success: zod.z.boolean(),
1529
+ needs: zod.z.array(NeedSchema).optional(),
1530
+ errors: zod.z.array(zod.z.string()).optional(),
1531
+ last_fetched_at: zod.z.string().optional()
1532
+ });
1533
+ var ImplementationSchema = zod.z.object({
1534
+ selected_api: zod.z.string(),
1535
+ app_id: zod.z.number().optional(),
1536
+ auth_type: zod.z.string().optional(),
1537
+ auth_fields: zod.z.string().optional(),
1538
+ actions: zod.z.array(ActionSchema).optional(),
1539
+ is_deprecated: zod.z.boolean().optional(),
1540
+ is_private_only: zod.z.boolean().optional(),
1541
+ is_invite_only: zod.z.boolean().optional(),
1542
+ is_beta: zod.z.boolean().optional().default(false),
1543
+ is_premium: zod.z.boolean().optional().default(false),
1544
+ is_hidden: zod.z.string().optional(),
1545
+ name: zod.z.string().optional(),
1546
+ slug: zod.z.string().optional(),
1547
+ images: zod.z.record(zod.z.string().nullable()).optional(),
1548
+ primary_color: zod.z.string().optional(),
1549
+ secondary_color: zod.z.string().optional(),
1550
+ current_implementation: zod.z.string().optional(),
1551
+ other_implementations: zod.z.string().optional()
1552
+ });
1553
+ zod.z.object({
1554
+ count: zod.z.number(),
1555
+ next: zod.z.string().nullable().optional(),
1556
+ previous: zod.z.string().nullable().optional(),
1557
+ results: zod.z.array(ImplementationSchema)
1558
+ });
1559
+ var ImplementationMetaSchema = zod.z.object({
1560
+ id: zod.z.string(),
1561
+ // e.g. "ZapierFormatterCLIAPI@1.0.7"
1562
+ name: zod.z.string(),
1563
+ slug: zod.z.string(),
1564
+ images: zod.z.object({
1565
+ url_16x16: zod.z.string().optional(),
1566
+ url_32x32: zod.z.string().optional(),
1567
+ url_64x64: zod.z.string().optional(),
1568
+ url_128x128: zod.z.string().optional()
1569
+ }).optional(),
1570
+ // Include other fields for completeness but we'll only use what we need
1571
+ ageInDays: zod.z.union([zod.z.string(), zod.z.number()]).optional(),
1572
+ authType: zod.z.string().nullable().optional(),
1573
+ banner: zod.z.string().optional(),
1574
+ categories: zod.z.array(
1575
+ zod.z.object({
1576
+ id: zod.z.number(),
1577
+ name: zod.z.string(),
1578
+ slug: zod.z.string()
1579
+ })
1580
+ ).optional(),
1581
+ isBeta: zod.z.boolean().optional(),
1582
+ isBuiltIn: zod.z.boolean().optional(),
1583
+ isDeprecated: zod.z.boolean().optional(),
1584
+ isFeatured: zod.z.boolean().optional(),
1585
+ isHidden: zod.z.boolean().optional(),
1586
+ isInvite: zod.z.boolean().optional(),
1587
+ isPremium: zod.z.boolean().optional(),
1588
+ isPublic: zod.z.boolean().optional(),
1589
+ isUpcoming: zod.z.boolean().optional(),
1590
+ popularity: zod.z.number().optional(),
1591
+ apiDocsUrl: zod.z.string().optional(),
1592
+ classification: zod.z.string().optional()
1593
+ });
1594
+ zod.z.object({
1595
+ count: zod.z.number(),
1596
+ next: zod.z.string().nullable().optional(),
1597
+ previous: zod.z.string().nullable().optional(),
1598
+ results: zod.z.array(ImplementationMetaSchema)
1599
+ });
1600
+
1601
+ // src/schemas/UserProfile.ts
1602
+ var UserProfileItemSchema = withFormatter(
1603
+ UserProfileSchema.omit({ user_id: true }).extend({
1604
+ full_name: zod.z.string()
1605
+ // Computed field: first_name + " " + last_name
1606
+ }),
1607
+ {
1608
+ format: (item) => {
1609
+ const details = [];
1610
+ details.push({ text: item.email, style: "dim" });
1611
+ if (item.timezone) {
1612
+ details.push({
1613
+ text: `Timezone: ${item.timezone}`,
1614
+ style: "accent"
1615
+ });
954
1616
  }
1617
+ details.push({
1618
+ text: `Member since: ${item.since_signup}`,
1619
+ style: "dim"
1620
+ });
1621
+ return {
1622
+ title: item.full_name,
1623
+ subtitle: `@${item.username}`,
1624
+ details
1625
+ };
955
1626
  }
956
1627
  }
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
1628
+ );
1629
+
1630
+ // src/plugins/getProfile/schemas.ts
1631
+ var GetProfileSchema = withOutputSchema(
1632
+ zod.z.object({}).optional().describe("Get current user's profile information"),
1633
+ UserProfileItemSchema
1634
+ );
1635
+
1636
+ // src/plugins/getProfile/index.ts
1637
+ var getProfilePlugin = ({ context }) => {
1638
+ const getProfile = createFunction(async function getProfile2() {
1639
+ const profile = await context.api.get("/api/v4/profile/", {
1640
+ authRequired: true
1641
+ });
1642
+ const { user_id: _unusedUserId, ...data } = profile;
1643
+ return {
1644
+ data: {
1645
+ ...data,
1646
+ // Pass through all API response fields
1647
+ full_name: `${profile.first_name} ${profile.last_name}`
1648
+ // Computed field
1649
+ }
964
1650
  };
1651
+ }, GetProfileSchema);
1652
+ return {
1653
+ getProfile,
1654
+ context: {
1655
+ meta: {
1656
+ getProfile: {
1657
+ inputSchema: GetProfileSchema
1658
+ }
1659
+ }
1660
+ }
1661
+ };
1662
+ };
1663
+ var AppItemSchema = withFormatter(
1664
+ zod.z.object({
1665
+ // Essential properties only
1666
+ title: zod.z.string(),
1667
+ // Mapped from name
1668
+ key: zod.z.string(),
1669
+ // Mapped from selected_api
1670
+ current_implementation_id: zod.z.string(),
1671
+ // From id, keeps the full version
1672
+ version: zod.z.string().optional(),
1673
+ // Extracted from implementation ID
1674
+ description: zod.z.string().optional(),
1675
+ slug: zod.z.string().optional()
1676
+ }),
1677
+ {
1678
+ format: (item) => {
1679
+ return {
1680
+ title: item.title,
1681
+ subtitle: `(${item.key})`,
1682
+ details: []
1683
+ };
1684
+ }
965
1685
  }
966
- return actions;
967
- }
1686
+ );
968
1687
 
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}`);
1688
+ // src/plugins/listApps/schemas.ts
1689
+ var ListAppsSchema = withOutputSchema(
1690
+ zod.z.object({
1691
+ appKeys: zod.z.array(zod.z.string()).optional().describe(
1692
+ "Filter apps by app keys (e.g., 'SlackCLIAPI' or slug like 'github')"
1693
+ ),
1694
+ search: zod.z.string().optional().describe("Search for apps by name"),
1695
+ pageSize: zod.z.number().min(1).optional().describe("Number of apps per page"),
1696
+ maxItems: zod.z.number().min(1).optional().describe("Maximum total items to return across all pages")
1697
+ }).describe("List all available apps with optional filtering"),
1698
+ AppItemSchema
1699
+ );
1700
+
1701
+ // src/utils/domain-utils.ts
1702
+ function splitVersionedKey(versionedKey) {
1703
+ const parts = versionedKey.split("@");
1704
+ if (parts.length >= 2) {
1705
+ const baseKey = parts[0];
1706
+ const version = parts.slice(1).join("@");
1707
+ return [baseKey, version];
981
1708
  }
982
- return action;
1709
+ return [versionedKey, void 0];
983
1710
  }
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}`
1711
+ function normalizeImplementationMetaToAppItem(implementationMeta) {
1712
+ const [selectedApi, appVersion] = splitVersionedKey(implementationMeta.id);
1713
+ return {
1714
+ title: implementationMeta.name,
1715
+ key: selectedApi,
1716
+ current_implementation_id: implementationMeta.id,
1717
+ // Keep the full versioned ID
1718
+ version: appVersion,
1719
+ // Extract version separately
1720
+ slug: implementationMeta.slug
1721
+ };
1722
+ }
1723
+ function normalizeAuthenticationItem(auth, options = {}) {
1724
+ let appKey = options.app_key;
1725
+ let version = options.version;
1726
+ if (auth.selected_api) {
1727
+ const [extractedAppKey, extractedVersion] = splitVersionedKey(
1728
+ auth.selected_api
1004
1729
  );
1730
+ if (!appKey) {
1731
+ appKey = extractedAppKey;
1732
+ }
1733
+ if (!version) {
1734
+ version = extractedVersion;
1735
+ }
1005
1736
  }
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;
1737
+ const {
1738
+ selected_api: selectedApi,
1739
+ customuser_id: userId,
1740
+ ...restOfAuth
1741
+ } = auth;
1017
1742
  return {
1018
- success: true,
1019
- data: result,
1020
- metadata: {
1021
- executionTime,
1022
- requestId: generateRequestId()
1023
- }
1743
+ ...restOfAuth,
1744
+ // Pass through all other API response fields except selected_api
1745
+ implementation_id: selectedApi,
1746
+ // Rename selected_api to implementation_id
1747
+ title: auth.title || auth.label || void 0,
1748
+ // Coerce title from label if missing
1749
+ is_expired: auth.is_stale,
1750
+ // Map is_stale to is_expired
1751
+ expired_at: auth.marked_stale_at,
1752
+ // Map marked_stale_at to expired_at
1753
+ app_key: appKey,
1754
+ // App key from implementations endpoint or parsed from selected_api
1755
+ version,
1756
+ // Version from selected_api or provided
1757
+ user_id: userId
1758
+ // Map customuser_id to user_id
1024
1759
  };
1025
1760
  }
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
- }
1761
+ function normalizeActionItem(action) {
1762
+ const { name, type, selected_api: appKey, ...restOfAction } = action;
1763
+ return {
1764
+ ...restOfAction,
1765
+ app_key: appKey || "",
1766
+ action_type: type,
1767
+ title: name,
1768
+ // Map name to title
1769
+ type: "action"
1056
1770
  };
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
1771
  }
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 || {}
1772
+ function groupVersionedAppKeysByType(appKeys) {
1773
+ const result = {
1774
+ selectedApi: [],
1775
+ slug: []
1088
1776
  };
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: [] });
1777
+ const seenSelectedApi = /* @__PURE__ */ new Set();
1778
+ const seenSlugs = /* @__PURE__ */ new Set();
1779
+ for (const key of appKeys) {
1780
+ const [keyWithoutVersion, version] = splitVersionedKey(key);
1781
+ const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1782
+ if (uuidRegex.test(keyWithoutVersion)) {
1783
+ throw new Error(
1784
+ `UUID app keys are not supported. Use app slug or implementation ID instead of: ${key}`
1785
+ );
1786
+ }
1787
+ if (isSnakeCasedSlug(keyWithoutVersion)) {
1788
+ const dashified = dashifySnakeCasedSlug(keyWithoutVersion);
1789
+ const slugWithVersion = version ? `${dashified}@${version}` : dashified;
1790
+ if (!seenSlugs.has(slugWithVersion)) {
1791
+ seenSlugs.add(slugWithVersion);
1792
+ result.slug.push(slugWithVersion);
1159
1793
  }
1794
+ continue;
1795
+ }
1796
+ if (keyWithoutVersion.match(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)) {
1797
+ seenSlugs.add(key);
1798
+ result.slug.push(key);
1799
+ continue;
1800
+ }
1801
+ if (!seenSelectedApi.has(key)) {
1802
+ seenSelectedApi.add(key);
1803
+ result.selectedApi.push(key);
1160
1804
  }
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
1805
  }
1177
- return typeDefinitions;
1806
+ return result;
1178
1807
  }
1179
- function parseAppIdentifier(identifier) {
1180
- const parts = identifier.split("@");
1808
+ function groupAppKeysByType(appKeys) {
1809
+ const grouped = groupVersionedAppKeysByType(appKeys);
1181
1810
  return {
1182
- app: parts[0],
1183
- version: parts[1]
1811
+ selectedApi: [
1812
+ ...new Set(grouped.selectedApi.map((key) => key.split("@")[0]))
1813
+ ],
1814
+ slug: [...new Set(grouped.slug.map((key) => key.split("@")[0]))]
1184
1815
  };
1185
1816
  }
1186
- function generateTypeDefinitions(appKey, actions, version) {
1187
- if (actions.length === 0) {
1188
- return generateEmptyTypesFile(appKey, version);
1817
+ function isSnakeCasedSlug(slug) {
1818
+ if (slug.match(/^_[0-9]/)) {
1819
+ slug = slug.slice(1);
1189
1820
  }
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
1821
+ return !!slug.match(/^[a-z0-9]+(?:_[a-z0-9]+)*$/);
1324
1822
  }
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;
1823
+ function dashifySnakeCasedSlug(slug) {
1824
+ if (!isSnakeCasedSlug(slug)) {
1825
+ return slug;
1349
1826
  }
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";
1827
+ if (slug.startsWith("_")) {
1828
+ slug = slug.slice(1);
1391
1829
  }
1830
+ return slug.replace(/_/g, "-");
1392
1831
  }
1393
1832
 
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(", ")}`
1833
+ // src/plugins/listApps/index.ts
1834
+ var listAppsPlugin = ({ context }) => {
1835
+ const listApps = createPaginatedFunction(async function listAppsPage(options) {
1836
+ const api = context.api;
1837
+ const opts = options;
1838
+ const appKeys = [...opts.appKeys ?? []].map(
1839
+ (key) => splitVersionedKey(key)[0]
1840
+ );
1841
+ if (opts.search) {
1842
+ const searchParams2 = {};
1843
+ searchParams2.term = opts.search;
1844
+ const searchEnvelope = await api.get(
1845
+ "/api/v4/implementations-meta/search/",
1846
+ {
1847
+ searchParams: searchParams2
1848
+ }
1426
1849
  );
1850
+ const implementations = searchEnvelope.results.map(
1851
+ normalizeImplementationMetaToAppItem
1852
+ );
1853
+ const appKeysSet = new Set(appKeys);
1854
+ for (const implementation of implementations) {
1855
+ if (!appKeysSet.has(implementation.key)) {
1856
+ appKeysSet.add(implementation.key);
1857
+ appKeys.push(implementation.key);
1858
+ }
1859
+ }
1427
1860
  }
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);
1861
+ const searchParams = {};
1862
+ if (opts.pageSize) {
1863
+ searchParams.limit = opts.pageSize.toString();
1435
1864
  }
1436
- if (output) {
1437
- fs.mkdirSync(path.dirname(output), { recursive: true });
1438
- fs.writeFileSync(output, finalOutput, "utf8");
1865
+ searchParams.latest_only = "true";
1866
+ if (opts.cursor) {
1867
+ searchParams.offset = opts.cursor;
1439
1868
  }
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
- );
1869
+ if (appKeys.length > 0) {
1870
+ const groupedAppKeys = groupAppKeysByType(appKeys);
1871
+ if (groupedAppKeys.selectedApi.length > 0) {
1872
+ searchParams.selected_apis = groupedAppKeys.selectedApi.join(",");
1873
+ }
1874
+ if (groupedAppKeys.slug.length > 0) {
1875
+ searchParams.slugs = groupedAppKeys.slug.join(",");
1514
1876
  }
1515
- return void 0;
1516
1877
  }
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" });
1878
+ const implementationsEnvelope = await api.get(
1879
+ "/api/v4/implementations-meta/lookup/",
1880
+ {
1881
+ searchParams
1564
1882
  }
1565
- if (item.category) {
1566
- details.push({
1567
- text: `Category: ${item.category}`,
1568
- style: "accent"
1569
- });
1883
+ );
1884
+ return {
1885
+ data: implementationsEnvelope.results.map(
1886
+ normalizeImplementationMetaToAppItem
1887
+ ),
1888
+ nextCursor: extractCursor(implementationsEnvelope)
1889
+ };
1890
+ }, ListAppsSchema);
1891
+ return {
1892
+ listApps,
1893
+ context: {
1894
+ meta: {
1895
+ listApps: {
1896
+ inputSchema: ListAppsSchema
1897
+ }
1570
1898
  }
1571
- return {
1572
- title: item.name || item.key,
1573
- subtitle: `(${item.key})`,
1574
- details
1575
- };
1576
1899
  }
1577
- }
1578
- );
1579
-
1580
- // src/functions/listApps/schemas.ts
1581
- var ListAppsSchema = withOutputSchema(
1900
+ };
1901
+ };
1902
+ var GetAppSchema = withOutputSchema(
1582
1903
  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"
1904
+ appKey: AppKeyPropertySchema.describe(
1905
+ "App key of app to fetch (e.g., 'SlackCLIAPI')"
1589
1906
  )
1590
- }).describe("List all available apps with optional filtering"),
1907
+ }).describe("Get detailed information about a specific app"),
1591
1908
  AppItemSchema
1592
1909
  );
1593
1910
 
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
1911
+ // src/plugins/getApp/index.ts
1912
+ var getAppPlugin = ({ sdk }) => {
1913
+ const getApp = createFunction(async function getApp2(options) {
1914
+ const { appKey } = options;
1915
+ const appsIterator = sdk.listApps({
1916
+ ...options,
1917
+ appKeys: [appKey]
1918
+ }).items();
1919
+ const apps = [];
1920
+ for await (const app of appsIterator) {
1921
+ apps.push(app);
1922
+ break;
1923
+ }
1924
+ if (apps.length === 0) {
1925
+ throw new ZapierAppNotFoundError(appKey);
1926
+ }
1927
+ return {
1928
+ data: apps[0]
1929
+ };
1930
+ }, GetAppSchema);
1931
+ return {
1932
+ getApp,
1933
+ context: {
1934
+ meta: {
1935
+ getApp: {
1936
+ inputSchema: GetAppSchema
1937
+ }
1938
+ }
1939
+ }
1940
+ };
1611
1941
  };
1612
1942
  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()
1943
+ ActionSchema.omit({ type: true, name: true }).extend({
1944
+ app_key: zod.z.string(),
1945
+ // Mapped from selected_api
1946
+ action_type: ActionSchema.shape.type,
1947
+ // Mapped from original 'type' field
1948
+ title: zod.z.string(),
1949
+ // Mapped from original 'name' field
1950
+ type: zod.z.literal("action")
1951
+ // Fixed type identifier
1619
1952
  }),
1620
1953
  {
1621
1954
  format: (item) => {
1622
1955
  const details = [];
1623
- details.push({ text: `Type: ${item.type}`, style: "accent" });
1624
- if (item.appKey) {
1625
- details.push({ text: `App: ${item.appKey}`, style: "normal" });
1956
+ details.push({
1957
+ text: `Type: ${item.action_type}`,
1958
+ style: "accent"
1959
+ });
1960
+ if (item.app_key) {
1961
+ details.push({
1962
+ text: `App: ${item.app_key}`,
1963
+ style: "normal"
1964
+ });
1626
1965
  }
1627
1966
  if (item.description) {
1628
1967
  details.push({ text: item.description, style: "dim" });
1629
1968
  }
1630
1969
  return {
1631
- title: item.name || item.key,
1970
+ title: item.title || item.name || item.key,
1632
1971
  subtitle: `(${item.key})`,
1633
1972
  details
1634
1973
  };
@@ -1636,22 +1975,88 @@ var ActionItemSchema = withFormatter(
1636
1975
  }
1637
1976
  );
1638
1977
 
1639
- // src/functions/listActions/schemas.ts
1978
+ // src/plugins/listActions/schemas.ts
1640
1979
  var ListActionsSchema = withOutputSchema(
1641
1980
  zod.z.object({
1642
- appKey: AppKeyPropertySchema.optional(),
1643
- type: ActionTypePropertySchema.optional().describe(
1981
+ appKey: AppKeyPropertySchema.describe(
1982
+ "App key of actions to list (e.g., 'SlackCLIAPI')"
1983
+ ),
1984
+ actionType: ActionTypePropertySchema.optional().describe(
1644
1985
  "Filter actions by type"
1645
- )
1986
+ ),
1987
+ pageSize: zod.z.number().min(1).optional().describe("Number of actions per page"),
1988
+ maxItems: zod.z.number().min(1).optional().describe("Maximum total items to return across all pages")
1646
1989
  }).describe("List all actions for a specific app"),
1647
1990
  ActionItemSchema
1648
1991
  );
1649
1992
 
1650
- // src/functions/listActions/info.ts
1651
- var listActionsInfo = {
1652
- name: listActions.name,
1653
- inputSchema: ListActionsSchema,
1654
- implementation: listActions
1993
+ // src/plugins/listActions/index.ts
1994
+ var listActionsPlugin = ({ sdk, context }) => {
1995
+ const listActions = createPaginatedFunction(async function listActionsPage(options) {
1996
+ const { api } = context;
1997
+ const app = await sdk.getApp({ appKey: options.appKey });
1998
+ const implementationId = app.data.current_implementation_id?.split("@")[0];
1999
+ if (!implementationId) {
2000
+ throw new ZapierConfigurationError(
2001
+ "No current_implementation_id found for app",
2002
+ { configType: "current_implementation_id" }
2003
+ );
2004
+ }
2005
+ const searchParams = {
2006
+ global: "true",
2007
+ public_only: "true",
2008
+ selected_apis: implementationId
2009
+ };
2010
+ const data = await api.get("/api/v4/implementations/", {
2011
+ searchParams,
2012
+ customErrorHandler: ({ status }) => {
2013
+ if (status === 401) {
2014
+ return new ZapierAuthenticationError(
2015
+ `Authentication failed. Your token may not have permission to access implementations or may be expired. (HTTP ${status})`,
2016
+ { statusCode: status }
2017
+ );
2018
+ }
2019
+ if (status === 403) {
2020
+ return new ZapierAuthenticationError(
2021
+ `Access forbidden. Your token may not have the required scopes to list implementations. (HTTP ${status})`,
2022
+ { statusCode: status }
2023
+ );
2024
+ }
2025
+ return void 0;
2026
+ }
2027
+ });
2028
+ let allActions = [];
2029
+ for (const implementation of data.results || []) {
2030
+ if (implementation.actions) {
2031
+ for (const action of implementation.actions) {
2032
+ const actionWithContext = {
2033
+ ...action,
2034
+ selected_api: action.selected_api || implementation.selected_api
2035
+ };
2036
+ allActions.push(normalizeActionItem(actionWithContext));
2037
+ }
2038
+ }
2039
+ }
2040
+ if (options.actionType) {
2041
+ allActions = allActions.filter(
2042
+ (action) => action.action_type === options.actionType
2043
+ );
2044
+ }
2045
+ return {
2046
+ data: allActions,
2047
+ nextCursor: void 0
2048
+ };
2049
+ }, ListActionsSchema);
2050
+ return {
2051
+ listActions,
2052
+ context: {
2053
+ meta: {
2054
+ listActions: {
2055
+ inputSchema: ListActionsSchema
2056
+ }
2057
+ }
2058
+ }
2059
+ };
1655
2060
  };
1656
2061
  var GetActionSchema = zod.z.object({
1657
2062
  appKey: AppKeyPropertySchema,
@@ -1659,305 +2064,589 @@ var GetActionSchema = zod.z.object({
1659
2064
  actionKey: ActionKeyPropertySchema
1660
2065
  }).describe("Get detailed information about a specific action");
1661
2066
 
1662
- // src/functions/getAction/info.ts
1663
- var getActionInfo = {
1664
- name: getAction.name,
1665
- inputSchema: GetActionSchema,
1666
- implementation: getAction
2067
+ // src/plugins/getAction/index.ts
2068
+ var getActionPlugin = ({ sdk }) => {
2069
+ const getAction = createFunction(async function getAction2(options) {
2070
+ const { actionKey, actionType, appKey } = options;
2071
+ const actionsResult = await sdk.listActions({ appKey });
2072
+ for (const action of actionsResult.data) {
2073
+ if (action.key === actionKey && action.action_type === actionType) {
2074
+ return { data: action };
2075
+ }
2076
+ }
2077
+ throw new ZapierResourceNotFoundError(
2078
+ `Action not found: ${actionKey} with type ${actionType}`,
2079
+ { resourceType: "Action", resourceId: `${actionKey} (${actionType})` }
2080
+ );
2081
+ }, GetActionSchema);
2082
+ return {
2083
+ getAction,
2084
+ context: {
2085
+ meta: {
2086
+ getAction: {
2087
+ inputSchema: GetActionSchema
2088
+ }
2089
+ }
2090
+ }
2091
+ };
1667
2092
  };
1668
2093
  var RunActionSchema = zod.z.object({
1669
2094
  appKey: AppKeyPropertySchema,
1670
2095
  actionType: ActionTypePropertySchema,
1671
2096
  actionKey: ActionKeyPropertySchema,
2097
+ authenticationId: AuthenticationIdPropertySchema.nullable().optional(),
1672
2098
  inputs: InputsPropertySchema.optional().describe(
1673
2099
  "Input parameters for the action"
1674
2100
  ),
1675
- authenticationId: AuthenticationIdPropertySchema.optional()
2101
+ pageSize: zod.z.number().min(1).optional().describe("Number of results per page"),
2102
+ maxItems: zod.z.number().min(1).optional().describe("Maximum total items to return across all pages")
1676
2103
  }).describe("Execute an action with the given inputs");
1677
2104
 
1678
- // src/functions/runAction/info.ts
1679
- var runActionInfo = {
1680
- name: runAction.name,
1681
- inputSchema: RunActionSchema,
1682
- implementation: runAction
2105
+ // src/plugins/runAction/index.ts
2106
+ async function executeAction(actionOptions) {
2107
+ const {
2108
+ api,
2109
+ sdk,
2110
+ appKey,
2111
+ actionKey,
2112
+ actionType,
2113
+ executionOptions,
2114
+ authenticationId
2115
+ } = actionOptions;
2116
+ const appData = await sdk.getApp({ appKey });
2117
+ const selectedApi = appData.data.current_implementation_id;
2118
+ if (!selectedApi) {
2119
+ throw new ZapierConfigurationError(
2120
+ "No current_implementation_id found for app",
2121
+ { configType: "current_implementation_id" }
2122
+ );
2123
+ }
2124
+ const runRequestData = {
2125
+ selected_api: selectedApi,
2126
+ action_key: actionKey,
2127
+ action_type: actionType,
2128
+ inputs: executionOptions.inputs || {}
2129
+ };
2130
+ if (authenticationId !== null && authenticationId !== void 0) {
2131
+ runRequestData.authentication_id = authenticationId;
2132
+ }
2133
+ const runRequest = {
2134
+ data: runRequestData
2135
+ };
2136
+ const runData = await api.post("/api/actions/v1/runs", runRequest);
2137
+ const runId = runData.data.id;
2138
+ return await api.poll(`/api/actions/v1/runs/${runId}`, {
2139
+ successStatus: 200,
2140
+ pendingStatus: 202,
2141
+ resultExtractor: (result) => result.data
2142
+ });
2143
+ }
2144
+ var runActionPlugin = ({ sdk, context }) => {
2145
+ const runAction = createPaginatedFunction(async function runActionPage(options) {
2146
+ const { api } = context;
2147
+ const {
2148
+ appKey,
2149
+ actionKey,
2150
+ actionType,
2151
+ authenticationId,
2152
+ inputs = {}
2153
+ } = options;
2154
+ const actionData = await sdk.getAction({
2155
+ appKey,
2156
+ actionKey,
2157
+ actionType
2158
+ });
2159
+ if (actionData.data.action_type !== actionType) {
2160
+ throw new ZapierValidationError(
2161
+ `Action type mismatch: expected ${actionType}, got ${actionData.data.action_type}`
2162
+ );
2163
+ }
2164
+ const result = await executeAction({
2165
+ api,
2166
+ sdk,
2167
+ appKey,
2168
+ actionKey,
2169
+ actionType,
2170
+ executionOptions: { inputs },
2171
+ authenticationId});
2172
+ if (result.errors && result.errors.length > 0) {
2173
+ const errorMessage = result.errors.map(
2174
+ (error) => error.detail || error.title || "Unknown error"
2175
+ ).join("; ");
2176
+ throw new ZapierActionError(`Action execution failed: ${errorMessage}`, {
2177
+ appKey,
2178
+ actionKey
2179
+ });
2180
+ }
2181
+ return {
2182
+ data: result.results || [],
2183
+ nextCursor: void 0
2184
+ // No pagination implemented yet
2185
+ };
2186
+ }, RunActionSchema);
2187
+ return {
2188
+ runAction,
2189
+ context: {
2190
+ meta: {
2191
+ runAction: {
2192
+ inputSchema: RunActionSchema
2193
+ }
2194
+ }
2195
+ }
2196
+ };
1683
2197
  };
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"
2198
+ var ListAuthenticationsSchema = zod.z.object({
2199
+ appKey: AppKeyPropertySchema.optional().describe(
2200
+ "App key of authentications to list (e.g., 'SlackCLIAPI')"
2201
+ ),
2202
+ search: zod.z.string().optional().describe("Search term to filter authentications by title"),
2203
+ title: zod.z.string().optional().describe("Filter authentications by exact title match"),
2204
+ account_id: zod.z.string().optional().describe("Filter by account ID"),
2205
+ owner: zod.z.string().optional().describe("Filter by owner"),
2206
+ pageSize: zod.z.number().min(1).optional().describe("Number of authentications per page"),
2207
+ maxItems: zod.z.number().min(1).optional().describe("Maximum total items to return across all pages")
2208
+ }).describe("List available authentications with optional filtering");
2209
+
2210
+ // src/plugins/listAuthentications/index.ts
2211
+ var listAuthenticationsPlugin = ({ sdk, context }) => {
2212
+ const listAuthentications = createPaginatedFunction(
2213
+ async function listAuthenticationsPage(options) {
2214
+ const { api } = context;
2215
+ const searchParams = {};
2216
+ if (options.appKey) {
2217
+ const app = await sdk.getApp({
2218
+ appKey: options.appKey
1701
2219
  });
2220
+ const selectedApi = app.data.current_implementation_id;
2221
+ if (selectedApi) {
2222
+ const versionlessApi = selectedApi.split("@")[0];
2223
+ searchParams.versionless_selected_api = versionlessApi;
2224
+ }
1702
2225
  }
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
- });
2226
+ if (options.search) {
2227
+ searchParams.search = options.search;
2228
+ } else if (options.title) {
2229
+ searchParams.search = options.title;
2230
+ }
2231
+ if (options.account_id) {
2232
+ searchParams.account_id = options.account_id;
2233
+ }
2234
+ if (options.owner) {
2235
+ searchParams.owner = options.owner;
2236
+ }
2237
+ searchParams.limit = options.pageSize.toString();
2238
+ if (options.cursor) {
2239
+ searchParams.offset = options.cursor;
2240
+ }
2241
+ const data = await api.get(
2242
+ "/api/v4/authentications/",
2243
+ {
2244
+ searchParams,
2245
+ customErrorHandler: ({ status }) => {
2246
+ if (status === 401) {
2247
+ return new ZapierAuthenticationError(
2248
+ `Authentication failed. Your token may not have permission to access authentications or may be expired. (HTTP ${status})`,
2249
+ { statusCode: status }
2250
+ );
2251
+ }
2252
+ if (status === 403) {
2253
+ return new ZapierAuthenticationError(
2254
+ `Access forbidden. Your token may not have the required scopes to list authentications. (HTTP ${status})`,
2255
+ { statusCode: status }
2256
+ );
2257
+ }
2258
+ return void 0;
2259
+ },
2260
+ authRequired: true
2261
+ }
2262
+ );
2263
+ let auths = (data.results || []).map(
2264
+ (auth) => normalizeAuthenticationItem(auth)
2265
+ );
2266
+ if (options.title) {
2267
+ auths = auths.filter((auth) => auth.title === options.title);
1712
2268
  }
1713
2269
  return {
1714
- title: item.title || `Authentication ${item.id}`,
1715
- subtitle: `(ID: ${item.id})`,
1716
- details
2270
+ data: auths,
2271
+ nextCursor: extractCursor(data)
1717
2272
  };
2273
+ },
2274
+ ListAuthenticationsSchema
2275
+ );
2276
+ return {
2277
+ listAuthentications,
2278
+ context: {
2279
+ meta: {
2280
+ listAuthentications: {
2281
+ inputSchema: ListAuthenticationsSchema
2282
+ }
2283
+ }
1718
2284
  }
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
2285
+ };
1760
2286
  };
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
- );
2287
+ var GetAuthenticationSchema = zod.z.object({
2288
+ authenticationId: zod.z.number().int().positive().describe("Authentication ID to retrieve")
2289
+ }).describe("Get a specific authentication by ID");
1779
2290
 
1780
- // src/functions/findFirstAuthentication/info.ts
1781
- var findFirstAuthenticationInfo = {
1782
- name: findFirstAuthentication.name,
1783
- inputSchema: FindFirstAuthenticationSchema,
1784
- implementation: findFirstAuthentication
2291
+ // src/plugins/getAuthentication/index.ts
2292
+ var getAuthenticationPlugin = ({ context }) => {
2293
+ const getAuthentication = createFunction(async function getAuthentication2(options) {
2294
+ const { api } = context;
2295
+ const { authenticationId } = options;
2296
+ const data = await api.get(
2297
+ `/api/v4/authentications/${authenticationId}/`,
2298
+ {
2299
+ customErrorHandler: ({ status }) => {
2300
+ if (status === 401) {
2301
+ return new ZapierAuthenticationError(
2302
+ `Authentication failed. Your token may not have permission to access authentications or may be expired. (HTTP ${status})`,
2303
+ { statusCode: status }
2304
+ );
2305
+ }
2306
+ if (status === 403) {
2307
+ return new ZapierAuthenticationError(
2308
+ `Access forbidden. Your token may not have the required scopes to get authentication ${authenticationId}. (HTTP ${status})`,
2309
+ { statusCode: status }
2310
+ );
2311
+ }
2312
+ if (status === 404) {
2313
+ return new ZapierResourceNotFoundError(
2314
+ `Authentication ${authenticationId} not found. It may not exist or you may not have access to it. (HTTP ${status})`,
2315
+ {
2316
+ resourceType: "Authentication",
2317
+ resourceId: String(authenticationId)
2318
+ }
2319
+ );
2320
+ }
2321
+ return void 0;
2322
+ },
2323
+ authRequired: true
2324
+ }
2325
+ );
2326
+ return {
2327
+ data: normalizeAuthenticationItem(data)
2328
+ };
2329
+ }, GetAuthenticationSchema);
2330
+ return {
2331
+ getAuthentication,
2332
+ context: {
2333
+ meta: {
2334
+ getAuthentication: {
2335
+ inputSchema: GetAuthenticationSchema
2336
+ }
2337
+ }
2338
+ }
2339
+ };
1785
2340
  };
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
- );
2341
+ var FindFirstAuthenticationSchema = zod.z.object({
2342
+ appKey: AppKeyPropertySchema.optional().describe(
2343
+ "App key of authentication to find (e.g., 'SlackCLIAPI')"
2344
+ ),
2345
+ search: zod.z.string().optional().describe("Search term to filter authentications by title"),
2346
+ title: zod.z.string().optional().describe("Filter authentications by exact title match"),
2347
+ account_id: zod.z.string().optional().describe("Filter by account ID"),
2348
+ owner: zod.z.string().optional().describe("Filter by owner")
2349
+ }).describe("Find the first authentication matching the criteria");
1804
2350
 
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
- }
2351
+ // src/plugins/findFirstAuthentication/index.ts
2352
+ var findFirstAuthenticationPlugin = ({ sdk }) => {
2353
+ const findFirstAuthentication = createFunction(
2354
+ async function findFirstAuthentication2(options = {}) {
2355
+ const authsResponse = await sdk.listAuthentications({
2356
+ ...options,
2357
+ maxItems: 1
2358
+ });
1823
2359
  return {
1824
- title: item.name || item.key,
1825
- subtitle: `(${item.key})`,
1826
- details
2360
+ data: authsResponse.data.length > 0 ? authsResponse.data[0] : null
1827
2361
  };
2362
+ },
2363
+ FindFirstAuthenticationSchema
2364
+ );
2365
+ return {
2366
+ findFirstAuthentication,
2367
+ context: {
2368
+ meta: {
2369
+ findFirstAuthentication: {
2370
+ inputSchema: FindFirstAuthenticationSchema
2371
+ }
2372
+ }
1828
2373
  }
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
2374
+ };
1851
2375
  };
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)"
2376
+ var FindUniqueAuthenticationSchema = zod.z.object({
2377
+ appKey: AppKeyPropertySchema.optional().describe(
2378
+ "App key of authentication to find (e.g., 'SlackCLIAPI')"
1857
2379
  ),
1858
- debug: DebugPropertySchema.describe(
1859
- "Enable debug logging during generation"
1860
- )
1861
- }).describe("Generate TypeScript SDK code for a specific app");
2380
+ search: zod.z.string().optional().describe("Search term to filter authentications by title"),
2381
+ title: zod.z.string().optional().describe("Filter authentications by exact title match"),
2382
+ account_id: zod.z.string().optional().describe("Filter by account ID"),
2383
+ owner: zod.z.string().optional().describe("Filter by owner")
2384
+ }).describe("Find a unique authentication matching the criteria");
1862
2385
 
1863
- // src/functions/generateTypes/info.ts
1864
- var generateTypesInfo = {
1865
- name: generateTypes.name,
1866
- inputSchema: GenerateTypesSchema,
1867
- implementation: generateTypes
2386
+ // src/plugins/findUniqueAuthentication/index.ts
2387
+ var findUniqueAuthenticationPlugin = ({ sdk }) => {
2388
+ const findUniqueAuthentication = createFunction(
2389
+ async function findUniqueAuthentication2(options = {}) {
2390
+ const authsResponse = await sdk.listAuthentications({
2391
+ ...options,
2392
+ maxItems: 2
2393
+ // Get up to 2 to check for uniqueness
2394
+ });
2395
+ if (authsResponse.data.length === 0) {
2396
+ throw new ZapierResourceNotFoundError(
2397
+ "No authentication found matching the specified criteria",
2398
+ { resourceType: "Authentication" }
2399
+ );
2400
+ }
2401
+ if (authsResponse.data.length > 1) {
2402
+ throw new ZapierValidationError(
2403
+ "Multiple authentications found matching the specified criteria. Expected exactly one."
2404
+ );
2405
+ }
2406
+ return {
2407
+ data: authsResponse.data[0]
2408
+ };
2409
+ },
2410
+ FindUniqueAuthenticationSchema
2411
+ );
2412
+ return {
2413
+ findUniqueAuthentication,
2414
+ context: {
2415
+ meta: {
2416
+ findUniqueAuthentication: {
2417
+ inputSchema: FindUniqueAuthenticationSchema
2418
+ }
2419
+ }
2420
+ }
2421
+ };
1868
2422
  };
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)"
2423
+ var ListInputFieldsSchema = zod.z.object({
2424
+ appKey: AppKeyPropertySchema,
2425
+ actionType: ActionTypePropertySchema,
2426
+ actionKey: ActionKeyPropertySchema,
2427
+ authenticationId: AuthenticationIdPropertySchema.nullable().optional(),
2428
+ inputs: InputsPropertySchema.optional().describe(
2429
+ "Current input values that may affect available fields"
1873
2430
  ),
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");
2431
+ pageSize: zod.z.number().min(1).optional().describe("Number of input fields per page"),
2432
+ maxItems: zod.z.number().min(1).optional().describe("Maximum total items to return across all pages")
2433
+ }).describe("Get the input fields required for a specific action");
1879
2434
 
1880
- // src/functions/bundleCode/info.ts
1881
- var bundleCodeInfo = {
1882
- name: bundleCode.name,
1883
- inputSchema: BundleCodeSchema,
1884
- implementation: bundleCode
2435
+ // src/plugins/listInputFields/index.ts
2436
+ function getInputFieldTypeFromNeed(need) {
2437
+ if (need.list) {
2438
+ return "ARRAY" /* ARRAY */;
2439
+ }
2440
+ const typeMap = {
2441
+ string: "STRING" /* STRING */,
2442
+ decimal: "NUMBER" /* NUMBER */,
2443
+ integer: "INTEGER" /* INTEGER */,
2444
+ boolean: "BOOLEAN" /* BOOLEAN */,
2445
+ dict: "OBJECT" /* OBJECT */
2446
+ };
2447
+ return typeMap[need.type || ""] || "STRING" /* STRING */;
2448
+ }
2449
+ function getInputFieldFormatFromNeed(need) {
2450
+ if (need.prefill || need.choices) {
2451
+ return "SELECT" /* SELECT */;
2452
+ }
2453
+ const formatMap = {
2454
+ text: "MULTILINE" /* MULTILINE */,
2455
+ datetime: "DATETIME" /* DATETIME */,
2456
+ file: "FILE" /* FILE */,
2457
+ password: "PASSWORD" /* PASSWORD */,
2458
+ code: "CODE" /* CODE */
2459
+ };
2460
+ return formatMap[need.type || ""];
2461
+ }
2462
+ function getItemsTypeFromNeed(need) {
2463
+ if (!need.list) {
2464
+ return void 0;
2465
+ }
2466
+ const typeMap = {
2467
+ string: "STRING" /* STRING */,
2468
+ decimal: "NUMBER" /* NUMBER */,
2469
+ integer: "INTEGER" /* INTEGER */,
2470
+ boolean: "BOOLEAN" /* BOOLEAN */,
2471
+ dict: "OBJECT" /* OBJECT */
2472
+ };
2473
+ return typeMap[need.type || ""] || "STRING" /* STRING */;
2474
+ }
2475
+ function transformNeedToInputFieldItem(need) {
2476
+ const itemsType = getItemsTypeFromNeed(need);
2477
+ return {
2478
+ ...need,
2479
+ // Pass through all original Need fields
2480
+ id: need.key,
2481
+ default_value: need.default || "",
2482
+ depends_on: need.depends_on || [],
2483
+ description: need.help_text || "",
2484
+ invalidates_input_fields: need.alters_custom_fields || false,
2485
+ is_required: need.required || false,
2486
+ placeholder: need.placeholder || "",
2487
+ title: need.label || "",
2488
+ value_type: getInputFieldTypeFromNeed(need),
2489
+ format: getInputFieldFormatFromNeed(need),
2490
+ items: itemsType ? { type: itemsType } : void 0
2491
+ };
2492
+ }
2493
+ var listInputFieldsPlugin = ({ sdk, context }) => {
2494
+ const listInputFields = createPaginatedFunction(
2495
+ async function listInputFieldsPage(options) {
2496
+ const { api } = context;
2497
+ const { appKey, actionKey, actionType, authenticationId, inputs } = options;
2498
+ const appData = await sdk.getApp({ appKey });
2499
+ const selectedApi = appData.data.current_implementation_id;
2500
+ if (!selectedApi) {
2501
+ throw new ZapierConfigurationError(
2502
+ "No current_implementation_id found for app",
2503
+ { configType: "current_implementation_id" }
2504
+ );
2505
+ }
2506
+ const needsRequest = {
2507
+ selected_api: selectedApi,
2508
+ action: actionKey,
2509
+ type_of: actionType,
2510
+ params: inputs || {}
2511
+ };
2512
+ if (authenticationId !== null) {
2513
+ needsRequest.authentication_id = authenticationId;
2514
+ }
2515
+ const needsData = await api.post(
2516
+ "/api/v4/implementations/needs/",
2517
+ needsRequest
2518
+ );
2519
+ if (!needsData.success) {
2520
+ throw new ZapierApiError(
2521
+ `Failed to get action fields: ${needsData.errors?.join(", ") || "Unknown error"}`
2522
+ );
2523
+ }
2524
+ const inputFields = (needsData.needs || []).map(
2525
+ transformNeedToInputFieldItem
2526
+ );
2527
+ return {
2528
+ data: inputFields,
2529
+ nextCursor: void 0
2530
+ // No pagination needed since we return all input fields
2531
+ };
2532
+ },
2533
+ ListInputFieldsSchema
2534
+ );
2535
+ return {
2536
+ listInputFields,
2537
+ context: {
2538
+ meta: {
2539
+ listInputFields: {
2540
+ inputSchema: ListInputFieldsSchema
2541
+ }
2542
+ }
2543
+ }
2544
+ };
1885
2545
  };
1886
2546
 
1887
- // src/functions/fetch/info.ts
1888
- var fetchInfo = {
1889
- name: "fetch",
1890
- inputSchema: RelayFetchSchema,
1891
- implementation: fetch
2547
+ // src/plugins/request/index.ts
2548
+ function transformUrlToRelayPath(url) {
2549
+ const targetUrl = new URL(url);
2550
+ const relayPath = `/relay/${targetUrl.host}${targetUrl.pathname}${targetUrl.search}${targetUrl.hash}`;
2551
+ return relayPath;
2552
+ }
2553
+ var requestPlugin = ({ context }) => {
2554
+ const request = createFunction(async function request2(options) {
2555
+ const { api } = context;
2556
+ const {
2557
+ url,
2558
+ method = "GET",
2559
+ body,
2560
+ headers: optionsHeaders,
2561
+ authenticationId,
2562
+ callbackUrl,
2563
+ authenticationTemplate
2564
+ } = options;
2565
+ const relayPath = transformUrlToRelayPath(url);
2566
+ const headers = {};
2567
+ if (optionsHeaders) {
2568
+ const headerEntries = optionsHeaders instanceof Headers ? Array.from(optionsHeaders.entries()) : Array.isArray(optionsHeaders) ? optionsHeaders : Object.entries(optionsHeaders);
2569
+ for (const [key, value] of headerEntries) {
2570
+ headers[key] = value;
2571
+ }
2572
+ }
2573
+ if (authenticationId) {
2574
+ headers["X-Relay-Authentication-Id"] = authenticationId.toString();
2575
+ }
2576
+ if (callbackUrl) {
2577
+ headers["X-Relay-Callback-Url"] = callbackUrl;
2578
+ }
2579
+ if (authenticationTemplate) {
2580
+ headers["X-Authentication-Template"] = authenticationTemplate;
2581
+ }
2582
+ return await api.fetch(relayPath, {
2583
+ method,
2584
+ body,
2585
+ headers
2586
+ });
2587
+ }, RelayRequestSchema);
2588
+ return {
2589
+ request,
2590
+ context: {
2591
+ meta: {
2592
+ request: {
2593
+ inputSchema: RelayRequestSchema
2594
+ }
2595
+ }
2596
+ }
2597
+ };
1892
2598
  };
1893
2599
 
1894
2600
  // 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
- })
2601
+ function createSdk(initialSdk = {}, initialContext = { meta: {} }) {
2602
+ return {
2603
+ ...initialSdk,
2604
+ getContext: () => initialContext,
2605
+ addPlugin(plugin, options = {}) {
2606
+ const currentSdkWithContext = {
2607
+ ...initialSdk,
2608
+ getContext: () => initialContext
2609
+ };
2610
+ const pluginResult = plugin({
2611
+ sdk: currentSdkWithContext,
2612
+ context: initialContext,
2613
+ ...options
2614
+ });
2615
+ const { context: pluginContext, ...sdkProperties } = pluginResult;
2616
+ const newSdk = { ...initialSdk, ...sdkProperties };
2617
+ let newContext = {
2618
+ ...initialContext,
2619
+ meta: initialContext.meta || {}
2620
+ };
2621
+ if (pluginContext) {
2622
+ const { meta: pluginMeta, ...otherPluginContext } = pluginContext;
2623
+ newContext = {
2624
+ ...newContext,
2625
+ ...otherPluginContext
2626
+ };
2627
+ if (pluginMeta) {
2628
+ newContext = {
2629
+ ...newContext,
2630
+ meta: {
2631
+ ...newContext.meta,
2632
+ // Existing meta (now guaranteed to exist)
2633
+ ...pluginMeta
2634
+ // New meta from plugin
2635
+ }
2636
+ };
2637
+ }
2638
+ }
2639
+ return createSdk(newSdk, newContext);
2640
+ }
1953
2641
  };
1954
- return fullSdk;
2642
+ }
2643
+ function createZapierSdk(options = {}) {
2644
+ return createSdk().addPlugin(apiPlugin, options).addPlugin(listAppsPlugin).addPlugin(getAppPlugin).addPlugin(listActionsPlugin).addPlugin(getActionPlugin).addPlugin(listInputFieldsPlugin).addPlugin(runActionPlugin).addPlugin(listAuthenticationsPlugin).addPlugin(getAuthenticationPlugin).addPlugin(findFirstAuthenticationPlugin).addPlugin(findUniqueAuthenticationPlugin).addPlugin(requestPlugin).addPlugin(fetchPlugin).addPlugin(appsPlugin).addPlugin(getProfilePlugin).addPlugin(registryPlugin);
1955
2645
  }
1956
2646
 
1957
2647
  exports.ActionKeyPropertySchema = ActionKeyPropertySchema;
1958
2648
  exports.ActionTypePropertySchema = ActionTypePropertySchema;
1959
2649
  exports.AppKeyPropertySchema = AppKeyPropertySchema;
1960
- exports.AppNotFoundError = AppNotFoundError;
1961
2650
  exports.AuthenticationIdPropertySchema = AuthenticationIdPropertySchema;
1962
2651
  exports.DebugPropertySchema = DebugPropertySchema;
1963
2652
  exports.InputsPropertySchema = InputsPropertySchema;
@@ -1966,21 +2655,28 @@ exports.OffsetPropertySchema = OffsetPropertySchema;
1966
2655
  exports.OutputPropertySchema = OutputPropertySchema;
1967
2656
  exports.ParamsPropertySchema = ParamsPropertySchema;
1968
2657
  exports.RelayFetchSchema = RelayFetchSchema;
1969
- exports.ZapierSdkError = ZapierSdkError;
2658
+ exports.RelayRequestSchema = RelayRequestSchema;
2659
+ exports.ZapierActionError = ZapierActionError;
2660
+ exports.ZapierApiError = ZapierApiError;
2661
+ exports.ZapierAppNotFoundError = ZapierAppNotFoundError;
2662
+ exports.ZapierAuthenticationError = ZapierAuthenticationError;
2663
+ exports.ZapierBundleError = ZapierBundleError;
2664
+ exports.ZapierConfigurationError = ZapierConfigurationError;
2665
+ exports.ZapierError = ZapierError;
2666
+ exports.ZapierNotFoundError = ZapierNotFoundError;
2667
+ exports.ZapierResourceNotFoundError = ZapierResourceNotFoundError;
2668
+ exports.ZapierTimeoutError = ZapierTimeoutError;
2669
+ exports.ZapierUnknownError = ZapierUnknownError;
2670
+ exports.ZapierValidationError = ZapierValidationError;
1970
2671
  exports.actionKeyResolver = actionKeyResolver;
1971
2672
  exports.actionTypeResolver = actionTypeResolver;
1972
2673
  exports.appKeyResolver = appKeyResolver;
2674
+ exports.appsPlugin = appsPlugin;
1973
2675
  exports.authenticationIdResolver = authenticationIdResolver;
1974
- exports.bundleCode = bundleCode;
1975
- exports.createAppsPlugin = createAppsPlugin;
2676
+ exports.createSdk = createSdk;
1976
2677
  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;
2678
+ exports.fetchPlugin = fetchPlugin;
2679
+ exports.formatErrorMessage = formatErrorMessage;
1984
2680
  exports.getResolutionOrder = getResolutionOrder;
1985
2681
  exports.getResolutionOrderForParams = getResolutionOrderForParams;
1986
2682
  exports.getResolvableParams = getResolvableParams;
@@ -1992,10 +2688,4 @@ exports.getTokenFromEnvOrConfig = getTokenFromEnvOrConfig;
1992
2688
  exports.hasResolver = hasResolver;
1993
2689
  exports.inputsResolver = inputsResolver;
1994
2690
  exports.isPositional = isPositional;
1995
- exports.listActions = listActions;
1996
- exports.listApps = listApps;
1997
- exports.listAuthentications = listAuthentications;
1998
- exports.listFields = listFields;
1999
- exports.relayFetch = relayFetch;
2000
2691
  exports.resolverRegistry = resolverRegistry;
2001
- exports.runAction = runAction;