openkitt 0.1.2 → 0.1.6

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 (233) hide show
  1. package/dist/cli.js +3697 -341
  2. package/package.json +5 -5
  3. package/scripts/publish.sh +63 -49
  4. package/dist/ast/engine.d.ts +0 -26
  5. package/dist/ast/engine.js +0 -130
  6. package/dist/ast/engine.js.map +0 -1
  7. package/dist/ast/operations.d.ts +0 -13
  8. package/dist/ast/operations.js +0 -329
  9. package/dist/ast/operations.js.map +0 -1
  10. package/dist/ast/validator.d.ts +0 -19
  11. package/dist/ast/validator.js +0 -281
  12. package/dist/ast/validator.js.map +0 -1
  13. package/dist/audit/logger.d.ts +0 -14
  14. package/dist/audit/logger.js +0 -102
  15. package/dist/audit/logger.js.map +0 -1
  16. package/dist/cli.d.ts +0 -4
  17. package/dist/cli.js.map +0 -1
  18. package/dist/commands/create-confirm.d.ts +0 -13
  19. package/dist/commands/create-confirm.js +0 -38
  20. package/dist/commands/create-confirm.js.map +0 -1
  21. package/dist/commands/create-infra.d.ts +0 -20
  22. package/dist/commands/create-infra.js +0 -63
  23. package/dist/commands/create-infra.js.map +0 -1
  24. package/dist/commands/create-manifest.d.ts +0 -10
  25. package/dist/commands/create-manifest.js +0 -21
  26. package/dist/commands/create-manifest.js.map +0 -1
  27. package/dist/commands/create-packages.d.ts +0 -17
  28. package/dist/commands/create-packages.js +0 -69
  29. package/dist/commands/create-packages.js.map +0 -1
  30. package/dist/commands/create-pipeline.d.ts +0 -15
  31. package/dist/commands/create-pipeline.js +0 -57
  32. package/dist/commands/create-pipeline.js.map +0 -1
  33. package/dist/commands/create-scaffolding.d.ts +0 -12
  34. package/dist/commands/create-scaffolding.js +0 -137
  35. package/dist/commands/create-scaffolding.js.map +0 -1
  36. package/dist/commands/create-staging.d.ts +0 -13
  37. package/dist/commands/create-staging.js +0 -17
  38. package/dist/commands/create-staging.js.map +0 -1
  39. package/dist/commands/create-transforms.d.ts +0 -10
  40. package/dist/commands/create-transforms.js +0 -33
  41. package/dist/commands/create-transforms.js.map +0 -1
  42. package/dist/commands/create.d.ts +0 -2
  43. package/dist/commands/create.js +0 -155
  44. package/dist/commands/create.js.map +0 -1
  45. package/dist/commands/delete.d.ts +0 -2
  46. package/dist/commands/delete.js +0 -83
  47. package/dist/commands/delete.js.map +0 -1
  48. package/dist/commands/deploy.d.ts +0 -5
  49. package/dist/commands/deploy.js +0 -371
  50. package/dist/commands/deploy.js.map +0 -1
  51. package/dist/commands/domain.d.ts +0 -2
  52. package/dist/commands/domain.js +0 -90
  53. package/dist/commands/domain.js.map +0 -1
  54. package/dist/commands/env.d.ts +0 -2
  55. package/dist/commands/env.js +0 -153
  56. package/dist/commands/env.js.map +0 -1
  57. package/dist/commands/help.d.ts +0 -3
  58. package/dist/commands/help.js +0 -107
  59. package/dist/commands/help.js.map +0 -1
  60. package/dist/commands/init.d.ts +0 -2
  61. package/dist/commands/init.js +0 -217
  62. package/dist/commands/init.js.map +0 -1
  63. package/dist/commands/list.d.ts +0 -2
  64. package/dist/commands/list.js +0 -142
  65. package/dist/commands/list.js.map +0 -1
  66. package/dist/commands/login.d.ts +0 -2
  67. package/dist/commands/login.js +0 -235
  68. package/dist/commands/login.js.map +0 -1
  69. package/dist/commands/logs.d.ts +0 -2
  70. package/dist/commands/logs.js +0 -90
  71. package/dist/commands/logs.js.map +0 -1
  72. package/dist/commands/publish.d.ts +0 -2
  73. package/dist/commands/publish.js +0 -113
  74. package/dist/commands/publish.js.map +0 -1
  75. package/dist/commands/run.d.ts +0 -14
  76. package/dist/commands/run.js +0 -196
  77. package/dist/commands/run.js.map +0 -1
  78. package/dist/commands/settings.d.ts +0 -3
  79. package/dist/commands/settings.js +0 -278
  80. package/dist/commands/settings.js.map +0 -1
  81. package/dist/commands/status.d.ts +0 -2
  82. package/dist/commands/status.js +0 -88
  83. package/dist/commands/status.js.map +0 -1
  84. package/dist/commands/versions.d.ts +0 -2
  85. package/dist/commands/versions.js +0 -242
  86. package/dist/commands/versions.js.map +0 -1
  87. package/dist/credentials/config.d.ts +0 -12
  88. package/dist/credentials/config.js +0 -196
  89. package/dist/credentials/config.js.map +0 -1
  90. package/dist/credentials/encryption.d.ts +0 -9
  91. package/dist/credentials/encryption.js +0 -100
  92. package/dist/credentials/encryption.js.map +0 -1
  93. package/dist/credentials/keychain.d.ts +0 -8
  94. package/dist/credentials/keychain.js +0 -236
  95. package/dist/credentials/keychain.js.map +0 -1
  96. package/dist/credentials/railway.d.ts +0 -9
  97. package/dist/credentials/railway.js +0 -69
  98. package/dist/credentials/railway.js.map +0 -1
  99. package/dist/llm/client.d.ts +0 -59
  100. package/dist/llm/client.js +0 -530
  101. package/dist/llm/client.js.map +0 -1
  102. package/dist/llm/operations.d.ts +0 -39
  103. package/dist/llm/operations.js +0 -131
  104. package/dist/llm/operations.js.map +0 -1
  105. package/dist/llm/rate-limiter.d.ts +0 -20
  106. package/dist/llm/rate-limiter.js +0 -57
  107. package/dist/llm/rate-limiter.js.map +0 -1
  108. package/dist/llm/scaffolding.d.ts +0 -51
  109. package/dist/llm/scaffolding.js +0 -118
  110. package/dist/llm/scaffolding.js.map +0 -1
  111. package/dist/manifest/drift.d.ts +0 -6
  112. package/dist/manifest/drift.js +0 -45
  113. package/dist/manifest/drift.js.map +0 -1
  114. package/dist/manifest/reader.d.ts +0 -12
  115. package/dist/manifest/reader.js +0 -99
  116. package/dist/manifest/reader.js.map +0 -1
  117. package/dist/manifest/types.d.ts +0 -31
  118. package/dist/manifest/types.js +0 -2
  119. package/dist/manifest/types.js.map +0 -1
  120. package/dist/manifest/writer.d.ts +0 -9
  121. package/dist/manifest/writer.js +0 -142
  122. package/dist/manifest/writer.js.map +0 -1
  123. package/dist/mcp/client.d.ts +0 -21
  124. package/dist/mcp/client.js +0 -213
  125. package/dist/mcp/client.js.map +0 -1
  126. package/dist/mcp/lifecycle.d.ts +0 -12
  127. package/dist/mcp/lifecycle.js +0 -149
  128. package/dist/mcp/lifecycle.js.map +0 -1
  129. package/dist/mcp/project-guard.d.ts +0 -14
  130. package/dist/mcp/project-guard.js +0 -27
  131. package/dist/mcp/project-guard.js.map +0 -1
  132. package/dist/prompts/operations.d.ts +0 -1
  133. package/dist/prompts/operations.js +0 -160
  134. package/dist/prompts/operations.js.map +0 -1
  135. package/dist/prompts/scaffolding.d.ts +0 -1
  136. package/dist/prompts/scaffolding.js +0 -331
  137. package/dist/prompts/scaffolding.js.map +0 -1
  138. package/dist/prompts/version.d.ts +0 -2
  139. package/dist/prompts/version.js +0 -3
  140. package/dist/prompts/version.js.map +0 -1
  141. package/dist/sandbox/command-allowlist.d.ts +0 -6
  142. package/dist/sandbox/command-allowlist.js +0 -103
  143. package/dist/sandbox/command-allowlist.js.map +0 -1
  144. package/dist/sandbox/package-allowlist.d.ts +0 -6
  145. package/dist/sandbox/package-allowlist.js +0 -49
  146. package/dist/sandbox/package-allowlist.js.map +0 -1
  147. package/dist/sandbox/scanner.d.ts +0 -25
  148. package/dist/sandbox/scanner.js +0 -196
  149. package/dist/sandbox/scanner.js.map +0 -1
  150. package/dist/sandbox/staging.d.ts +0 -12
  151. package/dist/sandbox/staging.js +0 -107
  152. package/dist/sandbox/staging.js.map +0 -1
  153. package/dist/scaffold/frameworks/express.d.ts +0 -3
  154. package/dist/scaffold/frameworks/express.js +0 -242
  155. package/dist/scaffold/frameworks/express.js.map +0 -1
  156. package/dist/scaffold/frameworks/hono.d.ts +0 -3
  157. package/dist/scaffold/frameworks/hono.js +0 -238
  158. package/dist/scaffold/frameworks/hono.js.map +0 -1
  159. package/dist/scaffold/frameworks/nextjs.d.ts +0 -3
  160. package/dist/scaffold/frameworks/nextjs.js +0 -447
  161. package/dist/scaffold/frameworks/nextjs.js.map +0 -1
  162. package/dist/scaffold/frameworks/tanstack-start.d.ts +0 -3
  163. package/dist/scaffold/frameworks/tanstack-start.js +0 -280
  164. package/dist/scaffold/frameworks/tanstack-start.js.map +0 -1
  165. package/dist/scaffold/index.d.ts +0 -4
  166. package/dist/scaffold/index.js +0 -138
  167. package/dist/scaffold/index.js.map +0 -1
  168. package/dist/scaffold/integrations/backend.d.ts +0 -3
  169. package/dist/scaffold/integrations/backend.js +0 -403
  170. package/dist/scaffold/integrations/backend.js.map +0 -1
  171. package/dist/scaffold/integrations/posthog.d.ts +0 -2
  172. package/dist/scaffold/integrations/posthog.js +0 -21
  173. package/dist/scaffold/integrations/posthog.js.map +0 -1
  174. package/dist/scaffold/integrations/sentry.d.ts +0 -2
  175. package/dist/scaffold/integrations/sentry.js +0 -16
  176. package/dist/scaffold/integrations/sentry.js.map +0 -1
  177. package/dist/scaffold/integrations/storybook.d.ts +0 -2
  178. package/dist/scaffold/integrations/storybook.js +0 -79
  179. package/dist/scaffold/integrations/storybook.js.map +0 -1
  180. package/dist/scaffold/integrations/vitest.d.ts +0 -2
  181. package/dist/scaffold/integrations/vitest.js +0 -37
  182. package/dist/scaffold/integrations/vitest.js.map +0 -1
  183. package/dist/scaffold/package-builder.d.ts +0 -3
  184. package/dist/scaffold/package-builder.js +0 -136
  185. package/dist/scaffold/package-builder.js.map +0 -1
  186. package/dist/scaffold/packages.d.ts +0 -4
  187. package/dist/scaffold/packages.js +0 -144
  188. package/dist/scaffold/packages.js.map +0 -1
  189. package/dist/scaffold/types.d.ts +0 -20
  190. package/dist/scaffold/types.js +0 -2
  191. package/dist/scaffold/types.js.map +0 -1
  192. package/dist/types.d.ts +0 -11
  193. package/dist/types.js +0 -2
  194. package/dist/types.js.map +0 -1
  195. package/dist/utils/auth-guard.d.ts +0 -5
  196. package/dist/utils/auth-guard.js +0 -52
  197. package/dist/utils/auth-guard.js.map +0 -1
  198. package/dist/utils/cleanup.d.ts +0 -2
  199. package/dist/utils/cleanup.js +0 -37
  200. package/dist/utils/cleanup.js.map +0 -1
  201. package/dist/utils/constraints.d.ts +0 -11
  202. package/dist/utils/constraints.js +0 -162
  203. package/dist/utils/constraints.js.map +0 -1
  204. package/dist/utils/display.d.ts +0 -32
  205. package/dist/utils/display.js +0 -103
  206. package/dist/utils/display.js.map +0 -1
  207. package/dist/utils/global-config.d.ts +0 -8
  208. package/dist/utils/global-config.js +0 -39
  209. package/dist/utils/global-config.js.map +0 -1
  210. package/dist/utils/pm.d.ts +0 -4
  211. package/dist/utils/pm.js +0 -40
  212. package/dist/utils/pm.js.map +0 -1
  213. package/dist/utils/prerequisites.d.ts +0 -9
  214. package/dist/utils/prerequisites.js +0 -96
  215. package/dist/utils/prerequisites.js.map +0 -1
  216. package/dist/utils/prompts.d.ts +0 -25
  217. package/dist/utils/prompts.js +0 -148
  218. package/dist/utils/prompts.js.map +0 -1
  219. package/dist/utils/validation.d.ts +0 -9
  220. package/dist/utils/validation.js +0 -38
  221. package/dist/utils/validation.js.map +0 -1
  222. package/dist/versions/compat.d.ts +0 -13
  223. package/dist/versions/compat.js +0 -127
  224. package/dist/versions/compat.js.map +0 -1
  225. package/dist/versions/integrity.d.ts +0 -9
  226. package/dist/versions/integrity.js +0 -60
  227. package/dist/versions/integrity.js.map +0 -1
  228. package/dist/versions/parser.d.ts +0 -13
  229. package/dist/versions/parser.js +0 -106
  230. package/dist/versions/parser.js.map +0 -1
  231. package/dist/versions/registry.d.ts +0 -30
  232. package/dist/versions/registry.js +0 -165
  233. package/dist/versions/registry.js.map +0 -1
package/dist/cli.js CHANGED
@@ -1,401 +1,3757 @@
1
1
  #!/usr/bin/env node
