@brickkit/cli 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dashboard-dist/{api-reference-B-bZRtNV.js → api-reference-mT9VNcPb.js} +69 -69
- package/dashboard-dist/app.js +12 -13
- package/dashboard-dist/{client-BJJtVSVr.js → client-CwATkLJa.js} +1 -1
- package/dashboard-dist/{core-Z7NJFk0K.js → core-BEUWp6B5.js} +1 -1
- package/dashboard-dist/docs-BRrtyxDB.js +4 -0
- package/dashboard-dist/kit.js +1 -1
- package/dashboard-dist/popover-Bj9x-88h.js +1 -0
- package/dist/bin.js +154 -217
- package/dist/bin.js.map +1 -1
- package/dist/build.js +463 -0
- package/dist/build.js.map +1 -0
- package/dist/client-contract-file.js +356 -1
- package/dist/client-contract-file.js.map +1 -0
- package/dist/compiler.d.ts +12 -2
- package/dist/compiler2.js +12 -5
- package/dist/compiler2.js.map +1 -1
- package/dist/config.d.ts +3 -0
- package/dist/config.js +1 -250
- package/dist/config2.d.ts +122 -0
- package/dist/config2.js +207 -0
- package/dist/config2.js.map +1 -0
- package/dist/dashboard-extension.d.ts +3 -0
- package/dist/{dev-telemetry-store.js → dashboard-host.js} +1533 -1574
- package/dist/dashboard-host.js.map +1 -0
- package/dist/dashboard-protocol.js +189 -0
- package/dist/dashboard-protocol.js.map +1 -0
- package/dist/dashboard.d.ts +4 -1
- package/dist/definitions.js +33 -0
- package/dist/definitions.js.map +1 -0
- package/dist/dev-application.js +34 -0
- package/dist/dev-application.js.map +1 -0
- package/dist/dev-protocol.js +21 -0
- package/dist/dev-protocol.js.map +1 -0
- package/dist/dev-reporter.js +2 -1
- package/dist/dev-reporter.js.map +1 -1
- package/dist/dev-telemetry.js +5 -20
- package/dist/dev-telemetry.js.map +1 -1
- package/dist/dev-worker.js +79 -19
- package/dist/dev-worker.js.map +1 -1
- package/dist/index.d.ts +15 -74
- package/dist/index.js +12 -5
- package/dist/index.js.map +1 -0
- package/dist/lint/oxlint.js +5 -3
- package/dist/lint/oxlint.js.map +1 -1
- package/dist/own-module.js +7 -0
- package/dist/own-module.js.map +1 -0
- package/dist/plugin.d.ts +6 -5
- package/dist/plugin.js +5 -39
- package/dist/plugin.js.map +1 -1
- package/dist/production-dashboard.d.ts +2 -0
- package/dist/production-dashboard.js +51 -0
- package/dist/production-dashboard.js.map +1 -0
- package/dist/production-dashboard2.d.ts +34 -0
- package/dist/{presets.js → project.js} +104 -106
- package/dist/project.js.map +1 -0
- package/dist/serve.d.ts +24 -0
- package/dist/serve.js +1 -0
- package/dist/serve2.js +49 -0
- package/dist/serve2.js.map +1 -0
- package/dist/vite.js +26 -47
- package/dist/vite.js.map +1 -1
- package/dist/workflows.d.ts +2 -2
- package/dist/workflows2.js +59 -37
- package/dist/workflows2.js.map +1 -1
- package/inspector-dist/client/assets/app-CeSwVsRm.css +2 -0
- package/inspector-dist/client/assets/{highlighted-body-B3W2YXNL-DYVdwGy2.js → highlighted-body-B3W2YXNL-CfRnuITN.js} +1 -1
- package/inspector-dist/client/assets/{home-CyjkvtII.js → home-hwPlkNhv.js} +1529 -378
- package/inspector-dist/client/assets/manifest-0e76e9ac.js +1 -0
- package/inspector-dist/client/assets/mermaid-3ZIDBTTL-ZDR2PNY_.js +1 -0
- package/inspector-dist/client/assets/root-ChBNTZd2.css +2 -0
- package/inspector-dist/client/assets/{root-DX9wtogx.js → root-SLeEf-sT.js} +17 -29
- package/inspector-dist/client/assets/{run-detail-C69EJGql.js → run-detail-DYbVkIFH.js} +398 -76
- package/inspector-dist/client/assets/{tabs-B6B88IjT.js → tabs-CaJisoyb.js} +189 -2130
- package/inspector-dist/client/assets/{zstd-browser-decoder-ByUgcY9H.js → zstd-browser-decoder-D94wmfAU.js} +1 -1
- package/inspector-dist/server/assets/{app-WoDoT62X.js → app-DGlfWVUI.js} +69783 -70608
- package/inspector-dist/server/assets/{chunk-RLXIAIE6-CbvDIAEa.js → chunk-RLXIAIE6-F0SJZlei.js} +4 -6
- package/inspector-dist/server/assets/{dist-qR-969AD.js → dist-BCbwm6jl.js} +2 -4
- package/inspector-dist/server/assets/{dist-CQnQcIJg.js → dist-CG2aVufI.js} +0 -2
- package/inspector-dist/server/assets/{dist-BRxZSWUN.js → dist-Ce0I2PUv.js} +2 -5
- package/inspector-dist/server/assets/{dist-DqRd9pyS.js → dist-DY0UlahA.js} +0 -2
- package/inspector-dist/server/assets/{encryption-_PuklZNX.js → encryption-DdQgC8Rk.js} +2 -4
- package/inspector-dist/server/assets/{event-metadata-BVakQJ_y.js → event-metadata-n7E4zEmT.js} +0 -2
- package/inspector-dist/server/assets/{functions-CImcpqNl.js → functions-CNVQtbgg.js} +2 -4
- package/inspector-dist/server/assets/{global-singleton-CPirHxFh.js → global-singleton-D8sIN5du.js} +0 -2
- package/inspector-dist/server/assets/{highlighted-body-B3W2YXNL-fPMB_t7F.js → highlighted-body-B3W2YXNL-CWRzMxYD.js} +2 -4
- package/inspector-dist/server/assets/mermaid-3ZIDBTTL-D0v0ngVr.js +1 -0
- package/inspector-dist/server/assets/{parse-D9Vvgzt9.js → parse-Begau9cA.js} +0 -2
- package/inspector-dist/server/assets/{rolldown-runtime-CLg409Sh.js → rolldown-runtime-C1I3wEg2.js} +1 -2
- package/inspector-dist/server/assets/{serialization-format-DDtsVTU1.js → serialization-format-BbuGfHog.js} +6 -8
- package/inspector-dist/server/assets/{token-BW4GdQZh.js → token-BgMmJNP5.js} +2 -4
- package/inspector-dist/server/assets/{token-D6FXdkJT.js → token-BrUX0bxz.js} +2 -4
- package/inspector-dist/server/assets/{token-util-BoNmi-wE.js → token-util-DZN32qmT.js} +1 -3
- package/inspector-dist/server/assets/{wrapper-wiqsGXcE.js → wrapper-CIC3w0oC.js} +1 -3
- package/inspector-dist/server/assets/{ws-transport-DV7oG4mL.js → ws-transport-CxTYB11n.js} +24094 -24096
- package/inspector-dist/server/assets/{zstd-browser-decoder-Cswf0KO6.js → zstd-browser-decoder-D7bCXbGg.js} +2 -4
- package/inspector-dist/server/index.js +1 -3
- package/package.json +12 -2
- package/dashboard-dist/docs-Dpfc0wJb.js +0 -4
- package/dashboard-dist/popover-BzejBolB.js +0 -1
- package/dist/app-entry.js +0 -1
- package/dist/app-entry2.js +0 -18
- package/dist/app-entry2.js.map +0 -1
- package/dist/client-contract-file2.js +0 -33
- package/dist/client-contract-file2.js.map +0 -1
- package/dist/client-contract.js +0 -1
- package/dist/client-contract2.js +0 -296
- package/dist/client-contract2.js.map +0 -1
- package/dist/config.js.map +0 -1
- package/dist/dev-telemetry-store.js.map +0 -1
- package/dist/emit.d.ts +0 -5
- package/dist/presets.js.map +0 -1
- package/dist/runner.js +0 -519
- package/dist/runner.js.map +0 -1
- package/inspector-dist/client/assets/app-CCzpuUz_.css +0 -2
- package/inspector-dist/client/assets/manifest-ba30b52d.js +0 -1
- package/inspector-dist/client/assets/mermaid-3ZIDBTTL-Dy6IVqPy.js +0 -1
- package/inspector-dist/client/assets/root-8BMab1lL.css +0 -2
- package/inspector-dist/client/assets/world-config-context-C3BqXPIv.js +0 -30
- package/inspector-dist/server/assets/mermaid-3ZIDBTTL-bADXySE3.js +0 -3
package/dist/serve.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { t as DashboardExtensionOptions } from "./dashboard-extension.js";
|
|
2
|
+
import { t as ProductionDashboard } from "./production-dashboard2.js";
|
|
3
|
+
import { BrickApp } from "@brickkit/core";
|
|
4
|
+
/**
|
|
5
|
+
* Serve an app: the monitoring dashboard it asks for with `brick({ dashboard })`
|
|
6
|
+
* (unless `dashboard` is false), then the app itself. What `brick dev`'s
|
|
7
|
+
* worker, `brick start` and a built server run.
|
|
8
|
+
*/
|
|
9
|
+
export declare function serveApp(app: BrickApp, options: {
|
|
10
|
+
port: number;
|
|
11
|
+
dashboard?: DashboardExtensionOptions | false;
|
|
12
|
+
}): Promise<ProductionDashboard | undefined>;
|
|
13
|
+
/**
|
|
14
|
+
* Shut the app down at SIGINT or SIGTERM, finishing the deliveries in flight,
|
|
15
|
+
* then exit. A second signal exits at once, for a delivery that never finishes.
|
|
16
|
+
*/
|
|
17
|
+
export declare function shutdownOnSignal(app: Pick<BrickApp, "shutdown">): void;
|
|
18
|
+
/** The startup lines: each service's routes as mounted, then where to reach the app. */
|
|
19
|
+
export declare function printBanner(app: BrickApp, options: {
|
|
20
|
+
label: string;
|
|
21
|
+
port: number;
|
|
22
|
+
dashboard?: Pick<ProductionDashboard, "host" | "port">;
|
|
23
|
+
}): void;
|
|
24
|
+
//# sourceMappingURL=serve.d.ts.map
|
package/dist/serve.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as printBanner, n as serveApp, r as shutdownOnSignal } from "./serve2.js";
|
package/dist/serve2.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// src/serve.ts
|
|
2
|
+
/**
|
|
3
|
+
* Serve an app: the monitoring dashboard it asks for with `brick({ dashboard })`
|
|
4
|
+
* (unless `dashboard` is false), then the app itself. What `brick dev`'s
|
|
5
|
+
* worker, `brick start` and a built server run.
|
|
6
|
+
*/
|
|
7
|
+
async function serveApp(app, options) {
|
|
8
|
+
const dashboard = app.definition.dashboard && options.dashboard !== false ? await (await import("./production-dashboard.js")).startProductionDashboard(app, {
|
|
9
|
+
appPort: options.port,
|
|
10
|
+
dashboard: options.dashboard
|
|
11
|
+
}) : void 0;
|
|
12
|
+
await app.serve({ port: options.port });
|
|
13
|
+
return dashboard;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Shut the app down at SIGINT or SIGTERM, finishing the deliveries in flight,
|
|
17
|
+
* then exit. A second signal exits at once, for a delivery that never finishes.
|
|
18
|
+
*/
|
|
19
|
+
function shutdownOnSignal(app) {
|
|
20
|
+
let stopping = false;
|
|
21
|
+
const stop = (signal) => {
|
|
22
|
+
if (stopping) return process.exit(signal === "SIGINT" ? 130 : 143);
|
|
23
|
+
stopping = true;
|
|
24
|
+
app.shutdown().finally(() => process.exit(0));
|
|
25
|
+
};
|
|
26
|
+
for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, stop);
|
|
27
|
+
}
|
|
28
|
+
/** The startup lines: each service's routes as mounted, then where to reach the app. */
|
|
29
|
+
function printBanner(app, options) {
|
|
30
|
+
const { services, routes } = app.definition;
|
|
31
|
+
console.log(`\n🧱 Brick-TS ${options.label} Server`);
|
|
32
|
+
console.log(` Registered Services: ${services.length}`);
|
|
33
|
+
for (const svc of services) {
|
|
34
|
+
console.log(` • ${svc.name} (${svc.listActions().length} actions)`);
|
|
35
|
+
for (const route of routes) if (route.service === svc.name) console.log(` -> ${route.method.padEnd(6)} ${route.path}`);
|
|
36
|
+
}
|
|
37
|
+
const base = `http://localhost:${options.port}`;
|
|
38
|
+
console.log(`\n⚡ API Gateway running on: ${base}`);
|
|
39
|
+
console.log(`🩺 Health check: ${base}/_health`);
|
|
40
|
+
const dashboard = options.dashboard;
|
|
41
|
+
if (dashboard) {
|
|
42
|
+
const shown = dashboard.host === "0.0.0.0" || dashboard.host === "::" ? "localhost" : dashboard.host.includes(":") ? `[${dashboard.host.replace(/^\[|\]$/g, "")}]` : dashboard.host;
|
|
43
|
+
console.log(`📊 Dashboard: http://${shown}:${dashboard.port} (health: /_health)`);
|
|
44
|
+
}
|
|
45
|
+
console.log(`🗺️ Architecture graph: ${base}/_brick/services\n`);
|
|
46
|
+
}
|
|
47
|
+
export { serveApp as n, shutdownOnSignal as r, printBanner as t };
|
|
48
|
+
|
|
49
|
+
//# sourceMappingURL=serve2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serve2.js","names":[],"sources":["../src/serve.ts"],"sourcesContent":["import type { BrickApp } from \"@brickkit/core\";\nimport type { DashboardExtensionOptions } from \"./dashboard-extension\";\nimport type { ProductionDashboard } from \"./production-dashboard\";\n\n/**\n * Serve an app: the monitoring dashboard it asks for with `brick({ dashboard })`\n * (unless `dashboard` is false), then the app itself. What `brick dev`'s\n * worker, `brick start` and a built server run.\n */\nexport async function serveApp(\n app: BrickApp,\n options: { port: number; dashboard?: DashboardExtensionOptions | false },\n): Promise<ProductionDashboard | undefined> {\n // Before listening, so the first request is already traced and its logs kept.\n // Loaded only when asked for: a built server bundles this file, and resolves\n // the dashboard from @brickkit/cli at run time (see build.ts).\n const dashboard =\n app.definition.dashboard && options.dashboard !== false\n ? await (\n await import(\"./production-dashboard\")\n ).startProductionDashboard(app, {\n appPort: options.port,\n dashboard: options.dashboard,\n })\n : undefined;\n await app.serve({ port: options.port });\n return dashboard;\n}\n\n/**\n * Shut the app down at SIGINT or SIGTERM, finishing the deliveries in flight,\n * then exit. A second signal exits at once, for a delivery that never finishes.\n */\nexport function shutdownOnSignal(app: Pick<BrickApp, \"shutdown\">) {\n let stopping = false;\n const stop = (signal: NodeJS.Signals) => {\n if (stopping) return process.exit(signal === \"SIGINT\" ? 130 : 143);\n stopping = true;\n void app.shutdown().finally(() => process.exit(0));\n };\n // `on`, not `once`: the workflow bundle loads signal-exit, which re-raises the\n // signal itself when it finds no listener left, and `once` removes ours first.\n for (const signal of [\"SIGINT\", \"SIGTERM\"] as const) process.on(signal, stop);\n}\n\n/** The startup lines: each service's routes as mounted, then where to reach the app. */\nexport function printBanner(\n app: BrickApp,\n options: {\n label: string;\n port: number;\n dashboard?: Pick<ProductionDashboard, \"host\" | \"port\">;\n },\n) {\n const { services, routes } = app.definition;\n console.log(`\\n🧱 Brick-TS ${options.label} Server`);\n console.log(` Registered Services: ${services.length}`);\n for (const svc of services) {\n console.log(` • ${svc.name} (${svc.listActions().length} actions)`);\n for (const route of routes)\n if (route.service === svc.name)\n console.log(` -> ${route.method.padEnd(6)} ${route.path}`);\n }\n const base = `http://localhost:${options.port}`;\n console.log(`\\n⚡ API Gateway running on: ${base}`);\n console.log(`🩺 Health check: ${base}/_health`);\n const dashboard = options.dashboard;\n if (dashboard) {\n const shown =\n dashboard.host === \"0.0.0.0\" || dashboard.host === \"::\"\n ? \"localhost\"\n : dashboard.host.includes(\":\")\n ? `[${dashboard.host.replace(/^\\[|\\]$/g, \"\")}]`\n : dashboard.host;\n console.log(\n `📊 Dashboard: http://${shown}:${dashboard.port} (health: /_health)`,\n );\n }\n console.log(`🗺️ Architecture graph: ${base}/_brick/services\\n`);\n}\n"],"mappings":";;;;;;AASA,eAAsB,SACpB,KACA,SAC0C;CAI1C,MAAM,YACJ,IAAI,WAAW,aAAa,QAAQ,cAAc,QAC9C,OACE,MAAM,OAAO,6BAAA,CACb,yBAAyB,KAAK;EAC9B,SAAS,QAAQ;EACjB,WAAW,QAAQ;CACrB,CAAC,IACD,KAAA;CACN,MAAM,IAAI,MAAM,EAAE,MAAM,QAAQ,KAAK,CAAC;CACtC,OAAO;AACT;;;;;AAMA,SAAgB,iBAAiB,KAAiC;CAChE,IAAI,WAAW;CACf,MAAM,QAAQ,WAA2B;EACvC,IAAI,UAAU,OAAO,QAAQ,KAAK,WAAW,WAAW,MAAM,GAAG;EACjE,WAAW;EACX,IAAS,SAAS,CAAC,CAAC,cAAc,QAAQ,KAAK,CAAC,CAAC;CACnD;CAGA,KAAK,MAAM,UAAU,CAAC,UAAU,SAAS,GAAY,QAAQ,GAAG,QAAQ,IAAI;AAC9E;;AAGA,SAAgB,YACd,KACA,SAKA;CACA,MAAM,EAAE,UAAU,WAAW,IAAI;CACjC,QAAQ,IAAI,iBAAiB,QAAQ,MAAM,QAAQ;CACnD,QAAQ,IAAI,2BAA2B,SAAS,QAAQ;CACxD,KAAK,MAAM,OAAO,UAAU;EAC1B,QAAQ,IAAI,QAAQ,IAAI,KAAK,IAAI,IAAI,YAAY,CAAC,CAAC,OAAO,UAAU;EACpE,KAAK,MAAM,SAAS,QAClB,IAAI,MAAM,YAAY,IAAI,MACxB,QAAQ,IAAI,WAAW,MAAM,OAAO,OAAO,CAAC,EAAE,GAAG,MAAM,MAAM;CACnE;CACA,MAAM,OAAO,oBAAoB,QAAQ;CACzC,QAAQ,IAAI,+BAA+B,MAAM;CACjD,QAAQ,IAAI,2BAA2B,KAAK,SAAS;CACrD,MAAM,YAAY,QAAQ;CAC1B,IAAI,WAAW;EACb,MAAM,QACJ,UAAU,SAAS,aAAa,UAAU,SAAS,OAC/C,cACA,UAAU,KAAK,SAAS,GAAG,IACzB,IAAI,UAAU,KAAK,QAAQ,YAAY,EAAE,EAAE,KAC3C,UAAU;EAClB,QAAQ,IACN,kCAAkC,MAAM,GAAG,UAAU,KAAK,oBAC5D;CACF;CACA,QAAQ,IAAI,4BAA4B,KAAK,mBAAmB;AAClE"}
|
package/dist/vite.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { n as
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
1
|
+
import { n as writeAppContract } from "./client-contract-file.js";
|
|
2
|
+
import { s as PROJECT_DEFAULTS } from "./config2.js";
|
|
3
|
+
import { t as ownModule } from "./own-module.js";
|
|
4
|
+
import { t as openDashboard } from "./dashboard-host.js";
|
|
5
|
+
import { s as ROUTES } from "./dashboard-protocol.js";
|
|
6
|
+
import { dirname, join, resolve } from "node:path";
|
|
7
|
+
import { getGlobalRegistry, requireBrickApp } from "@brickkit/core";
|
|
8
8
|
import { createServer, isRunnableDevEnvironment, normalizePath } from "vite";
|
|
9
9
|
import { ModuleRunner } from "vite/module-runner";
|
|
10
10
|
// src/dev-vite-dashboard.ts
|
|
@@ -14,28 +14,17 @@ import { ModuleRunner } from "vite/module-runner";
|
|
|
14
14
|
* history, so it survives worker restarts.
|
|
15
15
|
*/
|
|
16
16
|
async function startViteDashboard(options) {
|
|
17
|
-
const
|
|
17
|
+
const dashboard = await openDashboard({
|
|
18
|
+
port: options.port,
|
|
18
19
|
directory: options.directory,
|
|
19
|
-
|
|
20
|
-
warn: (message) => options.logger.warn(message)
|
|
20
|
+
historyDays: options.historyDays,
|
|
21
|
+
warn: (message) => options.logger.warn(message),
|
|
22
|
+
docs: true,
|
|
23
|
+
dashboard: options.dashboard,
|
|
24
|
+
portHint: "Set dashboard.port in brickClient() to another, or dashboard: false."
|
|
21
25
|
});
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
let dashboard;
|
|
25
|
-
try {
|
|
26
|
-
dashboard = await startDevDashboard({
|
|
27
|
-
port: options.port ?? 9400,
|
|
28
|
-
store,
|
|
29
|
-
history,
|
|
30
|
-
docs: () => docs.current,
|
|
31
|
-
dashboard: options.dashboard
|
|
32
|
-
});
|
|
33
|
-
} catch (error) {
|
|
34
|
-
history?.close();
|
|
35
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
36
|
-
options.logger.warn(`[Brick-TS] ${reason} Continuing without the dashboard.`);
|
|
37
|
-
return;
|
|
38
|
-
}
|
|
26
|
+
if (!dashboard) return void 0;
|
|
27
|
+
const { store, docs } = dashboard;
|
|
39
28
|
options.logger.info(` ➜ Brick dashboard: http://127.0.0.1:${dashboard.port}`);
|
|
40
29
|
let stopped = false;
|
|
41
30
|
let origin;
|
|
@@ -45,10 +34,10 @@ async function startViteDashboard(options) {
|
|
|
45
34
|
if (documents) store.setApiDocuments(documents, origin);
|
|
46
35
|
};
|
|
47
36
|
return {
|
|
48
|
-
ingestUrl: `http://127.0.0.1:${dashboard.port}
|
|
37
|
+
ingestUrl: `http://127.0.0.1:${dashboard.port}${ROUTES.ingest.path}`,
|
|
49
38
|
architecture(app) {
|
|
50
39
|
store.setArchitecture(getGlobalRegistry().exportArchitecture(app.definition), store.latestGeneration);
|
|
51
|
-
docs
|
|
40
|
+
docs?.configure(dirname(options.entry), app.definition.documentation);
|
|
52
41
|
const load = ++loads;
|
|
53
42
|
app.referenceDocuments().then((loaded) => {
|
|
54
43
|
if (load !== loads || stopped) return;
|
|
@@ -64,8 +53,6 @@ async function startViteDashboard(options) {
|
|
|
64
53
|
if (stopped) return;
|
|
65
54
|
stopped = true;
|
|
66
55
|
dashboard.stop();
|
|
67
|
-
docs.close();
|
|
68
|
-
history?.close();
|
|
69
56
|
}
|
|
70
57
|
};
|
|
71
58
|
}
|
|
@@ -76,7 +63,7 @@ function brickClient(options) {
|
|
|
76
63
|
const resolvedId = "\0" + virtualId;
|
|
77
64
|
const reporterId = "virtual:brick-dev-reporter";
|
|
78
65
|
const resolvedReporterId = "\0" + reporterId;
|
|
79
|
-
const reporterModule =
|
|
66
|
+
const reporterModule = ownModule("dev-reporter");
|
|
80
67
|
let entry;
|
|
81
68
|
let output;
|
|
82
69
|
let config;
|
|
@@ -87,10 +74,6 @@ function brickClient(options) {
|
|
|
87
74
|
const dependencies = /* @__PURE__ */ new Set();
|
|
88
75
|
let revision = 0;
|
|
89
76
|
const changedFiles = /* @__PURE__ */ new Set();
|
|
90
|
-
async function writeContract(value) {
|
|
91
|
-
const source = generateClientContract(requireBrickApp(value));
|
|
92
|
-
await writeContractSource(output, source);
|
|
93
|
-
}
|
|
94
77
|
function collectDependencies(node, seen = /* @__PURE__ */ new Set()) {
|
|
95
78
|
if (!node || seen.has(node)) return;
|
|
96
79
|
seen.add(node);
|
|
@@ -103,9 +86,7 @@ function brickClient(options) {
|
|
|
103
86
|
configResolved(resolved) {
|
|
104
87
|
config = resolved;
|
|
105
88
|
entry = normalizePath(resolve(config.root, options.entry));
|
|
106
|
-
output = normalizePath(resolve(config.root, options.output ?? "
|
|
107
|
-
if (entry === output) throw new Error("Brick: contract output must not overwrite the app entry.");
|
|
108
|
-
if (options.dashboard) themeCss(options.dashboard.theme);
|
|
89
|
+
output = normalizePath(resolve(config.root, options.output ?? join(PROJECT_DEFAULTS.generated, "contract.ts")));
|
|
109
90
|
},
|
|
110
91
|
async configureServer(server) {
|
|
111
92
|
const environment = server.environments.ssr;
|
|
@@ -137,7 +118,7 @@ function brickClient(options) {
|
|
|
137
118
|
});
|
|
138
119
|
}
|
|
139
120
|
const app = (await runner.import(entry)).default;
|
|
140
|
-
await
|
|
121
|
+
await writeAppContract(app, entry, output);
|
|
141
122
|
dashboard?.architecture(requireBrickApp(app));
|
|
142
123
|
dependencies.clear();
|
|
143
124
|
collectDependencies(environment.moduleGraph.getModuleById(entry));
|
|
@@ -169,7 +150,7 @@ function brickClient(options) {
|
|
|
169
150
|
invalidate(entry);
|
|
170
151
|
try {
|
|
171
152
|
const app = (await currentRunner.import(entry)).default;
|
|
172
|
-
await
|
|
153
|
+
await writeAppContract(app, entry, output);
|
|
173
154
|
dashboard?.architecture(requireBrickApp(app));
|
|
174
155
|
} finally {
|
|
175
156
|
collectDependencies(this.environment.moduleGraph.getModuleById(entry));
|
|
@@ -205,7 +186,7 @@ function brickClient(options) {
|
|
|
205
186
|
try {
|
|
206
187
|
const environment = loader.environments.ssr;
|
|
207
188
|
if (!environment || !isRunnableDevEnvironment(environment)) throw new Error("Brick: missing build-time SSR loader.");
|
|
208
|
-
await
|
|
189
|
+
await writeAppContract((await environment.runner.import(entry)).default, entry, output);
|
|
209
190
|
} finally {
|
|
210
191
|
await loader.close();
|
|
211
192
|
}
|
|
@@ -225,11 +206,9 @@ installDevReporter({ url: ${JSON.stringify(dashboard.ingestUrl)} });
|
|
|
225
206
|
`;
|
|
226
207
|
}
|
|
227
208
|
if (id !== resolvedId) return;
|
|
228
|
-
return `${dashboard ? `import ${JSON.stringify(reporterId)};\n` : ""}import
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
}
|
|
232
|
-
export default app;
|
|
209
|
+
return `${dashboard ? `import ${JSON.stringify(reporterId)};\n` : ""}import { requireBrickApp } from "@brickkit/core";
|
|
210
|
+
import app from ${JSON.stringify(entry)};
|
|
211
|
+
export default requireBrickApp(app);
|
|
233
212
|
`;
|
|
234
213
|
}
|
|
235
214
|
};
|
package/dist/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.js","names":[],"sources":["../src/dev-vite-dashboard.ts","../src/vite.ts"],"sourcesContent":["import { dirname } from \"node:path\";\nimport {\n getGlobalRegistry,\n type ApiDocument,\n type BrickApp,\n} from \"@brickkit/core\";\nimport {\n DEFAULT_DASHBOARD_PORT,\n startDevDashboard,\n type DevDashboard,\n} from \"./dev-dashboard\";\nimport { DocsHost } from \"./dev-docs\";\nimport type { DashboardExtensionOptions } from \"./dashboard-extension\";\nimport { DEFAULT_HISTORY_DAYS, openHistory } from \"./dev-history\";\nimport { DevTelemetryStore } from \"./dev-telemetry-store\";\n\nexport interface DashboardLogger {\n info(message: string): void;\n warn(message: string): void;\n}\n\nexport interface ViteDashboard {\n /** Where the app reports its spans; see installDevReporter. */\n readonly ingestUrl: string;\n /** Record the architecture of the application module Vite loaded. */\n architecture(app: BrickApp): void;\n /** Where the dev server is reachable, once it is listening. */\n origin(url: string): void;\n stop(): void;\n}\n\n/**\n * Serve the dashboard from inside the Vite dev server. Dev servers run the app\n * in a worker, which reports its spans here over HTTP. This process keeps the\n * history, so it survives worker restarts.\n */\nexport async function startViteDashboard(options: {\n port?: number;\n /** The project folder; history is kept in `.brick/` inside it. */\n directory: string;\n /** The app entry module; the paths in `documentation` start at its folder. */\n entry: string;\n /** Days of requests to keep on disk; zero for none. */\n historyDays?: number;\n /** The extension (an absolute path) and theme. */\n dashboard?: DashboardExtensionOptions;\n logger: DashboardLogger;\n}): Promise<ViteDashboard | undefined> {\n const history = await openHistory({\n directory: options.directory,\n days: options.historyDays ?? DEFAULT_HISTORY_DAYS,\n warn: (message) => options.logger.warn(message),\n });\n const store = new DevTelemetryStore({ history });\n const docs = new DocsHost(store, (message) => options.logger.warn(message));\n let dashboard: DevDashboard;\n try {\n dashboard = await startDevDashboard({\n port: options.port ?? DEFAULT_DASHBOARD_PORT,\n store,\n history,\n docs: () => docs.current,\n dashboard: options.dashboard,\n });\n } catch (error) {\n history?.close();\n const reason = error instanceof Error ? error.message : String(error);\n options.logger.warn(\n `[Brick-TS] ${reason} Continuing without the dashboard.`,\n );\n return undefined;\n }\n options.logger.info(\n ` ➜ Brick dashboard: http://127.0.0.1:${dashboard.port}`,\n );\n\n let stopped = false;\n let origin: string | undefined;\n let documents: ApiDocument[] | undefined;\n let loads = 0;\n // The server starts listening after the app first loads, so the documents\n // are published again once its address is known.\n const publishDocuments = () => {\n if (documents) store.setApiDocuments(documents, origin);\n };\n return {\n ingestUrl: `http://127.0.0.1:${dashboard.port}/api/ingest`,\n architecture(app) {\n store.setArchitecture(\n getGlobalRegistry().exportArchitecture(app.definition),\n store.latestGeneration,\n );\n void docs.configure(dirname(options.entry), app.definition.documentation);\n // A later load supersedes this one if it finishes first.\n const load = ++loads;\n app.referenceDocuments().then(\n (loaded) => {\n if (load !== loads || stopped) return;\n documents = loaded;\n publishDocuments();\n },\n (error: unknown) =>\n options.logger.warn(\n `[Brick-TS] Could not load the API documents: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n },\n origin(url) {\n origin = url;\n publishDocuments();\n },\n stop() {\n if (stopped) return;\n stopped = true;\n dashboard.stop();\n docs.close();\n history?.close();\n },\n };\n}\n","import { resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { writeContractSource } from \"./client-contract-file\";\nimport {\n createServer,\n isRunnableDevEnvironment,\n normalizePath,\n type Plugin,\n type ResolvedConfig,\n type EnvironmentModuleNode,\n} from \"vite\";\nimport { generateClientContract } from \"./client-contract\";\nimport { requireBrickApp } from \"./app-entry\";\nimport { startViteDashboard, type ViteDashboard } from \"./dev-vite-dashboard\";\nimport {\n themeCss,\n type DashboardExtensionOptions,\n type DashboardTheme,\n} from \"./dashboard-extension\";\n\nexport type { DashboardTheme };\nimport { ModuleRunner } from \"vite/module-runner\";\n\nexport interface BrickClientPluginOptions {\n /** Any module whose default export is a BrickApp; do not call listen() there. */\n entry: string;\n /** Generated browser contract, relative to the Vite root (default _brick/contract.ts). */\n output?: string;\n /**\n * Local dashboard for the app's requests, traces, errors, and reloads, served\n * during `vite dev` (default: on at port 9400). Apps must pass\n * `telemetry: true` to brick() to record requests. `historyDays` is how long\n * finished requests are kept in `.brick/` (default 90, 0 for none). Set to\n * false to disable. `extension` (relative to the Vite root) and `theme`\n * customise it, as in `brick dev`.\n */\n dashboard?:\n | ({ port?: number; historyDays?: number } & DashboardExtensionOptions)\n | false;\n}\n\n/** Load a BrickApp through Vite's server module graph, including dependency HMR. */\nexport function brickClient(options: BrickClientPluginOptions): Plugin {\n const virtualId = \"virtual:brick-app\";\n const resolvedId = \"\\0\" + virtualId;\n const reporterId = \"virtual:brick-dev-reporter\";\n const resolvedReporterId = \"\\0\" + reporterId;\n // Imported by file path: the package name may not resolve from the app's root.\n const reporterModule = fileURLToPath(\n new URL(\n import.meta.url.endsWith(\".ts\")\n ? \"./dev-reporter.ts\"\n : \"./dev-reporter.js\",\n import.meta.url,\n ),\n );\n let entry: string;\n let output: string;\n let config: ResolvedConfig;\n let buildGeneration: Promise<void> | undefined;\n let runner: ModuleRunner | undefined;\n let dashboard: ViteDashboard | undefined;\n let reload = Promise.resolve();\n const dependencies = new Set<string>();\n let revision = 0;\n const changedFiles = new Set<string>();\n\n async function writeContract(value: unknown) {\n const source = generateClientContract(requireBrickApp(value));\n await writeContractSource(output, source);\n }\n\n function collectDependencies(\n node: EnvironmentModuleNode | undefined,\n seen = new Set<EnvironmentModuleNode>(),\n ) {\n if (!node || seen.has(node)) return;\n seen.add(node);\n if (node.file) dependencies.add(node.file);\n for (const imported of node.importedModules)\n collectDependencies(imported, seen);\n }\n\n return {\n name: \"brick:client\",\n enforce: \"pre\",\n configResolved(resolved) {\n config = resolved;\n entry = normalizePath(resolve(config.root, options.entry));\n output = normalizePath(\n resolve(config.root, options.output ?? \"_brick/contract.ts\"),\n );\n if (entry === output)\n throw new Error(\n \"Brick: contract output must not overwrite the app entry.\",\n );\n if (options.dashboard) themeCss(options.dashboard.theme);\n },\n async configureServer(server) {\n const environment = server.environments.ssr;\n if (!environment)\n throw new Error(\n \"Brick: client generation requires a Vite SSR environment.\",\n );\n // Frameworks such as Start own their SSR runner. Use an independent runner\n // on the same transform graph to read app metadata without changing theirs.\n runner = new ModuleRunner({\n hmr: false,\n transport: {\n invoke: (payload) => environment.hot.handleInvoke(payload),\n },\n });\n // The dashboard starts before the app is evaluated, so its tracer is\n // registered before the app's first request can be made.\n if (options.dashboard !== false) {\n const started = await startViteDashboard({\n port: options.dashboard?.port,\n historyDays: options.dashboard?.historyDays,\n dashboard: {\n extension: options.dashboard?.extension\n ? resolve(server.config.root, options.dashboard.extension)\n : undefined,\n theme: options.dashboard?.theme,\n },\n directory: server.config.root,\n entry,\n logger: server.config.logger,\n });\n dashboard = started;\n server.httpServer?.once(\"close\", () => started?.stop());\n server.httpServer?.once(\"listening\", () => {\n const address = server.httpServer?.address();\n if (address && typeof address === \"object\") {\n const scheme = server.config.server.https ? \"https\" : \"http\";\n started?.origin(`${scheme}://localhost:${address.port}`);\n }\n });\n }\n const app = (await runner.import(entry)).default;\n await writeContract(app);\n dashboard?.architecture(requireBrickApp(app));\n dependencies.clear();\n collectDependencies(environment.moduleGraph.getModuleById(entry));\n dependencies.add(entry);\n },\n async hotUpdate(context) {\n if (\n this.environment.name !== \"ssr\" ||\n !dependencies.has(context.file) ||\n context.file === output\n )\n return;\n if (!runner) return;\n const currentRunner = runner;\n const currentRevision = ++revision;\n changedFiles.add(context.file);\n reload = reload\n .catch(() => {})\n .then(async () => {\n await new Promise((done) => setTimeout(done, 30));\n if (currentRevision !== revision) return;\n for (const module of context.modules)\n this.environment.moduleGraph.invalidateModule(module);\n const graph = currentRunner.evaluatedModules;\n const seen = new Set<string>();\n const invalidate = (id: string) => {\n if (seen.has(id)) return;\n seen.add(id);\n const node = graph.getModuleById(id);\n if (!node) return;\n for (const importer of node.importers) invalidate(importer);\n // Registration modules mutate imported services. Reevaluate their\n // dependencies too so removed actions cannot survive in a singleton.\n for (const imported of node.imports) invalidate(imported);\n graph.invalidateModule(node);\n };\n for (const file of changedFiles) {\n for (const node of graph.getModulesByFile(file) ?? [])\n invalidate(node.id);\n }\n changedFiles.clear();\n invalidate(entry);\n try {\n const app = (await currentRunner.import(entry)).default;\n await writeContract(app);\n dashboard?.architecture(requireBrickApp(app));\n } finally {\n collectDependencies(\n this.environment.moduleGraph.getModuleById(entry),\n );\n }\n dependencies.clear();\n collectDependencies(\n this.environment.moduleGraph.getModuleById(entry),\n );\n dependencies.add(entry);\n });\n await reload;\n },\n async closeBundle() {\n await runner?.close();\n dashboard?.stop();\n },\n async buildStart() {\n if (config.command !== \"build\") return;\n buildGeneration ??= (async () => {\n // Evaluate the server entry through Vite's TS/alias resolver before client compilation.\n // This loader has no app plugins, so it cannot recursively trigger generation.\n const loader = await createServer({\n configFile: false,\n root: config.root,\n mode: config.mode,\n envDir: config.envDir,\n base: config.base,\n define: config.define,\n logLevel: \"silent\",\n resolve: { alias: config.resolve.alias },\n ssr: config.ssr,\n server: { middlewareMode: true, watch: null },\n });\n try {\n const environment = loader.environments.ssr;\n if (!environment || !isRunnableDevEnvironment(environment))\n throw new Error(\"Brick: missing build-time SSR loader.\");\n await writeContract((await environment.runner.import(entry)).default);\n } finally {\n await loader.close();\n }\n })();\n await buildGeneration;\n },\n resolveId(id) {\n if (id !== virtualId && id !== reporterId) return;\n if (this.environment.config.consumer === \"client\") {\n throw new Error(\n \"Brick: virtual:brick-app is server-only; never import the backend app in the browser.\",\n );\n }\n return id === virtualId ? resolvedId : resolvedReporterId;\n },\n load(id) {\n if (id === resolvedReporterId) {\n // The app imports the reporter only while the dashboard is running.\n if (!dashboard) return \"\";\n return `import { installDevReporter } from ${JSON.stringify(reporterModule)};\ninstallDevReporter({ url: ${JSON.stringify(dashboard.ingestUrl)} });\n`;\n }\n if (id !== resolvedId) return;\n // The reporter is imported first so tracing is installed before the app is built.\n const reporter = dashboard\n ? `import ${JSON.stringify(reporterId)};\\n`\n : \"\";\n return `${reporter}import app from ${JSON.stringify(entry)};\nif (!app || typeof app.fetch !== \"function\" || typeof app.endpoint !== \"function\") {\n throw new Error(\"Brick: the entry module must default-export a BrickApp created by brick().\");\n}\nexport default app;\n`;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoCA,eAAsB,mBAAmB,SAWF;CACrC,MAAM,UAAU,MA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;IACD,IAAI;KACF,MAAM,cAAc,OAAO,aAAa;KACxC,IAAI,CAAC,eAAe,CAAC,yBAAyB,WAAW,GACvD,MAAM,IAAI,MAAM,uCAAuC;KACzD,MAAM,eAAe,MAAM,YAAY,OAAO,OAAO,KAAK,EAAA,CAAG,OAAO;IACtE,UAAU;KACR,MAAM,OAAO,MAAM;IACrB;GACF,EAAA,CAAG;GACH,MAAM;EACR;EACA,UAAU,IAAI;GACZ,IAAI,OAAO,aAAa,OAAO,YAAY;GAC3C,IAAI,KAAK,YAAY,OAAO,aAAa,UACvC,MAAM,IAAI,MACR,uFACF;GAEF,OAAO,OAAO,YAAY,aAAa;EACzC;EACA,KAAK,IAAI;GACP,IAAI,OAAO,oBAAoB;IAE7B,IAAI,CAAC,WAAW,OAAO;IACvB,OAAO,sCAAsC,KAAK,UAAU,cAAc,EAAE;4BACxD,KAAK,UAAU,UAAU,SAAS,EAAE;;GAE1D;GACA,IAAI,OAAO,YAAY;GAKvB,OAAO,GAHU,YACb,UAAU,KAAK,UAAU,UAAU,EAAE,OACrC,GACe,kBAAkB,KAAK,UAAU,KAAK,EAAE;;;;;;EAM7D;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../src/dev-vite-dashboard.ts","../src/vite.ts"],"sourcesContent":["import { dirname } from \"node:path\";\nimport {\n getGlobalRegistry,\n type ApiDocument,\n type BrickApp,\n} from \"@brickkit/core\";\nimport { openDashboard } from \"./dashboard-host\";\nimport { ROUTES } from \"./dashboard-protocol\";\nimport type { DashboardExtensionOptions } from \"./dashboard-extension\";\n\nexport interface DashboardLogger {\n info(message: string): void;\n warn(message: string): void;\n}\n\nexport interface ViteDashboard {\n /** Where the app reports its spans; see installDevReporter. */\n readonly ingestUrl: string;\n /** Record the architecture of the application module Vite loaded. */\n architecture(app: BrickApp): void;\n /** Where the dev server is reachable, once it is listening. */\n origin(url: string): void;\n stop(): void;\n}\n\n/**\n * Serve the dashboard from inside the Vite dev server. Dev servers run the app\n * in a worker, which reports its spans here over HTTP. This process keeps the\n * history, so it survives worker restarts.\n */\nexport async function startViteDashboard(options: {\n port?: number;\n /** The project folder; history is kept in `.brick/` inside it. */\n directory: string;\n /** The app entry module; the paths in `documentation` start at its folder. */\n entry: string;\n /** Days of requests to keep on disk; zero for none. */\n historyDays?: number;\n /** The extension (an absolute path) and theme. */\n dashboard?: DashboardExtensionOptions;\n logger: DashboardLogger;\n}): Promise<ViteDashboard | undefined> {\n const dashboard = await openDashboard({\n port: options.port,\n directory: options.directory,\n historyDays: options.historyDays,\n warn: (message) => options.logger.warn(message),\n docs: true,\n dashboard: options.dashboard,\n portHint:\n \"Set dashboard.port in brickClient() to another, or dashboard: false.\",\n });\n if (!dashboard) return undefined;\n const { store, docs } = dashboard;\n options.logger.info(\n ` ➜ Brick dashboard: http://127.0.0.1:${dashboard.port}`,\n );\n\n let stopped = false;\n let origin: string | undefined;\n let documents: ApiDocument[] | undefined;\n let loads = 0;\n // The server starts listening after the app first loads, so the documents\n // are published again once its address is known.\n const publishDocuments = () => {\n if (documents) store.setApiDocuments(documents, origin);\n };\n return {\n ingestUrl: `http://127.0.0.1:${dashboard.port}${ROUTES.ingest.path}`,\n architecture(app) {\n store.setArchitecture(\n getGlobalRegistry().exportArchitecture(app.definition),\n store.latestGeneration,\n );\n void docs?.configure(\n dirname(options.entry),\n app.definition.documentation,\n );\n // A later load supersedes this one if it finishes first.\n const load = ++loads;\n app.referenceDocuments().then(\n (loaded) => {\n if (load !== loads || stopped) return;\n documents = loaded;\n publishDocuments();\n },\n (error: unknown) =>\n options.logger.warn(\n `[Brick-TS] Could not load the API documents: ${error instanceof Error ? error.message : String(error)}`,\n ),\n );\n },\n origin(url) {\n origin = url;\n publishDocuments();\n },\n stop() {\n if (stopped) return;\n stopped = true;\n dashboard.stop();\n },\n };\n}\n","import { join, resolve } from \"node:path\";\nimport { writeAppContract } from \"./client-contract-file\";\nimport { CONTRACT_FILE, PROJECT_DEFAULTS } from \"./config\";\nimport { ownModule } from \"./own-module\";\nimport {\n createServer,\n isRunnableDevEnvironment,\n normalizePath,\n type Plugin,\n type ResolvedConfig,\n type EnvironmentModuleNode,\n} from \"vite\";\nimport { requireBrickApp } from \"@brickkit/core\";\nimport { startViteDashboard, type ViteDashboard } from \"./dev-vite-dashboard\";\nimport type {\n DashboardExtensionOptions,\n DashboardTheme,\n} from \"./dashboard-extension\";\nimport { ModuleRunner } from \"vite/module-runner\";\n\nexport type { DashboardTheme };\n\nexport interface BrickClientPluginOptions {\n /** Any module whose default export is a BrickApp; do not call listen() there. */\n entry: string;\n /** Generated browser contract, relative to the Vite root (default _brick/contract.ts). */\n output?: string;\n /**\n * Local dashboard for the app's requests, traces, errors, and reloads, served\n * during `vite dev` (default: on at port 9400). Apps must pass\n * `telemetry: true` to brick() to record requests. `historyDays` is how long\n * finished requests are kept in `.brick/` (default 90, 0 for none). Set to\n * false to disable. `extension` (relative to the Vite root) and `theme`\n * customise it, as in `brick dev`.\n */\n dashboard?:\n | ({ port?: number; historyDays?: number } & DashboardExtensionOptions)\n | false;\n}\n\n/** Load a BrickApp through Vite's server module graph, including dependency HMR. */\nexport function brickClient(options: BrickClientPluginOptions): Plugin {\n const virtualId = \"virtual:brick-app\";\n const resolvedId = \"\\0\" + virtualId;\n const reporterId = \"virtual:brick-dev-reporter\";\n const resolvedReporterId = \"\\0\" + reporterId;\n // Imported by file path: the package name may not resolve from the app's root.\n const reporterModule = ownModule(\"dev-reporter\");\n let entry: string;\n let output: string;\n let config: ResolvedConfig;\n let buildGeneration: Promise<void> | undefined;\n let runner: ModuleRunner | undefined;\n let dashboard: ViteDashboard | undefined;\n let reload = Promise.resolve();\n const dependencies = new Set<string>();\n let revision = 0;\n const changedFiles = new Set<string>();\n\n function collectDependencies(\n node: EnvironmentModuleNode | undefined,\n seen = new Set<EnvironmentModuleNode>(),\n ) {\n if (!node || seen.has(node)) return;\n seen.add(node);\n if (node.file) dependencies.add(node.file);\n for (const imported of node.importedModules)\n collectDependencies(imported, seen);\n }\n\n return {\n name: \"brick:client\",\n enforce: \"pre\",\n configResolved(resolved) {\n config = resolved;\n entry = normalizePath(resolve(config.root, options.entry));\n output = normalizePath(\n resolve(\n config.root,\n options.output ?? join(PROJECT_DEFAULTS.generated, CONTRACT_FILE),\n ),\n );\n },\n async configureServer(server) {\n const environment = server.environments.ssr;\n if (!environment)\n throw new Error(\n \"Brick: client generation requires a Vite SSR environment.\",\n );\n // Frameworks such as Start own their SSR runner. Use an independent runner\n // on the same transform graph to read app metadata without changing theirs.\n runner = new ModuleRunner({\n hmr: false,\n transport: {\n invoke: (payload) => environment.hot.handleInvoke(payload),\n },\n });\n // The dashboard starts before the app is evaluated, so its tracer is\n // registered before the app's first request can be made.\n if (options.dashboard !== false) {\n const started = await startViteDashboard({\n port: options.dashboard?.port,\n historyDays: options.dashboard?.historyDays,\n dashboard: {\n extension: options.dashboard?.extension\n ? resolve(server.config.root, options.dashboard.extension)\n : undefined,\n theme: options.dashboard?.theme,\n },\n directory: server.config.root,\n entry,\n logger: server.config.logger,\n });\n dashboard = started;\n server.httpServer?.once(\"close\", () => started?.stop());\n server.httpServer?.once(\"listening\", () => {\n const address = server.httpServer?.address();\n if (address && typeof address === \"object\") {\n const scheme = server.config.server.https ? \"https\" : \"http\";\n started?.origin(`${scheme}://localhost:${address.port}`);\n }\n });\n }\n const app = (await runner.import(entry)).default;\n await writeAppContract(app, entry, output);\n dashboard?.architecture(requireBrickApp(app));\n dependencies.clear();\n collectDependencies(environment.moduleGraph.getModuleById(entry));\n dependencies.add(entry);\n },\n async hotUpdate(context) {\n if (\n this.environment.name !== \"ssr\" ||\n !dependencies.has(context.file) ||\n context.file === output\n )\n return;\n if (!runner) return;\n const currentRunner = runner;\n const currentRevision = ++revision;\n changedFiles.add(context.file);\n reload = reload\n .catch(() => {})\n .then(async () => {\n await new Promise((done) => setTimeout(done, 30));\n if (currentRevision !== revision) return;\n for (const module of context.modules)\n this.environment.moduleGraph.invalidateModule(module);\n const graph = currentRunner.evaluatedModules;\n const seen = new Set<string>();\n const invalidate = (id: string) => {\n if (seen.has(id)) return;\n seen.add(id);\n const node = graph.getModuleById(id);\n if (!node) return;\n for (const importer of node.importers) invalidate(importer);\n // Registration modules mutate imported services. Reevaluate their\n // dependencies too so removed actions cannot survive in a singleton.\n for (const imported of node.imports) invalidate(imported);\n graph.invalidateModule(node);\n };\n for (const file of changedFiles) {\n for (const node of graph.getModulesByFile(file) ?? [])\n invalidate(node.id);\n }\n changedFiles.clear();\n invalidate(entry);\n try {\n const app = (await currentRunner.import(entry)).default;\n await writeAppContract(app, entry, output);\n dashboard?.architecture(requireBrickApp(app));\n } finally {\n collectDependencies(\n this.environment.moduleGraph.getModuleById(entry),\n );\n }\n dependencies.clear();\n collectDependencies(\n this.environment.moduleGraph.getModuleById(entry),\n );\n dependencies.add(entry);\n });\n await reload;\n },\n async closeBundle() {\n await runner?.close();\n dashboard?.stop();\n },\n async buildStart() {\n if (config.command !== \"build\") return;\n buildGeneration ??= (async () => {\n // Evaluate the server entry through Vite's TS/alias resolver before client compilation.\n // This loader has no app plugins, so it cannot recursively trigger generation.\n const loader = await createServer({\n configFile: false,\n root: config.root,\n mode: config.mode,\n envDir: config.envDir,\n base: config.base,\n define: config.define,\n logLevel: \"silent\",\n resolve: { alias: config.resolve.alias },\n ssr: config.ssr,\n server: { middlewareMode: true, watch: null },\n });\n try {\n const environment = loader.environments.ssr;\n if (!environment || !isRunnableDevEnvironment(environment))\n throw new Error(\"Brick: missing build-time SSR loader.\");\n await writeAppContract(\n (await environment.runner.import(entry)).default,\n entry,\n output,\n );\n } finally {\n await loader.close();\n }\n })();\n await buildGeneration;\n },\n resolveId(id) {\n if (id !== virtualId && id !== reporterId) return;\n if (this.environment.config.consumer === \"client\") {\n throw new Error(\n \"Brick: virtual:brick-app is server-only; never import the backend app in the browser.\",\n );\n }\n return id === virtualId ? resolvedId : resolvedReporterId;\n },\n load(id) {\n if (id === resolvedReporterId) {\n if (!dashboard) return \"\";\n return `import { installDevReporter } from ${JSON.stringify(reporterModule)};\ninstallDevReporter({ url: ${JSON.stringify(dashboard.ingestUrl)} });\n`;\n }\n if (id !== resolvedId) return;\n // The reporter is imported first so tracing is installed before the app is built.\n const reporter = dashboard\n ? `import ${JSON.stringify(reporterId)};\\n`\n : \"\";\n return `${reporter}import { requireBrickApp } from \"@brickkit/core\";\nimport app from ${JSON.stringify(entry)};\nexport default requireBrickApp(app);\n`;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,eAAsB,mBAAmB,SAWF;CACrC,MAAM,YAAY,MAAM,cAAc;EACpC,MAAM,QAAQ;EACd,WAAW,QAAQ;EACnB,aAAa,QAAQ;EACrB,OAAO,YAAY,QAAQ,OAAO,KAAK,OAAO;EAC9C,MAAM;EACN,WAAW,QAAQ;EACnB,UACE;CACJ,CAAC;CACD,IAAI,CAAC,WAAW,OAAO,KAAA;CACvB,MAAM,EAAE,OAAO,SAAS;CACxB,QAAQ,OAAO,KACb,0CAA0C,UAAU,MACtD;CAEA,IAAI,UAAU;CACd,IAAI;CACJ,IAAI;CACJ,IAAI,QAAQ;CAGZ,MAAM,yBAAyB;EAC7B,IAAI,WAAW,MAAM,gBAAgB,WAAW,MAAM;CACxD;CACA,OAAO;EACL,WAAW,oBAAoB,UAAU,OAAO,OAAO,OAAO;EAC9D,aAAa,KAAK;GAChB,MAAM,gBACJ,kBAAkB,CAAC,CAAC,mBAAmB,IAAI,UAAU,GACrD,MAAM,gBACR;GACA,MAAW,UACT,QAAQ,QAAQ,KAAK,GACrB,IAAI,WAAW,aACjB;GAEA,MAAM,OAAO,EAAE;GACf,IAAI,mBAAmB,CAAC,CAAC,MACtB,WAAW;IACV,IAAI,SAAS,SAAS,SAAS;IAC/B,YAAY;IACZ,iBAAiB;GACnB,IACC,UACC,QAAQ,OAAO,KACb,gDAAgD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACvG,CACJ;EACF;EACA,OAAO,KAAK;GACV,SAAS;GACT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CAAG,SACzC,OACA,MACF;IACF,UAAU;KACR,MAAM,OAAO,MAAM;IACrB;GACF,EAAA,CAAG;GACH,MAAM;EACR;EACA,UAAU,IAAI;GACZ,IAAI,OAAO,aAAa,OAAO,YAAY;GAC3C,IAAI,KAAK,YAAY,OAAO,aAAa,UACvC,MAAM,IAAI,MACR,uFACF;GAEF,OAAO,OAAO,YAAY,aAAa;EACzC;EACA,KAAK,IAAI;GACP,IAAI,OAAO,oBAAoB;IAC7B,IAAI,CAAC,WAAW,OAAO;IACvB,OAAO,sCAAsC,KAAK,UAAU,cAAc,EAAE;4BACxD,KAAK,UAAU,UAAU,SAAS,EAAE;;GAE1D;GACA,IAAI,OAAO,YAAY;GAKvB,OAAO,GAHU,YACb,UAAU,KAAK,UAAU,UAAU,EAAE,OACrC,GACe;kBACP,KAAK,UAAU,KAAK,EAAE;;;EAGpC;CACF;AACF"}
|
package/dist/workflows.d.ts
CHANGED
|
@@ -19,8 +19,8 @@ export declare function workflowTransformPlugin(root?: string): Promise<BunPlugi
|
|
|
19
19
|
* Call it in a script or test before importing the files, with the project root.
|
|
20
20
|
*
|
|
21
21
|
* It does nothing, and returns `false`, when the Workflow SDK and its builders are
|
|
22
|
-
* not installed in the project.
|
|
23
|
-
*
|
|
22
|
+
* not installed in the project. Each root gets ids relative to itself; a file
|
|
23
|
+
* under no registered root uses the first one.
|
|
24
24
|
*
|
|
25
25
|
* @param root - The project root, where the SDK is installed. Default: the working directory.
|
|
26
26
|
* @returns Whether the transform is active.
|
package/dist/workflows2.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import { n as ConfigError } from "./config2.js";
|
|
1
2
|
import { createRequire } from "node:module";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { WORKFLOW_BUNDLE, resolveWorkflowPaths } from "@brickkit/core";
|
|
2
6
|
import { pathToFileURL } from "node:url";
|
|
3
|
-
import { resolveWorkflowPaths } from "@brickkit/core";
|
|
4
7
|
import { readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
5
|
-
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
6
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
7
8
|
// src/workflows.ts
|
|
8
9
|
const DIRECTIVE = /["']use (?:step|workflow)["']/;
|
|
9
10
|
/**
|
|
@@ -11,7 +12,7 @@ const DIRECTIVE = /["']use (?:step|workflow)["']/;
|
|
|
11
12
|
* text inside the SDK's own code and is already built. Not `.cjs` and `.cts`
|
|
12
13
|
* either: Bun drops `module.exports` from a file a plugin loads.
|
|
13
14
|
*/
|
|
14
|
-
const TRANSFORMED = new RegExp(String.raw`^(?!.*(?:node_modules
|
|
15
|
+
const TRANSFORMED = new RegExp(String.raw`^(?!.*(?:node_modules|${WORKFLOW_BUNDLE.dir.replaceAll(".", "\\.")}/)).*\.(?:m?[jt]s|[jt]sx)$`);
|
|
15
16
|
/** Bun's own loader for each extension: JSX is allowed in `.js` but not in `.mjs`. */
|
|
16
17
|
function loaderFor(path) {
|
|
17
18
|
if (path.endsWith(".tsx")) return "tsx";
|
|
@@ -19,15 +20,16 @@ function loaderFor(path) {
|
|
|
19
20
|
return path.endsWith(".mjs") ? "js" : "jsx";
|
|
20
21
|
}
|
|
21
22
|
async function loadBuilders(root) {
|
|
23
|
+
let path;
|
|
22
24
|
try {
|
|
23
|
-
|
|
24
|
-
return {
|
|
25
|
-
builders: await import(pathToFileURL(path).href),
|
|
26
|
-
path
|
|
27
|
-
};
|
|
25
|
+
path = createRequire(join(root, "package.json")).resolve("@workflow/builders");
|
|
28
26
|
} catch {
|
|
29
27
|
return;
|
|
30
28
|
}
|
|
29
|
+
return {
|
|
30
|
+
builders: await import(pathToFileURL(path).href),
|
|
31
|
+
path
|
|
32
|
+
};
|
|
31
33
|
}
|
|
32
34
|
/**
|
|
33
35
|
* The plugin that turns `"use workflow"` and `"use step"` files into workflows and
|
|
@@ -39,27 +41,40 @@ async function loadBuilders(root) {
|
|
|
39
41
|
* installed in the project.
|
|
40
42
|
*/
|
|
41
43
|
async function workflowTransformPlugin(root = process.cwd()) {
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
if (!builders) return void 0;
|
|
44
|
+
const load = await transformer(root);
|
|
45
|
+
if (!load) return void 0;
|
|
45
46
|
return {
|
|
46
47
|
name: "brick:workflows",
|
|
47
48
|
setup(build) {
|
|
48
|
-
build.onLoad({ filter: TRANSFORMED },
|
|
49
|
-
const source = readFileSync(args.path, "utf8");
|
|
50
|
-
if (!DIRECTIVE.test(source)) return {
|
|
51
|
-
contents: source,
|
|
52
|
-
loader: loaderFor(args.path)
|
|
53
|
-
};
|
|
54
|
-
return builders.applySwcTransform(relative(projectRoot, args.path).replaceAll("\\", "/"), source, "step", args.path, projectRoot, projectRoot).then(({ code }) => ({
|
|
55
|
-
contents: code,
|
|
56
|
-
loader: "jsx"
|
|
57
|
-
}));
|
|
58
|
-
});
|
|
49
|
+
build.onLoad({ filter: TRANSFORMED }, load);
|
|
59
50
|
}
|
|
60
51
|
};
|
|
61
52
|
}
|
|
62
|
-
|
|
53
|
+
/** The transform for files of the project at `root`, or `undefined` without the SDK. */
|
|
54
|
+
async function transformer(root) {
|
|
55
|
+
const projectRoot = resolve(root);
|
|
56
|
+
const builders = (await loadBuilders(projectRoot))?.builders;
|
|
57
|
+
if (!builders) return void 0;
|
|
58
|
+
return (args) => {
|
|
59
|
+
const source = readFileSync(args.path, "utf8");
|
|
60
|
+
if (!DIRECTIVE.test(source)) return {
|
|
61
|
+
contents: source,
|
|
62
|
+
loader: loaderFor(args.path)
|
|
63
|
+
};
|
|
64
|
+
return builders.applySwcTransform(relative(projectRoot, args.path).replaceAll("\\", "/"), source, "step", args.path, projectRoot, projectRoot).then(({ code }) => ({
|
|
65
|
+
contents: code,
|
|
66
|
+
loader: "jsx"
|
|
67
|
+
}));
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** The transform of each root registered in this process. */
|
|
71
|
+
const registered = /* @__PURE__ */ new Map();
|
|
72
|
+
/** The registered root a file belongs to: the innermost that holds it, else the first. */
|
|
73
|
+
function rootOf(file) {
|
|
74
|
+
let found;
|
|
75
|
+
for (const root of registered.keys()) if (file.startsWith(root + sep) && root.length > (found?.length ?? -1)) found = root;
|
|
76
|
+
return found ?? registered.keys().next().value;
|
|
77
|
+
}
|
|
63
78
|
/**
|
|
64
79
|
* Make files marked `"use workflow"` or `"use step"` load as workflows and steps.
|
|
65
80
|
*
|
|
@@ -69,18 +84,24 @@ let installed = false;
|
|
|
69
84
|
* Call it in a script or test before importing the files, with the project root.
|
|
70
85
|
*
|
|
71
86
|
* It does nothing, and returns `false`, when the Workflow SDK and its builders are
|
|
72
|
-
* not installed in the project.
|
|
73
|
-
*
|
|
87
|
+
* not installed in the project. Each root gets ids relative to itself; a file
|
|
88
|
+
* under no registered root uses the first one.
|
|
74
89
|
*
|
|
75
90
|
* @param root - The project root, where the SDK is installed. Default: the working directory.
|
|
76
91
|
* @returns Whether the transform is active.
|
|
77
92
|
*/
|
|
78
93
|
async function registerWorkflowTransform(root = process.cwd()) {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
94
|
+
const projectRoot = resolve(root);
|
|
95
|
+
if (registered.has(projectRoot)) return true;
|
|
96
|
+
const load = await transformer(projectRoot);
|
|
97
|
+
if (!load) return false;
|
|
98
|
+
registered.set(projectRoot, load);
|
|
99
|
+
if (registered.size === 1) Bun.plugin({
|
|
100
|
+
name: "brick:workflows",
|
|
101
|
+
setup(build) {
|
|
102
|
+
build.onLoad({ filter: TRANSFORMED }, (args) => registered.get(rootOf(args.path))(args));
|
|
103
|
+
}
|
|
104
|
+
});
|
|
84
105
|
return true;
|
|
85
106
|
}
|
|
86
107
|
/** The state of the last build, kept beside the bundle it describes. */
|
|
@@ -234,19 +255,19 @@ async function buildWorkflows(options = {}) {
|
|
|
234
255
|
buildTarget: "standalone",
|
|
235
256
|
dirs: ["."],
|
|
236
257
|
workingDir: root,
|
|
237
|
-
stepsBundlePath: output(
|
|
238
|
-
workflowsBundlePath: output(
|
|
239
|
-
webhookBundlePath: output(
|
|
258
|
+
stepsBundlePath: output(WORKFLOW_BUNDLE.steps),
|
|
259
|
+
workflowsBundlePath: output(WORKFLOW_BUNDLE.flow),
|
|
260
|
+
webhookBundlePath: output(WORKFLOW_BUNDLE.webhook),
|
|
240
261
|
suppressCreateWorkflowsBundleLogs: true,
|
|
241
262
|
suppressCreateWebhookBundleLogs: true,
|
|
242
263
|
suppressCreateManifestLogs: true
|
|
243
264
|
});
|
|
244
265
|
const statePath = join(dir, STATE_FILE);
|
|
245
|
-
const bundles = [
|
|
266
|
+
const bundles = [WORKFLOW_BUNDLE.flow, WORKFLOW_BUNDLE.steps].map((name) => join(dir, name));
|
|
246
267
|
const outputs = [
|
|
247
268
|
...bundles,
|
|
248
|
-
join(dir,
|
|
249
|
-
join(dir,
|
|
269
|
+
join(dir, WORKFLOW_BUNDLE.manifest),
|
|
270
|
+
join(dir, WORKFLOW_BUNDLE.webhook)
|
|
250
271
|
];
|
|
251
272
|
const configs = await tsconfigInputs(await builder.findTsConfigPath());
|
|
252
273
|
const key = JSON.stringify([
|
|
@@ -285,6 +306,7 @@ async function buildWorkflows(options = {}) {
|
|
|
285
306
|
async function buildAppWorkflows(app, options = {}) {
|
|
286
307
|
const target = app.events?.workflows;
|
|
287
308
|
if (!target) return false;
|
|
309
|
+
if (registered.size && !registered.has(resolve(target.root))) throw new ConfigError(`Brick: the app's workflows root ${target.root} is not the folder its workflow files were transformed from (${[...registered.keys()].join(", ")}). Run brick from the workflows root, or leave events.workflows.root unset.`);
|
|
288
310
|
const started = performance.now();
|
|
289
311
|
if (await buildWorkflows({
|
|
290
312
|
root: target.root,
|
package/dist/workflows2.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflows2.js","names":[],"sources":["../src/workflows.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, isAbsolute, join, relative, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { resolveWorkflowPaths, type BrickApp } from \"@brickkit/core\";\n\ninterface Builders {\n StandaloneBuilder: new (config: Record<string, unknown>) => {\n build(): Promise<void>;\n getInputFiles(): Promise<string[]>;\n findTsConfigPath(): Promise<string | undefined>;\n };\n detectWorkflowPatterns(source: string): {\n hasDirective: boolean;\n hasSerde: boolean;\n };\n applySwcTransform(\n filename: string,\n source: string,\n mode: \"step\" | \"workflow\" | \"detect\" | false,\n absolutePath: string,\n projectRoot: string,\n moduleSpecifierRoot?: string,\n ): Promise<{ code: string }>;\n}\n\ntype BunPlugin = Parameters<typeof Bun.plugin>[0];\n\nconst DIRECTIVE = /[\"']use (?:step|workflow)[\"']/;\n\n/**\n * Every project source file. Not the generated bundle: it holds the directives as\n * text inside the SDK's own code and is already built. Not `.cjs` and `.cts`\n * either: Bun drops `module.exports` from a file a plugin loads.\n */\nconst TRANSFORMED = new RegExp(\n String.raw`^(?!.*(?:node_modules|\\.well-known/workflow/)).*\\.(?:m?[jt]s|[jt]sx)$`,\n);\n\n/** Bun's own loader for each extension: JSX is allowed in `.js` but not in `.mjs`. */\nfunction loaderFor(path: string): \"ts\" | \"tsx\" | \"js\" | \"jsx\" {\n if (path.endsWith(\".tsx\")) return \"tsx\";\n if (/\\.m?ts$/.test(path)) return \"ts\";\n return path.endsWith(\".mjs\") ? \"js\" : \"jsx\";\n}\n\nasync function loadBuilders(\n root: string,\n): Promise<{ builders: Builders; path: string } | undefined> {\n try {\n const path = createRequire(join(root, \"package.json\")).resolve(\n \"@workflow/builders\",\n );\n return {\n builders: (await import(pathToFileURL(path).href)) as Builders,\n path,\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * The plugin that turns `\"use workflow\"` and `\"use step\"` files into workflows and\n * steps. `registerWorkflowTransform` installs it for the running process;\n * `brick build` hands it to `Bun.build`.\n *\n * @param root - The project root, where the SDK is installed. Default: the working directory.\n * @returns The plugin, or `undefined` when the Workflow SDK and its builders are not\n * installed in the project.\n */\nexport async function workflowTransformPlugin(\n root: string = process.cwd(),\n): Promise<BunPlugin | undefined> {\n const projectRoot = resolve(root);\n const builders = (await loadBuilders(projectRoot))?.builders;\n if (!builders) return undefined;\n return {\n name: \"brick:workflows\",\n setup(build) {\n // Not async: Bun treats a module whose load returns a promise as async, and\n // `require()` refuses it. Only a file with a directive waits for SWC.\n build.onLoad({ filter: TRANSFORMED }, (args) => {\n const source = readFileSync(args.path, \"utf8\");\n if (!DIRECTIVE.test(source))\n return { contents: source, loader: loaderFor(args.path) };\n // SWC strips the types but leaves JSX as it is.\n return builders\n .applySwcTransform(\n relative(projectRoot, args.path).replaceAll(\"\\\\\", \"/\"),\n source,\n \"step\",\n args.path,\n projectRoot,\n projectRoot,\n )\n .then(({ code }) => ({ contents: code, loader: \"jsx\" as const }));\n });\n },\n };\n}\n\nlet installed = false;\n\n/**\n * Make files marked `\"use workflow\"` or `\"use step\"` load as workflows and steps.\n *\n * A workflow function gets the `workflowId` that `defineListener({ workflow })`\n * needs, and a step registers itself so the runtime can run it in this process.\n * `brick dev`, `brick start` and `brick worker` call it before they load the app.\n * Call it in a script or test before importing the files, with the project root.\n *\n * It does nothing, and returns `false`, when the Workflow SDK and its builders are\n * not installed in the project. Bun allows plugins once per process, so a second\n * call is ignored.\n *\n * @param root - The project root, where the SDK is installed. Default: the working directory.\n * @returns Whether the transform is active.\n */\nexport async function registerWorkflowTransform(\n root: string = process.cwd(),\n): Promise<boolean> {\n if (installed) return true;\n const plugin = await workflowTransformPlugin(root);\n if (!plugin) return false;\n installed = true;\n Bun.plugin(plugin);\n return true;\n}\n\n/** The state of the last build, kept beside the bundle it describes. */\nconst STATE_FILE = \".brick-build.json\";\n/** Bump it when what the state records changes, so an older state is not trusted. */\nconst STATE_VERSION = 2;\n/**\n * esbuild starts each module of a bundle with a `// <path>` comment, whatever\n * the file (`data.json` too). The other comments it keeps name no file.\n */\nconst MODULE_COMMENT = /^\\/\\/ (.+)$/gm;\nconst LOCKFILES = [\n \"bun.lock\",\n \"bun.lockb\",\n \"package-lock.json\",\n \"pnpm-lock.yaml\",\n \"yarn.lock\",\n];\n\n/** A file's modification time and size, or an empty string when it is gone. */\ntype Stamps = Record<string, string>;\n\ninterface BuildState {\n key: string;\n /** Every source file the builder looks at. */\n sources: Stamps;\n /** The files the bundle holds or was built with; the bundle is stale when one changes. */\n inputs: Stamps;\n}\n\nasync function stamps(paths: Iterable<string>): Promise<Stamps> {\n const list = [...paths];\n const all = await Promise.all(\n list.map(async (path) => {\n try {\n const { mtimeMs, size } = await stat(path);\n return `${mtimeMs}:${size}`;\n } catch {\n return \"\";\n }\n }),\n );\n return Object.fromEntries(list.map((path, index) => [path, all[index]]));\n}\n\nfunction lockfileOf(root: string): string | undefined {\n for (let dir = root; ; dir = dirname(dir)) {\n for (const name of LOCKFILES)\n if (existsSync(join(dir, name))) return join(dir, name);\n if (dirname(dir) === dir) return undefined;\n }\n}\n\nasync function tsconfigInputs(path: string | undefined): Promise<string[]> {\n const files = new Set<string>();\n async function visit(file: string) {\n if (files.has(file)) return;\n files.add(file);\n let config: unknown;\n try {\n config = Bun.JSONC.parse(await readFile(file, \"utf8\"));\n } catch {\n return;\n }\n if (!config || typeof config !== \"object\" || !(\"extends\" in config)) return;\n const parents = Array.isArray(config.extends)\n ? config.extends\n : [config.extends];\n const require = createRequire(file);\n for (const parent of parents) {\n if (typeof parent !== \"string\") continue;\n // esbuild's order, which builds the bundle: a path as written, then with\n // .json; for a package, its tsconfig.json before `${parent}.json`, never `main`.\n const isPath =\n isAbsolute(parent) ||\n parent.startsWith(\"./\") ||\n parent.startsWith(\"../\");\n const candidates = isPath\n ? [parent, `${parent}.json`]\n : [`${parent}/tsconfig.json`, `${parent}.json`, parent];\n let found: string | undefined;\n for (const specifier of candidates) {\n try {\n found = require.resolve(specifier);\n } catch {\n continue;\n }\n if (found.endsWith(\".json\")) break;\n found = undefined;\n }\n // esbuild still reads the tsconfig.json of a package whose `exports` hides it.\n found ??= isPath\n ? undefined\n : require.resolve\n .paths(parent)\n ?.map((dir) => join(dir, parent, \"tsconfig.json\"))\n .find(existsSync);\n if (found) await visit(found);\n }\n }\n if (path) await visit(path);\n return [...files];\n}\n\n/**\n * Whether the bundle on disk still matches its sources: nothing it was built\n * from has changed, and no other source has come to hold a workflow, a step or a\n * serializable class that the bundle would need to know.\n */\nasync function isCurrent(\n statePath: string,\n key: string,\n sources: string[],\n builders: Builders,\n outputs: string[],\n): Promise<boolean> {\n let state: BuildState;\n try {\n state = JSON.parse(await readFile(statePath, \"utf8\")) as BuildState;\n } catch {\n return false;\n }\n if (state.key !== key || !outputs.every((file) => existsSync(file)))\n return false;\n // A file added or removed can change what an import resolves to.\n if (\n sources.length !== Object.keys(state.sources).length ||\n sources.some((path) => !(path in state.sources))\n )\n return false;\n const inputs = await stamps(Object.keys(state.inputs));\n if (\n Object.entries(state.inputs).some(([path, stamp]) => inputs[path] !== stamp)\n )\n return false;\n const others = sources.filter((path) => !(path in state.inputs));\n const now = await stamps(others);\n const changed = others.filter((path) => now[path] !== state.sources[path]);\n const holds = await Promise.all(\n changed.map(async (path) => {\n const found = builders.detectWorkflowPatterns(\n await readFile(path, \"utf8\"),\n );\n return found.hasDirective || found.hasSerde;\n }),\n );\n return !holds.some(Boolean);\n}\n\n/**\n * Write down what the bundle was built from: the files esbuild bundled (it names\n * each one in a comment), every file with a directive or a serializable class, and\n * the files that decide how imports resolve. Writes nothing when one of them\n * changed while the build ran, because the bundle may then not match what was\n * recorded.\n */\nasync function recordState(\n statePath: string,\n key: string,\n sources: string[],\n builders: Builders,\n root: string,\n dir: string,\n bundles: string[],\n extra: (string | undefined)[],\n startedAt: number,\n): Promise<void> {\n // Stamped before they are read, so an edit made in between shows on the next reload.\n const sourceStamps = await stamps(sources);\n const found = new Set(extra.filter((path) => path !== undefined));\n for (const bundle of bundles) {\n const text = await readFile(bundle, \"utf8\");\n for (const [, path] of text.matchAll(MODULE_COMMENT)) {\n // The flow bundle imports the steps bundle as a module; both are outputs.\n const file = resolve(root, path);\n if (!file.startsWith(dir)) found.add(file);\n }\n }\n await Promise.all(\n sources.map(async (path) => {\n const patterns = builders.detectWorkflowPatterns(\n await readFile(path, \"utf8\"),\n );\n if (patterns.hasDirective || patterns.hasSerde) found.add(path);\n }),\n );\n // A comment that names no file, such as `// see foo.ts`, stamps as empty.\n const inputs = Object.fromEntries(\n Object.entries(await stamps(found)).filter(([, stamp]) => stamp),\n );\n if (\n Object.values(inputs).some((stamp) => Number.parseFloat(stamp) >= startedAt)\n )\n return;\n const state: BuildState = { key, sources: sourceStamps, inputs };\n await writeFile(statePath, JSON.stringify(state));\n}\n\n/**\n * Build the bundle that runs an app's workflows: `flow.mjs` and `manifest.json`\n * in `<root>/.well-known/workflow/v1`, from every file under `root` marked\n * `\"use workflow\"` or `\"use step\"`.\n *\n * `brick dev` and `brick start` call it before events start. Call it in a script\n * or test before starting events.\n *\n * @param options - `root`: the project root. Default: the working directory.\n * `reuse`: keep the bundle of the last build when nothing it was built from has\n * changed, which saves about a second on each reload of `brick dev`. Default:\n * `false`, always build.\n * @returns Whether it built the bundle; `false` when it kept the last one.\n * @throws When `@workflow/builders` is not installed in the project.\n */\nexport async function buildWorkflows(\n options: { root?: string; reuse?: boolean } = {},\n): Promise<boolean> {\n const { root, dir } = resolveWorkflowPaths(options);\n const loaded = await loadBuilders(root);\n if (!loaded)\n throw new Error(\n `Cannot build workflows: @workflow/builders is not installed in ${root}. Add it with: bun add -d @workflow/builders`,\n );\n const { builders } = loaded;\n const output = (name: string) =>\n `./${relative(root, join(dir, name)).replaceAll(\"\\\\\", \"/\")}`;\n const builder = new builders.StandaloneBuilder({\n buildTarget: \"standalone\",\n dirs: [\".\"],\n workingDir: root,\n stepsBundlePath: output(\"__step_registrations.mjs\"),\n workflowsBundlePath: output(\"flow.mjs\"),\n webhookBundlePath: output(\"webhook.mjs\"),\n suppressCreateWorkflowsBundleLogs: true,\n suppressCreateWebhookBundleLogs: true,\n suppressCreateManifestLogs: true,\n });\n const statePath = join(dir, STATE_FILE);\n const bundles = [\"flow.mjs\", \"__step_registrations.mjs\"].map((name) =>\n join(dir, name),\n );\n const outputs = [\n ...bundles,\n join(dir, \"manifest.json\"),\n join(dir, \"webhook.mjs\"),\n ];\n const configs = await tsconfigInputs(await builder.findTsConfigPath());\n const key = JSON.stringify([\n STATE_VERSION,\n loaded.path,\n // Resolve again on reload so a formerly missing parent also invalidates reuse.\n await stamps(configs),\n // The builder reads these too, and writes a different bundle for each.\n ...[\n \"NODE_ENV\",\n \"WORKFLOW_DISCOVER_NODE_MODULES\",\n \"WORKFLOW_SOURCEMAP\",\n \"WORKFLOW_EMIT_SOURCEMAPS_FOR_DEBUGGING\",\n \"WORKFLOW_PUBLIC_MANIFEST\",\n ].map((name) => process.env[name] ?? \"\"),\n ]);\n const sources = await builder.getInputFiles();\n if (\n options.reuse &&\n (await isCurrent(statePath, key, sources, builders, outputs))\n )\n return false;\n // A build that fails halfway leaves outputs the old state no longer describes.\n await rm(statePath, { force: true });\n const startedAt = Date.now();\n await builder.build();\n try {\n await recordState(\n statePath,\n key,\n sources,\n builders,\n root,\n dir,\n bundles,\n [join(root, \"package.json\"), lockfileOf(root), ...configs],\n startedAt,\n );\n } catch {\n // Without a state the next reload builds again, which is only slower.\n }\n return true;\n}\n\n/**\n * Build the workflow bundle an app needs, if it has workflow listeners.\n *\n * @param app - The loaded app.\n * @param options - `reuse`: keep the last bundle when its sources have not changed.\n * @returns Whether the app has a bundle, built now or kept from the last build.\n */\nexport async function buildAppWorkflows(\n app: BrickApp,\n options: { reuse?: boolean } = {},\n): Promise<boolean> {\n const target = app.events?.workflows;\n if (!target) return false;\n const started = performance.now();\n const built = await buildWorkflows({\n root: target.root,\n reuse: options.reuse,\n });\n if (built)\n console.log(\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,YACJ,WACA,KACA,SACA,UACA,MACA,KACA,SACA;GAAC,KAAK,MAAM,cAAc;GAAG,WAAW,IAAI;GAAG,GAAG;EAAO,GACzD,SACF;CACF,QAAQ,CAER;CACA,OAAO;AACT;;;;;;;;AASA,eAAsB,kBACpB,KACA,UAA+B,CAAC,GACd;CAClB,MAAM,SAAS,IAAI,QAAQ;CAC3B,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,UAAU,YAAY,IAAI;CAKhC,IAAI,MAJgB,eAAe;EACjC,MAAM,OAAO;EACb,OAAO,QAAQ;CACjB,CAAC,GAEC,QAAQ,IACN,iCAAiC,KAAK,MAAM,YAAY,IAAI,IAAI,OAAO,EAAE,GAC3E;CACF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"workflows2.js","names":[],"sources":["../src/workflows.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n resolveWorkflowPaths,\n WORKFLOW_BUNDLE,\n type BrickApp,\n} from \"@brickkit/core\";\nimport { ConfigError } from \"./config\";\n\ninterface Builders {\n StandaloneBuilder: new (config: Record<string, unknown>) => {\n build(): Promise<void>;\n getInputFiles(): Promise<string[]>;\n findTsConfigPath(): Promise<string | undefined>;\n };\n detectWorkflowPatterns(source: string): {\n hasDirective: boolean;\n hasSerde: boolean;\n };\n applySwcTransform(\n filename: string,\n source: string,\n mode: \"step\" | \"workflow\" | \"detect\" | false,\n absolutePath: string,\n projectRoot: string,\n moduleSpecifierRoot?: string,\n ): Promise<{ code: string }>;\n}\n\ntype BunPlugin = Parameters<typeof Bun.plugin>[0];\n\nconst DIRECTIVE = /[\"']use (?:step|workflow)[\"']/;\n\n/**\n * Every project source file. Not the generated bundle: it holds the directives as\n * text inside the SDK's own code and is already built. Not `.cjs` and `.cts`\n * either: Bun drops `module.exports` from a file a plugin loads.\n */\nconst TRANSFORMED = new RegExp(\n String.raw`^(?!.*(?:node_modules|${WORKFLOW_BUNDLE.dir.replaceAll(\".\", \"\\\\.\")}/)).*\\.(?:m?[jt]s|[jt]sx)$`,\n);\n\n/** Bun's own loader for each extension: JSX is allowed in `.js` but not in `.mjs`. */\nfunction loaderFor(path: string): \"ts\" | \"tsx\" | \"js\" | \"jsx\" {\n if (path.endsWith(\".tsx\")) return \"tsx\";\n if (/\\.m?ts$/.test(path)) return \"ts\";\n return path.endsWith(\".mjs\") ? \"js\" : \"jsx\";\n}\n\nasync function loadBuilders(\n root: string,\n): Promise<{ builders: Builders; path: string } | undefined> {\n let path: string;\n try {\n path = createRequire(join(root, \"package.json\")).resolve(\n \"@workflow/builders\",\n );\n } catch {\n // Not installed: the app uses no workflows. A broken install throws below.\n return undefined;\n }\n return {\n builders: (await import(pathToFileURL(path).href)) as Builders,\n path,\n };\n}\n\n/**\n * The plugin that turns `\"use workflow\"` and `\"use step\"` files into workflows and\n * steps. `registerWorkflowTransform` installs it for the running process;\n * `brick build` hands it to `Bun.build`.\n *\n * @param root - The project root, where the SDK is installed. Default: the working directory.\n * @returns The plugin, or `undefined` when the Workflow SDK and its builders are not\n * installed in the project.\n */\nexport async function workflowTransformPlugin(\n root: string = process.cwd(),\n): Promise<BunPlugin | undefined> {\n const load = await transformer(root);\n if (!load) return undefined;\n return {\n name: \"brick:workflows\",\n setup(build) {\n build.onLoad({ filter: TRANSFORMED }, load);\n },\n };\n}\n\ntype Load = Bun.OnLoadCallback;\n\n/** The transform for files of the project at `root`, or `undefined` without the SDK. */\nasync function transformer(root: string): Promise<Load | undefined> {\n const projectRoot = resolve(root);\n const builders = (await loadBuilders(projectRoot))?.builders;\n if (!builders) return undefined;\n // Not async: Bun treats a module whose load returns a promise as async, and\n // `require()` refuses it. Only a file with a directive waits for SWC.\n return (args) => {\n const source = readFileSync(args.path, \"utf8\");\n if (!DIRECTIVE.test(source))\n return { contents: source, loader: loaderFor(args.path) };\n // SWC strips the types but leaves JSX as it is.\n return builders\n .applySwcTransform(\n relative(projectRoot, args.path).replaceAll(\"\\\\\", \"/\"),\n source,\n \"step\",\n args.path,\n projectRoot,\n projectRoot,\n )\n .then(({ code }) => ({ contents: code, loader: \"jsx\" as const }));\n };\n}\n\n/** The transform of each root registered in this process. */\nconst registered = new Map<string, Load>();\n\n/** The registered root a file belongs to: the innermost that holds it, else the first. */\nfunction rootOf(file: string): string {\n let found: string | undefined;\n for (const root of registered.keys())\n if (file.startsWith(root + sep) && root.length > (found?.length ?? -1))\n found = root;\n return found ?? registered.keys().next().value!;\n}\n\n/**\n * Make files marked `\"use workflow\"` or `\"use step\"` load as workflows and steps.\n *\n * A workflow function gets the `workflowId` that `defineListener({ workflow })`\n * needs, and a step registers itself so the runtime can run it in this process.\n * `brick dev`, `brick start` and `brick worker` call it before they load the app.\n * Call it in a script or test before importing the files, with the project root.\n *\n * It does nothing, and returns `false`, when the Workflow SDK and its builders are\n * not installed in the project. Each root gets ids relative to itself; a file\n * under no registered root uses the first one.\n *\n * @param root - The project root, where the SDK is installed. Default: the working directory.\n * @returns Whether the transform is active.\n */\nexport async function registerWorkflowTransform(\n root: string = process.cwd(),\n): Promise<boolean> {\n const projectRoot = resolve(root);\n if (registered.has(projectRoot)) return true;\n const load = await transformer(projectRoot);\n if (!load) return false;\n registered.set(projectRoot, load);\n // Bun keeps a plugin until the process ends, so one plugin serves every root.\n if (registered.size === 1)\n Bun.plugin({\n name: \"brick:workflows\",\n setup(build) {\n build.onLoad({ filter: TRANSFORMED }, (args) =>\n registered.get(rootOf(args.path))!(args),\n );\n },\n });\n return true;\n}\n\n/** The state of the last build, kept beside the bundle it describes. */\nconst STATE_FILE = \".brick-build.json\";\n/** Bump it when what the state records changes, so an older state is not trusted. */\nconst STATE_VERSION = 2;\n/**\n * esbuild starts each module of a bundle with a `// <path>` comment, whatever\n * the file (`data.json` too). The other comments it keeps name no file.\n */\nconst MODULE_COMMENT = /^\\/\\/ (.+)$/gm;\nconst LOCKFILES = [\n \"bun.lock\",\n \"bun.lockb\",\n \"package-lock.json\",\n \"pnpm-lock.yaml\",\n \"yarn.lock\",\n];\n\n/** A file's modification time and size, or an empty string when it is gone. */\ntype Stamps = Record<string, string>;\n\ninterface BuildState {\n key: string;\n /** Every source file the builder looks at. */\n sources: Stamps;\n /** The files the bundle holds or was built with; the bundle is stale when one changes. */\n inputs: Stamps;\n}\n\nasync function stamps(paths: Iterable<string>): Promise<Stamps> {\n const list = [...paths];\n const all = await Promise.all(\n list.map(async (path) => {\n try {\n const { mtimeMs, size } = await stat(path);\n return `${mtimeMs}:${size}`;\n } catch {\n return \"\";\n }\n }),\n );\n return Object.fromEntries(list.map((path, index) => [path, all[index]]));\n}\n\nfunction lockfileOf(root: string): string | undefined {\n for (let dir = root; ; dir = dirname(dir)) {\n for (const name of LOCKFILES)\n if (existsSync(join(dir, name))) return join(dir, name);\n if (dirname(dir) === dir) return undefined;\n }\n}\n\nasync function tsconfigInputs(path: string | undefined): Promise<string[]> {\n const files = new Set<string>();\n async function visit(file: string) {\n if (files.has(file)) return;\n files.add(file);\n let config: unknown;\n try {\n config = Bun.JSONC.parse(await readFile(file, \"utf8\"));\n } catch {\n return;\n }\n if (!config || typeof config !== \"object\" || !(\"extends\" in config)) return;\n const parents = Array.isArray(config.extends)\n ? config.extends\n : [config.extends];\n const require = createRequire(file);\n for (const parent of parents) {\n if (typeof parent !== \"string\") continue;\n // esbuild's order, which builds the bundle: a path as written, then with\n // .json; for a package, its tsconfig.json before `${parent}.json`, never `main`.\n const isPath =\n isAbsolute(parent) ||\n parent.startsWith(\"./\") ||\n parent.startsWith(\"../\");\n const candidates = isPath\n ? [parent, `${parent}.json`]\n : [`${parent}/tsconfig.json`, `${parent}.json`, parent];\n let found: string | undefined;\n for (const specifier of candidates) {\n try {\n found = require.resolve(specifier);\n } catch {\n continue;\n }\n if (found.endsWith(\".json\")) break;\n found = undefined;\n }\n // esbuild still reads the tsconfig.json of a package whose `exports` hides it.\n found ??= isPath\n ? undefined\n : require.resolve\n .paths(parent)\n ?.map((dir) => join(dir, parent, \"tsconfig.json\"))\n .find(existsSync);\n if (found) await visit(found);\n }\n }\n if (path) await visit(path);\n return [...files];\n}\n\n/**\n * Whether the bundle on disk still matches its sources: nothing it was built\n * from has changed, and no other source has come to hold a workflow, a step or a\n * serializable class that the bundle would need to know.\n */\nasync function isCurrent(\n statePath: string,\n key: string,\n sources: string[],\n builders: Builders,\n outputs: string[],\n): Promise<boolean> {\n let state: BuildState;\n try {\n state = JSON.parse(await readFile(statePath, \"utf8\")) as BuildState;\n } catch {\n return false;\n }\n if (state.key !== key || !outputs.every((file) => existsSync(file)))\n return false;\n // A file added or removed can change what an import resolves to.\n if (\n sources.length !== Object.keys(state.sources).length ||\n sources.some((path) => !(path in state.sources))\n )\n return false;\n const inputs = await stamps(Object.keys(state.inputs));\n if (\n Object.entries(state.inputs).some(([path, stamp]) => inputs[path] !== stamp)\n )\n return false;\n const others = sources.filter((path) => !(path in state.inputs));\n const now = await stamps(others);\n const changed = others.filter((path) => now[path] !== state.sources[path]);\n const holds = await Promise.all(\n changed.map(async (path) => {\n const found = builders.detectWorkflowPatterns(\n await readFile(path, \"utf8\"),\n );\n return found.hasDirective || found.hasSerde;\n }),\n );\n return !holds.some(Boolean);\n}\n\n/**\n * Write down what the bundle was built from: the files esbuild bundled (it names\n * each one in a comment), every file with a directive or a serializable class, and\n * the files that decide how imports resolve. Writes nothing when one of them\n * changed while the build ran, because the bundle may then not match what was\n * recorded.\n */\nasync function recordState(\n statePath: string,\n key: string,\n sources: string[],\n builders: Builders,\n root: string,\n dir: string,\n bundles: string[],\n extra: (string | undefined)[],\n startedAt: number,\n): Promise<void> {\n // Stamped before they are read, so an edit made in between shows on the next reload.\n const sourceStamps = await stamps(sources);\n const found = new Set(extra.filter((path) => path !== undefined));\n for (const bundle of bundles) {\n const text = await readFile(bundle, \"utf8\");\n for (const [, path] of text.matchAll(MODULE_COMMENT)) {\n // The flow bundle imports the steps bundle as a module; both are outputs.\n const file = resolve(root, path);\n if (!file.startsWith(dir)) found.add(file);\n }\n }\n await Promise.all(\n sources.map(async (path) => {\n const patterns = builders.detectWorkflowPatterns(\n await readFile(path, \"utf8\"),\n );\n if (patterns.hasDirective || patterns.hasSerde) found.add(path);\n }),\n );\n // A comment that names no file, such as `// see foo.ts`, stamps as empty.\n const inputs = Object.fromEntries(\n Object.entries(await stamps(found)).filter(([, stamp]) => stamp),\n );\n if (\n Object.values(inputs).some((stamp) => Number.parseFloat(stamp) >= startedAt)\n )\n return;\n const state: BuildState = { key, sources: sourceStamps, inputs };\n await writeFile(statePath, JSON.stringify(state));\n}\n\n/**\n * Build the bundle that runs an app's workflows: `flow.mjs` and `manifest.json`\n * in `<root>/.well-known/workflow/v1`, from every file under `root` marked\n * `\"use workflow\"` or `\"use step\"`.\n *\n * `brick dev` and `brick start` call it before events start. Call it in a script\n * or test before starting events.\n *\n * @param options - `root`: the project root. Default: the working directory.\n * `reuse`: keep the bundle of the last build when nothing it was built from has\n * changed, which saves about a second on each reload of `brick dev`. Default:\n * `false`, always build.\n * @returns Whether it built the bundle; `false` when it kept the last one.\n * @throws When `@workflow/builders` is not installed in the project.\n */\nexport async function buildWorkflows(\n options: { root?: string; reuse?: boolean } = {},\n): Promise<boolean> {\n const { root, dir } = resolveWorkflowPaths(options);\n const loaded = await loadBuilders(root);\n if (!loaded)\n throw new Error(\n `Cannot build workflows: @workflow/builders is not installed in ${root}. Add it with: bun add -d @workflow/builders`,\n );\n const { builders } = loaded;\n const output = (name: string) =>\n `./${relative(root, join(dir, name)).replaceAll(\"\\\\\", \"/\")}`;\n const builder = new builders.StandaloneBuilder({\n buildTarget: \"standalone\",\n dirs: [\".\"],\n workingDir: root,\n stepsBundlePath: output(WORKFLOW_BUNDLE.steps),\n workflowsBundlePath: output(WORKFLOW_BUNDLE.flow),\n webhookBundlePath: output(WORKFLOW_BUNDLE.webhook),\n suppressCreateWorkflowsBundleLogs: true,\n suppressCreateWebhookBundleLogs: true,\n suppressCreateManifestLogs: true,\n });\n const statePath = join(dir, STATE_FILE);\n const bundles = [WORKFLOW_BUNDLE.flow, WORKFLOW_BUNDLE.steps].map((name) =>\n join(dir, name),\n );\n const outputs = [\n ...bundles,\n join(dir, WORKFLOW_BUNDLE.manifest),\n join(dir, WORKFLOW_BUNDLE.webhook),\n ];\n const configs = await tsconfigInputs(await builder.findTsConfigPath());\n const key = JSON.stringify([\n STATE_VERSION,\n loaded.path,\n // Resolve again on reload so a formerly missing parent also invalidates reuse.\n await stamps(configs),\n // The builder reads these too, and writes a different bundle for each.\n ...[\n \"NODE_ENV\",\n \"WORKFLOW_DISCOVER_NODE_MODULES\",\n \"WORKFLOW_SOURCEMAP\",\n \"WORKFLOW_EMIT_SOURCEMAPS_FOR_DEBUGGING\",\n \"WORKFLOW_PUBLIC_MANIFEST\",\n ].map((name) => process.env[name] ?? \"\"),\n ]);\n const sources = await builder.getInputFiles();\n if (\n options.reuse &&\n (await isCurrent(statePath, key, sources, builders, outputs))\n )\n return false;\n // A build that fails halfway leaves outputs the old state no longer describes.\n await rm(statePath, { force: true });\n const startedAt = Date.now();\n await builder.build();\n try {\n await recordState(\n statePath,\n key,\n sources,\n builders,\n root,\n dir,\n bundles,\n [join(root, \"package.json\"), lockfileOf(root), ...configs],\n startedAt,\n );\n } catch {\n // Without a state the next reload builds again, which is only slower.\n }\n return true;\n}\n\n/**\n * Build the workflow bundle an app needs, if it has workflow listeners.\n *\n * @param app - The loaded app.\n * @param options - `reuse`: keep the last bundle when its sources have not changed.\n * @returns Whether the app has a bundle, built now or kept from the last build.\n */\nexport async function buildAppWorkflows(\n app: BrickApp,\n options: { reuse?: boolean } = {},\n): Promise<boolean> {\n const target = app.events?.workflows;\n if (!target) return false;\n // Ids come from the path relative to the root, so the transform the files\n // loaded with and the bundle must share it. `brick build` loads none.\n if (registered.size && !registered.has(resolve(target.root)))\n throw new ConfigError(\n `Brick: the app's workflows root ${target.root} is not the folder its workflow files were transformed from (${[...registered.keys()].join(\", \")}). Run brick from the workflows root, or leave events.workflows.root unset.`,\n );\n const started = performance.now();\n const built = await buildWorkflows({\n root: target.root,\n reuse: options.reuse,\n });\n if (built)\n console.log(\n `[Brick-TS] Built workflows in ${Math.round(performance.now() - started)}ms`,\n );\n return true;\n}\n"],"mappings":";;;;;;;;AAkCA,MAAM,YAAY;;;;;;AAOlB,MAAM,cAAc,IAAI,OACtB,OAAO,GAAG,yBAAyB,gBAAgB,IAAI,WAAW,KAAK,KAAK,EAAE,2BAChF;;AAGA,SAAS,UAAU,MAA2C;CAC5D,IAAI,KAAK,SAAS,MAAM,GAAG,OAAO;CAClC,IAAI,UAAU,KAAK,IAAI,GAAG,OAAO;CACjC,OAAO,KAAK,SAAS,MAAM,IAAI,OAAO;AACxC;AAEA,eAAe,aACb,MAC2D;CAC3D,IAAI;CACJ,IAAI;EACF,OAAO,cAAc,KAAK,MAAM,cAAc,CAAC,CAAC,CAAC,QAC/C,oBACF;CACF,QAAQ;EAEN;CACF;CACA,OAAO;EACL,UAAW,MAAM,OAAO,cAAc,IAAI,CAAC,CAAC;EAC5C;CACF;AACF;;;;;;;;;;AAWA,eAAsB,wBACpB,OAAe,QAAQ,IAAI,GACK;CAChC,MAAM,OAAO,MAAM,YAAY,IAAI;CACnC,IAAI,CAAC,MAAM,OAAO,KAAA;CAClB,OAAO;EACL,MAAM;EACN,MAAM,OAAO;GACX,MAAM,OAAO,EAAE,QAAQ,YAAY,GAAG,IAAI;EAC5C;CACF;AACF;;AAKA,eAAe,YAAY,MAAyC;CAClE,MAAM,cAAc,QAAQ,IAAI;CAChC,MAAM,YAAY,MAAM,aAAa,WAAW,EAAA,EAAI;CACpD,IAAI,CAAC,UAAU,OAAO,KAAA;CAGtB,QAAQ,SAAS;EACf,MAAM,SAAS,aAAa,KAAK,MAAM,MAAM;EAC7C,IAAI,CAAC,UAAU,KAAK,MAAM,GACxB,OAAO;GAAE,UAAU;GAAQ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