@zapier/zapier-sdk-cli 0.77.9 → 0.78.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/cli.cjs CHANGED
@@ -5,7 +5,7 @@ var commander = require('commander');
5
5
  var zapierSdk = require('@zapier/zapier-sdk');
6
6
  var zod = require('zod');
7
7
  var inquirer = require('inquirer');
8
- var chalk8 = require('chalk');
8
+ var chalk9 = require('chalk');
9
9
  var core = require('@inquirer/core');
10
10
  var ora = require('ora');
11
11
  var fs = require('fs');
@@ -59,7 +59,7 @@ function _interopNamespace(e) {
59
59
  }
60
60
 
61
61
  var inquirer__default = /*#__PURE__*/_interopDefault(inquirer);
62
- var chalk8__default = /*#__PURE__*/_interopDefault(chalk8);
62
+ var chalk9__default = /*#__PURE__*/_interopDefault(chalk9);
63
63
  var ora__default = /*#__PURE__*/_interopDefault(ora);
64
64
  var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
65
65
  var path__namespace = /*#__PURE__*/_interopNamespace(path);
@@ -104,9 +104,9 @@ function normalizeChoices(choices) {
104
104
  var theme = core.makeTheme({
105
105
  icon: { cursor: "\u276F" },
106
106
  style: {
107
- disabled: (text) => chalk8__default.default.dim(`- ${text}`),
108
- searchTerm: (text) => chalk8__default.default.cyan(text),
109
- keysHelpTip: (keys) => keys.map(([key, action]) => `${chalk8__default.default.bold(key)} ${chalk8__default.default.dim(action)}`).join(chalk8__default.default.dim(" \u2022 "))
107
+ disabled: (text) => chalk9__default.default.dim(`- ${text}`),
108
+ searchTerm: (text) => chalk9__default.default.cyan(text),
109
+ keysHelpTip: (keys) => keys.map(([key, action]) => `${chalk9__default.default.bold(key)} ${chalk9__default.default.dim(action)}`).join(chalk9__default.default.dim(" \u2022 "))
110
110
  }
111
111
  });
112
112
  var searchSelect = core.createPrompt(
@@ -131,8 +131,8 @@ var searchSelect = core.createPrompt(
131
131
  return { first, last };
132
132
  }, [searchResults]);
133
133
  const defaultActive = core.useMemo(() => {
134
- const requested = config2.initialActive;
135
- if (searchTerm === "" && requested !== void 0 && requested >= 0 && requested < searchResults.length && isSelectable(searchResults[requested])) {
134
+ const requested = searchTerm === "" ? config2.initialActive : config2.initialActiveForTerm?.({ term: searchTerm });
135
+ if (requested !== void 0 && requested >= 0 && requested < searchResults.length && isSelectable(searchResults[requested])) {
136
136
  return requested;
137
137
  }
138
138
  return bounds.first;
@@ -249,10 +249,10 @@ async function promptText({
249
249
  ]);
250
250
  return value;
251
251
  }
252
- var display = (c) => c.hint ? `${c.label} ${chalk8__default.default.dim(`(${c.hint})`)}` : c.label;
252
+ var display = (c) => c.hint ? `${c.label} ${chalk9__default.default.dim(`(${c.hint})`)}` : c.label;
253
253
  var HIGH_CONTRAST_PROMPT_THEME = {
254
254
  style: {
255
- answer: (text) => chalk8__default.default.inverse.bold(` ${text} `)
255
+ answer: (text) => chalk9__default.default.inverse.bold(` ${text} `)
256
256
  }
257
257
  };
258
258
  function buildSelectRows(question, term) {
@@ -268,8 +268,8 @@ function buildSelectRows(question, term) {
268
268
  name: display(c),
269
269
  value: c.value
270
270
  }));
271
- const skipRow = offers(question, "skip") ? [row(chalk8__default.default.dim("Skip (optional)"), "skip")] : [];
272
- const customRow = offers(question, "custom") ? [row(chalk8__default.default.dim("Enter a value manually\u2026"), "custom")] : [];
271
+ const skipRow = offers(question, "skip") ? [row(chalk9__default.default.dim("Skip (optional)"), "skip")] : [];
272
+ const customRow = offers(question, "custom") ? [row(chalk9__default.default.dim("Enter a value manually\u2026"), "custom")] : [];
273
273
  const committed = !!t || question.search !== void 0;
274
274
  let rows;
275
275
  if (!committed) {
@@ -280,13 +280,13 @@ function buildSelectRows(question, term) {
280
280
  rows = [...customRow, ...skipRow];
281
281
  }
282
282
  if (offers(question, "search"))
283
- rows.push(row(chalk8__default.default.cyan("Search again\u2026"), "search"));
283
+ rows.push(row(chalk9__default.default.cyan("Search again\u2026"), "search"));
284
284
  if (offers(question, "next_page"))
285
- rows.push(row(chalk8__default.default.dim("Load more\u2026"), "next_page"));
286
- if (offers(question, "retry")) rows.push(row(chalk8__default.default.yellow("Retry"), "retry"));
287
- if (offers(question, "cancel")) rows.push(row(chalk8__default.default.dim("Cancel"), "cancel"));
285
+ rows.push(row(chalk9__default.default.dim("Load more\u2026"), "next_page"));
286
+ if (offers(question, "retry")) rows.push(row(chalk9__default.default.yellow("Retry"), "retry"));
287
+ if (offers(question, "cancel")) rows.push(row(chalk9__default.default.dim("Cancel"), "cancel"));
288
288
  for (const note of question.notes ?? [])
289
- rows.push({ name: chalk8__default.default.dim(note), value: note, disabled: true });
289
+ rows.push({ name: chalk9__default.default.dim(note), value: note, disabled: true });
290
290
  return rows;
291
291
  }
292
292
  function foldPage(acc, question, field) {
@@ -366,12 +366,12 @@ async function answerSelect(question, field, box, failed, mode) {
366
366
  })),
367
367
  ...offers(question, "next_page") ? [
368
368
  {
369
- name: chalk8__default.default.dim("Load more\u2026"),
369
+ name: chalk9__default.default.dim("Load more\u2026"),
370
370
  value: { action: "next_page" }
371
371
  }
372
372
  ] : [],
373
373
  ...(question.notes ?? []).map((note) => ({
374
- name: chalk8__default.default.dim(note),
374
+ name: chalk9__default.default.dim(note),
375
375
  value: note,
376
376
  disabled: true
377
377
  }))
@@ -448,14 +448,14 @@ async function answerSelect(question, field, box, failed, mode) {
448
448
  case "retry":
449
449
  return { type: "retry" };
450
450
  case "skip":
451
- printAnswered(view.message, chalk8__default.default.dim("(skipped)"));
451
+ printAnswered(view.message, chalk9__default.default.dim("(skipped)"));
452
452
  return { type: "skip" };
453
453
  case "cancel":
454
454
  return { type: "cancel" };
455
455
  }
456
456
  }
457
457
  function printAnswered(message, label) {
458
- console.log(`${chalk8__default.default.green("\u2714")} ${message} ${chalk8__default.default.cyan(label)}`);
458
+ console.log(`${chalk9__default.default.green("\u2714")} ${message} ${chalk9__default.default.cyan(label)}`);
459
459
  }
