@warlock.js/core 5.0.2 → 5.1.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 +47 -0
- package/esm/cli/cli-commands.manager.mjs +36 -1
- package/esm/cli/cli-commands.manager.mjs.map +1 -1
- package/esm/cli/commands/dev-server.command.mjs +1 -1
- package/esm/cli/commands/doctor/boot-for-diagnostics.mjs +207 -0
- package/esm/cli/commands/doctor/boot-for-diagnostics.mjs.map +1 -0
- package/esm/cli/commands/doctor/checks/config.check.mjs +5 -2
- package/esm/cli/commands/doctor/checks/config.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/connectors.check.mjs +38 -12
- package/esm/cli/commands/doctor/checks/connectors.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/handler-signature.check.mjs +8 -4
- package/esm/cli/commands/doctor/checks/handler-signature.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/health.check.mjs +77 -11
- package/esm/cli/commands/doctor/checks/health.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/index.mjs +5 -0
- package/esm/cli/commands/doctor/checks/index.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/optional-peers.check.mjs +116 -53
- package/esm/cli/commands/doctor/checks/optional-peers.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/release-hygiene.check.mjs +27 -9
- package/esm/cli/commands/doctor/checks/release-hygiene.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/routes.check.mjs +51 -12
- package/esm/cli/commands/doctor/checks/routes.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/doctor-command.action.mjs +16 -6
- package/esm/cli/commands/doctor/doctor-command.action.mjs.map +1 -1
- package/esm/cli/commands/doctor/run-checks.mjs +15 -6
- package/esm/cli/commands/doctor/run-checks.mjs.map +1 -1
- package/esm/cli/commands/doctor.command.mjs +17 -9
- package/esm/cli/commands/doctor.command.mjs.map +1 -1
- package/esm/connectors/describe-server-address.mjs +89 -6
- package/esm/connectors/describe-server-address.mjs.map +1 -1
- package/esm/connectors/http-connector.d.mts +18 -0
- package/esm/connectors/http-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.mjs +36 -3
- package/esm/connectors/http-connector.mjs.map +1 -1
- package/esm/dev-server/dev-logger.mjs +1 -4
- package/esm/dev-server/dev-logger.mjs.map +1 -1
- package/esm/dev-server/development-server.mjs +3 -7
- package/esm/dev-server/development-server.mjs.map +1 -1
- package/esm/dev-server/module-loader.mjs +1 -1
- package/esm/dev-server/ready-block.mjs +62 -0
- package/esm/dev-server/ready-block.mjs.map +1 -0
- package/esm/generations/add-command.action.mjs +2 -575
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/generations/features/access.feature.mjs +76 -0
- package/esm/generations/features/access.feature.mjs.map +1 -0
- package/esm/generations/features/ai-anthropic.feature.mjs +10 -0
- package/esm/generations/features/ai-anthropic.feature.mjs.map +1 -0
- package/esm/generations/features/ai-bedrock.feature.mjs +10 -0
- package/esm/generations/features/ai-bedrock.feature.mjs.map +1 -0
- package/esm/generations/features/ai-google.feature.mjs +10 -0
- package/esm/generations/features/ai-google.feature.mjs.map +1 -0
- package/esm/generations/features/ai-ollama.feature.mjs +10 -0
- package/esm/generations/features/ai-ollama.feature.mjs.map +1 -0
- package/esm/generations/features/ai-openai.feature.mjs +10 -0
- package/esm/generations/features/ai-openai.feature.mjs.map +1 -0
- package/esm/generations/features/ai-panoptic.feature.mjs +13 -0
- package/esm/generations/features/ai-panoptic.feature.mjs.map +1 -0
- package/esm/generations/features/ai-tools.feature.mjs +13 -0
- package/esm/generations/features/ai-tools.feature.mjs.map +1 -0
- package/esm/generations/features/ai-workspace.feature.mjs +13 -0
- package/esm/generations/features/ai-workspace.feature.mjs.map +1 -0
- package/esm/generations/features/ai.feature.mjs +15 -0
- package/esm/generations/features/ai.feature.mjs.map +1 -0
- package/esm/generations/features/herald.feature.mjs +19 -0
- package/esm/generations/features/herald.feature.mjs.map +1 -0
- package/esm/generations/features/image.feature.mjs +9 -0
- package/esm/generations/features/image.feature.mjs.map +1 -0
- package/esm/generations/features/index.mjs +72 -0
- package/esm/generations/features/index.mjs.map +1 -0
- package/esm/generations/features/mail.feature.mjs +10 -0
- package/esm/generations/features/mail.feature.mjs.map +1 -0
- package/esm/generations/features/mongodb.feature.mjs +9 -0
- package/esm/generations/features/mongodb.feature.mjs.map +1 -0
- package/esm/generations/features/mysql.feature.mjs +9 -0
- package/esm/generations/features/mysql.feature.mjs.map +1 -0
- package/esm/generations/features/notifications.feature.mjs +43 -0
- package/esm/generations/features/notifications.feature.mjs.map +1 -0
- package/esm/generations/features/postgres.feature.mjs +9 -0
- package/esm/generations/features/postgres.feature.mjs.map +1 -0
- package/esm/generations/features/react-email.feature.mjs +70 -0
- package/esm/generations/features/react-email.feature.mjs.map +1 -0
- package/esm/generations/features/react.feature.mjs +16 -0
- package/esm/generations/features/react.feature.mjs.map +1 -0
- package/esm/generations/features/redis.feature.mjs +9 -0
- package/esm/generations/features/redis.feature.mjs.map +1 -0
- package/esm/generations/features/s3.feature.mjs +13 -0
- package/esm/generations/features/s3.feature.mjs.map +1 -0
- package/esm/generations/features/scheduler.feature.mjs +9 -0
- package/esm/generations/features/scheduler.feature.mjs.map +1 -0
- package/esm/generations/features/ses.feature.mjs +9 -0
- package/esm/generations/features/ses.feature.mjs.map +1 -0
- package/esm/generations/features/shadcn.feature.mjs +397 -0
- package/esm/generations/features/shadcn.feature.mjs.map +1 -0
- package/esm/generations/features/shared/link-ai-package-import.mjs +37 -0
- package/esm/generations/features/shared/link-ai-package-import.mjs.map +1 -0
- package/esm/generations/features/shared/migration-timestamp.mjs +17 -0
- package/esm/generations/features/shared/migration-timestamp.mjs.map +1 -0
- package/esm/generations/features/socket.feature.mjs +15 -0
- package/esm/generations/features/socket.feature.mjs.map +1 -0
- package/esm/generations/features/tailwind.feature.mjs +174 -0
- package/esm/generations/features/tailwind.feature.mjs.map +1 -0
- package/esm/generations/features/test.feature.mjs +96 -0
- package/esm/generations/features/test.feature.mjs.map +1 -0
- package/esm/generations/features/web.feature.mjs +179 -0
- package/esm/generations/features/web.feature.mjs.map +1 -0
- package/esm/generations/stubs.mjs +95 -8
- package/esm/generations/stubs.mjs.map +1 -1
- package/esm/http/index.d.mts +1 -0
- package/esm/http/index.mjs +1 -0
- package/esm/http/ready-report.d.mts +56 -0
- package/esm/http/ready-report.d.mts.map +1 -0
- package/esm/http/ready-report.mjs +24 -0
- package/esm/http/ready-report.mjs.map +1 -0
- package/esm/index.d.mts +2 -1
- package/esm/index.mjs +2 -1
- package/llms-full.txt +322 -1
- package/llms.txt +2 -0
- package/package.json +12 -12
- package/skills/use-request-locals/SKILL.md +24 -1
- package/skills/warlock-conventions/SKILL.md +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,53 @@ 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.1.0
|
|
10
|
+
|
|
11
|
+
> **If you use `@warlock.js/web`, upgrade.** React did not execute at all in published
|
|
12
|
+
> installs of 5.0.0 through 5.0.2 — the defect and its fix are in that package's
|
|
13
|
+
> changelog. `core` ships the CLI-side half of this release.
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- **`warlock add tailwind`** — installs and wires Tailwind CSS v4 through PostCSS.
|
|
18
|
+
- **`warlock add shadcn`** — sets up the prerequisites shadcn/ui expects. It is *not* a
|
|
19
|
+
wrapper around the shadcn CLI: you still run that yourself to add components, this
|
|
20
|
+
only makes the project ready for it.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- **`warlock dev` prints one status block per run.** The banner is printed exactly once,
|
|
25
|
+
and the URL it prints is never a raw `[::1]` address. The single-boot guard behind
|
|
26
|
+
this is **new in this release — it was never present in any published version**, so
|
|
27
|
+
duplicate boots on 5.0.x were real, not a display artefact.
|
|
28
|
+
- **`warlock doctor` now reports the same route count as `warlock dev`.** The two walked
|
|
29
|
+
routes differently and disagreed. `doctor` also emits zero warnings on a healthy
|
|
30
|
+
project — so a warning now means something — and fails loudly on a route module that
|
|
31
|
+
genuinely fails to load, instead of counting it as fine.
|
|
32
|
+
|
|
33
|
+
### Removed
|
|
34
|
+
|
|
35
|
+
- **A false comment that the `warlock add web` scaffold emitted in 5.0.0 through 5.0.2**,
|
|
36
|
+
claiming a page's route is derived from its file location. No such derivation has ever
|
|
37
|
+
existed. The stub no longer emits it; **apps already scaffolded on those versions still
|
|
38
|
+
carry the comment in their own source** and must delete it by hand.
|
|
39
|
+
|
|
40
|
+
### Internal
|
|
41
|
+
|
|
42
|
+
- The `add` feature registry was split into one module per feature, replacing the single
|
|
43
|
+
growing switch.
|
|
44
|
+
- Fixed 7 mojibake checkmarks in CLI output.
|
|
45
|
+
|
|
46
|
+
## 5.0.2 - 2026-08-25
|
|
47
|
+
|
|
48
|
+
No changes to `@warlock.js/core`. Released in lockstep with the `@warlock.js/web` SSR
|
|
49
|
+
fix (`ssr.noExternal`) — see that package's changelog.
|
|
50
|
+
|
|
51
|
+
## 5.0.1 - 2026-08-25
|
|
52
|
+
|
|
53
|
+
No changes to `@warlock.js/core`. Released in lockstep with the `create-warlock` vite
|
|
54
|
+
resolution pin and the `@warlock.js/web` peer narrowing — see those packages' changelogs.
|
|
55
|
+
|
|
9
56
|
## 5.0.0 - 2026-08-25
|
|
10
57
|
|
|
11
58
|
### Upgrading
|
|
@@ -10,6 +10,7 @@ import { warlockConfigManager } from "../warlock-config/warlock-config.manager.m
|
|
|
10
10
|
import { registerConfiguredConnectors } from "../connectors/register-configured-connectors.mjs";
|
|
11
11
|
import { filesOrchestrator } from "../dev-server/files-orchestrator.mjs";
|
|
12
12
|
import { loadConfigFiles } from "../config/load-config-files.mjs";
|
|
13
|
+
import { isDevWorker } from "../dev-server/supervisor.mjs";
|
|
13
14
|
import { manifestManager } from "../manifest/manifest-manager.mjs";
|
|
14
15
|
import { displayBootError, displayCommandError, displayCommandHelp, displayCommandNotFound, displayCommandSuccess, displayExecutingCommand, displayHelp, displayMissingCommand, displayMissingOptions, displayWarlockVersionInTerminal, isMatchingCommandName } from "./cli-commands.utils.mjs";
|
|
15
16
|
import { cliCommandsLoader } from "./commands-loader.mjs";
|
|
@@ -46,6 +47,40 @@ function exitAfterFlush(code) {
|
|
|
46
47
|
process.stdout.write("", drained);
|
|
47
48
|
process.stderr.write("", drained);
|
|
48
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Whether this process is the CHILD half of a supervised command.
|
|
52
|
+
*
|
|
53
|
+
* ## The finding this encodes
|
|
54
|
+
*
|
|
55
|
+
* `warlock dev` printing `› Running dev...` twice was NOT a double boot, and
|
|
56
|
+
* the distinction is the whole point of this function existing rather than the
|
|
57
|
+
* line simply being deleted. The sequence, in file order:
|
|
58
|
+
*
|
|
59
|
+
* 1. `execute()` prints the header (below) — BEFORE `commandPreAction`.
|
|
60
|
+
* 2. `cli/commands/dev-server.command.ts` `preAction` calls
|
|
61
|
+
* `superviseDevServer()` when `!isDevWorker()`.
|
|
62
|
+
* 3. `dev-server/supervisor.ts` `spawnWorker()` re-spawns `process.argv` with
|
|
63
|
+
* `WARLOCK_DEV_WORKER=1`, so the child runs `warlock dev` again and prints
|
|
64
|
+
* the header too.
|
|
65
|
+
* 4. `superviseDevServer()` returns a promise that never settles, so the
|
|
66
|
+
* supervisor's `await commandPreAction(...)` never resolves — `loadPreloaders`
|
|
67
|
+
* and `command.execute` are unreachable in the supervisor.
|
|
68
|
+
*
|
|
69
|
+
* Step 4 is why only ONE process ever loads config, connectors, app modules or
|
|
70
|
+
* a scheduler. Verified by running it: one `APP-CODE-LOADED`, one
|
|
71
|
+
* `Application.markBooted`, one `⚡ Warlock.js` banner, one route registration,
|
|
72
|
+
* two processes. The `2 job(s) registered` in the original report is two jobs
|
|
73
|
+
* in one scheduler, not two schedulers — a genuine double boot would have
|
|
74
|
+
* printed that warning twice.
|
|
75
|
+
*
|
|
76
|
+
* So the defect is exactly one duplicated line, and this is the guard that
|
|
77
|
+
* keeps it one. `tests/unit/cli/dev-command-single-boot.test.ts` fails if the
|
|
78
|
+
* supervisor ever starts running preloaders — i.e. if the double boot the
|
|
79
|
+
* duplicated line looked like ever becomes real.
|
|
80
|
+
*/
|
|
81
|
+
function isRespawnedWorker() {
|
|
82
|
+
return isDevWorker();
|
|
83
|
+
}
|
|
49
84
|
var CLICommandsManager = class {
|
|
50
85
|
constructor() {
|
|
51
86
|
this.commands = [];
|
|
@@ -297,7 +332,7 @@ var CLICommandsManager = class {
|
|
|
297
332
|
process.exit(1);
|
|
298
333
|
}
|
|
299
334
|
data.options = this.applyDefaultOptions(command, data.options);
|
|
300
|
-
displayExecutingCommand(command.name);
|
|
335
|
+
if (!isRespawnedWorker()) displayExecutingCommand(command.name);
|
|
301
336
|
if (command.commandPreAction) await command.commandPreAction(data);
|
|
302
337
|
if (command.commandPreload) try {
|
|
303
338
|
await this.loadPreloaders(command);
|
|
@@ -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 { 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, ParsedCliArgs, parseCliArgs } from \"./parse-cli-args\";\r\nimport { findSimilar } from \"./string-similarity\";\r\nimport { 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\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 displayExecutingCommand(command.name);\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 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":";;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,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;AAiBA,IAAa,qBAAb,MAAgC;;kBAIE,CAAC;qCAKa,IA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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 { 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, ParsedCliArgs, parseCliArgs } from \"./parse-cli-args\";\r\nimport { findSimilar } from \"./string-similarity\";\r\nimport { 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 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,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;IAC7C,cAAc,QAAQ;IACtB,QAAQ,QAAQ,iBAAiB;IACjC,aAAa,QAAQ;IACrB,OAAO,QAAQ;IACf,SAAS,QAAQ,eAAe,SAAS,IAAI,QAAQ,iBAAiB;GACxE,CAAC;GAED,KAAK,YAAY,IAAI,YAAY,OAAO;GAGxC,IAAI,QAAQ,cACV,KAAK,SAAS,IAAI,QAAQ,cAAc,UAAU;EAEtD,CAAC;EAED,OAAO;CACT;;;;CAKA,AAAO,WAAW,MAAsC;EAEtD,IAAI,UA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B,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;GAE7B,IAAI,WAAW,eAAe,MAC5B,MAAM,kBAAkB,kBAAwC;QAEhE,MAAM,kBAAkB,MAAM,WAAW,UAAU;EAEvD;CACF;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { command } from "../../commands/cli-command.mjs";
|
|
2
|
-
import { displayStartupBanner } from "../cli-commands.utils.mjs";
|
|
3
2
|
import { isDevWorker, superviseDevServer } from "../../dev-server/supervisor.mjs";
|
|
3
|
+
import { displayStartupBanner } from "../cli-commands.utils.mjs";
|
|
4
4
|
import { checkForFrameworkUpdate } from "../../dev-server/check-for-updates.mjs";
|
|
5
5
|
import { startDevelopmentServer } from "../../dev-server/start-development-server.mjs";
|
|
6
6
|
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import "../../../config/config-getter.mjs";
|
|
2
|
+
import { container } from "../../../container/index.mjs";
|
|
3
|
+
import { router } from "../../../router/router.mjs";
|
|
4
|
+
import { ConnectorLifecyclePhase } from "../../../connectors/types.mjs";
|
|
5
|
+
import { connectorsManager } from "../../../connectors/connectors-manager.mjs";
|
|
6
|
+
import { registerConfiguredConnectors } from "../../../connectors/register-configured-connectors.mjs";
|
|
7
|
+
import { ModuleLoadError } from "../../../dev-server/module-loader.mjs";
|
|
8
|
+
import { filesOrchestrator } from "../../../dev-server/files-orchestrator.mjs";
|
|
9
|
+
|
|
10
|
+
//#region ../core/src/cli/commands/doctor/boot-for-diagnostics.ts
|
|
11
|
+
/**
|
|
12
|
+
* @fileoverview The boot pass `warlock doctor` runs before its checks.
|
|
13
|
+
*
|
|
14
|
+
* THE RULE: **doctor boots, it never starts.**
|
|
15
|
+
*
|
|
16
|
+
* The connector contract already splits the two things doctor needs to keep
|
|
17
|
+
* apart. `boot()` is where a connector REGISTERS — the HTTP connector builds a
|
|
18
|
+
* Fastify instance and adds `/health` + `/ready` to it, the web connector
|
|
19
|
+
* installs one route per page on the app router — and `start()` is where it
|
|
20
|
+
* CONNECTS: opens the database, dials the cache, binds the port. Doctor runs
|
|
21
|
+
* every `boot()` and no `start()`, so it sees the exact surface a served app
|
|
22
|
+
* would have while opening no connection and binding no port.
|
|
23
|
+
*
|
|
24
|
+
* That seam is what makes the checks true. Before it existed here, doctor
|
|
25
|
+
* preloaded config and framework bootstrap only: no app module was ever
|
|
26
|
+
* imported, so no route module ever ran, so `routes` reported `0` on an app
|
|
27
|
+
* `warlock dev` served 14 routes for — while `health` reported the endpoints as
|
|
28
|
+
* "registered" from a config flag alone. Two checks, one app, contradictory
|
|
29
|
+
* answers, and the wrong one was the one users acted on.
|
|
30
|
+
*
|
|
31
|
+
* ORDERING mirrors `DevelopmentServer.start()` exactly, because the route
|
|
32
|
+
* surface is order-dependent: early connectors boot, then models (decorator
|
|
33
|
+
* registries the route modules resolve against), then locales/events/mains/
|
|
34
|
+
* routes, then late connectors — which is where `web` turns pages into routes.
|
|
35
|
+
* Get the order wrong and the count is wrong, which is the defect this replaces.
|
|
36
|
+
*
|
|
37
|
+
* NOT read-only in one narrow sense: it imports the app's own modules, so
|
|
38
|
+
* whatever a module does at import time happens. That is unavoidable — routes
|
|
39
|
+
* only exist as the side effect of importing the file that declares them — and
|
|
40
|
+
* it is the same import the dev server performs. It also refreshes
|
|
41
|
+
* `.warlock/manifest.json`, the framework's own file cache. Nothing in the
|
|
42
|
+
* app's data, and no network, is touched.
|
|
43
|
+
*/
|
|
44
|
+
/**
|
|
45
|
+
* The one connector whose `boot()` can bind a port. See {@link shouldSkipBoot}.
|
|
46
|
+
*/
|
|
47
|
+
const SOCKET_CONNECTOR = "socket";
|
|
48
|
+
/**
|
|
49
|
+
* Normalize anything thrown into a one-line message.
|
|
50
|
+
*/
|
|
51
|
+
function messageOf(error) {
|
|
52
|
+
return error instanceof Error ? error.message : String(error);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Whether doctor must refuse to boot this connector, and why.
|
|
56
|
+
*
|
|
57
|
+
* Exactly one case, and it is not a taste call: `SocketConnector.boot()` shares
|
|
58
|
+
* the HTTP connector's raw server when there is one, and CREATES its own —
|
|
59
|
+
* `server.listen(socketConfig.port)` — when there is not. The HTTP connector
|
|
60
|
+
* boots first (lower priority number), so the shared path is what normally
|
|
61
|
+
* happens; an app that configures `socket` without `http` is the exception, and
|
|
62
|
+
* for that app booting socket would make a diagnostic command open a listening
|
|
63
|
+
* port. Detected by asking the container what HTTP actually left behind rather
|
|
64
|
+
* than by re-deriving the condition from config.
|
|
65
|
+
*/
|
|
66
|
+
function shouldSkipBoot(name) {
|
|
67
|
+
if (name === SOCKET_CONNECTOR && !container.has("http.server")) return "no http connector to share a server with — booting it would bind a port";
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Boot every registered connector in one lifecycle phase, isolating failures.
|
|
71
|
+
*
|
|
72
|
+
* A connector that throws on boot is recorded and the loop continues: one bad
|
|
73
|
+
* connector must not hide the rest of the report, and "which connector failed
|
|
74
|
+
* to boot" is itself a finding worth printing.
|
|
75
|
+
*/
|
|
76
|
+
async function bootPhase(phase, connectors) {
|
|
77
|
+
for (const connector of connectorsManager.list()) {
|
|
78
|
+
if (connector.lifecyclePhase !== phase) continue;
|
|
79
|
+
const skipReason = shouldSkipBoot(connector.name);
|
|
80
|
+
if (skipReason) {
|
|
81
|
+
connectors.skipped.push({
|
|
82
|
+
name: connector.name,
|
|
83
|
+
reason: skipReason
|
|
84
|
+
});
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
await connector.boot();
|
|
89
|
+
connectors.booted.push(connector.name);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
connectors.failures.push({
|
|
92
|
+
name: connector.name,
|
|
93
|
+
message: messageOf(error)
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Import every app module the dev server imports at boot, collecting failures
|
|
100
|
+
* instead of letting the first one abort the pass.
|
|
101
|
+
*
|
|
102
|
+
* `loadAll()` is deliberately reused rather than reimplemented: it owns the
|
|
103
|
+
* canonical order (locale → event → main → route) and the `withSourceFile`
|
|
104
|
+
* scoping that gives each route its origin file. It aggregates its failures and
|
|
105
|
+
* throws them at the end, which is exactly the shape needed here — every module
|
|
106
|
+
* is attempted, and one broken route file cannot mask another.
|
|
107
|
+
*/
|
|
108
|
+
async function loadAppModules() {
|
|
109
|
+
try {
|
|
110
|
+
await filesOrchestrator.moduleLoader.loadAll();
|
|
111
|
+
return [];
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (error instanceof AggregateError) return error.errors.map((failure) => {
|
|
114
|
+
return failure instanceof ModuleLoadError ? {
|
|
115
|
+
file: failure.file.relativePath,
|
|
116
|
+
message: messageOf(failure.cause)
|
|
117
|
+
} : {
|
|
118
|
+
file: "unknown",
|
|
119
|
+
message: messageOf(failure)
|
|
120
|
+
};
|
|
121
|
+
});
|
|
122
|
+
return [{
|
|
123
|
+
file: "unknown",
|
|
124
|
+
message: messageOf(error)
|
|
125
|
+
}];
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Eagerly import model files so the decorator-driven registries the route
|
|
130
|
+
* modules resolve names against are populated first — the same reason
|
|
131
|
+
* `DevelopmentServer.autoDiscoverFiles()` exists, and it must keep the same
|
|
132
|
+
* position in the sequence.
|
|
133
|
+
*/
|
|
134
|
+
async function discoverModels() {
|
|
135
|
+
const failures = [];
|
|
136
|
+
for (const file of filesOrchestrator.files.values()) {
|
|
137
|
+
if (file.type !== "model") continue;
|
|
138
|
+
try {
|
|
139
|
+
await filesOrchestrator.moduleLoader.loadModule(file, "model");
|
|
140
|
+
} catch (error) {
|
|
141
|
+
failures.push({
|
|
142
|
+
file: file.relativePath,
|
|
143
|
+
message: error instanceof ModuleLoadError ? messageOf(error.cause) : messageOf(error)
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return failures;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Run the boot pass and report what it found.
|
|
151
|
+
*
|
|
152
|
+
* Never throws. Every failure mode — a connector array the config manager
|
|
153
|
+
* refuses, a connector that throws on boot, a route module that fails to
|
|
154
|
+
* import — becomes a field on the returned context, which the checks turn into
|
|
155
|
+
* a printed verdict. A diagnostic command that crashes while diagnosing tells
|
|
156
|
+
* the user nothing.
|
|
157
|
+
*/
|
|
158
|
+
async function bootForDiagnostics() {
|
|
159
|
+
const connectors = {
|
|
160
|
+
registered: [],
|
|
161
|
+
configured: [],
|
|
162
|
+
booted: [],
|
|
163
|
+
skipped: [],
|
|
164
|
+
failures: []
|
|
165
|
+
};
|
|
166
|
+
const context = {
|
|
167
|
+
booted: false,
|
|
168
|
+
routeModules: 0,
|
|
169
|
+
appRoutes: 0,
|
|
170
|
+
totalRoutes: 0,
|
|
171
|
+
moduleFailures: [],
|
|
172
|
+
connectors
|
|
173
|
+
};
|
|
174
|
+
try {
|
|
175
|
+
await filesOrchestrator.init();
|
|
176
|
+
await filesOrchestrator.initializeAll();
|
|
177
|
+
filesOrchestrator.specialFilesCollector.collect(filesOrchestrator.getFiles());
|
|
178
|
+
context.routeModules = filesOrchestrator.specialFilesCollector.getFilesByType("route").length;
|
|
179
|
+
} catch (error) {
|
|
180
|
+
context.moduleFailures.push({
|
|
181
|
+
file: "src/",
|
|
182
|
+
message: messageOf(error)
|
|
183
|
+
});
|
|
184
|
+
return context;
|
|
185
|
+
}
|
|
186
|
+
try {
|
|
187
|
+
registerConfiguredConnectors();
|
|
188
|
+
} catch (error) {
|
|
189
|
+
connectors.registrationError = messageOf(error);
|
|
190
|
+
}
|
|
191
|
+
connectors.registered = connectorsManager.list().map((connector) => connector.name);
|
|
192
|
+
connectors.configured = connectors.registered.filter((name) => {
|
|
193
|
+
return !connectorsManager.isBuiltInName(name);
|
|
194
|
+
});
|
|
195
|
+
await bootPhase("early", connectors);
|
|
196
|
+
context.moduleFailures.push(...await discoverModels());
|
|
197
|
+
context.moduleFailures.push(...await loadAppModules());
|
|
198
|
+
context.appRoutes = router.routeCount();
|
|
199
|
+
await bootPhase("late", connectors);
|
|
200
|
+
context.totalRoutes = router.routeCount();
|
|
201
|
+
context.booted = true;
|
|
202
|
+
return context;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
//#endregion
|
|
206
|
+
export { bootForDiagnostics };
|
|
207
|
+
//# sourceMappingURL=boot-for-diagnostics.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"boot-for-diagnostics.mjs","names":[],"sources":["../../../../../../../../../core/src/cli/commands/doctor/boot-for-diagnostics.ts"],"sourcesContent":["import { config } from \"../../../config/config-getter\";\r\nimport { connectorsManager } from \"../../../connectors/connectors-manager\";\r\nimport { registerConfiguredConnectors } from \"../../../connectors/register-configured-connectors\";\r\nimport { ConnectorLifecyclePhase } from \"../../../connectors/types\";\r\nimport { container } from \"../../../container\";\r\nimport { filesOrchestrator } from \"../../../dev-server/files-orchestrator\";\r\nimport { ModuleLoadError } from \"../../../dev-server/module-loader\";\r\nimport { router } from \"../../../router/router\";\r\nimport type { DoctorBootContext, ModuleFailure } from \"./check.types\";\r\n\r\n/**\r\n * @fileoverview The boot pass `warlock doctor` runs before its checks.\r\n *\r\n * THE RULE: **doctor boots, it never starts.**\r\n *\r\n * The connector contract already splits the two things doctor needs to keep\r\n * apart. `boot()` is where a connector REGISTERS — the HTTP connector builds a\r\n * Fastify instance and adds `/health` + `/ready` to it, the web connector\r\n * installs one route per page on the app router — and `start()` is where it\r\n * CONNECTS: opens the database, dials the cache, binds the port. Doctor runs\r\n * every `boot()` and no `start()`, so it sees the exact surface a served app\r\n * would have while opening no connection and binding no port.\r\n *\r\n * That seam is what makes the checks true. Before it existed here, doctor\r\n * preloaded config and framework bootstrap only: no app module was ever\r\n * imported, so no route module ever ran, so `routes` reported `0` on an app\r\n * `warlock dev` served 14 routes for — while `health` reported the endpoints as\r\n * \"registered\" from a config flag alone. Two checks, one app, contradictory\r\n * answers, and the wrong one was the one users acted on.\r\n *\r\n * ORDERING mirrors `DevelopmentServer.start()` exactly, because the route\r\n * surface is order-dependent: early connectors boot, then models (decorator\r\n * registries the route modules resolve against), then locales/events/mains/\r\n * routes, then late connectors — which is where `web` turns pages into routes.\r\n * Get the order wrong and the count is wrong, which is the defect this replaces.\r\n *\r\n * NOT read-only in one narrow sense: it imports the app's own modules, so\r\n * whatever a module does at import time happens. That is unavoidable — routes\r\n * only exist as the side effect of importing the file that declares them — and\r\n * it is the same import the dev server performs. It also refreshes\r\n * `.warlock/manifest.json`, the framework's own file cache. Nothing in the\r\n * app's data, and no network, is touched.\r\n */\r\n\r\n/**\r\n * The one connector whose `boot()` can bind a port. See {@link shouldSkipBoot}.\r\n */\r\nconst SOCKET_CONNECTOR = \"socket\";\r\n\r\n/**\r\n * Normalize anything thrown into a one-line message.\r\n */\r\nfunction messageOf(error: unknown): string {\r\n return error instanceof Error ? error.message : String(error);\r\n}\r\n\r\n/**\r\n * Whether doctor must refuse to boot this connector, and why.\r\n *\r\n * Exactly one case, and it is not a taste call: `SocketConnector.boot()` shares\r\n * the HTTP connector's raw server when there is one, and CREATES its own —\r\n * `server.listen(socketConfig.port)` — when there is not. The HTTP connector\r\n * boots first (lower priority number), so the shared path is what normally\r\n * happens; an app that configures `socket` without `http` is the exception, and\r\n * for that app booting socket would make a diagnostic command open a listening\r\n * port. Detected by asking the container what HTTP actually left behind rather\r\n * than by re-deriving the condition from config.\r\n */\r\nfunction shouldSkipBoot(name: string): string | undefined {\r\n if (name === SOCKET_CONNECTOR && !container.has(\"http.server\")) {\r\n return \"no http connector to share a server with — booting it would bind a port\";\r\n }\r\n\r\n return undefined;\r\n}\r\n\r\n/**\r\n * Boot every registered connector in one lifecycle phase, isolating failures.\r\n *\r\n * A connector that throws on boot is recorded and the loop continues: one bad\r\n * connector must not hide the rest of the report, and \"which connector failed\r\n * to boot\" is itself a finding worth printing.\r\n */\r\nasync function bootPhase(\r\n phase: ConnectorLifecyclePhase,\r\n connectors: DoctorBootContext[\"connectors\"],\r\n): Promise<void> {\r\n for (const connector of connectorsManager.list()) {\r\n if (connector.lifecyclePhase !== phase) continue;\r\n\r\n const skipReason = shouldSkipBoot(connector.name);\r\n\r\n if (skipReason) {\r\n connectors.skipped.push({ name: connector.name, reason: skipReason });\r\n continue;\r\n }\r\n\r\n try {\r\n await connector.boot();\r\n connectors.booted.push(connector.name);\r\n } catch (error) {\r\n connectors.failures.push({ name: connector.name, message: messageOf(error) });\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Import every app module the dev server imports at boot, collecting failures\r\n * instead of letting the first one abort the pass.\r\n *\r\n * `loadAll()` is deliberately reused rather than reimplemented: it owns the\r\n * canonical order (locale → event → main → route) and the `withSourceFile`\r\n * scoping that gives each route its origin file. It aggregates its failures and\r\n * throws them at the end, which is exactly the shape needed here — every module\r\n * is attempted, and one broken route file cannot mask another.\r\n */\r\nasync function loadAppModules(): Promise<ModuleFailure[]> {\r\n try {\r\n await filesOrchestrator.moduleLoader.loadAll();\r\n return [];\r\n } catch (error) {\r\n if (error instanceof AggregateError) {\r\n return (error.errors as unknown[]).map((failure) => {\r\n return failure instanceof ModuleLoadError\r\n ? { file: failure.file.relativePath, message: messageOf(failure.cause) }\r\n : { file: \"unknown\", message: messageOf(failure) };\r\n });\r\n }\r\n\r\n return [{ file: \"unknown\", message: messageOf(error) }];\r\n }\r\n}\r\n\r\n/**\r\n * Eagerly import model files so the decorator-driven registries the route\r\n * modules resolve names against are populated first — the same reason\r\n * `DevelopmentServer.autoDiscoverFiles()` exists, and it must keep the same\r\n * position in the sequence.\r\n */\r\nasync function discoverModels(): Promise<ModuleFailure[]> {\r\n const failures: ModuleFailure[] = [];\r\n\r\n for (const file of filesOrchestrator.files.values()) {\r\n if (file.type !== \"model\") continue;\r\n\r\n try {\r\n await filesOrchestrator.moduleLoader.loadModule(file, \"model\");\r\n } catch (error) {\r\n failures.push({\r\n file: file.relativePath,\r\n message: error instanceof ModuleLoadError ? messageOf(error.cause) : messageOf(error),\r\n });\r\n }\r\n }\r\n\r\n return failures;\r\n}\r\n\r\n/**\r\n * Run the boot pass and report what it found.\r\n *\r\n * Never throws. Every failure mode — a connector array the config manager\r\n * refuses, a connector that throws on boot, a route module that fails to\r\n * import — becomes a field on the returned context, which the checks turn into\r\n * a printed verdict. A diagnostic command that crashes while diagnosing tells\r\n * the user nothing.\r\n */\r\nexport async function bootForDiagnostics(): Promise<DoctorBootContext> {\r\n const connectors: DoctorBootContext[\"connectors\"] = {\r\n registered: [],\r\n configured: [],\r\n booted: [],\r\n skipped: [],\r\n failures: [],\r\n };\r\n\r\n const context: DoctorBootContext = {\r\n booted: false,\r\n routeModules: 0,\r\n appRoutes: 0,\r\n totalRoutes: 0,\r\n moduleFailures: [],\r\n connectors,\r\n };\r\n\r\n try {\r\n // `init()` is idempotent and the preloader already ran it; calling it again\r\n // costs nothing and keeps this function honest on its own.\r\n await filesOrchestrator.init();\r\n await filesOrchestrator.initializeAll();\r\n\r\n filesOrchestrator.specialFilesCollector.collect(filesOrchestrator.getFiles());\r\n\r\n context.routeModules = filesOrchestrator.specialFilesCollector.getFilesByType(\"route\").length;\r\n } catch (error) {\r\n context.moduleFailures.push({ file: \"src/\", message: messageOf(error) });\r\n\r\n return context;\r\n }\r\n\r\n // The app's own connectors (`warlock.config.ts > connectors`) must be\r\n // registered before any phase boots, exactly as the dev preloader does it —\r\n // otherwise doctor would report on the eleven built-ins alone and miss the\r\n // connector the app actually configured. This is also the call that refuses a\r\n // duplicate or reserved connector name, so a config that would crash the next\r\n // real boot is caught here instead.\r\n try {\r\n registerConfiguredConnectors();\r\n } catch (error) {\r\n connectors.registrationError = messageOf(error);\r\n }\r\n\r\n connectors.registered = connectorsManager.list().map((connector) => connector.name);\r\n connectors.configured = connectors.registered.filter((name) => {\r\n return !connectorsManager.isBuiltInName(name);\r\n });\r\n\r\n await bootPhase(ConnectorLifecyclePhase.Early, connectors);\r\n\r\n context.moduleFailures.push(...(await discoverModels()));\r\n context.moduleFailures.push(...(await loadAppModules()));\r\n\r\n // Snapshot BEFORE the late phase: everything the app's own route modules\r\n // registered. The difference between this and the total is what connectors\r\n // contributed (pages, for `web`), and reporting the two separately is what\r\n // lets a user reconcile doctor's number with the dev server's.\r\n context.appRoutes = router.routeCount();\r\n\r\n await bootPhase(ConnectorLifecyclePhase.Late, connectors);\r\n\r\n context.totalRoutes = router.routeCount();\r\n\r\n context.booted = true;\r\n\r\n return context;\r\n}\r\n\r\n/**\r\n * Whether the app declares an HTTP surface at all. Checks that only make sense\r\n * for a served app use this to opt out instead of inventing a verdict.\r\n */\r\nexport function hasHttpConfig(): boolean {\r\n return Boolean(config.get(\"http\"));\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAM,mBAAmB;;;;AAKzB,SAAS,UAAU,OAAwB;CACzC,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;;;;;;;;;;;;AAcA,SAAS,eA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;CACF;CAEA,OAAO;AACT;;;;;;;;;;AAWA,eAAsB,qBAAiD;CACrE,MAAM,aAA8C;EAClD,YAAY,CAAC;EACb,YAAY,CAAC;EACb,QAAQ,CAAC;EACT,SAAS,CAAC;EACV,UAAU,CAAC;CACb;CAEA,MAAM,UAA6B;EACjC,QAAQ;EACR,cAAc;EACd,WAAW;EACX,aAAa;EACb,gBAAgB,CAAC;EACjB;CACF;CAEA,IAAI;EAGF,MAAM,kBAAkB,KAAK;EAC7B,MAAM,kBAAkB,cAAc;EAEtC,kBAAkB,sBAAsB,QAAQ,kBAAkB,SAAS,CAAC;EAE5E,QAAQ,eAAe,kBAAkB,sBAAsB,eAAe,OAAO,CAAC,CAAC;CACzF,SAAS,OAAO;EACd,QAAQ,eAAe,KAAK;GAAE,MAAM;GAAQ,SAAS,UAAU,KAAK;EAAE,CAAC;EAEvE,OAAO;CACT;CAQA,IAAI;EACF,6BAA6B;CAC/B,SAAS,OAAO;EACd,WAAW,oBAAoB,UAAU,KAAK;CAChD;CAEA,WAAW,aAAa,kBAAkB,KAAK,CAAC,CAAC,KAAK,cAAc,UAAU,IAAI;CAClF,WAAW,aAAa,WAAW,WAAW,QAAQ,SAAS;EAC7D,OAAO,CAAC,kBAAkB,cAAc,IAAI;CAC9C,CAAC;CAED,MAAM,mBAAyC,UAAU;CAEzD,QAAQ,eAAe,KAAK,GAAI,MAAM,eAAe,CAAE;CACvD,QAAQ,eAAe,KAAK,GAAI,MAAM,eAAe,CAAE;CAMvD,QAAQ,YAAY,OAAO,WAAW;CAEtC,MAAM,kBAAwC,UAAU;CAExD,QAAQ,cAAc,OAAO,WAAW;CAExC,QAAQ,SAAS;CAEjB,OAAO;AACT"}
|
|
@@ -15,8 +15,11 @@ function isPresent(value) {
|
|
|
15
15
|
return value !== null && value !== void 0;
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
|
-
* Verifies that the required top-level config sections are present.
|
|
19
|
-
*
|
|
18
|
+
* Verifies that the required top-level config sections are present.
|
|
19
|
+
*
|
|
20
|
+
* NEEDS NO BOOTED APP — config files are loaded by the command's preloaders,
|
|
21
|
+
* before the boot pass. Reads each section via `config.get` only; never mutates
|
|
22
|
+
* configuration.
|
|
20
23
|
*/
|
|
21
24
|
const configCheck = {
|
|
22
25
|
name: "config",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.check.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/doctor/checks/config.check.ts"],"sourcesContent":["import { config } from \"../../../../config/config-getter\";\nimport type { DoctorCheck } from \"../check.types\";\n\n/**\n * Config sections that a typical Warlock HTTP application is expected to\n * register. A missing section here is release/runtime-blocking, so absence is\n * a `fail` rather than a warning.\n */\nconst REQUIRED_CONFIG_SECTIONS = [\"app\", \"http\"] as const;\n\n/**\n * `@mongez/config` returns `null` (not `undefined`) for an unregistered key,\n * so treat both nullish values as \"missing\".\n */\nfunction isPresent(value: unknown): boolean {\n return value !== null && value !== undefined;\n}\n\n/**\n * Verifies that the required top-level config sections are present. Reads each
|
|
1
|
+
{"version":3,"file":"config.check.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/doctor/checks/config.check.ts"],"sourcesContent":["import { config } from \"../../../../config/config-getter\";\nimport type { DoctorCheck } from \"../check.types\";\n\n/**\n * Config sections that a typical Warlock HTTP application is expected to\n * register. A missing section here is release/runtime-blocking, so absence is\n * a `fail` rather than a warning.\n */\nconst REQUIRED_CONFIG_SECTIONS = [\"app\", \"http\"] as const;\n\n/**\n * `@mongez/config` returns `null` (not `undefined`) for an unregistered key,\n * so treat both nullish values as \"missing\".\n */\nfunction isPresent(value: unknown): boolean {\n return value !== null && value !== undefined;\n}\n\n/**\n * Verifies that the required top-level config sections are present.\n *\n * NEEDS NO BOOTED APP — config files are loaded by the command's preloaders,\n * before the boot pass. Reads each section via `config.get` only; never mutates\n * configuration.\n */\nexport const configCheck: DoctorCheck = {\n name: \"config\",\n run: () => {\n const missing = REQUIRED_CONFIG_SECTIONS.filter((section) => {\n return !isPresent(config.get(section));\n });\n\n if (missing.length > 0) {\n return {\n name: \"config\",\n status: \"fail\",\n detail: `missing required config section(s): ${missing.join(\", \")}`,\n };\n }\n\n return {\n name: \"config\",\n status: \"ok\",\n detail: `required sections present (${REQUIRED_CONFIG_SECTIONS.join(\", \")})`,\n };\n },\n};\n"],"mappings":";;;;;;;;AAQA,MAAM,2BAA2B,CAAC,OAAO,MAAM;;;;;AAM/C,SAAS,UAAU,OAAyB;CAC1C,OAAO,UAAU,QAAQ,UAAU;AACrC;;;;;;;;AASA,MAAa,cAA2B;CACtC,MAAM;CACN,WAAW;EACT,MAAM,UAAU,yBAAyB,QAAQ,YAAY;GAC3D,OAAO,CAAC,UAAU,OAAO,IAAI,OAAO,CAAC;EACvC,CAAC;EAED,IAAI,QAAQ,SAAS,GACnB,OAAO;GACL,MAAM;GACN,QAAQ;GACR,QAAQ,uCAAuC,QAAQ,KAAK,IAAI;EAClE;EAGF,OAAO;GACL,MAAM;GACN,QAAQ;GACR,QAAQ,8BAA8B,yBAAyB,KAAK,IAAI,EAAE;EAC5E;CACF;AACF"}
|
|
@@ -1,24 +1,50 @@
|
|
|
1
|
-
import { connectorsManager } from "../../../../connectors/connectors-manager.mjs";
|
|
2
|
-
|
|
3
1
|
//#region ../core/src/cli/commands/doctor/checks/connectors.check.ts
|
|
4
2
|
/**
|
|
5
|
-
* Reports
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
3
|
+
* Reports whether the app's connectors survive boot.
|
|
4
|
+
*
|
|
5
|
+
* NEEDS A BOOTED APP: the boot pass runs every connector's `boot()` and no
|
|
6
|
+
* `start()`, and this check reads the outcome.
|
|
7
|
+
*
|
|
8
|
+
* WHAT THIS REPLACED, AND WHY: the previous version printed
|
|
9
|
+
* `11 registered, none active`. Both halves were tautologies. Eleven is the
|
|
10
|
+
* number of built-in connectors the manager constructs when its module is
|
|
11
|
+
* imported — it is the same on every project that has ever existed and says
|
|
12
|
+
* nothing about the app. And "none active" was guaranteed, because `active` is
|
|
13
|
+
* set by `start()` and doctor deliberately never starts anything: the warning
|
|
14
|
+
* could not be absent from a healthy app, so it could not mean anything on a
|
|
15
|
+
* broken one.
|
|
16
|
+
*
|
|
17
|
+
* What is reported instead is a fact that varies with the project and can be
|
|
18
|
+
* wrong: the connectors the app itself configured, and whether each of them
|
|
19
|
+
* boots. A connector that throws on boot is a boot-time crash the user has not
|
|
20
|
+
* hit yet.
|
|
9
21
|
*
|
|
10
|
-
*
|
|
11
|
-
* `
|
|
22
|
+
* Verdicts:
|
|
23
|
+
* - `warlock.config.ts > connectors` refused (duplicate or reserved name) →
|
|
24
|
+
* `fail`. The next real boot would throw the same error;
|
|
25
|
+
* - a connector's `boot()` threw → `fail`, named, with the message;
|
|
26
|
+
* - otherwise → `ok`, listing what booted.
|
|
12
27
|
*/
|
|
13
28
|
const connectorsCheck = {
|
|
14
29
|
name: "connectors",
|
|
15
|
-
run: () => {
|
|
16
|
-
const connectors =
|
|
17
|
-
|
|
30
|
+
run: (context) => {
|
|
31
|
+
const { connectors } = context;
|
|
32
|
+
if (connectors.registrationError) return {
|
|
33
|
+
name: "connectors",
|
|
34
|
+
status: "fail",
|
|
35
|
+
detail: `warlock.config.ts > connectors was refused: ${connectors.registrationError}`
|
|
36
|
+
};
|
|
37
|
+
if (connectors.failures.length > 0) return {
|
|
38
|
+
name: "connectors",
|
|
39
|
+
status: "fail",
|
|
40
|
+
detail: `${connectors.failures.length} connector(s) failed to boot:\n` + connectors.failures.map((failure) => ` - ${failure.name}: ${failure.message}`).join("\n")
|
|
41
|
+
};
|
|
42
|
+
if (!context.booted) return;
|
|
43
|
+
const skipped = connectors.skipped.map((entry) => `; skipped ${entry.name} (${entry.reason})`).join("");
|
|
18
44
|
return {
|
|
19
45
|
name: "connectors",
|
|
20
46
|
status: "ok",
|
|
21
|
-
detail:
|
|
47
|
+
detail: `all booted without error (${connectors.configured.length > 0 ? `${connectors.configured.join(", ")} from warlock.config.ts + ${connectors.registered.length - connectors.configured.length} built-in` : `${connectors.registered.length} built-in, none configured in warlock.config.ts`})${skipped}`
|
|
22
48
|
};
|
|
23
49
|
}
|
|
24
50
|
};
|