@zapier/zapier-sdk-cli 0.67.6 → 0.69.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.
package/dist/index.cjs CHANGED
@@ -11,7 +11,7 @@ var zapierSdk = require('@zapier/zapier-sdk');
11
11
  var zod = require('zod');
12
12
  var chalk3 = require('chalk');
13
13
  var os = require('os');
14
- var inquirer = require('inquirer');
14
+ var inquirer3 = require('inquirer');
15
15
  var express = require('express');
16
16
  var promises$1 = require('readline/promises');
17
17
  var open = require('open');
@@ -25,8 +25,13 @@ require('is-installed-globally');
25
25
  var child_process = require('child_process');
26
26
  var Handlebars = require('handlebars');
27
27
  var url = require('url');
28
+ var core = require('@inquirer/core');
29
+ var packageJsonLib = require('package-json');
30
+ var semver = require('semver');
31
+ var crossSpawn = require('cross-spawn');
32
+ var wrapAnsi = require('wrap-ansi');
33
+ var Table = require('cli-table3');
28
34
  var experimental = require('@zapier/zapier-sdk/experimental');
29
- require('wrap-ansi');
30
35
 
31
36
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
32
37
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -56,13 +61,18 @@ var crypto__default = /*#__PURE__*/_interopDefault(crypto);
56
61
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
57
62
  var lockfile__namespace = /*#__PURE__*/_interopNamespace(lockfile);
58
63
  var chalk3__default = /*#__PURE__*/_interopDefault(chalk3);
59
- var inquirer__default = /*#__PURE__*/_interopDefault(inquirer);
64
+ var inquirer3__default = /*#__PURE__*/_interopDefault(inquirer3);
60
65
  var express__default = /*#__PURE__*/_interopDefault(express);
61
66
  var open__default = /*#__PURE__*/_interopDefault(open);
62
67
  var ora__default = /*#__PURE__*/_interopDefault(ora);
63
68
  var pkceChallenge__default = /*#__PURE__*/_interopDefault(pkceChallenge);
64
69
  var ts__namespace = /*#__PURE__*/_interopNamespace(ts);
65
70
  var Handlebars__default = /*#__PURE__*/_interopDefault(Handlebars);
71
+ var packageJsonLib__default = /*#__PURE__*/_interopDefault(packageJsonLib);
72
+ var semver__default = /*#__PURE__*/_interopDefault(semver);
73
+ var crossSpawn__default = /*#__PURE__*/_interopDefault(crossSpawn);
74
+ var wrapAnsi__default = /*#__PURE__*/_interopDefault(wrapAnsi);
75
+ var Table__default = /*#__PURE__*/_interopDefault(Table);
66
76
 
67
77
  var __defProp = Object.defineProperty;