460
460
  async function answerInput(question) {
461
461
  const message = question.placeholder ? question.message.replace(/:?\s*$/, ` (${question.placeholder}):`) : question.message;
@@ -502,7 +502,7 @@ function createCliAnswer({
502
502
  try {
503
503
  if (result.error !== void 0) {
504
504
  const message = typeof result.error === "string" ? result.error : result.error.message;
505
- console.log(chalk8__default.default.yellow(`! ${message}`));
505
+ console.log(chalk9__default.default.yellow(`! ${message}`));
506
506
  }
507
507
  const question = result.question;
508
508
  const field = question.path.length ? question.path.join(".") : "value";
@@ -602,7 +602,7 @@ var SHARED_COMMAND_CLI_OPTIONS = [
602
602
 
603
603
  // package.json
604
604
  var package_default = {
605
- version: "0.77.9"};
605
+ version: "0.78.0"};
606
606
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
607
607
  var LOCKFILES = [
608
608
  ["pnpm-lock.yaml", "pnpm"],
@@ -767,7 +767,7 @@ async function formatItemsFromSchema(_functionInfo, items, startingNumber = 0, o
767
767
  formatItemsGeneric(items, startingNumber);
768
768
  }
769
769
  function formatSingleItem(formatted, itemNumber) {
770
- let titleLine = `${chalk8__default.default.gray(`${itemNumber + 1}.`)} ${chalk8__default.default.cyan(formatted.title)}`;
770
+ let titleLine = `${chalk9__default.default.gray(`${itemNumber + 1}.`)} ${chalk9__default.default.cyan(formatted.title)}`;
771
771
  const subtitleParts = [];
772
772
  if (formatted.hint !== void 0) {
773
773
  subtitleParts.push(
@@ -785,11 +785,11 @@ function formatSingleItem(formatted, itemNumber) {
785
785
  }
786
786
  const uniqueParts = [...new Set(subtitleParts)];
787
787
  if (uniqueParts.length > 0) {
788
- titleLine += ` ${chalk8__default.default.gray(`(${uniqueParts.join(", ")})`)}`;
788
+ titleLine += ` ${chalk9__default.default.gray(`(${uniqueParts.join(", ")})`)}`;
789
789
  }
790
790
  console.log(titleLine);
791
791
  if (formatted.description) {
792
- console.log(` ${chalk8__default.default.dim(formatted.description)}`);
792
+ console.log(` ${chalk9__default.default.dim(formatted.description)}`);
793
793
  }
794
794
  if (formatted.raw !== void 0) {
795
795
  formatJsonOutput(formatted.raw);
@@ -800,7 +800,7 @@ function formatSingleItem(formatted, itemNumber) {
800
800
  if (detail.label) {
801
801
  const isMultiline = detail.text.includes("\n");
802
802
  if (isMultiline) {
803
- console.log(` ${chalk8__default.default.gray(detail.label + ":")}`);
803
+ console.log(` ${chalk9__default.default.gray(detail.label + ":")}`);
804
804
  const displayText = formatDetailText(
805
805
  detail.text,
806
806
  DETAIL_INDENT + " "
@@ -809,7 +809,7 @@ function formatSingleItem(formatted, itemNumber) {
809
809
  console.log(`${DETAIL_INDENT} ${styledText}`);
810
810
  } else {
811
811
  const styledValue = applyStyle(detail.text, detail.style);
812
- console.log(` ${chalk8__default.default.gray(detail.label + ":")} ${styledValue}`);
812
+ console.log(` ${chalk9__default.default.gray(detail.label + ":")} ${styledValue}`);
813
813
  }
814
814
  } else {
815
815
  const displayText = formatDetailText(detail.text, DETAIL_INDENT);
@@ -833,16 +833,16 @@ function formatDetailText(text, indent = DETAIL_INDENT) {
833
833
  function applyStyle(value, style) {
834
834
  switch (style) {
835
835
  case "dim":
836
- return chalk8__default.default.dim(value);
836
+ return chalk9__default.default.dim(value);
837
837
  case "accent":
838
- return chalk8__default.default.magenta(value);
838
+ return chalk9__default.default.magenta(value);
839
839
  case "warning":
840
- return chalk8__default.default.red(value);
840
+ return chalk9__default.default.red(value);
841
841
  case "success":
842
- return chalk8__default.default.green(value);
842
+ return chalk9__default.default.green(value);
843
843
  case "normal":
844
844
  default:
845
- return chalk8__default.default.blue(value);
845
+ return chalk9__default.default.blue(value);
846
846
  }
847
847
  }
848
848
  function convertGenericItemToFormattedItem(item) {
@@ -991,10 +991,10 @@ function createInteractiveRenderer(context = {}) {
991
991
  const obj = item;
992
992
  const name = obj?.name || obj?.key || obj?.id || "Item";
993
993
  console.log(
994
- `${chalk8__default.default.gray(`${startingNumber + index + 1}.`)} ${chalk8__default.default.cyan(String(name))}`
994
+ `${chalk9__default.default.gray(`${startingNumber + index + 1}.`)} ${chalk9__default.default.cyan(String(name))}`
995
995
  );
996
996
  if (obj?.description)
997
- console.log(` ${chalk8__default.default.dim(String(obj.description))}`);
997
+ console.log(` ${chalk9__default.default.dim(String(obj.description))}`);
998
998
  console.log();
999
999
  });
1000
1000
  }
@@ -1005,35 +1005,35 @@ function createInteractiveRenderer(context = {}) {
1005
1005
  if (!(Symbol.asyncIterator in Object(source))) {
1006
1006
  const items = source?.data;
1007
1007
  if (!Array.isArray(items) || items.length === 0) {
1008
- console.log(chalk8__default.default.yellow(`No ${itemName} found.`));
1008
+ console.log(chalk9__default.default.yellow(`No ${itemName} found.`));
1009
1009
  return;
1010
1010
  }
1011
1011
  await renderItemsForDisplay(items, functionInfo, 0);
1012
- console.log(chalk8__default.default.green(`
1012
+ console.log(chalk9__default.default.green(`
1013
1013
  \u2705 Showing ${items.length} ${itemName}`));
1014
1014
  return;
1015
1015
  }
1016
1016
  let totalShown = 0;
1017
1017
  let pageCount = 0;
1018
- console.log(chalk8__default.default.blue(`\u{1F4CB} ${getListTitle(functionInfo)}
1018
+ console.log(chalk9__default.default.blue(`\u{1F4CB} ${getListTitle(functionInfo)}
1019
1019
  `));
1020
1020
  for await (const page of source) {
1021
1021
  const items = page.data ?? [];
1022
1022
  pageCount++;
1023
1023
  if (items.length === 0 && pageCount === 1) {
1024
- console.log(chalk8__default.default.yellow(`No ${itemName} found.`));
1024
+ console.log(chalk9__default.default.yellow(`No ${itemName} found.`));
1025
1025
  return;
1026
1026
  }
1027
1027
  if (items.length === 0) break;
1028
1028
  if (pageCount > 1) {
1029
1029
  console.clear();
1030
- console.log(chalk8__default.default.blue(`\u{1F4CB} ${getListTitle(functionInfo)}
1030
+ console.log(chalk9__default.default.blue(`\u{1F4CB} ${getListTitle(functionInfo)}
1031
1031
  `));
1032
1032
  }
1033
1033
  await renderItemsForDisplay(items, functionInfo, totalShown);
1034
1034
  totalShown += items.length;
1035
1035
  console.log(
1036
- chalk8__default.default.green(
1036
+ chalk9__default.default.green(
1037
1037
  `
1038
1038
  \u2705 Showing ${totalShown} ${itemName} (page ${pageCount})`
1039
1039
  )
@@ -1052,7 +1052,7 @@ function createInteractiveRenderer(context = {}) {
1052
1052
  break;
1053
1053
  }
1054
1054
  }
1055
- console.log(chalk8__default.default.gray(`
1055
+ console.log(chalk9__default.default.gray(`
1056
1056
  \u{1F4C4} Finished browsing ${itemName}`));
1057
1057
  },
1058
1058
  async renderCollectedList(items, { maxItems, userSpecifiedMaxItems, functionInfo } = {}) {
@@ -1062,30 +1062,30 @@ function createInteractiveRenderer(context = {}) {
1062
1062
  }
1063
1063
  const itemName = getItemName(functionInfo);
1064
1064
  if (items.length === 0) {
1065
- console.log(chalk8__default.default.yellow(`No ${itemName} found.`));
1065
+ console.log(chalk9__default.default.yellow(`No ${itemName} found.`));
1066
1066
  return;
1067
1067
  }
1068
- console.log(chalk8__default.default.green(`
1068
+ console.log(chalk9__default.default.green(`
1069
1069
  \u2705 Found ${items.length} ${itemName}:
1070
1070
  `));
1071
1071
  await renderItemsForDisplay(items, functionInfo);
1072
1072
  if (userSpecifiedMaxItems && maxItems) {
1073
1073
  console.log(
1074
- chalk8__default.default.gray(
1074
+ chalk9__default.default.gray(
1075
1075
  `
1076
1076
  \u{1F4C4} Showing up to ${maxItems} ${itemName} (--max-items ${maxItems})`
1077
1077
  )
1078
1078
  );
1079
1079
  } else {
1080
- console.log(chalk8__default.default.gray(`
1080
+ console.log(chalk9__default.default.gray(`
1081
1081
  \u{1F4C4} All available ${itemName} shown`));
1082
1082
  }
1083
1083
  },
1084
1084
  renderItem(value, options) {
1085
1085
  if (options?.outputFile) {
1086
1086
  const label = options.commandName ? `\u2705 ${options.commandName} completed successfully!` : "\u2705 Done!";
1087
- console.log(chalk8__default.default.green(label));
1088
- console.log(chalk8__default.default.gray(`Output written to: ${options.outputFile}`));
1087
+ console.log(chalk9__default.default.green(label));
1088
+ console.log(chalk9__default.default.gray(`Output written to: ${options.outputFile}`));
1089
1089
  } else {
1090
1090
  formatJsonOutput(value);
1091
1091
  }
@@ -1095,17 +1095,17 @@ function createInteractiveRenderer(context = {}) {
1095
1095
  },
1096
1096
  renderError(error) {
1097
1097
  if (error instanceof ZapierCliMissingParametersError) {
1098
- console.error(chalk8__default.default.red("\u274C " + formatMissingParamsError(error)));
1099
- console.error("\n" + chalk8__default.default.dim("Use --help to see available options"));
1098
+ console.error(chalk9__default.default.red("\u274C " + formatMissingParamsError(error)));
1099
+ console.error("\n" + chalk9__default.default.dim("Use --help to see available options"));
1100
1100
  throw new ZapierCliExitError(error.message, 1);
1101
1101
  }
1102
1102
  if (zapierSdk.isZapierError(error)) {
1103
1103
  const formattedMessage = zapierSdk.formatErrorMessage(error);
1104
- console.error(chalk8__default.default.red("\u274C Error:"), formattedMessage);
1104
+ console.error(chalk9__default.default.red("\u274C Error:"), formattedMessage);
1105
1105
  throw new ZapierCliExitError(formattedMessage, 1);
1106
1106
  }
1107
1107
  const msg = error instanceof Error ? error.message : "Unknown error";
1108
- console.error(chalk8__default.default.red("\u274C Error:"), msg);
1108
+ console.error(chalk9__default.default.red("\u274C Error:"), msg);
1109
1109
  throw new ZapierCliExitError(msg, 1);
1110
1110
  }
1111
1111
  };
@@ -1221,7 +1221,7 @@ async function promptConfirm(confirmType, itemType) {
1221
1221
  }
1222
1222
  const configOrFn = CONFIRM_MESSAGES[confirmType];
1223
1223
  const { messageBefore, messageAfter } = typeof configOrFn === "function" ? configOrFn(itemType) : configOrFn;
1224
- console.log(chalk8__default.default.yellow(`
1224
+ console.log(chalk9__default.default.yellow(`
1225
1225
  ${messageBefore}
1226
1226
  `));
1227
1227
  const { confirmed } = await inquirer__default.default.prompt([
@@ -1245,12 +1245,12 @@ function emitParamDeprecationWarnings({
1245
1245
  if (Array.isArray(value) && value.length === 0) continue;
1246
1246
  console.warn();
1247
1247
  console.warn(
1248
- chalk8__default.default.yellow.bold("\u26A0\uFE0F DEPRECATION WARNING") + chalk8__default.default.yellow(
1248
+ chalk9__default.default.yellow.bold("\u26A0\uFE0F DEPRECATION WARNING") + chalk9__default.default.yellow(
1249
1249
  ` - \`${toKebabCase(param.name)}\` is deprecated and may be removed in a future release.`
1250
1250
  )
1251
1251
  );
1252
1252
  if (param.deprecationMessage) {
1253
- console.warn(chalk8__default.default.yellow(` ${param.deprecationMessage}`));
1253
+ console.warn(chalk9__default.default.yellow(` ${param.deprecationMessage}`));
1254
1254
  }
1255
1255
  console.warn();
1256
1256
  }
@@ -1643,7 +1643,7 @@ function createCommandConfig(cliCommandName, functionInfo, sdk) {
1643
1643
  functionInfo.itemType
1644
1644
  );
1645
1645
  if (!confirmResult.confirmed) {
1646
- console.log(chalk8__default.default.yellow("Operation cancelled."));
1646
+ console.log(chalk9__default.default.yellow("Operation cancelled."));
1647
1647
  return;
1648
1648
  }
1649
1649
  confirmMessageAfter = confirmResult.messageAfter;
@@ -1704,7 +1704,7 @@ function createCommandConfig(cliCommandName, functionInfo, sdk) {
1704
1704
  renderer.renderItem(normalizedResult.value);
1705
1705
  }
1706
1706
  if (confirmMessageAfter) {
1707
- console.log(chalk8__default.default.yellow(`
1707
+ console.log(chalk9__default.default.yellow(`
1708
1708
  ${confirmMessageAfter}`));
1709
1709
  }
1710
1710
  break;
@@ -2385,6 +2385,10 @@ function getActiveCredentials(options) {
2385
2385
  if (!name) return void 0;
2386
2386
  return findEntry(readRegistry(), name, normalizeBaseUrl(options?.baseUrl));
2387
2387
  }
2388
+ function listStoredCredentials(options) {
2389
+ const baseUrl2 = normalizeBaseUrl(options?.baseUrl);
2390
+ return readRegistry().filter((entry) => entry.baseUrl === baseUrl2).sort((left, right) => right.createdAt - left.createdAt);
2391
+ }
2388
2392
  var MAX_CREDENTIAL_NAME_ATTEMPTS = 500;
2389
2393
  function firstAvailableCredentialName({
2390
2394
  baseName,
@@ -2489,6 +2493,29 @@ async function getStoredClientCredentials(options) {
2489
2493
  scope: [...entry.scopes].sort().join(" ")
2490
2494
  };
2491
2495
  }
2496
+ async function activateStoredCredentials({
2497
+ name,
2498
+ baseUrl: baseUrl2
2499
+ }) {
2500
+ const resolvedBaseUrl = normalizeBaseUrl(baseUrl2);
2501
+ const entry = findEntry(readRegistry(), name, resolvedBaseUrl);
2502
+ if (!entry) {
2503
+ throw new ZapierCliValidationError(
2504
+ `No stored credentials named "${name}" were found.`
2505
+ );
2506
+ }
2507
+ const credentials2 = await getStoredClientCredentials({
2508
+ name,
2509
+ baseUrl: resolvedBaseUrl
2510
+ });
2511
+ if (!credentials2) {
2512
+ throw new ZapierCliValidationError(
2513
+ `Stored credentials "${name}" are missing from the system keychain. Add a new account to recreate them.`
2514
+ );
2515
+ }
2516
+ getConfig().set(CREDENTIALS_KEY, name);
2517
+ return entry;
2518
+ }
2492
2519
  function deleteRegistryEntry(registry, name, baseUrl2) {
2493
2520
  const idx = registry.findIndex(
2494
2521
  (e) => e.name === name && e.baseUrl === baseUrl2
@@ -3042,6 +3069,219 @@ async function setupClientCredentials({
3042
3069
  }
3043
3070
  return { clientId };
3044
3071
  }
3072
+ function isSameCredentials(left, right) {
3073
+ return left.name === right.name && left.baseUrl === right.baseUrl;
3074
+ }
3075
+ function createdAtIso(credentials2) {
3076
+ return new Date(credentials2.createdAt).toISOString();
3077
+ }
3078
+ function searchableFields(credentials2) {
3079
+ return [
3080
+ { text: credentials2.name.toLowerCase(), weight: 0 },
3081
+ { text: credentials2.clientId.toLowerCase(), weight: 1e3 },
3082
+ ...credentials2.scopes.map((scope) => ({
3083
+ text: scope.toLowerCase(),
3084
+ weight: 2e3
3085
+ })),
3086
+ {
3087
+ text: createdAtIso(credentials2).slice(0, 10).toLowerCase(),
3088
+ weight: 3e3
3089
+ }
3090
+ ];
3091
+ }
3092
+ function textMatchScore(text, query) {
3093
+ if (text === query) return 0;
3094
+ if (text.startsWith(query)) return 100 + text.length - query.length;
3095
+ const index = text.indexOf(query);
3096
+ if (index === -1) return void 0;
3097
+ return 200 + text.length - query.length;
3098
+ }
3099
+ function closestFieldScore(fields, query) {
3100
+ let closest;
3101
+ for (const field of fields) {
3102
+ const textScore = textMatchScore(field.text, query);
3103
+ if (textScore === void 0) continue;
3104
+ const score = field.weight + textScore;
3105
+ closest = closest === void 0 ? score : Math.min(closest, score);
3106
+ }
3107
+ return closest;
3108
+ }
3109
+ function searchScore(credentials2, term) {
3110
+ const query = term.trim().toLowerCase();
3111
+ const tokens = query.split(/\s+/).filter(Boolean);
3112
+ const fields = searchableFields(credentials2);
3113
+ let tokenScore = 0;
3114
+ for (const token of tokens) {
3115
+ const score = closestFieldScore(fields, token);
3116
+ if (score === void 0) return void 0;
3117
+ tokenScore += score;
3118
+ }
3119
+ const phraseScore = closestFieldScore(fields, query);
3120
+ return phraseScore === void 0 ? 1e4 + tokenScore : phraseScore;
3121
+ }
3122
+ function formatCredentialsChoice({
3123
+ credentials: credentials2,
3124
+ current
3125
+ }) {
3126
+ const currentLabel = current ? chalk9__default.default.cyan(" (current)") : "";
3127
+ const details = [
3128
+ credentials2.clientId,
3129
+ credentials2.scopes.join(", "),
3130
+ `created ${createdAtIso(credentials2).slice(0, 10)}`
3131
+ ].join(" \xB7 ");
3132
+ return {
3133
+ name: `${credentials2.name}${currentLabel} ${chalk9__default.default.dim(`\xB7 ${details}`)}`,
3134
+ short: credentials2.name,
3135
+ value: { action: "switch", credentials: credentials2 }
3136
+ };
3137
+ }
3138
+ function buildCredentialsChoices({
3139
+ credentials: credentials2,
3140
+ activeCredentials,
3141
+ term = ""
3142
+ }) {
3143
+ const sortedCredentials = [...credentials2].sort(
3144
+ (left, right) => right.createdAt - left.createdAt
3145
+ );
3146
+ const current = activeCredentials ? sortedCredentials.find(
3147
+ (entry) => isSameCredentials(entry, activeCredentials)
3148
+ ) : void 0;
3149
+ const rankedCredentials = term ? sortedCredentials.map((credentials3) => ({
3150
+ credentials: credentials3,
3151
+ score: searchScore(credentials3, term)
3152
+ })).filter(
3153
+ (result) => result.score !== void 0
3154
+ ).sort((left, right) => left.score - right.score).map(({ credentials: credentials3 }) => credentials3) : [
3155
+ ...current ? [current] : [],
3156
+ ...sortedCredentials.filter((credentials3) => credentials3 !== current)
3157
+ ];
3158
+ return [
3159
+ {
3160
+ name: "+ Add a new account",
3161
+ short: "Add a new account",
3162
+ value: { action: "create" }
3163
+ },
3164
+ ...rankedCredentials.map(
3165
+ (credentials3) => formatCredentialsChoice({
3166
+ credentials: credentials3,
3167
+ current: credentials3 === current
3168
+ })
3169
+ )
3170
+ ];
3171
+ }
3172
+ async function promptForCredentials({
3173
+ credentials: credentials2,
3174
+ activeCredentials
3175
+ }) {
3176
+ return searchSelect({
3177
+ message: "Select credentials or add a new account:",
3178
+ source: (term) => buildCredentialsChoices({
3179
+ credentials: credentials2,
3180
+ activeCredentials,
3181
+ term
3182
+ }),
3183
+ initialActive: credentials2.length > 0 ? 1 : 0,
3184
+ initialActiveForTerm: () => 1
3185
+ });
3186
+ }
3187
+
3188
+ // src/utils/auth/stored-login-credentials.ts
3189
+ function authFlowOnlyOptions(options) {
3190
+ return [
3191
+ ...options.timeout === void 0 ? [] : ["--timeout"],
3192
+ ...options.useApprovals === true ? ["--use-approvals"] : [],
3193
+ ...options.headless === true ? ["--headless"] : []
3194
+ ];
3195
+ }
3196
+ function assertCanSwitchCredentials({
3197
+ credentials: credentials2,
3198
+ options,
3199
+ resolvedCredentials
3200
+ }) {
3201
+ if (resolvedCredentials !== void 0) {
3202
+ throw new ZapierCliValidationError(
3203
+ "Cannot switch stored credentials while credentials are configured through SDK options or environment variables. Remove those credentials before switching accounts."
3204
+ );
3205
+ }
3206
+ const incompatibleOptions = authFlowOnlyOptions(options);
3207
+ if (incompatibleOptions.length === 0) return;
3208
+ throw new ZapierCliValidationError(
3209
+ `Cannot switch to stored credentials "${credentials2.name}" while using ${incompatibleOptions.join(
3210
+ ", "
3211
+ )}. These options only apply when logging in to a new account.`
3212
+ );
3213
+ }
3214
+ function findStoredCredentialsByName({
3215
+ name,
3216
+ baseUrl: baseUrl2
3217
+ }) {
3218
+ return listStoredCredentials({ baseUrl: baseUrl2 }).find(
3219
+ (credentials2) => credentials2.name === name
3220
+ );
3221
+ }
3222
+ async function switchCredentials({
3223
+ credentials: credentials2,
3224
+ options,
3225
+ resolvedCredentials
3226
+ }) {
3227
+ assertCanSwitchCredentials({ credentials: credentials2, options, resolvedCredentials });
3228
+ await activateStoredCredentials({
3229
+ name: credentials2.name,
3230
+ baseUrl: credentials2.baseUrl
3231
+ });
3232
+ process.stderr.write(
3233
+ `\u2705 Credentials "${credentials2.name}" are now active.
3234
+ `
3235
+ );
3236
+ }
3237
+ async function chooseStoredLoginCredentialsAtBaseUrl({
3238
+ baseUrl: baseUrl2,
3239
+ options,
3240
+ resolvedCredentials
3241
+ }) {
3242
+ if (resolvedCredentials !== void 0 || authFlowOnlyOptions(options).length > 0) {
3243
+ return "none";
3244
+ }
3245
+ const storedCredentials = listStoredCredentials({ baseUrl: baseUrl2 });
3246
+ if (storedCredentials.length === 0) return "none";
3247
+ const selection = await promptForCredentials({
3248
+ credentials: storedCredentials,
3249
+ activeCredentials: getActiveCredentials({ baseUrl: baseUrl2 })
3250
+ });
3251
+ if (selection.action === "create") return "create";
3252
+ await switchCredentials({
3253
+ credentials: selection.credentials,
3254
+ options,
3255
+ resolvedCredentials
3256
+ });
3257
+ return "switch";
3258
+ }
3259
+ async function chooseStoredLoginCredentials({
3260
+ imports,
3261
+ options
3262
+ }) {
3263
+ const resolvedCredentials = await imports.resolveCredentials();
3264
+ const credentialsBaseUrl2 = await resolveCredentialsBaseUrl({
3265
+ options: imports.sdkOptions,
3266
+ resolvedCredentials
3267
+ });
3268
+ return chooseStoredLoginCredentialsAtBaseUrl({
3269
+ baseUrl: credentialsBaseUrl2,
3270
+ options,
3271
+ resolvedCredentials
3272
+ });
3273
+ }
3274
+ async function confirmNewCredentialsName(name) {
3275
+ const { confirmed } = await inquirer__default.default.prompt([
3276
+ {
3277
+ type: "confirm",
3278
+ name: "confirmed",
3279
+ default: false,
3280
+ message: `No stored credentials named "${name}" were found. Continue with a new account and save it as "${name}"?`
3281
+ }
3282
+ ]);
3283
+ return confirmed;
3284
+ }
3045
3285
 
3046
3286
  // src/utils/constants.ts
3047
3287
  var LOGIN_PORTS = [49505, 50575, 52804, 55981, 61010, 63851];
@@ -3066,20 +3306,20 @@ var getCallablePromise = () => {
3066
3306
  var getCallablePromise_default = getCallablePromise;
3067
3307
  var log = {
3068
3308
  info: (message, ...args) => {
3069
- console.error(chalk8__default.default.blue("\u2139"), message, ...args);
3309
+ console.error(chalk9__default.default.blue("\u2139"), message, ...args);
3070
3310
  },
3071
3311
  error: (message, ...args) => {
3072
- console.error(chalk8__default.default.red("\u2716"), message, ...args);
3312
+ console.error(chalk9__default.default.red("\u2716"), message, ...args);
3073
3313
  },
3074
3314
  success: (message, ...args) => {
3075
- console.error(chalk8__default.default.green("\u2713"), message, ...args);
3315
+ console.error(chalk9__default.default.green("\u2713"), message, ...args);
3076
3316
  },
3077
3317
  warn: (message, ...args) => {
3078
- console.error(chalk8__default.default.yellow("\u26A0"), message, ...args);
3318
+ console.error(chalk9__default.default.yellow("\u26A0"), message, ...args);
3079
3319
  },
3080
3320
  debug: (message, ...args) => {
3081
3321
  if (process.env.DEBUG === "true" || process.argv.includes("--debug")) {
3082
- console.error(chalk8__default.default.gray("\u{1F41B}"), message, ...args);
3322
+ console.error(chalk9__default.default.gray("\u{1F41B}"), message, ...args);
3083
3323
  }
3084
3324
  }
3085
3325
  };
@@ -3926,9 +4166,6 @@ var HEADLESS_SIGNUP_RECOVERY_MESSAGE = "Restart `zapier-sdk signup --headless` t
3926
4166
  function getEntryPointLabel(entryPoint) {
3927
4167
  return entryPoint === "signup" ? "Signup" : "Login";
3928
4168
  }
3929
- function getActiveCredentialsAction(entryPoint) {
3930
- return entryPoint === "signup" ? "continue signup" : "log in again";
3931
- }
3932
4169
  function getCredentialsPromptMessage(entryPoint) {
3933
4170
  return entryPoint === "signup" ? "Enter a name to identify these credentials:" : "Enter a name to identify them:";
3934
4171
  }
@@ -3943,9 +4180,22 @@ function validateCredentialsName(name) {
3943
4180
  if (!trimmedName) throw new ZapierCliValidationError("Name cannot be empty");
3944
4181
  return trimmedName;
3945
4182
  }
4183
+ function validateNewCredentialsName({
4184
+ name,
4185
+ baseUrl: baseUrl2
4186
+ }) {
4187
+ const validatedName = validateCredentialsName(name);
4188
+ if (credentialNameExists({ name: validatedName, baseUrl: baseUrl2 })) {
4189
+ throw new ZapierCliValidationError(
4190
+ `Credentials named "${validatedName}" already exist. Choose a different name.`
4191
+ );
4192
+ }
4193
+ return validatedName;
4194
+ }
3946
4195
  async function promptCredentialsName({
3947
4196
  email,
3948
- promptMessage
4197
+ promptMessage,
4198
+ baseUrl: baseUrl2
3949
4199
  }) {
3950
4200
  const { credentialName } = await inquirer__default.default.prompt([
3951
4201
  {
@@ -3955,7 +4205,7 @@ async function promptCredentialsName({
3955
4205
  default: defaultCredentialsName(email),
3956
4206
  validate: (input) => {
3957
4207
  try {
3958
- validateCredentialsName(input);
4208
+ validateNewCredentialsName({ name: input, baseUrl: baseUrl2 });
3959
4209
  return true;
3960
4210
  } catch (err) {
3961
4211
  return err instanceof Error ? err.message : String(err);
@@ -3963,7 +4213,7 @@ async function promptCredentialsName({
3963
4213
  }
3964
4214
  }
3965
4215
  ]);
3966
- return validateCredentialsName(credentialName);
4216
+ return validateNewCredentialsName({ name: credentialName, baseUrl: baseUrl2 });
3967
4217
  }
3968
4218
  function resolveDefaultCredentialsName({
3969
4219
  email
@@ -3979,7 +4229,8 @@ async function resolveCredentialName({
3979
4229
  if (interactive) {
3980
4230
  return promptCredentialsName({
3981
4231
  email,
3982
- promptMessage: getCredentialsPromptMessage(entryPoint)
4232
+ promptMessage: getCredentialsPromptMessage(entryPoint),
4233
+ baseUrl: baseUrl2
3983
4234
  });
3984
4235
  }
3985
4236
  const baseName = resolveDefaultCredentialsName({ email });
@@ -4020,6 +4271,11 @@ function promptlessCredentialResetError(credentials2) {
4020
4271
  `Already logged in as "${credentials2.name}". Run \`logout\` first or use an interactive terminal to re-authenticate.`
4021
4272
  );
4022
4273
  }
4274
+ function unnamedNonInteractiveLoginError(credentials2) {
4275
+ throw new ZapierCliValidationError(
4276
+ `Already logged in as "${credentials2.name}". Provide \`--name\` to activate or create named credentials, or run \`logout\` first.`
4277
+ );
4278
+ }
4023
4279
  function promptlessLegacyJwtUpgradeError() {
4024
4280
  throw new ZapierCliValidationError(
4025
4281
  "Legacy JWT login detected. Run `logout` first or use an interactive terminal to migrate to client credentials."
@@ -4029,16 +4285,20 @@ async function clearExistingAuthState({
4029
4285
  imports,
4030
4286
  baseUrl: baseUrl2,
4031
4287
  interactive,
4032
- entryPoint
4288
+ entryPoint,
4289
+ preserveExistingCredentials = false
4033
4290
  }) {
4034
4291
  const activeCredentials = getActiveCredentials({ baseUrl: baseUrl2 });
4035
4292
  const flowLabel = getEntryPointLabel(entryPoint);
4293
+ if (activeCredentials && (entryPoint === "login" || preserveExistingCredentials)) {
4294
+ return true;
4295
+ }
4036
4296
  if (activeCredentials) {
4037
4297
  const confirmed = interactive ? await promptConfirm2({
4038
4298
  defaultValue: false,
4039
4299
  message: `You are already logged in as "${activeCredentials.name}".
4040
4300
  Logging out will delete these credentials and may interrupt other Zapier SDK or CLI sessions using them.
4041
- Log out and ${getActiveCredentialsAction(entryPoint)}?`
4301
+ Log out and continue signup?`
4042
4302
  }) : promptlessCredentialResetError(activeCredentials);
4043
4303
  if (!confirmed) {
4044
4304
  process.stderr.write(`${flowLabel} cancelled.
@@ -4253,12 +4513,14 @@ async function provisionAccountCredentials({
4253
4513
  async function runAccountAuth({
4254
4514
  imports,
4255
4515
  options,
4256
- entryPoint
4516
+ entryPoint,
4517
+ storedCredentialsMode = "choose",
4518
+ preserveExistingCredentials = false
4257
4519
  }) {
4258
4520
  if (options.callbackUrl !== void 0) {
4259
4521
  const { callbackUrl } = options;
4260
4522
  const pending = getPendingOauthFlow({ entryPoint });
4261
- const finishName = options.name !== void 0 ? validateCredentialsName(options.name) : void 0;
4523
+ const finishName = options.name === void 0 ? void 0 : validateCredentialsName(options.name);
4262
4524
  if (finishName !== void 0 && finishName !== pending.credentialName) {
4263
4525
  throw new ZapierCliValidationError(
4264
4526
  "Cannot change --name while completing a pending OAuth flow. Start a new non-interactive login with the desired --name."
@@ -4318,7 +4580,6 @@ async function runAccountAuth({
4318
4580
  });
4319
4581
  return;
4320
4582
  }
4321
- const timeoutSeconds = parseTimeoutSeconds(options.timeout);
4322
4583
  const interactive = !resolveNonInteractive(options);
4323
4584
  const resolvedCredentials = await imports.resolveCredentials();
4324
4585
  const pkceCredentials = toPkceCredentials(resolvedCredentials);
@@ -4327,8 +4588,34 @@ async function runAccountAuth({
4327
4588
  options: imports.sdkOptions,
4328
4589
  resolvedCredentials
4329
4590
  });
4330
- const providedName = options.name !== void 0 ? validateCredentialsName(options.name) : void 0;
4331
- if (providedName !== void 0) {
4591
+ const providedName = options.name === void 0 ? void 0 : validateCredentialsName(options.name);
4592
+ if (entryPoint === "login") {
4593
+ if (providedName !== void 0) {
4594
+ const matchingCredentials = findStoredCredentialsByName({
4595
+ name: providedName,
4596
+ baseUrl: credentialsBaseUrl2
4597
+ });
4598
+ if (matchingCredentials) {
4599
+ await switchCredentials({
4600
+ credentials: matchingCredentials,
4601
+ options,
4602
+ resolvedCredentials
4603
+ });
4604
+ return;
4605
+ }
4606
+ if (interactive && !await confirmNewCredentialsName(providedName)) {
4607
+ process.stderr.write("Login cancelled.\n");
4608
+ return;
4609
+ }
4610
+ } else if (interactive && storedCredentialsMode === "choose") {
4611
+ const selection = await chooseStoredLoginCredentialsAtBaseUrl({
4612
+ baseUrl: credentialsBaseUrl2,
4613
+ options,
4614
+ resolvedCredentials
4615
+ });
4616
+ if (selection === "switch") return;
4617
+ }
4618
+ } else if (providedName !== void 0) {
4332
4619
  const activeCredentials = getActiveCredentials({
4333
4620
  baseUrl: credentialsBaseUrl2
4334
4621
  });
@@ -4338,14 +4625,22 @@ async function runAccountAuth({
4338
4625
  );
4339
4626
  }
4340
4627
  }
4628
+ if (entryPoint === "login" && !interactive && providedName === void 0) {
4629
+ const activeCredentials = getActiveCredentials({
4630
+ baseUrl: credentialsBaseUrl2
4631
+ });
4632
+ if (activeCredentials) unnamedNonInteractiveLoginError(activeCredentials);
4633
+ }
4341
4634
  if (!await clearExistingAuthState({
4342
4635
  imports,
4343
4636
  baseUrl: credentialsBaseUrl2,
4344
4637
  interactive,
4345
- entryPoint
4638
+ entryPoint,
4639
+ preserveExistingCredentials
4346
4640
  })) {
4347
4641
  return;
4348
4642
  }
4643
+ const timeoutSeconds = parseTimeoutSeconds(options.timeout);
4349
4644
  const useApprovals = options.useApprovals === true;
4350
4645
  if (!interactive) {
4351
4646
  await startPendingOauthFlow({
@@ -4382,7 +4677,7 @@ async function runAccountAuth({
4382
4677
  }
4383
4678
  var LoginSchema = zod.z.object({
4384
4679
  name: zod.z.string().optional().describe(
4385
- "Name to identify these credentials (defaults to <email>@<hostname>). Provide this to set a custom name without the interactive prompt."
4680
+ "Activate stored credentials with this name. If none exist, create new credentials with this name; interactive login asks for confirmation first."
4386
4681
  ),
4387
4682
  timeout: zod.z.string().optional().describe("Login timeout in seconds (default: 300)"),
4388
4683
  useApprovals: zod.z.boolean().optional().describe(
@@ -6178,7 +6473,7 @@ function buildTemplateVariables({
6178
6473
  };
6179
6474
  }
6180
6475
  function cleanupProject({ projectDir }) {
6181
- console.log("\n" + chalk8__default.default.yellow("!") + " Cleaning up...");
6476
+ console.log("\n" + chalk9__default.default.yellow("!") + " Cleaning up...");
6182
6477
  fs.rmSync(projectDir, { recursive: true, force: true });
6183
6478
  }
6184
6479
  async function withInterruptCleanup(cleanup, fn) {
@@ -6388,8 +6683,8 @@ function buildNextSteps({
6388
6683
  }
6389
6684
  function createConsoleDisplayHooks() {
6390
6685
  return {
6391
- onItemComplete: (message) => console.log(" " + chalk8__default.default.green("\u2713") + " " + chalk8__default.default.dim(message)),
6392
- onWarn: (message) => console.warn(chalk8__default.default.yellow("!") + " " + message),
6686
+ onItemComplete: (message) => console.log(" " + chalk9__default.default.green("\u2713") + " " + chalk9__default.default.dim(message)),
6687
+ onWarn: (message) => console.warn(chalk9__default.default.yellow("!") + " " + message),
6393
6688
  onStepStart: ({
6394
6689
  description,
6395
6690
  stepNumber,
@@ -6398,31 +6693,31 @@ function createConsoleDisplayHooks() {
6398
6693
  nonInteractive
6399
6694
  }) => {
6400
6695
  const progressMessage = `${description}...`;
6401
- const stepCounter = chalk8__default.default.dim(`${stepNumber}/${totalSteps}`);
6696
+ const stepCounter = chalk9__default.default.dim(`${stepNumber}/${totalSteps}`);
6402
6697
  if (nonInteractive) {
6403
6698
  console.log(
6404
- "\n" + chalk8__default.default.bold(`\u276F ${progressMessage}`) + " " + stepCounter + "\n"
6699
+ "\n" + chalk9__default.default.bold(`\u276F ${progressMessage}`) + " " + stepCounter + "\n"
6405
6700
  );
6406
6701
  } else {
6407
6702
  console.log(
6408
- chalk8__default.default.dim("\u2192") + " " + progressMessage + " " + stepCounter
6703
+ chalk9__default.default.dim("\u2192") + " " + progressMessage + " " + stepCounter
6409
6704
  );
6410
6705
  }
6411
6706
  if (command) {
6412
- console.log(" " + chalk8__default.default.cyan(`$ ${command}`));
6707
+ console.log(" " + chalk9__default.default.cyan(`$ ${command}`));
6413
6708
  }
6414
6709
  },
6415
6710
  onStepSuccess: ({ stepNumber, totalSteps }) => console.log(
6416
- "\n" + chalk8__default.default.green("\u2713") + " " + chalk8__default.default.dim(`Step ${stepNumber}/${totalSteps} complete`) + "\n"
6711
+ "\n" + chalk9__default.default.green("\u2713") + " " + chalk9__default.default.dim(`Step ${stepNumber}/${totalSteps} complete`) + "\n"
6417
6712
  ),
6418
6713
  onStepError: ({ description, command, err }) => {
6419
6714
  const detail = err instanceof Error && err.message ? `
6420
- ${chalk8__default.default.dim(err.message)}` : "";
6715
+ ${chalk9__default.default.dim(err.message)}` : "";
6421
6716
  const hint = command ? `
6422
- ${chalk8__default.default.dim("run manually:")} ${chalk8__default.default.cyan(`$ ${command}`)}` : "";
6717
+ ${chalk9__default.default.dim("run manually:")} ${chalk9__default.default.cyan(`$ ${command}`)}` : "";
6423
6718
  console.error(
6424
6719
  `
6425
- ${chalk8__default.default.red("\u2716")} ${chalk8__default.default.bold(description)}${chalk8__default.default.dim(" failed")}${detail}${hint}`
6720
+ ${chalk9__default.default.red("\u2716")} ${chalk9__default.default.bold(description)}${chalk9__default.default.dim(" failed")}${detail}${hint}`
6426
6721
  );
6427
6722
  }
6428
6723
  };
@@ -6434,22 +6729,22 @@ function displaySummaryAndNextSteps({
6434
6729
  packageManager
6435
6730
  }) {
6436
6731
  const formatStatus = (complete) => ({
6437
- icon: complete ? chalk8__default.default.green("\u2713") : chalk8__default.default.yellow("!"),
6438
- text: complete ? chalk8__default.default.green("Setup complete") : chalk8__default.default.yellow("Setup interrupted")
6732
+ icon: complete ? chalk9__default.default.green("\u2713") : chalk9__default.default.yellow("!"),
6733
+ text: complete ? chalk9__default.default.green("Setup complete") : chalk9__default.default.yellow("Setup interrupted")
6439
6734
  });
6440
- const formatNextStep = (step, i) => " " + chalk8__default.default.dim(`${i + 1}.`) + " " + chalk8__default.default.bold(step.description);
6441
- const formatCommand = (cmd) => " " + chalk8__default.default.cyan(`$ ${cmd}`);
6442
- const formatCompletedStep = (step) => " " + chalk8__default.default.green("\u2713") + " " + step.description;
6735
+ const formatNextStep = (step, i) => " " + chalk9__default.default.dim(`${i + 1}.`) + " " + chalk9__default.default.bold(step.description);
6736
+ const formatCommand = (cmd) => " " + chalk9__default.default.cyan(`$ ${cmd}`);
6737
+ const formatCompletedStep = (step) => " " + chalk9__default.default.green("\u2713") + " " + step.description;
6443
6738
  const { execCmd } = getPackageManagerCommands({ packageManager });
6444
6739
  const leftoverSteps = steps.filter(
6445
6740
  (s) => !completedSetupStepIds.includes(s.id)
6446
6741
  );
6447
6742
  const isComplete = leftoverSteps.length === 0;
6448
6743
  const status = formatStatus(isComplete);
6449
- console.log("\n" + chalk8__default.default.bold("\u276F Summary") + "\n");
6450
- console.log(" " + chalk8__default.default.dim("Project") + " " + chalk8__default.default.bold(projectName));
6744
+ console.log("\n" + chalk9__default.default.bold("\u276F Summary") + "\n");
6745
+ console.log(" " + chalk9__default.default.dim("Project") + " " + chalk9__default.default.bold(projectName));
6451
6746
  console.log(
6452
- " " + chalk8__default.default.dim("Status") + " " + status.icon + " " + status.text
6747
+ " " + chalk9__default.default.dim("Status") + " " + status.icon + " " + status.text
6453
6748
  );
6454
6749
  const completedSteps = steps.filter(
6455
6750
  (s) => completedSetupStepIds.includes(s.id)
@@ -6459,7 +6754,7 @@ function displaySummaryAndNextSteps({
6459
6754
  for (const step of completedSteps) console.log(formatCompletedStep(step));
6460
6755
  }
6461
6756
  const nextSteps = buildNextSteps({ projectName, leftoverSteps, execCmd });
6462
- console.log("\n" + chalk8__default.default.bold("\u276F Next Steps") + "\n");
6757
+ console.log("\n" + chalk9__default.default.bold("\u276F Next Steps") + "\n");
6463
6758
  nextSteps.forEach((step, i) => {
6464
6759
  console.log(formatNextStep(step, i));
6465
6760
  if (step.command) console.log(formatCommand(step.command));
@@ -6644,26 +6939,26 @@ function displayUpdateNotification(versionInfo, packageName) {
6644
6939
  if (versionInfo.isDeprecated) {
6645
6940
  console.error();
6646
6941
  console.error(
6647
- chalk8__default.default.red.bold("\u26A0\uFE0F DEPRECATION WARNING") + chalk8__default.default.red(
6942
+ chalk9__default.default.red.bold("\u26A0\uFE0F DEPRECATION WARNING") + chalk9__default.default.red(
6648
6943
  ` - ${packageName} v${versionInfo.currentVersion} is deprecated.`
6649
6944
  )
6650
6945
  );
6651
6946
  if (versionInfo.deprecationMessage) {
6652
- console.error(chalk8__default.default.red(` ${versionInfo.deprecationMessage}`));
6947
+ console.error(chalk9__default.default.red(` ${versionInfo.deprecationMessage}`));
6653
6948
  }
6654
- console.error(chalk8__default.default.red(` Please update to the latest version.`));
6949
+ console.error(chalk9__default.default.red(` Please update to the latest version.`));
6655
6950
  console.error();
6656
6951
  }
6657
6952
  if (versionInfo.hasUpdate) {
6658
6953
  console.error();
6659
6954
  console.error(
6660
- chalk8__default.default.yellow.bold("\u{1F4E6} Update available!") + chalk8__default.default.yellow(
6955
+ chalk9__default.default.yellow.bold("\u{1F4E6} Update available!") + chalk9__default.default.yellow(
6661
6956
  ` ${packageName} v${versionInfo.currentVersion} \u2192 v${versionInfo.latestVersion}`
6662
6957
  )
6663
6958
  );
6664
6959
  console.error(
6665
- chalk8__default.default.yellow(
6666
- ` Run ${chalk8__default.default.bold(getUpdateCommand(packageName))} to update.`
6960
+ chalk9__default.default.yellow(
6961
+ ` Run ${chalk9__default.default.bold(getUpdateCommand(packageName))} to update.`
6667
6962
  )
6668
6963
  );
6669
6964
  console.error();
@@ -6704,7 +6999,7 @@ var boltFillRanks = new Map(
6704
6999
  );
6705
7000
  var STATUS_ROW_INDEX = Math.floor(boltRows.length / 2);
6706
7001
  function formatPhase({ label, detail }) {
6707
- return detail ? `${chalk8__default.default.bold(label)} ${chalk8__default.default.dim(detail)}` : chalk8__default.default.bold(label);
7002
+ return detail ? `${chalk9__default.default.bold(label)} ${chalk9__default.default.dim(detail)}` : chalk9__default.default.bold(label);
6708
7003
  }
6709
7004
  function formatLoaderFrame({
6710
7005
  phase,
@@ -6716,7 +7011,7 @@ function formatLoaderFrame({
6716
7011
  const cellIndex = rowIndex * row.length + columnIndex;
6717
7012
  const fillRank = boltFillRanks.get(cellIndex);
6718
7013
  const isFilled = fillRank !== void 0 && fillRank < fillStage;
6719
- return isFilled ? chalk8__default.default.bold.yellow(cell) : chalk8__default.default.dim.yellow(cell);
7014
+ return isFilled ? chalk9__default.default.bold.yellow(cell) : chalk9__default.default.dim.yellow(cell);
6720
7015
  }).join("");
6721
7016
  const status = rowIndex === STATUS_ROW_INDEX ? ` ${formatPhase(phase)}` : "";
6722
7017
  return `${bolt}${status}`;
@@ -6748,12 +7043,12 @@ async function runWithSetupLoader({
6748
7043
  const result = await promise;
6749
7044
  clearInterval(animationTimer);
6750
7045
  const elapsedSeconds = ((Date.now() - startedAt) / 1e3).toFixed(1);
6751
- loader.succeed(`${formatPhase(phase)} ${chalk8__default.default.dim(`${elapsedSeconds}s`)}`);
7046
+ loader.succeed(`${formatPhase(phase)} ${chalk9__default.default.dim(`${elapsedSeconds}s`)}`);
6752
7047
  return result;
6753
7048
  } catch (error) {
6754
7049
  clearInterval(animationTimer);
6755
7050
  const elapsedSeconds = ((Date.now() - startedAt) / 1e3).toFixed(1);
6756
- loader.fail(`${formatPhase(phase)} ${chalk8__default.default.dim(`${elapsedSeconds}s`)}`);
7051
+ loader.fail(`${formatPhase(phase)} ${chalk9__default.default.dim(`${elapsedSeconds}s`)}`);
6757
7052
  throw error;
6758
7053
  }
6759
7054
  }
@@ -7244,7 +7539,7 @@ async function runCommand({
7244
7539
  detail: commandLabel
7245
7540
  });
7246
7541
  }
7247
- console.log(chalk8__default.default.dim(commandLabel));
7542
+ console.log(chalk9__default.default.dim(commandLabel));
7248
7543
  return await execute;
7249
7544
  } catch (error) {
7250
7545
  const message = error instanceof Error ? error.message : String(error);
@@ -7350,6 +7645,14 @@ function createWizardContext({
7350
7645
  imports,
7351
7646
  createAnswer: () => createCliAnswer({ mode: "closed-list" }),
7352
7647
  setupController: createSetupController(),
7648
+ selectStoredLoginCredentials: () => chooseStoredLoginCredentials({ imports, options: {} }),
7649
+ authenticateNewAccount: ({ entryPoint, headless }) => runAccountAuth({
7650
+ imports,
7651
+ options: { headless },
7652
+ entryPoint,
7653
+ storedCredentialsMode: "fresh",
7654
+ preserveExistingCredentials: true
7655
+ }),
7353
7656
  checkForUpdates,
7354
7657
  openUrl: async (url) => {
7355
7658
  await open__default.default(url);
@@ -7383,6 +7686,14 @@ function isCredentialWriteError(error) {
7383
7686
  const message = error instanceof Error ? error.message : String(error);
7384
7687
  return /permission|sandbox|eacces|eperm/i.test(message);
7385
7688
  }
7689
+ async function confirmAuthentication(context) {
7690
+ const { data: profile } = await runWithSetupLoader({
7691
+ promise: context.imports.getProfile({}),
7692
+ label: "Confirming Zapier account"
7693
+ });
7694
+ context.accountEmail = profile.email;
7695
+ console.log(`Authenticated as ${profile.email}.`);
7696
+ }
7386
7697
  async function authenticate(context) {
7387
7698
  const activeProfile = await runWithSetupLoader({
7388
7699
  promise: context.imports.getProfile({}).then(({ data }) => data).catch((error) => {
@@ -7391,7 +7702,12 @@ async function authenticate(context) {
7391
7702
  }),
7392
7703
  label: "Checking Zapier authentication"
7393
7704
  });
7394
- if (activeProfile) {
7705
+ const storedCredentialsSelection = await context.selectStoredLoginCredentials();
7706
+ if (storedCredentialsSelection === "switch") {
7707
+ await confirmAuthentication(context);
7708
+ return;
7709
+ }
7710
+ if (storedCredentialsSelection === "none" && activeProfile) {
7395
7711
  const shouldLogout = await resolveSetupConfirm({
7396
7712
  answer: context.createAnswer(),
7397
7713
  controller: context.setupController,
@@ -7432,10 +7748,14 @@ Log out and use a different account?`,
7432
7748
  ]
7433
7749
  });
7434
7750
  const headless = environment === "headless";
7435
- const runAuth = flow === "login" ? context.imports.login : context.imports.signup;
7436
7751
  printAuthCommand({ context, flow, headless });
7437
7752
  try {
7438
- await runAuth({ headless });
7753
+ if (storedCredentialsSelection === "create") {
7754
+ await context.authenticateNewAccount({ entryPoint: flow, headless });
7755
+ } else {
7756
+ const runAuth = flow === "login" ? context.imports.login : context.imports.signup;
7757
+ await runAuth({ headless });
7758
+ }
7439
7759
  } catch (error) {
7440
7760
  if (isCredentialWriteError(error)) {
7441
7761
  console.error(
@@ -7444,12 +7764,7 @@ Log out and use a different account?`,
7444
7764
  }
7445
7765
  throw error;
7446
7766
  }
7447
- const { data: profile } = await runWithSetupLoader({
7448
- promise: context.imports.getProfile({}),
7449
- label: "Confirming Zapier account"
7450
- });
7451
- context.accountEmail = profile.email;
7452
- console.log(`Authenticated as ${profile.email}.`);
7767
+ await confirmAuthentication(context);
7453
7768
  }
7454
7769
  var agentLabels = {
7455
7770
  claude: "Claude Code",
@@ -7491,7 +7806,7 @@ function printAgentPrompt({
7491
7806
  message
7492
7807
  }) {
7493
7808
  console.log();
7494
- console.log(chalk8__default.default.bgYellow.black.bold(message));
7809
+ console.log(chalk9__default.default.bgYellow.black.bold(message));
7495
7810
  console.log();
7496
7811
  console.log(buildAgentPrompt({ context }));
7497
7812
  }
@@ -7776,7 +8091,7 @@ var MINIMUM_MESSAGE_WIDTH = 20;
7776
8091
  var MAXIMUM_MESSAGE_WIDTH = 88;
7777
8092
  function showPhase({ number, title }) {
7778
8093
  console.log();
7779
- console.log(chalk8__default.default.bgCyan.black.bold(` ${number}/${PHASE_COUNT} ${title} `));
8094
+ console.log(chalk9__default.default.bgCyan.black.bold(` ${number}/${PHASE_COUNT} ${title} `));
7780
8095
  }
7781
8096
  function printWrapped(text) {
7782
8097
  const width = Math.max(
@@ -7790,7 +8105,7 @@ function printWrapped(text) {
7790
8105
  }
7791
8106
  function showReadyMessage() {
7792
8107
  console.log();
7793
- console.log(chalk8__default.default.bgGreen.black.bold(" \u2713 Zapier SDK setup complete "));
8108
+ console.log(chalk9__default.default.bgGreen.black.bold(" \u2713 Zapier SDK setup complete "));
7794
8109
  console.log();
7795
8110
  printWrapped(
7796
8111
  "Use active Zapier connections to access 9,000+ app connectors without managing each app's OAuth, token refresh, or retries."
@@ -7802,7 +8117,7 @@ function showReadyMessage() {
7802
8117
  console.log();
7803
8118
  }
7804
8119
  async function runWizard(context) {
7805
- console.log(chalk8__default.default.bold("Zapier SDK setup"));
8120
+ console.log(chalk9__default.default.bold("Zapier SDK setup"));
7806
8121
  showPhase({ number: 1, title: "Project directory" });
7807
8122
  await chooseDirectory(context);
7808
8123
  showPhase({ number: 2, title: "Node.js" });
@@ -7817,7 +8132,7 @@ async function runWizard(context) {
7817
8132
  showPhase({ number: 6, title: "Slack demo" });
7818
8133
  await offerSlackTest(context);
7819
8134
  showReadyMessage();
7820
- console.log(chalk8__default.default.bgCyan.black.bold(" Next steps "));
8135
+ console.log(chalk9__default.default.bgCyan.black.bold(" Next steps "));
7821
8136
  await openAgentHandoff(context);
7822
8137
  }
7823
8138
 
@@ -7832,7 +8147,11 @@ var setupImports = [
7832
8147
  listConnectionsRef2,
7833
8148
  loginRef,
7834
8149
  logoutRef,
7835
- signupRef
8150
+ signupRef,
8151
+ zapierSdk.apiPluginRef,
8152
+ zapierSdk.resolveCredentialsPluginRef,
8153
+ zapierSdk.eventEmissionPluginRef,
8154
+ zapierSdk.sdkOptionsPluginRef
7836
8155
  ];
7837
8156
  var setupPlugin = zapierSdk.defineMethod({
7838
8157
  name: "setup",
@@ -7863,13 +8182,13 @@ function createInteractiveCallback() {
7863
8182
  const attrs = message.message_attributes;
7864
8183
  console.log(
7865
8184
  `
7866
- ${chalk8__default.default.bold(`Message #${messageNumber}`)} ${chalk8__default.default.dim(message.id)} ${chalk8__default.default.dim(`(lease #${attrs.lease_count})`)}`
8185
+ ${chalk9__default.default.bold(`Message #${messageNumber}`)} ${chalk9__default.default.dim(message.id)} ${chalk9__default.default.dim(`(lease #${attrs.lease_count})`)}`
7867
8186
  );
7868
8187
  if (attrs.error_message) {
7869
- console.log(chalk8__default.default.yellow(` upstream error: ${attrs.error_message}`));
8188
+ console.log(chalk9__default.default.yellow(` upstream error: ${attrs.error_message}`));
7870
8189
  }
7871
8190
  if (attrs.possible_duplicate_data) {
7872
- console.log(chalk8__default.default.yellow(" possible duplicate data"));
8191
+ console.log(chalk9__default.default.yellow(" possible duplicate data"));
7873
8192
  }
7874
8193
  while (true) {
7875
8194
  let action;
@@ -7899,7 +8218,7 @@ ${chalk8__default.default.bold(`Message #${messageNumber}`)} ${chalk8__default.d
7899
8218
  throw error;
7900
8219
  }
7901
8220
  if (action === "view") {
7902
- console.log(chalk8__default.default.dim(JSON.stringify(message.payload, null, 2)));
8221
+ console.log(chalk9__default.default.dim(JSON.stringify(message.payload, null, 2)));
7903
8222
  continue;
7904
8223
  }
7905
8224
  if (action === "ack") {
@@ -8002,7 +8321,7 @@ function describeReason(reason) {
8002
8321
  }
8003
8322
  function printDrainError(reason, message) {
8004
8323
  console.error(
8005
- chalk8__default.default.red(`Error processing ${message.id}: ${describeReason(reason)}`)
8324
+ chalk9__default.default.red(`Error processing ${message.id}: ${describeReason(reason)}`)
8006
8325
  );
8007
8326
  }
8008
8327
  function printDrainSummary(counts) {
@@ -8012,7 +8331,7 @@ function printDrainSummary(counts) {
8012
8331
  if (skipped > 0) parts.push(`${skipped} skipped`);
8013
8332
  parts.push(`${counts.rejected} rejected`);
8014
8333
  console.log(
8015
- chalk8__default.default.dim(
8334
+ chalk9__default.default.dim(
8016
8335
  `
8017
8336
  Processed ${total} message${total === 1 ? "" : "s"} (${parts.join(", ")}).`
8018
8337
  )
@@ -8020,7 +8339,7 @@ Processed ${total} message${total === 1 ? "" : "s"} (${parts.join(", ")}).`
8020
8339
  }
8021
8340
  function warnInteractiveContinueOnErrorOverride() {
8022
8341
  console.warn(
8023
- chalk8__default.default.yellow(
8342
+ chalk9__default.default.yellow(
8024
8343
  'Note: continueOnError=false is overridden to true in interactive mode (the "Skip (let lease expire)" choice would otherwise terminate the drain).'
8025
8344
  )
8026
8345
  );
@@ -8346,7 +8665,7 @@ function renderDeprecationNotices() {
8346
8665
  console.error();
8347
8666
  for (const message of messages) {
8348
8667
  for (const line of buildBoxLines(message)) {
8349
- console.error(chalk8__default.default.red.bold(line));
8668
+ console.error(chalk9__default.default.red.bold(line));
8350
8669
  }
8351
8670
  console.error();
8352
8671
  }
@@ -8367,7 +8686,7 @@ function buildBoxLines(message) {
8367
8686
  // package.json with { type: 'json' }
8368
8687
  var package_default2 = {
8369
8688
  name: "@zapier/zapier-sdk-cli",
8370
- version: "0.77.9"};
8689
+ version: "0.78.0"};
8371
8690
 
8372
8691
  // src/sdk.ts
8373
8692
  var warnedDeprecatedMethods = /* @__PURE__ */ new Set();
@@ -8378,9 +8697,9 @@ var cliCoreOptions = {
8378
8697
  warnedDeprecatedMethods.add(methodName);
8379
8698
  console.warn();
8380
8699
  console.warn(
8381
- chalk8__default.default.yellow.bold("\u26A0\uFE0F DEPRECATION WARNING") + chalk8__default.default.yellow(` - \`${toKebabCase(methodName)}\` is deprecated.`)
8700
+ chalk9__default.default.yellow.bold("\u26A0\uFE0F DEPRECATION WARNING") + chalk9__default.default.yellow(` - \`${toKebabCase(methodName)}\` is deprecated.`)
8382
8701
  );
8383
- console.warn(chalk8__default.default.yellow(` ${deprecation.message}`));
8702
+ console.warn(chalk9__default.default.yellow(` ${deprecation.message}`));
8384
8703
  console.warn();
8385
8704
  }
8386
8705
  };
@@ -8653,11 +8972,11 @@ function buildFrameLines(state, frameIndex) {
8653
8972
  const bodyWidth = width - 2;
8654
8973
  const bodyTextWidth = innerWidth - 2;
8655
8974
  const content = [];
8656
- content.push(chalk8__default.default.bold.cyan("Approval review"));
8975
+ content.push(chalk9__default.default.bold.cyan("Approval review"));
8657
8976
  content.push("");
8658
8977
  if (!state.verdict) {
8659
8978
  content.push(
8660
- chalk8__default.default.yellow(`${SPINNER_FRAMES[frameIndex]} Checking approval...`)
8979
+ chalk9__default.default.yellow(`${SPINNER_FRAMES[frameIndex]} Checking approval...`)
8661
8980
  );
8662
8981
  }
8663
8982
  const recentMessages = state.messages.slice(-5);
@@ -8668,13 +8987,13 @@ function buildFrameLines(state, frameIndex) {
8668
8987
  "\n"
8669
8988
  );
8670
8989
  segments.forEach((segment, segmentIndex) => {
8671
- const prefix = segmentIndex === 0 ? chalk8__default.default.cyan("> ") : " ";
8672
- content.push(`${prefix}${dimmed ? chalk8__default.default.dim(segment) : segment}`);
8990
+ const prefix = segmentIndex === 0 ? chalk9__default.default.cyan("> ") : " ";
8991
+ content.push(`${prefix}${dimmed ? chalk9__default.default.dim(segment) : segment}`);
8673
8992
  });
8674
8993
  });
8675
8994
  if (state.streamError) {
8676
8995
  if (hasMessages || !state.verdict) content.push("");
8677
- content.push(chalk8__default.default.bold.red("Approval stream error"));
8996
+ content.push(chalk9__default.default.bold.red("Approval stream error"));
8678
8997
  for (const segment of wrapAnsi4__default.default(state.streamError, bodyTextWidth, {
8679
8998
  hard: true
8680
8999
  }).split("\n")) {
@@ -8684,7 +9003,7 @@ function buildFrameLines(state, frameIndex) {
8684
9003
  if (state.verdict) {
8685
9004
  if (hasMessages || state.streamError) content.push("");
8686
9005
  content.push(
8687
- chalk8__default.default.bold.green(`${state.verdict.icon} ${state.verdict.label}`)
9006
+ chalk9__default.default.bold.green(`${state.verdict.icon} ${state.verdict.label}`)
8688
9007
  );
8689
9008
  if (state.verdict.reason) {
8690
9009
  for (const segment of wrapAnsi4__default.default(state.verdict.reason, bodyTextWidth, {
@@ -8696,12 +9015,12 @@ function buildFrameLines(state, frameIndex) {
8696
9015
  }
8697
9016
  const pad = (line) => {
8698
9017
  const padding = " ".repeat(Math.max(0, innerWidth - displayWidth(line)));
8699
- return `${chalk8__default.default.cyan("\u2502")} ${line}${padding} ${chalk8__default.default.cyan("\u2502")}`;
9018
+ return `${chalk9__default.default.cyan("\u2502")} ${line}${padding} ${chalk9__default.default.cyan("\u2502")}`;
8700
9019
  };
8701
9020
  return [
8702
- chalk8__default.default.cyan(`\u256D${"\u2500".repeat(bodyWidth)}\u256E`),
9021
+ chalk9__default.default.cyan(`\u256D${"\u2500".repeat(bodyWidth)}\u256E`),
8703
9022
  ...content.map(pad),
8704
- chalk8__default.default.cyan(`\u2570${"\u2500".repeat(bodyWidth)}\u256F`)
9023
+ chalk9__default.default.cyan(`\u2570${"\u2500".repeat(bodyWidth)}\u256F`)
8705
9024
  ];
8706
9025
  }
8707
9026
  function createApprovalProgressRenderer({