@zapier/zapier-sdk-cli 0.34.12 → 0.35.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 zod = require('zod');
6
6
  var zapierSdk = require('@zapier/zapier-sdk');
7
7
  var inquirer = require('inquirer');
8
- var chalk3 = require('chalk');
8
+ var chalk7 = require('chalk');
9
9
  var util = require('util');
10
10
  var cliLogin = require('@zapier/zapier-sdk-cli-login');
11
11
  var open = require('open');
@@ -48,7 +48,7 @@ function _interopNamespace(e) {
48
48
  }
49
49
 
50
50
  var inquirer__default = /*#__PURE__*/_interopDefault(inquirer);
51
- var chalk3__default = /*#__PURE__*/_interopDefault(chalk3);
51
+ var chalk7__default = /*#__PURE__*/_interopDefault(chalk7);
52
52
  var util__default = /*#__PURE__*/_interopDefault(util);
53
53
  var cliLogin__namespace = /*#__PURE__*/_interopNamespace(cliLogin);
54
54
  var open__default = /*#__PURE__*/_interopDefault(open);
@@ -82,8 +82,33 @@ var ZapierCliExitError = class extends ZapierCliError {
82
82
  this.exitCode = exitCode;
83
83
  }
84
84
  };
85
+ var ZapierCliValidationError = class extends ZapierCliError {
86
+ constructor(message) {
87
+ super(message);
88
+ this.name = "ZapierCliValidationError";
89
+ this.code = "ZAPIER_CLI_VALIDATION_ERROR";
90
+ this.exitCode = 1;
91
+ }
92
+ };
93
+ var ZapierCliMissingParametersError = class extends ZapierCliError {
94
+ constructor(params) {
95
+ super(
96
+ `Missing required parameters: ${params.map((p) => p.name).join(", ")}`
97
+ );
98
+ this.name = "ZapierCliMissingParametersError";
99
+ this.code = "ZAPIER_CLI_MISSING_PARAMETERS";
100
+ this.exitCode = 1;
101
+ this.params = params;
102
+ }
103
+ };
85
104
 
86
105
  // src/utils/parameter-resolver.ts
