@warlock.js/core 5.5.0 → 5.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/esm/application/app.d.mts.map +1 -1
- package/esm/application/app.mjs +7 -1
- package/esm/application/app.mjs.map +1 -1
- package/esm/benchmark/profiler.d.mts.map +1 -1
- package/esm/benchmark/profiler.mjs +4 -3
- package/esm/benchmark/profiler.mjs.map +1 -1
- package/esm/cli/cli-commands.manager.mjs +10 -7
- package/esm/cli/cli-commands.manager.mjs.map +1 -1
- package/esm/cli/cli-commands.utils.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/optional-peers.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/release-hygiene.check.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/column-dsl-parser.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
- package/esm/cli/commands/routes/format-routes-table.mjs +3 -3
- package/esm/cli/commands/routes/format-routes-table.mjs.map +1 -1
- package/esm/cli/commands/routes/route-row.mjs.map +1 -1
- package/esm/cli/commands/routes.command.mjs.map +1 -1
- package/esm/cli/framework-cli-commands.mjs.map +1 -1
- package/esm/cli/parse-cli-args.mjs +1 -0
- package/esm/cli/parse-cli-args.mjs.map +1 -1
- package/esm/cli/string-similarity.mjs +13 -4
- package/esm/cli/string-similarity.mjs.map +1 -1
- package/esm/commands/cli-command.d.mts.map +1 -1
- package/esm/commands/cli-command.mjs +5 -2
- package/esm/commands/cli-command.mjs.map +1 -1
- package/esm/config/config-loader.mjs +3 -1
- package/esm/config/config-loader.mjs.map +1 -1
- package/esm/config/locale-configuration.mjs +11 -1
- package/esm/config/locale-configuration.mjs.map +1 -1
- package/esm/container/container-instance-registry.mjs +40 -0
- package/esm/container/container-instance-registry.mjs.map +1 -0
- package/esm/container/index.d.mts +11 -0
- package/esm/container/index.d.mts.map +1 -1
- package/esm/container/index.mjs +11 -0
- package/esm/container/index.mjs.map +1 -1
- package/esm/database/drop-tables-action.mjs.map +1 -1
- package/esm/database/migrate-action.mjs.map +1 -1
- package/esm/database/seed-command-action.mjs.map +1 -1
- package/esm/dev-server/dependency-graph.d.mts.map +1 -1
- package/esm/dev-server/dependency-graph.mjs +2 -1
- package/esm/dev-server/dependency-graph.mjs.map +1 -1
- package/esm/dev-server/dev-logger.mjs +7 -5
- package/esm/dev-server/dev-logger.mjs.map +1 -1
- package/esm/dev-server/file-event-handler.mjs.map +1 -1
- package/esm/dev-server/files-orchestrator.mjs +1 -1
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/dev-server/layer-executor.mjs.map +1 -1
- package/esm/dev-server/loader/build-transpile-init.mjs.map +1 -1
- package/esm/dev-server/loader/load-hook.mjs.map +1 -1
- package/esm/dev-server/loader/register-loader.mjs.map +1 -1
- package/esm/dev-server/loader/resolve-hook.mjs.map +1 -1
- package/esm/dev-server/loader/transpile-cache.mjs.map +1 -1
- package/esm/dev-server/module-loader.mjs.map +1 -1
- package/esm/dev-server/parse-imports.mjs +22 -8
- package/esm/dev-server/parse-imports.mjs.map +1 -1
- package/esm/dev-server/type-generator.mjs.map +1 -1
- package/esm/dev-server/types.d.mts.map +1 -1
- package/esm/dev-server/utils.mjs.map +1 -1
- package/esm/encryption/encrypt.mjs +1 -0
- package/esm/encryption/encrypt.mjs.map +1 -1
- package/esm/errors/container-key-missing-error.mjs +28 -0
- package/esm/errors/container-key-missing-error.mjs.map +1 -0
- package/esm/errors/unknown-locale-error.mjs +28 -0
- package/esm/errors/unknown-locale-error.mjs.map +1 -0
- package/esm/generations/add-command.action.mjs +8 -2
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/generations/features/access.feature.mjs.map +1 -1
- package/esm/generations/features/ai-anthropic.feature.mjs.map +1 -1
- package/esm/generations/features/ai-bedrock.feature.mjs.map +1 -1
- package/esm/generations/features/ai-google.feature.mjs.map +1 -1
- package/esm/generations/features/ai-ollama.feature.mjs.map +1 -1
- package/esm/generations/features/ai-openai.feature.mjs.map +1 -1
- package/esm/generations/features/ai-panoptic.feature.mjs.map +1 -1
- package/esm/generations/features/ai-tools.feature.mjs.map +1 -1
- package/esm/generations/features/ai-workspace.feature.mjs.map +1 -1
- package/esm/generations/features/ai.feature.mjs.map +1 -1
- package/esm/generations/features/herald.feature.mjs.map +1 -1
- package/esm/generations/features/notifications.feature.mjs.map +1 -1
- package/esm/generations/features/scheduler.feature.mjs.map +1 -1
- package/esm/generations/features/shared/patch-tsconfig-include.mjs.map +1 -1
- package/esm/generations/features/shared/relocate-conflicting-home-route.mjs +6 -1
- package/esm/generations/features/shared/relocate-conflicting-home-route.mjs.map +1 -1
- package/esm/generations/features/tailwind.feature.mjs.map +1 -1
- package/esm/generations/features/types.mjs.map +1 -1
- package/esm/generations/features/web.feature.mjs.map +1 -1
- package/esm/http/context/request-memo.mjs.map +1 -1
- package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
- package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
- package/esm/http/middleware/concurrency-limit.middleware.mjs.map +1 -1
- package/esm/http/middleware/idempotency.middleware.d.mts.map +1 -1
- package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
- package/esm/http/middleware/maintenance.middleware.mjs +1 -2
- package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
- package/esm/http/middleware/max-body-size.middleware.mjs.map +1 -1
- package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
- package/esm/http/middleware/utils/cidr-match.d.mts.map +1 -1
- package/esm/http/middleware/utils/cidr-match.mjs +1 -0
- package/esm/http/middleware/utils/cidr-match.mjs.map +1 -1
- package/esm/http/port-preflight.d.mts.map +1 -1
- package/esm/http/port-preflight.mjs.map +1 -1
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs +16 -9
- package/esm/http/request.mjs.map +1 -1
- package/esm/http/response.d.mts +38 -0
- package/esm/http/response.d.mts.map +1 -1
- package/esm/http/response.mjs +47 -0
- package/esm/http/response.mjs.map +1 -1
- package/esm/http/server.d.mts.map +1 -1
- package/esm/http/server.mjs.map +1 -1
- package/esm/http/types.d.mts.map +1 -1
- package/esm/image/image.d.mts.map +1 -1
- package/esm/image/image.mjs.map +1 -1
- package/esm/mail/send-mail.mjs.map +1 -1
- package/esm/production/build-contributions.mjs.map +1 -1
- package/esm/production/bundle-framework-dependencies.mjs +152 -0
- package/esm/production/bundle-framework-dependencies.mjs.map +1 -0
- package/esm/production/production-builder.mjs +30 -3
- package/esm/production/production-builder.mjs.map +1 -1
- package/esm/production/production-supervisor.mjs.map +1 -1
- package/esm/production/tsconfig-path-aliases.mjs +99 -0
- package/esm/production/tsconfig-path-aliases.mjs.map +1 -0
- package/esm/react/index.d.mts.map +1 -1
- package/esm/react/index.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/filter-applicator.mjs +4 -2
- package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
- package/esm/repositories/contracts/query-builder.contract.d.mts.map +1 -1
- package/esm/repositories/contracts/types.d.mts.map +1 -1
- package/esm/resource/resource-field-builder.d.mts.map +1 -1
- package/esm/resource/resource-field-builder.mjs.map +1 -1
- package/esm/resource/types.d.mts.map +1 -1
- package/esm/router/positional-handler-diagnostics.d.mts.map +1 -1
- package/esm/router/positional-handler-diagnostics.mjs +9 -3
- package/esm/router/positional-handler-diagnostics.mjs.map +1 -1
- package/esm/router/route-registry.mjs +1 -1
- package/esm/router/route-registry.mjs.map +1 -1
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs +1 -2
- package/esm/router/router.mjs.map +1 -1
- package/esm/router/types.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
- package/esm/storage/scoped-storage.d.mts.map +1 -1
- package/esm/storage/scoped-storage.mjs +1 -0
- package/esm/storage/scoped-storage.mjs.map +1 -1
- package/esm/storage/storage.d.mts.map +1 -1
- package/esm/storage/storage.mjs +6 -2
- package/esm/storage/storage.mjs.map +1 -1
- package/esm/storage/types.d.mts.map +1 -1
- package/esm/storage/utils/contain-path.mjs.map +1 -1
- package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
- package/esm/storage/utils/safe-fetch.mjs +6 -1
- package/esm/storage/utils/safe-fetch.mjs.map +1 -1
- package/esm/tests/start-http-development-server.d.mts.map +1 -1
- package/esm/tests/start-http-development-server.mjs.map +1 -1
- package/esm/tests/test-lifecycle-state.mjs.map +1 -1
- package/esm/tests/test-setup-timeout.mjs.map +1 -1
- package/esm/tests/vitest-setup.d.mts.map +1 -1
- package/esm/tests/vitest-setup.mjs.map +1 -1
- package/esm/use-cases/use-cases-registry.d.mts.map +1 -1
- package/esm/use-cases/use-cases-registry.mjs.map +1 -1
- package/esm/utils/app-log.mjs.map +1 -1
- package/esm/utils/queue.mjs.map +1 -1
- package/esm/utils/sleep.mjs.map +1 -1
- package/esm/utils/version-compare.d.mts.map +1 -1
- package/esm/utils/version-compare.mjs +12 -4
- package/esm/utils/version-compare.mjs.map +1 -1
- package/esm/validation/plugins/database-plugin.mjs.map +1 -1
- package/esm/vite/lower-stage3-decorators.mjs +1 -0
- package/esm/vite/lower-stage3-decorators.mjs.map +1 -1
- package/package.json +12 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration.generator.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/generate/generators/migration.generator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport path from \"node:path\";\r\nimport { appPath } from \"../../../../utils\";\r\nimport type { CommandActionData } from \"../../../../commands/types\";\r\nimport { migrationAlterStub, migrationStub } from \"../templates/stubs\";\r\nimport { parseColumnDsl } from \"./column-dsl-parser\";\r\nimport { parseName } from \"../utils/name-parser\";\r\nimport { ensureDirectoryAsync, putFileAsync, setDryRun } from \"../utils/writer\";\r\n\r\n/**\r\n * Generate a migration file for a model\r\n */\r\n/**\r\n * Create a migration file for a model\r\n */\r\nexport async function createMigrationFile(moduleName: string
|
|
1
|
+
{"version":3,"file":"migration.generator.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/generate/generators/migration.generator.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport path from \"node:path\";\r\nimport { appPath } from \"../../../../utils\";\r\nimport type { CommandActionData } from \"../../../../commands/types\";\r\nimport { migrationAlterStub, migrationStub } from \"../templates/stubs\";\r\nimport { parseColumnDsl } from \"./column-dsl-parser\";\r\nimport { parseName } from \"../utils/name-parser\";\r\nimport { ensureDirectoryAsync, putFileAsync, setDryRun } from \"../utils/writer\";\r\n\r\n/**\r\n * Generate a migration file for a model\r\n */\r\n/**\r\n * Create a migration file for a model\r\n */\r\nexport async function createMigrationFile(\r\n moduleName: string,\r\n entityName: string,\r\n options: any = {},\r\n) {\r\n const entity = parseName(entityName);\r\n\r\n // Generate timestamp: MM-DD-YYYY_HH-MM-SS\r\n const now = new Date();\r\n const timestamp = `${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}-${now.getFullYear()}_${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}-${String(now.getSeconds()).padStart(2, \"0\")}`;\r\n\r\n const migrationFileName = `${timestamp}-${entity.kebab}.migration.ts`;\r\n const migrationsPath = path.join(appPath(), moduleName, \"models\", entity.kebab, \"migrations\");\r\n\r\n // Ensure migrations directory exists\r\n await ensureDirectoryAsync(migrationsPath);\r\n\r\n const addParams = options.add as string;\r\n const dropParams = options.drop as string;\r\n const renameParams = options.rename as string;\r\n const timestamps = options.timestamps !== \"false\" && options.timestamps !== false;\r\n\r\n let migrationContent = \"\";\r\n\r\n if (addParams || dropParams || renameParams) {\r\n // Generate alter stub\r\n const parsedAdd = parseColumnDsl(addParams || \"\");\r\n const helpersSet = new Set<string>();\r\n\r\n const addLines = parsedAdd.map((col) => {\r\n helpersSet.add(col.helper);\r\n return ` ${col.name}: ${col.helper}()${col.modifiers.join(\"\")},`;\r\n });\r\n\r\n let formattedDrop: string | undefined = undefined;\r\n if (dropParams) {\r\n formattedDrop = JSON.stringify(dropParams.split(\",\").map((s) => s.trim()));\r\n }\r\n\r\n let formattedRename: string | undefined = undefined;\r\n if (renameParams) {\r\n const obj: Record<string, string> = {};\r\n renameParams\r\n .split(\",\")\r\n .map((s) => s.trim())\r\n .forEach((p) => {\r\n const [oldN, newN] = p.split(\":\").map((s) => s.trim());\r\n if (oldN && newN) obj[oldN] = newN;\r\n });\r\n formattedRename = JSON.stringify(obj, null, 2).replace(/\\n/g, \"\\n \");\r\n }\r\n\r\n migrationContent = migrationAlterStub(entity, {\r\n add: addLines.length > 0 ? addLines.join(\"\\n\") : undefined,\r\n drop: formattedDrop,\r\n rename: formattedRename,\r\n imports: Array.from(helpersSet),\r\n });\r\n } else {\r\n // Generate create stub\r\n migrationContent = migrationStub(entity, {\r\n timestamps,\r\n });\r\n }\r\n\r\n // Create migration file\r\n const migrationFilePath = path.join(migrationsPath, migrationFileName);\r\n await putFileAsync(migrationFilePath, migrationContent);\r\n\r\n return migrationFilePath;\r\n}\r\n\r\n/**\r\n * Generate a migration file for a model\r\n */\r\nexport async function generateMigration(data: CommandActionData) {\r\n const modelPath = data.args[0] as string;\r\n\r\n if (!modelPath) {\r\n console.log(colors.red(\"Error: Model path is required\"));\r\n console.log(colors.gray(\"Usage: warlock gen.migration <model-path>\"));\r\n console.log(colors.gray(\"Example: warlock gen.migration products/product\"));\r\n return;\r\n }\r\n\r\n // Parse model path (e.g., \"products/product\")\r\n const [moduleName, entityName] = modelPath.split(\"/\");\r\n\r\n if (!moduleName || !entityName) {\r\n console.log(colors.red(\"Error: Invalid model path format. Expected: <module>/<entity>\"));\r\n console.log(colors.gray(\"Example: warlock gen.migration products/product\"));\r\n return;\r\n }\r\n\r\n setDryRun(Boolean(data.options.dryRun));\r\n\r\n const migrationFilePath = await createMigrationFile(moduleName, entityName, data.options);\r\n\r\n console.log(\r\n colors.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;CAExF,QAAQ,IACN,OAAO,KAAK,oCAAoC,KAAK,SAAS,QAAQ,GAAG,iBAAiB,GAAG,CAC/F;AACF"}
|
|
@@ -111,12 +111,12 @@ function printRoutesTable(rows) {
|
|
|
111
111
|
return;
|
|
112
112
|
}
|
|
113
113
|
const widths = columnWidths(rows);
|
|
114
|
-
const headerLine = COLUMNS.map((column, index) => column.header.padEnd(widths[index])).join(GAP).trimEnd();
|
|
114
|
+
const headerLine = COLUMNS.map((column, index) => column.header.padEnd(widths[index] ?? 0)).join(GAP).trimEnd();
|
|
115
115
|
console.log(colors.bold(headerLine));
|
|
116
116
|
for (const row of rows) {
|
|
117
117
|
const cells = COLUMNS.map((column, index) => {
|
|
118
|
-
if (column.key === "method") return colorizeMethodCell(row.method, widths[index]);
|
|
119
|
-
return cellText(row, column.key).padEnd(widths[index]);
|
|
118
|
+
if (column.key === "method") return colorizeMethodCell(row.method, widths[index] ?? 0);
|
|
119
|
+
return cellText(row, column.key).padEnd(widths[index] ?? 0);
|
|
120
120
|
});
|
|
121
121
|
console.log(cells.join(GAP).trimEnd());
|
|
122
122
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format-routes-table.mjs","names":[],"sources":["../../../../../../../../../core/src/cli/commands/routes/format-routes-table.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { methodRank, type RouteRow } from \"./route-row\";\n\n/** The columns rendered, in order, with their header labels. */\nconst COLUMNS = [\n { key: \"method\", header: \"METHOD\" },\n { key: \"path\", header: \"PATH\" },\n { key: \"name\", header: \"NAME\" },\n { key: \"action\", header: \"ACTION\" },\n { key: \"middleware\", header: \"MW\" },\n { key: \"source\", header: \"SOURCE\" },\n] as const;\n\ntype ColumnKey = (typeof COLUMNS)[number][\"key\"];\n\n/** Two spaces between columns. */\nconst GAP = \" \";\n\n/** Shown for an empty string cell so the column doesn't read as a gap. */\nconst EMPTY_CELL = \"—\";\n\n/**\n * The plain (uncolored) text of one cell. Numbers render as-is; an empty string\n * renders as {@link EMPTY_CELL}. This is the single source of truth for both\n * the width math and the rendered text, so colored and uncolored output stay\n * aligned.\n *\n * @param row - The row\n * @param key - The column key\n * @returns The cell's printable text\n */\nfunction cellText(row: RouteRow, key: ColumnKey): string {\n if (key === \"middleware\") return String(row.middleware);\n\n const value = row[key] as string;\n\n return value.length > 0 ? value : EMPTY_CELL;\n}\n\n/**\n * Per-column display width: the longest of the header and every cell.\n *\n * @param rows - The rows to measure\n * @returns One width per column, in column order\n */\nfunction columnWidths(rows: RouteRow[]): number[] {\n return COLUMNS.map((column) =>\n Math.max(column.header.length, ...rows.map((row) => cellText(row, column.key).length)),\n );\n}\n\n/**\n * Build a one-line, human-readable summary: the total plus a per-method\n * breakdown ordered by {@link methodRank}, e.g.\n * `42 routes (38 GET · 2 POST · 1 PUT · 1 DELETE)`.\n *\n * @param rows - The rows being summarized\n * @returns The summary line\n */\nexport function routesSummary(rows: RouteRow[]): string {\n const noun = rows.length === 1 ? \"route\" : \"routes\";\n\n if (rows.length === 0) return `0 ${noun}`;\n\n const counts = new Map<string, number>();\n\n for (const row of rows) {\n counts.set(row.method, (counts.get(row.method) ?? 0) + 1);\n }\n\n const breakdown = [...counts.entries()]\n .sort(([a], [b]) => methodRank(a) - methodRank(b))\n .map(([method, count]) => `${count} ${method}`)\n .join(\" · \");\n\n return `${rows.length} ${noun} (${breakdown})`;\n}\n\n/**\n * Render the routes table as an ordered list of plain (uncolored) lines:\n * a header row, one row per route, a blank line, then the summary. Returned as\n * strings (not printed) so the layout is unit-testable without ANSI noise.\n *\n * @param rows - The rows to render (already filtered/sorted by the caller)\n * @returns The lines to print, top to bottom\n */\nexport function formatRoutesTableLines(rows: RouteRow[]): string[] {\n if (rows.length === 0) {\n return [\"No routes registered.\"];\n }\n\n const widths = columnWidths(rows);\n\n const renderRow = (cells: string[]) =>\n cells.map((text, index) => text.padEnd(widths[index])).join(GAP).trimEnd();\n\n const lines = [renderRow(COLUMNS.map((column) => column.header))];\n\n for (const row of rows) {\n lines.push(renderRow(COLUMNS.map((column) => cellText(row, column.key))));\n }\n\n lines.push(\"\");\n lines.push(routesSummary(rows));\n\n return lines;\n}\n\n/** Per-verb color for the METHOD column. Unknown verbs fall back to white. */\nconst METHOD_COLOR: Record<string, (input: string) => string> = {\n GET: colors.green,\n POST: colors.blue,\n PUT: colors.yellow,\n PATCH: colors.yellow,\n DELETE: colors.red,\n OPTIONS: colors.gray,\n HEAD: colors.gray,\n ALL: colors.magenta,\n};\n\n/**\n * Colorize the method label, then right-pad with plain spaces so column\n * alignment is computed from the visible width, not the ANSI-coded length.\n *\n * @param method - The uppercased HTTP verb\n * @param width - The METHOD column width\n * @returns The colored, padded cell\n */\nfunction colorizeMethodCell(method: string, width: number): string {\n const colorize = METHOD_COLOR[method] ?? colors.white;\n\n return colorize(method) + \" \".repeat(Math.max(0, width - method.length));\n}\n\n/**\n * Print the routes table to stdout with a bold header, verb-colored METHOD\n * column, and a dimmed summary. The empty case prints a single yellow notice\n * (a booted app with zero routes usually means a route module failed to load).\n *\n * Thin presentation wrapper over {@link formatRoutesTableLines} /\n * {@link routesSummary} — those stay the source of truth for layout.\n *\n * @param rows - The rows to print (already filtered/sorted by the caller)\n */\nexport function printRoutesTable(rows: RouteRow[]): void {\n if (rows.length === 0) {\n console.log(colors.yellow(\"No routes registered — did a route module fail to load?\"));\n return;\n }\n\n const widths = columnWidths(rows);\n\n const headerLine = COLUMNS.map((column, index) => column.header.padEnd(widths[index]))\n .join(GAP)\n .trimEnd();\n\n console.log(colors.bold(headerLine));\n\n for (const row of rows) {\n const cells = COLUMNS.map((column, index) => {\n if (column.key === \"method\") {\n return colorizeMethodCell(row.method, widths[index]);\n }\n\n return cellText(row, column.key).padEnd(widths[index]);\n });\n\n console.log(cells.join(GAP).trimEnd());\n }\n\n console.log(\"\");\n console.log(colors.gray(routesSummary(rows)));\n}\n"],"mappings":";;;;;AAIA,MAAM,UAAU;CACd;EAAE,KAAK;EAAU,QAAQ;CAAS;CAClC;EAAE,KAAK;EAAQ,QAAQ;CAAO;CAC9B;EAAE,KAAK;EAAQ,QAAQ;CAAO;CAC9B;EAAE,KAAK;EAAU,QAAQ;CAAS;CAClC;EAAE,KAAK;EAAc,QAAQ;CAAK;CAClC;EAAE,KAAK;EAAU,QAAQ;CAAS;AACpC;;AAKA,MAAM,MAAM;;AAGZ,MAAM,aAAa;;;;;;;;;;;AAYnB,SAAS,SAAS,KAAe,KAAwB;CACvD,IAAI,QAAQ,cAAc,OAAO,OAAO,IAAI,UAAU;CAEtD,MAAM,QAAQ,IAAI;CAElB,OAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;;;;;;;AAQA,SAAS,aAAa,MAA4B;CAChD,OAAO,QAAQ,KAAK,WAClB,KAAK,IAAI,OAAO,OAAO,QAAQ,GAAG,KAAK,KAAK,QAAQ,SAAS,KAAK,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,CACvF;AACF;;;;;;;;;AAUA,SAAgB,cAAc,MAA0B;CACtD,MAAM,OAAO,KAAK,WAAW,IAAI,UAAU;CAE3C,IAAI,KAAK,WAAW,GAAG,OAAO,KAAK;CAEnC,MAAM,yBAAS,IAAI,IAAoB;CAEvC,KAAK,MAAM,OAAO,MAChB,OAAO,IAAI,IAAI,SAAS,OAAO,IAAI,IAAI,MAAM,KAAK,KAAK,CAAC;CAG1D,MAAM,YAAY,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CACpC,MAAM,CAAC,IAAI,CAAC,OAAO,WAAW,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CACjD,KAAK,CAAC,QAAQ,WAAW,GAAG,MAAM,GAAG,QAAQ,CAAC,CAC9C,KAAK,KAAK;CAEb,OAAO,GAAG,KAAK,OAAO,GAAG,KAAK,IAAI,UAAU;AAC9C;;
|
|
1
|
+
{"version":3,"file":"format-routes-table.mjs","names":[],"sources":["../../../../../../../../../core/src/cli/commands/routes/format-routes-table.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { methodRank, type RouteRow } from \"./route-row\";\n\n/** The columns rendered, in order, with their header labels. */\nconst COLUMNS = [\n { key: \"method\", header: \"METHOD\" },\n { key: \"path\", header: \"PATH\" },\n { key: \"name\", header: \"NAME\" },\n { key: \"action\", header: \"ACTION\" },\n { key: \"middleware\", header: \"MW\" },\n { key: \"source\", header: \"SOURCE\" },\n] as const;\n\ntype ColumnKey = (typeof COLUMNS)[number][\"key\"];\n\n/** Two spaces between columns. */\nconst GAP = \" \";\n\n/** Shown for an empty string cell so the column doesn't read as a gap. */\nconst EMPTY_CELL = \"—\";\n\n/**\n * The plain (uncolored) text of one cell. Numbers render as-is; an empty string\n * renders as {@link EMPTY_CELL}. This is the single source of truth for both\n * the width math and the rendered text, so colored and uncolored output stay\n * aligned.\n *\n * @param row - The row\n * @param key - The column key\n * @returns The cell's printable text\n */\nfunction cellText(row: RouteRow, key: ColumnKey): string {\n if (key === \"middleware\") return String(row.middleware);\n\n const value = row[key] as string;\n\n return value.length > 0 ? value : EMPTY_CELL;\n}\n\n/**\n * Per-column display width: the longest of the header and every cell.\n *\n * @param rows - The rows to measure\n * @returns One width per column, in column order\n */\nfunction columnWidths(rows: RouteRow[]): number[] {\n return COLUMNS.map((column) =>\n Math.max(column.header.length, ...rows.map((row) => cellText(row, column.key).length)),\n );\n}\n\n/**\n * Build a one-line, human-readable summary: the total plus a per-method\n * breakdown ordered by {@link methodRank}, e.g.\n * `42 routes (38 GET · 2 POST · 1 PUT · 1 DELETE)`.\n *\n * @param rows - The rows being summarized\n * @returns The summary line\n */\nexport function routesSummary(rows: RouteRow[]): string {\n const noun = rows.length === 1 ? \"route\" : \"routes\";\n\n if (rows.length === 0) return `0 ${noun}`;\n\n const counts = new Map<string, number>();\n\n for (const row of rows) {\n counts.set(row.method, (counts.get(row.method) ?? 0) + 1);\n }\n\n const breakdown = [...counts.entries()]\n .sort(([a], [b]) => methodRank(a) - methodRank(b))\n .map(([method, count]) => `${count} ${method}`)\n .join(\" · \");\n\n return `${rows.length} ${noun} (${breakdown})`;\n}\n\n/**\n * Render the routes table as an ordered list of plain (uncolored) lines:\n * a header row, one row per route, a blank line, then the summary. Returned as\n * strings (not printed) so the layout is unit-testable without ANSI noise.\n *\n * @param rows - The rows to render (already filtered/sorted by the caller)\n * @returns The lines to print, top to bottom\n */\nexport function formatRoutesTableLines(rows: RouteRow[]): string[] {\n if (rows.length === 0) {\n return [\"No routes registered.\"];\n }\n\n const widths = columnWidths(rows);\n\n // `widths` is built from these same columns, so every index resolves. `?? 0`\n // rather than an assertion: 0 is padEnd's no-op, so an unreadable width\n // produces an UNALIGNED table rather than a crash — this renders `warlock\n // routes`, and a table that throws tells the operator nothing about routes.\n const renderRow = (cells: string[]) =>\n cells\n .map((text, index) => text.padEnd(widths[index] ?? 0))\n .join(GAP)\n .trimEnd();\n\n const lines = [renderRow(COLUMNS.map((column) => column.header))];\n\n for (const row of rows) {\n lines.push(renderRow(COLUMNS.map((column) => cellText(row, column.key))));\n }\n\n lines.push(\"\");\n lines.push(routesSummary(rows));\n\n return lines;\n}\n\n/** Per-verb color for the METHOD column. Unknown verbs fall back to white. */\nconst METHOD_COLOR: Record<string, (input: string) => string> = {\n GET: colors.green,\n POST: colors.blue,\n PUT: colors.yellow,\n PATCH: colors.yellow,\n DELETE: colors.red,\n OPTIONS: colors.gray,\n HEAD: colors.gray,\n ALL: colors.magenta,\n};\n\n/**\n * Colorize the method label, then right-pad with plain spaces so column\n * alignment is computed from the visible width, not the ANSI-coded length.\n *\n * @param method - The uppercased HTTP verb\n * @param width - The METHOD column width\n * @returns The colored, padded cell\n */\nfunction colorizeMethodCell(method: string, width: number): string {\n const colorize = METHOD_COLOR[method] ?? colors.white;\n\n return colorize(method) + \" \".repeat(Math.max(0, width - method.length));\n}\n\n/**\n * Print the routes table to stdout with a bold header, verb-colored METHOD\n * column, and a dimmed summary. The empty case prints a single yellow notice\n * (a booted app with zero routes usually means a route module failed to load).\n *\n * Thin presentation wrapper over {@link formatRoutesTableLines} /\n * {@link routesSummary} — those stay the source of truth for layout.\n *\n * @param rows - The rows to print (already filtered/sorted by the caller)\n */\nexport function printRoutesTable(rows: RouteRow[]): void {\n if (rows.length === 0) {\n console.log(colors.yellow(\"No routes registered — did a route module fail to load?\"));\n return;\n }\n\n const widths = columnWidths(rows);\n\n const headerLine = COLUMNS.map((column, index) => column.header.padEnd(widths[index] ?? 0))\n .join(GAP)\n .trimEnd();\n\n console.log(colors.bold(headerLine));\n\n for (const row of rows) {\n const cells = COLUMNS.map((column, index) => {\n if (column.key === \"method\") {\n return colorizeMethodCell(row.method, widths[index] ?? 0);\n }\n\n return cellText(row, column.key).padEnd(widths[index] ?? 0);\n });\n\n console.log(cells.join(GAP).trimEnd());\n }\n\n console.log(\"\");\n console.log(colors.gray(routesSummary(rows)));\n}\n"],"mappings":";;;;;AAIA,MAAM,UAAU;CACd;EAAE,KAAK;EAAU,QAAQ;CAAS;CAClC;EAAE,KAAK;EAAQ,QAAQ;CAAO;CAC9B;EAAE,KAAK;EAAQ,QAAQ;CAAO;CAC9B;EAAE,KAAK;EAAU,QAAQ;CAAS;CAClC;EAAE,KAAK;EAAc,QAAQ;CAAK;CAClC;EAAE,KAAK;EAAU,QAAQ;CAAS;AACpC;;AAKA,MAAM,MAAM;;AAGZ,MAAM,aAAa;;;;;;;;;;;AAYnB,SAAS,SAAS,KAAe,KAAwB;CACvD,IAAI,QAAQ,cAAc,OAAO,OAAO,IAAI,UAAU;CAEtD,MAAM,QAAQ,IAAI;CAElB,OAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;;;;;;;AAQA,SAAS,aAAa,MAA4B;CAChD,OAAO,QAAQ,KAAK,WAClB,KAAK,IAAI,OAAO,OAAO,QAAQ,GAAG,KAAK,KAAK,QAAQ,SAAS,KAAK,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,CACvF;AACF;;;;;;;;;AAUA,SAAgB,cAAc,MAA0B;CACtD,MAAM,OAAO,KAAK,WAAW,IAAI,UAAU;CAE3C,IAA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I,QAAQ,OAAO,UAAU,CAAC;GAG1D,OAAO,SAAS,KAAK,OAAO,GAAG,CAAC,CAAC,OAAO,OAAO,UAAU,CAAC;EAC5D,CAAC;EAED,QAAQ,IAAI,MAAM,KAAK,GAAG,CAAC,CAAC,QAAQ,CAAC;CACvC;CAEA,QAAQ,IAAI,EAAE;CACd,QAAQ,IAAI,OAAO,KAAK,cAAc,IAAI,CAAC,CAAC;AAC9C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"route-row.mjs","names":[],"sources":["../../../../../../../../../core/src/cli/commands/routes/route-row.ts"],"sourcesContent":["import type { Route } from \"../../../router/types\";\n\n/**\n * A single registered route, normalized to the flat, display-ready shape the\n * `warlock routes` table (and its `--json` output) render. Kept separate from\n * the live {@link Route} so the formatter and filters never touch the handler\n * function, validation object, or Fastify server options — only printable\n * scalars.\n */\nexport type RouteRow = {\n /** Uppercased HTTP verb (`\"all\"` → `\"ALL\"`). */\n method: string;\n\n /** Full request path (prefix already folded in by the router). */\n path: string;\n\n /** Route name, or `\"\"` when the route was registered without one. */\n name: string;\n\n /** Handler/controller-action label — the handler function name, or `\"anonymous\"`. */\n action: string;\n\n /** Number of middleware attached to the route. */\n middleware: number;\n\n /** Relative source file the route was registered from, or `\"\"`. */\n source: string;\n};\n\n/** Filters accepted by `warlock routes`, each optional and additive (AND-ed). */\nexport type RouteFilter = {\n /** Exact HTTP method (case-insensitive). */\n method?: string;\n\n /** Case-insensitive substring matched against the path. */\n path?: string;\n\n /** Case-insensitive substring matched against the route name. */\n name?: string;\n};\n\n/**\n * Display order of HTTP methods — used to rank rows within a path and to order\n * the per-method breakdown in the summary line.\n */\nexport const METHOD_ORDER = [\
|
|
1
|
+
{"version":3,"file":"route-row.mjs","names":[],"sources":["../../../../../../../../../core/src/cli/commands/routes/route-row.ts"],"sourcesContent":["import type { Route } from \"../../../router/types\";\n\n/**\n * A single registered route, normalized to the flat, display-ready shape the\n * `warlock routes` table (and its `--json` output) render. Kept separate from\n * the live {@link Route} so the formatter and filters never touch the handler\n * function, validation object, or Fastify server options — only printable\n * scalars.\n */\nexport type RouteRow = {\n /** Uppercased HTTP verb (`\"all\"` → `\"ALL\"`). */\n method: string;\n\n /** Full request path (prefix already folded in by the router). */\n path: string;\n\n /** Route name, or `\"\"` when the route was registered without one. */\n name: string;\n\n /** Handler/controller-action label — the handler function name, or `\"anonymous\"`. */\n action: string;\n\n /** Number of middleware attached to the route. */\n middleware: number;\n\n /** Relative source file the route was registered from, or `\"\"`. */\n source: string;\n};\n\n/** Filters accepted by `warlock routes`, each optional and additive (AND-ed). */\nexport type RouteFilter = {\n /** Exact HTTP method (case-insensitive). */\n method?: string;\n\n /** Case-insensitive substring matched against the path. */\n path?: string;\n\n /** Case-insensitive substring matched against the route name. */\n name?: string;\n};\n\n/**\n * Display order of HTTP methods — used to rank rows within a path and to order\n * the per-method breakdown in the summary line.\n */\nexport const METHOD_ORDER = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"OPTIONS\", \"HEAD\", \"ALL\"];\n\n/**\n * Rank of a method for sorting. Unknown methods sort last (stable among\n * themselves).\n *\n * @param method - Uppercased HTTP verb\n * @returns The sort index\n */\nexport function methodRank(method: string): number {\n const index = METHOD_ORDER.indexOf(method);\n return index === -1 ? METHOD_ORDER.length : index;\n}\n\n/**\n * Derive the handler/controller-action label for a route. Uses the handler\n * function's name, stripping the `bound ` prefix that `Function.prototype.bind`\n * prepends, and falls back to `\"anonymous\"` for an unnamed handler.\n *\n * @param route - The route to label\n * @returns A printable action label\n */\nfunction routeAction(route: Route): string {\n const handler = route.handler as unknown;\n\n if (typeof handler !== \"function\") return \"anonymous\";\n\n const name = handler.name?.replace(/^bound /, \"\").trim();\n\n return name ? name : \"anonymous\";\n}\n\n/**\n * Normalize a live {@link Route} into a printable {@link RouteRow}.\n *\n * @param route - The registered route\n * @returns The display-ready row\n */\nexport function toRouteRow(route: Route): RouteRow {\n return {\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name ?? \"\",\n action: routeAction(route),\n middleware: route.middleware?.length ?? 0,\n source: route.sourceFile ?? \"\",\n };\n}\n\n/**\n * Apply the `--method` / `--path` / `--name` filters to a set of rows. An\n * omitted filter matches everything; provided filters are AND-ed.\n *\n * @param rows - The rows to filter\n * @param filter - The active filters\n * @returns The matching rows (a new array)\n */\nexport function filterRouteRows(rows: RouteRow[], filter: RouteFilter): RouteRow[] {\n const method = filter.method?.toUpperCase();\n const path = filter.path?.toLowerCase();\n const name = filter.name?.toLowerCase();\n\n return rows.filter((row) => {\n if (method && row.method !== method) return false;\n if (path && !row.path.toLowerCase().includes(path)) return false;\n if (name && !row.name.toLowerCase().includes(name)) return false;\n return true;\n });\n}\n\n/**\n * Sort rows by path (ascending), then by HTTP-method order within a path, so\n * every verb of one resource lists together in a predictable sequence.\n *\n * @param rows - The rows to sort\n * @returns A new, sorted array\n */\nexport function sortRouteRows(rows: RouteRow[]): RouteRow[] {\n return [...rows].sort((a, b) => {\n if (a.path !== b.path) return a.path < b.path ? -1 : 1;\n return methodRank(a.method) - methodRank(b.method);\n });\n}\n"],"mappings":";;;;;AA6CA,MAAa,eAAe;CAAC;CAAO;CAAQ;CAAO;CAAS;CAAU;CAAW;CAAQ;AAAK;;;;;;;;AAS9F,SAAgB,WAAW,QAAwB;CACjD,MAAM,QAAQ,aAAa,QAAQ,MAAM;CACzC,OAAO,UAAU,KAAK,aAAa,SAAS;AAC9C;;;;;;;;;AAUA,SAAS,YAAY,OAAsB;CACzC,MAAM,UAAU,MAAM;CAEtB,IAAI,OAAO,YAAY,YAAY,OAAO;CAE1C,MAAM,OAAO,QAAQ,MAAM,QAAQ,WAAW,EAAE,CAAC,CAAC,KAAK;CAEvD,OAAO,OAAO,OAAO;AACvB;;;;;;;AAQA,SAAgB,WAAW,OAAwB;CACjD,OAAO;EACL,QAAQ,MAAM,OAAO,YAAY;EACjC,MAAM,MAAM;EACZ,MAAM,MAAM,QAAQ;EACpB,QAAQ,YAAY,KAAK;EACzB,YAAY,MAAM,YAAY,UAAU;EACxC,QAAQ,MAAM,cAAc;CAC9B;AACF;;;;;;;;;AAUA,SAAgB,gBAAgB,MAAkB,QAAiC;CACjF,MAAM,SAAS,OAAO,QAAQ,YAAY;CAC1C,MAAM,OAAO,OAAO,MAAM,YAAY;CACtC,MAAM,OAAO,OAAO,MAAM,YAAY;CAEtC,OAAO,KAAK,QAAQ,QAAQ;EAC1B,IAAI,UAAU,IAAI,WAAW,QAAQ,OAAO;EAC5C,IAAI,QAAQ,CAAC,IAAI,KAAK,YAAY,CAAC,CAAC,SAAS,IAAI,GAAG,OAAO;EAC3D,IAAI,QAAQ,CAAC,IAAI,KAAK,YAAY,CAAC,CAAC,SAAS,IAAI,GAAG,OAAO;EAC3D,OAAO;CACT,CAAC;AACH;;;;;;;;AASA,SAAgB,cAAc,MAA8B;CAC1D,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,MAAM,GAAG,MAAM;EAC9B,IAAI,EAAE,SAAS,EAAE,MAAM,OAAO,EAAE,OAAO,EAAE,OAAO,KAAK;EACrD,OAAO,WAAW,EAAE,MAAM,IAAI,WAAW,EAAE,MAAM;CACnD,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.command.mjs","names":[],"sources":["../../../../../../../../core/src/cli/commands/routes.command.ts"],"sourcesContent":["import { command } from \"../../commands/cli-command\";\r\nimport { routesCommandAction } from \"./routes/routes-command.action\";\nimport { routesDiffCommandAction } from \"./routes/routes-diff.action\";\n\r\n/**\r\n * `warlock routes` — list every registered HTTP route as a table (a read-only\r\n * sibling of `warlock doctor`). Filter with `--method` / `--path` / `--name`,\r\n * or emit the normalized rows as JSON with `--json`.\r\n *\r\n * Preload plan: load config + bootstrap app code so route modules register on\r\n * the router singleton, but start NO connectors — listing routes must never\r\n * open a database/cache/socket connection. Because the route-module loader is\r\n * fail-loud, a route file that throws on import surfaces here instead of being\r\n * silently omitted from the table.\r\n */\r\nexport const routesCommand = command({\n name: \"routes\",\r\n description:\r\n \"List the registered HTTP routes as a table (read-only); filter with --method / --path / --name, or emit JSON with --json\",\r\n action: routesCommandAction,\r\n preload: {\r\n config: true,\r\n env: true,\r\n bootstrap: true,\r\n },\r\n options: [\r\n {\r\n text: \"--method, -m\",\r\n description: \"Filter by HTTP method (case-insensitive, e.g. GET, POST)\",\r\n type: \"string\",\r\n },\r\n {\r\n text: \"--path, -p\",\r\n description: \"Filter by a case-insensitive path substring\",\r\n type: \"string\",\r\n },\r\n {\r\n text: \"--name, -n\",\r\n description: \"Filter by a case-insensitive route-name substring\",\r\n type: \"string\",\r\n },\r\n {\r\n text: \"--json, -j\",\r\n description: \"Output the routes as JSON instead of a table\",\r\n type: \"boolean\",\r\n },\r\n ],\r\n});\n\n/** Compare live development page routes with the last successful build. */\nexport const routesDiffCommand = command({\n name: \"routes:diff\",\n description: \"Compare live page routes with the last successful production build\",\n action: routesDiffCommandAction,\n preload: {\n runtimeStrategy: \"development\",\n warlockConfig: true,\n config: true,\n env: true,\n bootstrap: true,\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,MAAa,gBAAgB,QAAQ;CACnC,MAAM;CACN,aACE;CACF,QAAQ;CACR,SAAS;EACP,QAAQ;EACR,KAAK;EACL,WAAW;CACb;CACA,SAAS;EACP;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR;EACA;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR;EACA;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR;EACA;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR;CACF;AACF,CAAC;;AAGD,MAAa,oBAAoB,QAAQ;CACvC,MAAM;CACN,aAAa;CACb,QAAQ;CACR,SAAS;EACP,iBAAiB;EACjB,eAAe;EACf,QAAQ;EACR,KAAK;EACL,WAAW;CACb;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"routes.command.mjs","names":[],"sources":["../../../../../../../../core/src/cli/commands/routes.command.ts"],"sourcesContent":["import { command } from \"../../commands/cli-command\";\r\nimport { routesCommandAction } from \"./routes/routes-command.action\";\r\nimport { routesDiffCommandAction } from \"./routes/routes-diff.action\";\r\n\r\n/**\r\n * `warlock routes` — list every registered HTTP route as a table (a read-only\r\n * sibling of `warlock doctor`). Filter with `--method` / `--path` / `--name`,\r\n * or emit the normalized rows as JSON with `--json`.\r\n *\r\n * Preload plan: load config + bootstrap app code so route modules register on\r\n * the router singleton, but start NO connectors — listing routes must never\r\n * open a database/cache/socket connection. Because the route-module loader is\r\n * fail-loud, a route file that throws on import surfaces here instead of being\r\n * silently omitted from the table.\r\n */\r\nexport const routesCommand = command({\r\n name: \"routes\",\r\n description:\r\n \"List the registered HTTP routes as a table (read-only); filter with --method / --path / --name, or emit JSON with --json\",\r\n action: routesCommandAction,\r\n preload: {\r\n config: true,\r\n env: true,\r\n bootstrap: true,\r\n },\r\n options: [\r\n {\r\n text: \"--method, -m\",\r\n description: \"Filter by HTTP method (case-insensitive, e.g. GET, POST)\",\r\n type: \"string\",\r\n },\r\n {\r\n text: \"--path, -p\",\r\n description: \"Filter by a case-insensitive path substring\",\r\n type: \"string\",\r\n },\r\n {\r\n text: \"--name, -n\",\r\n description: \"Filter by a case-insensitive route-name substring\",\r\n type: \"string\",\r\n },\r\n {\r\n text: \"--json, -j\",\r\n description: \"Output the routes as JSON instead of a table\",\r\n type: \"boolean\",\r\n },\r\n ],\r\n});\r\n\r\n/** Compare live development page routes with the last successful build. */\r\nexport const routesDiffCommand = command({\r\n name: \"routes:diff\",\r\n description: \"Compare live page routes with the last successful production build\",\r\n action: routesDiffCommandAction,\r\n preload: {\r\n runtimeStrategy: \"development\",\r\n warlockConfig: true,\r\n config: true,\r\n env: true,\r\n bootstrap: true,\r\n },\r\n});\r\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,MAAa,gBAAgB,QAAQ;CACnC,MAAM;CACN,aACE;CACF,QAAQ;CACR,SAAS;EACP,QAAQ;EACR,KAAK;EACL,WAAW;CACb;CACA,SAAS;EACP;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR;EACA;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR;EACA;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR;EACA;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR;CACF;AACF,CAAC;;AAGD,MAAa,oBAAoB,QAAQ;CACvC,MAAM;CACN,aAAa;CACb,QAAQ;CACR,SAAS;EACP,iBAAiB;EACjB,eAAe;EACf,QAAQ;EACR,KAAK;EACL,WAAW;CACb;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"framework-cli-commands.mjs","names":[],"sources":["../../../../../../../core/src/cli/framework-cli-commands.ts"],"sourcesContent":["import { addCommand } from \"./commands/add.command\";\r\nimport { buildCommand } from \"./commands/build.command\";\r\nimport { createDatabaseCommand } from \"./commands/create-database.command\";\r\nimport { devServerCommand } from \"./commands/dev-server.command\";\r\nimport { doctorCommand } from \"./commands/doctor.command\";\r\nimport { dropTablesCommand } from \"./commands/drop-tables.command\";\r\nimport {\r\n generateCommand,\r\n generateControllerCommand,\r\n generateMigrationCommand,\r\n generateModelCommand,\r\n generateModuleCommand,\r\n generateRepositoryCommand,\r\n generateResourceCommand,\r\n generateServiceCommand,\r\n} from \"./commands/generate/generate.command\";\r\nimport { migrateCommand } from \"./commands/migrate.command\";\r\nimport { routesCommand, routesDiffCommand } from \"./commands/routes.command\";\nimport { seedCommand } from \"./commands/seed.command\";\r\nimport { startProductionCommand } from \"./commands/start-production.command\";\r\nimport { storagePutCommand } from \"./commands/storage-put.command\";\r\nimport { typingsGeneratorCommand } from \"./commands/typings-generator.command\";\r\nimport { updateCommand } from \"./commands/update.command\";\r\n\r\nexport const frameworkCommands = [\r\n // development commands\r\n devServerCommand,\r\n typingsGeneratorCommand,\r\n\r\n // diagnostics commands\r\n doctorCommand,\n routesCommand,\n routesDiffCommand,\n\r\n // production commands\r\n buildCommand,\r\n startProductionCommand,\r\n\r\n // database commands\r\n migrateCommand,\r\n seedCommand,\r\n createDatabaseCommand,\r\n dropTablesCommand,\r\n\r\n // generation/installation commands\r\n addCommand,\r\n updateCommand,\r\n\r\n // scaffolding commands\r\n generateCommand,\r\n generateModuleCommand,\r\n generateControllerCommand,\r\n generateServiceCommand,\r\n generateModelCommand,\r\n generateRepositoryCommand,\r\n generateResourceCommand,\r\n generateMigrationCommand,\r\n\r\n // storage commands\r\n storagePutCommand,\r\n];\r\n"],"mappings":";;;;;;;;;;;;;;;;AAwBA,MAAa,oBAAoB;CAE/B;CACA;CAGA;CACA;CACA;CAGA;CACA;CAGA;CACA;CACA;CACA;CAGA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;AACF"}
|
|
1
|
+
{"version":3,"file":"framework-cli-commands.mjs","names":[],"sources":["../../../../../../../core/src/cli/framework-cli-commands.ts"],"sourcesContent":["import { addCommand } from \"./commands/add.command\";\r\nimport { buildCommand } from \"./commands/build.command\";\r\nimport { createDatabaseCommand } from \"./commands/create-database.command\";\r\nimport { devServerCommand } from \"./commands/dev-server.command\";\r\nimport { doctorCommand } from \"./commands/doctor.command\";\r\nimport { dropTablesCommand } from \"./commands/drop-tables.command\";\r\nimport {\r\n generateCommand,\r\n generateControllerCommand,\r\n generateMigrationCommand,\r\n generateModelCommand,\r\n generateModuleCommand,\r\n generateRepositoryCommand,\r\n generateResourceCommand,\r\n generateServiceCommand,\r\n} from \"./commands/generate/generate.command\";\r\nimport { migrateCommand } from \"./commands/migrate.command\";\r\nimport { routesCommand, routesDiffCommand } from \"./commands/routes.command\";\r\nimport { seedCommand } from \"./commands/seed.command\";\r\nimport { startProductionCommand } from \"./commands/start-production.command\";\r\nimport { storagePutCommand } from \"./commands/storage-put.command\";\r\nimport { typingsGeneratorCommand } from \"./commands/typings-generator.command\";\r\nimport { updateCommand } from \"./commands/update.command\";\r\n\r\nexport const frameworkCommands = [\r\n // development commands\r\n devServerCommand,\r\n typingsGeneratorCommand,\r\n\r\n // diagnostics commands\r\n doctorCommand,\r\n routesCommand,\r\n routesDiffCommand,\r\n\r\n // production commands\r\n buildCommand,\r\n startProductionCommand,\r\n\r\n // database commands\r\n migrateCommand,\r\n seedCommand,\r\n createDatabaseCommand,\r\n dropTablesCommand,\r\n\r\n // generation/installation commands\r\n addCommand,\r\n updateCommand,\r\n\r\n // scaffolding commands\r\n generateCommand,\r\n generateModuleCommand,\r\n generateControllerCommand,\r\n generateServiceCommand,\r\n generateModelCommand,\r\n generateRepositoryCommand,\r\n generateResourceCommand,\r\n generateMigrationCommand,\r\n\r\n // storage commands\r\n storagePutCommand,\r\n];\r\n"],"mappings":";;;;;;;;;;;;;;;;AAwBA,MAAa,oBAAoB;CAE/B;CACA;CAGA;CACA;CACA;CAGA;CACA;CAGA;CACA;CACA;CACA;CAGA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;AACF"}
|
|
@@ -92,6 +92,7 @@ function parseCliArgs(argv, schema = []) {
|
|
|
92
92
|
const startIndex = isFirstArgOption ? 2 : 3;
|
|
93
93
|
for (let i = startIndex; i < argv.length; i++) {
|
|
94
94
|
const arg = argv[i];
|
|
95
|
+
if (arg === void 0) continue;
|
|
95
96
|
if (arg.startsWith("--")) {
|
|
96
97
|
const withoutDashes = arg.slice(2);
|
|
97
98
|
const equalIndex = withoutDashes.indexOf("=");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-cli-args.mjs","names":[],"sources":["../../../../../../../core/src/cli/parse-cli-args.ts"],"sourcesContent":["import { toCamelCase } from \"@mongez/reinforcements\";\n\nexport type ParsedCliArgs = {\n name: string;\n args: string[];\n options: Record<string, string | boolean>;\n};\n\n/**\n * The slice of a declared command option this parser needs.\n *\n * `CLICommand.commandOptions` (`ResolvedCLICommandOption[]`) satisfies it, but\n * the parser stays independent of the command classes so it can be unit-tested\n * and reused with a hand-written schema.\n */\nexport type CliOptionSchema = {\n name?: string;\n alias?: string;\n type?: \"string\" | \"boolean\" | \"number\";\n};\n\n/**\n * Thrown when a declared boolean option is given a value that is neither\n * true-ish nor false-ish.\n *\n * We refuse to guess. Guessing is exactly what produced #21: `--rollback=false`\n * was kept as the truthy string `\"false\"` and dropped every table. An option\n * that gates a destructive action must fail loudly on input it cannot read.\n */\nexport class CliOptionValueError extends Error {\n public constructor(\n public readonly optionToken: string,\n public readonly value: string,\n ) {\n super(\n `Invalid value ${JSON.stringify(value)} for boolean option ${optionToken}. ` +\n `Expected one of: true, false, 1, 0, yes, no — or pass ${optionToken} on its own for true.`,\n );\n\n this.name = \"CliOptionValueError\";\n }\n}\n\nconst TRUE_VALUES = new Set([\"true\", \"1\", \"yes\"]);\nconst FALSE_VALUES = new Set([\"false\", \"0\", \"no\"]);\n\n/**\n * Collect the camelCased keys (names AND aliases) of every option the command\n * declared as `type: \"boolean\"`.\n *\n * Both sides are camelCased because declared names keep their raw kebab form\n * (`\"pending-only\"`) while the parser emits camelCase keys (`pendingOnly`).\n */\nfunction collectBooleanKeys(schema: CliOptionSchema[]): Set<string> {\n const keys = new Set<string>();\n\n for (const option of schema) {\n if (option.type !== \"boolean\") continue;\n\n if (option.name) {\n keys.add(toCamelCase(option.name));\n }\n\n if (option.alias) {\n keys.add(toCamelCase(option.alias));\n }\n }\n\n return keys;\n}\n\n/**\n * Turn the value written after `=` into a real boolean, or throw.\n */\nfunction toBoolean(optionToken: string, value: string): boolean {\n const normalized = value.toLowerCase();\n\n if (TRUE_VALUES.has(normalized)) return true;\n if (FALSE_VALUES.has(normalized)) return false;\n\n throw new CliOptionValueError(optionToken, value);\n}\n\n/**\n * Parse CLI arguments from process.argv\n *\n * Called with a `schema` (the resolved command's declared options), every\n * option declared `type: \"boolean\"` is resolved as a boolean:\n * `--flag` → true, `--flag=false|0|no` → false, `--flag=true|1|yes` → true,\n * and `--flag <token>` leaves `<token>` as a POSITIONAL instead of swallowing\n * it as the flag's value. Anything else throws {@link CliOptionValueError}.\n *\n * Called without a schema — which is how the command name is discovered,\n * before any command object exists — behaviour is unchanged: every value stays\n * a raw string and a bare `--flag` still consumes the following non-dash token.\n * Nothing is blanket-coerced here on purpose: `--name=false` on a string-typed\n * option must survive as the string `\"false\"`.\n *\n * Options the schema does not declare keep the schema-less behaviour.\n *\n * @example\n * parseCliArgs([\"node\", \"warlock\", \"migrate\", \"--rollback\", \"file.ts\"])\n * // Returns: { name: \"migrate\", args: [], options: { rollback: \"file.ts\" } }\n *\n * @example\n * // `rollback` declared as type: \"boolean\" — the file stays a positional\n * parseCliArgs([\"node\", \"warlock\", \"migrate\", \"--rollback\", \"file.ts\"], migrateOptions)\n * // Returns: { name: \"migrate\", args: [\"file.ts\"], options: { rollback: true } }\n *\n * @example\n * parseCliArgs([\"node\", \"warlock\", \"dev\", \"--port=3000\", \"--fresh\"])\n * // Returns: { name: \"dev\", args: [], options: { port: \"3000\", fresh: true } }\n */\nexport function parseCliArgs(argv: string[], schema: CliOptionSchema[] = []): ParsedCliArgs {\n // Command is at index 2 (after \"node\" and script path)\n // But if index 2 starts with \"-\", it's an option, not a command\n const potentialCommand = argv[2] || \"\";\n const isFirstArgOption = potentialCommand.startsWith(\"-\");\n const command = isFirstArgOption ? \"\" : potentialCommand;\n const args: string[] = [];\n const options: Record<string, string | boolean> = {};\n const booleanKeys = collectBooleanKeys(schema);\n\n // Parse arguments starting from index 3 (or 2 if first arg was an option)\n const startIndex = isFirstArgOption ? 2 : 3;\n for (let i = startIndex; i < argv.length; i++) {\n const arg = argv[i];\n\n if (arg.startsWith(\"--\")) {\n // Long option: --key or --key=value\n const withoutDashes = arg.slice(2);\n const equalIndex = withoutDashes.indexOf(\"=\");\n\n if (equalIndex !== -1) {\n // --key=value format\n const key = toCamelCase(withoutDashes.slice(0, equalIndex));\n const value = withoutDashes.slice(equalIndex + 1);\n options[key] = booleanKeys.has(key)\n ? toBoolean(`--${withoutDashes.slice(0, equalIndex)}`, value)\n : value;\n } else {\n // --key format (check if next arg is a value)\n const key = toCamelCase(withoutDashes);\n const nextArg = argv[i + 1];\n\n // A declared boolean NEVER consumes the next token: `--rollback\n // users.ts` means \"rollback, and here is a positional\", not \"rollback\n // the file users.ts\". Swallowing it silently discarded the operator's\n // only stated scope and rolled back everything.\n if (booleanKeys.has(key)) {\n options[key] = true;\n } else if (nextArg && !nextArg.startsWith(\"-\")) {\n // If next arg exists and doesn't start with -, treat it as value\n options[key] = nextArg;\n i++; // Skip next arg\n } else {\n options[key] = true;\n }\n }\n } else if (arg.startsWith(\"-\") && arg.length > 1) {\n // Short option: -f, -t=value, or -abc (multiple flags)\n const flags = arg.slice(1);\n const equalIndex = flags.indexOf(\"=\");\n\n if (equalIndex !== -1) {\n // -t=value format\n const rawKey = flags.slice(0, equalIndex);\n const key = toCamelCase(rawKey);\n const value = flags.slice(equalIndex + 1);\n options[key] = booleanKeys.has(key) ? toBoolean(`-${rawKey}`, value) : value;\n } else if (flags.length === 1) {\n // Single flag: -f\n const key = toCamelCase(flags);\n const nextArg = argv[i + 1];\n\n if (booleanKeys.has(key)) {\n options[key] = true;\n } else if (nextArg && !nextArg.startsWith(\"-\")) {\n options[key] = nextArg;\n i++; // Skip next arg\n } else {\n options[key] = true;\n }\n } else {\n // Multiple flags: -abc becomes { a: true, b: true, c: true }\n // A bundle carries no value and never consumes the next token, so a\n // declared boolean already resolves to `true` here.\n for (const flag of flags) {\n options[toCamelCase(flag)] = true;\n }\n }\n } else {\n // Positional argument\n args.push(arg);\n }\n }\n\n return { name: command, args, options };\n}\n"],"mappings":";;;;;;;;;;;AA6BA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,AAAO,YACL,AAAgB,aAChB,AAAgB,OAChB;EACA,MACE,iBAAiB,KAAK,UAAU,KAAK,EAAE,sBAAsB,YAAY,0DACd,YAAY,sBACzE;EANgB;EACA;EAOhB,KAAK,OAAO;CACd;AACF;AAEA,MAAM,cAAc,IAAI,IAAI;CAAC;CAAQ;CAAK;AAAK,CAAC;AAChD,MAAM,eAAe,IAAI,IAAI;CAAC;CAAS;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L,MAAM,MAAM,YAAY,aAAa;IACrC,MAAM,UAAU,KAAK,IAAI;IAMzB,IAAI,YAAY,IAAI,GAAG,GACrB,QAAQ,OAAO;SACV,IAAI,WAAW,CAAC,QAAQ,WAAW,GAAG,GAAG;KAE9C,QAAQ,OAAO;KACf;IACF,OACE,QAAQ,OAAO;GAEnB;EACF,OAAO,IAAI,IAAI,WAAW,GAAG,KAAK,IAAI,SAAS,GAAG;GAEhD,MAAM,QAAQ,IAAI,MAAM,CAAC;GACzB,MAAM,aAAa,MAAM,QAAQ,GAAG;GAEpC,IAAI,eAAe,IAAI;IAErB,MAAM,SAAS,MAAM,MAAM,GAAG,UAAU;IACxC,MAAM,MAAM,YAAY,MAAM;IAC9B,MAAM,QAAQ,MAAM,MAAM,aAAa,CAAC;IACxC,QAAQ,OAAO,YAAY,IAAI,GAAG,IAAI,UAAU,IAAI,UAAU,KAAK,IAAI;GACzE,OAAO,IAAI,MAAM,WAAW,GAAG;IAE7B,MAAM,MAAM,YAAY,KAAK;IAC7B,MAAM,UAAU,KAAK,IAAI;IAEzB,IAAI,YAAY,IAAI,GAAG,GACrB,QAAQ,OAAO;SACV,IAAI,WAAW,CAAC,QAAQ,WAAW,GAAG,GAAG;KAC9C,QAAQ,OAAO;KACf;IACF,OACE,QAAQ,OAAO;GAEnB,OAIE,KAAK,MAAM,QAAQ,OACjB,QAAQ,YAAY,IAAI,KAAK;EAGnC,OAEE,KAAK,KAAK,GAAG;CAEjB;CAEA,OAAO;EAAE,MAAM;EAAS;EAAM;CAAQ;AACxC"}
|
|
1
|
+
{"version":3,"file":"parse-cli-args.mjs","names":[],"sources":["../../../../../../../core/src/cli/parse-cli-args.ts"],"sourcesContent":["import { toCamelCase } from \"@mongez/reinforcements\";\n\nexport type ParsedCliArgs = {\n name: string;\n args: string[];\n options: Record<string, string | boolean>;\n};\n\n/**\n * The slice of a declared command option this parser needs.\n *\n * `CLICommand.commandOptions` (`ResolvedCLICommandOption[]`) satisfies it, but\n * the parser stays independent of the command classes so it can be unit-tested\n * and reused with a hand-written schema.\n */\nexport type CliOptionSchema = {\n name?: string;\n alias?: string;\n type?: \"string\" | \"boolean\" | \"number\";\n};\n\n/**\n * Thrown when a declared boolean option is given a value that is neither\n * true-ish nor false-ish.\n *\n * We refuse to guess. Guessing is exactly what produced #21: `--rollback=false`\n * was kept as the truthy string `\"false\"` and dropped every table. An option\n * that gates a destructive action must fail loudly on input it cannot read.\n */\nexport class CliOptionValueError extends Error {\n public constructor(\n public readonly optionToken: string,\n public readonly value: string,\n ) {\n super(\n `Invalid value ${JSON.stringify(value)} for boolean option ${optionToken}. ` +\n `Expected one of: true, false, 1, 0, yes, no — or pass ${optionToken} on its own for true.`,\n );\n\n this.name = \"CliOptionValueError\";\n }\n}\n\nconst TRUE_VALUES = new Set([\"true\", \"1\", \"yes\"]);\nconst FALSE_VALUES = new Set([\"false\", \"0\", \"no\"]);\n\n/**\n * Collect the camelCased keys (names AND aliases) of every option the command\n * declared as `type: \"boolean\"`.\n *\n * Both sides are camelCased because declared names keep their raw kebab form\n * (`\"pending-only\"`) while the parser emits camelCase keys (`pendingOnly`).\n */\nfunction collectBooleanKeys(schema: CliOptionSchema[]): Set<string> {\n const keys = new Set<string>();\n\n for (const option of schema) {\n if (option.type !== \"boolean\") continue;\n\n if (option.name) {\n keys.add(toCamelCase(option.name));\n }\n\n if (option.alias) {\n keys.add(toCamelCase(option.alias));\n }\n }\n\n return keys;\n}\n\n/**\n * Turn the value written after `=` into a real boolean, or throw.\n */\nfunction toBoolean(optionToken: string, value: string): boolean {\n const normalized = value.toLowerCase();\n\n if (TRUE_VALUES.has(normalized)) return true;\n if (FALSE_VALUES.has(normalized)) return false;\n\n throw new CliOptionValueError(optionToken, value);\n}\n\n/**\n * Parse CLI arguments from process.argv\n *\n * Called with a `schema` (the resolved command's declared options), every\n * option declared `type: \"boolean\"` is resolved as a boolean:\n * `--flag` → true, `--flag=false|0|no` → false, `--flag=true|1|yes` → true,\n * and `--flag <token>` leaves `<token>` as a POSITIONAL instead of swallowing\n * it as the flag's value. Anything else throws {@link CliOptionValueError}.\n *\n * Called without a schema — which is how the command name is discovered,\n * before any command object exists — behaviour is unchanged: every value stays\n * a raw string and a bare `--flag` still consumes the following non-dash token.\n * Nothing is blanket-coerced here on purpose: `--name=false` on a string-typed\n * option must survive as the string `\"false\"`.\n *\n * Options the schema does not declare keep the schema-less behaviour.\n *\n * @example\n * parseCliArgs([\"node\", \"warlock\", \"migrate\", \"--rollback\", \"file.ts\"])\n * // Returns: { name: \"migrate\", args: [], options: { rollback: \"file.ts\" } }\n *\n * @example\n * // `rollback` declared as type: \"boolean\" — the file stays a positional\n * parseCliArgs([\"node\", \"warlock\", \"migrate\", \"--rollback\", \"file.ts\"], migrateOptions)\n * // Returns: { name: \"migrate\", args: [\"file.ts\"], options: { rollback: true } }\n *\n * @example\n * parseCliArgs([\"node\", \"warlock\", \"dev\", \"--port=3000\", \"--fresh\"])\n * // Returns: { name: \"dev\", args: [], options: { port: \"3000\", fresh: true } }\n */\nexport function parseCliArgs(argv: string[], schema: CliOptionSchema[] = []): ParsedCliArgs {\n // Command is at index 2 (after \"node\" and script path)\n // But if index 2 starts with \"-\", it's an option, not a command\n const potentialCommand = argv[2] || \"\";\n const isFirstArgOption = potentialCommand.startsWith(\"-\");\n const command = isFirstArgOption ? \"\" : potentialCommand;\n const args: string[] = [];\n const options: Record<string, string | boolean> = {};\n const booleanKeys = collectBooleanKeys(schema);\n\n // Parse arguments starting from index 3 (or 2 if first arg was an option)\n const startIndex = isFirstArgOption ? 2 : 3;\n for (let i = startIndex; i < argv.length; i++) {\n const arg = argv[i];\n\n // `i < argv.length` bounds this, but the compiler does not narrow an index\n // read from a loop condition. Skipping rather than coercing: this file\n // already refuses to guess about an operator's input (see\n // `CliOptionValueError` above), and an `?? \"\"` here would silently push an\n // empty POSITIONAL onto `args` — which for a command that takes a file or\n // a table name is a scope the operator never typed.\n if (arg === undefined) continue;\n\n if (arg.startsWith(\"--\")) {\n // Long option: --key or --key=value\n const withoutDashes = arg.slice(2);\n const equalIndex = withoutDashes.indexOf(\"=\");\n\n if (equalIndex !== -1) {\n // --key=value format\n const key = toCamelCase(withoutDashes.slice(0, equalIndex));\n const value = withoutDashes.slice(equalIndex + 1);\n options[key] = booleanKeys.has(key)\n ? toBoolean(`--${withoutDashes.slice(0, equalIndex)}`, value)\n : value;\n } else {\n // --key format (check if next arg is a value)\n const key = toCamelCase(withoutDashes);\n const nextArg = argv[i + 1];\n\n // A declared boolean NEVER consumes the next token: `--rollback\n // users.ts` means \"rollback, and here is a positional\", not \"rollback\n // the file users.ts\". Swallowing it silently discarded the operator's\n // only stated scope and rolled back everything.\n if (booleanKeys.has(key)) {\n options[key] = true;\n } else if (nextArg && !nextArg.startsWith(\"-\")) {\n // If next arg exists and doesn't start with -, treat it as value\n options[key] = nextArg;\n i++; // Skip next arg\n } else {\n options[key] = true;\n }\n }\n } else if (arg.startsWith(\"-\") && arg.length > 1) {\n // Short option: -f, -t=value, or -abc (multiple flags)\n const flags = arg.slice(1);\n const equalIndex = flags.indexOf(\"=\");\n\n if (equalIndex !== -1) {\n // -t=value format\n const rawKey = flags.slice(0, equalIndex);\n const key = toCamelCase(rawKey);\n const value = flags.slice(equalIndex + 1);\n options[key] = booleanKeys.has(key) ? toBoolean(`-${rawKey}`, value) : value;\n } else if (flags.length === 1) {\n // Single flag: -f\n const key = toCamelCase(flags);\n const nextArg = argv[i + 1];\n\n if (booleanKeys.has(key)) {\n options[key] = true;\n } else if (nextArg && !nextArg.startsWith(\"-\")) {\n options[key] = nextArg;\n i++; // Skip next arg\n } else {\n options[key] = true;\n }\n } else {\n // Multiple flags: -abc becomes { a: true, b: true, c: true }\n // A bundle carries no value and never consumes the next token, so a\n // declared boolean already resolves to `true` here.\n for (const flag of flags) {\n options[toCamelCase(flag)] = true;\n }\n }\n } else {\n // Positional argument\n args.push(arg);\n }\n }\n\n return { name: command, args, options };\n}\n"],"mappings":";;;;;;;;;;;AA6BA,IAAa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EAAE,MAAM;EAAS;EAAM;CAAQ;AACxC"}
|
|
@@ -17,11 +17,20 @@ function levenshteinDistance(str1, str2) {
|
|
|
17
17
|
const len1 = s1.length;
|
|
18
18
|
const len2 = s2.length;
|
|
19
19
|
const matrix = Array.from({ length: len1 + 1 }, (_, i) => Array.from({ length: len2 + 1 }, (_, j) => i === 0 ? j : j === 0 ? i : 0));
|
|
20
|
-
for (let i = 1; i <= len1; i++)
|
|
21
|
-
const
|
|
22
|
-
|
|
20
|
+
for (let i = 1; i <= len1; i++) {
|
|
21
|
+
const previousRow = matrix[i - 1];
|
|
22
|
+
const currentRow = matrix[i];
|
|
23
|
+
if (previousRow === void 0 || currentRow === void 0) continue;
|
|
24
|
+
for (let j = 1; j <= len2; j++) {
|
|
25
|
+
const deletion = previousRow[j];
|
|
26
|
+
const insertion = currentRow[j - 1];
|
|
27
|
+
const substitution = previousRow[j - 1];
|
|
28
|
+
if (deletion === void 0 || insertion === void 0 || substitution === void 0) continue;
|
|
29
|
+
const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
|
|
30
|
+
currentRow[j] = Math.min(deletion + 1, insertion + 1, substitution + cost);
|
|
31
|
+
}
|
|
23
32
|
}
|
|
24
|
-
return matrix[len1][len2];
|
|
33
|
+
return matrix[len1]?.[len2] ?? Math.max(len1, len2);
|
|
25
34
|
}
|
|
26
35
|
/**
|
|
27
36
|
* Find similar strings from a list
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"string-similarity.mjs","names":[],"sources":["../../../../../../../core/src/cli/string-similarity.ts"],"sourcesContent":["/**\n * String similarity utilities for CLI command suggestions\n * Uses Levenshtein distance algorithm for fuzzy matching\n */\n\n/**\n * Calculate the Levenshtein distance between two strings\n * Lower distance = more similar\n *\n * @param str1 - First string\n * @param str2 - Second string\n * @returns Distance (number of edits required to transform str1 to str2)\n */\nexport function levenshteinDistance(str1: string, str2: string): number {\n const s1 = str1.toLowerCase();\n const s2 = str2.toLowerCase();\n\n const len1 = s1.length;\n const len2 = s2.length;\n\n // Create matrix\n const matrix: number[][] = Array.from({ length: len1 + 1 }, (_, i) =>\n Array.from({ length: len2 + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),\n );\n\n // Fill matrix\n for (let i = 1; i <= len1; i++) {\n for (let j = 1; j <= len2; j++) {\n const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;\n
|
|
1
|
+
{"version":3,"file":"string-similarity.mjs","names":[],"sources":["../../../../../../../core/src/cli/string-similarity.ts"],"sourcesContent":["/**\n * String similarity utilities for CLI command suggestions\n * Uses Levenshtein distance algorithm for fuzzy matching\n */\n\n/**\n * Calculate the Levenshtein distance between two strings\n * Lower distance = more similar\n *\n * @param str1 - First string\n * @param str2 - Second string\n * @returns Distance (number of edits required to transform str1 to str2)\n */\nexport function levenshteinDistance(str1: string, str2: string): number {\n const s1 = str1.toLowerCase();\n const s2 = str2.toLowerCase();\n\n const len1 = s1.length;\n const len2 = s2.length;\n\n // Create matrix\n const matrix: number[][] = Array.from({ length: len1 + 1 }, (_, i) =>\n Array.from({ length: len2 + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),\n );\n\n // Fill matrix\n //\n // Every index below is in bounds by construction — the matrix is built\n // `len1 + 1` by `len2 + 1` immediately above. Under\n // `noUncheckedIndexedAccess` the compiler still types each read as possibly\n // undefined, and the rows are hoisted rather than defaulted: a `?? 0` in the\n // middle of a distance calculation would not fail, it would quietly return a\n // SHORTER distance and change which command the CLI suggests.\n for (let i = 1; i <= len1; i++) {\n const previousRow = matrix[i - 1];\n const currentRow = matrix[i];\n\n if (previousRow === undefined || currentRow === undefined) continue;\n\n for (let j = 1; j <= len2; j++) {\n const deletion = previousRow[j];\n const insertion = currentRow[j - 1];\n const substitution = previousRow[j - 1];\n\n if (deletion === undefined || insertion === undefined || substitution === undefined) {\n continue;\n }\n\n const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;\n\n currentRow[j] = Math.min(deletion + 1, insertion + 1, substitution + cost);\n }\n }\n\n // `len1`/`len2` index the last row and column, both allocated above. Falling\n // back to the worst-case distance (the longer string's length) rather than 0\n // keeps an unreadable result looking MAXIMALLY dissimilar — a 0 would make\n // it look like a perfect match and promote it to the top suggestion.\n return matrix[len1]?.[len2] ?? Math.max(len1, len2);\n}\n\n/**\n * Suggestion result with similarity score\n */\nexport type Suggestion = {\n /** The suggested value */\n value: string;\n /** Distance score (lower = more similar) */\n distance: number;\n};\n\n/**\n * Find similar strings from a list\n *\n * @param input - The input string to find matches for\n * @param candidates - List of candidate strings\n * @param maxDistance - Maximum distance to consider (default: 3)\n * @param maxResults - Maximum number of results to return (default: 3)\n * @returns Array of suggestions sorted by similarity\n *\n * @example\n * ```typescript\n * findSimilar(\"biuld\", [\"build\", \"dev\", \"start\", \"test\"])\n * // Returns: [{ value: \"build\", distance: 1 }]\n * ```\n */\nexport function findSimilar(\n input: string,\n candidates: string[],\n maxDistance: number = 3,\n maxResults: number = 3,\n): Suggestion[] {\n const results: Suggestion[] = [];\n\n for (const candidate of candidates) {\n const distance = levenshteinDistance(input, candidate);\n\n if (distance <= maxDistance && distance > 0) {\n results.push({ value: candidate, distance });\n }\n }\n\n // Sort by distance (most similar first)\n results.sort((a, b) => a.distance - b.distance);\n\n return results.slice(0, maxResults);\n}\n\n/**\n * Check if a string starts with any of the given prefixes\n * Useful for command name matching\n */\nexport function startsWithAny(str: string, prefixes: string[]): boolean {\n return prefixes.some((prefix) => str.toLowerCase().startsWith(prefix.toLowerCase()));\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,oBAAoB,MAAc,MAAsB;CACtE,MAAM,KAAK,KAAK,YAAY;CAC5B,MAAM,KAAK,KAAK,YAAY;CAE5B,MAAM,OAAO,GAAG;CAChB,MAAM,OAAO,GAAG;CAGhB,MAAM,SAAqB,MAAM,KAAK,EAAE,QAAQ,OAAO,EAAE,IAAI,GAAG,MAC9D,MAAM,KAAK,EAAE,QAAQ,OAAO,EAAE,IAAI,GAAG,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
1
|
+
{"version":3,"file":"cli-command.d.mts","names":[],"sources":["../../../../../../../core/src/commands/cli-command.ts"],"mappings":";;;cAUa,UAAA;EAqDF,IAAA;EArDE;;;EAIJ,aAAA,GAAgB,gBAAA;EAKA;;;EAAhB,aAAA,GAAgB,gBAAA;EAyDD;;;;EAnDf,gBAAA,GAAmB,gBAAA;EA0HT;;;EArHV,cAAA,GAAiB,iBAAA;EAmOA;;;EA9NjB,kBAAA;EAsOqC;;;EAjOrC,cAAA,EAAgB,wBAAA;EArBhB;;;;;EA4BA,mBAAA;EAZA;;;EAiBA,YAAA;EAAA;;;EAKA,YAAA;EAOL;;;cADO,IAAA,UACP,WAAA;EAoBK;;;EARA,MAAA,CAAO,MAAA,EAAQ,gBAAA;EAyBf;;;EAjBA,WAAA,CAAY,WAAA;EAyBL;;;EAjBP,UAAA,CAAW,YAAA;EAkCX;;;;EAzBA,KAAA,CAAM,KAAA;EA0CN;;;EAlCA,MAAA,CAAO,MAAA,EAAQ,gBAAA;EAoCpB;;;;EA3BK,SAAA,CAAU,MAAA,EAAQ,gBAAA;EA8Df;;;EAtDH,OAAA,CAAQ,OAAA,EAAS,gBAAA;EA6GhB;;;EApGD,aAAA,CAAc,YAAA;EAkIR;;;EA1HN,MAAA,CAAO,MAAA,EAAQ,gBAAA;EACf,MAAA,CACL,IAAA,UACA,WAAA,WACA,OAAA,GAAU,IAAA,CAAK,gBAAA;EAsH2B;AAS9C;;;;;;;;EAT8C,UArFlC,WAAA,CAAY,MAAA,EAAQ,gBAAA,GAAmB,wBAAA;;;;;;;;;UAuDzC,iBAAA;;;;EAsBD,OAAA,CAAQ,OAAA,EAAS,iBAAA;;;;EAQX,OAAA,CAAQ,IAAA,EAAM,iBAAA,GAAiB,OAAA;AAAA;AAAA,iBAS9B,OAAA,CAAQ,OAAA,EAAS,iBAAA,GAAiB,UAAA"}
|
|
@@ -93,10 +93,13 @@ var CLICommand = class {
|
|
|
93
93
|
const parts = option.text.trim().split(",").map((part) => part.trim());
|
|
94
94
|
let name = "";
|
|
95
95
|
let alias = "";
|
|
96
|
-
|
|
96
|
+
const firstPart = parts[0];
|
|
97
|
+
if (!firstPart) throw new Error("Command option text cannot be empty");
|
|
98
|
+
if (parts.length === 1) name = this.extractOptionName(firstPart);
|
|
97
99
|
else if (parts.length === 2) {
|
|
98
|
-
const first =
|
|
100
|
+
const first = firstPart;
|
|
99
101
|
const second = parts[1];
|
|
102
|
+
if (!second) throw new Error("Command option alias cannot be empty");
|
|
100
103
|
if (first.startsWith("--")) {
|
|
101
104
|
name = this.extractOptionName(first);
|
|
102
105
|
alias = this.extractOptionName(second);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-command.mjs","names":[],"sources":["../../../../../../../core/src/commands/cli-command.ts"],"sourcesContent":["import type {\n CLICommandAction,\n CLICommandOption,\n CLICommandOptions,\n CLICommandPreload,\n CLICommandSource,\n CommandActionData,\n ResolvedCLICommandOption,\n} from \"./types\";\n\nexport class CLICommand {\n /**\n * Command source\n */\n public commandSource?: CLICommandSource;\n\n /**\n * Command action\n */\n public commandAction?: CLICommandAction;\n\n /**\n * Command pre action\n * This will be executed before loading preloaders\n */\n public commandPreAction?: CLICommandAction;\n\n /**\n * Command preload\n */\n public commandPreload?: CLICommandPreload;\n\n /**\n * Command description\n */\n public commandDescription?: string;\n\n /**\n * Command options\n */\n public commandOptions: ResolvedCLICommandOption[] = [];\n\n /**\n * Command relative path\n * Available only for project commands\n * Auto injected by the framework itself\n */\n public commandRelativePath?: string;\n\n /**\n * Determine if the command is persistent\n */\n public isPersistent: boolean = false;\n\n /**\n * Command alias (short name)\n */\n public commandAlias?: string;\n\n /**\n * Constructor\n */\n public constructor(\n public name: string,\n description?: string,\n ) {\n if (description) {\n this.commandDescription = description;\n }\n\n return this;\n }\n\n /**\n * Add command source\n */\n public source(source: CLICommandSource): this {\n this.commandSource = source;\n return this;\n }\n\n /**\n * Set command description\n */\n public description(description: string): this {\n this.commandDescription = description;\n return this;\n }\n\n /**\n * Determine if the command is persistent\n */\n public persistent(isPersistent = true): this {\n this.isPersistent = isPersistent;\n return this;\n }\n\n /**\n * Set command alias (short name)\n * @example .alias(\"m\") for \"migrate\"\n */\n public alias(alias: string): this {\n this.commandAlias = alias;\n return this;\n }\n\n /**\n * Command action\n */\n public action(action: CLICommandAction): this {\n this.commandAction = action;\n return this;\n }\n\n /**\n * Command pre action\n * This will be executed before loading preloaders\n */\n public preAction(action: CLICommandAction): this {\n this.commandPreAction = action;\n return this;\n }\n\n /**\n * Add command options\n */\n public options(options: CLICommandOption[]): this {\n options.map((option) => this.option(option));\n\n return this;\n }\n\n /**\n * Add command relative path\n */\n public $relativePath(relativePath: string) {\n this.commandRelativePath = relativePath;\n return this;\n }\n\n /**\n * Add command option\n */\n public option(option: CLICommandOption): this;\n public option(\n name: string,\n description?: string,\n options?: Omit<CLICommandOption, \"name\" | \"text\" | \"description\">,\n ): this;\n public option(\n ...args:\n | [CLICommandOption]\n | [string, string?, Omit<CLICommandOption, \"name\" | \"text\" | \"description\">?]\n ): this {\n let option: CLICommandOption;\n if (args.length === 1) {\n option = args[0] as CLICommandOption;\n } else {\n option = {\n text: args[0],\n description: args[1],\n ...args[2],\n name: \"\",\n };\n }\n\n this.commandOptions.push(this.parseOption(option));\n\n return this;\n }\n\n /**\n * Parse option name and alias if exists\n *\n * Supports formats:\n * - \"--port, -p\" → name: \"port\", alias: \"p\"\n * - \"-p, --port\" → name: \"port\", alias: \"p\"\n * - \"--port\" → name: \"port\", alias: undefined\n * - \"-p\" → name: \"p\", alias: undefined\n */\n protected parseOption(option: CLICommandOption): ResolvedCLICommandOption {\n const text = option.text.trim();\n\n // Split by comma to check for alias\n const parts = text.split(\",\").map((part) => part.trim());\n\n let name = \"\";\n let alias = \"\";\n\n if (parts.length === 1) {\n // Single option: \"--port\" or \"-p\"\n name = this.extractOptionName(
|
|
1
|
+
{"version":3,"file":"cli-command.mjs","names":[],"sources":["../../../../../../../core/src/commands/cli-command.ts"],"sourcesContent":["import type {\n CLICommandAction,\n CLICommandOption,\n CLICommandOptions,\n CLICommandPreload,\n CLICommandSource,\n CommandActionData,\n ResolvedCLICommandOption,\n} from \"./types\";\n\nexport class CLICommand {\n /**\n * Command source\n */\n public commandSource?: CLICommandSource;\n\n /**\n * Command action\n */\n public commandAction?: CLICommandAction;\n\n /**\n * Command pre action\n * This will be executed before loading preloaders\n */\n public commandPreAction?: CLICommandAction;\n\n /**\n * Command preload\n */\n public commandPreload?: CLICommandPreload;\n\n /**\n * Command description\n */\n public commandDescription?: string;\n\n /**\n * Command options\n */\n public commandOptions: ResolvedCLICommandOption[] = [];\n\n /**\n * Command relative path\n * Available only for project commands\n * Auto injected by the framework itself\n */\n public commandRelativePath?: string;\n\n /**\n * Determine if the command is persistent\n */\n public isPersistent: boolean = false;\n\n /**\n * Command alias (short name)\n */\n public commandAlias?: string;\n\n /**\n * Constructor\n */\n public constructor(\n public name: string,\n description?: string,\n ) {\n if (description) {\n this.commandDescription = description;\n }\n\n return this;\n }\n\n /**\n * Add command source\n */\n public source(source: CLICommandSource): this {\n this.commandSource = source;\n return this;\n }\n\n /**\n * Set command description\n */\n public description(description: string): this {\n this.commandDescription = description;\n return this;\n }\n\n /**\n * Determine if the command is persistent\n */\n public persistent(isPersistent = true): this {\n this.isPersistent = isPersistent;\n return this;\n }\n\n /**\n * Set command alias (short name)\n * @example .alias(\"m\") for \"migrate\"\n */\n public alias(alias: string): this {\n this.commandAlias = alias;\n return this;\n }\n\n /**\n * Command action\n */\n public action(action: CLICommandAction): this {\n this.commandAction = action;\n return this;\n }\n\n /**\n * Command pre action\n * This will be executed before loading preloaders\n */\n public preAction(action: CLICommandAction): this {\n this.commandPreAction = action;\n return this;\n }\n\n /**\n * Add command options\n */\n public options(options: CLICommandOption[]): this {\n options.map((option) => this.option(option));\n\n return this;\n }\n\n /**\n * Add command relative path\n */\n public $relativePath(relativePath: string) {\n this.commandRelativePath = relativePath;\n return this;\n }\n\n /**\n * Add command option\n */\n public option(option: CLICommandOption): this;\n public option(\n name: string,\n description?: string,\n options?: Omit<CLICommandOption, \"name\" | \"text\" | \"description\">,\n ): this;\n public option(\n ...args:\n | [CLICommandOption]\n | [string, string?, Omit<CLICommandOption, \"name\" | \"text\" | \"description\">?]\n ): this {\n let option: CLICommandOption;\n if (args.length === 1) {\n option = args[0] as CLICommandOption;\n } else {\n option = {\n text: args[0],\n description: args[1],\n ...args[2],\n name: \"\",\n };\n }\n\n this.commandOptions.push(this.parseOption(option));\n\n return this;\n }\n\n /**\n * Parse option name and alias if exists\n *\n * Supports formats:\n * - \"--port, -p\" → name: \"port\", alias: \"p\"\n * - \"-p, --port\" → name: \"port\", alias: \"p\"\n * - \"--port\" → name: \"port\", alias: undefined\n * - \"-p\" → name: \"p\", alias: undefined\n */\n protected parseOption(option: CLICommandOption): ResolvedCLICommandOption {\n const text = option.text.trim();\n\n // Split by comma to check for alias\n const parts = text.split(\",\").map((part) => part.trim());\n\n let name = \"\";\n let alias = \"\";\n const firstPart = parts[0];\n\n if (!firstPart) {\n throw new Error(\"Command option text cannot be empty\");\n }\n\n if (parts.length === 1) {\n // Single option: \"--port\" or \"-p\"\n name = this.extractOptionName(firstPart);\n } else if (parts.length === 2) {\n // Two options: \"--port, -p\" or \"-p, --port\"\n const first = firstPart;\n const second = parts[1];\n\n if (!second) {\n throw new Error(\"Command option alias cannot be empty\");\n }\n\n // Determine which is the long form (name) and which is short (alias)\n if (first.startsWith(\"--\")) {\n name = this.extractOptionName(first);\n alias = this.extractOptionName(second);\n } else {\n name = this.extractOptionName(second);\n alias = this.extractOptionName(first);\n }\n }\n\n if (alias === \"h\" || name === \"help\") {\n throw new Error(\"Help option is not allowed, it's reserved for displaying command help\");\n }\n\n return {\n ...option,\n name,\n alias,\n };\n }\n\n /**\n * Extract option name from text (removes -- or -)\n *\n * @example\n * extractOptionName(\"--port\") → \"port\"\n * extractOptionName(\"-p\") → \"p\"\n * extractOptionName(\"--port=3000\") → \"port\"\n */\n private extractOptionName(text: string): string {\n // Remove leading dashes\n let name = text.replace(/^-+/, \"\");\n\n // Remove value assignment if exists (e.g., \"--port=3000\" → \"port\")\n const equalIndex = name.indexOf(\"=\");\n if (equalIndex !== -1) {\n name = name.slice(0, equalIndex);\n }\n\n // Remove angle brackets if exists (e.g., \"--port <number>\" → \"port\")\n const spaceIndex = name.indexOf(\" \");\n if (spaceIndex !== -1) {\n name = name.slice(0, spaceIndex);\n }\n\n return name.trim();\n }\n\n /**\n * Command preload\n */\n public preload(options: CLICommandPreload) {\n this.commandPreload = options;\n return this;\n }\n\n /**\n * Execute the command\n */\n public async execute(data: CommandActionData) {\n if (!this.commandAction) {\n throw new Error(`Command \"${this.name}\" has no action defined`);\n }\n\n await this.commandAction(data);\n }\n}\n\nexport function command(options: CLICommandOptions) {\n const commandInstnace = new CLICommand(options.name, options.description);\n\n if (options.preload) {\n commandInstnace.preload(options.preload);\n }\n\n if (options.persistent) {\n commandInstnace.persistent(options.persistent);\n }\n\n if (options.alias) {\n commandInstnace.alias(options.alias);\n }\n\n commandInstnace.action(options.action);\n\n if (options.options) {\n commandInstnace.options(options.options);\n }\n\n if (options.preAction) {\n commandInstnace.preAction(options.preAction);\n }\n\n return commandInstnace;\n}\n"],"mappings":";AAUA,IAAa,aAAb,MAAwB;;;;CAoDtB,AAAO,YACL,AAAO,MACP,aACA;EAFO;wBAvB2C,CAAC;sBAYtB;EAc7B,IAAI,aACF,KAAK,qBAAqB;EAG5B,OAAO;CACT;;;;CAKA,AAAO,OAAO,QAAgC;EAC5C,KAAK,gBAAgB;EACrB,OAAO;CACT;;;;CAKA,AAAO,YAAY,aAA2B;EAC5C,KAAK,qBAAqB;EAC1B,OAAO;CACT;;;;CAKA,AAAO,WAAW,eAAe,MAAY;EAC3C,KAAK,eAAe;EACpB,OAAO;CACT;;;;;CAMA,AAAO,MAAM,OAAqB;EAChC,KAAK,eAAe;EACpB,OAAO;CACT;;;;CAKA,AAAO,OAAO,QAAgC;EAC5C,KAAK,gBAAgB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,kBAAkB,MAAsB;EAE9C,IAAI,OAAO,KAAK,QAAQ,OAAO,EAAE;EAGjC,MAAM,aAAa,KAAK,QAAQ,GAAG;EACnC,IAAI,eAAe,IACjB,OAAO,KAAK,MAAM,GAAG,UAAU;EAIjC,MAAM,aAAa,KAAK,QAAQ,GAAG;EACnC,IAAI,eAAe,IACjB,OAAO,KAAK,MAAM,GAAG,UAAU;EAGjC,OAAO,KAAK,KAAK;CACnB;;;;CAKA,AAAO,QAAQ,SAA4B;EACzC,KAAK,iBAAiB;EACtB,OAAO;CACT;;;;CAKA,MAAa,QAAQ,MAAyB;EAC5C,IAAI,CAAC,KAAK,eACR,MAAM,IAAI,MAAM,YAAY,KAAK,KAAK,wBAAwB;EAGhE,MAAM,KAAK,cAAc,IAAI;CAC/B;AACF;AAEA,SAAgB,QAAQ,SAA4B;CAClD,MAAM,kBAAkB,IAAI,WAAW,QAAQ,MAAM,QAAQ,WAAW;CAExE,IAAI,QAAQ,SACV,gBAAgB,QAAQ,QAAQ,OAAO;CAGzC,IAAI,QAAQ,YACV,gBAAgB,WAAW,QAAQ,UAAU;CAG/C,IAAI,QAAQ,OACV,gBAAgB,MAAM,QAAQ,KAAK;CAGrC,gBAAgB,OAAO,QAAQ,MAAM;CAErC,IAAI,QAAQ,SACV,gBAAgB,QAAQ,QAAQ,OAAO;CAGzC,IAAI,QAAQ,WACV,gBAAgB,UAAU,QAAQ,SAAS;CAG7C,OAAO;AACT"}
|
|
@@ -39,7 +39,9 @@ var ConfigLoader = class {
|
|
|
39
39
|
getConfigName(relativePath) {
|
|
40
40
|
const match = relativePath.match(/^src\/config\/(.+)\.(ts|tsx)$/);
|
|
41
41
|
if (!match) throw new Error(`Invalid config file path: ${relativePath}`);
|
|
42
|
-
|
|
42
|
+
const configName = match[1];
|
|
43
|
+
if (!configName) throw new Error(`Invalid config file path: ${relativePath}`);
|
|
44
|
+
return configName;
|
|
43
45
|
}
|
|
44
46
|
};
|
|
45
47
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-loader.mjs","names":[],"sources":["../../../../../../../core/src/config/config-loader.ts"],"sourcesContent":["import config from \"@mongez/config\";\r\nimport { colors } from \"@mongez/copper\";\r\nimport { pathToFileURL } from \"node:url\";\r\nimport type { FileManager } from \"../dev-server/file-manager\";\r\nimport { configSpecialHandlers } from \"./config-special-handlers\";\r\n\r\n/**\r\n * Special Config Handler\r\n * A function that handles special configuration loading\r\n */\r\n// Returns unknown, not void: ConfigSpecialHandlers.execute() RETURNS handler(config)\r\n// rather than discarding it, and a test pins that (\"returns the handler's resolved\r\n// value\"). The implementation and the test agreed; only this type said handlers\r\n// produce nothing, which made any value-returning handler fail to typecheck.\r\nexport type SpecialConfigHandler = (configValue: any) => unknown | Promise<unknown>;\r\n\r\n/**\r\n * Config Loader\r\n * Dynamically loads all configuration files and registers them with @mongez/config\r\n * Supports special handlers for configs that require additional processing\r\n */\r\nexport class ConfigLoader {\r\n public async loadAll(configFiles: FileManager[]): Promise<void> {\r\n for (const file of configFiles) {\r\n await this.loadConfig(file);\r\n }\r\n }\r\n\r\n /**\r\n * Load a single configuration file.\r\n *\r\n * The ESM loader hook stamps a version token onto the URL so that each HMR\r\n * cycle gets a fresh module — no manual cache-busting needed here.\r\n */\r\n public async loadConfig(file: FileManager): Promise<void> {\r\n const configName = this.getConfigName(file.relativePath);\r\n\r\n try {\r\n const fileUrl = pathToFileURL(file.absolutePath).href;\r\n const configModule = await import(fileUrl);\r\n const configValue = configModule.default;\r\n\r\n if (configValue === undefined) {\r\n console.log(\r\n colors.red(`config error: `),\r\n `Config file ${colors.yellow(file.relativePath)} does not have a default export`,\r\n );\r\n return;\r\n }\r\n\r\n config.set(configName, configValue);\r\n await configSpecialHandlers.execute(configName, configValue);\r\n } catch (error) {\r\n throw error;\r\n }\r\n }\r\n\r\n public async reloadConfig(file: FileManager): Promise<void> {\r\n await this.loadConfig(file);\r\n }\r\n\r\n private getConfigName(relativePath: string): string {\r\n const match = relativePath.match(/^src\\/config\\/(.+)\\.(ts|tsx)$/);\r\n\r\n if (!match) {\r\n throw new Error(`Invalid config file path: ${relativePath}`);\r\n }\r\n\r\n
|
|
1
|
+
{"version":3,"file":"config-loader.mjs","names":[],"sources":["../../../../../../../core/src/config/config-loader.ts"],"sourcesContent":["import config from \"@mongez/config\";\r\nimport { colors } from \"@mongez/copper\";\r\nimport { pathToFileURL } from \"node:url\";\r\nimport type { FileManager } from \"../dev-server/file-manager\";\r\nimport { configSpecialHandlers } from \"./config-special-handlers\";\r\n\r\n/**\r\n * Special Config Handler\r\n * A function that handles special configuration loading\r\n */\r\n// Returns unknown, not void: ConfigSpecialHandlers.execute() RETURNS handler(config)\r\n// rather than discarding it, and a test pins that (\"returns the handler's resolved\r\n// value\"). The implementation and the test agreed; only this type said handlers\r\n// produce nothing, which made any value-returning handler fail to typecheck.\r\nexport type SpecialConfigHandler = (configValue: any) => unknown | Promise<unknown>;\r\n\r\n/**\r\n * Config Loader\r\n * Dynamically loads all configuration files and registers them with @mongez/config\r\n * Supports special handlers for configs that require additional processing\r\n */\r\nexport class ConfigLoader {\r\n public async loadAll(configFiles: FileManager[]): Promise<void> {\r\n for (const file of configFiles) {\r\n await this.loadConfig(file);\r\n }\r\n }\r\n\r\n /**\r\n * Load a single configuration file.\r\n *\r\n * The ESM loader hook stamps a version token onto the URL so that each HMR\r\n * cycle gets a fresh module — no manual cache-busting needed here.\r\n */\r\n public async loadConfig(file: FileManager): Promise<void> {\r\n const configName = this.getConfigName(file.relativePath);\r\n\r\n try {\r\n const fileUrl = pathToFileURL(file.absolutePath).href;\r\n const configModule = await import(fileUrl);\r\n const configValue = configModule.default;\r\n\r\n if (configValue === undefined) {\r\n console.log(\r\n colors.red(`config error: `),\r\n `Config file ${colors.yellow(file.relativePath)} does not have a default export`,\r\n );\r\n return;\r\n }\r\n\r\n config.set(configName, configValue);\r\n await configSpecialHandlers.execute(configName, configValue);\r\n } catch (error) {\r\n throw error;\r\n }\r\n }\r\n\r\n public async reloadConfig(file: FileManager): Promise<void> {\r\n await this.loadConfig(file);\r\n }\r\n\r\n private getConfigName(relativePath: string): string {\r\n const match = relativePath.match(/^src\\/config\\/(.+)\\.(ts|tsx)$/);\r\n\r\n if (!match) {\r\n throw new Error(`Invalid config file path: ${relativePath}`);\r\n }\r\n\r\n const configName = match[1];\n\n if (!configName) {\n throw new Error(`Invalid config file path: ${relativePath}`);\n }\n\n return configName;\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;AAqBA,IAAa,eAAb,MAA0B;CACxB,MAAa,QAAQ,aAA2C;EAC9D,KAAK,MAAM,QAAQ,aACjB,MAAM,KAAK,WAAW,IAAI;CAE9B;;;;;;;CAQA,MAAa,WAAW,MAAkC;EACxD,MAAM,aAAa,KAAK,cAAc,KAAK,YAAY;EAEvD,IAAI;GAGF,MAAM,eAAc,MADO,OADX,cAAc,KAAK,YAAY,CAAC,CAAC,MAEjB,CAAC;GAEjC,IAAI,gBAAgB,QAAW;IAC7B,QAAQ,IACN,OAAO,IAAI,gBAAgB,GAC3B,eAAe,OAAO,OAAO,KAAK,YAAY,EAAE,gCAClD;IACA;GACF;GAEA,OAAO,IAAI,YAAY,WAAW;GAClC,MAAM,sBAAsB,QAAQ,YAAY,WAAW;EAC7D,SAAS,OAAO;GACd,MAAM;EACR;CACF;CAEA,MAAa,aAAa,MAAkC;EAC1D,MAAM,KAAK,WAAW,IAAI;CAC5B;CAEA,AAAQ,cAAc,cAA8B;EAClD,MAAM,QAAQ,aAAa,MAAM,+BAA+B;EAEhE,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,6BAA6B,cAAc;EAG7D,MAAM,aAAa,MAAM;EAEzB,IAAI,CAAC,YACH,MAAM,IAAI,MAAM,6BAA6B,cAAc;EAG7D,OAAO;CACT;AACF"}
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
//#region ../core/src/config/locale-configuration.ts
|
|
2
|
+
/**
|
|
3
|
+
* The name of the cookie the framework uses to persist a request's locale
|
|
4
|
+
* across requests.
|
|
5
|
+
*
|
|
6
|
+
* The ONE place this string is written. `Request.resolveLocale()` reads it,
|
|
7
|
+
* `Response.setLocale()` writes it; neither hardcodes the literal. Changing
|
|
8
|
+
* this constant changes both sides together instead of requiring two edits
|
|
9
|
+
* that can silently fall out of sync.
|
|
10
|
+
*/
|
|
11
|
+
const LOCALE_COOKIE_NAME = "locale";
|
|
2
12
|
function isNonEmptyStringArray(value) {
|
|
3
13
|
return Array.isArray(value) && value.length > 0 && value.every((candidate) => typeof candidate === "string");
|
|
4
14
|
}
|
|
@@ -25,5 +35,5 @@ function assertLocaleConfiguration(config) {
|
|
|
25
35
|
}
|
|
26
36
|
|
|
27
37
|
//#endregion
|
|
28
|
-
export { assertLocaleConfiguration, resolveLocaleConfiguration };
|
|
38
|
+
export { LOCALE_COOKIE_NAME, assertLocaleConfiguration, resolveLocaleConfiguration };
|
|
29
39
|
//# sourceMappingURL=locale-configuration.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"locale-configuration.mjs","names":[],"sources":["../../../../../../../core/src/config/locale-configuration.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"locale-configuration.mjs","names":[],"sources":["../../../../../../../core/src/config/locale-configuration.ts"],"sourcesContent":["/**\n * The name of the cookie the framework uses to persist a request's locale\n * across requests.\n *\n * The ONE place this string is written. `Request.resolveLocale()` reads it,\n * `Response.setLocale()` writes it; neither hardcodes the literal. Changing\n * this constant changes both sides together instead of requiring two edits\n * that can silently fall out of sync.\n */\nexport const LOCALE_COOKIE_NAME = \"locale\";\n\nexport type LocaleConfiguration = {\n defaultLocaleCode: string;\n /**\n * The declared allow-list, or `undefined` when the application declares none.\n *\n * The absence of a list is NOT an implicit list of one. With nothing to\n * validate against, a client locale has nothing it can fail — coercing it to\n * the default would discard what the client actually asked for.\n */\n localeCodes: string[] | undefined;\n};\n\ntype AppLocaleConfiguration = {\n localeCode?: unknown;\n localeCodes?: unknown;\n};\n\nfunction isNonEmptyStringArray(value: unknown): value is string[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every((candidate) => typeof candidate === \"string\")\n );\n}\n\n/**\n * Resolve the locale configuration used by every request.\n *\n * It fails closed only where there is a declared allow-list to fail against;\n * an application that declares none opts out of validation, not into a\n * single-locale list.\n */\nexport function resolveLocaleConfiguration(\n localeCode: unknown,\n localeCodes: unknown,\n): LocaleConfiguration {\n const defaultLocaleCode =\n typeof localeCode === \"string\" && localeCode.length > 0 ? localeCode : \"en\";\n\n return {\n defaultLocaleCode,\n localeCodes: isNonEmptyStringArray(localeCodes) ? localeCodes : undefined,\n };\n}\n\n/**\n * A default outside the declared list makes every fallback contradictory, so\n * configuration loading must stop before the application can accept requests.\n */\nexport function assertLocaleConfiguration(config: AppLocaleConfiguration): void {\n const { defaultLocaleCode } = resolveLocaleConfiguration(config.localeCode, config.localeCodes);\n\n if (\n isNonEmptyStringArray(config.localeCodes) &&\n !config.localeCodes.includes(defaultLocaleCode)\n ) {\n throw new Error(\n `app.localeCodes does not include the resolved default locale \"${defaultLocaleCode}\". ` +\n `Add \"${defaultLocaleCode}\" to app.localeCodes or change app.localeCode; ` +\n `boot cannot continue with a default that the application does not support.`,\n );\n }\n}\n"],"mappings":";;;;;;;;;;AASA,MAAa,qBAAqB;AAmBlC,SAAS,sBAAsB,OAAmC;CAChE,OACE,MAAM,QAAQ,KAAK,KACnB,MAAM,SAAS,KACf,MAAM,OAAO,cAAc,OAAO,cAAc,QAAQ;AAE5D;;;;;;;;AASA,SAAgB,2BACd,YACA,aACqB;CAIrB,OAAO;EACL,mBAHA,OAAO,eAAe,YAAY,WAAW,SAAS,IAAI,aAAa;EAIvE,aAAa,sBAAsB,WAAW,IAAI,cAAc;CAClE;AACF;;;;;AAMA,SAAgB,0BAA0B,QAAsC;CAC9E,MAAM,EAAE,sBAAsB,2BAA2B,OAAO,YAAY,OAAO,WAAW;CAE9F,IACE,sBAAsB,OAAO,WAAW,KACxC,CAAC,OAAO,YAAY,SAAS,iBAAiB,GAE9C,MAAM,IAAI,MACR,iEAAiE,kBAAkB,UACzE,kBAAkB,0HAE9B;AAEJ"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
//#region ../core/src/container/container-instance-registry.ts
|
|
2
|
+
/**
|
|
3
|
+
* `globalThis` key the registry is stored under. A `Symbol.for` registry
|
|
4
|
+
* key (not a module-scope variable) is required because the whole point of
|
|
5
|
+
* this file is that it gets evaluated more than once per process — Vite's
|
|
6
|
+
* SSR module runner and Node's ESM loader each hold their own copy of
|
|
7
|
+
* `@warlock.js/core` in the monorepo dev path, and `globalThis` is the only
|
|
8
|
+
* object both evaluations actually share.
|
|
9
|
+
*/
|
|
10
|
+
const registryKey = Symbol.for("warlock.js/core/container-instance-registry");
|
|
11
|
+
function getRegistry() {
|
|
12
|
+
const globalWithRegistry = globalThis;
|
|
13
|
+
if (!globalWithRegistry[registryKey]) globalWithRegistry[registryKey] = [];
|
|
14
|
+
return globalWithRegistry[registryKey];
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Registers this module evaluation as a live container instance.
|
|
18
|
+
*
|
|
19
|
+
* Called once at module load, and only ever appends — it never reads back
|
|
20
|
+
* what it just wrote to decide anything, so it cannot itself judge whether
|
|
21
|
+
* a duplicate exists. That judgment happens later, and only on the
|
|
22
|
+
* container's miss/throw path (see `getRegisteredContainerInstanceCount`
|
|
23
|
+
* usage in `index.ts`), specifically so re-evaluation under a test runner's
|
|
24
|
+
* module reset is never mistaken for duplication at load time.
|
|
25
|
+
*/
|
|
26
|
+
function registerContainerInstance() {
|
|
27
|
+
const record = { id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}` };
|
|
28
|
+
if (typeof import.meta !== "undefined" && import.meta.url) record.moduleUrl = import.meta.url;
|
|
29
|
+
getRegistry().push(record);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* All container instances registered on this process/runtime so far.
|
|
33
|
+
*/
|
|
34
|
+
function getRegisteredContainerInstances() {
|
|
35
|
+
return getRegistry();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
//#endregion
|
|
39
|
+
export { getRegisteredContainerInstances, registerContainerInstance };
|
|
40
|
+
//# sourceMappingURL=container-instance-registry.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"container-instance-registry.mjs","names":[],"sources":["../../../../../../../core/src/container/container-instance-registry.ts"],"sourcesContent":["/**\n * A single loaded copy of the container module, as seen by\n * {@link registerContainerInstance}.\n */\nexport type ContainerInstanceRecord = {\n /**\n * Generated once per module evaluation — never derived from anything a\n * duplicate evaluation could coincidentally share.\n */\n id: string;\n /**\n * `import.meta.url` of this evaluation, when the runtime exposes it\n * cheaply. Omitted rather than guessed when unavailable.\n */\n moduleUrl?: string;\n};\n\n/**\n * `globalThis` key the registry is stored under. A `Symbol.for` registry\n * key (not a module-scope variable) is required because the whole point of\n * this file is that it gets evaluated more than once per process — Vite's\n * SSR module runner and Node's ESM loader each hold their own copy of\n * `@warlock.js/core` in the monorepo dev path, and `globalThis` is the only\n * object both evaluations actually share.\n */\nconst registryKey = Symbol.for(\"warlock.js/core/container-instance-registry\");\n\ntype GlobalWithContainerRegistry = typeof globalThis & {\n [registryKey]?: ContainerInstanceRecord[];\n};\n\nfunction getRegistry(): ContainerInstanceRecord[] {\n const globalWithRegistry = globalThis as GlobalWithContainerRegistry;\n\n if (!globalWithRegistry[registryKey]) {\n globalWithRegistry[registryKey] = [];\n }\n\n return globalWithRegistry[registryKey];\n}\n\n/**\n * Registers this module evaluation as a live container instance.\n *\n * Called once at module load, and only ever appends — it never reads back\n * what it just wrote to decide anything, so it cannot itself judge whether\n * a duplicate exists. That judgment happens later, and only on the\n * container's miss/throw path (see `getRegisteredContainerInstanceCount`\n * usage in `index.ts`), specifically so re-evaluation under a test runner's\n * module reset is never mistaken for duplication at load time.\n */\nexport function registerContainerInstance(): void {\n const record: ContainerInstanceRecord = {\n id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,\n };\n\n if (typeof import.meta !== \"undefined\" && import.meta.url) {\n record.moduleUrl = import.meta.url;\n }\n\n getRegistry().push(record);\n}\n\n/**\n * All container instances registered on this process/runtime so far.\n */\nexport function getRegisteredContainerInstances(): readonly ContainerInstanceRecord[] {\n return getRegistry();\n}\n\n/**\n * Clears the registry. Test-only: lets a spec simulate a second loaded\n * instance, or reset back to the innocent single-instance case, without\n * actually loading a second copy of the module.\n */\nexport function resetContainerInstanceRegistryForTests(): void {\n getRegistry().length = 0;\n}\n"],"mappings":";;;;;;;;;AAyBA,MAAM,cAAc,OAAO,IAAI,6CAA6C;AAM5E,SAAS,cAAyC;CAChD,MAAM,qBAAqB;CAE3B,IAAI,CAAC,mBAAmB,cACtB,mBAAmB,eAAe,CAAC;CAGrC,OAAO,mBAAmB;AAC5B;;;;;;;;;;;AAYA,SAAgB,4BAAkC;CAChD,MAAM,SAAkC,EACtC,IAAI,GAAG,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC,IACtE;CAEA,IAAI,OAAO,OAAO,SAAS,eAAe,OAAO,KAAK,KACpD,OAAO,YAAY,OAAO,KAAK;CAGjC,YAAY,CAAC,CAAC,KAAK,MAAM;AAC3B;;;;AAKA,SAAgB,kCAAsE;CACpF,OAAO,YAAY;AACrB"}
|
|
@@ -30,6 +30,17 @@ declare class Container {
|
|
|
30
30
|
* Check if a key exists in the container
|
|
31
31
|
*/
|
|
32
32
|
has(key: ContainerKeys): boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Get a value from the container, or throw if `key` is not registered.
|
|
35
|
+
*
|
|
36
|
+
* Behaves exactly like an ordinary "not registered" error when only one
|
|
37
|
+
* copy of this module is loaded. When {@link getRegisteredContainerInstances}
|
|
38
|
+
* shows more than one, the thrown error additionally names that count, so
|
|
39
|
+
* a duplicate-instance dev-path miss is never indistinguishable from a
|
|
40
|
+
* genuine missing registration.
|
|
41
|
+
*/
|
|
42
|
+
getOrFail<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];
|
|
43
|
+
getOrFail<T = any>(key: string): T;
|
|
33
44
|
/**
|
|
34
45
|
* Delete a key from the container
|
|
35
46
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../core/src/container/index.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../core/src/container/index.ts"],"mappings":";;;;;;;;;KAiBY,cAAA;EACV,MAAA,EAAQ,MAAA;EACR,aAAA,EAAe,eAAA;EACf,cAAA;EACA,MAAA,EAAQ,MAAA;EACR,iBAAA,EAAmB,UAAA;AAAA;AAAA,KAGhB,aAAA,SAAsB,cAAc;AAAA,cAEnC,SAAA;EATJ;;;EAaO,GAAA,iBAAoB,cAAA,EAAgB,GAAA,EAAK,CAAA,EAAG,KAAA,EAAO,cAAA,CAAe,CAAA;EAClE,GAAA,UAAa,GAAA,UAAa,KAAA,EAAO,CAAA;EAXxC;;;EAmBO,GAAA,iBAAoB,cAAA,EAAgB,GAAA,EAAK,CAAA,GAAI,cAAA,CAAe,CAAA;EAC5D,GAAA,UAAa,GAAA,WAAc,CAAA;EAnBL;AAC7B;;EA0BO,GAAA,CAAI,GAAA,EAAK,aAAA;EAxBuB;AAAA;AAAA;;;;;;;EAqChC,SAAA,iBAA0B,cAAA,EAAgB,GAAA,EAAK,CAAA,GAAI,cAAA,CAAe,CAAA;EAClE,SAAA,UAAmB,GAAA,WAAc,CAAA;EAvBQ;;;EAoCzC,MAAA,CAAO,GAAA;AAAA;AAAA,cAKH,SAAA,EAAS,SAAkB"}
|
package/esm/container/index.mjs
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
import { ContainerKeyMissingError } from "../errors/container-key-missing-error.mjs";
|
|
2
|
+
import { getRegisteredContainerInstances, registerContainerInstance } from "./container-instance-registry.mjs";
|
|
3
|
+
|
|
1
4
|
//#region ../core/src/container/index.ts
|
|
2
5
|
const containerMap = /* @__PURE__ */ new Map();
|
|
6
|
+
registerContainerInstance();
|
|
3
7
|
var Container = class {
|
|
4
8
|
set(key, value) {
|
|
5
9
|
containerMap.set(key, value);
|
|
@@ -13,6 +17,13 @@ var Container = class {
|
|
|
13
17
|
has(key) {
|
|
14
18
|
return containerMap.has(key);
|
|
15
19
|
}
|
|
20
|
+
getOrFail(key) {
|
|
21
|
+
if (!containerMap.has(key)) {
|
|
22
|
+
const instanceCount = getRegisteredContainerInstances().length;
|
|
23
|
+
throw new ContainerKeyMissingError(key, instanceCount);
|
|
24
|
+
}
|
|
25
|
+
return containerMap.get(key);
|
|
26
|
+
}
|
|
16
27
|
/**
|
|
17
28
|
* Delete a key from the container
|
|
18
29
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../core/src/container/index.ts"],"sourcesContent":["import { type DataSource } from \"@warlock.js/cascade\";\nimport { type FastifyInstance } from \"fastify\";\nimport { type Server } from \"socket.io\";\nimport { type Router } from \"../router\";\n\nconst containerMap: Map<string, any> = new Map();\n\n/**\n * Known container types for better IDE support\n */\nexport type ContainerTypes = {\n router: Router;\n \"http.server\": FastifyInstance;\n \"http.baseUrl\": string;\n socket: Server;\n \"database.source\": DataSource;\n};\n\ntype ContainerKeys = keyof ContainerTypes | (string & {});\n\nclass Container {\n /**\n * Set a value in the container\n */\n public set<K extends keyof ContainerTypes>(key: K, value: ContainerTypes[K]): void;\n public set<T = any>(key: string, value: T): void;\n public set(key: any, value: any) {\n containerMap.set(key, value);\n }\n\n /**\n * Get a value from the container\n */\n public get<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];\n public get<T = any>(key: string): T;\n public get(key: any): any {\n return containerMap.get(key);\n }\n\n /**\n * Check if a key exists in the container\n */\n public has(key: ContainerKeys) {\n return containerMap.has(key);\n }\n\n /**\n * Delete a key from the container\n */\n public delete(key: string) {\n containerMap.delete(key);\n }\n}\n\nexport const container = new Container();\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../core/src/container/index.ts"],"sourcesContent":["import { type DataSource } from \"@warlock.js/cascade\";\nimport { type FastifyInstance } from \"fastify\";\nimport { type Server } from \"socket.io\";\nimport { ContainerKeyMissingError } from \"../errors/container-key-missing-error\";\nimport { type Router } from \"../router\";\nimport {\n getRegisteredContainerInstances,\n registerContainerInstance,\n} from \"./container-instance-registry\";\n\nconst containerMap: Map<string, any> = new Map();\n\nregisterContainerInstance();\n\n/**\n * Known container types for better IDE support\n */\nexport type ContainerTypes = {\n router: Router;\n \"http.server\": FastifyInstance;\n \"http.baseUrl\": string;\n socket: Server;\n \"database.source\": DataSource;\n};\n\ntype ContainerKeys = keyof ContainerTypes | (string & {});\n\nclass Container {\n /**\n * Set a value in the container\n */\n public set<K extends keyof ContainerTypes>(key: K, value: ContainerTypes[K]): void;\n public set<T = any>(key: string, value: T): void;\n public set(key: any, value: any) {\n containerMap.set(key, value);\n }\n\n /**\n * Get a value from the container\n */\n public get<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];\n public get<T = any>(key: string): T;\n public get(key: any): any {\n return containerMap.get(key);\n }\n\n /**\n * Check if a key exists in the container\n */\n public has(key: ContainerKeys) {\n return containerMap.has(key);\n }\n\n /**\n * Get a value from the container, or throw if `key` is not registered.\n *\n * Behaves exactly like an ordinary \"not registered\" error when only one\n * copy of this module is loaded. When {@link getRegisteredContainerInstances}\n * shows more than one, the thrown error additionally names that count, so\n * a duplicate-instance dev-path miss is never indistinguishable from a\n * genuine missing registration.\n */\n public getOrFail<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];\n public getOrFail<T = any>(key: string): T;\n public getOrFail(key: any): any {\n if (!containerMap.has(key)) {\n const instanceCount = getRegisteredContainerInstances().length;\n throw new ContainerKeyMissingError(key, instanceCount);\n }\n\n return containerMap.get(key);\n }\n\n /**\n * Delete a key from the container\n */\n public delete(key: string) {\n containerMap.delete(key);\n }\n}\n\nexport const container = new Container();\n"],"mappings":";;;;AAUA,MAAM,+BAAiC,IAAI,IAAI;AAE/C,0BAA0B;AAe1B,IAAM,YAAN,MAAgB;CAMd,AAAO,IAAI,KAAU,OAAY;EAC/B,aAAa,IAAI,KAAK,KAAK;CAC7B;CAOA,AAAO,IAAI,KAAe;EACxB,OAAO,aAAa,IAAI,GAAG;CAC7B;;;;CAKA,AAAO,IAAI,KAAoB;EAC7B,OAAO,aAAa,IAAI,GAAG;CAC7B;CAaA,AAAO,UAAU,KAAe;EAC9B,IAAI,CAAC,aAAa,IAAI,GAAG,GAAG;GAC1B,MAAM,gBAAgB,gCAAgC,CAAC,CAAC;GACxD,MAAM,IAAI,yBAAyB,KAAK,aAAa;EACvD;EAEA,OAAO,aAAa,IAAI,GAAG;CAC7B;;;;CAKA,AAAO,OAAO,KAAa;EACzB,aAAa,OAAO,GAAG;CACzB;AACF;AAEA,MAAa,YAAY,IAAI,UAAU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"drop-tables-action.mjs","names":[],"sources":["../../../../../../../core/src/database/drop-tables-action.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport { dataSourceRegistry, dropAllTables } from \"@warlock.js/cascade\";\r\nimport { log } from \"@warlock.js/logger\";\r\nimport { confirm } from \"../cli/commands/generate/utils/prompt\";\r\nimport type { CommandActionData } from \"../commands/types\";\r\n\r\nexport async function dropTablesAction(command: CommandActionData) {\r\n const { force } = command.options;\r\n\r\n if (force) {\r\n const { dropped } = await dropAllTables();\r\n log.success(\
|
|
1
|
+
{"version":3,"file":"drop-tables-action.mjs","names":[],"sources":["../../../../../../../core/src/database/drop-tables-action.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport { dataSourceRegistry, dropAllTables } from \"@warlock.js/cascade\";\r\nimport { log } from \"@warlock.js/logger\";\r\nimport { confirm } from \"../cli/commands/generate/utils/prompt\";\r\nimport type { CommandActionData } from \"../commands/types\";\r\n\r\nexport async function dropTablesAction(command: CommandActionData) {\r\n const { force } = command.options;\r\n\r\n if (force) {\r\n const { dropped } = await dropAllTables();\r\n log.success(\"database\", \"drop\", `Dropped ${colors.yellowBright(dropped)} tables successfully.`);\r\n return;\r\n }\r\n\r\n // Preview phase — we keep direct driver access so we can show per-table\r\n // row counts before asking for confirmation. The actual drop still goes\r\n // through the Cascade Operations API.\r\n const driver = dataSourceRegistry.get().driver;\r\n const tables = await driver.blueprint.listTables();\r\n\r\n if (tables.length === 0) {\r\n log.warn(\"database\", \"drop\", \"No tables found in the database.\");\r\n return;\r\n }\r\n\r\n log.info(\"database\", \"drop\", `Found ${colors.yellowBright(tables.length)} tables:`);\r\n\r\n for (const table of tables) {\r\n const count = await driver.queryBuilder(table).count();\r\n console.log(` - ${colors.cyan(table)}: ${colors.green(count)} rows`);\r\n }\r\n\r\n const confirmed = await confirm(\r\n `Are you sure you want to drop all ${colors.red(tables.length)} tables?`,\r\n );\r\n\r\n if (!confirmed) {\r\n log.info(\"database\", \"drop\", \"Operation cancelled.\");\r\n return;\r\n }\r\n\r\n const { dropped } = await dropAllTables();\r\n\r\n log.success(\"database\", \"drop\", `Dropped ${colors.yellowBright(dropped)} tables successfully.`);\r\n}\r\n"],"mappings":";;;;;;AAMA,eAAsB,iBAAiB,SAA4B;CACjE,MAAM,EAAE,UAAU,QAAQ;CAE1B,IAAI,OAAO;EACT,MAAM,EAAE,YAAY,MAAM,cAAc;EACxC,IAAI,QAAQ,YAAY,QAAQ,WAAW,OAAO,aAAa,OAAO,EAAE,sBAAsB;EAC9F;CACF;CAKA,MAAM,SAAS,mBAAmB,IAAI,CAAC,CAAC;CACxC,MAAM,SAAS,MAAM,OAAO,UAAU,WAAW;CAEjD,IAAI,OAAO,WAAW,GAAG;EACvB,IAAI,KAAK,YAAY,QAAQ,kCAAkC;EAC/D;CACF;CAEA,IAAI,KAAK,YAAY,QAAQ,SAAS,OAAO,aAAa,OAAO,MAAM,EAAE,SAAS;CAElF,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,QAAQ,MAAM,OAAO,aAAa,KAAK,CAAC,CAAC,MAAM;EACrD,QAAQ,IAAI,OAAO,OAAO,KAAK,KAAK,EAAE,IAAI,OAAO,MAAM,KAAK,EAAE,MAAM;CACtE;CAMA,IAAI,CAAC,MAJmB,QACtB,qCAAqC,OAAO,IAAI,OAAO,MAAM,EAAE,SACjE,GAEgB;EACd,IAAI,KAAK,YAAY,QAAQ,sBAAsB;EACnD;CACF;CAEA,MAAM,EAAE,YAAY,MAAM,cAAc;CAExC,IAAI,QAAQ,YAAY,QAAQ,WAAW,OAAO,aAAa,OAAO,EAAE,sBAAsB;AAChG"}
|