@warlock.js/core 5.6.0 → 5.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/esm/benchmark/profiler.d.mts.map +1 -1
- package/esm/benchmark/profiler.mjs +4 -3
- package/esm/benchmark/profiler.mjs.map +1 -1
- package/esm/cli/cli-commands.manager.mjs +10 -7
- package/esm/cli/cli-commands.manager.mjs.map +1 -1
- package/esm/cli/commands/routes/format-routes-table.mjs +3 -3
- package/esm/cli/commands/routes/format-routes-table.mjs.map +1 -1
- package/esm/cli/parse-cli-args.mjs +1 -0
- package/esm/cli/parse-cli-args.mjs.map +1 -1
- package/esm/cli/string-similarity.mjs +13 -4
- package/esm/cli/string-similarity.mjs.map +1 -1
- package/esm/commands/cli-command.d.mts.map +1 -1
- package/esm/commands/cli-command.mjs +5 -2
- package/esm/commands/cli-command.mjs.map +1 -1
- package/esm/config/config-loader.mjs +3 -1
- package/esm/config/config-loader.mjs.map +1 -1
- package/esm/dev-server/dependency-graph.d.mts.map +1 -1
- package/esm/dev-server/dependency-graph.mjs +2 -1
- package/esm/dev-server/dependency-graph.mjs.map +1 -1
- package/esm/dev-server/dev-logger.mjs +7 -5
- package/esm/dev-server/dev-logger.mjs.map +1 -1
- package/esm/dev-server/files-orchestrator.mjs +1 -1
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/dev-server/parse-imports.mjs +22 -8
- package/esm/dev-server/parse-imports.mjs.map +1 -1
- package/esm/encryption/encrypt.mjs +1 -0
- package/esm/encryption/encrypt.mjs.map +1 -1
- package/esm/generations/add-command.action.mjs +8 -2
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/generations/features/shared/relocate-conflicting-home-route.mjs +6 -1
- package/esm/generations/features/shared/relocate-conflicting-home-route.mjs.map +1 -1
- package/esm/http/middleware/maintenance.middleware.mjs +1 -2
- package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
- package/esm/http/middleware/utils/cidr-match.d.mts.map +1 -1
- package/esm/http/middleware/utils/cidr-match.mjs +1 -0
- package/esm/http/middleware/utils/cidr-match.mjs.map +1 -1
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs +14 -7
- package/esm/http/request.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/filter-applicator.mjs +4 -2
- package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
- package/esm/router/positional-handler-diagnostics.d.mts.map +1 -1
- package/esm/router/positional-handler-diagnostics.mjs +9 -3
- package/esm/router/positional-handler-diagnostics.mjs.map +1 -1
- package/esm/router/route-registry.mjs +1 -1
- package/esm/router/route-registry.mjs.map +1 -1
- package/esm/storage/scoped-storage.d.mts.map +1 -1
- package/esm/storage/scoped-storage.mjs +1 -0
- package/esm/storage/scoped-storage.mjs.map +1 -1
- package/esm/storage/storage.d.mts.map +1 -1
- package/esm/storage/storage.mjs +6 -2
- package/esm/storage/storage.mjs.map +1 -1
- package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
- package/esm/storage/utils/safe-fetch.mjs +6 -1
- package/esm/storage/utils/safe-fetch.mjs.map +1 -1
- package/esm/utils/version-compare.d.mts.map +1 -1
- package/esm/utils/version-compare.mjs +12 -4
- package/esm/utils/version-compare.mjs.map +1 -1
- package/esm/vite/lower-stage3-decorators.mjs +1 -0
- package/esm/vite/lower-stage3-decorators.mjs.map +1 -1
- package/package.json +12 -12
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,24 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
6
6
|
|
|
7
7
|
> ⚠ **Versioning: `@warlock.js/*` does not follow SemVer strictly — breaking changes may ship in a minor.** This is a deliberate decision, not an oversight: the framework is pre-adoption and the cost of a major per behaviour fix currently outweighs the benefit. **Pin an exact version or a tilde range (`~4.13.0`) if you need to opt into changes rather than receive them.** Every breaking change is marked **BREAKING** in its entry and summarised in an *Upgrading* section at the top of the release. **This policy will change once the framework has consumers beyond its author.**
|
|
8
8
|
|
|
9
|
+
## 5.7.0 - 2026-09-11
|
|
10
|
+
|
|
11
|
+
### Security
|
|
12
|
+
|
|
13
|
+
- **The SSRF guard now fails closed on an address it cannot classify.** An unclassifiable IP was previously treated as public, so an outbound request could reach an internal address the guard exists to block.
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- **The dev server no longer says it is watching for changes before it is serving.** On a slow boot that line could arrive minutes before the port was bound.
|
|
18
|
+
- The dev-server error formatter can no longer throw while formatting an error, which replaced the developer's real error with its own crash.
|
|
19
|
+
- `warlock add` with an unknown feature now names it, instead of dying with `Cannot read properties of undefined`.
|
|
20
|
+
- Bracket-notation request bodies (`items[0][name]`) no longer silently drop values.
|
|
21
|
+
- `warlock routes` and the circular-import report degrade to unaligned output instead of throwing on an unexpected shape.
|
|
22
|
+
|
|
23
|
+
### Changed
|
|
24
|
+
|
|
25
|
+
- Internal type-safety hardening across the CLI, dev server and request handling; no other behaviour change.
|
|
26
|
+
|
|
9
27
|
## 5.6.0 - 2026-09-08
|
|
10
28
|
### Fixed
|
|
11
29
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"profiler.d.mts","names":[],"sources":["../../../../../../../core/src/benchmark/profiler.ts"],"mappings":";;;cAkBa,iBAAA;EAAA,iBACM,UAAA;EAAA,iBACA,QAAA;EAAA,iBACA,OAAA;EAAA,QACT,QAAA;cAEW,OAAA,GAAU,wBAAA;EAoBP;;;;;;;;EAAf,MAAA,CAAO,MAAA,EAAQ,sBAAA,YAAkC,oBAAA;EAxBvC;;;;;;;;;;EAqEV,KAAA,CAAM,IAAA,WAAe,cAAA;EAAf;;;;;;;;
|
|
1
|
+
{"version":3,"file":"profiler.d.mts","names":[],"sources":["../../../../../../../core/src/benchmark/profiler.ts"],"mappings":";;;cAkBa,iBAAA;EAAA,iBACM,UAAA;EAAA,iBACA,QAAA;EAAA,iBACA,OAAA;EAAA,QACT,QAAA;cAEW,OAAA,GAAU,wBAAA;EAoBP;;;;;;;;EAAf,MAAA,CAAO,MAAA,EAAQ,sBAAA,YAAkC,oBAAA;EAxBvC;;;;;;;;;;EAqEV,KAAA,CAAM,IAAA,WAAe,cAAA;EAAf;;;;;;;;EAsCN,QAAA,IAAY,MAAA,SAAe,cAAA;EAyD3B;;AAAO;;;;EAxCD,KAAA,IAAS,OAAA;;;;;;;;;;;EAmBf,KAAA,CAAM,IAAA;;;;;;;EAqBN,OAAA;AAAA"}
|
|
@@ -56,8 +56,9 @@ var BenchmarkProfiler = class {
|
|
|
56
56
|
if (!entry || entry.latencies.length === 0) return void 0;
|
|
57
57
|
const latencies = [...entry.latencies].sort((a, b) => a - b);
|
|
58
58
|
const count = latencies.length;
|
|
59
|
+
if (count === 0) return void 0;
|
|
59
60
|
const getP = (percentile) => {
|
|
60
|
-
return latencies[Math.min(count - 1, Math.floor(count * percentile))];
|
|
61
|
+
return latencies[Math.min(count - 1, Math.floor(count * percentile))] ?? 0;
|
|
61
62
|
};
|
|
62
63
|
return {
|
|
63
64
|
p50: getP(.5),
|
|
@@ -65,8 +66,8 @@ var BenchmarkProfiler = class {
|
|
|
65
66
|
p95: getP(.95),
|
|
66
67
|
p99: getP(.99),
|
|
67
68
|
avg: Math.round(entry.sum / count * 100) / 100,
|
|
68
|
-
min: latencies[0],
|
|
69
|
-
max: latencies[count - 1],
|
|
69
|
+
min: latencies[0] ?? 0,
|
|
70
|
+
max: latencies[count - 1] ?? 0,
|
|
70
71
|
count: entry.total,
|
|
71
72
|
errors: entry.errors,
|
|
72
73
|
errorRate: Math.round(entry.errors / entry.total * 100) / 100,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"profiler.mjs","names":[],"sources":["../../../../../../../core/src/benchmark/profiler.ts"],"sourcesContent":["import { NoopChannel } from \"./channels/noop.channel\";\nimport type {\n BenchmarkChannel,\n BenchmarkErrorResult,\n BenchmarkProfilerOptions,\n BenchmarkStats,\n BenchmarkSuccessResult,\n} from \"./types\";\n\ntype BenchmarkEntry = {\n latencies: number[];\n sum: number;\n total: number;\n errors: number;\n firstSeenAt: Date;\n lastSeenAt: Date;\n};\n\nexport class BenchmarkProfiler {\n private readonly maxSamples: number;\n private readonly channels: BenchmarkChannel[];\n private readonly entries = new Map<string, BenchmarkEntry>();\n private interval?: ReturnType<typeof setInterval>;\n\n public constructor(options?: BenchmarkProfilerOptions) {\n this.maxSamples = options?.maxSamples ?? 1000;\n this.channels = options?.channels ?? [new NoopChannel()];\n\n if (options?.flushEvery) {\n this.interval = setInterval(() => {\n // We use void to explicitly ignore the promise, as this is a background interval\n void this.flush();\n }, options.flushEvery);\n }\n }\n\n /**\n * Record one measurement result. Called automatically by measure() when a profiler is set.\n *\n * @param result - The success or error result from measure()\n *\n * @example\n * profiler.record(result);\n */\n public record(result: BenchmarkSuccessResult<unknown> | BenchmarkErrorResult): void {\n let entry = this.entries.get(result.name);\n\n if (!entry) {\n entry = {\n latencies: [],\n sum: 0,\n total: 0,\n errors: 0,\n firstSeenAt: result.startedAt,\n lastSeenAt: result.endedAt,\n };\n\n this.entries.set(result.name, entry);\n }\n\n entry.latencies.push(result.latency);\n entry.sum += result.latency;\n\n if (entry.latencies.length > this.maxSamples) {\n const removed = entry.latencies.shift();\n if (removed !== undefined) {\n entry.sum -= removed;\n }\n }\n\n entry.total += 1;\n\n if (!result.success) {\n entry.errors += 1;\n }\n\n entry.lastSeenAt = result.endedAt;\n }\n\n /**\n * Get aggregated stats for one operation name.\n * Computes p50/p95/p99 by sorting the ring buffer on demand.\n *\n * @param name - The operation name to get stats for.\n * @returns Stats object or undefined if no data yet.\n *\n * @example\n * const stats = profiler.stats(\"db-query\");\n */\n public stats(name: string): BenchmarkStats | undefined {\n const entry = this.entries.get(name);\n if (!entry || entry.latencies.length === 0) return undefined;\n\n const latencies = [...entry.latencies].sort((a, b) => a - b);\n const count = latencies.length;\n\n const getP = (percentile: number) => {\n const index = Math.min(count - 1, Math.floor(count * percentile));\n return latencies[index];\n };\n\n return {\n p50: getP(0.5),\n p90: getP(0.9),\n p95: getP(0.95),\n p99: getP(0.99),\n avg: Math.round((entry.sum / count) * 100) / 100,\n min: latencies[0],\n max: latencies[count - 1],\n count: entry.total,\n errors: entry.errors,\n errorRate: Math.round((entry.errors / entry.total) * 100) / 100,\n firstSeenAt: entry.firstSeenAt,\n lastSeenAt: entry.lastSeenAt,\n };\n }\n\n /**\n * Get stats for all tracked operations.\n *\n * @returns A record mapping operation names to their stats.\n *\n * @example\n * const all = profiler.allStats();\n */\n public allStats(): Record<string, BenchmarkStats> {\n const all: Record<string, BenchmarkStats> = {};\n for (const name of this.entries.keys()) {\n const operationStats = this.stats(name);\n if (operationStats) {\n all[name] = operationStats;\n }\n }\n return all;\n }\n\n /**\n * Send allStats() to all registered channels.\n *\n * @example\n * await profiler.flush();\n */\n public async flush(): Promise<void> {\n const stats = this.allStats();\n if (Object.keys(stats).length === 0) return;\n\n for (const channel of this.channels) {\n await channel.onFlush(stats);\n }\n }\n\n /**\n * Clear ring buffer for one or all operations.\n * Does NOT reset unbounded total/error counters.\n *\n * @param name - Optional operation name. If omitted, clears all ring buffers.\n *\n * @example\n * profiler.reset(\"db-query\");\n * profiler.reset();\n */\n public reset(name?: string): void {\n if (name) {\n const entry = this.entries.get(name);\n if (entry) {\n entry.latencies = [];\n entry.sum = 0;\n }\n } else {\n for (const entry of this.entries.values()) {\n entry.latencies = [];\n entry.sum = 0;\n }\n }\n }\n\n /**\n * Dispose the profiler, clearing its auto-flush interval.\n *\n * @example\n * profiler.dispose();\n */\n public dispose(): void {\n if (this.interval) {\n clearInterval(this.interval);\n this.interval = undefined;\n }\n }\n}\n"],"mappings":";;;AAkBA,IAAa,oBAAb,MAA+B;CAM7B,AAAO,YAAY,SAAoC;iCAH5B,IAAI,IAA4B;EAIzD,KAAK,aAAa,SAAS,cAAc;EACzC,KAAK,WAAW,SAAS,YAAY,CAAC,IAAI,YAAY,CAAC;EAEvD,IAAI,SAAS,YACX,KAAK,WAAW,kBAAkB;GAEhC,AAAK,KAAK,MAAM;EAClB,GAAG,QAAQ,UAAU;CAEzB;;;;;;;;;CAUA,AAAO,OAAO,QAAsE;EAClF,IAAI,QAAQ,KAAK,QAAQ,IAAI,OAAO,IAAI;EAExC,IAAI,CAAC,OAAO;GACV,QAAQ;IACN,WAAW,CAAC;IACZ,KAAK;IACL,OAAO;IACP,QAAQ;IACR,aAAa,OAAO;IACpB,YAAY,OAAO;GACrB;GAEA,KAAK,QAAQ,IAAI,OAAO,MAAM,KAAK;EACrC;EAEA,MAAM,UAAU,KAAK,OAAO,OAAO;EACnC,MAAM,OAAO,OAAO;EAEpB,IAAI,MAAM,UAAU,SAAS,KAAK,YAAY;GAC5C,MAAM,UAAU,MAAM,UAAU,MAAM;GACtC,IAAI,YAAY,QACd,MAAM,OAAO;EAEjB;EAEA,MAAM,SAAS;EAEf,IAAI,CAAC,OAAO,SACV,MAAM,UAAU;EAGlB,MAAM,aAAa,OAAO;CAC5B;;;;;;;;;;;CAYA,AAAO,MAAM,MAA0C;EACrD,MAAM,QAAQ,KAAK,QAAQ,IAAI,IAAI;EACnC,IAAI,CAAC,SAAS,MAAM,UAAU,WAAW,GAAG,OAAO;EAEnD,MAAM,YAAY,CAAC,GAAG,MAAM,SAAS,CAAC,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC;EAC3D,MAAM,QAAQ,UAAU;EAExB,MAAM,QAAQ,eAAuB;GAEnC,OAAO,UADO,KAAK,IAAI,QAAQ,GAAG,KAAK,MAAM,QAAQ,UAAU,CAC1C;
|
|
1
|
+
{"version":3,"file":"profiler.mjs","names":[],"sources":["../../../../../../../core/src/benchmark/profiler.ts"],"sourcesContent":["import { NoopChannel } from \"./channels/noop.channel\";\nimport type {\n BenchmarkChannel,\n BenchmarkErrorResult,\n BenchmarkProfilerOptions,\n BenchmarkStats,\n BenchmarkSuccessResult,\n} from \"./types\";\n\ntype BenchmarkEntry = {\n latencies: number[];\n sum: number;\n total: number;\n errors: number;\n firstSeenAt: Date;\n lastSeenAt: Date;\n};\n\nexport class BenchmarkProfiler {\n private readonly maxSamples: number;\n private readonly channels: BenchmarkChannel[];\n private readonly entries = new Map<string, BenchmarkEntry>();\n private interval?: ReturnType<typeof setInterval>;\n\n public constructor(options?: BenchmarkProfilerOptions) {\n this.maxSamples = options?.maxSamples ?? 1000;\n this.channels = options?.channels ?? [new NoopChannel()];\n\n if (options?.flushEvery) {\n this.interval = setInterval(() => {\n // We use void to explicitly ignore the promise, as this is a background interval\n void this.flush();\n }, options.flushEvery);\n }\n }\n\n /**\n * Record one measurement result. Called automatically by measure() when a profiler is set.\n *\n * @param result - The success or error result from measure()\n *\n * @example\n * profiler.record(result);\n */\n public record(result: BenchmarkSuccessResult<unknown> | BenchmarkErrorResult): void {\n let entry = this.entries.get(result.name);\n\n if (!entry) {\n entry = {\n latencies: [],\n sum: 0,\n total: 0,\n errors: 0,\n firstSeenAt: result.startedAt,\n lastSeenAt: result.endedAt,\n };\n\n this.entries.set(result.name, entry);\n }\n\n entry.latencies.push(result.latency);\n entry.sum += result.latency;\n\n if (entry.latencies.length > this.maxSamples) {\n const removed = entry.latencies.shift();\n if (removed !== undefined) {\n entry.sum -= removed;\n }\n }\n\n entry.total += 1;\n\n if (!result.success) {\n entry.errors += 1;\n }\n\n entry.lastSeenAt = result.endedAt;\n }\n\n /**\n * Get aggregated stats for one operation name.\n * Computes p50/p95/p99 by sorting the ring buffer on demand.\n *\n * @param name - The operation name to get stats for.\n * @returns Stats object or undefined if no data yet.\n *\n * @example\n * const stats = profiler.stats(\"db-query\");\n */\n public stats(name: string): BenchmarkStats | undefined {\n const entry = this.entries.get(name);\n if (!entry || entry.latencies.length === 0) return undefined;\n\n const latencies = [...entry.latencies].sort((a, b) => a - b);\n const count = latencies.length;\n\n if (count === 0) return undefined;\n\n const getP = (percentile: number) => {\n const index = Math.min(count - 1, Math.floor(count * percentile));\n return latencies[index] ?? 0;\n };\n\n return {\n p50: getP(0.5),\n p90: getP(0.9),\n p95: getP(0.95),\n p99: getP(0.99),\n avg: Math.round((entry.sum / count) * 100) / 100,\n min: latencies[0] ?? 0,\n max: latencies[count - 1] ?? 0,\n count: entry.total,\n errors: entry.errors,\n errorRate: Math.round((entry.errors / entry.total) * 100) / 100,\n firstSeenAt: entry.firstSeenAt,\n lastSeenAt: entry.lastSeenAt,\n };\n }\n\n /**\n * Get stats for all tracked operations.\n *\n * @returns A record mapping operation names to their stats.\n *\n * @example\n * const all = profiler.allStats();\n */\n public allStats(): Record<string, BenchmarkStats> {\n const all: Record<string, BenchmarkStats> = {};\n for (const name of this.entries.keys()) {\n const operationStats = this.stats(name);\n if (operationStats) {\n all[name] = operationStats;\n }\n }\n return all;\n }\n\n /**\n * Send allStats() to all registered channels.\n *\n * @example\n * await profiler.flush();\n */\n public async flush(): Promise<void> {\n const stats = this.allStats();\n if (Object.keys(stats).length === 0) return;\n\n for (const channel of this.channels) {\n await channel.onFlush(stats);\n }\n }\n\n /**\n * Clear ring buffer for one or all operations.\n * Does NOT reset unbounded total/error counters.\n *\n * @param name - Optional operation name. If omitted, clears all ring buffers.\n *\n * @example\n * profiler.reset(\"db-query\");\n * profiler.reset();\n */\n public reset(name?: string): void {\n if (name) {\n const entry = this.entries.get(name);\n if (entry) {\n entry.latencies = [];\n entry.sum = 0;\n }\n } else {\n for (const entry of this.entries.values()) {\n entry.latencies = [];\n entry.sum = 0;\n }\n }\n }\n\n /**\n * Dispose the profiler, clearing its auto-flush interval.\n *\n * @example\n * profiler.dispose();\n */\n public dispose(): void {\n if (this.interval) {\n clearInterval(this.interval);\n this.interval = undefined;\n }\n }\n}\n"],"mappings":";;;AAkBA,IAAa,oBAAb,MAA+B;CAM7B,AAAO,YAAY,SAAoC;iCAH5B,IAAI,IAA4B;EAIzD,KAAK,aAAa,SAAS,cAAc;EACzC,KAAK,WAAW,SAAS,YAAY,CAAC,IAAI,YAAY,CAAC;EAEvD,IAAI,SAAS,YACX,KAAK,WAAW,kBAAkB;GA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AAM;GACd,WAAW,KAAK,MAAO,MAAM,SAAS,MAAM,QAAS,GAAG,IAAI;GAC5D,aAAa,MAAM;GACnB,YAAY,MAAM;EACpB;CACF;;;;;;;;;CAUA,AAAO,WAA2C;EAChD,MAAM,MAAsC,CAAC;EAC7C,KAAK,MAAM,QAAQ,KAAK,QAAQ,KAAK,GAAG;GACtC,MAAM,iBAAiB,KAAK,MAAM,IAAI;GACtC,IAAI,gBACF,IAAI,QAAQ;EAEhB;EACA,OAAO;CACT;;;;;;;CAQA,MAAa,QAAuB;EAClC,MAAM,QAAQ,KAAK,SAAS;EAC5B,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,WAAW,GAAG;EAErC,KAAK,MAAM,WAAW,KAAK,UACzB,MAAM,QAAQ,QAAQ,KAAK;CAE/B;;;;;;;;;;;CAYA,AAAO,MAAM,MAAqB;EAChC,IAAI,MAAM;GACR,MAAM,QAAQ,KAAK,QAAQ,IAAI,IAAI;GACnC,IAAI,OAAO;IACT,MAAM,YAAY,CAAC;IACnB,MAAM,MAAM;GACd;EACF,OACE,KAAK,MAAM,SAAS,KAAK,QAAQ,OAAO,GAAG;GACzC,MAAM,YAAY,CAAC;GACnB,MAAM,MAAM;EACd;CAEJ;;;;;;;CAQA,AAAO,UAAgB;EACrB,IAAI,KAAK,UAAU;GACjB,cAAc,KAAK,QAAQ;GAC3B,KAAK,WAAW;EAClB;CACF;AACF"}
|
|
@@ -95,7 +95,7 @@ var CLICommandsManager = class {
|
|
|
95
95
|
register(...commands) {
|
|
96
96
|
this.commands.push(...commands);
|
|
97
97
|
commands.forEach((command) => {
|
|
98
|
-
const commandKey = command.name.split(" ")[0];
|
|
98
|
+
const commandKey = command.name.split(" ")[0] ?? command.name;
|
|
99
99
|
manifestManager.addCommandToList(command.name, {
|
|
100
100
|
relativePath: command.commandRelativePath,
|
|
101
101
|
source: command.commandSource || "project",
|
|
@@ -126,10 +126,10 @@ var CLICommandsManager = class {
|
|
|
126
126
|
for (const name of this.commandsMap.keys()) names.push(name);
|
|
127
127
|
for (const alias of this.aliasMap.keys()) names.push(alias);
|
|
128
128
|
const manifestCommands = manifestManager.commandsJson?.commands || {};
|
|
129
|
-
for (const name of Object.
|
|
130
|
-
const baseName = name.split(" ")[0];
|
|
129
|
+
for (const [name, meta] of Object.entries(manifestCommands)) {
|
|
130
|
+
const baseName = name.split(" ")[0] ?? name;
|
|
131
131
|
if (!names.includes(baseName)) names.push(baseName);
|
|
132
|
-
const alias =
|
|
132
|
+
const alias = meta?.alias;
|
|
133
133
|
if (alias && !names.includes(alias)) names.push(alias);
|
|
134
134
|
}
|
|
135
135
|
return names;
|
|
@@ -274,8 +274,8 @@ var CLICommandsManager = class {
|
|
|
274
274
|
*/
|
|
275
275
|
async loadProjectCommands(name) {
|
|
276
276
|
const jsonCommandsFile = await manifestManager.loadCommands();
|
|
277
|
-
if (jsonCommandsFile) for (const fullCommandName
|
|
278
|
-
|
|
277
|
+
if (jsonCommandsFile) for (const [fullCommandName, cmdMeta] of Object.entries(jsonCommandsFile.commands)) {
|
|
278
|
+
if (cmdMeta === void 0) continue;
|
|
279
279
|
if (isMatchingCommandName(fullCommandName, name) || cmdMeta.alias === name) {
|
|
280
280
|
const commandPath = cmdMeta.relativePath;
|
|
281
281
|
if (commandPath) {
|
|
@@ -315,7 +315,10 @@ var CLICommandsManager = class {
|
|
|
315
315
|
if (opt.defaultValue !== void 0) {
|
|
316
316
|
if (!(result[opt.name] !== void 0 || opt.alias && result[opt.alias] !== void 0)) result[opt.name] = opt.defaultValue;
|
|
317
317
|
}
|
|
318
|
-
if (opt.alias !== void 0 && result[opt.alias] !== void 0 && result[opt.name] === void 0)
|
|
318
|
+
if (opt.alias !== void 0 && result[opt.alias] !== void 0 && result[opt.name] === void 0) {
|
|
319
|
+
const aliasValue = result[opt.alias];
|
|
320
|
+
if (aliasValue !== void 0) result[opt.name] = aliasValue;
|
|
321
|
+
}
|
|
319
322
|
});
|
|
320
323
|
return result;
|
|
321
324
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-commands.manager.mjs","names":[],"sources":["../../../../../../../core/src/cli/cli-commands.manager.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport { fileExistsAsync } from \"@warlock.js/fs\";\r\nimport { Application } from \"../application\";\r\nimport { bootstrap } from \"../bootstrap\";\r\nimport { loadConfigFiles } from \"../config/load-config-files\";\r\nimport { connectorsManager } from \"../connectors/connectors-manager\";\r\nimport { registerConfiguredConnectors } from \"../connectors/register-configured-connectors\";\r\nimport { ConnectorLifecyclePhase } from \"../connectors/types\";\r\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\r\nimport { isDevWorker } from \"../dev-server/supervisor\";\r\nimport { preflightConfiguredHttpPort } from \"../http/boot-port-preflight\";\r\nimport { manifestManager } from \"../manifest/manifest-manager\";\r\nimport { appPath } from \"../utils\";\r\nimport { loadEnvironmentFiles } from \"../utils/load-environment\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { CLICommand } from \"../commands/cli-command\";\r\nimport {\r\n displayBootError,\r\n displayCommandError,\r\n displayCommandHelp,\r\n displayCommandNotFound,\r\n displayCommandSuccess,\r\n displayExecutingCommand,\r\n displayHelp,\r\n displayMissingCommand,\r\n displayMissingOptions,\r\n displayWarlockVersionInTerminal,\r\n type HelpCommandInfo,\r\n isMatchingCommandName,\r\n} from \"./cli-commands.utils\";\r\nimport { cliCommandsLoader } from \"./commands-loader\";\r\nimport { frameworkCommands } from \"./framework-cli-commands\";\r\nimport { CliOptionValueError, type ParsedCliArgs, parseCliArgs } from \"./parse-cli-args\";\r\nimport { findSimilar } from \"./string-similarity\";\r\nimport type { CommandActionData, ResolvedCLICommandOption } from \"../commands/types\";\r\n\r\n/**\r\n * Best-effort budget (ms) for draining stdout/stderr before a forced exit.\r\n * Bounded so a stuck stream can never hang the CLI.\r\n */\r\nconst EXIT_FLUSH_BUDGET = 500;\r\n\r\n/**\r\n * Exit with `code` once stdout/stderr have drained.\r\n *\r\n * `process.exit()` truncates writes still queued on a non-TTY stdout — a pipe,\r\n * a CI log — which is how the *reason* for a failure gets lost even when the\r\n * exit code is right. `exitCode` is set up front so that a natural exit (should\r\n * the drain outlive the process's remaining work) is non-zero too.\r\n */\r\nfunction exitAfterFlush(code: number) {\r\n process.exitCode = code;\r\n\r\n const timer = setTimeout(() => process.exit(code), EXIT_FLUSH_BUDGET);\r\n timer.unref?.();\r\n\r\n let pending = 2;\r\n const drained = () => {\r\n if (--pending > 0) return;\r\n\r\n clearTimeout(timer);\r\n process.exit(code);\r\n };\r\n\r\n // A zero-length write's callback fires once everything queued ahead of it has\r\n // been handed to the OS.\r\n process.stdout.write(\"\", drained);\r\n process.stderr.write(\"\", drained);\r\n}\r\n\r\n/**\r\n * How a command run ended, from the process's point of view.\r\n *\r\n * - `succeeded` — finished, nothing rejected afterwards; the CLI may exit 0.\r\n * - `failed` — reported an error; the exit code is owned by whoever reported it.\r\n * - `running` — a persistent command (dev/start) now owns the process.\r\n *\r\n * `execute` returns this instead of exiting on success itself. A method that\r\n * terminates the process out from under its caller cannot be awaited honestly:\r\n * the exit it schedules outlives the call, so the success it represents is\r\n * still unsettled when `execute` resolves — which is exactly how a green check\r\n * ends up printed next to the failure that contradicts it.\r\n */\r\nexport type CommandRunVerdict = \"succeeded\" | \"failed\" | \"running\";\r\n\r\n/**\r\n * Whether this process is the CHILD half of a supervised command.\r\n *\r\n * ## The finding this encodes\r\n *\r\n * `warlock dev` printing `› Running dev...` twice was NOT a double boot, and\r\n * the distinction is the whole point of this function existing rather than the\r\n * line simply being deleted. The sequence, in file order:\r\n *\r\n * 1. `execute()` prints the header (below) — BEFORE `commandPreAction`.\r\n * 2. `cli/commands/dev-server.command.ts` `preAction` calls\r\n * `superviseDevServer()` when `!isDevWorker()`.\r\n * 3. `dev-server/supervisor.ts` `spawnWorker()` re-spawns `process.argv` with\r\n * `WARLOCK_DEV_WORKER=1`, so the child runs `warlock dev` again and prints\r\n * the header too.\r\n * 4. `superviseDevServer()` returns a promise that never settles, so the\r\n * supervisor's `await commandPreAction(...)` never resolves — `loadPreloaders`\r\n * and `command.execute` are unreachable in the supervisor.\r\n *\r\n * Step 4 is why only ONE process ever loads config, connectors, app modules or\r\n * a scheduler. Verified by running it: one `APP-CODE-LOADED`, one\r\n * `Application.markBooted`, one `⚡ Warlock.js` banner, one route registration,\r\n * two processes. The `2 job(s) registered` in the original report is two jobs\r\n * in one scheduler, not two schedulers — a genuine double boot would have\r\n * printed that warning twice.\r\n *\r\n * So the defect is exactly one duplicated line, and this is the guard that\r\n * keeps it one. `tests/unit/cli/dev-command-single-boot.test.ts` fails if the\r\n * supervisor ever starts running preloaders — i.e. if the double boot the\r\n * duplicated line looked like ever becomes real.\r\n */\r\nfunction isRespawnedWorker(): boolean {\r\n return isDevWorker();\r\n}\r\n\r\nexport class CLICommandsManager {\r\n /**\r\n * List of commands\r\n */\r\n public commands: CLICommand[] = [];\r\n\r\n /**\r\n * Commands map (name -> command)\r\n */\r\n public commandsMap: Map<string, CLICommand> = new Map();\r\n\r\n /**\r\n * Alias map (alias -> command name)\r\n */\r\n public aliasMap: Map<string, string> = new Map();\r\n\r\n /**\r\n * Register the given commands\r\n */\r\n public register(...commands: CLICommand[]): this {\r\n this.commands.push(...commands);\r\n\r\n commands.forEach((command) => {\r\n const commandKey = command.name.split(\" \")[0];\r\n\r\n manifestManager.addCommandToList(command.name, {\r\n relativePath: command.commandRelativePath,\r\n source: command.commandSource || \"project\",\r\n description: command.commandDescription,\r\n alias: command.commandAlias,\r\n options: command.commandOptions.length > 0 ? command.commandOptions : undefined,\r\n });\r\n\r\n this.commandsMap.set(commandKey, command);\r\n\r\n // Register alias if exists\r\n if (command.commandAlias) {\r\n this.aliasMap.set(command.commandAlias, commandKey);\r\n }\r\n });\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Get command by name or alias\r\n */\r\n public getCommand(name: string): CLICommand | undefined {\r\n // First try direct lookup\r\n let command = this.commandsMap.get(name);\r\n if (command) return command;\r\n\r\n // Try alias lookup\r\n const realName = this.aliasMap.get(name);\r\n if (realName) {\r\n return this.commandsMap.get(realName);\r\n }\r\n\r\n return;\r\n }\r\n\r\n /**\r\n * Get all command names and aliases\r\n * Used for fuzzy matching suggestions\r\n */\r\n public getAllCommandNames(): string[] {\r\n const names: string[] = [];\r\n\r\n // Add all command names\r\n for (const name of this.commandsMap.keys()) {\r\n names.push(name);\r\n }\r\n\r\n // Add all aliases\r\n for (const alias of this.aliasMap.keys()) {\r\n names.push(alias);\r\n }\r\n\r\n // Also include cached commands from manifest\r\n const manifestCommands = manifestManager.commandsJson?.commands || {};\r\n for (const name of Object.keys(manifestCommands)) {\r\n const baseName = name.split(\" \")[0];\r\n if (!names.includes(baseName)) {\r\n names.push(baseName);\r\n }\r\n const alias = manifestCommands[name].alias;\r\n if (alias && !names.includes(alias)) {\r\n names.push(alias);\r\n }\r\n }\r\n\r\n return names;\r\n }\r\n\r\n /**\r\n * Start the cli manager\r\n */\r\n public async start() {\r\n // Schema-less first pass: it exists to discover the command name and the\r\n // command-independent flags (--help, --version, --no-cache). Values here are\r\n // raw strings; the typed pass below is the one whose options reach a command.\r\n const { name, options } = parseCliArgs(process.argv);\r\n\r\n if (options.noCache) {\r\n manifestManager.clearCommandsCache();\r\n // remove the commands.json file as wel\r\n await manifestManager.removeCommandsFile();\r\n }\r\n\r\n if (options.version || options.v) {\r\n await displayWarlockVersionInTerminal();\r\n process.exit(0);\r\n }\r\n\r\n // Try to load from manifest first (fastest path)\r\n await manifestManager.loadCommands();\r\n\r\n // Register framework commands first (needed for help)\r\n this.register(\r\n ...frameworkCommands.map((command) => {\r\n if (!command.commandSource) {\r\n command.commandSource = \"framework\";\r\n }\r\n return command;\r\n }),\r\n );\r\n\r\n const isHelpCommand = options.help || options.h;\r\n\r\n // Handle global help (no command)\r\n if (!name && isHelpCommand) {\r\n await this.showGlobalHelp();\r\n process.exit(0);\r\n }\r\n\r\n // Handle warm cache\r\n if (options.warmCache) {\r\n await this.warmCache();\r\n process.exit(0);\r\n }\r\n\r\n if (!name) {\r\n displayMissingCommand();\r\n process.exit(1);\r\n }\r\n\r\n const command = await this.lazyGetCommand(name);\r\n\r\n if (manifestManager.hasChanges) {\r\n await manifestManager.saveCommands();\r\n }\r\n\r\n if (!command) {\r\n // Find similar commands for suggestions\r\n const allCommandNames = this.getAllCommandNames();\r\n const suggestions = findSimilar(name, allCommandNames).map((s) => s.value);\r\n\r\n displayCommandNotFound(name, suggestions);\r\n process.exit(1);\r\n }\r\n\r\n // Handle command-specific help\r\n if (isHelpCommand) {\r\n displayCommandHelp({\r\n name: command.name,\r\n alias: command.commandAlias,\r\n description: command.commandDescription,\r\n options: command.commandOptions,\r\n });\r\n process.exit(0);\r\n }\r\n\r\n // The first parse above had no command to consult, so every value in it is\r\n // a raw string. Now that the command is resolved, re-read argv against its\r\n // declared options so a `type: \"boolean\"` option arrives as a boolean.\r\n const resolved = this.resolveCommandArgs(command);\r\n\r\n const verdict = await this.execute(command, {\r\n options: resolved.options,\r\n args: resolved.args,\r\n });\r\n\r\n // The process-level exit belongs to the entrypoint, not to `execute`.\r\n // A one-shot command can leave a handle open (a db connection, a watcher a\r\n // plugin forgot to close), so the CLI exits explicitly rather than waiting\r\n // for the loop to drain — but only on a verdict of `succeeded`. `failed`\r\n // already exited non-zero through whoever reported it, and `running` means\r\n // a persistent command owns the process now.\r\n if (verdict === \"succeeded\") {\r\n exitAfterFlush(0);\r\n }\r\n }\r\n\r\n /**\r\n * Re-parse argv against the resolved command's declared options.\r\n *\r\n * parseCliArgs runs twice on purpose. The first run produces the command\r\n * name, and there is no schema to consult yet; the second one, here, can be\r\n * type-aware. Re-reading argv (rather than post-processing the first result)\r\n * is what makes `--rollback users.ts` recoverable: by the time the first pass\r\n * returns, the swallowed positional is indistinguishable from a value.\r\n */\r\n protected resolveCommandArgs(command: CLICommand, argv: string[] = process.argv): ParsedCliArgs {\r\n try {\r\n return parseCliArgs(argv, command.commandOptions);\r\n } catch (error) {\r\n if (error instanceof CliOptionValueError) {\r\n console.log();\r\n console.log(` ${colors.redBright(\"Error:\")} ${error.message}`);\r\n console.log();\r\n process.exit(1);\r\n }\r\n\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Show global help with all commands\r\n * Uses manifest if available for fast display\r\n */\r\n protected async showGlobalHelp() {\r\n if (\r\n manifestManager.isCommandLoaded &&\r\n Object.keys(manifestManager.commandsJson?.commands || {}).length > 0\r\n ) {\r\n // Use manifest directly - no need to load command files\r\n const helpCommands: HelpCommandInfo[] = Object.entries(\r\n manifestManager.commandsJson?.commands || {},\r\n ).map(([name, cmd]) => ({\r\n name,\r\n alias: cmd.alias,\r\n description: cmd.description,\r\n source: cmd.source,\r\n }));\r\n\r\n await displayHelp(helpCommands);\r\n return;\r\n }\r\n\r\n // Fallback: No manifest, build from registered commands\r\n // This happens on first run before warm-cache\r\n await this.loadPluginsCommands();\r\n\r\n const projectCommands = await cliCommandsLoader.scanAll();\r\n\r\n this.register(...projectCommands);\r\n\r\n await manifestManager.saveCommands();\r\n\r\n // Build help info from registered commands\r\n const helpCommands: HelpCommandInfo[] = this.commands.map((cmd) => ({\r\n name: cmd.name,\r\n alias: cmd.commandAlias,\r\n description: cmd.commandDescription,\r\n source: cmd.commandSource || \"project\",\r\n }));\r\n\r\n await displayHelp(helpCommands);\r\n }\r\n\r\n /**\r\n * Warm cache - scan all project commands and save to manifest\r\n */\r\n protected async warmCache() {\r\n console.log();\r\n console.log(` ${colors.cyan(\"›\")} Scanning project commands...`);\r\n\r\n const projectCommands = await cliCommandsLoader.scanAll();\r\n\r\n this.register(...projectCommands);\r\n\r\n await manifestManager.saveCommands();\r\n\r\n console.log(\r\n ` ${colors.green(\"✔\")} Cached ${colors.bold(String(projectCommands.length))} project commands`,\r\n );\r\n console.log();\r\n }\r\n\r\n /**\r\n * Load plugins commands\r\n */\r\n protected async loadPluginsCommands() {\r\n await warlockConfigManager.load();\r\n\r\n if (warlockConfigManager.isLoaded) {\r\n this.register(\r\n ...(warlockConfigManager.get(\"cli\")?.commands || []).map((command) => {\r\n if (!command.commandSource) {\r\n command.commandSource = \"plugin\";\r\n }\r\n return command;\r\n }),\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Try to find the command based on the given command name or alias\r\n */\r\n protected async lazyGetCommand(name: string) {\r\n // first step, try to find it directly through current commands\r\n let command = this.getCommand(name);\r\n if (command) {\r\n return command;\r\n }\r\n\r\n // second step, try to find it through warlock config commands\r\n await this.loadPluginsCommands();\r\n\r\n command = this.getCommand(name);\r\n\r\n if (command) {\r\n return command;\r\n }\r\n\r\n // third step, try to find it through project commands\r\n await this.loadProjectCommands(name);\r\n\r\n command = this.getCommand(name);\r\n if (command) {\r\n return command;\r\n }\r\n\r\n return null;\r\n }\r\n\r\n /**\r\n * Load project commands\r\n */\r\n protected async loadProjectCommands(name: string) {\r\n // first get the commands.json contents as an object\r\n const jsonCommandsFile = await manifestManager.loadCommands();\r\n\r\n if (jsonCommandsFile) {\r\n // Check by name or alias\r\n for (const fullCommandName in jsonCommandsFile.commands) {\r\n const cmdMeta = jsonCommandsFile.commands[fullCommandName];\r\n\r\n // Match by name or alias\r\n if (isMatchingCommandName(fullCommandName, name) || cmdMeta.alias === name) {\r\n const commandPath = cmdMeta.relativePath;\r\n if (commandPath) {\r\n const executedCommand = await cliCommandsLoader.load(commandPath);\r\n\r\n if (executedCommand) {\r\n executedCommand.$relativePath(commandPath);\r\n this.register(executedCommand);\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n const command = await cliCommandsLoader.locate(name);\r\n\r\n if (command) {\r\n this.register(command);\r\n return;\r\n }\r\n }\r\n\r\n /**\r\n * Validate required options\r\n */\r\n protected validateOptions(\r\n command: CLICommand,\r\n options: Record<string, string | boolean | number>,\r\n ): ResolvedCLICommandOption[] {\r\n const missing: ResolvedCLICommandOption[] = [];\r\n\r\n command.commandOptions.forEach((opt) => {\r\n if (opt.required) {\r\n // Check if option is provided by name or alias\r\n const hasOption =\r\n options[opt.name] !== undefined || (opt.alias && options[opt.alias] !== undefined);\r\n if (!hasOption) {\r\n missing.push(opt);\r\n }\r\n }\r\n });\r\n\r\n return missing;\r\n }\r\n\r\n /**\r\n * Apply default values to options\r\n */\r\n protected applyDefaultOptions(\r\n command: CLICommand,\r\n options: Record<string, string | boolean | number>,\r\n ): Record<string, string | boolean | number> {\r\n const result = { ...options };\r\n\r\n command.commandOptions.forEach((opt) => {\r\n if (opt.defaultValue !== undefined) {\r\n const hasOption =\r\n result[opt.name] !== undefined || (opt.alias && result[opt.alias] !== undefined);\r\n if (!hasOption) {\r\n result[opt.name] = opt.defaultValue;\r\n }\r\n }\r\n\r\n // `!== undefined`, not truthiness: `-r=false` now resolves to the boolean\r\n // `false`, and a truthiness test would drop it before it ever reached the\r\n // canonical name — leaving `rollback` undefined instead of explicitly off.\r\n if (\r\n opt.alias !== undefined &&\r\n result[opt.alias] !== undefined &&\r\n result[opt.name] === undefined\r\n ) {\r\n result[opt.name] = result[opt.alias];\r\n }\r\n });\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Execute the given command and report how it ended.\r\n *\r\n * Returning the verdict — rather than exiting on success from in here — is\r\n * what makes the awaited result trustworthy: see {@link CommandRunVerdict}.\r\n */\r\n public async execute(command: CLICommand, data: CommandActionData): Promise<CommandRunVerdict> {\r\n const startTime = Date.now();\r\n\r\n // Validate required options\r\n const missingOptions = this.validateOptions(command, data.options);\r\n if (missingOptions.length > 0) {\r\n displayMissingOptions(missingOptions);\r\n process.exit(1);\r\n }\r\n\r\n // Apply default values\r\n data.options = this.applyDefaultOptions(command, data.options);\r\n\r\n // ONE header per `warlock <command>` the user typed — not one per process.\r\n //\r\n // `warlock dev` is TWO processes by design: the invocation the user typed\r\n // becomes a thin supervisor (`dev-server/supervisor.ts`) that re-spawns\r\n // `process.argv` with `WARLOCK_DEV_WORKER=1`, and the child is the actual\r\n // server. Both are `warlock dev`, so both reached this line and the user saw\r\n //\r\n // › Running dev...\r\n // › Running dev...\r\n //\r\n // which reads exactly like the application booting twice. It is not — see\r\n // the block comment on `isRespawnedWorker` — but the line was still wrong,\r\n // and it re-printed on every crash-restart on top of the supervisor's own\r\n // \"restarting\" notice.\r\n //\r\n // The SUPERVISOR keeps the header, not the worker: it prints immediately\r\n // (so a slow boot is not silent), it prints once for the whole session\r\n // (restarts are already announced as restarts), and it is the process the\r\n // user actually started.\r\n if (!isRespawnedWorker()) {\r\n displayExecutingCommand(command.name);\r\n }\r\n\r\n if (command.commandPreAction) {\r\n await command.commandPreAction(data);\r\n }\r\n\r\n // load preloaders\r\n if (command.commandPreload) {\r\n try {\r\n await this.loadPreloaders(command);\r\n } catch (error) {\r\n // A preload failure (a bad import in a config file, a connector that\r\n // throws on boot, a missing module export) happens BEFORE the command's\r\n // action runs — there is no run loop to recover into, so it is ALWAYS\r\n // fatal, persistent command (dev/start) or not. Surface the real cause\r\n // and the offending file, then exit. This MUST stay outside the\r\n // command-execute try/catch below: letting a preload rejection escape\r\n // turned `warlock dev` into a silent hang — the unhandled rejection slid\r\n // past while the already-started loader worker thread kept the process\r\n // alive, freezing just after the banner with no error printed.\r\n displayBootError(command.name, error as Error);\r\n process.exit(1);\r\n }\r\n }\r\n\r\n this.captureFatalAsyncErrors(command);\r\n\r\n try {\r\n await command.execute(data);\r\n\r\n // Persistent commands (dev/start) hand control to their run loop here.\r\n // There is no success banner to print and nothing to exit for.\r\n if (command.isPersistent) return \"running\";\r\n\r\n // Yield one full event-loop turn before declaring success, and AWAIT that\r\n // yield. Node flags an unhandled rejection only after the current turn's\r\n // microtasks drain, so reporting success synchronously here fired FIRST\r\n // and erased the failure — a `build` whose async work rejected exited 0\r\n // having emitted nothing.\r\n //\r\n // The await is the load-bearing part, not the yield. Scheduling this as a\r\n // bare `setImmediate` let `execute()` RESOLVE while the verdict was still\r\n // pending: the callback outlived the call it belonged to, so the green\r\n // check could surface after the caller had already moved on — in a later\r\n // command, or after a rejection reported in the interim, which the guard\r\n // below cannot see because by then it reads the state of a run that has\r\n // already ended. Awaiting binds the banner to THIS invocation: `execute`\r\n // does not resolve until the verdict it is about to report has settled.\r\n //\r\n // `setImmediate` runs in the same loop iteration's check phase, so this\r\n // cannot hang on a lingering handle the way dropping the exit would; it\r\n // only lets `captureFatalAsyncErrors` win the race when there is one.\r\n await new Promise<void>((resolve) => setImmediate(resolve));\r\n\r\n // The yield is what gives a floating rejection the chance to be reported;\r\n // this is what acts on it. A green check printed after that error would\r\n // contradict it, and the exit that follows would reset `process.exitCode`\r\n // to 0 — re-erasing the very failure this whole path exists to surface.\r\n if (this.fatalAsyncErrorReported) return \"failed\";\r\n\r\n displayCommandSuccess(command.name, Date.now() - startTime);\r\n\r\n return \"succeeded\";\r\n } catch (error) {\r\n displayCommandError(command.name, error as Error);\r\n // Persistent commands (dev/start) own their startup-failure exits;\r\n // by the time an error reaches here they've already entered their\r\n // run loop, so it's a runtime error we log but don't crash on —\r\n // HMR or process supervisors can recover. Non-persistent\r\n // one-shot commands always exit on failure.\r\n if (!command.isPersistent) {\r\n process.exit(1);\r\n }\r\n\r\n return \"failed\";\r\n }\r\n }\r\n\r\n /**\r\n * Fail loudly on async errors that escape the command's own promise.\r\n *\r\n * `execute` awaits `command.execute(data)`, but work the command merely\r\n * *started* settles outside that await — `@mongez/events` `trigger` /\r\n * `triggerAll` are synchronous and do not await their listeners, so an async\r\n * listener that throws leaves a floating rejection behind. Node reports it at\r\n * the end of the turn, by which point the CLI had already exited 0: the\r\n * failure was erased and the command looked green.\r\n *\r\n * Persistent commands (dev/start) are exempt from the exit for the same\r\n * reason as the catch block in `execute`: by the time they reach this point\r\n * they own a run loop that is expected to survive runtime errors so HMR or a\r\n * supervisor can recover. They still print — silence is what made this class\r\n * of failure invisible in the first place.\r\n */\r\n protected fatalAsyncErrorReported = false;\r\n\r\n protected captureFatalAsyncErrors(command: CLICommand) {\r\n const onFatalAsyncError = (reason: unknown) => {\r\n // A rejection reason is not necessarily an Error (`Promise.reject(\"x\")`),\r\n // and a crash handler must never itself throw.\r\n const error = reason instanceof Error ? reason : new Error(String(reason));\r\n\r\n // Set before printing, so the deferred success banner is suppressed even\r\n // if displaying the error yields.\r\n this.fatalAsyncErrorReported = true;\r\n\r\n displayCommandError(command.name, error);\r\n\r\n if (!command.isPersistent) {\r\n exitAfterFlush(1);\r\n }\r\n };\r\n\r\n process.on(\"unhandledRejection\", onFatalAsyncError);\r\n process.on(\"uncaughtException\", onFatalAsyncError);\r\n }\r\n\r\n /**\r\n * Load preloaders\r\n */\r\n protected async loadPreloaders(command: CLICommand) {\r\n const preloaders = command.commandPreload || {};\r\n\r\n if (preloaders.runtimeStrategy) {\r\n Application.setRuntimeStrategy(preloaders.runtimeStrategy);\r\n }\r\n\r\n // Override, not a default: a command that declares an environment gets it\r\n // regardless of what the shell exported. Then read it back — `process.env`\r\n // is process-global and anything may have written to it, so a value that\r\n // did not take must fail here, loudly, rather than surface later as a\r\n // production React bundle under `warlock dev`.\r\n if (preloaders.environment) {\r\n Application.setEnvironment(preloaders.environment);\r\n\r\n if (process.env.NODE_ENV !== preloaders.environment) {\r\n throw new Error(\r\n `Command \"${command.name}\" set NODE_ENV to \"${preloaders.environment}\", but it read back as ` +\r\n `\"${process.env.NODE_ENV}\". The environment did not take, and every decision made ` +\r\n `downstream of it — env file selection, bundler dep optimisation — would be wrong.`,\r\n );\r\n }\r\n }\r\n\r\n // Env BEFORE config, unconditionally, for every command.\r\n //\r\n // `warlock.config.ts` is a module whose body runs on import, and projects\r\n // legitimately call `env(\"BUILD_OUT\", \"dist\")` in it. Loading config first\r\n // evaluated that body against an empty env store, so every such call\r\n // silently returned its default — under `build` and `start`, which never\r\n // loaded env at all, and under `dev` too, because config was loaded first\r\n // regardless. The ordering is load-bearing in the other direction as well:\r\n // `loadEnv()` reads `process.env.NODE_ENV` at call time to choose\r\n // `.env.<NODE_ENV>` over `.env`, so it must follow `setEnvironment` above.\r\n await loadEnvironmentFiles();\r\n\r\n await warlockConfigManager.load();\r\n\r\n if (preloaders.config || preloaders.bootstrap || preloaders.prestart) {\r\n await filesOrchestrator.init();\r\n }\r\n\r\n // `preloaders.env` is gone: env is loaded above for every command, so the\r\n // branch that used to serve it could only re-parse the same files and\r\n // re-override `process.env` a second time.\r\n if (preloaders.bootstrap) {\r\n await bootstrap();\r\n\r\n if (await fileExistsAsync(appPath(\"bootstrap.ts\"))) {\r\n await filesOrchestrator.load(\"src/app/bootstrap.ts\");\r\n }\r\n }\r\n\r\n // Load configuration files\r\n if (preloaders.config) {\r\n await loadConfigFiles(preloaders.config);\r\n }\r\n\r\n if (preloaders.prestart) {\r\n if (await fileExistsAsync(appPath(\"prestart.ts\"))) {\r\n await filesOrchestrator.load(\"src/app/prestart.ts\");\r\n }\r\n }\r\n\r\n // Initialize connectors.\r\n // `connectors: true` only starts the early phase here — late-phase\r\n // connectors (http, socket) start after the command's action loads\r\n // app code. Explicit lists bypass phase splitting (caller knows\r\n // exactly which connectors they want).\r\n if (preloaders.connectors) {\r\n // REGISTER before starting — the non-bundled counterpart of section 2.5\r\n // of the generated production entry, and the \"dev preloader\" path\r\n // `register-configured-connectors.ts` documents.\r\n //\r\n // Without this, `warlock.config.ts > connectors` drove the BUILD only:\r\n // `warlock build` read the array to drain each connector's contribution,\r\n // but under `warlock dev` nothing ever registered it, so an app had to\r\n // call `connectorsManager.register(...)` from its own `main.ts` to get a\r\n // connector running. Apps that did BOTH then registered the same\r\n // connector twice in production — once here from the baked config, once\r\n // from their own app code — and it booted twice, which surfaced as\r\n // `Route name \"...\" is already taken` while installing page routes.\r\n //\r\n // The array is omitted deliberately, so the function reads the config\r\n // loaded above; `expectedNames` is omitted too, because drift is a\r\n // build↔runtime relationship and dev has no build to drift from.\r\n //\r\n // The idempotency this function provides is against ITSELF — a second\r\n // call skips names the first registered. It does NOT protect against an\r\n // app calling `connectorsManager.register()` directly, which pushes\r\n // unconditionally, and which runs AFTER this point in both modes. So a\r\n // connector belongs in the config array or in app code, never both:\r\n // listing it in both is the duplicate this comment's route-name error\r\n // describes.\r\n registerConfiguredConnectors();\r\n\r\n // Fail fast on a busy port BEFORE the early-phase connectors (database,\r\n // cache, ...) connect. `http` itself is a LATE-phase connector, so its\r\n // own preflight is not reached until after those early connectors are\r\n // up and every app module has been imported — 7-13s of work discarded\r\n // before anyone learns the port was taken. This is the dev-preload\r\n // counterpart of the check the generated production entry runs at the\r\n // same point in its own boot sequence (`production-builder.ts`, step\r\n // 2.6) — a cheap bind-and-release probe, not a connector reorder.\r\n await preflightConfiguredHttpPort();\r\n\r\n if (preloaders.connectors === true) {\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\r\n } else {\r\n await connectorsManager.start(preloaders.connectors);\r\n }\r\n }\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAM,oBAAoB;;;;;;;;;AAU1B,SAAS,eAAe,MAAc;CACpC,QAAQ,WAAW;CAEnB,MAAM,QAAQ,iBAAiB,QAAQ,KAAK,IAAI,GAAG,iBAAiB;CACpE,MAAM,QAAQ;CAEd,IAAI,UAAU;CACd,MAAM,gBAAgB;EACpB,IAAI,EAAE,UAAU,GAAG;EAEnB,aAAa,KAAK;EAClB,QAAQ,KAAK,IAAI;CACnB;CAIA,QAAQ,OAAO,MAAM,IAAI,OAAO;CAChC,QAAQ,OAAO,MAAM,IAAI,OAAO;AAClC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAS,oBAA6B;CACpC,OAAO,YAAY;AACrB;AAEA,IAAa,qBAAb,MAAgC;;kBAIE,CAAC;qCAKa,IAAI,IAAI;kCAKf,IAAI,IAAI;iCA4hBX;;;;;CAvhBpC,AAAO,SAAS,GAAG,UAA8B;EAC/C,KAAK,SAAS,KAAK,GAAG,QAAQ;EAE9B,SAAS,SAAS,YAAY;GAC5B,MAAM,aAAa,QAAQ,KAAK,MAAM,GAAG,CAAC,CAAC;GAE3C,gBAAgB,iBAAiB,QAAQ,MAAM;IA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0B;GAE/B,oBAAoB,QAAQ,MAAM,KAAK;GAEvC,IAAI,CAAC,QAAQ,cACX,eAAe,CAAC;EAEpB;EAEA,QAAQ,GAAG,sBAAsB,iBAAiB;EAClD,QAAQ,GAAG,qBAAqB,iBAAiB;CACnD;;;;CAKA,MAAgB,eAAe,SAAqB;EAClD,MAAM,aAAa,QAAQ,kBAAkB,CAAC;EAE9C,IAAI,WAAW,iBACb,YAAY,mBAAmB,WAAW,eAAe;EAQ3D,IAAI,WAAW,aAAa;GAC1B,YAAY,eAAe,WAAW,WAAW;GAEjD,IAAI,QAAQ,IAAI,aAAa,WAAW,aACtC,MAAM,IAAI,MACR,YAAY,QAAQ,KAAK,qBAAqB,WAAW,YAAY,0BAC/D,QAAQ,IAAI,SAAS,2IAE7B;EAEJ;EAYA,MAAM,qBAAqB;EAE3B,MAAM,qBAAqB,KAAK;EAEhC,IAAI,WAAW,UAAU,WAAW,aAAa,WAAW,UAC1D,MAAM,kBAAkB,KAAK;EAM/B,IAAI,WAAW,WAAW;GACxB,MAAM,UAAU;GAEhB,IAAI,MAAM,gBAAgB,QAAQ,cAAc,CAAC,GAC/C,MAAM,kBAAkB,KAAK,sBAAsB;EAEvD;EAGA,IAAI,WAAW,QACb,MAAM,gBAAgB,WAAW,MAAM;EAGzC,IAAI,WAAW,UACb;OAAI,MAAM,gBAAgB,QAAQ,aAAa,CAAC,GAC9C,MAAM,kBAAkB,KAAK,qBAAqB;EACpD;EAQF,IAAI,WAAW,YAAY;GAyBzB,6BAA6B;GAU7B,MAAM,4BAA4B;GAElC,IAAI,WAAW,eAAe,MAC5B,MAAM,kBAAkB,kBAAwC;QAEhE,MAAM,kBAAkB,MAAM,WAAW,UAAU;EAEvD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"cli-commands.manager.mjs","names":[],"sources":["../../../../../../../core/src/cli/cli-commands.manager.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport { fileExistsAsync } from \"@warlock.js/fs\";\r\nimport { Application } from \"../application\";\r\nimport { bootstrap } from \"../bootstrap\";\r\nimport { loadConfigFiles } from \"../config/load-config-files\";\r\nimport { connectorsManager } from \"../connectors/connectors-manager\";\r\nimport { registerConfiguredConnectors } from \"../connectors/register-configured-connectors\";\r\nimport { ConnectorLifecyclePhase } from \"../connectors/types\";\r\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\r\nimport { isDevWorker } from \"../dev-server/supervisor\";\r\nimport { preflightConfiguredHttpPort } from \"../http/boot-port-preflight\";\r\nimport { manifestManager } from \"../manifest/manifest-manager\";\r\nimport { appPath } from \"../utils\";\r\nimport { loadEnvironmentFiles } from \"../utils/load-environment\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { CLICommand } from \"../commands/cli-command\";\r\nimport {\r\n displayBootError,\r\n displayCommandError,\r\n displayCommandHelp,\r\n displayCommandNotFound,\r\n displayCommandSuccess,\r\n displayExecutingCommand,\r\n displayHelp,\r\n displayMissingCommand,\r\n displayMissingOptions,\r\n displayWarlockVersionInTerminal,\r\n type HelpCommandInfo,\r\n isMatchingCommandName,\r\n} from \"./cli-commands.utils\";\r\nimport { cliCommandsLoader } from \"./commands-loader\";\r\nimport { frameworkCommands } from \"./framework-cli-commands\";\r\nimport { CliOptionValueError, type ParsedCliArgs, parseCliArgs } from \"./parse-cli-args\";\r\nimport { findSimilar } from \"./string-similarity\";\r\nimport type { CommandActionData, ResolvedCLICommandOption } from \"../commands/types\";\r\n\r\n/**\r\n * Best-effort budget (ms) for draining stdout/stderr before a forced exit.\r\n * Bounded so a stuck stream can never hang the CLI.\r\n */\r\nconst EXIT_FLUSH_BUDGET = 500;\r\n\r\n/**\r\n * Exit with `code` once stdout/stderr have drained.\r\n *\r\n * `process.exit()` truncates writes still queued on a non-TTY stdout — a pipe,\r\n * a CI log — which is how the *reason* for a failure gets lost even when the\r\n * exit code is right. `exitCode` is set up front so that a natural exit (should\r\n * the drain outlive the process's remaining work) is non-zero too.\r\n */\r\nfunction exitAfterFlush(code: number) {\r\n process.exitCode = code;\r\n\r\n const timer = setTimeout(() => process.exit(code), EXIT_FLUSH_BUDGET);\r\n timer.unref?.();\r\n\r\n let pending = 2;\r\n const drained = () => {\r\n if (--pending > 0) return;\r\n\r\n clearTimeout(timer);\r\n process.exit(code);\r\n };\r\n\r\n // A zero-length write's callback fires once everything queued ahead of it has\r\n // been handed to the OS.\r\n process.stdout.write(\"\", drained);\r\n process.stderr.write(\"\", drained);\r\n}\r\n\r\n/**\r\n * How a command run ended, from the process's point of view.\r\n *\r\n * - `succeeded` — finished, nothing rejected afterwards; the CLI may exit 0.\r\n * - `failed` — reported an error; the exit code is owned by whoever reported it.\r\n * - `running` — a persistent command (dev/start) now owns the process.\r\n *\r\n * `execute` returns this instead of exiting on success itself. A method that\r\n * terminates the process out from under its caller cannot be awaited honestly:\r\n * the exit it schedules outlives the call, so the success it represents is\r\n * still unsettled when `execute` resolves — which is exactly how a green check\r\n * ends up printed next to the failure that contradicts it.\r\n */\r\nexport type CommandRunVerdict = \"succeeded\" | \"failed\" | \"running\";\r\n\r\n/**\r\n * Whether this process is the CHILD half of a supervised command.\r\n *\r\n * ## The finding this encodes\r\n *\r\n * `warlock dev` printing `› Running dev...` twice was NOT a double boot, and\r\n * the distinction is the whole point of this function existing rather than the\r\n * line simply being deleted. The sequence, in file order:\r\n *\r\n * 1. `execute()` prints the header (below) — BEFORE `commandPreAction`.\r\n * 2. `cli/commands/dev-server.command.ts` `preAction` calls\r\n * `superviseDevServer()` when `!isDevWorker()`.\r\n * 3. `dev-server/supervisor.ts` `spawnWorker()` re-spawns `process.argv` with\r\n * `WARLOCK_DEV_WORKER=1`, so the child runs `warlock dev` again and prints\r\n * the header too.\r\n * 4. `superviseDevServer()` returns a promise that never settles, so the\r\n * supervisor's `await commandPreAction(...)` never resolves — `loadPreloaders`\r\n * and `command.execute` are unreachable in the supervisor.\r\n *\r\n * Step 4 is why only ONE process ever loads config, connectors, app modules or\r\n * a scheduler. Verified by running it: one `APP-CODE-LOADED`, one\r\n * `Application.markBooted`, one `⚡ Warlock.js` banner, one route registration,\r\n * two processes. The `2 job(s) registered` in the original report is two jobs\r\n * in one scheduler, not two schedulers — a genuine double boot would have\r\n * printed that warning twice.\r\n *\r\n * So the defect is exactly one duplicated line, and this is the guard that\r\n * keeps it one. `tests/unit/cli/dev-command-single-boot.test.ts` fails if the\r\n * supervisor ever starts running preloaders — i.e. if the double boot the\r\n * duplicated line looked like ever becomes real.\r\n */\r\nfunction isRespawnedWorker(): boolean {\r\n return isDevWorker();\r\n}\r\n\r\nexport class CLICommandsManager {\r\n /**\r\n * List of commands\r\n */\r\n public commands: CLICommand[] = [];\r\n\r\n /**\r\n * Commands map (name -> command)\r\n */\r\n public commandsMap: Map<string, CLICommand> = new Map();\r\n\r\n /**\r\n * Alias map (alias -> command name)\r\n */\r\n public aliasMap: Map<string, string> = new Map();\r\n\r\n /**\r\n * Register the given commands\r\n */\r\n public register(...commands: CLICommand[]): this {\r\n this.commands.push(...commands);\r\n\r\n commands.forEach((command) => {\r\n // `split` always yields a first element, so this holds. Falling back to\r\n // the whole name rather than asserting keeps the map keyed by a REAL\r\n // command name — a key of `undefined` would register the command under\r\n // the literal string \"undefined\" and make it unreachable by its own name.\r\n const commandKey = command.name.split(\" \")[0] ?? command.name;\r\n\r\n manifestManager.addCommandToList(command.name, {\r\n relativePath: command.commandRelativePath,\r\n source: command.commandSource || \"project\",\r\n description: command.commandDescription,\r\n alias: command.commandAlias,\r\n options: command.commandOptions.length > 0 ? command.commandOptions : undefined,\r\n });\r\n\r\n this.commandsMap.set(commandKey, command);\r\n\r\n // Register alias if exists\r\n if (command.commandAlias) {\r\n this.aliasMap.set(command.commandAlias, commandKey);\r\n }\r\n });\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Get command by name or alias\r\n */\r\n public getCommand(name: string): CLICommand | undefined {\r\n // First try direct lookup\r\n let command = this.commandsMap.get(name);\r\n if (command) return command;\r\n\r\n // Try alias lookup\r\n const realName = this.aliasMap.get(name);\r\n if (realName) {\r\n return this.commandsMap.get(realName);\r\n }\r\n\r\n return;\r\n }\r\n\r\n /**\r\n * Get all command names and aliases\r\n * Used for fuzzy matching suggestions\r\n */\r\n public getAllCommandNames(): string[] {\r\n const names: string[] = [];\r\n\r\n // Add all command names\r\n for (const name of this.commandsMap.keys()) {\r\n names.push(name);\r\n }\r\n\r\n // Add all aliases\r\n for (const alias of this.aliasMap.keys()) {\r\n names.push(alias);\r\n }\r\n\r\n // Also include cached commands from manifest\r\n const manifestCommands = manifestManager.commandsJson?.commands || {};\r\n // `Object.entries` rather than keys + index: the index read is\r\n // `T | undefined` under the strictness contract even for a key that came\r\n // from the object itself, and these names feed the CLI's \"did you mean?\"\r\n // suggestions — a literal \"undefined\" in that list is a suggestion no\r\n // operator can act on.\r\n for (const [name, meta] of Object.entries(manifestCommands)) {\r\n const baseName = name.split(\" \")[0] ?? name;\r\n\r\n if (!names.includes(baseName)) {\r\n names.push(baseName);\r\n }\r\n\r\n const alias = meta?.alias;\r\n\r\n if (alias && !names.includes(alias)) {\r\n names.push(alias);\r\n }\r\n }\r\n\r\n return names;\r\n }\r\n\r\n /**\r\n * Start the cli manager\r\n */\r\n public async start() {\r\n // Schema-less first pass: it exists to discover the command name and the\r\n // command-independent flags (--help, --version, --no-cache). Values here are\r\n // raw strings; the typed pass below is the one whose options reach a command.\r\n const { name, options } = parseCliArgs(process.argv);\r\n\r\n if (options.noCache) {\r\n manifestManager.clearCommandsCache();\r\n // remove the commands.json file as wel\r\n await manifestManager.removeCommandsFile();\r\n }\r\n\r\n if (options.version || options.v) {\r\n await displayWarlockVersionInTerminal();\r\n process.exit(0);\r\n }\r\n\r\n // Try to load from manifest first (fastest path)\r\n await manifestManager.loadCommands();\r\n\r\n // Register framework commands first (needed for help)\r\n this.register(\r\n ...frameworkCommands.map((command) => {\r\n if (!command.commandSource) {\r\n command.commandSource = \"framework\";\r\n }\r\n return command;\r\n }),\r\n );\r\n\r\n const isHelpCommand = options.help || options.h;\r\n\r\n // Handle global help (no command)\r\n if (!name && isHelpCommand) {\r\n await this.showGlobalHelp();\r\n process.exit(0);\r\n }\r\n\r\n // Handle warm cache\r\n if (options.warmCache) {\r\n await this.warmCache();\r\n process.exit(0);\r\n }\r\n\r\n if (!name) {\r\n displayMissingCommand();\r\n process.exit(1);\r\n }\r\n\r\n const command = await this.lazyGetCommand(name);\r\n\r\n if (manifestManager.hasChanges) {\r\n await manifestManager.saveCommands();\r\n }\r\n\r\n if (!command) {\r\n // Find similar commands for suggestions\r\n const allCommandNames = this.getAllCommandNames();\r\n const suggestions = findSimilar(name, allCommandNames).map((s) => s.value);\r\n\r\n displayCommandNotFound(name, suggestions);\r\n process.exit(1);\r\n }\r\n\r\n // Handle command-specific help\r\n if (isHelpCommand) {\r\n displayCommandHelp({\r\n name: command.name,\r\n alias: command.commandAlias,\r\n description: command.commandDescription,\r\n options: command.commandOptions,\r\n });\r\n process.exit(0);\r\n }\r\n\r\n // The first parse above had no command to consult, so every value in it is\r\n // a raw string. Now that the command is resolved, re-read argv against its\r\n // declared options so a `type: \"boolean\"` option arrives as a boolean.\r\n const resolved = this.resolveCommandArgs(command);\r\n\r\n const verdict = await this.execute(command, {\r\n options: resolved.options,\r\n args: resolved.args,\r\n });\r\n\r\n // The process-level exit belongs to the entrypoint, not to `execute`.\r\n // A one-shot command can leave a handle open (a db connection, a watcher a\r\n // plugin forgot to close), so the CLI exits explicitly rather than waiting\r\n // for the loop to drain — but only on a verdict of `succeeded`. `failed`\r\n // already exited non-zero through whoever reported it, and `running` means\r\n // a persistent command owns the process now.\r\n if (verdict === \"succeeded\") {\r\n exitAfterFlush(0);\r\n }\r\n }\r\n\r\n /**\r\n * Re-parse argv against the resolved command's declared options.\r\n *\r\n * parseCliArgs runs twice on purpose. The first run produces the command\r\n * name, and there is no schema to consult yet; the second one, here, can be\r\n * type-aware. Re-reading argv (rather than post-processing the first result)\r\n * is what makes `--rollback users.ts` recoverable: by the time the first pass\r\n * returns, the swallowed positional is indistinguishable from a value.\r\n */\r\n protected resolveCommandArgs(command: CLICommand, argv: string[] = process.argv): ParsedCliArgs {\r\n try {\r\n return parseCliArgs(argv, command.commandOptions);\r\n } catch (error) {\r\n if (error instanceof CliOptionValueError) {\r\n console.log();\r\n console.log(` ${colors.redBright(\"Error:\")} ${error.message}`);\r\n console.log();\r\n process.exit(1);\r\n }\r\n\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Show global help with all commands\r\n * Uses manifest if available for fast display\r\n */\r\n protected async showGlobalHelp() {\r\n if (\r\n manifestManager.isCommandLoaded &&\r\n Object.keys(manifestManager.commandsJson?.commands || {}).length > 0\r\n ) {\r\n // Use manifest directly - no need to load command files\r\n const helpCommands: HelpCommandInfo[] = Object.entries(\r\n manifestManager.commandsJson?.commands || {},\r\n ).map(([name, cmd]) => ({\r\n name,\r\n alias: cmd.alias,\r\n description: cmd.description,\r\n source: cmd.source,\r\n }));\r\n\r\n await displayHelp(helpCommands);\r\n return;\r\n }\r\n\r\n // Fallback: No manifest, build from registered commands\r\n // This happens on first run before warm-cache\r\n await this.loadPluginsCommands();\r\n\r\n const projectCommands = await cliCommandsLoader.scanAll();\r\n\r\n this.register(...projectCommands);\r\n\r\n await manifestManager.saveCommands();\r\n\r\n // Build help info from registered commands\r\n const helpCommands: HelpCommandInfo[] = this.commands.map((cmd) => ({\r\n name: cmd.name,\r\n alias: cmd.commandAlias,\r\n description: cmd.commandDescription,\r\n source: cmd.commandSource || \"project\",\r\n }));\r\n\r\n await displayHelp(helpCommands);\r\n }\r\n\r\n /**\r\n * Warm cache - scan all project commands and save to manifest\r\n */\r\n protected async warmCache() {\r\n console.log();\r\n console.log(` ${colors.cyan(\"›\")} Scanning project commands...`);\r\n\r\n const projectCommands = await cliCommandsLoader.scanAll();\r\n\r\n this.register(...projectCommands);\r\n\r\n await manifestManager.saveCommands();\r\n\r\n console.log(\r\n ` ${colors.green(\"✔\")} Cached ${colors.bold(String(projectCommands.length))} project commands`,\r\n );\r\n console.log();\r\n }\r\n\r\n /**\r\n * Load plugins commands\r\n */\r\n protected async loadPluginsCommands() {\r\n await warlockConfigManager.load();\r\n\r\n if (warlockConfigManager.isLoaded) {\r\n this.register(\r\n ...(warlockConfigManager.get(\"cli\")?.commands || []).map((command) => {\r\n if (!command.commandSource) {\r\n command.commandSource = \"plugin\";\r\n }\r\n return command;\r\n }),\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Try to find the command based on the given command name or alias\r\n */\r\n protected async lazyGetCommand(name: string) {\r\n // first step, try to find it directly through current commands\r\n let command = this.getCommand(name);\r\n if (command) {\r\n return command;\r\n }\r\n\r\n // second step, try to find it through warlock config commands\r\n await this.loadPluginsCommands();\r\n\r\n command = this.getCommand(name);\r\n\r\n if (command) {\r\n return command;\r\n }\r\n\r\n // third step, try to find it through project commands\r\n await this.loadProjectCommands(name);\r\n\r\n command = this.getCommand(name);\r\n if (command) {\r\n return command;\r\n }\r\n\r\n return null;\r\n }\r\n\r\n /**\r\n * Load project commands\r\n */\r\n protected async loadProjectCommands(name: string) {\r\n // first get the commands.json contents as an object\r\n const jsonCommandsFile = await manifestManager.loadCommands();\r\n\r\n if (jsonCommandsFile) {\r\n // Check by name or alias\r\n // `Object.entries` hands the metadata over already narrowed; a `for...in`\r\n // index read is `T | undefined` and every field below is read off it.\r\n for (const [fullCommandName, cmdMeta] of Object.entries(jsonCommandsFile.commands)) {\r\n if (cmdMeta === undefined) continue;\r\n\r\n // Match by name or alias\r\n if (isMatchingCommandName(fullCommandName, name) || cmdMeta.alias === name) {\r\n const commandPath = cmdMeta.relativePath;\r\n if (commandPath) {\r\n const executedCommand = await cliCommandsLoader.load(commandPath);\r\n\r\n if (executedCommand) {\r\n executedCommand.$relativePath(commandPath);\r\n this.register(executedCommand);\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n const command = await cliCommandsLoader.locate(name);\r\n\r\n if (command) {\r\n this.register(command);\r\n return;\r\n }\r\n }\r\n\r\n /**\r\n * Validate required options\r\n */\r\n protected validateOptions(\r\n command: CLICommand,\r\n options: Record<string, string | boolean | number>,\r\n ): ResolvedCLICommandOption[] {\r\n const missing: ResolvedCLICommandOption[] = [];\r\n\r\n command.commandOptions.forEach((opt) => {\r\n if (opt.required) {\r\n // Check if option is provided by name or alias\r\n const hasOption =\r\n options[opt.name] !== undefined || (opt.alias && options[opt.alias] !== undefined);\r\n if (!hasOption) {\r\n missing.push(opt);\r\n }\r\n }\r\n });\r\n\r\n return missing;\r\n }\r\n\r\n /**\r\n * Apply default values to options\r\n */\r\n protected applyDefaultOptions(\r\n command: CLICommand,\r\n options: Record<string, string | boolean | number>,\r\n ): Record<string, string | boolean | number> {\r\n const result = { ...options };\r\n\r\n command.commandOptions.forEach((opt) => {\r\n if (opt.defaultValue !== undefined) {\r\n const hasOption =\r\n result[opt.name] !== undefined || (opt.alias && result[opt.alias] !== undefined);\r\n if (!hasOption) {\r\n result[opt.name] = opt.defaultValue;\r\n }\r\n }\r\n\r\n // `!== undefined`, not truthiness: `-r=false` now resolves to the boolean\r\n // `false`, and a truthiness test would drop it before it ever reached the\r\n // canonical name — leaving `rollback` undefined instead of explicitly off.\r\n if (\r\n opt.alias !== undefined &&\r\n result[opt.alias] !== undefined &&\r\n result[opt.name] === undefined\r\n ) {\r\n // The `!== undefined` guard on the line above already proves this read\r\n // is defined, but the compiler does not carry a guard on one index\r\n // expression to a second, textually identical one. Reading it into a\r\n // local makes the narrowing survive, WITHOUT weakening the check — an\r\n // `?? ` fallback here would resurrect exactly the bug the comment above\r\n // describes, turning an explicit `-r=false` into a default.\r\n const aliasValue = result[opt.alias];\r\n\r\n if (aliasValue !== undefined) {\r\n result[opt.name] = aliasValue;\r\n }\r\n }\r\n });\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Execute the given command and report how it ended.\r\n *\r\n * Returning the verdict — rather than exiting on success from in here — is\r\n * what makes the awaited result trustworthy: see {@link CommandRunVerdict}.\r\n */\r\n public async execute(command: CLICommand, data: CommandActionData): Promise<CommandRunVerdict> {\r\n const startTime = Date.now();\r\n\r\n // Validate required options\r\n const missingOptions = this.validateOptions(command, data.options);\r\n if (missingOptions.length > 0) {\r\n displayMissingOptions(missingOptions);\r\n process.exit(1);\r\n }\r\n\r\n // Apply default values\r\n data.options = this.applyDefaultOptions(command, data.options);\r\n\r\n // ONE header per `warlock <command>` the user typed — not one per process.\r\n //\r\n // `warlock dev` is TWO processes by design: the invocation the user typed\r\n // becomes a thin supervisor (`dev-server/supervisor.ts`) that re-spawns\r\n // `process.argv` with `WARLOCK_DEV_WORKER=1`, and the child is the actual\r\n // server. Both are `warlock dev`, so both reached this line and the user saw\r\n //\r\n // › Running dev...\r\n // › Running dev...\r\n //\r\n // which reads exactly like the application booting twice. It is not — see\r\n // the block comment on `isRespawnedWorker` — but the line was still wrong,\r\n // and it re-printed on every crash-restart on top of the supervisor's own\r\n // \"restarting\" notice.\r\n //\r\n // The SUPERVISOR keeps the header, not the worker: it prints immediately\r\n // (so a slow boot is not silent), it prints once for the whole session\r\n // (restarts are already announced as restarts), and it is the process the\r\n // user actually started.\r\n if (!isRespawnedWorker()) {\r\n displayExecutingCommand(command.name);\r\n }\r\n\r\n if (command.commandPreAction) {\r\n await command.commandPreAction(data);\r\n }\r\n\r\n // load preloaders\r\n if (command.commandPreload) {\r\n try {\r\n await this.loadPreloaders(command);\r\n } catch (error) {\r\n // A preload failure (a bad import in a config file, a connector that\r\n // throws on boot, a missing module export) happens BEFORE the command's\r\n // action runs — there is no run loop to recover into, so it is ALWAYS\r\n // fatal, persistent command (dev/start) or not. Surface the real cause\r\n // and the offending file, then exit. This MUST stay outside the\r\n // command-execute try/catch below: letting a preload rejection escape\r\n // turned `warlock dev` into a silent hang — the unhandled rejection slid\r\n // past while the already-started loader worker thread kept the process\r\n // alive, freezing just after the banner with no error printed.\r\n displayBootError(command.name, error as Error);\r\n process.exit(1);\r\n }\r\n }\r\n\r\n this.captureFatalAsyncErrors(command);\r\n\r\n try {\r\n await command.execute(data);\r\n\r\n // Persistent commands (dev/start) hand control to their run loop here.\r\n // There is no success banner to print and nothing to exit for.\r\n if (command.isPersistent) return \"running\";\r\n\r\n // Yield one full event-loop turn before declaring success, and AWAIT that\r\n // yield. Node flags an unhandled rejection only after the current turn's\r\n // microtasks drain, so reporting success synchronously here fired FIRST\r\n // and erased the failure — a `build` whose async work rejected exited 0\r\n // having emitted nothing.\r\n //\r\n // The await is the load-bearing part, not the yield. Scheduling this as a\r\n // bare `setImmediate` let `execute()` RESOLVE while the verdict was still\r\n // pending: the callback outlived the call it belonged to, so the green\r\n // check could surface after the caller had already moved on — in a later\r\n // command, or after a rejection reported in the interim, which the guard\r\n // below cannot see because by then it reads the state of a run that has\r\n // already ended. Awaiting binds the banner to THIS invocation: `execute`\r\n // does not resolve until the verdict it is about to report has settled.\r\n //\r\n // `setImmediate` runs in the same loop iteration's check phase, so this\r\n // cannot hang on a lingering handle the way dropping the exit would; it\r\n // only lets `captureFatalAsyncErrors` win the race when there is one.\r\n await new Promise<void>((resolve) => setImmediate(resolve));\r\n\r\n // The yield is what gives a floating rejection the chance to be reported;\r\n // this is what acts on it. A green check printed after that error would\r\n // contradict it, and the exit that follows would reset `process.exitCode`\r\n // to 0 — re-erasing the very failure this whole path exists to surface.\r\n if (this.fatalAsyncErrorReported) return \"failed\";\r\n\r\n displayCommandSuccess(command.name, Date.now() - startTime);\r\n\r\n return \"succeeded\";\r\n } catch (error) {\r\n displayCommandError(command.name, error as Error);\r\n // Persistent commands (dev/start) own their startup-failure exits;\r\n // by the time an error reaches here they've already entered their\r\n // run loop, so it's a runtime error we log but don't crash on —\r\n // HMR or process supervisors can recover. Non-persistent\r\n // one-shot commands always exit on failure.\r\n if (!command.isPersistent) {\r\n process.exit(1);\r\n }\r\n\r\n return \"failed\";\r\n }\r\n }\r\n\r\n /**\r\n * Fail loudly on async errors that escape the command's own promise.\r\n *\r\n * `execute` awaits `command.execute(data)`, but work the command merely\r\n * *started* settles outside that await — `@mongez/events` `trigger` /\r\n * `triggerAll` are synchronous and do not await their listeners, so an async\r\n * listener that throws leaves a floating rejection behind. Node reports it at\r\n * the end of the turn, by which point the CLI had already exited 0: the\r\n * failure was erased and the command looked green.\r\n *\r\n * Persistent commands (dev/start) are exempt from the exit for the same\r\n * reason as the catch block in `execute`: by the time they reach this point\r\n * they own a run loop that is expected to survive runtime errors so HMR or a\r\n * supervisor can recover. They still print — silence is what made this class\r\n * of failure invisible in the first place.\r\n */\r\n protected fatalAsyncErrorReported = false;\r\n\r\n protected captureFatalAsyncErrors(command: CLICommand) {\r\n const onFatalAsyncError = (reason: unknown) => {\r\n // A rejection reason is not necessarily an Error (`Promise.reject(\"x\")`),\r\n // and a crash handler must never itself throw.\r\n const error = reason instanceof Error ? reason : new Error(String(reason));\r\n\r\n // Set before printing, so the deferred success banner is suppressed even\r\n // if displaying the error yields.\r\n this.fatalAsyncErrorReported = true;\r\n\r\n displayCommandError(command.name, error);\r\n\r\n if (!command.isPersistent) {\r\n exitAfterFlush(1);\r\n }\r\n };\r\n\r\n process.on(\"unhandledRejection\", onFatalAsyncError);\r\n process.on(\"uncaughtException\", onFatalAsyncError);\r\n }\r\n\r\n /**\r\n * Load preloaders\r\n */\r\n protected async loadPreloaders(command: CLICommand) {\r\n const preloaders = command.commandPreload || {};\r\n\r\n if (preloaders.runtimeStrategy) {\r\n Application.setRuntimeStrategy(preloaders.runtimeStrategy);\r\n }\r\n\r\n // Override, not a default: a command that declares an environment gets it\r\n // regardless of what the shell exported. Then read it back — `process.env`\r\n // is process-global and anything may have written to it, so a value that\r\n // did not take must fail here, loudly, rather than surface later as a\r\n // production React bundle under `warlock dev`.\r\n if (preloaders.environment) {\r\n Application.setEnvironment(preloaders.environment);\r\n\r\n if (process.env.NODE_ENV !== preloaders.environment) {\r\n throw new Error(\r\n `Command \"${command.name}\" set NODE_ENV to \"${preloaders.environment}\", but it read back as ` +\r\n `\"${process.env.NODE_ENV}\". The environment did not take, and every decision made ` +\r\n `downstream of it — env file selection, bundler dep optimisation — would be wrong.`,\r\n );\r\n }\r\n }\r\n\r\n // Env BEFORE config, unconditionally, for every command.\r\n //\r\n // `warlock.config.ts` is a module whose body runs on import, and projects\r\n // legitimately call `env(\"BUILD_OUT\", \"dist\")` in it. Loading config first\r\n // evaluated that body against an empty env store, so every such call\r\n // silently returned its default — under `build` and `start`, which never\r\n // loaded env at all, and under `dev` too, because config was loaded first\r\n // regardless. The ordering is load-bearing in the other direction as well:\r\n // `loadEnv()` reads `process.env.NODE_ENV` at call time to choose\r\n // `.env.<NODE_ENV>` over `.env`, so it must follow `setEnvironment` above.\r\n await loadEnvironmentFiles();\r\n\r\n await warlockConfigManager.load();\r\n\r\n if (preloaders.config || preloaders.bootstrap || preloaders.prestart) {\r\n await filesOrchestrator.init();\r\n }\r\n\r\n // `preloaders.env` is gone: env is loaded above for every command, so the\r\n // branch that used to serve it could only re-parse the same files and\r\n // re-override `process.env` a second time.\r\n if (preloaders.bootstrap) {\r\n await bootstrap();\r\n\r\n if (await fileExistsAsync(appPath(\"bootstrap.ts\"))) {\r\n await filesOrchestrator.load(\"src/app/bootstrap.ts\");\r\n }\r\n }\r\n\r\n // Load configuration files\r\n if (preloaders.config) {\r\n await loadConfigFiles(preloaders.config);\r\n }\r\n\r\n if (preloaders.prestart) {\r\n if (await fileExistsAsync(appPath(\"prestart.ts\"))) {\r\n await filesOrchestrator.load(\"src/app/prestart.ts\");\r\n }\r\n }\r\n\r\n // Initialize connectors.\r\n // `connectors: true` only starts the early phase here — late-phase\r\n // connectors (http, socket) start after the command's action loads\r\n // app code. Explicit lists bypass phase splitting (caller knows\r\n // exactly which connectors they want).\r\n if (preloaders.connectors) {\r\n // REGISTER before starting — the non-bundled counterpart of section 2.5\r\n // of the generated production entry, and the \"dev preloader\" path\r\n // `register-configured-connectors.ts` documents.\r\n //\r\n // Without this, `warlock.config.ts > connectors` drove the BUILD only:\r\n // `warlock build` read the array to drain each connector's contribution,\r\n // but under `warlock dev` nothing ever registered it, so an app had to\r\n // call `connectorsManager.register(...)` from its own `main.ts` to get a\r\n // connector running. Apps that did BOTH then registered the same\r\n // connector twice in production — once here from the baked config, once\r\n // from their own app code — and it booted twice, which surfaced as\r\n // `Route name \"...\" is already taken` while installing page routes.\r\n //\r\n // The array is omitted deliberately, so the function reads the config\r\n // loaded above; `expectedNames` is omitted too, because drift is a\r\n // build↔runtime relationship and dev has no build to drift from.\r\n //\r\n // The idempotency this function provides is against ITSELF — a second\r\n // call skips names the first registered. It does NOT protect against an\r\n // app calling `connectorsManager.register()` directly, which pushes\r\n // unconditionally, and which runs AFTER this point in both modes. So a\r\n // connector belongs in the config array or in app code, never both:\r\n // listing it in both is the duplicate this comment's route-name error\r\n // describes.\r\n registerConfiguredConnectors();\r\n\r\n // Fail fast on a busy port BEFORE the early-phase connectors (database,\r\n // cache, ...) connect. `http` itself is a LATE-phase connector, so its\r\n // own preflight is not reached until after those early connectors are\r\n // up and every app module has been imported — 7-13s of work discarded\r\n // before anyone learns the port was taken. This is the dev-preload\r\n // counterpart of the check the generated production entry runs at the\r\n // same point in its own boot sequence (`production-builder.ts`, step\r\n // 2.6) — a cheap bind-and-release probe, not a connector reorder.\r\n await preflightConfiguredHttpPort();\r\n\r\n if (preloaders.connectors === true) {\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\r\n } else {\r\n await connectorsManager.start(preloaders.connectors);\r\n }\r\n }\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAM,oBAAoB;;;;;;;;;AAU1B,SAAS,eAAe,MAAc;CACpC,QAAQ,WAAW;CAEnB,MAAM,QAAQ,iBAAiB,QAAQ,KAAK,IAAI,GAAG,iBAAiB;CACpE,MAAM,QAAQ;CAEd,IAAI,UAAU;CACd,MAAM,gBAAgB;EACpB,IAAI,EAAE,UAAU,GAAG;EAEnB,aAAa,KAAK;EAClB,QAAQ,KAAK,IAAI;CACnB;CAIA,QAAQ,OAAO,MAA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MAAM,kBAAkB,KAAK,sBAAsB;EAEvD;EAGA,IAAI,WAAW,QACb,MAAM,gBAAgB,WAAW,MAAM;EAGzC,IAAI,WAAW,UACb;OAAI,MAAM,gBAAgB,QAAQ,aAAa,CAAC,GAC9C,MAAM,kBAAkB,KAAK,qBAAqB;EACpD;EAQF,IAAI,WAAW,YAAY;GAyBzB,6BAA6B;GAU7B,MAAM,4BAA4B;GAElC,IAAI,WAAW,eAAe,MAC5B,MAAM,kBAAkB,kBAAwC;QAEhE,MAAM,kBAAkB,MAAM,WAAW,UAAU;EAEvD;CACF;AACF"}
|
|
@@ -111,12 +111,12 @@ function printRoutesTable(rows) {
|
|
|
111
111
|
return;
|
|
112
112
|
}
|
|
113
113
|
const widths = columnWidths(rows);
|
|
114
|
-
const headerLine = COLUMNS.map((column, index) => column.header.padEnd(widths[index])).join(GAP).trimEnd();
|
|
114
|
+
const headerLine = COLUMNS.map((column, index) => column.header.padEnd(widths[index] ?? 0)).join(GAP).trimEnd();
|
|
115
115
|
console.log(colors.bold(headerLine));
|
|
116
116
|
for (const row of rows) {
|
|
117
117
|
const cells = COLUMNS.map((column, index) => {
|
|
118
|
-
if (column.key === "method") return colorizeMethodCell(row.method, widths[index]);
|
|
119
|
-
return cellText(row, column.key).padEnd(widths[index]);
|
|
118
|
+
if (column.key === "method") return colorizeMethodCell(row.method, widths[index] ?? 0);
|
|
119
|
+
return cellText(row, column.key).padEnd(widths[index] ?? 0);
|
|
120
120
|
});
|
|
121
121
|
console.log(cells.join(GAP).trimEnd());
|
|
122
122
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format-routes-table.mjs","names":[],"sources":["../../../../../../../../../core/src/cli/commands/routes/format-routes-table.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { methodRank, type RouteRow } from \"./route-row\";\n\n/** The columns rendered, in order, with their header labels. */\nconst COLUMNS = [\n { key: \"method\", header: \"METHOD\" },\n { key: \"path\", header: \"PATH\" },\n { key: \"name\", header: \"NAME\" },\n { key: \"action\", header: \"ACTION\" },\n { key: \"middleware\", header: \"MW\" },\n { key: \"source\", header: \"SOURCE\" },\n] as const;\n\ntype ColumnKey = (typeof COLUMNS)[number][\"key\"];\n\n/** Two spaces between columns. */\nconst GAP = \" \";\n\n/** Shown for an empty string cell so the column doesn't read as a gap. */\nconst EMPTY_CELL = \"—\";\n\n/**\n * The plain (uncolored) text of one cell. Numbers render as-is; an empty string\n * renders as {@link EMPTY_CELL}. This is the single source of truth for both\n * the width math and the rendered text, so colored and uncolored output stay\n * aligned.\n *\n * @param row - The row\n * @param key - The column key\n * @returns The cell's printable text\n */\nfunction cellText(row: RouteRow, key: ColumnKey): string {\n if (key === \"middleware\") return String(row.middleware);\n\n const value = row[key] as string;\n\n return value.length > 0 ? value : EMPTY_CELL;\n}\n\n/**\n * Per-column display width: the longest of the header and every cell.\n *\n * @param rows - The rows to measure\n * @returns One width per column, in column order\n */\nfunction columnWidths(rows: RouteRow[]): number[] {\n return COLUMNS.map((column) =>\n Math.max(column.header.length, ...rows.map((row) => cellText(row, column.key).length)),\n );\n}\n\n/**\n * Build a one-line, human-readable summary: the total plus a per-method\n * breakdown ordered by {@link methodRank}, e.g.\n * `42 routes (38 GET · 2 POST · 1 PUT · 1 DELETE)`.\n *\n * @param rows - The rows being summarized\n * @returns The summary line\n */\nexport function routesSummary(rows: RouteRow[]): string {\n const noun = rows.length === 1 ? \"route\" : \"routes\";\n\n if (rows.length === 0) return `0 ${noun}`;\n\n const counts = new Map<string, number>();\n\n for (const row of rows) {\n counts.set(row.method, (counts.get(row.method) ?? 0) + 1);\n }\n\n const breakdown = [...counts.entries()]\n .sort(([a], [b]) => methodRank(a) - methodRank(b))\n .map(([method, count]) => `${count} ${method}`)\n .join(\" · \");\n\n return `${rows.length} ${noun} (${breakdown})`;\n}\n\n/**\n * Render the routes table as an ordered list of plain (uncolored) lines:\n * a header row, one row per route, a blank line, then the summary. Returned as\n * strings (not printed) so the layout is unit-testable without ANSI noise.\n *\n * @param rows - The rows to render (already filtered/sorted by the caller)\n * @returns The lines to print, top to bottom\n */\nexport function formatRoutesTableLines(rows: RouteRow[]): string[] {\n if (rows.length === 0) {\n return [\"No routes registered.\"];\n }\n\n const widths = columnWidths(rows);\n\n const renderRow = (cells: string[]) =>\n cells\n .map((text, index) => text.padEnd(widths[index]))\n .join(GAP)\n .trimEnd();\n\n const lines = [renderRow(COLUMNS.map((column) => column.header))];\n\n for (const row of rows) {\n lines.push(renderRow(COLUMNS.map((column) => cellText(row, column.key))));\n }\n\n lines.push(\"\");\n lines.push(routesSummary(rows));\n\n return lines;\n}\n\n/** Per-verb color for the METHOD column. Unknown verbs fall back to white. */\nconst METHOD_COLOR: Record<string, (input: string) => string> = {\n GET: colors.green,\n POST: colors.blue,\n PUT: colors.yellow,\n PATCH: colors.yellow,\n DELETE: colors.red,\n OPTIONS: colors.gray,\n HEAD: colors.gray,\n ALL: colors.magenta,\n};\n\n/**\n * Colorize the method label, then right-pad with plain spaces so column\n * alignment is computed from the visible width, not the ANSI-coded length.\n *\n * @param method - The uppercased HTTP verb\n * @param width - The METHOD column width\n * @returns The colored, padded cell\n */\nfunction colorizeMethodCell(method: string, width: number): string {\n const colorize = METHOD_COLOR[method] ?? colors.white;\n\n return colorize(method) + \" \".repeat(Math.max(0, width - method.length));\n}\n\n/**\n * Print the routes table to stdout with a bold header, verb-colored METHOD\n * column, and a dimmed summary. The empty case prints a single yellow notice\n * (a booted app with zero routes usually means a route module failed to load).\n *\n * Thin presentation wrapper over {@link formatRoutesTableLines} /\n * {@link routesSummary} — those stay the source of truth for layout.\n *\n * @param rows - The rows to print (already filtered/sorted by the caller)\n */\nexport function printRoutesTable(rows: RouteRow[]): void {\n if (rows.length === 0) {\n console.log(colors.yellow(\"No routes registered — did a route module fail to load?\"));\n return;\n }\n\n const widths = columnWidths(rows);\n\n const headerLine = COLUMNS.map((column, index) => column.header.padEnd(widths[index]))\n .join(GAP)\n .trimEnd();\n\n console.log(colors.bold(headerLine));\n\n for (const row of rows) {\n const cells = COLUMNS.map((column, index) => {\n if (column.key === \"method\") {\n return colorizeMethodCell(row.method, widths[index]);\n }\n\n return cellText(row, column.key).padEnd(widths[index]);\n });\n\n console.log(cells.join(GAP).trimEnd());\n }\n\n console.log(\"\");\n console.log(colors.gray(routesSummary(rows)));\n}\n"],"mappings":";;;;;AAIA,MAAM,UAAU;CACd;EAAE,KAAK;EAAU,QAAQ;CAAS;CAClC;EAAE,KAAK;EAAQ,QAAQ;CAAO;CAC9B;EAAE,KAAK;EAAQ,QAAQ;CAAO;CAC9B;EAAE,KAAK;EAAU,QAAQ;CAAS;CAClC;EAAE,KAAK;EAAc,QAAQ;CAAK;CAClC;EAAE,KAAK;EAAU,QAAQ;CAAS;AACpC;;AAKA,MAAM,MAAM;;AAGZ,MAAM,aAAa;;;;;;;;;;;AAYnB,SAAS,SAAS,KAAe,KAAwB;CACvD,IAAI,QAAQ,cAAc,OAAO,OAAO,IAAI,UAAU;CAEtD,MAAM,QAAQ,IAAI;CAElB,OAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;;;;;;;AAQA,SAAS,aAAa,MAA4B;CAChD,OAAO,QAAQ,KAAK,WAClB,KAAK,IAAI,OAAO,OAAO,QAAQ,GAAG,KAAK,KAAK,QAAQ,SAAS,KAAK,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,CACvF;AACF;;;;;;;;;AAUA,SAAgB,cAAc,MAA0B;CACtD,MAAM,OAAO,KAAK,WAAW,IAAI,UAAU;CAE3C,IAAI,KAAK,WAAW,GAAG,OAAO,KAAK;CAEnC,MAAM,yBAAS,IAAI,IAAoB;CAEvC,KAAK,MAAM,OAAO,MAChB,OAAO,IAAI,IAAI,SAAS,OAAO,IAAI,IAAI,MAAM,KAAK,KAAK,CAAC;CAG1D,MAAM,YAAY,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CACpC,MAAM,CAAC,IAAI,CAAC,OAAO,WAAW,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CACjD,KAAK,CAAC,QAAQ,WAAW,GAAG,MAAM,GAAG,QAAQ,CAAC,CAC9C,KAAK,KAAK;CAEb,OAAO,GAAG,KAAK,OAAO,GAAG,KAAK,IAAI,UAAU;AAC9C;;
|
|
1
|
+
{"version":3,"file":"format-routes-table.mjs","names":[],"sources":["../../../../../../../../../core/src/cli/commands/routes/format-routes-table.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { methodRank, type RouteRow } from \"./route-row\";\n\n/** The columns rendered, in order, with their header labels. */\nconst COLUMNS = [\n { key: \"method\", header: \"METHOD\" },\n { key: \"path\", header: \"PATH\" },\n { key: \"name\", header: \"NAME\" },\n { key: \"action\", header: \"ACTION\" },\n { key: \"middleware\", header: \"MW\" },\n { key: \"source\", header: \"SOURCE\" },\n] as const;\n\ntype ColumnKey = (typeof COLUMNS)[number][\"key\"];\n\n/** Two spaces between columns. */\nconst GAP = \" \";\n\n/** Shown for an empty string cell so the column doesn't read as a gap. */\nconst EMPTY_CELL = \"—\";\n\n/**\n * The plain (uncolored) text of one cell. Numbers render as-is; an empty string\n * renders as {@link EMPTY_CELL}. This is the single source of truth for both\n * the width math and the rendered text, so colored and uncolored output stay\n * aligned.\n *\n * @param row - The row\n * @param key - The column key\n * @returns The cell's printable text\n */\nfunction cellText(row: RouteRow, key: ColumnKey): string {\n if (key === \"middleware\") return String(row.middleware);\n\n const value = row[key] as string;\n\n return value.length > 0 ? value : EMPTY_CELL;\n}\n\n/**\n * Per-column display width: the longest of the header and every cell.\n *\n * @param rows - The rows to measure\n * @returns One width per column, in column order\n */\nfunction columnWidths(rows: RouteRow[]): number[] {\n return COLUMNS.map((column) =>\n Math.max(column.header.length, ...rows.map((row) => cellText(row, column.key).length)),\n );\n}\n\n/**\n * Build a one-line, human-readable summary: the total plus a per-method\n * breakdown ordered by {@link methodRank}, e.g.\n * `42 routes (38 GET · 2 POST · 1 PUT · 1 DELETE)`.\n *\n * @param rows - The rows being summarized\n * @returns The summary line\n */\nexport function routesSummary(rows: RouteRow[]): string {\n const noun = rows.length === 1 ? \"route\" : \"routes\";\n\n if (rows.length === 0) return `0 ${noun}`;\n\n const counts = new Map<string, number>();\n\n for (const row of rows) {\n counts.set(row.method, (counts.get(row.method) ?? 0) + 1);\n }\n\n const breakdown = [...counts.entries()]\n .sort(([a], [b]) => methodRank(a) - methodRank(b))\n .map(([method, count]) => `${count} ${method}`)\n .join(\" · \");\n\n return `${rows.length} ${noun} (${breakdown})`;\n}\n\n/**\n * Render the routes table as an ordered list of plain (uncolored) lines:\n * a header row, one row per route, a blank line, then the summary. Returned as\n * strings (not printed) so the layout is unit-testable without ANSI noise.\n *\n * @param rows - The rows to render (already filtered/sorted by the caller)\n * @returns The lines to print, top to bottom\n */\nexport function formatRoutesTableLines(rows: RouteRow[]): string[] {\n if (rows.length === 0) {\n return [\"No routes registered.\"];\n }\n\n const widths = columnWidths(rows);\n\n // `widths` is built from these same columns, so every index resolves. `?? 0`\n // rather than an assertion: 0 is padEnd's no-op, so an unreadable width\n // produces an UNALIGNED table rather than a crash — this renders `warlock\n // routes`, and a table that throws tells the operator nothing about routes.\n const renderRow = (cells: string[]) =>\n cells\n .map((text, index) => text.padEnd(widths[index] ?? 0))\n .join(GAP)\n .trimEnd();\n\n const lines = [renderRow(COLUMNS.map((column) => column.header))];\n\n for (const row of rows) {\n lines.push(renderRow(COLUMNS.map((column) => cellText(row, column.key))));\n }\n\n lines.push(\"\");\n lines.push(routesSummary(rows));\n\n return lines;\n}\n\n/** Per-verb color for the METHOD column. Unknown verbs fall back to white. */\nconst METHOD_COLOR: Record<string, (input: string) => string> = {\n GET: colors.green,\n POST: colors.blue,\n PUT: colors.yellow,\n PATCH: colors.yellow,\n DELETE: colors.red,\n OPTIONS: colors.gray,\n HEAD: colors.gray,\n ALL: colors.magenta,\n};\n\n/**\n * Colorize the method label, then right-pad with plain spaces so column\n * alignment is computed from the visible width, not the ANSI-coded length.\n *\n * @param method - The uppercased HTTP verb\n * @param width - The METHOD column width\n * @returns The colored, padded cell\n */\nfunction colorizeMethodCell(method: string, width: number): string {\n const colorize = METHOD_COLOR[method] ?? colors.white;\n\n return colorize(method) + \" \".repeat(Math.max(0, width - method.length));\n}\n\n/**\n * Print the routes table to stdout with a bold header, verb-colored METHOD\n * column, and a dimmed summary. The empty case prints a single yellow notice\n * (a booted app with zero routes usually means a route module failed to load).\n *\n * Thin presentation wrapper over {@link formatRoutesTableLines} /\n * {@link routesSummary} — those stay the source of truth for layout.\n *\n * @param rows - The rows to print (already filtered/sorted by the caller)\n */\nexport function printRoutesTable(rows: RouteRow[]): void {\n if (rows.length === 0) {\n console.log(colors.yellow(\"No routes registered — did a route module fail to load?\"));\n return;\n }\n\n const widths = columnWidths(rows);\n\n const headerLine = COLUMNS.map((column, index) => column.header.padEnd(widths[index] ?? 0))\n .join(GAP)\n .trimEnd();\n\n console.log(colors.bold(headerLine));\n\n for (const row of rows) {\n const cells = COLUMNS.map((column, index) => {\n if (column.key === \"method\") {\n return colorizeMethodCell(row.method, widths[index] ?? 0);\n }\n\n return cellText(row, column.key).padEnd(widths[index] ?? 0);\n });\n\n console.log(cells.join(GAP).trimEnd());\n }\n\n console.log(\"\");\n console.log(colors.gray(routesSummary(rows)));\n}\n"],"mappings":";;;;;AAIA,MAAM,UAAU;CACd;EAAE,KAAK;EAAU,QAAQ;CAAS;CAClC;EAAE,KAAK;EAAQ,QAAQ;CAAO;CAC9B;EAAE,KAAK;EAAQ,QAAQ;CAAO;CAC9B;EAAE,KAAK;EAAU,QAAQ;CAAS;CAClC;EAAE,KAAK;EAAc,QAAQ;CAAK;CAClC;EAAE,KAAK;EAAU,QAAQ;CAAS;AACpC;;AAKA,MAAM,MAAM;;AAGZ,MAAM,aAAa;;;;;;;;;;;AAYnB,SAAS,SAAS,KAAe,KAAwB;CACvD,IAAI,QAAQ,cAAc,OAAO,OAAO,IAAI,UAAU;CAEtD,MAAM,QAAQ,IAAI;CAElB,OAAO,MAAM,SAAS,IAAI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,QAAQ,KAAK,QAAQ,UAAU,OAAO,OAAO,OAAO,OAAO,UAAU,CAAC,CAAC,CAAC,CACxF,KAAK,GAAG,CAAC,CACT,QAAQ;CAEX,QAAQ,IAAI,OAAO,KAAK,UAAU,CAAC;CAEnC,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,QAAQ,QAAQ,KAAK,QAAQ,UAAU;GAC3C,IAAI,OAAO,QAAQ,UACjB,OAAO,mBAAmB,IAAI,QAAQ,OAAO,UAAU,CAAC;GAG1D,OAAO,SAAS,KAAK,OAAO,GAAG,CAAC,CAAC,OAAO,OAAO,UAAU,CAAC;EAC5D,CAAC;EAED,QAAQ,IAAI,MAAM,KAAK,GAAG,CAAC,CAAC,QAAQ,CAAC;CACvC;CAEA,QAAQ,IAAI,EAAE;CACd,QAAQ,IAAI,OAAO,KAAK,cAAc,IAAI,CAAC,CAAC;AAC9C"}
|
|
@@ -92,6 +92,7 @@ function parseCliArgs(argv, schema = []) {
|
|
|
92
92
|
const startIndex = isFirstArgOption ? 2 : 3;
|
|
93
93
|
for (let i = startIndex; i < argv.length; i++) {
|
|
94
94
|
const arg = argv[i];
|
|
95
|
+
if (arg === void 0) continue;
|
|
95
96
|
if (arg.startsWith("--")) {
|
|
96
97
|
const withoutDashes = arg.slice(2);
|
|
97
98
|
const equalIndex = withoutDashes.indexOf("=");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-cli-args.mjs","names":[],"sources":["../../../../../../../core/src/cli/parse-cli-args.ts"],"sourcesContent":["import { toCamelCase } from \"@mongez/reinforcements\";\n\nexport type ParsedCliArgs = {\n name: string;\n args: string[];\n options: Record<string, string | boolean>;\n};\n\n/**\n * The slice of a declared command option this parser needs.\n *\n * `CLICommand.commandOptions` (`ResolvedCLICommandOption[]`) satisfies it, but\n * the parser stays independent of the command classes so it can be unit-tested\n * and reused with a hand-written schema.\n */\nexport type CliOptionSchema = {\n name?: string;\n alias?: string;\n type?: \"string\" | \"boolean\" | \"number\";\n};\n\n/**\n * Thrown when a declared boolean option is given a value that is neither\n * true-ish nor false-ish.\n *\n * We refuse to guess. Guessing is exactly what produced #21: `--rollback=false`\n * was kept as the truthy string `\"false\"` and dropped every table. An option\n * that gates a destructive action must fail loudly on input it cannot read.\n */\nexport class CliOptionValueError extends Error {\n public constructor(\n public readonly optionToken: string,\n public readonly value: string,\n ) {\n super(\n `Invalid value ${JSON.stringify(value)} for boolean option ${optionToken}. ` +\n `Expected one of: true, false, 1, 0, yes, no — or pass ${optionToken} on its own for true.`,\n );\n\n this.name = \"CliOptionValueError\";\n }\n}\n\nconst TRUE_VALUES = new Set([\"true\", \"1\", \"yes\"]);\nconst FALSE_VALUES = new Set([\"false\", \"0\", \"no\"]);\n\n/**\n * Collect the camelCased keys (names AND aliases) of every option the command\n * declared as `type: \"boolean\"`.\n *\n * Both sides are camelCased because declared names keep their raw kebab form\n * (`\"pending-only\"`) while the parser emits camelCase keys (`pendingOnly`).\n */\nfunction collectBooleanKeys(schema: CliOptionSchema[]): Set<string> {\n const keys = new Set<string>();\n\n for (const option of schema) {\n if (option.type !== \"boolean\") continue;\n\n if (option.name) {\n keys.add(toCamelCase(option.name));\n }\n\n if (option.alias) {\n keys.add(toCamelCase(option.alias));\n }\n }\n\n return keys;\n}\n\n/**\n * Turn the value written after `=` into a real boolean, or throw.\n */\nfunction toBoolean(optionToken: string, value: string): boolean {\n const normalized = value.toLowerCase();\n\n if (TRUE_VALUES.has(normalized)) return true;\n if (FALSE_VALUES.has(normalized)) return false;\n\n throw new CliOptionValueError(optionToken, value);\n}\n\n/**\n * Parse CLI arguments from process.argv\n *\n * Called with a `schema` (the resolved command's declared options), every\n * option declared `type: \"boolean\"` is resolved as a boolean:\n * `--flag` → true, `--flag=false|0|no` → false, `--flag=true|1|yes` → true,\n * and `--flag <token>` leaves `<token>` as a POSITIONAL instead of swallowing\n * it as the flag's value. Anything else throws {@link CliOptionValueError}.\n *\n * Called without a schema — which is how the command name is discovered,\n * before any command object exists — behaviour is unchanged: every value stays\n * a raw string and a bare `--flag` still consumes the following non-dash token.\n * Nothing is blanket-coerced here on purpose: `--name=false` on a string-typed\n * option must survive as the string `\"false\"`.\n *\n * Options the schema does not declare keep the schema-less behaviour.\n *\n * @example\n * parseCliArgs([\"node\", \"warlock\", \"migrate\", \"--rollback\", \"file.ts\"])\n * // Returns: { name: \"migrate\", args: [], options: { rollback: \"file.ts\" } }\n *\n * @example\n * // `rollback` declared as type: \"boolean\" — the file stays a positional\n * parseCliArgs([\"node\", \"warlock\", \"migrate\", \"--rollback\", \"file.ts\"], migrateOptions)\n * // Returns: { name: \"migrate\", args: [\"file.ts\"], options: { rollback: true } }\n *\n * @example\n * parseCliArgs([\"node\", \"warlock\", \"dev\", \"--port=3000\", \"--fresh\"])\n * // Returns: { name: \"dev\", args: [], options: { port: \"3000\", fresh: true } }\n */\nexport function parseCliArgs(argv: string[], schema: CliOptionSchema[] = []): ParsedCliArgs {\n // Command is at index 2 (after \"node\" and script path)\n // But if index 2 starts with \"-\", it's an option, not a command\n const potentialCommand = argv[2] || \"\";\n const isFirstArgOption = potentialCommand.startsWith(\"-\");\n const command = isFirstArgOption ? \"\" : potentialCommand;\n const args: string[] = [];\n const options: Record<string, string | boolean> = {};\n const booleanKeys = collectBooleanKeys(schema);\n\n // Parse arguments starting from index 3 (or 2 if first arg was an option)\n const startIndex = isFirstArgOption ? 2 : 3;\n for (let i = startIndex; i < argv.length; i++) {\n const arg = argv[i];\n\n if (arg.startsWith(\"--\")) {\n // Long option: --key or --key=value\n const withoutDashes = arg.slice(2);\n const equalIndex = withoutDashes.indexOf(\"=\");\n\n if (equalIndex !== -1) {\n // --key=value format\n const key = toCamelCase(withoutDashes.slice(0, equalIndex));\n const value = withoutDashes.slice(equalIndex + 1);\n options[key] = booleanKeys.has(key)\n ? toBoolean(`--${withoutDashes.slice(0, equalIndex)}`, value)\n : value;\n } else {\n // --key format (check if next arg is a value)\n const key = toCamelCase(withoutDashes);\n const nextArg = argv[i + 1];\n\n // A declared boolean NEVER consumes the next token: `--rollback\n // users.ts` means \"rollback, and here is a positional\", not \"rollback\n // the file users.ts\". Swallowing it silently discarded the operator's\n // only stated scope and rolled back everything.\n if (booleanKeys.has(key)) {\n options[key] = true;\n } else if (nextArg && !nextArg.startsWith(\"-\")) {\n // If next arg exists and doesn't start with -, treat it as value\n options[key] = nextArg;\n i++; // Skip next arg\n } else {\n options[key] = true;\n }\n }\n } else if (arg.startsWith(\"-\") && arg.length > 1) {\n // Short option: -f, -t=value, or -abc (multiple flags)\n const flags = arg.slice(1);\n const equalIndex = flags.indexOf(\"=\");\n\n if (equalIndex !== -1) {\n // -t=value format\n const rawKey = flags.slice(0, equalIndex);\n const key = toCamelCase(rawKey);\n const value = flags.slice(equalIndex + 1);\n options[key] = booleanKeys.has(key) ? toBoolean(`-${rawKey}`, value) : value;\n } else if (flags.length === 1) {\n // Single flag: -f\n const key = toCamelCase(flags);\n const nextArg = argv[i + 1];\n\n if (booleanKeys.has(key)) {\n options[key] = true;\n } else if (nextArg && !nextArg.startsWith(\"-\")) {\n options[key] = nextArg;\n i++; // Skip next arg\n } else {\n options[key] = true;\n }\n } else {\n // Multiple flags: -abc becomes { a: true, b: true, c: true }\n // A bundle carries no value and never consumes the next token, so a\n // declared boolean already resolves to `true` here.\n for (const flag of flags) {\n options[toCamelCase(flag)] = true;\n }\n }\n } else {\n // Positional argument\n args.push(arg);\n }\n }\n\n return { name: command, args, options };\n}\n"],"mappings":";;;;;;;;;;;AA6BA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,AAAO,YACL,AAAgB,aAChB,AAAgB,OAChB;EACA,MACE,iBAAiB,KAAK,UAAU,KAAK,EAAE,sBAAsB,YAAY,0DACd,YAAY,sBACzE;EANgB;EACA;EAOhB,KAAK,OAAO;CACd;AACF;AAEA,MAAM,cAAc,IAAI,IAAI;CAAC;CAAQ;CAAK;AAAK,CAAC;AAChD,MAAM,eAAe,IAAI,IAAI;CAAC;CAAS;CAAK;AAAI,C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,YAAY,aAAa;IACrC,MAAM,UAAU,KAAK,IAAI;IAMzB,IAAI,YAAY,IAAI,GAAG,GACrB,QAAQ,OAAO;SACV,IAAI,WAAW,CAAC,QAAQ,WAAW,GAAG,GAAG;KAE9C,QAAQ,OAAO;KACf;IACF,OACE,QAAQ,OAAO;GAEnB;EACF,OAAO,IAAI,IAAI,WAAW,GAAG,KAAK,IAAI,SAAS,GAAG;GAEhD,MAAM,QAAQ,IAAI,MAAM,CAAC;GACzB,MAAM,aAAa,MAAM,QAAQ,GAAG;GAEpC,IAAI,eAAe,IAAI;IAErB,MAAM,SAAS,MAAM,MAAM,GAAG,UAAU;IACxC,MAAM,MAAM,YAAY,MAAM;IAC9B,MAAM,QAAQ,MAAM,MAAM,aAAa,CAAC;IACxC,QAAQ,OAAO,YAAY,IAAI,GAAG,IAAI,UAAU,IAAI,UAAU,KAAK,IAAI;GACzE,OAAO,IAAI,MAAM,WAAW,GAAG;IAE7B,MAAM,MAAM,YAAY,KAAK;IAC7B,MAAM,UAAU,KAAK,IAAI;IAEzB,IAAI,YAAY,IAAI,GAAG,GACrB,QAAQ,OAAO;SACV,IAAI,WAAW,CAAC,QAAQ,WAAW,GAAG,GAAG;KAC9C,QAAQ,OAAO;KACf;IACF,OACE,QAAQ,OAAO;GAEnB,OAIE,KAAK,MAAM,QAAQ,OACjB,QAAQ,YAAY,IAAI,KAAK;EAGnC,OAEE,KAAK,KAAK,GAAG;CAEjB;CAEA,OAAO;EAAE,MAAM;EAAS;EAAM;CAAQ;AACxC"}
|
|
1
|
+
{"version":3,"file":"parse-cli-args.mjs","names":[],"sources":["../../../../../../../core/src/cli/parse-cli-args.ts"],"sourcesContent":["import { toCamelCase } from \"@mongez/reinforcements\";\n\nexport type ParsedCliArgs = {\n name: string;\n args: string[];\n options: Record<string, string | boolean>;\n};\n\n/**\n * The slice of a declared command option this parser needs.\n *\n * `CLICommand.commandOptions` (`ResolvedCLICommandOption[]`) satisfies it, but\n * the parser stays independent of the command classes so it can be unit-tested\n * and reused with a hand-written schema.\n */\nexport type CliOptionSchema = {\n name?: string;\n alias?: string;\n type?: \"string\" | \"boolean\" | \"number\";\n};\n\n/**\n * Thrown when a declared boolean option is given a value that is neither\n * true-ish nor false-ish.\n *\n * We refuse to guess. Guessing is exactly what produced #21: `--rollback=false`\n * was kept as the truthy string `\"false\"` and dropped every table. An option\n * that gates a destructive action must fail loudly on input it cannot read.\n */\nexport class CliOptionValueError extends Error {\n public constructor(\n public readonly optionToken: string,\n public readonly value: string,\n ) {\n super(\n `Invalid value ${JSON.stringify(value)} for boolean option ${optionToken}. ` +\n `Expected one of: true, false, 1, 0, yes, no — or pass ${optionToken} on its own for true.`,\n );\n\n this.name = \"CliOptionValueError\";\n }\n}\n\nconst TRUE_VALUES = new Set([\"true\", \"1\", \"yes\"]);\nconst FALSE_VALUES = new Set([\"false\", \"0\", \"no\"]);\n\n/**\n * Collect the camelCased keys (names AND aliases) of every option the command\n * declared as `type: \"boolean\"`.\n *\n * Both sides are camelCased because declared names keep their raw kebab form\n * (`\"pending-only\"`) while the parser emits camelCase keys (`pendingOnly`).\n */\nfunction collectBooleanKeys(schema: CliOptionSchema[]): Set<string> {\n const keys = new Set<string>();\n\n for (const option of schema) {\n if (option.type !== \"boolean\") continue;\n\n if (option.name) {\n keys.add(toCamelCase(option.name));\n }\n\n if (option.alias) {\n keys.add(toCamelCase(option.alias));\n }\n }\n\n return keys;\n}\n\n/**\n * Turn the value written after `=` into a real boolean, or throw.\n */\nfunction toBoolean(optionToken: string, value: string): boolean {\n const normalized = value.toLowerCase();\n\n if (TRUE_VALUES.has(normalized)) return true;\n if (FALSE_VALUES.has(normalized)) return false;\n\n throw new CliOptionValueError(optionToken, value);\n}\n\n/**\n * Parse CLI arguments from process.argv\n *\n * Called with a `schema` (the resolved command's declared options), every\n * option declared `type: \"boolean\"` is resolved as a boolean:\n * `--flag` → true, `--flag=false|0|no` → false, `--flag=true|1|yes` → true,\n * and `--flag <token>` leaves `<token>` as a POSITIONAL instead of swallowing\n * it as the flag's value. Anything else throws {@link CliOptionValueError}.\n *\n * Called without a schema — which is how the command name is discovered,\n * before any command object exists — behaviour is unchanged: every value stays\n * a raw string and a bare `--flag` still consumes the following non-dash token.\n * Nothing is blanket-coerced here on purpose: `--name=false` on a string-typed\n * option must survive as the string `\"false\"`.\n *\n * Options the schema does not declare keep the schema-less behaviour.\n *\n * @example\n * parseCliArgs([\"node\", \"warlock\", \"migrate\", \"--rollback\", \"file.ts\"])\n * // Returns: { name: \"migrate\", args: [], options: { rollback: \"file.ts\" } }\n *\n * @example\n * // `rollback` declared as type: \"boolean\" — the file stays a positional\n * parseCliArgs([\"node\", \"warlock\", \"migrate\", \"--rollback\", \"file.ts\"], migrateOptions)\n * // Returns: { name: \"migrate\", args: [\"file.ts\"], options: { rollback: true } }\n *\n * @example\n * parseCliArgs([\"node\", \"warlock\", \"dev\", \"--port=3000\", \"--fresh\"])\n * // Returns: { name: \"dev\", args: [], options: { port: \"3000\", fresh: true } }\n */\nexport function parseCliArgs(argv: string[], schema: CliOptionSchema[] = []): ParsedCliArgs {\n // Command is at index 2 (after \"node\" and script path)\n // But if index 2 starts with \"-\", it's an option, not a command\n const potentialCommand = argv[2] || \"\";\n const isFirstArgOption = potentialCommand.startsWith(\"-\");\n const command = isFirstArgOption ? \"\" : potentialCommand;\n const args: string[] = [];\n const options: Record<string, string | boolean> = {};\n const booleanKeys = collectBooleanKeys(schema);\n\n // Parse arguments starting from index 3 (or 2 if first arg was an option)\n const startIndex = isFirstArgOption ? 2 : 3;\n for (let i = startIndex; i < argv.length; i++) {\n const arg = argv[i];\n\n // `i < argv.length` bounds this, but the compiler does not narrow an index\n // read from a loop condition. Skipping rather than coercing: this file\n // already refuses to guess about an operator's input (see\n // `CliOptionValueError` above), and an `?? \"\"` here would silently push an\n // empty POSITIONAL onto `args` — which for a command that takes a file or\n // a table name is a scope the operator never typed.\n if (arg === undefined) continue;\n\n if (arg.startsWith(\"--\")) {\n // Long option: --key or --key=value\n const withoutDashes = arg.slice(2);\n const equalIndex = withoutDashes.indexOf(\"=\");\n\n if (equalIndex !== -1) {\n // --key=value format\n const key = toCamelCase(withoutDashes.slice(0, equalIndex));\n const value = withoutDashes.slice(equalIndex + 1);\n options[key] = booleanKeys.has(key)\n ? toBoolean(`--${withoutDashes.slice(0, equalIndex)}`, value)\n : value;\n } else {\n // --key format (check if next arg is a value)\n const key = toCamelCase(withoutDashes);\n const nextArg = argv[i + 1];\n\n // A declared boolean NEVER consumes the next token: `--rollback\n // users.ts` means \"rollback, and here is a positional\", not \"rollback\n // the file users.ts\". Swallowing it silently discarded the operator's\n // only stated scope and rolled back everything.\n if (booleanKeys.has(key)) {\n options[key] = true;\n } else if (nextArg && !nextArg.startsWith(\"-\")) {\n // If next arg exists and doesn't start with -, treat it as value\n options[key] = nextArg;\n i++; // Skip next arg\n } else {\n options[key] = true;\n }\n }\n } else if (arg.startsWith(\"-\") && arg.length > 1) {\n // Short option: -f, -t=value, or -abc (multiple flags)\n const flags = arg.slice(1);\n const equalIndex = flags.indexOf(\"=\");\n\n if (equalIndex !== -1) {\n // -t=value format\n const rawKey = flags.slice(0, equalIndex);\n const key = toCamelCase(rawKey);\n const value = flags.slice(equalIndex + 1);\n options[key] = booleanKeys.has(key) ? toBoolean(`-${rawKey}`, value) : value;\n } else if (flags.length === 1) {\n // Single flag: -f\n const key = toCamelCase(flags);\n const nextArg = argv[i + 1];\n\n if (booleanKeys.has(key)) {\n options[key] = true;\n } else if (nextArg && !nextArg.startsWith(\"-\")) {\n options[key] = nextArg;\n i++; // Skip next arg\n } else {\n options[key] = true;\n }\n } else {\n // Multiple flags: -abc becomes { a: true, b: true, c: true }\n // A bundle carries no value and never consumes the next token, so a\n // declared boolean already resolves to `true` here.\n for (const flag of flags) {\n options[toCamelCase(flag)] = true;\n }\n }\n } else {\n // Positional argument\n args.push(arg);\n }\n }\n\n return { name: command, args, options };\n}\n"],"mappings":";;;;;;;;;;;AA6BA,IAAa,sBAAb,cAAy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AAS;EAAM;CAAQ;AACxC"}
|
|
@@ -17,11 +17,20 @@ function levenshteinDistance(str1, str2) {
|
|
|
17
17
|
const len1 = s1.length;
|
|
18
18
|
const len2 = s2.length;
|
|
19
19
|
const matrix = Array.from({ length: len1 + 1 }, (_, i) => Array.from({ length: len2 + 1 }, (_, j) => i === 0 ? j : j === 0 ? i : 0));
|
|
20
|
-
for (let i = 1; i <= len1; i++)
|
|
21
|
-
const
|
|
22
|
-
|
|
20
|
+
for (let i = 1; i <= len1; i++) {
|
|
21
|
+
const previousRow = matrix[i - 1];
|
|
22
|
+
const currentRow = matrix[i];
|
|
23
|
+
if (previousRow === void 0 || currentRow === void 0) continue;
|
|
24
|
+
for (let j = 1; j <= len2; j++) {
|
|
25
|
+
const deletion = previousRow[j];
|
|
26
|
+
const insertion = currentRow[j - 1];
|
|
27
|
+
const substitution = previousRow[j - 1];
|
|
28
|
+
if (deletion === void 0 || insertion === void 0 || substitution === void 0) continue;
|
|
29
|
+
const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
|
|
30
|
+
currentRow[j] = Math.min(deletion + 1, insertion + 1, substitution + cost);
|
|
31
|
+
}
|
|
23
32
|
}
|
|
24
|
-
return matrix[len1][len2];
|
|
33
|
+
return matrix[len1]?.[len2] ?? Math.max(len1, len2);
|
|
25
34
|
}
|
|
26
35
|
/**
|
|
27
36
|
* Find similar strings from a list
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string-similarity.mjs","names":[],"sources":["../../../../../../../core/src/cli/string-similarity.ts"],"sourcesContent":["/**\n * String similarity utilities for CLI command suggestions\n * Uses Levenshtein distance algorithm for fuzzy matching\n */\n\n/**\n * Calculate the Levenshtein distance between two strings\n * Lower distance = more similar\n *\n * @param str1 - First string\n * @param str2 - Second string\n * @returns Distance (number of edits required to transform str1 to str2)\n */\nexport function levenshteinDistance(str1: string, str2: string): number {\n const s1 = str1.toLowerCase();\n const s2 = str2.toLowerCase();\n\n const len1 = s1.length;\n const len2 = s2.length;\n\n // Create matrix\n const matrix: number[][] = Array.from({ length: len1 + 1 }, (_, i) =>\n Array.from({ length: len2 + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),\n );\n\n // Fill matrix\n for (let i = 1; i <= len1; i++) {\n for (let j = 1; j <= len2; j++) {\n const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;\n
|
|
1
|
+
{"version":3,"file":"string-similarity.mjs","names":[],"sources":["../../../../../../../core/src/cli/string-similarity.ts"],"sourcesContent":["/**\n * String similarity utilities for CLI command suggestions\n * Uses Levenshtein distance algorithm for fuzzy matching\n */\n\n/**\n * Calculate the Levenshtein distance between two strings\n * Lower distance = more similar\n *\n * @param str1 - First string\n * @param str2 - Second string\n * @returns Distance (number of edits required to transform str1 to str2)\n */\nexport function levenshteinDistance(str1: string, str2: string): number {\n const s1 = str1.toLowerCase();\n const s2 = str2.toLowerCase();\n\n const len1 = s1.length;\n const len2 = s2.length;\n\n // Create matrix\n const matrix: number[][] = Array.from({ length: len1 + 1 }, (_, i) =>\n Array.from({ length: len2 + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),\n );\n\n // Fill matrix\n //\n // Every index below is in bounds by construction — the matrix is built\n // `len1 + 1` by `len2 + 1` immediately above. Under\n // `noUncheckedIndexedAccess` the compiler still types each read as possibly\n // undefined, and the rows are hoisted rather than defaulted: a `?? 0` in the\n // middle of a distance calculation would not fail, it would quietly return a\n // SHORTER distance and change which command the CLI suggests.\n for (let i = 1; i <= len1; i++) {\n const previousRow = matrix[i - 1];\n const currentRow = matrix[i];\n\n if (previousRow === undefined || currentRow === undefined) continue;\n\n for (let j = 1; j <= len2; j++) {\n const deletion = previousRow[j];\n const insertion = currentRow[j - 1];\n const substitution = previousRow[j - 1];\n\n if (deletion === undefined || insertion === undefined || substitution === undefined) {\n continue;\n }\n\n const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;\n\n currentRow[j] = Math.min(deletion + 1, insertion + 1, substitution + cost);\n }\n }\n\n // `len1`/`len2` index the last row and column, both allocated above. Falling\n // back to the worst-case distance (the longer string's length) rather than 0\n // keeps an unreadable result looking MAXIMALLY dissimilar — a 0 would make\n // it look like a perfect match and promote it to the top suggestion.\n return matrix[len1]?.[len2] ?? Math.max(len1, len2);\n}\n\n/**\n * Suggestion result with similarity score\n */\nexport type Suggestion = {\n /** The suggested value */\n value: string;\n /** Distance score (lower = more similar) */\n distance: number;\n};\n\n/**\n * Find similar strings from a list\n *\n * @param input - The input string to find matches for\n * @param candidates - List of candidate strings\n * @param maxDistance - Maximum distance to consider (default: 3)\n * @param maxResults - Maximum number of results to return (default: 3)\n * @returns Array of suggestions sorted by similarity\n *\n * @example\n * ```typescript\n * findSimilar(\"biuld\", [\"build\", \"dev\", \"start\", \"test\"])\n * // Returns: [{ value: \"build\", distance: 1 }]\n * ```\n */\nexport function findSimilar(\n input: string,\n candidates: string[],\n maxDistance: number = 3,\n maxResults: number = 3,\n): Suggestion[] {\n const results: Suggestion[] = [];\n\n for (const candidate of candidates) {\n const distance = levenshteinDistance(input, candidate);\n\n if (distance <= maxDistance && distance > 0) {\n results.push({ value: candidate, distance });\n }\n }\n\n // Sort by distance (most similar first)\n results.sort((a, b) => a.distance - b.distance);\n\n return results.slice(0, maxResults);\n}\n\n/**\n * Check if a string starts with any of the given prefixes\n * Useful for command name matching\n */\nexport function startsWithAny(str: string, prefixes: string[]): boolean {\n return prefixes.some((prefix) => str.toLowerCase().startsWith(prefix.toLowerCase()));\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,oBAAoB,MAAc,MAAsB;CACtE,MAAM,KAAK,KAAK,YAAY;CAC5B,MAAM,KAAK,KAAK,YAAY;CAE5B,MAAM,OAAO,GAAG;CAChB,MAAM,OAAO,GAAG;CAGhB,MAAM,SAAqB,MAAM,KAAK,EAAE,QAAQ,OAAO,EAAE,IAAI,GAAG,MAC9D,MAAM,KAAK,EAAE,QAAQ,OAAO,EAAE,IAAI,GAAG,MAAO,MAAM,I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3,"file":"cli-command.d.mts","names":[],"sources":["../../../../../../../core/src/commands/cli-command.ts"],"mappings":";;;cAUa,UAAA;EAqDF,IAAA;EArDE;;;EAIJ,aAAA,GAAgB,gBAAA;EAKA;;;EAAhB,aAAA,GAAgB,gBAAA;EAyDD;;;;EAnDf,gBAAA,GAAmB,gBAAA;EA0HT;;;EArHV,cAAA,GAAiB,iBAAA;EAmOA;;;EA9NjB,kBAAA;EAsOqC;;;EAjOrC,cAAA,EAAgB,wBAAA;EArBhB;;;;;EA4BA,mBAAA;EAZA;;;EAiBA,YAAA;EAAA;;;EAKA,YAAA;EAOL;;;cADO,IAAA,UACP,WAAA;EAoBK;;;EARA,MAAA,CAAO,MAAA,EAAQ,gBAAA;EAyBf;;;EAjBA,WAAA,CAAY,WAAA;EAyBL;;;EAjBP,UAAA,CAAW,YAAA;EAkCX;;;;EAzBA,KAAA,CAAM,KAAA;EA0CN;;;EAlCA,MAAA,CAAO,MAAA,EAAQ,gBAAA;EAoCpB;;;;EA3BK,SAAA,CAAU,MAAA,EAAQ,gBAAA;EA8Df;;;EAtDH,OAAA,CAAQ,OAAA,EAAS,gBAAA;EA6GhB;;;EApGD,aAAA,CAAc,YAAA;EAkIR;;;EA1HN,MAAA,CAAO,MAAA,EAAQ,gBAAA;EACf,MAAA,CACL,IAAA,UACA,WAAA,WACA,OAAA,GAAU,IAAA,CAAK,gBAAA;EAsH2B;AAS9C;;;;;;;;EAT8C,UArFlC,WAAA,CAAY,MAAA,EAAQ,gBAAA,GAAmB,wBAAA;;;;;;;;;UAuDzC,iBAAA;;;;EAsBD,OAAA,CAAQ,OAAA,EAAS,iBAAA;;;;EAQX,OAAA,CAAQ,IAAA,EAAM,iBAAA,GAAiB,OAAA;AAAA;AAAA,iBAS9B,OAAA,CAAQ,OAAA,EAAS,iBAAA,GAAiB,UAAA"}
|
|
@@ -93,10 +93,13 @@ var CLICommand = class {
|
|
|
93
93
|
const parts = option.text.trim().split(",").map((part) => part.trim());
|
|
94
94
|
let name = "";
|
|
95
95
|
let alias = "";
|
|
96
|
-
|
|
96
|
+
const firstPart = parts[0];
|
|
97
|
+
if (!firstPart) throw new Error("Command option text cannot be empty");
|
|
98
|
+
if (parts.length === 1) name = this.extractOptionName(firstPart);
|
|
97
99
|
else if (parts.length === 2) {
|
|
98
|
-
const first =
|
|
100
|
+
const first = firstPart;
|
|
99
101
|
const second = parts[1];
|
|
102
|
+
if (!second) throw new Error("Command option alias cannot be empty");
|
|
100
103
|
if (first.startsWith("--")) {
|
|
101
104
|
name = this.extractOptionName(first);
|
|
102
105
|
alias = this.extractOptionName(second);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-command.mjs","names":[],"sources":["../../../../../../../core/src/commands/cli-command.ts"],"sourcesContent":["import type {\n CLICommandAction,\n CLICommandOption,\n CLICommandOptions,\n CLICommandPreload,\n CLICommandSource,\n CommandActionData,\n ResolvedCLICommandOption,\n} from \"./types\";\n\nexport class CLICommand {\n /**\n * Command source\n */\n public commandSource?: CLICommandSource;\n\n /**\n * Command action\n */\n public commandAction?: CLICommandAction;\n\n /**\n * Command pre action\n * This will be executed before loading preloaders\n */\n public commandPreAction?: CLICommandAction;\n\n /**\n * Command preload\n */\n public commandPreload?: CLICommandPreload;\n\n /**\n * Command description\n */\n public commandDescription?: string;\n\n /**\n * Command options\n */\n public commandOptions: ResolvedCLICommandOption[] = [];\n\n /**\n * Command relative path\n * Available only for project commands\n * Auto injected by the framework itself\n */\n public commandRelativePath?: string;\n\n /**\n * Determine if the command is persistent\n */\n public isPersistent: boolean = false;\n\n /**\n * Command alias (short name)\n */\n public commandAlias?: string;\n\n /**\n * Constructor\n */\n public constructor(\n public name: string,\n description?: string,\n ) {\n if (description) {\n this.commandDescription = description;\n }\n\n return this;\n }\n\n /**\n * Add command source\n */\n public source(source: CLICommandSource): this {\n this.commandSource = source;\n return this;\n }\n\n /**\n * Set command description\n */\n public description(description: string): this {\n this.commandDescription = description;\n return this;\n }\n\n /**\n * Determine if the command is persistent\n */\n public persistent(isPersistent = true): this {\n this.isPersistent = isPersistent;\n return this;\n }\n\n /**\n * Set command alias (short name)\n * @example .alias(\"m\") for \"migrate\"\n */\n public alias(alias: string): this {\n this.commandAlias = alias;\n return this;\n }\n\n /**\n * Command action\n */\n public action(action: CLICommandAction): this {\n this.commandAction = action;\n return this;\n }\n\n /**\n * Command pre action\n * This will be executed before loading preloaders\n */\n public preAction(action: CLICommandAction): this {\n this.commandPreAction = action;\n return this;\n }\n\n /**\n * Add command options\n */\n public options(options: CLICommandOption[]): this {\n options.map((option) => this.option(option));\n\n return this;\n }\n\n /**\n * Add command relative path\n */\n public $relativePath(relativePath: string) {\n this.commandRelativePath = relativePath;\n return this;\n }\n\n /**\n * Add command option\n */\n public option(option: CLICommandOption): this;\n public option(\n name: string,\n description?: string,\n options?: Omit<CLICommandOption, \"name\" | \"text\" | \"description\">,\n ): this;\n public option(\n ...args:\n | [CLICommandOption]\n | [string, string?, Omit<CLICommandOption, \"name\" | \"text\" | \"description\">?]\n ): this {\n let option: CLICommandOption;\n if (args.length === 1) {\n option = args[0] as CLICommandOption;\n } else {\n option = {\n text: args[0],\n description: args[1],\n ...args[2],\n name: \"\",\n };\n }\n\n this.commandOptions.push(this.parseOption(option));\n\n return this;\n }\n\n /**\n * Parse option name and alias if exists\n *\n * Supports formats:\n * - \"--port, -p\" → name: \"port\", alias: \"p\"\n * - \"-p, --port\" → name: \"port\", alias: \"p\"\n * - \"--port\" → name: \"port\", alias: undefined\n * - \"-p\" → name: \"p\", alias: undefined\n */\n protected parseOption(option: CLICommandOption): ResolvedCLICommandOption {\n const text = option.text.trim();\n\n // Split by comma to check for alias\n const parts = text.split(\",\").map((part) => part.trim());\n\n let name = \"\";\n let alias = \"\";\n\n if (parts.length === 1) {\n // Single option: \"--port\" or \"-p\"\n name = this.extractOptionName(
|
|
1
|
+
{"version":3,"file":"cli-command.mjs","names":[],"sources":["../../../../../../../core/src/commands/cli-command.ts"],"sourcesContent":["import type {\n CLICommandAction,\n CLICommandOption,\n CLICommandOptions,\n CLICommandPreload,\n CLICommandSource,\n CommandActionData,\n ResolvedCLICommandOption,\n} from \"./types\";\n\nexport class CLICommand {\n /**\n * Command source\n */\n public commandSource?: CLICommandSource;\n\n /**\n * Command action\n */\n public commandAction?: CLICommandAction;\n\n /**\n * Command pre action\n * This will be executed before loading preloaders\n */\n public commandPreAction?: CLICommandAction;\n\n /**\n * Command preload\n */\n public commandPreload?: CLICommandPreload;\n\n /**\n * Command description\n */\n public commandDescription?: string;\n\n /**\n * Command options\n */\n public commandOptions: ResolvedCLICommandOption[] = [];\n\n /**\n * Command relative path\n * Available only for project commands\n * Auto injected by the framework itself\n */\n public commandRelativePath?: string;\n\n /**\n * Determine if the command is persistent\n */\n public isPersistent: boolean = false;\n\n /**\n * Command alias (short name)\n */\n public commandAlias?: string;\n\n /**\n * Constructor\n */\n public constructor(\n public name: string,\n description?: string,\n ) {\n if (description) {\n this.commandDescription = description;\n }\n\n return this;\n }\n\n /**\n * Add command source\n */\n public source(source: CLICommandSource): this {\n this.commandSource = source;\n return this;\n }\n\n /**\n * Set command description\n */\n public description(description: string): this {\n this.commandDescription = description;\n return this;\n }\n\n /**\n * Determine if the command is persistent\n */\n public persistent(isPersistent = true): this {\n this.isPersistent = isPersistent;\n return this;\n }\n\n /**\n * Set command alias (short name)\n * @example .alias(\"m\") for \"migrate\"\n */\n public alias(alias: string): this {\n this.commandAlias = alias;\n return this;\n }\n\n /**\n * Command action\n */\n public action(action: CLICommandAction): this {\n this.commandAction = action;\n return this;\n }\n\n /**\n * Command pre action\n * This will be executed before loading preloaders\n */\n public preAction(action: CLICommandAction): this {\n this.commandPreAction = action;\n return this;\n }\n\n /**\n * Add command options\n */\n public options(options: CLICommandOption[]): this {\n options.map((option) => this.option(option));\n\n return this;\n }\n\n /**\n * Add command relative path\n */\n public $relativePath(relativePath: string) {\n this.commandRelativePath = relativePath;\n return this;\n }\n\n /**\n * Add command option\n */\n public option(option: CLICommandOption): this;\n public option(\n name: string,\n description?: string,\n options?: Omit<CLICommandOption, \"name\" | \"text\" | \"description\">,\n ): this;\n public option(\n ...args:\n | [CLICommandOption]\n | [string, string?, Omit<CLICommandOption, \"name\" | \"text\" | \"description\">?]\n ): this {\n let option: CLICommandOption;\n if (args.length === 1) {\n option = args[0] as CLICommandOption;\n } else {\n option = {\n text: args[0],\n description: args[1],\n ...args[2],\n name: \"\",\n };\n }\n\n this.commandOptions.push(this.parseOption(option));\n\n return this;\n }\n\n /**\n * Parse option name and alias if exists\n *\n * Supports formats:\n * - \"--port, -p\" → name: \"port\", alias: \"p\"\n * - \"-p, --port\" → name: \"port\", alias: \"p\"\n * - \"--port\" → name: \"port\", alias: undefined\n * - \"-p\" → name: \"p\", alias: undefined\n */\n protected parseOption(option: CLICommandOption): ResolvedCLICommandOption {\n const text = option.text.trim();\n\n // Split by comma to check for alias\n const parts = text.split(\",\").map((part) => part.trim());\n\n let name = \"\";\n let alias = \"\";\n const firstPart = parts[0];\n\n if (!firstPart) {\n throw new Error(\"Command option text cannot be empty\");\n }\n\n if (parts.length === 1) {\n // Single option: \"--port\" or \"-p\"\n name = this.extractOptionName(firstPart);\n } else if (parts.length === 2) {\n // Two options: \"--port, -p\" or \"-p, --port\"\n const first = firstPart;\n const second = parts[1];\n\n if (!second) {\n throw new Error(\"Command option alias cannot be empty\");\n }\n\n // Determine which is the long form (name) and which is short (alias)\n if (first.startsWith(\"--\")) {\n name = this.extractOptionName(first);\n alias = this.extractOptionName(second);\n } else {\n name = this.extractOptionName(second);\n alias = this.extractOptionName(first);\n }\n }\n\n if (alias === \"h\" || name === \"help\") {\n throw new Error(\"Help option is not allowed, it's reserved for displaying command help\");\n }\n\n return {\n ...option,\n name,\n alias,\n };\n }\n\n /**\n * Extract option name from text (removes -- or -)\n *\n * @example\n * extractOptionName(\"--port\") → \"port\"\n * extractOptionName(\"-p\") → \"p\"\n * extractOptionName(\"--port=3000\") → \"port\"\n */\n private extractOptionName(text: string): string {\n // Remove leading dashes\n let name = text.replace(/^-+/, \"\");\n\n // Remove value assignment if exists (e.g., \"--port=3000\" → \"port\")\n const equalIndex = name.indexOf(\"=\");\n if (equalIndex !== -1) {\n name = name.slice(0, equalIndex);\n }\n\n // Remove angle brackets if exists (e.g., \"--port <number>\" → \"port\")\n const spaceIndex = name.indexOf(\" \");\n if (spaceIndex !== -1) {\n name = name.slice(0, spaceIndex);\n }\n\n return name.trim();\n }\n\n /**\n * Command preload\n */\n public preload(options: CLICommandPreload) {\n this.commandPreload = options;\n return this;\n }\n\n /**\n * Execute the command\n */\n public async execute(data: CommandActionData) {\n if (!this.commandAction) {\n throw new Error(`Command \"${this.name}\" has no action defined`);\n }\n\n await this.commandAction(data);\n }\n}\n\nexport function command(options: CLICommandOptions) {\n const commandInstnace = new CLICommand(options.name, options.description);\n\n if (options.preload) {\n commandInstnace.preload(options.preload);\n }\n\n if (options.persistent) {\n commandInstnace.persistent(options.persistent);\n }\n\n if (options.alias) {\n commandInstnace.alias(options.alias);\n }\n\n commandInstnace.action(options.action);\n\n if (options.options) {\n commandInstnace.options(options.options);\n }\n\n if (options.preAction) {\n commandInstnace.preAction(options.preAction);\n }\n\n return commandInstnace;\n}\n"],"mappings":";AAUA,IAAa,aAAb,MAAwB;;;;CAoDtB,AAAO,YACL,AAAO,MACP,aACA;EAFO;wBAvB2C,CAAC;sBAYtB;EAc7B,IAAI,aACF,KAAK,qBAAqB;EAG5B,OAAO;CACT;;;;CAKA,AAAO,OAAO,QAAgC;EAC5C,KAAK,gBAAgB;EACrB,OAAO;CACT;;;;CAKA,AAAO,YAAY,aAA2B;EAC5C,KAAK,qBAAqB;EAC1B,OAAO;CACT;;;;CAKA,AAAO,WAAW,eAAe,MAAY;EAC3C,KAAK,eAAe;EACpB,OAAO;CACT;;;;;CAMA,AAAO,MAAM,OAAqB;EAChC,KAAK,eAAe;EACpB,OAAO;CACT;;;;CAKA,AAAO,OAAO,QAAgC;EAC5C,KAAK,gBAAgB;EACrB,OAAO;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sB;EAE9C,IAAI,OAAO,KAAK,QAAQ,OAAO,EAAE;EAGjC,MAAM,aAAa,KAAK,QAAQ,GAAG;EACnC,IAAI,eAAe,IACjB,OAAO,KAAK,MAAM,GAAG,UAAU;EAIjC,MAAM,aAAa,KAAK,QAAQ,GAAG;EACnC,IAAI,eAAe,IACjB,OAAO,KAAK,MAAM,GAAG,UAAU;EAGjC,OAAO,KAAK,KAAK;CACnB;;;;CAKA,AAAO,QAAQ,SAA4B;EACzC,KAAK,iBAAiB;EACtB,OAAO;CACT;;;;CAKA,MAAa,QAAQ,MAAyB;EAC5C,IAAI,CAAC,KAAK,eACR,MAAM,IAAI,MAAM,YAAY,KAAK,KAAK,wBAAwB;EAGhE,MAAM,KAAK,cAAc,IAAI;CAC/B;AACF;AAEA,SAAgB,QAAQ,SAA4B;CAClD,MAAM,kBAAkB,IAAI,WAAW,QAAQ,MAAM,QAAQ,WAAW;CAExE,IAAI,QAAQ,SACV,gBAAgB,QAAQ,QAAQ,OAAO;CAGzC,IAAI,QAAQ,YACV,gBAAgB,WAAW,QAAQ,UAAU;CAG/C,IAAI,QAAQ,OACV,gBAAgB,MAAM,QAAQ,KAAK;CAGrC,gBAAgB,OAAO,QAAQ,MAAM;CAErC,IAAI,QAAQ,SACV,gBAAgB,QAAQ,QAAQ,OAAO;CAGzC,IAAI,QAAQ,WACV,gBAAgB,UAAU,QAAQ,SAAS;CAG7C,OAAO;AACT"}
|
|
@@ -39,7 +39,9 @@ var ConfigLoader = class {
|
|
|
39
39
|
getConfigName(relativePath) {
|
|
40
40
|
const match = relativePath.match(/^src\/config\/(.+)\.(ts|tsx)$/);
|
|
41
41
|
if (!match) throw new Error(`Invalid config file path: ${relativePath}`);
|
|
42
|
-
|
|
42
|
+
const configName = match[1];
|
|
43
|
+
if (!configName) throw new Error(`Invalid config file path: ${relativePath}`);
|
|
44
|
+
return configName;
|
|
43
45
|
}
|
|
44
46
|
};
|
|
45
47
|
|