2
- import { Command } from "commander";
3
- import pc from "picocolors";
4
- import { createInterface, emitKeypressEvents } from "node:readline";
5
- import { stdin as input, stdout as output } from "node:process";
6
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
- import { homedir } from "node:os";
8
- import { basename, join } from "node:path";
9
- import { pathToFileURL } from "node:url";
10
- import { checkPrerequisites, displayPrerequisites, displayLlmStatus } from "./utils/prerequisites.js";
11
- import { checkAuthGuard } from "./utils/auth-guard.js";
12
- import { warn } from "./utils/display.js";
13
- import { registerCleanupHandlers, setReplMode } from './utils/cleanup.js';
14
- import { findWorkspaceRoot, readManifest } from './manifest/reader.js';
15
- const APP_VERSION = "0.1.0";
16
- const BASE_PROMPT = "kitt";
17
- const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
18
- const UPDATE_CHECK_TIMEOUT_MS = 5_000;
19
- const STATE_CHANGING_COMMANDS = new Set([
20
- "init",
21
- "create",
22
- "delete",
23
- "deploy",
24
- "deploy:template",
25
- "env:create",
26
- "env:vars",
27
- "domain",
28
- "publish",
29
- ]);
30
- const KITT_DIR = join(homedir(), ".kitt");
31
- const UPDATE_CHECK_FILE = join(KITT_DIR, "update-check.json");
32
- const commandRegistry = {
33
- init: { modulePath: "./commands/init.js" },
34
- create: { modulePath: "./commands/create.js" },
35
- delete: { modulePath: "./commands/delete.js" },
36
- deploy: { modulePath: "./commands/deploy.js" },
37
- "deploy:template": { modulePath: "./commands/deploy.js" },
38
- "env:create": { modulePath: "./commands/env.js" },
39
- "env:vars": { modulePath: "./commands/env.js" },
40
- domain: { modulePath: "./commands/domain.js" },
41
- logs: { modulePath: "./commands/logs.js" },
42
- status: { modulePath: "./commands/status.js" },
43
- login: { modulePath: "./commands/login.js" },
44
- logout: { modulePath: "./commands/login.js" },
45
- settings: { modulePath: "./commands/settings.js" },
46
- versions: { modulePath: "./commands/versions.js" },
47
- list: { modulePath: "./commands/list.js" },
48
- run: { modulePath: "./commands/run.js" },
49
- publish: { modulePath: './commands/publish.js' },
50
- help: { modulePath: "./commands/help.js" }
2
+ import { createRequire } from "node:module";
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __toESM = (mod, isNodeMode, target) => {
9
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
10
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
+ for (let key of __getOwnPropNames(mod))
12
+ if (!__hasOwnProp.call(to, key))
13
+ __defProp(to, key, {
14
+ get: () => mod[key],
15
+ enumerable: true
16
+ });
17
+ return to;
51
18
  };
52
- function displayBanner() {
53
- console.log(pc.cyan(' ______ _______________________'));
54
- console.log(pc.cyan(' ___ //_/___ /__ __/__ __/'));
55
- console.log(pc.cyan(' __ ,< __ / __ / __ / '));
56
- console.log(pc.cyan(' _ /| | __/ / _ / _ / '));
57
- console.log(pc.cyan(' /_/ |_| /___/ /_/ /_/ '));
58
- console.log('');
59
- console.log(` ${pc.bold(pc.white('KITT'))} ${pc.dim('v' + APP_VERSION)} ${pc.dim('— AI-Powered App Scaffolding CLI')}`);
60
- console.log(` ${pc.dim('/login → /init → /create → /deploy → /publish')}`);
61
- console.log(` ${pc.dim('Type /help for all commands')}`);
62
- console.log('');
63
- }
64
- function tokenizeCommand(inputValue) {
65
- const tokenPattern = /"([^"]*)"|'([^']*)'|`([^`]*)`|(\S+)/g;
66
- const tokens = [];
67
- let match = tokenPattern.exec(inputValue);
68
- while (match !== null) {
69
- tokens.push(match[1] ?? match[2] ?? match[3] ?? match[4]);
70
- match = tokenPattern.exec(inputValue);
19
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
+ var __export = (target, all) => {
21
+ for (var name in all)
22
+ __defProp(target, name, {
23
+ get: all[name],
24
+ enumerable: true,
25
+ configurable: true,
26
+ set: (newValue) => all[name] = () => newValue
27
+ });
28
+ };
29
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
30
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
31
+
32
+ // node_modules/commander/lib/error.js
33
+ var require_error = __commonJS((exports) => {
34
+ class CommanderError extends Error {
35
+ constructor(exitCode, code, message) {
36
+ super(message);
37
+ Error.captureStackTrace(this, this.constructor);
38
+ this.name = this.constructor.name;
39
+ this.code = code;
40
+ this.exitCode = exitCode;
41
+ this.nestedError = undefined;
71
42
  }
72
- return tokens;
73
- }
74
- function parseCommand(inputValue) {
75
- const trimmed = inputValue.trim();
76
- if (trimmed.length === 0) {
77
- return undefined;
43
+ }
44
+
45
+ class InvalidArgumentError extends CommanderError {
46
+ constructor(message) {
47
+ super(1, "commander.invalidArgument", message);
48
+ Error.captureStackTrace(this, this.constructor);
49
+ this.name = this.constructor.name;
78
50
  }
79
- const parts = tokenizeCommand(trimmed);
80
- if (parts.length === 0) {
81
- return undefined;
51
+ }
52
+ exports.CommanderError = CommanderError;
53
+ exports.InvalidArgumentError = InvalidArgumentError;
54
+ });
55
+
56
+ // node_modules/commander/lib/argument.js
57
+ var require_argument = __commonJS((exports) => {
58
+ var { InvalidArgumentError } = require_error();
59
+
60
+ class Argument {
61
+ constructor(name, description) {
62
+ this.description = description || "";
63
+ this.variadic = false;
64
+ this.parseArg = undefined;
65
+ this.defaultValue = undefined;
66
+ this.defaultValueDescription = undefined;
67
+ this.argChoices = undefined;
68
+ switch (name[0]) {
69
+ case "<":
70
+ this.required = true;
71
+ this._name = name.slice(1, -1);
72
+ break;
73
+ case "[":
74
+ this.required = false;
75
+ this._name = name.slice(1, -1);
76
+ break;
77
+ default:
78
+ this.required = true;
79
+ this._name = name;
80
+ break;
81
+ }
82
+ if (this._name.endsWith("...")) {
83
+ this.variadic = true;
84
+ this._name = this._name.slice(0, -3);
85
+ }
82
86
  }
83
- const rawCommand = parts[0];
84
- const normalized = rawCommand.startsWith("/") ? rawCommand : `/${rawCommand}`;
85
- return {
86
- key: normalized.slice(1).toLowerCase(),
87
- displayName: normalized,
88
- args: parts.slice(1)
89
- };
90
- }
91
- function isVersionNewer(latest, current) {
92
- const normalize = (value) => {
93
- const [main] = value.trim().replace(/^v/i, "").split("-");
94
- return main
95
- .split(".")
96
- .map((segment) => Number.parseInt(segment, 10))
97
- .map((segment) => (Number.isFinite(segment) ? segment : 0));
98
- };
99
- const latestParts = normalize(latest);
100
- const currentParts = normalize(current);
101
- const maxLen = Math.max(latestParts.length, currentParts.length);
102
- for (let index = 0; index < maxLen; index += 1) {
103
- const latestPart = latestParts[index] ?? 0;
104
- const currentPart = currentParts[index] ?? 0;
105
- if (latestPart > currentPart) {
106
- return true;
87
+ name() {
88
+ return this._name;
89
+ }
90
+ _collectValue(value, previous) {
91
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
92
+ return [value];
93
+ }
94
+ previous.push(value);
95
+ return previous;
96
+ }
97
+ default(value, description) {
98
+ this.defaultValue = value;
99
+ this.defaultValueDescription = description;
100
+ return this;
101
+ }
102
+ argParser(fn) {
103
+ this.parseArg = fn;
104
+ return this;
105
+ }
106
+ choices(values) {
107
+ this.argChoices = values.slice();
108
+ this.parseArg = (arg, previous) => {
109
+ if (!this.argChoices.includes(arg)) {
110
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
107
111
  }
108
- if (latestPart < currentPart) {
109
- return false;
112
+ if (this.variadic) {
113
+ return this._collectValue(arg, previous);
110
114
  }
115
+ return arg;
116
+ };
117
+ return this;
111
118
  }
112
- return false;
113
- }
114
- function hasFreshUpdateCache(now) {
115
- if (!existsSync(UPDATE_CHECK_FILE)) {
116
- return false;
119
+ argRequired() {
120
+ this.required = true;
121
+ return this;
117
122
  }
118
- try {
119
- const rawCache = readFileSync(UPDATE_CHECK_FILE, "utf-8").trim();
120
- if (rawCache.length === 0) {
121
- return false;
123
+ argOptional() {
124
+ this.required = false;
125
+ return this;
126
+ }
127
+ }
128
+ function humanReadableArgName(arg) {
129
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
130
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
131
+ }
132
+ exports.Argument = Argument;
133
+ exports.humanReadableArgName = humanReadableArgName;
134
+ });
135
+
136
+ // node_modules/commander/lib/help.js
137
+ var require_help = __commonJS((exports) => {
138
+ var { humanReadableArgName } = require_argument();
139
+
140
+ class Help {
141
+ constructor() {
142
+ this.helpWidth = undefined;
143
+ this.minWidthToWrap = 40;
144
+ this.sortSubcommands = false;
145
+ this.sortOptions = false;
146
+ this.showGlobalOptions = false;
147
+ }
148
+ prepareContext(contextOptions) {
149
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
150
+ }
151
+ visibleCommands(cmd) {
152
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
153
+ const helpCommand = cmd._getHelpCommand();
154
+ if (helpCommand && !helpCommand._hidden) {
155
+ visibleCommands.push(helpCommand);
156
+ }
157
+ if (this.sortSubcommands) {
158
+ visibleCommands.sort((a, b) => {
159
+ return a.name().localeCompare(b.name());
160
+ });
161
+ }
162
+ return visibleCommands;
163
+ }
164
+ compareOptions(a, b) {
165
+ const getSortKey = (option) => {
166
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
167
+ };
168
+ return getSortKey(a).localeCompare(getSortKey(b));
169
+ }
170
+ visibleOptions(cmd) {
171
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
172
+ const helpOption = cmd._getHelpOption();
173
+ if (helpOption && !helpOption.hidden) {
174
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
175
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
176
+ if (!removeShort && !removeLong) {
177
+ visibleOptions.push(helpOption);
178
+ } else if (helpOption.long && !removeLong) {
179
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
180
+ } else if (helpOption.short && !removeShort) {
181
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
122
182
  }
123
- const parsed = JSON.parse(rawCache);
124
- if (typeof parsed.checkedAt !== "string") {
125
- return false;
183
+ }
184
+ if (this.sortOptions) {
185
+ visibleOptions.sort(this.compareOptions);
186
+ }
187
+ return visibleOptions;
188
+ }
189
+ visibleGlobalOptions(cmd) {
190
+ if (!this.showGlobalOptions)
191
+ return [];
192
+ const globalOptions = [];
193
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
194
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
195
+ globalOptions.push(...visibleOptions);
196
+ }
197
+ if (this.sortOptions) {
198
+ globalOptions.sort(this.compareOptions);
199
+ }
200
+ return globalOptions;
201
+ }
202
+ visibleArguments(cmd) {
203
+ if (cmd._argsDescription) {
204
+ cmd.registeredArguments.forEach((argument) => {
205
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
206
+ });
207
+ }
208
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
209
+ return cmd.registeredArguments;
210
+ }
211
+ return [];
212
+ }
213
+ subcommandTerm(cmd) {
214
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
215
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
216
+ }
217
+ optionTerm(option) {
218
+ return option.flags;
219
+ }
220
+ argumentTerm(argument) {
221
+ return argument.name();
222
+ }
223
+ longestSubcommandTermLength(cmd, helper) {
224
+ return helper.visibleCommands(cmd).reduce((max, command) => {
225
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
226
+ }, 0);
227
+ }
228
+ longestOptionTermLength(cmd, helper) {
229
+ return helper.visibleOptions(cmd).reduce((max, option) => {
230
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
231
+ }, 0);
232
+ }
233
+ longestGlobalOptionTermLength(cmd, helper) {
234
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
235
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
236
+ }, 0);
237
+ }
238
+ longestArgumentTermLength(cmd, helper) {
239
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
240
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
241
+ }, 0);
242
+ }
243
+ commandUsage(cmd) {
244
+ let cmdName = cmd._name;
245
+ if (cmd._aliases[0]) {
246
+ cmdName = cmdName + "|" + cmd._aliases[0];
247
+ }
248
+ let ancestorCmdNames = "";
249
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
250
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
251
+ }
252
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
253
+ }
254
+ commandDescription(cmd) {
255
+ return cmd.description();
256
+ }
257
+ subcommandDescription(cmd) {
258
+ return cmd.summary() || cmd.description();
259
+ }
260
+ optionDescription(option) {
261
+ const extraInfo = [];
262
+ if (option.argChoices) {
263
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
264
+ }
265
+ if (option.defaultValue !== undefined) {
266
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
267
+ if (showDefault) {
268
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
126
269
  }
127
- const checkedAtMs = Date.parse(parsed.checkedAt);
128
- if (!Number.isFinite(checkedAtMs)) {
129
- return false;
270
+ }
271
+ if (option.presetArg !== undefined && option.optional) {
272
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
273
+ }
274
+ if (option.envVar !== undefined) {
275
+ extraInfo.push(`env: ${option.envVar}`);
276
+ }
277
+ if (extraInfo.length > 0) {
278
+ const extraDescription = `(${extraInfo.join(", ")})`;
279
+ if (option.description) {
280
+ return `${option.description} ${extraDescription}`;
130
281
  }
131
- return now.getTime() - checkedAtMs < UPDATE_CHECK_INTERVAL_MS;
282
+ return extraDescription;
283
+ }
284
+ return option.description;
132
285
  }
133
- catch {
134
- return false;
286
+ argumentDescription(argument) {
287
+ const extraInfo = [];
288
+ if (argument.argChoices) {
289
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
290
+ }
291
+ if (argument.defaultValue !== undefined) {
292
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
293
+ }
294
+ if (extraInfo.length > 0) {
295
+ const extraDescription = `(${extraInfo.join(", ")})`;
296
+ if (argument.description) {
297
+ return `${argument.description} ${extraDescription}`;
298
+ }
299
+ return extraDescription;
300
+ }
301
+ return argument.description;
135
302
  }
136
- }
137
- function writeUpdateCache(now, latestVersion) {
138
- mkdirSync(KITT_DIR, { recursive: true });
139
- const payload = {
140
- checkedAt: now.toISOString(),
141
- latestVersion,
142
- };
143
- writeFileSync(UPDATE_CHECK_FILE, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
144
- }
145
- export async function checkForUpdates(context) {
146
- if (context.noUpdateCheck) {
303
+ formatItemList(heading, items, helper) {
304
+ if (items.length === 0)
305
+ return [];
306
+ return [helper.styleTitle(heading), ...items, ""];
307
+ }
308
+ groupItems(unsortedItems, visibleItems, getGroup) {
309
+ const result = new Map;
310
+ unsortedItems.forEach((item) => {
311
+ const group = getGroup(item);
312
+ if (!result.has(group))
313
+ result.set(group, []);
314
+ });
315
+ visibleItems.forEach((item) => {
316
+ const group = getGroup(item);
317
+ if (!result.has(group)) {
318
+ result.set(group, []);
319
+ }
320
+ result.get(group).push(item);
321
+ });
322
+ return result;
323
+ }
324
+ formatHelp(cmd, helper) {
325
+ const termWidth = helper.padWidth(cmd, helper);
326
+ const helpWidth = helper.helpWidth ?? 80;
327
+ function callFormatItem(term, description) {
328
+ return helper.formatItem(term, termWidth, description, helper);
329
+ }
330
+ let output = [
331
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
332
+ ""
333
+ ];
334
+ const commandDescription = helper.commandDescription(cmd);
335
+ if (commandDescription.length > 0) {
336
+ output = output.concat([
337
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
338
+ ""
339
+ ]);
340
+ }
341
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
342
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
343
+ });
344
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
345
+ const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
346
+ optionGroups.forEach((options, group) => {
347
+ const optionList = options.map((option) => {
348
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
349
+ });
350
+ output = output.concat(this.formatItemList(group, optionList, helper));
351
+ });
352
+ if (helper.showGlobalOptions) {
353
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
354
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
355
+ });
356
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
357
+ }
358
+ const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
359
+ commandGroups.forEach((commands, group) => {
360
+ const commandList = commands.map((sub) => {
361
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
362
+ });
363
+ output = output.concat(this.formatItemList(group, commandList, helper));
364
+ });
365
+ return output.join(`
366
+ `);
367
+ }
368
+ displayWidth(str) {
369
+ return stripColor(str).length;
370
+ }
371
+ styleTitle(str) {
372
+ return str;
373
+ }
374
+ styleUsage(str) {
375
+ return str.split(" ").map((word) => {
376
+ if (word === "[options]")
377
+ return this.styleOptionText(word);
378
+ if (word === "[command]")
379
+ return this.styleSubcommandText(word);
380
+ if (word[0] === "[" || word[0] === "<")
381
+ return this.styleArgumentText(word);
382
+ return this.styleCommandText(word);
383
+ }).join(" ");
384
+ }
385
+ styleCommandDescription(str) {
386
+ return this.styleDescriptionText(str);
387
+ }
388
+ styleOptionDescription(str) {
389
+ return this.styleDescriptionText(str);
390
+ }
391
+ styleSubcommandDescription(str) {
392
+ return this.styleDescriptionText(str);
393
+ }
394
+ styleArgumentDescription(str) {
395
+ return this.styleDescriptionText(str);
396
+ }
397
+ styleDescriptionText(str) {
398
+ return str;
399
+ }
400
+ styleOptionTerm(str) {
401
+ return this.styleOptionText(str);
402
+ }
403
+ styleSubcommandTerm(str) {
404
+ return str.split(" ").map((word) => {
405
+ if (word === "[options]")
406
+ return this.styleOptionText(word);
407
+ if (word[0] === "[" || word[0] === "<")
408
+ return this.styleArgumentText(word);
409
+ return this.styleSubcommandText(word);
410
+ }).join(" ");
411
+ }
412
+ styleArgumentTerm(str) {
413
+ return this.styleArgumentText(str);
414
+ }
415
+ styleOptionText(str) {
416
+ return str;
417
+ }
418
+ styleArgumentText(str) {
419
+ return str;
420
+ }
421
+ styleSubcommandText(str) {
422
+ return str;
423
+ }
424
+ styleCommandText(str) {
425
+ return str;
426
+ }
427
+ padWidth(cmd, helper) {
428
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
429
+ }
430
+ preformatted(str) {
431
+ return /\n[^\S\r\n]/.test(str);
432
+ }
433
+ formatItem(term, termWidth, description, helper) {
434
+ const itemIndent = 2;
435
+ const itemIndentStr = " ".repeat(itemIndent);
436
+ if (!description)
437
+ return itemIndentStr + term;
438
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
439
+ const spacerWidth = 2;
440
+ const helpWidth = this.helpWidth ?? 80;
441
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
442
+ let formattedDescription;
443
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
444
+ formattedDescription = description;
445
+ } else {
446
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
447
+ formattedDescription = wrappedDescription.replace(/\n/g, `
448
+ ` + " ".repeat(termWidth + spacerWidth));
449
+ }
450
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
451
+ ${itemIndentStr}`);
452
+ }
453
+ boxWrap(str, width) {
454
+ if (width < this.minWidthToWrap)
455
+ return str;
456
+ const rawLines = str.split(/\r\n|\n/);
457
+ const chunkPattern = /[\s]*[^\s]+/g;
458
+ const wrappedLines = [];
459
+ rawLines.forEach((line) => {
460
+ const chunks = line.match(chunkPattern);
461
+ if (chunks === null) {
462
+ wrappedLines.push("");
463
+ return;
464
+ }
465
+ let sumChunks = [chunks.shift()];
466
+ let sumWidth = this.displayWidth(sumChunks[0]);
467
+ chunks.forEach((chunk) => {
468
+ const visibleWidth = this.displayWidth(chunk);
469
+ if (sumWidth + visibleWidth <= width) {
470
+ sumChunks.push(chunk);
471
+ sumWidth += visibleWidth;
472
+ return;
473
+ }
474
+ wrappedLines.push(sumChunks.join(""));
475
+ const nextChunk = chunk.trimStart();
476
+ sumChunks = [nextChunk];
477
+ sumWidth = this.displayWidth(nextChunk);
478
+ });
479
+ wrappedLines.push(sumChunks.join(""));
480
+ });
481
+ return wrappedLines.join(`
482
+ `);
483
+ }
484
+ }
485
+ function stripColor(str) {
486
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
487
+ return str.replace(sgrPattern, "");
488
+ }
489
+ exports.Help = Help;
490
+ exports.stripColor = stripColor;
491
+ });
492
+
493
+ // node_modules/commander/lib/option.js
494
+ var require_option = __commonJS((exports) => {
495
+ var { InvalidArgumentError } = require_error();
496
+
497
+ class Option {
498
+ constructor(flags, description) {
499
+ this.flags = flags;
500
+ this.description = description || "";
501
+ this.required = flags.includes("<");
502
+ this.optional = flags.includes("[");
503
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
504
+ this.mandatory = false;
505
+ const optionFlags = splitOptionFlags(flags);
506
+ this.short = optionFlags.shortFlag;
507
+ this.long = optionFlags.longFlag;
508
+ this.negate = false;
509
+ if (this.long) {
510
+ this.negate = this.long.startsWith("--no-");
511
+ }
512
+ this.defaultValue = undefined;
513
+ this.defaultValueDescription = undefined;
514
+ this.presetArg = undefined;
515
+ this.envVar = undefined;
516
+ this.parseArg = undefined;
517
+ this.hidden = false;
518
+ this.argChoices = undefined;
519
+ this.conflictsWith = [];
520
+ this.implied = undefined;
521
+ this.helpGroupHeading = undefined;
522
+ }
523
+ default(value, description) {
524
+ this.defaultValue = value;
525
+ this.defaultValueDescription = description;
526
+ return this;
527
+ }
528
+ preset(arg) {
529
+ this.presetArg = arg;
530
+ return this;
531
+ }
532
+ conflicts(names) {
533
+ this.conflictsWith = this.conflictsWith.concat(names);
534
+ return this;
535
+ }
536
+ implies(impliedOptionValues) {
537
+ let newImplied = impliedOptionValues;
538
+ if (typeof impliedOptionValues === "string") {
539
+ newImplied = { [impliedOptionValues]: true };
540
+ }
541
+ this.implied = Object.assign(this.implied || {}, newImplied);
542
+ return this;
543
+ }
544
+ env(name) {
545
+ this.envVar = name;
546
+ return this;
547
+ }
548
+ argParser(fn) {
549
+ this.parseArg = fn;
550
+ return this;
551
+ }
552
+ makeOptionMandatory(mandatory = true) {
553
+ this.mandatory = !!mandatory;
554
+ return this;
555
+ }
556
+ hideHelp(hide = true) {
557
+ this.hidden = !!hide;
558
+ return this;
559
+ }
560
+ _collectValue(value, previous) {
561
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
562
+ return [value];
563
+ }
564
+ previous.push(value);
565
+ return previous;
566
+ }
567
+ choices(values) {
568
+ this.argChoices = values.slice();
569
+ this.parseArg = (arg, previous) => {
570
+ if (!this.argChoices.includes(arg)) {
571
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
572
+ }
573
+ if (this.variadic) {
574
+ return this._collectValue(arg, previous);
575
+ }
576
+ return arg;
577
+ };
578
+ return this;
579
+ }
580
+ name() {
581
+ if (this.long) {
582
+ return this.long.replace(/^--/, "");
583
+ }
584
+ return this.short.replace(/^-/, "");
585
+ }
586
+ attributeName() {
587
+ if (this.negate) {
588
+ return camelcase(this.name().replace(/^no-/, ""));
589
+ }
590
+ return camelcase(this.name());
591
+ }
592
+ helpGroup(heading) {
593
+ this.helpGroupHeading = heading;
594
+ return this;
595
+ }
596
+ is(arg) {
597
+ return this.short === arg || this.long === arg;
598
+ }
599
+ isBoolean() {
600
+ return !this.required && !this.optional && !this.negate;
601
+ }
602
+ }
603
+
604
+ class DualOptions {
605
+ constructor(options) {
606
+ this.positiveOptions = new Map;
607
+ this.negativeOptions = new Map;
608
+ this.dualOptions = new Set;
609
+ options.forEach((option) => {
610
+ if (option.negate) {
611
+ this.negativeOptions.set(option.attributeName(), option);
612
+ } else {
613
+ this.positiveOptions.set(option.attributeName(), option);
614
+ }
615
+ });
616
+ this.negativeOptions.forEach((value, key) => {
617
+ if (this.positiveOptions.has(key)) {
618
+ this.dualOptions.add(key);
619
+ }
620
+ });
621
+ }
622
+ valueFromOption(value, option) {
623
+ const optionKey = option.attributeName();
624
+ if (!this.dualOptions.has(optionKey))
625
+ return true;
626
+ const preset = this.negativeOptions.get(optionKey).presetArg;
627
+ const negativeValue = preset !== undefined ? preset : false;
628
+ return option.negate === (negativeValue === value);
629
+ }
630
+ }
631
+ function camelcase(str) {
632
+ return str.split("-").reduce((str2, word) => {
633
+ return str2 + word[0].toUpperCase() + word.slice(1);
634
+ });
635
+ }
636
+ function splitOptionFlags(flags) {
637
+ let shortFlag;
638
+ let longFlag;
639
+ const shortFlagExp = /^-[^-]$/;
640
+ const longFlagExp = /^--[^-]/;
641
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
642
+ if (shortFlagExp.test(flagParts[0]))
643
+ shortFlag = flagParts.shift();
644
+ if (longFlagExp.test(flagParts[0]))
645
+ longFlag = flagParts.shift();
646
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
647
+ shortFlag = flagParts.shift();
648
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
649
+ shortFlag = longFlag;
650
+ longFlag = flagParts.shift();
651
+ }
652
+ if (flagParts[0].startsWith("-")) {
653
+ const unsupportedFlag = flagParts[0];
654
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
655
+ if (/^-[^-][^-]/.test(unsupportedFlag))
656
+ throw new Error(`${baseError}
657
+ - a short flag is a single dash and a single character
658
+ - either use a single dash and a single character (for a short flag)
659
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
660
+ if (shortFlagExp.test(unsupportedFlag))
661
+ throw new Error(`${baseError}
662
+ - too many short flags`);
663
+ if (longFlagExp.test(unsupportedFlag))
664
+ throw new Error(`${baseError}
665
+ - too many long flags`);
666
+ throw new Error(`${baseError}
667
+ - unrecognised flag format`);
668
+ }
669
+ if (shortFlag === undefined && longFlag === undefined)
670
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
671
+ return { shortFlag, longFlag };
672
+ }
673
+ exports.Option = Option;
674
+ exports.DualOptions = DualOptions;
675
+ });
676
+
677
+ // node_modules/commander/lib/suggestSimilar.js
678
+ var require_suggestSimilar = __commonJS((exports) => {
679
+ var maxDistance = 3;
680
+ function editDistance(a, b) {
681
+ if (Math.abs(a.length - b.length) > maxDistance)
682
+ return Math.max(a.length, b.length);
683
+ const d = [];
684
+ for (let i = 0;i <= a.length; i++) {
685
+ d[i] = [i];
686
+ }
687
+ for (let j = 0;j <= b.length; j++) {
688
+ d[0][j] = j;
689
+ }
690
+ for (let j = 1;j <= b.length; j++) {
691
+ for (let i = 1;i <= a.length; i++) {
692
+ let cost = 1;
693
+ if (a[i - 1] === b[j - 1]) {
694
+ cost = 0;
695
+ } else {
696
+ cost = 1;
697
+ }
698
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
699
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
700
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
701
+ }
702
+ }
703
+ }
704
+ return d[a.length][b.length];
705
+ }
706
+ function suggestSimilar(word, candidates) {
707
+ if (!candidates || candidates.length === 0)
708
+ return "";
709
+ candidates = Array.from(new Set(candidates));
710
+ const searchingOptions = word.startsWith("--");
711
+ if (searchingOptions) {
712
+ word = word.slice(2);
713
+ candidates = candidates.map((candidate) => candidate.slice(2));
714
+ }
715
+ let similar = [];
716
+ let bestDistance = maxDistance;
717
+ const minSimilarity = 0.4;
718
+ candidates.forEach((candidate) => {
719
+ if (candidate.length <= 1)
720
+ return;
721
+ const distance = editDistance(word, candidate);
722
+ const length = Math.max(word.length, candidate.length);
723
+ const similarity = (length - distance) / length;
724
+ if (similarity > minSimilarity) {
725
+ if (distance < bestDistance) {
726
+ bestDistance = distance;
727
+ similar = [candidate];
728
+ } else if (distance === bestDistance) {
729
+ similar.push(candidate);
730
+ }
731
+ }
732
+ });
733
+ similar.sort((a, b) => a.localeCompare(b));
734
+ if (searchingOptions) {
735
+ similar = similar.map((candidate) => `--${candidate}`);
736
+ }
737
+ if (similar.length > 1) {
738
+ return `
739
+ (Did you mean one of ${similar.join(", ")}?)`;
740
+ }
741
+ if (similar.length === 1) {
742
+ return `
743
+ (Did you mean ${similar[0]}?)`;
744
+ }
745
+ return "";
746
+ }
747
+ exports.suggestSimilar = suggestSimilar;
748
+ });
749
+
750
+ // node_modules/commander/lib/command.js
751
+ var require_command = __commonJS((exports) => {
752
+ var EventEmitter = __require("node:events").EventEmitter;
753
+ var childProcess = __require("node:child_process");
754
+ var path = __require("node:path");
755
+ var fs = __require("node:fs");
756
+ var process2 = __require("node:process");
757
+ var { Argument, humanReadableArgName } = require_argument();
758
+ var { CommanderError } = require_error();
759
+ var { Help, stripColor } = require_help();
760
+ var { Option, DualOptions } = require_option();
761
+ var { suggestSimilar } = require_suggestSimilar();
762
+
763
+ class Command extends EventEmitter {
764
+ constructor(name) {
765
+ super();
766
+ this.commands = [];
767
+ this.options = [];
768
+ this.parent = null;
769
+ this._allowUnknownOption = false;
770
+ this._allowExcessArguments = false;
771
+ this.registeredArguments = [];
772
+ this._args = this.registeredArguments;
773
+ this.args = [];
774
+ this.rawArgs = [];
775
+ this.processedArgs = [];
776
+ this._scriptPath = null;
777
+ this._name = name || "";
778
+ this._optionValues = {};
779
+ this._optionValueSources = {};
780
+ this._storeOptionsAsProperties = false;
781
+ this._actionHandler = null;
782
+ this._executableHandler = false;
783
+ this._executableFile = null;
784
+ this._executableDir = null;
785
+ this._defaultCommandName = null;
786
+ this._exitCallback = null;
787
+ this._aliases = [];
788
+ this._combineFlagAndOptionalValue = true;
789
+ this._description = "";
790
+ this._summary = "";
791
+ this._argsDescription = undefined;
792
+ this._enablePositionalOptions = false;
793
+ this._passThroughOptions = false;
794
+ this._lifeCycleHooks = {};
795
+ this._showHelpAfterError = false;
796
+ this._showSuggestionAfterError = true;
797
+ this._savedState = null;
798
+ this._outputConfiguration = {
799
+ writeOut: (str) => process2.stdout.write(str),
800
+ writeErr: (str) => process2.stderr.write(str),
801
+ outputError: (str, write) => write(str),
802
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
803
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
804
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
805
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
806
+ stripColor: (str) => stripColor(str)
807
+ };
808
+ this._hidden = false;
809
+ this._helpOption = undefined;
810
+ this._addImplicitHelpCommand = undefined;
811
+ this._helpCommand = undefined;
812
+ this._helpConfiguration = {};
813
+ this._helpGroupHeading = undefined;
814
+ this._defaultCommandGroup = undefined;
815
+ this._defaultOptionGroup = undefined;
816
+ }
817
+ copyInheritedSettings(sourceCommand) {
818
+ this._outputConfiguration = sourceCommand._outputConfiguration;
819
+ this._helpOption = sourceCommand._helpOption;
820
+ this._helpCommand = sourceCommand._helpCommand;
821
+ this._helpConfiguration = sourceCommand._helpConfiguration;
822
+ this._exitCallback = sourceCommand._exitCallback;
823
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
824
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
825
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
826
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
827
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
828
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
829
+ return this;
830
+ }
831
+ _getCommandAndAncestors() {
832
+ const result = [];
833
+ for (let command = this;command; command = command.parent) {
834
+ result.push(command);
835
+ }
836
+ return result;
837
+ }
838
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
839
+ let desc = actionOptsOrExecDesc;
840
+ let opts = execOpts;
841
+ if (typeof desc === "object" && desc !== null) {
842
+ opts = desc;
843
+ desc = null;
844
+ }
845
+ opts = opts || {};
846
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
847
+ const cmd = this.createCommand(name);
848
+ if (desc) {
849
+ cmd.description(desc);
850
+ cmd._executableHandler = true;
851
+ }
852
+ if (opts.isDefault)
853
+ this._defaultCommandName = cmd._name;
854
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
855
+ cmd._executableFile = opts.executableFile || null;
856
+ if (args)
857
+ cmd.arguments(args);
858
+ this._registerCommand(cmd);
859
+ cmd.parent = this;
860
+ cmd.copyInheritedSettings(this);
861
+ if (desc)
862
+ return this;
863
+ return cmd;
864
+ }
865
+ createCommand(name) {
866
+ return new Command(name);
867
+ }
868
+ createHelp() {
869
+ return Object.assign(new Help, this.configureHelp());
870
+ }
871
+ configureHelp(configuration) {
872
+ if (configuration === undefined)
873
+ return this._helpConfiguration;
874
+ this._helpConfiguration = configuration;
875
+ return this;
876
+ }
877
+ configureOutput(configuration) {
878
+ if (configuration === undefined)
879
+ return this._outputConfiguration;
880
+ this._outputConfiguration = {
881
+ ...this._outputConfiguration,
882
+ ...configuration
883
+ };
884
+ return this;
885
+ }
886
+ showHelpAfterError(displayHelp = true) {
887
+ if (typeof displayHelp !== "string")
888
+ displayHelp = !!displayHelp;
889
+ this._showHelpAfterError = displayHelp;
890
+ return this;
891
+ }
892
+ showSuggestionAfterError(displaySuggestion = true) {
893
+ this._showSuggestionAfterError = !!displaySuggestion;
894
+ return this;
895
+ }
896
+ addCommand(cmd, opts) {
897
+ if (!cmd._name) {
898
+ throw new Error(`Command passed to .addCommand() must have a name
899
+ - specify the name in Command constructor or using .name()`);
900
+ }
901
+ opts = opts || {};
902
+ if (opts.isDefault)
903
+ this._defaultCommandName = cmd._name;
904
+ if (opts.noHelp || opts.hidden)
905
+ cmd._hidden = true;
906
+ this._registerCommand(cmd);
907
+ cmd.parent = this;
908
+ cmd._checkForBrokenPassThrough();
909
+ return this;
910
+ }
911
+ createArgument(name, description) {
912
+ return new Argument(name, description);
913
+ }
914
+ argument(name, description, parseArg, defaultValue) {
915
+ const argument = this.createArgument(name, description);
916
+ if (typeof parseArg === "function") {
917
+ argument.default(defaultValue).argParser(parseArg);
918
+ } else {
919
+ argument.default(parseArg);
920
+ }
921
+ this.addArgument(argument);
922
+ return this;
923
+ }
924
+ arguments(names) {
925
+ names.trim().split(/ +/).forEach((detail) => {
926
+ this.argument(detail);
927
+ });
928
+ return this;
929
+ }
930
+ addArgument(argument) {
931
+ const previousArgument = this.registeredArguments.slice(-1)[0];
932
+ if (previousArgument?.variadic) {
933
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
934
+ }
935
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
936
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
937
+ }
938
+ this.registeredArguments.push(argument);
939
+ return this;
940
+ }
941
+ helpCommand(enableOrNameAndArgs, description) {
942
+ if (typeof enableOrNameAndArgs === "boolean") {
943
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
944
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
945
+ this._initCommandGroup(this._getHelpCommand());
946
+ }
947
+ return this;
948
+ }
949
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
950
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
951
+ const helpDescription = description ?? "display help for command";
952
+ const helpCommand = this.createCommand(helpName);
953
+ helpCommand.helpOption(false);
954
+ if (helpArgs)
955
+ helpCommand.arguments(helpArgs);
956
+ if (helpDescription)
957
+ helpCommand.description(helpDescription);
958
+ this._addImplicitHelpCommand = true;
959
+ this._helpCommand = helpCommand;
960
+ if (enableOrNameAndArgs || description)
961
+ this._initCommandGroup(helpCommand);
962
+ return this;
963
+ }
964
+ addHelpCommand(helpCommand, deprecatedDescription) {
965
+ if (typeof helpCommand !== "object") {
966
+ this.helpCommand(helpCommand, deprecatedDescription);
967
+ return this;
968
+ }
969
+ this._addImplicitHelpCommand = true;
970
+ this._helpCommand = helpCommand;
971
+ this._initCommandGroup(helpCommand);
972
+ return this;
973
+ }
974
+ _getHelpCommand() {
975
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
976
+ if (hasImplicitHelpCommand) {
977
+ if (this._helpCommand === undefined) {
978
+ this.helpCommand(undefined, undefined);
979
+ }
980
+ return this._helpCommand;
981
+ }
982
+ return null;
983
+ }
984
+ hook(event, listener) {
985
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
986
+ if (!allowedValues.includes(event)) {
987
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
988
+ Expecting one of '${allowedValues.join("', '")}'`);
989
+ }
990
+ if (this._lifeCycleHooks[event]) {
991
+ this._lifeCycleHooks[event].push(listener);
992
+ } else {
993
+ this._lifeCycleHooks[event] = [listener];
994
+ }
995
+ return this;
996
+ }
997
+ exitOverride(fn) {
998
+ if (fn) {
999
+ this._exitCallback = fn;
1000
+ } else {
1001
+ this._exitCallback = (err) => {
1002
+ if (err.code !== "commander.executeSubCommandAsync") {
1003
+ throw err;
1004
+ } else {}
1005
+ };
1006
+ }
1007
+ return this;
1008
+ }
1009
+ _exit(exitCode, code, message) {
1010
+ if (this._exitCallback) {
1011
+ this._exitCallback(new CommanderError(exitCode, code, message));
1012
+ }
1013
+ process2.exit(exitCode);
1014
+ }
1015
+ action(fn) {
1016
+ const listener = (args) => {
1017
+ const expectedArgsCount = this.registeredArguments.length;
1018
+ const actionArgs = args.slice(0, expectedArgsCount);
1019
+ if (this._storeOptionsAsProperties) {
1020
+ actionArgs[expectedArgsCount] = this;
1021
+ } else {
1022
+ actionArgs[expectedArgsCount] = this.opts();
1023
+ }
1024
+ actionArgs.push(this);
1025
+ return fn.apply(this, actionArgs);
1026
+ };
1027
+ this._actionHandler = listener;
1028
+ return this;
1029
+ }
1030
+ createOption(flags, description) {
1031
+ return new Option(flags, description);
1032
+ }
1033
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1034
+ try {
1035
+ return target.parseArg(value, previous);
1036
+ } catch (err) {
1037
+ if (err.code === "commander.invalidArgument") {
1038
+ const message = `${invalidArgumentMessage} ${err.message}`;
1039
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1040
+ }
1041
+ throw err;
1042
+ }
1043
+ }
1044
+ _registerOption(option) {
1045
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1046
+ if (matchingOption) {
1047
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1048
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1049
+ - already used by option '${matchingOption.flags}'`);
1050
+ }
1051
+ this._initOptionGroup(option);
1052
+ this.options.push(option);
1053
+ }
1054
+ _registerCommand(command) {
1055
+ const knownBy = (cmd) => {
1056
+ return [cmd.name()].concat(cmd.aliases());
1057
+ };
1058
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1059
+ if (alreadyUsed) {
1060
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1061
+ const newCmd = knownBy(command).join("|");
1062
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1063
+ }
1064
+ this._initCommandGroup(command);
1065
+ this.commands.push(command);
1066
+ }
1067
+ addOption(option) {
1068
+ this._registerOption(option);
1069
+ const oname = option.name();
1070
+ const name = option.attributeName();
1071
+ if (option.negate) {
1072
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1073
+ if (!this._findOption(positiveLongFlag)) {
1074
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1075
+ }
1076
+ } else if (option.defaultValue !== undefined) {
1077
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1078
+ }
1079
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1080
+ if (val == null && option.presetArg !== undefined) {
1081
+ val = option.presetArg;
1082
+ }
1083
+ const oldValue = this.getOptionValue(name);
1084
+ if (val !== null && option.parseArg) {
1085
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1086
+ } else if (val !== null && option.variadic) {
1087
+ val = option._collectValue(val, oldValue);
1088
+ }
1089
+ if (val == null) {
1090
+ if (option.negate) {
1091
+ val = false;
1092
+ } else if (option.isBoolean() || option.optional) {
1093
+ val = true;
1094
+ } else {
1095
+ val = "";
1096
+ }
1097
+ }
1098
+ this.setOptionValueWithSource(name, val, valueSource);
1099
+ };
1100
+ this.on("option:" + oname, (val) => {
1101
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1102
+ handleOptionValue(val, invalidValueMessage, "cli");
1103
+ });
1104
+ if (option.envVar) {
1105
+ this.on("optionEnv:" + oname, (val) => {
1106
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1107
+ handleOptionValue(val, invalidValueMessage, "env");
1108
+ });
1109
+ }
1110
+ return this;
1111
+ }
1112
+ _optionEx(config, flags, description, fn, defaultValue) {
1113
+ if (typeof flags === "object" && flags instanceof Option) {
1114
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1115
+ }
1116
+ const option = this.createOption(flags, description);
1117
+ option.makeOptionMandatory(!!config.mandatory);
1118
+ if (typeof fn === "function") {
1119
+ option.default(defaultValue).argParser(fn);
1120
+ } else if (fn instanceof RegExp) {
1121
+ const regex = fn;
1122
+ fn = (val, def) => {
1123
+ const m = regex.exec(val);
1124
+ return m ? m[0] : def;
1125
+ };
1126
+ option.default(defaultValue).argParser(fn);
1127
+ } else {
1128
+ option.default(fn);
1129
+ }
1130
+ return this.addOption(option);
1131
+ }
1132
+ option(flags, description, parseArg, defaultValue) {
1133
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1134
+ }
1135
+ requiredOption(flags, description, parseArg, defaultValue) {
1136
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1137
+ }
1138
+ combineFlagAndOptionalValue(combine = true) {
1139
+ this._combineFlagAndOptionalValue = !!combine;
1140
+ return this;
1141
+ }
1142
+ allowUnknownOption(allowUnknown = true) {
1143
+ this._allowUnknownOption = !!allowUnknown;
1144
+ return this;
1145
+ }
1146
+ allowExcessArguments(allowExcess = true) {
1147
+ this._allowExcessArguments = !!allowExcess;
1148
+ return this;
1149
+ }
1150
+ enablePositionalOptions(positional = true) {
1151
+ this._enablePositionalOptions = !!positional;
1152
+ return this;
1153
+ }
1154
+ passThroughOptions(passThrough = true) {
1155
+ this._passThroughOptions = !!passThrough;
1156
+ this._checkForBrokenPassThrough();
1157
+ return this;
1158
+ }
1159
+ _checkForBrokenPassThrough() {
1160
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1161
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1162
+ }
1163
+ }
1164
+ storeOptionsAsProperties(storeAsProperties = true) {
1165
+ if (this.options.length) {
1166
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1167
+ }
1168
+ if (Object.keys(this._optionValues).length) {
1169
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1170
+ }
1171
+ this._storeOptionsAsProperties = !!storeAsProperties;
1172
+ return this;
1173
+ }
1174
+ getOptionValue(key) {
1175
+ if (this._storeOptionsAsProperties) {
1176
+ return this[key];
1177
+ }
1178
+ return this._optionValues[key];
1179
+ }
1180
+ setOptionValue(key, value) {
1181
+ return this.setOptionValueWithSource(key, value, undefined);
1182
+ }
1183
+ setOptionValueWithSource(key, value, source) {
1184
+ if (this._storeOptionsAsProperties) {
1185
+ this[key] = value;
1186
+ } else {
1187
+ this._optionValues[key] = value;
1188
+ }
1189
+ this._optionValueSources[key] = source;
1190
+ return this;
1191
+ }
1192
+ getOptionValueSource(key) {
1193
+ return this._optionValueSources[key];
1194
+ }
1195
+ getOptionValueSourceWithGlobals(key) {
1196
+ let source;
1197
+ this._getCommandAndAncestors().forEach((cmd) => {
1198
+ if (cmd.getOptionValueSource(key) !== undefined) {
1199
+ source = cmd.getOptionValueSource(key);
1200
+ }
1201
+ });
1202
+ return source;
1203
+ }
1204
+ _prepareUserArgs(argv, parseOptions) {
1205
+ if (argv !== undefined && !Array.isArray(argv)) {
1206
+ throw new Error("first parameter to parse must be array or undefined");
1207
+ }
1208
+ parseOptions = parseOptions || {};
1209
+ if (argv === undefined && parseOptions.from === undefined) {
1210
+ if (process2.versions?.electron) {
1211
+ parseOptions.from = "electron";
1212
+ }
1213
+ const execArgv = process2.execArgv ?? [];
1214
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1215
+ parseOptions.from = "eval";
1216
+ }
1217
+ }
1218
+ if (argv === undefined) {
1219
+ argv = process2.argv;
1220
+ }
1221
+ this.rawArgs = argv.slice();
1222
+ let userArgs;
1223
+ switch (parseOptions.from) {
1224
+ case undefined:
1225
+ case "node":
1226
+ this._scriptPath = argv[1];
1227
+ userArgs = argv.slice(2);
1228
+ break;
1229
+ case "electron":
1230
+ if (process2.defaultApp) {
1231
+ this._scriptPath = argv[1];
1232
+ userArgs = argv.slice(2);
1233
+ } else {
1234
+ userArgs = argv.slice(1);
1235
+ }
1236
+ break;
1237
+ case "user":
1238
+ userArgs = argv.slice(0);
1239
+ break;
1240
+ case "eval":
1241
+ userArgs = argv.slice(1);
1242
+ break;
1243
+ default:
1244
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1245
+ }
1246
+ if (!this._name && this._scriptPath)
1247
+ this.nameFromFilename(this._scriptPath);
1248
+ this._name = this._name || "program";
1249
+ return userArgs;
1250
+ }
1251
+ parse(argv, parseOptions) {
1252
+ this._prepareForParse();
1253
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1254
+ this._parseCommand([], userArgs);
1255
+ return this;
1256
+ }
1257
+ async parseAsync(argv, parseOptions) {
1258
+ this._prepareForParse();
1259
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1260
+ await this._parseCommand([], userArgs);
1261
+ return this;
1262
+ }
1263
+ _prepareForParse() {
1264
+ if (this._savedState === null) {
1265
+ this.saveStateBeforeParse();
1266
+ } else {
1267
+ this.restoreStateBeforeParse();
1268
+ }
1269
+ }
1270
+ saveStateBeforeParse() {
1271
+ this._savedState = {
1272
+ _name: this._name,
1273
+ _optionValues: { ...this._optionValues },
1274
+ _optionValueSources: { ...this._optionValueSources }
1275
+ };
1276
+ }
1277
+ restoreStateBeforeParse() {
1278
+ if (this._storeOptionsAsProperties)
1279
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1280
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1281
+ this._name = this._savedState._name;
1282
+ this._scriptPath = null;
1283
+ this.rawArgs = [];
1284
+ this._optionValues = { ...this._savedState._optionValues };
1285
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1286
+ this.args = [];
1287
+ this.processedArgs = [];
1288
+ }
1289
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1290
+ if (fs.existsSync(executableFile))
147
1291
  return;