106
+ function formatZodError(error) {
107
+ return error.issues.map((issue) => {
108
+ const field = issue.path.length > 0 ? issue.path.join(".") : "input";
109
+ return `${field}: ${issue.message}`;
110
+ }).join(", ");
111
+ }
87
112
  function getLocalResolutionOrder(paramName, resolvers, resolved = /* @__PURE__ */ new Set()) {
88
113
  const resolver = resolvers[paramName];
89
114
  if (!resolver || resolver.type === "static") {
@@ -118,8 +143,9 @@ function getLocalResolutionOrderForParams(paramNames, resolvers) {
118
143
  return order;
119
144
  }
120
145
  var SchemaParameterResolver = class {
121
- async resolveParameters(schema, providedParams, sdk2, functionName) {
146
+ async resolveParameters(schema, providedParams, sdk2, functionName, options) {
122
147
  return zapierSdk.runWithTelemetryContext(async () => {
148
+ const interactiveMode = options?.interactiveMode ?? true;
123
149
  const parseResult = schema.safeParse(providedParams);
124
150
  const allParams = this.extractParametersFromSchema(schema);
125
151
  const resolvableParams = allParams.filter(
@@ -132,7 +158,7 @@ var SchemaParameterResolver = class {
132
158
  const functionallyRequired = missingResolvable.filter((param) => {
133
159
  if (param.isRequired) return true;
134
160
  if (param.name === "inputs") {
135
- return true;
161
+ return interactiveMode;
136
162
  }
137
163
  return false;
138
164
  });
@@ -151,7 +177,7 @@ var SchemaParameterResolver = class {
151
177
  }
152
178
  if (functionallyRequired.length === 0 && alwaysPrompt.length === 0) {
153
179
  if (!parseResult.success) {
154
- throw parseResult.error;
180
+ throw new ZapierCliValidationError(formatZodError(parseResult.error));
155
181
  }
156
182
  return parseResult.data;
157
183
  }
@@ -179,21 +205,30 @@ var SchemaParameterResolver = class {
179
205
  }
180
206
  return param;
181
207
  }).filter((param) => param !== void 0);
182
- for (const param of orderedRequiredParams) {
183
- try {
184
- const value = await this.resolveParameter(
185
- param,
186
- context,
187
- functionName
188
- );
189
- this.setNestedValue(resolvedParams, param.path, value);
190
- context.resolvedParams = resolvedParams;
191
- } catch (error) {
192
- if (this.isUserCancellation(error)) {
193
- console.log(chalk3__default.default.yellow("\n\nOperation cancelled by user"));
194
- throw new ZapierCliUserCancellationError();
208
+ if (!interactiveMode) {
209
+ await this.resolveRequiredParamsNonInteractive(
210
+ orderedRequiredParams,
211
+ context,
212
+ resolvedParams,
213
+ functionName
214
+ );
215
+ } else {
216
+ for (const param of orderedRequiredParams) {
217
+ try {
218
+ const value = await this.resolveParameter(
219
+ param,
220
+ context,
221
+ functionName
222
+ );
223
+ this.setNestedValue(resolvedParams, param.path, value);
224
+ context.resolvedParams = resolvedParams;
225
+ } catch (error) {
226
+ if (this.isUserCancellation(error)) {
227
+ console.log(chalk7__default.default.yellow("\n\nOperation cancelled by user"));
228
+ throw new ZapierCliUserCancellationError();
229
+ }
230
+ throw error;
195
231
  }
196
- throw error;
197
232
  }
198
233
  }
199
234
  const resolvedParamNames = new Set(
@@ -210,7 +245,7 @@ var SchemaParameterResolver = class {
210
245
  ...trulyOptional.filter((p) => !resolvedParamNames.has(p.name))
211
246
  );
212
247
  }
213
- if (alwaysPrompt.length > 0) {
248
+ if (interactiveMode && alwaysPrompt.length > 0) {
214
249
  const alwaysPromptNames = alwaysPrompt.map((p) => p.name);
215
250
  const alwaysPromptResolutionOrder = getLocalResolutionOrderForParams(
216
251
  alwaysPromptNames,
@@ -228,14 +263,14 @@ var SchemaParameterResolver = class {
228
263
  context.resolvedParams = resolvedParams;
229
264
  } catch (error) {
230
265
  if (this.isUserCancellation(error)) {
231
- console.log(chalk3__default.default.yellow("\n\nOperation cancelled by user"));
266
+ console.log(chalk7__default.default.yellow("\n\nOperation cancelled by user"));
232
267
  throw new ZapierCliUserCancellationError();
233
268
  }
234
269
  throw error;
235
270
  }
236
271
  }
237
272
  }
238
- if (trulyOptional.length > 0) {
273
+ if (interactiveMode && trulyOptional.length > 0) {
239
274
  const optionalNames = trulyOptional.map((p) => p.name).join(", ");
240
275
  const shouldResolveOptional = await inquirer__default.default.prompt([
241
276
  {
@@ -265,7 +300,7 @@ var SchemaParameterResolver = class {
265
300
  context.resolvedParams = resolvedParams;
266
301
  } catch (error) {
267
302
  if (this.isUserCancellation(error)) {
268
- console.log(chalk3__default.default.yellow("\n\nOperation cancelled by user"));
303
+ console.log(chalk7__default.default.yellow("\n\nOperation cancelled by user"));
269
304
  throw new ZapierCliUserCancellationError();
270
305
  }
271
306
  throw error;
@@ -275,10 +310,9 @@ var SchemaParameterResolver = class {
275
310
  }
276
311
  const finalResult = schema.safeParse(resolvedParams);
277
312
  if (!finalResult.success) {
278
- console.error(
279
- chalk3__default.default.red("\u274C Parameter validation failed after resolution:")
313
+ throw new ZapierCliValidationError(
314
+ `Parameter validation failed: ${formatZodError(finalResult.error)}`
280
315
  );
281
- throw finalResult.error;
282
316
  }
283
317
  return finalResult.data;
284
318
  });
@@ -320,6 +354,54 @@ var SchemaParameterResolver = class {
320
354
  isRequired
321
355
  };
322
356
  }
357
+ /**
358
+ * Calls `tryResolveWithoutPrompt` on a dynamic resolver.
359
+ * Returns the resolution result object, or null if unresolvable / throws.
360
+ * Note: { resolvedValue: null } is a valid result (e.g. connectionId when app has no auth);
361
+ * only a null return from the resolver itself means "could not auto-resolve".
362
+ */
363
+ async tryAutoResolve(dynamicResolver, context) {
364
+ if (!dynamicResolver.tryResolveWithoutPrompt) return null;
365
+ try {
366
+ return await dynamicResolver.tryResolveWithoutPrompt(
367
+ context.sdk,
368
+ context.resolvedParams
369
+ );
370
+ } catch (err) {
371
+ console.warn(
372
+ `Auto-resolver threw unexpectedly; treating as unresolved. Error: ${err instanceof Error ? err.message : String(err)}`
373
+ );
374
+ return null;
375
+ }
376
+ }
377
+ /**
378
+ * Non-interactive resolution: auto-resolves what it can via tryAutoResolve,
379
+ * throws ZapierCliMissingParametersError for anything that requires user input.
380
+ */
381
+ async resolveRequiredParamsNonInteractive(params, context, resolvedParams, functionName) {
382
+ const missingParams = [];
383
+ for (const param of params) {
384
+ const resolver = this.getResolver(param.name, context.sdk, functionName);
385
+ const autoResolution = resolver?.type === "dynamic" ? await this.tryAutoResolve(resolver, context) : null;
386
+ if (autoResolution != null) {
387
+ this.setNestedValue(
388
+ resolvedParams,
389
+ param.path,
390
+ autoResolution.resolvedValue
391
+ );
392
+ context.resolvedParams = resolvedParams;
393
+ } else {
394
+ missingParams.push({
395
+ name: param.name,
396
+ // Required params render as positional CLI args (<name>); so do explicitly positional optional params.
397
+ isPositional: param.isRequired || zapierSdk.isPositional(param.schema)
398
+ });
399
+ }
400
+ }
401
+ if (missingParams.length > 0) {
402
+ throw new ZapierCliMissingParametersError(missingParams);
403
+ }
404
+ }
323
405
  async resolveParameter(param, context, functionName) {
324
406
  const resolver = this.getResolver(
325
407
  param.name,
@@ -329,7 +411,7 @@ var SchemaParameterResolver = class {
329
411
  if (!resolver) {
330
412
  throw new Error(`No resolver found for parameter: ${param.name}`);
331
413
  }
332
- console.log(chalk3__default.default.blue(`
414
+ console.log(chalk7__default.default.blue(`
333
415
  \u{1F50D} Resolving ${param.name}...`));
334
416
  if (resolver.type === "static") {
335
417
  const staticResolver = resolver;
@@ -345,20 +427,15 @@ var SchemaParameterResolver = class {
345
427
  return answers[param.name];
346
428
  } else if (resolver.type === "dynamic") {
347
429
  const dynamicResolver = resolver;
348
- if (dynamicResolver.tryResolveWithoutPrompt) {
349
- try {
350
- const preResolvedValue = await dynamicResolver.tryResolveWithoutPrompt(
351
- context.sdk,
352
- context.resolvedParams
353
- );
354
- if (preResolvedValue != null) {
355
- return preResolvedValue.resolvedValue;
356
- }
357
- } catch {
358
- }
430
+ const autoResolution = await this.tryAutoResolve(
431
+ dynamicResolver,
432
+ context
433
+ );
434
+ if (autoResolution != null) {
435
+ return autoResolution.resolvedValue;
359
436
  }
360
437
  if (param.isRequired && param.name !== "connectionId") {
361
- console.log(chalk3__default.default.gray(`Fetching options for ${param.name}...`));
438
+ console.log(chalk7__default.default.gray(`Fetching options for ${param.name}...`));
362
439
  }
363
440
  const items = await dynamicResolver.fetch(
364
441
  context.sdk,
@@ -395,7 +472,7 @@ var SchemaParameterResolver = class {
395
472
  }
396
473
  };
397
474
  console.log(
398
- chalk3__default.default.gray(
475
+ chalk7__default.default.gray(
399
476
  `Fetching input fields for ${param.name}${iteration > 1 ? ` (iteration ${iteration})` : ""}...`
400
477
  )
401
478
  );
@@ -406,7 +483,7 @@ var SchemaParameterResolver = class {
406
483
  if (!rootFieldItems || rootFieldItems.length === 0) {
407
484
  if (iteration === 1) {
408
485
  console.log(
409
- chalk3__default.default.yellow(`No input fields required for this action.`)
486
+ chalk7__default.default.yellow(`No input fields required for this action.`)
410
487
  );
411
488
  }
412
489
  break;
@@ -428,7 +505,7 @@ var SchemaParameterResolver = class {
428
505
  }
429
506
  if (iteration >= maxIterations) {
430
507
  console.log(
431
- chalk3__default.default.yellow(
508
+ chalk7__default.default.yellow(
432
509
  `
433
510
  \u26A0\uFE0F Maximum field resolution iterations reached. Some dynamic fields may not have been discovered.`
434
511
  )
@@ -450,7 +527,7 @@ var SchemaParameterResolver = class {
450
527
  const fieldsetTitle = typedItem.title || typedItem.key;
451
528
  const pathDisplay = fieldsetPath.length > 0 ? ` (in ${fieldsetPath.join(" > ")})` : "";
452
529
  console.log(
453
- chalk3__default.default.cyan(
530
+ chalk7__default.default.cyan(
454
531
  `
455
532
  \u{1F4C1} Processing fieldset: ${fieldsetTitle}${pathDisplay}`
456
533
  )
@@ -482,7 +559,7 @@ var SchemaParameterResolver = class {
482
559
  newRequiredCount++;
483
560
  if (newRequiredCount === 1 && fieldsetPath.length === 0) {
484
561
  console.log(
485
- chalk3__default.default.blue(
562
+ chalk7__default.default.blue(
486
563
  `
487
564
  \u{1F4DD} Please provide values for the following ${iteration === 1 ? "" : "additional "}input fields:`
488
565
  )
@@ -503,7 +580,7 @@ var SchemaParameterResolver = class {
503
580
  if (optionalFields.length > 0) {
504
581
  const pathContext = fieldsetPath.length > 0 ? ` in ${fieldsetPath.join(" > ")}` : "";
505
582
  console.log(
506
- chalk3__default.default.gray(
583
+ chalk7__default.default.gray(
507
584
  `
508
585
  There are ${optionalFields.length} ${iteration === 1 ? "" : "additional "}optional field(s) available${pathContext}.`
509
586
  )
@@ -518,7 +595,7 @@ There are ${optionalFields.length} ${iteration === 1 ? "" : "additional "}option
518
595
  }
519
596
  ]);
520
597
  if (shouldConfigureOptional.configure) {
521
- console.log(chalk3__default.default.cyan(`
598
+ console.log(chalk7__default.default.cyan(`
522
599
  Optional fields${pathContext}:`));
523
600
  for (const field of optionalFields) {
524
601
  await this.promptForField(field, targetInputs, context);
@@ -534,7 +611,7 @@ Optional fields${pathContext}:`));
534
611
  }
535
612
  } catch (error) {
536
613
  if (this.isUserCancellation(error)) {
537
- console.log(chalk3__default.default.yellow("\n\nOperation cancelled by user"));
614
+ console.log(chalk7__default.default.yellow("\n\nOperation cancelled by user"));
538
615
  throw new ZapierCliUserCancellationError();
539
616
  }
540
617
  throw error;
@@ -589,7 +666,7 @@ Optional fields${pathContext}:`));
589
666
  async fetchChoices(fieldMeta, inputs, context, cursor) {
590
667
  try {
591
668
  console.log(
592
- chalk3__default.default.gray(
669
+ chalk7__default.default.gray(
593
670
  cursor ? ` Fetching more choices...` : ` Fetching choices for ${fieldMeta.title}...`
594
671
  )
595
672
  );
@@ -608,7 +685,7 @@ Optional fields${pathContext}:`));
608
685
  }));
609
686
  if (choices.length === 0 && !cursor) {
610
687
  console.log(
611
- chalk3__default.default.yellow(` No choices available for ${fieldMeta.title}`)
688
+ chalk7__default.default.yellow(` No choices available for ${fieldMeta.title}`)
612
689
  );
613
690
  }
614
691
  return {
@@ -617,7 +694,7 @@ Optional fields${pathContext}:`));
617
694
  };
618
695
  } catch (error) {
619
696
  console.warn(
620
- chalk3__default.default.yellow(` \u26A0\uFE0F Failed to fetch choices for ${fieldMeta.title}:`),
697
+ chalk7__default.default.yellow(` \u26A0\uFE0F Failed to fetch choices for ${fieldMeta.title}:`),
621
698
  error
622
699
  );
623
700
  return { choices: [] };
@@ -643,7 +720,7 @@ Optional fields${pathContext}:`));
643
720
  }));
644
721
  if (nextCursor) {
645
722
  promptChoices.push({
646
- name: chalk3__default.default.dim("(Load more...)"),
723
+ name: chalk7__default.default.dim("(Load more...)"),
647
724
  value: LOAD_MORE_SENTINEL
648
725
  });
649
726
  }
@@ -706,7 +783,7 @@ Optional fields${pathContext}:`));
706
783
  };
707
784
  }
708
785
  if (fieldMeta.description) {
709
- promptConfig.prefix = chalk3__default.default.gray(`\u2139 ${fieldMeta.description}
786
+ promptConfig.prefix = chalk7__default.default.gray(`\u2139 ${fieldMeta.description}
710
787
  `);
711
788
  }
712
789
  try {
@@ -714,7 +791,7 @@ Optional fields${pathContext}:`));
714
791
  return answer[fieldMeta.key];
715
792
  } catch (error) {
716
793
  if (this.isUserCancellation(error)) {
717
- console.log(chalk3__default.default.yellow("\n\nOperation cancelled by user"));
794
+ console.log(chalk7__default.default.yellow("\n\nOperation cancelled by user"));
718
795
  throw new ZapierCliUserCancellationError();
719
796
  }
720
797
  throw error;
@@ -732,7 +809,7 @@ Optional fields${pathContext}:`));
732
809
  }
733
810
  } catch (error) {
734
811
  if (this.isUserCancellation(error)) {
735
- console.log(chalk3__default.default.yellow("\n\nOperation cancelled by user"));
812
+ console.log(chalk7__default.default.yellow("\n\nOperation cancelled by user"));
736
813
  throw new ZapierCliUserCancellationError();
737
814
  }
738
815
  throw error;
@@ -805,6 +882,91 @@ Optional fields${pathContext}:`));
805
882
  return functionInfo?.resolvers || {};
806
883
  }
807
884
  };
885
+
886
+ // src/utils/cli-options.ts
887
+ var RESERVED_CLI_OPTIONS = [
888
+ {
889
+ name: "version" /* Version */,
890
+ flag: "--version",
891
+ short: "-V",
892
+ description: "Display version number"
893
+ },
894
+ {
895
+ name: "help" /* Help */,
896
+ flag: "--help",
897
+ short: "-h",
898
+ description: "Display help for command"
899
+ }
900
+ ];
901
+ function getReservedCliOption(name) {
902
+ const option = RESERVED_CLI_OPTIONS.find((opt) => opt.name === name);
903
+ if (!option) throw new Error(`Reserved CLI option not found: ${name}`);
904
+ return option;
905
+ }
906
+ var SHARED_COMMAND_CLI_OPTIONS = [
907
+ {
908
+ name: "json",
909
+ flag: "--json",
910
+ description: "Output raw JSON instead of formatted results"
911
+ }
912
+ ];
913
+
914
+ // package.json
915
+ var package_default = {
916
+ version: "0.35.0"};
917
+
918
+ // src/telemetry/builders.ts
919
+ function createCliBaseEvent(context = {}) {
920
+ return {
921
+ event_id: zapierSdk.generateEventId(),
922
+ timestamp_ms: zapierSdk.getCurrentTimestamp(),
923
+ release_id: zapierSdk.getReleaseId(),
924
+ customuser_id: context.customuser_id ?? null,
925
+ account_id: context.account_id ?? null,
926
+ identity_id: context.identity_id ?? null,
927
+ visitor_id: context.visitor_id ?? null,
928
+ correlation_id: context.correlation_id ?? null
929
+ };
930
+ }
931
+ function buildCliCommandExecutedEvent({
932
+ data,
933
+ context = {},
934
+ cliVersion = package_default.version
935
+ }) {
936
+ const osInfo = zapierSdk.getOsInfo();
937
+ const platformVersions = zapierSdk.getPlatformVersions();
938
+ return {
939
+ ...createCliBaseEvent(context),
940
+ system_name: "zapier-sdk-cli",
941
+ session_id: context.session_id ?? null,
942
+ cli_version: data.cli_version ?? cliVersion,
943
+ cli_arguments: data.cli_arguments ?? null,
944
+ cli_primary_command: data.cli_primary_command,
945
+ os_platform: osInfo.platform,
946
+ os_release: osInfo.release,
947
+ os_architecture: osInfo.architecture,
948
+ platform_versions: platformVersions,
949
+ selected_api: context.selected_api ?? null,
950
+ app_id: context.app_id ?? null,
951
+ app_version_id: context.app_version_id ?? null,
952
+ execution_duration_ms: data.execution_duration_ms ?? null,
953
+ success_flag: data.success_flag,
954
+ exit_code: data.exit_code ?? (data.success_flag ? 0 : 1),
955
+ error_message: data.error_message ?? null,
956
+ command_category: data.command_category ?? null,
957
+ requires_auth: null,
958
+ is_ci_environment: zapierSdk.isCi(),
959
+ ci_platform: zapierSdk.getCiPlatform(),
960
+ package_manager: data.package_manager ?? "pnpm",
961
+ // Default based on project setup
962
+ made_network_requests: data.made_network_requests ?? null,
963
+ files_modified_count: data.files_modified_count ?? null,
964
+ files_created_count: data.files_created_count ?? null,
965
+ files_processed_size_bytes: data.files_processed_size_bytes ?? null,
966
+ cpu_time_ms: data.cpu_time_ms ?? null,
967
+ subprocess_count: data.subprocess_count ?? null
968
+ };
969
+ }
808
970
  function getFormatMetadata(schema) {
809
971
  return schema?._zod?.def?.formatMeta;
810
972
  }
@@ -836,7 +998,7 @@ function formatItemsFromSchema(functionInfo, items, startingNumber = 0) {
836
998
  });
837
999
  }
838
1000
  function formatSingleItem(formatted, itemNumber) {
839
- let titleLine = `${chalk3__default.default.gray(`${itemNumber + 1}.`)} ${chalk3__default.default.cyan(formatted.title)}`;
1001
+ let titleLine = `${chalk7__default.default.gray(`${itemNumber + 1}.`)} ${chalk7__default.default.cyan(formatted.title)}`;
840
1002
  const subtitleParts = [];
841
1003
  if (formatted.keys) {
842
1004
  subtitleParts.push(...formatted.keys);
@@ -848,11 +1010,11 @@ function formatSingleItem(formatted, itemNumber) {
848
1010
  }
849
1011
  const uniqueParts = [...new Set(subtitleParts)];
850
1012
  if (uniqueParts.length > 0) {
851
- titleLine += ` ${chalk3__default.default.gray(`(${uniqueParts.join(", ")})`)}`;
1013
+ titleLine += ` ${chalk7__default.default.gray(`(${uniqueParts.join(", ")})`)}`;
852
1014
  }
853
1015
  console.log(titleLine);
854
1016
  if (formatted.description) {
855
- console.log(` ${chalk3__default.default.dim(formatted.description)}`);
1017
+ console.log(` ${chalk7__default.default.dim(formatted.description)}`);
856
1018
  }
857
1019
  if (formatted.data !== void 0) {
858
1020
  formatJsonOutput(formatted.data);
@@ -868,16 +1030,16 @@ function formatSingleItem(formatted, itemNumber) {
868
1030
  function applyStyle(value, style) {
869
1031
  switch (style) {
870
1032
  case "dim":
871
- return chalk3__default.default.dim(value);
1033
+ return chalk7__default.default.dim(value);
872
1034
  case "accent":
873
- return chalk3__default.default.magenta(value);
1035
+ return chalk7__default.default.magenta(value);
874
1036
  case "warning":
875
- return chalk3__default.default.red(value);
1037
+ return chalk7__default.default.red(value);
876
1038
  case "success":
877
- return chalk3__default.default.green(value);
1039
+ return chalk7__default.default.green(value);
878
1040
  case "normal":
879
1041
  default:
880
- return chalk3__default.default.blue(value);
1042
+ return chalk7__default.default.blue(value);
881
1043
  }
882
1044
  }
883
1045
  function convertGenericItemToFormattedItem(item) {
@@ -897,93 +1059,229 @@ function formatItemsGeneric(items, startingNumber = 0) {
897
1059
  });
898
1060
  }
899
1061
 
900
- // src/utils/cli-options.ts
901
- var RESERVED_CLI_OPTIONS = [
902
- {
903
- name: "version" /* Version */,
904
- flag: "--version",
905
- short: "-V",
906
- description: "Display version number"
907
- },
908
- {
909
- name: "help" /* Help */,
910
- flag: "--help",
911
- short: "-h",
912
- description: "Display help for command"
913
- }
914
- ];
915
- function getReservedCliOption(name) {
916
- const option = RESERVED_CLI_OPTIONS.find((opt) => opt.name === name);
917
- if (!option) throw new Error(`Reserved CLI option not found: ${name}`);
918
- return option;
1062
+ // src/utils/string-utils.ts
1063
+ function toKebabCase(str) {
1064
+ return str.replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").replace(/([a-z\d])([A-Z])/g, "$1-$2").toLowerCase();
919
1065
  }
920
- var SHARED_COMMAND_CLI_OPTIONS = [
921
- {
922
- name: "json",
923
- flag: "--json",
924
- description: "Output raw JSON instead of formatted results"
1066
+ function formatMissingParamsError(error) {
1067
+ return [
1068
+ "Missing required parameters:",
1069
+ ...error.params.map(
1070
+ ({ name, isPositional: isPositional3 }) => isPositional3 ? ` \u2022 <${toKebabCase(name)}>` : ` \u2022 --${toKebabCase(name)}`
1071
+ )
1072
+ ].join("\n");
1073
+ }
1074
+ function buildJsonErrors(error) {
1075
+ if (error instanceof ZapierCliMissingParametersError) {
1076
+ return error.params.map(({ name, isPositional: isPositional3 }) => ({
1077
+ code: error.code,
1078
+ message: isPositional3 ? `<${toKebabCase(name)}> is required in non-interactive mode` : `--${toKebabCase(name)} is required in non-interactive mode`
1079
+ }));
1080
+ }
1081
+ const code = error instanceof zapierSdk.ZapierError ? error.code : "UNKNOWN_ERROR";
1082
+ const message = error instanceof Error ? error.message : String(error);
1083
+ return [{ code, message }];
1084
+ }
1085
+ async function unwrapHttpResponse(response) {
1086
+ const text = await response.text().catch(() => "[unable to read body]");
1087
+ try {
1088
+ return {
1089
+ statusCode: response.status,
1090
+ headers: Object.fromEntries(response.headers.entries()),
1091
+ body: JSON.parse(text)
1092
+ };
1093
+ } catch {
1094
+ throw new Error(
1095
+ `Failed to parse response as JSON (status: ${response.status}). Body: ${text.slice(0, 500)}`
1096
+ );
925
1097
  }
926
- ];
927
-
928
- // package.json
929
- var package_default = {
930
- version: "0.34.12"};
931
-
932
- // src/telemetry/builders.ts
933
- function createCliBaseEvent(context = {}) {
1098
+ }
1099
+ function outputJson(envelope) {
1100
+ console.log(JSON.stringify(envelope, null, 2));
1101
+ }
1102
+ function createJsonRenderer() {
934
1103
  return {
935
- event_id: zapierSdk.generateEventId(),
936
- timestamp_ms: zapierSdk.getCurrentTimestamp(),
937
- release_id: zapierSdk.getReleaseId(),
938
- customuser_id: context.customuser_id ?? null,
939
- account_id: context.account_id ?? null,
940
- identity_id: context.identity_id ?? null,
941
- visitor_id: context.visitor_id ?? null,
942
- correlation_id: context.correlation_id ?? null
1104
+ async renderPaginatedList(source, _functionInfo) {
1105
+ let page;
1106
+ if (Symbol.asyncIterator in Object(source)) {
1107
+ const iter = source[Symbol.asyncIterator]();
1108
+ const result = await iter.next();
1109
+ page = result.done ? void 0 : result.value;
1110
+ } else {
1111
+ page = await source;
1112
+ }
1113
+ const data = Array.isArray(page?.data) ? page.data : [];
1114
+ outputJson({
1115
+ data,
1116
+ ...page?.nextCursor && { nextCursor: page.nextCursor },
1117
+ errors: []
1118
+ });
1119
+ },
1120
+ renderCollectedList(items, _options) {
1121
+ outputJson({ data: items, errors: [] });
1122
+ },
1123
+ renderItem(value, options) {
1124
+ outputJson({
1125
+ data: options?.outputFile ? { outputFile: options.outputFile } : value ?? null,
1126
+ errors: []
1127
+ });
1128
+ },
1129
+ async renderResponse(response) {
1130
+ console.log(JSON.stringify(await unwrapHttpResponse(response), null, 2));
1131
+ },
1132
+ renderError(error) {
1133
+ outputJson({ data: null, errors: buildJsonErrors(error) });
1134
+ throw new ZapierCliExitError(
1135
+ error instanceof Error ? error.message : String(error),
1136
+ 1
1137
+ );
1138
+ }
943
1139
  };
944
1140
  }
945
- function buildCliCommandExecutedEvent({
946
- data,
947
- context = {},
948
- cliVersion = package_default.version
949
- }) {
950
- const osInfo = zapierSdk.getOsInfo();
951
- const platformVersions = zapierSdk.getPlatformVersions();
1141
+ function getItemName(functionInfo) {
1142
+ if (functionInfo?.itemType) return `${functionInfo.itemType} items`;
1143
+ return "items";
1144
+ }
1145
+ function getListTitle(functionInfo) {
1146
+ if (functionInfo.itemType) return `Available ${functionInfo.itemType} items`;
1147
+ return "items";
1148
+ }
1149
+ function renderItemsForDisplay(items, functionInfo, startingNumber = 0) {
1150
+ if (functionInfo?.inputSchema) {
1151
+ formatItemsFromSchema(
1152
+ functionInfo,
1153
+ items,
1154
+ startingNumber
1155
+ );
1156
+ } else {
1157
+ items.forEach((item, index) => {
1158
+ const obj = item;
1159
+ const name = obj?.name || obj?.key || obj?.id || "Item";
1160
+ console.log(
1161
+ `${chalk7__default.default.gray(`${startingNumber + index + 1}.`)} ${chalk7__default.default.cyan(String(name))}`
1162
+ );
1163
+ if (obj?.description)
1164
+ console.log(` ${chalk7__default.default.dim(String(obj.description))}`);
1165
+ console.log();
1166
+ });
1167
+ }
1168
+ }
1169
+ function createInteractiveRenderer() {
952
1170
  return {
953
- ...createCliBaseEvent(context),
954
- system_name: "zapier-sdk-cli",
955
- session_id: context.session_id ?? null,
956
- cli_version: data.cli_version ?? cliVersion,
957
- cli_arguments: data.cli_arguments ?? null,
958
- cli_primary_command: data.cli_primary_command,
959
- os_platform: osInfo.platform,
960
- os_release: osInfo.release,
961
- os_architecture: osInfo.architecture,
962
- platform_versions: platformVersions,
963
- selected_api: context.selected_api ?? null,
964
- app_id: context.app_id ?? null,
965
- app_version_id: context.app_version_id ?? null,
966
- execution_duration_ms: data.execution_duration_ms ?? null,
967
- success_flag: data.success_flag,
968
- exit_code: data.exit_code ?? (data.success_flag ? 0 : 1),
969
- error_message: data.error_message ?? null,
970
- command_category: data.command_category ?? null,
971
- requires_auth: null,
972
- is_ci_environment: zapierSdk.isCi(),
973
- ci_platform: zapierSdk.getCiPlatform(),
974
- package_manager: data.package_manager ?? "pnpm",
975
- // Default based on project setup
976
- made_network_requests: data.made_network_requests ?? null,
977
- files_modified_count: data.files_modified_count ?? null,
978
- files_created_count: data.files_created_count ?? null,
979
- files_processed_size_bytes: data.files_processed_size_bytes ?? null,
980
- cpu_time_ms: data.cpu_time_ms ?? null,
981
- subprocess_count: data.subprocess_count ?? null
1171
+ async renderPaginatedList(source, functionInfo) {
1172
+ const itemName = getItemName(functionInfo);
1173
+ if (!(Symbol.asyncIterator in Object(source))) {
1174
+ const items = source?.data;
1175
+ if (!Array.isArray(items) || items.length === 0) {
1176
+ console.log(chalk7__default.default.yellow(`No ${itemName} found.`));
1177
+ return;
1178
+ }
1179
+ renderItemsForDisplay(items, functionInfo, 0);
1180
+ console.log(chalk7__default.default.green(`
1181
+ \u2705 Showing ${items.length} ${itemName}`));
1182
+ return;
1183
+ }
1184
+ let totalShown = 0;
1185
+ let pageCount = 0;
1186
+ console.log(chalk7__default.default.blue(`\u{1F4CB} ${getListTitle(functionInfo)}
1187
+ `));
1188
+ for await (const page of source) {
1189
+ const items = page.data ?? [];
1190
+ pageCount++;
1191
+ if (items.length === 0 && pageCount === 1) {
1192
+ console.log(chalk7__default.default.yellow(`No ${itemName} found.`));
1193
+ return;
1194
+ }
1195
+ if (items.length === 0) break;
1196
+ if (pageCount > 1) {
1197
+ console.clear();
1198
+ console.log(chalk7__default.default.blue(`\u{1F4CB} ${getListTitle(functionInfo)}
1199
+ `));
1200
+ }
1201
+ renderItemsForDisplay(items, functionInfo, totalShown);
1202
+ totalShown += items.length;
1203
+ console.log(
1204
+ chalk7__default.default.green(
1205
+ `
1206
+ \u2705 Showing ${totalShown} ${itemName} (page ${pageCount})`
1207
+ )
1208
+ );
1209
+ if (page.nextCursor) {
1210
+ const { continueReading } = await inquirer__default.default.prompt([
1211
+ {
1212
+ type: "confirm",
1213
+ name: "continueReading",
1214
+ message: "Load next page?",
1215
+ default: true
1216
+ }
1217
+ ]);
1218
+ if (!continueReading) break;
1219
+ } else {
1220
+ break;
1221
+ }
1222
+ }
1223
+ console.log(chalk7__default.default.gray(`
1224
+ \u{1F4C4} Finished browsing ${itemName}`));
1225
+ },
1226
+ renderCollectedList(items, { maxItems, userSpecifiedMaxItems, functionInfo } = {}) {
1227
+ if (!Array.isArray(items)) {
1228
+ formatJsonOutput(items);
1229
+ return;
1230
+ }
1231
+ const itemName = getItemName(functionInfo);
1232
+ if (items.length === 0) {
1233
+ console.log(chalk7__default.default.yellow(`No ${itemName} found.`));
1234
+ return;
1235
+ }
1236
+ console.log(chalk7__default.default.green(`
1237
+ \u2705 Found ${items.length} ${itemName}:
1238
+ `));
1239
+ renderItemsForDisplay(items, functionInfo);
1240
+ if (userSpecifiedMaxItems && maxItems) {
1241
+ console.log(
1242
+ chalk7__default.default.gray(
1243
+ `
1244
+ \u{1F4C4} Showing up to ${maxItems} ${itemName} (--max-items ${maxItems})`
1245
+ )
1246
+ );
1247
+ } else {
1248
+ console.log(chalk7__default.default.gray(`
1249
+ \u{1F4C4} All available ${itemName} shown`));
1250
+ }
1251
+ },
1252
+ renderItem(value, options) {
1253
+ if (options?.outputFile) {
1254
+ const label = options.commandName ? `\u2705 ${options.commandName} completed successfully!` : "\u2705 Done!";
1255
+ console.log(chalk7__default.default.green(label));
1256
+ console.log(chalk7__default.default.gray(`Output written to: ${options.outputFile}`));
1257
+ } else {
1258
+ formatJsonOutput(value);
1259
+ }
1260
+ },
1261
+ async renderResponse(response) {
1262
+ formatJsonOutput(await unwrapHttpResponse(response));
1263
+ },
1264
+ renderError(error) {
1265
+ if (error instanceof ZapierCliMissingParametersError) {
1266
+ console.error(chalk7__default.default.red("\u274C " + formatMissingParamsError(error)));
1267
+ console.error("\n" + chalk7__default.default.dim("Use --help to see available options"));
1268
+ throw new ZapierCliExitError(error.message, 1);
1269
+ }
1270
+ if (error instanceof zapierSdk.ZapierError) {
1271
+ const formattedMessage = zapierSdk.formatErrorMessage(error);
1272
+ console.error(chalk7__default.default.red("\u274C Error:"), formattedMessage);
1273
+ throw new ZapierCliExitError(formattedMessage, 1);
1274
+ }
1275
+ const msg = error instanceof Error ? error.message : "Unknown error";
1276
+ console.error(chalk7__default.default.red("\u274C Error:"), msg);
1277
+ throw new ZapierCliExitError(msg, 1);
1278
+ }
982
1279
  };
983
1280
  }
984
1281
 
985
1282
  // src/utils/cli-generator.ts
986
1283
  var CLI_COMMAND_EXECUTED_EVENT_SUBJECT = "platform.sdk.CliCommandExecutedEvent";
1284
+ var PAGINATION_PARAM_NAMES = /* @__PURE__ */ new Set(["maxItems", "pageSize", "cursor"]);
987
1285
  var SENSITIVE_FLAGS = [
988
1286
  "--credentials",
989
1287
  "--credentials-client-secret",
@@ -1014,6 +1312,62 @@ function sanitizeCliArguments(args) {
1014
1312
  }
1015
1313
  return sanitized;
1016
1314
  }
1315
+ function getNormalizedResult(result, { isListCommand }) {
1316
+ if (result instanceof Response) {
1317
+ return { kind: "response", value: result };
1318
+ }
1319
+ if (isListCommand) {
1320
+ const sdkResult2 = result;
1321
+ if (!Array.isArray(sdkResult2?.data)) {
1322
+ throw new Error(
1323
+ `List command returned unexpected shape (expected { data: [] }): ${JSON.stringify(result).slice(0, 200)}`
1324
+ );
1325
+ }
1326
+ return {
1327
+ kind: "list",
1328
+ data: sdkResult2.data,
1329
+ nextCursor: sdkResult2.nextCursor
1330
+ };
1331
+ }
1332
+ const sdkResult = result;
1333
+ return {
1334
+ kind: "item",
1335
+ value: result !== null && typeof result === "object" && "data" in result ? sdkResult.data : result
1336
+ };
1337
+ }
1338
+ function hasItems(sdkResult) {
1339
+ return sdkResult != null && typeof sdkResult.items === "function";
1340
+ }
1341
+ function hasPages(sdkResult) {
1342
+ return sdkResult != null && typeof sdkResult[Symbol.asyncIterator] === "function";
1343
+ }
1344
+ async function* toItemsStream(sdkResult) {
1345
+ if (hasItems(sdkResult)) {
1346
+ yield* sdkResult.items();
1347
+ return;
1348
+ }
1349
+ if (hasPages(sdkResult)) {
1350
+ for await (const page of sdkResult) {
1351
+ yield* page.data ?? [];
1352
+ }
1353
+ return;
1354
+ }
1355
+ throw new ZapierCliExitError(
1356
+ `SDK method returned a value that is not async-iterable. Got: ${typeof sdkResult}. List methods must return an AsyncIterable or an object with an items() method.`,
1357
+ 1
1358
+ );
1359
+ }
1360
+ async function collectItemsFromResult({
1361
+ sdkResult,
1362
+ maxItems
1363
+ }) {
1364
+ const items = [];
1365
+ for await (const item of toItemsStream(sdkResult)) {
1366
+ items.push(item);
1367
+ if (maxItems !== void 0 && items.length >= maxItems) break;
1368
+ }
1369
+ return maxItems !== void 0 ? items.slice(0, maxItems) : items;
1370
+ }
1017
1371
  var CONFIRM_MESSAGES = {
1018
1372
  "create-secret": {
1019
1373
  messageBefore: "You are about to create a sensitive secret that will be displayed as plain text.\nOnce created, you cannot retrieve it again.",
@@ -1028,7 +1382,7 @@ async function promptConfirm(confirmType) {
1028
1382
  return { confirmed: true };
1029
1383
  }
1030
1384
  const { messageBefore, messageAfter } = CONFIRM_MESSAGES[confirmType];
1031
- console.log(chalk3__default.default.yellow(`
1385
+ console.log(chalk7__default.default.yellow(`
1032
1386
  ${messageBefore}
1033
1387
  `));
1034
1388
  const { confirmed } = await inquirer__default.default.prompt([
@@ -1050,11 +1404,20 @@ function emitDeprecationWarning({
1050
1404
  }
1051
1405
  console.warn();
1052
1406
  console.warn(
1053
- chalk3__default.default.yellow.bold("\u26A0\uFE0F DEPRECATION WARNING") + chalk3__default.default.yellow(` - \`${cliCommandName}\` is deprecated.`)
1407
+ chalk7__default.default.yellow.bold("\u26A0\uFE0F DEPRECATION WARNING") + chalk7__default.default.yellow(` - \`${cliCommandName}\` is deprecated.`)
1054
1408
  );
1055
- console.warn(chalk3__default.default.yellow(` ${deprecation.message}`));
1409
+ console.warn(chalk7__default.default.yellow(` ${deprecation.message}`));
1056
1410
  console.warn();
1057
1411
  }
1412
+ function resolveOutputMode({
1413
+ isListCommand,
1414
+ hasPaginationParams,
1415
+ hasUserSpecifiedMaxItems
1416
+ }) {
1417
+ if (!isListCommand || !hasPaginationParams) return "single";
1418
+ if (hasUserSpecifiedMaxItems) return "collect";
1419
+ return "paginate";
1420
+ }
1058
1421
  function analyzeZodSchema(schema, functionInfo) {
1059
1422
  const parameters = [];
1060
1423
  const schemaDef = schema._zod?.def;
@@ -1194,9 +1557,6 @@ function reconstructPositionalArgs(inputParameters, flatParams) {
1194
1557
  }
1195
1558
  return args;
1196
1559
  }
1197
- function toKebabCase(str) {
1198
- return str.replace(/([A-Z])/g, "-$1").toLowerCase();
1199
- }
1200
1560
  function methodNameToCliCommand(methodName) {
1201
1561
  return toKebabCase(methodName);
1202
1562
  }
@@ -1286,23 +1646,31 @@ function createCommandConfig(cliCommandName, functionInfo, sdk2) {
1286
1646
  let success = true;
1287
1647
  let errorMessage = null;
1288
1648
  let resolvedParams = {};
1649
+ const commandObj = args[args.length - 1];
1650
+ const options = commandObj.opts();
1651
+ const interactiveMode = !options.json;
1652
+ const renderer = interactiveMode ? createInteractiveRenderer() : createJsonRenderer();
1289
1653
  try {
1290
- const commandObj = args[args.length - 1];
1291
- const options = commandObj.opts();
1654
+ const commandObj2 = args[args.length - 1];
1655
+ const options2 = commandObj2.opts();
1292
1656
  emitDeprecationWarning({
1293
1657
  cliCommandName,
1294
1658
  deprecation: functionInfo.deprecation
1295
1659
  });
1296
1660
  const isListCommand = functionInfo.type === "list";
1297
1661
  const hasPaginationParams = parameters.some(
1298
- (p) => p.name === "maxItems" || p.name === "pageSize"
1662
+ (p) => PAGINATION_PARAM_NAMES.has(p.name)
1299
1663
  );
1300
- const hasUserSpecifiedMaxItems = "maxItems" in options && options.maxItems !== void 0;
1301
- const shouldUseJson = options.json;
1664
+ const hasUserSpecifiedMaxItems = "maxItems" in options2 && options2.maxItems !== void 0;
1665
+ const outputMode = resolveOutputMode({
1666
+ isListCommand,
1667
+ hasPaginationParams,
1668
+ hasUserSpecifiedMaxItems
1669
+ });
1302
1670
  const rawParams = convertCliArgsToSdkParams(
1303
1671
  parameters,
1304
1672
  args.slice(0, -1),
1305
- options
1673
+ options2
1306
1674
  );
1307
1675
  if (schema && !usesInputParameters) {
1308
1676
  const resolver = new SchemaParameterResolver();
@@ -1310,128 +1678,96 @@ function createCommandConfig(cliCommandName, functionInfo, sdk2) {
1310
1678
  schema,
1311
1679
  rawParams,
1312
1680
  sdk2,
1313
- functionInfo.name
1681
+ functionInfo.name,
1682
+ { interactiveMode }
1314
1683
  );
1315
1684
  } else {
1316
1685
  resolvedParams = rawParams;
1317
1686
  }
1318
1687
  const confirm = functionInfo.confirm;
1319
1688
  let confirmMessageAfter;
1320
- if (confirm && !shouldUseJson) {
1689
+ if (confirm && interactiveMode) {
1321
1690
  const confirmResult = await promptConfirm(confirm);
1322
1691
  if (!confirmResult.confirmed) {
1323
- console.log(chalk3__default.default.yellow("Operation cancelled."));
1692
+ console.log(chalk7__default.default.yellow("Operation cancelled."));
1324
1693
  return;
1325
1694
  }
1326
1695
  confirmMessageAfter = confirmResult.messageAfter;
1327
1696
  }
1328
- if (isListCommand && hasPaginationParams && !shouldUseJson && !hasUserSpecifiedMaxItems) {
1329
- const sdkObj = sdk2;
1330
- const sdkIterable = sdkObj[functionInfo.name](resolvedParams);
1331
- await handlePaginatedListWithAsyncIteration(
1332
- functionInfo.name,
1333
- sdkIterable,
1334
- functionInfo
1335
- );
1336
- } else {
1337
- const hasOutputFile = resolvedParams.output;
1338
- if (hasOutputFile) {
1339
- const sdkObj = sdk2;
1340
- await sdkObj[functionInfo.name](resolvedParams);
1341
- console.log(
1342
- chalk3__default.default.green(`\u2705 ${cliCommandName} completed successfully!`)
1343
- );
1344
- console.log(chalk3__default.default.gray(`Output written to: ${hasOutputFile}`));
1345
- return;
1346
- }
1347
- let result;
1348
- if (usesInputParameters) {
1349
- const positionalArgs = reconstructPositionalArgs(
1350
- functionInfo.inputParameters,
1351
- resolvedParams
1352
- );
1353
- const sdkObj = sdk2;
1354
- result = await sdkObj[functionInfo.name](...positionalArgs);
1355
- } else {
1356
- const sdkObj = sdk2;
1357
- result = await sdkObj[functionInfo.name](resolvedParams);
1358
- }
1359
- if (result instanceof Response) {
1360
- const response = result;
1361
- let body;
1362
- const text = await response.text().catch(() => "[unable to read body]");
1363
- try {
1364
- body = JSON.parse(text);
1365
- } catch {
1366
- throw new Error(
1367
- `Failed to parse response as JSON (status: ${response.status}). Body: ${text.slice(0, 500)}`
1368
- );
1369
- }
1370
- result = {
1371
- statusCode: response.status,
1372
- headers: Object.fromEntries(response.headers.entries()),
1373
- body
1374
- };
1697
+ const sdkMethod = sdk2[functionInfo.name];
1698
+ switch (outputMode) {
1699
+ case "paginate": {
1700
+ const source = sdkMethod(resolvedParams);
1701
+ await renderer.renderPaginatedList(source, functionInfo);
1702
+ break;
1375
1703
  }
1376
- const items = result?.data ? result.data : result;
1377
- if (shouldUseJson) {
1378
- console.log(JSON.stringify(items, null, 2));
1379
- } else if (isListCommand) {
1380
- formatNonPaginatedResults(
1381
- items,
1382
- resolvedParams.maxItems,
1383
- hasUserSpecifiedMaxItems,
1384
- shouldUseJson,
1704
+ case "collect": {
1705
+ const maxItems = resolvedParams.maxItems;
1706
+ const sdkResult = sdkMethod({ ...resolvedParams, maxItems });
1707
+ const allItems = await collectItemsFromResult({
1708
+ sdkResult,
1709
+ maxItems
1710
+ });
1711
+ renderer.renderCollectedList(allItems, {
1712
+ maxItems,
1713
+ userSpecifiedMaxItems: hasUserSpecifiedMaxItems,
1385
1714
  functionInfo
1386
- );
1387
- } else {
1388
- formatJsonOutput(items);
1715
+ });
1716
+ break;
1389
1717
  }
1390
- if (confirmMessageAfter) {
1391
- console.log(chalk3__default.default.yellow(`
1718
+ case "single": {
1719
+ const callSdkMethod = () => {
1720
+ if (usesInputParameters) {
1721
+ const positionalArgs = reconstructPositionalArgs(
1722
+ functionInfo.inputParameters,
1723
+ resolvedParams
1724
+ );
1725
+ return sdkMethod(...positionalArgs);
1726
+ }
1727
+ return sdkMethod(resolvedParams);
1728
+ };
1729
+ const outputFile = resolvedParams.output;
1730
+ if (outputFile) {
1731
+ await callSdkMethod();
1732
+ renderer.renderItem(null, {
1733
+ outputFile,
1734
+ commandName: cliCommandName
1735
+ });
1736
+ break;
1737
+ }
1738
+ const result = await callSdkMethod();
1739
+ const normalizedResult = getNormalizedResult(result, {
1740
+ isListCommand
1741
+ });
1742
+ if (normalizedResult.kind === "response") {
1743
+ await renderer.renderResponse(normalizedResult.value);
1744
+ } else if (normalizedResult.kind === "list") {
1745
+ renderer.renderCollectedList(normalizedResult.data, {
1746
+ maxItems: resolvedParams.maxItems,
1747
+ userSpecifiedMaxItems: hasUserSpecifiedMaxItems,
1748
+ functionInfo
1749
+ });
1750
+ } else {
1751
+ renderer.renderItem(normalizedResult.value);
1752
+ }
1753
+ if (confirmMessageAfter) {
1754
+ console.log(chalk7__default.default.yellow(`
1392
1755
  ${confirmMessageAfter}`));
1756
+ }
1757
+ break;
1393
1758
  }
1394
1759
  }
1395
1760
  } catch (error) {
1396
1761
  success = false;
1397
1762
  errorMessage = error instanceof Error ? error.message : String(error);
1398
- if (error instanceof Error && error.message.includes('"code"')) {
1399
- try {
1400
- const validationErrors = JSON.parse(error.message);
1401
- console.error(chalk3__default.default.red("\u274C Validation Error:"));
1402
- validationErrors.forEach((err) => {
1403
- const errorObj = err;
1404
- const field = errorObj?.path?.join(".") || "unknown";
1405
- console.error(
1406
- chalk3__default.default.yellow(
1407
- ` \u2022 ${field}: ${errorObj?.message || "Unknown error"}`
1408
- )
1409
- );
1410
- });
1411
- console.error(
1412
- "\n" + chalk3__default.default.dim(`Use --help to see available options`)
1413
- );
1414
- throw new ZapierCliExitError("Validation failed", 1);
1415
- } catch {
1416
- console.error(
1417
- chalk3__default.default.red("Error:"),
1418
- error instanceof Error ? error.message : String(error)
1419
- );
1420
- throw new ZapierCliExitError(
1421
- error instanceof Error ? error.message : String(error),
1422
- 1
1423
- );
1424
- }
1763
+ if (error instanceof ZapierCliMissingParametersError) {
1764
+ renderer.renderError(error);
1765
+ } else if (error instanceof ZapierCliValidationError) {
1766
+ renderer.renderError(error);
1425
1767
  } else if (error instanceof ZapierCliError) {
1426
1768
  throw error;
1427
- } else if (error instanceof zapierSdk.ZapierError) {
1428
- const formattedMessage = zapierSdk.formatErrorMessage(error);
1429
- console.error(chalk3__default.default.red("\u274C Error:"), formattedMessage);
1430
- throw new ZapierCliExitError(formattedMessage, 1);
1431
1769
  } else {
1432
- const msg = error instanceof Error ? error.message : "Unknown error";
1433
- console.error(chalk3__default.default.red("\u274C Error:"), msg);
1434
- throw new ZapierCliExitError(msg, 1);
1770
+ renderer.renderError(error);
1435
1771
  }
1436
1772
  } finally {
1437
1773
  try {
@@ -1460,7 +1796,8 @@ ${confirmMessageAfter}`));
1460
1796
  parameters,
1461
1797
  handler,
1462
1798
  hidden: functionInfo.categories?.includes("deprecated") ?? false,
1463
- aliases: functionInfo.aliases
1799
+ aliases: functionInfo.aliases,
1800
+ supportsJsonOutput: functionInfo.supportsJsonOutput
1464
1801
  };
1465
1802
  }
1466
1803
  function collect(value, previous = []) {
@@ -1471,7 +1808,7 @@ function addCommand(program2, commandName, config) {
1471
1808
  const command = program2.command(commandName, { hidden: config.hidden ?? false }).description(config.description);
1472
1809
  let hasPositionalArray = false;
1473
1810
  config.parameters.forEach((param) => {
1474
- const kebabName = param.name.replace(/([A-Z])/g, "-$1").toLowerCase();
1811
+ const kebabName = toKebabCase(param.name);
1475
1812
  if (param.hasResolver && param.required) {
1476
1813
  command.argument(
1477
1814
  `[${kebabName}]`,
@@ -1526,9 +1863,9 @@ function addCommand(program2, commandName, config) {
1526
1863
  });
1527
1864
  const paramNames = new Set(config.parameters.map((p) => p.name));
1528
1865
  SHARED_COMMAND_CLI_OPTIONS.forEach((opt) => {
1529
- if (!paramNames.has(opt.name)) {
1530
- command.option(opt.flag, opt.description);
1531
- }
1866
+ if (paramNames.has(opt.name)) return;
1867
+ if (config.supportsJsonOutput === false && opt.name === "json") return;
1868
+ command.option(opt.flag, opt.description);
1532
1869
  });
1533
1870
  command.action(config.handler);
1534
1871
  }
@@ -1589,161 +1926,6 @@ function convertValue(value, type) {
1589
1926
  return value;
1590
1927
  }
1591
1928
  }
1592
- async function handlePaginatedListWithAsyncIteration(sdkMethodName, sdkResult, functionInfo) {
1593
- const itemName = getItemNameFromMethod(functionInfo);
1594
- let totalShown = 0;
1595
- let pageCount = 0;
1596
- console.log(
1597
- chalk3__default.default.blue(`\u{1F4CB} ${getListTitleFromMethod(sdkMethodName, functionInfo)}
1598
- `)
1599
- );
1600
- try {
1601
- for await (const page of sdkResult) {
1602
- const items = page.data || page;
1603
- pageCount++;
1604
- if (!Array.isArray(items)) {
1605
- console.log(chalk3__default.default.yellow(`No ${itemName} found.`));
1606
- return;
1607
- }
1608
- if (items.length === 0 && pageCount === 1) {
1609
- console.log(chalk3__default.default.yellow(`No ${itemName} found.`));
1610
- return;
1611
- }
1612
- if (items.length === 0) {
1613
- break;
1614
- }
1615
- if (pageCount > 1) {
1616
- console.clear();
1617
- console.log(
1618
- chalk3__default.default.blue(
1619
- `\u{1F4CB} ${getListTitleFromMethod(sdkMethodName, functionInfo)}
1620
- `
1621
- )
1622
- );
1623
- }
1624
- if (functionInfo && functionInfo.inputSchema) {
1625
- formatItemsFromSchema(
1626
- functionInfo,
1627
- items,
1628
- totalShown
1629
- );
1630
- } else {
1631
- formatItemsGeneric2(items, totalShown);
1632
- }
1633
- totalShown += items.length;
1634
- console.log(
1635
- chalk3__default.default.green(
1636
- `
1637
- \u2705 Showing ${totalShown} ${itemName} (page ${pageCount})`
1638
- )
1639
- );
1640
- if (page.nextCursor) {
1641
- const { continueReading } = await inquirer__default.default.prompt([
1642
- {
1643
- type: "confirm",
1644
- name: "continueReading",
1645
- message: `Load next page?`,
1646
- default: true
1647
- }
1648
- ]);
1649
- if (!continueReading) {
1650
- break;
1651
- }
1652
- } else {
1653
- break;
1654
- }
1655
- }
1656
- console.log(chalk3__default.default.gray(`
1657
- \u{1F4C4} Finished browsing ${itemName}`));
1658
- } catch (error) {
1659
- const items = sdkResult?.data || sdkResult;
1660
- if (Array.isArray(items)) {
1661
- if (items.length === 0) {
1662
- console.log(chalk3__default.default.yellow(`No ${itemName} found.`));
1663
- return;
1664
- }
1665
- if (functionInfo && functionInfo.inputSchema) {
1666
- formatItemsFromSchema(
1667
- functionInfo,
1668
- items,
1669
- 0
1670
- );
1671
- } else {
1672
- formatItemsGeneric2(items, 0);
1673
- }
1674
- console.log(chalk3__default.default.green(`
1675
- \u2705 Showing ${items.length} ${itemName}`));
1676
- } else {
1677
- throw error;
1678
- }
1679
- }
1680
- }
1681
- function formatNonPaginatedResults(result, requestedMaxItems, userSpecifiedMaxItems, useRawJson, functionInfo) {
1682
- if (!Array.isArray(result)) {
1683
- if (useRawJson) {
1684
- console.log(JSON.stringify(result, null, 2));
1685
- } else {
1686
- formatJsonOutput(result);
1687
- }
1688
- return;
1689
- }
1690
- if (useRawJson) {
1691
- console.log(JSON.stringify(result, null, 2));
1692
- return;
1693
- }
1694
- const itemName = functionInfo ? getItemNameFromMethod(functionInfo) : "items";
1695
- if (result.length === 0) {
1696
- console.log(chalk3__default.default.yellow(`No ${itemName} found.`));
1697
- return;
1698
- }
1699
- console.log(chalk3__default.default.green(`
1700
- \u2705 Found ${result.length} ${itemName}:
1701
- `));
1702
- if (functionInfo && functionInfo.inputSchema) {
1703
- formatItemsFromSchema(
1704
- functionInfo,
1705
- result
1706
- );
1707
- } else {
1708
- formatItemsGeneric2(result);
1709
- }
1710
- if (userSpecifiedMaxItems && requestedMaxItems) {
1711
- console.log(
1712
- chalk3__default.default.gray(
1713
- `
1714
- \u{1F4C4} Showing up to ${requestedMaxItems} ${itemName} (--max-items ${requestedMaxItems})`
1715
- )
1716
- );
1717
- } else {
1718
- console.log(chalk3__default.default.gray(`
1719
- \u{1F4C4} All available ${itemName} shown`));
1720
- }
1721
- }
1722
- function formatItemsGeneric2(items, startingNumber = 0) {
1723
- items.forEach((item, index) => {
1724
- const itemObj = item;
1725
- const name = itemObj?.name || itemObj?.key || itemObj?.id || "Item";
1726
- console.log(
1727
- `${chalk3__default.default.gray(`${startingNumber + index + 1}.`)} ${chalk3__default.default.cyan(String(name))}`
1728
- );
1729
- if (itemObj?.description) {
1730
- console.log(` ${chalk3__default.default.dim(String(itemObj.description))}`);
1731
- }
1732
- console.log();
1733
- });
1734
- }
1735
- function getItemNameFromMethod(functionInfo) {
1736
- if (functionInfo.itemType) {
1737
- return `${functionInfo.itemType} items`;
1738
- }
1739
- return "items";
1740
- }
1741
- function getListTitleFromMethod(methodName, functionInfo) {
1742
- if (functionInfo.itemType) {
1743
- return `Available ${functionInfo.itemType} items`;
1744
- }
1745
- return `${methodName} items`;
1746
- }
1747
1929
  var LOGIN_PORTS = [49505, 50575, 52804, 55981, 61010, 63851];
1748
1930
  var LOGIN_TIMEOUT_MS = 3e5;
1749
1931
  var spinPromise = async (promise, text) => {
@@ -1763,20 +1945,20 @@ var spinPromise = async (promise, text) => {
1763
1945
  };
1764
1946
  var log = {
1765
1947
  info: (message, ...args) => {
1766
- console.log(chalk3__default.default.blue("\u2139"), message, ...args);
1948
+ console.log(chalk7__default.default.blue("\u2139"), message, ...args);
1767
1949
  },
1768
1950
  error: (message, ...args) => {
1769
- console.error(chalk3__default.default.red("\u2716"), message, ...args);
1951
+ console.error(chalk7__default.default.red("\u2716"), message, ...args);
1770
1952
  },
1771
1953
  success: (message, ...args) => {
1772
- console.log(chalk3__default.default.green("\u2713"), message, ...args);
1954
+ console.log(chalk7__default.default.green("\u2713"), message, ...args);
1773
1955
  },
1774
1956
  warn: (message, ...args) => {
1775
- console.log(chalk3__default.default.yellow("\u26A0"), message, ...args);
1957
+ console.log(chalk7__default.default.yellow("\u26A0"), message, ...args);
1776
1958
  },
1777
1959
  debug: (message, ...args) => {
1778
1960
  if (process.env.DEBUG === "true" || process.argv.includes("--debug")) {
1779
- console.log(chalk3__default.default.gray("\u{1F41B}"), message, ...args);
1961
+ console.log(chalk7__default.default.gray("\u{1F41B}"), message, ...args);
1780
1962
  }
1781
1963
  }
1782
1964
  };
@@ -2052,7 +2234,8 @@ var loginPlugin = ({
2052
2234
  meta: {
2053
2235
  login: {
2054
2236
  categories: ["account"],
2055
- inputSchema: LoginSchema
2237
+ inputSchema: LoginSchema,
2238
+ supportsJsonOutput: false
2056
2239
  }
2057
2240
  }
2058
2241
  }
@@ -2071,7 +2254,8 @@ var logoutPlugin = () => ({
2071
2254
  meta: {
2072
2255
  logout: {
2073
2256
  categories: ["account"],
2074
- inputSchema: LogoutSchema
2257
+ inputSchema: LogoutSchema,
2258
+ supportsJsonOutput: false
2075
2259
  }
2076
2260
  }
2077
2261
  }
@@ -3842,7 +4026,7 @@ function buildTemplateVariables({
3842
4026
  };
3843
4027
  }
3844
4028
  function cleanupProject({ projectDir }) {
3845
- console.log("\n" + chalk3__default.default.yellow("!") + " Cleaning up...");
4029
+ console.log("\n" + chalk7__default.default.yellow("!") + " Cleaning up...");
3846
4030
  fs.rmSync(projectDir, { recursive: true, force: true });
3847
4031
  }
3848
4032
  async function withInterruptCleanup(cleanup, fn) {
@@ -4052,8 +4236,8 @@ function buildNextSteps({
4052
4236
  }
4053
4237
  function createConsoleDisplayHooks() {
4054
4238
  return {
4055
- onItemComplete: (message) => console.log(" " + chalk3__default.default.green("\u2713") + " " + chalk3__default.default.dim(message)),
4056
- onWarn: (message) => console.warn(chalk3__default.default.yellow("!") + " " + message),
4239
+ onItemComplete: (message) => console.log(" " + chalk7__default.default.green("\u2713") + " " + chalk7__default.default.dim(message)),
4240
+ onWarn: (message) => console.warn(chalk7__default.default.yellow("!") + " " + message),
4057
4241
  onStepStart: ({
4058
4242
  description,
4059
4243
  stepNumber,
@@ -4062,31 +4246,31 @@ function createConsoleDisplayHooks() {
4062
4246
  skipPrompts
4063
4247
  }) => {
4064
4248
  const progressMessage = `${description}...`;
4065
- const stepCounter = chalk3__default.default.dim(`${stepNumber}/${totalSteps}`);
4249
+ const stepCounter = chalk7__default.default.dim(`${stepNumber}/${totalSteps}`);
4066
4250
  if (skipPrompts) {
4067
4251
  console.log(
4068
- "\n" + chalk3__default.default.bold(`\u276F ${progressMessage}`) + " " + stepCounter + "\n"
4252
+ "\n" + chalk7__default.default.bold(`\u276F ${progressMessage}`) + " " + stepCounter + "\n"
4069
4253
  );
4070
4254
  } else {
4071
4255
  console.log(
4072
- chalk3__default.default.dim("\u2192") + " " + progressMessage + " " + stepCounter
4256
+ chalk7__default.default.dim("\u2192") + " " + progressMessage + " " + stepCounter
4073
4257
  );
4074
4258
  }
4075
4259
  if (command) {
4076
- console.log(" " + chalk3__default.default.cyan(`$ ${command}`));
4260
+ console.log(" " + chalk7__default.default.cyan(`$ ${command}`));
4077
4261
  }
4078
4262
  },
4079
4263
  onStepSuccess: ({ stepNumber, totalSteps }) => console.log(
4080
- "\n" + chalk3__default.default.green("\u2713") + " " + chalk3__default.default.dim(`Step ${stepNumber}/${totalSteps} complete`) + "\n"
4264
+ "\n" + chalk7__default.default.green("\u2713") + " " + chalk7__default.default.dim(`Step ${stepNumber}/${totalSteps} complete`) + "\n"
4081
4265
  ),
4082
4266
  onStepError: ({ description, command, err }) => {
4083
4267
  const detail = err instanceof Error && err.message ? `
4084
- ${chalk3__default.default.dim(err.message)}` : "";
4268
+ ${chalk7__default.default.dim(err.message)}` : "";
4085
4269
  const hint = command ? `
4086
- ${chalk3__default.default.dim("run manually:")} ${chalk3__default.default.cyan(`$ ${command}`)}` : "";
4270
+ ${chalk7__default.default.dim("run manually:")} ${chalk7__default.default.cyan(`$ ${command}`)}` : "";
4087
4271
  console.error(
4088
4272
  `
4089
- ${chalk3__default.default.red("\u2716")} ${chalk3__default.default.bold(description)}${chalk3__default.default.dim(" failed")}${detail}${hint}`
4273
+ ${chalk7__default.default.red("\u2716")} ${chalk7__default.default.bold(description)}${chalk7__default.default.dim(" failed")}${detail}${hint}`
4090
4274
  );
4091
4275
  }
4092
4276
  };
@@ -4098,22 +4282,22 @@ function displaySummaryAndNextSteps({
4098
4282
  packageManager
4099
4283
  }) {
4100
4284
  const formatStatus = (complete) => ({
4101
- icon: complete ? chalk3__default.default.green("\u2713") : chalk3__default.default.yellow("!"),
4102
- text: complete ? chalk3__default.default.green("Setup complete") : chalk3__default.default.yellow("Setup interrupted")
4285
+ icon: complete ? chalk7__default.default.green("\u2713") : chalk7__default.default.yellow("!"),
4286
+ text: complete ? chalk7__default.default.green("Setup complete") : chalk7__default.default.yellow("Setup interrupted")
4103
4287
  });
4104
- const formatNextStep = (step, i) => " " + chalk3__default.default.dim(`${i + 1}.`) + " " + chalk3__default.default.bold(step.description);
4105
- const formatCommand = (cmd) => " " + chalk3__default.default.cyan(`$ ${cmd}`);
4106
- const formatCompletedStep = (step) => " " + chalk3__default.default.green("\u2713") + " " + step.description;
4288
+ const formatNextStep = (step, i) => " " + chalk7__default.default.dim(`${i + 1}.`) + " " + chalk7__default.default.bold(step.description);
4289
+ const formatCommand = (cmd) => " " + chalk7__default.default.cyan(`$ ${cmd}`);
4290
+ const formatCompletedStep = (step) => " " + chalk7__default.default.green("\u2713") + " " + step.description;
4107
4291
  const { execCmd } = getPackageManagerCommands({ packageManager });
4108
4292
  const leftoverSteps = steps.filter(
4109
4293
  (s) => !completedSetupStepIds.includes(s.id)
4110
4294
  );
4111
4295
  const isComplete = leftoverSteps.length === 0;
4112
4296
  const status = formatStatus(isComplete);
4113
- console.log("\n" + chalk3__default.default.bold("\u276F Summary") + "\n");
4114
- console.log(" " + chalk3__default.default.dim("Project") + " " + chalk3__default.default.bold(projectName));
4297
+ console.log("\n" + chalk7__default.default.bold("\u276F Summary") + "\n");
4298
+ console.log(" " + chalk7__default.default.dim("Project") + " " + chalk7__default.default.bold(projectName));
4115
4299
  console.log(
4116
- " " + chalk3__default.default.dim("Status") + " " + status.icon + " " + status.text
4300
+ " " + chalk7__default.default.dim("Status") + " " + status.icon + " " + status.text
4117
4301
  );
4118
4302
  const completedSteps = steps.filter(
4119
4303
  (s) => completedSetupStepIds.includes(s.id)
@@ -4123,7 +4307,7 @@ function displaySummaryAndNextSteps({
4123
4307
  for (const step of completedSteps) console.log(formatCompletedStep(step));
4124
4308
  }
4125
4309
  const nextSteps = buildNextSteps({ projectName, leftoverSteps, execCmd });
4126
- console.log("\n" + chalk3__default.default.bold("\u276F Next Steps") + "\n");
4310
+ console.log("\n" + chalk7__default.default.bold("\u276F Next Steps") + "\n");
4127
4311
  nextSteps.forEach((step, i) => {
4128
4312
  console.log(formatNextStep(step, i));
4129
4313
  if (step.command) console.log(formatCommand(step.command));
@@ -4185,7 +4369,8 @@ var initPlugin = () => {
4185
4369
  meta: {
4186
4370
  init: {
4187
4371
  categories: ["utility"],
4188
- inputSchema: InitSchema
4372
+ inputSchema: InitSchema,
4373
+ supportsJsonOutput: false
4189
4374
  }
4190
4375
  }
4191
4376
  }
@@ -4204,7 +4389,7 @@ function createZapierCliSdk(options = {}) {
4204
4389
  // package.json with { type: 'json' }
4205
4390
  var package_default2 = {
4206
4391
  name: "@zapier/zapier-sdk-cli",
4207
- version: "0.34.12"};
4392
+ version: "0.35.0"};
4208
4393
  var ONE_DAY_MS = 24 * 60 * 60 * 1e3;
4209
4394
  var CACHE_RESET_INTERVAL_MS = (() => {
4210
4395
  const { ZAPIER_SDK_UPDATE_CHECK_INTERVAL_MS = `${ONE_DAY_MS}` } = process.env;
@@ -4314,26 +4499,26 @@ function displayUpdateNotification(versionInfo, packageName) {
4314
4499
  if (versionInfo.isDeprecated) {
4315
4500
  console.error();
4316
4501
  console.error(
4317
- chalk3__default.default.red.bold("\u26A0\uFE0F DEPRECATION WARNING") + chalk3__default.default.red(
4502
+ chalk7__default.default.red.bold("\u26A0\uFE0F DEPRECATION WARNING") + chalk7__default.default.red(
4318
4503
  ` - ${packageName} v${versionInfo.currentVersion} is deprecated.`
4319
4504
  )
4320
4505
  );
4321
4506
  if (versionInfo.deprecationMessage) {
4322
- console.error(chalk3__default.default.red(` ${versionInfo.deprecationMessage}`));
4507
+ console.error(chalk7__default.default.red(` ${versionInfo.deprecationMessage}`));
4323
4508
  }
4324
- console.error(chalk3__default.default.red(` Please update to the latest version.`));
4509
+ console.error(chalk7__default.default.red(` Please update to the latest version.`));
4325
4510
  console.error();
4326
4511
  }
4327
4512
  if (versionInfo.hasUpdate) {
4328
4513
  console.error();
4329
4514
  console.error(
4330
- chalk3__default.default.yellow.bold("\u{1F4E6} Update available!") + chalk3__default.default.yellow(
4515
+ chalk7__default.default.yellow.bold("\u{1F4E6} Update available!") + chalk7__default.default.yellow(
4331
4516
  ` ${packageName} v${versionInfo.currentVersion} \u2192 v${versionInfo.latestVersion}`
4332
4517
  )
4333
4518
  );
4334
4519
  console.error(
4335
- chalk3__default.default.yellow(
4336
- ` Run ${chalk3__default.default.bold(getUpdateCommand(packageName))} to update.`
4520
+ chalk7__default.default.yellow(
4521
+ ` Run ${chalk7__default.default.bold(getUpdateCommand(packageName))} to update.`
4337
4522
  )
4338
4523
  );
4339
4524
  console.error();