@brickkit/cli 0.15.0 → 0.16.0-beta.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.
- package/dashboard-dist/{CollapsiblePanel-CbUysOp5.js → CollapsiblePanel-DvJpFahB.js} +2 -2
- package/dashboard-dist/Geist-Variable.woff2 +0 -0
- package/dashboard-dist/GeistMono-Variable.woff2 +0 -0
- package/dashboard-dist/{api-reference-BP4ULs5J.js → api-reference-C2_JX174.js} +82 -70
- package/dashboard-dist/app.css +2 -2
- package/dashboard-dist/app.js +5 -5
- package/dashboard-dist/{client-CID_ep-s.js → client-DsITZplk.js} +1 -1
- package/dashboard-dist/{core-B123mLVe.js → core-sW89OSz5.js} +1 -1
- package/dashboard-dist/docs-D3U7gUWq.js +4 -0
- package/dashboard-dist/kit.js +1 -1
- package/dashboard-dist/{popover-B4rnc_po.js → popover-Bb2Q3jiK.js} +1 -1
- package/dist/bin.d.ts +1 -2
- package/dist/bin.js +6 -6
- package/dist/bin.js.map +1 -1
- package/dist/build.js.map +1 -1
- package/dist/client-contract-file.js +2 -1
- package/dist/client-contract-file.js.map +1 -1
- package/dist/compiler.d.ts +1 -2
- package/dist/config2.d.ts +1 -2
- package/dist/dashboard-extension.d.ts +1 -2
- package/dist/dashboard-host.js.map +1 -1
- package/dist/dashboard.d.ts +4 -4
- package/dist/definitions.js +1 -0
- package/dist/definitions.js.map +1 -1
- package/dist/dev-application.js.map +1 -1
- package/dist/dev-reporter.d.ts +1 -2
- package/dist/dev-reporter.js.map +1 -1
- package/dist/dev-telemetry.js.map +1 -1
- package/dist/dev-worker.js.map +1 -1
- package/dist/index.d.ts +1 -2
- package/dist/lint/oxlint.d.ts +1 -2
- package/dist/plugin.d.ts +1 -2
- package/dist/production-dashboard2.d.ts +1 -2
- package/dist/project.js +35 -12
- package/dist/project.js.map +1 -1
- package/dist/serve.d.ts +1 -2
- package/dist/serve2.js.map +1 -1
- package/dist/vite.d.ts +1 -2
- package/dist/vite.js.map +1 -1
- package/dist/workflows.d.ts +1 -2
- package/inspector-dist/client/assets/app-Wfnqu2Ic.css +4610 -0
- package/inspector-dist/client/assets/{dist-BK8w6xOr.js → dist-CEyPxAJU.js} +2008 -334
- package/inspector-dist/client/assets/{entry.client-D9jbgmTR.js → entry.client-Cszf0uLP.js} +4628 -2593
- package/inspector-dist/client/assets/highlighted-body-JLMTFACH-CgFt8UnP.js +41 -0
- package/inspector-dist/client/assets/{home-hwPlkNhv.js → home-B2m1nnIz.js} +191 -105
- package/inspector-dist/client/assets/{jsx-runtime-CPEah4WQ.js → jsx-runtime-DRYYXgdJ.js} +2946 -2001
- package/inspector-dist/client/assets/{manifest-0e76e9ac.js → manifest-cfc09adc.js} +1 -1
- package/inspector-dist/client/assets/mermaid-WFAXDIZX-BoRESrqm.js +1 -0
- package/inspector-dist/client/assets/root-CVescmwt.css +4544 -0
- package/inspector-dist/client/assets/{root-SLeEf-sT.js → root-CVhM1JOR.js} +3 -3
- package/inspector-dist/client/assets/{run-detail-DYbVkIFH.js → run-detail-BdV01jxD.js} +90 -50
- package/inspector-dist/client/assets/tabs-BVrPbzfI.css +66 -0
- package/inspector-dist/client/assets/{tabs-CaJisoyb.js → tabs-C2hdi5D4.js} +12496 -8708
- package/inspector-dist/client/assets/{zstd-browser-decoder-D94wmfAU.js → zstd-browser-decoder-DQWDmc2d.js} +2 -2
- package/inspector-dist/server/assets/{app-DGlfWVUI.js → app-w0nTXgJd.js} +51489 -51478
- package/inspector-dist/server/assets/{chunk-RLXIAIE6-F0SJZlei.js → chunk-7TTQLYRW-BO6_qAAU.js} +10986 -7848
- package/inspector-dist/server/assets/cjs-DPK66Gxq.js +3600 -0
- package/inspector-dist/server/assets/{dist-BCbwm6jl.js → dist-DTHqO9VA.js} +149 -1619
- package/inspector-dist/server/assets/{dist-Ce0I2PUv.js → dist-OLuKLJ4s.js} +8 -8
- package/inspector-dist/server/assets/{encryption-DdQgC8Rk.js → encryption-DMo4uOFN.js} +5 -5
- package/inspector-dist/server/assets/{event-metadata-n7E4zEmT.js → event-metadata-Bx8Ts484.js} +1 -1
- package/inspector-dist/server/assets/functions-B9XwHSzK.js +6972 -0
- package/inspector-dist/server/assets/{global-singleton-D8sIN5du.js → global-singleton-rNtXNHKV.js} +1 -1
- package/inspector-dist/server/assets/highlighted-body-JLMTFACH-B0HDNeQE.js +41 -0
- package/inspector-dist/server/assets/mermaid-WFAXDIZX-B-AIJZhh.js +1 -0
- package/inspector-dist/server/assets/serialization-DsMds3lJ.js +5716 -0
- package/inspector-dist/server/assets/{serialization-format-BbuGfHog.js → serialization-format-B27jSUCM.js} +30 -9
- package/inspector-dist/server/assets/state-resolver-DVs_zsEO.js +1422 -0
- package/inspector-dist/server/assets/{token-BgMmJNP5.js → token-CvvD8Y5H.js} +1 -1
- package/inspector-dist/server/assets/token-CxjWFNNq.js +63 -0
- package/inspector-dist/server/assets/token-util-D9IsWeEs.js +3 -0
- package/inspector-dist/server/assets/{wrapper-CIC3w0oC.js → wrapper-B_u9Z5Up.js} +58 -26
- package/inspector-dist/server/assets/{ws-transport-CxTYB11n.js → ws-transport-CamzQ5O8.js} +24379 -24240
- package/inspector-dist/server/assets/{zstd-browser-decoder-D7bCXbGg.js → zstd-browser-decoder-DlGbqUuc.js} +2 -2
- package/inspector-dist/server/index.js +1 -1
- package/package.json +21 -21
- package/dashboard-dist/docs-B5JrvjJm.js +0 -4
- package/inspector-dist/client/assets/app-CeSwVsRm.css +0 -2
- package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-CfRnuITN.js +0 -34
- package/inspector-dist/client/assets/mermaid-3ZIDBTTL-ZDR2PNY_.js +0 -1
- package/inspector-dist/client/assets/root-ChBNTZd2.css +0 -2
- package/inspector-dist/client/assets/tabs-L5XKzOpP.css +0 -1
- package/inspector-dist/server/assets/functions-CNVQtbgg.js +0 -1170
- package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-CWRzMxYD.js +0 -34
- package/inspector-dist/server/assets/mermaid-3ZIDBTTL-D0v0ngVr.js +0 -1
- package/inspector-dist/server/assets/parse-Begau9cA.js +0 -469
package/dist/bin.js
CHANGED
|
@@ -102,7 +102,7 @@ function runFileRules(options) {
|
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
104
|
// src/lint.ts
|
|
105
|
-
const posix
|
|
105
|
+
const posix = (path) => path.split(sep).join("/");
|
|
106
106
|
const SOURCE = new Bun.Glob(`**/*.{${[...DEFINITION_EXTENSIONS, "cts"].join(",")}}`);
|
|
107
107
|
/**
|
|
108
108
|
* `brick lint`: the file rules through oxlint, then the app
|
|
@@ -151,7 +151,7 @@ function sourceFiles(check, under = check.root) {
|
|
|
151
151
|
cwd: under,
|
|
152
152
|
onlyFiles: true
|
|
153
153
|
})].map((file) => resolve(under, file)).filter((file) => {
|
|
154
|
-
const rel = posix
|
|
154
|
+
const rel = posix(relative(check.root, file));
|
|
155
155
|
return !check.ignored(rel) && !TEST_FILE.test(rel) && !rel.startsWith("dist/");
|
|
156
156
|
});
|
|
157
157
|
}
|
|
@@ -169,7 +169,7 @@ const APP_CHECKS = {
|
|
|
169
169
|
async function checkApp(check) {
|
|
170
170
|
const messages = [];
|
|
171
171
|
const message = (rule, severity, file, text, line = 1) => ({
|
|
172
|
-
file: posix
|
|
172
|
+
file: posix(relative(check.root, file)),
|
|
173
173
|
line,
|
|
174
174
|
column: 1,
|
|
175
175
|
rule: `brick/${rule}`,
|
|
@@ -197,7 +197,7 @@ function singleAppEntry(check, _app, add) {
|
|
|
197
197
|
if (!/import\s*\{[^}]*\bbrick\b[^}]*\}\s*from\s*["']@brickkit\/core["']/.test(source)) continue;
|
|
198
198
|
for (const match of source.matchAll(/(?<![.\w])brick\s*\(/g)) {
|
|
199
199
|
if (file === check.entry && ++calls === 1) continue;
|
|
200
|
-
add(file, file === check.entry ? "The entry calls brick() more than once; keep one app." : `brick() is called outside the entry (${posix
|
|
200
|
+
add(file, file === check.entry ? "The entry calls brick() more than once; keep one app." : `brick() is called outside the entry (${posix(relative(check.root, check.entry))}); keep one app.`, lineOf(source, match.index));
|
|
201
201
|
}
|
|
202
202
|
}
|
|
203
203
|
}
|
|
@@ -222,7 +222,7 @@ const IMPORT = /(?:import|export)\s+(type\s+)?([\w$]+\s*,?\s*)?(\*(?:\s+as\s+[\w
|
|
|
222
222
|
async function noCrossServiceTables(check, app, add) {
|
|
223
223
|
const owners = tableOwners(app);
|
|
224
224
|
for (const file of sourceFiles(check, check.services)) {
|
|
225
|
-
const folder = posix
|
|
225
|
+
const folder = posix(relative(check.services, file)).split("/")[0];
|
|
226
226
|
const service = serviceOfFolder(app, folder);
|
|
227
227
|
if (!service) continue;
|
|
228
228
|
const source = readFileSync(file, "utf8");
|
|
@@ -236,7 +236,7 @@ async function noCrossServiceTables(check, app, add) {
|
|
|
236
236
|
continue;
|
|
237
237
|
}
|
|
238
238
|
const line = lineOf(source, match.index);
|
|
239
|
-
const where = posix
|
|
239
|
+
const where = posix(relative(check.services, target)).split("/");
|
|
240
240
|
const otherFolder = !where[0].startsWith("..") && where.length > 1 ? where[0] : void 0;
|
|
241
241
|
if (otherFolder && otherFolder !== folder && DEFINITION_FILE.exec(basename(target))?.[2] === "table") {
|
|
242
242
|
add(file, `Service "${service}" imports ${basename(target)} from ${otherFolder}/; call that service's actions or listen to its events instead.`, line);
|
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","../src/schedules.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","import type { ScheduleState } from \"@brickkit/core\";\nimport { loadBrickApp } from \"./app-entry\";\nimport { ConfigError } from \"./config\";\nimport { describeSchedule } from \"./dashboard-protocol\";\n\n/** The schedules as a plain table: name, when, next run, last outcome. */\nexport function formatSchedules(schedules: ScheduleState[]): string {\n const rows = [\n [\"NAME\", \"WHEN\", \"NEXT RUN\", \"LAST RUN\"],\n ...schedules.map((schedule) => {\n const last = schedule.runs[0];\n return [\n schedule.name,\n describeSchedule(schedule),\n schedule.running\n ? \"running\"\n : !schedule.enabled\n ? \"disabled\"\n : (schedule.nextRunAt ?? \"not started yet\"),\n last\n ? `${last.outcome} ${last.finishedAt}${last.error ? ` (${last.error})` : \"\"}`\n : \"never\",\n ];\n }),\n ];\n const widths = rows[0]!.map((_, column) =>\n Math.max(...rows.map((row) => row[column]!.length)),\n );\n return rows\n .map((row) =>\n row\n .map((cell, column) =>\n column === row.length - 1 ? cell : cell.padEnd(widths[column]!),\n )\n .join(\" \"),\n )\n .join(\"\\n\");\n}\n\n/**\n * What `brick schedules` runs: list the app's schedules from its schedule\n * table, or, with `run`, make one due now. The processes that run the\n * schedules (`brick start`, `brick worker`) pick it up at their next poll.\n *\n * @throws When the app has no schedules, or none named `run`.\n */\nexport async function runSchedulesCommand(\n entry: string,\n options: { run?: string } = {},\n): Promise<string> {\n const app = await loadBrickApp(entry);\n const schedules = app.events?.schedules;\n if (!schedules)\n throw new ConfigError(\n \"Brick: this app has no schedules. Add them with brick({ events: { schedules } }).\",\n );\n if (options.run === undefined) return formatSchedules(await schedules.list());\n try {\n return (await schedules.trigger(options.run))\n ? `'${options.run}' is due now: a process running the schedules starts it at its next poll.`\n : `'${options.run}' is running now, so it was not started again.`;\n } catch (error) {\n throw new ConfigError((error as Error).message);\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 { runSchedulesCommand } from \"./schedules\";\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(\n \"Deliver the app's events and run its schedules without serving HTTP\",\n )\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(\"schedules\")\n .description(\n \"List the app's schedules with their next run, or run one now with --run\",\n )\n .argument(\n \"[entry]\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .option(\"--run <name>\", \"Make this schedule due now\")\n .action(\n async (\n entry: string | undefined,\n opts: { run?: string },\n command: Command,\n ) => {\n const project = await projectOf(command);\n console.log(\n await runSchedulesCommand(\n requireEntry(command, entry, project),\n opts,\n ),\n );\n // The app's database connections would keep the process open.\n process.exit(0);\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 if (result.workflows) console.log(`Workflows: ${result.workflows}`);\n console.log(`Run: bun ${result.entry}`);\n // The imported entry may hold timers or sockets open (#109).\n process.exit(0);\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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CAAC;EAC7C,IAAI,SAAS,GAAG,QAAQ,KAAK,IAAI;CACnC,CACF;CAEF,QACG,QAAQ,MAAM,CAAC,CACf,MAAM,UAAU,CAAC,CACjB,YAAY,iCAAiC,CAAC,CAC9C,SAAS,WAAW,wBAAwB,CAAC,CAC7C,OACC,OAAO,OAA2B,OAAe,YAAqB;EACpE,MAAM,UAAU,MAAM,UAAU,OAAO;EACvC,MAAM,MAAM,MAAM,eAChB,aAAa,SAAS,OAAO,OAAO,GACpC,OACF;EACA,MAAM,eAAe,kBAAkB,CAAC,CAAC,mBACvC,IAAI,UACN;EACA,QAAQ,IAAI,KAAK,UAAU,cAAc,MAAM,CAAC,CAAC;CACnD,CACF;CAEF,OAAO;AACT;AAEA,eAAe,OAAO;CAEpB,MADgB,cACJ,CAAC,CAAC,WACZ,QAAQ,KAAK,SAAS,IAAI,QAAQ,OAAO,CAAC,GAAG,QAAQ,MAAM,KAAK,CAClE;AACF;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":["cliPkg.version"],"sources":["../src/lint/run.ts","../src/lint.ts","../src/db.ts","../src/schedules.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","import type { ScheduleState } from \"@brickkit/core\";\nimport { loadBrickApp } from \"./app-entry\";\nimport { ConfigError } from \"./config\";\nimport { describeSchedule } from \"./dashboard-protocol\";\n\n/** The schedules as a plain table: name, when, next run, last outcome. */\nexport function formatSchedules(schedules: ScheduleState[]): string {\n const rows = [\n [\"NAME\", \"WHEN\", \"NEXT RUN\", \"LAST RUN\"],\n ...schedules.map((schedule) => {\n const last = schedule.runs[0];\n return [\n schedule.name,\n describeSchedule(schedule),\n schedule.running\n ? \"running\"\n : !schedule.enabled\n ? \"disabled\"\n : (schedule.nextRunAt ?? \"not started yet\"),\n last\n ? `${last.outcome} ${last.finishedAt}${last.error ? ` (${last.error})` : \"\"}`\n : \"never\",\n ];\n }),\n ];\n const widths = rows[0]!.map((_, column) =>\n Math.max(...rows.map((row) => row[column]!.length)),\n );\n return rows\n .map((row) =>\n row\n .map((cell, column) =>\n column === row.length - 1 ? cell : cell.padEnd(widths[column]!),\n )\n .join(\" \"),\n )\n .join(\"\\n\");\n}\n\n/**\n * What `brick schedules` runs: list the app's schedules from its schedule\n * table, or, with `run`, make one due now. The processes that run the\n * schedules (`brick start`, `brick worker`) pick it up at their next poll.\n *\n * @throws When the app has no schedules, or none named `run`.\n */\nexport async function runSchedulesCommand(\n entry: string,\n options: { run?: string } = {},\n): Promise<string> {\n const app = await loadBrickApp(entry);\n const schedules = app.events?.schedules;\n if (!schedules)\n throw new ConfigError(\n \"Brick: this app has no schedules. Add them with brick({ events: { schedules } }).\",\n );\n if (options.run === undefined) return formatSchedules(await schedules.list());\n try {\n return (await schedules.trigger(options.run))\n ? `'${options.run}' is due now: a process running the schedules starts it at its next poll.`\n : `'${options.run}' is running now, so it was not started again.`;\n } catch (error) {\n throw new ConfigError((error as Error).message);\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 { runSchedulesCommand } from \"./schedules\";\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(\n \"Deliver the app's events and run its schedules without serving HTTP\",\n )\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(\"schedules\")\n .description(\n \"List the app's schedules with their next run, or run one now with --run\",\n )\n .argument(\n \"[entry]\",\n \"Application entry file (must default-export a BrickApp)\",\n )\n .option(\"--run <name>\", \"Make this schedule due now\")\n .action(\n async (\n entry: string | undefined,\n opts: { run?: string },\n command: Command,\n ) => {\n const project = await projectOf(command);\n console.log(\n await runSchedulesCommand(\n requireEntry(command, entry, project),\n opts,\n ),\n );\n // The app's database connections would keep the process open.\n process.exit(0);\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 if (result.workflows) console.log(`Workflows: ${result.workflows}`);\n console.log(`Run: bun ${result.entry}`);\n // The imported entry may hold timers or sockets open (#109).\n process.exit(0);\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,Y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OAAO,MAAM,QAAQ;GAAE;GAAO,eADd,UAAU,OAAO;EACK,CAAC;EAC7C,IAAI,SAAS,GAAG,QAAQ,KAAK,IAAI;CACnC,CACF;CAEF,QACG,QAAQ,MAAM,CAAC,CACf,MAAM,UAAU,CAAC,CACjB,YAAY,iCAAiC,CAAC,CAC9C,SAAS,WAAW,wBAAwB,CAAC,CAC7C,OACC,OAAO,OAA2B,OAAe,YAAqB;EACpE,MAAM,UAAU,MAAM,UAAU,OAAO;EACvC,MAAM,MAAM,MAAM,eAChB,aAAa,SAAS,OAAO,OAAO,GACpC,OACF;EACA,MAAM,eAAe,kBAAkB,CAAC,CAAC,mBACvC,IAAI,UACN;EACA,QAAQ,IAAI,KAAK,UAAU,cAAc,MAAM,CAAC,CAAC;CACnD,CACF;CAEF,OAAO;AACT;AAEA,eAAe,OAAO;CAEpB,MADgB,cACJ,CAAC,CAAC,WACZ,QAAQ,KAAK,SAAS,IAAI,QAAQ,OAAO,CAAC,GAAG,QAAQ,MAAM,KAAK,CAClE;AACF;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"}
|
package/dist/build.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","names":[],"sources":["../src/manifest.ts","../src/runner.ts","../src/compiler/aot.ts","../src/build.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\nimport { writeFileIfChanged } from \"./client-contract-file\";\n\nimport {\n DEFINITION_EXTENSIONS,\n DEFINITION_FILE,\n DEFINITION_KINDS,\n MANIFEST_FILE,\n type DefinitionKind,\n} from \"./definitions\";\n\n/** Services register before the resources that join them; every other kind after. */\nconst FIRST: readonly DefinitionKind[] = [\"service\", \"resource\"];\n\nfunction rank(file: string) {\n const index = FIRST.indexOf(\n DEFINITION_FILE.exec(file)?.[2] as DefinitionKind,\n );\n return index === -1 ? FIRST.length : index;\n}\n\n/** Definition files under `services`: service files first, then resources, then the rest, each by path. */\nexport function scanDefinitionFiles(services: string): string[] {\n if (!existsSync(services)) return [];\n // Built per call: index.ts imports this module (through runner) and still\n // exports defineConfig, so Node may load it (ESLint reading brick.config.ts).\n const glob = new Bun.Glob(\n `**/*.{${DEFINITION_KINDS.join(\",\")}}.{${DEFINITION_EXTENSIONS.join(\",\")}}`,\n );\n const files = [...glob.scanSync({ cwd: services, onlyFiles: true })]\n .map((file) => file.split(sep).join(\"/\"))\n .filter((file) => !file.split(\"/\").includes(\"node_modules\"));\n return files.sort(\n (a, b) => rank(a) - rank(b) || (a < b ? -1 : a > b ? 1 : 0),\n );\n}\n\n/** The source of `services.gen.ts`, which imports every definition file so each registers itself. */\nexport function renderManifest(services: string, generated: string): string {\n const imports = scanDefinitionFiles(services).map((file) => {\n let specifier = relative(generated, join(services, file))\n .split(sep)\n .join(\"/\")\n .replace(DEFINITION_FILE, \"$1.$2\");\n if (!specifier.startsWith(\".\")) specifier = `./${specifier}`;\n return `import ${JSON.stringify(specifier)};\\n`;\n });\n return `// Generated by Brick. Do not edit.\n// Imports every definition file under the services folder, so each one\n// registers itself on its service. The app entry imports this file.\n${imports.join(\"\")}\nexport {};\n`;\n}\n\n/** Write `<generated>/services.gen.ts`, leaving it untouched when nothing changed. */\nexport async function writeServiceManifest(options: {\n services: string;\n generated: string;\n}): Promise<string> {\n const output = join(options.generated, MANIFEST_FILE);\n await writeFileIfChanged(\n output,\n renderManifest(options.services, options.generated),\n );\n return output;\n}\n","import { existsSync, watch } from \"node:fs\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\nimport {\n brick,\n dashboardKey,\n DASHBOARD_KEY_ENV,\n isBrickApp,\n} from \"@brickkit/core\";\nimport { importEntry } from \"./app-entry\";\nimport { TEMPORARY_FILE_PREFIX } from \"./client-contract-file\";\nimport {\n ConfigError,\n CONTRACT_FILE,\n DEFAULT_DASHBOARD_PORT,\n PROJECT_DEFAULTS,\n resolvePort,\n} from \"./config\";\nimport { openDashboard } from \"./dashboard-host\";\nimport { ownModule } from \"./own-module\";\nimport type { DashboardExtensionOptions } from \"./dashboard-extension\";\nimport { startDevApplication } from \"./dev-application\";\nimport type { WorkerMessage, WorkerOptions } from \"./dev-protocol\";\nimport { writeServiceManifest } from \"./manifest\";\nimport { printBanner, serveApp, shutdownOnSignal } from \"./serve\";\nimport { buildAppWorkflows } from \"./workflows\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n /**\n * @deprecated Only used without an `entry`; an exported app sets its own\n * prefix in `brick({ prefix })`.\n */\n prefix?: string;\n /** Generate a browser contract before starting the backend and frontend. */\n clientOutput?: string;\n /** Frontend command, launched once after the first successful generation. */\n frontend?: string;\n /**\n * Local dashboard with live requests, traces, errors, and reloads. Needs an\n * entry. `port` is where it listens and `historyDays` how long finished\n * requests are kept on disk; zero keeps live data only. `extension` and\n * `theme` customise it (see `DashboardExtensionOptions`).\n */\n dashboard?:\n | ({ port?: number; historyDays?: number } & DashboardExtensionOptions)\n | false;\n /**\n * Keep `<generated>/services.gen.ts` importing every definition file under\n * `services`: written before the app starts and again when files change.\n */\n manifest?: { services: string; generated: string };\n}\n\n/**\n * What `brick start` runs: serve the entry's default-exported app as it built\n * it (else one with the registered services), with the monitoring dashboard\n * it asks for, until SIGINT or SIGTERM.\n */\nexport async function startProdServer(options: {\n entry?: string;\n port?: number;\n /** The production dashboard's extension and theme. */\n dashboard?: DashboardExtensionOptions;\n}) {\n let exported: unknown;\n if (options.entry) {\n console.log(\n `[Brick-TS] Loading application entry: ${resolve(options.entry)}`,\n );\n exported = await importEntry(options.entry, { run: true });\n }\n const port = resolvePort(options.port);\n const app = isBrickApp(exported) ? exported : brick();\n await buildAppWorkflows(app);\n const dashboard = await serveApp(app, {\n port,\n dashboard: options.dashboard,\n });\n shutdownOnSignal(app);\n printBanner(app, { label: \"Production\", port, dashboard });\n return app;\n}\n\n/**\n * What `brick worker` runs: load the app, deliver its events and run its\n * schedules from this process, without serving HTTP. Run it beside API processes that only record\n * events (`events: { dispatch: false }`), or alone for an app with no routes.\n * Workflow listeners run here too: the world starts and the steps of every run\n * in it execute in this process.\n *\n * @param options - `entry`: the app file, which must default-export a `brick()` app.\n * @returns The app.\n * @throws When the entry is missing, has no `events`, or only records events.\n */\nexport async function startWorker(options: { entry: string }) {\n console.log(\n `[Brick-TS] Loading application entry: ${resolve(options.entry)}`,\n );\n const app = await importEntry(options.entry, { run: true });\n if (!isBrickApp(app))\n throw new ConfigError(\n \"Brick: a worker needs an entry that default-exports a BrickApp.\",\n );\n if (!app.events)\n throw new ConfigError(\n \"Brick: this app has no events, so a worker has nothing to deliver.\",\n );\n if (!app.events.describe().dispatch)\n throw new ConfigError(\n \"Brick: this app only records events (events.dispatch is false), so a worker would deliver nothing. Enable dispatch for the worker process.\",\n );\n await buildAppWorkflows(app);\n await app.start();\n app.events.start();\n shutdownOnSignal(app);\n const { listeners, schedules = [] } = app.events.describe();\n console.log(`\\n🧱 Brick-TS Worker`);\n console.log(\n ` Delivering events to ${listeners.length} ${listeners.length === 1 ? \"listener\" : \"listeners\"}: ${listeners.map((l) => l.name).join(\", \") || \"none\"}`,\n );\n if (schedules.length)\n console.log(\n ` Running ${schedules.length} ${schedules.length === 1 ? \"schedule\" : \"schedules\"}: ${schedules.map((s) => s.name).join(\", \")}`,\n );\n console.log(\"\");\n return app;\n}\n\n/**\n * What `brick dev` runs: start the application, restart it when its files\n * change, and serve the dashboard beside it. With an `entry`, the app runs in\n * a worker process that restarts on every change to the entry or the files it\n * imports, and reports its requests to the dashboard; without one, a server\n * with the registered services starts in this process.\n *\n * @param options - `entry`, `port` (else `PORT`, else 4000), `prefix`,\n * `clientOutput` to regenerate the typed client's contract on each start,\n * `frontend` to launch a frontend command once, and `dashboard` (`port` and\n * `historyDays`, or `false`).\n * @returns The application, when started in this process.\n * @throws When `frontend` is given without `clientOutput`, or the dashboard\n * would use the app's port.\n */\nexport async function startDevServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n if (!entry && (options.clientOutput || options.frontend))\n throw new ConfigError(\n \"Brick: --client and --frontend require an app entry.\",\n );\n if (options.frontend && !options.clientOutput)\n throw new ConfigError(\"Brick: --frontend requires --client <file>.\");\n const port = resolvePort(options.port);\n if (!entry) return startDevApplication({ port, prefix: options.prefix });\n const resolvedEntry = resolve(entry);\n if (!existsSync(resolvedEntry))\n throw new ConfigError(\n `[Brick-TS] Error: Entry file not found: ${resolvedEntry}`,\n );\n\n if (\n options.dashboard &&\n (options.dashboard.port ?? DEFAULT_DASHBOARD_PORT) === port\n )\n throw new ConfigError(\n \"Brick: dashboard port must differ from the API port. Use --dashboard-port <number>.\",\n );\n const manifest = options.manifest;\n if (manifest) await writeServiceManifest(manifest);\n const contract = resolve(\n options.clientOutput ??\n join(manifest?.generated ?? PROJECT_DEFAULTS.generated, CONTRACT_FILE),\n );\n const workerOptions: WorkerOptions = {\n entry: resolvedEntry,\n port,\n prefix: options.prefix,\n clientOutput: options.clientOutput && contract,\n telemetry: Boolean(options.dashboard),\n };\n // Bind the dashboard before the first worker starts, so the worker's spans\n // have somewhere to go.\n const dashboard = options.dashboard\n ? await openDashboard({\n port: options.dashboard.port,\n directory: process.cwd(),\n historyDays: options.dashboard.historyDays,\n warn: (message) => console.warn(message),\n docs: true,\n dashboard: {\n extension: options.dashboard.extension,\n theme: options.dashboard.theme,\n },\n restart: () => {\n void restart(\"dashboard\");\n },\n portHint: \"Use --dashboard-port <number> or --no-dashboard.\",\n })\n : undefined;\n const telemetry = dashboard?.store;\n let frontend: ReturnType<typeof Bun.spawn> | undefined;\n const dependencyFiles = new Set<string>();\n const dependencyWatchers = new Map<string, ReturnType<typeof watch>>();\n let stopped = false;\n const intentionalExits = new WeakSet<ReturnType<typeof Bun.spawn>>();\n const receive = (message: WorkerMessage, generation: number) => {\n switch (message.type) {\n case \"brick:telemetry\":\n telemetry?.ingest(message.records, generation);\n return;\n case \"brick:error\":\n telemetry?.recordWorkerError(message.phase, message.error, generation);\n return;\n case \"brick:contract-ready\":\n if (options.frontend && !frontend && !stopped)\n frontend = Bun.spawn(\n [process.env.SHELL ?? \"/bin/sh\", \"-c\", options.frontend],\n {\n detached: true,\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n },\n );\n telemetry?.recordReload({\n kind: \"contract-ready\",\n generation,\n detail: \"browser contract generated\",\n });\n return;\n case \"brick:architecture\":\n telemetry?.setArchitecture(message.architecture, generation);\n void dashboard?.setPluginExtensions(message.architecture.plugins ?? []);\n return;\n case \"brick:inspector\":\n if (generation === telemetry?.latestGeneration)\n telemetry.setInspector({\n port: message.port,\n token: message.token,\n workflows: message.workflows,\n });\n return;\n case \"brick:documentation\":\n void dashboard?.docs?.configure(\n dirname(resolvedEntry),\n message.documentation,\n );\n return;\n case \"brick:api-documents\":\n telemetry?.setApiDocuments(\n message.documents,\n `http://localhost:${port}`,\n );\n return;\n case \"brick:dependencies\":\n for (const file of message.files) {\n if (file === contract) continue;\n dependencyFiles.add(file);\n const directory = dirname(file);\n if (!dependencyWatchers.has(directory))\n dependencyWatchers.set(\n directory,\n watch(directory, (_event, filename) => {\n if (\n !filename ||\n !dependencyFiles.has(resolve(directory, filename))\n )\n return;\n scheduleRestart();\n }),\n );\n }\n return;\n }\n };\n const launch = () => {\n // The new process serves its own inspector once it is up.\n telemetry?.setInspector(undefined);\n const generation = telemetry?.startGeneration() ?? 0;\n const application = Bun.spawn(\n [\n process.execPath,\n ownModule(\"dev-worker\"),\n JSON.stringify(workerOptions),\n ],\n {\n cwd: process.cwd(),\n env: dashboard\n ? { ...process.env, [DASHBOARD_KEY_ENV]: dashboardKey() }\n : process.env,\n stdout: \"inherit\",\n stderr: \"inherit\",\n ipc: (message: WorkerMessage) => receive(message, generation),\n },\n );\n void application.exited.then((code) => {\n if (generation === telemetry?.latestGeneration)\n telemetry.setInspector(undefined);\n if (!stopped && !intentionalExits.has(application)) {\n console.error(\n `[Brick-TS] Application process exited with code ${code}. Waiting for changes to restart.`,\n );\n telemetry?.recordReload({\n kind: \"exited\",\n generation,\n detail: `exit code ${code}`,\n });\n }\n telemetry?.interruptGeneration(generation);\n });\n return application;\n };\n if (dashboard) {\n console.log(`📊 Dev dashboard: http://127.0.0.1:${dashboard.port}`);\n }\n let child = launch();\n // The worker reports the other files the entry imports (brick:dependencies).\n const watchDirs = [\n ...new Set([\n dirname(resolvedEntry),\n ...(manifest ? [manifest.services] : []),\n ]),\n ].filter(existsSync);\n let pending: ReturnType<typeof setTimeout> | undefined;\n let restarting = false;\n let dirty = false;\n\n async function restart(trigger: \"changes\" | \"dashboard\" = \"changes\") {\n dirty = true;\n if (restarting || stopped) return;\n restarting = true;\n try {\n while (dirty && !stopped) {\n dirty = false;\n console.log(\n trigger === \"changes\"\n ? \"\\n📝 Changes detected. Restarting server...\"\n : \"\\n🔄 Restart requested from the dashboard. Restarting server...\",\n );\n telemetry?.recordReload({\n kind: \"restarting\",\n generation: telemetry.latestGeneration,\n detail:\n trigger === \"changes\" ? \"source changed\" : \"restart from dashboard\",\n });\n intentionalExits.add(child);\n child.kill();\n await child.exited;\n if (!stopped) child = launch();\n }\n } finally {\n restarting = false;\n }\n }\n\n function scheduleRestart() {\n clearTimeout(pending);\n pending = setTimeout(() => {\n void restart();\n }, 100);\n }\n const extension = options.dashboard && options.dashboard.extension;\n const extensionDir =\n extension && !watchDirs.includes(dirname(resolve(extension)))\n ? `${dirname(resolve(extension))}${sep}`\n : undefined;\n const watchers = watchDirs.map((dir) =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename || filename.split(/[\\\\/]/).includes(\"node_modules\")) return;\n const file = resolve(dir, filename);\n if (\n file === contract ||\n basename(file).startsWith(TEMPORARY_FILE_PREFIX) ||\n // The dashboard rebuilds its extension itself; the app restarts only\n // for the files it imports.\n (extensionDir !== undefined &&\n file.startsWith(extensionDir) &&\n !dependencyFiles.has(file))\n )\n return;\n // A definition file was added or removed: refresh the import list first.\n if (manifest && file.startsWith(manifest.services + sep)) {\n void writeServiceManifest(manifest)\n .catch((error: unknown) =>\n console.error(\"[Brick-TS] Could not write services.gen.ts:\", error),\n )\n .finally(scheduleRestart);\n return;\n }\n scheduleRestart();\n }),\n );\n const stop = () => {\n if (stopped) return;\n stopped = true;\n clearTimeout(pending);\n for (const watcher of watchers) watcher.close();\n for (const watcher of dependencyWatchers.values()) watcher.close();\n if (frontend) {\n if (process.platform === \"win32\") {\n Bun.spawnSync([\"taskkill\", \"/pid\", String(frontend.pid), \"/t\", \"/f\"]);\n } else {\n try {\n process.kill(-frontend.pid, \"SIGTERM\");\n } catch (error) {\n if (\n !(\n error instanceof Error &&\n \"code\" in error &&\n error.code === \"ESRCH\"\n )\n )\n throw error;\n }\n }\n }\n dashboard?.stop();\n child.kill();\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n process.off(\"exit\", stop);\n };\n const onSignal = (signal: NodeJS.Signals) => {\n if (stopped) {\n child.kill(\"SIGKILL\");\n process.exit(signal === \"SIGINT\" ? 130 : 143);\n }\n stop();\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n void child.exited.then(() => process.exit(0));\n };\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n process.on(\"exit\", stop);\n console.log(`\\n👀 Watching for changes in: ${watchDirs.join(\", \")}`);\n return { stop };\n}\n","import { aot } from \"elysia/plugin/aot/bun\";\nimport type { BunPlugin } from \"bun\";\n\n/** Keep the pinned Elysia beta's incomplete stripping from breaking builds. */\nexport function brickAot(entry: string, keep: boolean): BunPlugin {\n // `keep`: WS routes still need cookie setup during reconstruction in beta.29,\n // and shipped workflows mount their webhook route only when a world is set at\n // run time. Retain those modules while continuing to precompile HTTP handlers.\n if (keep) return aot(entry, { target: \"bun\", strip: false });\n return {\n name: \"brick-elysia-aot\",\n async setup(build) {\n await aot(entry, { target: \"bun\", strip: true }).setup({\n ...build,\n onLoad(options, callback) {\n return build.onLoad(options, async (args) => {\n const result = await callback(args);\n if (\n !result ||\n !(\"contents\" in result) ||\n typeof result.contents !== \"string\"\n )\n return result;\n let contents = result.contents;\n if (\n /[/\\\\]elysia[/\\\\]dist[/\\\\]ws[/\\\\]route\\.m?js$/.test(args.path) &&\n contents.includes(\n \"[elysia-aot] WebSocket route builder was stripped\",\n )\n ) {\n for (const name of [\"resolveWSOptions\", \"accumulateWSOptions\"]) {\n if (!contents.includes(`export function ${name}`))\n contents += `\\nexport function ${name}() { throw new Error(\"WebSocket support was stripped\"); }\\n`;\n }\n }\n return contents === result.contents\n ? result\n : { ...result, contents };\n });\n },\n });\n },\n };\n}\n","import { mkdtemp, mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { compileBrickApplication, WORKFLOW_BUNDLE } from \"@brickkit/core\";\nimport type { BunPlugin } from \"bun\";\nimport { emitCompiledApplication } from \"./compiler\";\nimport { brickAot } from \"./compiler/aot\";\nimport { loadBrickApp } from \"./app-entry\";\nimport { ownModule } from \"./own-module\";\nimport { DEFAULT_OUTDIR, resolvePort } from \"./config\";\nimport { shipWorkflows, workflowTransformPlugin } from \"./workflows\";\nimport {\n themeCss,\n writeDashboardExtension,\n type DashboardExtensionOptions,\n} from \"./dashboard-extension\";\n\nexport interface BuildApplicationOptions {\n /** A module whose default export is a BrickApp, without starting a server. */\n entry: string;\n outdir?: string;\n port?: number;\n /** Precompile Elysia's HTTP handlers at build time (default true). */\n aot?: boolean;\n /**\n * The dashboard's extension, built into `<outdir>/dashboard` with those of\n * the app's plugins for the production dashboard to serve; its theme is\n * checked here too.\n */\n dashboard?: DashboardExtensionOptions;\n}\n\n/**\n * The production dashboard stays out of the bundle: it serves files that ship\n * with @brickkit/cli, so a built server whose app asks for it imports it from\n * there at run time. Without a dashboard the bundle needs nothing installed.\n */\nconst productionDashboardAtRunTime: BunPlugin = {\n name: \"brick:production-dashboard\",\n setup(build) {\n build.onResolve({ filter: /^\\.\\/production-dashboard(\\.[jt]s)?$/ }, () => ({\n path: \"@brickkit/cli/production-dashboard\",\n external: true,\n }));\n },\n};\n\n/** The files `brick build` writes to the output folder, `server.js` last. */\nconst OUTPUTS = [\"routes.js\", \"brick-ir.json\", \"server.js.map\", \"server.js\"];\n\n/** Bundle an exported BrickApp with its compiled IR and its original configuration. */\nexport async function buildApplication(options: BuildApplicationOptions) {\n const entry = resolve(options.entry);\n if (!(await Bun.file(entry).exists()))\n throw new Error(`Brick compiler: entry not found: ${entry}`);\n const outdir = resolve(options.outdir ?? DEFAULT_OUTDIR);\n if (OUTPUTS.some((name) => entry === join(outdir, name)))\n throw new Error(\n \"Brick compiler: output would overwrite the application entry\",\n );\n const port = resolvePort(options.port, undefined, \"\");\n themeCss(options.dashboard?.theme);\n const extension = options.dashboard?.extension\n ? resolve(options.dashboard.extension)\n : undefined;\n if (extension && !(await Bun.file(extension).exists()))\n throw new Error(\n `Brick compiler: dashboard extension not found: ${extension}`,\n );\n const app = await loadBrickApp(entry);\n const root = app.events?.workflows?.root ?? process.cwd();\n const services = [...app.definition.services];\n const compilation = compileBrickApplication({\n services,\n prefix: app.definition.prefix,\n });\n await mkdir(dirname(outdir), { recursive: true });\n const staging = await mkdtemp(join(dirname(outdir), \".brick-build-\"));\n try {\n await Bun.write(\n join(staging, \"routes.js\"),\n emitCompiledApplication(compilation.ir),\n );\n const dashboard = (await writeDashboardExtension(\n extension,\n app.definition.plugins ?? [],\n join(staging, \"dashboard\"),\n ))\n ? join(outdir, \"dashboard\")\n : undefined;\n const theme = JSON.stringify(options.dashboard?.theme);\n const source = `import { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { loadCompiledBrickApp } from \"@brickkit/core\";\nimport { resolvePort } from ${JSON.stringify(ownModule(\"config\"))};\nimport { serveApp, shutdownOnSignal } from ${JSON.stringify(ownModule(\"serve\"))};\nconst workflows = fileURLToPath(new URL(${JSON.stringify(`./${WORKFLOW_BUNDLE.dir}`)}, import.meta.url));\nexport const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), undefined, {\n workflows: existsSync(workflows) ? workflows : undefined,\n});\nexport default app;\nif (import.meta.main) {\n await serveApp(app, {\n port: resolvePort(undefined, ${port}),\n dashboard: { extension: ${dashboard ? 'fileURLToPath(new URL(\"./dashboard\", import.meta.url))' : \"undefined\"}, theme: ${theme} },\n });\n console.log(\"Brick compiled server listening on http://localhost:\" + app.server.port);\n shutdownOnSignal(app);\n}\n`;\n await Bun.write(join(staging, \"entry.ts\"), source);\n // Whether to ship workflows depends on the files the bundle holds, not on\n // the env: an app may declare its workflow listeners only at run time.\n let directives = false;\n const transform = await workflowTransformPlugin(root, () => {\n directives = true;\n });\n const result = await Bun.build({\n entrypoints: [join(staging, \"entry.ts\")],\n target: \"bun\",\n format: \"esm\",\n outdir: staging,\n naming: \"server.js\",\n sourcemap: \"external\",\n // AOT first: the workflow plugin loads every project file it sees, so after\n // it the AOT plugin would never get to transform the entry.\n plugins: [\n ...(options.aot === false\n ? []\n : [\n brickAot(\n join(staging, \"entry.ts\"),\n app.definition.sockets.length > 0 || transform !== undefined,\n ),\n ]),\n ...(transform ? [transform] : []),\n productionDashboardAtRunTime,\n ],\n });\n if (!result.success)\n throw new AggregateError(result.logs, \"Brick compiler: bundling failed\");\n const workflows =\n (directives || Boolean(app.events?.workflows)) &&\n (await shipWorkflows(root, staging, Boolean(app.events?.workflows)));\n await Bun.write(\n join(staging, \"brick-ir.json\"),\n JSON.stringify(compilation.ir, null, 2) + \"\\n\",\n );\n await mkdir(outdir, { recursive: true });\n for (const name of OUTPUTS)\n await rename(join(staging, name), join(outdir, name));\n // Only the bundle is ours: other files under .well-known stay.\n const bundle = join(outdir, WORKFLOW_BUNDLE.dir);\n await rm(bundle, { recursive: true, force: true });\n if (workflows) {\n await mkdir(dirname(bundle), { recursive: true });\n await rename(join(staging, WORKFLOW_BUNDLE.dir), bundle);\n }\n if (dashboard) {\n await rm(dashboard, { recursive: true, force: true });\n await rename(join(staging, \"dashboard\"), dashboard);\n }\n return {\n outdir,\n entry: join(outdir, \"server.js\"),\n ir: compilation.ir,\n dashboard,\n workflows: workflows ? join(outdir, WORKFLOW_BUNDLE.dir) : undefined,\n };\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,MAAM,QAAmC,CAAC,WAAW,UAAU;AAE/D,SAAS,KAAK,MAAc;CAC1B,MAAM,QAAQ,MAAM,QAClB,gBAAgB,KAAK,IAAI,CAAC,GAAG,EAC/B;CACA,OAAO,UAAU,KAAK,MAAM,SAAS;AACvC;;AAGA,SAAgB,oBAAoB,UAA4B;CAC9D,IAAI,CAAC,WAAW,QAAQ,GAAG,OAAO,CAAC;CASnC,OAHc,CAAC,GAAG,IAHD,IAAI,KACnB,SAAS,iBAAiB,KAAK,GAAG,EAAE,KAAK,sBAAsB,KAAK,GAAG,EAAE,EAEtD,CAAC,CAAC,SAAS;EAAE,KAAK;EAAU,WAAW;CAAK,CAAC,CAAC,CAAC,CACjE,KAAK,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CACxC,QAAQ,SAAS,CAAC,KAAK,MAAM,GAAG,CAAC,CAAC,SAAS,cAAc,CACjD,CAAC,CAAC,MACV,GAAG,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,EAC3D;AACF;;AAGA,SAAgB,eAAe,UAAkB,WAA2B;CAS1E,OAAO;;;EARS,oBAAoB,QAAQ,CAAC,CAAC,KAAK,SAAS;EAC1D,IAAI,YAAY,SAAS,WAAW,KAAK,UAA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;EAC7D;CACF,UAAU;EACR,MAAM,GAAG,SAAS;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CACpD;AACF"}
|
|
1
|
+
{"version":3,"file":"build.js","names":[],"sources":["../src/manifest.ts","../src/runner.ts","../src/compiler/aot.ts","../src/build.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join, relative, sep } from \"node:path\";\nimport { writeFileIfChanged } from \"./client-contract-file\";\n\nimport {\n DEFINITION_EXTENSIONS,\n DEFINITION_FILE,\n DEFINITION_KINDS,\n MANIFEST_FILE,\n type DefinitionKind,\n} from \"./definitions\";\n\n/** Services register before the resources that join them; every other kind after. */\nconst FIRST: readonly DefinitionKind[] = [\"service\", \"resource\"];\n\nfunction rank(file: string) {\n const index = FIRST.indexOf(\n DEFINITION_FILE.exec(file)?.[2] as DefinitionKind,\n );\n return index === -1 ? FIRST.length : index;\n}\n\n/** Definition files under `services`: service files first, then resources, then the rest, each by path. */\nexport function scanDefinitionFiles(services: string): string[] {\n if (!existsSync(services)) return [];\n // Built per call: index.ts imports this module (through runner) and still\n // exports defineConfig, so Node may load it (ESLint reading brick.config.ts).\n const glob = new Bun.Glob(\n `**/*.{${DEFINITION_KINDS.join(\",\")}}.{${DEFINITION_EXTENSIONS.join(\",\")}}`,\n );\n const files = [...glob.scanSync({ cwd: services, onlyFiles: true })]\n .map((file) => file.split(sep).join(\"/\"))\n .filter((file) => !file.split(\"/\").includes(\"node_modules\"));\n return files.sort(\n (a, b) => rank(a) - rank(b) || (a < b ? -1 : a > b ? 1 : 0),\n );\n}\n\n/** The source of `services.gen.ts`, which imports every definition file so each registers itself. */\nexport function renderManifest(services: string, generated: string): string {\n const imports = scanDefinitionFiles(services).map((file) => {\n let specifier = relative(generated, join(services, file))\n .split(sep)\n .join(\"/\")\n .replace(DEFINITION_FILE, \"$1.$2\");\n if (!specifier.startsWith(\".\")) specifier = `./${specifier}`;\n return `import ${JSON.stringify(specifier)};\\n`;\n });\n return `// Generated by Brick. Do not edit.\n// Imports every definition file under the services folder, so each one\n// registers itself on its service. The app entry imports this file.\n${imports.join(\"\")}\nexport {};\n`;\n}\n\n/** Write `<generated>/services.gen.ts`, leaving it untouched when nothing changed. */\nexport async function writeServiceManifest(options: {\n services: string;\n generated: string;\n}): Promise<string> {\n const output = join(options.generated, MANIFEST_FILE);\n await writeFileIfChanged(\n output,\n renderManifest(options.services, options.generated),\n );\n return output;\n}\n","import { existsSync, watch } from \"node:fs\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\nimport {\n brick,\n dashboardKey,\n DASHBOARD_KEY_ENV,\n isBrickApp,\n} from \"@brickkit/core\";\nimport { importEntry } from \"./app-entry\";\nimport { TEMPORARY_FILE_PREFIX } from \"./client-contract-file\";\nimport {\n ConfigError,\n CONTRACT_FILE,\n DEFAULT_DASHBOARD_PORT,\n PROJECT_DEFAULTS,\n resolvePort,\n} from \"./config\";\nimport { openDashboard } from \"./dashboard-host\";\nimport { ownModule } from \"./own-module\";\nimport type { DashboardExtensionOptions } from \"./dashboard-extension\";\nimport { startDevApplication } from \"./dev-application\";\nimport type { WorkerMessage, WorkerOptions } from \"./dev-protocol\";\nimport { writeServiceManifest } from \"./manifest\";\nimport { printBanner, serveApp, shutdownOnSignal } from \"./serve\";\nimport { buildAppWorkflows } from \"./workflows\";\n\nexport interface DevServerOptions {\n port?: number;\n entry?: string;\n /**\n * @deprecated Only used without an `entry`; an exported app sets its own\n * prefix in `brick({ prefix })`.\n */\n prefix?: string;\n /** Generate a browser contract before starting the backend and frontend. */\n clientOutput?: string;\n /** Frontend command, launched once after the first successful generation. */\n frontend?: string;\n /**\n * Local dashboard with live requests, traces, errors, and reloads. Needs an\n * entry. `port` is where it listens and `historyDays` how long finished\n * requests are kept on disk; zero keeps live data only. `extension` and\n * `theme` customise it (see `DashboardExtensionOptions`).\n */\n dashboard?:\n | ({ port?: number; historyDays?: number } & DashboardExtensionOptions)\n | false;\n /**\n * Keep `<generated>/services.gen.ts` importing every definition file under\n * `services`: written before the app starts and again when files change.\n */\n manifest?: { services: string; generated: string };\n}\n\n/**\n * What `brick start` runs: serve the entry's default-exported app as it built\n * it (else one with the registered services), with the monitoring dashboard\n * it asks for, until SIGINT or SIGTERM.\n */\nexport async function startProdServer(options: {\n entry?: string;\n port?: number;\n /** The production dashboard's extension and theme. */\n dashboard?: DashboardExtensionOptions;\n}) {\n let exported: unknown;\n if (options.entry) {\n console.log(\n `[Brick-TS] Loading application entry: ${resolve(options.entry)}`,\n );\n exported = await importEntry(options.entry, { run: true });\n }\n const port = resolvePort(options.port);\n const app = isBrickApp(exported) ? exported : brick();\n await buildAppWorkflows(app);\n const dashboard = await serveApp(app, {\n port,\n dashboard: options.dashboard,\n });\n shutdownOnSignal(app);\n printBanner(app, { label: \"Production\", port, dashboard });\n return app;\n}\n\n/**\n * What `brick worker` runs: load the app, deliver its events and run its\n * schedules from this process, without serving HTTP. Run it beside API processes that only record\n * events (`events: { dispatch: false }`), or alone for an app with no routes.\n * Workflow listeners run here too: the world starts and the steps of every run\n * in it execute in this process.\n *\n * @param options - `entry`: the app file, which must default-export a `brick()` app.\n * @returns The app.\n * @throws When the entry is missing, has no `events`, or only records events.\n */\nexport async function startWorker(options: { entry: string }) {\n console.log(\n `[Brick-TS] Loading application entry: ${resolve(options.entry)}`,\n );\n const app = await importEntry(options.entry, { run: true });\n if (!isBrickApp(app))\n throw new ConfigError(\n \"Brick: a worker needs an entry that default-exports a BrickApp.\",\n );\n if (!app.events)\n throw new ConfigError(\n \"Brick: this app has no events, so a worker has nothing to deliver.\",\n );\n if (!app.events.describe().dispatch)\n throw new ConfigError(\n \"Brick: this app only records events (events.dispatch is false), so a worker would deliver nothing. Enable dispatch for the worker process.\",\n );\n await buildAppWorkflows(app);\n await app.start();\n app.events.start();\n shutdownOnSignal(app);\n const { listeners, schedules = [] } = app.events.describe();\n console.log(`\\n🧱 Brick-TS Worker`);\n console.log(\n ` Delivering events to ${listeners.length} ${listeners.length === 1 ? \"listener\" : \"listeners\"}: ${listeners.map((l) => l.name).join(\", \") || \"none\"}`,\n );\n if (schedules.length)\n console.log(\n ` Running ${schedules.length} ${schedules.length === 1 ? \"schedule\" : \"schedules\"}: ${schedules.map((s) => s.name).join(\", \")}`,\n );\n console.log(\"\");\n return app;\n}\n\n/**\n * What `brick dev` runs: start the application, restart it when its files\n * change, and serve the dashboard beside it. With an `entry`, the app runs in\n * a worker process that restarts on every change to the entry or the files it\n * imports, and reports its requests to the dashboard; without one, a server\n * with the registered services starts in this process.\n *\n * @param options - `entry`, `port` (else `PORT`, else 4000), `prefix`,\n * `clientOutput` to regenerate the typed client's contract on each start,\n * `frontend` to launch a frontend command once, and `dashboard` (`port` and\n * `historyDays`, or `false`).\n * @returns The application, when started in this process.\n * @throws When `frontend` is given without `clientOutput`, or the dashboard\n * would use the app's port.\n */\nexport async function startDevServer(options: DevServerOptions = {}) {\n const entry = options.entry;\n if (!entry && (options.clientOutput || options.frontend))\n throw new ConfigError(\n \"Brick: --client and --frontend require an app entry.\",\n );\n if (options.frontend && !options.clientOutput)\n throw new ConfigError(\"Brick: --frontend requires --client <file>.\");\n const port = resolvePort(options.port);\n if (!entry) return startDevApplication({ port, prefix: options.prefix });\n const resolvedEntry = resolve(entry);\n if (!existsSync(resolvedEntry))\n throw new ConfigError(\n `[Brick-TS] Error: Entry file not found: ${resolvedEntry}`,\n );\n\n if (\n options.dashboard &&\n (options.dashboard.port ?? DEFAULT_DASHBOARD_PORT) === port\n )\n throw new ConfigError(\n \"Brick: dashboard port must differ from the API port. Use --dashboard-port <number>.\",\n );\n const manifest = options.manifest;\n if (manifest) await writeServiceManifest(manifest);\n const contract = resolve(\n options.clientOutput ??\n join(manifest?.generated ?? PROJECT_DEFAULTS.generated, CONTRACT_FILE),\n );\n const workerOptions: WorkerOptions = {\n entry: resolvedEntry,\n port,\n prefix: options.prefix,\n clientOutput: options.clientOutput && contract,\n telemetry: Boolean(options.dashboard),\n };\n // Bind the dashboard before the first worker starts, so the worker's spans\n // have somewhere to go.\n const dashboard = options.dashboard\n ? await openDashboard({\n port: options.dashboard.port,\n directory: process.cwd(),\n historyDays: options.dashboard.historyDays,\n warn: (message) => console.warn(message),\n docs: true,\n dashboard: {\n extension: options.dashboard.extension,\n theme: options.dashboard.theme,\n },\n restart: () => {\n void restart(\"dashboard\");\n },\n portHint: \"Use --dashboard-port <number> or --no-dashboard.\",\n })\n : undefined;\n const telemetry = dashboard?.store;\n let frontend: ReturnType<typeof Bun.spawn> | undefined;\n const dependencyFiles = new Set<string>();\n const dependencyWatchers = new Map<string, ReturnType<typeof watch>>();\n let stopped = false;\n const intentionalExits = new WeakSet<ReturnType<typeof Bun.spawn>>();\n const receive = (message: WorkerMessage, generation: number) => {\n switch (message.type) {\n case \"brick:telemetry\":\n telemetry?.ingest(message.records, generation);\n return;\n case \"brick:error\":\n telemetry?.recordWorkerError(message.phase, message.error, generation);\n return;\n case \"brick:contract-ready\":\n if (options.frontend && !frontend && !stopped)\n frontend = Bun.spawn(\n [process.env.SHELL ?? \"/bin/sh\", \"-c\", options.frontend],\n {\n detached: true,\n cwd: process.cwd(),\n stdout: \"inherit\",\n stderr: \"inherit\",\n },\n );\n telemetry?.recordReload({\n kind: \"contract-ready\",\n generation,\n detail: \"browser contract generated\",\n });\n return;\n case \"brick:architecture\":\n telemetry?.setArchitecture(message.architecture, generation);\n void dashboard?.setPluginExtensions(message.architecture.plugins ?? []);\n return;\n case \"brick:inspector\":\n if (generation === telemetry?.latestGeneration)\n telemetry.setInspector({\n port: message.port,\n token: message.token,\n workflows: message.workflows,\n });\n return;\n case \"brick:documentation\":\n void dashboard?.docs?.configure(\n dirname(resolvedEntry),\n message.documentation,\n );\n return;\n case \"brick:api-documents\":\n telemetry?.setApiDocuments(\n message.documents,\n `http://localhost:${port}`,\n );\n return;\n case \"brick:dependencies\":\n for (const file of message.files) {\n if (file === contract) continue;\n dependencyFiles.add(file);\n const directory = dirname(file);\n if (!dependencyWatchers.has(directory))\n dependencyWatchers.set(\n directory,\n watch(directory, (_event, filename) => {\n if (\n !filename ||\n !dependencyFiles.has(resolve(directory, filename))\n )\n return;\n scheduleRestart();\n }),\n );\n }\n return;\n }\n };\n const launch = () => {\n // The new process serves its own inspector once it is up.\n telemetry?.setInspector(undefined);\n const generation = telemetry?.startGeneration() ?? 0;\n const application = Bun.spawn(\n [\n process.execPath,\n ownModule(\"dev-worker\"),\n JSON.stringify(workerOptions),\n ],\n {\n cwd: process.cwd(),\n env: dashboard\n ? { ...process.env, [DASHBOARD_KEY_ENV]: dashboardKey() }\n : process.env,\n stdout: \"inherit\",\n stderr: \"inherit\",\n ipc: (message: WorkerMessage) => receive(message, generation),\n },\n );\n void application.exited.then((code) => {\n if (generation === telemetry?.latestGeneration)\n telemetry.setInspector(undefined);\n if (!stopped && !intentionalExits.has(application)) {\n console.error(\n `[Brick-TS] Application process exited with code ${code}. Waiting for changes to restart.`,\n );\n telemetry?.recordReload({\n kind: \"exited\",\n generation,\n detail: `exit code ${code}`,\n });\n }\n telemetry?.interruptGeneration(generation);\n });\n return application;\n };\n if (dashboard) {\n console.log(`📊 Dev dashboard: http://127.0.0.1:${dashboard.port}`);\n }\n let child = launch();\n // The worker reports the other files the entry imports (brick:dependencies).\n const watchDirs = [\n ...new Set([\n dirname(resolvedEntry),\n ...(manifest ? [manifest.services] : []),\n ]),\n ].filter(existsSync);\n let pending: ReturnType<typeof setTimeout> | undefined;\n let restarting = false;\n let dirty = false;\n\n async function restart(trigger: \"changes\" | \"dashboard\" = \"changes\") {\n dirty = true;\n if (restarting || stopped) return;\n restarting = true;\n try {\n while (dirty && !stopped) {\n dirty = false;\n console.log(\n trigger === \"changes\"\n ? \"\\n📝 Changes detected. Restarting server...\"\n : \"\\n🔄 Restart requested from the dashboard. Restarting server...\",\n );\n telemetry?.recordReload({\n kind: \"restarting\",\n generation: telemetry.latestGeneration,\n detail:\n trigger === \"changes\" ? \"source changed\" : \"restart from dashboard\",\n });\n intentionalExits.add(child);\n child.kill();\n await child.exited;\n if (!stopped) child = launch();\n }\n } finally {\n restarting = false;\n }\n }\n\n function scheduleRestart() {\n clearTimeout(pending);\n pending = setTimeout(() => {\n void restart();\n }, 100);\n }\n const extension = options.dashboard && options.dashboard.extension;\n const extensionDir =\n extension && !watchDirs.includes(dirname(resolve(extension)))\n ? `${dirname(resolve(extension))}${sep}`\n : undefined;\n const watchers = watchDirs.map((dir) =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename || filename.split(/[\\\\/]/).includes(\"node_modules\")) return;\n const file = resolve(dir, filename);\n if (\n file === contract ||\n basename(file).startsWith(TEMPORARY_FILE_PREFIX) ||\n // The dashboard rebuilds its extension itself; the app restarts only\n // for the files it imports.\n (extensionDir !== undefined &&\n file.startsWith(extensionDir) &&\n !dependencyFiles.has(file))\n )\n return;\n // A definition file was added or removed: refresh the import list first.\n if (manifest && file.startsWith(manifest.services + sep)) {\n void writeServiceManifest(manifest)\n .catch((error: unknown) =>\n console.error(\"[Brick-TS] Could not write services.gen.ts:\", error),\n )\n .finally(scheduleRestart);\n return;\n }\n scheduleRestart();\n }),\n );\n const stop = () => {\n if (stopped) return;\n stopped = true;\n clearTimeout(pending);\n for (const watcher of watchers) watcher.close();\n for (const watcher of dependencyWatchers.values()) watcher.close();\n if (frontend) {\n if (process.platform === \"win32\") {\n Bun.spawnSync([\"taskkill\", \"/pid\", String(frontend.pid), \"/t\", \"/f\"]);\n } else {\n try {\n process.kill(-frontend.pid, \"SIGTERM\");\n } catch (error) {\n if (\n !(\n error instanceof Error &&\n \"code\" in error &&\n error.code === \"ESRCH\"\n )\n )\n throw error;\n }\n }\n }\n dashboard?.stop();\n child.kill();\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n process.off(\"exit\", stop);\n };\n const onSignal = (signal: NodeJS.Signals) => {\n if (stopped) {\n child.kill(\"SIGKILL\");\n process.exit(signal === \"SIGINT\" ? 130 : 143);\n }\n stop();\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n void child.exited.then(() => process.exit(0));\n };\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n process.on(\"exit\", stop);\n console.log(`\\n👀 Watching for changes in: ${watchDirs.join(\", \")}`);\n return { stop };\n}\n","import { aot } from \"elysia/plugin/aot/bun\";\nimport type { BunPlugin } from \"bun\";\n\n/** Keep the pinned Elysia beta's incomplete stripping from breaking builds. */\nexport function brickAot(entry: string, keep: boolean): BunPlugin {\n // `keep`: WS routes still need cookie setup during reconstruction in beta.29,\n // and shipped workflows mount their webhook route only when a world is set at\n // run time. Retain those modules while continuing to precompile HTTP handlers.\n if (keep) return aot(entry, { target: \"bun\", strip: false });\n return {\n name: \"brick-elysia-aot\",\n async setup(build) {\n await aot(entry, { target: \"bun\", strip: true }).setup({\n ...build,\n onLoad(options, callback) {\n return build.onLoad(options, async (args) => {\n const result = await callback(args);\n if (\n !result ||\n !(\"contents\" in result) ||\n typeof result.contents !== \"string\"\n )\n return result;\n let contents = result.contents;\n if (\n /[/\\\\]elysia[/\\\\]dist[/\\\\]ws[/\\\\]route\\.m?js$/.test(args.path) &&\n contents.includes(\n \"[elysia-aot] WebSocket route builder was stripped\",\n )\n ) {\n for (const name of [\"resolveWSOptions\", \"accumulateWSOptions\"]) {\n if (!contents.includes(`export function ${name}`))\n contents += `\\nexport function ${name}() { throw new Error(\"WebSocket support was stripped\"); }\\n`;\n }\n }\n return contents === result.contents\n ? result\n : { ...result, contents };\n });\n },\n });\n },\n };\n}\n","import { mkdtemp, mkdir, rename, rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { compileBrickApplication, WORKFLOW_BUNDLE } from \"@brickkit/core\";\nimport type { BunPlugin } from \"bun\";\nimport { emitCompiledApplication } from \"./compiler\";\nimport { brickAot } from \"./compiler/aot\";\nimport { loadBrickApp } from \"./app-entry\";\nimport { ownModule } from \"./own-module\";\nimport { DEFAULT_OUTDIR, resolvePort } from \"./config\";\nimport { shipWorkflows, workflowTransformPlugin } from \"./workflows\";\nimport {\n themeCss,\n writeDashboardExtension,\n type DashboardExtensionOptions,\n} from \"./dashboard-extension\";\n\nexport interface BuildApplicationOptions {\n /** A module whose default export is a BrickApp, without starting a server. */\n entry: string;\n outdir?: string;\n port?: number;\n /** Precompile Elysia's HTTP handlers at build time (default true). */\n aot?: boolean;\n /**\n * The dashboard's extension, built into `<outdir>/dashboard` with those of\n * the app's plugins for the production dashboard to serve; its theme is\n * checked here too.\n */\n dashboard?: DashboardExtensionOptions;\n}\n\n/**\n * The production dashboard stays out of the bundle: it serves files that ship\n * with @brickkit/cli, so a built server whose app asks for it imports it from\n * there at run time. Without a dashboard the bundle needs nothing installed.\n */\nconst productionDashboardAtRunTime: BunPlugin = {\n name: \"brick:production-dashboard\",\n setup(build) {\n build.onResolve({ filter: /^\\.\\/production-dashboard(\\.[jt]s)?$/ }, () => ({\n path: \"@brickkit/cli/production-dashboard\",\n external: true,\n }));\n },\n};\n\n/** The files `brick build` writes to the output folder, `server.js` last. */\nconst OUTPUTS = [\"routes.js\", \"brick-ir.json\", \"server.js.map\", \"server.js\"];\n\n/** Bundle an exported BrickApp with its compiled IR and its original configuration. */\nexport async function buildApplication(options: BuildApplicationOptions) {\n const entry = resolve(options.entry);\n if (!(await Bun.file(entry).exists()))\n throw new Error(`Brick compiler: entry not found: ${entry}`);\n const outdir = resolve(options.outdir ?? DEFAULT_OUTDIR);\n if (OUTPUTS.some((name) => entry === join(outdir, name)))\n throw new Error(\n \"Brick compiler: output would overwrite the application entry\",\n );\n const port = resolvePort(options.port, undefined, \"\");\n themeCss(options.dashboard?.theme);\n const extension = options.dashboard?.extension\n ? resolve(options.dashboard.extension)\n : undefined;\n if (extension && !(await Bun.file(extension).exists()))\n throw new Error(\n `Brick compiler: dashboard extension not found: ${extension}`,\n );\n const app = await loadBrickApp(entry);\n const root = app.events?.workflows?.root ?? process.cwd();\n const services = [...app.definition.services];\n const compilation = compileBrickApplication({\n services,\n prefix: app.definition.prefix,\n });\n await mkdir(dirname(outdir), { recursive: true });\n const staging = await mkdtemp(join(dirname(outdir), \".brick-build-\"));\n try {\n await Bun.write(\n join(staging, \"routes.js\"),\n emitCompiledApplication(compilation.ir),\n );\n const dashboard = (await writeDashboardExtension(\n extension,\n app.definition.plugins ?? [],\n join(staging, \"dashboard\"),\n ))\n ? join(outdir, \"dashboard\")\n : undefined;\n const theme = JSON.stringify(options.dashboard?.theme);\n const source = `import { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { loadCompiledBrickApp } from \"@brickkit/core\";\nimport { resolvePort } from ${JSON.stringify(ownModule(\"config\"))};\nimport { serveApp, shutdownOnSignal } from ${JSON.stringify(ownModule(\"serve\"))};\nconst workflows = fileURLToPath(new URL(${JSON.stringify(`./${WORKFLOW_BUNDLE.dir}`)}, import.meta.url));\nexport const app = await loadCompiledBrickApp(() => import(${JSON.stringify(entry)}), undefined, {\n workflows: existsSync(workflows) ? workflows : undefined,\n});\nexport default app;\nif (import.meta.main) {\n await serveApp(app, {\n port: resolvePort(undefined, ${port}),\n dashboard: { extension: ${dashboard ? 'fileURLToPath(new URL(\"./dashboard\", import.meta.url))' : \"undefined\"}, theme: ${theme} },\n });\n console.log(\"Brick compiled server listening on http://localhost:\" + app.server.port);\n shutdownOnSignal(app);\n}\n`;\n await Bun.write(join(staging, \"entry.ts\"), source);\n // Whether to ship workflows depends on the files the bundle holds, not on\n // the env: an app may declare its workflow listeners only at run time.\n let directives = false;\n const transform = await workflowTransformPlugin(root, () => {\n directives = true;\n });\n const result = await Bun.build({\n entrypoints: [join(staging, \"entry.ts\")],\n target: \"bun\",\n format: \"esm\",\n outdir: staging,\n naming: \"server.js\",\n sourcemap: \"external\",\n // AOT first: the workflow plugin loads every project file it sees, so after\n // it the AOT plugin would never get to transform the entry.\n plugins: [\n ...(options.aot === false\n ? []\n : [\n brickAot(\n join(staging, \"entry.ts\"),\n app.definition.sockets.length > 0 || transform !== undefined,\n ),\n ]),\n ...(transform ? [transform] : []),\n productionDashboardAtRunTime,\n ],\n });\n if (!result.success)\n throw new AggregateError(result.logs, \"Brick compiler: bundling failed\");\n const workflows =\n (directives || Boolean(app.events?.workflows)) &&\n (await shipWorkflows(root, staging, Boolean(app.events?.workflows)));\n await Bun.write(\n join(staging, \"brick-ir.json\"),\n JSON.stringify(compilation.ir, null, 2) + \"\\n\",\n );\n await mkdir(outdir, { recursive: true });\n for (const name of OUTPUTS)\n await rename(join(staging, name), join(outdir, name));\n // Only the bundle is ours: other files under .well-known stay.\n const bundle = join(outdir, WORKFLOW_BUNDLE.dir);\n await rm(bundle, { recursive: true, force: true });\n if (workflows) {\n await mkdir(dirname(bundle), { recursive: true });\n await rename(join(staging, WORKFLOW_BUNDLE.dir), bundle);\n }\n if (dashboard) {\n await rm(dashboard, { recursive: true, force: true });\n await rename(join(staging, \"dashboard\"), dashboard);\n }\n return {\n outdir,\n entry: join(outdir, \"server.js\"),\n ir: compilation.ir,\n dashboard,\n workflows: workflows ? join(outdir, WORKFLOW_BUNDLE.dir) : undefined,\n };\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,MAAM,QAAmC,CAAC,WAAW,UAAU;AAE/D,SAAS,KAAK,MAAc;CAC1B,MAAM,QAAQ,MAAM,QAClB,gBAAgB,KAAK,IAAI,CAAC,GAAG,EAC/B;CACA,OAAO,UAAU,KAAK,MAAM,SAAS;AACvC;;AAGA,SAAgB,oBAAoB,UAA4B;CAC9D,IAAI,CAAC,WAAW,QAAQ,GAAG,OAAO,CAAC;CASnC,OAHc,CAAC,GAAG,IAHD,IAAI,KACnB,SAAS,iBAAiB,KAAK,GAAG,EAAE,KAAK,sBAAsB,KAAK,GAAG,EAAE,EAEtD,CAAC,CAAC,SAAS;EAAE,KAAK;EAAU,WAAW;CAAK,CAAC,CAAC,CAAC,CACjE,KAAK,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,CACxC,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MAAM,OAAO,KAAK,SAAS,gBAAgB,GAAG,GAAG,MAAM;EACzD;EACA,IAAI,WAAW;GACb,MAAM,GAAG,WAAW;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;GACpD,MAAM,OAAO,KAAK,SAAS,WAAW,GAAG,SAAS;EACpD;EACA,OAAO;GACL;GACA,OAAO,KAAK,QAAQ,WAAW;GAC/B,IAAI,YAAY;GAChB;GACA,WAAW,YAAY,KAAK,QAAQ,gBAAgB,GAAG,IAAI,KAAA;EAC7D;CACF,UAAU;EACR,MAAM,GAAG,SAAS;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CACpD;AACF"}
|
|
@@ -2,7 +2,7 @@ import { n as ConfigError } from "./config2.js";
|
|
|
2
2
|
import { r as registerWorkflowTransform } from "./workflows2.js";
|
|
3
3
|
import { existsSync } from "node:fs";
|
|
4
4
|
import { dirname, join, resolve } from "node:path";
|
|
5
|
-
import { actionOwners, getActionRoute, getPluginActionRoute, requireBrickApp, serializeSocketSchema } from "@brickkit/core";
|
|
5
|
+
import { actionOwners, getActionRoute, getPluginActionRoute, isWebhook, requireBrickApp, serializeSocketSchema } from "@brickkit/core";
|
|
6
6
|
import { pathToFileURL } from "node:url";
|
|
7
7
|
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
8
8
|
import { createHash, randomUUID } from "node:crypto";
|
|
@@ -75,6 +75,7 @@ function addServiceActions(service, prefix, contract, types, schemas) {
|
|
|
75
75
|
contract[service.name] = namespace;
|
|
76
76
|
types[service.name] = namespaceTypes;
|
|
77
77
|
for (const action of service.listActions()) {
|
|
78
|
+
if (isWebhook(action)) continue;
|
|
78
79
|
const route = getActionRoute(action, prefix);
|
|
79
80
|
if (route === false) continue;
|
|
80
81
|
const pluginRoute = getPluginActionRoute(action, prefix) || void 0;
|