@brickkit/cli 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +1 -1
  2. package/dashboard-dist/CollapsiblePanel-CbUysOp5.js +2 -0
  3. package/dashboard-dist/CompositeRoot-D4sRkYq3.js +1 -0
  4. package/dashboard-dist/Geist-Variable.woff2 +0 -0
  5. package/dashboard-dist/GeistMono-Variable.woff2 +0 -0
  6. package/dashboard-dist/PopoverPopup-CiI2avT_.js +1 -0
  7. package/dashboard-dist/api-reference-B-bZRtNV.js +265 -0
  8. package/dashboard-dist/app.css +2 -2
  9. package/dashboard-dist/app.js +13 -13
  10. package/dashboard-dist/ccount-CcG1m-Yh.js +1 -0
  11. package/dashboard-dist/client-BJJtVSVr.js +1 -0
  12. package/dashboard-dist/core-Z7NJFk0K.js +1 -0
  13. package/dashboard-dist/docs-Dpfc0wJb.js +4 -0
  14. package/dashboard-dist/docs.css +1 -1
  15. package/dashboard-dist/kit.js +1 -0
  16. package/dashboard-dist/popover-BzejBolB.js +1 -0
  17. package/dashboard-dist/react-dom-client.js +3 -0
  18. package/dashboard-dist/react-dom.js +3 -0
  19. package/dashboard-dist/react-jsx-runtime.js +1 -1
  20. package/dashboard-dist/react.js +3 -3
  21. package/dashboard-dist/theme.css +123 -0
  22. package/dist/app-entry2.js +2 -3
  23. package/dist/bin.d.ts +0 -2
  24. package/dist/bin.js +606 -49
  25. package/dist/bin.js.map +1 -1
  26. package/dist/client-contract-file2.js +2 -3
  27. package/dist/client-contract2.js +18 -10
  28. package/dist/client-contract2.js.map +1 -1
  29. package/dist/compiler.d.ts +1 -2
  30. package/dist/compiler.js +1 -1
  31. package/dist/compiler2.js +3 -4
  32. package/dist/config.js +250 -0
  33. package/dist/config.js.map +1 -0
  34. package/dist/dashboard-extension.d.ts +25 -0
  35. package/dist/dashboard.d.ts +2997 -0
  36. package/dist/dev-reporter.d.ts +0 -2
  37. package/dist/dev-reporter.js +1 -2
  38. package/dist/dev-telemetry-store.js +1411 -966
  39. package/dist/dev-telemetry-store.js.map +1 -1
  40. package/dist/dev-telemetry.js +3 -4
  41. package/dist/dev-telemetry.js.map +1 -1
  42. package/dist/dev-worker.js +3 -4
  43. package/dist/emit.d.ts +0 -2
  44. package/dist/index.d.ts +96 -17
  45. package/dist/index.js +4 -5
  46. package/dist/lint/eslint.d.ts +2 -0
  47. package/dist/lint/eslint.js +1 -0
  48. package/dist/lint/oxlint.d.ts +17 -0
  49. package/dist/lint/oxlint.js +18 -0
  50. package/dist/lint/oxlint.js.map +1 -0
  51. package/dist/plugin.d.ts +70 -0
  52. package/dist/plugin.js +64 -0
  53. package/dist/plugin.js.map +1 -0
  54. package/dist/presets.js +1066 -0
  55. package/dist/presets.js.map +1 -0
  56. package/dist/runner.js +114 -32
  57. package/dist/runner.js.map +1 -1
  58. package/dist/vite.d.ts +6 -5
  59. package/dist/vite.js +13 -9
  60. package/dist/vite.js.map +1 -1
  61. package/dist/workflows.d.ts +0 -2
  62. package/dist/workflows2.js +3 -4
  63. package/inspector-dist/client/assets/api.rpc-BvRk9kiK.js +0 -0
  64. package/inspector-dist/client/assets/api.stream._streamId-BvRk9kiK.js +0 -0
  65. package/inspector-dist/client/assets/app-CCzpuUz_.css +2 -0
  66. package/inspector-dist/client/assets/dist-BK8w6xOr.js +3930 -0
  67. package/inspector-dist/client/assets/dist-CG2aVufI.js +197 -0
  68. package/inspector-dist/client/assets/entry.client-D9jbgmTR.js +9391 -0
  69. package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-DYVdwGy2.js +34 -0
  70. package/inspector-dist/client/assets/home-CyjkvtII.js +2883 -0
  71. package/inspector-dist/client/assets/jsx-runtime-CPEah4WQ.js +7084 -0
  72. package/inspector-dist/client/assets/manifest-ba30b52d.js +1 -0
  73. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-Dy6IVqPy.js +1 -0
  74. package/inspector-dist/client/assets/root-8BMab1lL.css +2 -0
  75. package/inspector-dist/client/assets/root-DX9wtogx.js +332 -0
  76. package/inspector-dist/client/assets/run-detail-C69EJGql.js +1549 -0
  77. package/inspector-dist/client/assets/tabs-B6B88IjT.js +75692 -0
  78. package/inspector-dist/client/assets/tabs-L5XKzOpP.css +1 -0
  79. package/inspector-dist/client/assets/world-config-context-C3BqXPIv.js +30 -0
  80. package/inspector-dist/client/assets/zstd-browser-decoder-ByUgcY9H.js +41 -0
  81. package/inspector-dist/server/assets/app-WoDoT62X.js +100155 -0
  82. package/inspector-dist/server/assets/chunk-RLXIAIE6-CbvDIAEa.js +42977 -0
  83. package/inspector-dist/server/assets/dist-BRxZSWUN.js +1140 -0
  84. package/inspector-dist/server/assets/dist-CQnQcIJg.js +199 -0
  85. package/inspector-dist/server/assets/dist-DqRd9pyS.js +1644 -0
  86. package/inspector-dist/server/assets/dist-qR-969AD.js +10327 -0
  87. package/inspector-dist/server/assets/encryption-_PuklZNX.js +888 -0
  88. package/inspector-dist/server/assets/event-metadata-BVakQJ_y.js +147 -0
  89. package/inspector-dist/server/assets/functions-CImcpqNl.js +1172 -0
  90. package/inspector-dist/server/assets/global-singleton-CPirHxFh.js +82 -0
  91. package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-fPMB_t7F.js +36 -0
  92. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-bADXySE3.js +3 -0
  93. package/inspector-dist/server/assets/parse-D9Vvgzt9.js +471 -0
  94. package/inspector-dist/server/assets/rolldown-runtime-CLg409Sh.js +44 -0
  95. package/inspector-dist/server/assets/serialization-format-DDtsVTU1.js +478 -0
  96. package/inspector-dist/server/assets/token-BW4GdQZh.js +62 -0
  97. package/inspector-dist/server/assets/token-D6FXdkJT.js +57 -0
  98. package/inspector-dist/server/assets/token-util-BoNmi-wE.js +457 -0
  99. package/inspector-dist/server/assets/wrapper-wiqsGXcE.js +3626 -0
  100. package/inspector-dist/server/assets/ws-transport-DV7oG4mL.js +29478 -0
  101. package/inspector-dist/server/assets/zstd-browser-decoder-Cswf0KO6.js +40 -0
  102. package/inspector-dist/server/index.js +2 -57
  103. package/package.json +57 -32
  104. package/vite-client.d.ts +1 -1
  105. package/dashboard-dist/CollapsiblePanel-a54TwMKb.js +0 -2
  106. package/dashboard-dist/PopoverPopup-BLzjTqsi.js +0 -1
  107. package/dashboard-dist/api-reference-r893F8zi.js +0 -260
  108. package/dashboard-dist/core-BWAwhSFf.js +0 -1
  109. package/dashboard-dist/docs-CkMy3Y5i.js +0 -4
  110. package/dashboard-dist/preload-helper-CjQDFR0M.js +0 -1
  111. package/dist/bin.d.ts.map +0 -1
  112. package/dist/build.js +0 -119
  113. package/dist/build.js.map +0 -1
  114. package/dist/dev-reporter.d.ts.map +0 -1
  115. package/dist/emit.d.ts.map +0 -1
  116. package/dist/index.d.ts.map +0 -1
  117. package/dist/vite.d.ts.map +0 -1
  118. package/dist/workflows.d.ts.map +0 -1
  119. package/inspector-dist/client/assets/api.rpc-l0sNRNKZ.js +0 -1
  120. package/inspector-dist/client/assets/api.stream._streamId-l0sNRNKZ.js +0 -1
  121. package/inspector-dist/client/assets/app-CY7CQBRo.css +0 -1
  122. package/inspector-dist/client/assets/entry.client-BJ6G3n5t.js +0 -11697
  123. package/inspector-dist/client/assets/highlighted-body-B3W2YXNL-C-3wZnxf.js +0 -19
  124. package/inspector-dist/client/assets/home-CSKAS4P2.js +0 -4979
  125. package/inspector-dist/client/assets/index-DECCyMR0.js +0 -4482
  126. package/inspector-dist/client/assets/index-Dot7CgrA.js +0 -9837
  127. package/inspector-dist/client/assets/index-HqNj_XIX.js +0 -200
  128. package/inspector-dist/client/assets/manifest-4baa7c6f.js +0 -1
  129. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-DC0K8uTy.js +0 -58626
  130. package/inspector-dist/client/assets/mermaid-3ZIDBTTL-F88p7PFX.css +0 -1
  131. package/inspector-dist/client/assets/root-Bmn5n3jF.js +0 -305
  132. package/inspector-dist/client/assets/root-CfCr265_.css +0 -1
  133. package/inspector-dist/client/assets/run-detail-CWoGxu_0.css +0 -1
  134. package/inspector-dist/client/assets/run-detail-Cc7tSGNq.js +0 -6237
  135. package/inspector-dist/client/assets/world-config-context-BAD1QCrR.js +0 -26
  136. package/inspector-dist/client/assets/zstd-browser-decoder-BQoRpP7L.js +0 -28
  137. package/inspector-dist/server/assets/app-C-ZVJtic.js +0 -174880
  138. package/inspector-dist/server/assets/highlighted-body-B3W2YXNL-C8sq8F_D.js +0 -71
  139. package/inspector-dist/server/assets/index-BfLBLRRi.js +0 -204
  140. package/inspector-dist/server/assets/index-BzrGWk7J.js +0 -1164
  141. package/inspector-dist/server/assets/index-CWJr34WJ.js +0 -1296
  142. package/inspector-dist/server/assets/index-CYlmUaKx.js +0 -191
  143. package/inspector-dist/server/assets/mermaid-3ZIDBTTL-Dv5rjfMN.js +0 -58
  144. package/inspector-dist/server/assets/token-DnLp3wBO.js +0 -95
  145. package/inspector-dist/server/assets/token-util-Bpfp-B0w.js +0 -33
  146. package/inspector-dist/server/assets/wrapper-D5LIcZ_u.js +0 -67
  147. package/inspector-dist/server/assets/zstd-browser-decoder-BM8GpVB8.js +0 -77
