brumate 0.1.1 → 0.2.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/dist/{boot-DN1ZU8Hg.d.ts → boot-D-IdPy7B.d.ts} +24 -2
- package/dist/cli.js +2 -2
- package/dist/client-C0UCNL3J.js +1643 -0
- package/dist/client-C0UCNL3J.js.map +1 -0
- package/dist/{client-DwJInP_a.d.ts → client-MD0ZmcFR.d.ts} +101 -26
- package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
- package/dist/client-routes-JTbGtukf.js.map +1 -0
- package/dist/context-CTiSzQRc.js +27 -0
- package/dist/context-CTiSzQRc.js.map +1 -0
- package/dist/context-btHuB01Z.d.ts +42 -0
- package/dist/defer-D0bo1Gqx.js +52 -0
- package/dist/defer-D0bo1Gqx.js.map +1 -0
- package/dist/{devtools-BKjnHrnv.js → devtools-C50VH8gZ.js} +2 -2
- package/dist/devtools-C50VH8gZ.js.map +1 -0
- package/dist/{devtools-panel-AWOn0VK2.js → devtools-panel-AYjfwPhj.js} +4 -3
- package/dist/devtools-panel-AYjfwPhj.js.map +1 -0
- package/dist/events-BKWRqtMg.js +52 -0
- package/dist/events-BKWRqtMg.js.map +1 -0
- package/dist/{files-DdT84mPy.js → files-Bnn1JqHx.js} +18 -3
- package/dist/files-Bnn1JqHx.js.map +1 -0
- package/dist/{html-DEeoepg3.js → html-bHZbkK-h.js} +26 -8
- package/dist/html-bHZbkK-h.js.map +1 -0
- package/dist/{html-Du8jY2Cc.d.ts → html-y1q7-t7D.d.ts} +12 -5
- package/dist/index.d.ts +77 -29
- package/dist/index.js +12 -4
- package/dist/index.js.map +1 -1
- package/dist/{inspect-BPchdWbU.js → inspect-BJtACnQp.js} +784 -82
- package/dist/inspect-BJtACnQp.js.map +1 -0
- package/dist/{loader-Dc9OwY5I.js → loader-B18i3_-T.js} +46 -11
- package/dist/loader-B18i3_-T.js.map +1 -0
- package/dist/{navigate-CzLjnoPH.js → navigate-BwuZveDF.js} +71 -12
- package/dist/navigate-BwuZveDF.js.map +1 -0
- package/dist/{produce-BRGHP7e0.js → produce-CWfJ4byV.js} +43 -2
- package/dist/produce-CWfJ4byV.js.map +1 -0
- package/dist/{produce-CtZ32UGG.d.ts → produce-D4K7qpaL.d.ts} +23 -11
- package/dist/routes-BZNt7DSZ.d.ts +38 -0
- package/dist/{rpc-9fSqL_YK.js → rpc-B-Zkn6Ch.js} +24 -18
- package/dist/rpc-B-Zkn6Ch.js.map +1 -0
- package/dist/runtime/batch.d.ts +23 -0
- package/dist/runtime/batch.js +69 -0
- package/dist/runtime/batch.js.map +1 -0
- package/dist/runtime/client.d.ts +5 -5
- package/dist/runtime/client.js +5 -1345
- package/dist/runtime/context.d.ts +2 -2
- package/dist/runtime/context.js +1 -1
- package/dist/runtime/devtools.d.ts +5 -4
- package/dist/runtime/devtools.js +1 -1
- package/dist/runtime/env.d.ts +44 -0
- package/dist/runtime/env.js +61 -0
- package/dist/runtime/env.js.map +1 -0
- package/dist/runtime/events.d.ts +27 -0
- package/dist/runtime/events.js +1 -0
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/html.d.ts +2 -2
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/routes.d.ts +2 -21
- package/dist/runtime/routes.js +31 -1
- package/dist/runtime/routes.js.map +1 -1
- package/dist/runtime/server.d.ts +6 -5
- package/dist/runtime/server.js +5 -6
- package/dist/runtime/signals.d.ts +22 -1
- package/dist/runtime/signals.js +29 -1
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +2 -2
- package/dist/runtime/static-loader.js +1 -1
- package/dist/runtime/testing.d.ts +46 -5
- package/dist/runtime/testing.js +240 -33
- package/dist/runtime/testing.js.map +1 -1
- package/dist/secrets-BxagsJxJ.js +23 -0
- package/dist/secrets-BxagsJxJ.js.map +1 -0
- package/dist/{server-BxqjLUnV.d.ts → server-BA9SJ2Vm.d.ts} +544 -106
- package/dist/server-BqfM95r1.js +2762 -0
- package/dist/server-BqfM95r1.js.map +1 -0
- package/dist/skew-FRmAy9iy.js +49 -0
- package/dist/skew-FRmAy9iy.js.map +1 -0
- package/dist/standard-schema-BNY82yX3.d.ts +63 -0
- package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-BzE9SRaj.d.ts} +2 -2
- package/dist/{static-loader-ClNkHZGn.js → static-loader-DOygOFj5.js} +52 -21
- package/dist/static-loader-DOygOFj5.js.map +1 -0
- package/dist/{stream-bgNCMcaA.js → stream-JaMHMdBD.js} +126 -61
- package/dist/stream-JaMHMdBD.js.map +1 -0
- package/dist/vite.d.ts +42 -1
- package/dist/vite.js +435 -55
- package/dist/vite.js.map +1 -1
- package/package.json +15 -2
- package/types.d.ts +9 -1
- package/dist/client-routes-DakuM32C.js.map +0 -1
- package/dist/context-BG8KCF3v.js +0 -15
- package/dist/context-BG8KCF3v.js.map +0 -1
- package/dist/context-aeo9esY9.d.ts +0 -16
- package/dist/devtools-BKjnHrnv.js.map +0 -1
- package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
- package/dist/files-DdT84mPy.js.map +0 -1
- package/dist/html-DEeoepg3.js.map +0 -1
- package/dist/inspect-BPchdWbU.js.map +0 -1
- package/dist/loader-Dc9OwY5I.js.map +0 -1
- package/dist/navigate-CzLjnoPH.js.map +0 -1
- package/dist/produce-BRGHP7e0.js.map +0 -1
- package/dist/rpc-9fSqL_YK.js.map +0 -1
- package/dist/runtime/client.js.map +0 -1
- package/dist/server-DZsgnPKS.js +0 -1615
- package/dist/server-DZsgnPKS.js.map +0 -1
- package/dist/shared-CWYOd0H3.js +0 -40
- package/dist/shared-CWYOd0H3.js.map +0 -1
- package/dist/static-loader-ClNkHZGn.js.map +0 -1
- package/dist/stream-bgNCMcaA.js.map +0 -1
package/dist/vite.js
CHANGED
|
@@ -1,12 +1,158 @@
|
|
|
1
|
-
import { C as resolveFromDisk, E as analyzeProject, O as forEachNode, P as getLocation, S as isReactiveModule, _ as getComponentName, b as generateShared, d as instanceScope, f as slotIndex, g as functionId, i as scopeLabel, j as parse, k as resolveRelative, o as compile, r as report, t as formatReport, v as hash, w as builtin, y as SHARED_QUERY } from "./inspect-
|
|
1
|
+
import { C as resolveFromDisk, E as analyzeProject, O as forEachNode, P as getLocation, S as isReactiveModule, _ as getComponentName, b as generateShared, d as instanceScope, f as slotIndex, g as functionId, i as scopeLabel, j as parse, k as resolveRelative, o as compile, r as report, t as formatReport, v as hash, w as builtin, y as SHARED_QUERY } from "./inspect-BJtACnQp.js";
|
|
2
2
|
import { s as toNodeHeaders } from "./cookies-Av5WFmcf.js";
|
|
3
|
-
import { a as
|
|
3
|
+
import { a as hasServerMiddleware, c as serverExports, i as findServerFiles, l as serverModule, n as findFiles, o as hasUseServer, r as findScripts, s as isScriptFile, t as defaultExclude, u as serverStubs } from "./files-Bnn1JqHx.js";
|
|
4
|
+
import { parseSync } from "oxc-parser";
|
|
4
5
|
import { createHash } from "node:crypto";
|
|
5
|
-
import { existsSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
6
7
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
7
8
|
import path, { resolve } from "node:path";
|
|
8
9
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
10
|
import { isRunnableDevEnvironment, normalizePath, searchForWorkspaceRoot, transformWithOxc } from "vite";
|
|
11
|
+
//#region src/env-file.ts
|
|
12
|
+
/** The name of the function that declares the variables. */
|
|
13
|
+
const DEFINE = "defineEnv";
|
|
14
|
+
/** The names of the properties of an object literal. Other keys throw. */
|
|
15
|
+
function keysOf(node, group, filename) {
|
|
16
|
+
if (node.type !== "ObjectExpression") throw new Error(`The ${group} variables of ${filename} must be an object literal, so the compiler can read their names`);
|
|
17
|
+
return node.properties.map((property) => {
|
|
18
|
+
if (property.type === "Property" && !property.computed) return property.key.type === "Identifier" ? property.key.name : String(property.key.value);
|
|
19
|
+
throw new Error(`The ${group} variables of ${filename} must be plain properties, so the compiler can read their names`);
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
/** Finds the `defineEnv` call of the file. */
|
|
23
|
+
function findCall(program) {
|
|
24
|
+
let found;
|
|
25
|
+
const visit = (node) => {
|
|
26
|
+
if (found || typeof node !== "object" || node === null) return;
|
|
27
|
+
const value = node;
|
|
28
|
+
if (value.type === "CallExpression" && value.callee?.name === DEFINE) {
|
|
29
|
+
found = value;
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
for (const child of Object.values(value)) if (Array.isArray(child)) child.forEach(visit);
|
|
33
|
+
else if (typeof child === "object") visit(child);
|
|
34
|
+
};
|
|
35
|
+
visit(program);
|
|
36
|
+
return found;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Reads the variables that a file of environment variables declares. The
|
|
40
|
+
* schemas are written in the call, as object literals, so their names can
|
|
41
|
+
* be read without running the file.
|
|
42
|
+
*/
|
|
43
|
+
function parseEnvFile(source, filename) {
|
|
44
|
+
const { program, errors } = parseSync(filename, source, { lang: "ts" });
|
|
45
|
+
if (errors[0]) throw new Error(`${errors[0].message} (${filename})`);
|
|
46
|
+
const call = findCall(program);
|
|
47
|
+
const schema = call?.arguments[0];
|
|
48
|
+
if (!call || schema?.type !== "ObjectExpression") throw new Error(`${filename} must call ${DEFINE} with an object literal of server and public variables`);
|
|
49
|
+
const result = {
|
|
50
|
+
server: [],
|
|
51
|
+
public: [],
|
|
52
|
+
schemaEnd: schema.end,
|
|
53
|
+
hasOptions: call.arguments.length > 1
|
|
54
|
+
};
|
|
55
|
+
schema.properties.forEach((property, index) => {
|
|
56
|
+
if (property.type !== "Property" || property.computed || property.key.type !== "Identifier") throw new Error(`${DEFINE} in ${filename} takes server and public variables only`);
|
|
57
|
+
const group = property.key.name;
|
|
58
|
+
if (group !== "server" && group !== "public") throw new Error(`${DEFINE} in ${filename} takes server and public variables, not ${group}`);
|
|
59
|
+
result[group] = keysOf(property.value, group, filename);
|
|
60
|
+
if (group === "server") {
|
|
61
|
+
const next = schema.properties[index + 1];
|
|
62
|
+
const comma = source.indexOf(",", property.end);
|
|
63
|
+
const end = next ? next.start : comma !== -1 && comma < schema.end ? comma + 1 : property.end;
|
|
64
|
+
result.serverRange = {
|
|
65
|
+
start: property.start,
|
|
66
|
+
end
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The copy of the file that the browser gets: the server schemas are gone,
|
|
74
|
+
* and the values of the public variables, read when the build or the dev
|
|
75
|
+
* server ran, are the source of the call. The public schemas check them in
|
|
76
|
+
* the browser, as the server's do on the server.
|
|
77
|
+
*/
|
|
78
|
+
function clientEnvModule(source, filename, values) {
|
|
79
|
+
const file = parseEnvFile(source, filename);
|
|
80
|
+
if (file.hasOptions) throw new Error(`${DEFINE} in ${filename} takes no options, because the Vite plugin writes the values of the browser`);
|
|
81
|
+
const given = {};
|
|
82
|
+
for (const name of file.public) {
|
|
83
|
+
const value = values[name];
|
|
84
|
+
if (value !== void 0) given[name] = value;
|
|
85
|
+
}
|
|
86
|
+
const edits = [{
|
|
87
|
+
start: file.schemaEnd,
|
|
88
|
+
end: file.schemaEnd,
|
|
89
|
+
text: `, { source: ${JSON.stringify(given)} }`
|
|
90
|
+
}];
|
|
91
|
+
if (file.serverRange) edits.push({
|
|
92
|
+
...file.serverRange,
|
|
93
|
+
text: ""
|
|
94
|
+
});
|
|
95
|
+
let result = "";
|
|
96
|
+
let position = 0;
|
|
97
|
+
for (const edit of edits.toSorted((a, b) => a.start - b.start)) {
|
|
98
|
+
result += source.slice(position, edit.start) + edit.text;
|
|
99
|
+
position = edit.end;
|
|
100
|
+
}
|
|
101
|
+
return result + source.slice(position);
|
|
102
|
+
}
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/builds.ts
|
|
105
|
+
/** The file in the client build that names its build. */
|
|
106
|
+
const BUILD_FILE = ".brumate/build.json";
|
|
107
|
+
/** The file in the client build that lists the builds whose files are in it. */
|
|
108
|
+
const BUILDS_FILE = ".brumate/builds.json";
|
|
109
|
+
/** The directory of the client build, from the root and the prerender options. */
|
|
110
|
+
function clientBuildDirectory(root, prerender) {
|
|
111
|
+
const client = typeof prerender === "object" ? prerender.client : void 0;
|
|
112
|
+
return path.resolve(root, client ?? "dist/client");
|
|
113
|
+
}
|
|
114
|
+
/** The ID of the build in a client build directory, or undefined without one. */
|
|
115
|
+
function readBuildId(directory) {
|
|
116
|
+
const file = path.join(directory, BUILD_FILE);
|
|
117
|
+
if (!existsSync(file)) return;
|
|
118
|
+
try {
|
|
119
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
120
|
+
return typeof parsed.build === "string" ? parsed.build : void 0;
|
|
121
|
+
} catch {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Writes the ID of a build to its client output, adds the build to the list
|
|
127
|
+
* of builds, and removes the files of builds older than the `keep` builds
|
|
128
|
+
* before this one, unless a kept build wrote the same file. Returns the IDs
|
|
129
|
+
* of the builds whose files went.
|
|
130
|
+
*/
|
|
131
|
+
function pruneBuilds(directory, id, files, keep, now = Date.now()) {
|
|
132
|
+
const list = path.join(directory, BUILDS_FILE);
|
|
133
|
+
let builds = [];
|
|
134
|
+
if (existsSync(list)) try {
|
|
135
|
+
builds = JSON.parse(readFileSync(list, "utf8")).builds ?? [];
|
|
136
|
+
} catch {
|
|
137
|
+
builds = [];
|
|
138
|
+
}
|
|
139
|
+
builds = builds.filter((build) => build.id !== id);
|
|
140
|
+
builds.push({
|
|
141
|
+
id,
|
|
142
|
+
at: now,
|
|
143
|
+
files
|
|
144
|
+
});
|
|
145
|
+
builds.sort((a, b) => a.at - b.at);
|
|
146
|
+
const kept = builds.slice(Math.max(0, builds.length - 1 - keep));
|
|
147
|
+
const dropped = builds.slice(0, builds.length - kept.length);
|
|
148
|
+
const keptFiles = new Set(kept.flatMap((build) => build.files));
|
|
149
|
+
for (const build of dropped) for (const file of build.files) if (!keptFiles.has(file)) rmSync(path.join(directory, file), { force: true });
|
|
150
|
+
mkdirSync(path.join(directory, ".brumate"), { recursive: true });
|
|
151
|
+
writeFileSync(path.join(directory, BUILD_FILE), `${JSON.stringify({ build: id })}\n`);
|
|
152
|
+
writeFileSync(list, `${JSON.stringify({ builds: kept }, null, 2)}\n`);
|
|
153
|
+
return dropped.map((build) => build.id);
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
10
156
|
//#region src/packages.ts
|
|
11
157
|
const toPosix = (file) => file.split(path.sep).join("/");
|
|
12
158
|
function readJson(file) {
|
|
@@ -339,7 +485,8 @@ async function prerender(routes, root, base, options) {
|
|
|
339
485
|
const { handle } = await import(pathToFileURL(routes).href);
|
|
340
486
|
const document = {
|
|
341
487
|
head: options.head?.(manifest) ?? "",
|
|
342
|
-
scripts: `<script type="module" async src="${base}${entry.file}"><\/script
|
|
488
|
+
scripts: `<script type="module" async src="${base}${entry.file}"><\/script>`,
|
|
489
|
+
prerender: true
|
|
343
490
|
};
|
|
344
491
|
const queue = [...options.paths ?? ["/"]];
|
|
345
492
|
const seen = new Set(queue);
|
|
@@ -426,7 +573,7 @@ function routeEntries(node, resolve, path = "", layouts = []) {
|
|
|
426
573
|
return result;
|
|
427
574
|
}
|
|
428
575
|
/** Measures the client build. */
|
|
429
|
-
function buildReport({ chunks: list, sources, routes, budget }) {
|
|
576
|
+
function buildReport({ chunks: list, sources, routes, events: handlers, budget, relative = (file) => file }) {
|
|
430
577
|
const chunks = new Map(list.map((chunk) => [chunk.fileName, chunk]));
|
|
431
578
|
const sizes = new Map(list.map((chunk) => [chunk.fileName, gzipSize(chunk.code)]));
|
|
432
579
|
const sum = (names) => {
|
|
@@ -440,19 +587,46 @@ function buildReport({ chunks: list, sources, routes, budget }) {
|
|
|
440
587
|
const coreChunks = coreChunk ? withImports(coreChunk.fileName, chunks) : /* @__PURE__ */ new Set();
|
|
441
588
|
for (const name of loaderChunks) coreChunks.delete(name);
|
|
442
589
|
const byFile = /* @__PURE__ */ new Map();
|
|
590
|
+
const byModule = /* @__PURE__ */ new Map();
|
|
591
|
+
const everyPage = /* @__PURE__ */ new Set([...loaderChunks, ...coreChunks]);
|
|
443
592
|
for (const chunk of list) for (const id of chunk.moduleIds) {
|
|
444
593
|
const file = /^(.*\.brm)\?brumate-client/.exec(id)?.[1];
|
|
445
594
|
if (file) {
|
|
446
595
|
const set = byFile.get(file) ?? /* @__PURE__ */ new Set();
|
|
447
596
|
withImports(chunk.fileName, chunks, set);
|
|
448
597
|
byFile.set(file, set);
|
|
598
|
+
byModule.set(id, chunk.fileName);
|
|
449
599
|
}
|
|
450
600
|
}
|
|
451
|
-
for (const set of byFile.values()) for (const name of
|
|
601
|
+
for (const set of byFile.values()) for (const name of everyPage) set.delete(name);
|
|
452
602
|
const components = [...byFile].map(([file, names]) => ({
|
|
453
603
|
file,
|
|
454
604
|
bytes: sum(names)
|
|
455
605
|
})).toSorted((a, b) => b.bytes - a.bytes);
|
|
606
|
+
const eventChunks = (event) => {
|
|
607
|
+
const names = /* @__PURE__ */ new Set();
|
|
608
|
+
const entry = byModule.get(`${event.file}?brumate-client`);
|
|
609
|
+
if (entry) withImports(entry, chunks, names);
|
|
610
|
+
for (const part of event.parts) {
|
|
611
|
+
const chunk = byModule.get(`${event.file}?brumate-client&part=${part}`);
|
|
612
|
+
if (chunk) withImports(chunk, chunks, names);
|
|
613
|
+
}
|
|
614
|
+
for (const name of everyPage) names.delete(name);
|
|
615
|
+
return names;
|
|
616
|
+
};
|
|
617
|
+
const measured = (handlers ?? partEvents(byModule.keys())).map((event) => {
|
|
618
|
+
const names = eventChunks(event);
|
|
619
|
+
return {
|
|
620
|
+
event,
|
|
621
|
+
names,
|
|
622
|
+
bytes: sum(names)
|
|
623
|
+
};
|
|
624
|
+
});
|
|
625
|
+
const events = measured.map(({ event, bytes }) => ({
|
|
626
|
+
file: event.file,
|
|
627
|
+
label: event.label,
|
|
628
|
+
bytes
|
|
629
|
+
})).toSorted((a, b) => b.bytes - a.bytes);
|
|
456
630
|
const reachable = (files) => {
|
|
457
631
|
const seen = /* @__PURE__ */ new Set();
|
|
458
632
|
const visit = (file) => {
|
|
@@ -478,14 +652,39 @@ function buildReport({ chunks: list, sources, routes, budget }) {
|
|
|
478
652
|
const overBudget = [];
|
|
479
653
|
if (budget?.loader !== void 0 && loader > budget.loader) overBudget.push(`The loader is ${formatBytes(loader)}, over the budget of ${formatBytes(budget.loader)}.`);
|
|
480
654
|
for (const route of routeSizes) if (budget?.route !== void 0 && route.bytes > budget.route) overBudget.push(`The route ${route.path} can load ${formatBytes(route.bytes)}, over the budget of ${formatBytes(budget.route)}.`);
|
|
655
|
+
for (const component of components) if (budget?.component !== void 0 && component.bytes > budget.component) overBudget.push(`The component ${relative(component.file)} ships ${formatBytes(component.bytes)}, over the budget of ${formatBytes(budget.component)}.`);
|
|
656
|
+
for (const { event, names, bytes } of measured.toSorted((a, b) => b.bytes - a.bytes)) if (budget?.event !== void 0 && bytes > budget.event) {
|
|
657
|
+
const imports = largestImports(names, chunks);
|
|
658
|
+
overBudget.push(`The handler ${event.label} of ${relative(event.file)} loads ${formatBytes(bytes)}, over the budget of ${formatBytes(budget.event)}.${imports.length > 0 ? ` Its largest imports are ${imports.map(relative).join(", ")}.` : ""}`);
|
|
659
|
+
}
|
|
481
660
|
return {
|
|
482
661
|
loader,
|
|
483
662
|
core: sum(coreChunks),
|
|
484
663
|
components,
|
|
485
664
|
routes: routeSizes,
|
|
665
|
+
events,
|
|
486
666
|
overBudget
|
|
487
667
|
};
|
|
488
668
|
}
|
|
669
|
+
/** Each part of a client module as a handler of its own, when the build does not name them. */
|
|
670
|
+
function partEvents(ids) {
|
|
671
|
+
const result = [];
|
|
672
|
+
for (const id of ids) {
|
|
673
|
+
const match = /^(.*\.brm)\?brumate-client&part=(.+)$/.exec(id);
|
|
674
|
+
if (match && match[2] !== "update" && match[2] !== "shared") result.push({
|
|
675
|
+
file: match[1],
|
|
676
|
+
label: `part ${match[2]}`,
|
|
677
|
+
parts: [match[2]]
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
return result;
|
|
681
|
+
}
|
|
682
|
+
/** The three largest modules in the chunks that are not client modules of components. */
|
|
683
|
+
function largestImports(names, chunks) {
|
|
684
|
+
const sizes = [];
|
|
685
|
+
for (const name of names) for (const [id, bytes] of Object.entries(chunks.get(name)?.modules ?? {})) if (!id.includes("?brumate-client")) sizes.push([id.replace(/^\0/, ""), bytes]);
|
|
686
|
+
return sizes.toSorted((a, b) => b[1] - a[1]).slice(0, 3).map(([id]) => id);
|
|
687
|
+
}
|
|
489
688
|
function formatBytes(bytes) {
|
|
490
689
|
return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} kB`;
|
|
491
690
|
}
|
|
@@ -504,6 +703,10 @@ function formatBuildReport(report, relative) {
|
|
|
504
703
|
lines.push(" Components, largest first");
|
|
505
704
|
for (const component of report.components) lines.push(` ${relative(component.file)}: ${formatBytes(component.bytes)}`);
|
|
506
705
|
}
|
|
706
|
+
if (report.events.length > 0) {
|
|
707
|
+
lines.push(" What the first run of a handler loads, largest first");
|
|
708
|
+
for (const event of report.events.slice(0, 10)) lines.push(` ${relative(event.file)} ${event.label}: ${formatBytes(event.bytes)}`);
|
|
709
|
+
}
|
|
507
710
|
return lines.join("\n");
|
|
508
711
|
}
|
|
509
712
|
//#endregion
|
|
@@ -568,8 +771,10 @@ function routeFiles(paths) {
|
|
|
568
771
|
/**
|
|
569
772
|
* Writes a route tree as module code, with an import for each file. `rpc`
|
|
570
773
|
* is the URL prefix of server function calls, for forms that post to one.
|
|
774
|
+
* `middleware` is the path of the entry middleware, which runs for every
|
|
775
|
+
* request, when the app has one.
|
|
571
776
|
*/
|
|
572
|
-
function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false) {
|
|
777
|
+
function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false, middleware, build, hints = []) {
|
|
573
778
|
const imports = [];
|
|
574
779
|
const load = (file) => {
|
|
575
780
|
const name = `m${imports.length}`;
|
|
@@ -606,11 +811,12 @@ function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false
|
|
|
606
811
|
const routes = write(tree);
|
|
607
812
|
return [
|
|
608
813
|
"import { handleRoute } from 'brumate/server';",
|
|
609
|
-
"import { functions } from 'virtual:brumate/server';",
|
|
814
|
+
"import { functions, fileMiddleware } from 'virtual:brumate/server';",
|
|
815
|
+
...middleware ? [`import middleware from ${JSON.stringify(middleware)};`] : [],
|
|
610
816
|
...imports,
|
|
611
817
|
`export const routes = ${routes};`,
|
|
612
818
|
"export function handle(request, options) {",
|
|
613
|
-
` return handleRoute(routes, request, { rpc: ${JSON.stringify(rpc)}, origins: ${JSON.stringify(origins)}, functions${dev ? ", dev: true" : ""}, ...options });`,
|
|
819
|
+
` return handleRoute(routes, request, { rpc: ${JSON.stringify(rpc)}, origins: ${JSON.stringify(origins)}, functions, fileMiddleware${middleware ? ", middleware" : ""}${dev ? ", dev: true" : ""}${build === void 0 ? "" : `, build: ${JSON.stringify(build)}`}${hints.length > 0 ? `, hints: ${JSON.stringify(hints)}` : ""}, ...options });`,
|
|
614
820
|
"}"
|
|
615
821
|
].join("\n");
|
|
616
822
|
}
|
|
@@ -663,6 +869,8 @@ const RENDER_QUERY = "?brumate-render";
|
|
|
663
869
|
const SERVER_QUERY = "?brumate-server";
|
|
664
870
|
/** Exports `mount` from `brumate/testing`, with the loader of this project's client modules. */
|
|
665
871
|
const TESTING = "virtual:brumate/testing";
|
|
872
|
+
/** The modules that every page loads early, in the client build. See `hints` of `handleRoute`. */
|
|
873
|
+
const HINTS_FILE = ".brumate/hints.json";
|
|
666
874
|
/** The dev server answers the devtools panel about a component at this path. */
|
|
667
875
|
const INSPECT = "/__brumate/inspect";
|
|
668
876
|
/** What tells two lists of packages of components apart. */
|
|
@@ -743,9 +951,43 @@ function buildFingerprint() {
|
|
|
743
951
|
/** The Vite plugin for `.brm` files. */
|
|
744
952
|
function brumate(options = {}) {
|
|
745
953
|
const rpc = options.rpc ?? "/_brumate";
|
|
954
|
+
/** The entry middleware, when the app has one. */
|
|
955
|
+
const middlewareFile = () => {
|
|
956
|
+
if (options.middleware === false) return;
|
|
957
|
+
const file = normalizePath(path.resolve(root, options.middleware ?? "src/middleware.ts"));
|
|
958
|
+
if (!existsSync(file)) {
|
|
959
|
+
if (options.middleware !== void 0) throw new Error(`The middleware file ${options.middleware} does not exist`);
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
return file;
|
|
963
|
+
};
|
|
964
|
+
/** The file of environment variables, when the app has one. */
|
|
965
|
+
const envFile = () => {
|
|
966
|
+
if (options.env === false) return;
|
|
967
|
+
const file = normalizePath(path.resolve(root, options.env ?? "src/env.ts"));
|
|
968
|
+
if (!existsSync(file)) {
|
|
969
|
+
if (options.env !== void 0) throw new Error(`The env file ${options.env} does not exist`);
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
return file;
|
|
973
|
+
};
|
|
974
|
+
/** The names of the server variables, read from the env file, by its source. */
|
|
975
|
+
let envKeys;
|
|
976
|
+
const serverEnvKeys = () => {
|
|
977
|
+
const file = envFile();
|
|
978
|
+
if (!file) return;
|
|
979
|
+
const source = readFileSync(file, "utf8");
|
|
980
|
+
if (envKeys?.source !== source) envKeys = {
|
|
981
|
+
source,
|
|
982
|
+
server: parseEnvFile(source, file).server
|
|
983
|
+
};
|
|
984
|
+
return envKeys.server;
|
|
985
|
+
};
|
|
746
986
|
const exclude = options.exclude ?? defaultExclude;
|
|
747
987
|
let root = process.cwd();
|
|
748
988
|
let outDir = "";
|
|
989
|
+
/** The ID of the build, for skew protection. Undefined on the dev server. */
|
|
990
|
+
let buildId;
|
|
749
991
|
let base = "/";
|
|
750
992
|
let isSsrBuild = false;
|
|
751
993
|
let isServe = false;
|
|
@@ -843,35 +1085,62 @@ function brumate(options = {}) {
|
|
|
843
1085
|
liveProps = analyzeProject(sources, resolveComponent);
|
|
844
1086
|
compiled.clear();
|
|
845
1087
|
};
|
|
1088
|
+
/** The options of the compile of a file. */
|
|
1089
|
+
const compileOptions = (file) => ({
|
|
1090
|
+
filename: nameOf(file),
|
|
1091
|
+
liveProps: liveProps.get(file),
|
|
1092
|
+
path: file,
|
|
1093
|
+
merge: options.merge ?? 4096,
|
|
1094
|
+
a11y: options.a11y,
|
|
1095
|
+
hideNames: !isServe,
|
|
1096
|
+
serverImport: (specifier, name) => serverImport(file, specifier, name),
|
|
1097
|
+
resolveModule: (specifier, importer) => {
|
|
1098
|
+
const local = resolveFromDisk(specifier, importer);
|
|
1099
|
+
const found = local === void 0 && isPackageSpecifier(specifier) ? resolvePackageImport(specifier, importer) : void 0;
|
|
1100
|
+
return found ? {
|
|
1101
|
+
path: found,
|
|
1102
|
+
source: readFileSync(found, "utf8")
|
|
1103
|
+
} : local;
|
|
1104
|
+
}
|
|
1105
|
+
});
|
|
846
1106
|
const compileFile = async (file) => {
|
|
847
1107
|
const source = await readFile(file, "utf8");
|
|
848
1108
|
let cached = compiled.get(file);
|
|
849
1109
|
if (cached?.source !== source) {
|
|
850
1110
|
cached = {
|
|
851
1111
|
source,
|
|
852
|
-
result: compile(source,
|
|
853
|
-
filename: nameOf(file),
|
|
854
|
-
liveProps: liveProps.get(file),
|
|
855
|
-
path: file,
|
|
856
|
-
merge: options.merge ?? 4096,
|
|
857
|
-
a11y: options.a11y,
|
|
858
|
-
hideNames: !isServe,
|
|
859
|
-
serverImport: (specifier, name) => serverImport(file, specifier, name),
|
|
860
|
-
resolveModule: (specifier, importer) => {
|
|
861
|
-
const local = resolveFromDisk(specifier, importer);
|
|
862
|
-
const found = local === void 0 && isPackageSpecifier(specifier) ? resolvePackageImport(specifier, importer) : void 0;
|
|
863
|
-
return found ? {
|
|
864
|
-
path: found,
|
|
865
|
-
source: readFileSync(found, "utf8")
|
|
866
|
-
} : local;
|
|
867
|
-
}
|
|
868
|
-
})
|
|
1112
|
+
result: compile(source, compileOptions(file))
|
|
869
1113
|
};
|
|
870
1114
|
compiled.set(file, cached);
|
|
871
1115
|
shapes.set(file, shapeOf(cached.result));
|
|
872
1116
|
}
|
|
873
1117
|
return cached;
|
|
874
1118
|
};
|
|
1119
|
+
/** The compiles whose imports were checked for the env file. */
|
|
1120
|
+
const envChecked = /* @__PURE__ */ new WeakSet();
|
|
1121
|
+
/**
|
|
1122
|
+
* Compiles a component again with the server variables of the env file,
|
|
1123
|
+
* when one of its imports resolves to it, by any specifier, such as an
|
|
1124
|
+
* alias. The compile fails when code that runs in the browser reads one.
|
|
1125
|
+
*/
|
|
1126
|
+
const checkEnvReads = async (file, { source, result }, resolve) => {
|
|
1127
|
+
const env = envFile();
|
|
1128
|
+
if (!env || envChecked.has(result)) return;
|
|
1129
|
+
const specifiers = /* @__PURE__ */ new Set();
|
|
1130
|
+
for (const declaration of result.plan.graph.model.declarations) if (declaration.imported) specifiers.add(declaration.imported.source);
|
|
1131
|
+
const resolved = await Promise.all([...specifiers].map(async (specifier) => {
|
|
1132
|
+
return (await resolve(specifier, file))?.id.split("?")[0] === env ? specifier : void 0;
|
|
1133
|
+
}));
|
|
1134
|
+
const imports = new Set(resolved.filter((specifier) => specifier !== void 0));
|
|
1135
|
+
if (imports.size > 0) {
|
|
1136
|
+
const server = serverEnvKeys() ?? [];
|
|
1137
|
+
compile(source, {
|
|
1138
|
+
...compileOptions(file),
|
|
1139
|
+
envImport: (specifier) => imports.has(specifier) ? server : void 0
|
|
1140
|
+
});
|
|
1141
|
+
}
|
|
1142
|
+
envChecked.add(result);
|
|
1143
|
+
};
|
|
875
1144
|
const manifest = async () => {
|
|
876
1145
|
const list = [...files];
|
|
877
1146
|
const needed = await Promise.all(list.map(async ([, file]) => isServe || (await compileFile(file)).result.clientCode));
|
|
@@ -904,19 +1173,34 @@ function brumate(options = {}) {
|
|
|
904
1173
|
const spreads = components.map((_, index) => ` ...m${index}.rpc,`);
|
|
905
1174
|
const functionFiles = [...serverFiles.entries()].filter(([, file]) => keep(file));
|
|
906
1175
|
const fileImports = functionFiles.map(([, file], index) => `import * as f${index} from ${JSON.stringify(file + query)};`);
|
|
1176
|
+
const guards = [];
|
|
907
1177
|
const fileSpreads = functionFiles.map(([id, file], index) => {
|
|
908
|
-
|
|
1178
|
+
const source = readFileSync(file, "utf8");
|
|
1179
|
+
const names = serverExports(source, file);
|
|
1180
|
+
const guarded = hasServerMiddleware(source, file);
|
|
1181
|
+
return names.map((name) => {
|
|
1182
|
+
const key = JSON.stringify(functionId(id, name, !isServe));
|
|
1183
|
+
if (guarded) guards.push(` ${key}: f${index}.middleware,`);
|
|
1184
|
+
return ` ${key}: f${index}[${JSON.stringify(name)}],`;
|
|
1185
|
+
}).join("\n");
|
|
909
1186
|
});
|
|
1187
|
+
const env = envFile();
|
|
1188
|
+
const entry = middlewareFile();
|
|
910
1189
|
return [
|
|
1190
|
+
...env ? [`import ${JSON.stringify(env)};`] : [],
|
|
911
1191
|
"import { handleRequest } from 'brumate/server';",
|
|
1192
|
+
...entry ? [`import middleware from ${JSON.stringify(entry)};`] : [],
|
|
912
1193
|
...imports,
|
|
913
1194
|
...fileImports,
|
|
914
1195
|
"export const functions = {",
|
|
915
1196
|
...spreads,
|
|
916
1197
|
...fileSpreads,
|
|
917
1198
|
"};",
|
|
918
|
-
"export
|
|
919
|
-
|
|
1199
|
+
"export const fileMiddleware = {",
|
|
1200
|
+
...guards,
|
|
1201
|
+
"};",
|
|
1202
|
+
"export function handle(request, options) {",
|
|
1203
|
+
` return handleRequest(functions, request, ${JSON.stringify(rpc)}, { origins: ${JSON.stringify(options.origins ?? [])}, ${entry ? "middleware, " : ""}fileMiddleware${buildId === void 0 ? "" : `, build: ${JSON.stringify(buildId)}`}, ...options });`,
|
|
920
1204
|
"}"
|
|
921
1205
|
].join("\n");
|
|
922
1206
|
};
|
|
@@ -934,7 +1218,20 @@ function brumate(options = {}) {
|
|
|
934
1218
|
}
|
|
935
1219
|
return routeFiles(paths);
|
|
936
1220
|
};
|
|
937
|
-
|
|
1221
|
+
/**
|
|
1222
|
+
* The modules that every page loads early, which the client build wrote,
|
|
1223
|
+
* or none before a client build or in development.
|
|
1224
|
+
*/
|
|
1225
|
+
const clientHints = () => {
|
|
1226
|
+
const file = path.join(clientBuildDirectory(root, options.prerender), HINTS_FILE);
|
|
1227
|
+
return !isServe && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : [];
|
|
1228
|
+
};
|
|
1229
|
+
/** The route tree module. A DOM test gets the server version of each component in it. */
|
|
1230
|
+
const routeTree = (server = false) => {
|
|
1231
|
+
const env = envFile();
|
|
1232
|
+
const code = routeModule(currentRoutes(), (file) => `${routesDirectory()}/${file}${server && file.endsWith(".brm") ? SERVER_QUERY : ""}`, rpc, options.origins, isServe, middlewareFile(), buildId, clientHints());
|
|
1233
|
+
return env ? `import ${JSON.stringify(env)};\n${code}` : code;
|
|
1234
|
+
};
|
|
938
1235
|
/** Writes the paths of the routes as types for `href`, when they changed. */
|
|
939
1236
|
const writeRouteTypes = () => {
|
|
940
1237
|
if (options.routeTypes === false || !existsSync(routesDirectory())) return;
|
|
@@ -997,13 +1294,12 @@ function brumate(options = {}) {
|
|
|
997
1294
|
if (module) server.moduleGraph.invalidateModule(module);
|
|
998
1295
|
}
|
|
999
1296
|
try {
|
|
1000
|
-
const {
|
|
1001
|
-
const
|
|
1002
|
-
const answer = await handleRequest(functions, new Request(new URL(request.url ?? "/", "http://localhost"), {
|
|
1297
|
+
const { handle } = await server.ssrLoadModule(SERVER);
|
|
1298
|
+
const answer = await handle(new Request(new URL(request.url ?? "/", "http://localhost"), {
|
|
1003
1299
|
method: "POST",
|
|
1004
1300
|
headers: Object.entries(request.headers).flatMap(([name, value]) => value === void 0 ? [] : [[name, String(value)]]),
|
|
1005
1301
|
body: new Uint8Array(await readBody(request))
|
|
1006
|
-
}),
|
|
1302
|
+
}), { address: request.socket.remoteAddress });
|
|
1007
1303
|
response.statusCode = answer.status;
|
|
1008
1304
|
for (const [name, value] of Object.entries(toNodeHeaders(answer.headers))) response.setHeader(name, value);
|
|
1009
1305
|
response.end(await answer.text());
|
|
@@ -1097,16 +1393,23 @@ function brumate(options = {}) {
|
|
|
1097
1393
|
const shared = packageConfig(config);
|
|
1098
1394
|
if (!env.isSsrBuild) {
|
|
1099
1395
|
const preload = config.build?.modulePreload;
|
|
1100
|
-
|
|
1396
|
+
const keep = options.skew?.keep ? { build: { emptyOutDir: false } } : {};
|
|
1397
|
+
if (preload === false) return {
|
|
1398
|
+
...shared,
|
|
1399
|
+
...keep
|
|
1400
|
+
};
|
|
1101
1401
|
const resolve = typeof preload === "object" ? preload.resolveDependencies : void 0;
|
|
1102
1402
|
return {
|
|
1103
1403
|
...shared,
|
|
1104
|
-
build: {
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1404
|
+
build: {
|
|
1405
|
+
...keep.build,
|
|
1406
|
+
modulePreload: { resolveDependencies(filename, deps, context) {
|
|
1407
|
+
const list = resolve ? resolve(filename, deps, context) : deps;
|
|
1408
|
+
if (context.hostId !== loaderChunk || !coreChunk) return list;
|
|
1409
|
+
const rest = list.filter((dep) => dep !== coreChunk);
|
|
1410
|
+
return rest.length === 1 && rest[0] === filename ? [] : rest;
|
|
1411
|
+
} }
|
|
1412
|
+
}
|
|
1110
1413
|
};
|
|
1111
1414
|
}
|
|
1112
1415
|
if (!options.prerender) return shared;
|
|
@@ -1150,10 +1453,23 @@ function brumate(options = {}) {
|
|
|
1150
1453
|
code: item.code,
|
|
1151
1454
|
isEntry: item.isEntry,
|
|
1152
1455
|
imports: item.imports,
|
|
1153
|
-
moduleIds: item.moduleIds
|
|
1456
|
+
moduleIds: item.moduleIds,
|
|
1457
|
+
modules: Object.fromEntries(Object.entries(item.modules).map(([id, module]) => [id, module.renderedLength]))
|
|
1154
1458
|
});
|
|
1155
1459
|
const list = [...files.values()];
|
|
1156
1460
|
const contents = await Promise.all(list.map((file) => readFile(file, "utf8")));
|
|
1461
|
+
const events = [];
|
|
1462
|
+
for (const [file, { source, result }] of compiled) for (const [site, symbol] of result.plan.symbols) {
|
|
1463
|
+
const loads = result.loaders[symbol];
|
|
1464
|
+
if (loads) {
|
|
1465
|
+
const { line, column } = getLocation(source, site.range.start);
|
|
1466
|
+
events.push({
|
|
1467
|
+
file,
|
|
1468
|
+
label: `${site.label} (${line}:${column})`,
|
|
1469
|
+
parts: loads
|
|
1470
|
+
});
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1157
1473
|
const measured = buildReport({
|
|
1158
1474
|
chunks,
|
|
1159
1475
|
sources: new Map(list.map((file, index) => [file, contents[index]])),
|
|
@@ -1161,12 +1477,35 @@ function brumate(options = {}) {
|
|
|
1161
1477
|
tree: currentRoutes(),
|
|
1162
1478
|
resolve: (file) => `${routesDirectory()}/${file}`
|
|
1163
1479
|
} : void 0,
|
|
1164
|
-
|
|
1480
|
+
events,
|
|
1481
|
+
budget: options.budget,
|
|
1482
|
+
relative: nameOf
|
|
1165
1483
|
});
|
|
1166
1484
|
if (options.report) this.info(`\n${formatBuildReport(measured, nameOf)}`);
|
|
1167
1485
|
if (measured.overBudget.length > 0) this.error(measured.overBudget.join("\n"));
|
|
1168
1486
|
},
|
|
1169
1487
|
async writeBundle(_output, bundle) {
|
|
1488
|
+
if (!isSsrBuild) {
|
|
1489
|
+
const chunks = new Map(Object.values(bundle).flatMap((item) => item.type === "chunk" ? [[item.fileName, item]] : []));
|
|
1490
|
+
const hints = /* @__PURE__ */ new Set();
|
|
1491
|
+
const add = (name) => {
|
|
1492
|
+
const chunk = name === void 0 ? void 0 : chunks.get(name);
|
|
1493
|
+
if (chunk && !hints.has(chunk.fileName)) {
|
|
1494
|
+
hints.add(chunk.fileName);
|
|
1495
|
+
chunk.imports.forEach(add);
|
|
1496
|
+
}
|
|
1497
|
+
};
|
|
1498
|
+
add(loaderChunk);
|
|
1499
|
+
add(coreChunk);
|
|
1500
|
+
await mkdir(path.join(outDir, ".brumate"), { recursive: true });
|
|
1501
|
+
await writeFile(path.join(outDir, HINTS_FILE), JSON.stringify([...hints].map((name) => `${base}${name}`)));
|
|
1502
|
+
if (buildId !== void 0) {
|
|
1503
|
+
const written = Object.values(bundle).map((item) => item.fileName);
|
|
1504
|
+
const removed = pruneBuilds(outDir, buildId, written, options.skew?.keep ?? 0);
|
|
1505
|
+
if (removed.length > 0) this.info(`Removed the files of ${removed.length} older builds`);
|
|
1506
|
+
}
|
|
1507
|
+
return;
|
|
1508
|
+
}
|
|
1170
1509
|
if (!options.prerender || !isSsrBuild) return;
|
|
1171
1510
|
const chunk = Object.values(bundle).find((item) => item.type === "chunk" && item.isEntry && item.name === PRERENDER_ENTRY);
|
|
1172
1511
|
if (!chunk) return;
|
|
@@ -1175,13 +1514,30 @@ function brumate(options = {}) {
|
|
|
1175
1514
|
this.info(`Prerendered ${written.length} pages`);
|
|
1176
1515
|
},
|
|
1177
1516
|
async buildStart() {
|
|
1517
|
+
if (!isServe) {
|
|
1518
|
+
if (isSsrBuild) {
|
|
1519
|
+
const client = clientBuildDirectory(root, options.prerender);
|
|
1520
|
+
buildId = process.env.BRUMATE_BUILD || readBuildId(client);
|
|
1521
|
+
if (buildId === void 0) this.warn(`No ${BUILD_FILE} in ${path.relative(root, client)}, so the server does not know its build ID. Build the client first, or set BRUMATE_BUILD, for skew protection`);
|
|
1522
|
+
} else buildId = process.env.BRUMATE_BUILD || `${Date.now().toString(36)}${hash(String(Math.random()))}`;
|
|
1523
|
+
}
|
|
1178
1524
|
coreModule = isServe ? void 0 : (await this.resolve("brumate/client", path.join(root, "index.html")))?.id;
|
|
1179
1525
|
await scan();
|
|
1180
1526
|
writeRouteTypes();
|
|
1181
1527
|
},
|
|
1182
1528
|
async resolveId(id, importer, resolveOptions) {
|
|
1183
1529
|
if (id === START || id === MANIFEST || id === SERVER || id === ROUTES || id === TESTING) return `\0${id}`;
|
|
1184
|
-
|
|
1530
|
+
const env = resolveOptions?.ssr ? void 0 : envFile();
|
|
1531
|
+
const from = importer?.split("?")[0];
|
|
1532
|
+
if (env && importer && from && from !== env && isScriptFile(from) && !importer.startsWith("\0") && !importer.includes(SERVER_QUERY) && !importer.includes("/node_modules/")) {
|
|
1533
|
+
const resolved = await this.resolve(id, importer, {
|
|
1534
|
+
...resolveOptions,
|
|
1535
|
+
skipSelf: true
|
|
1536
|
+
});
|
|
1537
|
+
if (resolved?.id.split("?")[0] === env) this.error(`${relative(from)} imports ${relative(env)}, and the browser loads it. Only components can import the env file in code that the browser loads, because the compiler checks what they read. Read the variable in a component or a server function, and pass the value on.`);
|
|
1538
|
+
return resolved ?? void 0;
|
|
1539
|
+
}
|
|
1540
|
+
if (resolveOptions?.ssr || !importer || !importer.includes(SERVER_QUERY) && importer !== `\0${SERVER}` && importer !== `\0${ROUTES}` || id.includes(SERVER_QUERY)) return;
|
|
1185
1541
|
const resolved = await this.resolve(id, importer, {
|
|
1186
1542
|
...resolveOptions,
|
|
1187
1543
|
skipSelf: true
|
|
@@ -1213,20 +1569,31 @@ function brumate(options = {}) {
|
|
|
1213
1569
|
options.navigate === false ? "import { startWithoutNavigation as start } from 'brumate/static-loader';" : "import { start } from 'brumate/loader';",
|
|
1214
1570
|
`import { load } from ${JSON.stringify(MANIFEST)};`,
|
|
1215
1571
|
...isServe ? ["import { hotLoad } from 'brumate/hot';"] : [],
|
|
1216
|
-
`start({ load${isServe ? ": hotLoad(import.meta.hot, load)" : ""}, rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)}${options.preload === false ? ", preload: false" : ""} });`,
|
|
1572
|
+
`start({ load${isServe ? ": hotLoad(import.meta.hot, load)" : ""}, rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)}${options.preload === false ? ", preload: false" : ""}${buildId === void 0 ? "" : `, build: ${JSON.stringify(buildId)}`} });`,
|
|
1217
1573
|
...isServe && options.devtools !== false ? [`import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}));`] : []
|
|
1218
1574
|
].join("\n");
|
|
1219
1575
|
if (id === `\0${MANIFEST}`) return await manifest();
|
|
1220
1576
|
if (id === `\0${SERVER}`) return serverRegistry(!loadOptions?.ssr);
|
|
1221
|
-
if (id === `\0${ROUTES}`) return routeTree();
|
|
1222
|
-
if (id === `\0${TESTING}`)
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1577
|
+
if (id === `\0${ROUTES}`) return routeTree(!loadOptions?.ssr);
|
|
1578
|
+
if (id === `\0${TESTING}`) {
|
|
1579
|
+
const entry = middlewareFile();
|
|
1580
|
+
return [
|
|
1581
|
+
"import { answerCalls as answer, createMount, createVisit } from 'brumate/testing';",
|
|
1582
|
+
`import { load } from ${JSON.stringify(MANIFEST)};`,
|
|
1583
|
+
...entry ? [`import middleware from ${JSON.stringify(entry)};`] : [],
|
|
1584
|
+
`export const mount = createMount({ load, rpc: ${JSON.stringify(rpc)} });`,
|
|
1585
|
+
"export const visit = createVisit({",
|
|
1586
|
+
" load,",
|
|
1587
|
+
` rpc: ${JSON.stringify(rpc)},`,
|
|
1588
|
+
` routes: async () => (await import(${JSON.stringify(ROUTES)})).handle,`,
|
|
1589
|
+
` calls: async () => (await import(${JSON.stringify(SERVER)})).handle,`,
|
|
1590
|
+
"});",
|
|
1591
|
+
"export function answerCalls(options) {",
|
|
1592
|
+
` const server = import(${JSON.stringify(SERVER)});`,
|
|
1593
|
+
` return answer(async () => (await server).functions, { rpc: ${JSON.stringify(rpc)}, ${entry ? "middleware, " : ""}fileMiddleware: async () => (await server).fileMiddleware, ...options });`,
|
|
1594
|
+
"}"
|
|
1595
|
+
].join("\n");
|
|
1596
|
+
}
|
|
1230
1597
|
const [file, query] = id.split("?");
|
|
1231
1598
|
if (!file?.endsWith(".brm")) return;
|
|
1232
1599
|
const params = new URLSearchParams(query);
|
|
@@ -1236,6 +1603,7 @@ function brumate(options = {}) {
|
|
|
1236
1603
|
let output;
|
|
1237
1604
|
try {
|
|
1238
1605
|
output = await compileFile(file);
|
|
1606
|
+
await checkEnvReads(file, output, (specifier, importer) => this.resolve(specifier, importer));
|
|
1239
1607
|
} catch (error) {
|
|
1240
1608
|
const { message, frame, loc } = errorPayload(error, root);
|
|
1241
1609
|
this.error({
|
|
@@ -1285,6 +1653,14 @@ function brumate(options = {}) {
|
|
|
1285
1653
|
},
|
|
1286
1654
|
async transform(code, id, transformOptions) {
|
|
1287
1655
|
const [file] = id.split("?");
|
|
1656
|
+
if (file && !transformOptions?.ssr && file === envFile()) try {
|
|
1657
|
+
return {
|
|
1658
|
+
code: clientEnvModule(code, file, process.env),
|
|
1659
|
+
map: null
|
|
1660
|
+
};
|
|
1661
|
+
} catch (error) {
|
|
1662
|
+
this.error(error.message);
|
|
1663
|
+
}
|
|
1288
1664
|
if (file && isScriptFile(file) && hasUseServer(code)) try {
|
|
1289
1665
|
const fileId = serverFileId(normalizePath(file));
|
|
1290
1666
|
if (transformOptions?.ssr) return {
|
|
@@ -1328,6 +1704,7 @@ function brumate(options = {}) {
|
|
|
1328
1704
|
if (manifests.includes(normalizePath(file)) && packagesKey(findPackages(root)) !== packagesKey(packages)) server.restart();
|
|
1329
1705
|
});
|
|
1330
1706
|
server.watcher.on("all", (event, file) => {
|
|
1707
|
+
if (normalizePath(file) === envFile()) compiled.clear();
|
|
1331
1708
|
for (const importer of dependents.get(normalizePath(file)) ?? []) {
|
|
1332
1709
|
compiled.delete(importer);
|
|
1333
1710
|
for (const module of server.moduleGraph.getModulesByFile(importer) ?? []) server.moduleGraph.invalidateModule(module);
|
|
@@ -1380,7 +1757,10 @@ function brumate(options = {}) {
|
|
|
1380
1757
|
const environment = this.environment;
|
|
1381
1758
|
if (environment.config.consumer === "client") return updateClient(file, server, timestamp);
|
|
1382
1759
|
const normalized = normalizePath(file);
|
|
1383
|
-
if (!file.endsWith(".brm") && !dependents.has(normalized))
|
|
1760
|
+
if (!file.endsWith(".brm") && !dependents.has(normalized) && normalized !== middlewareFile() && normalized !== envFile()) {
|
|
1761
|
+
if (environment.moduleGraph.getModulesByFile(normalized)?.size) server.environments.client.hot.send({ type: "full-reload" });
|
|
1762
|
+
return;
|
|
1763
|
+
}
|
|
1384
1764
|
const invalidated = /* @__PURE__ */ new Set();
|
|
1385
1765
|
for (const module of environment.moduleGraph.idToModuleMap.values()) {
|
|
1386
1766
|
const id = module.id ?? "";
|