@gusto/create-baerly-storage 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/THIRD-PARTY-LICENSES.txt +204 -0
  2. package/dist/index.js +1537 -145
  3. package/dist/index.js.map +1 -1
  4. package/dist/templates/addons/docker/Dockerfile +13 -11
  5. package/dist/templates/minimal-cloudflare/AGENTS.md +77 -399
  6. package/dist/templates/minimal-cloudflare/README.md +33 -97
  7. package/dist/templates/minimal-cloudflare/package.json +12 -9
  8. package/dist/templates/minimal-cloudflare/pnpm-workspace.yaml +13 -7
  9. package/dist/templates/minimal-cloudflare/tsconfig.app.json +2 -3
  10. package/dist/templates/minimal-cloudflare/tsconfig.worker.json +2 -3
  11. package/dist/templates/minimal-cloudflare/vitest.config.ts +1 -1
  12. package/dist/templates/minimal-cloudflare/wrangler.jsonc +4 -2
  13. package/dist/templates/minimal-node/AGENTS.md +80 -380
  14. package/dist/templates/minimal-node/README.md +37 -135
  15. package/dist/templates/minimal-node/package.json +11 -9
  16. package/dist/templates/minimal-node/pnpm-workspace.yaml +14 -9
  17. package/dist/templates/minimal-node/tsconfig.app.json +2 -3
  18. package/dist/templates/minimal-node/tsconfig.server.json +2 -3
  19. package/dist/templates/react-cloudflare/AGENTS.md +101 -444
  20. package/dist/templates/react-cloudflare/README.md +14 -54
  21. package/dist/templates/react-cloudflare/package.json +18 -15
  22. package/dist/templates/react-cloudflare/pnpm-workspace.yaml +13 -7
  23. package/dist/templates/react-cloudflare/tsconfig.app.json +2 -3
  24. package/dist/templates/react-cloudflare/tsconfig.worker.json +2 -3
  25. package/dist/templates/react-cloudflare/vitest.config.ts +1 -1
  26. package/dist/templates/react-cloudflare/wrangler.jsonc +4 -2
  27. package/dist/templates/react-node/AGENTS.md +108 -474
  28. package/dist/templates/react-node/README.md +35 -125
  29. package/dist/templates/react-node/package.json +16 -14
  30. package/dist/templates/react-node/pnpm-workspace.yaml +14 -9
  31. package/dist/templates/react-node/tsconfig.app.json +2 -3
  32. package/dist/templates/react-node/tsconfig.server.json +2 -3
  33. package/package.json +7 -7
  34. package/dist/templates/minimal-cloudflare/uint8array-base64.d.ts +0 -16
  35. package/dist/templates/minimal-node/uint8array-base64.d.ts +0 -16
  36. package/dist/templates/react-cloudflare/uint8array-base64.d.ts +0 -16
  37. package/dist/templates/react-node/uint8array-base64.d.ts +0 -16
package/dist/index.js CHANGED
@@ -1,14 +1,1375 @@
1
1
  #!/usr/bin/env node