package/dist/bin.js CHANGED
@@ -1,20 +1,461 @@
1
1
  #!/usr/bin/env bun
2
- import { r as DEFAULT_DASHBOARD_PORT } from "./dev-telemetry-store.js";
3
- import { a as parsePort, i as startWorker, n as startDevServer, r as startProdServer } from "./runner.js";
4
- import { t as buildApplication } from "./build.js";
5
- import { t as loadBrickApp } from "./app-entry2.js";
2
+ import { c as resolveDevPort, i as startWorker, n as startDevServer, o as writeServiceManifest, r as startProdServer, s as parsePort } from "./runner.js";
3
+ import { n as DEFAULT_DASHBOARD_PORT } from "./dev-telemetry-store.js";
4
+ import { i as buildApplication, r as loadConfig, t as ConfigError } from "./config.js";
6
5
  import { t as writeClientContract } from "./client-contract-file2.js";
7
- import { generateOpenApiSpec, getGlobalRegistry } from "@brickkit/core";
6
+ import { t as loadBrickApp } from "./app-entry2.js";
7
+ import { i as resolveRules, r as fileRules } from "./presets.js";
8
+ import { createRequire } from "node:module";
9
+ import { fileURLToPath } from "node:url";
10
+ import { drizzleSchema, generateOpenApiSpec, getGlobalRegistry, getPluginActionRoute, getTableName, kebabCase, migrateDatabase, sql } from "@brickkit/core";
11
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
12
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
13
  import { Command, InvalidArgumentError } from "commander";