68
78
  var __export = (target, all) => {
@@ -2001,7 +2011,7 @@ async function promptCredentialsName({
2001
2011
  email,
2002
2012
  promptMessage
2003
2013
  }) {
2004
- const { credentialName } = await inquirer__default.default.prompt([
2014
+ const { credentialName } = await inquirer3__default.default.prompt([
2005
2015
  {
2006
2016
  type: "input",
2007
2017
  name: "credentialName",
@@ -2064,7 +2074,7 @@ async function promptConfirm({
2064
2074
  message,
2065
2075
  defaultValue
2066
2076
  }) {
2067
- const { confirmed } = await inquirer__default.default.prompt([
2077
+ const { confirmed } = await inquirer3__default.default.prompt([
2068
2078
  { type: "confirm", name: "confirmed", message, default: defaultValue }
2069
2079
  ]);
2070
2080
  return confirmed;
@@ -4140,26 +4150,57 @@ var InitSchema = zod.z.object({
4140
4150
  }).describe(
4141
4151
  "Create a new Zapier SDK project in a new directory with starter files"
4142
4152
  );
4153
+ var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
4154
+ var LOCKFILES = [
4155
+ ["pnpm-lock.yaml", "pnpm"],
4156
+ ["yarn.lock", "yarn"],
4157
+ ["bun.lock", "bun"],
4158
+ ["bun.lockb", "bun"],
4159
+ ["package-lock.json", "npm"]
4160
+ ];
4161
+ function readDeclaredPackageManager(cwd) {
4162
+ try {
4163
+ const manifest = JSON.parse(
4164
+ fs.readFileSync(path.join(cwd, "package.json"), "utf8")
4165
+ );
4166
+ if (typeof manifest !== "object" || manifest === null || !("packageManager" in manifest) || typeof manifest.packageManager !== "string") {
4167
+ return void 0;
4168
+ }
4169
+ const [name] = manifest.packageManager.split("@", 1);
4170
+ return PACKAGE_MANAGERS.find((packageManager) => packageManager === name);
4171
+ } catch {
4172
+ return void 0;
4173
+ }
4174
+ }
4143
4175
  function detectPackageManager(cwd = process.cwd()) {
4144
- const ua = process.env.npm_config_user_agent;
4145
- if (ua) {
4146
- if (ua.includes("yarn")) return { name: "yarn", source: "runtime" };
4147
- if (ua.includes("pnpm")) return { name: "pnpm", source: "runtime" };
4148
- if (ua.includes("bun")) return { name: "bun", source: "runtime" };
4149
- if (ua.includes("npm")) return { name: "npm", source: "runtime" };
4150
- }
4151
- const files = [
4152
- ["pnpm-lock.yaml", "pnpm"],
4153
- ["yarn.lock", "yarn"],
4154
- ["bun.lockb", "bun"],
4155
- ["package-lock.json", "npm"]
4156
- ];
4157
- for (const [file, name] of files) {
4158
- if (fs.existsSync(path.join(cwd, file))) {
4159
- return { name, source: "lockfile" };
4176
+ const lockfileManagers = new Set(
4177
+ LOCKFILES.filter(([file]) => fs.existsSync(path.join(cwd, file))).map(
4178
+ ([, packageManager]) => packageManager
4179
+ )
4180
+ );
4181
+ if (lockfileManagers.size === 1) {
4182
+ return { name: [...lockfileManagers][0], source: "lockfile" };
4183
+ }
4184
+ const declaredPackageManager = readDeclaredPackageManager(cwd);
4185
+ if (declaredPackageManager) {
4186
+ return { name: declaredPackageManager, source: "package-json" };
4187
+ }
4188
+ const userAgent = process.env.npm_config_user_agent;
4189
+ if (userAgent) {
4190
+ if (userAgent.includes("yarn")) {
4191
+ return { name: "yarn", source: "runtime" };
4192
+ }
4193
+ if (userAgent.includes("pnpm")) {
4194
+ return { name: "pnpm", source: "runtime" };
4195
+ }
4196
+ if (userAgent.includes("bun")) {
4197
+ return { name: "bun", source: "runtime" };
4198
+ }
4199
+ if (userAgent.includes("npm")) {
4200
+ return { name: "npm", source: "runtime" };
4160
4201
  }
4161
4202
  }
4162
- return { name: "unknown", source: "fallback" };
4203
+ return { name: "npm", source: "fallback" };
4163
4204
  }
4164
4205
  function getDirentParentPath(entry) {
4165
4206
  const e = entry;
@@ -4207,7 +4248,7 @@ async function promptYesNo({
4207
4248
  nonInteractive
4208
4249
  }) {
4209
4250
  if (nonInteractive) return defaultValue;
4210
- const { answer } = await inquirer__default.default.prompt([
4251
+ const { answer } = await inquirer3__default.default.prompt([
4211
4252
  { type: "confirm", name: "answer", message, default: defaultValue }
4212
4253
  ]);
4213
4254
  return answer;
@@ -4557,17 +4598,16 @@ var initPlugin = zapierSdk.defineMethod({
4557
4598
  const cwd = process.cwd();
4558
4599
  const { projectName, projectDir } = validateInitOptions({ rawName, cwd });
4559
4600
  const displayHooks = createConsoleDisplayHooks();
4560
- const packageManagerInfo = detectPackageManager(cwd);
4561
- if (packageManagerInfo.name === "unknown") {
4601
+ const packageManager = detectPackageManager(cwd);
4602
+ if (packageManager.source === "fallback") {
4562
4603
  displayHooks.onWarn(
4563
4604
  "Could not detect package manager, defaulting to npm."
4564
4605
  );
4565
4606
  }
4566
- const packageManager = packageManagerInfo.name === "unknown" ? "npm" : packageManagerInfo.name;
4567
4607
  const steps = getInitSteps({
4568
4608
  projectDir,
4569
4609
  projectName,
4570
- packageManager,
4610
+ packageManager: packageManager.name,
4571
4611
  displayHooks
4572
4612
  });
4573
4613
  const completedSetupStepIds = [];
@@ -4595,8 +4635,1729 @@ var initPlugin = zapierSdk.defineMethod({
4595
4635
  projectName,
4596
4636
  steps,
4597
4637
  completedSetupStepIds,
4598
- packageManager
4638
+ packageManager: packageManager.name
4639
+ });
4640
+ }
4641
+ });
4642
+ function isSelectable(item) {
4643
+ return !core.Separator.isSeparator(item) && !item.disabled;
4644
+ }
4645
+ function normalizeChoices(choices) {
4646
+ return choices.map((choice) => {
4647
+ if (core.Separator.isSeparator(choice)) return choice;
4648
+ const name = choice.name ?? String(choice.value);
4649
+ return {
4650
+ value: choice.value,
4651
+ name,
4652
+ short: choice.short ?? name,
4653
+ disabled: choice.disabled ?? false
4654
+ };
4655
+ });
4656
+ }
4657
+ var theme = core.makeTheme({
4658
+ icon: { cursor: "\u276F" },
4659
+ style: {
4660
+ disabled: (text) => chalk3__default.default.dim(`- ${text}`),
4661
+ searchTerm: (text) => chalk3__default.default.cyan(text),
4662
+ keysHelpTip: (keys) => keys.map(([key, action]) => `${chalk3__default.default.bold(key)} ${chalk3__default.default.dim(action)}`).join(chalk3__default.default.dim(" \u2022 "))
4663
+ }
4664
+ });
4665
+ var searchSelect = core.createPrompt(
4666
+ (config2, done) => {
4667
+ const { pageSize = 7 } = config2;
4668
+ const [status, setStatus] = core.useState(
4669
+ "loading"
4670
+ );
4671
+ const [searchTerm, setSearchTerm] = core.useState("");
4672
+ const [searchResults, setSearchResults] = core.useState([]);
4673
+ const [searchError, setSearchError] = core.useState();
4674
+ const prefix = core.usePrefix({ status, theme });
4675
+ const bounds = core.useMemo(() => {
4676
+ const first = searchResults.findIndex(isSelectable);
4677
+ let last = -1;
4678
+ for (let i = searchResults.length - 1; i >= 0; i--) {
4679
+ if (isSelectable(searchResults[i])) {
4680
+ last = i;
4681
+ break;
4682
+ }
4683
+ }
4684
+ return { first, last };
4685
+ }, [searchResults]);
4686
+ const defaultActive = core.useMemo(() => {
4687
+ const requested = config2.initialActive;
4688
+ if (searchTerm === "" && requested !== void 0 && requested >= 0 && requested < searchResults.length && isSelectable(searchResults[requested])) {
4689
+ return requested;
4690
+ }
4691
+ return bounds.first;
4692
+ }, [searchResults, searchTerm, bounds.first]);
4693
+ const [active = defaultActive, setActive] = core.useState();
4694
+ core.useEffect(() => {
4695
+ const controller = new AbortController();
4696
+ setStatus("loading");
4697
+ setSearchError(void 0);
4698
+ const fetchResults = async () => {
4699
+ try {
4700
+ const results = await config2.source(searchTerm || void 0);
4701
+ if (!controller.signal.aborted) {
4702
+ setActive(void 0);
4703
+ setSearchError(void 0);
4704
+ setSearchResults(normalizeChoices(results));
4705
+ setStatus("idle");
4706
+ }
4707
+ } catch (error2) {
4708
+ if (!controller.signal.aborted && error2 instanceof Error) {
4709
+ setSearchError(error2.message);
4710
+ }
4711
+ }
4712
+ };
4713
+ void fetchResults();
4714
+ return () => {
4715
+ controller.abort();
4716
+ };
4717
+ }, [searchTerm]);
4718
+ const selectedChoice = searchResults[active];
4719
+ core.useKeypress((key, rl) => {
4720
+ if (core.isEnterKey(key)) {
4721
+ if (selectedChoice && isSelectable(selectedChoice)) {
4722
+ setStatus("done");
4723
+ done(selectedChoice.value);
4724
+ } else {
4725
+ rl.write(searchTerm);
4726
+ }
4727
+ } else if (core.isTabKey(key) && selectedChoice && isSelectable(selectedChoice)) {
4728
+ rl.clearLine(0);
4729
+ rl.write(selectedChoice.name);
4730
+ setSearchTerm(selectedChoice.name);
4731
+ } else if (status !== "loading" && (core.isUpKey(key) || core.isDownKey(key))) {
4732
+ rl.clearLine(0);
4733
+ if (core.isUpKey(key) && active !== bounds.first || core.isDownKey(key) && active !== bounds.last) {
4734
+ const offset = core.isUpKey(key) ? -1 : 1;
4735
+ let next = active;
4736
+ do {
4737
+ next = (next + offset + searchResults.length) % searchResults.length;
4738
+ } while (!isSelectable(searchResults[next]));
4739
+ setActive(next);
4740
+ }
4741
+ } else {
4742
+ setSearchTerm(rl.line);
4743
+ }
4744
+ });
4745
+ const page = core.usePagination({
4746
+ items: searchResults,
4747
+ active,
4748
+ renderItem({ item, isActive }) {
4749
+ if (core.Separator.isSeparator(item)) {
4750
+ return ` ${item.separator}`;
4751
+ }
4752
+ if (item.disabled) {
4753
+ const disabledLabel = typeof item.disabled === "string" ? item.disabled : "(disabled)";
4754
+ return theme.style.disabled(`${item.name} ${disabledLabel}`);
4755
+ }
4756
+ const color = isActive ? theme.style.highlight : (x) => x;
4757
+ const cursor = isActive ? theme.icon.cursor : ` `;
4758
+ return color(`${cursor} ${item.name}`);
4759
+ },
4760
+ pageSize,
4761
+ loop: false
4762
+ });
4763
+ const message = theme.style.message(config2.message, status);
4764
+ if (status === "done" && selectedChoice && isSelectable(selectedChoice)) {
4765
+ return [prefix, message, theme.style.answer(selectedChoice.short)].filter(Boolean).join(" ").trimEnd();
4766
+ }
4767
+ const searchStr = theme.style.searchTerm(searchTerm);
4768
+ const helpTip = theme.style.keysHelpTip([
4769
+ ["\u2191\u2193", "navigate"],
4770
+ ["\u23CE", "select"]
4771
+ ]);
4772
+ let error;
4773
+ if (searchError) {
4774
+ error = theme.style.error(searchError);
4775
+ } else if (searchResults.length === 0 && searchTerm !== "" && status === "idle") {
4776
+ error = theme.style.error("No results found");
4777
+ }
4778
+ const header = [prefix, message, searchStr].filter(Boolean).join(" ").trimEnd();
4779
+ const body = [error ?? page, " ", helpTip].filter(Boolean).join("\n").trimEnd();
4780
+ return [header, body];
4781
+ }
4782
+ );
4783
+
4784
+ // src/utils/controller-answer.ts
4785
+ function offers(question, action) {
4786
+ return question.actions.some((a) => a.action === action);
4787
+ }
4788
+ function isActionRow(value) {
4789
+ return typeof value === "object" && value !== null && "action" in value;
4790
+ }
4791
+ async function promptText({
4792
+ message,
4793
+ password
4794
+ }) {
4795
+ const { value } = await inquirer3__default.default.prompt([
4796
+ {
4797
+ type: password ? "password" : "input",
4798
+ name: "value",
4799
+ message,
4800
+ theme: HIGH_CONTRAST_PROMPT_THEME
4801
+ }
4802
+ ]);
4803
+ return value;
4804
+ }
4805
+ var display = (c) => c.hint ? `${c.label} ${chalk3__default.default.dim(`(${c.hint})`)}` : c.label;
4806
+ var HIGH_CONTRAST_PROMPT_THEME = {
4807
+ style: {
4808
+ answer: (text) => chalk3__default.default.inverse.bold(` ${text} `)
4809
+ }
4810
+ };
4811
+ function buildSelectRows(question, term) {
4812
+ const row = (name, action) => ({
4813
+ name,
4814
+ value: { action }
4815
+ });
4816
+ const t = term.trim().toLowerCase();
4817
+ const matched = t ? question.choices.filter(
4818
+ (c) => `${c.label} ${c.hint ?? ""}`.toLowerCase().includes(t)
4819
+ ) : question.choices;
4820
+ const matchRows = matched.map((c) => ({
4821
+ name: display(c),
4822
+ value: c.value
4823
+ }));
4824
+ const skipRow = offers(question, "skip") ? [row(chalk3__default.default.dim("Skip (optional)"), "skip")] : [];
4825
+ const customRow = offers(question, "custom") ? [row(chalk3__default.default.dim("Enter a value manually\u2026"), "custom")] : [];
4826
+ const committed = !!t || question.search !== void 0;
4827
+ let rows;
4828
+ if (!committed) {
4829
+ rows = [...skipRow, ...customRow, ...matchRows];
4830
+ } else if (matchRows.length > 0) {
4831
+ rows = [...matchRows, ...skipRow, ...customRow];
4832
+ } else {
4833
+ rows = [...customRow, ...skipRow];
4834
+ }
4835
+ if (offers(question, "search"))
4836
+ rows.push(row(chalk3__default.default.cyan("Search again\u2026"), "search"));
4837
+ if (offers(question, "next_page"))
4838
+ rows.push(row(chalk3__default.default.dim("Load more\u2026"), "next_page"));
4839
+ if (offers(question, "retry")) rows.push(row(chalk3__default.default.yellow("Retry"), "retry"));
4840
+ if (offers(question, "cancel")) rows.push(row(chalk3__default.default.dim("Cancel"), "cancel"));
4841
+ for (const note of question.notes ?? [])
4842
+ rows.push({ name: chalk3__default.default.dim(note), value: note, disabled: true });
4843
+ return rows;
4844
+ }
4845
+ function foldPage(acc, question, field) {
4846
+ const page = question.page;
4847
+ if (!page) {
4848
+ return {
4849
+ key: field,
4850
+ pageIndex: 0,
4851
+ choices: question.choices,
4852
+ newStart: 0,
4853
+ checked: []
4854
+ };
4855
+ }
4856
+ const key = `${field}#${page.generation}`;
4857
+ if (acc?.key === key && page.index === acc.pageIndex + 1) {
4858
+ return {
4859
+ key,
4860
+ pageIndex: page.index,
4861
+ choices: [...acc.choices, ...question.choices],
4862
+ newStart: acc.choices.length,
4863
+ checked: acc.checked
4864
+ };
4865
+ }
4866
+ if (acc?.key === key && page.index === acc.pageIndex) {
4867
+ return { ...acc, newStart: 0 };
4868
+ }
4869
+ return {
4870
+ key,
4871
+ pageIndex: page.index,
4872
+ choices: question.choices,
4873
+ newStart: 0,
4874
+ checked: []
4875
+ };
4876
+ }
4877
+ async function answerSelect(question, field, box, failed, mode) {
4878
+ const acc = failed ? void 0 : box.acc = foldPage(box.acc, question, field);
4879
+ const view = acc ? { ...question, choices: acc.choices } : question;
4880
+ const isClosedListPrompt = mode === "closed-list" && !failed && !view.multiple;
4881
+ const booleanValues = view.choices.map(({ value: value2 }) => value2);
4882
+ if (isClosedListPrompt && booleanValues.length === 2 && booleanValues.includes("true") && booleanValues.includes("false")) {
4883
+ const { value: value2 } = await inquirer3__default.default.prompt([
4884
+ {
4885
+ type: "confirm",
4886
+ name: "value",
4887
+ message: view.message,
4888
+ default: booleanValues[0] === "true",
4889
+ theme: HIGH_CONTRAST_PROMPT_THEME
4890
+ }
4891
+ ]);
4892
+ return { type: "choose", value: String(value2) };
4893
+ }
4894
+ if (isClosedListPrompt && view.choices.length > 0 && !offers(view, "search") && !offers(view, "next_page") && !offers(view, "retry")) {
4895
+ const choices = view.choices.map((choice) => ({
4896
+ name: display(choice),
4897
+ value: choice.value
4898
+ }));
4899
+ const { value: value2 } = await inquirer3__default.default.prompt([
4900
+ {
4901
+ type: "list",
4902
+ name: "value",
4903
+ message: view.message,
4904
+ choices,
4905
+ theme: HIGH_CONTRAST_PROMPT_THEME
4906
+ }
4907
+ ]);
4908
+ return { type: "choose", value: value2 };
4909
+ }
4910
+ if (question.multiple && acc) {
4911
+ if (acc.newStart > 0 && process.stdout.isTTY) {
4912
+ process.stdout.write("\x1B[1A\x1B[2K");
4913
+ }
4914
+ const choices = [
4915
+ ...acc.choices.map((c) => ({
4916
+ name: display(c),
4917
+ value: c.value,
4918
+ checked: acc.checked.includes(c.value)
4919
+ })),
4920
+ ...offers(question, "next_page") ? [
4921
+ {
4922
+ name: chalk3__default.default.dim("Load more\u2026"),
4923
+ value: { action: "next_page" }
4924
+ }
4925
+ ] : [],
4926
+ ...(question.notes ?? []).map((note) => ({
4927
+ name: chalk3__default.default.dim(note),
4928
+ value: note,
4929
+ disabled: true
4930
+ }))
4931
+ ];
4932
+ const { values } = await inquirer3__default.default.prompt([
4933
+ {
4934
+ type: "checkbox",
4935
+ name: "values",
4936
+ message: question.message,
4937
+ choices,
4938
+ theme: HIGH_CONTRAST_PROMPT_THEME
4939
+ }
4940
+ ]);
4941
+ const selected = values;
4942
+ const picked = selected.filter((v) => !isActionRow(v));
4943
+ if (selected.some(isActionRow)) {
4944
+ box.acc = { ...acc, checked: picked };
4945
+ return { type: "next_page" };
4946
+ }
4947
+ if (picked.length === 0 && offers(question, "skip")) {
4948
+ return { type: "skip" };
4949
+ }
4950
+ return { type: "choose", value: picked };
4951
+ }
4952
+ if (offers(question, "search") && question.search === void 0) {
4953
+ const optional = offers(question, "skip");
4954
+ const parts = [
4955
+ ...optional ? ["optional"] : [],
4956
+ ...question.placeholder ? [question.placeholder] : []
4957
+ ];
4958
+ const hint = parts.length ? ` (${parts.join(", ")})` : "";
4959
+ while (true) {
4960
+ const term = (await promptText({
4961
+ message: `Enter or search ${field}${hint}:`,
4962
+ password: false
4963
+ })).trim();
4964
+ if (term) return { type: "search", term };
4965
+ if (optional) return { type: "skip" };
4966
+ }
4967
+ }
4968
+ const newStart = acc?.newStart ?? 0;
4969
+ const firstFreshValue = newStart > 0 ? view.choices[newStart]?.value : void 0;
4970
+ const initialActive = firstFreshValue !== void 0 ? buildSelectRows(view, "").findIndex((r) => r.value === firstFreshValue) : -1;
4971
+ const value = await searchSelect(
4972
+ {
4973
+ message: view.message,
4974
+ source: (term) => buildSelectRows(view, term ?? ""),
4975
+ ...initialActive >= 0 ? { initialActive } : {}
4976
+ },
4977
+ { clearPromptOnDone: true }
4978
+ );
4979
+ if (!isActionRow(value)) {
4980
+ const picked = view.choices.find((c) => c.value === value);
4981
+ printAnswered(view.message, picked?.label ?? String(value));
4982
+ return { type: "choose", value };
4983
+ }
4984
+ switch (value.action) {
4985
+ case "search": {
4986
+ const term = await promptText({
4987
+ message: `Search ${field}:`,
4988
+ password: false
4989
+ });
4990
+ return { type: "search", term };
4991
+ }
4992
+ case "custom": {
4993
+ const custom = await promptText({
4994
+ message: `Enter ${field}:`,
4995
+ password: false
4996
+ });
4997
+ return { type: "custom", value: custom };
4998
+ }
4999
+ case "next_page":
5000
+ return { type: "next_page" };
5001
+ case "retry":
5002
+ return { type: "retry" };
5003
+ case "skip":
5004
+ printAnswered(view.message, chalk3__default.default.dim("(skipped)"));
5005
+ return { type: "skip" };
5006
+ case "cancel":
5007
+ return { type: "cancel" };
5008
+ }
5009
+ }
5010
+ function printAnswered(message, label) {
5011
+ console.log(`${chalk3__default.default.green("\u2714")} ${message} ${chalk3__default.default.cyan(label)}`);
5012
+ }
5013
+ async function answerInput(question) {
5014
+ const message = question.placeholder ? question.message.replace(/:?\s*$/, ` (${question.placeholder}):`) : question.message;
5015
+ const value = await promptText({
5016
+ message,
5017
+ password: question.inputType === "password"
5018
+ });
5019
+ if (value === "" && offers(question, "skip")) {
5020
+ return { type: "skip" };
5021
+ }
5022
+ return { type: "custom", value };
5023
+ }
5024
+ async function answerCollection(question) {
5025
+ if (!offers(question, "done")) {
5026
+ return { type: "add" };
5027
+ }
5028
+ if (question.description) console.log(question.description);
5029
+ const { again } = await inquirer3__default.default.prompt([
5030
+ {
5031
+ type: "confirm",
5032
+ name: "again",
5033
+ message: question.message,
5034
+ default: false,
5035
+ theme: HIGH_CONTRAST_PROMPT_THEME
5036
+ }
5037
+ ]);
5038
+ return again ? { type: "add" } : { type: "done" };
5039
+ }
5040
+ function createCliAnswer({
5041
+ mode = "search"
5042
+ } = {}) {
5043
+ const box = {};
5044
+ return async ({ result }) => {
5045
+ try {
5046
+ if (result.error !== void 0) {
5047
+ const message = typeof result.error === "string" ? result.error : result.error.message;
5048
+ console.log(chalk3__default.default.yellow(`! ${message}`));
5049
+ }
5050
+ const question = result.question;
5051
+ const field = question.path.length ? question.path.join(".") : "value";
5052
+ switch (question.type) {
5053
+ case "select":
5054
+ return await answerSelect(
5055
+ question,
5056
+ field,
5057
+ box,
5058
+ result.status === "failed",
5059
+ mode
5060
+ );
5061
+ case "input":
5062
+ return await answerInput(question);
5063
+ case "collection":
5064
+ return await answerCollection(question);
5065
+ }
5066
+ } catch (error) {
5067
+ if (error instanceof Error && error.name === "ExitPromptError") {
5068
+ return { type: "cancel" };
5069
+ }
5070
+ throw error;
5071
+ }
5072
+ };
5073
+ }
5074
+ var ONE_DAY_MILLISECONDS = 24 * 60 * 60 * 1e3;
5075
+ var CACHE_RESET_INTERVAL_MILLISECONDS = (() => {
5076
+ const {
5077
+ ZAPIER_SDK_UPDATE_CHECK_INTERVAL_SECONDS,
5078
+ ZAPIER_SDK_UPDATE_CHECK_INTERVAL_MS
5079
+ } = process.env;
5080
+ let intervalMs;
5081
+ if (ZAPIER_SDK_UPDATE_CHECK_INTERVAL_SECONDS !== void 0) {
5082
+ const seconds = parseInt(ZAPIER_SDK_UPDATE_CHECK_INTERVAL_SECONDS);
5083
+ intervalMs = isNaN(seconds) ? NaN : seconds * 1e3;
5084
+ } else if (ZAPIER_SDK_UPDATE_CHECK_INTERVAL_MS !== void 0) {
5085
+ intervalMs = parseInt(ZAPIER_SDK_UPDATE_CHECK_INTERVAL_MS);
5086
+ } else {
5087
+ intervalMs = ONE_DAY_MILLISECONDS;
5088
+ }
5089
+ if (isNaN(intervalMs) || intervalMs < 0) {
5090
+ return -1;
5091
+ }
5092
+ return intervalMs;
5093
+ })();
5094
+ function getVersionCache() {
5095
+ try {
5096
+ const cache = getConfig().get("version_cache");
5097
+ const now = Date.now();
5098
+ if (!cache || !cache.last_reset_timestamp || now - cache.last_reset_timestamp >= CACHE_RESET_INTERVAL_MILLISECONDS) {
5099
+ const newCache = {
5100
+ last_reset_timestamp: now,
5101
+ packages: {}
5102
+ };
5103
+ getConfig().set("version_cache", newCache);
5104
+ return newCache;
5105
+ }
5106
+ return cache;
5107
+ } catch (error) {
5108
+ log_default.debug(`Failed to read version cache: ${error}`);
5109
+ return {
5110
+ last_reset_timestamp: Date.now(),
5111
+ packages: {}
5112
+ };
5113
+ }
5114
+ }
5115
+ function setCachedPackageInfo(packageName, version, info) {
5116
+ try {
5117
+ const cache = getVersionCache();
5118
+ if (!cache.packages[packageName]) {
5119
+ cache.packages[packageName] = {};
5120
+ }
5121
+ cache.packages[packageName][version] = info;
5122
+ getConfig().set("version_cache", cache);
5123
+ } catch (error) {
5124
+ log_default.debug(`Failed to cache package info: ${error}`);
5125
+ }
5126
+ }
5127
+ function getCachedPackageInfo(packageName, version) {
5128
+ try {
5129
+ const cache = getVersionCache();
5130
+ return cache.packages[packageName]?.[version];
5131
+ } catch (error) {
5132
+ log_default.debug(`Failed to get cached package info: ${error}`);
5133
+ return void 0;
5134
+ }
5135
+ }
5136
+ async function fetchCachedPackageInfo(packageName, version) {
5137
+ const cacheKey = version || "latest";
5138
+ let cachedInfo = getCachedPackageInfo(packageName, cacheKey);
5139
+ if (cachedInfo) {
5140
+ return cachedInfo;
5141
+ }
5142
+ const packageInfo = await packageJsonLib__default.default(packageName, {
5143
+ version,
5144
+ fullMetadata: true
5145
+ });
5146
+ const info = {
5147
+ version: packageInfo.version,
5148
+ deprecated: packageInfo.deprecated,
5149
+ fetched_at: (/* @__PURE__ */ new Date()).toISOString()
5150
+ };
5151
+ setCachedPackageInfo(packageName, cacheKey, info);
5152
+ return info;
5153
+ }
5154
+ async function checkForUpdates({
5155
+ packageName,
5156
+ currentVersion
5157
+ }) {
5158
+ try {
5159
+ const latestPackageInfo = await fetchCachedPackageInfo(packageName);
5160
+ const latestVersion = latestPackageInfo.version;
5161
+ const hasUpdate = semver__default.default.gt(latestVersion, currentVersion);
5162
+ let currentPackageInfo;
5163
+ try {
5164
+ currentPackageInfo = await fetchCachedPackageInfo(
5165
+ packageName,
5166
+ currentVersion
5167
+ );
5168
+ } catch (error) {
5169
+ if (!(error instanceof packageJsonLib.VersionNotFoundError)) {
5170
+ log_default.debug(`Failed to check deprecation for current version: ${error}`);
5171
+ }
5172
+ currentPackageInfo = latestPackageInfo;
5173
+ }
5174
+ const isDeprecated = Boolean(currentPackageInfo.deprecated);
5175
+ const deprecationMessage = isDeprecated ? String(currentPackageInfo.deprecated) : void 0;
5176
+ return {
5177
+ hasUpdate,
5178
+ latestVersion,
5179
+ currentVersion,
5180
+ isDeprecated,
5181
+ deprecationMessage
5182
+ };
5183
+ } catch (error) {
5184
+ log_default.debug(`Failed to check for updates: ${error}`);
5185
+ return {
5186
+ hasUpdate: false,
5187
+ currentVersion,
5188
+ isDeprecated: false
5189
+ };
5190
+ }
5191
+ }
5192
+ var BRAILLE_BLANK = "\u2800";
5193
+ var LIGHTNING_INTERVAL_MILLISECONDS = 140;
5194
+ var boltRows = [
5195
+ "\u2800\u2800\u2880\u28FE\u2800\u2800\u2800\u2800",
5196
+ "\u2800\u2800\u28E0\u28FF\u28FF\u2800\u2800\u2800",
5197
+ "\u2800\u28FC\u28FF\u28FF\u28FF\u28C0\u28C0\u2840",
5198
+ "\u2808\u2809\u2809\u28FF\u28FF\u28FF\u285F\u2800",
5199
+ "\u2800\u2800\u2800\u28FF\u28FF\u280B\u2800\u2800",
5200
+ "\u2800\u2800\u2800\u287F\u2801\u2800\u2800\u2800"
5201
+ ];
5202
+ var boltFillOrder = boltRows.flatMap(
5203
+ (row, rowIndex) => [...row].flatMap(
5204
+ (cell, columnIndex) => cell === BRAILLE_BLANK ? [] : rowIndex * row.length + columnIndex
5205
+ )
5206
+ );
5207
+ var fillStages = [
5208
+ ...Array.from({ length: boltFillOrder.length + 1 }, (_, index) => index),
5209
+ boltFillOrder.length,
5210
+ 0
5211
+ ];
5212
+ var boltFillRanks = new Map(
5213
+ boltFillOrder.map((cellIndex, fillIndex) => [cellIndex, fillIndex])
5214
+ );
5215
+ var STATUS_ROW_INDEX = Math.floor(boltRows.length / 2);
5216
+ function formatPhase({ label, detail }) {
5217
+ return detail ? `${chalk3__default.default.bold(label)} ${chalk3__default.default.dim(detail)}` : chalk3__default.default.bold(label);
5218
+ }
5219
+ function formatLoaderFrame({
5220
+ phase,
5221
+ fillStage
5222
+ }) {
5223
+ return boltRows.map((row, rowIndex) => {
5224
+ const bolt = [...row].map((cell, columnIndex) => {
5225
+ if (cell === BRAILLE_BLANK) return cell;
5226
+ const cellIndex = rowIndex * row.length + columnIndex;
5227
+ const fillRank = boltFillRanks.get(cellIndex);
5228
+ const isFilled = fillRank !== void 0 && fillRank < fillStage;
5229
+ return isFilled ? chalk3__default.default.bold.yellow(cell) : chalk3__default.default.dim.yellow(cell);
5230
+ }).join("");
5231
+ const status = rowIndex === STATUS_ROW_INDEX ? ` ${formatPhase(phase)}` : "";
5232
+ return `${bolt}${status}`;
5233
+ }).join("\n");
5234
+ }
5235
+ async function runWithSetupLoader({
5236
+ promise,
5237
+ ...phase
5238
+ }) {
5239
+ const startedAt = Date.now();
5240
+ let fillFrameIndex = 0;
5241
+ const loader = ora__default.default({
5242
+ isEnabled: process.stderr.isTTY === true,
5243
+ spinner: { interval: 80, frames: [""] },
5244
+ text: formatLoaderFrame({
5245
+ phase,
5246
+ fillStage: fillStages[fillFrameIndex]
5247
+ })
5248
+ }).start();
5249
+ const animationTimer = setInterval(() => {
5250
+ fillFrameIndex = (fillFrameIndex + 1) % fillStages.length;
5251
+ loader.text = formatLoaderFrame({
5252
+ phase,
5253
+ fillStage: fillStages[fillFrameIndex]
4599
5254
  });
5255
+ }, LIGHTNING_INTERVAL_MILLISECONDS);
5256
+ animationTimer.unref?.();
5257
+ try {
5258
+ const result = await promise;
5259
+ clearInterval(animationTimer);
5260
+ const elapsedSeconds = ((Date.now() - startedAt) / 1e3).toFixed(1);
5261
+ loader.succeed(`${formatPhase(phase)} ${chalk3__default.default.dim(`${elapsedSeconds}s`)}`);
5262
+ return result;
5263
+ } catch (error) {
5264
+ clearInterval(animationTimer);
5265
+ const elapsedSeconds = ((Date.now() - startedAt) / 1e3).toFixed(1);
5266
+ loader.fail(`${formatPhase(phase)} ${chalk3__default.default.dim(`${elapsedSeconds}s`)}`);
5267
+ throw error;
5268
+ }
5269
+ }
5270
+ function isRecord(value) {
5271
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5272
+ }
5273
+ function readPackageJson({
5274
+ directory
5275
+ }) {
5276
+ try {
5277
+ const manifest = JSON.parse(
5278
+ fs.readFileSync(path.join(directory, "package.json"), "utf8")
5279
+ );
5280
+ return isRecord(manifest) ? manifest : void 0;
5281
+ } catch {
5282
+ return void 0;
5283
+ }
5284
+ }
5285
+ var SetupOptionSchema = zod.z.object({
5286
+ label: zod.z.string(),
5287
+ value: zod.z.string()
5288
+ });
5289
+ var SetupOptionsSchema = zod.z.array(SetupOptionSchema).min(1);
5290
+ var SetupDecisionSchema = zod.z.object({
5291
+ message: zod.z.string(),
5292
+ options: SetupOptionsSchema,
5293
+ answer: zod.z.string()
5294
+ });
5295
+ var SetupInputSchema = zod.z.object({
5296
+ message: zod.z.string(),
5297
+ answer: zod.z.string()
5298
+ });
5299
+ var setupDecisionResolver = zapierSdk.defineResolver({
5300
+ requireParameters: ["message", "options"],
5301
+ listItems: ({ input }) => ({ data: input.options }),
5302
+ prompt: ({ items, input }) => ({
5303
+ type: "list",
5304
+ message: input.message,
5305
+ choices: items
5306
+ }),
5307
+ validate: ({ input, value }) => {
5308
+ if (typeof value !== "string") return "Choose an available option.";
5309
+ return input.options.some((option) => option.value === value) || "Choose one of the available options.";
5310
+ }
5311
+ });
5312
+ var setupInputResolver = zapierSdk.defineResolver({
5313
+ type: "static",
5314
+ inputType: "text",
5315
+ requireParameters: ["message"]
5316
+ });
5317
+ var resolveSetupDecisionPlugin = zapierSdk.defineMethod({
5318
+ name: "resolveSetupDecision",
5319
+ description: "Resolve one setup wizard decision.",
5320
+ inputSchema: SetupDecisionSchema,
5321
+ resolvers: { answer: setupDecisionResolver },
5322
+ run: ({ input }) => input
5323
+ });
5324
+ var resolveSetupInputPlugin = zapierSdk.defineMethod({
5325
+ name: "resolveSetupInput",
5326
+ description: "Resolve one setup wizard text input.",
5327
+ inputSchema: SetupInputSchema,
5328
+ resolvers: { answer: setupInputResolver },
5329
+ run: ({ input }) => input
5330
+ });
5331
+ function createSetupController() {
5332
+ const setupResolutionSdk = zapierSdk.createSdk(
5333
+ zapierSdk.definePlugin({
5334
+ name: "setup-resolution",
5335
+ exports: [
5336
+ resolveSetupDecisionPlugin,
5337
+ resolveSetupInputPlugin,
5338
+ zapierSdk.getRegistryPlugin
5339
+ ]
5340
+ })
5341
+ );
5342
+ return zapierSdk.createController(setupResolutionSdk);
5343
+ }
5344
+ async function resolveWithCancellation({
5345
+ run
5346
+ }) {
5347
+ try {
5348
+ return await run();
5349
+ } catch (error) {
5350
+ if (zapierSdk.isCoreCancelledSignal(error)) {
5351
+ throw new ZapierCliUserCancellationError();
5352
+ }
5353
+ throw error;
5354
+ }
5355
+ }
5356
+ async function resolveSetupDecision({
5357
+ answer,
5358
+ controller,
5359
+ message,
5360
+ options
5361
+ }) {
5362
+ const parsedOptions = SetupOptionsSchema.parse(options);
5363
+ const resolved = await resolveWithCancellation({
5364
+ run: () => controller.resolve({
5365
+ method: "resolveSetupDecision",
5366
+ input: { message, options: parsedOptions },
5367
+ answer,
5368
+ interactive: true
5369
+ })
5370
+ });
5371
+ return SetupDecisionSchema.parse(resolved).answer;
5372
+ }
5373
+ async function resolveSetupConfirm({
5374
+ answer,
5375
+ controller,
5376
+ defaultValue,
5377
+ message
5378
+ }) {
5379
+ const values = defaultValue ? [true, false] : [false, true];
5380
+ const resolved = await resolveSetupDecision({
5381
+ answer,
5382
+ controller,
5383
+ message,
5384
+ options: values.map((value) => ({
5385
+ label: value ? "Yes" : "No",
5386
+ value: String(value)
5387
+ }))
5388
+ });
5389
+ return resolved === "true";
5390
+ }
5391
+ async function resolveSetupInput({
5392
+ answer,
5393
+ controller,
5394
+ message
5395
+ }) {
5396
+ const resolved = await resolveWithCancellation({
5397
+ run: () => controller.resolve({
5398
+ method: "resolveSetupInput",
5399
+ input: { message },
5400
+ answer: ({ result, state }) => answer({
5401
+ state,
5402
+ result: {
5403
+ ...result,
5404
+ question: { ...result.question, message }
5405
+ }
5406
+ }),
5407
+ interactive: true
5408
+ })
5409
+ });
5410
+ return SetupInputSchema.parse(resolved).answer.trim();
5411
+ }
5412
+ async function resolveSetupSelect({
5413
+ answer,
5414
+ controller,
5415
+ choices,
5416
+ message
5417
+ }) {
5418
+ const resolved = await resolveSetupDecision({
5419
+ answer,
5420
+ controller,
5421
+ message,
5422
+ options: choices
5423
+ });
5424
+ const selected = choices.find(({ value }) => value === resolved);
5425
+ if (!selected) {
5426
+ throw new Error("Resolved setup selection is not an available choice.");
5427
+ }
5428
+ return selected.value;
5429
+ }
5430
+
5431
+ // src/plugins/setup/dependencies.ts
5432
+ var REQUIRED_PACKAGES = [
5433
+ { name: "@zapier/zapier-sdk", dev: false, checkForUpdates: true },
5434
+ { name: "@zapier/zapier-sdk-cli", dev: true, checkForUpdates: true },
5435
+ {
5436
+ name: "@types/node",
5437
+ dev: true,
5438
+ checkForUpdates: false,
5439
+ typescriptOnly: true
5440
+ },
5441
+ {
5442
+ name: "typescript",
5443
+ dev: true,
5444
+ checkForUpdates: false,
5445
+ typescriptOnly: true
5446
+ },
5447
+ { name: "tsx", dev: true, checkForUpdates: false, typescriptOnly: true }
5448
+ ];
5449
+ function getInstallCommand({
5450
+ packageManager,
5451
+ packages,
5452
+ dev = false
5453
+ }) {
5454
+ const verb = packageManager === "npm" ? "install" : "add";
5455
+ const devFlag = packageManager === "bun" ? "-d" : "-D";
5456
+ return {
5457
+ command: packageManager,
5458
+ args: [verb, ...dev ? [devFlag] : [], ...packages]
5459
+ };
5460
+ }
5461
+ async function executeInstall(context, command) {
5462
+ try {
5463
+ await context.runCommand({ ...command, cwd: context.cwd });
5464
+ } catch (error) {
5465
+ const message = error instanceof Error ? error.message : String(error);
5466
+ if (message.includes("EPERM") && message.includes(".npm/_cacache")) {
5467
+ console.error(
5468
+ "This EPERM usually means the command sandbox blocked npm cache writes; it does not usually mean your file permissions are broken."
5469
+ );
5470
+ }
5471
+ throw error;
5472
+ }
5473
+ }
5474
+ function getDeclaredPackageNames(cwd) {
5475
+ const manifest = readPackageJson({ directory: cwd });
5476
+ if (!manifest) return /* @__PURE__ */ new Set();
5477
+ const names = /* @__PURE__ */ new Set();
5478
+ for (const section of ["dependencies", "devDependencies"]) {
5479
+ const dependencies = manifest[section];
5480
+ if (!isRecord(dependencies)) continue;
5481
+ for (const name of Object.keys(dependencies)) names.add(name);
5482
+ }
5483
+ return names;
5484
+ }
5485
+ function getInstalledPackageVersion({
5486
+ cwd,
5487
+ packageName
5488
+ }) {
5489
+ let directory = cwd;
5490
+ while (true) {
5491
+ const manifest = readPackageJson({
5492
+ directory: path.join(directory, "node_modules", ...packageName.split("/"))
5493
+ });
5494
+ if (manifest?.name === packageName && typeof manifest.version === "string") {
5495
+ return manifest.version;
5496
+ }
5497
+ const parent = path.dirname(directory);
5498
+ if (parent === directory) return void 0;
5499
+ directory = parent;
5500
+ }
5501
+ }
5502
+ async function installPackages({
5503
+ context,
5504
+ packages
5505
+ }) {
5506
+ const runtimePackages = packages.filter(({ dependency }) => !dependency.dev).map(({ dependency }) => dependency.name);
5507
+ if (runtimePackages.length > 0) {
5508
+ await executeInstall(
5509
+ context,
5510
+ getInstallCommand({
5511
+ packageManager: context.packageManager,
5512
+ packages: runtimePackages
5513
+ })
5514
+ );
5515
+ }
5516
+ const developmentPackages = packages.filter(({ dependency }) => dependency.dev).map(({ dependency }) => dependency.name);
5517
+ if (developmentPackages.length > 0) {
5518
+ await executeInstall(
5519
+ context,
5520
+ getInstallCommand({
5521
+ packageManager: context.packageManager,
5522
+ packages: developmentPackages,
5523
+ dev: true
5524
+ })
5525
+ );
5526
+ }
5527
+ }
5528
+ async function offerMissingPackageInstall({
5529
+ context,
5530
+ packages
5531
+ }) {
5532
+ if (packages.length === 0) return;
5533
+ const shouldInstall = await resolveSetupConfirm({
5534
+ answer: context.createAnswer(),
5535
+ controller: context.setupController,
5536
+ message: `These packages are required to continue. Install them now: ${packages.map(({ dependency }) => dependency.name).join(", ")}?`,
5537
+ defaultValue: true
5538
+ });
5539
+ if (!shouldInstall) {
5540
+ console.log(
5541
+ "The Zapier SDK packages are required to continue. Setup cancelled without installing dependencies."
5542
+ );
5543
+ throw new ZapierCliUserCancellationError(
5544
+ "Required Zapier SDK packages were not installed"
5545
+ );
5546
+ }
5547
+ await installPackages({ context, packages });
5548
+ }
5549
+ async function offerPackageUpdate({
5550
+ context,
5551
+ packageState
5552
+ }) {
5553
+ const { currentVersion, dependency } = packageState;
5554
+ if (!currentVersion || !dependency.checkForUpdates) return;
5555
+ const update = await runWithSetupLoader({
5556
+ promise: context.checkForUpdates({
5557
+ packageName: dependency.name,
5558
+ currentVersion
5559
+ }),
5560
+ label: "Checking for updates",
5561
+ detail: dependency.name
5562
+ });
5563
+ if (!update.hasUpdate || !update.latestVersion) return;
5564
+ const shouldUpdate = await resolveSetupConfirm({
5565
+ answer: context.createAnswer(),
5566
+ controller: context.setupController,
5567
+ message: `Update ${dependency.name} from ${currentVersion} to ${update.latestVersion}?`,
5568
+ defaultValue: true
5569
+ });
5570
+ if (!shouldUpdate) return;
5571
+ await executeInstall(
5572
+ context,
5573
+ getInstallCommand({
5574
+ packageManager: context.packageManager,
5575
+ packages: [`${dependency.name}@${update.latestVersion}`],
5576
+ dev: dependency.dev
5577
+ })
5578
+ );
5579
+ }
5580
+ async function prepareDependencies(context) {
5581
+ const declaredPackageNames = getDeclaredPackageNames(context.cwd);
5582
+ const requiredPackages = REQUIRED_PACKAGES.filter(
5583
+ ({ typescriptOnly }) => !typescriptOnly || context.projectLanguage === "typescript"
5584
+ );
5585
+ const packages = requiredPackages.map((dependency) => ({
5586
+ dependency,
5587
+ currentVersion: declaredPackageNames.has(dependency.name) ? getInstalledPackageVersion({
5588
+ cwd: context.cwd,
5589
+ packageName: dependency.name
5590
+ }) : void 0
5591
+ }));
5592
+ await offerMissingPackageInstall({
5593
+ context,
5594
+ packages: packages.filter(
5595
+ ({ dependency }) => !declaredPackageNames.has(dependency.name)
5596
+ )
5597
+ });
5598
+ for (const packageState of packages) {
5599
+ await offerPackageUpdate({ context, packageState });
5600
+ }
5601
+ }
5602
+
5603
+ // src/plugins/setup/package-commands.ts
5604
+ function createLocalPackageCommand({
5605
+ packageManager,
5606
+ binary,
5607
+ args = []
5608
+ }) {
5609
+ const runner = {
5610
+ npm: { command: "npx", args: ["--no-install"] },
5611
+ pnpm: { command: "pnpm", args: ["exec"] },
5612
+ yarn: { command: "yarn", args: ["exec"] },
5613
+ bun: { command: "bunx", args: ["--no-install"] }
5614
+ };
5615
+ return {
5616
+ command: runner[packageManager].command,
5617
+ args: [...runner[packageManager].args, binary, ...args]
5618
+ };
5619
+ }
5620
+ function createPackageRunnerCommand({
5621
+ packageManager,
5622
+ packageName,
5623
+ args = []
5624
+ }) {
5625
+ const runner = {
5626
+ npm: { command: "npx", args: ["--yes"] },
5627
+ pnpm: { command: "pnpm", args: ["dlx"] },
5628
+ yarn: { command: "yarn", args: ["dlx"] },
5629
+ bun: { command: "bunx", args: [] }
5630
+ };
5631
+ return {
5632
+ command: runner[packageManager].command,
5633
+ args: [...runner[packageManager].args, packageName, ...args]
5634
+ };
5635
+ }
5636
+ function formatPackageCommand({
5637
+ command,
5638
+ args
5639
+ }) {
5640
+ return [command, ...args].join(" ");
5641
+ }
5642
+
5643
+ // src/plugins/setup/project.ts
5644
+ var COMMAND_MAX_BUFFER_BYTES = 10 * 1024 * 1024;
5645
+ var PROJECT_INIT_COMMANDS = {
5646
+ npm: { command: "npm", args: ["init", "-y"] },
5647
+ pnpm: { command: "pnpm", args: ["init"] },
5648
+ yarn: { command: "yarn", args: ["init", "-y"] },
5649
+ bun: { command: "bun", args: ["init", "-y"] }
5650
+ };
5651
+ var CapturedCommandError = class extends Error {
5652
+ constructor(error, stdout, stderr) {
5653
+ super(error.message);
5654
+ this.stdout = stdout;
5655
+ this.stderr = stderr;
5656
+ }
5657
+ };
5658
+ function commandError({
5659
+ command,
5660
+ code,
5661
+ signal
5662
+ }) {
5663
+ return new Error(
5664
+ signal ? `${command} was terminated by ${signal}` : `${command} exited with code ${code ?? "unknown"}`
5665
+ );
5666
+ }
5667
+ function executeCapturedCommand({
5668
+ command,
5669
+ args,
5670
+ cwd,
5671
+ input
5672
+ }) {
5673
+ return new Promise((resolve4, reject) => {
5674
+ const child = crossSpawn__default.default(command, args, {
5675
+ cwd,
5676
+ shell: false,
5677
+ stdio: ["pipe", "pipe", "pipe"]
5678
+ });
5679
+ let stdout = "";
5680
+ let stderr = "";
5681
+ const append = ({
5682
+ chunk,
5683
+ stream
5684
+ }) => {
5685
+ if (stream === "stdout") stdout += chunk.toString();
5686
+ else stderr += chunk.toString();
5687
+ if (Buffer.byteLength(stdout) + Buffer.byteLength(stderr) > COMMAND_MAX_BUFFER_BYTES) {
5688
+ child.kill();
5689
+ reject(new Error("Command output exceeded the capture limit."));
5690
+ }
5691
+ };
5692
+ child.stdout?.on(
5693
+ "data",
5694
+ (chunk) => append({ chunk, stream: "stdout" })
5695
+ );
5696
+ child.stderr?.on(
5697
+ "data",
5698
+ (chunk) => append({ chunk, stream: "stderr" })
5699
+ );
5700
+ child.once("error", reject);
5701
+ child.once("close", (code, signal) => {
5702
+ if (code === 0) {
5703
+ resolve4(stdout.trim());
5704
+ return;
5705
+ }
5706
+ reject(
5707
+ new CapturedCommandError(
5708
+ commandError({ command, code, signal }),
5709
+ stdout,
5710
+ stderr
5711
+ )
5712
+ );
5713
+ });
5714
+ child.stdin?.end(input);
5715
+ });
5716
+ }
5717
+ function executeStreamingCommand({
5718
+ command,
5719
+ args,
5720
+ cwd,
5721
+ input
5722
+ }) {
5723
+ return new Promise((resolve4, reject) => {
5724
+ const child = crossSpawn__default.default(command, args, {
5725
+ cwd,
5726
+ shell: false,
5727
+ stdio: [input === void 0 ? "inherit" : "pipe", "inherit", "inherit"]
5728
+ });
5729
+ child.once("error", reject);
5730
+ child.once("close", (code, signal) => {
5731
+ if (code === 0) {
5732
+ resolve4("");
5733
+ return;
5734
+ }
5735
+ reject(commandError({ command, code, signal }));
5736
+ });
5737
+ if (input !== void 0) child.stdin?.end(input);
5738
+ });
5739
+ }
5740
+ async function runCommand({
5741
+ command,
5742
+ args = [],
5743
+ cwd,
5744
+ capture = true,
5745
+ input
5746
+ }) {
5747
+ const commandLabel = `$ ${command} ${args.join(" ")}`.trim();
5748
+ const execute = capture ? executeCapturedCommand({ command, args, cwd, input }) : executeStreamingCommand({ command, args, cwd, input });
5749
+ try {
5750
+ if (capture) {
5751
+ return await runWithSetupLoader({
5752
+ promise: execute,
5753
+ label: "Running command",
5754
+ detail: commandLabel
5755
+ });
5756
+ }
5757
+ console.log(chalk3__default.default.dim(commandLabel));
5758
+ return await execute;
5759
+ } catch (error) {
5760
+ const message = error instanceof Error ? error.message : String(error);
5761
+ if (error instanceof CapturedCommandError) {
5762
+ if (error.stdout) process.stdout.write(error.stdout);
5763
+ if (error.stderr) process.stderr.write(error.stderr);
5764
+ if (!error.stdout && !error.stderr) console.error(message);
5765
+ } else {
5766
+ console.error(message);
5767
+ }
5768
+ throw new ZapierCliExitError(message);
5769
+ }
5770
+ }
5771
+ async function chooseDirectory(context) {
5772
+ const useCurrentDirectory = await resolveSetupConfirm({
5773
+ answer: context.createAnswer(),
5774
+ controller: context.setupController,
5775
+ message: `Set up the Zapier SDK in ${context.cwd}?`,
5776
+ defaultValue: true
5777
+ });
5778
+ if (useCurrentDirectory) return;
5779
+ const setupCommand = formatPackageCommand(
5780
+ createLocalPackageCommand({
5781
+ packageManager: context.packageManager,
5782
+ binary: "zapier-sdk",
5783
+ args: ["setup"]
5784
+ })
5785
+ );
5786
+ console.log(
5787
+ `Setup cancelled. Navigate to the intended directory and run \`${setupCommand}\` again.`
5788
+ );
5789
+ throw new ZapierCliUserCancellationError("Setup cancelled by user");
5790
+ }
5791
+ async function ensureSupportedNode(context) {
5792
+ let version;
5793
+ try {
5794
+ version = await context.runCommand({
5795
+ command: "node",
5796
+ args: ["-v"],
5797
+ cwd: context.cwd,
5798
+ capture: true
5799
+ });
5800
+ } catch {
5801
+ console.error(
5802
+ "Node.js 20 or higher is required. Install it from https://nodejs.org, then run setup again."
5803
+ );
5804
+ throw new ZapierCliExitError(
5805
+ "Setup could not continue without Node.js 20 or higher."
5806
+ );
5807
+ }
5808
+ const major = Number(version.replace(/^v/, "").split(".")[0]);
5809
+ if (!Number.isFinite(major) || major < 20) {
5810
+ console.error(
5811
+ `Node.js 20 or higher is required; found ${version}. Upgrade Node.js, then run setup again.`
5812
+ );
5813
+ throw new ZapierCliExitError(
5814
+ "Setup could not continue without Node.js 20 or higher."
5815
+ );
5816
+ }
5817
+ console.log(`Node.js ${version} is ready.`);
5818
+ }
5819
+ function detectProjectLanguage({
5820
+ cwd,
5821
+ hasExistingProject
5822
+ }) {
5823
+ if (!hasExistingProject || fs.existsSync(path.join(cwd, "tsconfig.json"))) {
5824
+ return "typescript";
5825
+ }
5826
+ const manifest = readPackageJson({ directory: cwd });
5827
+ const hasTypeScript = [
5828
+ manifest?.dependencies,
5829
+ manifest?.devDependencies
5830
+ ].some(
5831
+ (dependencies) => isRecord(dependencies) && "typescript" in dependencies
5832
+ );
5833
+ return hasTypeScript ? "typescript" : "javascript";
5834
+ }
5835
+ async function prepareProject(context) {
5836
+ context.packageManager = detectPackageManager(context.cwd).name;
5837
+ console.log(`Using ${context.packageManager} for dependency installs.`);
5838
+ const hasExistingProject = fs.existsSync(path.join(context.cwd, "package.json"));
5839
+ context.projectLanguage = detectProjectLanguage({
5840
+ cwd: context.cwd,
5841
+ hasExistingProject
5842
+ });
5843
+ if (hasExistingProject) {
5844
+ console.log("Found package.json; using this project as-is.");
5845
+ } else {
5846
+ await context.runCommand({
5847
+ ...PROJECT_INIT_COMMANDS[context.packageManager],
5848
+ cwd: context.cwd
5849
+ });
5850
+ }
5851
+ await prepareDependencies(context);
5852
+ }
5853
+
5854
+ // src/plugins/setup/context.ts
5855
+ function createWizardContext({
5856
+ imports
5857
+ }) {
5858
+ return {
5859
+ cwd: process.cwd(),
5860
+ imports,
5861
+ createAnswer: () => createCliAnswer({ mode: "closed-list" }),
5862
+ setupController: createSetupController(),
5863
+ checkForUpdates,
5864
+ openUrl: async (url) => {
5865
+ await open__default.default(url);
5866
+ },
5867
+ runCommand,
5868
+ packageManager: detectPackageManager(process.cwd()).name,
5869
+ projectLanguage: "typescript"
5870
+ };
5871
+ }
5872
+ var SetupSchema = zod.z.object({}).describe("Set up the Zapier SDK in an existing or new project");
5873
+ function printAuthCommand({
5874
+ context,
5875
+ flow,
5876
+ headless
5877
+ }) {
5878
+ const command = createLocalPackageCommand({
5879
+ packageManager: context.packageManager,
5880
+ binary: "zapier-sdk",
5881
+ args: [flow, ...headless ? ["--headless"] : []]
5882
+ });
5883
+ console.log(`$ ${formatPackageCommand(command)}`);
5884
+ if (headless) {
5885
+ console.log(
5886
+ "Open the printed URL in another browser, then paste the final OAuth callback URL when prompted."
5887
+ );
5888
+ }
5889
+ }
5890
+ function isCredentialWriteError(error) {
5891
+ const code = typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "";
5892
+ if (/^(eacces|eperm)$/i.test(code)) return true;
5893
+ const message = error instanceof Error ? error.message : String(error);
5894
+ return /permission|sandbox|eacces|eperm/i.test(message);
5895
+ }
5896
+ async function authenticate(context) {
5897
+ const activeProfile = await runWithSetupLoader({
5898
+ promise: context.imports.getProfile({}).then(({ data }) => data).catch((error) => {
5899
+ if (zapierSdk.isZapierAuthenticationError(error)) return void 0;
5900
+ throw error;
5901
+ }),
5902
+ label: "Checking Zapier authentication"
5903
+ });
5904
+ if (activeProfile) {
5905
+ const shouldLogout = await resolveSetupConfirm({
5906
+ answer: context.createAnswer(),
5907
+ controller: context.setupController,
5908
+ message: `You are already logged in as "${activeProfile.email}".
5909
+ Logging out will delete these credentials and may interrupt other Zapier SDK or CLI sessions using them.
5910
+ Log out and use a different account?`,
5911
+ defaultValue: false
5912
+ });
5913
+ if (!shouldLogout) {
5914
+ context.accountEmail = activeProfile.email;
5915
+ console.log(`Continuing as ${activeProfile.email}.`);
5916
+ return;
5917
+ }
5918
+ const logoutCommand = createLocalPackageCommand({
5919
+ packageManager: context.packageManager,
5920
+ binary: "zapier-sdk",
5921
+ args: ["logout"]
5922
+ });
5923
+ console.log(`$ ${formatPackageCommand(logoutCommand)}`);
5924
+ await context.imports.logout({});
5925
+ }
5926
+ const flow = await resolveSetupSelect({
5927
+ answer: context.createAnswer(),
5928
+ controller: context.setupController,
5929
+ message: "Zapier account:",
5930
+ choices: [
5931
+ { label: "Log in to an existing account", value: "login" },
5932
+ { label: "Create a new Zapier account", value: "signup" }
5933
+ ]
5934
+ });
5935
+ const environment = await resolveSetupSelect({
5936
+ answer: context.createAnswer(),
5937
+ controller: context.setupController,
5938
+ message: "Environment:",
5939
+ choices: [
5940
+ { label: "Local machine with a browser", value: "local" },
5941
+ { label: "Remote or headless", value: "headless" }
5942
+ ]
5943
+ });
5944
+ const headless = environment === "headless";
5945
+ const runAuth = flow === "login" ? context.imports.login : context.imports.signup;
5946
+ printAuthCommand({ context, flow, headless });
5947
+ try {
5948
+ await runAuth({ headless });
5949
+ } catch (error) {
5950
+ if (isCredentialWriteError(error)) {
5951
+ console.error(
5952
+ "Authentication could not write credentials. A permissions or sandbox restriction may be blocking disk access."
5953
+ );
5954
+ }
5955
+ throw error;
5956
+ }
5957
+ const { data: profile } = await runWithSetupLoader({
5958
+ promise: context.imports.getProfile({}),
5959
+ label: "Confirming Zapier account"
5960
+ });
5961
+ context.accountEmail = profile.email;
5962
+ console.log(`Authenticated as ${profile.email}.`);
5963
+ }
5964
+ var agentLabels = {
5965
+ claude: "Claude Code",
5966
+ codex: "Codex",
5967
+ cursor: "Cursor",
5968
+ "vscode-copilot": "VS Code Copilot"
5969
+ };
5970
+ function buildAgentPrompt({ context }) {
5971
+ const listConnectionsCommand = formatPackageCommand(
5972
+ createLocalPackageCommand({
5973
+ packageManager: context.packageManager,
5974
+ binary: "zapier-sdk",
5975
+ args: ["list-connections", "--owner", "me", "--json"]
5976
+ })
5977
+ );
5978
+ const listActionsCommand = formatPackageCommand(
5979
+ createLocalPackageCommand({
5980
+ packageManager: context.packageManager,
5981
+ binary: "zapier-sdk",
5982
+ args: ["list-actions", "APP_KEY"]
5983
+ })
5984
+ );
5985
+ return `Start by running this command to discover my active connected apps outside of your sandbox:
5986
+
5987
+ ${listConnectionsCommand}
5988
+
5989
+ Using the connected apps returned by that command:
5990
+
5991
+ - Pick 1-3 apps and show commands I can use to explore their actions, such as: ${listActionsCommand}
5992
+ - Do not run those list-actions commands.
5993
+ - Suggest 3 specific ideas based on my connected apps. Each idea should read from one app, optionally process data, and write to another.
5994
+ - Do not suggest event-driven workflows.
5995
+ - Keep each idea to one sentence. Example: "pull in-progress Jira issues and DM yourself a summary on Slack".
5996
+
5997
+ Do not inspect files or modify the project. If fewer than two distinct apps are listed, explain that cross-app ideas require another active connection instead of inventing apps.`;
5998
+ }
5999
+ function printAgentPrompt({
6000
+ context,
6001
+ message
6002
+ }) {
6003
+ console.log();
6004
+ console.log(chalk3__default.default.bgYellow.black.bold(message));
6005
+ console.log();
6006
+ console.log(buildAgentPrompt({ context }));
6007
+ }
6008
+ async function openAgentHandoff(context) {
6009
+ const agent = await resolveSetupSelect({
6010
+ answer: context.createAnswer(),
6011
+ controller: context.setupController,
6012
+ message: "Want to open your agent and have it give you suggestions to start?",
6013
+ choices: [
6014
+ { label: "No", value: "none" },
6015
+ { label: "Claude Code", value: "claude" },
6016
+ { label: "Cursor", value: "cursor" },
6017
+ { label: "Codex", value: "codex" },
6018
+ { label: "VS Code Copilot", value: "vscode-copilot" },
6019
+ { label: "Other", value: "other" }
6020
+ ]
6021
+ });
6022
+ if (agent === "none") return;
6023
+ if (agent === "other") {
6024
+ printAgentPrompt({
6025
+ context,
6026
+ message: "Paste this prompt into your AI agent:"
6027
+ });
6028
+ return;
6029
+ }
6030
+ const prompt = buildAgentPrompt({ context });
6031
+ const encodedPrompt = encodeURIComponent(prompt);
6032
+ const encodedPath = encodeURIComponent(context.cwd);
6033
+ try {
6034
+ switch (agent) {
6035
+ case "claude":
6036
+ await context.openUrl(
6037
+ `claude://code/new?q=${encodedPrompt}&folder=${encodedPath}`
6038
+ );
6039
+ break;
6040
+ case "codex":
6041
+ await context.openUrl(
6042
+ `codex://threads/new?prompt=${encodedPrompt}&path=${encodedPath}`
6043
+ );
6044
+ break;
6045
+ case "cursor":
6046
+ await context.runCommand({
6047
+ command: "cursor",
6048
+ args: ["."],
6049
+ cwd: context.cwd,
6050
+ capture: true
6051
+ });
6052
+ console.log(`Cursor opened in ${context.cwd}.`);
6053
+ break;
6054
+ case "vscode-copilot":
6055
+ await context.runCommand({
6056
+ command: "code",
6057
+ args: ["chat", "--mode", "agent", "-"],
6058
+ cwd: context.cwd,
6059
+ input: prompt
6060
+ });
6061
+ break;
6062
+ default: {
6063
+ const unsupportedAgent = agent;
6064
+ throw new Error(`Unsupported agent: ${unsupportedAgent}`);
6065
+ }
6066
+ }
6067
+ } catch {
6068
+ console.warn(
6069
+ `Could not open ${agentLabels[agent]}. Open it manually to continue.`
6070
+ );
6071
+ }
6072
+ printAgentPrompt({
6073
+ context,
6074
+ message: "If it didn't load correctly, paste this prompt into your agent:"
6075
+ });
6076
+ }
6077
+ var CONNECTIONS_URL = "https://zapier.com/app/assets/connections";
6078
+ var CONNECTION_DISPLAY_LIMIT = 10;
6079
+ async function ensureConnectionsAvailable(context) {
6080
+ const page = await runWithSetupLoader({
6081
+ promise: context.imports.listConnections({
6082
+ owner: "me",
6083
+ maxItems: CONNECTION_DISPLAY_LIMIT
6084
+ }),
6085
+ label: "Loading app connections"
6086
+ });
6087
+ if (page.data.length === 0) {
6088
+ console.log(
6089
+ `No active connections found. Connect or reconnect an app at ${CONNECTIONS_URL}, then come back and run setup again.`
6090
+ );
6091
+ throw new ZapierCliExitError(
6092
+ "Setup stopped before completion because no active connections are available."
6093
+ );
6094
+ }
6095
+ const table = new Table__default.default({
6096
+ head: ["App", "Connection"],
6097
+ style: { compact: true }
6098
+ });
6099
+ table.push(
6100
+ ...page.data.map((connection) => [
6101
+ connection.slug || connection.app_key,
6102
+ connection.title
6103
+ ])
6104
+ );
6105
+ console.log(
6106
+ `Active Zapier connections (showing up to ${CONNECTION_DISPLAY_LIMIT}):`
6107
+ );
6108
+ console.log(table.toString());
6109
+ }
6110
+ var CONNECTION_PLACEHOLDER = "__ZAPIER_SDK_SLACK_CONNECTION__";
6111
+ var EMAIL_PLACEHOLDER = "__ZAPIER_SDK_ACCOUNT_EMAIL__";
6112
+ var APP_PLACEHOLDER = "__ZAPIER_SDK_SLACK_APP__";
6113
+ var SLACK_SLUG = "slack";
6114
+ function getSlackTestPath(context) {
6115
+ const extension = context.projectLanguage === "typescript" ? "ts" : "mjs";
6116
+ return path.join("src", "sdk-demo", `zapier-slack-test.${extension}`);
6117
+ }
6118
+ function getSlackTestTemplatePath(context) {
6119
+ const extension = context.projectLanguage === "typescript" ? "ts" : "mjs";
6120
+ return path.join(TEMPLATES_DIR, "setup", `zapier-slack-test.${extension}`);
6121
+ }
6122
+ async function findSlackConnection(context) {
6123
+ const page = await runWithSetupLoader({
6124
+ promise: context.imports.listConnections({
6125
+ owner: "me",
6126
+ app: SLACK_SLUG,
6127
+ maxItems: 1
6128
+ }),
6129
+ label: "Looking for a Slack connection"
6130
+ });
6131
+ return page.data.find(({ slug }) => slug === SLACK_SLUG);
6132
+ }
6133
+ function toTemplateString(value) {
6134
+ return JSON.stringify(value).slice(1, -1);
6135
+ }
6136
+ function renderSlackTest({
6137
+ context,
6138
+ app,
6139
+ connection,
6140
+ email
6141
+ }) {
6142
+ return fs.readFileSync(getSlackTestTemplatePath(context), "utf8").replace(APP_PLACEHOLDER, () => toTemplateString(app)).replace(CONNECTION_PLACEHOLDER, () => toTemplateString(connection)).replace(EMAIL_PLACEHOLDER, () => toTemplateString(email));
6143
+ }
6144
+ function writeSlackTest({
6145
+ context,
6146
+ app,
6147
+ connection,
6148
+ email
6149
+ }) {
6150
+ const slackTestPath = getSlackTestPath(context);
6151
+ const path2 = path.join(context.cwd, slackTestPath);
6152
+ if (!fs.existsSync(path.dirname(path2))) fs.mkdirSync(path.dirname(path2), { recursive: true });
6153
+ fs.writeFileSync(path2, renderSlackTest({ context, app, connection, email }));
6154
+ console.log(`Created ${slackTestPath}.`);
6155
+ }
6156
+ async function executeSlackTest(context) {
6157
+ const slackTestPath = getSlackTestPath(context);
6158
+ if (context.projectLanguage === "javascript") {
6159
+ await context.runCommand({
6160
+ command: "node",
6161
+ args: [slackTestPath],
6162
+ cwd: context.cwd,
6163
+ capture: false
6164
+ });
6165
+ return;
6166
+ }
6167
+ const command = context.packageManager === "bun" ? { command: "bun", args: [] } : createLocalPackageCommand({
6168
+ packageManager: context.packageManager,
6169
+ binary: "tsx"
6170
+ });
6171
+ const args = [...command.args, slackTestPath];
6172
+ await context.runCommand({
6173
+ command: command.command,
6174
+ args,
6175
+ cwd: context.cwd,
6176
+ capture: false
6177
+ });
6178
+ }
6179
+ async function trySlackTest(context) {
6180
+ try {
6181
+ await executeSlackTest(context);
6182
+ return true;
6183
+ } catch (error) {
6184
+ const message = error instanceof Error ? error.message : String(error);
6185
+ console.warn(`Slack demo failed: ${message}. Setup will continue.`);
6186
+ return false;
6187
+ }
6188
+ }
6189
+ async function offerSlackTest(context) {
6190
+ if (!context.accountEmail) {
6191
+ console.log("No account email found; skipping the Slack demo.");
6192
+ return;
6193
+ }
6194
+ const slackConnection = await findSlackConnection(context);
6195
+ if (!slackConnection) {
6196
+ console.log("No active Slack connection found; skipping the Slack demo.");
6197
+ return;
6198
+ }
6199
+ const slackTestPath = getSlackTestPath(context);
6200
+ const shouldRun = await resolveSetupConfirm({
6201
+ answer: context.createAnswer(),
6202
+ controller: context.setupController,
6203
+ message: `Run the Slack self-DM test using ${context.accountEmail}?`,
6204
+ defaultValue: true
6205
+ });
6206
+ if (!shouldRun) return;
6207
+ const path2 = path.join(context.cwd, slackTestPath);
6208
+ if (fs.existsSync(path2)) {
6209
+ const shouldOverwrite = await resolveSetupConfirm({
6210
+ answer: context.createAnswer(),
6211
+ controller: context.setupController,
6212
+ message: `${slackTestPath} already exists. Is it okay to overwrite it?`,
6213
+ defaultValue: false
6214
+ });
6215
+ if (!shouldOverwrite) {
6216
+ console.log("Keeping the existing Slack test file.");
6217
+ const shouldRunExisting = await resolveSetupConfirm({
6218
+ answer: context.createAnswer(),
6219
+ controller: context.setupController,
6220
+ message: `Run the existing ${slackTestPath}?`,
6221
+ defaultValue: false
6222
+ });
6223
+ if (shouldRunExisting) await trySlackTest(context);
6224
+ return;
6225
+ }
6226
+ }
6227
+ let email = context.accountEmail;
6228
+ writeSlackTest({
6229
+ context,
6230
+ app: SLACK_SLUG,
6231
+ connection: slackConnection.id,
6232
+ email
6233
+ });
6234
+ if (await trySlackTest(context)) return;
6235
+ email = await resolveSetupInput({
6236
+ answer: context.createAnswer(),
6237
+ controller: context.setupController,
6238
+ message: "Slack email for one retry after the failed test:"
6239
+ });
6240
+ if (!email) {
6241
+ console.log("Skipping the Slack test.");
6242
+ return;
6243
+ }
6244
+ writeSlackTest({
6245
+ context,
6246
+ app: SLACK_SLUG,
6247
+ connection: slackConnection.id,
6248
+ email
6249
+ });
6250
+ await trySlackTest(context);
6251
+ }
6252
+
6253
+ // src/plugins/setup/skill.ts
6254
+ async function installOptionalSkill(context) {
6255
+ const shouldInstall = await resolveSetupConfirm({
6256
+ answer: context.createAnswer(),
6257
+ controller: context.setupController,
6258
+ message: "Install the optional Zapier SDK skill for extra agent context? This is not required for SDK setup.",
6259
+ defaultValue: true
6260
+ });
6261
+ if (!shouldInstall) {
6262
+ console.log("Skipping the optional Zapier SDK skill.");
6263
+ return;
6264
+ }
6265
+ const command = createPackageRunnerCommand({
6266
+ packageManager: context.packageManager,
6267
+ packageName: "skills",
6268
+ args: ["add", "zapier/sdk", "-y"]
6269
+ });
6270
+ try {
6271
+ await context.runCommand({
6272
+ ...command,
6273
+ cwd: context.cwd,
6274
+ capture: true
6275
+ });
6276
+ } catch {
6277
+ console.warn(
6278
+ `Could not install the optional Zapier SDK skill. To install it manually, run: ${formatPackageCommand(command)}`
6279
+ );
6280
+ }
6281
+ }
6282
+
6283
+ // src/plugins/setup/wizard.ts
6284
+ var PHASE_COUNT = 6;
6285
+ var MINIMUM_MESSAGE_WIDTH = 20;
6286
+ var MAXIMUM_MESSAGE_WIDTH = 88;
6287
+ function showPhase({ number, title }) {
6288
+ console.log();
6289
+ console.log(chalk3__default.default.bgCyan.black.bold(` ${number}/${PHASE_COUNT} ${title} `));
6290
+ }
6291
+ function printWrapped(text) {
6292
+ const width = Math.max(
6293
+ MINIMUM_MESSAGE_WIDTH,
6294
+ Math.min(
6295
+ process.stdout.columns ?? MAXIMUM_MESSAGE_WIDTH,
6296
+ MAXIMUM_MESSAGE_WIDTH
6297
+ )
6298
+ );
6299
+ console.log(wrapAnsi__default.default(text, width));
6300
+ }
6301
+ function showReadyMessage() {
6302
+ console.log();
6303
+ console.log(chalk3__default.default.bgGreen.black.bold(" \u2713 Zapier SDK setup complete "));
6304
+ console.log();
6305
+ printWrapped(
6306
+ "Use active Zapier connections to access 9,000+ app connectors without managing each app's OAuth, token refresh, or retries."
6307
+ );
6308
+ console.log();
6309
+ printWrapped(
6310
+ "To learn more about the Zapier SDK, visit https://docs.zapier.com/sdk"
6311
+ );
6312
+ console.log();
6313
+ }
6314
+ async function runWizard(context) {
6315
+ console.log(chalk3__default.default.bold("Zapier SDK setup"));
6316
+ showPhase({ number: 1, title: "Project directory" });
6317
+ await chooseDirectory(context);
6318
+ showPhase({ number: 2, title: "Node.js" });
6319
+ await ensureSupportedNode(context);
6320
+ showPhase({ number: 3, title: "Dependencies" });
6321
+ await prepareProject(context);
6322
+ await installOptionalSkill(context);
6323
+ showPhase({ number: 4, title: "Zapier account" });
6324
+ await authenticate(context);
6325
+ showPhase({ number: 5, title: "App connections" });
6326
+ await ensureConnectionsAvailable(context);
6327
+ showPhase({ number: 6, title: "Slack demo" });
6328
+ await offerSlackTest(context);
6329
+ showReadyMessage();
6330
+ console.log(chalk3__default.default.bgCyan.black.bold(" Next steps "));
6331
+ await openAgentHandoff(context);
6332
+ }
6333
+
6334
+ // src/plugins/setup/index.ts
6335
+ var getProfileRef = zapierSdk.declareMethod({ id: "getProfile" });
6336
+ var listConnectionsRef2 = zapierSdk.declareMethod({ id: "listConnections" });
6337
+ var loginRef = zapierSdk.declareMethod({ id: "login" });
6338
+ var logoutRef = zapierSdk.declareMethod({ id: "logout" });
6339
+ var signupRef = zapierSdk.declareMethod({ id: "signup" });
6340
+ var setupImports = [
6341
+ getProfileRef,
6342
+ listConnectionsRef2,
6343
+ loginRef,
6344
+ logoutRef,
6345
+ signupRef
6346
+ ];
6347
+ var setupPlugin = zapierSdk.defineMethod({
6348
+ name: "setup",
6349
+ imports: setupImports,
6350
+ categories: ["utility"],
6351
+ supportsJsonOutput: false,
6352
+ inputSchema: SetupSchema,
6353
+ output: "raw",
6354
+ run: async ({ imports }) => {
6355
+ if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
6356
+ throw new ZapierCliExitError(
6357
+ "`zapier-sdk setup` requires an interactive terminal."
6358
+ );
6359
+ }
6360
+ await runWizard(createWizardContext({ imports }));
4600
6361
  }
4601
6362
  });
4602
6363
  function jsonReplacer(_key, value) {
@@ -4633,7 +6394,7 @@ ${chalk3__default.default.bold(`Message #${messageNumber}`)} ${chalk3__default.d
4633
6394
  while (true) {
4634
6395
  let action;
4635
6396
  try {
4636
- const answer = await inquirer__default.default.prompt([
6397
+ const answer = await inquirer3__default.default.prompt([
4637
6398
  {
4638
6399
  type: "list",
4639
6400
  name: "action",
@@ -5100,7 +6861,7 @@ function collectDeprecationNoticeAndForward(event, onEvent) {
5100
6861
  // package.json with { type: 'json' }
5101
6862
  var package_default = {
5102
6863
  name: "@zapier/zapier-sdk-cli",
5103
- version: "0.67.6"};
6864
+ version: "0.69.0"};
5104
6865
 
5105
6866
  // src/sdk.ts
5106
6867
  var warnedDeprecatedMethods = /* @__PURE__ */ new Set();
@@ -5140,6 +6901,7 @@ var cliSdkPlugin = zapierSdk.definePlugin({
5140
6901
  mcpPlugin,
5141
6902
  getLoginConfigPathPlugin,
5142
6903
  initPlugin,
6904
+ setupPlugin,
5143
6905
  bundleCodePlugin,
5144
6906
  feedbackPlugin,
5145
6907
  curlPlugin,
@@ -5183,7 +6945,7 @@ function createZapierCliSdk(options = {}) {
5183
6945
 
5184
6946
  // package.json
5185
6947
  var package_default2 = {
5186
- version: "0.67.6"};
6948
+ version: "0.69.0"};
5187
6949
 
5188
6950
  // src/telemetry/builders.ts
5189
6951
  function createCliBaseEvent(context = {}) {
@@ -5231,8 +6993,7 @@ function buildCliCommandExecutedEvent({
5231
6993
  ci_platform: zapierSdk.getCiPlatform(),
5232
6994
  ...zapierSdk.getTtyContext(),
5233
6995
  agent: zapierSdk.getAgent(),
5234
- package_manager: data.package_manager ?? "pnpm",
5235
- // Default based on project setup
6996
+ package_manager: data.package_manager ?? detectPackageManager(process.cwd()).name,
5236
6997
  made_network_requests: data.made_network_requests ?? null,
5237
6998
  files_modified_count: data.files_modified_count ?? null,
5238
6999
  files_created_count: data.files_created_count ?? null,