@brickkit/cli 0.12.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/dashboard-dist/{api-reference-B-bZRtNV.js → api-reference-mT9VNcPb.js} +69 -69
  2. package/dashboard-dist/app.css +1 -1
  3. package/dashboard-dist/app.js +12 -13
  4. package/dashboard-dist/{client-BJJtVSVr.js → client-CwATkLJa.js} +1 -1
  5. package/dashboard-dist/{core-Z7NJFk0K.js → core-BEUWp6B5.js} +1 -1
  6. package/dashboard-dist/docs-BRrtyxDB.js +4 -0
  7. package/dashboard-dist/kit.js +1 -1
  8. package/dashboard-dist/popover-Bj9x-88h.js +1 -0
  9. package/dist/bin.js +154 -217
  10. package/dist/bin.js.map +1 -1
  11. package/dist/build.js +463 -0
  12. package/dist/build.js.map +1 -0
  13. package/dist/client-contract-file.js +356 -1
  14. package/dist/client-contract-file.js.map +1 -0
  15. package/dist/compiler.d.ts +12 -2
  16. package/dist/compiler2.js +12 -5
  17. package/dist/compiler2.js.map +1 -1
  18. package/dist/config.d.ts +3 -0
  19. package/dist/config.js +1 -250
  20. package/dist/config2.d.ts +122 -0
  21. package/dist/config2.js +207 -0
  22. package/dist/config2.js.map +1 -0
  23. package/dist/dashboard-extension.d.ts +3 -0
  24. package/dist/{dev-telemetry-store.js → dashboard-host.js} +1533 -1574
  25. package/dist/dashboard-host.js.map +1 -0
  26. package/dist/dashboard-protocol.js +189 -0
  27. package/dist/dashboard-protocol.js.map +1 -0
  28. package/dist/dashboard.d.ts +4 -1
  29. package/dist/definitions.js +33 -0
  30. package/dist/definitions.js.map +1 -0
  31. package/dist/dev-application.js +34 -0
  32. package/dist/dev-application.js.map +1 -0
  33. package/dist/dev-protocol.js +21 -0
  34. package/dist/dev-protocol.js.map +1 -0
  35. package/dist/dev-reporter.js +2 -1
  36. package/dist/dev-reporter.js.map +1 -1
  37. package/dist/dev-telemetry.js +5 -20
  38. package/dist/dev-telemetry.js.map +1 -1
  39. package/dist/dev-worker.js +79 -19
  40. package/dist/dev-worker.js.map +1 -1
  41. package/dist/index.d.ts +15 -74
  42. package/dist/index.js +12 -5
  43. package/dist/index.js.map +1 -0
  44. package/dist/lint/oxlint.js +5 -3
  45. package/dist/lint/oxlint.js.map +1 -1
  46. package/dist/own-module.js +7 -0
  47. package/dist/own-module.js.map +1 -0
  48. package/dist/plugin.d.ts +6 -5
  49. package/dist/plugin.js +5 -39
  50. package/dist/plugin.js.map +1 -1
  51. package/dist/production-dashboard.d.ts +2 -0
  52. package/dist/production-dashboard.js +51 -0
  53. package/dist/production-dashboard.js.map +1 -0
  54. package/dist/production-dashboard2.d.ts +34 -0
  55. package/dist/{presets.js → project.js} +104 -106
  56. package/dist/project.js.map +1 -0
  57. package/dist/serve.d.ts +24 -0
  58. package/dist/serve.js +1 -0
  59. package/dist/serve2.js +49 -0
  60. package/dist/serve2.js.map +1 -0
  61. package/dist/vite.js +26 -47
  62. package/dist/vite.js.map +1 -1
  63. package/dist/workflows.d.ts +2 -2
  64. package/dist/workflows2.js +59 -37
  65. package/dist/workflows2.js.map +1 -1
  66. package/inspector-dist/client/assets/app-CeSwVsRm.css +2 -0
  67. package/inspector-dist/client/assets/{highlighted-body-B3W2YXNL-DYVdwGy2.js → highlighted-body-B3W2YXNL-CfRnuITN.js} +1 -1
  68. package/inspector-dist/client/assets/{home-CyjkvtII.js → home-hwPlkNhv.js} +1529 -378
  69. package/inspector-dist/client/assets/manifest-0e76e9ac.js +1 -0
  70. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-ZDR2PNY_.js +1 -0
  71. package/inspector-dist/client/assets/root-ChBNTZd2.css +2 -0
  72. package/inspector-dist/client/assets/{root-DX9wtogx.js → root-SLeEf-sT.js} +17 -29
  73. package/inspector-dist/client/assets/{run-detail-C69EJGql.js → run-detail-DYbVkIFH.js} +398 -76
  74. package/inspector-dist/client/assets/{tabs-B6B88IjT.js → tabs-CaJisoyb.js} +189 -2130
  75. package/inspector-dist/client/assets/{zstd-browser-decoder-ByUgcY9H.js → zstd-browser-decoder-D94wmfAU.js} +1 -1
  76. package/inspector-dist/server/assets/{app-WoDoT62X.js → app-DGlfWVUI.js} +69783 -70608
  77. package/inspector-dist/server/assets/{chunk-RLXIAIE6-CbvDIAEa.js → chunk-RLXIAIE6-F0SJZlei.js} +4 -6
  78. package/inspector-dist/server/assets/{dist-qR-969AD.js → dist-BCbwm6jl.js} +2 -4
  79. package/inspector-dist/server/assets/{dist-CQnQcIJg.js → dist-CG2aVufI.js} +0 -2
  80. package/inspector-dist/server/assets/{dist-BRxZSWUN.js → dist-Ce0I2PUv.js} +2 -5
  81. package/inspector-dist/server/assets/{dist-DqRd9pyS.js → dist-DY0UlahA.js} +0 -2
  82. package/inspector-dist/server/assets/{encryption-_PuklZNX.js → encryption-DdQgC8Rk.js} +2 -4
  83. package/inspector-dist/server/assets/{event-metadata-BVakQJ_y.js → event-metadata-n7E4zEmT.js} +0 -2
  84. package/inspector-dist/server/assets/{functions-CImcpqNl.js → functions-CNVQtbgg.js} +2 -4
  85. package/inspector-dist/server/assets/{global-singleton-CPirHxFh.js → global-singleton-D8sIN5du.js} +0 -2
  86. package/inspector-dist/server/assets/{highlighted-body-B3W2YXNL-fPMB_t7F.js → highlighted-body-B3W2YXNL-CWRzMxYD.js} +2 -4
  87. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-D0v0ngVr.js +1 -0
  88. package/inspector-dist/server/assets/{parse-D9Vvgzt9.js → parse-Begau9cA.js} +0 -2
  89. package/inspector-dist/server/assets/{rolldown-runtime-CLg409Sh.js → rolldown-runtime-C1I3wEg2.js} +1 -2
  90. package/inspector-dist/server/assets/{serialization-format-DDtsVTU1.js → serialization-format-BbuGfHog.js} +6 -8
  91. package/inspector-dist/server/assets/{token-BW4GdQZh.js → token-BgMmJNP5.js} +2 -4
  92. package/inspector-dist/server/assets/{token-D6FXdkJT.js → token-BrUX0bxz.js} +2 -4
  93. package/inspector-dist/server/assets/{token-util-BoNmi-wE.js → token-util-DZN32qmT.js} +1 -3
  94. package/inspector-dist/server/assets/{wrapper-wiqsGXcE.js → wrapper-CIC3w0oC.js} +1 -3
  95. package/inspector-dist/server/assets/{ws-transport-DV7oG4mL.js → ws-transport-CxTYB11n.js} +24094 -24096
  96. package/inspector-dist/server/assets/{zstd-browser-decoder-Cswf0KO6.js → zstd-browser-decoder-D7bCXbGg.js} +2 -4
  97. package/inspector-dist/server/index.js +1 -3
  98. package/package.json +12 -2
  99. package/dashboard-dist/docs-Dpfc0wJb.js +0 -4
  100. package/dashboard-dist/popover-BzejBolB.js +0 -1
  101. package/dist/app-entry.js +0 -1
  102. package/dist/app-entry2.js +0 -18
  103. package/dist/app-entry2.js.map +0 -1
  104. package/dist/client-contract-file2.js +0 -33
  105. package/dist/client-contract-file2.js.map +0 -1
  106. package/dist/client-contract.js +0 -1
  107. package/dist/client-contract2.js +0 -296
  108. package/dist/client-contract2.js.map +0 -1
  109. package/dist/config.js.map +0 -1
  110. package/dist/dev-telemetry-store.js.map +0 -1
  111. package/dist/emit.d.ts +0 -5
  112. package/dist/presets.js.map +0 -1
  113. package/dist/runner.js +0 -519
  114. package/dist/runner.js.map +0 -1
  115. package/inspector-dist/client/assets/app-CCzpuUz_.css +0 -2
  116. package/inspector-dist/client/assets/manifest-ba30b52d.js +0 -1
  117. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-Dy6IVqPy.js +0 -1
  118. package/inspector-dist/client/assets/root-8BMab1lL.css +0 -2
  119. package/inspector-dist/client/assets/world-config-context-C3BqXPIv.js +0 -30
  120. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-bADXySE3.js +0 -3