9
- //#endregion
10
- //#region src/bin.ts
11
- const CLI_VERSION = "0.10.0";
14
+ import { spawnSync } from "node:child_process";
15
+ import { tmpdir } from "node:os";
16
+ // src/lint/run.ts
17
+ /** The built lint/oxlint entry, which oxlint loads under Node. */
18
+ function pluginPath() {
19
+ const here = fileURLToPath(import.meta.url);
20
+ return here.endsWith(".ts") ? resolve(dirname(here), "../../dist/lint/oxlint.js") : resolve(dirname(here), "lint/oxlint.js");
21
+ }
22
+ function oxlintBin(root) {
23
+ for (const base of [join(root, "package.json"), fileURLToPath(import.meta.url)]) try {
24
+ const pkg = createRequire(base).resolve("oxlint/package.json");
25
+ return join(dirname(pkg), "bin/oxlint");
26
+ } catch {}
27
+ throw new ConfigError("Brick: brick lint needs oxlint; add it: bun add -d oxlint");
28
+ }
29
+ /**
30
+ * Run the file rules over a project with oxlint, as `brick lint` does.
31
+ * Only rules set to "error" or "warn" run; `ignore` globs are relative to `root`.
32
+ */
33
+ function runFileRules(options) {
34
+ const rules = Object.fromEntries(Object.entries(options.rules).filter(([, severity]) => severity !== "off"));
35
+ if (Object.keys(rules).length === 0) return [];
36
+ const directory = mkdtempSync(join(tmpdir(), "brick-lint-"));
37
+ try {
38
+ const config = join(directory, "oxlintrc.json");
39
+ writeFileSync(config, JSON.stringify({
40
+ plugins: [],
41
+ categories: { correctness: "off" },
42
+ jsPlugins: [{
43
+ name: "brick",
44
+ specifier: pluginPath()
45
+ }],
46
+ settings: { brick: options.settings },
47
+ rules
48
+ }));
49
+ const result = spawnSync(oxlintBin(options.root), [
50
+ "-c",
51
+ config,
52
+ "--format",
53
+ "json",
54
+ "--disable-nested-config",
55
+ "--no-error-on-unmatched-pattern",
56
+ ...options.fix ? ["--fix"] : [],
57
+ ...(options.ignore ?? []).flatMap((pattern) => ["--ignore-pattern", pattern]),
58
+ ...options.paths ?? ["."]
59
+ ], {
60
+ cwd: options.root,
61
+ encoding: "utf8",
62
+ maxBuffer: 67108864
63
+ });
64
+ if (result.error) throw result.error;
65
+ let report;
66
+ try {
67
+ report = JSON.parse(result.stdout);
68
+ } catch {
69
+ throw new Error(`Brick: oxlint failed (exit ${result.status}):\n${result.stderr || result.stdout}`);
70
+ }
71
+ return (report.diagnostics ?? []).map((diagnostic) => ({
72
+ file: diagnostic.filename,
73
+ line: diagnostic.labels?.[0]?.span.line ?? 1,
74
+ column: diagnostic.labels?.[0]?.span.column ?? 1,
75
+ rule: diagnostic.code?.replace(/^brick\((.*)\)$/, "brick/$1") ?? "syntax",
76
+ severity: diagnostic.severity === "error" ? "error" : "warn",
77
+ message: diagnostic.message
78
+ }));
79
+ } finally {
80
+ rmSync(directory, {
81
+ recursive: true,
82
+ force: true
83
+ });
84
+ }
85
+ }
86
+ // src/lint.ts
87
+ const posix$1 = (path) => path.split(sep).join("/");
88
+ const SOURCE = new Bun.Glob("**/*.{ts,tsx,mts,cts}");
89
+ /**
90
+ * `brick lint`: the file rules through oxlint, then the app
91
+ * rules against the loaded app. Prints `file:line:col` lines and returns the
92
+ * exit code: 1 when anything is an error.
93
+ */
94
+ async function runLint(options) {
95
+ const { project } = options;
96
+ const root = project?.root ?? process.cwd();
97
+ const config = project?.config.lint ?? {};
98
+ let resolved;
99
+ try {
100
+ resolved = resolveRules(config.presets, config.rules);
101
+ } catch (error) {
102
+ throw new ConfigError(`brick.config.ts: lint.rules: ${error.message}`);
103
+ }
104
+ const fromRoot = (path) => posix$1(relative(root, path)) || ".";
105
+ const services = project?.services ?? resolve(root, "src/services");
106
+ const generated = project?.generated ?? resolve(root, "_brick");
107
+ const entry = options.entry ? resolve(options.entry) : project?.entry ?? resolve(root, "src/app.ts");
108
+ const ignore = [...config.ignore ?? [], `${fromRoot(generated)}/**`];
109
+ const messages = runFileRules({
110
+ root,
111
+ rules: fileRules(resolved),
112
+ settings: {
113
+ root,
114
+ services: fromRoot(services),
115
+ entry: fromRoot(entry),
116
+ generated: fromRoot(generated),
117
+ web: "web"
118
+ },
119
+ ignore
120
+ });
121
+ const globs = ignore.map((pattern) => new Bun.Glob(pattern));
122
+ if (existsSync(entry)) {
123
+ if (project) await writeServiceManifest(project);
124
+ messages.push(...await checkApp({
125
+ root,
126
+ entry,
127
+ services,
128
+ severity: (rule) => rule === "no-cross-service-tables" ? "error" : resolved[`brick/${rule}`] ?? "off",
129
+ ignored: (rel) => rel.split("/").includes("node_modules") || globs.some((glob) => glob.match(rel))
130
+ }));
131
+ } else if (options.entry || project) throw new Error(`Brick: entry not found: ${entry}`);
132
+ return report(messages);
133
+ }
134
+ function report(messages) {
135
+ messages.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
136
+ for (const m of messages) console.log(`${m.file}:${m.line}:${m.column} ${m.severity === "error" ? "error" : "warning"} ${m.message} ${m.rule}`);
137
+ const errors = messages.filter((m) => m.severity === "error").length;
138
+ const warnings = messages.length - errors;
139
+ console.log(messages.length ? `\n✖ ${messages.length} problem${messages.length === 1 ? "" : "s"} (${errors} error${errors === 1 ? "" : "s"}, ${warnings} warning${warnings === 1 ? "" : "s"})` : "✔ No lint problems");
140
+ return errors > 0 ? 1 : 0;
141
+ }
142
+ /** Project source files, from the root, without tests, ignored and generated files. */
143
+ function sourceFiles(check, under = check.root) {
144
+ if (!existsSync(under)) return [];
145
+ return [...SOURCE.scanSync({
146
+ cwd: under,
147
+ onlyFiles: true
148
+ })].map((file) => resolve(under, file)).filter((file) => {
149
+ const rel = posix$1(relative(check.root, file));
150
+ return !check.ignored(rel) && !/\.(test|spec)\.[cm]?tsx?$/.test(rel) && !rel.startsWith("dist/");
151
+ });
152
+ }
153
+ function lineOf(source, index) {
154
+ return source.slice(0, index).split("\n").length;
155
+ }
156
+ /** The app rules: they need the loaded app, so only brick lint runs them. */
157
+ async function checkApp(check) {
158
+ const messages = [];
159
+ const add = (rule, file, message, line = 1) => {
160
+ const severity = check.severity(rule);
161
+ if (severity === "off") return;
162
+ messages.push({
163
+ file: posix$1(relative(check.root, file)),
164
+ line,
165
+ column: 1,
166
+ rule: `brick/${rule}`,
167
+ severity,
168
+ message
169
+ });
170
+ };
171
+ let app;
172
+ try {
173
+ app = await loadBrickApp(check.entry);
174
+ } catch (error) {
175
+ const message = error.message;
176
+ if (/duplicate/i.test(message)) {
177
+ add("unique-names", check.entry, message);
178
+ return messages;
179
+ }
180
+ throw error;
181
+ }
182
+ singleAppEntry(check, sourceFiles(check), add);
183
+ uniqueNames(check, app, add);
184
+ await noCrossServiceTables(check, app, add);
185
+ declaredEvents(check, app, add);
186
+ testColocated(check, add);
187
+ return messages;
188
+ }
189
+ function singleAppEntry(check, files, add) {
190
+ if (check.severity("single-app-entry") === "off") return;
191
+ let calls = 0;
192
+ for (const file of files) {
193
+ const source = readFileSync(file, "utf8");
194
+ if (!/import\s*\{[^}]*\bbrick\b[^}]*\}\s*from\s*["']@brickkit\/core["']/.test(source)) continue;
195
+ for (const match of source.matchAll(/(?<![.\w])brick\s*\(/g)) {
196
+ if (file === check.entry && ++calls === 1) continue;
197
+ add("single-app-entry", file, file === check.entry ? "The entry calls brick() more than once; keep one app." : `brick() is called outside the entry (${posix$1(relative(check.root, check.entry))}); keep one app.`, lineOf(source, match.index));
198
+ }
199
+ }
200
+ }
201
+ function uniqueNames(check, app, add) {
202
+ const services = [...app.definition.services];
203
+ const seen = /* @__PURE__ */ new Set();
204
+ for (const service of services) {
205
+ if (seen.has(service.name)) add("unique-names", check.entry, `Two services are named "${service.name}".`);
206
+ seen.add(service.name);
207
+ const owners = /* @__PURE__ */ new Map();
208
+ const claim = (name, what) => {
209
+ const segment = kebabCase(name);
210
+ const other = owners.get(segment);
211
+ if (other) add("unique-names", check.entry, `In service "${service.name}", ${what} and ${other} share the name "${segment}".`);
212
+ else owners.set(segment, what);
213
+ };
214
+ for (const action of service.listActions()) if (action.config.path === void 0 && !action.resourceAction && getPluginActionRoute(action) === void 0) claim(action.name, `action "${action.name}"`);
215
+ for (const socket of service.listSockets()) if (socket.schema.path === void 0) claim(socket.schema.name, `socket "${socket.schema.name}"`);
216
+ for (const resource of service.listResources()) claim(resource.name, `resource "${resource.name}"`);
217
+ }
218
+ }
219
+ /** Which service owns each table: its resources' and registered tables, or a database it alone uses. */
220
+ function tableOwners(app) {
221
+ const owners = /* @__PURE__ */ new Map();
222
+ const users = /* @__PURE__ */ new Map();
223
+ for (const service of app.definition.services) {
224
+ for (const table of service.tables?.values() ?? []) owners.set(table, service.name);
225
+ const database = service.options.database;
226
+ if (database) users.set(database, [...users.get(database) ?? [], service.name]);
227
+ }
228
+ for (const [database, names] of users) if (names.length === 1) {
229
+ for (const table of Object.values(database.tables ?? {})) if (!owners.has(table)) owners.set(table, names[0]);
230
+ }
231
+ return owners;
232
+ }
233
+ function serviceOfFolder(app, folder) {
234
+ return app.definition.services.find((service) => service.name === folder || kebabCase(service.name) === folder)?.name;
235
+ }
236
+ const IMPORT = /import\s+(type\s+)?([\w$]+\s*,?\s*)?(\*\s+as\s+[\w$]+|\{[^}]*\})?\s*from\s*["']([^"']+)["']/g;
237
+ async function noCrossServiceTables(check, app, add) {
238
+ const owners = tableOwners(app);
239
+ for (const file of sourceFiles(check, check.services)) {
240
+ const folder = posix$1(relative(check.services, file)).split("/")[0];
241
+ const service = serviceOfFolder(app, folder);
242
+ if (!service) continue;
243
+ const source = readFileSync(file, "utf8");
244
+ for (const match of source.matchAll(IMPORT)) {
245
+ const [, typeOnly, defaultName, rest, specifier] = match;
246
+ if (typeOnly || !specifier.startsWith(".")) continue;
247
+ let target;
248
+ try {
249
+ target = Bun.resolveSync(specifier, dirname(file));
250
+ } catch {
251
+ continue;
252
+ }
253
+ const line = lineOf(source, match.index);
254
+ const where = posix$1(relative(check.services, target)).split("/");
255
+ const otherFolder = !where[0].startsWith("..") && where.length > 1 ? where[0] : void 0;
256
+ if (otherFolder && otherFolder !== folder && /\.table\.[cm]?tsx?$/.test(target)) {
257
+ add("no-cross-service-tables", file, `Service "${service}" imports ${basename(target)} from ${otherFolder}/; call that service's actions or listen to its events instead.`, line);
258
+ continue;
259
+ }
260
+ const module = await import(target).catch(() => ({}));
261
+ const names = [];
262
+ if (defaultName?.trim()) names.push("default");
263
+ if (rest?.startsWith("*")) names.push(...Object.keys(module));
264
+ else if (rest) for (const part of rest.slice(1, -1).split(",")) {
265
+ const name = part.trim().split(/\s+as\s+/)[0];
266
+ if (name && !name.startsWith("type ")) names.push(name);
267
+ }
268
+ for (const name of names) {
269
+ const owner = owners.get(module[name]);
270
+ if (owner && owner !== service) add("no-cross-service-tables", file, `Service "${service}" imports table ${name === "default" ? basename(target) : `"${name}"`} owned by "${owner}"; call ${owner}'s actions or listen to its events instead.`, line);
271
+ }
272
+ }
273
+ }
274
+ }
275
+ function declaredEvents(check, app, add) {
276
+ if (check.severity("declared-events") === "off") return;
277
+ for (const service of app.definition.services) {
278
+ if (!service.options.events) continue;
279
+ const names = new Set(Object.values(service.events).map((e) => e.name));
280
+ const resources = service.listResources().map((r) => r.name);
281
+ const declared = (name) => {
282
+ const [owner, event] = name.split(".", 2);
283
+ return names.has(name) || resources.includes(owner) && /^(create|update|delete)$/.test(event);
284
+ };
285
+ for (const action of service.listActions()) for (const name of action.config.emits ?? []) if (!declared(name)) add("declared-events", check.entry, `Action "${service.name}.${action.name}" emits "${name}", which is not in ${service.name}'s event catalog.`);
286
+ const folder = [kebabCase(service.name), service.name].map((name) => resolve(check.services, name)).find(existsSync);
287
+ for (const file of folder ? sourceFiles(check, folder) : []) {
288
+ const source = readFileSync(file, "utf8");
289
+ for (const match of source.matchAll(/emitEvent\s*\([^,]+,\s*["'`]([^"'`]+)["'`]/g)) if (!declared(match[1])) add("declared-events", file, `"${match[1]}" is not in ${service.name}'s event catalog.`, lineOf(source, match.index));
290
+ }
291
+ }
292
+ }
293
+ function testColocated(check, add) {
294
+ if (check.severity("test-colocated") === "off") return;
295
+ for (const file of sourceFiles(check, check.services)) {
296
+ const match = /^(.*)\.(action|command)\.[cm]?tsx?$/.exec(basename(file));
297
+ if (!match) continue;
298
+ const test = resolve(dirname(file), `${match[1]}.test.ts`);
299
+ if (!existsSync(test) && !existsSync(`${test}x`)) add("test-colocated", file, `${basename(file)} has no ${match[1]}.test.ts beside it.`);
300
+ }
301
+ }
302
+ // src/db.ts
303
+ /**
304
+ * The app's databases and their tables: those passed to `defineDatabase`
305
+ * (outbox tables included), resource tables, and the tables plugins own.
306
+ * Throws when two handles share a name, since the name picks the migrations folder.
307
+ */
308
+ function appDatabases(app) {
309
+ const found = /* @__PURE__ */ new Map();
310
+ for (const service of app.definition.services) {
311
+ const database = service.getDatabaseHandle?.();
312
+ if (!database) continue;
313
+ let entry = found.get(database);
314
+ if (!entry) {
315
+ entry = {
316
+ name: database.name ?? service.name,
317
+ services: 0,
318
+ tables: /* @__PURE__ */ new Set()
319
+ };
320
+ found.set(database, entry);
321
+ }
322
+ entry.services++;
323
+ for (const table of [...Object.values(database.tables), ...service.tables.values()]) entry.tables.add(table);
324
+ }
325
+ const databases = [...found].filter(([, entry]) => entry.tables.size > 0);
326
+ const names = /* @__PURE__ */ new Map();
327
+ for (const [database, entry] of databases) {
328
+ if (!database.name && entry.services > 1) throw new Error(`Brick: services share a database without a name, so its migrations folder would follow service order; give it \`defineDatabase({ name })\`.`);
329
+ if (names.has(entry.name)) throw new Error(`Brick: two databases are named "${entry.name}"; give each \`defineDatabase({ name })\` its own name, or share one handle between the services.`);
330
+ names.set(entry.name, database);
331
+ }
332
+ return databases.map(([database, entry]) => ({
333
+ name: entry.name,
334
+ database,
335
+ tables: [...entry.tables]
336
+ }));
337
+ }
338
+ /** Run `brick db generate|migrate|push` against every database of the app. */
339
+ async function runDbCommand(command, app, options) {
340
+ const log = options.log ?? console.log;
341
+ const databases = appDatabases(app);
342
+ if (!databases.length) throw new Error("Brick: the app has no database with tables.");
343
+ try {
344
+ if (command === "migrate") for (const entry of databases) {
345
+ const folder = join(options.out, entry.name);
346
+ if (!existsSync(join(folder, "meta", "_journal.json"))) throw new Error(`Brick: no migrations in ${folder}; run \`brick db generate\` first.`);
347
+ }
348
+ for (const entry of databases) {
349
+ const folder = join(options.out, entry.name);
350
+ const label = `${entry.name} (${entry.database.engine})`;
351
+ if (command === "generate") {
352
+ const file = await generate(entry, folder, options.name);
353
+ log(file ? `${label}: wrote ${file}` : `${label}: no schema changes`);
354
+ } else if (command === "migrate") {
355
+ await migrateDatabase(entry.database, folder);
356
+ log(`${label}: migrations in ${folder} applied`);
357
+ } else {
358
+ const applied = await push(entry, options.force ?? false, log);
359
+ log(applied ? `${label}: applied ${applied} change${applied === 1 ? "" : "s"}` : `${label}: no schema changes`);
360
+ }
361
+ }
362
+ } finally {
363
+ await Promise.all(databases.map((entry) => entry.database.close?.()));
364
+ }
365
+ }
366
+ const kit = () => import("drizzle-kit/api");
367
+ /**
368
+ * Diff the tables against the folder's last snapshot with drizzle-kit and write
369
+ * the SQL, snapshot and journal in drizzle-kit's layout, so drizzle-kit and
370
+ * Drizzle's migrator read the folder too. Returns the SQL file, if any.
371
+ */
372
+ async function generate(entry, folder, name = "migration") {
373
+ const { generateDrizzleJson, generateMigration, ...sqlite } = await kit();
374
+ const postgres = entry.database.engine === "postgres";
375
+ const meta = join(folder, "meta");
376
+ const journalFile = join(meta, "_journal.json");
377
+ const journal = existsSync(journalFile) ? JSON.parse(readFileSync(journalFile, "utf8")) : {
378
+ version: "7",
379
+ dialect: postgres ? "postgresql" : "sqlite",
380
+ entries: []
381
+ };
382
+ const last = journal.entries.at(-1);
383
+ const idx = last ? last.idx + 1 : 0;
384
+ const prev = last ? JSON.parse(readFileSync(join(meta, `${last.tag.slice(0, 4)}_snapshot.json`), "utf8")) : void 0;
385
+ const schema = drizzleSchema(entry.tables);
386
+ let cur;
387
+ let statements;
388
+ if (postgres) {
389
+ const next = generateDrizzleJson(schema, prev?.id);
390
+ statements = await generateMigration(prev ?? generateDrizzleJson({}), next);
391
+ cur = next;
392
+ } else {
393
+ const next = await sqlite.generateSQLiteDrizzleJson(schema, prev?.id);
394
+ statements = await sqlite.generateSQLiteMigration(prev ?? await sqlite.generateSQLiteDrizzleJson({}), next);
395
+ cur = next;
396
+ }
397
+ if (!statements.length) return void 0;
398
+ const prefix = String(idx).padStart(4, "0");
399
+ const tag = `${prefix}_${name}`;
400
+ mkdirSync(meta, { recursive: true });
401
+ const file = join(folder, `${tag}.sql`);
402
+ writeFileSync(file, statements.join("\n--> statement-breakpoint\n"));
403
+ writeFileSync(join(meta, `${prefix}_snapshot.json`), JSON.stringify(cur, null, 2));
404
+ journal.entries.push({
405
+ idx,
406
+ version: cur.version,
407
+ when: Date.now(),
408
+ tag,
409
+ breakpoints: true
410
+ });
411
+ writeFileSync(journalFile, JSON.stringify(journal, null, 2));
412
+ return file;
413
+ }
414
+ /**
415
+ * Make the database match the tables with drizzle-kit's push, touching only
416
+ * the tables Brick knows. Returns how many statements ran.
417
+ */
418
+ async function push(entry, force, log) {
419
+ const { pushSchema, pushSQLiteSchema } = await kit();
420
+ const db = entry.database.getDb();
421
+ const names = new Set(entry.tables.map((table) => getTableName(table)));
422
+ const schema = drizzleSchema(entry.tables);
423
+ const postgres = entry.database.engine === "postgres";
424
+ const result = postgres ? await pushSchema(schema, { execute: async (query) => ({ rows: await db.execute(query) }) }, [...new Set(entry.tables.map((table) => table[Symbol.for("drizzle:Schema")] ?? "public"))], [...names]) : await pushSQLiteSchema(schema, onlyTables(db, names));
425
+ const statements = result.statementsToExecute;
426
+ if (!statements.length) return 0;
427
+ for (const warning of result.warnings) log(warning);
428
+ if (result.hasDataLoss && !force) throw new Error(`Brick: pushing ${entry.name} would lose data (see above). Rerun with --force to apply it, or use \`brick db generate\` and edit the migration.`);
429
+ if (postgres) await db.transaction(async (tx) => {
430
+ for (const statement of statements) await tx.execute(sql.raw(statement));
431
+ });
432
+ else await result.apply();
433
+ return statements.length;
434
+ }
435
+ /**
436
+ * drizzle-kit's SQLite push has no table filter: hide the tables Brick does not
437
+ * know (FTS sidecars, other apps' tables) from what it reads, so it neither
438
+ * drops them nor asks whether a new table renames one.
439
+ */
440
+ function onlyTables(db, names) {
441
+ return {
442
+ all: (query) => db.all(query).filter((row) => {
443
+ const table = row.tableName ?? row.tableFrom ?? row.tbl_name ?? row.view_name;
444
+ return table === void 0 || names.has(table);
445
+ }),
446
+ run: (query) => db.run(query)
447
+ };
448
+ }
449
+ // src/bin.ts
450
+ const CLI_VERSION = "0.12.0";
12
451
  const PORT_HELP = "Port to listen on (CLI --port overrides PORT env, default 4000)";
452
+ const EXTENSION_HELP = "Dashboard extension module (default export defineDashboard(...)), or the dashboard folder brick build wrote";
13
453
  const PORT_RESOLUTION_HELP = `
14
454
  Port Resolution (dev/start commands):
15
455
  - CLI --port flag takes precedence
16
456
  - Falls back to PORT environment variable
17
- - Defaults to 4000 if neither is set
457
+ - Then dev.port in brick.config.ts (brick dev only)
458
+ - Defaults to 4000 if none is set
18
459
  - Valid range: 1-65535
19
460
 
20
461
  Examples:
@@ -23,6 +464,7 @@ Examples:
23
464
  PORT=3000 brick dev app.ts # port 3000 (from env)
24
465
  brick dev app.ts --port 6000 # port 6000 (CLI overrides PORT=3000)
25
466
  `;
467
+ const CONFIG_HELP = "Path to brick.config.ts (default: the nearest one in this folder or its parents)";
26
468
  function parsePortOption(value) {
27
469
  try {
28
470
  return parsePort(value, void 0);
@@ -39,9 +481,46 @@ function parseFileOption(value, usage) {
39
481
  if (value.startsWith("-")) throw new InvalidArgumentError(`${usage} (got flag-like value '${value}')`);
40
482
  return value;
41
483
  }
42
- function resolveDevPort(cliPort) {
43
- if (cliPort !== void 0) return cliPort;
44
- return parsePort(void 0, process.env.PORT);
484
+ /** `--config` on a `gen` subcommand: commander hands it to `gen`, which takes it too. */
485
+ function configOf(command) {
486
+ return command.optsWithGlobals().config;
487
+ }
488
+ /** The entry argument, else the config's entry; without either, commander's usual error. */
489
+ function requireEntry(command, entry, project) {
490
+ const resolved = entry ?? project?.entry;
491
+ if (!resolved) command.error("error: missing required argument 'entry'", {
492
+ exitCode: 1,
493
+ code: "commander.missingArgument"
494
+ });
495
+ return resolved;
496
+ }
497
+ /** Load the app after refreshing the services manifest it imports. */
498
+ async function loadProjectApp(entry, project) {
499
+ if (project) await writeServiceManifest(project);
500
+ return loadBrickApp(entry);
501
+ }
502
+ /** A config path, made absolute from the config file's folder. */
503
+ function fromRoot(project, path) {
504
+ return path && project ? resolve(project.root, path) : path;
505
+ }
506
+ /** The config's dashboard settings; a `--dashboard-extension` flag replaces its extension. */
507
+ function configDashboard(project, extensionFlag) {
508
+ const dashboard = project?.config.dashboard;
509
+ if (!dashboard && !extensionFlag) return void 0;
510
+ return {
511
+ extension: extensionFlag ?? fromRoot(project, dashboard?.extension),
512
+ theme: dashboard?.theme
513
+ };
514
+ }
515
+ async function writeOpenApi(entry, output, project) {
516
+ const app = await loadProjectApp(entry, project);
517
+ const spec = generateOpenApiSpec({
518
+ services: [...app.definition.services],
519
+ prefix: app.definition.prefix
520
+ });
521
+ const json = JSON.stringify(spec, null, 2);
522
+ if (output) await Bun.write(output, json);
523
+ return json;
45
524
  }
46
525
  function createProgram() {
47
526
  const program = new Command();
@@ -53,68 +532,138 @@ Usage:
53
532
  brick build <app.ts> [--outdir <dir>] [--port <number>] [--no-aot] Compile a default-exported BrickApp into a Bun server
54
533
  brick gen openapi <entry> [--output <file>] Generate OpenAPI 3.1 JSON specification
55
534
  brick gen client <entry> [--output <file>] Generate a typed browser client contract
535
+ brick gen manifest Write <generated>/services.gen.ts
536
+ brick db generate [entry] [--out <dir>] [--name <name>] Write a SQL migration for the schema changes
537
+ brick db migrate [entry] [--out <dir>] Apply the migrations that have not run yet
538
+ brick db push [entry] [--force] Change the database to match the schema (development)
539
+ brick lint [entry] Check the project against the Brick lint rules
56
540
  brick info <entry> Export architecture JSON schema
541
+
542
+ With a brick.config.ts, the entry and most flags come from the config file,
543
+ and every command takes --config <path>.
57
544
  ${PORT_RESOLUTION_HELP}`);
58
- program.command("dev").description("Start development server with live reload").option("--client <file>", "Generate and watch a browser contract before startup").option("--frontend <command>", "Start frontend after contract generation; requires --client").option("--dashboard-port <number>", `Port for the local dashboard (default ${DEFAULT_DASHBOARD_PORT})`, parsePortOption).option("--history-days <number>", `Days of requests the dashboard keeps on disk, 0 for none (default 90)`, parseHistoryDays).option("--no-dashboard", "Do not start the local dashboard").argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entry, opts) => {
59
- const port = resolveDevPort(opts.port);
545
+ program.command("dev").description("Start development server with live reload").option("--client <file>", "Generate and watch a browser contract before startup").option("--frontend <command>", "Start frontend after contract generation; requires --client").option("--dashboard-port <number>", `Port for the local dashboard (default ${DEFAULT_DASHBOARD_PORT})`, parsePortOption).option("--history-days <number>", `Days of requests the dashboard keeps on disk, 0 for none (default 90)`, parseHistoryDays).option("--no-dashboard", "Do not start the local dashboard").option("--dashboard-extension <file>", EXTENSION_HELP).argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).option("--config <path>", CONFIG_HELP).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entryArg, opts) => {
546
+ const project = await loadConfig(opts.config);
547
+ const config = project?.config;
548
+ const entry = entryArg ?? project?.entry;
549
+ const port = resolveDevPort(opts.port, config?.dev?.port);
60
550
  if (opts.dashboard === false && opts.dashboardPort !== void 0) throw new Error("Brick: --dashboard-port cannot be combined with --no-dashboard.");
61
551
  if (opts.dashboard === false && opts.historyDays !== void 0) throw new Error("Brick: --history-days cannot be combined with --no-dashboard.");
552
+ const configured = config?.dev?.dashboard;
553
+ const dashboardOff = opts.dashboard === false || configured === false && opts.dashboardPort === void 0 && opts.historyDays === void 0;
554
+ const dashboardConfig = configured || void 0;
555
+ if (dashboardOff && opts.dashboardExtension) throw new Error("Brick: --dashboard-extension cannot be combined with --no-dashboard.");
62
556
  await startDevServer({
63
557
  entry,
64
558
  port,
65
- clientOutput: opts.client,
66
- frontend: opts.frontend,
67
- dashboard: entry && opts.dashboard !== false ? {
68
- port: opts.dashboardPort ?? 9400,
69
- historyDays: opts.historyDays
70
- } : false
559
+ clientOutput: opts.client ?? fromRoot(project, config?.client?.output),
560
+ frontend: opts.frontend ?? config?.dev?.frontend,
561
+ dashboard: entry && !dashboardOff ? {
562
+ port: opts.dashboardPort ?? dashboardConfig?.port ?? 9400,
563
+ historyDays: opts.historyDays ?? dashboardConfig?.historyDays,
564
+ ...configDashboard(project, opts.dashboardExtension)
565
+ } : false,
566
+ manifest: project
71
567
  });
72
568
  });
73
- program.command("start").description("Start production server").argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entry, opts) => {
569
+ program.command("start").description("Start production server").argument("[entry]", "Application entry file").option("--port <number>", PORT_HELP, parsePortOption).option("--dashboard-extension <file>", EXTENSION_HELP).option("--config <path>", CONFIG_HELP).addHelpText("after", PORT_RESOLUTION_HELP).action(async (entry, opts) => {
570
+ const project = await loadConfig(opts.config);
74
571
  const port = resolveDevPort(opts.port);
75
572
  await startProdServer({
76
- entry,
77
- port
573
+ entry: entry ?? project?.entry,
574
+ port,
575
+ dashboard: configDashboard(project, opts.dashboardExtension)
78
576
  });
79
577
  });
80
- program.command("worker").description("Deliver the app's events without serving HTTP").argument("<entry>", "Application entry file (must default-export a BrickApp)").action(async (entry) => {
81
- await startWorker({ entry });
578
+ program.command("worker").description("Deliver the app's events without serving HTTP").argument("[entry]", "Application entry file (must default-export a BrickApp)").option("--config <path>", CONFIG_HELP).action(async (entry, opts, command) => {
579
+ const project = await loadConfig(opts.config);
580
+ await startWorker({ entry: requireEntry(command, entry, project) });
82
581
  });
83
- program.command("build").description("Compile a default-exported BrickApp into a Bun server").argument("<entry>", "Application entry file (must default-export a BrickApp)").option("--outdir <dir>", "Output directory", (v) => parseFileOption(v, "Usage: brick build <app.ts> [--outdir <directory>]")).option("--port <number>", "Default listening port", parsePortOption).option("--no-aot", "Disable ahead-of-time compilation").option("--prefix <path>", "DEPRECATED: configure prefix in brick() app instead").option("--no-request-logging", "DEPRECATED: configure requestLogging in brick() app instead").action(async (entry, opts) => {
582
+ program.command("build").description("Compile a default-exported BrickApp into a Bun server").argument("[entry]", "Application entry file (must default-export a BrickApp)").option("--config <path>", CONFIG_HELP).option("--outdir <dir>", "Output directory", (v) => parseFileOption(v, "Usage: brick build <app.ts> [--outdir <directory>]")).option("--port <number>", "Default listening port", parsePortOption).option("--no-aot", "Disable ahead-of-time compilation").option("--dashboard-extension <file>", "Dashboard extension module to build into <outdir>/dashboard").option("--prefix <path>", "DEPRECATED: configure prefix in brick() app instead").option("--no-request-logging", "DEPRECATED: configure requestLogging in brick() app instead").action(async (entryArg, opts, command) => {
84
583
  if (opts.prefix !== void 0 || opts.requestLogging === false) throw new Error("Brick: configure prefix and requestLogging in your default-exported brick() app instead of build flags.");
584
+ const project = await loadConfig(opts.config);
585
+ const build = project?.config.build;
586
+ if (build?.requestLogging === false) throw new Error("Brick: configure requestLogging in your default-exported brick() app instead of build.requestLogging.");
587
+ const entry = requireEntry(command, entryArg, project);
588
+ if (project) await writeServiceManifest(project);
85
589
  const result = await buildApplication({
86
590
  entry,
87
- outdir: opts.outdir,
591
+ outdir: opts.outdir ?? fromRoot(project, build?.outdir),
88
592
  port: opts.port,
89
- aot: opts.aot
593
+ aot: opts.aot === false ? false : build?.aot,
594
+ dashboard: configDashboard(project, opts.dashboardExtension)
90
595
  });
91
596
  for (const warning of result.ir.diagnostics) console.warn(`[Brick compiler] ${warning}`);
92
597
  console.log(`Compiled ${result.ir.services.length} services / ${result.ir.routes.length} routes`);
93
598
  console.log(`IR: ${result.outdir}/brick-ir.json`);
599
+ if (result.dashboard) console.log(`Dashboard extension: ${result.dashboard}`);
94
600
  console.log(`Run: bun ${result.entry}`);
95
601
  });
96
- const gen = program.command("gen").description("Generate artifacts from a BrickApp entry").argument("[subcommand]", "Generator to run (openapi, client)").action((subcommand) => {
97
- console.error(`Unknown generator: ${subcommand ?? "(none)"}. Available: openapi, client`);
98
- process.exit(1);
602
+ const gen = program.command("gen").description("Generate artifacts from a BrickApp entry").argument("[subcommand]", "Generator to run (openapi, client, manifest)").option("--config <path>", CONFIG_HELP).action(async (subcommand, opts) => {
603
+ const project = subcommand === void 0 ? await loadConfig(opts.config) : void 0;
604
+ if (!project) {
605
+ console.error(`Unknown generator: ${subcommand ?? "(none)"}. Available: openapi, client, manifest`);
606
+ process.exit(1);
607
+ }
608
+ const manifest = await writeServiceManifest(project);
609
+ console.log(`Services manifest written to ${manifest}`);
610
+ const client = fromRoot(project, project.config.client?.output);
611
+ if (client) {
612
+ await writeClientContract(project.entry, client);
613
+ console.log(`Client contract written to ${client}`);
614
+ }
615
+ const openapi = fromRoot(project, project.config.openapi?.output);
616
+ if (openapi) {
617
+ await writeOpenApi(project.entry, openapi, project);
618
+ console.log(`✅ OpenAPI 3.1 specification written to ${openapi}`);
619
+ }
99
620
  });
100
- gen.command("openapi").description("Generate OpenAPI 3.1 JSON specification").argument("<entry>", "Application entry file").option("--output <file>", "Write specification to file instead of stdout", (v) => parseFileOption(v, "Usage: brick gen openapi <entry> [--output <file>]")).action(async (entry, opts) => {
101
- const app = await loadBrickApp(entry);
102
- const spec = generateOpenApiSpec({
103
- services: [...app.definition.services],
104
- prefix: app.definition.prefix
105
- });
106
- const jsonOutput = JSON.stringify(spec, null, 2);
107
- if (opts.output) {
108
- await Bun.write(opts.output, jsonOutput);
109
- console.log(`✅ OpenAPI 3.1 specification written to ${opts.output}`);
110
- } else console.log(jsonOutput);
111
- });
112
- gen.command("client").description("Generate a typed browser client contract").argument("<entry>", "Application entry file").option("--output <file>", "Write contract to file (default _brick/contract.ts)", (v) => parseFileOption(v, "Usage: brick gen client <entry> [--output <file>]")).action(async (entry, opts) => {
113
- const output = await writeClientContract(entry, opts.output);
621
+ gen.command("openapi").description("Generate OpenAPI 3.1 JSON specification").argument("[entry]", "Application entry file").option("--config <path>", CONFIG_HELP).option("--output <file>", "Write specification to file instead of stdout", (v) => parseFileOption(v, "Usage: brick gen openapi <entry> [--output <file>]")).action(async (entry, opts, command) => {
622
+ const project = await loadConfig(configOf(command));
623
+ const output = opts.output ?? fromRoot(project, project?.config.openapi?.output);
624
+ const json = await writeOpenApi(requireEntry(command, entry, project), output, project);
625
+ if (output) console.log(`✅ OpenAPI 3.1 specification written to ${output}`);
626
+ else console.log(json);
627
+ });
628
+ gen.command("client").description("Generate a typed browser client contract").argument("[entry]", "Application entry file").option("--config <path>", CONFIG_HELP).option("--output <file>", "Write contract to file (default _brick/contract.ts)", (v) => parseFileOption(v, "Usage: brick gen client <entry> [--output <file>]")).action(async (entry, opts, command) => {
629
+ const project = await loadConfig(configOf(command));
630
+ const target = requireEntry(command, entry, project);
631
+ if (project) await writeServiceManifest(project);
632
+ const output = await writeClientContract(target, opts.output ?? fromRoot(project, project?.config.client?.output) ?? (project && join(project.generated, "contract.ts")));
114
633
  console.log(`Client contract written to ${output}`);
115
634
  });
116
- program.command("info").alias("services").description("Export architecture JSON schema").argument("<entry>", "Application entry file").action(async (entry) => {
117
- const app = await loadBrickApp(entry);
635
+ gen.command("manifest").description("Write <generated>/services.gen.ts, which imports every definition file").option("--config <path>", CONFIG_HELP).action(async (_opts, command) => {
636
+ const project = await loadConfig(configOf(command));
637
+ const output = await writeServiceManifest(project ?? {
638
+ services: resolve("src/services"),
639
+ generated: resolve("_brick")
640
+ });
641
+ console.log(`Services manifest written to ${output}`);
642
+ });
643
+ const db = program.command("db").description("Manage the app's database schema with drizzle-kit: generate, migrate, push");
644
+ const dbCommand = (name, description) => db.command(name).description(description).argument("[entry]", "Application entry file").option("--config <path>", CONFIG_HELP);
645
+ const OUT_HELP = "Migrations folder (default drizzle, beside brick.config.ts); each database gets a subfolder named after it";
646
+ const dbAction = (name) => async (entry, opts, command) => {
647
+ const project = await loadConfig(opts.config);
648
+ await runDbCommand(name, await loadProjectApp(requireEntry(command, entry, project), project), {
649
+ out: opts.out ?? fromRoot(project, "drizzle"),
650
+ name: opts.name,
651
+ force: opts.force
652
+ });
653
+ };
654
+ dbCommand("generate", "Write a SQL migration for the schema changes since the last one").option("--out <dir>", OUT_HELP).option("--name <name>", "Migration name (default migration)").action(dbAction("generate"));
655
+ dbCommand("migrate", "Apply the migrations that have not run yet").option("--out <dir>", OUT_HELP).action(dbAction("migrate"));
656
+ dbCommand("push", "Change the database to match the schema directly, without migration files (development)").option("--force", "Apply changes that drop data").action(dbAction("push"));
657
+ program.command("lint").description("Check the project against the Brick lint rules").argument("[entry]", "Application entry file").option("--config <path>", CONFIG_HELP).action(async (entry, opts) => {
658
+ const code = await runLint({
659
+ entry,
660
+ project: await loadConfig(opts.config)
661
+ });
662
+ if (code !== 0) process.exit(code);
663
+ });
664
+ program.command("info").alias("services").description("Export architecture JSON schema").argument("[entry]", "Application entry file").option("--config <path>", CONFIG_HELP).action(async (entry, opts, command) => {
665
+ const project = await loadConfig(opts.config);
666
+ const app = await loadProjectApp(requireEntry(command, entry, project), project);
118
667
  const architecture = getGlobalRegistry().exportArchitecture(app.definition);
119
668
  console.log(JSON.stringify(architecture, null, 2));
120
669
  });
@@ -122,7 +671,12 @@ ${PORT_RESOLUTION_HELP}`);
122
671
  }
123
672
  async function main() {
124
673
  const program = createProgram();
125
- if (process.argv.slice(2).length === 0) {
674
+ const userArgs = process.argv.slice(2);
675
+ if (userArgs.length === 0 && await loadConfig()) {
676
+ await program.parseAsync([...process.argv, "dev"]);
677
+ return;
678
+ }
679
+ if (userArgs.length === 0) {
126
680
  const port = parsePort(void 0, process.env.PORT);
127
681
  await startDevServer({ port });
128
682
  return;
@@ -132,10 +686,13 @@ async function main() {
132
686
  main().catch((err) => {
133
687
  if (err?.exitCode !== void 0) process.exit(err.exitCode);
134
688
  if (err?.code?.startsWith?.("commander.")) process.exit(1);
689
+ if (err instanceof ConfigError) {
690
+ console.error(err.message);
691
+ process.exit(1);
692
+ }
135
693
  console.error("Fatal error:", err);
136
694
  process.exit(1);
137
695
  });
138
- //#endregion
139
696
  export { createProgram };
140
697
 
141
698
  //# sourceMappingURL=bin.js.map