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