2
- import { defineCommand, runCommand, showUsage } from "citty";
3
- import pc from "picocolors";
4
- import { cancel, confirm, intro, isCancel, note, outro, select, text } from "@clack/prompts";
2
+ import { parseArgs as parseArgs$1, styleText } from "node:util";
3
+ import process$1, { stdin, stdout } from "node:process";
4
+ import f__default from "node:readline";
5
+ import "node:tty";
5
6
  import { constants, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
6
- import { basename, dirname, join, resolve, sep } from "node:path";
7
+ import { basename, dirname, join, resolve as resolve$1, sep } from "node:path";
7
8
  import { spawn, spawnSync } from "node:child_process";
8
9
  import { fileURLToPath } from "node:url";
9
10
  import { access, appendFile, mkdir, readFile, stat, writeFile } from "node:fs/promises";
10
11
  import { dirname as dirname$1, normalize, relative } from "node:path/posix";
11
- //#region src/git.ts
12
+ // ../../node_modules/.pnpm/citty@0.2.2/node_modules/citty/dist/_chunks/libs/scule.mjs
13
+ const NUMBER_CHAR_RE = /\d/;
14
+ const STR_SPLITTERS = [
15
+ "-",
16
+ "_",
17
+ "/",
18
+ "."
19
+ ];
20
+ function isUppercase(char = "") {
21
+ if (NUMBER_CHAR_RE.test(char)) return;
22
+ return char !== char.toLowerCase();
23
+ }
24
+ function splitByCase(str, separators) {
25
+ const splitters = separators ?? STR_SPLITTERS;
26
+ const parts = [];
27
+ if (!str || typeof str !== "string") return parts;
28
+ let buff = "";
29
+ let previousUpper;
30
+ let previousSplitter;
31
+ for (const char of str) {
32
+ const isSplitter = splitters.includes(char);
33
+ if (isSplitter === true) {
34
+ parts.push(buff);
35
+ buff = "";
36
+ previousUpper = void 0;
37
+ continue;
38
+ }
39
+ const isUpper = isUppercase(char);
40
+ if (previousSplitter === false) {
41
+ if (previousUpper === false && isUpper === true) {
42
+ parts.push(buff);
43
+ buff = char;
44
+ previousUpper = isUpper;
45
+ continue;
46
+ }
47
+ if (previousUpper === true && isUpper === false && buff.length > 1) {
48
+ const lastChar = buff.at(-1);
49
+ parts.push(buff.slice(0, Math.max(0, buff.length - 1)));
50
+ buff = lastChar + char;
51
+ previousUpper = isUpper;
52
+ continue;
53
+ }
54
+ }
55
+ buff += char;
56
+ previousUpper = isUpper;
57
+ previousSplitter = isSplitter;
58
+ }
59
+ parts.push(buff);
60
+ return parts;
61
+ }
62
+ function upperFirst(str) {
63
+ return str ? str[0].toUpperCase() + str.slice(1) : "";
64
+ }
65
+ function lowerFirst(str) {
66
+ return str ? str[0].toLowerCase() + str.slice(1) : "";
67
+ }
68
+ function pascalCase(str, opts) {
69
+ return str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => upperFirst(opts?.normalize ? p.toLowerCase() : p)).join("") : "";
70
+ }
71
+ function camelCase(str, opts) {
72
+ return lowerFirst(pascalCase(str || "", opts));
73
+ }
74
+ function kebabCase(str, joiner) {
75
+ return str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => p.toLowerCase()).join(joiner ?? "-") : "";
76
+ }
77
+ function snakeCase(str) {
78
+ return kebabCase(str || "", "_");
79
+ }
80
+ // ../../node_modules/.pnpm/citty@0.2.2/node_modules/citty/dist/index.mjs
81
+ function toArray(val) {
82
+ if (Array.isArray(val)) return val;
83
+ return val === void 0 ? [] : [val];
84
+ }
85
+ function formatLineColumns(lines, linePrefix = "") {
86
+ const maxLength = [];
87
+ for (const line of lines) for (const [i, element] of line.entries()) maxLength[i] = Math.max(maxLength[i] || 0, element.length);
88
+ return lines.map((l) => l.map((c, i) => linePrefix + c[i === 0 ? "padStart" : "padEnd"](maxLength[i])).join(" ")).join("\n");
89
+ }
90
+ function resolveValue(input) {
91
+ return typeof input === "function" ? input() : input;
92
+ }
93
+ var CLIError = class extends Error {
94
+ code;
95
+ constructor(message, code) {
96
+ super(message);
97
+ this.name = "CLIError";
98
+ this.code = code;
99
+ }
100
+ };
101
+ function parseRawArgs(args = [], opts = {}) {
102
+ const booleans = new Set(opts.boolean || []);
103
+ const strings = new Set(opts.string || []);
104
+ const aliasMap = opts.alias || {};
105
+ const defaults = opts.default || {};
106
+ const aliasToMain = /* @__PURE__ */ new Map();
107
+ const mainToAliases = /* @__PURE__ */ new Map();
108
+ for (const [key, value] of Object.entries(aliasMap)) {
109
+ const targets = value;
110
+ for (const target of targets) {
111
+ aliasToMain.set(key, target);
112
+ if (!mainToAliases.has(target)) mainToAliases.set(target, []);
113
+ mainToAliases.get(target).push(key);
114
+ aliasToMain.set(target, key);
115
+ if (!mainToAliases.has(key)) mainToAliases.set(key, []);
116
+ mainToAliases.get(key).push(target);
117
+ }
118
+ }
119
+ const options = {};
120
+ function getType(name) {
121
+ if (booleans.has(name)) return "boolean";
122
+ const aliases = mainToAliases.get(name) || [];
123
+ for (const alias of aliases) if (booleans.has(alias)) return "boolean";
124
+ return "string";
125
+ }
126
+ function isStringType(name) {
127
+ if (strings.has(name)) return true;
128
+ const aliases = mainToAliases.get(name) || [];
129
+ for (const alias of aliases) if (strings.has(alias)) return true;
130
+ return false;
131
+ }
132
+ const allOptions = /* @__PURE__ */ new Set([
133
+ ...booleans,
134
+ ...strings,
135
+ ...Object.keys(aliasMap),
136
+ ...Object.values(aliasMap).flat(),
137
+ ...Object.keys(defaults)
138
+ ]);
139
+ for (const name of allOptions) if (!options[name]) options[name] = {
140
+ type: getType(name),
141
+ default: defaults[name]
142
+ };
143
+ for (const [alias, main] of aliasToMain.entries()) if (alias.length === 1 && options[main] && !options[main].short) options[main].short = alias;
144
+ const processedArgs = [];
145
+ const negatedFlags = {};
146
+ for (let i = 0; i < args.length; i++) {
147
+ const arg = args[i];
148
+ if (arg === "--") {
149
+ processedArgs.push(...args.slice(i));
150
+ break;
151
+ }
152
+ if (arg.startsWith("--no-")) {
153
+ const flagName = arg.slice(5);
154
+ negatedFlags[flagName] = true;
155
+ continue;
156
+ }
157
+ processedArgs.push(arg);
158
+ }
159
+ let parsed;
160
+ try {
161
+ parsed = parseArgs$1({
162
+ args: processedArgs,
163
+ options: Object.keys(options).length > 0 ? options : void 0,
164
+ allowPositionals: true,
165
+ strict: false
166
+ });
167
+ } catch {
168
+ parsed = {
169
+ values: {},
170
+ positionals: processedArgs
171
+ };
172
+ }
173
+ const out = { _: [] };
174
+ out._ = parsed.positionals;
175
+ for (const [key, value] of Object.entries(parsed.values)) {
176
+ let coerced = value;
177
+ if (getType(key) === "boolean" && typeof value === "string") coerced = value !== "false";
178
+ else if (isStringType(key) && typeof value === "boolean") coerced = "";
179
+ out[key] = coerced;
180
+ }
181
+ for (const [name] of Object.entries(negatedFlags)) {
182
+ out[name] = false;
183
+ const mainName = aliasToMain.get(name);
184
+ if (mainName) out[mainName] = false;
185
+ const aliases = mainToAliases.get(name);
186
+ if (aliases) for (const alias of aliases) out[alias] = false;
187
+ }
188
+ for (const [alias, main] of aliasToMain.entries()) {
189
+ if (out[alias] !== void 0 && out[main] === void 0) out[main] = out[alias];
190
+ if (out[main] !== void 0 && out[alias] === void 0) out[alias] = out[main];
191
+ if (out[alias] !== out[main] && defaults[main] === out[main]) out[main] = out[alias];
192
+ }
193
+ return out;
194
+ }
195
+ const noColor = /* @__PURE__ */ (() => {
196
+ const env = globalThis.process?.env ?? {};
197
+ return env.NO_COLOR === "1" || env.TERM === "dumb" || env.TEST || env.CI;
198
+ })();
199
+ const _c = (c, r = 39) => (t) => noColor ? t : `\u001B[${c}m${t}\u001B[${r}m`;
200
+ const bold = /* @__PURE__ */ _c(1, 22);
201
+ const cyan = /* @__PURE__ */ _c(36);
202
+ const gray = /* @__PURE__ */ _c(90);
203
+ const underline = /* @__PURE__ */ _c(4, 24);
204
+ function parseArgs(rawArgs, argsDef) {
205
+ const parseOptions = {
206
+ boolean: [],
207
+ string: [],
208
+ alias: {},
209
+ default: {}
210
+ };
211
+ const args = resolveArgs(argsDef);
212
+ for (const arg of args) {
213
+ if (arg.type === "positional") continue;
214
+ if (arg.type === "string" || arg.type === "enum") parseOptions.string.push(arg.name);
215
+ else if (arg.type === "boolean") parseOptions.boolean.push(arg.name);
216
+ if (arg.default !== void 0) parseOptions.default[arg.name] = arg.default;
217
+ if (arg.alias) parseOptions.alias[arg.name] = arg.alias;
218
+ const camelName = camelCase(arg.name);
219
+ const kebabName = kebabCase(arg.name);
220
+ if (camelName !== arg.name || kebabName !== arg.name) {
221
+ const existingAliases = toArray(parseOptions.alias[arg.name] || []);
222
+ if (camelName !== arg.name && !existingAliases.includes(camelName)) existingAliases.push(camelName);
223
+ if (kebabName !== arg.name && !existingAliases.includes(kebabName)) existingAliases.push(kebabName);
224
+ if (existingAliases.length > 0) parseOptions.alias[arg.name] = existingAliases;
225
+ }
226
+ }
227
+ const parsed = parseRawArgs(rawArgs, parseOptions);
228
+ const [...positionalArguments] = parsed._;
229
+ const parsedArgsProxy = new Proxy(parsed, { get(target, prop) {
230
+ return target[prop] ?? target[camelCase(prop)] ?? target[kebabCase(prop)];
231
+ } });
232
+ for (const [, arg] of args.entries()) if (arg.type === "positional") {
233
+ const nextPositionalArgument = positionalArguments.shift();
234
+ if (nextPositionalArgument !== void 0) parsedArgsProxy[arg.name] = nextPositionalArgument;
235
+ else if (arg.default === void 0 && arg.required !== false) throw new CLIError(`Missing required positional argument: ${arg.name.toUpperCase()}`, "EARG");
236
+ else parsedArgsProxy[arg.name] = arg.default;
237
+ } else if (arg.type === "enum") {
238
+ const argument = parsedArgsProxy[arg.name];
239
+ const options = arg.options || [];
240
+ if (argument !== void 0 && options.length > 0 && !options.includes(argument)) throw new CLIError(`Invalid value for argument: ${cyan(`--${arg.name}`)} (${cyan(argument)}). Expected one of: ${options.map((o) => cyan(o)).join(", ")}.`, "EARG");
241
+ } else if (arg.required && parsedArgsProxy[arg.name] === void 0) throw new CLIError(`Missing required argument: --${arg.name}`, "EARG");
242
+ return parsedArgsProxy;
243
+ }
244
+ function resolveArgs(argsDef) {
245
+ const args = [];
246
+ for (const [name, argDef] of Object.entries(argsDef || {})) args.push({
247
+ ...argDef,
248
+ name,
249
+ alias: toArray(argDef.alias)
250
+ });
251
+ return args;
252
+ }
253
+ async function resolvePlugins(plugins) {
254
+ return Promise.all(plugins.map((p) => resolveValue(p)));
255
+ }
256
+ function defineCommand(def) {
257
+ return def;
258
+ }
259
+ async function runCommand$1(cmd, opts) {
260
+ const cmdArgs = await resolveValue(cmd.args || {});
261
+ const parsedArgs = parseArgs(opts.rawArgs, cmdArgs);
262
+ const context = {
263
+ rawArgs: opts.rawArgs,
264
+ args: parsedArgs,
265
+ data: opts.data,
266
+ cmd
267
+ };
268
+ const plugins = await resolvePlugins(cmd.plugins ?? []);
269
+ let result;
270
+ let runError;
271
+ try {
272
+ for (const plugin of plugins) await plugin.setup?.(context);
273
+ if (typeof cmd.setup === "function") await cmd.setup(context);
274
+ const subCommands = await resolveValue(cmd.subCommands);
275
+ if (subCommands && Object.keys(subCommands).length > 0) {
276
+ const subCommandArgIndex = findSubCommandIndex(opts.rawArgs, cmdArgs);
277
+ const explicitName = opts.rawArgs[subCommandArgIndex];
278
+ if (explicitName) {
279
+ const subCommand = await _findSubCommand(subCommands, explicitName);
280
+ if (!subCommand) throw new CLIError(`Unknown command ${cyan(explicitName)}`, "E_UNKNOWN_COMMAND");
281
+ await runCommand$1(subCommand, { rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1) });
282
+ } else {
283
+ const defaultSubCommand = await resolveValue(cmd.default);
284
+ if (defaultSubCommand) {
285
+ if (cmd.run) throw new CLIError(`Cannot specify both 'run' and 'default' on the same command.`, "E_DEFAULT_CONFLICT");
286
+ const subCommand = await _findSubCommand(subCommands, defaultSubCommand);
287
+ if (!subCommand) throw new CLIError(`Default sub command ${cyan(defaultSubCommand)} not found in subCommands.`, "E_UNKNOWN_COMMAND");
288
+ await runCommand$1(subCommand, { rawArgs: opts.rawArgs });
289
+ } else if (!cmd.run) throw new CLIError(`No command specified.`, "E_NO_COMMAND");
290
+ }
291
+ }
292
+ if (typeof cmd.run === "function") result = await cmd.run(context);
293
+ } catch (error) {
294
+ runError = error;
295
+ }
296
+ const cleanupErrors = [];
297
+ if (typeof cmd.cleanup === "function") try {
298
+ await cmd.cleanup(context);
299
+ } catch (error) {
300
+ cleanupErrors.push(error);
301
+ }
302
+ for (const plugin of [...plugins].reverse()) try {
303
+ await plugin.cleanup?.(context);
304
+ } catch (error) {
305
+ cleanupErrors.push(error);
306
+ }
307
+ if (runError) throw runError;
308
+ if (cleanupErrors.length === 1) throw cleanupErrors[0];
309
+ if (cleanupErrors.length > 1) throw new Error("Multiple cleanup errors", { cause: cleanupErrors });
310
+ return { result };
311
+ }
312
+ async function _findSubCommand(subCommands, name) {
313
+ if (name in subCommands) return resolveValue(subCommands[name]);
314
+ for (const sub of Object.values(subCommands)) {
315
+ const resolved = await resolveValue(sub);
316
+ const meta = await resolveValue(resolved?.meta);
317
+ if (meta?.alias) {
318
+ if (toArray(meta.alias).includes(name)) return resolved;
319
+ }
320
+ }
321
+ }
322
+ function findSubCommandIndex(rawArgs, argsDef) {
323
+ for (let i = 0; i < rawArgs.length; i++) {
324
+ const arg = rawArgs[i];
325
+ if (arg === "--") return -1;
326
+ if (arg.startsWith("-")) {
327
+ if (!arg.includes("=") && _isValueFlag(arg, argsDef)) i++;
328
+ continue;
329
+ }
330
+ return i;
331
+ }
332
+ return -1;
333
+ }
334
+ function _isValueFlag(flag, argsDef) {
335
+ const name = flag.replace(/^-{1,2}/, "");
336
+ const normalized = camelCase(name);
337
+ for (const [key, def] of Object.entries(argsDef)) {
338
+ if (def.type !== "string" && def.type !== "enum") continue;
339
+ if (normalized === camelCase(key)) return true;
340
+ if ((Array.isArray(def.alias) ? def.alias : def.alias ? [def.alias] : []).includes(name)) return true;
341
+ }
342
+ return false;
343
+ }
344
+ async function showUsage(cmd, parent) {
345
+ try {
346
+ console.log(await renderUsage(cmd, parent) + "\n");
347
+ } catch (error) {
348
+ console.error(error);
349
+ }
350
+ }
351
+ const negativePrefixRe = /^no[-A-Z]/;
352
+ async function renderUsage(cmd, parent) {
353
+ const cmdMeta = await resolveValue(cmd.meta || {});
354
+ const cmdArgs = resolveArgs(await resolveValue(cmd.args || {}));
355
+ const parentMeta = await resolveValue(parent?.meta || {});
356
+ const commandName = `${parentMeta.name ? `${parentMeta.name} ` : ""}` + (cmdMeta.name || process.argv[1]);
357
+ const argLines = [];
358
+ const posLines = [];
359
+ const commandsLines = [];
360
+ const usageLine = [];
361
+ for (const arg of cmdArgs) if (arg.type === "positional") {
362
+ const name = arg.name.toUpperCase();
363
+ const isRequired = arg.required !== false && arg.default === void 0;
364
+ posLines.push([cyan(name + renderValueHint(arg)), renderDescription(arg, isRequired)]);
365
+ usageLine.push(isRequired ? `<${name}>` : `[${name}]`);
366
+ } else {
367
+ const isRequired = arg.required === true && arg.default === void 0;
368
+ const argStr = [...(arg.alias || []).map((a) => `-${a}`), `--${arg.name}`].join(", ") + renderValueHint(arg);
369
+ argLines.push([cyan(argStr), renderDescription(arg, isRequired)]);
370
+ /**
371
+ * print negative boolean arg variant usage when
372
+ * - enabled by default or has `negativeDescription`
373
+ * - not prefixed with `no-` or `no[A-Z]`
374
+ */
375
+ if (arg.type === "boolean" && (arg.default === true || arg.negativeDescription) && !negativePrefixRe.test(arg.name)) {
376
+ const negativeArgStr = [...(arg.alias || []).map((a) => `--no-${a}`), `--no-${arg.name}`].join(", ");
377
+ argLines.push([cyan(negativeArgStr), [arg.negativeDescription, isRequired ? gray("(Required)") : ""].filter(Boolean).join(" ")]);
378
+ }
379
+ if (isRequired) usageLine.push(`--${arg.name}` + renderValueHint(arg));
380
+ }
381
+ if (cmd.subCommands) {
382
+ const commandNames = [];
383
+ const subCommands = await resolveValue(cmd.subCommands);
384
+ for (const [name, sub] of Object.entries(subCommands)) {
385
+ const meta = await resolveValue((await resolveValue(sub))?.meta);
386
+ if (meta?.hidden) continue;
387
+ const aliases = toArray(meta?.alias);
388
+ const label = [name, ...aliases].join(", ");
389
+ commandsLines.push([cyan(label), meta?.description || ""]);
390
+ commandNames.push(name, ...aliases);
391
+ }
392
+ usageLine.push(commandNames.join("|"));
393
+ }
394
+ const usageLines = [];
395
+ const version = cmdMeta.version || parentMeta.version;
396
+ usageLines.push(gray(`${cmdMeta.description} (${commandName + (version ? ` v${version}` : "")})`), "");
397
+ const hasOptions = argLines.length > 0 || posLines.length > 0;
398
+ usageLines.push(`${underline(bold("USAGE"))} ${cyan(`${commandName}${hasOptions ? " [OPTIONS]" : ""} ${usageLine.join(" ")}`)}`, "");
399
+ if (posLines.length > 0) {
400
+ usageLines.push(underline(bold("ARGUMENTS")), "");
401
+ usageLines.push(formatLineColumns(posLines, " "));
402
+ usageLines.push("");
403
+ }
404
+ if (argLines.length > 0) {
405
+ usageLines.push(underline(bold("OPTIONS")), "");
406
+ usageLines.push(formatLineColumns(argLines, " "));
407
+ usageLines.push("");
408
+ }
409
+ if (commandsLines.length > 0) {
410
+ usageLines.push(underline(bold("COMMANDS")), "");
411
+ usageLines.push(formatLineColumns(commandsLines, " "));
412
+ usageLines.push("", `Use ${cyan(`${commandName} <command> --help`)} for more information about a command.`);
413
+ }
414
+ return usageLines.filter((l) => typeof l === "string").join("\n");
415
+ }
416
+ function renderValueHint(arg) {
417
+ const valueHint = arg.valueHint ? `=<${arg.valueHint}>` : "";
418
+ const fallbackValueHint = valueHint || `=<${snakeCase(arg.name)}>`;
419
+ if (!arg.type || arg.type === "positional" || arg.type === "boolean") return valueHint;
420
+ if (arg.type === "enum" && arg.options?.length) return `=<${arg.options.join("|")}>`;
421
+ return fallbackValueHint;
422
+ }
423
+ function renderDescription(arg, required) {
424
+ const requiredHint = required ? gray("(Required)") : "";
425
+ const defaultHint = arg.default === void 0 ? "" : gray(`(Default: ${arg.default})`);
426
+ return [
427
+ arg.description,
428
+ requiredHint,
429
+ defaultHint
430
+ ].filter(Boolean).join(" ");
431
+ }
432
+ // ../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/utils.js
433
+ const getCodePointsLength = (() => {
434
+ const SURROGATE_PAIR_RE = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
435
+ return (input) => {
436
+ let surrogatePairsNr = 0;
437
+ SURROGATE_PAIR_RE.lastIndex = 0;
438
+ while (SURROGATE_PAIR_RE.test(input)) surrogatePairsNr += 1;
439
+ return input.length - surrogatePairsNr;
440
+ };
441
+ })();
442
+ const isFullWidth = (x) => {
443
+ return x === 12288 || x >= 65281 && x <= 65376 || x >= 65504 && x <= 65510;
444
+ };
445
+ const isWideNotCJKTNotEmoji = (x) => {
446
+ return x === 8987 || x === 9001 || x >= 12272 && x <= 12287 || x >= 12289 && x <= 12350 || x >= 12441 && x <= 12543 || x >= 12549 && x <= 12591 || x >= 12593 && x <= 12686 || x >= 12688 && x <= 12771 || x >= 12783 && x <= 12830 || x >= 12832 && x <= 12871 || x >= 12880 && x <= 19903 || x >= 65040 && x <= 65049 || x >= 65072 && x <= 65106 || x >= 65108 && x <= 65126 || x >= 65128 && x <= 65131 || x >= 127488 && x <= 127490 || x >= 127504 && x <= 127547 || x >= 127552 && x <= 127560 || x >= 131072 && x <= 196605 || x >= 196608 && x <= 262141;
447
+ };
448
+ // ../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/index.js
449
+ const ANSI_RE = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y;
450
+ const CONTROL_RE = /[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y;
451
+ const CJKT_WIDE_RE = /(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy;
452
+ const TAB_RE = /\t{1,1000}/y;
453
+ const EMOJI_RE = /[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy;
454
+ const LATIN_RE = /(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y;
455
+ const MODIFIER_RE = /\p{M}+/gu;
456
+ const NO_TRUNCATION$1 = {
457
+ limit: 1e400,
458
+ ellipsis: ""
459
+ };
460
+ const getStringTruncatedWidth = (input, truncationOptions = {}, widthOptions = {}) => {
461
+ const LIMIT = truncationOptions.limit ?? 1e400;
462
+ const ELLIPSIS = truncationOptions.ellipsis ?? "";
463
+ const ELLIPSIS_WIDTH = truncationOptions?.ellipsisWidth ?? (ELLIPSIS ? getStringTruncatedWidth(ELLIPSIS, NO_TRUNCATION$1, widthOptions).width : 0);
464
+ const ANSI_WIDTH = 0;
465
+ const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;
466
+ const TAB_WIDTH = widthOptions.tabWidth ?? 8;
467
+ const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;
468
+ const FULL_WIDTH_WIDTH = 2;
469
+ const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;
470
+ const WIDE_WIDTH = widthOptions.wideWidth ?? FULL_WIDTH_WIDTH;
471
+ const PARSE_BLOCKS = [
472
+ [LATIN_RE, REGULAR_WIDTH],
473
+ [ANSI_RE, ANSI_WIDTH],
474
+ [CONTROL_RE, CONTROL_WIDTH],
475
+ [TAB_RE, TAB_WIDTH],
476
+ [EMOJI_RE, EMOJI_WIDTH],
477
+ [CJKT_WIDE_RE, WIDE_WIDTH]
478
+ ];
479
+ let indexPrev = 0;
480
+ let index = 0;
481
+ let length = input.length;
482
+ let lengthExtra = 0;
483
+ let truncationEnabled = false;
484
+ let truncationIndex = length;
485
+ let truncationLimit = Math.max(0, LIMIT - ELLIPSIS_WIDTH);
486
+ let unmatchedStart = 0;
487
+ let unmatchedEnd = 0;
488
+ let width = 0;
489
+ let widthExtra = 0;
490
+ outer: while (true) {
491
+ if (unmatchedEnd > unmatchedStart || index >= length && index > indexPrev) {
492
+ const unmatched = input.slice(unmatchedStart, unmatchedEnd) || input.slice(indexPrev, index);
493
+ lengthExtra = 0;
494
+ for (const char of unmatched.replaceAll(MODIFIER_RE, "")) {
495
+ const codePoint = char.codePointAt(0) || 0;
496
+ if (isFullWidth(codePoint)) widthExtra = FULL_WIDTH_WIDTH;
497
+ else if (isWideNotCJKTNotEmoji(codePoint)) widthExtra = WIDE_WIDTH;
498
+ else widthExtra = REGULAR_WIDTH;
499
+ if (width + widthExtra > truncationLimit) truncationIndex = Math.min(truncationIndex, Math.max(unmatchedStart, indexPrev) + lengthExtra);
500
+ if (width + widthExtra > LIMIT) {
501
+ truncationEnabled = true;
502
+ break outer;
503
+ }
504
+ lengthExtra += char.length;
505
+ width += widthExtra;
506
+ }
507
+ unmatchedStart = unmatchedEnd = 0;
508
+ }
509
+ if (index >= length) break outer;
510
+ for (let i = 0, l = PARSE_BLOCKS.length; i < l; i++) {
511
+ const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i];
512
+ BLOCK_RE.lastIndex = index;
513
+ if (BLOCK_RE.test(input)) {
514
+ lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;
515
+ widthExtra = lengthExtra * BLOCK_WIDTH;
516
+ if (width + widthExtra > truncationLimit) truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));
517
+ if (width + widthExtra > LIMIT) {
518
+ truncationEnabled = true;
519
+ break outer;
520
+ }
521
+ width += widthExtra;
522
+ unmatchedStart = indexPrev;
523
+ unmatchedEnd = index;
524
+ index = indexPrev = BLOCK_RE.lastIndex;
525
+ continue outer;
526
+ }
527
+ }
528
+ index += 1;
529
+ }
530
+ return {
531
+ width: truncationEnabled ? truncationLimit : width,
532
+ index: truncationEnabled ? truncationIndex : length,
533
+ truncated: truncationEnabled,
534
+ ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH
535
+ };
536
+ };
537
+ // ../../node_modules/.pnpm/fast-string-width@3.0.2/node_modules/fast-string-width/dist/index.js
538
+ const NO_TRUNCATION = {
539
+ limit: 1e400,
540
+ ellipsis: "",
541
+ ellipsisWidth: 0
542
+ };
543
+ const fastStringWidth = (input, options = {}) => {
544
+ return getStringTruncatedWidth(input, NO_TRUNCATION, options).width;
545
+ };
546
+ // ../../node_modules/.pnpm/fast-wrap-ansi@0.2.2/node_modules/fast-wrap-ansi/lib/main.js
547
+ const ESC$1 = "\x1B";
548
+ const CSI$1 = "›";
549
+ const END_CODE = 39;
550
+ const ANSI_ESCAPE_BELL = "\x07";
551
+ const ANSI_CSI = "[";
552
+ const ANSI_OSC = "]";
553
+ const ANSI_SGR_TERMINATOR = "m";
554
+ const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
555
+ const GROUP_REGEX = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, "y");
556
+ const getClosingCode = (openingCode) => {
557
+ if (openingCode >= 30 && openingCode <= 37) return 39;
558
+ if (openingCode >= 90 && openingCode <= 97) return 39;
559
+ if (openingCode >= 40 && openingCode <= 47) return 49;
560
+ if (openingCode >= 100 && openingCode <= 107) return 49;
561
+ if (openingCode === 1 || openingCode === 2) return 22;
562
+ if (openingCode === 3) return 23;
563
+ if (openingCode === 4) return 24;
564
+ if (openingCode === 7) return 27;
565
+ if (openingCode === 8) return 28;
566
+ if (openingCode === 9) return 29;
567
+ if (openingCode === 0) return 0;
568
+ };
569
+ const wrapAnsiCode = (code) => `${ESC$1}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
570
+ const wrapAnsiHyperlink = (url) => `${ESC$1}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;
571
+ const wrapWord = (rows, word, columns) => {
572
+ const characters = word[Symbol.iterator]();
573
+ let isInsideEscape = false;
574
+ let isInsideLinkEscape = false;
575
+ let lastRow = rows.at(-1);
576
+ let visible = lastRow === void 0 ? 0 : fastStringWidth(lastRow);
577
+ let currentCharacter = characters.next();
578
+ let nextCharacter = characters.next();
579
+ let rawCharacterIndex = 0;
580
+ while (!currentCharacter.done) {
581
+ const character = currentCharacter.value;
582
+ const characterLength = fastStringWidth(character);
583
+ if (visible + characterLength <= columns) rows[rows.length - 1] += character;
584
+ else {
585
+ rows.push(character);
586
+ visible = 0;
587
+ }
588
+ if (character === ESC$1 || character === CSI$1) {
589
+ isInsideEscape = true;
590
+ isInsideLinkEscape = word.startsWith(ANSI_ESCAPE_LINK, rawCharacterIndex + 1);
591
+ }
592
+ if (isInsideEscape) {
593
+ if (isInsideLinkEscape) {
594
+ if (character === ANSI_ESCAPE_BELL) {
595
+ isInsideEscape = false;
596
+ isInsideLinkEscape = false;
597
+ }
598
+ } else if (character === ANSI_SGR_TERMINATOR) isInsideEscape = false;
599
+ } else {
600
+ visible += characterLength;
601
+ if (visible === columns && !nextCharacter.done) {
602
+ rows.push("");
603
+ visible = 0;
604
+ }
605
+ }
606
+ currentCharacter = nextCharacter;
607
+ nextCharacter = characters.next();
608
+ rawCharacterIndex += character.length;
609
+ }
610
+ lastRow = rows.at(-1);
611
+ if (!visible && lastRow !== void 0 && lastRow.length && rows.length > 1) rows[rows.length - 2] += rows.pop();
612
+ };
613
+ const stringVisibleTrimSpacesRight = (string) => {
614
+ const words = string.split(" ");
615
+ let last = words.length;
616
+ while (last) {
617
+ if (fastStringWidth(words[last - 1])) break;
618
+ last--;
619
+ }
620
+ if (last === words.length) return string;
621
+ return words.slice(0, last).join(" ") + words.slice(last).join("");
622
+ };
623
+ const exec = (string, columns, options = {}) => {
624
+ if (options.trim !== false && string.trim() === "") return "";
625
+ let returnValue = "";
626
+ let escapeCode;
627
+ let escapeUrl;
628
+ const words = string.split(" ");
629
+ let rows = [""];
630
+ let rowLength = 0;
631
+ for (let index = 0; index < words.length; index++) {
632
+ const word = words[index];
633
+ if (options.trim !== false) {
634
+ const row = rows.at(-1) ?? "";
635
+ const trimmed = row.trimStart();
636
+ if (row.length !== trimmed.length) {
637
+ rows[rows.length - 1] = trimmed;
638
+ rowLength = fastStringWidth(trimmed);
639
+ }
640
+ }
641
+ if (index !== 0) {
642
+ if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
643
+ rows.push("");
644
+ rowLength = 0;
645
+ }
646
+ if (rowLength || options.trim === false) {
647
+ rows[rows.length - 1] += " ";
648
+ rowLength++;
649
+ }
650
+ }
651
+ const wordLength = fastStringWidth(word);
652
+ if (options.hard && wordLength > columns) {
653
+ const remainingColumns = columns - rowLength;
654
+ const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns);
655
+ if (Math.floor((wordLength - 1) / columns) < breaksStartingThisLine) rows.push("");
656
+ wrapWord(rows, word, columns);
657
+ rowLength = fastStringWidth(rows.at(-1) ?? "");
658
+ continue;
659
+ }
660
+ if (rowLength + wordLength > columns && rowLength && wordLength) {
661
+ if (options.wordWrap === false && rowLength < columns) {
662
+ wrapWord(rows, word, columns);
663
+ rowLength = fastStringWidth(rows.at(-1) ?? "");
664
+ continue;
665
+ }
666
+ rows.push("");
667
+ rowLength = 0;
668
+ }
669
+ if (rowLength + wordLength > columns && options.wordWrap === false) {
670
+ wrapWord(rows, word, columns);
671
+ rowLength = fastStringWidth(rows.at(-1) ?? "");
672
+ continue;
673
+ }
674
+ rows[rows.length - 1] += word;
675
+ rowLength += wordLength;
676
+ }
677
+ if (options.trim !== false) rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
678
+ const preString = rows.join("\n");
679
+ let inSurrogate = false;
680
+ for (let i = 0; i < preString.length; i++) {
681
+ const character = preString[i];
682
+ returnValue += character;
683
+ if (!inSurrogate) {
684
+ inSurrogate = character >= "\ud800" && character <= "\udbff";
685
+ if (inSurrogate) continue;
686
+ } else inSurrogate = false;
687
+ if (character === ESC$1 || character === CSI$1) {
688
+ GROUP_REGEX.lastIndex = i + 1;
689
+ const groups = GROUP_REGEX.exec(preString)?.groups;
690
+ if (groups?.code !== void 0) {
691
+ const code = Number.parseFloat(groups.code);
692
+ escapeCode = code === END_CODE ? void 0 : code;
693
+ } else if (groups?.uri !== void 0) escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
694
+ }
695
+ if (preString[i + 1] === "\n") {
696
+ if (escapeUrl) returnValue += wrapAnsiHyperlink("");
697
+ const closingCode = escapeCode ? getClosingCode(escapeCode) : void 0;
698
+ if (escapeCode && closingCode) returnValue += wrapAnsiCode(closingCode);
699
+ } else if (character === "\n") {
700
+ if (escapeCode && getClosingCode(escapeCode)) returnValue += wrapAnsiCode(escapeCode);
701
+ if (escapeUrl) returnValue += wrapAnsiHyperlink(escapeUrl);
702
+ }
703
+ }
704
+ return returnValue;
705
+ };
706
+ const CRLF_OR_LF = /\r?\n/;
707
+ function wrapAnsi(string, columns, options) {
708
+ return String(string).normalize().split(CRLF_OR_LF).map((line) => exec(line, columns, options)).join("\n");
709
+ }
710
+ // ../../node_modules/.pnpm/sisteransi@2.0.0/node_modules/sisteransi/dist/index.js
711
+ const ESC = "\x1B";
712
+ const CSI = `${ESC}[`;
713
+ const cursor = {
714
+ to(x, y) {
715
+ if (!y) return `${CSI}${x + 1}G`;
716
+ return `${CSI}${y + 1};${x + 1}H`;
717
+ },
718
+ move(x, y) {
719
+ let ret = "";
720
+ if (x < 0) ret += `${CSI}${-x}D`;
721
+ else if (x > 0) ret += `${CSI}${x}C`;
722
+ if (y < 0) ret += `${CSI}${-y}A`;
723
+ else if (y > 0) ret += `${CSI}${y}B`;
724
+ return ret;
725
+ },
726
+ up: (count = 1) => `${CSI}${count}A`,
727
+ down: (count = 1) => `${CSI}${count}B`,
728
+ forward: (count = 1) => `${CSI}${count}C`,
729
+ backward: (count = 1) => `${CSI}${count}D`,
730
+ nextLine: (count = 1) => `${CSI}E`.repeat(count),
731
+ prevLine: (count = 1) => `${CSI}F`.repeat(count),
732
+ left: `${CSI}G`,
733
+ hide: `${CSI}?25l`,
734
+ show: `${CSI}?25h`,
735
+ save: `${ESC}7`,
736
+ restore: `${ESC}8`
737
+ };
738
+ const erase = {
739
+ screen: `${CSI}2J`,
740
+ up: (count = 1) => `${CSI}1J`.repeat(count),
741
+ down: (count = 1) => `${CSI}J`.repeat(count),
742
+ line: `${CSI}2K`,
743
+ lineEnd: `${CSI}K`,
744
+ lineStart: `${CSI}1K`,
745
+ lines(count) {
746
+ let clear = "";
747
+ for (let i = 0; i < count; i++) clear += this.line + (i < count - 1 ? cursor.up() : "");
748
+ if (count) clear += cursor.left;
749
+ return clear;
750
+ }
751
+ };
752
+ // ../../node_modules/.pnpm/@clack+core@1.6.0/node_modules/@clack/core/dist/index.mjs
753
+ function findCursor(o, s, l) {
754
+ if (!l.some((r) => !r.disabled)) return o;
755
+ const t = o + s, n = Math.max(l.length - 1, 0), e = t < 0 ? n : t > n ? 0 : t;
756
+ return l[e]?.disabled ? findCursor(e, s < 0 ? -1 : 1, l) : e;
757
+ }
758
+ const settings = {
759
+ actions: /* @__PURE__ */ new Set([
760
+ "up",
761
+ "down",
762
+ "left",
763
+ "right",
764
+ "space",
765
+ "enter",
766
+ "cancel"
767
+ ]),
768
+ aliases: /* @__PURE__ */ new Map([
769
+ ["k", "up"],
770
+ ["j", "down"],
771
+ ["h", "left"],
772
+ ["l", "right"],
773
+ ["", "cancel"],
774
+ ["escape", "cancel"]
775
+ ]),
776
+ messages: {
777
+ cancel: "Canceled",
778
+ error: "Something went wrong"
779
+ },
780
+ withGuide: true,
781
+ accessible: void 0,
782
+ date: {
783
+ monthNames: [...[
784
+ "January",
785
+ "February",
786
+ "March",
787
+ "April",
788
+ "May",
789
+ "June",
790
+ "July",
791
+ "August",
792
+ "September",
793
+ "October",
794
+ "November",
795
+ "December"
796
+ ]],
797
+ messages: {
798
+ required: "Please enter a valid date",
799
+ invalidMonth: "There are only 12 months in a year",
800
+ invalidDay: (n, e) => `There are only ${n} days in ${e}`,
801
+ afterMin: (n) => `Date must be on or after ${n.toISOString().slice(0, 10)}`,
802
+ beforeMax: (n) => `Date must be on or before ${n.toISOString().slice(0, 10)}`
803
+ }
804
+ }
805
+ };
806
+ function isAccessible(n) {
807
+ if (n !== void 0) return n;
808
+ if (settings.accessible !== void 0) return settings.accessible;
809
+ const e = process.env.ACCESSIBLE;
810
+ return e !== void 0 && e !== "" && e !== "0" && e !== "false";
811
+ }
812
+ function isActionKey(n, e) {
813
+ if (typeof n == "string") return settings.aliases.get(n) === e;
814
+ for (const s of n) if (s !== void 0 && isActionKey(s, e)) return true;
815
+ return false;
816
+ }
817
+ function diffLines(i, s) {
818
+ if (i === s) return;
819
+ const e = i.split(`
820
+ `), t = s.split(`
821
+ `), r = Math.max(e.length, t.length), f = [];
822
+ for (let n = 0; n < r; n++) e[n] !== t[n] && f.push(n);
823
+ return {
824
+ lines: f,
825
+ numLinesBefore: e.length,
826
+ numLinesAfter: t.length,
827
+ numLines: r
828
+ };
829
+ }
830
+ globalThis.process.platform.startsWith("win");
831
+ const CANCEL_SYMBOL = Symbol("clack:cancel");
832
+ function isCancel(e) {
833
+ return e === CANCEL_SYMBOL;
834
+ }
835
+ function setRawMode(e, r) {
836
+ const o = e;
837
+ o.isTTY && o.setRawMode(r);
838
+ }
839
+ const getColumns = (e) => "columns" in e && typeof e.columns == "number" ? e.columns : 80;
840
+ const getRows = (e) => "rows" in e && typeof e.rows == "number" ? e.rows : 20;
841
+ function wrapTextWithPrefix(e, r, o, n = o, s = o, t) {
842
+ return wrapAnsi(r, getColumns(e ?? stdout) - fastStringWidth(o), {
843
+ hard: true,
844
+ trim: false
845
+ }).split(`
846
+ `).map((c, a, g) => {
847
+ const m = t ? t(c, a) : c;
848
+ return a === 0 ? `${n}${m}` : a === g.length - 1 ? `${s}${m}` : `${o}${m}`;
849
+ }).join(`
850
+ `);
851
+ }
852
+ function runValidation(e, a) {
853
+ if ("~standard" in e) {
854
+ const n = e["~standard"].validate(a);
855
+ return n instanceof Promise ? n.then((r) => r.issues?.at(0)?.message) : n.issues?.at(0)?.message;
856
+ }
857
+ return e(a);
858
+ }
859
+ let C$1 = class C {
860
+ input;
861
+ output;
862
+ _abortSignal;
863
+ rl;
864
+ opts;
865
+ _render;
866
+ _track = false;
867
+ _prevFrame = "";
868
+ _subscribers = /* @__PURE__ */ new Map();
869
+ _cursor = 0;
870
+ state = "initial";
871
+ error = "";
872
+ value;
873
+ userInput = "";
874
+ /**
875
+ * Whether accessible (static, screen-reader friendly) output is enabled for
876
+ * this prompt, resolved from the `accessible` option, the global setting,
877
+ * and the `ACCESSIBLE` env var.
878
+ */
879
+ get accessible() {
880
+ return isAccessible(this.opts.accessible);
881
+ }
882
+ constructor(t, e = true) {
883
+ const { input: i = stdin, output: s = stdout, render: r, signal: n, ...o } = t;
884
+ this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = r.bind(this), this._track = e, this._abortSignal = n, this.input = i, this.output = s;
885
+ }
886
+ /**
887
+ * Unsubscribe all listeners
888
+ */
889
+ unsubscribe() {
890
+ this._subscribers.clear();
891
+ }
892
+ /**
893
+ * Set a subscriber with opts
894
+ * @param event - The event name
895
+ */
896
+ setSubscriber(t, e) {
897
+ const i = this._subscribers.get(t) ?? [];
898
+ i.push(e), this._subscribers.set(t, i);
899
+ }
900
+ /**
901
+ * Subscribe to an event
902
+ * @param event - The event name
903
+ * @param cb - The callback
904
+ */
905
+ on(t, e) {
906
+ this.setSubscriber(t, { cb: e });
907
+ }
908
+ /**
909
+ * Subscribe to an event once
910
+ * @param event - The event name
911
+ * @param cb - The callback
912
+ */
913
+ once(t, e) {
914
+ this.setSubscriber(t, {
915
+ cb: e,
916
+ once: true
917
+ });
918
+ }
919
+ /**
920
+ * Emit an event with data
921
+ * @param event - The event name
922
+ * @param data - The data to pass to the callback
923
+ */
924
+ emit(t, ...e) {
925
+ const i = this._subscribers.get(t) ?? [], s = [];
926
+ for (const r of i) r.cb(...e), r.once && s.push(() => i.splice(i.indexOf(r), 1));
927
+ for (const r of s) r();
928
+ }
929
+ prompt() {
930
+ return new Promise((t) => {
931
+ if (this._abortSignal) {
932
+ if (this._abortSignal.aborted) return this.state = "cancel", this.close(), t(CANCEL_SYMBOL);
933
+ this._abortSignal.addEventListener("abort", () => {
934
+ this.state = "cancel", this.close();
935
+ }, { once: true });
936
+ }
937
+ this.rl = f__default.createInterface({
938
+ input: this.input,
939
+ tabSize: 2,
940
+ prompt: "",
941
+ escapeCodeTimeout: 50,
942
+ terminal: true
943
+ }), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, true), this.input.on("keypress", this.onKeypress), setRawMode(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
944
+ this.output.write(cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t(this.value);
945
+ }), this.once("cancel", () => {
946
+ this.output.write(cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t(CANCEL_SYMBOL);
947
+ });
948
+ });
949
+ }
950
+ _isActionKey(t, e) {
951
+ return t === " ";
952
+ }
953
+ _shouldSubmit(t, e) {
954
+ return true;
955
+ }
956
+ _setValue(t) {
957
+ this.value = t, this.emit("value", this.value);
958
+ }
959
+ _setUserInput(t, e) {
960
+ this.userInput = t ?? "", this.emit("userInput", this.userInput), e && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);
961
+ }
962
+ _clearUserInput() {
963
+ this.rl?.write(null, {
964
+ ctrl: true,
965
+ name: "u"
966
+ }), this._setUserInput("");
967
+ }
968
+ async onKeypress(t, e) {
969
+ if (this.state !== "validating") {
970
+ if (this._track && e.name !== "return" && (e.name && this._isActionKey(t, e) && this.rl?.write(null, {
971
+ ctrl: true,
972
+ name: "h"
973
+ }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit("cursor", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit("cursor", e.name)), t && (t.toLowerCase() === "y" || t.toLowerCase() === "n") && this.emit("confirm", t.toLowerCase() === "y"), this.emit("key", t, e), e?.name === "return" && this._shouldSubmit(t, e)) {
974
+ if (this.opts.validate) {
975
+ const i = runValidation(this.opts.validate, this.value);
976
+ let s;
977
+ i instanceof Promise ? (this.state = "validating", this.render(), s = await i) : s = i, s && (this.error = s instanceof Error ? s.message : s, this.state = "error", this.rl?.write(this.userInput));
978
+ }
979
+ this.state !== "error" && (this.state = "submit");
980
+ }
981
+ isActionKey([
982
+ t,
983
+ e?.name,
984
+ e?.sequence
985
+ ], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
986
+ }
987
+ }
988
+ close() {
989
+ this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
990
+ `), setRawMode(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();
991
+ }
992
+ restoreCursor() {
993
+ const t = wrapAnsi(this._prevFrame, getColumns(this.output), {
994
+ hard: true,
995
+ trim: false
996
+ }).split(`
997
+ `).length - 1;
998
+ this.output.write(cursor.move(-999, t * -1));
999
+ }
1000
+ render() {
1001
+ const t = wrapAnsi(this._render(this) ?? "", getColumns(this.output), {
1002
+ hard: true,
1003
+ trim: false
1004
+ });
1005
+ if (t !== this._prevFrame) {
1006
+ if (this.state === "initial") this.output.write(cursor.hide);
1007
+ else {
1008
+ const e = diffLines(this._prevFrame, t), i = getRows(this.output);
1009
+ if (this.restoreCursor(), e) {
1010
+ const s = Math.max(0, e.numLinesAfter - i), r = Math.max(0, e.numLinesBefore - i);
1011
+ let n = e.lines.find((o) => o >= s);
1012
+ if (n === void 0) {
1013
+ this._prevFrame = t;
1014
+ return;
1015
+ }
1016
+ if (e.lines.length === 1) {
1017
+ this.output.write(cursor.move(0, n - r)), this.output.write(erase.lines(1));
1018
+ const o = t.split(`
1019
+ `);
1020
+ this.output.write(o[n]), this._prevFrame = t, this.output.write(cursor.move(0, o.length - n - 1));
1021
+ return;
1022
+ } else if (e.lines.length > 1) {
1023
+ if (s < r) n = s;
1024
+ else {
1025
+ const h = n - r;
1026
+ h > 0 && this.output.write(cursor.move(0, h));
1027
+ }
1028
+ this.output.write(erase.down());
1029
+ const m = t.split(`
1030
+ `).slice(n);
1031
+ this.output.write(m.join(`
1032
+ `)), this._prevFrame = t;
1033
+ return;
1034
+ }
1035
+ }
1036
+ this.output.write(erase.down());
1037
+ }
1038
+ this.output.write(t), this.state === "initial" && (this.state = "active"), this._prevFrame = t;
1039
+ }
1040
+ }
1041
+ };
1042
+ var r = class extends C$1 {
1043
+ get cursor() {
1044
+ return this.value ? 0 : 1;
1045
+ }
1046
+ get _value() {
1047
+ return this.cursor === 0;
1048
+ }
1049
+ constructor(t) {
1050
+ super(t, false), this.value = !!t.initialValue, this.on("userInput", () => {
1051
+ this.value = this._value;
1052
+ }), this.on("confirm", (i) => {
1053
+ this.output.write(cursor.move(0, -1)), this.value = i, this.state = "submit", this.close();
1054
+ }), this.on("cursor", () => {
1055
+ this.value = !this.value;
1056
+ });
1057
+ }
1058
+ };
1059
+ let n$1 = class n extends C$1 {
1060
+ options;
1061
+ cursor = 0;
1062
+ get _selectedValue() {
1063
+ return this.options[this.cursor];
1064
+ }
1065
+ changeValue() {
1066
+ const e = this._selectedValue;
1067
+ this.value = e === void 0 ? void 0 : e.value;
1068
+ }
1069
+ constructor(e) {
1070
+ super(e, false), this.options = e.options;
1071
+ const o = this.options.findIndex(({ value: s }) => s === e.initialValue), t = o === -1 ? 0 : o;
1072
+ this.cursor = this.options[t]?.disabled ? findCursor(t, 1, this.options) : t, this.changeValue(), this.on("cursor", (s) => {
1073
+ switch (s) {
1074
+ case "left":
1075
+ case "up":
1076
+ this.cursor = findCursor(this.cursor, -1, this.options);
1077
+ break;
1078
+ case "down":
1079
+ case "right": this.cursor = findCursor(this.cursor, 1, this.options);
1080
+ }
1081
+ this.changeValue();
1082
+ });
1083
+ }
1084
+ };
1085
+ var n = class extends C$1 {
1086
+ get userInputWithCursor() {
1087
+ if (this.state === "submit") return this.userInput;
1088
+ const t = this.userInput;
1089
+ if (this.cursor >= t.length) return `${this.userInput}\u2588`;
1090
+ const r = t.slice(0, this.cursor), s = t.slice(this.cursor, this.cursor + 1), e = t.slice(this.cursor + 1);
1091
+ return `${r}${styleText("inverse", s)}${e}`;
1092
+ }
1093
+ get cursor() {
1094
+ return this._cursor;
1095
+ }
1096
+ constructor(t) {
1097
+ super({
1098
+ ...t,
1099
+ initialUserInput: t.initialUserInput ?? t.initialValue
1100
+ }), this.on("userInput", (r) => {
1101
+ this._setValue(r);
1102
+ }), this.on("finalize", () => {
1103
+ this.value || (this.value = t.defaultValue), this.value === void 0 && (this.value = "");
1104
+ });
1105
+ }
1106
+ };
1107
+ // ../../node_modules/.pnpm/@clack+prompts@1.9.0/node_modules/@clack/prompts/dist/index.mjs
1108
+ function isUnicodeSupported() {
1109
+ if (process$1.platform !== "win32") return process$1.env.TERM !== "linux";
1110
+ return Boolean(process$1.env.CI) || Boolean(process$1.env.WT_SESSION) || Boolean(process$1.env.TERMINUS_SUBLIME) || process$1.env.ConEmuTask === "{cmd::Cmder}" || process$1.env.TERM_PROGRAM === "Terminus-Sublime" || process$1.env.TERM_PROGRAM === "vscode" || process$1.env.TERM === "xterm-256color" || process$1.env.TERM === "alacritty" || process$1.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
1111
+ }
1112
+ const unicode = isUnicodeSupported();
1113
+ const unicodeOr = (e, o) => unicode ? e : o;
1114
+ const S_STEP_ACTIVE = unicodeOr("◆", "*");
1115
+ const S_STEP_CANCEL = unicodeOr("■", "x");
1116
+ const S_STEP_ERROR = unicodeOr("▲", "x");
1117
+ const S_STEP_SUBMIT = unicodeOr("◇", "o");
1118
+ const S_BAR_START = unicodeOr("┌", "T");
1119
+ const S_BAR = unicodeOr("│", "|");
1120
+ const S_BAR_END = unicodeOr("└", "—");
1121
+ const S_RADIO_ACTIVE = unicodeOr("●", ">");
1122
+ const S_RADIO_INACTIVE = unicodeOr("○", " ");
1123
+ const S_BAR_H = unicodeOr("─", "-");
1124
+ const S_CORNER_TOP_RIGHT = unicodeOr("╮", "+");
1125
+ const S_CONNECT_LEFT = unicodeOr("├", "+");
1126
+ const S_CORNER_BOTTOM_RIGHT = unicodeOr("╯", "+");
1127
+ const S_CORNER_BOTTOM_LEFT = unicodeOr("╰", "+");
1128
+ const symbol = (e) => {
1129
+ switch (e) {
1130
+ case "initial":
1131
+ case "active": return styleText("cyan", S_STEP_ACTIVE);
1132
+ case "cancel": return styleText("red", S_STEP_CANCEL);
1133
+ case "error": return styleText("yellow", S_STEP_ERROR);
1134
+ case "submit": return styleText("green", S_STEP_SUBMIT);
1135
+ case "validating": return styleText("dim", S_STEP_ACTIVE);
1136
+ }
1137
+ };
1138
+ const symbolBar = (e) => {
1139
+ switch (e) {
1140
+ case "initial":
1141
+ case "active": return styleText("cyan", S_BAR);
1142
+ case "cancel": return styleText("red", S_BAR);
1143
+ case "error": return styleText("yellow", S_BAR);
1144
+ case "submit": return styleText("green", S_BAR);
1145
+ }
1146
+ };
1147
+ function formatInstructionFooter(e, o, r) {
1148
+ const s = r ? `${styleText("cyan", S_BAR)} ` : "", n = wrapTextWithPrefix(e, o.join(" • "), s).split(`
1149
+ `);
1150
+ return r && n.push(styleText("cyan", S_BAR_END)), n;
1151
+ }
1152
+ const E$1 = (l, e, w, p, b, C = false) => {
1153
+ let r = e, O = 0;
1154
+ if (C) for (let i = p - 1; i >= w; i--) {
1155
+ const m = l[i];
1156
+ if (m && (r -= m.length), O++, r <= b) break;
1157
+ }
1158
+ else for (let i = w; i < p; i++) {
1159
+ const m = l[i];
1160
+ if (m && (r -= m.length), O++, r <= b) break;
1161
+ }
1162
+ return {
1163
+ lineCount: r,
1164
+ removals: O
1165
+ };
1166
+ };
1167
+ const limitOptions = ({ cursor: l, options: e, style: w, output: p = process.stdout, maxItems: b = Number.POSITIVE_INFINITY, columnPadding: C = 0, rowPadding: r = 4 }) => {
1168
+ const i = getColumns(p) - C, m = getRows(p), M = styleText("dim", "..."), v = Math.max(m - r, 0), a = Math.max(Math.min(b, v), 5);
1169
+ let f = 0;
1170
+ l >= a - 3 && (f = Math.max(Math.min(l - a + 3, e.length - a), 0));
1171
+ let d = a < e.length && f > 0, c = a < e.length && f + a < e.length;
1172
+ const I = Math.min(f + a, e.length), s = [];
1173
+ let g = 0;
1174
+ d && g++, c && g++;
1175
+ const T = f + (d ? 1 : 0), W = I - (c ? 1 : 0);
1176
+ for (let t = T; t < W; t++) {
1177
+ const n = e[t], h = wrapAnsi(n !== void 0 ? w(n, t === l) : "", i, {
1178
+ hard: true,
1179
+ trim: false
1180
+ }).split(`
1181
+ `);
1182
+ s.push(h), g += h.length;
1183
+ }
1184
+ if (g > v) {
1185
+ let t = 0, n = 0, o = g;
1186
+ const h = l - T;
1187
+ let u = v;
1188
+ const L = () => E$1(s, o, 0, h, u), y = () => E$1(s, o, h + 1, s.length, u, true);
1189
+ d ? ({lineCount: o, removals: t} = L(), o > u && (c || (u -= 1), {lineCount: o, removals: n} = y())) : (c || (u -= 1), {lineCount: o, removals: n} = y(), o > u && (u -= 1, {lineCount: o, removals: t} = L())), t > 0 && (d = true, s.splice(0, t)), n > 0 && (c = true, s.splice(s.length - n, n));
1190
+ }
1191
+ const x = [];
1192
+ d && x.push(M);
1193
+ for (const t of s) for (const n of t) x.push(n);
1194
+ return c && x.push(M), x;
1195
+ };
1196
+ const confirm = (e) => {
1197
+ const a = e.active ?? "Yes", o = e.inactive ?? "No";
1198
+ return new r({
1199
+ active: a,
1200
+ inactive: o,
1201
+ signal: e.signal,
1202
+ input: e.input,
1203
+ output: e.output,
1204
+ initialValue: e.initialValue ?? true,
1205
+ render() {
1206
+ const i = e.withGuide ?? settings.withGuide, u = `${symbol(this.state)} `, l = i ? `${styleText("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(e.output, e.message, l, u), s = `${i ? `${styleText("gray", S_BAR)}
1207
+ ` : ""}${f}
1208
+ `, c = this.value ? a : o;
1209
+ switch (this.state) {
1210
+ case "submit": return `${s}${i ? `${styleText("gray", S_BAR)} ` : ""}${styleText("dim", c)}`;
1211
+ case "cancel": return `${s}${i ? `${styleText("gray", S_BAR)} ` : ""}${styleText(["strikethrough", "dim"], c)}${i ? `
1212
+ ${styleText("gray", S_BAR)}` : ""}`;
1213
+ default: {
1214
+ const r = i ? `${styleText("cyan", S_BAR)} ` : "", g = i ? styleText("cyan", S_BAR_END) : "";
1215
+ return `${s}${r}${this.value ? `${styleText("green", S_RADIO_ACTIVE)} ${a}` : `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", a)}`}${e.vertical ? i ? `
1216
+ ${styleText("cyan", S_BAR)} ` : `
1217
+ ` : ` ${styleText("dim", "/")} `}${this.value ? `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", o)}` : `${styleText("green", S_RADIO_ACTIVE)} ${o}`}
1218
+ ${g}
1219
+ `;
1220
+ }
1221
+ }
1222
+ }
1223
+ }).prompt();
1224
+ };
1225
+ `${styleText("dim", "↑/↓")}`, `${styleText("dim", "Space:")}`, `${styleText("dim", "Enter:")}`;
1226
+ const cancel = (o = "", t) => {
1227
+ const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText("gray", S_BAR_END)} ` : "";
1228
+ i.write(`${e}${styleText("red", o)}
1229
+
1230
+ `);
1231
+ };
1232
+ const intro = (o = "", t) => {
1233
+ const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText("gray", S_BAR_START)} ` : "";
1234
+ i.write(`${e}${o}
1235
+ `);
1236
+ };
1237
+ const outro = (o = "", t) => {
1238
+ const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText("gray", S_BAR)}
1239
+ ${styleText("gray", S_BAR_END)} ` : "";
1240
+ i.write(`${e}${o}
1241
+
1242
+ `);
1243
+ };
1244
+ const W = (o) => o;
1245
+ const C = (o, e, s) => {
1246
+ const a = {
1247
+ hard: true,
1248
+ trim: false
1249
+ }, i = wrapAnsi(o, e, a).split(`
1250
+ `), c = i.reduce((n, t) => Math.max(fastStringWidth(t), n), 0);
1251
+ return wrapAnsi(o, e - (i.map(s).reduce((n, t) => Math.max(fastStringWidth(t), n), 0) - c), a);
1252
+ };
1253
+ const note = (o = "", e = "", s) => {
1254
+ const a = s?.output ?? process$1.stdout, i = s?.withGuide ?? settings.withGuide, c = s?.format ?? W, g = [
1255
+ "",
1256
+ ...C(o, getColumns(a) - 6, c).split(`
1257
+ `).map(c),
1258
+ ""
1259
+ ], n = fastStringWidth(e), t = Math.max(g.reduce((m, F) => {
1260
+ const O = fastStringWidth(F);
1261
+ return O > m ? O : m;
1262
+ }, 0), n) + 2, h = g.map((m) => `${styleText("gray", S_BAR)} ${m}${" ".repeat(t - fastStringWidth(m))}${styleText("gray", S_BAR)}`).join(`
1263
+ `), T = i ? `${styleText("gray", S_BAR)}
1264
+ ` : "", l$1 = i ? S_CONNECT_LEFT : S_CORNER_BOTTOM_LEFT;
1265
+ a.write(`${T}${styleText("green", S_STEP_SUBMIT)} ${styleText("reset", e)} ${styleText("gray", S_BAR_H.repeat(Math.max(t - n - 1, 1)) + S_CORNER_TOP_RIGHT)}
1266
+ ${h}
1267
+ ${styleText("gray", l$1 + S_BAR_H.repeat(t + 2) + S_CORNER_BOTTOM_RIGHT)}
1268
+ `);
1269
+ };
1270
+ const SELECT_INSTRUCTIONS = [`${styleText("dim", "↑/↓")} to navigate`, `${styleText("dim", "Enter:")} confirm`];
1271
+ const c = (t, o) => t.includes(`
1272
+ `) ? t.split(`
1273
+ `).map((d) => o(d)).join(`
1274
+ `) : o(t);
1275
+ const select = (t) => {
1276
+ const o = (n, m) => {
1277
+ if (n === void 0) return "";
1278
+ const s = n.label ?? String(n.value);
1279
+ switch (m) {
1280
+ case "disabled": return `${styleText("gray", S_RADIO_INACTIVE)} ${c(s, (i) => styleText("gray", i))}${n.hint ? ` ${styleText("dim", `(${n.hint ?? "disabled"})`)}` : ""}`;
1281
+ case "selected": return `${c(s, (i) => styleText("dim", i))}`;
1282
+ case "active": return `${styleText("green", S_RADIO_ACTIVE)} ${s}${n.hint ? ` ${styleText("dim", `(${n.hint})`)}` : ""}`;
1283
+ case "cancelled": return `${c(s, (i) => styleText(["strikethrough", "dim"], i))}`;
1284
+ default: return `${styleText("dim", S_RADIO_INACTIVE)} ${c(s, (i) => styleText("dim", i))}`;
1285
+ }
1286
+ }, d = t.showInstructions ?? true;
1287
+ return new n$1({
1288
+ options: t.options,
1289
+ signal: t.signal,
1290
+ input: t.input,
1291
+ output: t.output,
1292
+ initialValue: t.initialValue,
1293
+ render() {
1294
+ const n = t.withGuide ?? settings.withGuide, m = `${symbol(this.state)} `, s = `${symbolBar(this.state)} `, i = wrapTextWithPrefix(t.output, t.message, s, m), u = `${n ? `${styleText("gray", S_BAR)}
1295
+ ` : ""}${i}
1296
+ `;
1297
+ switch (this.state) {
1298
+ case "submit": {
1299
+ const r = n ? `${styleText("gray", S_BAR)} ` : "";
1300
+ return `${u}${wrapTextWithPrefix(t.output, o(this.options[this.cursor], "selected"), r)}`;
1301
+ }
1302
+ case "cancel": {
1303
+ const r = n ? `${styleText("gray", S_BAR)} ` : "";
1304
+ return `${u}${wrapTextWithPrefix(t.output, o(this.options[this.cursor], "cancelled"), r)}${n ? `
1305
+ ${styleText("gray", S_BAR)}` : ""}`;
1306
+ }
1307
+ default: {
1308
+ const r = n ? `${styleText("cyan", S_BAR)} ` : "", a = u.split(`
1309
+ `).length, p = d ? formatInstructionFooter(t.output, SELECT_INSTRUCTIONS, n) : n ? [styleText("cyan", S_BAR_END)] : [], f = p.join(`
1310
+ `), b = p.length + 1;
1311
+ return `${u}${r}${limitOptions({
1312
+ output: t.output,
1313
+ cursor: this.cursor,
1314
+ options: this.options,
1315
+ maxItems: t.maxItems,
1316
+ columnPadding: r.length,
1317
+ rowPadding: a + b,
1318
+ style: (g, x) => o(g, g.disabled ? "disabled" : x ? "active" : "inactive")
1319
+ }).join(`
1320
+ ${r}`)}
1321
+ ${f}
1322
+ `;
1323
+ }
1324
+ }
1325
+ }
1326
+ }).prompt();
1327
+ };
1328
+ `${styleText("gray", S_BAR)}`;
1329
+ const text = (t) => new n({
1330
+ validate: t.validate,
1331
+ placeholder: t.placeholder,
1332
+ defaultValue: t.defaultValue,
1333
+ initialValue: t.initialValue,
1334
+ output: t.output,
1335
+ signal: t.signal,
1336
+ input: t.input,
1337
+ render() {
1338
+ const r = t?.withGuide ?? settings.withGuide, l = `${`${r ? `${styleText("gray", S_BAR)}
1339
+ ` : ""}${symbol(this.state)} `}${t.message}
1340
+ `, d = t.placeholder && t.placeholder.length > 0 ? styleText("inverse", t.placeholder[0]) + styleText("dim", t.placeholder.slice(1)) : styleText(["inverse", "hidden"], "_"), o = this.userInput ? this.userInputWithCursor : d, s = this.value ?? "";
1341
+ switch (this.state) {
1342
+ case "validating": {
1343
+ const n = r ? `${styleText("cyan", S_BAR)} ` : "", i = r ? styleText("cyan", S_BAR_END) : "";
1344
+ return `${l}${n}${styleText("dim", o)}
1345
+ ${i} ${styleText("dim", "Validating...")}
1346
+ `;
1347
+ }
1348
+ case "error": {
1349
+ const n = this.error ? ` ${styleText("yellow", this.error)}` : "", i = r ? `${styleText("yellow", S_BAR)} ` : "", c = r ? styleText("yellow", S_BAR_END) : "";
1350
+ return `${l.trim()}
1351
+ ${i}${o}
1352
+ ${c}${n}
1353
+ `;
1354
+ }
1355
+ case "submit": {
1356
+ const n = s ? `${r ? " " : ""}${styleText("dim", s)}` : "";
1357
+ return `${l}${r ? styleText("gray", S_BAR) : ""}${n}`;
1358
+ }
1359
+ case "cancel": {
1360
+ const n = s ? ` ${styleText(["strikethrough", "dim"], s)}` : "", i = r ? styleText("gray", S_BAR) : "";
1361
+ return `${l}${i}${n}${s.trim() ? `
1362
+ ${i}` : ""}`;
1363
+ }
1364
+ default: return `${l}${r ? `${styleText("cyan", S_BAR)} ` : ""}${o}
1365
+ ${r ? styleText("cyan", S_BAR_END) : ""}
1366
+ `;
1367
+ }
1368
+ }
1369
+ }).prompt();
1370
+ // package.json
1371
+ var version = "0.7.0";
1372
+ // src/git.ts
12
1373
  /**
13
1374
  * Optional post-scaffold `git init` + initial commit. Mirrors what
14
1375
  * `create-vite`, `create-next-app`, and Cloudflare's `c3` already do
@@ -149,8 +1510,7 @@ const initRepoAndCommit = (details, runner = defaultGitRunner) => {
149
1510
  branch: "main"
150
1511
  };
151
1512
  };
152
- //#endregion
153
- //#region src/prompts.ts
1513
+ // src/prompts.ts
154
1514
  /**
155
1515
  * Interactive wizard for `create-baerly-storage`. Invoked only when the
156
1516
  * process is attached to a real TTY and at least one required arg
@@ -182,9 +1542,11 @@ const STARTERS = [{
182
1542
  hint: "React + Vite SPA over a sample notes collection"
183
1543
  }];
184
1544
  const runWizard = async (input, opts = {}) => {
185
- intro(pc.bold(pc.cyan("create-baerly-storage")));
1545
+ intro(styleText(["bold", "cyan"], "create-baerly-storage"));
186
1546
  const projectName = input.projectName ?? await promptProjectName();
187
- if (existsSync(resolve(projectName === "." ? process.cwd() : resolve(process.cwd(), projectName), "wrangler.jsonc"))) {
1547
+ const outDir = projectName === "." ? process.cwd() : resolve$1(process.cwd(), projectName);
1548
+ const wranglerPath = resolve$1(outDir, "wrangler.jsonc");
1549
+ if (existsSync(wranglerPath)) {
188
1550
  note("Detected existing Cloudflare Worker — bolting baerly on instead of scaffolding.");
189
1551
  const install = input.install ?? await promptInstall();
190
1552
  return {
@@ -287,8 +1649,7 @@ const promptGit = async () => {
287
1649
  }
288
1650
  return v;
289
1651
  };
290
- //#endregion
291
- //#region src/pm-detect.ts
1652
+ // src/pm-detect.ts
292
1653
  /**
293
1654
  * Which package manager invoked us. Read from
294
1655
  * `npm_config_user_agent` — set by npm/pnpm/yarn when they run
@@ -315,7 +1676,7 @@ const installCommand = (pm) => {
315
1676
  * `yarn dev`. The scaffolded `package.json` scripts assume this
316
1677
  * shape.
317
1678
  */
318
- const runCommand$1 = (pm, script) => {
1679
+ const runCommand = (pm, script) => {
319
1680
  if (pm === "pnpm") return `pnpm ${script}`;
320
1681
  if (pm === "yarn") return `yarn ${script}`;
321
1682
  return `npm run ${script}`;
@@ -333,8 +1694,7 @@ const probePmVersion = (pm) => {
333
1694
  const out = (res.stdout ?? "").trim();
334
1695
  return out.length > 0 ? out : void 0;
335
1696
  };
336
- //#endregion
337
- //#region src/substitute.ts
1697
+ // src/substitute.ts
338
1698
  /**
339
1699
  * Rewrite text content (any non-JSON-aware file). Applies sentinel
340
1700
  * renames longest-first. Unknown `fromKey` values cause the rename to
@@ -378,8 +1738,7 @@ const substitutePackageJson = (text, ctx) => {
378
1738
  }
379
1739
  return `${JSON.stringify(pkg, null, 2)}\n`;
380
1740
  };
381
- //#endregion
382
- //#region src/scaffold.ts
1741
+ // src/scaffold.ts
383
1742
  /**
384
1743
  * Optional add-ons and compatibility tokens recognised by the CLI.
385
1744
  * `docker` is a scaffold template overlay; `agent-rules` is the legacy
@@ -488,9 +1847,9 @@ const STARTER_TO_EXAMPLE = {
488
1847
  */
489
1848
  const resolveTemplatesRoot = () => {
490
1849
  const here = dirname(fileURLToPath(import.meta.url));
491
- const distSidecar = resolve(here, "templates");
1850
+ const distSidecar = resolve$1(here, "templates");
492
1851
  if (existsSync(distSidecar)) return distSidecar;
493
- return resolve(here, "..", "..", "..", "examples");
1852
+ return resolve$1(here, "..", "..", "..", "examples");
494
1853
  };
495
1854
  /**
496
1855
  * Resolve the add-ons root. In a built CLI, add-on trees are copied
@@ -501,9 +1860,9 @@ const resolveTemplatesRoot = () => {
501
1860
  */
502
1861
  const resolveAddonsRoot = () => {
503
1862
  const here = dirname(fileURLToPath(import.meta.url));
504
- const distSidecar = resolve(here, "templates", "addons");
1863
+ const distSidecar = resolve$1(here, "templates", "addons");
505
1864
  if (existsSync(distSidecar)) return distSidecar;
506
- return resolve(here, "..", "templates", "addons");
1865
+ return resolve$1(here, "..", "templates", "addons");
507
1866
  };
508
1867
  /**
509
1868
  * Read the CLI's own package.json:version. Used to rewrite
@@ -511,7 +1870,8 @@ const resolveAddonsRoot = () => {
511
1870
  * `create-baerly-storage` ships in the same release train as `@baerly/*`.
512
1871
  */
513
1872
  const readCliVersion = () => {
514
- const pkgPath = resolve(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
1873
+ const here = dirname(fileURLToPath(import.meta.url));
1874
+ const pkgPath = resolve$1(here, "..", "package.json");
515
1875
  const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
516
1876
  if (typeof pkg.version !== "string" || pkg.version.length === 0) throw new Error(`create-baerly-storage: could not read version from ${pkgPath}`);
517
1877
  return pkg.version;
@@ -568,11 +1928,12 @@ const scaffold = async (opts) => {
568
1928
  const domain = opts.domain ?? "";
569
1929
  const templatesRoot = opts.templatesRoot ?? resolveTemplatesRoot();
570
1930
  const outRoot = opts.outRoot ?? process.cwd();
571
- const outDir = inPlace ? resolve(outRoot) : resolve(outRoot, opts.projectName);
1931
+ const outDir = inPlace ? resolve$1(outRoot) : resolve$1(outRoot, opts.projectName);
572
1932
  const appName = inPlace ? basename(outDir) : opts.projectName;
573
1933
  if (inPlace && !/^[a-z0-9][a-z0-9_-]*$/.test(appName)) throw new Error(`create-baerly-storage: appName must be lowercase, alphanumeric + "_"/"-", starting with [a-z0-9] (got ${JSON.stringify(appName)}) — derived from current directory ${JSON.stringify(outDir)}`);
574
1934
  const starter = opts.starter ?? "minimal";
575
- const exampleName = STARTER_TO_EXAMPLE[`${opts.target}:${starter}`];
1935
+ const lookupKey = `${opts.target}:${starter}`;
1936
+ const exampleName = STARTER_TO_EXAMPLE[lookupKey];
576
1937
  const templateDir = exampleName === void 0 ? "" : join(templatesRoot, exampleName);
577
1938
  if (exampleName === void 0 || !existsSync(templateDir)) throw new Error(`create-baerly-storage: template not found for target=${opts.target} starter=${starter}`);
578
1939
  const manifest = loadManifest(templateDir);
@@ -600,8 +1961,8 @@ const scaffold = async (opts) => {
600
1961
  domain,
601
1962
  pm,
602
1963
  installCmd: installCommand(pm),
603
- runDev: runCommand$1(pm, "dev"),
604
- runTypecheck: runCommand$1(pm, "typecheck")
1964
+ runDev: runCommand(pm, "dev"),
1965
+ runTypecheck: runCommand(pm, "typecheck")
605
1966
  },
606
1967
  cliVersion: readCliVersion()
607
1968
  };
@@ -650,24 +2011,26 @@ const scaffold = async (opts) => {
650
2011
  return {
651
2012
  outDir,
652
2013
  filesWritten,
653
- nextSteps: inPlace ? [installCommand(pm), runCommand$1(pm, "dev")] : [
2014
+ nextSteps: inPlace ? [installCommand(pm), runCommand(pm, "dev")] : [
654
2015
  `cd ${opts.projectName}`,
655
2016
  installCommand(pm),
656
- runCommand$1(pm, "dev")
2017
+ runCommand(pm, "dev")
657
2018
  ],
658
2019
  cliVersion: ctx.cliVersion,
659
2020
  appName
660
2021
  };
661
2022
  };
662
- //#endregion
663
- //#region ../protocol/src/errors.ts
2023
+ // ../protocol/src/errors.ts
664
2024
  /**
665
- * Codes whose default failure class is resolved by retrying with a fresh read.
666
- * Throw sites may override this when the same code is context-sensitive
667
- * (notably caller-supplied `_id` collisions, which also use `Conflict`).
2025
+ * Codes whose failure can clear on retry. `BaerlyError.retriable` is
2026
+ * exactly membership in this set; there are no per-instance overrides.
668
2027
  */
669
- const RETRIABLE_CODES = /* @__PURE__ */ new Set(["NetworkError", "Conflict"]);
670
- /** True iff this error code's default failure class is retriable. */
2028
+ const RETRIABLE_CODES = /* @__PURE__ */ new Set([
2029
+ "NetworkError",
2030
+ "WriteConflict",
2031
+ "MaintenancePending"
2032
+ ]);
2033
+ /** True iff this error code is retriable (membership in {@link RETRIABLE_CODES}). */
671
2034
  const isRetriableCode = (code) => RETRIABLE_CODES.has(code);
672
2035
  /**
673
2036
  * The single error class thrown by baerly-storage. Discriminate by `code`, not
@@ -680,12 +2043,18 @@ const isRetriableCode = (code) => RETRIABLE_CODES.has(code);
680
2043
  * @example
681
2044
  * ```ts
682
2045
  * try {
683
- * await db.collection("tickets").insert({ title: "hi" });
2046
+ * await db.collection("tickets").insert({ _id: "t-1", title: "hi" });
684
2047
  * } catch (err) {
685
- * if (err instanceof BaerlyError && err.code === "Conflict") {
686
- * // Check err.retriable; CAS can retry, duplicate _id cannot.
2048
+ * if (!(err instanceof BaerlyError)) throw err;
2049
+ * if (err.code === "AlreadyExists") {
2050
+ * // t-1 is taken; retrying cannot succeed.
2051
+ * } else if (err.code === "AmbiguousCommit") {
2052
+ * // May have landed: re-read err._id before deciding.
2053
+ * } else if (err.retriable) {
2054
+ * // WriteConflict or NetworkError: retry with bounded backoff.
2055
+ * } else {
2056
+ * throw err;
687
2057
  * }
688
- * throw err;
689
2058
  * }
690
2059
  * ```
691
2060
  */
@@ -704,6 +2073,14 @@ var BaerlyError = class extends Error {
704
2073
  */
705
2074
  issues;
706
2075
  /**
2076
+ * The `_id` of the row whose commit outcome is unknown, set only when
2077
+ * `code === "AmbiguousCommit"`. For an auto-ID insert it is the minted
2078
+ * id, so the caller can re-read the row and retry with the same `_id`
2079
+ * rather than mint a second document. A missing row does not prove the
2080
+ * write failed. The HTTP layer carries it in `HttpErrorEnvelope`.
2081
+ */
2082
+ _id;
2083
+ /**
707
2084
  * Raw HTTP status, set only by the client-side wire decoder when
708
2085
  * inflating an `HttpErrorEnvelope` into this class. Server-side
709
2086
  * throws never set it (the HTTP layer's `mapError` derives the
@@ -715,27 +2092,47 @@ var BaerlyError = class extends Error {
715
2092
  status;
716
2093
  /** Canonical corrective action; crosses the wire via `HttpErrorEnvelope.error.resolution`. */
717
2094
  resolution;
718
- retriableOverride;
2095
+ /** Suggested delay in seconds before retrying; set only for `MaintenancePending`. Crosses the wire via `HttpErrorEnvelope.error.retryAfter` and the `Retry-After` header. */
2096
+ retryAfter;
719
2097
  /**
720
- * Whether this error instance is retriable. Defaults from `code`, but
721
- * context-sensitive throw sites can override it.
2098
+ * `true` iff re-running the operation from its read step can succeed:
2099
+ * `NetworkError` (retry with backoff) and `WriteConflict` (re-read, then
2100
+ * write again). A `Collection` / `Query` verb re-reads on every call, so
2101
+ * calling it again is the retry; a blind resend of the same conditional
2102
+ * `Storage` put loses again. A pure function of `code`
2103
+ * ({@link isRetriableCode}): every instance of a code gives the same
2104
+ * answer. `AmbiguousCommit` is `false` because the write may have landed;
2105
+ * reconcile by `_id` first.
722
2106
  */
723
2107
  get retriable() {
724
- return this.retriableOverride ?? isRetriableCode(this.code);
2108
+ return isRetriableCode(this.code);
725
2109
  }
726
- constructor(code, message, cause, issues, status, resolution, retriableOverride) {
2110
+ /**
2111
+ * `code` and `message` are positional; everything else goes in `options`,
2112
+ * as with `new Error(message, { cause })`. Passing an `Error` (or any
2113
+ * non-options value) as the third argument does not compile; the
2114
+ * options object is where `cause` goes.
2115
+ *
2116
+ * @example
2117
+ * ```ts
2118
+ * throw new BaerlyError("NetworkError", "PUT failed", { cause: err });
2119
+ * throw new BaerlyError("AmbiguousCommit", "commit outcome unknown", { _id: "t-1" });
2120
+ * ```
2121
+ */
2122
+ constructor(code, message, options) {
727
2123
  super(message);
728
2124
  this.name = "BaerlyError";
729
2125
  this.code = code;
730
- this.cause = cause;
731
- this.retriableOverride = retriableOverride;
2126
+ this.cause = options?.cause;
2127
+ const { issues, status, resolution, _id, retryAfter } = options ?? {};
732
2128
  if (issues !== void 0) this.issues = issues;
733
2129
  if (status !== void 0) this.status = status;
734
2130
  if (resolution !== void 0) this.resolution = resolution;
2131
+ if (_id !== void 0) this._id = _id;
2132
+ if (retryAfter !== void 0) this.retryAfter = retryAfter;
735
2133
  }
736
2134
  };
737
- //#endregion
738
- //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
2135
+ // ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js
739
2136
  /**
740
2137
  * Creates a JSON scanner on the given text.
741
2138
  * If ignoreTrivia is set, whitespaces or comments are ignored.
@@ -850,11 +2247,13 @@ function createScanner(text, ignoreTrivia = false) {
850
2247
  start = pos;
851
2248
  continue;
852
2249
  }
853
- if (ch >= 0 && ch <= 31) if (isLineBreak(ch)) {
854
- result += text.substring(start, pos);
855
- scanError = 2;
856
- break;
857
- } else scanError = 6;
2250
+ if (ch >= 0 && ch <= 31) {
2251
+ if (isLineBreak(ch)) {
2252
+ result += text.substring(start, pos);
2253
+ scanError = 2;
2254
+ break;
2255
+ } else scanError = 6;
2256
+ }
858
2257
  pos++;
859
2258
  }
860
2259
  return result;
@@ -1112,8 +2511,7 @@ var CharacterCodes;
1112
2511
  CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
1113
2512
  CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
1114
2513
  })(CharacterCodes || (CharacterCodes = {}));
1115
- //#endregion
1116
- //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js
2514
+ // ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js
1117
2515
  const cachedSpaces = new Array(20).fill(0).map((_, index) => {
1118
2516
  return " ".repeat(index);
1119
2517
  });
@@ -1147,8 +2545,7 @@ const supportedEols = [
1147
2545
  "\r",
1148
2546
  "\r\n"
1149
2547
  ];
1150
- //#endregion
1151
- //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js
2548
+ // ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/format.js
1152
2549
  function format(documentText, range, options) {
1153
2550
  let initialIndentLevel;
1154
2551
  let formatText;
@@ -1271,14 +2668,14 @@ function format(documentText, range, options) {
1271
2668
  else if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) replaceContent = cachedSpaces[1];
1272
2669
  else if (secondToken !== 5 && secondToken !== 17) hasError = true;
1273
2670
  break;
1274
- case 16:
1275
- hasError = true;
1276
- break;
2671
+ case 16: hasError = true;
1277
2672
  }
1278
2673
  if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) replaceContent = newLinesAndIndent();
1279
2674
  }
1280
- if (secondToken === 17) if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
1281
- else replaceContent = options.insertFinalNewline ? eol : "";
2675
+ if (secondToken === 17) {
2676
+ if (options.keepLines && numberLineBreaks > 0) replaceContent = newLinesAndIndent();
2677
+ else replaceContent = options.insertFinalNewline ? eol : "";
2678
+ }
1282
2679
  const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
1283
2680
  addEdit(replaceContent, firstTokenEnd, secondTokenStart);
1284
2681
  firstToken = secondToken;
@@ -1316,8 +2713,7 @@ function getEOL(options, text) {
1316
2713
  function isEOL(text, offset) {
1317
2714
  return "\r\n".indexOf(text.charAt(offset)) !== -1;
1318
2715
  }
1319
- //#endregion
1320
- //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js
2716
+ // ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js
1321
2717
  var ParseOptions;
1322
2718
  (function(ParseOptions) {
1323
2719
  ParseOptions.DEFAULT = { allowTrailingComma: false };
@@ -1536,9 +2932,7 @@ function visit(text, visitor, options = ParseOptions.DEFAULT) {
1536
2932
  case 2:
1537
2933
  handleError(12);
1538
2934
  break;
1539
- case 6:
1540
- handleError(16);
1541
- break;
2935
+ case 6: handleError(16);
1542
2936
  }
1543
2937
  switch (token) {
1544
2938
  case 12:
@@ -1694,8 +3088,7 @@ function getNodeType(value) {
1694
3088
  default: return "null";
1695
3089
  }
1696
3090
  }
1697
- //#endregion
1698
- //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js
3091
+ // ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/edit.js
1699
3092
  function setProperty(text, originalPath, value, options) {
1700
3093
  const path = originalPath.slice();
1701
3094
  const root = parseTree(text, []);
@@ -1704,9 +3097,10 @@ function setProperty(text, originalPath, value, options) {
1704
3097
  while (path.length > 0) {
1705
3098
  lastSegment = path.pop();
1706
3099
  parent = findNodeAtLocation(root, path);
1707
- if (parent === void 0 && value !== void 0) if (typeof lastSegment === "string") value = { [lastSegment]: value };
1708
- else value = [value];
1709
- else break;
3100
+ if (parent === void 0 && value !== void 0) {
3101
+ if (typeof lastSegment === "string") value = { [lastSegment]: value };
3102
+ else value = [value];
3103
+ } else break;
1710
3104
  }
1711
3105
  if (!parent) {
1712
3106
  if (value === void 0) throw new Error("Can not delete in empty document");
@@ -1717,29 +3111,30 @@ function setProperty(text, originalPath, value, options) {
1717
3111
  }, options);
1718
3112
  } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
1719
3113
  const existing = findNodeAtLocation(parent, [lastSegment]);
1720
- if (existing !== void 0) if (value === void 0) {
1721
- if (!existing.parent) throw new Error("Malformed AST");
1722
- const propertyIndex = parent.children.indexOf(existing.parent);
1723
- let removeBegin;
1724
- let removeEnd = existing.parent.offset + existing.parent.length;
1725
- if (propertyIndex > 0) {
1726
- let previous = parent.children[propertyIndex - 1];
1727
- removeBegin = previous.offset + previous.length;
1728
- } else {
1729
- removeBegin = parent.offset + 1;
1730
- if (parent.children.length > 1) removeEnd = parent.children[1].offset;
1731
- }
1732
- return withFormatting(text, {
1733
- offset: removeBegin,
1734
- length: removeEnd - removeBegin,
1735
- content: ""
3114
+ if (existing !== void 0) {
3115
+ if (value === void 0) {
3116
+ if (!existing.parent) throw new Error("Malformed AST");
3117
+ const propertyIndex = parent.children.indexOf(existing.parent);
3118
+ let removeBegin;
3119
+ let removeEnd = existing.parent.offset + existing.parent.length;
3120
+ if (propertyIndex > 0) {
3121
+ let previous = parent.children[propertyIndex - 1];
3122
+ removeBegin = previous.offset + previous.length;
3123
+ } else {
3124
+ removeBegin = parent.offset + 1;
3125
+ if (parent.children.length > 1) removeEnd = parent.children[1].offset;
3126
+ }
3127
+ return withFormatting(text, {
3128
+ offset: removeBegin,
3129
+ length: removeEnd - removeBegin,
3130
+ content: ""
3131
+ }, options);
3132
+ } else return withFormatting(text, {
3133
+ offset: existing.offset,
3134
+ length: existing.length,
3135
+ content: JSON.stringify(value)
1736
3136
  }, options);
1737
- } else return withFormatting(text, {
1738
- offset: existing.offset,
1739
- length: existing.length,
1740
- content: JSON.stringify(value)
1741
- }, options);
1742
- else {
3137
+ } else {
1743
3138
  if (value === void 0) return [];
1744
3139
  const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
1745
3140
  const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length;
@@ -1866,8 +3261,7 @@ function withFormatting(text, edit, options) {
1866
3261
  function applyEdit(text, edit) {
1867
3262
  return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
1868
3263
  }
1869
- //#endregion
1870
- //#region ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js
3264
+ // ../../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js
1871
3265
  var ScanError;
1872
3266
  (function(ScanError) {
1873
3267
  ScanError[ScanError["None"] = 0] = "None";
@@ -1959,8 +3353,7 @@ function applyEdits(text, edits) {
1959
3353
  }
1960
3354
  return text;
1961
3355
  }
1962
- //#endregion
1963
- //#region ../cli/src/wrangler-patch.ts
3356
+ // ../cli/src/wrangler-patch.ts
1964
3357
  /**
1965
3358
  * Surgical wrangler.jsonc helpers used by `baerly deploy` and the
1966
3359
  * `@gusto/create-baerly-storage` bolt-on flow. All functions are pure (no I/O) —
@@ -2084,8 +3477,7 @@ const patchWranglerJsonc = (source, binding, vars) => {
2084
3477
  changes
2085
3478
  };
2086
3479
  };
2087
- //#endregion
2088
- //#region src/init-snippet.ts
3480
+ // src/init-snippet.ts
2089
3481
  /**
2090
3482
  * Render the worker-entry paste-string that the create-baerly-storage
2091
3483
  * bolt-on flow prints after patching `wrangler.jsonc`. The user
@@ -2102,7 +3494,8 @@ const patchWranglerJsonc = (source, binding, vars) => {
2102
3494
  * explicit `.ts`/`.tsx` extensions").
2103
3495
  */
2104
3496
  const computeConfigImportPath = (wranglerMain) => {
2105
- const fromDir = dirname$1(normalize(wranglerMain));
3497
+ const normalised = normalize(wranglerMain);
3498
+ const fromDir = dirname$1(normalised);
2106
3499
  if (fromDir === "." || fromDir === "") return "./baerly.config.ts";
2107
3500
  const rel = relative(fromDir, "baerly.config.ts");
2108
3501
  return rel.startsWith("..") ? rel : `./${rel}`;
@@ -2123,8 +3516,7 @@ export default baerlyWorker<AppEnv>((env) => ({
2123
3516
  }));
2124
3517
  `;
2125
3518
  };
2126
- //#endregion
2127
- //#region src/install.ts
3519
+ // src/install.ts
2128
3520
  /**
2129
3521
  * `Installer` DI seam for the post-scaffold install step. The default
2130
3522
  * implementation shells out to the detected package manager via
@@ -2144,8 +3536,7 @@ const defaultInstaller = { run: (pm, cwd) => new Promise((resolve, reject) => {
2144
3536
  child.on("error", reject);
2145
3537
  child.on("close", (code) => resolve({ code: code ?? 1 }));
2146
3538
  }) };
2147
- //#endregion
2148
- //#region src/agent-rules.ts
3539
+ // src/agent-rules.ts
2149
3540
  /**
2150
3541
  * Bolt-on agent-rules writer. The CLI enables this by default for
2151
3542
  * existing wrangler projects and lets users opt out with
@@ -2197,8 +3588,8 @@ Anti-patterns that compile but are wrong:
2197
3588
 
2198
3589
  - \`db.collection(...).insertOne(...)\` — no such method. Use
2199
3590
  \`db.collection(...).insert(...)\`.
2200
- - \`.useIndex("name")\` — does not exist. The query planner picks
2201
- indexes automatically from registered \`IndexDefinition\`s.
3591
+ - \`.useIndex("name")\` — does not exist. Declared \`indexes\` do not
3592
+ change how a read runs; every read scans the collection.
2202
3593
  - \`z.string().nullable()\` — \`DocumentValue\` excludes \`null\`. Use
2203
3594
  \`.optional()\`; \`null\` in update patches is the RFC 7386 deletion
2204
3595
  sentinel.
@@ -2206,8 +3597,11 @@ Anti-patterns that compile but are wrong:
2206
3597
  only: \`.where({ field: value }).all()\` (object literal, equality)
2207
3598
  or \`.where(q => q.gte("field", n)).all()\` (callback DSL,
2208
3599
  operators: \`eq\` / \`gt\` / \`gte\` / \`lt\` / \`lte\` / \`in\`).
2209
- - \`.all()\` on a hot path — page or cursor-iterate. \`.all()\` is for
2210
- bounded result sets only.
3600
+ - Paging or cursor-iterating \`.all()\` — there is no offset, page or
3601
+ cursor API. Bound every read instead: scope it with
3602
+ \`.where(...)\` and cap it with \`.limit(n)\` (plus \`.order(...)\` for a
3603
+ stable top N). Each read still folds the whole collection, so a limit
3604
+ caps the rows returned, not the work done.
2211
3605
  ${BLOCK_END}
2212
3606
  `;
2213
3607
  const fileExists$1 = async (path) => {
@@ -2226,20 +3620,20 @@ const dirExists = async (path) => {
2226
3620
  }
2227
3621
  };
2228
3622
  const detectAgentRulesTarget = async (outDir) => {
2229
- if (await dirExists(resolve(outDir, ".claude", "rules"))) return {
2230
- path: resolve(outDir, ".claude", "rules", "baerly.md"),
3623
+ if (await dirExists(resolve$1(outDir, ".claude", "rules"))) return {
3624
+ path: resolve$1(outDir, ".claude", "rules", "baerly.md"),
2231
3625
  mode: "dedicated"
2232
3626
  };
2233
- if (await fileExists$1(resolve(outDir, "AGENTS.md"))) return {
2234
- path: resolve(outDir, "AGENTS.md"),
3627
+ if (await fileExists$1(resolve$1(outDir, "AGENTS.md"))) return {
3628
+ path: resolve$1(outDir, "AGENTS.md"),
2235
3629
  mode: "shared"
2236
3630
  };
2237
- if (await dirExists(resolve(outDir, ".cursor", "rules"))) return {
2238
- path: resolve(outDir, ".cursor", "rules", "baerly.md"),
3631
+ if (await dirExists(resolve$1(outDir, ".cursor", "rules"))) return {
3632
+ path: resolve$1(outDir, ".cursor", "rules", "baerly.md"),
2239
3633
  mode: "dedicated"
2240
3634
  };
2241
3635
  return {
2242
- path: resolve(outDir, "AGENTS.md"),
3636
+ path: resolve$1(outDir, "AGENTS.md"),
2243
3637
  mode: "shared"
2244
3638
  };
2245
3639
  };
@@ -2298,8 +3692,7 @@ const writeAgentRulesBlock = async (outDir) => {
2298
3692
  action: "appended"
2299
3693
  };
2300
3694
  };
2301
- //#endregion
2302
- //#region src/bolt-on.ts
3695
+ // src/bolt-on.ts
2303
3696
  /**
2304
3697
  * The wrangler bolt-on flow for `create-baerly-storage`. Runs when `runner.ts`
2305
3698
  * detects an existing `wrangler.jsonc` in the resolved `outDir` — the
@@ -2359,7 +3752,7 @@ const appendBaerlyStorageDep = async (pkgJsonPath, changes) => {
2359
3752
  changes.push("package.json: added @gusto/baerly-storage dependency");
2360
3753
  };
2361
3754
  const boltOnExistingWrangler = async (opts) => {
2362
- const wranglerPath = resolve(opts.outDir, "wrangler.jsonc");
3755
+ const wranglerPath = resolve$1(opts.outDir, "wrangler.jsonc");
2363
3756
  if (!await fileExists(wranglerPath)) throw new BaerlyError("InvalidConfig", `create-baerly-storage bolt-on: ${wranglerPath} missing — bolt-on mode requires wrangler.jsonc`);
2364
3757
  const wranglerSource = await readFile(wranglerPath, "utf8");
2365
3758
  const detectedName = readWranglerName(wranglerSource);
@@ -2378,25 +3771,26 @@ const boltOnExistingWrangler = async (opts) => {
2378
3771
  await writeFile(wranglerPath, patch.text, "utf8");
2379
3772
  for (const c of patch.changes) changes.push(`wrangler.jsonc: ${c}`);
2380
3773
  }
2381
- const devVarsPath = resolve(opts.outDir, ".dev.vars");
3774
+ const devVarsPath = resolve$1(opts.outDir, ".dev.vars");
2382
3775
  if (!await fileExists(devVarsPath)) {
2383
3776
  await writeFile(devVarsPath, `SHARED_SECRET=${DEV_SHARED_SECRET}\n`, "utf8");
2384
3777
  changes.push(".dev.vars: seeded SHARED_SECRET (dev-only placeholder; replace before deploy)");
2385
3778
  }
2386
- const gitignorePath = resolve(opts.outDir, ".gitignore");
3779
+ const gitignorePath = resolve$1(opts.outDir, ".gitignore");
2387
3780
  let gitignoreText = "";
2388
3781
  if (await fileExists(gitignorePath)) gitignoreText = await readFile(gitignorePath, "utf8");
2389
3782
  if (!gitignoreCovers(gitignoreText, ".dev.vars")) {
2390
- await appendFile(gitignorePath, `${gitignoreText.length === 0 || gitignoreText.endsWith("\n") ? "" : "\n"}.dev.vars\n`, "utf8");
3783
+ const suffix = gitignoreText.length === 0 || gitignoreText.endsWith("\n") ? "" : "\n";
3784
+ await appendFile(gitignorePath, `${suffix}.dev.vars\n`, "utf8");
2391
3785
  changes.push(".gitignore: added .dev.vars");
2392
3786
  }
2393
- const configPath = resolve(opts.outDir, "baerly.config.ts");
3787
+ const configPath = resolve$1(opts.outDir, "baerly.config.ts");
2394
3788
  const configExists = await fileExists(configPath);
2395
3789
  if (!configExists || opts.force === true) {
2396
3790
  await writeFile(configPath, configTemplate(app, opts.tenant), "utf8");
2397
3791
  changes.push(`baerly.config.ts: ${configExists ? "rewrote" : "wrote"}`);
2398
3792
  }
2399
- const pkgJsonPath = resolve(opts.outDir, "package.json");
3793
+ const pkgJsonPath = resolve$1(opts.outDir, "package.json");
2400
3794
  if (await fileExists(pkgJsonPath)) await appendBaerlyStorageDep(pkgJsonPath, changes);
2401
3795
  let agentRules;
2402
3796
  if (opts.agentRules === true) {
@@ -2423,8 +3817,7 @@ const boltOnExistingWrangler = async (opts) => {
2423
3817
  ...agentRules !== void 0 && { agentRules }
2424
3818
  };
2425
3819
  };
2426
- //#endregion
2427
- //#region src/runner.ts
3820
+ // src/runner.ts
2428
3821
  /**
2429
3822
  * `create-baerly-storage` command logic — citty `defineCommand` plus the
2430
3823
  * programmatic `runCreateBaerly` entry consumed by tests. The bin
@@ -2508,7 +3901,7 @@ const CREATE_BAERLY_ARGS = {
2508
3901
  description: "Emit JSON envelope to stdout (success) or stderr (error)."
2509
3902
  }
2510
3903
  };
2511
- const resolveOutDir = (projectName) => projectName === "." ? process.cwd() : resolve(process.cwd(), projectName);
3904
+ const resolveOutDir = (projectName) => projectName === "." ? process.cwd() : resolve$1(process.cwd(), projectName);
2512
3905
  const dispatchBoltOn = async (opts) => {
2513
3906
  try {
2514
3907
  const result = await boltOnExistingWrangler({
@@ -2535,9 +3928,9 @@ const dispatchBoltOn = async (opts) => {
2535
3928
  } })}\n`);
2536
3929
  else if (opts.isInteractive) {
2537
3930
  const changesBlock = result.changes.length === 0 ? " (no changes — already bolted on)" : result.changes.map((c) => ` ${c}`).join("\n");
2538
- outro(`${pc.green("✓")} bolted baerly onto ${opts.outDir}\n\nChanges:\n${changesBlock}\n\nPaste this into ${result.snippetTarget}, replacing the stock handler:\n\n` + result.snippet + `\nNext steps:\n` + result.nextSteps.map((s) => ` ${s}`).join("\n"));
3931
+ outro(`${styleText("green", "✓")} bolted baerly onto ${opts.outDir}\n\nChanges:\n${changesBlock}\n\nPaste this into ${result.snippetTarget}, replacing the stock handler:\n\n` + result.snippet + `\nNext steps:\n` + result.nextSteps.map((s) => ` ${s}`).join("\n"));
2539
3932
  } else {
2540
- process.stdout.write(`${pc.green("✓")} bolted baerly onto ${opts.outDir}\n`);
3933
+ process.stdout.write(`${styleText("green", "✓")} bolted baerly onto ${opts.outDir}\n`);
2541
3934
  if (result.changes.length > 0) {
2542
3935
  process.stdout.write(`\n Changes:\n`);
2543
3936
  for (const c of result.changes) process.stdout.write(` ${c}\n`);
@@ -2556,7 +3949,7 @@ const dispatchBoltOn = async (opts) => {
2556
3949
  message: msg,
2557
3950
  command: "create-baerly-storage"
2558
3951
  } })}\n`);
2559
- else process.stderr.write(`${pc.red("create-baerly-storage:")} ${msg}\n`);
3952
+ else process.stderr.write(`${styleText("red", "create-baerly-storage:", { stream: process.stderr })} ${msg}\n`);
2560
3953
  return 1;
2561
3954
  }
2562
3955
  };
@@ -2612,8 +4005,8 @@ const handleCreateBaerly = async (args, opts = {}) => {
2612
4005
  if (args.projectName === void 0) throw new Error("projectName is required (positional)");
2613
4006
  projectName = args.projectName;
2614
4007
  const outDir = resolveOutDir(projectName);
2615
- if (args.target === "node" && existsSync(resolve(outDir, "wrangler.jsonc"))) throw new Error("create-baerly-storage: detected wrangler.jsonc but --target=node was passed. Bolt-on only supports Cloudflare. Remove --target=node, or move out of this directory to scaffold a Node app.");
2616
- if (existsSync(resolve(outDir, "wrangler.jsonc"))) return await dispatchBoltOn({
4008
+ if (args.target === "node" && existsSync(resolve$1(outDir, "wrangler.jsonc"))) throw new Error("create-baerly-storage: detected wrangler.jsonc but --target=node was passed. Bolt-on only supports Cloudflare. Remove --target=node, or move out of this directory to scaffold a Node app.");
4009
+ if (existsSync(resolve$1(outDir, "wrangler.jsonc"))) return await dispatchBoltOn({
2617
4010
  outDir,
2618
4011
  tenant: args.tenant ?? "default",
2619
4012
  force: args.force === true,
@@ -2660,12 +4053,12 @@ const handleCreateBaerly = async (args, opts = {}) => {
2660
4053
  let hint = `${outcome.reason}${detail}`;
2661
4054
  if (outcome.reason === "git-not-available") hint = `git is not installed; install it then run \`git init && git add . && git commit -m '…'\` in ${result.outDir}.`;
2662
4055
  else if (outcome.reason === "no-identity") hint = `git user.name / user.email are not configured. Set them with \`git config --global user.name '…'\` + \`git config --global user.email '…'\`, then commit manually.`;
2663
- process.stderr.write(`${pc.yellow("create-baerly-storage:")} git init skipped — ${hint}\n`);
4056
+ process.stderr.write(`${styleText("yellow", "create-baerly-storage:", { stream: process.stderr })} git init skipped — ${hint}\n`);
2664
4057
  }
2665
4058
  }
2666
4059
  if (install) {
2667
4060
  const { code } = await (opts.installer ?? defaultInstaller).run(pm, result.outDir);
2668
- if (code !== 0) process.stderr.write(`${pc.yellow("create-baerly-storage:")} install exited with code ${code}. Run \`${pm} install\` in ${result.outDir} manually.\n`);
4061
+ if (code !== 0) process.stderr.write(`${styleText("yellow", "create-baerly-storage:", { stream: process.stderr })} install exited with code ${code}. Run \`${pm} install\` in ${result.outDir} manually.\n`);
2669
4062
  }
2670
4063
  if (jsonMode) process.stdout.write(`${JSON.stringify({ result: {
2671
4064
  command: "create-baerly-storage",
@@ -2674,9 +4067,9 @@ const handleCreateBaerly = async (args, opts = {}) => {
2674
4067
  filesWritten: result.filesWritten.length,
2675
4068
  nextSteps: result.nextSteps
2676
4069
  } })}\n`);
2677
- else if (isInteractive) outro(`${pc.green("✓")} ${result.outDir}\n\n Next steps:\n` + result.nextSteps.map((s) => ` ${s}`).join("\n"));
4070
+ else if (isInteractive) outro(`${styleText("green", "✓")} ${result.outDir}\n\n Next steps:\n` + result.nextSteps.map((s) => ` ${s}`).join("\n"));
2678
4071
  else {
2679
- process.stdout.write(`${pc.green("✓")} scaffolded ${result.outDir}\n`);
4072
+ process.stdout.write(`${styleText("green", "✓")} scaffolded ${result.outDir}\n`);
2680
4073
  process.stdout.write(`\n Next steps:\n`);
2681
4074
  for (const s of result.nextSteps) process.stdout.write(` ${s}\n`);
2682
4075
  process.stdout.write("\n");
@@ -2689,14 +4082,14 @@ const handleCreateBaerly = async (args, opts = {}) => {
2689
4082
  message: msg,
2690
4083
  command: "create-baerly-storage"
2691
4084
  } })}\n`);
2692
- else process.stderr.write(`${pc.red("create-baerly-storage:")} ${msg}\n`);
4085
+ else process.stderr.write(`${styleText("red", "create-baerly-storage:", { stream: process.stderr })} ${msg}\n`);
2693
4086
  return 1;
2694
4087
  }
2695
4088
  };
2696
4089
  const main = defineCommand({
2697
4090
  meta: {
2698
4091
  name: "create-baerly-storage",
2699
- version: "0.0.0",
4092
+ version,
2700
4093
  description: "Scaffold a new baerly app (Cloudflare Worker or self-hosted Node)."
2701
4094
  },
2702
4095
  args: CREATE_BAERLY_ARGS,
@@ -2705,8 +4098,7 @@ const main = defineCommand({
2705
4098
  if (code !== 0) process.exit(code);
2706
4099
  }
2707
4100
  });
2708
- //#endregion
2709
- //#region src/index.ts
4101
+ // src/index.ts
2710
4102
  /**
2711
4103
  * `create-baerly-storage` bin entry. Imports the citty command from `./runner.ts`
2712
4104
  * and dispatches via an inline `runBin` shim. Kept as a thin shim so
@@ -2721,7 +4113,7 @@ const main = defineCommand({
2721
4113
  * with its own dependency surface — the cross-package import
2722
4114
  * overhead beats the dedup at this scale.
2723
4115
  */
2724
- const resolve$1 = async (v) => {
4116
+ const resolve = async (v) => {
2725
4117
  if (typeof v === "function") return v();
2726
4118
  return v;
2727
4119
  };
@@ -2731,7 +4123,7 @@ const writeError = (json, code, message) => {
2731
4123
  message,
2732
4124
  command: "create-baerly-storage"
2733
4125
  } })}\n`);
2734
- else process.stderr.write(`${pc.red("create-baerly-storage:")} ${code}: ${message}\n`);
4126
+ else process.stderr.write(`${styleText("red", "create-baerly-storage:", { stream: process.stderr })} ${code}: ${message}\n`);
2735
4127
  };
2736
4128
  const argv = process.argv.slice(2);
2737
4129
  const wantJson = argv.includes("--json");
@@ -2741,7 +4133,7 @@ const run = async () => {
2741
4133
  process.exit(0);
2742
4134
  }
2743
4135
  if (argv.includes("--version") || argv.includes("-v")) {
2744
- const version = (await resolve$1(main.meta) ?? {}).version;
4136
+ const version = (await resolve(main.meta) ?? {}).version;
2745
4137
  if (typeof version !== "string" || version.length === 0) {
2746
4138
  writeError(wantJson, "InvalidConfig", "no version declared on this command");
2747
4139
  process.exit(1);
@@ -2750,14 +4142,14 @@ const run = async () => {
2750
4142
  process.exit(0);
2751
4143
  }
2752
4144
  try {
2753
- await runCommand(main, { rawArgs: [...argv] });
4145
+ await runCommand$1(main, { rawArgs: [...argv] });
2754
4146
  process.exit(0);
2755
4147
  } catch (error) {
2756
- writeError(wantJson, "InvalidConfig", error instanceof Error ? error.message : String(error));
4148
+ const message = error instanceof Error ? error.message : String(error);
4149
+ writeError(wantJson, "InvalidConfig", message);
2757
4150
  process.exit(1);
2758
4151
  }
2759
4152
  };
2760
4153
  run();
2761
- //#endregion
2762
4154
 
2763
4155
  //# sourceMappingURL=index.js.map