1292
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1293
+ const executableMissing = `'${executableFile}' does not exist
1294
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1295
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1296
+ - ${executableDirMessage}`;
1297
+ throw new Error(executableMissing);
148
1298
  }
149
- const now = new Date();
150
- if (hasFreshUpdateCache(now)) {
1299
+ _executeSubCommand(subcommand, args) {
1300
+ args = args.slice();
1301
+ let launchWithNode = false;
1302
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1303
+ function findFile(baseDir, baseName) {
1304
+ const localBin = path.resolve(baseDir, baseName);
1305
+ if (fs.existsSync(localBin))
1306
+ return localBin;
1307
+ if (sourceExt.includes(path.extname(baseName)))
1308
+ return;
1309
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1310
+ if (foundExt)
1311
+ return `${localBin}${foundExt}`;
151
1312
  return;
1313
+ }
1314
+ this._checkForMissingMandatoryOptions();
1315
+ this._checkForConflictingOptions();
1316
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1317
+ let executableDir = this._executableDir || "";
1318
+ if (this._scriptPath) {
1319
+ let resolvedScriptPath;
1320
+ try {
1321
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1322
+ } catch {
1323
+ resolvedScriptPath = this._scriptPath;
1324
+ }
1325
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1326
+ }
1327
+ if (executableDir) {
1328
+ let localFile = findFile(executableDir, executableFile);
1329
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1330
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1331
+ if (legacyName !== this._name) {
1332
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1333
+ }
1334
+ }
1335
+ executableFile = localFile || executableFile;
1336
+ }
1337
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1338
+ let proc;
1339
+ if (process2.platform !== "win32") {
1340
+ if (launchWithNode) {
1341
+ args.unshift(executableFile);
1342
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1343
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1344
+ } else {
1345
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1346
+ }
1347
+ } else {
1348
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1349
+ args.unshift(executableFile);
1350
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1351
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1352
+ }
1353
+ if (!proc.killed) {
1354
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1355
+ signals.forEach((signal) => {
1356
+ process2.on(signal, () => {
1357
+ if (proc.killed === false && proc.exitCode === null) {
1358
+ proc.kill(signal);
1359
+ }
1360
+ });
1361
+ });
1362
+ }
1363
+ const exitCallback = this._exitCallback;
1364
+ proc.on("close", (code) => {
1365
+ code = code ?? 1;
1366
+ if (!exitCallback) {
1367
+ process2.exit(code);
1368
+ } else {
1369
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1370
+ }
1371
+ });
1372
+ proc.on("error", (err) => {
1373
+ if (err.code === "ENOENT") {
1374
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1375
+ } else if (err.code === "EACCES") {
1376
+ throw new Error(`'${executableFile}' not executable`);
1377
+ }
1378
+ if (!exitCallback) {
1379
+ process2.exit(1);
1380
+ } else {
1381
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1382
+ wrappedError.nestedError = err;
1383
+ exitCallback(wrappedError);
1384
+ }
1385
+ });
1386
+ this.runningCommand = proc;
152
1387
  }
