@easysociable/cli 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +4 -1
  2. package/dist/easysociable.js +301 -2829
  3. package/dist/easysociable.js.map +1 -1
  4. package/package.json +17 -12
  5. package/skills/ONBOARDING.md +3 -1
  6. package/skills/easysociable-content/INSTALL.md +60 -0
  7. package/skills/easysociable-content/SKILL.md +107 -96
  8. package/skills/easysociable-content/fixtures/golden-run-en/draft.md +13 -0
  9. package/skills/easysociable-content/fixtures/golden-run-en/idea.md +26 -0
  10. package/skills/easysociable-content/fixtures/golden-run-en/pack-tiktok.json +11 -0
  11. package/skills/easysociable-content/platforms/claude.md +1 -2
  12. package/skills/easysociable-content/platforms/codex.md +1 -2
  13. package/skills/easysociable-content/platforms/hermes.md +1 -2
  14. package/skills/easysociable-content/platforms/openclaw.md +1 -2
  15. package/skills/easysociable-content/references/CLI.md +25 -12
  16. package/skills/easysociable-content/references/CONTRACT_SYNC.md +42 -0
  17. package/skills/easysociable-content/references/MCP.md +7 -12
  18. package/skills/easysociable-content/references/PAGE_PACK.md +128 -5
  19. package/skills/easysociable-content/references/PLATFORM_GUIDE.md +36 -0
  20. package/skills/easysociable-content/references/RUN_LAYOUT.md +73 -0
  21. package/skills/easysociable-content/references/TROUBLESHOOTING.md +11 -9
  22. package/skills/easysociable-content/references/VAULT.md +32 -12
  23. package/skills/easysociable-content/references/VOICE.md +16 -0
  24. package/skills/easysociable-content/scripts/contracts.mjs +183 -0
  25. package/skills/easysociable-content/scripts/export-contracts.mjs +76 -0
  26. package/skills/easysociable-content/scripts/fixture.test.mjs +24 -0
  27. package/skills/easysociable-content/scripts/package-skill.mjs +49 -0
  28. package/skills/easysociable-content/scripts/setup.mjs +127 -83
  29. package/skills/easysociable-content/scripts/setup.test.mjs +49 -38
  30. package/skills/easysociable-content/scripts/starter.mjs +50 -48
  31. package/skills/easysociable-content/scripts/validate-export.mjs +42 -0
  32. package/skills/easysociable-content/scripts/validate-pack.mjs +48 -0
  33. package/skills/easysociable-content/scripts/validate-run.mjs +100 -0
  34. package/skills/easysociable-content/scripts/validate.test.mjs +101 -0
  35. package/skills/easysociable-content/scripts/workbench.mjs +135 -0
  36. package/skills/easysociable-content/starter/CLAUDE.md +756 -0
  37. package/skills/easysociable-content/starter/accounts/README.md +9 -0
  38. package/skills/easysociable-content/starter/accounts/_index.md +31 -0
  39. package/skills/easysociable-content/starter/accounts/overrides/README.md +3 -0
  40. package/skills/easysociable-content/starter/discovery/README.md +18 -0
  41. package/skills/easysociable-content/starter/discovery/_index.md +27 -0
  42. package/skills/easysociable-content/starter/discovery/_template.md +41 -0
  43. package/skills/easysociable-content/starter/engine.json +19 -0
  44. package/skills/easysociable-content/starter/exports/README.md +28 -0
  45. package/skills/easysociable-content/starter/inbox/README.md +9 -0
  46. package/skills/easysociable-content/starter/inbox/_index.md +24 -0
  47. package/skills/easysociable-content/starter/inbox/entries/README.md +3 -0
  48. package/skills/easysociable-content/starter/platforms/README.md +19 -0
  49. package/skills/easysociable-content/starter/platforms/ig.md +69 -0
  50. package/skills/easysociable-content/starter/platforms/instagram.md +5 -0
  51. package/skills/easysociable-content/starter/platforms/linkedin.md +72 -0
  52. package/skills/easysociable-content/starter/platforms/threads.md +69 -0
  53. package/skills/easysociable-content/starter/platforms/tiktok.md +71 -0
  54. package/skills/easysociable-content/starter/platforms/x.md +78 -0
  55. package/skills/easysociable-content/starter/platforms/xiaohongshu.md +19 -0
  56. package/skills/easysociable-content/starter/profiles/_index.md +13 -0
  57. package/skills/easysociable-content/starter/profiles/default/README.md +11 -0
  58. package/skills/easysociable-content/starter/profiles/default/audience.md +38 -0
  59. package/skills/easysociable-content/starter/profiles/default/pillars.md +33 -0
  60. package/skills/easysociable-content/starter/profiles/default/voice.md +24 -0
  61. package/skills/easysociable-content/starter/published/_index.md +20 -0
  62. package/skills/easysociable-content/starter/raw/README.md +4 -0
  63. package/skills/easysociable-content/starter/raw/_index.md +12 -0
  64. package/skills/easysociable-content/starter/runs/README.md +22 -0
  65. package/skills/easysociable-content/starter/runs/_index.md +41 -0
  66. package/skills/easysociable-content/starter/runs/_template/brief.md +66 -0
  67. package/skills/easysociable-content/starter/runs/_template/draft.md +11 -0
  68. package/skills/easysociable-content/starter/runs/_template/editor.md +18 -0
  69. package/skills/easysociable-content/starter/runs/_template/feedback.md +15 -0
  70. package/skills/easysociable-content/starter/runs/_template/idea.md +27 -0
  71. package/skills/easysociable-content/starter/runs/_template/pack.md +47 -0
  72. package/skills/easysociable-content/starter/runs/_template/packet.md +25 -0
  73. package/skills/easysociable-content/starter/runs/_template/rubric.md +19 -0
  74. package/skills/easysociable-content/starter/swipe/_index.md +27 -0
  75. package/skills/easysociable-content/starter/swipe/_template.md +34 -0
  76. package/skills/easysociable-content/starter/topics/README.md +25 -0
  77. package/skills/easysociable-content/starter/topics/WATCHLIST.md +65 -0
  78. package/skills/easysociable-content/starter/topics/_index.md +44 -0
  79. package/skills/easysociable-content/starter/topics/_template-item.md +90 -0
  80. package/skills/easysociable-content/starter/topics/items/README.md +4 -0
  81. package/skills/easysociable-content/starter/topics/scoring.md +201 -0
  82. package/skills/easysociable-content/starter/topics/watchlists/README.md +10 -0
  83. package/skills/easysociable-content/starter/topics/watchlists/_shared.md +14 -0
  84. package/skills/easysociable-content/starter/topics/watchlists/default.md +6 -0
  85. package/skills/easysociable-content/starter/wiki/README.md +13 -0
  86. package/skills/easysociable-content/starter/wiki/atoms/_index.md +23 -0
  87. package/skills/easysociable-content/starter/wiki/atoms/_template.md +31 -0
  88. package/skills/easysociable-content/starter/wiki/claims/_index.md +26 -0
  89. package/skills/easysociable-content/starter/wiki/claims/_template.md +38 -0
  90. package/skills/easysociable-content/starter/workbench/README.md +17 -0
  91. package/skills/easysociable-content/workbench/build.py +1074 -0
  92. package/skills/easysociable-content/workbench/serve.py +53 -0
  93. package/skills/easysociable-content/workbench/template.html +2119 -0
  94. package/skills/easysociable-content/workflows/ANALYSIS_AND_COVERAGE.md +14 -5
  95. package/skills/easysociable-content/workflows/CONTENT_EXPORT.md +16 -11
  96. package/skills/easysociable-content/workflows/GETTING_STARTED.md +40 -0
  97. package/skills/easysociable-content/workflows/MCP_FIRST.md +3 -8
  98. package/skills/easysociable-content/workflows/OUT_OF_SCOPE.md +18 -0
  99. package/skills/easysociable-content/workflows/PACK_AUTHORING.md +42 -0
  100. package/skills/easysociable-content/workflows/SWIPE_CAPTURE.md +18 -0
  101. package/skills/easysociable-content/workflows/TOPIC_DRAFT.md +28 -4
  102. package/skills/easysociable-content/workflows/WORKING_DRAFT.md +17 -8
  103. package/skills/easysociable-slideshow/SKILL.md +20 -13
  104. package/skills/easysociable-slideshow/references/VAULT.md +13 -11
  105. package/skills/easysociable-template/scripts/generate-theme-from-hex.mjs +0 -0
  106. package/skills/easysociable-content/workflows/DEVICE_TASKS.md +0 -5
  107. package/skills/easysociable-content/workflows/EXPERIMENTS.md +0 -6
  108. package/skills/easysociable-content/workflows/PUBLICATION.md +0 -5
@@ -4,16 +4,10 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __getProtoOf = Object.getPrototypeOf;
6
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
- }) : x)(function(x) {
10
- if (typeof require !== "undefined") return require.apply(this, arguments);
11
- throw Error('Dynamic require of "' + x + '" is not supported');
12
- });
13
7
  var __esm = (fn, res) => function __init() {
14
8
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
15
9
  };
16
- var __commonJS = (cb, mod) => function __require2() {
10
+ var __commonJS = (cb, mod) => function __require() {
17
11
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
12
  };
19
13
  var __export = (target, all) => {
@@ -37,2751 +31,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
37
31
  mod
38
32
  ));
39
33
 