package/dist/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bin.js","names":["posix","cliPkg.version"],"sources":["../src/lint/run.ts","../src/lint.ts","../src/db.ts","../package.json","../src/bin.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { ConfigError } from \"../config\";\nimport type { BrickSettings } from \"./ast\";\nimport type { Severity } from \"./presets\";\n\nexport interface LintMessage {\n /** Path from the project root. */\n file: string;\n line: number;\n column: number;\n /** `brick/<rule>`. */\n rule: string;\n severity: \"error\" | \"warn\";\n message: string;\n}\n\n/** The built lint/oxlint entry, which oxlint loads under Node. */\nfunction pluginPath() {\n const here = fileURLToPath(import.meta.url);\n // From source (tests run src/ under Bun), use the build; bundled, this code sits in dist/.\n return here.endsWith(\".ts\")\n ? resolve(dirname(here), \"../../dist/lint/oxlint.js\")\n : resolve(dirname(here), \"lint/oxlint.js\");\n}\n\nfunction oxlintBin(root: string) {\n for (const base of [\n join(root, \"package.json\"),\n fileURLToPath(import.meta.url),\n ]) {\n try {\n const pkg = createRequire(base).resolve(\"oxlint/package.json\");\n return join(dirname(pkg), \"bin/oxlint\");\n } catch {\n // not installed there; try the next place\n }\n }\n throw new ConfigError(\n \"Brick: brick lint needs oxlint; add it: bun add -d oxlint\",\n );\n}\n\n/**\n * Run the file rules over a project with oxlint, as `brick lint` does.\n * Only rules set to \"error\" or \"warn\" run; `ignore` globs are relative to `root`.\n */\nexport function runFileRules(options: {\n root: string;\n rules: Record<string, Severity>;\n settings: BrickSettings;\n ignore?: string[];\n /** Files or folders to lint, from `root` (default: all of it). */\n paths?: string[];\n fix?: boolean;\n}): LintMessage[] {\n const rules = Object.fromEntries(\n Object.entries(options.rules).filter(([, severity]) => severity !== \"off\"),\n );\n if (Object.keys(rules).length === 0) return [];\n const directory = mkdtempSync(join(tmpdir(), \"brick-lint-\"));\n try {\n const config = join(directory, \"oxlintrc.json\");\n writeFileSync(\n config,\n JSON.stringify({\n plugins: [],\n categories: { correctness: \"off\" },\n jsPlugins: [{ name: \"brick\", specifier: pluginPath() }],\n settings: { brick: options.settings },\n rules,\n }),\n );\n const result = spawnSync(\n oxlintBin(options.root),\n [\n \"-c\",\n config,\n \"--format\",\n \"json\",\n \"--disable-nested-config\",\n \"--no-error-on-unmatched-pattern\",\n ...(options.fix ? [\"--fix\"] : []),\n ...(options.ignore ?? []).flatMap((pattern) => [\n \"--ignore-pattern\",\n pattern,\n ]),\n ...(options.paths ?? [\".\"]),\n ],\n { cwd: options.root, encoding: \"utf8\", maxBuffer: 64 * 1024 * 1024 },\n );\n if (result.error) throw result.error;\n let report: {\n diagnostics?: {\n message: string;\n code?: string;\n severity: string;\n filename: string;\n labels?: { span: { line: number; column: number } }[];\n }[];\n };\n try {\n report = JSON.parse(result.stdout);\n } catch {\n throw new Error(\n `Brick: oxlint failed (exit ${result.status}):\\n${result.stderr || result.stdout}`,\n );\n }\n return (report.diagnostics ?? []).map((diagnostic) => ({\n file: diagnostic.filename,\n line: diagnostic.labels?.[0]?.span.line ?? 1,\n column: diagnostic.labels?.[0]?.span.column ?? 1,\n // Parse errors come without a rule code.\n rule: diagnostic.code?.replace(/^brick\\((.*)\\)$/, \"brick/$1\") ?? \"syntax\",\n severity: diagnostic.severity === \"error\" ? \"error\" : \"warn\",\n message: diagnostic.message,\n }));\n } finally {\n rmSync(directory, { recursive: true, force: true });\n }\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { basename, dirname, relative, resolve, sep } from \"node:path\";\nimport { getPluginActionRoute, kebabCase } from \"@brickkit/core\";\nimport { loadBrickApp, type BrickApp } from \"./app-entry\";\nimport { ConfigError, type LoadedConfig } from \"./config\";\nimport {\n ALWAYS_ERROR,\n fileRules,\n resolveRules,\n type Severity,\n} from \"./lint/presets\";\nimport { runFileRules, type LintMessage } from \"./lint/run\";\nimport { writeServiceManifest } from \"./manifest\";\n\nconst posix = (path: string) => path.split(sep).join(\"/\");\nconst SOURCE = new Bun.Glob(\"**/*.{ts,tsx,mts,cts}\");\n\ninterface AppCheck {\n root: string;\n entry: string;\n services: string;\n severity: (rule: string) => Severity;\n ignored: (rel: string) => boolean;\n}\n\n/**\n * `brick lint`: the file rules through oxlint, then the app\n * rules against the loaded app. Prints `file:line:col` lines and returns the\n * exit code: 1 when anything is an error.\n */\nexport async function runLint(options: {\n entry?: string;\n project?: LoadedConfig;\n}): Promise<number> {\n const { project } = options;\n const root = project?.root ?? process.cwd();\n const config = project?.config.lint ?? {};\n let resolved: Record<string, Severity>;\n try {\n resolved = resolveRules(config.presets, config.rules);\n } catch (error) {\n throw new ConfigError(\n `brick.config.ts: lint.rules: ${(error as Error).message}`,\n );\n }\n const fromRoot = (path: string) => posix(relative(root, path)) || \".\";\n const services = project?.services ?? resolve(root, \"src/services\");\n const generated = project?.generated ?? resolve(root, \"_brick\");\n const entry = options.entry\n ? resolve(options.entry)\n : (project?.entry ?? resolve(root, \"src/app.ts\"));\n const ignore = [...(config.ignore ?? []), `${fromRoot(generated)}/**`];\n const messages = runFileRules({\n root,\n rules: fileRules(resolved),\n settings: {\n root,\n services: fromRoot(services),\n entry: fromRoot(entry),\n generated: fromRoot(generated),\n web: \"web\",\n },\n ignore,\n });\n const globs = ignore.map((pattern) => new Bun.Glob(pattern));\n if (existsSync(entry)) {\n if (project) await writeServiceManifest(project);\n messages.push(\n ...(await checkApp({\n root,\n entry,\n services,\n severity: (rule) =>\n rule === ALWAYS_ERROR\n ? \"error\"\n : (resolved[`brick/${rule}`] ?? \"off\"),\n ignored: (rel) =>\n rel.split(\"/\").includes(\"node_modules\") ||\n globs.some((glob) => glob.match(rel)),\n })),\n );\n } else if (options.entry || project)\n throw new Error(`Brick: entry not found: ${entry}`);\n return report(messages);\n}\n\nfunction report(messages: LintMessage[]): number {\n messages.sort(\n (a, b) =>\n a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column,\n );\n for (const m of messages)\n console.log(\n `${m.file}:${m.line}:${m.column} ${m.severity === \"error\" ? \"error\" : \"warning\"} ${m.message} ${m.rule}`,\n );\n const errors = messages.filter((m) => m.severity === \"error\").length;\n const warnings = messages.length - errors;\n console.log(\n messages.length\n ? `\\n✖ ${messages.length} problem${messages.length === 1 ? \"\" : \"s\"} (${errors} error${errors === 1 ? \"\" : \"s\"}, ${warnings} warning${warnings === 1 ? \"\" : \"s\"})`\n : \"✔ No lint problems\",\n );\n return errors > 0 ? 1 : 0;\n}\n\n/** Project source files, from the root, without tests, ignored and generated files. */\nfunction sourceFiles(check: AppCheck, under = check.root): string[] {\n if (!existsSync(under)) return [];\n return [...SOURCE.scanSync({ cwd: under, onlyFiles: true })]\n .map((file) => resolve(under, file))\n .filter((file) => {\n const rel = posix(relative(check.root, file));\n return (\n !check.ignored(rel) &&\n !/\\.(test|spec)\\.[cm]?tsx?$/.test(rel) &&\n !rel.startsWith(\"dist/\")\n );\n });\n}\n\nfunction lineOf(source: string, index: number) {\n return source.slice(0, index).split(\"\\n\").length;\n}\n\n/** The app rules: they need the loaded app, so only brick lint runs them. */\nasync function checkApp(check: AppCheck): Promise<LintMessage[]> {\n const messages: LintMessage[] = [];\n const add = (rule: string, file: string, message: string, line = 1) => {\n const severity = check.severity(rule);\n if (severity === \"off\") return;\n messages.push({\n file: posix(relative(check.root, file)),\n line,\n column: 1,\n rule: `brick/${rule}`,\n severity,\n message,\n });\n };\n let app: BrickApp;\n try {\n app = await loadBrickApp(check.entry);\n } catch (error) {\n const message = (error as Error).message;\n // Startup refuses duplicate names; report it as the rule, not a crash.\n if (/duplicate/i.test(message)) {\n add(\"unique-names\", check.entry, message);\n return messages;\n }\n throw error;\n }\n const files = sourceFiles(check);\n singleAppEntry(check, files, add);\n uniqueNames(check, app, add);\n await noCrossServiceTables(check, app, add);\n declaredEvents(check, app, add);\n testColocated(check, add);\n return messages;\n}\n\ntype Add = (rule: string, file: string, message: string, line?: number) => void;\n\nfunction singleAppEntry(check: AppCheck, files: string[], add: Add) {\n if (check.severity(\"single-app-entry\") === \"off\") return;\n let calls = 0;\n for (const file of files) {\n const source = readFileSync(file, \"utf8\");\n // shortcut: a text search for brick( in files that import it from core.\n if (\n !/import\\s*\\{[^}]*\\bbrick\\b[^}]*\\}\\s*from\\s*[\"']@brickkit\\/core[\"']/.test(\n source,\n )\n )\n continue;\n for (const match of source.matchAll(/(?<![.\\w])brick\\s*\\(/g)) {\n if (file === check.entry && ++calls === 1) continue;\n add(\n \"single-app-entry\",\n file,\n file === check.entry\n ? \"The entry calls brick() more than once; keep one app.\"\n : `brick() is called outside the entry (${posix(relative(check.root, check.entry))}); keep one app.`,\n lineOf(source, match.index),\n );\n }\n }\n}\n\nfunction uniqueNames(check: AppCheck, app: BrickApp, add: Add) {\n const services = [...app.definition.services];\n const seen = new Set<string>();\n for (const service of services) {\n if (seen.has(service.name))\n add(\n \"unique-names\",\n check.entry,\n `Two services are named \"${service.name}\".`,\n );\n seen.add(service.name);\n // Actions, sockets and resources share the service's URL segments;\n // an explicit path or a resource action takes no segment of its own.\n const owners = new Map<string, string>();\n const claim = (name: string, what: string) => {\n const segment = kebabCase(name);\n const other = owners.get(segment);\n if (other)\n add(\n \"unique-names\",\n check.entry,\n `In service \"${service.name}\", ${what} and ${other} share the name \"${segment}\".`,\n );\n else owners.set(segment, what);\n };\n for (const action of service.listActions())\n if (\n action.config.path === undefined &&\n !(action as { resourceAction?: unknown }).resourceAction &&\n getPluginActionRoute(action) === undefined\n )\n claim(action.name, `action \"${action.name}\"`);\n for (const socket of service.listSockets())\n if (socket.schema.path === undefined)\n claim(socket.schema.name, `socket \"${socket.schema.name}\"`);\n for (const resource of service.listResources())\n claim(resource.name, `resource \"${resource.name}\"`);\n }\n}\n\n/** Which service owns each table: its resources' and registered tables, or a database it alone uses. */\nfunction tableOwners(app: BrickApp) {\n const owners = new Map<unknown, string>();\n const users = new Map<unknown, string[]>();\n for (const service of app.definition.services) {\n for (const table of (\n service as { tables?: Map<string, unknown> }\n ).tables?.values() ?? [])\n owners.set(table, service.name);\n const database = (service.options as { database?: { tables?: object } })\n .database;\n if (database)\n users.set(database, [...(users.get(database) ?? []), service.name]);\n }\n for (const [database, names] of users)\n if (names.length === 1)\n for (const table of Object.values(\n (database as { tables?: object }).tables ?? {},\n ))\n if (!owners.has(table)) owners.set(table, names[0]!);\n return owners;\n}\n\nfunction serviceOfFolder(app: BrickApp, folder: string) {\n return app.definition.services.find(\n (service) => service.name === folder || kebabCase(service.name) === folder,\n )?.name;\n}\n\nconst IMPORT =\n /import\\s+(type\\s+)?([\\w$]+\\s*,?\\s*)?(\\*\\s+as\\s+[\\w$]+|\\{[^}]*\\})?\\s*from\\s*[\"']([^\"']+)[\"']/g;\n\nasync function noCrossServiceTables(check: AppCheck, app: BrickApp, add: Add) {\n const owners = tableOwners(app);\n for (const file of sourceFiles(check, check.services)) {\n const folder = posix(relative(check.services, file)).split(\"/\")[0]!;\n const service = serviceOfFolder(app, folder);\n if (!service) continue;\n const source = readFileSync(file, \"utf8\");\n for (const match of source.matchAll(IMPORT)) {\n const [, typeOnly, defaultName, rest, specifier] = match;\n if (typeOnly || !specifier!.startsWith(\".\")) continue;\n let target: string;\n try {\n target = Bun.resolveSync(specifier!, dirname(file));\n } catch {\n continue;\n }\n const line = lineOf(source, match.index);\n const where = posix(relative(check.services, target)).split(\"/\");\n const otherFolder =\n !where[0]!.startsWith(\"..\") && where.length > 1 ? where[0] : undefined;\n if (\n otherFolder &&\n otherFolder !== folder &&\n /\\.table\\.[cm]?tsx?$/.test(target)\n ) {\n add(\n \"no-cross-service-tables\",\n file,\n `Service \"${service}\" imports ${basename(target)} from ${otherFolder}/; call that service's actions or listen to its events instead.`,\n line,\n );\n continue;\n }\n const module: Record<string, unknown> = await import(target).catch(\n () => ({}),\n );\n const names: string[] = [];\n if (defaultName?.trim()) names.push(\"default\");\n if (rest?.startsWith(\"*\")) names.push(...Object.keys(module));\n else if (rest)\n for (const part of rest.slice(1, -1).split(\",\")) {\n const name = part.trim().split(/\\s+as\\s+/)[0]!;\n if (name && !name.startsWith(\"type \")) names.push(name);\n }\n for (const name of names) {\n const owner = owners.get(module[name]);\n if (owner && owner !== service)\n add(\n \"no-cross-service-tables\",\n file,\n `Service \"${service}\" imports table ${name === \"default\" ? basename(target) : `\"${name}\"`} owned by \"${owner}\"; call ${owner}'s actions or listen to its events instead.`,\n line,\n );\n }\n }\n }\n}\n\nfunction declaredEvents(check: AppCheck, app: BrickApp, add: Add) {\n if (check.severity(\"declared-events\") === \"off\") return;\n for (const service of app.definition.services) {\n if (!service.options.events) continue; // no catalog: any name goes\n const names = new Set(Object.values(service.events).map((e) => e.name));\n const resources = service.listResources().map((r) => r.name);\n // Catalog events are <service>.<event>; CRUD writes still emit\n // <resource>.create|update|delete.\n const declared = (name: string) => {\n const [owner, event] = name.split(\".\", 2);\n return (\n names.has(name) ||\n (resources.includes(owner!) && /^(create|update|delete)$/.test(event!))\n );\n };\n for (const action of service.listActions())\n for (const name of action.config.emits ?? [])\n if (!declared(name))\n add(\n \"declared-events\",\n check.entry,\n `Action \"${service.name}.${action.name}\" emits \"${name}\", which is not in ${service.name}'s event catalog.`,\n );\n const folder = [kebabCase(service.name), service.name]\n .map((name) => resolve(check.services, name))\n .find(existsSync);\n for (const file of folder ? sourceFiles(check, folder) : []) {\n const source = readFileSync(file, \"utf8\");\n for (const match of source.matchAll(\n /emitEvent\\s*\\([^,]+,\\s*[\"'`]([^\"'`]+)[\"'`]/g,\n ))\n if (!declared(match[1]!))\n add(\n \"declared-events\",\n file,\n `\"${match[1]}\" is not in ${service.name}'s event catalog.`,\n lineOf(source, match.index),\n );\n }\n }\n}\n\nfunction testColocated(check: AppCheck, add: Add) {\n if (check.severity(\"test-colocated\") === \"off\") return;\n for (const file of sourceFiles(check, check.services)) {\n const match = /^(.*)\\.(action|command)\\.[cm]?tsx?$/.exec(basename(file));\n if (!match) continue;\n const test = resolve(dirname(file), `${match[1]}.test.ts`);\n if (!existsSync(test) && !existsSync(`${test}x`))\n add(\n \"test-colocated\",\n file,\n `${basename(file)} has no ${match[1]}.test.ts beside it.`,\n );\n }\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n drizzleSchema,\n getTableName,\n migrateDatabase,\n sql,\n type BrickApp,\n type DatabaseHandle,\n type Table,\n} from \"@brickkit/core\";\n\n/** A database the app's services use, with every table Brick knows on it. */\nexport interface AppDatabase {\n /** `defineDatabase({ name })`, else the first service that uses it. */\n name: string;\n database: DatabaseHandle<unknown>;\n tables: Table[];\n}\n\n/**\n * The app's databases and their tables: those passed to `defineDatabase`\n * (outbox tables included), resource tables, and the tables plugins own.\n * Throws when two handles share a name, since the name picks the migrations folder.\n */\nexport function appDatabases(app: BrickApp): AppDatabase[] {\n const found = new Map<\n DatabaseHandle<unknown>,\n { name: string; services: number; tables: Set<Table> }\n >();\n for (const service of app.definition.services) {\n const database = service.getDatabaseHandle?.();\n if (!database) continue;\n let entry = found.get(database);\n if (!entry) {\n entry = {\n name: database.name ?? service.name,\n services: 0,\n tables: new Set(),\n };\n found.set(database, entry);\n }\n entry.services++;\n // By table object: same-named tables in different Postgres schemas both count.\n for (const table of [\n ...Object.values(database.tables),\n ...service.tables.values(),\n ])\n entry.tables.add(table);\n }\n const databases = [...found].filter(([, entry]) => entry.tables.size > 0);\n const names = new Map<string, DatabaseHandle<unknown>>();\n for (const [database, entry] of databases) {\n if (!database.name && entry.services > 1)\n throw new Error(\n `Brick: services share a database without a name, so its migrations folder would follow service order; give it \\`defineDatabase({ name })\\`.`,\n );\n if (names.has(entry.name))\n throw new Error(\n `Brick: two databases are named \"${entry.name}\"; give each \\`defineDatabase({ name })\\` its own name, or share one handle between the services.`,\n );\n names.set(entry.name, database);\n }\n return databases.map(([database, entry]) => ({\n name: entry.name,\n database,\n tables: [...entry.tables],\n }));\n}\n\nexport interface DbCommandOptions {\n /** Migrations folder; each database writes to its own `<out>/<name>` subfolder. */\n out: string;\n /** `generate`: the migration's name. */\n name?: string;\n /** `push`: apply changes that drop data. */\n force?: boolean;\n log?: (line: string) => void;\n}\n\n/** Run `brick db generate|migrate|push` against every database of the app. */\nexport async function runDbCommand(\n command: \"generate\" | \"migrate\" | \"push\",\n app: BrickApp,\n options: DbCommandOptions,\n): Promise<void> {\n const log = options.log ?? console.log;\n const databases = appDatabases(app);\n if (!databases.length)\n throw new Error(\"Brick: the app has no database with tables.\");\n try {\n // All or nothing: a missing journal stops migrate before any database moves.\n if (command === \"migrate\")\n for (const entry of databases) {\n const folder = join(options.out, entry.name);\n if (!existsSync(join(folder, \"meta\", \"_journal.json\")))\n throw new Error(\n `Brick: no migrations in ${folder}; run \\`brick db generate\\` first.`,\n );\n }\n for (const entry of databases) {\n // One layout for any database count, so adding a database never moves another's migrations.\n const folder = join(options.out, entry.name);\n const label = `${entry.name} (${entry.database.engine})`;\n if (command === \"generate\") {\n const file = await generate(entry, folder, options.name);\n log(file ? `${label}: wrote ${file}` : `${label}: no schema changes`);\n } else if (command === \"migrate\") {\n await migrateDatabase(entry.database, folder);\n log(`${label}: migrations in ${folder} applied`);\n } else {\n const applied = await push(entry, options.force ?? false, log);\n log(\n applied\n ? `${label}: applied ${applied} change${applied === 1 ? \"\" : \"s\"}`\n : `${label}: no schema changes`,\n );\n }\n }\n } finally {\n await Promise.all(databases.map((entry) => entry.database.close?.()));\n }\n}\n\nconst kit = () => import(\"drizzle-kit/api\");\n\ntype Snapshot = { id: string; version: string };\ntype Journal = {\n version: string;\n dialect: string;\n entries: {\n idx: number;\n version: string;\n when: number;\n tag: string;\n breakpoints: boolean;\n }[];\n};\n\n/**\n * Diff the tables against the folder's last snapshot with drizzle-kit and write\n * the SQL, snapshot and journal in drizzle-kit's layout, so drizzle-kit and\n * Drizzle's migrator read the folder too. Returns the SQL file, if any.\n */\nasync function generate(\n entry: AppDatabase,\n folder: string,\n name = \"migration\",\n): Promise<string | undefined> {\n const { generateDrizzleJson, generateMigration, ...sqlite } = await kit();\n const postgres = entry.database.engine === \"postgres\";\n const meta = join(folder, \"meta\");\n const journalFile = join(meta, \"_journal.json\");\n const journal: Journal = existsSync(journalFile)\n ? JSON.parse(readFileSync(journalFile, \"utf8\"))\n : {\n version: \"7\",\n dialect: postgres ? \"postgresql\" : \"sqlite\",\n entries: [],\n };\n const last = journal.entries.at(-1);\n const idx = last ? last.idx + 1 : 0;\n const prev: Snapshot | undefined = last\n ? JSON.parse(\n readFileSync(\n join(meta, `${last.tag.slice(0, 4)}_snapshot.json`),\n \"utf8\",\n ),\n )\n : undefined;\n const schema = drizzleSchema(entry.tables);\n let cur: Snapshot;\n let statements: string[];\n if (postgres) {\n const next = generateDrizzleJson(schema, prev?.id);\n statements = await generateMigration(\n (prev as never) ?? generateDrizzleJson({}),\n next,\n );\n cur = next;\n } else {\n const next = await sqlite.generateSQLiteDrizzleJson(schema, prev?.id);\n statements = await sqlite.generateSQLiteMigration(\n (prev as never) ?? (await sqlite.generateSQLiteDrizzleJson({})),\n next,\n );\n cur = next;\n }\n if (!statements.length) return undefined;\n const prefix = String(idx).padStart(4, \"0\");\n const tag = `${prefix}_${name}`;\n mkdirSync(meta, { recursive: true });\n const file = join(folder, `${tag}.sql`);\n writeFileSync(file, statements.join(\"\\n--> statement-breakpoint\\n\"));\n writeFileSync(\n join(meta, `${prefix}_snapshot.json`),\n JSON.stringify(cur, null, 2),\n );\n journal.entries.push({\n idx,\n version: cur.version,\n when: Date.now(),\n tag,\n breakpoints: true,\n });\n writeFileSync(journalFile, JSON.stringify(journal, null, 2));\n return file;\n}\n\n/**\n * Make the database match the tables with drizzle-kit's push, touching only\n * the tables Brick knows. Returns how many statements ran.\n */\nasync function push(\n entry: AppDatabase,\n force: boolean,\n log: (line: string) => void,\n): Promise<number> {\n const { pushSchema, pushSQLiteSchema } = await kit();\n const db = entry.database.getDb() as any;\n const names = new Set(entry.tables.map((table) => getTableName(table)));\n const schema = drizzleSchema(entry.tables);\n const postgres = entry.database.engine === \"postgres\";\n const result = postgres\n ? await pushSchema(\n schema,\n // drizzle-kit reads `rows` (node-postgres); postgres-js returns the rows.\n {\n execute: async (query: never) => ({ rows: await db.execute(query) }),\n } as never,\n [\n ...new Set(\n entry.tables.map(\n // What drizzle's getTableConfig(table).schema reads.\n (table) =>\n ((table as never)[Symbol.for(\"drizzle:Schema\")] as\n | string\n | undefined) ?? \"public\",\n ),\n ),\n ],\n [...names],\n )\n : await pushSQLiteSchema(schema, onlyTables(db, names) as never);\n const statements = result.statementsToExecute;\n if (!statements.length) return 0;\n for (const warning of result.warnings) log(warning);\n if (result.hasDataLoss && !force)\n throw new Error(\n `Brick: pushing ${entry.name} would lose data (see above). Rerun with --force to apply it, or use \\`brick db generate\\` and edit the migration.`,\n );\n if (postgres)\n await db.transaction(async (tx: any) => {\n for (const statement of statements) await tx.execute(sql.raw(statement));\n });\n else await result.apply();\n return statements.length;\n}\n\n/**\n * drizzle-kit's SQLite push has no table filter: hide the tables Brick does not\n * know (FTS sidecars, other apps' tables) from what it reads, so it neither\n * drops them nor asks whether a new table renames one.\n */\nfunction onlyTables(db: any, names: Set<string>) {\n return {\n all: (query: unknown) =>\n db.all(query).filter((row: Record<string, unknown>) => {\n const table =\n row.tableName ?? row.tableFrom ?? row.tbl_name ?? row.view_name;\n return table === undefined || names.has(table as string);\n }),\n run: (query: unknown) => db.run(query),\n };\n}\n","","#!/usr/bin/env bun\nimport { join, resolve } from \"node:path\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport { startDevServer, startProdServer, startWorker } from \"./runner\";\nimport { DEFAULT_DASHBOARD_PORT } from \"./dev-dashboard\";\nimport { DEFAULT_HISTORY_DAYS } from \"./dev-history\";\nimport { buildApplication } from \"./build\";\nimport { writeClientContract } from \"./client-contract-file\";\nimport { generateOpenApiSpec, getGlobalRegistry } from \"@brickkit/core\";\nimport { parsePort, resolveDevPort } from \"./port-utils\";\nimport { loadBrickApp } from \"./app-entry\";\nimport { ConfigError, loadConfig, type LoadedConfig } from \"./config\";\nimport { writeServiceManifest } from \"./manifest\";\nimport { runLint } from \"./lint\";\nimport { runDbCommand } from \"./db\";\nimport cliPkg from \"../package.json\";\n\n// Single source of truth for the CLI version (inlined at build time).\nconst CLI_VERSION: string = cliPkg.version;\n\nconst PORT_HELP =\n \"Port to listen on (CLI --port overrides PORT env, default 4000)\";\n\nconst EXTENSION_HELP =\n \"Dashboard extension module (default export defineDashboard(...)), or the dashboard folder brick build wrote\";\n\nconst PORT_RESOLUTION_HELP = `\nPort Resolution (dev/start commands):\n - CLI --port flag takes precedence\n - Falls back to PORT environment variable\n - Then dev.port in brick.config.ts (brick dev only)\n - Defaults to 4000 if none is set\n - Valid range: 1-65535\n\nExamples:\n brick dev app.ts # port 4000 (default)\n brick dev app.ts --port 5000 # port 5000 (explicit)\n PORT=3000 brick dev app.ts # port 3000 (from env)\n brick dev app.ts --port 6000 # port 6000 (CLI overrides PORT=3000)\n`;\n\nconst CONFIG_HELP =\n \"Path to brick.config.ts (default: the nearest one in this folder or its parents)\";\n\ntype ConfigOpts = { config?: string };\n\nfunction parsePortOption(value: string): number {\n try {\n return parsePort(value, undefined);\n } catch (err) {\n throw new InvalidArgumentError((err as Error).message);\n }\n}\n\nfunction parseHistoryDays(value: string): number {\n const days = Number(value);\n if (!/^\\d+$/.test(value.trim()) || !Number.isSafeInteger(days)) {\n throw new InvalidArgumentError(\n `--history-days must be a whole number of days, or 0 for none (got '${value}')`,\n );\n }\n return days;\n}\n\nfunction parseFileOption(value: string, usage: string): string {\n if (value.startsWith(\"-\")) {\n throw new InvalidArgumentError(`${usage} (got flag-like value '${value}')`);\n }\n return value;\n}\n\n/** `--config` on a `gen` subcommand: commander hands it to `gen`, which takes it too. */\nfunction configOf(command: Command): string | undefined {\n return command.optsWithGlobals<ConfigOpts>().config;\n}\n\n/** The entry argument, else the config's entry; without either, commander's usual error. */\nfunction requireEntry(\n command: Command,\n entry: string | undefined,\n project: LoadedConfig | undefined,\n): string {\n const resolved = entry ?? project?.entry;\n if (!resolved)\n command.error(\"error: missing required argument 'entry'\", {\n exitCode: 1,\n code: \"commander.missingArgument\",\n });\n return resolved!;\n}\n\n/** Load the app after refreshing the services manifest it imports. */\nasync function loadProjectApp(\n entry: string,\n project: LoadedConfig | undefined,\n) {\n if (project) await writeServiceManifest(project);\n return loadBrickApp(entry);\n}\n\n/** A config path, made absolute from the config file's folder. */\nfunction fromRoot(\n project: LoadedConfig | undefined,\n path: string | undefined,\n): string | undefined {\n return path && project ? resolve(project.root, path) : path;\n}\n\n/** The config's dashboard settings; a `--dashboard-extension` flag replaces its extension. */\nfunction configDashboard(\n project: LoadedConfig | undefined,\n extensionFlag?: string,\n) {\n const dashboard = project?.config.dashboard;\n if (!dashboard && !extensionFlag) return undefined;\n return {\n extension: extensionFlag ?? fromRoot(project, dashboard?.extension),\n theme: dashboard?.theme,\n };\n}\n\nasync function writeOpenApi(\n entry: string,\n output: string | undefined,\n project: LoadedConfig | undefined,\n) {\n const app = await loadProjectApp(entry, project);\n const spec = generateOpenApiSpec({\n services: [...app.definition.services],\n prefix: app.definition.prefix,\n });\n const json = JSON.stringify(spec, null, 2);\n if (output) await Bun.write(output, json);\n return json;\n}\n\nexport function createProgram(): Command {\n const program = new Command();\n program\n .name(\"brick\")\n .description(\"🧱 Brick-TS CLI\")\n .version(CLI_VERSION)\n .showHelpAfterError()\n .addHelpText(\n \"after\",\n `\nUsage:\n brick dev [entry] [--port <number>] [--dashboard-port <number>] [--history-days <number>] [--no-dashboard] Start development server with live reload and dashboard\n brick start [entry] [--port <number>] Start production server\n brick worker <entry> Deliver events without serving HTTP\n brick build <app.ts> [--outdir <dir>] [--port <number>] [--no-aot] Compile a default-exported BrickApp into a Bun server\n brick gen openapi <entry> [--output <file>] Generate OpenAPI 3.1 JSON specification\n brick gen client <entry> [--output <file>] Generate a typed browser client contract\n brick gen manifest Write <generated>/services.gen.ts\n brick db generate [entry] [--out <dir>] [--name <name>] Write a SQL migration for the schema changes\n brick db migrate [entry] [--out <dir>] Apply the migrations that have not run yet\n brick db push [entry] [--force] Change the database to match the schema (development)\n brick lint [entry] Check the project against the Brick lint rules\n brick info <entry> Export architecture JSON schema\n\nWith a brick.config.ts, the entry and most flags come from the config file,\nand every command takes --config <path>.\n${PORT_RESOLUTION_HELP}`,\n );\n\n program\n .command(\"dev\")\n .description(\"Start development server with live reload\")\n .option(\n \"--client <file>\",\n \"Generate and watch a browser contract before startup\",\n )\n .option(\n \"--frontend <command>\",\n \"Start frontend after contract generation; requires --client\",\n )\n .option(\n \"--dashboard-port <number>\",\n `Port for the local dashboard (default ${DEFAULT_DASHBOARD_PORT})`,\n parsePortOption,\n )\n .option(\n \"--history-days <number>\",\n `Days of requests the dashboard keeps on disk, 0 for none (default ${DEFAULT_HISTORY_DAYS})`,\n parseHistoryDays,\n )\n .option(\"--no-dashboard\", \"Do not start the local dashboard\")\n .option(\"--dashboard-extension <file>\", EXTENSION_HELP)\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .option(\"--config <path>\", CONFIG_HELP)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(\n async (\n entryArg: string | undefined,\n opts: ConfigOpts & {\n port?: number;\n client?: string;\n frontend?: string;\n dashboardPort?: number;\n historyDays?: number;\n dashboard?: boolean;\n dashboardExtension?: string;\n },\n ) => {\n const project = await loadConfig(opts.config);\n const config = project?.config;\n const entry = entryArg ?? project?.entry;\n const port = resolveDevPort(opts.port, config?.dev?.port);\n if (opts.dashboard === false && opts.dashboardPort !== undefined) {\n throw new Error(\n \"Brick: --dashboard-port cannot be combined with --no-dashboard.\",\n );\n }\n if (opts.dashboard === false && opts.historyDays !== undefined) {\n throw new Error(\n \"Brick: --history-days cannot be combined with --no-dashboard.\",\n );\n }\n const configured = config?.dev?.dashboard;\n // The config can turn the dashboard off; a dashboard flag turns it back on.\n const dashboardOff =\n opts.dashboard === false ||\n (configured === false &&\n opts.dashboardPort === undefined &&\n opts.historyDays === undefined);\n const dashboardConfig = configured || undefined;\n if (dashboardOff && opts.dashboardExtension) {\n throw new Error(\n \"Brick: --dashboard-extension cannot be combined with --no-dashboard.\",\n );\n }\n await startDevServer({\n entry,\n port,\n clientOutput:\n opts.client ?? fromRoot(project, config?.client?.output),\n frontend: opts.frontend ?? config?.dev?.frontend,\n // The dashboard reads the app's requests, so it needs an entry.\n dashboard:\n entry && !dashboardOff\n ? {\n port:\n opts.dashboardPort ??\n dashboardConfig?.port ??\n DEFAULT_DASHBOARD_PORT,\n historyDays: opts.historyDays ?? dashboardConfig?.historyDays,\n ...configDashboard(project, opts.dashboardExtension),\n }\n : false,\n manifest: project,\n });\n },\n );\n\n program\n .command(\"start\")\n .description(\"Start production server\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .option(\"--dashboard-extension <file>\", EXTENSION_HELP)\n .option(\"--config <path>\", CONFIG_HELP)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(\n async (\n entry: string | undefined,\n opts: ConfigOpts & { port?: number; dashboardExtension?: string },\n ) => {\n const project = await loadConfig(opts.config);\n const port = resolveDevPort(opts.port);\n await startProdServer({\n entry: entry ?? project?.entry,\n port,\n dashboard: configDashboard(project, opts.dashboardExtension),\n });\n },\n );\n\n program\n .command(\"worker\")\n .description(\"Deliver the app's events without serving HTTP\")\n .argument(\n \"[entry]\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .option(\"--config <path>\", CONFIG_HELP)\n .action(\n async (entry: string | undefined, opts: ConfigOpts, command: Command) => {\n const project = await loadConfig(opts.config);\n await startWorker({ entry: requireEntry(command, entry, project) });\n },\n );\n\n program\n .command(\"build\")\n .description(\"Compile a default-exported BrickApp into a Bun server\")\n .argument(\n \"[entry]\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .option(\"--config <path>\", CONFIG_HELP)\n .option(\"--outdir <dir>\", \"Output directory\", (v: string) =>\n parseFileOption(v, \"Usage: brick build <app.ts> [--outdir <directory>]\"),\n )\n .option(\"--port <number>\", \"Default listening port\", parsePortOption)\n .option(\"--no-aot\", \"Disable ahead-of-time compilation\")\n .option(\n \"--dashboard-extension <file>\",\n \"Dashboard extension module to build into <outdir>/dashboard\",\n )\n .option(\n \"--prefix <path>\",\n \"DEPRECATED: configure prefix in brick() app instead\",\n )\n .option(\n \"--no-request-logging\",\n \"DEPRECATED: configure requestLogging in brick() app instead\",\n )\n .action(\n async (\n entryArg: string | undefined,\n opts: ConfigOpts & {\n outdir?: string;\n port?: number;\n aot?: boolean;\n prefix?: string;\n requestLogging?: boolean;\n dashboardExtension?: string;\n },\n command: Command,\n ) => {\n if (opts.prefix !== undefined || opts.requestLogging === false) {\n throw new Error(\n \"Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.\",\n );\n }\n const project = await loadConfig(opts.config);\n const build = project?.config.build;\n // shortcut: brick() sets up request logging when the app is created, so\n // a build cannot switch it off; only the default (true) is accepted.\n if (build?.requestLogging === false)\n throw new Error(\n \"Brick: configure requestLogging in your default-exported brick() app instead of build.requestLogging.\",\n );\n const entry = requireEntry(command, entryArg, project);\n if (project) await writeServiceManifest(project);\n const result = await buildApplication({\n entry,\n outdir: opts.outdir ?? fromRoot(project, build?.outdir),\n port: opts.port,\n // --no-aot can only switch it off, so otherwise the config decides.\n aot: opts.aot === false ? false : build?.aot,\n dashboard: configDashboard(project, opts.dashboardExtension),\n });\n for (const warning of result.ir.diagnostics)\n console.warn(`[Brick compiler] ${warning}`);\n console.log(\n `Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`,\n );\n console.log(`IR: ${result.outdir}/brick-ir.json`);\n if (result.dashboard)\n console.log(`Dashboard extension: ${result.dashboard}`);\n console.log(`Run: bun ${result.entry}`);\n },\n );\n\n const gen = program\n .command(\"gen\")\n .description(\"Generate artifacts from a BrickApp entry\")\n .argument(\"[subcommand]\", \"Generator to run (openapi, client, manifest)\")\n .option(\"--config <path>\", CONFIG_HELP)\n .action(async (subcommand: string | undefined, opts: ConfigOpts) => {\n const project =\n subcommand === undefined ? await loadConfig(opts.config) : undefined;\n if (!project) {\n console.error(\n `Unknown generator: ${subcommand ?? \"(none)\"}. Available: openapi, client, manifest`,\n );\n process.exit(1);\n }\n // With a config, bare `brick gen` writes everything the config names.\n const manifest = await writeServiceManifest(project);\n console.log(`Services manifest written to ${manifest}`);\n const client = fromRoot(project, project.config.client?.output);\n if (client) {\n await writeClientContract(project.entry, client);\n console.log(`Client contract written to ${client}`);\n }\n const openapi = fromRoot(project, project.config.openapi?.output);\n if (openapi) {\n await writeOpenApi(project.entry, openapi, project);\n console.log(`✅ OpenAPI 3.1 specification written to ${openapi}`);\n }\n });\n\n gen\n .command(\"openapi\")\n .description(\"Generate OpenAPI 3.1 JSON specification\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--config <path>\", CONFIG_HELP)\n .option(\n \"--output <file>\",\n \"Write specification to file instead of stdout\",\n (v: string) =>\n parseFileOption(\n v,\n \"Usage: brick gen openapi <entry> [--output <file>]\",\n ),\n )\n .action(\n async (\n entry: string | undefined,\n opts: ConfigOpts & { output?: string },\n command: Command,\n ) => {\n const project = await loadConfig(configOf(command));\n const output =\n opts.output ?? fromRoot(project, project?.config.openapi?.output);\n const json = await writeOpenApi(\n requireEntry(command, entry, project),\n output,\n project,\n );\n if (output)\n console.log(`✅ OpenAPI 3.1 specification written to ${output}`);\n else console.log(json);\n },\n );\n\n gen\n .command(\"client\")\n .description(\"Generate a typed browser client contract\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--config <path>\", CONFIG_HELP)\n .option(\n \"--output <file>\",\n \"Write contract to file (default _brick/contract.ts)\",\n (v: string) =>\n parseFileOption(v, \"Usage: brick gen client <entry> [--output <file>]\"),\n )\n .action(\n async (\n entry: string | undefined,\n opts: ConfigOpts & { output?: string },\n command: Command,\n ) => {\n const project = await loadConfig(configOf(command));\n const target = requireEntry(command, entry, project);\n if (project) await writeServiceManifest(project);\n const output = await writeClientContract(\n target,\n opts.output ??\n fromRoot(project, project?.config.client?.output) ??\n (project && join(project.generated, \"contract.ts\")),\n );\n console.log(`Client contract written to ${output}`);\n },\n );\n\n gen\n .command(\"manifest\")\n .description(\n \"Write <generated>/services.gen.ts, which imports every definition file\",\n )\n .option(\"--config <path>\", CONFIG_HELP)\n .action(async (_opts: ConfigOpts, command: Command) => {\n const project = await loadConfig(configOf(command));\n const output = await writeServiceManifest(\n project ?? {\n services: resolve(\"src/services\"),\n generated: resolve(\"_brick\"),\n },\n );\n console.log(`Services manifest written to ${output}`);\n });\n\n const db = program\n .command(\"db\")\n .description(\n \"Manage the app's database schema with drizzle-kit: generate, migrate, push\",\n );\n const dbCommand = (\n name: \"generate\" | \"migrate\" | \"push\",\n description: string,\n ) =>\n db\n .command(name)\n .description(description)\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--config <path>\", CONFIG_HELP);\n // push writes no files, so only generate and migrate take --out.\n const OUT_HELP =\n \"Migrations folder (default drizzle, beside brick.config.ts); each database gets a subfolder named after it\";\n const dbAction =\n (name: \"generate\" | \"migrate\" | \"push\") =>\n async (\n entry: string | undefined,\n opts: ConfigOpts & { out?: string; name?: string; force?: boolean },\n command: Command,\n ) => {\n const project = await loadConfig(opts.config);\n const app = await loadProjectApp(\n requireEntry(command, entry, project),\n project,\n );\n await runDbCommand(name, app, {\n out: opts.out ?? fromRoot(project, \"drizzle\")!,\n name: opts.name,\n force: opts.force,\n });\n };\n dbCommand(\n \"generate\",\n \"Write a SQL migration for the schema changes since the last one\",\n )\n .option(\"--out <dir>\", OUT_HELP)\n .option(\"--name <name>\", \"Migration name (default migration)\")\n .action(dbAction(\"generate\"));\n dbCommand(\"migrate\", \"Apply the migrations that have not run yet\")\n .option(\"--out <dir>\", OUT_HELP)\n .action(dbAction(\"migrate\"));\n dbCommand(\n \"push\",\n \"Change the database to match the schema directly, without migration files (development)\",\n )\n .option(\"--force\", \"Apply changes that drop data\")\n .action(dbAction(\"push\"));\n\n program\n .command(\"lint\")\n .description(\"Check the project against the Brick lint rules\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--config <path>\", CONFIG_HELP)\n .action(async (entry: string | undefined, opts: ConfigOpts) => {\n const project = await loadConfig(opts.config);\n const code = await runLint({ entry, project });\n if (code !== 0) process.exit(code);\n });\n\n program\n .command(\"info\")\n .alias(\"services\")\n .description(\"Export architecture JSON schema\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--config <path>\", CONFIG_HELP)\n .action(\n async (entry: string | undefined, opts: ConfigOpts, command: Command) => {\n const project = await loadConfig(opts.config);\n const app = await loadProjectApp(\n requireEntry(command, entry, project),\n project,\n );\n const architecture = getGlobalRegistry().exportArchitecture(\n app.definition,\n );\n console.log(JSON.stringify(architecture, null, 2));\n },\n );\n\n return program;\n}\n\nasync function main() {\n const program = createProgram();\n const userArgs = process.argv.slice(2);\n // With a config file, bare `brick` is `brick dev`.\n if (userArgs.length === 0 && (await loadConfig())) {\n await program.parseAsync([...process.argv, \"dev\"]);\n return;\n }\n // Preserve legacy behavior: bare `brick` starts the dev server.\n if (userArgs.length === 0) {\n const port = parsePort(undefined, process.env.PORT);\n await startDevServer({ port });\n return;\n }\n await program.parseAsync(process.argv);\n}\n\nmain().catch((err) => {\n // Commander already prints validation errors (missing arg, unknown option,\n // invalid port) and exits. Only print Fatal error for action failures.\n if (err?.exitCode !== undefined) {\n process.exit(err.exitCode);\n }\n if (err?.code?.startsWith?.(\"commander.\")) {\n process.exit(1);\n }\n // A config error already names the file and key; a stack adds nothing.\n if (err instanceof ConfigError) {\n console.error(err.message);\n process.exit(1);\n }\n console.error(\"Fatal error:\", err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AAsBA,SAAS,aAAa;CACpB,MAAM,OAAO,cAAc,YAAY,GAAG;CAE1C,OAAO,KAAK,SAAS,KAAK,IACtB,QAAQ,QAAQ,IAAI,GAAG,2BAA2B,IAClD,QAAQ,QAAQ,IAAI,GAAG,gBAAgB;AAC7C;AAEA,SAAS,UAAU,MAAc;CAC/B,KAAK,MAAM,QAAQ,CACjB,KAAK,MAAM,cAAc,GACzB,cAAc,YAAY,GAAG,CAC/B,GACE,IAAI;EACF,MAAM,MAAM,cAAc,IAAI,CAAC,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CAEA,IAAI,SAAS,WAAW,GAAG;EACzB,MAAM,OAAO,UAAU,KAAA,GAAW,QAAQ,IAAI,IAAI;EAClD,MAAM,eAAe,EAAE,KAAK,CAAC;EAC7B;CACF;CACA,MAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CAGpB,IAAI,KAAK,aAAa,KAAA,GACpB,QAAQ,KAAK,IAAI,QAAQ;CAE3B,IAAI,KAAK,MAAM,aAAa,YAAY,GACtC,QAAQ,KAAK,CAAC;CAGhB,IAAI,eAAe,aAAa;EAC9B,QAAQ,MAAM,IAAI,OAAO;EACzB,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,MAAM,gBAAgB,GAAG;CACjC,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"bin.js","names":["posix","cliPkg.version"],"sources":["../src/lint/run.ts","../src/lint.ts","../src/db.ts","../src/bin.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { mkdtempSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { ConfigError } from \"../config\";\nimport type { BrickSettings } from \"./ast\";\nimport type { Severity } from \"./presets\";\n\nexport interface LintMessage {\n /** Path from the project root. */\n file: string;\n line: number;\n column: number;\n /** `brick/<rule>`. */\n rule: string;\n severity: \"error\" | \"warn\";\n message: string;\n}\n\nlet fromSource: string | undefined;\n/** The lint/oxlint entry oxlint loads under Node: the bundle beside this code, or, run from source, a fresh bundle of it. */\nfunction pluginPath() {\n const here = fileURLToPath(import.meta.url);\n if (!here.endsWith(\".ts\")) return resolve(dirname(here), \"lint/oxlint.js\");\n if (fromSource) return fromSource;\n // Inside the package, so Node resolves the bundle's imports from here.\n const file = resolve(here, \"../../../node_modules/.cache/brick-lint.js\");\n // Built beside it, then renamed: another process may be loading it.\n const building = `${file}.${process.pid}`;\n const result = spawnSync(\n process.execPath,\n [\"build\", resolve(dirname(here), \"oxlint.ts\"), \"--target\", \"node\"].concat([\n \"--packages\",\n \"external\",\n \"--outfile\",\n building,\n ]),\n { encoding: \"utf8\" },\n );\n if (result.status !== 0)\n throw new Error(\n `Brick: building the lint plugin failed:\\n${result.stderr}`,\n );\n renameSync(building, file);\n return (fromSource = file);\n}\n\nfunction oxlintBin(root: string) {\n for (const base of [\n join(root, \"package.json\"),\n fileURLToPath(import.meta.url),\n ]) {\n try {\n const pkg = createRequire(base).resolve(\"oxlint/package.json\");\n return join(dirname(pkg), \"bin/oxlint\");\n } catch {}\n }\n throw new ConfigError(\n \"Brick: brick lint needs oxlint; add it: bun add -d oxlint\",\n );\n}\n\n/**\n * Run the file rules over a project with oxlint, as `brick lint` does.\n * Only rules set to \"error\" or \"warn\" run; `ignore` globs are relative to `root`.\n */\nexport function runFileRules(options: {\n root: string;\n rules: Record<string, Severity>;\n settings: BrickSettings;\n ignore?: string[];\n fix?: boolean;\n}): LintMessage[] {\n const rules = Object.fromEntries(\n Object.entries(options.rules).filter(([, severity]) => severity !== \"off\"),\n );\n if (Object.keys(rules).length === 0) return [];\n const directory = mkdtempSync(join(tmpdir(), \"brick-lint-\"));\n try {\n const config = join(directory, \"oxlintrc.json\");\n writeFileSync(\n config,\n JSON.stringify({\n plugins: [],\n categories: { correctness: \"off\" },\n jsPlugins: [{ name: \"brick\", specifier: pluginPath() }],\n settings: { brick: options.settings },\n rules,\n }),\n );\n const result = spawnSync(\n oxlintBin(options.root),\n [\n \"-c\",\n config,\n \"--format\",\n \"json\",\n \"--disable-nested-config\",\n \"--no-error-on-unmatched-pattern\",\n ...(options.fix ? [\"--fix\"] : []),\n ...(options.ignore ?? []).flatMap((pattern) => [\n \"--ignore-pattern\",\n pattern,\n ]),\n \".\",\n ],\n { cwd: options.root, encoding: \"utf8\", maxBuffer: 64 * 1024 * 1024 },\n );\n if (result.error) throw result.error;\n let report: {\n diagnostics?: {\n message: string;\n code?: string;\n severity: string;\n filename: string;\n labels?: { span: { line: number; column: number } }[];\n }[];\n };\n try {\n report = JSON.parse(result.stdout);\n } catch {\n throw new Error(\n `Brick: oxlint failed (exit ${result.status}):\\n${result.stderr || result.stdout}`,\n );\n }\n return (report.diagnostics ?? []).map((diagnostic) => ({\n file: diagnostic.filename,\n line: diagnostic.labels?.[0]?.span.line ?? 1,\n column: diagnostic.labels?.[0]?.span.column ?? 1,\n // Parse errors come without a rule code.\n rule: diagnostic.code?.replace(/^brick\\((.*)\\)$/, \"brick/$1\") ?? \"syntax\",\n severity: diagnostic.severity === \"error\" ? \"error\" : \"warn\",\n message: diagnostic.message,\n }));\n } finally {\n rmSync(directory, { recursive: true, force: true });\n }\n}\n","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { basename, dirname, relative, resolve, sep } from \"node:path\";\nimport { isCrudEvent } from \"@brickkit/core\";\nimport type { BrickApp, DatabaseHandle } from \"@brickkit/core\";\nimport { loadBrickApp } from \"./app-entry\";\nimport type { LoadedConfig } from \"./config\";\nimport { APP_RULES, type Severity } from \"./lint/presets\";\nimport { projectRules } from \"./lint/project\";\nimport { serviceFolders } from \"./lint/ast\";\nimport { runFileRules, type LintMessage } from \"./lint/run\";\nimport {\n DEFINITION_EXTENSIONS,\n DEFINITION_FILE,\n TEST_FILE,\n} from \"./definitions\";\nimport { writeServiceManifest } from \"./manifest\";\n\nconst posix = (path: string) => path.split(sep).join(\"/\");\nconst SOURCE = new Bun.Glob(\n `**/*.{${[...DEFINITION_EXTENSIONS, \"cts\"].join(\",\")}}`,\n);\n\ninterface AppCheck {\n root: string;\n entry: string;\n services: string;\n severity: (rule: string) => Severity;\n ignored: (rel: string) => boolean;\n}\n\n/**\n * `brick lint`: the file rules through oxlint, then the app\n * rules against the loaded app. Prints `file:line:col` lines and returns the\n * exit code: 1 when anything is an error.\n */\nexport async function runLint(options: {\n entry?: string;\n project: LoadedConfig;\n}): Promise<number> {\n const entry = options.entry ? resolve(options.entry) : options.project.entry;\n const project = { ...options.project, entry };\n const { root, services } = project;\n const { resolved, rules, settings, ignore } = projectRules(project);\n const messages = runFileRules({ root, rules, settings, ignore });\n const globs = ignore.map((pattern) => new Bun.Glob(pattern));\n if (existsSync(entry)) {\n if (project.file) await writeServiceManifest(project);\n messages.push(\n ...(await checkApp({\n root,\n entry,\n services,\n severity: (rule) => resolved[`brick/${rule}`] ?? \"off\",\n ignored: (rel) =>\n rel.split(\"/\").includes(\"node_modules\") ||\n globs.some((glob) => glob.match(rel)),\n })),\n );\n } else if (options.entry || project.file)\n throw new Error(`Brick: entry not found: ${entry}`);\n return report(messages);\n}\n\nfunction report(messages: LintMessage[]): number {\n messages.sort(\n (a, b) =>\n a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column,\n );\n for (const m of messages)\n console.log(\n `${m.file}:${m.line}:${m.column} ${m.severity === \"error\" ? \"error\" : \"warning\"} ${m.message} ${m.rule}`,\n );\n const errors = messages.filter((m) => m.severity === \"error\").length;\n const warnings = messages.length - errors;\n console.log(\n messages.length\n ? `\\n✖ ${messages.length} problem${messages.length === 1 ? \"\" : \"s\"} (${errors} error${errors === 1 ? \"\" : \"s\"}, ${warnings} warning${warnings === 1 ? \"\" : \"s\"})`\n : \"✔ No lint problems\",\n );\n return errors > 0 ? 1 : 0;\n}\n\n/** Project source files, from the root, without tests, ignored and generated files. */\nfunction sourceFiles(check: AppCheck, under = check.root): string[] {\n if (!existsSync(under)) return [];\n return [...SOURCE.scanSync({ cwd: under, onlyFiles: true })]\n .map((file) => resolve(under, file))\n .filter((file) => {\n const rel = posix(relative(check.root, file));\n return (\n !check.ignored(rel) && !TEST_FILE.test(rel) && !rel.startsWith(\"dist/\")\n );\n });\n}\n\nfunction lineOf(source: string, index: number) {\n return source.slice(0, index).split(\"\\n\").length;\n}\n\ntype Add = (file: string, message: string, line?: number) => void;\ntype AppRule = (check: AppCheck, app: BrickApp, add: Add) => unknown;\n\n/** Each app rule's check; a rule in APP_RULES without one fails to compile. */\nconst APP_CHECKS: Record<(typeof APP_RULES)[number], AppRule> = {\n \"single-app-entry\": singleAppEntry,\n \"no-cross-service-tables\": noCrossServiceTables,\n // Startup refuses duplicate names, so checkApp reports it when the app loads.\n \"unique-names\": () => {},\n \"declared-events\": declaredEvents,\n \"test-colocated\": testColocated,\n};\n\nasync function checkApp(check: AppCheck): Promise<LintMessage[]> {\n const messages: LintMessage[] = [];\n const message = (\n rule: string,\n severity: Exclude<Severity, \"off\">,\n file: string,\n text: string,\n line = 1,\n ): LintMessage => ({\n file: posix(relative(check.root, file)),\n line,\n column: 1,\n rule: `brick/${rule}`,\n severity,\n message: text,\n });\n let app: BrickApp;\n try {\n app = await loadBrickApp(check.entry);\n } catch (error) {\n // An app that cannot start fails lint, even with unique-names off.\n if ((error as Error).name === \"DuplicateNameError\") {\n return [\n message(\"unique-names\", \"error\", check.entry, (error as Error).message),\n ];\n }\n throw error;\n }\n for (const [rule, run] of Object.entries(APP_CHECKS)) {\n const severity = check.severity(rule);\n if (severity === \"off\") continue;\n await run(check, app, (file, text, line) =>\n messages.push(message(rule, severity, file, text, line)),\n );\n }\n return messages;\n}\n\nfunction singleAppEntry(check: AppCheck, _app: BrickApp, add: Add) {\n let calls = 0;\n for (const file of sourceFiles(check)) {\n const source = readFileSync(file, \"utf8\");\n // shortcut: a text search for brick( in files that import it from core.\n if (\n !/import\\s*\\{[^}]*\\bbrick\\b[^}]*\\}\\s*from\\s*[\"']@brickkit\\/core[\"']/.test(\n source,\n )\n )\n continue;\n for (const match of source.matchAll(/(?<![.\\w])brick\\s*\\(/g)) {\n if (file === check.entry && ++calls === 1) continue;\n add(\n file,\n file === check.entry\n ? \"The entry calls brick() more than once; keep one app.\"\n : `brick() is called outside the entry (${posix(relative(check.root, check.entry))}); keep one app.`,\n lineOf(source, match.index),\n );\n }\n }\n}\n\n/** Which service owns each table: its resources' and registered tables, or a database it alone uses. */\nfunction tableOwners(app: BrickApp) {\n const owners = new Map<unknown, string>();\n const users = new Map<DatabaseHandle<unknown>, string[]>();\n for (const service of app.definition.services) {\n for (const table of service.tables.values())\n owners.set(table, service.name);\n const { database } = service.options;\n if (database)\n users.set(database, [...(users.get(database) ?? []), service.name]);\n }\n for (const [database, names] of users)\n if (names.length === 1)\n for (const table of Object.values(database.tables))\n if (!owners.has(table)) owners.set(table, names[0]!);\n return owners;\n}\n\nfunction serviceOfFolder(app: BrickApp, folder: string) {\n return app.definition.services.find((service) =>\n serviceFolders(service.name).includes(folder),\n )?.name;\n}\n\n// shortcut: a text search for static imports and re-exports; misses `import()`.\nconst IMPORT =\n /(?:import|export)\\s+(type\\s+)?([\\w$]+\\s*,?\\s*)?(\\*(?:\\s+as\\s+[\\w$]+)?|\\{[^}]*\\})?\\s*from\\s*[\"']([^\"']+)[\"']/g;\n\nasync function noCrossServiceTables(check: AppCheck, app: BrickApp, add: Add) {\n const owners = tableOwners(app);\n for (const file of sourceFiles(check, check.services)) {\n const folder = posix(relative(check.services, file)).split(\"/\")[0]!;\n const service = serviceOfFolder(app, folder);\n if (!service) continue;\n const source = readFileSync(file, \"utf8\");\n for (const match of source.matchAll(IMPORT)) {\n const [, typeOnly, defaultName, rest, specifier] = match;\n if (typeOnly || !specifier!.startsWith(\".\")) continue;\n let target: string;\n try {\n target = Bun.resolveSync(specifier!, dirname(file));\n } catch {\n continue;\n }\n const line = lineOf(source, match.index);\n const where = posix(relative(check.services, target)).split(\"/\");\n const otherFolder =\n !where[0]!.startsWith(\"..\") && where.length > 1 ? where[0] : undefined;\n if (\n otherFolder &&\n otherFolder !== folder &&\n DEFINITION_FILE.exec(basename(target))?.[2] === \"table\"\n ) {\n add(\n file,\n `Service \"${service}\" imports ${basename(target)} from ${otherFolder}/; call that service's actions or listen to its events instead.`,\n line,\n );\n continue;\n }\n const module: Record<string, unknown> = await import(target).catch(\n () => ({}),\n );\n const names: string[] = [];\n if (defaultName?.trim()) names.push(\"default\");\n if (rest?.startsWith(\"*\")) names.push(...Object.keys(module));\n else if (rest)\n for (const part of rest.slice(1, -1).split(\",\")) {\n const name = part.trim().split(/\\s+as\\s+/)[0]!;\n if (name && !name.startsWith(\"type \")) names.push(name);\n }\n for (const name of names) {\n const owner = owners.get(module[name]);\n if (owner && owner !== service)\n add(\n file,\n `Service \"${service}\" imports table ${name === \"default\" ? basename(target) : `\"${name}\"`} owned by \"${owner}\"; call ${owner}'s actions or listen to its events instead.`,\n line,\n );\n }\n }\n }\n}\n\nfunction declaredEvents(check: AppCheck, app: BrickApp, add: Add) {\n for (const service of app.definition.services) {\n if (!service.options.events) continue; // no catalog: any name goes\n const names = new Set(Object.values(service.events).map((e) => e.name));\n const resources = service.listResources().map((r) => r.name);\n const declared = (name: string) =>\n names.has(name) || isCrudEvent(name, resources);\n for (const action of service.listActions())\n for (const name of action.config.emits ?? [])\n if (!declared(name))\n add(\n check.entry,\n `Action \"${service.name}.${action.name}\" emits \"${name}\", which is not in ${service.name}'s event catalog.`,\n );\n const folder = serviceFolders(service.name)\n .map((name) => resolve(check.services, name))\n .find(existsSync);\n for (const file of folder ? sourceFiles(check, folder) : []) {\n const source = readFileSync(file, \"utf8\");\n for (const match of source.matchAll(\n /emitEvent\\s*\\([^,]+,\\s*[\"'`]([^\"'`]+)[\"'`]/g,\n ))\n if (!declared(match[1]!))\n add(\n file,\n `\"${match[1]}\" is not in ${service.name}'s event catalog.`,\n lineOf(source, match.index),\n );\n }\n }\n}\n\nfunction testColocated(check: AppCheck, _app: BrickApp, add: Add) {\n for (const file of sourceFiles(check, check.services)) {\n const match = DEFINITION_FILE.exec(basename(file));\n if (match?.[2] !== \"action\" && match?.[2] !== \"command\") continue;\n const tested = readdirSync(dirname(file)).some(\n (sibling) =>\n TEST_FILE.test(sibling) && sibling.replace(TEST_FILE, \"\") === match[1],\n );\n if (!tested)\n add(file, `${basename(file)} has no ${match[1]}.test.ts beside it.`);\n }\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n drizzleSchema,\n getTableName,\n migrateDatabase,\n sql,\n type BrickApp,\n type DatabaseHandle,\n type Table,\n} from \"@brickkit/core\";\n\n/** A database the app's services use, with every table Brick knows on it. */\nexport interface AppDatabase {\n /** `defineDatabase({ name })`, else the first service that uses it. */\n name: string;\n database: DatabaseHandle<unknown>;\n tables: Table[];\n}\n\n/**\n * The app's databases and their tables: those passed to `defineDatabase`\n * (outbox tables included), resource tables, and the tables plugins own.\n * Throws when two handles share a name, since the name picks the migrations folder.\n */\nexport function appDatabases(app: BrickApp): AppDatabase[] {\n const found = new Map<\n DatabaseHandle<unknown>,\n { name: string; services: number; tables: Set<Table> }\n >();\n for (const service of app.definition.services) {\n const database = service.getDatabaseHandle?.();\n if (!database) continue;\n let entry = found.get(database);\n if (!entry) {\n entry = {\n name: database.name ?? service.name,\n services: 0,\n tables: new Set(),\n };\n found.set(database, entry);\n }\n entry.services++;\n // By table object: same-named tables in different Postgres schemas both count.\n for (const table of [\n ...Object.values(database.tables),\n ...service.tables.values(),\n ])\n entry.tables.add(table);\n }\n const databases = [...found].filter(([, entry]) => entry.tables.size > 0);\n const names = new Map<string, DatabaseHandle<unknown>>();\n for (const [database, entry] of databases) {\n if (!database.name && entry.services > 1)\n throw new Error(\n `Brick: services share a database without a name, so its migrations folder would follow service order; give it \\`defineDatabase({ name })\\`.`,\n );\n if (names.has(entry.name))\n throw new Error(\n `Brick: two databases are named \"${entry.name}\"; give each \\`defineDatabase({ name })\\` its own name, or share one handle between the services.`,\n );\n names.set(entry.name, database);\n }\n return databases.map(([database, entry]) => ({\n name: entry.name,\n database,\n tables: [...entry.tables],\n }));\n}\n\nexport interface DbCommandOptions {\n /** Migrations folder; each database writes to its own `<out>/<name>` subfolder. */\n out: string;\n /** `generate`: the migration's name. */\n name?: string;\n /** `push`: apply changes that drop data. */\n force?: boolean;\n}\n\n/** Run `brick db generate|migrate|push` against every database of the app. */\nexport async function runDbCommand(\n command: \"generate\" | \"migrate\" | \"push\",\n app: BrickApp,\n options: DbCommandOptions,\n): Promise<void> {\n const databases = appDatabases(app);\n if (!databases.length)\n throw new Error(\"Brick: the app has no database with tables.\");\n try {\n // All or nothing: a missing journal stops migrate before any database moves.\n if (command === \"migrate\")\n for (const entry of databases) {\n const folder = join(options.out, entry.name);\n if (!existsSync(join(folder, \"meta\", \"_journal.json\")))\n throw new Error(\n `Brick: no migrations in ${folder}; run \\`brick db generate\\` first.`,\n );\n }\n for (const entry of databases) {\n // One layout for any database count, so adding a database never moves another's migrations.\n const folder = join(options.out, entry.name);\n const label = `${entry.name} (${entry.database.engine})`;\n if (command === \"generate\") {\n const file = await generate(entry, folder, options.name);\n console.log(\n file ? `${label}: wrote ${file}` : `${label}: no schema changes`,\n );\n } else if (command === \"migrate\") {\n await migrateDatabase(entry.database, folder);\n console.log(`${label}: migrations in ${folder} applied`);\n } else {\n const applied = await push(entry, options.force ?? false);\n console.log(\n applied\n ? `${label}: applied ${applied} change${applied === 1 ? \"\" : \"s\"}`\n : `${label}: no schema changes`,\n );\n }\n }\n } finally {\n await Promise.all(databases.map((entry) => entry.database.close?.()));\n }\n}\n\nconst kit = () => import(\"drizzle-kit/api\");\n\ntype Snapshot = { id: string; version: string };\ntype Journal = {\n version: string;\n dialect: string;\n entries: {\n idx: number;\n version: string;\n when: number;\n tag: string;\n breakpoints: boolean;\n }[];\n};\n\n/**\n * Diff the tables against the folder's last snapshot with drizzle-kit and write\n * the SQL, snapshot and journal in drizzle-kit's layout, so drizzle-kit and\n * Drizzle's migrator read the folder too. Returns the SQL file, if any.\n */\nasync function generate(\n entry: AppDatabase,\n folder: string,\n name = \"migration\",\n): Promise<string | undefined> {\n const { generateDrizzleJson, generateMigration, ...sqlite } = await kit();\n const postgres = entry.database.engine === \"postgres\";\n const meta = join(folder, \"meta\");\n const journalFile = join(meta, \"_journal.json\");\n const journal: Journal = existsSync(journalFile)\n ? JSON.parse(readFileSync(journalFile, \"utf8\"))\n : {\n version: \"7\",\n dialect: postgres ? \"postgresql\" : \"sqlite\",\n entries: [],\n };\n const last = journal.entries.at(-1);\n const idx = last ? last.idx + 1 : 0;\n const prev: Snapshot | undefined = last\n ? JSON.parse(\n readFileSync(\n join(meta, `${last.tag.slice(0, 4)}_snapshot.json`),\n \"utf8\",\n ),\n )\n : undefined;\n const schema = drizzleSchema(entry.tables);\n let cur: Snapshot;\n let statements: string[];\n if (postgres) {\n const next = generateDrizzleJson(schema, prev?.id);\n statements = await generateMigration(\n (prev as never) ?? generateDrizzleJson({}),\n next,\n );\n cur = next;\n } else {\n const next = await sqlite.generateSQLiteDrizzleJson(schema, prev?.id);\n statements = await sqlite.generateSQLiteMigration(\n (prev as never) ?? (await sqlite.generateSQLiteDrizzleJson({})),\n next,\n );\n cur = next;\n }\n if (!statements.length) return undefined;\n const prefix = String(idx).padStart(4, \"0\");\n const tag = `${prefix}_${name}`;\n mkdirSync(meta, { recursive: true });\n const file = join(folder, `${tag}.sql`);\n writeFileSync(file, statements.join(\"\\n--> statement-breakpoint\\n\"));\n writeFileSync(\n join(meta, `${prefix}_snapshot.json`),\n JSON.stringify(cur, null, 2),\n );\n journal.entries.push({\n idx,\n version: cur.version,\n when: Date.now(),\n tag,\n breakpoints: true,\n });\n writeFileSync(journalFile, JSON.stringify(journal, null, 2));\n return file;\n}\n\n/**\n * Make the database match the tables with drizzle-kit's push, touching only\n * the tables Brick knows. Returns how many statements ran.\n */\nasync function push(entry: AppDatabase, force: boolean): Promise<number> {\n const { pushSchema, pushSQLiteSchema } = await kit();\n const db = entry.database.getDb() as any;\n const names = new Set(entry.tables.map((table) => getTableName(table)));\n const schema = drizzleSchema(entry.tables);\n const postgres = entry.database.engine === \"postgres\";\n const result = postgres\n ? await pushSchema(\n schema,\n // drizzle-kit reads `rows` (node-postgres); postgres-js returns the rows.\n {\n execute: async (query: never) => ({ rows: await db.execute(query) }),\n } as never,\n [\n ...new Set(\n entry.tables.map(\n // What drizzle's getTableConfig(table).schema reads.\n (table) =>\n ((table as never)[Symbol.for(\"drizzle:Schema\")] as\n | string\n | undefined) ?? \"public\",\n ),\n ),\n ],\n [...names],\n )\n : await pushSQLiteSchema(schema, onlyTables(db, names) as never);\n const statements = result.statementsToExecute;\n if (!statements.length) return 0;\n for (const warning of result.warnings) console.log(warning);\n if (result.hasDataLoss && !force)\n throw new Error(\n `Brick: pushing ${entry.name} would lose data (see above). Rerun with --force to apply it, or use \\`brick db generate\\` and edit the migration.`,\n );\n if (postgres)\n await db.transaction(async (tx: any) => {\n for (const statement of statements) await tx.execute(sql.raw(statement));\n });\n else await result.apply();\n return statements.length;\n}\n\n/**\n * drizzle-kit's SQLite push has no table filter: hide the tables Brick does not\n * know (FTS sidecars, other apps' tables) from what it reads, so it neither\n * drops them nor asks whether a new table renames one.\n */\nfunction onlyTables(db: any, names: Set<string>) {\n return {\n all: (query: unknown) =>\n db.all(query).filter((row: Record<string, unknown>) => {\n const table =\n row.tableName ?? row.tableFrom ?? row.tbl_name ?? row.view_name;\n return table === undefined || names.has(table as string);\n }),\n run: (query: unknown) => db.run(query),\n };\n}\n","#!/usr/bin/env bun\nimport { resolve } from \"node:path\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport { startDevServer, startProdServer, startWorker } from \"./runner\";\nimport { buildApplication } from \"./build\";\nimport { writeClientContract } from \"./client-contract-file\";\nimport { getGlobalRegistry } from \"@brickkit/core\";\nimport { loadBrickApp } from \"./app-entry\";\nimport {\n ConfigError,\n DEFAULT_DASHBOARD_PORT,\n DEFAULT_HISTORY_DAYS,\n DEFAULT_PORT,\n resolvePort,\n resolveDevDashboard,\n resolveProject,\n type LoadedConfig,\n} from \"./config\";\nimport { writeServiceManifest } from \"./manifest\";\nimport { runLint } from \"./lint\";\nimport { runDbCommand } from \"./db\";\nimport cliPkg from \"../package.json\";\n\n// Single source of truth for the CLI version (inlined at build time).\nconst CLI_VERSION: string = cliPkg.version;\n\nconst PORT_HELP = `Port to listen on (CLI --port overrides PORT env, default ${DEFAULT_PORT})`;\n\nconst EXTENSION_HELP =\n \"Dashboard extension module (default export defineDashboard(...)), or the dashboard folder brick build wrote\";\n\nconst PORT_RESOLUTION_HELP = `\nPort Resolution (dev/start commands):\n - CLI --port flag takes precedence\n - Falls back to PORT environment variable\n - Then dev.port in brick.config.ts (brick dev only)\n - Defaults to ${DEFAULT_PORT} if none is set\n - Valid range: 1-65535\n\nExamples:\n brick dev app.ts # port 4000 (default)\n brick dev app.ts --port 5000 # port 5000 (explicit)\n PORT=3000 brick dev app.ts # port 3000 (from env)\n brick dev app.ts --port 6000 # port 6000 (CLI overrides PORT=3000)\n`;\n\nconst CONFIG_HELP =\n \"Path to brick.config.ts (default: the nearest one in this folder or its parents)\";\n\nfunction parsePortOption(value: string): number {\n try {\n return resolvePort(value);\n } catch (err) {\n throw new InvalidArgumentError((err as Error).message);\n }\n}\n\nfunction parseHistoryDays(value: string): number {\n const days = Number(value);\n if (!/^\\d+$/.test(value.trim()) || !Number.isSafeInteger(days)) {\n throw new InvalidArgumentError(\n `--history-days must be a whole number of days, or 0 for none (got '${value}')`,\n );\n }\n return days;\n}\n\nfunction parseFileOption(value: string, usage: string): string {\n if (value.startsWith(\"-\")) {\n throw new InvalidArgumentError(`${usage} (got flag-like value '${value}')`);\n }\n return value;\n}\n\n/** The project of the program-level `--config`, else the nearest config file. */\nfunction projectOf(command: Command): Promise<LoadedConfig> {\n return resolveProject(command.optsWithGlobals<{ config?: string }>().config);\n}\n\nfunction entryOf(entry: string | undefined, project: LoadedConfig) {\n return entry ?? (project.file ? project.entry : undefined);\n}\n\n/** Without an entry argument or config entry, commander's usual error. */\nfunction requireEntry(\n command: Command,\n entry: string | undefined,\n project: LoadedConfig,\n): string {\n const resolved = entryOf(entry, project);\n if (!resolved)\n command.error(\"error: missing required argument 'entry'\", {\n exitCode: 1,\n code: \"commander.missingArgument\",\n });\n return resolved!;\n}\n\n/** Load the app after refreshing the services manifest it imports. */\nasync function loadProjectApp(entry: string, project: LoadedConfig) {\n if (project.file) await writeServiceManifest(project);\n return loadBrickApp(entry);\n}\n\nfunction fromRoot(\n project: LoadedConfig,\n path: string | undefined,\n): string | undefined {\n return path && resolve(project.root, path);\n}\n\n/** The config's dashboard settings; a `--dashboard-extension` flag replaces its extension. */\nfunction configDashboard(project: LoadedConfig, extensionFlag?: string) {\n const dashboard = project.config.dashboard;\n if (!dashboard && !extensionFlag) return undefined;\n return {\n extension: extensionFlag ?? fromRoot(project, dashboard?.extension),\n theme: dashboard?.theme,\n };\n}\n\nasync function writeOpenApi(\n entry: string,\n output: string | undefined,\n project: LoadedConfig,\n) {\n const app = await loadProjectApp(entry, project);\n const json = JSON.stringify(app.openApiDocument(), null, 2);\n if (output) await Bun.write(output, json);\n return json;\n}\n\nexport function createProgram(): Command {\n const program = new Command();\n program\n .name(\"brick\")\n .description(\"🧱 Brick-TS CLI\")\n .version(CLI_VERSION)\n .showHelpAfterError()\n .configureHelp({ showGlobalOptions: true })\n .option(\"--config <path>\", CONFIG_HELP)\n .addHelpText(\n \"after\",\n `\nWith a brick.config.ts, the entry and most flags come from the config file.\n${PORT_RESOLUTION_HELP}`,\n );\n\n program\n .command(\"dev\")\n .description(\"Start development server with live reload\")\n .option(\n \"--client <file>\",\n \"Generate and watch a browser contract before startup\",\n )\n .option(\n \"--frontend <command>\",\n \"Start frontend after contract generation; requires --client\",\n )\n .option(\n \"--dashboard-port <number>\",\n `Port for the local dashboard (default ${DEFAULT_DASHBOARD_PORT})`,\n parsePortOption,\n )\n .option(\n \"--history-days <number>\",\n `Days of requests the dashboard keeps on disk, 0 for none (default ${DEFAULT_HISTORY_DAYS})`,\n parseHistoryDays,\n )\n .option(\"--no-dashboard\", \"Do not start the local dashboard\")\n .option(\"--dashboard-extension <file>\", EXTENSION_HELP)\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(\n async (\n entryArg: string | undefined,\n opts: {\n port?: number;\n client?: string;\n frontend?: string;\n dashboardPort?: number;\n historyDays?: number;\n dashboard?: boolean;\n dashboardExtension?: string;\n },\n command: Command,\n ) => {\n const project = await projectOf(command);\n const { config } = project;\n const entry = entryOf(entryArg, project);\n const port = resolvePort(opts.port, config.dev?.port);\n const dashboard = resolveDevDashboard(config.dev?.dashboard, opts);\n await startDevServer({\n entry,\n port,\n clientOutput: opts.client ?? fromRoot(project, config.client?.output),\n frontend: opts.frontend ?? config.dev?.frontend,\n // The dashboard reads the app's requests, so it needs an entry.\n dashboard:\n entry && dashboard\n ? {\n ...dashboard,\n ...configDashboard(project, opts.dashboardExtension),\n }\n : false,\n manifest: project.file ? project : undefined,\n });\n },\n );\n\n program\n .command(\"start\")\n .description(\"Start production server\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\"--port <number>\", PORT_HELP, parsePortOption)\n .option(\"--dashboard-extension <file>\", EXTENSION_HELP)\n .addHelpText(\"after\", PORT_RESOLUTION_HELP)\n .action(\n async (\n entry: string | undefined,\n opts: { port?: number; dashboardExtension?: string },\n command: Command,\n ) => {\n const project = await projectOf(command);\n await startProdServer({\n entry: entryOf(entry, project),\n port: resolvePort(opts.port),\n dashboard: configDashboard(project, opts.dashboardExtension),\n });\n },\n );\n\n program\n .command(\"worker\")\n .description(\"Deliver the app's events without serving HTTP\")\n .argument(\n \"[entry]\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .action(\n async (entry: string | undefined, _opts: object, command: Command) => {\n const project = await projectOf(command);\n await startWorker({ entry: requireEntry(command, entry, project) });\n },\n );\n\n program\n .command(\"build\")\n .description(\"Compile a default-exported BrickApp into a Bun server\")\n .argument(\n \"[entry]\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .option(\"--outdir <dir>\", \"Output directory\", (v: string) =>\n parseFileOption(v, \"Usage: brick build <app.ts> [--outdir <directory>]\"),\n )\n .option(\"--port <number>\", \"Default listening port\", parsePortOption)\n .option(\"--no-aot\", \"Disable ahead-of-time compilation\")\n .option(\n \"--dashboard-extension <file>\",\n \"Dashboard extension module to build into <outdir>/dashboard\",\n )\n .option(\n \"--prefix <path>\",\n \"DEPRECATED: configure prefix in brick() app instead\",\n )\n .option(\n \"--no-request-logging\",\n \"DEPRECATED: configure requestLogging in brick() app instead\",\n )\n .action(\n async (\n entryArg: string | undefined,\n opts: {\n outdir?: string;\n port?: number;\n aot?: boolean;\n prefix?: string;\n requestLogging?: boolean;\n dashboardExtension?: string;\n },\n command: Command,\n ) => {\n if (opts.prefix !== undefined || opts.requestLogging === false) {\n throw new ConfigError(\n \"Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.\",\n );\n }\n const project = await projectOf(command);\n const build = project.config.build;\n // shortcut: brick() sets up request logging when the app is created, so\n // a build cannot switch it off; only the default (true) is accepted.\n if (build?.requestLogging === false)\n throw new ConfigError(\n \"Brick: configure requestLogging in your default-exported brick() app instead of build.requestLogging.\",\n );\n const entry = requireEntry(command, entryArg, project);\n if (project.file) await writeServiceManifest(project);\n const result = await buildApplication({\n entry,\n outdir: opts.outdir ?? project.outdir,\n port: opts.port,\n // --no-aot can only switch it off, so otherwise the config decides.\n aot: opts.aot === false ? false : build?.aot,\n dashboard: configDashboard(project, opts.dashboardExtension),\n });\n for (const warning of result.ir.diagnostics)\n console.warn(`[Brick compiler] ${warning}`);\n console.log(\n `Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`,\n );\n console.log(`IR: ${result.outdir}/brick-ir.json`);\n if (result.dashboard)\n console.log(`Dashboard extension: ${result.dashboard}`);\n console.log(`Run: bun ${result.entry}`);\n },\n );\n\n const gen = program\n .command(\"gen\")\n .description(\"Generate artifacts from a BrickApp entry\")\n .argument(\"[subcommand]\", \"Generator to run (openapi, client, manifest)\")\n .action(\n async (\n subcommand: string | undefined,\n _opts: object,\n command: Command,\n ) => {\n const project = await projectOf(command);\n if (subcommand !== undefined || !project.file) {\n console.error(\n `Unknown generator: ${subcommand ?? \"(none)\"}. Available: openapi, client, manifest`,\n );\n process.exit(1);\n }\n // With a config, bare `brick gen` writes everything the config names.\n const manifest = await writeServiceManifest(project);\n console.log(`Services manifest written to ${manifest}`);\n if (project.config.client?.output) {\n await writeClientContract(project.entry, project.contract);\n console.log(`Client contract written to ${project.contract}`);\n }\n const openapi = fromRoot(project, project.config.openapi?.output);\n if (openapi) {\n await writeOpenApi(project.entry, openapi, project);\n console.log(`✅ OpenAPI 3.1 specification written to ${openapi}`);\n }\n },\n );\n\n gen\n .command(\"openapi\")\n .description(\"Generate OpenAPI 3.1 JSON specification\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\n \"--output <file>\",\n \"Write specification to file instead of stdout\",\n (v: string) =>\n parseFileOption(\n v,\n \"Usage: brick gen openapi <entry> [--output <file>]\",\n ),\n )\n .action(\n async (\n entry: string | undefined,\n opts: { output?: string },\n command: Command,\n ) => {\n const project = await projectOf(command);\n const output =\n opts.output ?? fromRoot(project, project.config.openapi?.output);\n const json = await writeOpenApi(\n requireEntry(command, entry, project),\n output,\n project,\n );\n if (output)\n console.log(`✅ OpenAPI 3.1 specification written to ${output}`);\n else console.log(json);\n },\n );\n\n gen\n .command(\"client\")\n .description(\"Generate a typed browser client contract\")\n .argument(\"[entry]\", \"Application entry file\")\n .option(\n \"--output <file>\",\n \"Write contract to file (default _brick/contract.ts)\",\n (v: string) =>\n parseFileOption(v, \"Usage: brick gen client <entry> [--output <file>]\"),\n )\n .action(\n async (\n entry: string | undefined,\n opts: { output?: string },\n command: Command,\n ) => {\n const project = await projectOf(command);\n const target = requireEntry(command, entry, project);\n if (project.file) await writeServiceManifest(project);\n const output = await writeClientContract(\n target,\n opts.output ?? project.contract,\n );\n console.log(`Client contract written to ${output}`);\n },\n );\n\n gen\n .command(\"manifest\")\n .description(\n \"Write <generated>/services.gen.ts, which imports every definition file\",\n )\n .action(async (_opts: object, command: Command) => {\n const output = await writeServiceManifest(await projectOf(command));\n console.log(`Services manifest written to ${output}`);\n });\n\n const db = program\n .command(\"db\")\n .description(\n \"Manage the app's database schema with drizzle-kit: generate, migrate, push\",\n );\n const dbCommand = (\n name: \"generate\" | \"migrate\" | \"push\",\n description: string,\n ) =>\n db\n .command(name)\n .description(description)\n .argument(\"[entry]\", \"Application entry file\");\n // push writes no files, so only generate and migrate take --out.\n const OUT_HELP =\n \"Migrations folder (default drizzle, beside brick.config.ts); each database gets a subfolder named after it\";\n const dbAction =\n (name: \"generate\" | \"migrate\" | \"push\") =>\n async (\n entry: string | undefined,\n opts: { out?: string; name?: string; force?: boolean },\n command: Command,\n ) => {\n const project = await projectOf(command);\n const app = await loadProjectApp(\n requireEntry(command, entry, project),\n project,\n );\n await runDbCommand(name, app, {\n out: opts.out ?? fromRoot(project, \"drizzle\")!,\n name: opts.name,\n force: opts.force,\n });\n };\n dbCommand(\n \"generate\",\n \"Write a SQL migration for the schema changes since the last one\",\n )\n .option(\"--out <dir>\", OUT_HELP)\n .option(\"--name <name>\", \"Migration name (default migration)\")\n .action(dbAction(\"generate\"));\n dbCommand(\"migrate\", \"Apply the migrations that have not run yet\")\n .option(\"--out <dir>\", OUT_HELP)\n .action(dbAction(\"migrate\"));\n dbCommand(\n \"push\",\n \"Change the database to match the schema directly, without migration files (development)\",\n )\n .option(\"--force\", \"Apply changes that drop data\")\n .action(dbAction(\"push\"));\n\n program\n .command(\"lint\")\n .description(\"Check the project against the Brick lint rules\")\n .argument(\"[entry]\", \"Application entry file\")\n .action(\n async (entry: string | undefined, _opts: object, command: Command) => {\n const project = await projectOf(command);\n const code = await runLint({ entry, project });\n if (code !== 0) process.exit(code);\n },\n );\n\n program\n .command(\"info\")\n .alias(\"services\")\n .description(\"Export architecture JSON schema\")\n .argument(\"[entry]\", \"Application entry file\")\n .action(\n async (entry: string | undefined, _opts: object, command: Command) => {\n const project = await projectOf(command);\n const app = await loadProjectApp(\n requireEntry(command, entry, project),\n project,\n );\n const architecture = getGlobalRegistry().exportArchitecture(\n app.definition,\n );\n console.log(JSON.stringify(architecture, null, 2));\n },\n );\n\n return program;\n}\n\nasync function main() {\n const program = createProgram();\n await program.parseAsync(\n process.argv.length > 2 ? process.argv : [...process.argv, \"dev\"],\n );\n}\n\nmain().catch((err) => {\n // Commander already prints validation errors (missing arg, unknown option,\n // invalid port) and exits. Only print Fatal error for action failures.\n if (err?.exitCode !== undefined) {\n process.exit(err.exitCode);\n }\n if (err?.code?.startsWith?.(\"commander.\")) {\n process.exit(1);\n }\n // A config error already names the file and key; a stack adds nothing.\n if (err instanceof ConfigError) {\n console.error(err.message);\n process.exit(1);\n }\n console.error(\"Fatal error:\", err);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,IAAI;;AAEJ,SAAS,aAAa;CACpB,MAAM,OAAO,cAAc,YAAY,GAAG;CAC1C,IAAI,CAAC,KAAK,SAAS,KAAK,GAAG,OAAO,QAAQ,QAAQ,IAAI,GAAG,gBAAgB;CACzE,IAAI,YAAY,OAAO;CAEvB,MAAM,OAAO,QAAQ,MAAM,4CAA4C;CAEvE,MAAM,WAAW,GAAG,KAAK,GAAG,QAAQ;CACpC,MAAM,SAAS,UACb,QAAQ,UACR;EAAC;EAAS,QAAQ,QAAQ,IAAI,GAAG,WAAW;EAAG;EAAY;CAAM,CAAC,CAAC,OAAO;EACxE;EACA;EACA;EACA;CACF,CAAC,GACD,EAAE,UAAU,OAAO,CACrB;CACA,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,MACR,4CAA4C,OAAO,QACrD;CACF,WAAW,UAAU,IAAI;CACzB,OAAQ,aAAa;AACvB;AAEA,SAAS,UAAU,MAAc;CAC/B,KAAK,MAAM,QAAQ,CACjB,KAAK,MAAM,cAAc,GACzB,cAAc,YAAY,GAAG,CAC/B,GACE,IAAI;EACF,MAAM,MAAM,cAAc,IAAI,CAAC,CAAC,QAAQ,qBAAqB;EAC7D,OAAO,KAAK,QAAQ,GAAG,GAAG,YAAY;CACxC,QAAQ,CAAC;CAEX,MAAM,IAAI,YACR,2DACF;AACF;;;;;AAMA,SAAgB,aAAa,SAMX;CAChB,MAAM,QAAQ,O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