153
- const controller = new AbortController();
154
- const timeoutId = setTimeout(() => {
155
- controller.abort();
156
- }, UPDATE_CHECK_TIMEOUT_MS);
157
- try {
158
- const response = await fetch("https://registry.npmjs.org/openkitt/latest", {
159
- signal: controller.signal,
1388
+ _dispatchSubcommand(commandName, operands, unknown) {
1389
+ const subCommand = this._findCommand(commandName);
1390
+ if (!subCommand)
1391
+ this.help({ error: true });
1392
+ subCommand._prepareForParse();
1393
+ let promiseChain;
1394
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1395
+ promiseChain = this._chainOrCall(promiseChain, () => {
1396
+ if (subCommand._executableHandler) {
1397
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1398
+ } else {
1399
+ return subCommand._parseCommand(operands, unknown);
1400
+ }
1401
+ });
1402
+ return promiseChain;
1403
+ }
1404
+ _dispatchHelpCommand(subcommandName) {
1405
+ if (!subcommandName) {
1406
+ this.help();
1407
+ }
1408
+ const subCommand = this._findCommand(subcommandName);
1409
+ if (subCommand && !subCommand._executableHandler) {
1410
+ subCommand.help();
1411
+ }
1412
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1413
+ }
1414
+ _checkNumberOfArguments() {
1415
+ this.registeredArguments.forEach((arg, i) => {
1416
+ if (arg.required && this.args[i] == null) {
1417
+ this.missingArgument(arg.name());
1418
+ }
1419
+ });
1420
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1421
+ return;
1422
+ }
1423
+ if (this.args.length > this.registeredArguments.length) {
1424
+ this._excessArguments(this.args);
1425
+ }
1426
+ }
1427
+ _processArguments() {
1428
+ const myParseArg = (argument, value, previous) => {
1429
+ let parsedValue = value;
1430
+ if (value !== null && argument.parseArg) {
1431
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1432
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1433
+ }
1434
+ return parsedValue;
1435
+ };
1436
+ this._checkNumberOfArguments();
1437
+ const processedArgs = [];
1438
+ this.registeredArguments.forEach((declaredArg, index) => {
1439
+ let value = declaredArg.defaultValue;
1440
+ if (declaredArg.variadic) {
1441
+ if (index < this.args.length) {
1442
+ value = this.args.slice(index);
1443
+ if (declaredArg.parseArg) {
1444
+ value = value.reduce((processed, v) => {
1445
+ return myParseArg(declaredArg, v, processed);
1446
+ }, declaredArg.defaultValue);
1447
+ }
1448
+ } else if (value === undefined) {
1449
+ value = [];
1450
+ }
1451
+ } else if (index < this.args.length) {
1452
+ value = this.args[index];
1453
+ if (declaredArg.parseArg) {
1454
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1455
+ }
1456
+ }
1457
+ processedArgs[index] = value;
1458
+ });
1459
+ this.processedArgs = processedArgs;
1460
+ }
1461
+ _chainOrCall(promise, fn) {
1462
+ if (promise?.then && typeof promise.then === "function") {
1463
+ return promise.then(() => fn());
1464
+ }
1465
+ return fn();
1466
+ }
1467
+ _chainOrCallHooks(promise, event) {
1468
+ let result = promise;
1469
+ const hooks = [];
1470
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1471
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1472
+ hooks.push({ hookedCommand, callback });
160
1473
  });
161
- if (!response.ok) {
162
- return;
1474
+ });
1475
+ if (event === "postAction") {
1476
+ hooks.reverse();
1477
+ }
1478
+ hooks.forEach((hookDetail) => {
1479
+ result = this._chainOrCall(result, () => {
1480
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1481
+ });
1482
+ });
1483
+ return result;
1484
+ }
1485
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1486
+ let result = promise;
1487
+ if (this._lifeCycleHooks[event] !== undefined) {
1488
+ this._lifeCycleHooks[event].forEach((hook) => {
1489
+ result = this._chainOrCall(result, () => {
1490
+ return hook(this, subCommand);
1491
+ });
1492
+ });
1493
+ }
1494
+ return result;
1495
+ }
1496
+ _parseCommand(operands, unknown) {
1497
+ const parsed = this.parseOptions(unknown);
1498
+ this._parseOptionsEnv();
1499
+ this._parseOptionsImplied();
1500
+ operands = operands.concat(parsed.operands);
1501
+ unknown = parsed.unknown;
1502
+ this.args = operands.concat(unknown);
1503
+ if (operands && this._findCommand(operands[0])) {
1504
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1505
+ }
1506
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1507
+ return this._dispatchHelpCommand(operands[1]);
1508
+ }
1509
+ if (this._defaultCommandName) {
1510
+ this._outputHelpIfRequested(unknown);
1511
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1512
+ }
1513
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1514
+ this.help({ error: true });
1515
+ }
1516
+ this._outputHelpIfRequested(parsed.unknown);
1517
+ this._checkForMissingMandatoryOptions();
1518
+ this._checkForConflictingOptions();
1519
+ const checkForUnknownOptions = () => {
1520
+ if (parsed.unknown.length > 0) {
1521
+ this.unknownOption(parsed.unknown[0]);
163
1522
  }
164
- const payload = await response.json();
165
- if (typeof payload !== "object" || payload === null) {
166
- return;
1523
+ };
1524
+ const commandEvent = `command:${this.name()}`;
1525
+ if (this._actionHandler) {
1526
+ checkForUnknownOptions();
1527
+ this._processArguments();
1528
+ let promiseChain;
1529
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1530
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1531
+ if (this.parent) {
1532
+ promiseChain = this._chainOrCall(promiseChain, () => {
1533
+ this.parent.emit(commandEvent, operands, unknown);
1534
+ });
167
1535
  }
168
- const latestVersion = payload.version;
169
- if (typeof latestVersion !== "string" || latestVersion.length === 0) {
170
- return;
1536
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1537
+ return promiseChain;
1538
+ }
1539
+ if (this.parent?.listenerCount(commandEvent)) {
1540
+ checkForUnknownOptions();
1541
+ this._processArguments();
1542
+ this.parent.emit(commandEvent, operands, unknown);
1543
+ } else if (operands.length) {
1544
+ if (this._findCommand("*")) {
1545
+ return this._dispatchSubcommand("*", operands, unknown);
1546
+ }
1547
+ if (this.listenerCount("command:*")) {
1548
+ this.emit("command:*", operands, unknown);
1549
+ } else if (this.commands.length) {
1550
+ this.unknownCommand();
1551
+ } else {
1552
+ checkForUnknownOptions();
1553
+ this._processArguments();
1554
+ }
1555
+ } else if (this.commands.length) {
1556
+ checkForUnknownOptions();
1557
+ this.help({ error: true });
1558
+ } else {
1559
+ checkForUnknownOptions();
1560
+ this._processArguments();
1561
+ }
1562
+ }
1563
+ _findCommand(name) {
1564
+ if (!name)
1565
+ return;
1566
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1567
+ }
1568
+ _findOption(arg) {
1569
+ return this.options.find((option) => option.is(arg));
1570
+ }
1571
+ _checkForMissingMandatoryOptions() {
1572
+ this._getCommandAndAncestors().forEach((cmd) => {
1573
+ cmd.options.forEach((anOption) => {
1574
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1575
+ cmd.missingMandatoryOptionValue(anOption);
1576
+ }
1577
+ });
1578
+ });
1579
+ }
1580
+ _checkForConflictingLocalOptions() {
1581
+ const definedNonDefaultOptions = this.options.filter((option) => {
1582
+ const optionKey = option.attributeName();
1583
+ if (this.getOptionValue(optionKey) === undefined) {
1584
+ return false;
1585
+ }
1586
+ return this.getOptionValueSource(optionKey) !== "default";
1587
+ });
1588
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1589
+ optionsWithConflicting.forEach((option) => {
1590
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1591
+ if (conflictingAndDefined) {
1592
+ this._conflictingOption(option, conflictingAndDefined);
1593
+ }
1594
+ });
1595
+ }
1596
+ _checkForConflictingOptions() {
1597
+ this._getCommandAndAncestors().forEach((cmd) => {
1598
+ cmd._checkForConflictingLocalOptions();
1599
+ });
1600
+ }
1601
+ parseOptions(args) {
1602
+ const operands = [];
1603
+ const unknown = [];
1604
+ let dest = operands;
1605
+ function maybeOption(arg) {
1606
+ return arg.length > 1 && arg[0] === "-";
1607
+ }
1608
+ const negativeNumberArg = (arg) => {
1609
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
1610
+ return false;
1611
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
1612
+ };
1613
+ let activeVariadicOption = null;
1614
+ let activeGroup = null;
1615
+ let i = 0;
1616
+ while (i < args.length || activeGroup) {
1617
+ const arg = activeGroup ?? args[i++];
1618
+ activeGroup = null;
1619
+ if (arg === "--") {
1620
+ if (dest === unknown)
1621
+ dest.push(arg);
1622
+ dest.push(...args.slice(i));
1623
+ break;
1624
+ }
1625
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
1626
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1627
+ continue;
1628
+ }
1629
+ activeVariadicOption = null;
1630
+ if (maybeOption(arg)) {
1631
+ const option = this._findOption(arg);
1632
+ if (option) {
1633
+ if (option.required) {
1634
+ const value = args[i++];
1635
+ if (value === undefined)
1636
+ this.optionMissingArgument(option);
1637
+ this.emit(`option:${option.name()}`, value);
1638
+ } else if (option.optional) {
1639
+ let value = null;
1640
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
1641
+ value = args[i++];
1642
+ }
1643
+ this.emit(`option:${option.name()}`, value);
1644
+ } else {
1645
+ this.emit(`option:${option.name()}`);
1646
+ }
1647
+ activeVariadicOption = option.variadic ? option : null;
1648
+ continue;
1649
+ }
1650
+ }
1651
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1652
+ const option = this._findOption(`-${arg[1]}`);
1653
+ if (option) {
1654
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1655
+ this.emit(`option:${option.name()}`, arg.slice(2));
1656
+ } else {
1657
+ this.emit(`option:${option.name()}`);
1658
+ activeGroup = `-${arg.slice(2)}`;
1659
+ }
1660
+ continue;
1661
+ }
1662
+ }
1663
+ if (/^--[^=]+=/.test(arg)) {
1664
+ const index = arg.indexOf("=");
1665
+ const option = this._findOption(arg.slice(0, index));
1666
+ if (option && (option.required || option.optional)) {
1667
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1668
+ continue;
1669
+ }
1670
+ }
1671
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
1672
+ dest = unknown;
1673
+ }
1674
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1675
+ if (this._findCommand(arg)) {
1676
+ operands.push(arg);
1677
+ unknown.push(...args.slice(i));
1678
+ break;
1679
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1680
+ operands.push(arg, ...args.slice(i));
1681
+ break;
1682
+ } else if (this._defaultCommandName) {
1683
+ unknown.push(arg, ...args.slice(i));
1684
+ break;
1685
+ }
1686
+ }
1687
+ if (this._passThroughOptions) {
1688
+ dest.push(arg, ...args.slice(i));
1689
+ break;
1690
+ }
1691
+ dest.push(arg);
1692
+ }
1693
+ return { operands, unknown };
1694
+ }
1695
+ opts() {
1696
+ if (this._storeOptionsAsProperties) {
1697
+ const result = {};
1698
+ const len = this.options.length;
1699
+ for (let i = 0;i < len; i++) {
1700
+ const key = this.options[i].attributeName();
1701
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1702
+ }
1703
+ return result;
1704
+ }
1705
+ return this._optionValues;
1706
+ }
1707
+ optsWithGlobals() {
1708
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1709
+ }
1710
+ error(message, errorOptions) {
1711
+ this._outputConfiguration.outputError(`${message}
1712
+ `, this._outputConfiguration.writeErr);
1713
+ if (typeof this._showHelpAfterError === "string") {
1714
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1715
+ `);
1716
+ } else if (this._showHelpAfterError) {
1717
+ this._outputConfiguration.writeErr(`
1718
+ `);
1719
+ this.outputHelp({ error: true });
1720
+ }
1721
+ const config = errorOptions || {};
1722
+ const exitCode = config.exitCode || 1;
1723
+ const code = config.code || "commander.error";
1724
+ this._exit(exitCode, code, message);
1725
+ }
1726
+ _parseOptionsEnv() {
1727
+ this.options.forEach((option) => {
1728
+ if (option.envVar && option.envVar in process2.env) {
1729
+ const optionKey = option.attributeName();
1730
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1731
+ if (option.required || option.optional) {
1732
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1733
+ } else {
1734
+ this.emit(`optionEnv:${option.name()}`);
1735
+ }
1736
+ }
1737
+ }
1738
+ });
1739
+ }
1740
+ _parseOptionsImplied() {
1741
+ const dualHelper = new DualOptions(this.options);
1742
+ const hasCustomOptionValue = (optionKey) => {
1743
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1744
+ };
1745
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1746
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1747
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1748
+ });
1749
+ });
1750
+ }
1751
+ missingArgument(name) {
1752
+ const message = `error: missing required argument '${name}'`;
1753
+ this.error(message, { code: "commander.missingArgument" });
1754
+ }
1755
+ optionMissingArgument(option) {
1756
+ const message = `error: option '${option.flags}' argument missing`;
1757
+ this.error(message, { code: "commander.optionMissingArgument" });
1758
+ }
1759
+ missingMandatoryOptionValue(option) {
1760
+ const message = `error: required option '${option.flags}' not specified`;
1761
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1762
+ }
1763
+ _conflictingOption(option, conflictingOption) {
1764
+ const findBestOptionFromValue = (option2) => {
1765
+ const optionKey = option2.attributeName();
1766
+ const optionValue = this.getOptionValue(optionKey);
1767
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1768
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1769
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1770
+ return negativeOption;
171
1771
  }
172
- if (isVersionNewer(latestVersion, APP_VERSION)) {
173
- warn(`KITT v${latestVersion} is available (current: v${APP_VERSION}).\n Run "npm install -g openkitt@latest" to update,\n or use "npx openkitt@latest" on next launch.`);
1772
+ return positiveOption || option2;
1773
+ };
1774
+ const getErrorMessage = (option2) => {
1775
+ const bestOption = findBestOptionFromValue(option2);
1776
+ const optionKey = bestOption.attributeName();
1777
+ const source = this.getOptionValueSource(optionKey);
1778
+ if (source === "env") {
1779
+ return `environment variable '${bestOption.envVar}'`;
174
1780
  }
175
- writeUpdateCache(now, latestVersion);
1781
+ return `option '${bestOption.flags}'`;
1782
+ };
1783
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1784
+ this.error(message, { code: "commander.conflictingOption" });
176
1785
  }
177
- catch {
1786
+ unknownOption(flag) {
1787
+ if (this._allowUnknownOption)
178
1788
  return;
1789
+ let suggestion = "";
1790
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1791
+ let candidateFlags = [];
1792
+ let command = this;
1793
+ do {
1794
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1795
+ candidateFlags = candidateFlags.concat(moreFlags);
1796
+ command = command.parent;
1797
+ } while (command && !command._enablePositionalOptions);
1798
+ suggestion = suggestSimilar(flag, candidateFlags);
1799
+ }
1800
+ const message = `error: unknown option '${flag}'${suggestion}`;
1801
+ this.error(message, { code: "commander.unknownOption" });
1802
+ }
1803
+ _excessArguments(receivedArgs) {
1804
+ if (this._allowExcessArguments)
1805
+ return;
1806
+ const expected = this.registeredArguments.length;
1807
+ const s = expected === 1 ? "" : "s";
1808
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1809
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1810
+ this.error(message, { code: "commander.excessArguments" });
1811
+ }
1812
+ unknownCommand() {
1813
+ const unknownName = this.args[0];
1814
+ let suggestion = "";
1815
+ if (this._showSuggestionAfterError) {
1816
+ const candidateNames = [];
1817
+ this.createHelp().visibleCommands(this).forEach((command) => {
1818
+ candidateNames.push(command.name());
1819
+ if (command.alias())
1820
+ candidateNames.push(command.alias());
1821
+ });
1822
+ suggestion = suggestSimilar(unknownName, candidateNames);
1823
+ }
1824
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1825
+ this.error(message, { code: "commander.unknownCommand" });
1826
+ }
1827
+ version(str, flags, description) {
1828
+ if (str === undefined)
1829
+ return this._version;
1830
+ this._version = str;
1831
+ flags = flags || "-V, --version";
1832
+ description = description || "output the version number";
1833
+ const versionOption = this.createOption(flags, description);
1834
+ this._versionOptionName = versionOption.attributeName();
1835
+ this._registerOption(versionOption);
1836
+ this.on("option:" + versionOption.name(), () => {
1837
+ this._outputConfiguration.writeOut(`${str}
1838
+ `);
1839
+ this._exit(0, "commander.version", str);
1840
+ });
1841
+ return this;
1842
+ }
1843
+ description(str, argsDescription) {
1844
+ if (str === undefined && argsDescription === undefined)
1845
+ return this._description;
1846
+ this._description = str;
1847
+ if (argsDescription) {
1848
+ this._argsDescription = argsDescription;
1849
+ }
1850
+ return this;
1851
+ }
1852
+ summary(str) {
1853
+ if (str === undefined)
1854
+ return this._summary;
1855
+ this._summary = str;
1856
+ return this;
1857
+ }
1858
+ alias(alias) {
1859
+ if (alias === undefined)
1860
+ return this._aliases[0];
1861
+ let command = this;
1862
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1863
+ command = this.commands[this.commands.length - 1];
1864
+ }
1865
+ if (alias === command._name)
1866
+ throw new Error("Command alias can't be the same as its name");
1867
+ const matchingCommand = this.parent?._findCommand(alias);
1868
+ if (matchingCommand) {
1869
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1870
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1871
+ }
1872
+ command._aliases.push(alias);
1873
+ return this;
1874
+ }
1875
+ aliases(aliases) {
1876
+ if (aliases === undefined)
1877
+ return this._aliases;
1878
+ aliases.forEach((alias) => this.alias(alias));
1879
+ return this;
1880
+ }
1881
+ usage(str) {
1882
+ if (str === undefined) {
1883
+ if (this._usage)
1884
+ return this._usage;
1885
+ const args = this.registeredArguments.map((arg) => {
1886
+ return humanReadableArgName(arg);
1887
+ });
1888
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1889
+ }
1890
+ this._usage = str;
1891
+ return this;
1892
+ }
1893
+ name(str) {
1894
+ if (str === undefined)
1895
+ return this._name;
1896
+ this._name = str;
1897
+ return this;
1898
+ }
1899
+ helpGroup(heading) {
1900
+ if (heading === undefined)
1901
+ return this._helpGroupHeading ?? "";
1902
+ this._helpGroupHeading = heading;
1903
+ return this;
1904
+ }
1905
+ commandsGroup(heading) {
1906
+ if (heading === undefined)
1907
+ return this._defaultCommandGroup ?? "";
1908
+ this._defaultCommandGroup = heading;
1909
+ return this;
1910
+ }
1911
+ optionsGroup(heading) {
1912
+ if (heading === undefined)
1913
+ return this._defaultOptionGroup ?? "";
1914
+ this._defaultOptionGroup = heading;
1915
+ return this;
1916
+ }
1917
+ _initOptionGroup(option) {
1918
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
1919
+ option.helpGroup(this._defaultOptionGroup);
1920
+ }
1921
+ _initCommandGroup(cmd) {
1922
+ if (this._defaultCommandGroup && !cmd.helpGroup())
1923
+ cmd.helpGroup(this._defaultCommandGroup);
1924
+ }
1925
+ nameFromFilename(filename) {
1926
+ this._name = path.basename(filename, path.extname(filename));
1927
+ return this;
1928
+ }
1929
+ executableDir(path2) {
1930
+ if (path2 === undefined)
1931
+ return this._executableDir;
1932
+ this._executableDir = path2;
1933
+ return this;
1934
+ }
1935
+ helpInformation(contextOptions) {
1936
+ const helper = this.createHelp();
1937
+ const context = this._getOutputContext(contextOptions);
1938
+ helper.prepareContext({
1939
+ error: context.error,
1940
+ helpWidth: context.helpWidth,
1941
+ outputHasColors: context.hasColors
1942
+ });
1943
+ const text = helper.formatHelp(this, helper);
1944
+ if (context.hasColors)
1945
+ return text;
1946
+ return this._outputConfiguration.stripColor(text);
1947
+ }
1948
+ _getOutputContext(contextOptions) {
1949
+ contextOptions = contextOptions || {};
1950
+ const error = !!contextOptions.error;
1951
+ let baseWrite;
1952
+ let hasColors;
1953
+ let helpWidth;
1954
+ if (error) {
1955
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1956
+ hasColors = this._outputConfiguration.getErrHasColors();
1957
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1958
+ } else {
1959
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1960
+ hasColors = this._outputConfiguration.getOutHasColors();
1961
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1962
+ }
1963
+ const write = (str) => {
1964
+ if (!hasColors)
1965
+ str = this._outputConfiguration.stripColor(str);
1966
+ return baseWrite(str);
1967
+ };
1968
+ return { error, write, hasColors, helpWidth };
179
1969
  }
180
- finally {
181
- clearTimeout(timeoutId);
1970
+ outputHelp(contextOptions) {
1971
+ let deprecatedCallback;
1972
+ if (typeof contextOptions === "function") {
1973
+ deprecatedCallback = contextOptions;
1974
+ contextOptions = undefined;
1975
+ }
1976
+ const outputContext = this._getOutputContext(contextOptions);
1977
+ const eventContext = {
1978
+ error: outputContext.error,
1979
+ write: outputContext.write,
1980
+ command: this
1981
+ };
1982
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1983
+ this.emit("beforeHelp", eventContext);
1984
+ let helpInformation = this.helpInformation({ error: outputContext.error });
1985
+ if (deprecatedCallback) {
1986
+ helpInformation = deprecatedCallback(helpInformation);
1987
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1988
+ throw new Error("outputHelp callback must return a string or a Buffer");
1989
+ }
1990
+ }
1991
+ outputContext.write(helpInformation);
1992
+ if (this._getHelpOption()?.long) {
1993
+ this.emit(this._getHelpOption().long);
1994
+ }
1995
+ this.emit("afterHelp", eventContext);
1996
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
1997
+ }
1998
+ helpOption(flags, description) {
1999
+ if (typeof flags === "boolean") {
2000
+ if (flags) {
2001
+ if (this._helpOption === null)
2002
+ this._helpOption = undefined;
2003
+ if (this._defaultOptionGroup) {
2004
+ this._initOptionGroup(this._getHelpOption());
2005
+ }
2006
+ } else {
2007
+ this._helpOption = null;
2008
+ }
2009
+ return this;
2010
+ }
2011
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2012
+ if (flags || description)
2013
+ this._initOptionGroup(this._helpOption);
2014
+ return this;
2015
+ }
2016
+ _getHelpOption() {
2017
+ if (this._helpOption === undefined) {
2018
+ this.helpOption(undefined, undefined);
2019
+ }
2020
+ return this._helpOption;
182
2021
  }
2022
+ addHelpOption(option) {
2023
+ this._helpOption = option;
2024
+ this._initOptionGroup(option);
2025
+ return this;
2026
+ }
2027
+ help(contextOptions) {
2028
+ this.outputHelp(contextOptions);
2029
+ let exitCode = Number(process2.exitCode ?? 0);
2030
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2031
+ exitCode = 1;
2032
+ }
2033
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2034
+ }
2035
+ addHelpText(position, text) {
2036
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2037
+ if (!allowedValues.includes(position)) {
2038
+ throw new Error(`Unexpected value for position to addHelpText.
2039
+ Expecting one of '${allowedValues.join("', '")}'`);
2040
+ }
2041
+ const helpEvent = `${position}Help`;
2042
+ this.on(helpEvent, (context) => {
2043
+ let helpStr;
2044
+ if (typeof text === "function") {
2045
+ helpStr = text({ error: context.error, command: context.command });
2046
+ } else {
2047
+ helpStr = text;
2048
+ }
2049
+ if (helpStr) {
2050
+ context.write(`${helpStr}
2051
+ `);
2052
+ }
2053
+ });
2054
+ return this;
2055
+ }
2056
+ _outputHelpIfRequested(args) {
2057
+ const helpOption = this._getHelpOption();
2058
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2059
+ if (helpRequested) {
2060
+ this.outputHelp();
2061
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2062
+ }
2063
+ }
2064
+ }
2065
+ function incrementNodeInspectorPort(args) {
2066
+ return args.map((arg) => {
2067
+ if (!arg.startsWith("--inspect")) {
2068
+ return arg;
2069
+ }
2070
+ let debugOption;
2071
+ let debugHost = "127.0.0.1";
2072
+ let debugPort = "9229";
2073
+ let match;
2074
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2075
+ debugOption = match[1];
2076
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2077
+ debugOption = match[1];
2078
+ if (/^\d+$/.test(match[3])) {
2079
+ debugPort = match[3];
2080
+ } else {
2081
+ debugHost = match[3];
2082
+ }
2083
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2084
+ debugOption = match[1];
2085
+ debugHost = match[3];
2086
+ debugPort = match[4];
2087
+ }
2088
+ if (debugOption && debugPort !== "0") {
2089
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2090
+ }
2091
+ return arg;
2092
+ });
2093
+ }
2094
+ function useColor() {
2095
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2096
+ return false;
2097
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2098
+ return true;
2099
+ return;
2100
+ }
2101
+ exports.Command = Command;
2102
+ exports.useColor = useColor;
2103
+ });
2104
+
2105
+ // node_modules/commander/index.js
2106
+ var require_commander = __commonJS((exports) => {
2107
+ var { Argument } = require_argument();
2108
+ var { Command } = require_command();
2109
+ var { CommanderError, InvalidArgumentError } = require_error();
2110
+ var { Help } = require_help();
2111
+ var { Option } = require_option();
2112
+ exports.program = new Command;
2113
+ exports.createCommand = (name) => new Command(name);
2114
+ exports.createOption = (flags, description) => new Option(flags, description);
2115
+ exports.createArgument = (name, description) => new Argument(name, description);
2116
+ exports.Command = Command;
2117
+ exports.Option = Option;
2118
+ exports.Argument = Argument;
2119
+ exports.Help = Help;
2120
+ exports.CommanderError = CommanderError;
2121
+ exports.InvalidArgumentError = InvalidArgumentError;
2122
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2123
+ });
2124
+
2125
+ // node_modules/picocolors/picocolors.js
2126
+ var require_picocolors = __commonJS((exports, module) => {
2127
+ var p = process || {};
2128
+ var argv = p.argv || [];
2129
+ var env = p.env || {};
2130
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
2131
+ var formatter = (open, close, replace = open) => (input) => {
2132
+ let string = "" + input, index = string.indexOf(close, open.length);
2133
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
2134
+ };
2135
+ var replaceClose = (string, close, replace, index) => {
2136
+ let result = "", cursor = 0;
2137
+ do {
2138
+ result += string.substring(cursor, index) + replace;
2139
+ cursor = index + close.length;
2140
+ index = string.indexOf(close, cursor);
2141
+ } while (~index);
2142
+ return result + string.substring(cursor);
2143
+ };
2144
+ var createColors = (enabled = isColorSupported) => {
2145
+ let f = enabled ? formatter : () => String;
2146
+ return {
2147
+ isColorSupported: enabled,
2148
+ reset: f("\x1B[0m", "\x1B[0m"),
2149
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
2150
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
2151
+ italic: f("\x1B[3m", "\x1B[23m"),
2152
+ underline: f("\x1B[4m", "\x1B[24m"),
2153
+ inverse: f("\x1B[7m", "\x1B[27m"),
2154
+ hidden: f("\x1B[8m", "\x1B[28m"),
2155
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
2156
+ black: f("\x1B[30m", "\x1B[39m"),
2157
+ red: f("\x1B[31m", "\x1B[39m"),
2158
+ green: f("\x1B[32m", "\x1B[39m"),
2159
+ yellow: f("\x1B[33m", "\x1B[39m"),
2160
+ blue: f("\x1B[34m", "\x1B[39m"),
2161
+ magenta: f("\x1B[35m", "\x1B[39m"),
2162
+ cyan: f("\x1B[36m", "\x1B[39m"),
2163
+ white: f("\x1B[37m", "\x1B[39m"),
2164
+ gray: f("\x1B[90m", "\x1B[39m"),
2165
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
2166
+ bgRed: f("\x1B[41m", "\x1B[49m"),
2167
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
2168
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
2169
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
2170
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
2171
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
2172
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
2173
+ blackBright: f("\x1B[90m", "\x1B[39m"),
2174
+ redBright: f("\x1B[91m", "\x1B[39m"),
2175
+ greenBright: f("\x1B[92m", "\x1B[39m"),
2176
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
2177
+ blueBright: f("\x1B[94m", "\x1B[39m"),
2178
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
2179
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
2180
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
2181
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
2182
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
2183
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
2184
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
2185
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
2186
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
2187
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
2188
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
2189
+ };
2190
+ };
2191
+ module.exports = createColors();
2192
+ module.exports.createColors = createColors;
2193
+ });
2194
+
2195
+ // src/credentials/encryption.ts
2196
+ import { execSync } from "node:child_process";
2197
+ import {
2198
+ createCipheriv,
2199
+ createDecipheriv,
2200
+ pbkdf2Sync,
2201
+ randomBytes
2202
+ } from "node:crypto";
2203
+ import { readFileSync } from "node:fs";
2204
+ import { hostname, platform, userInfo } from "node:os";
2205
+ function getMachineId() {
2206
+ if (cachedMachineId) {
2207
+ return cachedMachineId;
2208
+ }
2209
+ const currentPlatform = platform();
2210
+ if (currentPlatform === "darwin") {
2211
+ try {
2212
+ const output = execSync("ioreg -rd1 -c IOPlatformExpertDevice", {
2213
+ encoding: "utf-8",
2214
+ stdio: "pipe"
2215
+ });
2216
+ const match = output.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);
2217
+ if (match?.[1]) {
2218
+ cachedMachineId = match[1].trim();
2219
+ return cachedMachineId;
2220
+ }
2221
+ } catch {}
2222
+ }
2223
+ if (currentPlatform === "linux") {
2224
+ try {
2225
+ const machineId = readFileSync("/etc/machine-id", "utf-8").trim();
2226
+ if (machineId) {
2227
+ cachedMachineId = machineId;
2228
+ return cachedMachineId;
2229
+ }
2230
+ } catch {}
2231
+ }
2232
+ if (currentPlatform === "win32") {
2233
+ try {
2234
+ const output = execSync('reg query "HKLM\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid', {
2235
+ encoding: "utf-8",
2236
+ stdio: "pipe"
2237
+ });
2238
+ const match = output.match(/MachineGuid\s+REG_\w+\s+([^\r\n]+)/i);
2239
+ if (match?.[1]) {
2240
+ cachedMachineId = match[1].trim();
2241
+ return cachedMachineId;
2242
+ }
2243
+ } catch {}
2244
+ }
2245
+ try {
2246
+ cachedMachineId = `${hostname()}${userInfo().username}`;
2247
+ } catch {
2248
+ cachedMachineId = hostname();
2249
+ }
2250
+ return cachedMachineId;
183
2251
  }
184
- async function resolveAndRunHandler(route, context, args, commandKey) {
185
- const loaded = (await import(route.modulePath));
186
- const handler = loaded.default ?? loaded.run ?? loaded.handle;
187
- if (handler) {
188
- await handler(context, args, commandKey);
2252
+ async function encrypt(plaintext) {
2253
+ const machineId = getMachineId();
2254
+ const salt = randomBytes(PBKDF2_SALT_LENGTH_BYTES);
2255
+ const iv = randomBytes(GCM_IV_LENGTH_BYTES);
2256
+ const key = pbkdf2Sync(`${machineId}${KITT_SALT}`, salt, PBKDF2_ITERATIONS, KEY_LENGTH_BYTES, "sha256");
2257
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
2258
+ const encrypted = Buffer.concat([
2259
+ cipher.update(plaintext, "utf8"),
2260
+ cipher.final()
2261
+ ]);
2262
+ const authTag = cipher.getAuthTag();
2263
+ return {
2264
+ encrypted: encrypted.toString("base64"),
2265
+ iv: iv.toString("base64"),
2266
+ salt: salt.toString("base64"),
2267
+ authTag: authTag.toString("base64")
2268
+ };
2269
+ }
2270
+ async function decrypt(data) {
2271
+ try {
2272
+ const machineId = getMachineId();
2273
+ const salt = Buffer.from(data.salt, "base64");
2274
+ const iv = Buffer.from(data.iv, "base64");
2275
+ const encrypted = Buffer.from(data.encrypted, "base64");
2276
+ const authTag = Buffer.from(data.authTag, "base64");
2277
+ const key = pbkdf2Sync(`${machineId}${KITT_SALT}`, salt, PBKDF2_ITERATIONS, KEY_LENGTH_BYTES, "sha256");
2278
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
2279
+ decipher.setAuthTag(authTag);
2280
+ const decrypted = Buffer.concat([
2281
+ decipher.update(encrypted),
2282
+ decipher.final()
2283
+ ]);
2284
+ return decrypted.toString("utf8");
2285
+ } catch {
2286
+ throw new Error("Failed to decrypt credential data. Data may be invalid, tampered, or from a different machine.");
2287
+ }
2288
+ }
2289
+ var KITT_SALT = "openkitt-credential-salt-v1", PBKDF2_ITERATIONS = 1e5, KEY_LENGTH_BYTES = 32, GCM_IV_LENGTH_BYTES = 12, PBKDF2_SALT_LENGTH_BYTES = 16, cachedMachineId;
2290
+ var init_encryption = () => {};
2291
+
2292
+ // src/credentials/keychain.ts
2293
+ import { execFileSync } from "node:child_process";
2294
+ function normalizeKey(key) {
2295
+ return key.startsWith(`${SERVICE_NAME}-`) ? key : `${SERVICE_NAME}-${key}`;
2296
+ }
2297
+ function isNotFoundError(errorMessage) {
2298
+ const normalized = errorMessage.toLowerCase();
2299
+ return normalized.includes("could not be found") || normalized.includes("item not found") || normalized.includes("not found") || normalized.includes("element not found");
2300
+ }
2301
+ function getErrorMessage(error) {
2302
+ if (error instanceof Error) {
2303
+ const maybeStderr = error.stderr;
2304
+ if (typeof maybeStderr === "string" && maybeStderr.trim().length > 0) {
2305
+ return maybeStderr.trim();
189
2306
  }
2307
+ if (Buffer.isBuffer(maybeStderr) && maybeStderr.length > 0) {
2308
+ return maybeStderr.toString("utf-8").trim();
2309
+ }
2310
+ if (error.message.trim().length > 0) {
2311
+ return error.message.trim();
2312
+ }
2313
+ }
2314
+ return "Unknown keychain error";
190
2315
  }
191
- async function dispatchCommand(commandLine, context) {
192
- const parsed = parseCommand(commandLine);
193
- if (!parsed) {
194
- return "continue";
2316
+ function runPowerShellEncoded(script) {
2317
+ const encodedCommand = Buffer.from(script, "utf16le").toString("base64");
2318
+ return execFileSync("powershell", ["-NoProfile", "-EncodedCommand", encodedCommand], {
2319
+ encoding: "utf-8",
2320
+ stdio: "pipe"
2321
+ }).trim();
2322
+ }
2323
+ function getWindowsReadScript(targetName) {
2324
+ const escapedTarget = targetName.replace(/'/g, "''");
2325
+ return `$ErrorActionPreference = 'Stop'
2326
+
2327
+ Add-Type @"
2328
+ using System;
2329
+ using System.Runtime.InteropServices;
2330
+
2331
+ public static class WinCred {
2332
+ [DllImport("Advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)]
2333
+ public static extern bool CredRead(string target, int type, int reservedFlag, out IntPtr credentialPtr);
2334
+
2335
+ [DllImport("Advapi32.dll", EntryPoint = "CredFree", SetLastError = true)]
2336
+ public static extern void CredFree(IntPtr cred);
2337
+
2338
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
2339
+ public struct CREDENTIAL {
2340
+ public int Flags;
2341
+ public int Type;
2342
+ public string TargetName;
2343
+ public string Comment;
2344
+ public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
2345
+ public int CredentialBlobSize;
2346
+ public IntPtr CredentialBlob;
2347
+ public int Persist;
2348
+ public int AttributeCount;
2349
+ public IntPtr Attributes;
2350
+ public string TargetAlias;
2351
+ public string UserName;
2352
+ }
2353
+ }
2354
+ "@
2355
+
2356
+ $target = '${escapedTarget}'
2357
+ $credPtr = [IntPtr]::Zero
2358
+
2359
+ if (-not [WinCred]::CredRead($target, 1, 0, [ref]$credPtr)) {
2360
+ exit 2
2361
+ }
2362
+
2363
+ try {
2364
+ $credential = [System.Runtime.InteropServices.Marshal]::PtrToStructure($credPtr, [type][WinCred+CREDENTIAL])
2365
+ if ($credential.CredentialBlobSize -le 0 -or $credential.CredentialBlob -eq [IntPtr]::Zero) {
2366
+ exit 3
2367
+ }
2368
+
2369
+ $bytes = New-Object byte[] $credential.CredentialBlobSize
2370
+ [System.Runtime.InteropServices.Marshal]::Copy($credential.CredentialBlob, $bytes, 0, $credential.CredentialBlobSize)
2371
+ $secret = [System.Text.Encoding]::Unicode.GetString($bytes)
2372
+ Write-Output $secret
2373
+ } finally {
2374
+ [WinCred]::CredFree($credPtr)
2375
+ }`;
2376
+ }
2377
+ function checkMacAvailable() {
2378
+ execFileSync("security", ["-h"], {
2379
+ encoding: "utf-8",
2380
+ stdio: "pipe"
2381
+ });
2382
+ return true;
2383
+ }
2384
+ function checkLinuxAvailable() {
2385
+ execFileSync("secret-tool", ["--help"], {
2386
+ encoding: "utf-8",
2387
+ stdio: "pipe"
2388
+ });
2389
+ return true;
2390
+ }
2391
+ function checkWindowsAvailable() {
2392
+ execFileSync("cmdkey", ["/?"], {
2393
+ encoding: "utf-8",
2394
+ stdio: "pipe"
2395
+ });
2396
+ return true;
2397
+ }
2398
+ async function isKeychainAvailable() {
2399
+ try {
2400
+ switch (process.platform) {
2401
+ case "darwin":
2402
+ return checkMacAvailable();
2403
+ case "linux":
2404
+ return checkLinuxAvailable();
2405
+ case "win32":
2406
+ return checkWindowsAvailable();
2407
+ default:
2408
+ return false;
195
2409
  }
196
- if (parsed.key === "exit") {
197
- return "exit";
2410
+ } catch {
2411
+ return false;
2412
+ }
2413
+ }
2414
+ async function setKeychainValue(key, value) {
2415
+ const normalizedKey = normalizeKey(key);
2416
+ try {
2417
+ switch (process.platform) {
2418
+ case "darwin":
2419
+ execFileSync("security", [
2420
+ "add-generic-password",
2421
+ "-a",
2422
+ normalizedKey,
2423
+ "-s",
2424
+ SERVICE_NAME,
2425
+ "-w",
2426
+ value,
2427
+ "-U"
2428
+ ], {
2429
+ encoding: "utf-8",
2430
+ stdio: "pipe"
2431
+ });
2432
+ return { success: true };
2433
+ case "linux":
2434
+ execFileSync("secret-tool", ["store", `--label=${SERVICE_NAME}`, "service", SERVICE_NAME, "key", normalizedKey], {
2435
+ encoding: "utf-8",
2436
+ stdio: "pipe",
2437
+ input: value
2438
+ });
2439
+ return { success: true };
2440
+ case "win32":
2441
+ execFileSync("cmdkey", [
2442
+ `/generic:${normalizedKey}`,
2443
+ `/user:${SERVICE_NAME}`,
2444
+ `/pass:${value}`
2445
+ ], {
2446
+ encoding: "utf-8",
2447
+ stdio: "pipe"
2448
+ });
2449
+ return { success: true };
2450
+ default:
2451
+ return { success: false, error: "Unsupported platform" };
198
2452
  }
199
- const route = commandRegistry[parsed.key];
200
- if (!route) {
201
- console.log(`Unknown command: ${parsed.displayName}. Type /help for available commands.`);
202
- return "unknown";
2453
+ } catch (error) {
2454
+ return { success: false, error: getErrorMessage(error) };
2455
+ }
2456
+ }
2457
+ async function getKeychainValue(key) {
2458
+ const normalizedKey = normalizeKey(key);
2459
+ try {
2460
+ switch (process.platform) {
2461
+ case "darwin":
2462
+ return execFileSync("security", ["find-generic-password", "-a", normalizedKey, "-s", SERVICE_NAME, "-w"], {
2463
+ encoding: "utf-8",
2464
+ stdio: "pipe"
2465
+ }).trim();
2466
+ case "linux":
2467
+ return execFileSync("secret-tool", ["lookup", "service", SERVICE_NAME, "key", normalizedKey], {
2468
+ encoding: "utf-8",
2469
+ stdio: "pipe"
2470
+ }).trim();
2471
+ case "win32": {
2472
+ const script = getWindowsReadScript(normalizedKey);
2473
+ const output = runPowerShellEncoded(script);
2474
+ return output.length > 0 ? output : null;
2475
+ }
2476
+ default:
2477
+ return null;
203
2478
  }
204
- const authCheck = await checkAuthGuard(parsed.key);
205
- if (!authCheck.allowed) {
206
- console.log(pc.red(`✗ ${authCheck.message}`));
207
- return "continue";
2479
+ } catch (error) {
2480
+ const errorMessage = getErrorMessage(error);
2481
+ if (isNotFoundError(errorMessage)) {
2482
+ return null;
208
2483
  }
209
- await resolveAndRunHandler(route, context, parsed.args, parsed.key);
210
- return "continue";
2484
+ return null;
2485
+ }
211
2486
  }
212
- export async function runSingleCommand(commandLine, context) {
213
- const parsed = parseCommand(commandLine);
214
- if (parsed && STATE_CHANGING_COMMANDS.has(parsed.key) && !context.yes) {
215
- console.log(pc.red(`✗ Non-interactive mode requires --yes for state-changing commands.\n Usage: npx openkitt --run "${parsed.key}" --yes`));
216
- return 1;
2487
+ async function deleteKeychainValue(key) {
2488
+ const normalizedKey = normalizeKey(key);
2489
+ try {
2490
+ switch (process.platform) {
2491
+ case "darwin":
2492
+ execFileSync("security", ["delete-generic-password", "-a", normalizedKey, "-s", SERVICE_NAME], {
2493
+ encoding: "utf-8",
2494
+ stdio: "pipe"
2495
+ });
2496
+ return { success: true };
2497
+ case "linux":
2498
+ execFileSync("secret-tool", ["clear", "service", SERVICE_NAME, "key", normalizedKey], {
2499
+ encoding: "utf-8",
2500
+ stdio: "pipe"
2501
+ });
2502
+ return { success: true };
2503
+ case "win32":
2504
+ execFileSync("cmdkey", [`/delete:${normalizedKey}`], {
2505
+ encoding: "utf-8",
2506
+ stdio: "pipe"
2507
+ });
2508
+ return { success: true };
2509
+ default:
2510
+ return { success: false, error: "Unsupported platform" };
2511
+ }
2512
+ } catch (error) {
2513
+ const errorMessage = getErrorMessage(error);
2514
+ if (isNotFoundError(errorMessage)) {
2515
+ return { success: true };
217
2516
  }
218
- const result = await dispatchCommand(commandLine, context);
219
- return result === "unknown" ? 1 : 0;
2517
+ return { success: false, error: errorMessage };
2518
+ }
220
2519
  }
221
- function createProgram() {
222
- const program = new Command();
223
- program
224
- .name("openkitt")
225
- .description("AI-powered app scaffolding CLI")
226
- .version(APP_VERSION, "-v, --version", "Display current KITT version and exit.")
227
- .helpOption("-h, --help", "Display available commands and flags.")
228
- .option("--verbose", "Enable verbose output.")
229
- .option("-q, --quiet", "Suppress non-essential output.")
230
- .option("--run <command>", "Execute a single command and exit (non-interactive mode).")
231
- .option("--dry-run", "Show proposed changes without executing.")
232
- .option("-y, --yes", "Auto-confirm all prompts.")
233
- .option("--config <json>", "Supply command selections as JSON.")
234
- .option("--env <name>", "Target environment.")
235
- .option("--no-update-check", "Skip automatic version check on launch.")
236
- .option("--debug", "Show LLM timing and token usage after scaffolding.");
237
- return program;
2520
+ var SERVICE_NAME = "openkitt";
2521
+ var init_keychain = () => {};
2522
+
2523
+ // src/credentials/config.ts
2524
+ var exports_config = {};
2525
+ __export(exports_config, {
2526
+ updateLlmModel: () => updateLlmModel,
2527
+ storeLlmCredentials: () => storeLlmCredentials,
2528
+ isLlmConfigured: () => isLlmConfigured,
2529
+ getLlmConfig: () => getLlmConfig,
2530
+ getLlmApiKey: () => getLlmApiKey,
2531
+ clearLlmCredentials: () => clearLlmCredentials
2532
+ });
2533
+ import { chmodSync, existsSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2534
+ import { homedir, platform as platform2 } from "node:os";
2535
+ import { join } from "node:path";
2536
+ function isWindows() {
2537
+ return platform2() === "win32";
238
2538
  }
239
- function buildAppContext(options) {
2539
+ function hasExtraPermissionBits(actualMode, allowedMode) {
2540
+ const activeBits = actualMode & 511;
2541
+ return (activeBits & ~allowedMode) !== 0;
2542
+ }
2543
+ function ensurePermissions(path, mode) {
2544
+ if (isWindows() || !existsSync(path)) {
2545
+ return;
2546
+ }
2547
+ const currentMode = statSync(path).mode;
2548
+ if (hasExtraPermissionBits(currentMode, mode)) {
2549
+ console.warn(`[kitt] Detected permissive config permissions for ${path}. Auto-fixing.`);
2550
+ chmodSync(path, mode);
2551
+ }
2552
+ }
2553
+ function ensureConfigDir() {
2554
+ if (!existsSync(CONFIG_DIR)) {
2555
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: DIR_MODE });
2556
+ }
2557
+ if (!isWindows()) {
2558
+ ensurePermissions(CONFIG_DIR, DIR_MODE);
2559
+ }
2560
+ }
2561
+ function readConfig() {
2562
+ ensureConfigDir();
2563
+ if (!existsSync(CONFIG_FILE)) {
2564
+ return {};
2565
+ }
2566
+ if (!isWindows()) {
2567
+ ensurePermissions(CONFIG_FILE, FILE_MODE);
2568
+ }
2569
+ const raw = readFileSync2(CONFIG_FILE, "utf-8").trim();
2570
+ if (raw.length === 0) {
2571
+ return {};
2572
+ }
2573
+ const parsed = JSON.parse(raw);
2574
+ if (!parsed || typeof parsed !== "object") {
2575
+ return {};
2576
+ }
2577
+ return parsed;
2578
+ }
2579
+ function writeConfig(config) {
2580
+ ensureConfigDir();
2581
+ const tempFile = `${CONFIG_FILE}.tmp-${process.pid}-${Date.now()}`;
2582
+ const payload = `${JSON.stringify(config, null, 2)}
2583
+ `;
2584
+ try {
2585
+ writeFileSync(tempFile, payload, { encoding: "utf-8", mode: FILE_MODE });
2586
+ if (!isWindows()) {
2587
+ chmodSync(tempFile, FILE_MODE);
2588
+ }
2589
+ renameSync(tempFile, CONFIG_FILE);
2590
+ if (!isWindows()) {
2591
+ chmodSync(CONFIG_FILE, FILE_MODE);
2592
+ }
2593
+ } catch (error) {
2594
+ if (existsSync(tempFile)) {
2595
+ unlinkSync(tempFile);
2596
+ }
2597
+ throw error;
2598
+ }
2599
+ }
2600
+ function isStoredProvider(value) {
2601
+ return value === "anthropic" || value === "openai" || value === "gemini";
2602
+ }
2603
+ function getStoredLlm(config) {
2604
+ const llm = config.llm;
2605
+ if (!llm || typeof llm !== "object") {
2606
+ return null;
2607
+ }
2608
+ if (!isStoredProvider(llm.provider)) {
2609
+ return null;
2610
+ }
2611
+ if (typeof llm.model !== "string" || llm.model.length === 0) {
2612
+ return null;
2613
+ }
2614
+ if (typeof llm.validatedAt !== "string" || llm.validatedAt.length === 0) {
2615
+ return null;
2616
+ }
2617
+ if (llm.storage !== "keychain" && llm.storage !== "encrypted") {
2618
+ return null;
2619
+ }
2620
+ return llm;
2621
+ }
2622
+ async function storeLlmCredentials(provider, model, apiKey) {
2623
+ const validatedAt = new Date().toISOString();
2624
+ const keychainAvailable = await isKeychainAvailable();
2625
+ if (keychainAvailable) {
2626
+ const result = await setKeychainValue(KEYCHAIN_API_KEY, apiKey);
2627
+ if (result.success) {
2628
+ writeConfig({
2629
+ llm: {
2630
+ provider,
2631
+ model,
2632
+ validatedAt,
2633
+ storage: "keychain"
2634
+ }
2635
+ });
2636
+ return;
2637
+ }
2638
+ }
2639
+ const encrypted = await encrypt(apiKey);
2640
+ await deleteKeychainValue(KEYCHAIN_API_KEY);
2641
+ writeConfig({
2642
+ llm: {
2643
+ provider,
2644
+ model,
2645
+ validatedAt,
2646
+ storage: "encrypted",
2647
+ apiKey: encrypted.encrypted,
2648
+ iv: encrypted.iv,
2649
+ salt: encrypted.salt,
2650
+ authTag: encrypted.authTag
2651
+ }
2652
+ });
2653
+ }
2654
+ async function getLlmApiKey() {
2655
+ const config = readConfig();
2656
+ const llm = getStoredLlm(config);
2657
+ if (!llm) {
2658
+ return null;
2659
+ }
2660
+ if (llm.storage === "keychain") {
2661
+ return getKeychainValue(KEYCHAIN_API_KEY);
2662
+ }
2663
+ if (typeof llm.apiKey !== "string" || typeof llm.iv !== "string" || typeof llm.salt !== "string" || typeof llm.authTag !== "string") {
2664
+ return null;
2665
+ }
2666
+ try {
2667
+ return await decrypt({
2668
+ encrypted: llm.apiKey,
2669
+ iv: llm.iv,
2670
+ salt: llm.salt,
2671
+ authTag: llm.authTag
2672
+ });
2673
+ } catch {
2674
+ return null;
2675
+ }
2676
+ }
2677
+ async function getLlmConfig() {
2678
+ const config = readConfig();
2679
+ const llm = getStoredLlm(config);
2680
+ if (!llm) {
2681
+ return null;
2682
+ }
2683
+ return {
2684
+ provider: llm.provider,
2685
+ model: llm.model,
2686
+ validatedAt: llm.validatedAt
2687
+ };
2688
+ }
2689
+ async function updateLlmModel(model) {
2690
+ const config = readConfig();
2691
+ const llm = getStoredLlm(config);
2692
+ if (!llm) {
2693
+ return;
2694
+ }
2695
+ writeConfig({
2696
+ ...config,
2697
+ llm: {
2698
+ ...llm,
2699
+ model
2700
+ }
2701
+ });
2702
+ }
2703
+ async function clearLlmCredentials() {
2704
+ await deleteKeychainValue(KEYCHAIN_API_KEY);
2705
+ const config = readConfig();
2706
+ if (!config.llm) {
2707
+ return;
2708
+ }
2709
+ const nextConfig = { ...config };
2710
+ delete nextConfig.llm;
2711
+ writeConfig(nextConfig);
2712
+ }
2713
+ async function isLlmConfigured() {
2714
+ const [apiKey, llmConfig] = await Promise.all([getLlmApiKey(), getLlmConfig()]);
2715
+ return apiKey !== null && llmConfig !== null;
2716
+ }
2717
+ var CONFIG_DIR, CONFIG_FILE, KEYCHAIN_API_KEY = "llm-api-key", DIR_MODE = 448, FILE_MODE = 384;
2718
+ var init_config = __esm(() => {
2719
+ init_encryption();
2720
+ init_keychain();
2721
+ CONFIG_DIR = join(homedir(), ".kitt");
2722
+ CONFIG_FILE = join(CONFIG_DIR, "config.json");
2723
+ });
2724
+
2725
+ // node_modules/sisteransi/src/index.js
2726
+ var require_src = __commonJS((exports, module) => {
2727
+ var ESC = "\x1B";
2728
+ var CSI = `${ESC}[`;
2729
+ var beep = "\x07";
2730
+ var cursor = {
2731
+ to(x, y) {
2732
+ if (!y)
2733
+ return `${CSI}${x + 1}G`;
2734
+ return `${CSI}${y + 1};${x + 1}H`;
2735
+ },
2736
+ move(x, y) {
2737
+ let ret = "";
2738
+ if (x < 0)
2739
+ ret += `${CSI}${-x}D`;
2740
+ else if (x > 0)
2741
+ ret += `${CSI}${x}C`;
2742
+ if (y < 0)
2743
+ ret += `${CSI}${-y}A`;
2744
+ else if (y > 0)
2745
+ ret += `${CSI}${y}B`;
2746
+ return ret;
2747
+ },
2748
+ up: (count = 1) => `${CSI}${count}A`,
2749
+ down: (count = 1) => `${CSI}${count}B`,
2750
+ forward: (count = 1) => `${CSI}${count}C`,
2751
+ backward: (count = 1) => `${CSI}${count}D`,
2752
+ nextLine: (count = 1) => `${CSI}E`.repeat(count),
2753
+ prevLine: (count = 1) => `${CSI}F`.repeat(count),
2754
+ left: `${CSI}G`,
2755
+ hide: `${CSI}?25l`,
2756
+ show: `${CSI}?25h`,
2757
+ save: `${ESC}7`,
2758
+ restore: `${ESC}8`
2759
+ };
2760
+ var scroll = {
2761
+ up: (count = 1) => `${CSI}S`.repeat(count),
2762
+ down: (count = 1) => `${CSI}T`.repeat(count)
2763
+ };
2764
+ var erase = {
2765
+ screen: `${CSI}2J`,
2766
+ up: (count = 1) => `${CSI}1J`.repeat(count),
2767
+ down: (count = 1) => `${CSI}J`.repeat(count),
2768
+ line: `${CSI}2K`,
2769
+ lineEnd: `${CSI}K`,
2770
+ lineStart: `${CSI}1K`,
2771
+ lines(count) {
2772
+ let clear = "";
2773
+ for (let i = 0;i < count; i++)
2774
+ clear += this.line + (i < count - 1 ? cursor.up() : "");
2775
+ if (count)
2776
+ clear += cursor.left;
2777
+ return clear;
2778
+ }
2779
+ };
2780
+ module.exports = { cursor, scroll, erase, beep };
2781
+ });
2782
+
2783
+ // node_modules/commander/esm.mjs
2784
+ var import__ = __toESM(require_commander(), 1);
2785
+ var {
2786
+ program,
2787
+ createCommand,
2788
+ createArgument,
2789
+ createOption,
2790
+ CommanderError,
2791
+ InvalidArgumentError,
2792
+ InvalidOptionArgumentError,
2793
+ Command,
2794
+ Argument,
2795
+ Option,
2796
+ Help
2797
+ } = import__.default;
2798
+
2799
+ // src/cli.ts
2800
+ var import_picocolors4 = __toESM(require_picocolors(), 1);
2801
+ import { createInterface, emitKeypressEvents } from "node:readline";
2802
+ import { stdin as input, stdout as output } from "node:process";
2803
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "node:fs";
2804
+ import { homedir as homedir3 } from "node:os";
2805
+ import { basename, join as join6 } from "node:path";
2806
+ import { pathToFileURL } from "node:url";
2807
+
2808
+ // src/utils/prerequisites.ts
2809
+ var import_picocolors = __toESM(require_picocolors(), 1);
2810
+ import { execSync as execSync2 } from "node:child_process";
2811
+ function getNodeVersion() {
2812
+ try {
2813
+ const output = execSync2("node --version", {
2814
+ encoding: "utf-8",
2815
+ stdio: "pipe"
2816
+ }).trim();
2817
+ return output.replace(/^v/, "");
2818
+ } catch {
2819
+ return "";
2820
+ }
2821
+ }
2822
+ function getBunVersion() {
2823
+ try {
2824
+ const output = execSync2("bun --version", {
2825
+ encoding: "utf-8",
2826
+ stdio: "pipe"
2827
+ }).trim();
2828
+ return output;
2829
+ } catch {
2830
+ return null;
2831
+ }
2832
+ }
2833
+ function getRailwayVersion() {
2834
+ try {
2835
+ const output = execSync2("railway --version", {
2836
+ encoding: "utf-8",
2837
+ stdio: "pipe"
2838
+ }).trim();
2839
+ return output || null;
2840
+ } catch {
2841
+ return null;
2842
+ }
2843
+ }
2844
+ async function checkPrerequisites() {
2845
+ const nodeVersion = getNodeVersion();
2846
+ const bunVersion = getBunVersion();
2847
+ const railwayVersion = getRailwayVersion();
2848
+ return [
2849
+ {
2850
+ name: "Node.js",
2851
+ found: !!nodeVersion,
2852
+ version: nodeVersion || undefined
2853
+ },
2854
+ {
2855
+ name: "Bun",
2856
+ found: !!bunVersion,
2857
+ version: bunVersion || undefined,
2858
+ installUrl: bunVersion ? undefined : "https://bun.sh"
2859
+ },
2860
+ {
2861
+ name: "Railway CLI",
2862
+ found: !!railwayVersion,
2863
+ version: railwayVersion || undefined,
2864
+ installUrl: railwayVersion ? undefined : "https://docs.railway.com/cli"
2865
+ }
2866
+ ];
2867
+ }
2868
+ function displayPrerequisites(statuses) {
2869
+ for (const status of statuses) {
2870
+ if (status.found) {
2871
+ const version = status.version ? `v${status.version}` : "";
2872
+ const paddedName = status.name.padEnd(12);
2873
+ console.log(` ${import_picocolors.default.green("✓")} ${paddedName} ${version}`);
2874
+ } else {
2875
+ const paddedName = status.name.padEnd(12);
2876
+ const installMsg = status.installUrl ? `not found. Install: ${status.installUrl}` : "not found";
2877
+ console.log(` ${import_picocolors.default.red("✗")} ${paddedName} ${installMsg}`);
2878
+ }
2879
+ }
2880
+ }
2881
+ async function displayLlmStatus() {
2882
+ const paddedName = "LLM".padEnd(12);
2883
+ try {
2884
+ const { isLlmConfigured: isLlmConfigured2, getLlmConfig: getLlmConfig2 } = await Promise.resolve().then(() => (init_config(), exports_config));
2885
+ const [configured, config] = await Promise.all([isLlmConfigured2(), getLlmConfig2()]);
2886
+ if (configured && config) {
2887
+ const label = `${config.provider[0].toUpperCase()}${config.provider.slice(1)} (${config.model})`;
2888
+ console.log(` ${import_picocolors.default.green("✓")} ${paddedName} ${label}`);
2889
+ } else {
2890
+ console.log(` ${import_picocolors.default.yellow("!")} ${paddedName} not configured`);
2891
+ }
2892
+ } catch {
2893
+ console.log(` ${import_picocolors.default.yellow("!")} ${paddedName} not configured`);
2894
+ }
2895
+ }
2896
+
2897
+ // src/utils/auth-guard.ts
2898
+ init_config();
2899
+
2900
+ // src/credentials/railway.ts
2901
+ import { execSync as execSync3 } from "node:child_process";
2902
+ async function isRailwayInstalled() {
2903
+ try {
2904
+ execSync3("railway --version", {
2905
+ encoding: "utf-8",
2906
+ stdio: "pipe"
2907
+ });
2908
+ return true;
2909
+ } catch {
2910
+ return false;
2911
+ }
2912
+ }
2913
+ async function checkRailwayAuth() {
2914
+ const installed = await isRailwayInstalled();
2915
+ if (!installed) {
2916
+ return {
2917
+ authenticated: false,
2918
+ error: "Railway CLI not installed"
2919
+ };
2920
+ }
2921
+ try {
2922
+ const output = execSync3("railway whoami", {
2923
+ encoding: "utf-8",
2924
+ stdio: "pipe"
2925
+ }).trim();
2926
+ if (output && output.length > 0) {
2927
+ return {
2928
+ authenticated: true,
2929
+ username: output
2930
+ };
2931
+ }
2932
+ return {
2933
+ authenticated: false
2934
+ };
2935
+ } catch {
240
2936
  return {
241
- verbose: options.verbose,
242
- quiet: options.quiet,
243
- dryRun: options.dryRun,
244
- yes: options.yes,
245
- debug: options.debug ?? false,
246
- config: options.config,
247
- env: options.env,
248
- noUpdateCheck: options.updateCheck === false
2937
+ authenticated: false
249
2938
  };
2939
+ }
2940
+ }
2941
+
2942
+ // src/utils/auth-guard.ts
2943
+ var COMMAND_AUTH = {
2944
+ login: "none",
2945
+ logout: "none",
2946
+ help: "none",
2947
+ settings: "none",
2948
+ list: "none",
2949
+ versions: "none",
2950
+ exit: "none",
2951
+ init: "both",
2952
+ create: "both",
2953
+ delete: "both",
2954
+ deploy: "both",
2955
+ "deploy:template": "both",
2956
+ "env:create": "both",
2957
+ "env:vars": "both",
2958
+ domain: "both",
2959
+ logs: "both",
2960
+ status: "both"
2961
+ };
2962
+ async function checkAuthGuard(commandKey) {
2963
+ const requirement = COMMAND_AUTH[commandKey];
2964
+ if (!requirement || requirement === "none") {
2965
+ return { allowed: true };
2966
+ }
2967
+ if (requirement === "llm" || requirement === "both") {
2968
+ const llmConfigured = await isLlmConfigured();
2969
+ if (!llmConfigured) {
2970
+ return {
2971
+ allowed: false,
2972
+ message: "LLM API key required. Run /login llm to configure."
2973
+ };
2974
+ }
2975
+ }
2976
+ if (requirement === "railway" || requirement === "both") {
2977
+ const railwayStatus = await checkRailwayAuth();
2978
+ if (!railwayStatus.authenticated) {
2979
+ return {
2980
+ allowed: false,
2981
+ message: "Railway authentication required. Run /login railway to authenticate."
2982
+ };
2983
+ }
2984
+ }
2985
+ return { allowed: true };
2986
+ }
2987
+
2988
+ // node_modules/@clack/core/dist/index.mjs
2989
+ var import_sisteransi = __toESM(require_src(), 1);
2990
+ function DD({ onlyFirst: e = false } = {}) {
2991
+ const t = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");
2992
+ return new RegExp(t, e ? undefined : "g");
2993
+ }
2994
+ var uD = DD();
2995
+ function L(e) {
2996
+ return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e;
2997
+ }
2998
+ var W = { exports: {} };
2999
+ (function(e) {
3000
+ var u = {};
3001
+ e.exports = u, u.eastAsianWidth = function(F) {
3002
+ var s = F.charCodeAt(0), i = F.length == 2 ? F.charCodeAt(1) : 0, D = s;
3003
+ return 55296 <= s && s <= 56319 && 56320 <= i && i <= 57343 && (s &= 1023, i &= 1023, D = s << 10 | i, D += 65536), D == 12288 || 65281 <= D && D <= 65376 || 65504 <= D && D <= 65510 ? "F" : D == 8361 || 65377 <= D && D <= 65470 || 65474 <= D && D <= 65479 || 65482 <= D && D <= 65487 || 65490 <= D && D <= 65495 || 65498 <= D && D <= 65500 || 65512 <= D && D <= 65518 ? "H" : 4352 <= D && D <= 4447 || 4515 <= D && D <= 4519 || 4602 <= D && D <= 4607 || 9001 <= D && D <= 9002 || 11904 <= D && D <= 11929 || 11931 <= D && D <= 12019 || 12032 <= D && D <= 12245 || 12272 <= D && D <= 12283 || 12289 <= D && D <= 12350 || 12353 <= D && D <= 12438 || 12441 <= D && D <= 12543 || 12549 <= D && D <= 12589 || 12593 <= D && D <= 12686 || 12688 <= D && D <= 12730 || 12736 <= D && D <= 12771 || 12784 <= D && D <= 12830 || 12832 <= D && D <= 12871 || 12880 <= D && D <= 13054 || 13056 <= D && D <= 19903 || 19968 <= D && D <= 42124 || 42128 <= D && D <= 42182 || 43360 <= D && D <= 43388 || 44032 <= D && D <= 55203 || 55216 <= D && D <= 55238 || 55243 <= D && D <= 55291 || 63744 <= D && D <= 64255 || 65040 <= D && D <= 65049 || 65072 <= D && D <= 65106 || 65108 <= D && D <= 65126 || 65128 <= D && D <= 65131 || 110592 <= D && D <= 110593 || 127488 <= D && D <= 127490 || 127504 <= D && D <= 127546 || 127552 <= D && D <= 127560 || 127568 <= D && D <= 127569 || 131072 <= D && D <= 194367 || 177984 <= D && D <= 196605 || 196608 <= D && D <= 262141 ? "W" : 32 <= D && D <= 126 || 162 <= D && D <= 163 || 165 <= D && D <= 166 || D == 172 || D == 175 || 10214 <= D && D <= 10221 || 10629 <= D && D <= 10630 ? "Na" : D == 161 || D == 164 || 167 <= D && D <= 168 || D == 170 || 173 <= D && D <= 174 || 176 <= D && D <= 180 || 182 <= D && D <= 186 || 188 <= D && D <= 191 || D == 198 || D == 208 || 215 <= D && D <= 216 || 222 <= D && D <= 225 || D == 230 || 232 <= D && D <= 234 || 236 <= D && D <= 237 || D == 240 || 242 <= D && D <= 243 || 247 <= D && D <= 250 || D == 252 || D == 254 || D == 257 || D == 273 || D == 275 || D == 283 || 294 <= D && D <= 295 || D == 299 || 305 <= D && D <= 307 || D == 312 || 319 <= D && D <= 322 || D == 324 || 328 <= D && D <= 331 || D == 333 || 338 <= D && D <= 339 || 358 <= D && D <= 359 || D == 363 || D == 462 || D == 464 || D == 466 || D == 468 || D == 470 || D == 472 || D == 474 || D == 476 || D == 593 || D == 609 || D == 708 || D == 711 || 713 <= D && D <= 715 || D == 717 || D == 720 || 728 <= D && D <= 731 || D == 733 || D == 735 || 768 <= D && D <= 879 || 913 <= D && D <= 929 || 931 <= D && D <= 937 || 945 <= D && D <= 961 || 963 <= D && D <= 969 || D == 1025 || 1040 <= D && D <= 1103 || D == 1105 || D == 8208 || 8211 <= D && D <= 8214 || 8216 <= D && D <= 8217 || 8220 <= D && D <= 8221 || 8224 <= D && D <= 8226 || 8228 <= D && D <= 8231 || D == 8240 || 8242 <= D && D <= 8243 || D == 8245 || D == 8251 || D == 8254 || D == 8308 || D == 8319 || 8321 <= D && D <= 8324 || D == 8364 || D == 8451 || D == 8453 || D == 8457 || D == 8467 || D == 8470 || 8481 <= D && D <= 8482 || D == 8486 || D == 8491 || 8531 <= D && D <= 8532 || 8539 <= D && D <= 8542 || 8544 <= D && D <= 8555 || 8560 <= D && D <= 8569 || D == 8585 || 8592 <= D && D <= 8601 || 8632 <= D && D <= 8633 || D == 8658 || D == 8660 || D == 8679 || D == 8704 || 8706 <= D && D <= 8707 || 8711 <= D && D <= 8712 || D == 8715 || D == 8719 || D == 8721 || D == 8725 || D == 8730 || 8733 <= D && D <= 8736 || D == 8739 || D == 8741 || 8743 <= D && D <= 8748 || D == 8750 || 8756 <= D && D <= 8759 || 8764 <= D && D <= 8765 || D == 8776 || D == 8780 || D == 8786 || 8800 <= D && D <= 8801 || 8804 <= D && D <= 8807 || 8810 <= D && D <= 8811 || 8814 <= D && D <= 8815 || 8834 <= D && D <= 8835 || 8838 <= D && D <= 8839 || D == 8853 || D == 8857 || D == 8869 || D == 8895 || D == 8978 || 9312 <= D && D <= 9449 || 9451 <= D && D <= 9547 || 9552 <= D && D <= 9587 || 9600 <= D && D <= 9615 || 9618 <= D && D <= 9621 || 9632 <= D && D <= 9633 || 9635 <= D && D <= 9641 || 9650 <= D && D <= 9651 || 9654 <= D && D <= 9655 || 9660 <= D && D <= 9661 || 9664 <= D && D <= 9665 || 9670 <= D && D <= 9672 || D == 9675 || 9678 <= D && D <= 9681 || 9698 <= D && D <= 9701 || D == 9711 || 9733 <= D && D <= 9734 || D == 9737 || 9742 <= D && D <= 9743 || 9748 <= D && D <= 9749 || D == 9756 || D == 9758 || D == 9792 || D == 9794 || 9824 <= D && D <= 9825 || 9827 <= D && D <= 9829 || 9831 <= D && D <= 9834 || 9836 <= D && D <= 9837 || D == 9839 || 9886 <= D && D <= 9887 || 9918 <= D && D <= 9919 || 9924 <= D && D <= 9933 || 9935 <= D && D <= 9953 || D == 9955 || 9960 <= D && D <= 9983 || D == 10045 || D == 10071 || 10102 <= D && D <= 10111 || 11093 <= D && D <= 11097 || 12872 <= D && D <= 12879 || 57344 <= D && D <= 63743 || 65024 <= D && D <= 65039 || D == 65533 || 127232 <= D && D <= 127242 || 127248 <= D && D <= 127277 || 127280 <= D && D <= 127337 || 127344 <= D && D <= 127386 || 917760 <= D && D <= 917999 || 983040 <= D && D <= 1048573 || 1048576 <= D && D <= 1114109 ? "A" : "N";
3004
+ }, u.characterLength = function(F) {
3005
+ var s = this.eastAsianWidth(F);
3006
+ return s == "F" || s == "W" || s == "A" ? 2 : 1;
3007
+ };
3008
+ function t(F) {
3009
+ return F.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g) || [];
3010
+ }
3011
+ u.length = function(F) {
3012
+ for (var s = t(F), i = 0, D = 0;D < s.length; D++)
3013
+ i = i + this.characterLength(s[D]);
3014
+ return i;
3015
+ }, u.slice = function(F, s, i) {
3016
+ textLen = u.length(F), s = s || 0, i = i || 1, s < 0 && (s = textLen + s), i < 0 && (i = textLen + i);
3017
+ for (var D = "", C = 0, n = t(F), E = 0;E < n.length; E++) {
3018
+ var a = n[E], o = u.length(a);
3019
+ if (C >= s - (o == 2 ? 1 : 0))
3020
+ if (C + o <= i)
3021
+ D += a;
3022
+ else
3023
+ break;
3024
+ C += o;
3025
+ }
3026
+ return D;
3027
+ };
3028
+ })(W);
3029
+ var tD = W.exports;
3030
+ var eD = L(tD);
3031
+ var FD = function() {
3032
+ return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
3033
+ };
3034
+ var sD = L(FD);
3035
+ var w = 10;
3036
+ var N = (e = 0) => (u) => `\x1B[${u + e}m`;
3037
+ var I = (e = 0) => (u) => `\x1B[${38 + e};5;${u}m`;
3038
+ var R = (e = 0) => (u, t, F) => `\x1B[${38 + e};2;${u};${t};${F}m`;
3039
+ var r = { modifier: { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], blackBright: [90, 39], gray: [90, 39], grey: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgGray: [100, 49], bgGrey: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } };
3040
+ Object.keys(r.modifier);
3041
+ var iD = Object.keys(r.color);
3042
+ var CD = Object.keys(r.bgColor);
3043
+ [...iD, ...CD];
3044
+ function rD() {
3045
+ const e = new Map;
3046
+ for (const [u, t] of Object.entries(r)) {
3047
+ for (const [F, s] of Object.entries(t))
3048
+ r[F] = { open: `\x1B[${s[0]}m`, close: `\x1B[${s[1]}m` }, t[F] = r[F], e.set(s[0], s[1]);
3049
+ Object.defineProperty(r, u, { value: t, enumerable: false });
3050
+ }
3051
+ return Object.defineProperty(r, "codes", { value: e, enumerable: false }), r.color.close = "\x1B[39m", r.bgColor.close = "\x1B[49m", r.color.ansi = N(), r.color.ansi256 = I(), r.color.ansi16m = R(), r.bgColor.ansi = N(w), r.bgColor.ansi256 = I(w), r.bgColor.ansi16m = R(w), Object.defineProperties(r, { rgbToAnsi256: { value: (u, t, F) => u === t && t === F ? u < 8 ? 16 : u > 248 ? 231 : Math.round((u - 8) / 247 * 24) + 232 : 16 + 36 * Math.round(u / 255 * 5) + 6 * Math.round(t / 255 * 5) + Math.round(F / 255 * 5), enumerable: false }, hexToRgb: { value: (u) => {
3052
+ const t = /[a-f\d]{6}|[a-f\d]{3}/i.exec(u.toString(16));
3053
+ if (!t)
3054
+ return [0, 0, 0];
3055
+ let [F] = t;
3056
+ F.length === 3 && (F = [...F].map((i) => i + i).join(""));
3057
+ const s = Number.parseInt(F, 16);
3058
+ return [s >> 16 & 255, s >> 8 & 255, s & 255];
3059
+ }, enumerable: false }, hexToAnsi256: { value: (u) => r.rgbToAnsi256(...r.hexToRgb(u)), enumerable: false }, ansi256ToAnsi: { value: (u) => {
3060
+ if (u < 8)
3061
+ return 30 + u;
3062
+ if (u < 16)
3063
+ return 90 + (u - 8);
3064
+ let t, F, s;
3065
+ if (u >= 232)
3066
+ t = ((u - 232) * 10 + 8) / 255, F = t, s = t;
3067
+ else {
3068
+ u -= 16;
3069
+ const C = u % 36;
3070
+ t = Math.floor(u / 36) / 5, F = Math.floor(C / 6) / 5, s = C % 6 / 5;
3071
+ }
3072
+ const i = Math.max(t, F, s) * 2;
3073
+ if (i === 0)
3074
+ return 30;
3075
+ let D = 30 + (Math.round(s) << 2 | Math.round(F) << 1 | Math.round(t));
3076
+ return i === 2 && (D += 60), D;
3077
+ }, enumerable: false }, rgbToAnsi: { value: (u, t, F) => r.ansi256ToAnsi(r.rgbToAnsi256(u, t, F)), enumerable: false }, hexToAnsi: { value: (u) => r.ansi256ToAnsi(r.hexToAnsi256(u)), enumerable: false } }), r;
3078
+ }
3079
+ var ED = rD();
3080
+ var d = new Set(["\x1B", "›"]);
3081
+ var nD = "]";
3082
+ var _ = `${nD}8;;`;
3083
+ var xD = ["up", "down", "left", "right", "space", "enter", "cancel"];
3084
+ var B = { actions: new Set(xD), aliases: new Map([["k", "up"], ["j", "down"], ["h", "left"], ["l", "right"], ["\x03", "cancel"], ["escape", "cancel"]]) };
3085
+ var AD = globalThis.process.platform.startsWith("win");
3086
+ var S = Symbol("clack:cancel");
3087
+ var A;
3088
+ A = new WeakMap;
3089
+
3090
+ // node_modules/@clack/prompts/dist/index.mjs
3091
+ var import_picocolors2 = __toESM(require_picocolors(), 1);
3092
+ var import_sisteransi2 = __toESM(require_src(), 1);
3093
+ import y from "node:process";
3094
+ function ce() {
3095
+ return y.platform !== "win32" ? y.env.TERM !== "linux" : !!y.env.CI || !!y.env.WT_SESSION || !!y.env.TERMINUS_SUBLIME || y.env.ConEmuTask === "{cmd::Cmder}" || y.env.TERM_PROGRAM === "Terminus-Sublime" || y.env.TERM_PROGRAM === "vscode" || y.env.TERM === "xterm-256color" || y.env.TERM === "alacritty" || y.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
3096
+ }
3097
+ var V = ce();
3098
+ var u = (t, n) => V ? t : n;
3099
+ var le = u("◆", "*");
3100
+ var L2 = u("■", "x");
3101
+ var W2 = u("▲", "x");
3102
+ var C = u("◇", "o");
3103
+ var ue = u("┌", "T");
3104
+ var o = u("│", "|");
3105
+ var d2 = u("└", "—");
3106
+ var k = u("●", ">");
3107
+ var P = u("○", " ");
3108
+ var A2 = u("◻", "[•]");
3109
+ var T = u("◼", "[+]");
3110
+ var F = u("◻", "[ ]");
3111
+ var $e = u("▪", "•");
3112
+ var _2 = u("─", "-");
3113
+ var me = u("╮", "+");
3114
+ var de = u("├", "+");
3115
+ var pe = u("╯", "+");
3116
+ var q = u("●", "•");
3117
+ var D = u("◆", "*");
3118
+ var U = u("▲", "!");
3119
+ var K = u("■", "x");
3120
+ var J = `${import_picocolors2.default.gray(o)} `;
3121
+
3122
+ // src/utils/display.ts
3123
+ var import_picocolors3 = __toESM(require_picocolors(), 1);
3124
+ function warn(message) {
3125
+ console.log(`${import_picocolors3.default.yellow("⚠")} ${message}`);
3126
+ }
3127
+
3128
+ // src/sandbox/staging.ts
3129
+ import {
3130
+ copyFileSync,
3131
+ existsSync as existsSync3,
3132
+ mkdirSync as mkdirSync3,
3133
+ readdirSync,
3134
+ readFileSync as readFileSync3,
3135
+ rmSync as rmSync2,
3136
+ statSync as statSync3,
3137
+ writeFileSync as writeFileSync3
3138
+ } from "node:fs";
3139
+ import { dirname, join as join3, relative } from "node:path";
3140
+
3141
+ // src/audit/logger.ts
3142
+ import {
3143
+ appendFileSync,
3144
+ existsSync as existsSync2,
3145
+ mkdirSync as mkdirSync2,
3146
+ renameSync as renameSync2,
3147
+ rmSync,
3148
+ statSync as statSync2,
3149
+ writeFileSync as writeFileSync2
3150
+ } from "node:fs";
3151
+ import { join as join2 } from "node:path";
3152
+ var AUDIT_DIR_NAME = ".kitt";
3153
+ var AUDIT_FILE_NAME = "audit.log";
3154
+ var ROTATED_LOG_1 = "audit.log.1";
3155
+ var ROTATED_LOG_2 = "audit.log.2";
3156
+ var MAX_LOG_SIZE_BYTES = 10 * 1024 * 1024;
3157
+ function formatLine(type, message) {
3158
+ return `[${new Date().toISOString()}] ${type} ${message}
3159
+ `;
3160
+ }
3161
+ function ensureAuditDir(auditDir) {
3162
+ if (existsSync2(auditDir)) {
3163
+ return;
3164
+ }
3165
+ mkdirSync2(auditDir, { recursive: true, mode: 448 });
3166
+ }
3167
+ function rotateLogIfNeeded(logPath, log1Path, log2Path) {
3168
+ if (!existsSync2(logPath)) {
3169
+ return;
3170
+ }
3171
+ const stats = statSync2(logPath);
3172
+ if (stats.size < MAX_LOG_SIZE_BYTES) {
3173
+ return;
3174
+ }
3175
+ if (existsSync2(log2Path)) {
3176
+ rmSync(log2Path, { force: true });
3177
+ }
3178
+ if (existsSync2(log1Path)) {
3179
+ renameSync2(log1Path, log2Path);
3180
+ }
3181
+ renameSync2(logPath, log1Path);
3182
+ writeFileSync2(logPath, "", { encoding: "utf8", mode: 384 });
3183
+ }
3184
+ function writeAuditLine(logPath, log1Path, log2Path, type, message) {
3185
+ try {
3186
+ rotateLogIfNeeded(logPath, log1Path, log2Path);
3187
+ appendFileSync(logPath, formatLine(type, message), { encoding: "utf8", mode: 384 });
3188
+ } catch {
3189
+ return;
3190
+ }
3191
+ }
3192
+ function createAuditLogger(workspaceDir) {
3193
+ const auditDir = join2(workspaceDir, AUDIT_DIR_NAME);
3194
+ const logPath = join2(auditDir, AUDIT_FILE_NAME);
3195
+ const log1Path = join2(auditDir, ROTATED_LOG_1);
3196
+ const log2Path = join2(auditDir, ROTATED_LOG_2);
3197
+ return {
3198
+ log(type, message) {
3199
+ try {
3200
+ ensureAuditDir(auditDir);
3201
+ } catch {
3202
+ return;
3203
+ }
3204
+ writeAuditLine(logPath, log1Path, log2Path, type, message);
3205
+ },
3206
+ cmd(command, status, detail) {
3207
+ const suffix = detail ? ` (${detail})` : "";
3208
+ this.log("CMD", `${command} → ${status}${suffix}`);
3209
+ },
3210
+ cmdExec(command, status) {
3211
+ this.log("CMD_EXEC", `${command} → ${status}`);
3212
+ },
3213
+ mcp(tool, params, status, detail) {
3214
+ const suffix = detail ? ` (${detail})` : "";
3215
+ this.log("MCP", `${tool} (${params}) → ${status}${suffix}`);
3216
+ },
3217
+ llmCall(provider, model, promptVersion, estimatedTokens, status) {
3218
+ this.log("LLM_CALL", `${provider}/${model} (prompt: ${promptVersion}, est. ${estimatedTokens} tokens) → ${status}`);
3219
+ },
3220
+ fileWrite(path, hash) {
3221
+ const suffix = hash ? ` (SHA-256: ${hash})` : "";
3222
+ this.log("FILE_WRITE", `${path}${suffix}`);
3223
+ },
3224
+ staged(path, detail) {
3225
+ this.log("STAGED", `${path} (${detail})`);
3226
+ },
3227
+ userConfirmed() {
3228
+ this.log("USER_CONFIRMED", "staged changes");
3229
+ },
3230
+ security(action, message) {
3231
+ this.log("SECURITY", `${action} ${message}`);
3232
+ }
3233
+ };
3234
+ }
3235
+
3236
+ // src/sandbox/staging.ts
3237
+ var KITT_DIR = ".kitt";
3238
+ var STAGING_DIR = "staging";
3239
+ function getStagingDir(workspaceDir) {
3240
+ return join3(workspaceDir, KITT_DIR, STAGING_DIR);
3241
+ }
3242
+ function clearStaging(workspaceDir) {
3243
+ const logger = createAuditLogger(workspaceDir);
3244
+ const stagingDir = getStagingDir(workspaceDir);
3245
+ if (existsSync3(stagingDir)) {
3246
+ rmSync2(stagingDir, { recursive: true, force: true });
3247
+ }
3248
+ mkdirSync3(stagingDir, { recursive: true });
3249
+ logger.staged(join3(KITT_DIR, STAGING_DIR), "cleared");
3250
+ }
3251
+
3252
+ // src/utils/cleanup.ts
3253
+ var cleanupRegistered = false;
3254
+ var replMode = false;
3255
+ function setReplMode(value) {
3256
+ replMode = value;
3257
+ }
3258
+ function handleCleanupSignal(signal) {
3259
+ let cleared = false;
3260
+ try {
3261
+ clearStaging(".");
3262
+ cleared = true;
3263
+ } catch {}
3264
+ if (replMode) {
3265
+ return;
3266
+ }
3267
+ if (cleared) {
3268
+ warn(`Interrupted (${signal}). Staging cleared.`);
3269
+ }
3270
+ const exitCode = signal === "SIGINT" ? 130 : 143;
3271
+ process.exit(exitCode);
3272
+ }
3273
+ function registerCleanupHandlers() {
3274
+ if (cleanupRegistered) {
3275
+ return;
3276
+ }
3277
+ cleanupRegistered = true;
3278
+ process.on("SIGINT", () => {
3279
+ handleCleanupSignal("SIGINT");
3280
+ });
3281
+ process.on("SIGTERM", () => {
3282
+ handleCleanupSignal("SIGTERM");
3283
+ });
3284
+ }
3285
+
3286
+ // src/manifest/reader.ts
3287
+ import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
3288
+ import { join as join5, dirname as dirname2, resolve } from "node:path";
3289
+
3290
+ // src/utils/global-config.ts
3291
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "node:fs";
3292
+ import { homedir as homedir2 } from "node:os";
3293
+ import { join as join4 } from "node:path";
3294
+ function getGlobalConfigPath() {
3295
+ return join4(homedir2(), ".kitt", "workspace.json");
3296
+ }
3297
+ function readGlobalConfig() {
3298
+ const configPath = getGlobalConfigPath();
3299
+ if (!existsSync4(configPath)) {
3300
+ return {};
3301
+ }
3302
+ try {
3303
+ const raw = readFileSync4(configPath, "utf-8").trim();
3304
+ if (!raw)
3305
+ return {};
3306
+ const parsed = JSON.parse(raw);
3307
+ if (typeof parsed === "object" && parsed !== null) {
3308
+ return parsed;
3309
+ }
3310
+ return {};
3311
+ } catch {
3312
+ return {};
3313
+ }
3314
+ }
3315
+ function getGlobalWorkspacePath() {
3316
+ return readGlobalConfig().workspacePath ?? null;
3317
+ }
3318
+
3319
+ // src/manifest/reader.ts
3320
+ function isObjectRecord(value) {
3321
+ return typeof value === "object" && value !== null;
3322
+ }
3323
+ function isValidWorkspaceManifest(value) {
3324
+ if (!isObjectRecord(value)) {
3325
+ return false;
3326
+ }
3327
+ if (typeof value.version !== "string") {
3328
+ return false;
3329
+ }
3330
+ if (!isObjectRecord(value.workspace)) {
3331
+ return false;
3332
+ }
3333
+ if (typeof value.workspace.name !== "string") {
3334
+ return false;
3335
+ }
3336
+ const packageManager = value.workspace.packageManager;
3337
+ if (packageManager !== "bun" && packageManager !== "npm" && packageManager !== "pnpm" && packageManager !== "yarn") {
3338
+ return false;
3339
+ }
3340
+ if (!isObjectRecord(value.apps)) {
3341
+ return false;
3342
+ }
3343
+ if (!isObjectRecord(value.packages)) {
3344
+ return false;
3345
+ }
3346
+ if (!isObjectRecord(value.settings)) {
3347
+ return false;
3348
+ }
3349
+ return true;
3350
+ }
3351
+ function getManifestPath(workspaceDir) {
3352
+ return join5(workspaceDir, ".kitt", "manifest.json");
3353
+ }
3354
+ function isKittWorkspace(dir) {
3355
+ return existsSync5(getManifestPath(dir));
3356
+ }
3357
+ function findWorkspaceRoot(startDir) {
3358
+ let current = resolve(startDir);
3359
+ while (true) {
3360
+ if (isKittWorkspace(current))
3361
+ return current;
3362
+ const parent = dirname2(current);
3363
+ if (parent === current)
3364
+ break;
3365
+ current = parent;
3366
+ }
3367
+ const globalPath = getGlobalWorkspacePath();
3368
+ if (globalPath && isKittWorkspace(globalPath))
3369
+ return globalPath;
3370
+ return null;
3371
+ }
3372
+ function readManifest(workspaceDir) {
3373
+ const manifestPath = getManifestPath(workspaceDir);
3374
+ if (!existsSync5(manifestPath)) {
3375
+ return null;
3376
+ }
3377
+ try {
3378
+ const raw = readFileSync5(manifestPath, "utf-8").trim();
3379
+ if (raw.length === 0) {
3380
+ return null;
3381
+ }
3382
+ const parsed = JSON.parse(raw);
3383
+ if (!isValidWorkspaceManifest(parsed)) {
3384
+ return null;
3385
+ }
3386
+ return parsed;
3387
+ } catch {
3388
+ return null;
3389
+ }
3390
+ }
3391
+
3392
+ // src/cli.ts
3393
+ var APP_VERSION = JSON.parse(readFileSync6(new URL("../package.json", import.meta.url), "utf-8")).version;
3394
+ var BASE_PROMPT = "kitt";
3395
+ var UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
3396
+ var UPDATE_CHECK_TIMEOUT_MS = 5000;
3397
+ var STATE_CHANGING_COMMANDS = new Set([
3398
+ "init",
3399
+ "create",
3400
+ "delete",
3401
+ "deploy",
3402
+ "deploy:template",
3403
+ "env:create",
3404
+ "env:vars",
3405
+ "domain",
3406
+ "publish"
3407
+ ]);
3408
+ var KITT_DIR2 = join6(homedir3(), ".kitt");
3409
+ var UPDATE_CHECK_FILE = join6(KITT_DIR2, "update-check.json");
3410
+ var commandRegistry = {
3411
+ init: { modulePath: "./commands/init.js" },
3412
+ create: { modulePath: "./commands/create.js" },
3413
+ delete: { modulePath: "./commands/delete.js" },
3414
+ deploy: { modulePath: "./commands/deploy.js" },
3415
+ "deploy:template": { modulePath: "./commands/deploy.js" },
3416
+ "env:create": { modulePath: "./commands/env.js" },
3417
+ "env:vars": { modulePath: "./commands/env.js" },
3418
+ domain: { modulePath: "./commands/domain.js" },
3419
+ logs: { modulePath: "./commands/logs.js" },
3420
+ status: { modulePath: "./commands/status.js" },
3421
+ login: { modulePath: "./commands/login.js" },
3422
+ logout: { modulePath: "./commands/login.js" },
3423
+ settings: { modulePath: "./commands/settings.js" },
3424
+ versions: { modulePath: "./commands/versions.js" },
3425
+ list: { modulePath: "./commands/list.js" },
3426
+ run: { modulePath: "./commands/run.js" },
3427
+ publish: { modulePath: "./commands/publish.js" },
3428
+ help: { modulePath: "./commands/help.js" }
3429
+ };
3430
+ function displayBanner() {
3431
+ console.log(import_picocolors4.default.cyan(" ______ _______________________"));
3432
+ console.log(import_picocolors4.default.cyan(" ___ //_/___ /__ __/__ __/"));
3433
+ console.log(import_picocolors4.default.cyan(" __ ,< __ / __ / __ / "));
3434
+ console.log(import_picocolors4.default.cyan(" _ /| | __/ / _ / _ / "));
3435
+ console.log(import_picocolors4.default.cyan(" /_/ |_| /___/ /_/ /_/ "));
3436
+ console.log("");
3437
+ console.log(` ${import_picocolors4.default.bold(import_picocolors4.default.white("KITT"))} ${import_picocolors4.default.dim("v" + APP_VERSION)} ${import_picocolors4.default.dim("— AI-Powered App Scaffolding CLI")}`);
3438
+ console.log(` ${import_picocolors4.default.dim("/login → /init → /create → /deploy → /publish")}`);
3439
+ console.log(` ${import_picocolors4.default.dim("Type /help for all commands")}`);
3440
+ console.log("");
3441
+ }
3442
+ function tokenizeCommand(inputValue) {
3443
+ const tokenPattern = /"([^"]*)"|'([^']*)'|`([^`]*)`|(\S+)/g;
3444
+ const tokens = [];
3445
+ let match = tokenPattern.exec(inputValue);
3446
+ while (match !== null) {
3447
+ tokens.push(match[1] ?? match[2] ?? match[3] ?? match[4]);
3448
+ match = tokenPattern.exec(inputValue);
3449
+ }
3450
+ return tokens;
3451
+ }
3452
+ function parseCommand(inputValue) {
3453
+ const trimmed = inputValue.trim();
3454
+ if (trimmed.length === 0) {
3455
+ return;
3456
+ }
3457
+ const parts = tokenizeCommand(trimmed);
3458
+ if (parts.length === 0) {
3459
+ return;
3460
+ }
3461
+ const rawCommand = parts[0];
3462
+ const normalized = rawCommand.startsWith("/") ? rawCommand : `/${rawCommand}`;
3463
+ return {
3464
+ key: normalized.slice(1).toLowerCase(),
3465
+ displayName: normalized,
3466
+ args: parts.slice(1)
3467
+ };
3468
+ }
3469
+ function isVersionNewer(latest, current) {
3470
+ const normalize = (value) => {
3471
+ const [main] = value.trim().replace(/^v/i, "").split("-");
3472
+ return main.split(".").map((segment) => Number.parseInt(segment, 10)).map((segment) => Number.isFinite(segment) ? segment : 0);
3473
+ };
3474
+ const latestParts = normalize(latest);
3475
+ const currentParts = normalize(current);
3476
+ const maxLen = Math.max(latestParts.length, currentParts.length);
3477
+ for (let index = 0;index < maxLen; index += 1) {
3478
+ const latestPart = latestParts[index] ?? 0;
3479
+ const currentPart = currentParts[index] ?? 0;
3480
+ if (latestPart > currentPart) {
3481
+ return true;
3482
+ }
3483
+ if (latestPart < currentPart) {
3484
+ return false;
3485
+ }
3486
+ }
3487
+ return false;
3488
+ }
3489
+ function hasFreshUpdateCache(now) {
3490
+ if (!existsSync6(UPDATE_CHECK_FILE)) {
3491
+ return false;
3492
+ }
3493
+ try {
3494
+ const rawCache = readFileSync6(UPDATE_CHECK_FILE, "utf-8").trim();
3495
+ if (rawCache.length === 0) {
3496
+ return false;
3497
+ }
3498
+ const parsed = JSON.parse(rawCache);
3499
+ if (typeof parsed.checkedAt !== "string") {
3500
+ return false;
3501
+ }
3502
+ const checkedAtMs = Date.parse(parsed.checkedAt);
3503
+ if (!Number.isFinite(checkedAtMs)) {
3504
+ return false;
3505
+ }
3506
+ return now.getTime() - checkedAtMs < UPDATE_CHECK_INTERVAL_MS;
3507
+ } catch {
3508
+ return false;
3509
+ }
3510
+ }
3511
+ function writeUpdateCache(now, latestVersion) {
3512
+ mkdirSync5(KITT_DIR2, { recursive: true });
3513
+ const payload = {
3514
+ checkedAt: now.toISOString(),
3515
+ latestVersion
3516
+ };
3517
+ writeFileSync5(UPDATE_CHECK_FILE, `${JSON.stringify(payload, null, 2)}
3518
+ `, "utf-8");
3519
+ }
3520
+ async function checkForUpdates(context) {
3521
+ if (context.noUpdateCheck) {
3522
+ return;
3523
+ }
3524
+ const now = new Date;
3525
+ if (hasFreshUpdateCache(now)) {
3526
+ return;
3527
+ }
3528
+ const controller = new AbortController;
3529
+ const timeoutId = setTimeout(() => {
3530
+ controller.abort();
3531
+ }, UPDATE_CHECK_TIMEOUT_MS);
3532
+ try {
3533
+ const response = await fetch("https://registry.npmjs.org/openkitt/latest", {
3534
+ signal: controller.signal
3535
+ });
3536
+ if (!response.ok) {
3537
+ return;
3538
+ }
3539
+ const payload = await response.json();
3540
+ if (typeof payload !== "object" || payload === null) {
3541
+ return;
3542
+ }
3543
+ const latestVersion = payload.version;
3544
+ if (typeof latestVersion !== "string" || latestVersion.length === 0) {
3545
+ return;
3546
+ }
3547
+ if (isVersionNewer(latestVersion, APP_VERSION)) {
3548
+ warn(`KITT v${latestVersion} is available (current: v${APP_VERSION}).
3549
+ Run "npm install -g openkitt@latest" to update,
3550
+ or use "npx openkitt@latest" on next launch.`);
3551
+ }
3552
+ writeUpdateCache(now, latestVersion);
3553
+ } catch {
3554
+ return;
3555
+ } finally {
3556
+ clearTimeout(timeoutId);
3557
+ }
3558
+ }
3559
+ async function resolveAndRunHandler(route, context, args, commandKey) {
3560
+ const loaded = await import(route.modulePath);
3561
+ const handler = loaded.default ?? loaded.run ?? loaded.handle;
3562
+ if (handler) {
3563
+ await handler(context, args, commandKey);
3564
+ }
3565
+ }
3566
+ async function dispatchCommand(commandLine, context) {
3567
+ const parsed = parseCommand(commandLine);
3568
+ if (!parsed) {
3569
+ return "continue";
3570
+ }
3571
+ if (parsed.key === "exit") {
3572
+ return "exit";
3573
+ }
3574
+ const route = commandRegistry[parsed.key];
3575
+ if (!route) {
3576
+ console.log(`Unknown command: ${parsed.displayName}. Type /help for available commands.`);
3577
+ return "unknown";
3578
+ }
3579
+ const authCheck = await checkAuthGuard(parsed.key);
3580
+ if (!authCheck.allowed) {
3581
+ console.log(import_picocolors4.default.red(`✗ ${authCheck.message}`));
3582
+ return "continue";
3583
+ }
3584
+ await resolveAndRunHandler(route, context, parsed.args, parsed.key);
3585
+ return "continue";
3586
+ }
3587
+ async function runSingleCommand(commandLine, context) {
3588
+ const parsed = parseCommand(commandLine);
3589
+ if (parsed && STATE_CHANGING_COMMANDS.has(parsed.key) && !context.yes) {
3590
+ console.log(import_picocolors4.default.red(`✗ Non-interactive mode requires --yes for state-changing commands.
3591
+ Usage: npx openkitt --run "${parsed.key}" --yes`));
3592
+ return 1;
3593
+ }
3594
+ const result = await dispatchCommand(commandLine, context);
3595
+ return result === "unknown" ? 1 : 0;
3596
+ }
3597
+ function createProgram() {
3598
+ const program2 = new Command;
3599
+ program2.name("openkitt").description("AI-powered app scaffolding CLI").version(APP_VERSION, "-v, --version", "Display current KITT version and exit.").helpOption("-h, --help", "Display available commands and flags.").option("--verbose", "Enable verbose output.").option("-q, --quiet", "Suppress non-essential output.").option("--run <command>", "Execute a single command and exit (non-interactive mode).").option("--dry-run", "Show proposed changes without executing.").option("-y, --yes", "Auto-confirm all prompts.").option("--config <json>", "Supply command selections as JSON.").option("--env <name>", "Target environment.").option("--no-update-check", "Skip automatic version check on launch.").option("--debug", "Show LLM timing and token usage after scaffolding.");
3600
+ return program2;
3601
+ }
3602
+ function buildAppContext(options) {
3603
+ return {
3604
+ verbose: options.verbose,
3605
+ quiet: options.quiet,
3606
+ dryRun: options.dryRun,
3607
+ yes: options.yes,
3608
+ debug: options.debug ?? false,
3609
+ config: options.config,
3610
+ env: options.env,
3611
+ noUpdateCheck: options.updateCheck === false
3612
+ };
250
3613
  }
251
3614
  function makeCompleter(registry) {
252
- const allCommands = [...Object.keys(registry), "exit"];
253
- const slashCommands = allCommands.map((cmd) => "/" + cmd);
254
- return (line) => {
255
- const trimmed = line.trimStart();
256
- if (trimmed === "" || trimmed.startsWith("/")) {
257
- const hits = slashCommands.filter((cmd) => cmd.startsWith(trimmed));
258
- return [hits.length > 0 ? hits : slashCommands, trimmed];
259
- }
260
- return [[], line];
261
- };
3615
+ const allCommands = [...Object.keys(registry), "exit"];
3616
+ const slashCommands = allCommands.map((cmd) => "/" + cmd);
3617
+ return (line) => {
3618
+ const trimmed = line.trimStart();
3619
+ if (trimmed === "" || trimmed.startsWith("/")) {
3620
+ const hits = slashCommands.filter((cmd) => cmd.startsWith(trimmed));
3621
+ return [hits.length > 0 ? hits : slashCommands, trimmed];
3622
+ }
3623
+ return [[], line];
3624
+ };
262
3625
  }
263
3626
  function getBestCompletion(line, registry) {
264
- const allCommands = [...Object.keys(registry), "exit"];
265
- const slashCommands = allCommands.map((cmd) => "/" + cmd);
266
- const trimmed = line.trimStart();
267
- if (trimmed.length === 0 || !trimmed.startsWith("/"))
268
- return "";
269
- const hits = slashCommands.filter((cmd) => cmd.startsWith(trimmed) && cmd !== trimmed);
270
- return hits.length === 1 ? hits[0].slice(trimmed.length) : "";
3627
+ const allCommands = [...Object.keys(registry), "exit"];
3628
+ const slashCommands = allCommands.map((cmd) => "/" + cmd);
3629
+ const trimmed = line.trimStart();
3630
+ if (trimmed.length === 0 || !trimmed.startsWith("/"))
3631
+ return "";
3632
+ const hits = slashCommands.filter((cmd) => cmd.startsWith(trimmed) && cmd !== trimmed);
3633
+ return hits.length === 1 ? hits[0].slice(trimmed.length) : "";
271
3634
  }
272
3635
  function resolvePrompt() {
273
- const workspaceRoot = findWorkspaceRoot(process.cwd());
274
- if (!workspaceRoot)
275
- return `${BASE_PROMPT} > `;
276
- const manifest = readManifest(workspaceRoot);
277
- const name = manifest?.workspace.name ?? basename(workspaceRoot);
278
- return `${BASE_PROMPT} ${pc.cyan(`[${name}]`)} > `;
3636
+ const workspaceRoot = findWorkspaceRoot(process.cwd());
3637
+ if (!workspaceRoot)
3638
+ return `${BASE_PROMPT} > `;
3639
+ const manifest = readManifest(workspaceRoot);
3640
+ const name = manifest?.workspace.name ?? basename(workspaceRoot);
3641
+ return `${BASE_PROMPT} ${import_picocolors4.default.cyan(`[${name}]`)} > `;
279
3642
  }
280
3643
  async function startRepl(context) {
281
- const rl = createInterface({ input, output, prompt: resolvePrompt(), completer: makeCompleter(commandRegistry) });
282
- let ghostLen = 0;
283
- function drawGhost(ghost) {
284
- if (!process.stdout.isTTY)
285
- return;
286
- if (ghostLen > 0) {
287
- // Clear previous ghost: move cursor right ghostLen, then delete ghostLen chars going back
288
- process.stdout.write("\x1b[" + ghostLen + "P");
289
- }
290
- ghostLen = ghost.length;
291
- if (ghostLen > 0) {
292
- // Write dim ghost text, then move cursor back to original position
293
- process.stdout.write("\x1b[2m" + ghost + "\x1b[0m" + "\x1b[" + ghostLen + "D");
294
- }
295
- }
296
- function clearGhost() {
297
- if (ghostLen > 0 && process.stdout.isTTY) {
298
- process.stdout.write("\x1b[" + ghostLen + "P");
299
- ghostLen = 0;
300
- }
301
- }
302
- function acceptGhost() {
303
- if (ghostLen > 0) {
304
- // Read the ghost text back from the screen isn't possible,
305
- // so re-compute it and write it as real text via rl.write
306
- const ghost = getBestCompletion(rl.line, commandRegistry);
307
- if (ghost.length > 0) {
308
- clearGhost();
309
- rl.write(ghost);
310
- }
311
- }
3644
+ const rl = createInterface({ input, output, prompt: resolvePrompt(), completer: makeCompleter(commandRegistry) });
3645
+ let ghostLen = 0;
3646
+ function drawGhost(ghost) {
3647
+ if (!process.stdout.isTTY)
3648
+ return;
3649
+ if (ghostLen > 0) {
3650
+ process.stdout.write("\x1B[" + ghostLen + "P");
312
3651
  }
313
- if (process.stdin.isTTY) {
314
- emitKeypressEvents(process.stdin, rl);
315
- process.stdin.setRawMode(true);
316
- process.stdin.on("keypress", (_ch, key) => {
317
- if (!key)
318
- return;
319
- // Accept ghost on Tab (only when ghost is visible) or Right arrow
320
- if ((key.name === "tab" && ghostLen > 0) || (key.name === "right" && ghostLen > 0)) {
321
- acceptGhost();
322
- return;
323
- }
324
- // On Enter/Return, clear ghost before readline processes the line
325
- if (key.name === "return" || key.name === "enter") {
326
- clearGhost();
327
- return;
328
- }
329
- // On Escape or Ctrl+C, clear ghost
330
- if (key.name === "escape" || key.sequence === "\x03") {
331
- clearGhost();
332
- return;
333
- }
334
- // After any other keypress, redraw ghost based on new rl.line
335
- // Use setImmediate to wait for readline to update rl.line first
336
- setImmediate(() => {
337
- const ghost = getBestCompletion(rl.line, commandRegistry);
338
- drawGhost(ghost);
339
- });
340
- });
3652
+ ghostLen = ghost.length;
3653
+ if (ghostLen > 0) {
3654
+ process.stdout.write("\x1B[2m" + ghost + "\x1B[0m\x1B[" + ghostLen + "D");
3655
+ }
3656
+ }
3657
+ function clearGhost() {
3658
+ if (ghostLen > 0 && process.stdout.isTTY) {
3659
+ process.stdout.write("\x1B[" + ghostLen + "P");
3660
+ ghostLen = 0;
341
3661
  }
342
- rl.on("SIGINT", () => {
3662
+ }
3663
+ function acceptGhost() {
3664
+ if (ghostLen > 0) {
3665
+ const ghost = getBestCompletion(rl.line, commandRegistry);
3666
+ if (ghost.length > 0) {
343
3667
  clearGhost();
344
- console.log("Use /exit to quit.");
345
- rl.prompt();
346
- });
347
- rl.on("close", () => {
348
- process.exit(0);
349
- });
350
- rl.prompt();
351
- rl.on("line", async (line) => {
3668
+ rl.write(ghost);
3669
+ }
3670
+ }
3671
+ }
3672
+ if (process.stdin.isTTY) {
3673
+ emitKeypressEvents(process.stdin, rl);
3674
+ process.stdin.setRawMode(true);
3675
+ process.stdin.on("keypress", (_ch, key) => {
3676
+ if (!key)
3677
+ return;
3678
+ if (key.name === "tab" && ghostLen > 0 || key.name === "right" && ghostLen > 0) {
3679
+ acceptGhost();
3680
+ return;
3681
+ }
3682
+ if (key.name === "return" || key.name === "enter") {
352
3683
  clearGhost();
353
- try {
354
- const result = await dispatchCommand(line, context);
355
- if (result === "exit") {
356
- rl.close();
357
- return;
358
- }
359
- rl.setPrompt(resolvePrompt());
360
- rl.prompt();
361
- }
362
- catch (error) {
363
- const message = error instanceof Error ? error.message : "Unexpected error.";
364
- console.error(pc.red(message));
365
- rl.setPrompt(resolvePrompt());
366
- rl.prompt();
367
- }
3684
+ return;
3685
+ }
3686
+ if (key.name === "escape" || key.sequence === "\x03") {
3687
+ clearGhost();
3688
+ return;
3689
+ }
3690
+ setImmediate(() => {
3691
+ const ghost = getBestCompletion(rl.line, commandRegistry);
3692
+ drawGhost(ghost);
3693
+ });
368
3694
  });
3695
+ }
3696
+ rl.on("SIGINT", () => {
3697
+ clearGhost();
3698
+ console.log("Use /exit to quit.");
3699
+ rl.prompt();
3700
+ });
3701
+ rl.on("close", () => {
3702
+ process.exit(0);
3703
+ });
3704
+ rl.prompt();
3705
+ rl.on("line", async (line) => {
3706
+ clearGhost();
3707
+ try {
3708
+ const result = await dispatchCommand(line, context);
3709
+ if (result === "exit") {
3710
+ rl.close();
3711
+ return;
3712
+ }
3713
+ rl.setPrompt(resolvePrompt());
3714
+ rl.prompt();
3715
+ } catch (error) {
3716
+ const message = error instanceof Error ? error.message : "Unexpected error.";
3717
+ console.error(import_picocolors4.default.red(message));
3718
+ rl.setPrompt(resolvePrompt());
3719
+ rl.prompt();
3720
+ }
3721
+ });
369
3722
  }
370
3723
  async function main() {
371
- const program = createProgram();
372
- program.parse();
373
- const options = program.opts();
374
- const appContext = buildAppContext(options);
375
- registerCleanupHandlers();
376
- displayBanner();
377
- if (!options.quiet) {
378
- const prerequisites = await checkPrerequisites();
379
- displayPrerequisites(prerequisites);
380
- await displayLlmStatus();
381
- console.log("");
382
- }
383
- if (options.run) {
384
- const exitCode = await runSingleCommand(options.run, appContext);
385
- process.exit(exitCode);
386
- }
387
- await checkForUpdates(appContext);
388
- setReplMode(true);
389
- await startRepl(appContext);
3724
+ const program2 = createProgram();
3725
+ program2.parse();
3726
+ const options = program2.opts();
3727
+ const appContext = buildAppContext(options);
3728
+ registerCleanupHandlers();
3729
+ displayBanner();
3730
+ if (!options.quiet) {
3731
+ const prerequisites = await checkPrerequisites();
3732
+ displayPrerequisites(prerequisites);
3733
+ await displayLlmStatus();
3734
+ console.log("");
3735
+ }
3736
+ if (options.run) {
3737
+ const exitCode = await runSingleCommand(options.run, appContext);
3738
+ process.exit(exitCode);
3739
+ }
3740
+ await checkForUpdates(appContext);
3741
+ setReplMode(true);
3742
+ await startRepl(appContext);
390
3743
  }
391
3744
  function isDirectExecution() {
392
- const entryPoint = process.argv[1];
393
- if (!entryPoint) {
394
- return false;
395
- }
396
- return import.meta.url === pathToFileURL(entryPoint).href;
3745
+ const entryPoint = process.argv[1];
3746
+ if (!entryPoint) {
3747
+ return false;
3748
+ }
3749
+ return import.meta.url === pathToFileURL(entryPoint).href;
397
3750
  }
398
3751
  if (isDirectExecution()) {
399
- void main();
3752
+ main();
400
3753
  }
401
- //# sourceMappingURL=cli.js.map
3754
+ export {
3755
+ runSingleCommand,
3756
+ checkForUpdates
3757
+ };