40
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/error.js
41
- var require_error = __commonJS({
42
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/error.js"(exports) {
43
- "use strict";
44
- var CommanderError2 = class extends Error {
45
- /**
46
- * Constructs the CommanderError class
47
- * @param {number} exitCode suggested exit code which could be used with process.exit
48
- * @param {string} code an id string representing the error
49
- * @param {string} message human-readable description of the error
50
- * @constructor
51
- */
52
- constructor(exitCode2, code, message) {
53
- super(message);
54
- Error.captureStackTrace(this, this.constructor);
55
- this.name = this.constructor.name;
56
- this.code = code;
57
- this.exitCode = exitCode2;
58
- this.nestedError = void 0;
59
- }
60
- };
61
- var InvalidArgumentError2 = class extends CommanderError2 {
62
- /**
63
- * Constructs the InvalidArgumentError class
64
- * @param {string} [message] explanation of why argument is invalid
65
- * @constructor
66
- */
67
- constructor(message) {
68
- super(1, "commander.invalidArgument", message);
69
- Error.captureStackTrace(this, this.constructor);
70
- this.name = this.constructor.name;
71
- }
72
- };
73
- exports.CommanderError = CommanderError2;
74
- exports.InvalidArgumentError = InvalidArgumentError2;
75
- }
76
- });
77
-
78
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/argument.js
79
- var require_argument = __commonJS({
80
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/argument.js"(exports) {
81
- "use strict";
82
- var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
83
- var Argument2 = class {
84
- /**
85
- * Initialize a new command argument with the given name and description.
86
- * The default is that the argument is required, and you can explicitly
87
- * indicate this with <> around the name. Put [] around the name for an optional argument.
88
- *
89
- * @param {string} name
90
- * @param {string} [description]
91
- */
92
- constructor(name, description) {
93
- this.description = description || "";
94
- this.variadic = false;
95
- this.parseArg = void 0;
96
- this.defaultValue = void 0;
97
- this.defaultValueDescription = void 0;
98
- this.argChoices = void 0;
99
- switch (name[0]) {
100
- case "<":
101
- this.required = true;
102
- this._name = name.slice(1, -1);
103
- break;
104
- case "[":
105
- this.required = false;
106
- this._name = name.slice(1, -1);
107
- break;
108
- default:
109
- this.required = true;
110
- this._name = name;
111
- break;
112
- }
113
- if (this._name.length > 3 && this._name.slice(-3) === "...") {
114
- this.variadic = true;
115
- this._name = this._name.slice(0, -3);
116
- }
117
- }
118
- /**
119
- * Return argument name.
120
- *
121
- * @return {string}
122
- */
123
- name() {
124
- return this._name;
125
- }
126
- /**
127
- * @api private
128
- */
129
- _concatValue(value, previous) {
130
- if (previous === this.defaultValue || !Array.isArray(previous)) {
131
- return [value];
132
- }
133
- return previous.concat(value);
134
- }
135
- /**
136
- * Set the default value, and optionally supply the description to be displayed in the help.
137
- *
138
- * @param {*} value
139
- * @param {string} [description]
140
- * @return {Argument}
141
- */
142
- default(value, description) {
143
- this.defaultValue = value;
144
- this.defaultValueDescription = description;
145
- return this;
146
- }
147
- /**
148
- * Set the custom handler for processing CLI command arguments into argument values.
149
- *
150
- * @param {Function} [fn]
151
- * @return {Argument}
152
- */
153
- argParser(fn) {
154
- this.parseArg = fn;
155
- return this;
156
- }
157
- /**
158
- * Only allow argument value to be one of choices.
159
- *
160
- * @param {string[]} values
161
- * @return {Argument}
162
- */
163
- choices(values) {
164
- this.argChoices = values.slice();
165
- this.parseArg = (arg, previous) => {
166
- if (!this.argChoices.includes(arg)) {
167
- throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
168
- }
169
- if (this.variadic) {
170
- return this._concatValue(arg, previous);
171
- }
172
- return arg;
173
- };
174
- return this;
175
- }
176
- /**
177
- * Make argument required.
178
- */
179
- argRequired() {
180
- this.required = true;
181
- return this;
182
- }
183
- /**
184
- * Make argument optional.
185
- */
186
- argOptional() {
187
- this.required = false;
188
- return this;
189
- }
190
- };
191
- function humanReadableArgName(arg) {
192
- const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
193
- return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
194
- }
195
- exports.Argument = Argument2;
196
- exports.humanReadableArgName = humanReadableArgName;
197
- }
198
- });
199
-
200
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/help.js
201
- var require_help = __commonJS({
202
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/help.js"(exports) {
203
- "use strict";
204
- var { humanReadableArgName } = require_argument();
205
- var Help2 = class {
206
- constructor() {
207
- this.helpWidth = void 0;
208
- this.sortSubcommands = false;
209
- this.sortOptions = false;
210
- this.showGlobalOptions = false;
211
- }
212
- /**
213
- * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
214
- *
215
- * @param {Command} cmd
216
- * @returns {Command[]}
217
- */
218
- visibleCommands(cmd) {
219
- const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
220
- if (cmd._hasImplicitHelpCommand()) {
221
- const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);
222
- const helpCommand = cmd.createCommand(helpName).helpOption(false);
223
- helpCommand.description(cmd._helpCommandDescription);
224
- if (helpArgs) helpCommand.arguments(helpArgs);
225
- visibleCommands.push(helpCommand);
226
- }
227
- if (this.sortSubcommands) {
228
- visibleCommands.sort((a, b) => {
229
- return a.name().localeCompare(b.name());
230
- });
231
- }
232
- return visibleCommands;
233
- }
234
- /**
235
- * Compare options for sort.
236
- *
237
- * @param {Option} a
238
- * @param {Option} b
239
- * @returns number
240
- */
241
- compareOptions(a, b) {
242
- const getSortKey = (option) => {
243
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
244
- };
245
- return getSortKey(a).localeCompare(getSortKey(b));
246
- }
247
- /**
248
- * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
249
- *
250
- * @param {Command} cmd
251
- * @returns {Option[]}
252
- */
253
- visibleOptions(cmd) {
254
- const visibleOptions = cmd.options.filter((option) => !option.hidden);
255
- const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);
256
- const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);
257
- if (showShortHelpFlag || showLongHelpFlag) {
258
- let helpOption;
259
- if (!showShortHelpFlag) {
260
- helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);
261
- } else if (!showLongHelpFlag) {
262
- helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);
263
- } else {
264
- helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);
265
- }
266
- visibleOptions.push(helpOption);
267
- }
268
- if (this.sortOptions) {
269
- visibleOptions.sort(this.compareOptions);
270
- }
271
- return visibleOptions;
272
- }
273
- /**
274
- * Get an array of the visible global options. (Not including help.)
275
- *
276
- * @param {Command} cmd
277
- * @returns {Option[]}
278
- */
279
- visibleGlobalOptions(cmd) {
280
- if (!this.showGlobalOptions) return [];
281
- const globalOptions = [];
282
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
283
- const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
284
- globalOptions.push(...visibleOptions);
285
- }
286
- if (this.sortOptions) {
287
- globalOptions.sort(this.compareOptions);
288
- }
289
- return globalOptions;
290
- }
291
- /**
292
- * Get an array of the arguments if any have a description.
293
- *
294
- * @param {Command} cmd
295
- * @returns {Argument[]}
296
- */
297
- visibleArguments(cmd) {
298
- if (cmd._argsDescription) {
299
- cmd.registeredArguments.forEach((argument) => {
300
- argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
301
- });
302
- }
303
- if (cmd.registeredArguments.find((argument) => argument.description)) {
304
- return cmd.registeredArguments;
305
- }
306
- return [];
307
- }
308
- /**
309
- * Get the command term to show in the list of subcommands.
310
- *
311
- * @param {Command} cmd
312
- * @returns {string}
313
- */
314
- subcommandTerm(cmd) {
315
- const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
316
- return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
317
- (args ? " " + args : "");
318
- }
319
- /**
320
- * Get the option term to show in the list of options.
321
- *
322
- * @param {Option} option
323
- * @returns {string}
324
- */
325
- optionTerm(option) {
326
- return option.flags;
327
- }
328
- /**
329
- * Get the argument term to show in the list of arguments.
330
- *
331
- * @param {Argument} argument
332
- * @returns {string}
333
- */
334
- argumentTerm(argument) {
335
- return argument.name();
336
- }
337
- /**
338
- * Get the longest command term length.
339
- *
340
- * @param {Command} cmd
341
- * @param {Help} helper
342
- * @returns {number}
343
- */
344
- longestSubcommandTermLength(cmd, helper) {
345
- return helper.visibleCommands(cmd).reduce((max, command) => {
346
- return Math.max(max, helper.subcommandTerm(command).length);
347
- }, 0);
348
- }
349
- /**
350
- * Get the longest option term length.
351
- *
352
- * @param {Command} cmd
353
- * @param {Help} helper
354
- * @returns {number}
355
- */
356
- longestOptionTermLength(cmd, helper) {
357
- return helper.visibleOptions(cmd).reduce((max, option) => {
358
- return Math.max(max, helper.optionTerm(option).length);
359
- }, 0);
360
- }
361
- /**
362
- * Get the longest global option term length.
363
- *
364
- * @param {Command} cmd
365
- * @param {Help} helper
366
- * @returns {number}
367
- */
368
- longestGlobalOptionTermLength(cmd, helper) {
369
- return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
370
- return Math.max(max, helper.optionTerm(option).length);
371
- }, 0);
372
- }
373
- /**
374
- * Get the longest argument term length.
375
- *
376
- * @param {Command} cmd
377
- * @param {Help} helper
378
- * @returns {number}
379
- */
380
- longestArgumentTermLength(cmd, helper) {
381
- return helper.visibleArguments(cmd).reduce((max, argument) => {
382
- return Math.max(max, helper.argumentTerm(argument).length);
383
- }, 0);
384
- }
385
- /**
386
- * Get the command usage to be displayed at the top of the built-in help.
387
- *
388
- * @param {Command} cmd
389
- * @returns {string}
390
- */
391
- commandUsage(cmd) {
392
- let cmdName = cmd._name;
393
- if (cmd._aliases[0]) {
394
- cmdName = cmdName + "|" + cmd._aliases[0];
395
- }
396
- let ancestorCmdNames = "";
397
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
398
- ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
399
- }
400
- return ancestorCmdNames + cmdName + " " + cmd.usage();
401
- }
402
- /**
403
- * Get the description for the command.
404
- *
405
- * @param {Command} cmd
406
- * @returns {string}
407
- */
408
- commandDescription(cmd) {
409
- return cmd.description();
410
- }
411
- /**
412
- * Get the subcommand summary to show in the list of subcommands.
413
- * (Fallback to description for backwards compatibility.)
414
- *
415
- * @param {Command} cmd
416
- * @returns {string}
417
- */
418
- subcommandDescription(cmd) {
419
- return cmd.summary() || cmd.description();
420
- }
421
- /**
422
- * Get the option description to show in the list of options.
423
- *
424
- * @param {Option} option
425
- * @return {string}
426
- */
427
- optionDescription(option) {
428
- const extraInfo = [];
429
- if (option.argChoices) {
430
- extraInfo.push(
431
- // use stringify to match the display of the default value
432
- `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
433
- );
434
- }
435
- if (option.defaultValue !== void 0) {
436
- const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
437
- if (showDefault) {
438
- extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
439
- }
440
- }
441
- if (option.presetArg !== void 0 && option.optional) {
442
- extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
443
- }
444
- if (option.envVar !== void 0) {
445
- extraInfo.push(`env: ${option.envVar}`);
446
- }
447
- if (extraInfo.length > 0) {
448
- return `${option.description} (${extraInfo.join(", ")})`;
449
- }
450
- return option.description;
451
- }
452
- /**
453
- * Get the argument description to show in the list of arguments.
454
- *
455
- * @param {Argument} argument
456
- * @return {string}
457
- */
458
- argumentDescription(argument) {
459
- const extraInfo = [];
460
- if (argument.argChoices) {
461
- extraInfo.push(
462
- // use stringify to match the display of the default value
463
- `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
464
- );
465
- }
466
- if (argument.defaultValue !== void 0) {
467
- extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
468
- }
469
- if (extraInfo.length > 0) {
470
- const extraDescripton = `(${extraInfo.join(", ")})`;
471
- if (argument.description) {
472
- return `${argument.description} ${extraDescripton}`;
473
- }
474
- return extraDescripton;
475
- }
476
- return argument.description;
477
- }
478
- /**
479
- * Generate the built-in help text.
480
- *
481
- * @param {Command} cmd
482
- * @param {Help} helper
483
- * @returns {string}
484
- */
485
- formatHelp(cmd, helper) {
486
- const termWidth = helper.padWidth(cmd, helper);
487
- const helpWidth = helper.helpWidth || 80;
488
- const itemIndentWidth = 2;
489
- const itemSeparatorWidth = 2;
490
- function formatItem(term, description) {
491
- if (description) {
492
- const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
493
- return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
494
- }
495
- return term;
496
- }
497
- function formatList(textArray) {
498
- return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
499
- }
500
- let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
501
- const commandDescription = helper.commandDescription(cmd);
502
- if (commandDescription.length > 0) {
503
- output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ""]);
504
- }
505
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
506
- return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
507
- });
508
- if (argumentList.length > 0) {
509
- output = output.concat(["Arguments:", formatList(argumentList), ""]);
510
- }
511
- const optionList = helper.visibleOptions(cmd).map((option) => {
512
- return formatItem(helper.optionTerm(option), helper.optionDescription(option));
513
- });
514
- if (optionList.length > 0) {
515
- output = output.concat(["Options:", formatList(optionList), ""]);
516
- }
517
- if (this.showGlobalOptions) {
518
- const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
519
- return formatItem(helper.optionTerm(option), helper.optionDescription(option));
520
- });
521
- if (globalOptionList.length > 0) {
522
- output = output.concat(["Global Options:", formatList(globalOptionList), ""]);
523
- }
524
- }
525
- const commandList = helper.visibleCommands(cmd).map((cmd2) => {
526
- return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
527
- });
528
- if (commandList.length > 0) {
529
- output = output.concat(["Commands:", formatList(commandList), ""]);
530
- }
531
- return output.join("\n");
532
- }
533
- /**
534
- * Calculate the pad width from the maximum term length.
535
- *
536
- * @param {Command} cmd
537
- * @param {Help} helper
538
- * @returns {number}
539
- */
540
- padWidth(cmd, helper) {
541
- return Math.max(
542
- helper.longestOptionTermLength(cmd, helper),
543
- helper.longestGlobalOptionTermLength(cmd, helper),
544
- helper.longestSubcommandTermLength(cmd, helper),
545
- helper.longestArgumentTermLength(cmd, helper)
546
- );
547
- }
548
- /**
549
- * Wrap the given string to width characters per line, with lines after the first indented.
550
- * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
551
- *
552
- * @param {string} str
553
- * @param {number} width
554
- * @param {number} indent
555
- * @param {number} [minColumnWidth=40]
556
- * @return {string}
557
- *
558
- */
559
- wrap(str, width, indent, minColumnWidth = 40) {
560
- const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
561
- const manualIndent = new RegExp(`[\\n][${indents}]+`);
562
- if (str.match(manualIndent)) return str;
563
- const columnWidth = width - indent;
564
- if (columnWidth < minColumnWidth) return str;
565
- const leadingStr = str.slice(0, indent);
566
- const columnText = str.slice(indent).replace("\r\n", "\n");
567
- const indentString = " ".repeat(indent);
568
- const zeroWidthSpace = "\u200B";
569
- const breaks = `\\s${zeroWidthSpace}`;
570
- const regex = new RegExp(`
571
- |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
572
- const lines = columnText.match(regex) || [];
573
- return leadingStr + lines.map((line, i) => {
574
- if (line === "\n") return "";
575
- return (i > 0 ? indentString : "") + line.trimEnd();
576
- }).join("\n");
577
- }
578
- };
579
- exports.Help = Help2;
580
- }
581
- });
582
-
583
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/option.js
584
- var require_option = __commonJS({
585
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/option.js"(exports) {
586
- "use strict";
587
- var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
588
- var Option2 = class {
589
- /**
590
- * Initialize a new `Option` with the given `flags` and `description`.
591
- *
592
- * @param {string} flags
593
- * @param {string} [description]
594
- */
595
- constructor(flags, description) {
596
- this.flags = flags;
597
- this.description = description || "";
598
- this.required = flags.includes("<");
599
- this.optional = flags.includes("[");
600
- this.variadic = /\w\.\.\.[>\]]$/.test(flags);
601
- this.mandatory = false;
602
- const optionFlags = splitOptionFlags(flags);
603
- this.short = optionFlags.shortFlag;
604
- this.long = optionFlags.longFlag;
605
- this.negate = false;
606
- if (this.long) {
607
- this.negate = this.long.startsWith("--no-");
608
- }
609
- this.defaultValue = void 0;
610
- this.defaultValueDescription = void 0;
611
- this.presetArg = void 0;
612
- this.envVar = void 0;
613
- this.parseArg = void 0;
614
- this.hidden = false;
615
- this.argChoices = void 0;
616
- this.conflictsWith = [];
617
- this.implied = void 0;
618
- }
619
- /**
620
- * Set the default value, and optionally supply the description to be displayed in the help.
621
- *
622
- * @param {*} value
623
- * @param {string} [description]
624
- * @return {Option}
625
- */
626
- default(value, description) {
627
- this.defaultValue = value;
628
- this.defaultValueDescription = description;
629
- return this;
630
- }
631
- /**
632
- * Preset to use when option used without option-argument, especially optional but also boolean and negated.
633
- * The custom processing (parseArg) is called.
634
- *
635
- * @example
636
- * new Option('--color').default('GREYSCALE').preset('RGB');
637
- * new Option('--donate [amount]').preset('20').argParser(parseFloat);
638
- *
639
- * @param {*} arg
640
- * @return {Option}
641
- */
642
- preset(arg) {
643
- this.presetArg = arg;
644
- return this;
645
- }
646
- /**
647
- * Add option name(s) that conflict with this option.
648
- * An error will be displayed if conflicting options are found during parsing.
649
- *
650
- * @example
651
- * new Option('--rgb').conflicts('cmyk');
652
- * new Option('--js').conflicts(['ts', 'jsx']);
653
- *
654
- * @param {string | string[]} names
655
- * @return {Option}
656
- */
657
- conflicts(names) {
658
- this.conflictsWith = this.conflictsWith.concat(names);
659
- return this;
660
- }
661
- /**
662
- * Specify implied option values for when this option is set and the implied options are not.
663
- *
664
- * The custom processing (parseArg) is not called on the implied values.
665
- *
666
- * @example
667
- * program
668
- * .addOption(new Option('--log', 'write logging information to file'))
669
- * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
670
- *
671
- * @param {Object} impliedOptionValues
672
- * @return {Option}
673
- */
674
- implies(impliedOptionValues) {
675
- let newImplied = impliedOptionValues;
676
- if (typeof impliedOptionValues === "string") {
677
- newImplied = { [impliedOptionValues]: true };
678
- }
679
- this.implied = Object.assign(this.implied || {}, newImplied);
680
- return this;
681
- }
682
- /**
683
- * Set environment variable to check for option value.
684
- *
685
- * An environment variable is only used if when processed the current option value is
686
- * undefined, or the source of the current value is 'default' or 'config' or 'env'.
687
- *
688
- * @param {string} name
689
- * @return {Option}
690
- */
691
- env(name) {
692
- this.envVar = name;
693
- return this;
694
- }
695
- /**
696
- * Set the custom handler for processing CLI option arguments into option values.
697
- *
698
- * @param {Function} [fn]
699
- * @return {Option}
700
- */
701
- argParser(fn) {
702
- this.parseArg = fn;
703
- return this;
704
- }
705
- /**
706
- * Whether the option is mandatory and must have a value after parsing.
707
- *
708
- * @param {boolean} [mandatory=true]
709
- * @return {Option}
710
- */
711
- makeOptionMandatory(mandatory = true) {
712
- this.mandatory = !!mandatory;
713
- return this;
714
- }
715
- /**
716
- * Hide option in help.
717
- *
718
- * @param {boolean} [hide=true]
719
- * @return {Option}
720
- */
721
- hideHelp(hide = true) {
722
- this.hidden = !!hide;
723
- return this;
724
- }
725
- /**
726
- * @api private
727
- */
728
- _concatValue(value, previous) {
729
- if (previous === this.defaultValue || !Array.isArray(previous)) {
730
- return [value];
731
- }
732
- return previous.concat(value);
733
- }
734
- /**
735
- * Only allow option value to be one of choices.
736
- *
737
- * @param {string[]} values
738
- * @return {Option}
739
- */
740
- choices(values) {
741
- this.argChoices = values.slice();
742
- this.parseArg = (arg, previous) => {
743
- if (!this.argChoices.includes(arg)) {
744
- throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
745
- }
746
- if (this.variadic) {
747
- return this._concatValue(arg, previous);
748
- }
749
- return arg;
750
- };
751
- return this;
752
- }
753
- /**
754
- * Return option name.
755
- *
756
- * @return {string}
757
- */
758
- name() {
759
- if (this.long) {
760
- return this.long.replace(/^--/, "");
761
- }
762
- return this.short.replace(/^-/, "");
763
- }
764
- /**
765
- * Return option name, in a camelcase format that can be used
766
- * as a object attribute key.
767
- *
768
- * @return {string}
769
- * @api private
770
- */
771
- attributeName() {
772
- return camelcase(this.name().replace(/^no-/, ""));
773
- }
774
- /**
775
- * Check if `arg` matches the short or long flag.
776
- *
777
- * @param {string} arg
778
- * @return {boolean}
779
- * @api private
780
- */
781
- is(arg) {
782
- return this.short === arg || this.long === arg;
783
- }
784
- /**
785
- * Return whether a boolean option.
786
- *
787
- * Options are one of boolean, negated, required argument, or optional argument.
788
- *
789
- * @return {boolean}
790
- * @api private
791
- */
792
- isBoolean() {
793
- return !this.required && !this.optional && !this.negate;
794
- }
795
- };
796
- var DualOptions = class {
797
- /**
798
- * @param {Option[]} options
799
- */
800
- constructor(options) {
801
- this.positiveOptions = /* @__PURE__ */ new Map();
802
- this.negativeOptions = /* @__PURE__ */ new Map();
803
- this.dualOptions = /* @__PURE__ */ new Set();
804
- options.forEach((option) => {
805
- if (option.negate) {
806
- this.negativeOptions.set(option.attributeName(), option);
807
- } else {
808
- this.positiveOptions.set(option.attributeName(), option);
809
- }
810
- });
811
- this.negativeOptions.forEach((value, key) => {
812
- if (this.positiveOptions.has(key)) {
813
- this.dualOptions.add(key);
814
- }
815
- });
816
- }
817
- /**
818
- * Did the value come from the option, and not from possible matching dual option?
819
- *
820
- * @param {*} value
821
- * @param {Option} option
822
- * @returns {boolean}
823
- */
824
- valueFromOption(value, option) {
825
- const optionKey = option.attributeName();
826
- if (!this.dualOptions.has(optionKey)) return true;
827
- const preset = this.negativeOptions.get(optionKey).presetArg;
828
- const negativeValue = preset !== void 0 ? preset : false;
829
- return option.negate === (negativeValue === value);
830
- }
831
- };
832
- function camelcase(str) {
833
- return str.split("-").reduce((str2, word) => {
834
- return str2 + word[0].toUpperCase() + word.slice(1);
835
- });
836
- }
837
- function splitOptionFlags(flags) {
838
- let shortFlag;
839
- let longFlag;
840
- const flagParts = flags.split(/[ |,]+/);
841
- if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
842
- longFlag = flagParts.shift();
843
- if (!shortFlag && /^-[^-]$/.test(longFlag)) {
844
- shortFlag = longFlag;
845
- longFlag = void 0;
846
- }
847
- return { shortFlag, longFlag };
848
- }
849
- exports.Option = Option2;
850
- exports.splitOptionFlags = splitOptionFlags;
851
- exports.DualOptions = DualOptions;
852
- }
853
- });
854
-
855
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/suggestSimilar.js
856
- var require_suggestSimilar = __commonJS({
857
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/suggestSimilar.js"(exports) {
858
- "use strict";
859
- var maxDistance = 3;
860
- function editDistance(a, b) {
861
- if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
862
- const d = [];
863
- for (let i = 0; i <= a.length; i++) {
864
- d[i] = [i];
865
- }
866
- for (let j = 0; j <= b.length; j++) {
867
- d[0][j] = j;
868
- }
869
- for (let j = 1; j <= b.length; j++) {
870
- for (let i = 1; i <= a.length; i++) {
871
- let cost = 1;
872
- if (a[i - 1] === b[j - 1]) {
873
- cost = 0;
874
- } else {
875
- cost = 1;
876
- }
877
- d[i][j] = Math.min(
878
- d[i - 1][j] + 1,
879
- // deletion
880
- d[i][j - 1] + 1,
881
- // insertion
882
- d[i - 1][j - 1] + cost
883
- // substitution
884
- );
885
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
886
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
887
- }
888
- }
889
- }
890
- return d[a.length][b.length];
891
- }
892
- function suggestSimilar(word, candidates) {
893
- if (!candidates || candidates.length === 0) return "";
894
- candidates = Array.from(new Set(candidates));
895
- const searchingOptions = word.startsWith("--");
896
- if (searchingOptions) {
897
- word = word.slice(2);
898
- candidates = candidates.map((candidate) => candidate.slice(2));
899
- }
900
- let similar = [];
901
- let bestDistance = maxDistance;
902
- const minSimilarity = 0.4;
903
- candidates.forEach((candidate) => {
904
- if (candidate.length <= 1) return;
905
- const distance = editDistance(word, candidate);
906
- const length = Math.max(word.length, candidate.length);
907
- const similarity = (length - distance) / length;
908
- if (similarity > minSimilarity) {
909
- if (distance < bestDistance) {
910
- bestDistance = distance;
911
- similar = [candidate];
912
- } else if (distance === bestDistance) {
913
- similar.push(candidate);
914
- }
915
- }
916
- });
917
- similar.sort((a, b) => a.localeCompare(b));
918
- if (searchingOptions) {
919
- similar = similar.map((candidate) => `--${candidate}`);
920
- }
921
- if (similar.length > 1) {
922
- return `
923
- (Did you mean one of ${similar.join(", ")}?)`;
924
- }
925
- if (similar.length === 1) {
926
- return `
927
- (Did you mean ${similar[0]}?)`;
928
- }
929
- return "";
930
- }
931
- exports.suggestSimilar = suggestSimilar;
932
- }
933
- });
934
-
935
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/command.js
936
- var require_command = __commonJS({
937
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/lib/command.js"(exports) {
938
- "use strict";
939
- var EventEmitter = __require("events").EventEmitter;
940
- var childProcess = __require("child_process");
941
- var path = __require("path");
942
- var fs = __require("fs");
943
- var process4 = __require("process");
944
- var { Argument: Argument2, humanReadableArgName } = require_argument();
945
- var { CommanderError: CommanderError2 } = require_error();
946
- var { Help: Help2 } = require_help();
947
- var { Option: Option2, splitOptionFlags, DualOptions } = require_option();
948
- var { suggestSimilar } = require_suggestSimilar();
949
- var Command2 = class _Command extends EventEmitter {
950
- /**
951
- * Initialize a new `Command`.
952
- *
953
- * @param {string} [name]
954
- */
955
- constructor(name) {
956
- super();
957
- this.commands = [];
958
- this.options = [];
959
- this.parent = null;
960
- this._allowUnknownOption = false;
961
- this._allowExcessArguments = true;
962
- this.registeredArguments = [];
963
- this._args = this.registeredArguments;
964
- this.args = [];
965
- this.rawArgs = [];
966
- this.processedArgs = [];
967
- this._scriptPath = null;
968
- this._name = name || "";
969
- this._optionValues = {};
970
- this._optionValueSources = {};
971
- this._storeOptionsAsProperties = false;
972
- this._actionHandler = null;
973
- this._executableHandler = false;
974
- this._executableFile = null;
975
- this._executableDir = null;
976
- this._defaultCommandName = null;
977
- this._exitCallback = null;
978
- this._aliases = [];
979
- this._combineFlagAndOptionalValue = true;
980
- this._description = "";
981
- this._summary = "";
982
- this._argsDescription = void 0;
983
- this._enablePositionalOptions = false;
984
- this._passThroughOptions = false;
985
- this._lifeCycleHooks = {};
986
- this._showHelpAfterError = false;
987
- this._showSuggestionAfterError = true;
988
- this._outputConfiguration = {
989
- writeOut: (str) => process4.stdout.write(str),
990
- writeErr: (str) => process4.stderr.write(str),
991
- getOutHelpWidth: () => process4.stdout.isTTY ? process4.stdout.columns : void 0,
992
- getErrHelpWidth: () => process4.stderr.isTTY ? process4.stderr.columns : void 0,
993
- outputError: (str, write) => write(str)
994
- };
995
- this._hidden = false;
996
- this._hasHelpOption = true;
997
- this._helpFlags = "-h, --help";
998
- this._helpDescription = "display help for command";
999
- this._helpShortFlag = "-h";
1000
- this._helpLongFlag = "--help";
1001
- this._addImplicitHelpCommand = void 0;
1002
- this._helpCommandName = "help";
1003
- this._helpCommandnameAndArgs = "help [command]";
1004
- this._helpCommandDescription = "display help for command";
1005
- this._helpConfiguration = {};
1006
- }
1007
- /**
1008
- * Copy settings that are useful to have in common across root command and subcommands.
1009
- *
1010
- * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1011
- *
1012
- * @param {Command} sourceCommand
1013
- * @return {Command} `this` command for chaining
1014
- */
1015
- copyInheritedSettings(sourceCommand) {
1016
- this._outputConfiguration = sourceCommand._outputConfiguration;
1017
- this._hasHelpOption = sourceCommand._hasHelpOption;
1018
- this._helpFlags = sourceCommand._helpFlags;
1019
- this._helpDescription = sourceCommand._helpDescription;
1020
- this._helpShortFlag = sourceCommand._helpShortFlag;
1021
- this._helpLongFlag = sourceCommand._helpLongFlag;
1022
- this._helpCommandName = sourceCommand._helpCommandName;
1023
- this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;
1024
- this._helpCommandDescription = sourceCommand._helpCommandDescription;
1025
- this._helpConfiguration = sourceCommand._helpConfiguration;
1026
- this._exitCallback = sourceCommand._exitCallback;
1027
- this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1028
- this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1029
- this._allowExcessArguments = sourceCommand._allowExcessArguments;
1030
- this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1031
- this._showHelpAfterError = sourceCommand._showHelpAfterError;
1032
- this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1033
- return this;
1034
- }
1035
- /**
1036
- * @returns {Command[]}
1037
- * @api private
1038
- */
1039
- _getCommandAndAncestors() {
1040
- const result = [];
1041
- for (let command = this; command; command = command.parent) {
1042
- result.push(command);
1043
- }
1044
- return result;
1045
- }
1046
- /**
1047
- * Define a command.
1048
- *
1049
- * There are two styles of command: pay attention to where to put the description.
1050
- *
1051
- * @example
1052
- * // Command implemented using action handler (description is supplied separately to `.command`)
1053
- * program
1054
- * .command('clone <source> [destination]')
1055
- * .description('clone a repository into a newly created directory')
1056
- * .action((source, destination) => {
1057
- * console.log('clone command called');
1058
- * });
1059
- *
1060
- * // Command implemented using separate executable file (description is second parameter to `.command`)
1061
- * program
1062
- * .command('start <service>', 'start named service')
1063
- * .command('stop [service]', 'stop named service, or all if no name supplied');
1064
- *
1065
- * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1066
- * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1067
- * @param {Object} [execOpts] - configuration options (for executable)
1068
- * @return {Command} returns new command for action handler, or `this` for executable command
1069
- */
1070
- command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1071
- let desc = actionOptsOrExecDesc;
1072
- let opts = execOpts;
1073
- if (typeof desc === "object" && desc !== null) {
1074
- opts = desc;
1075
- desc = null;
1076
- }
1077
- opts = opts || {};
1078
- const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1079
- const cmd = this.createCommand(name);
1080
- if (desc) {
1081
- cmd.description(desc);
1082
- cmd._executableHandler = true;
1083
- }
1084
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1085
- cmd._hidden = !!(opts.noHelp || opts.hidden);
1086
- cmd._executableFile = opts.executableFile || null;
1087
- if (args) cmd.arguments(args);
1088
- this.commands.push(cmd);
1089
- cmd.parent = this;
1090
- cmd.copyInheritedSettings(this);
1091
- if (desc) return this;
1092
- return cmd;
1093
- }
1094
- /**
1095
- * Factory routine to create a new unattached command.
1096
- *
1097
- * See .command() for creating an attached subcommand, which uses this routine to
1098
- * create the command. You can override createCommand to customise subcommands.
1099
- *
1100
- * @param {string} [name]
1101
- * @return {Command} new command
1102
- */
1103
- createCommand(name) {
1104
- return new _Command(name);
1105
- }
1106
- /**
1107
- * You can customise the help with a subclass of Help by overriding createHelp,
1108
- * or by overriding Help properties using configureHelp().
1109
- *
1110
- * @return {Help}
1111
- */
1112
- createHelp() {
1113
- return Object.assign(new Help2(), this.configureHelp());
1114
- }
1115
- /**
1116
- * You can customise the help by overriding Help properties using configureHelp(),
1117
- * or with a subclass of Help by overriding createHelp().
1118
- *
1119
- * @param {Object} [configuration] - configuration options
1120
- * @return {Command|Object} `this` command for chaining, or stored configuration
1121
- */
1122
- configureHelp(configuration) {
1123
- if (configuration === void 0) return this._helpConfiguration;
1124
- this._helpConfiguration = configuration;
1125
- return this;
1126
- }
1127
- /**
1128
- * The default output goes to stdout and stderr. You can customise this for special
1129
- * applications. You can also customise the display of errors by overriding outputError.
1130
- *
1131
- * The configuration properties are all functions:
1132
- *
1133
- * // functions to change where being written, stdout and stderr
1134
- * writeOut(str)
1135
- * writeErr(str)
1136
- * // matching functions to specify width for wrapping help
1137
- * getOutHelpWidth()
1138
- * getErrHelpWidth()
1139
- * // functions based on what is being written out
1140
- * outputError(str, write) // used for displaying errors, and not used for displaying help
1141
- *
1142
- * @param {Object} [configuration] - configuration options
1143
- * @return {Command|Object} `this` command for chaining, or stored configuration
1144
- */
1145
- configureOutput(configuration) {
1146
- if (configuration === void 0) return this._outputConfiguration;
1147
- Object.assign(this._outputConfiguration, configuration);
1148
- return this;
1149
- }
1150
- /**
1151
- * Display the help or a custom message after an error occurs.
1152
- *
1153
- * @param {boolean|string} [displayHelp]
1154
- * @return {Command} `this` command for chaining
1155
- */
1156
- showHelpAfterError(displayHelp = true) {
1157
- if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1158
- this._showHelpAfterError = displayHelp;
1159
- return this;
1160
- }
1161
- /**
1162
- * Display suggestion of similar commands for unknown commands, or options for unknown options.
1163
- *
1164
- * @param {boolean} [displaySuggestion]
1165
- * @return {Command} `this` command for chaining
1166
- */
1167
- showSuggestionAfterError(displaySuggestion = true) {
1168
- this._showSuggestionAfterError = !!displaySuggestion;
1169
- return this;
1170
- }
1171
- /**
1172
- * Add a prepared subcommand.
1173
- *
1174
- * See .command() for creating an attached subcommand which inherits settings from its parent.
1175
- *
1176
- * @param {Command} cmd - new subcommand
1177
- * @param {Object} [opts] - configuration options
1178
- * @return {Command} `this` command for chaining
1179
- */
1180
- addCommand(cmd, opts) {
1181
- if (!cmd._name) {
1182
- throw new Error(`Command passed to .addCommand() must have a name
1183
- - specify the name in Command constructor or using .name()`);
1184
- }
1185
- opts = opts || {};
1186
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1187
- if (opts.noHelp || opts.hidden) cmd._hidden = true;
1188
- this.commands.push(cmd);
1189
- cmd.parent = this;
1190
- return this;
1191
- }
1192
- /**
1193
- * Factory routine to create a new unattached argument.
1194
- *
1195
- * See .argument() for creating an attached argument, which uses this routine to
1196
- * create the argument. You can override createArgument to return a custom argument.
1197
- *
1198
- * @param {string} name
1199
- * @param {string} [description]
1200
- * @return {Argument} new argument
1201
- */
1202
- createArgument(name, description) {
1203
- return new Argument2(name, description);
1204
- }
1205
- /**
1206
- * Define argument syntax for command.
1207
- *
1208
- * The default is that the argument is required, and you can explicitly
1209
- * indicate this with <> around the name. Put [] around the name for an optional argument.
1210
- *
1211
- * @example
1212
- * program.argument('<input-file>');
1213
- * program.argument('[output-file]');
1214
- *
1215
- * @param {string} name
1216
- * @param {string} [description]
1217
- * @param {Function|*} [fn] - custom argument processing function
1218
- * @param {*} [defaultValue]
1219
- * @return {Command} `this` command for chaining
1220
- */
1221
- argument(name, description, fn, defaultValue) {
1222
- const argument = this.createArgument(name, description);
1223
- if (typeof fn === "function") {
1224
- argument.default(defaultValue).argParser(fn);
1225
- } else {
1226
- argument.default(fn);
1227
- }
1228
- this.addArgument(argument);
1229
- return this;
1230
- }
1231
- /**
1232
- * Define argument syntax for command, adding multiple at once (without descriptions).
1233
- *
1234
- * See also .argument().
1235
- *
1236
- * @example
1237
- * program.arguments('<cmd> [env]');
1238
- *
1239
- * @param {string} names
1240
- * @return {Command} `this` command for chaining
1241
- */
1242
- arguments(names) {
1243
- names.trim().split(/ +/).forEach((detail) => {
1244
- this.argument(detail);
1245
- });
1246
- return this;
1247
- }
1248
- /**
1249
- * Define argument syntax for command, adding a prepared argument.
1250
- *
1251
- * @param {Argument} argument
1252
- * @return {Command} `this` command for chaining
1253
- */
1254
- addArgument(argument) {
1255
- const previousArgument = this.registeredArguments.slice(-1)[0];
1256
- if (previousArgument && previousArgument.variadic) {
1257
- throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1258
- }
1259
- if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1260
- throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1261
- }
1262
- this.registeredArguments.push(argument);
1263
- return this;
1264
- }
1265
- /**
1266
- * Override default decision whether to add implicit help command.
1267
- *
1268
- * addHelpCommand() // force on
1269
- * addHelpCommand(false); // force off
1270
- * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
1271
- *
1272
- * @return {Command} `this` command for chaining
1273
- */
1274
- addHelpCommand(enableOrNameAndArgs, description) {
1275
- if (enableOrNameAndArgs === false) {
1276
- this._addImplicitHelpCommand = false;
1277
- } else {
1278
- this._addImplicitHelpCommand = true;
1279
- if (typeof enableOrNameAndArgs === "string") {
1280
- this._helpCommandName = enableOrNameAndArgs.split(" ")[0];
1281
- this._helpCommandnameAndArgs = enableOrNameAndArgs;
1282
- }
1283
- this._helpCommandDescription = description || this._helpCommandDescription;
1284
- }
1285
- return this;
1286
- }
1287
- /**
1288
- * @return {boolean}
1289
- * @api private
1290
- */
1291
- _hasImplicitHelpCommand() {
1292
- if (this._addImplicitHelpCommand === void 0) {
1293
- return this.commands.length && !this._actionHandler && !this._findCommand("help");
1294
- }
1295
- return this._addImplicitHelpCommand;
1296
- }
1297
- /**
1298
- * Add hook for life cycle event.
1299
- *
1300
- * @param {string} event
1301
- * @param {Function} listener
1302
- * @return {Command} `this` command for chaining
1303
- */
1304
- hook(event, listener) {
1305
- const allowedValues = ["preSubcommand", "preAction", "postAction"];
1306
- if (!allowedValues.includes(event)) {
1307
- throw new Error(`Unexpected value for event passed to hook : '${event}'.
1308
- Expecting one of '${allowedValues.join("', '")}'`);
1309
- }
1310
- if (this._lifeCycleHooks[event]) {
1311
- this._lifeCycleHooks[event].push(listener);
1312
- } else {
1313
- this._lifeCycleHooks[event] = [listener];
1314
- }
1315
- return this;
1316
- }
1317
- /**
1318
- * Register callback to use as replacement for calling process.exit.
1319
- *
1320
- * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1321
- * @return {Command} `this` command for chaining
1322
- */
1323
- exitOverride(fn) {
1324
- if (fn) {
1325
- this._exitCallback = fn;
1326
- } else {
1327
- this._exitCallback = (err) => {
1328
- if (err.code !== "commander.executeSubCommandAsync") {
1329
- throw err;
1330
- } else {
1331
- }
1332
- };
1333
- }
1334
- return this;
1335
- }
1336
- /**
1337
- * Call process.exit, and _exitCallback if defined.
1338
- *
1339
- * @param {number} exitCode exit code for using with process.exit
1340
- * @param {string} code an id string representing the error
1341
- * @param {string} message human-readable description of the error
1342
- * @return never
1343
- * @api private
1344
- */
1345
- _exit(exitCode2, code, message) {
1346
- if (this._exitCallback) {
1347
- this._exitCallback(new CommanderError2(exitCode2, code, message));
1348
- }
1349
- process4.exit(exitCode2);
1350
- }
1351
- /**
1352
- * Register callback `fn` for the command.
1353
- *
1354
- * @example
1355
- * program
1356
- * .command('serve')
1357
- * .description('start service')
1358
- * .action(function() {
1359
- * // do work here
1360
- * });
1361
- *
1362
- * @param {Function} fn
1363
- * @return {Command} `this` command for chaining
1364
- */
1365
- action(fn) {
1366
- const listener = (args) => {
1367
- const expectedArgsCount = this.registeredArguments.length;
1368
- const actionArgs = args.slice(0, expectedArgsCount);
1369
- if (this._storeOptionsAsProperties) {
1370
- actionArgs[expectedArgsCount] = this;
1371
- } else {
1372
- actionArgs[expectedArgsCount] = this.opts();
1373
- }
1374
- actionArgs.push(this);
1375
- return fn.apply(this, actionArgs);
1376
- };
1377
- this._actionHandler = listener;
1378
- return this;
1379
- }
1380
- /**
1381
- * Factory routine to create a new unattached option.
1382
- *
1383
- * See .option() for creating an attached option, which uses this routine to
1384
- * create the option. You can override createOption to return a custom option.
1385
- *
1386
- * @param {string} flags
1387
- * @param {string} [description]
1388
- * @return {Option} new option
1389
- */
1390
- createOption(flags, description) {
1391
- return new Option2(flags, description);
1392
- }
1393
- /**
1394
- * Wrap parseArgs to catch 'commander.invalidArgument'.
1395
- *
1396
- * @param {Option | Argument} target
1397
- * @param {string} value
1398
- * @param {*} previous
1399
- * @param {string} invalidArgumentMessage
1400
- * @api private
1401
- */
1402
- _callParseArg(target, value, previous, invalidArgumentMessage) {
1403
- try {
1404
- return target.parseArg(value, previous);
1405
- } catch (err) {
1406
- if (err.code === "commander.invalidArgument") {
1407
- const message = `${invalidArgumentMessage} ${err.message}`;
1408
- this.error(message, { exitCode: err.exitCode, code: err.code });
1409
- }
1410
- throw err;
1411
- }
1412
- }
1413
- /**
1414
- * Add an option.
1415
- *
1416
- * @param {Option} option
1417
- * @return {Command} `this` command for chaining
1418
- */
1419
- addOption(option) {
1420
- const oname = option.name();
1421
- const name = option.attributeName();
1422
- if (option.negate) {
1423
- const positiveLongFlag = option.long.replace(/^--no-/, "--");
1424
- if (!this._findOption(positiveLongFlag)) {
1425
- this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1426
- }
1427
- } else if (option.defaultValue !== void 0) {
1428
- this.setOptionValueWithSource(name, option.defaultValue, "default");
1429
- }
1430
- this.options.push(option);
1431
- const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1432
- if (val == null && option.presetArg !== void 0) {
1433
- val = option.presetArg;
1434
- }
1435
- const oldValue = this.getOptionValue(name);
1436
- if (val !== null && option.parseArg) {
1437
- val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1438
- } else if (val !== null && option.variadic) {
1439
- val = option._concatValue(val, oldValue);
1440
- }
1441
- if (val == null) {
1442
- if (option.negate) {
1443
- val = false;
1444
- } else if (option.isBoolean() || option.optional) {
1445
- val = true;
1446
- } else {
1447
- val = "";
1448
- }
1449
- }
1450
- this.setOptionValueWithSource(name, val, valueSource);
1451
- };
1452
- this.on("option:" + oname, (val) => {
1453
- const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1454
- handleOptionValue(val, invalidValueMessage, "cli");
1455
- });
1456
- if (option.envVar) {
1457
- this.on("optionEnv:" + oname, (val) => {
1458
- const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1459
- handleOptionValue(val, invalidValueMessage, "env");
1460
- });
1461
- }
1462
- return this;
1463
- }
1464
- /**
1465
- * Internal implementation shared by .option() and .requiredOption()
1466
- *
1467
- * @api private
1468
- */
1469
- _optionEx(config3, flags, description, fn, defaultValue) {
1470
- if (typeof flags === "object" && flags instanceof Option2) {
1471
- throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1472
- }
1473
- const option = this.createOption(flags, description);
1474
- option.makeOptionMandatory(!!config3.mandatory);
1475
- if (typeof fn === "function") {
1476
- option.default(defaultValue).argParser(fn);
1477
- } else if (fn instanceof RegExp) {
1478
- const regex = fn;
1479
- fn = (val, def) => {
1480
- const m = regex.exec(val);
1481
- return m ? m[0] : def;
1482
- };
1483
- option.default(defaultValue).argParser(fn);
1484
- } else {
1485
- option.default(fn);
1486
- }
1487
- return this.addOption(option);
1488
- }
1489
- /**
1490
- * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1491
- *
1492
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1493
- * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1494
- *
1495
- * See the README for more details, and see also addOption() and requiredOption().
1496
- *
1497
- * @example
1498
- * program
1499
- * .option('-p, --pepper', 'add pepper')
1500
- * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1501
- * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1502
- * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1503
- *
1504
- * @param {string} flags
1505
- * @param {string} [description]
1506
- * @param {Function|*} [parseArg] - custom option processing function or default value
1507
- * @param {*} [defaultValue]
1508
- * @return {Command} `this` command for chaining
1509
- */
1510
- option(flags, description, parseArg, defaultValue) {
1511
- return this._optionEx({}, flags, description, parseArg, defaultValue);
1512
- }
1513
- /**
1514
- * Add a required option which must have a value after parsing. This usually means
1515
- * the option must be specified on the command line. (Otherwise the same as .option().)
1516
- *
1517
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1518
- *
1519
- * @param {string} flags
1520
- * @param {string} [description]
1521
- * @param {Function|*} [parseArg] - custom option processing function or default value
1522
- * @param {*} [defaultValue]
1523
- * @return {Command} `this` command for chaining
1524
- */
1525
- requiredOption(flags, description, parseArg, defaultValue) {
1526
- return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1527
- }
1528
- /**
1529
- * Alter parsing of short flags with optional values.
1530
- *
1531
- * @example
1532
- * // for `.option('-f,--flag [value]'):
1533
- * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1534
- * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1535
- *
1536
- * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
1537
- */
1538
- combineFlagAndOptionalValue(combine = true) {
1539
- this._combineFlagAndOptionalValue = !!combine;
1540
- return this;
1541
- }
1542
- /**
1543
- * Allow unknown options on the command line.
1544
- *
1545
- * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
1546
- * for unknown options.
1547
- */
1548
- allowUnknownOption(allowUnknown = true) {
1549
- this._allowUnknownOption = !!allowUnknown;
1550
- return this;
1551
- }
1552
- /**
1553
- * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1554
- *
1555
- * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
1556
- * for excess arguments.
1557
- */
1558
- allowExcessArguments(allowExcess = true) {
1559
- this._allowExcessArguments = !!allowExcess;
1560
- return this;
1561
- }
1562
- /**
1563
- * Enable positional options. Positional means global options are specified before subcommands which lets
1564
- * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1565
- * The default behaviour is non-positional and global options may appear anywhere on the command line.
1566
- *
1567
- * @param {Boolean} [positional=true]
1568
- */
1569
- enablePositionalOptions(positional = true) {
1570
- this._enablePositionalOptions = !!positional;
1571
- return this;
1572
- }
1573
- /**
1574
- * Pass through options that come after command-arguments rather than treat them as command-options,
1575
- * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1576
- * positional options to have been enabled on the program (parent commands).
1577
- * The default behaviour is non-positional and options may appear before or after command-arguments.
1578
- *
1579
- * @param {Boolean} [passThrough=true]
1580
- * for unknown options.
1581
- */
1582
- passThroughOptions(passThrough = true) {
1583
- this._passThroughOptions = !!passThrough;
1584
- if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {
1585
- throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");
1586
- }
1587
- return this;
1588
- }
1589
- /**
1590
- * Whether to store option values as properties on command object,
1591
- * or store separately (specify false). In both cases the option values can be accessed using .opts().
1592
- *
1593
- * @param {boolean} [storeAsProperties=true]
1594
- * @return {Command} `this` command for chaining
1595
- */
1596
- storeOptionsAsProperties(storeAsProperties = true) {
1597
- if (this.options.length) {
1598
- throw new Error("call .storeOptionsAsProperties() before adding options");
1599
- }
1600
- this._storeOptionsAsProperties = !!storeAsProperties;
1601
- return this;
1602
- }
1603
- /**
1604
- * Retrieve option value.
1605
- *
1606
- * @param {string} key
1607
- * @return {Object} value
1608
- */
1609
- getOptionValue(key) {
1610
- if (this._storeOptionsAsProperties) {
1611
- return this[key];
1612
- }
1613
- return this._optionValues[key];
1614
- }
1615
- /**
1616
- * Store option value.
1617
- *
1618
- * @param {string} key
1619
- * @param {Object} value
1620
- * @return {Command} `this` command for chaining
1621
- */
1622
- setOptionValue(key, value) {
1623
- return this.setOptionValueWithSource(key, value, void 0);
1624
- }
1625
- /**
1626
- * Store option value and where the value came from.
1627
- *
1628
- * @param {string} key
1629
- * @param {Object} value
1630
- * @param {string} source - expected values are default/config/env/cli/implied
1631
- * @return {Command} `this` command for chaining
1632
- */
1633
- setOptionValueWithSource(key, value, source) {
1634
- if (this._storeOptionsAsProperties) {
1635
- this[key] = value;
1636
- } else {
1637
- this._optionValues[key] = value;
1638
- }
1639
- this._optionValueSources[key] = source;
1640
- return this;
1641
- }
1642
- /**
1643
- * Get source of option value.
1644
- * Expected values are default | config | env | cli | implied
1645
- *
1646
- * @param {string} key
1647
- * @return {string}
1648
- */
1649
- getOptionValueSource(key) {
1650
- return this._optionValueSources[key];
1651
- }
1652
- /**
1653
- * Get source of option value. See also .optsWithGlobals().
1654
- * Expected values are default | config | env | cli | implied
1655
- *
1656
- * @param {string} key
1657
- * @return {string}
1658
- */
1659
- getOptionValueSourceWithGlobals(key) {
1660
- let source;
1661
- this._getCommandAndAncestors().forEach((cmd) => {
1662
- if (cmd.getOptionValueSource(key) !== void 0) {
1663
- source = cmd.getOptionValueSource(key);
1664
- }
1665
- });
1666
- return source;
1667
- }
1668
- /**
1669
- * Get user arguments from implied or explicit arguments.
1670
- * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1671
- *
1672
- * @api private
1673
- */
1674
- _prepareUserArgs(argv, parseOptions) {
1675
- if (argv !== void 0 && !Array.isArray(argv)) {
1676
- throw new Error("first parameter to parse must be array or undefined");
1677
- }
1678
- parseOptions = parseOptions || {};
1679
- if (argv === void 0) {
1680
- argv = process4.argv;
1681
- if (process4.versions && process4.versions.electron) {
1682
- parseOptions.from = "electron";
1683
- }
1684
- }
1685
- this.rawArgs = argv.slice();
1686
- let userArgs;
1687
- switch (parseOptions.from) {
1688
- case void 0:
1689
- case "node":
1690
- this._scriptPath = argv[1];
1691
- userArgs = argv.slice(2);
1692
- break;
1693
- case "electron":
1694
- if (process4.defaultApp) {
1695
- this._scriptPath = argv[1];
1696
- userArgs = argv.slice(2);
1697
- } else {
1698
- userArgs = argv.slice(1);
1699
- }
1700
- break;
1701
- case "user":
1702
- userArgs = argv.slice(0);
1703
- break;
1704
- default:
1705
- throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1706
- }
1707
- if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1708
- this._name = this._name || "program";
1709
- return userArgs;
1710
- }
1711
- /**
1712
- * Parse `argv`, setting options and invoking commands when defined.
1713
- *
1714
- * The default expectation is that the arguments are from node and have the application as argv[0]
1715
- * and the script being run in argv[1], with user parameters after that.
1716
- *
1717
- * @example
1718
- * program.parse(process.argv);
1719
- * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
1720
- * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1721
- *
1722
- * @param {string[]} [argv] - optional, defaults to process.argv
1723
- * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
1724
- * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1725
- * @return {Command} `this` command for chaining
1726
- */
1727
- parse(argv, parseOptions) {
1728
- const userArgs = this._prepareUserArgs(argv, parseOptions);
1729
- this._parseCommand([], userArgs);
1730
- return this;
1731
- }
1732
- /**
1733
- * Parse `argv`, setting options and invoking commands when defined.
1734
- *
1735
- * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
1736
- *
1737
- * The default expectation is that the arguments are from node and have the application as argv[0]
1738
- * and the script being run in argv[1], with user parameters after that.
1739
- *
1740
- * @example
1741
- * await program.parseAsync(process.argv);
1742
- * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
1743
- * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1744
- *
1745
- * @param {string[]} [argv]
1746
- * @param {Object} [parseOptions]
1747
- * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1748
- * @return {Promise}
1749
- */
1750
- async parseAsync(argv, parseOptions) {
1751
- const userArgs = this._prepareUserArgs(argv, parseOptions);
1752
- await this._parseCommand([], userArgs);
1753
- return this;
1754
- }
1755
- /**
1756
- * Execute a sub-command executable.
1757
- *
1758
- * @api private
1759
- */
1760
- _executeSubCommand(subcommand, args) {
1761
- args = args.slice();
1762
- let launchWithNode = false;
1763
- const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1764
- function findFile(baseDir, baseName) {
1765
- const localBin = path.resolve(baseDir, baseName);
1766
- if (fs.existsSync(localBin)) return localBin;
1767
- if (sourceExt.includes(path.extname(baseName))) return void 0;
1768
- const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1769
- if (foundExt) return `${localBin}${foundExt}`;
1770
- return void 0;
1771
- }
1772
- this._checkForMissingMandatoryOptions();
1773
- this._checkForConflictingOptions();
1774
- let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1775
- let executableDir = this._executableDir || "";
1776
- if (this._scriptPath) {
1777
- let resolvedScriptPath;
1778
- try {
1779
- resolvedScriptPath = fs.realpathSync(this._scriptPath);
1780
- } catch (err) {
1781
- resolvedScriptPath = this._scriptPath;
1782
- }
1783
- executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1784
- }
1785
- if (executableDir) {
1786
- let localFile = findFile(executableDir, executableFile);
1787
- if (!localFile && !subcommand._executableFile && this._scriptPath) {
1788
- const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1789
- if (legacyName !== this._name) {
1790
- localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1791
- }
1792
- }
1793
- executableFile = localFile || executableFile;
1794
- }
1795
- launchWithNode = sourceExt.includes(path.extname(executableFile));
1796
- let proc;
1797
- if (process4.platform !== "win32") {
1798
- if (launchWithNode) {
1799
- args.unshift(executableFile);
1800
- args = incrementNodeInspectorPort(process4.execArgv).concat(args);
1801
- proc = childProcess.spawn(process4.argv[0], args, { stdio: "inherit" });
1802
- } else {
1803
- proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1804
- }
1805
- } else {
1806
- args.unshift(executableFile);
1807
- args = incrementNodeInspectorPort(process4.execArgv).concat(args);
1808
- proc = childProcess.spawn(process4.execPath, args, { stdio: "inherit" });
1809
- }
1810
- if (!proc.killed) {
1811
- const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1812
- signals.forEach((signal) => {
1813
- process4.on(signal, () => {
1814
- if (proc.killed === false && proc.exitCode === null) {
1815
- proc.kill(signal);
1816
- }
1817
- });
1818
- });
1819
- }
1820
- const exitCallback = this._exitCallback;
1821
- if (!exitCallback) {
1822
- proc.on("close", process4.exit.bind(process4));
1823
- } else {
1824
- proc.on("close", () => {
1825
- exitCallback(new CommanderError2(process4.exitCode || 0, "commander.executeSubCommandAsync", "(close)"));
1826
- });
1827
- }
1828
- proc.on("error", (err) => {
1829
- if (err.code === "ENOENT") {
1830
- const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1831
- const executableMissing = `'${executableFile}' does not exist
1832
- - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1833
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1834
- - ${executableDirMessage}`;
1835
- throw new Error(executableMissing);
1836
- } else if (err.code === "EACCES") {
1837
- throw new Error(`'${executableFile}' not executable`);
1838
- }
1839
- if (!exitCallback) {
1840
- process4.exit(1);
1841
- } else {
1842
- const wrappedError = new CommanderError2(1, "commander.executeSubCommandAsync", "(error)");
1843
- wrappedError.nestedError = err;
1844
- exitCallback(wrappedError);
1845
- }
1846
- });
1847
- this.runningCommand = proc;
1848
- }
1849
- /**
1850
- * @api private
1851
- */
1852
- _dispatchSubcommand(commandName, operands, unknown3) {
1853
- const subCommand = this._findCommand(commandName);
1854
- if (!subCommand) this.help({ error: true });
1855
- let promiseChain;
1856
- promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1857
- promiseChain = this._chainOrCall(promiseChain, () => {
1858
- if (subCommand._executableHandler) {
1859
- this._executeSubCommand(subCommand, operands.concat(unknown3));
1860
- } else {
1861
- return subCommand._parseCommand(operands, unknown3);
1862
- }
1863
- });
1864
- return promiseChain;
1865
- }
1866
- /**
1867
- * Invoke help directly if possible, or dispatch if necessary.
1868
- * e.g. help foo
1869
- *
1870
- * @api private
1871
- */
1872
- _dispatchHelpCommand(subcommandName) {
1873
- if (!subcommandName) {
1874
- this.help();
1875
- }
1876
- const subCommand = this._findCommand(subcommandName);
1877
- if (subCommand && !subCommand._executableHandler) {
1878
- subCommand.help();
1879
- }
1880
- return this._dispatchSubcommand(subcommandName, [], [
1881
- this._helpLongFlag || this._helpShortFlag
1882
- ]);
1883
- }
1884
- /**
1885
- * Check this.args against expected this.registeredArguments.
1886
- *
1887
- * @api private
1888
- */
1889
- _checkNumberOfArguments() {
1890
- this.registeredArguments.forEach((arg, i) => {
1891
- if (arg.required && this.args[i] == null) {
1892
- this.missingArgument(arg.name());
1893
- }
1894
- });
1895
- if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1896
- return;
1897
- }
1898
- if (this.args.length > this.registeredArguments.length) {
1899
- this._excessArguments(this.args);
1900
- }
1901
- }
1902
- /**
1903
- * Process this.args using this.registeredArguments and save as this.processedArgs!
1904
- *
1905
- * @api private
1906
- */
1907
- _processArguments() {
1908
- const myParseArg = (argument, value, previous) => {
1909
- let parsedValue = value;
1910
- if (value !== null && argument.parseArg) {
1911
- const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1912
- parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1913
- }
1914
- return parsedValue;
1915
- };
1916
- this._checkNumberOfArguments();
1917
- const processedArgs = [];
1918
- this.registeredArguments.forEach((declaredArg, index) => {
1919
- let value = declaredArg.defaultValue;
1920
- if (declaredArg.variadic) {
1921
- if (index < this.args.length) {
1922
- value = this.args.slice(index);
1923
- if (declaredArg.parseArg) {
1924
- value = value.reduce((processed, v) => {
1925
- return myParseArg(declaredArg, v, processed);
1926
- }, declaredArg.defaultValue);
1927
- }
1928
- } else if (value === void 0) {
1929
- value = [];
1930
- }
1931
- } else if (index < this.args.length) {
1932
- value = this.args[index];
1933
- if (declaredArg.parseArg) {
1934
- value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1935
- }
1936
- }
1937
- processedArgs[index] = value;
1938
- });
1939
- this.processedArgs = processedArgs;
1940
- }
1941
- /**
1942
- * Once we have a promise we chain, but call synchronously until then.
1943
- *
1944
- * @param {Promise|undefined} promise
1945
- * @param {Function} fn
1946
- * @return {Promise|undefined}
1947
- * @api private
1948
- */
1949
- _chainOrCall(promise2, fn) {
1950
- if (promise2 && promise2.then && typeof promise2.then === "function") {
1951
- return promise2.then(() => fn());
1952
- }
1953
- return fn();
1954
- }
1955
- /**
1956
- *
1957
- * @param {Promise|undefined} promise
1958
- * @param {string} event
1959
- * @return {Promise|undefined}
1960
- * @api private
1961
- */
1962
- _chainOrCallHooks(promise2, event) {
1963
- let result = promise2;
1964
- const hooks = [];
1965
- this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
1966
- hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1967
- hooks.push({ hookedCommand, callback });
1968
- });
1969
- });
1970
- if (event === "postAction") {
1971
- hooks.reverse();
1972
- }
1973
- hooks.forEach((hookDetail) => {
1974
- result = this._chainOrCall(result, () => {
1975
- return hookDetail.callback(hookDetail.hookedCommand, this);
1976
- });
1977
- });
1978
- return result;
1979
- }
1980
- /**
1981
- *
1982
- * @param {Promise|undefined} promise
1983
- * @param {Command} subCommand
1984
- * @param {string} event
1985
- * @return {Promise|undefined}
1986
- * @api private
1987
- */
1988
- _chainOrCallSubCommandHook(promise2, subCommand, event) {
1989
- let result = promise2;
1990
- if (this._lifeCycleHooks[event] !== void 0) {
1991
- this._lifeCycleHooks[event].forEach((hook) => {
1992
- result = this._chainOrCall(result, () => {
1993
- return hook(this, subCommand);
1994
- });
1995
- });
1996
- }
1997
- return result;
1998
- }
1999
- /**
2000
- * Process arguments in context of this command.
2001
- * Returns action result, in case it is a promise.
2002
- *
2003
- * @api private
2004
- */
2005
- _parseCommand(operands, unknown3) {
2006
- const parsed = this.parseOptions(unknown3);
2007
- this._parseOptionsEnv();
2008
- this._parseOptionsImplied();
2009
- operands = operands.concat(parsed.operands);
2010
- unknown3 = parsed.unknown;
2011
- this.args = operands.concat(unknown3);
2012
- if (operands && this._findCommand(operands[0])) {
2013
- return this._dispatchSubcommand(operands[0], operands.slice(1), unknown3);
2014
- }
2015
- if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
2016
- return this._dispatchHelpCommand(operands[1]);
2017
- }
2018
- if (this._defaultCommandName) {
2019
- outputHelpIfRequested(this, unknown3);
2020
- return this._dispatchSubcommand(this._defaultCommandName, operands, unknown3);
2021
- }
2022
- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2023
- this.help({ error: true });
2024
- }
2025
- outputHelpIfRequested(this, parsed.unknown);
2026
- this._checkForMissingMandatoryOptions();
2027
- this._checkForConflictingOptions();
2028
- const checkForUnknownOptions = () => {
2029
- if (parsed.unknown.length > 0) {
2030
- this.unknownOption(parsed.unknown[0]);
2031
- }
2032
- };
2033
- const commandEvent = `command:${this.name()}`;
2034
- if (this._actionHandler) {
2035
- checkForUnknownOptions();
2036
- this._processArguments();
2037
- let promiseChain;
2038
- promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2039
- promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2040
- if (this.parent) {
2041
- promiseChain = this._chainOrCall(promiseChain, () => {
2042
- this.parent.emit(commandEvent, operands, unknown3);
2043
- });
2044
- }
2045
- promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2046
- return promiseChain;
2047
- }
2048
- if (this.parent && this.parent.listenerCount(commandEvent)) {
2049
- checkForUnknownOptions();
2050
- this._processArguments();
2051
- this.parent.emit(commandEvent, operands, unknown3);
2052
- } else if (operands.length) {
2053
- if (this._findCommand("*")) {
2054
- return this._dispatchSubcommand("*", operands, unknown3);
2055
- }
2056
- if (this.listenerCount("command:*")) {
2057
- this.emit("command:*", operands, unknown3);
2058
- } else if (this.commands.length) {
2059
- this.unknownCommand();
2060
- } else {
2061
- checkForUnknownOptions();
2062
- this._processArguments();
2063
- }
2064
- } else if (this.commands.length) {
2065
- checkForUnknownOptions();
2066
- this.help({ error: true });
2067
- } else {
2068
- checkForUnknownOptions();
2069
- this._processArguments();
2070
- }
2071
- }
2072
- /**
2073
- * Find matching command.
2074
- *
2075
- * @api private
2076
- */
2077
- _findCommand(name) {
2078
- if (!name) return void 0;
2079
- return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2080
- }
2081
- /**
2082
- * Return an option matching `arg` if any.
2083
- *
2084
- * @param {string} arg
2085
- * @return {Option}
2086
- * @api private
2087
- */
2088
- _findOption(arg) {
2089
- return this.options.find((option) => option.is(arg));
2090
- }
2091
- /**
2092
- * Display an error message if a mandatory option does not have a value.
2093
- * Called after checking for help flags in leaf subcommand.
2094
- *
2095
- * @api private
2096
- */
2097
- _checkForMissingMandatoryOptions() {
2098
- this._getCommandAndAncestors().forEach((cmd) => {
2099
- cmd.options.forEach((anOption) => {
2100
- if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2101
- cmd.missingMandatoryOptionValue(anOption);
2102
- }
2103
- });
2104
- });
2105
- }
2106
- /**
2107
- * Display an error message if conflicting options are used together in this.
2108
- *
2109
- * @api private
2110
- */
2111
- _checkForConflictingLocalOptions() {
2112
- const definedNonDefaultOptions = this.options.filter(
2113
- (option) => {
2114
- const optionKey = option.attributeName();
2115
- if (this.getOptionValue(optionKey) === void 0) {
2116
- return false;
2117
- }
2118
- return this.getOptionValueSource(optionKey) !== "default";
2119
- }
2120
- );
2121
- const optionsWithConflicting = definedNonDefaultOptions.filter(
2122
- (option) => option.conflictsWith.length > 0
2123
- );
2124
- optionsWithConflicting.forEach((option) => {
2125
- const conflictingAndDefined = definedNonDefaultOptions.find(
2126
- (defined) => option.conflictsWith.includes(defined.attributeName())
2127
- );
2128
- if (conflictingAndDefined) {
2129
- this._conflictingOption(option, conflictingAndDefined);
2130
- }
2131
- });
2132
- }
2133
- /**
2134
- * Display an error message if conflicting options are used together.
2135
- * Called after checking for help flags in leaf subcommand.
2136
- *
2137
- * @api private
2138
- */
2139
- _checkForConflictingOptions() {
2140
- this._getCommandAndAncestors().forEach((cmd) => {
2141
- cmd._checkForConflictingLocalOptions();
2142
- });
2143
- }
2144
- /**
2145
- * Parse options from `argv` removing known options,
2146
- * and return argv split into operands and unknown arguments.
2147
- *
2148
- * Examples:
2149
- *
2150
- * argv => operands, unknown
2151
- * --known kkk op => [op], []
2152
- * op --known kkk => [op], []
2153
- * sub --unknown uuu op => [sub], [--unknown uuu op]
2154
- * sub -- --unknown uuu op => [sub --unknown uuu op], []
2155
- *
2156
- * @param {String[]} argv
2157
- * @return {{operands: String[], unknown: String[]}}
2158
- */
2159
- parseOptions(argv) {
2160
- const operands = [];
2161
- const unknown3 = [];
2162
- let dest = operands;
2163
- const args = argv.slice();
2164
- function maybeOption(arg) {
2165
- return arg.length > 1 && arg[0] === "-";
2166
- }
2167
- let activeVariadicOption = null;
2168
- while (args.length) {
2169
- const arg = args.shift();
2170
- if (arg === "--") {
2171
- if (dest === unknown3) dest.push(arg);
2172
- dest.push(...args);
2173
- break;
2174
- }
2175
- if (activeVariadicOption && !maybeOption(arg)) {
2176
- this.emit(`option:${activeVariadicOption.name()}`, arg);
2177
- continue;
2178
- }
2179
- activeVariadicOption = null;
2180
- if (maybeOption(arg)) {
2181
- const option = this._findOption(arg);
2182
- if (option) {
2183
- if (option.required) {
2184
- const value = args.shift();
2185
- if (value === void 0) this.optionMissingArgument(option);
2186
- this.emit(`option:${option.name()}`, value);
2187
- } else if (option.optional) {
2188
- let value = null;
2189
- if (args.length > 0 && !maybeOption(args[0])) {
2190
- value = args.shift();
2191
- }
2192
- this.emit(`option:${option.name()}`, value);
2193
- } else {
2194
- this.emit(`option:${option.name()}`);
2195
- }
2196
- activeVariadicOption = option.variadic ? option : null;
2197
- continue;
2198
- }
2199
- }
2200
- if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2201
- const option = this._findOption(`-${arg[1]}`);
2202
- if (option) {
2203
- if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2204
- this.emit(`option:${option.name()}`, arg.slice(2));
2205
- } else {
2206
- this.emit(`option:${option.name()}`);
2207
- args.unshift(`-${arg.slice(2)}`);
2208
- }
2209
- continue;
2210
- }
2211
- }
2212
- if (/^--[^=]+=/.test(arg)) {
2213
- const index = arg.indexOf("=");
2214
- const option = this._findOption(arg.slice(0, index));
2215
- if (option && (option.required || option.optional)) {
2216
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
2217
- continue;
2218
- }
2219
- }
2220
- if (maybeOption(arg)) {
2221
- dest = unknown3;
2222
- }
2223
- if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown3.length === 0) {
2224
- if (this._findCommand(arg)) {
2225
- operands.push(arg);
2226
- if (args.length > 0) unknown3.push(...args);
2227
- break;
2228
- } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
2229
- operands.push(arg);
2230
- if (args.length > 0) operands.push(...args);
2231
- break;
2232
- } else if (this._defaultCommandName) {
2233
- unknown3.push(arg);
2234
- if (args.length > 0) unknown3.push(...args);
2235
- break;
2236
- }
2237
- }
2238
- if (this._passThroughOptions) {
2239
- dest.push(arg);
2240
- if (args.length > 0) dest.push(...args);
2241
- break;
2242
- }
2243
- dest.push(arg);
2244
- }
2245
- return { operands, unknown: unknown3 };
2246
- }
2247
- /**
2248
- * Return an object containing local option values as key-value pairs.
2249
- *
2250
- * @return {Object}
2251
- */
2252
- opts() {
2253
- if (this._storeOptionsAsProperties) {
2254
- const result = {};
2255
- const len = this.options.length;
2256
- for (let i = 0; i < len; i++) {
2257
- const key = this.options[i].attributeName();
2258
- result[key] = key === this._versionOptionName ? this._version : this[key];
2259
- }
2260
- return result;
2261
- }
2262
- return this._optionValues;
2263
- }
2264
- /**
2265
- * Return an object containing merged local and global option values as key-value pairs.
2266
- *
2267
- * @return {Object}
2268
- */
2269
- optsWithGlobals() {
2270
- return this._getCommandAndAncestors().reduce(
2271
- (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2272
- {}
2273
- );
2274
- }
2275
- /**
2276
- * Display error message and exit (or call exitOverride).
2277
- *
2278
- * @param {string} message
2279
- * @param {Object} [errorOptions]
2280
- * @param {string} [errorOptions.code] - an id string representing the error
2281
- * @param {number} [errorOptions.exitCode] - used with process.exit
2282
- */
2283
- error(message, errorOptions) {
2284
- this._outputConfiguration.outputError(`${message}
2285
- `, this._outputConfiguration.writeErr);
2286
- if (typeof this._showHelpAfterError === "string") {
2287
- this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2288
- `);
2289
- } else if (this._showHelpAfterError) {
2290
- this._outputConfiguration.writeErr("\n");
2291
- this.outputHelp({ error: true });
2292
- }
2293
- const config3 = errorOptions || {};
2294
- const exitCode2 = config3.exitCode || 1;
2295
- const code = config3.code || "commander.error";
2296
- this._exit(exitCode2, code, message);
2297
- }
2298
- /**
2299
- * Apply any option related environment variables, if option does
2300
- * not have a value from cli or client code.
2301
- *
2302
- * @api private
2303
- */
2304
- _parseOptionsEnv() {
2305
- this.options.forEach((option) => {
2306
- if (option.envVar && option.envVar in process4.env) {
2307
- const optionKey = option.attributeName();
2308
- if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
2309
- if (option.required || option.optional) {
2310
- this.emit(`optionEnv:${option.name()}`, process4.env[option.envVar]);
2311
- } else {
2312
- this.emit(`optionEnv:${option.name()}`);
2313
- }
2314
- }
2315
- }
2316
- });
2317
- }
2318
- /**
2319
- * Apply any implied option values, if option is undefined or default value.
2320
- *
2321
- * @api private
2322
- */
2323
- _parseOptionsImplied() {
2324
- const dualHelper = new DualOptions(this.options);
2325
- const hasCustomOptionValue = (optionKey) => {
2326
- return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2327
- };
2328
- this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2329
- Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2330
- this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2331
- });
2332
- });
2333
- }
2334
- /**
2335
- * Argument `name` is missing.
2336
- *
2337
- * @param {string} name
2338
- * @api private
2339
- */
2340
- missingArgument(name) {
2341
- const message = `error: missing required argument '${name}'`;
2342
- this.error(message, { code: "commander.missingArgument" });
2343
- }
2344
- /**
2345
- * `Option` is missing an argument.
2346
- *
2347
- * @param {Option} option
2348
- * @api private
2349
- */
2350
- optionMissingArgument(option) {
2351
- const message = `error: option '${option.flags}' argument missing`;
2352
- this.error(message, { code: "commander.optionMissingArgument" });
2353
- }
2354
- /**
2355
- * `Option` does not have a value, and is a mandatory option.
2356
- *
2357
- * @param {Option} option
2358
- * @api private
2359
- */
2360
- missingMandatoryOptionValue(option) {
2361
- const message = `error: required option '${option.flags}' not specified`;
2362
- this.error(message, { code: "commander.missingMandatoryOptionValue" });
2363
- }
2364
- /**
2365
- * `Option` conflicts with another option.
2366
- *
2367
- * @param {Option} option
2368
- * @param {Option} conflictingOption
2369
- * @api private
2370
- */
2371
- _conflictingOption(option, conflictingOption) {
2372
- const findBestOptionFromValue = (option2) => {
2373
- const optionKey = option2.attributeName();
2374
- const optionValue = this.getOptionValue(optionKey);
2375
- const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2376
- const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2377
- if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2378
- return negativeOption;
2379
- }
2380
- return positiveOption || option2;
2381
- };
2382
- const getErrorMessage = (option2) => {
2383
- const bestOption = findBestOptionFromValue(option2);
2384
- const optionKey = bestOption.attributeName();
2385
- const source = this.getOptionValueSource(optionKey);
2386
- if (source === "env") {
2387
- return `environment variable '${bestOption.envVar}'`;
2388
- }
2389
- return `option '${bestOption.flags}'`;
2390
- };
2391
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2392
- this.error(message, { code: "commander.conflictingOption" });
2393
- }
2394
- /**
2395
- * Unknown option `flag`.
2396
- *
2397
- * @param {string} flag
2398
- * @api private
2399
- */
2400
- unknownOption(flag) {
2401
- if (this._allowUnknownOption) return;
2402
- let suggestion = "";
2403
- if (flag.startsWith("--") && this._showSuggestionAfterError) {
2404
- let candidateFlags = [];
2405
- let command = this;
2406
- do {
2407
- const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2408
- candidateFlags = candidateFlags.concat(moreFlags);
2409
- command = command.parent;
2410
- } while (command && !command._enablePositionalOptions);
2411
- suggestion = suggestSimilar(flag, candidateFlags);
2412
- }
2413
- const message = `error: unknown option '${flag}'${suggestion}`;
2414
- this.error(message, { code: "commander.unknownOption" });
2415
- }
2416
- /**
2417
- * Excess arguments, more than expected.
2418
- *
2419
- * @param {string[]} receivedArgs
2420
- * @api private
2421
- */
2422
- _excessArguments(receivedArgs) {
2423
- if (this._allowExcessArguments) return;
2424
- const expected = this.registeredArguments.length;
2425
- const s = expected === 1 ? "" : "s";
2426
- const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2427
- const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2428
- this.error(message, { code: "commander.excessArguments" });
2429
- }
2430
- /**
2431
- * Unknown command.
2432
- *
2433
- * @api private
2434
- */
2435
- unknownCommand() {
2436
- const unknownName = this.args[0];
2437
- let suggestion = "";
2438
- if (this._showSuggestionAfterError) {
2439
- const candidateNames = [];
2440
- this.createHelp().visibleCommands(this).forEach((command) => {
2441
- candidateNames.push(command.name());
2442
- if (command.alias()) candidateNames.push(command.alias());
2443
- });
2444
- suggestion = suggestSimilar(unknownName, candidateNames);
2445
- }
2446
- const message = `error: unknown command '${unknownName}'${suggestion}`;
2447
- this.error(message, { code: "commander.unknownCommand" });
2448
- }
2449
- /**
2450
- * Get or set the program version.
2451
- *
2452
- * This method auto-registers the "-V, --version" option which will print the version number.
2453
- *
2454
- * You can optionally supply the flags and description to override the defaults.
2455
- *
2456
- * @param {string} [str]
2457
- * @param {string} [flags]
2458
- * @param {string} [description]
2459
- * @return {this | string | undefined} `this` command for chaining, or version string if no arguments
2460
- */
2461
- version(str, flags, description) {
2462
- if (str === void 0) return this._version;
2463
- this._version = str;
2464
- flags = flags || "-V, --version";
2465
- description = description || "output the version number";
2466
- const versionOption = this.createOption(flags, description);
2467
- this._versionOptionName = versionOption.attributeName();
2468
- this.options.push(versionOption);
2469
- this.on("option:" + versionOption.name(), () => {
2470
- this._outputConfiguration.writeOut(`${str}
2471
- `);
2472
- this._exit(0, "commander.version", str);
2473
- });
2474
- return this;
2475
- }
2476
- /**
2477
- * Set the description.
2478
- *
2479
- * @param {string} [str]
2480
- * @param {Object} [argsDescription]
2481
- * @return {string|Command}
2482
- */
2483
- description(str, argsDescription) {
2484
- if (str === void 0 && argsDescription === void 0) return this._description;
2485
- this._description = str;
2486
- if (argsDescription) {
2487
- this._argsDescription = argsDescription;
2488
- }
2489
- return this;
2490
- }
2491
- /**
2492
- * Set the summary. Used when listed as subcommand of parent.
2493
- *
2494
- * @param {string} [str]
2495
- * @return {string|Command}
2496
- */
2497
- summary(str) {
2498
- if (str === void 0) return this._summary;
2499
- this._summary = str;
2500
- return this;
2501
- }
2502
- /**
2503
- * Set an alias for the command.
2504
- *
2505
- * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2506
- *
2507
- * @param {string} [alias]
2508
- * @return {string|Command}
2509
- */
2510
- alias(alias) {
2511
- if (alias === void 0) return this._aliases[0];
2512
- let command = this;
2513
- if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2514
- command = this.commands[this.commands.length - 1];
2515
- }
2516
- if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2517
- command._aliases.push(alias);
2518
- return this;
2519
- }
2520
- /**
2521
- * Set aliases for the command.
2522
- *
2523
- * Only the first alias is shown in the auto-generated help.
2524
- *
2525
- * @param {string[]} [aliases]
2526
- * @return {string[]|Command}
2527
- */
2528
- aliases(aliases) {
2529
- if (aliases === void 0) return this._aliases;
2530
- aliases.forEach((alias) => this.alias(alias));
2531
- return this;
2532
- }
2533
- /**
2534
- * Set / get the command usage `str`.
2535
- *
2536
- * @param {string} [str]
2537
- * @return {String|Command}
2538
- */
2539
- usage(str) {
2540
- if (str === void 0) {
2541
- if (this._usage) return this._usage;
2542
- const args = this.registeredArguments.map((arg) => {
2543
- return humanReadableArgName(arg);
2544
- });
2545
- return [].concat(
2546
- this.options.length || this._hasHelpOption ? "[options]" : [],
2547
- this.commands.length ? "[command]" : [],
2548
- this.registeredArguments.length ? args : []
2549
- ).join(" ");
2550
- }
2551
- this._usage = str;
2552
- return this;
2553
- }
2554
- /**
2555
- * Get or set the name of the command.
2556
- *
2557
- * @param {string} [str]
2558
- * @return {string|Command}
2559
- */
2560
- name(str) {
2561
- if (str === void 0) return this._name;
2562
- this._name = str;
2563
- return this;
2564
- }
2565
- /**
2566
- * Set the name of the command from script filename, such as process.argv[1],
2567
- * or require.main.filename, or __filename.
2568
- *
2569
- * (Used internally and public although not documented in README.)
2570
- *
2571
- * @example
2572
- * program.nameFromFilename(require.main.filename);
2573
- *
2574
- * @param {string} filename
2575
- * @return {Command}
2576
- */
2577
- nameFromFilename(filename) {
2578
- this._name = path.basename(filename, path.extname(filename));
2579
- return this;
2580
- }
2581
- /**
2582
- * Get or set the directory for searching for executable subcommands of this command.
2583
- *
2584
- * @example
2585
- * program.executableDir(__dirname);
2586
- * // or
2587
- * program.executableDir('subcommands');
2588
- *
2589
- * @param {string} [path]
2590
- * @return {string|null|Command}
2591
- */
2592
- executableDir(path2) {
2593
- if (path2 === void 0) return this._executableDir;
2594
- this._executableDir = path2;
2595
- return this;
2596
- }
2597
- /**
2598
- * Return program help documentation.
2599
- *
2600
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2601
- * @return {string}
2602
- */
2603
- helpInformation(contextOptions) {
2604
- const helper = this.createHelp();
2605
- if (helper.helpWidth === void 0) {
2606
- helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2607
- }
2608
- return helper.formatHelp(this, helper);
2609
- }
2610
- /**
2611
- * @api private
2612
- */
2613
- _getHelpContext(contextOptions) {
2614
- contextOptions = contextOptions || {};
2615
- const context = { error: !!contextOptions.error };
2616
- let write;
2617
- if (context.error) {
2618
- write = (arg) => this._outputConfiguration.writeErr(arg);
2619
- } else {
2620
- write = (arg) => this._outputConfiguration.writeOut(arg);
2621
- }
2622
- context.write = contextOptions.write || write;
2623
- context.command = this;
2624
- return context;
2625
- }
2626
- /**
2627
- * Output help information for this command.
2628
- *
2629
- * Outputs built-in help, and custom text added using `.addHelpText()`.
2630
- *
2631
- * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2632
- */
2633
- outputHelp(contextOptions) {
2634
- let deprecatedCallback;
2635
- if (typeof contextOptions === "function") {
2636
- deprecatedCallback = contextOptions;
2637
- contextOptions = void 0;
2638
- }
2639
- const context = this._getHelpContext(contextOptions);
2640
- this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2641
- this.emit("beforeHelp", context);
2642
- let helpInformation = this.helpInformation(context);
2643
- if (deprecatedCallback) {
2644
- helpInformation = deprecatedCallback(helpInformation);
2645
- if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2646
- throw new Error("outputHelp callback must return a string or a Buffer");
2647
- }
2648
- }
2649
- context.write(helpInformation);
2650
- if (this._helpLongFlag) {
2651
- this.emit(this._helpLongFlag);
2652
- }
2653
- this.emit("afterHelp", context);
2654
- this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context));
2655
- }
2656
- /**
2657
- * You can pass in flags and a description to override the help
2658
- * flags and help description for your command. Pass in false to
2659
- * disable the built-in help option.
2660
- *
2661
- * @param {string | boolean} [flags]
2662
- * @param {string} [description]
2663
- * @return {Command} `this` command for chaining
2664
- */
2665
- helpOption(flags, description) {
2666
- if (typeof flags === "boolean") {
2667
- this._hasHelpOption = flags;
2668
- return this;
2669
- }
2670
- this._helpFlags = flags || this._helpFlags;
2671
- this._helpDescription = description || this._helpDescription;
2672
- const helpFlags = splitOptionFlags(this._helpFlags);
2673
- this._helpShortFlag = helpFlags.shortFlag;
2674
- this._helpLongFlag = helpFlags.longFlag;
2675
- return this;
2676
- }
2677
- /**
2678
- * Output help information and exit.
2679
- *
2680
- * Outputs built-in help, and custom text added using `.addHelpText()`.
2681
- *
2682
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2683
- */
2684
- help(contextOptions) {
2685
- this.outputHelp(contextOptions);
2686
- let exitCode2 = process4.exitCode || 0;
2687
- if (exitCode2 === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2688
- exitCode2 = 1;
2689
- }
2690
- this._exit(exitCode2, "commander.help", "(outputHelp)");
2691
- }
2692
- /**
2693
- * Add additional text to be displayed with the built-in help.
2694
- *
2695
- * Position is 'before' or 'after' to affect just this command,
2696
- * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2697
- *
2698
- * @param {string} position - before or after built-in help
2699
- * @param {string | Function} text - string to add, or a function returning a string
2700
- * @return {Command} `this` command for chaining
2701
- */
2702
- addHelpText(position, text) {
2703
- const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2704
- if (!allowedValues.includes(position)) {
2705
- throw new Error(`Unexpected value for position to addHelpText.
2706
- Expecting one of '${allowedValues.join("', '")}'`);
2707
- }
2708
- const helpEvent = `${position}Help`;
2709
- this.on(helpEvent, (context) => {
2710
- let helpStr;
2711
- if (typeof text === "function") {
2712
- helpStr = text({ error: context.error, command: context.command });
2713
- } else {
2714
- helpStr = text;
2715
- }
2716
- if (helpStr) {
2717
- context.write(`${helpStr}
2718
- `);
2719
- }
2720
- });
2721
- return this;
2722
- }
2723
- };
2724
- function outputHelpIfRequested(cmd, args) {
2725
- const helpOption = cmd._hasHelpOption && args.find((arg) => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
2726
- if (helpOption) {
2727
- cmd.outputHelp();
2728
- cmd._exit(0, "commander.helpDisplayed", "(outputHelp)");
2729
- }
2730
- }
2731
- function incrementNodeInspectorPort(args) {
2732
- return args.map((arg) => {
2733
- if (!arg.startsWith("--inspect")) {
2734
- return arg;
2735
- }
2736
- let debugOption;
2737
- let debugHost = "127.0.0.1";
2738
- let debugPort = "9229";
2739
- let match;
2740
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2741
- debugOption = match[1];
2742
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2743
- debugOption = match[1];
2744
- if (/^\d+$/.test(match[3])) {
2745
- debugPort = match[3];
2746
- } else {
2747
- debugHost = match[3];
2748
- }
2749
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2750
- debugOption = match[1];
2751
- debugHost = match[3];
2752
- debugPort = match[4];
2753
- }
2754
- if (debugOption && debugPort !== "0") {
2755
- return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2756
- }
2757
- return arg;
2758
- });
2759
- }
2760
- exports.Command = Command2;
2761
- }
2762
- });
2763
-
2764
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/index.js
2765
- var require_commander = __commonJS({
2766
- "../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/index.js"(exports, module) {
2767
- "use strict";
2768
- var { Argument: Argument2 } = require_argument();
2769
- var { Command: Command2 } = require_command();
2770
- var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
2771
- var { Help: Help2 } = require_help();
2772
- var { Option: Option2 } = require_option();
2773
- exports = module.exports = new Command2();
2774
- exports.program = exports;
2775
- exports.Command = Command2;
2776
- exports.Option = Option2;
2777
- exports.Argument = Argument2;
2778
- exports.Help = Help2;
2779
- exports.CommanderError = CommanderError2;
2780
- exports.InvalidArgumentError = InvalidArgumentError2;
2781
- exports.InvalidOptionArgumentError = InvalidArgumentError2;
2782
- }
2783
- });
2784
-
2785
34
  // ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js
2786
35
  // @__NO_SIDE_EFFECTS__
2787
36
  function $constructor(name, initializer5, params) {
@@ -18098,13 +15347,17 @@ function parseSlideshowRun(payload) {
18098
15347
  assertNoPrivateTemplateFields(payload);
18099
15348
  return parseDataEnvelope(payload, slideshowRunSchema);
18100
15349
  }
18101
- function parseBrandProfile(payload) {
18102
- return parseDataEnvelope(payload, brandProfileSchema);
15350
+ function parseSlideshowRunSummaryList(payload) {
15351
+ assertNoPrivateTemplateFields(payload);
15352
+ return parseDataEnvelope(payload, external_exports.array(slideshowRunSummarySchema));
15353
+ }
15354
+ function parseBrand(payload) {
15355
+ return parseDataEnvelope(payload, brandSchema);
18103
15356
  }
18104
- function parseBrandProfileList(payload) {
18105
- return parseDataEnvelope(payload, external_exports.array(brandProfileSchema));
15357
+ function parseBrandList(payload) {
15358
+ return parseDataEnvelope(payload, external_exports.array(brandSchema));
18106
15359
  }
18107
- var FORBIDDEN_PUBLIC_KEYS, templatePlatformSchema, canvasPresetSchema, pageRoleSchema, contentFamilySchema, contentArchetypeSchema, densityLevelSchema, visualStyleSchema, imageRoleSchema, slotSummarySchema, selectionMetadataSchema, selectionMetadataDraftSchema, listTemplatesQuerySchema, templateSummarySchema, publicTemplateSlotTypeSchema, publicTemplateSlotSchema, templateDetailSchema, templateSelectionSchema, presentationIntentSchema, renderSlotValueSchema, renderJobRequestSchema, legacyRenderJobRequestSchema, renderJobStatusSchema, renderCaptureHintSchema, renderJobViewSchema, renderPreviewMaterializationSchema, renderSelectionSummarySchema, renderManifestSchema, templateAuthoringCanvasSchema, templateAuthoringProvenanceSchema, templateImageModeSchema, templateImageNodeSchema, authoringImageNodeSchema, authoringIconNodeSchema, templateAuthoringSourceSchema, themeContrastEntrySchema, themePaletteSchema, themeTokensSchema, themeSummarySchema, themeDetailSchema, gradientTextSafeZoneSchema, gradientStopSchema, gradientSummarySchema, gradientDetailSchema, listGradientsQuerySchema, templateSurfaceKindSchema, templateSurfacePreviewSchema, templateImageProviderSchema, templateImageRightsStatusSchema, templateImageProvenanceSchema, importTemplateImageFileSchema, importTemplateImageInputSchema, importTemplateImageBodySchema, createRenderAssetInputSchema, renderAssetReferenceSchema, iconStyleSchema, templateIconLicenseSchema, searchTemplateIconsRequestSchema, templateIconCandidateSchema, getTemplateIconRequestSchema, templateIconProvenanceSchema, templateIconAssetReferenceSchema, templateIconErrorCodeSchema, templateImageReferenceSchema, themeCreateInputSchema, draftThemeInputSchema, createTemplateDraftInputSchema, updateTemplateDraftInputSchema, templateAuthoringDraftSchema, DEFAULT_AUTHORING_STUDIO_BASE_URL, templatePrincipalErrorSchema, slideshowPlatformCaps, slideshowPlatformSchema, slideshowRunStatusSchema, publicSlotValueSchema, contentPackPageSchema, contentPackSchema, slideshowRunPageSchema, brandProfilePreferenceSchema, brandProfileSchema, createBrandProfileInputSchema, updateBrandProfileInputSchema, slideshowRunSchema, createSlideshowRunInputSchema, updateSlideshowRunInputSchema, renderSlideshowRunInputSchema;
15360
+ var FORBIDDEN_PUBLIC_KEYS, templatePlatformSchema, canvasPresetSchema, pageRoleSchema, contentFamilySchema, contentArchetypeSchema, densityLevelSchema, visualStyleSchema, imageRoleSchema, slotSummarySchema, selectionMetadataSchema, selectionMetadataDraftSchema, listTemplatesQuerySchema, templateSummarySchema, publicTemplateSlotTypeSchema, publicTemplateSlotSchema, templateDetailSchema, templateSelectionSchema, presentationIntentSchema, renderSlotValueSchema, renderJobRequestSchema, legacyRenderJobRequestSchema, renderJobStatusSchema, renderCaptureHintSchema, renderJobViewSchema, renderPreviewMaterializationSchema, renderSelectionSummarySchema, renderManifestSchema, templateAuthoringCanvasSchema, templateAuthoringProvenanceSchema, templateImageModeSchema, templateImageNodeSchema, authoringImageNodeSchema, authoringIconNodeSchema, templateAuthoringSourceSchema, themeContrastEntrySchema, themePaletteSchema, themeTokensSchema, themeSummarySchema, themeDetailSchema, gradientTextSafeZoneSchema, gradientStopSchema, gradientSummarySchema, gradientDetailSchema, listGradientsQuerySchema, templateSurfaceKindSchema, templateSurfacePreviewSchema, templateImageProviderSchema, templateImageRightsStatusSchema, templateImageProvenanceSchema, importTemplateImageFileSchema, importTemplateImageInputSchema, importTemplateImageBodySchema, createRenderAssetInputSchema, renderAssetReferenceSchema, iconStyleSchema, templateIconLicenseSchema, searchTemplateIconsRequestSchema, templateIconCandidateSchema, getTemplateIconRequestSchema, templateIconProvenanceSchema, templateIconAssetReferenceSchema, templateIconErrorCodeSchema, templateImageReferenceSchema, themeCreateInputSchema, draftThemeInputSchema, createTemplateDraftInputSchema, updateTemplateDraftInputSchema, templateAuthoringDraftSchema, DEFAULT_AUTHORING_STUDIO_BASE_URL, templatePrincipalErrorSchema, slideshowPlatformCaps, slideshowPlatformSchema, slideshowRunStatusSchema, publicSlotValueSchema, contentPackPageSchema, contentPackSchema, slideshowRunPageSchema, brandProfilePreferenceSchema, brandProfileSchema, createBrandProfileInputSchema, updateBrandProfileInputSchema, brandTypographySchema, brandColorsSchema, brandSchema, createBrandInputSchema, updateBrandInputSchema, slideshowRunSummarySchema, slideshowRunSchema, createSlideshowRunInputSchema, updateSlideshowRunInputSchema, renderSlideshowRunInputSchema, listSlideshowRunsQuerySchema;
18108
15361
  var init_src = __esm({
18109
15362
  "../../packages/template-public-contracts/src/index.ts"() {
18110
15363
  "use strict";
@@ -18830,10 +16083,13 @@ var init_src = __esm({
18830
16083
  ]);
18831
16084
  slideshowRunStatusSchema = external_exports.enum([
18832
16085
  "draft",
16086
+ "ready",
18833
16087
  "rendering",
18834
16088
  "completed",
18835
16089
  "failed",
18836
- "expired"
16090
+ "expired",
16091
+ "archived",
16092
+ "trashed"
18837
16093
  ]);
18838
16094
  publicSlotValueSchema = external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null()]);
18839
16095
  contentPackPageSchema = external_exports.object({
@@ -18845,6 +16101,7 @@ var init_src = __esm({
18845
16101
  schemaVersion: external_exports.literal("content-pack.v1"),
18846
16102
  platform: slideshowPlatformSchema,
18847
16103
  title: external_exports.string().optional(),
16104
+ contentSlug: external_exports.string().optional(),
18848
16105
  pages: external_exports.array(contentPackPageSchema).min(1)
18849
16106
  }).strict().superRefine((value, ctx) => {
18850
16107
  const forbidden = JSON.stringify(value).toLowerCase();
@@ -18891,11 +16148,63 @@ var init_src = __esm({
18891
16148
  preference: brandProfilePreferenceSchema.default({})
18892
16149
  }).strict();
18893
16150
  updateBrandProfileInputSchema = createBrandProfileInputSchema.partial().strict();
16151
+ brandTypographySchema = external_exports.object({
16152
+ headingFontId: external_exports.string(),
16153
+ bodyFontId: external_exports.string()
16154
+ }).strict();
16155
+ brandColorsSchema = external_exports.object({
16156
+ canvas: external_exports.string(),
16157
+ surface: external_exports.string(),
16158
+ text: external_exports.string(),
16159
+ textMuted: external_exports.string(),
16160
+ primary: external_exports.string(),
16161
+ accent: external_exports.string()
16162
+ }).strict();
16163
+ brandSchema = external_exports.object({
16164
+ id: external_exports.string(),
16165
+ brandId: external_exports.string().optional(),
16166
+ name: external_exports.string(),
16167
+ displayName: external_exports.string().optional(),
16168
+ handle: external_exports.string().optional(),
16169
+ typography: brandTypographySchema.optional(),
16170
+ colors: brandColorsSchema.partial().optional(),
16171
+ logoAssetId: external_exports.string().nullable().optional(),
16172
+ revision: external_exports.number().int().positive().optional(),
16173
+ status: external_exports.string(),
16174
+ createdAt: external_exports.string().optional(),
16175
+ updatedAt: external_exports.string().optional()
16176
+ }).strict();
16177
+ createBrandInputSchema = external_exports.object({
16178
+ name: external_exports.string().min(1),
16179
+ displayName: external_exports.string().optional(),
16180
+ handle: external_exports.string().optional(),
16181
+ typography: brandTypographySchema.partial().optional(),
16182
+ colors: brandColorsSchema.partial().optional(),
16183
+ logoAssetId: external_exports.string().nullable().optional()
16184
+ }).strict();
16185
+ updateBrandInputSchema = createBrandInputSchema.partial().extend({
16186
+ baseRevision: external_exports.number().int().positive()
16187
+ }).strict();
16188
+ slideshowRunSummarySchema = external_exports.object({
16189
+ id: external_exports.string(),
16190
+ platform: slideshowPlatformSchema,
16191
+ title: external_exports.string().optional(),
16192
+ contentSlug: external_exports.string().optional(),
16193
+ status: slideshowRunStatusSchema,
16194
+ revision: external_exports.number().int().positive(),
16195
+ pageCount: external_exports.number().int().nonnegative(),
16196
+ brandProfileId: external_exports.string().optional(),
16197
+ studioUrl: external_exports.string().url().optional(),
16198
+ lastActivityAt: external_exports.string().optional(),
16199
+ createdAt: external_exports.string(),
16200
+ updatedAt: external_exports.string()
16201
+ }).strict();
18894
16202
  slideshowRunSchema = external_exports.object({
18895
16203
  id: external_exports.string(),
18896
16204
  ownerId: external_exports.string().optional(),
18897
16205
  platform: slideshowPlatformSchema,
18898
16206
  title: external_exports.string().optional(),
16207
+ contentSlug: external_exports.string().optional(),
18899
16208
  status: slideshowRunStatusSchema,
18900
16209
  revision: external_exports.number().int().positive().optional(),
18901
16210
  packSnapshot: contentPackSchema,
@@ -18903,18 +16212,23 @@ var init_src = __esm({
18903
16212
  pages: external_exports.array(slideshowRunPageSchema),
18904
16213
  brandProfileId: external_exports.string().optional(),
18905
16214
  studioUrl: external_exports.string().url().optional(),
16215
+ lastActivityAt: external_exports.string().optional(),
18906
16216
  updatedAt: external_exports.string(),
18907
16217
  createdAt: external_exports.string()
18908
16218
  }).strict();
18909
16219
  createSlideshowRunInputSchema = external_exports.object({
18910
16220
  pack: contentPackSchema,
16221
+ brandId: external_exports.string().optional(),
18911
16222
  brandProfileId: external_exports.string().optional(),
18912
- themeSnapshot: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
16223
+ themeSnapshot: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
16224
+ contentSlug: external_exports.string().optional()
18913
16225
  }).strict();
18914
16226
  updateSlideshowRunInputSchema = external_exports.object({
18915
16227
  pack: contentPackSchema.optional(),
16228
+ brandId: external_exports.string().optional(),
18916
16229
  brandProfileId: external_exports.string().optional(),
18917
16230
  themeSnapshot: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
16231
+ contentSlug: external_exports.string().optional(),
18918
16232
  baseRevision: external_exports.number().int().positive().optional(),
18919
16233
  pageIndex: external_exports.number().int().nonnegative().optional(),
18920
16234
  slots: external_exports.record(external_exports.string(), publicSlotValueSchema).optional(),
@@ -18926,6 +16240,14 @@ var init_src = __esm({
18926
16240
  outputFormats: external_exports.array(external_exports.literal("png")).length(1).default(["png"]),
18927
16241
  idempotencyKey: external_exports.string().min(1).max(128)
18928
16242
  }).strict();
16243
+ listSlideshowRunsQuerySchema = external_exports.object({
16244
+ q: external_exports.string().optional(),
16245
+ platform: slideshowPlatformSchema.optional(),
16246
+ profileId: external_exports.string().optional(),
16247
+ brandProfileId: external_exports.string().optional(),
16248
+ contentSlug: external_exports.string().optional(),
16249
+ status: slideshowRunStatusSchema.optional()
16250
+ }).strict();
18929
16251
  }
18930
16252
  });
18931
16253
 
@@ -19180,6 +16502,18 @@ var init_client = __esm({
19180
16502
  this.throwIfError(response.status, response.json);
19181
16503
  return parseSlideshowRun(response.json);
19182
16504
  }
16505
+ async listSlideshowRuns(query = {}) {
16506
+ const input = listSlideshowRunsQuerySchema.parse(query);
16507
+ const params = new URLSearchParams();
16508
+ for (const [key, value] of Object.entries(input)) {
16509
+ if (value !== void 0 && value !== "")
16510
+ params.set(key, String(value));
16511
+ }
16512
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
16513
+ const response = await this.request("GET", `/v1/slideshow/runs${suffix}`);
16514
+ this.throwIfError(response.status, response.json);
16515
+ return parseSlideshowRunSummaryList(response.json);
16516
+ }
19183
16517
  async getSlideshowRun(runId) {
19184
16518
  const response = await this.request("GET", `/v1/slideshow/runs/${encodeURIComponent(runId)}`);
19185
16519
  this.throwIfError(response.status, response.json);
@@ -19191,6 +16525,22 @@ var init_client = __esm({
19191
16525
  this.throwIfError(response.status, response.json);
19192
16526
  return parseSlideshowRun(response.json);
19193
16527
  }
16528
+ async archiveSlideshowRun(runId) {
16529
+ const response = await this.request("POST", `/v1/slideshow/runs/${encodeURIComponent(runId)}/archive`);
16530
+ this.throwIfError(response.status, response.json);
16531
+ return parseSlideshowRun(response.json);
16532
+ }
16533
+ async restoreSlideshowRun(runId) {
16534
+ const response = await this.request("POST", `/v1/slideshow/runs/${encodeURIComponent(runId)}/restore`);
16535
+ this.throwIfError(response.status, response.json);
16536
+ return parseSlideshowRun(response.json);
16537
+ }
16538
+ async trashSlideshowRun(runId) {
16539
+ const response = await this.request("DELETE", `/v1/slideshow/runs/${encodeURIComponent(runId)}`);
16540
+ this.throwIfError(response.status, response.json);
16541
+ const rows = parseSlideshowRunSummaryList(response.json);
16542
+ return rows[0];
16543
+ }
19194
16544
  async renderSlideshowRun(runId, body) {
19195
16545
  const input = renderSlideshowRunInputSchema.parse(body ?? {});
19196
16546
  const response = await this.request("POST", `/v1/slideshow/runs/${encodeURIComponent(runId)}/render`, input, { idempotencyKey: input.idempotencyKey });
@@ -19231,22 +16581,83 @@ var init_client = __esm({
19231
16581
  throw new Error(`Artifact download failed (${response.status})`);
19232
16582
  return new Uint8Array(await response.arrayBuffer());
19233
16583
  }
19234
- async listBrandProfiles() {
19235
- const response = await this.request("GET", "/v1/slideshow/brand-profiles");
16584
+ async listBrands() {
16585
+ const response = await this.request("GET", "/v1/brands");
19236
16586
  this.throwIfError(response.status, response.json);
19237
- return parseBrandProfileList(response.json);
16587
+ return parseBrandList(response.json);
19238
16588
  }
19239
- async createBrandProfile(body) {
19240
- const input = createBrandProfileInputSchema.parse(body);
19241
- const response = await this.request("POST", "/v1/slideshow/brand-profiles", input);
16589
+ async getBrand(brandId) {
16590
+ const response = await this.request("GET", `/v1/brands/${encodeURIComponent(brandId)}`);
19242
16591
  this.throwIfError(response.status, response.json);
19243
- return parseBrandProfile(response.json);
16592
+ return parseBrand(response.json);
19244
16593
  }
19245
- async updateBrandProfile(id, body) {
19246
- const input = updateBrandProfileInputSchema.parse(body);
19247
- const response = await this.request("PATCH", `/v1/slideshow/brand-profiles/${encodeURIComponent(id)}`, input);
16594
+ async createBrand(body) {
16595
+ const input = createBrandInputSchema.parse(body);
16596
+ const response = await this.request("POST", "/v1/brands", input);
16597
+ this.throwIfError(response.status, response.json);
16598
+ return parseBrand(response.json);
16599
+ }
16600
+ async updateBrand(brandId, body) {
16601
+ const input = updateBrandInputSchema.parse(body);
16602
+ const response = await this.request("PATCH", `/v1/brands/${encodeURIComponent(brandId)}`, input);
16603
+ this.throwIfError(response.status, response.json);
16604
+ return parseBrand(response.json);
16605
+ }
16606
+ async archiveBrand(brandId) {
16607
+ const response = await this.request("POST", `/v1/brands/${encodeURIComponent(brandId)}/archive`);
19248
16608
  this.throwIfError(response.status, response.json);
19249
- return parseBrandProfile(response.json);
16609
+ return parseBrand(response.json);
16610
+ }
16611
+ async restoreBrand(brandId) {
16612
+ const response = await this.request("POST", `/v1/brands/${encodeURIComponent(brandId)}/restore`);
16613
+ this.throwIfError(response.status, response.json);
16614
+ return parseBrand(response.json);
16615
+ }
16616
+ async trashBrand(brandId) {
16617
+ const response = await this.request("DELETE", `/v1/brands/${encodeURIComponent(brandId)}`);
16618
+ this.throwIfError(response.status, response.json);
16619
+ return parseBrand(response.json);
16620
+ }
16621
+ /** @deprecated Use listBrands */
16622
+ async listBrandProfiles() {
16623
+ const brands = await this.listBrands();
16624
+ return brands.map((brand) => ({
16625
+ id: brand.id,
16626
+ name: brand.name,
16627
+ preference: {
16628
+ themeId: void 0,
16629
+ fonts: brand.typography ? { heading: brand.typography.headingFontId, body: brand.typography.bodyFontId } : void 0,
16630
+ brandHex: brand.colors?.primary
16631
+ },
16632
+ createdAt: brand.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
16633
+ updatedAt: brand.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()
16634
+ }));
16635
+ }
16636
+ /** @deprecated Use createBrand */
16637
+ async createBrandProfile(body) {
16638
+ const brand = await this.createBrand({ name: body.name });
16639
+ return (await this.listBrandProfiles()).find((item) => item.id === brand.id) ?? {
16640
+ id: brand.id,
16641
+ name: brand.name,
16642
+ preference: body.preference,
16643
+ createdAt: brand.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
16644
+ updatedAt: brand.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()
16645
+ };
16646
+ }
16647
+ /** @deprecated Use updateBrand */
16648
+ async updateBrandProfile(id, body) {
16649
+ const current = await this.getBrand(id);
16650
+ await this.updateBrand(id, {
16651
+ baseRevision: current.revision ?? 1,
16652
+ name: body.name
16653
+ });
16654
+ return (await this.listBrandProfiles()).find((item) => item.id === id) ?? {
16655
+ id,
16656
+ name: body.name ?? current.name,
16657
+ preference: body.preference ?? {},
16658
+ createdAt: current.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
16659
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
16660
+ };
19250
16661
  }
19251
16662
  /**
19252
16663
  * Materialize a confirmed external/upload image into R2 + Directus Image.
@@ -34824,13 +32235,14 @@ var init_src5 = __esm({
34824
32235
  init_src2();
34825
32236
  objectSchema = { type: "object", properties: {}, additionalProperties: true };
34826
32237
  slideshowToolRegistry = [
34827
- { name: "create_run", title: "Create slideshow run", description: "Create an ADR-0026 Slideshow Run from a ContentPack.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { pack: { type: "object" }, brandProfileId: { type: "string" } }, required: ["pack"] }, outputSchema: objectSchema },
32238
+ { name: "list_runs", title: "List slideshow runs", description: "List owner-scoped Slideshow Runs with optional filters.", effect: "read-only", inputSchema: { ...objectSchema, properties: { q: { type: "string" }, platform: { type: "string" }, profileId: { type: "string" }, brandProfileId: { type: "string" }, contentSlug: { type: "string" }, status: { type: "string" } } }, outputSchema: objectSchema },
32239
+ { name: "create_run", title: "Create slideshow run", description: "Create an ADR-0026 Slideshow Run from a ContentPack.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { pack: { type: "object" }, brandId: { type: "string" }, brandProfileId: { type: "string" }, contentSlug: { type: "string" } }, required: ["pack"] }, outputSchema: objectSchema },
34828
32240
  { name: "get_run", title: "Get slideshow run", description: "Get an owner-scoped Slideshow Run.", effect: "read-only", inputSchema: { ...objectSchema, properties: { runId: { type: "string" } }, required: ["runId"] }, outputSchema: objectSchema },
34829
- { name: "update_run", title: "Update slideshow run", description: "Edit page-instance slots/layout/style/decorations or presentation preference with optimistic revision.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { runId: { type: "string" }, pack: { type: "object" }, brandProfileId: { type: "string" }, baseRevision: { type: "integer", minimum: 1 }, pageIndex: { type: "integer", minimum: 0 }, slots: { type: "object" }, layout: { type: "object" }, style: { type: "object" }, decorations: { type: "array" } }, required: ["runId"] }, outputSchema: objectSchema },
34830
- { name: "render_run", title: "Render slideshow run", description: "Render a topology-locked Run as an atomic PNG set.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { runId: { type: "string" }, idempotencyKey: { type: "string", minLength: 1, maxLength: 128 } }, required: ["runId", "idempotencyKey"] }, outputSchema: objectSchema },
34831
- { name: "list_brand_profiles", title: "List brand profiles", description: "List owner-scoped Brand Profiles.", effect: "read-only", inputSchema: { ...objectSchema, properties: {} }, outputSchema: objectSchema },
34832
- { name: "create_brand_profile", title: "Create brand profile", description: "Create a Brand Profile; Free workspaces are limited to one.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { name: { type: "string" }, preference: { type: "object" } }, required: ["name"] }, outputSchema: objectSchema },
34833
- { name: "update_brand_profile", title: "Update brand profile", description: "Update a Brand Profile preference.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { profileId: { type: "string" }, name: { type: "string" }, preference: { type: "object" } }, required: ["profileId"] }, outputSchema: objectSchema }
32241
+ { name: "update_run", title: "Update slideshow run", description: "Edit page-instance slots/layout/style/decorations or presentation preference with optimistic revision.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { runId: { type: "string" }, pack: { type: "object" }, brandId: { type: "string" }, brandProfileId: { type: "string" }, contentSlug: { type: "string" }, baseRevision: { type: "integer", minimum: 1 }, pageIndex: { type: "integer", minimum: 0 }, slots: { type: "object" }, layout: { type: "object" }, style: { type: "object" }, decorations: { type: "array" } }, required: ["runId"] }, outputSchema: objectSchema },
32242
+ { name: "archive_run", title: "Archive slideshow run", description: "Hide a Run from default lists without deleting it.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { runId: { type: "string" } }, required: ["runId"] }, outputSchema: objectSchema },
32243
+ { name: "restore_run", title: "Restore slideshow run", description: "Restore an archived or trashed Run.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { runId: { type: "string" } }, required: ["runId"] }, outputSchema: objectSchema },
32244
+ { name: "trash_run", title: "Trash slideshow run", description: "Move a Run to trash (recoverable for 30 days).", effect: "explicit-approval", inputSchema: { ...objectSchema, properties: { runId: { type: "string" } }, required: ["runId"] }, outputSchema: objectSchema },
32245
+ { name: "render_run", title: "Render slideshow run", description: "Render a topology-locked Run as an atomic PNG set.", effect: "local-write-job", inputSchema: { ...objectSchema, properties: { runId: { type: "string" }, idempotencyKey: { type: "string", minLength: 1, maxLength: 128 } }, required: ["runId", "idempotencyKey"] }, outputSchema: objectSchema }
34834
32246
  ];
34835
32247
  slideshowResourceTemplates = [
34836
32248
  { uriTemplate: "slideshow://runs/{runId}", name: "Slideshow Run", description: "Owner-scoped Run JSON snapshot", mimeType: "application/json" }
@@ -34843,20 +32255,29 @@ var init_src5 = __esm({
34843
32255
  const m = meta3();
34844
32256
  try {
34845
32257
  switch (toolName) {
32258
+ case "list_runs":
32259
+ return { ok: true, data: await this.client.listSlideshowRuns({
32260
+ q: args.q,
32261
+ platform: args.platform,
32262
+ profileId: args.profileId,
32263
+ brandProfileId: args.brandProfileId,
32264
+ contentSlug: args.contentSlug,
32265
+ status: args.status
32266
+ }), meta: m };
34846
32267
  case "create_run":
34847
- return { ok: true, data: await this.client.createSlideshowRun({ pack: args.pack, brandProfileId: args.brandProfileId }), meta: m };
32268
+ return { ok: true, data: await this.client.createSlideshowRun({ pack: args.pack, brandId: args.brandId, brandProfileId: args.brandProfileId, contentSlug: args.contentSlug }), meta: m };
34848
32269
  case "get_run":
34849
32270
  return { ok: true, data: await this.client.getSlideshowRun(String(args.runId)), meta: m };
34850
32271
  case "update_run":
34851
- return { ok: true, data: await this.client.updateSlideshowRun(String(args.runId), { pack: args.pack, brandProfileId: args.brandProfileId, baseRevision: args.baseRevision, pageIndex: args.pageIndex, slots: args.slots, layout: args.layout, style: args.style, decorations: args.decorations }), meta: m };
32272
+ return { ok: true, data: await this.client.updateSlideshowRun(String(args.runId), { pack: args.pack, brandId: args.brandId, brandProfileId: args.brandProfileId, contentSlug: args.contentSlug, baseRevision: args.baseRevision, pageIndex: args.pageIndex, slots: args.slots, layout: args.layout, style: args.style, decorations: args.decorations }), meta: m };
32273
+ case "archive_run":
32274
+ return { ok: true, data: await this.client.archiveSlideshowRun(String(args.runId)), meta: m };
32275
+ case "restore_run":
32276
+ return { ok: true, data: await this.client.restoreSlideshowRun(String(args.runId)), meta: m };
32277
+ case "trash_run":
32278
+ return { ok: true, data: await this.client.trashSlideshowRun(String(args.runId)), meta: m };
34852
32279
  case "render_run":
34853
32280
  return { ok: true, data: await this.client.renderSlideshowRun(String(args.runId), { outputFormats: args.outputFormats ?? ["png"], idempotencyKey: String(args.idempotencyKey) }), meta: m };
34854
- case "list_brand_profiles":
34855
- return { ok: true, data: await this.client.listBrandProfiles(), meta: m };
34856
- case "create_brand_profile":
34857
- return { ok: true, data: await this.client.createBrandProfile({ name: String(args.name), preference: args.preference ?? {} }), meta: m };
34858
- case "update_brand_profile":
34859
- return { ok: true, data: await this.client.updateBrandProfile(String(args.profileId), { name: args.name, preference: args.preference }), meta: m };
34860
32281
  default:
34861
32282
  return { ok: false, error: { code: "UNKNOWN_TOOL", message: `Unknown tool: ${toolName}`, retryable: false }, meta: m };
34862
32283
  }
@@ -34888,7 +32309,7 @@ async function serveUnifiedStdioMcp(client) {
34888
32309
  resourceTemplates: unifiedResourceTemplates
34889
32310
  }, { backendName: "gateway" });
34890
32311
  }
34891
- var removedTools, templateNames, slideshowNames, rename, templateTools, slideshowTools, imageTools, unifiedToolRegistry, unifiedResourceTemplates, UnifiedMcpBackend;
32312
+ var removedTools, templateNames, slideshowNames, brandTools, rename, templateTools, slideshowTools, imageTools, unifiedToolRegistry, unifiedResourceTemplates, UnifiedMcpBackend;
34892
32313
  var init_src6 = __esm({
34893
32314
  "../../packages/mcp-server/src/index.ts"() {
34894
32315
  "use strict";
@@ -34906,14 +32327,24 @@ var init_src6 = __esm({
34906
32327
  get_render_job: "get_template_render_job"
34907
32328
  };
34908
32329
  slideshowNames = {
32330
+ list_runs: "list_slideshow_runs",
34909
32331
  create_run: "create_slideshow_run",
34910
32332
  get_run: "get_slideshow_run",
34911
32333
  update_run: "update_slideshow_run",
34912
- render_run: "render_slideshow_run",
34913
- list_brand_profiles: "list_profiles",
34914
- create_brand_profile: "create_profile",
34915
- update_brand_profile: "update_profile"
34916
- };
32334
+ archive_run: "archive_slideshow_run",
32335
+ restore_run: "restore_slideshow_run",
32336
+ trash_run: "trash_slideshow_run",
32337
+ render_run: "render_slideshow_run"
32338
+ };
32339
+ brandTools = [
32340
+ { name: "list_brands", title: "List brands", description: "List owner-scoped Brands (identity + fonts + colors + logo).", effect: "read-only", inputSchema: { type: "object", properties: {}, additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
32341
+ { name: "get_brand", title: "Get brand", description: "Get one Brand by id.", effect: "read-only", inputSchema: { type: "object", properties: { brandId: { type: "string" } }, required: ["brandId"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
32342
+ { name: "create_brand", title: "Create brand", description: "Create a Brand with optional fonts, colors and logoAssetId.", effect: "local-write-job", inputSchema: { type: "object", properties: { name: { type: "string" }, displayName: { type: "string" }, handle: { type: "string" }, typography: { type: "object" }, colors: { type: "object" }, logoAssetId: { type: "string" } }, required: ["name"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
32343
+ { name: "update_brand", title: "Update brand", description: "Patch Brand appearance with optimistic baseRevision.", effect: "local-write-job", inputSchema: { type: "object", properties: { brandId: { type: "string" }, baseRevision: { type: "integer", minimum: 1 }, name: { type: "string" }, displayName: { type: "string" }, handle: { type: "string" }, typography: { type: "object" }, colors: { type: "object" }, logoAssetId: { type: "string" } }, required: ["brandId", "baseRevision"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
32344
+ { name: "archive_brand", title: "Archive brand", description: "Archive a Brand.", effect: "local-write-job", inputSchema: { type: "object", properties: { brandId: { type: "string" } }, required: ["brandId"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
32345
+ { name: "restore_brand", title: "Restore brand", description: "Restore an archived Brand.", effect: "local-write-job", inputSchema: { type: "object", properties: { brandId: { type: "string" } }, required: ["brandId"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
32346
+ { name: "trash_brand", title: "Trash brand", description: "Move a Brand to trash.", effect: "explicit-approval", inputSchema: { type: "object", properties: { brandId: { type: "string" } }, required: ["brandId"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } }
32347
+ ];
34917
32348
  rename = (tool, names) => ({ ...tool, name: names[tool.name] ?? tool.name });
34918
32349
  templateTools = templateToolRegistry.map((tool) => rename(tool, templateNames));
34919
32350
  slideshowTools = slideshowToolRegistry.filter((tool) => !removedTools.has(tool.name)).map((tool) => rename(tool, slideshowNames));
@@ -34926,7 +32357,7 @@ var init_src6 = __esm({
34926
32357
  { name: "restore_image", title: "Restore image", description: "Restore an image asset.", effect: "local-write-job", inputSchema: { type: "object", properties: { imageId: { type: "string" } }, required: ["imageId"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } },
34927
32358
  { name: "delete_image", title: "Trash image", description: "Move an image asset to trash.", effect: "explicit-approval", inputSchema: { type: "object", properties: { imageId: { type: "string" } }, required: ["imageId"], additionalProperties: false }, outputSchema: { type: "object", properties: {} } }
34928
32359
  ];
34929
- unifiedToolRegistry = [...templateTools, ...slideshowTools, ...imageTools];
32360
+ unifiedToolRegistry = [...templateTools, ...slideshowTools, ...brandTools, ...imageTools];
34930
32361
  unifiedResourceTemplates = slideshowResourceTemplates;
34931
32362
  UnifiedMcpBackend = class {
34932
32363
  client;
@@ -34942,6 +32373,47 @@ var init_src6 = __esm({
34942
32373
  if (templateTool) return this.template.invoke(Object.entries(templateNames).find(([, name]) => name === toolName)?.[0] ?? toolName, args);
34943
32374
  const slideshowTool = slideshowTools.find((tool) => tool.name === toolName);
34944
32375
  if (slideshowTool) return this.slideshow.invoke(Object.entries(slideshowNames).find(([, name]) => name === toolName)?.[0] ?? toolName, args);
32376
+ const brandTool = brandTools.find((tool) => tool.name === toolName);
32377
+ if (brandTool) {
32378
+ const meta4 = { requestId: `mcp_${Date.now().toString(36)}`, runtimeVersion: "0.0.0", schemaVersion: 1, toolContractVersion: "2026-08-28" };
32379
+ const brandId = typeof args.brandId === "string" ? args.brandId : "";
32380
+ const run = async () => {
32381
+ switch (toolName) {
32382
+ case "list_brands":
32383
+ return this.client.listBrands();
32384
+ case "get_brand":
32385
+ return this.client.getBrand(brandId);
32386
+ case "create_brand":
32387
+ return this.client.createBrand({
32388
+ name: String(args.name),
32389
+ displayName: args.displayName,
32390
+ handle: args.handle,
32391
+ typography: args.typography,
32392
+ colors: args.colors,
32393
+ logoAssetId: args.logoAssetId
32394
+ });
32395
+ case "update_brand":
32396
+ return this.client.updateBrand(brandId, {
32397
+ baseRevision: Number(args.baseRevision),
32398
+ name: args.name,
32399
+ displayName: args.displayName,
32400
+ handle: args.handle,
32401
+ typography: args.typography,
32402
+ colors: args.colors,
32403
+ logoAssetId: args.logoAssetId
32404
+ });
32405
+ case "archive_brand":
32406
+ return this.client.archiveBrand(brandId);
32407
+ case "restore_brand":
32408
+ return this.client.restoreBrand(brandId);
32409
+ case "trash_brand":
32410
+ return this.client.trashBrand(brandId);
32411
+ default:
32412
+ throw new Error(`Unknown brand tool: ${toolName}`);
32413
+ }
32414
+ };
32415
+ return run().then((data) => ({ ok: true, data, meta: meta4 })).catch((e) => ({ ok: false, error: { code: e?.code ?? "GATEWAY_ERROR", message: e?.message ?? "Gateway request failed", retryable: Boolean(e?.retryable) }, meta: meta4 }));
32416
+ }
34945
32417
  const imageTool = imageTools.find((tool) => tool.name === toolName);
34946
32418
  if (imageTool) {
34947
32419
  const imageId = typeof args.imageId === "string" ? encodeURIComponent(args.imageId) : "";
@@ -34979,32 +32451,13 @@ var init_v1_mcp = __esm({
34979
32451
  });
34980
32452
 
34981
32453
  // src/v1-cli.ts
32454
+ init_src2();
34982
32455
  import { cp, mkdtemp, readFile, rename as rename2, rm, writeFile, mkdir, chmod, copyFile } from "fs/promises";
34983
32456
  import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
34984
32457
  import { createHash } from "crypto";
34985
32458
  import { homedir as homedir2, tmpdir } from "os";
34986
32459
  import { join as join3 } from "path";
34987
- import { fileURLToPath as fileURLToPath2 } from "url";
34988
-
34989
- // ../../node_modules/.pnpm/commander@11.1.0/node_modules/commander/esm.mjs
34990
- var import_index = __toESM(require_commander(), 1);
34991
- var {
34992
- program,
34993
- createCommand,
34994
- createArgument,
34995
- createOption,
34996
- CommanderError,
34997
- InvalidArgumentError,
34998
- InvalidOptionArgumentError,
34999
- // deprecated old name
35000
- Command,
35001
- Argument,
35002
- Option,
35003
- Help
35004
- } = import_index.default;
35005
-
35006
- // src/v1-cli.ts
35007
- init_src2();
32460
+ import { Command } from "commander";
35008
32461
 
35009
32462
  // src/runtime/mcp-hosts.ts
35010
32463
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
@@ -35129,7 +32582,15 @@ function resolveDefaultSkillsSource(moduleUrl) {
35129
32582
  }
35130
32583
 
35131
32584
  // src/v1-cli.ts
35132
- var CLI_MODULE_URL = fileURLToPath2(import.meta.url);
32585
+ var CLI_MODULE_URL = import.meta.url;
32586
+ function readCliVersion() {
32587
+ try {
32588
+ const pkg = JSON.parse(readFileSync2(join3(cliPackageRoot(CLI_MODULE_URL), "package.json"), "utf8"));
32589
+ return typeof pkg.version === "string" && pkg.version ? pkg.version : "0.0.0";
32590
+ } catch {
32591
+ return "0.0.0";
32592
+ }
32593
+ }
35133
32594
  var credentialPath = join3(homedir2(), ".config", "easysociable", "credentials.json");
35134
32595
  function resolveInstallSkillIds(options) {
35135
32596
  return parseInstallSkills(typeof options.skills === "string" ? options.skills : void 0);
@@ -35345,22 +32806,22 @@ function addCrudCommands(parent, resource, routes) {
35345
32806
  }
35346
32807
  }
35347
32808
  function buildV1Cli() {
35348
- const program2 = new Command().name("easysociable").description("EasySociable Gateway CLI for Template and Slideshow V1").version("0.0.0").option("--json", "Emit a JSON envelope");
35349
- jsonOption(program2.command("install").description("Install Skills and one MCP registration for detected Codex/Claude hosts").option("--yes", "Apply the reviewed changes").option("--skills <list>", "Skills to install: content,template,slideshow (default: template,slideshow)").option("--source <path>", "Skill source root").option("--home <path>", "Home directory fixture for tests")).action(async (...args) => {
32809
+ const program = new Command().name("easysociable").description("EasySociable Gateway CLI for Template and Slideshow V1").version(readCliVersion()).option("--json", "Emit a JSON envelope");
32810
+ jsonOption(program.command("install").description("Install Skills and one MCP registration for detected Codex/Claude hosts").option("--yes", "Apply the reviewed changes").option("--skills <list>", "Skills to install: content,template,slideshow (default: template,slideshow)").option("--source <path>", "Skill source root").option("--home <path>", "Home directory fixture for tests")).action(async (...args) => {
35350
32811
  const command = args.at(-1);
35351
32812
  const opts = command.opts();
35352
32813
  const plan = await planInstallation(opts);
35353
32814
  const result = opts.yes === true ? await applyInstallation(opts) : { ...plan, applied: false, next: "Review changes and re-run with --yes" };
35354
32815
  print(result, Boolean(opts.json));
35355
32816
  });
35356
- jsonOption(program2.command("update").description("Update installed Skills and MCP registration with backup").option("--yes", "Apply the reviewed changes").option("--skills <list>", "Skills to install: content,template,slideshow (default: template,slideshow)").option("--source <path>", "Skill source root").option("--home <path>", "Home directory fixture for tests")).action(async (...args) => {
32817
+ jsonOption(program.command("update").description("Update installed Skills and MCP registration with backup").option("--yes", "Apply the reviewed changes").option("--skills <list>", "Skills to install: content,template,slideshow (default: template,slideshow)").option("--source <path>", "Skill source root").option("--home <path>", "Home directory fixture for tests")).action(async (...args) => {
35357
32818
  const command = args.at(-1);
35358
32819
  const opts = command.opts();
35359
32820
  const plan = await planInstallation(opts);
35360
32821
  const result = opts.yes === true ? await applyInstallation(opts) : { ...plan, applied: false, next: "Review changes and re-run with --yes" };
35361
32822
  print(result, Boolean(opts.json));
35362
32823
  });
35363
- const auth = program2.command("auth").description("Manage the shared EasySociable credential");
32824
+ const auth = program.command("auth").description("Manage the shared EasySociable credential");
35364
32825
  jsonOption(auth.command("status").description("Show authentication status")).action(async (...args) => {
35365
32826
  const command = args.at(-1);
35366
32827
  const stored = readStoredCredentials();
@@ -35377,17 +32838,18 @@ function buildV1Cli() {
35377
32838
  await rm(credentialPath, { force: true });
35378
32839
  process.stdout.write("Removed the stored EasySociable credential.\n");
35379
32840
  });
35380
- addCrudCommands(program2.command("profiles"), "profiles", { list: "/v1/profiles", get: "/v1/profiles/:id", create: "/v1/profiles", update: "/v1/profiles/:id", archive: "/v1/profiles/:id/archive", restore: "/v1/profiles/:id/restore", delete: "/v1/profiles/:id" });
35381
- const themes = program2.command("themes").description("Manage Profile-owned Themes");
32841
+ addCrudCommands(program.command("brands").description("Manage workspace Brands (identity, fonts, colors, logo)"), "brands", { list: "/v1/brands", get: "/v1/brands/:id", create: "/v1/brands", update: "/v1/brands/:id", archive: "/v1/brands/:id/archive", restore: "/v1/brands/:id/restore", delete: "/v1/brands/:id" });
32842
+ addCrudCommands(program.command("profiles").description("Deprecated \u2014 use brands"), "profiles", { list: "/v1/profiles", get: "/v1/profiles/:id", create: "/v1/profiles", update: "/v1/profiles/:id", archive: "/v1/profiles/:id/archive", restore: "/v1/profiles/:id/restore", delete: "/v1/profiles/:id" });
32843
+ const themes = program.command("themes").description("Deprecated \u2014 use brands");
35382
32844
  addCrudCommands(themes, "themes", { list: "/v1/themes", get: "/v1/themes/:id", create: "/v1/themes", update: "/v1/themes/:id", archive: "/v1/themes/:id/archive", restore: "/v1/themes/:id/restore", delete: "/v1/themes/:id" });
35383
32845
  jsonOption(themes.command("set-default").requiredOption("--profile-id <profileId>").requiredOption("--theme-id <themeId>")).action(withClient(async (client, opts) => client.requestJson("POST", `/v1/profiles/${opts.profileId}/default-theme`, { themeId: opts.themeId })));
35384
- const images = program2.command("images").description("Manage account image assets");
32846
+ const images = program.command("images").description("Manage account image assets");
35385
32847
  addCrudCommands(images, "images", { list: "/v1/images", get: "/v1/images/:id", create: "/v1/images/imports", update: "/v1/images/:id", archive: "/v1/images/:id/archive", restore: "/v1/images/:id/restore", delete: "/v1/images/:id" });
35386
32848
  jsonOption(images.command("upload").requiredOption("--file <path>")).action(withClient(async (client, opts) => client.requestJson("POST", "/v1/images/imports", JSON.parse(await readFile(String(opts.file), "utf8")))));
35387
32849
  jsonOption(images.command("import-url").requiredOption("--url <url>").option("--name <name>")).action(withClient(async (client, opts) => client.requestJson("POST", "/v1/images/imports", { sourceUrl: String(opts.url), ...opts.name ? { name: String(opts.name) } : {} })));
35388
32850
  jsonOption(images.command("search").requiredOption("--q <query>")).action(withClient(async (client, opts) => client.requestJson("GET", `/v1/images?q=${encodeURIComponent(String(opts.q))}`)));
35389
32851
  jsonOption(images.command("attest").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.requestJson("POST", `/v1/images/${opts.id}/attest`, { accepted: true })));
35390
- const templates = program2.command("templates").description("Create and manage Page Template drafts");
32852
+ const templates = program.command("templates").description("Create and manage Page Template drafts");
35391
32853
  jsonOption(templates.command("list")).action(withClient(async (client) => client.listTemplates()));
35392
32854
  jsonOption(templates.command("get").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.getTemplate(String(opts.id))));
35393
32855
  jsonOption(templates.command("create-draft").requiredOption("--file <path>")).action(withClient(async (client, opts) => client.createDraft(JSON.parse(await readFile(String(opts.file), "utf8")))));
@@ -35398,16 +32860,26 @@ function buildV1Cli() {
35398
32860
  jsonOption(templates.command("archive").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.archiveDraft(String(opts.id))));
35399
32861
  jsonOption(templates.command("restore").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.restoreDraft(String(opts.id))));
35400
32862
  jsonOption(templates.command("delete").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.deleteDraft(String(opts.id))));
35401
- const icons = program2.command("icons").description("Search the internal safe icon catalog");
32863
+ const icons = program.command("icons").description("Search the internal safe icon catalog");
35402
32864
  jsonOption(icons.command("search").requiredOption("--query <query>")).action(withClient(async (client, opts) => client.searchIcons({ query: String(opts.query) })));
35403
32865
  jsonOption(icons.command("get").requiredOption("--id <id>").requiredOption("--idempotency-key <key>")).action(withClient(async (client, opts) => client.getIcon({ iconId: String(opts.id), idempotencyKey: String(opts.idempotencyKey) })));
35404
- const slideshows = program2.command("slideshows").description("Create and render temporary Slideshow Runs");
35405
- jsonOption(slideshows.command("create").requiredOption("--file <path>")).action(withClient(async (client, opts) => client.createSlideshowRun(JSON.parse(await readFile(String(opts.file), "utf8")))));
32866
+ const slideshows = program.command("slideshows").description("List, create, update and render Slideshow Runs");
32867
+ jsonOption(slideshows.command("list").option("--q <text>").option("--platform <platform>").option("--profile-id <id>").option("--content-slug <slug>").option("--status <status>")).action(withClient(async (client, opts) => client.listSlideshowRuns({
32868
+ q: opts.q ? String(opts.q) : void 0,
32869
+ platform: opts.platform ? String(opts.platform) : void 0,
32870
+ profileId: opts.profileId ? String(opts.profileId) : void 0,
32871
+ contentSlug: opts.contentSlug ? String(opts.contentSlug) : void 0,
32872
+ status: opts.status ? String(opts.status) : void 0
32873
+ })));
32874
+ jsonOption(slideshows.command("create").requiredOption("--file <path>")).action(withClient(async (client, opts) => client.createSlideshowRun({ pack: JSON.parse(await readFile(String(opts.file), "utf8")) })));
35406
32875
  jsonOption(slideshows.command("get").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.getSlideshowRun(String(opts.id))));
35407
32876
  jsonOption(slideshows.command("update").requiredOption("--id <id>").requiredOption("--file <path>")).action(withClient(async (client, opts) => client.updateSlideshowRun(String(opts.id), JSON.parse(await readFile(String(opts.file), "utf8")))));
32877
+ jsonOption(slideshows.command("archive").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.archiveSlideshowRun(String(opts.id))));
32878
+ jsonOption(slideshows.command("restore").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.restoreSlideshowRun(String(opts.id))));
32879
+ jsonOption(slideshows.command("delete").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.trashSlideshowRun(String(opts.id))));
35408
32880
  jsonOption(slideshows.command("render").requiredOption("--id <id>").requiredOption("--idempotency-key <key>")).action(withClient(async (client, opts) => client.renderSlideshowRun(String(opts.id), { outputFormats: ["png"], idempotencyKey: String(opts.idempotencyKey) })));
35409
32881
  jsonOption(slideshows.command("export").requiredOption("--id <id>").requiredOption("--output <path>")).action(withClient(async (client, opts) => exportSlideshowRun(client, String(opts.id), String(opts.output))));
35410
- const renders = program2.command("renders").description("Inspect final render jobs");
32882
+ const renders = program.command("renders").description("Inspect final render jobs");
35411
32883
  jsonOption(renders.command("create-asset").requiredOption("--file <path>").requiredOption("--idempotency-key <key>")).action(withClient(async (client, opts) => {
35412
32884
  const fileName = String(opts.file);
35413
32885
  const bytes = await readFile(fileName);
@@ -35431,7 +32903,7 @@ function buildV1Cli() {
35431
32903
  jsonOption(renders.command("manifest").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.getRenderManifest(String(opts.id))));
35432
32904
  jsonOption(renders.command("wait").requiredOption("--id <id>")).action(withClient(async (client, opts) => client.pollRenderJob(String(opts.id))));
35433
32905
  jsonOption(renders.command("export").requiredOption("--id <id>").requiredOption("--output <path>")).action(withClient(async (client, opts) => exportManifest(client, String(opts.id), String(opts.output))));
35434
- const mcp = program2.command("mcp").description("Install and run the unified EasySociable MCP server");
32906
+ const mcp = program.command("mcp").description("Install and run the unified EasySociable MCP server");
35435
32907
  jsonOption(mcp.command("install").requiredOption("--host <host>", "codex, claude, hermes, or openclaw").option("--config-path <path>")).action((...args) => {
35436
32908
  const command = args.at(-1);
35437
32909
  const opts = command.opts();
@@ -35444,12 +32916,12 @@ function buildV1Cli() {
35444
32916
  const { serveUnifiedStdioMcp: serveUnifiedStdioMcp2 } = await Promise.resolve().then(() => (init_v1_mcp(), v1_mcp_exports));
35445
32917
  await serveUnifiedStdioMcp2(clientFromEnv());
35446
32918
  });
35447
- return program2;
32919
+ return program;
35448
32920
  }
35449
32921
  async function runV1Cli(argv = process.argv) {
35450
- const program2 = buildV1Cli();
32922
+ const program = buildV1Cli();
35451
32923
  try {
35452
- await program2.parseAsync(argv);
32924
+ await program.parseAsync(argv);
35453
32925
  return 0;
35454
32926
  } catch (error52) {
35455
32927
  process.stderr.write(`${error52 instanceof Error ? error52.message : String(error52)}