brumate 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/{boot-DN1ZU8Hg.d.ts → boot-C25Sa6vq.d.ts} +27 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/client-BD6XT-s5.js +1968 -0
  4. package/dist/client-BD6XT-s5.js.map +1 -0
  5. package/dist/{client-DwJInP_a.d.ts → client-D0CqSxoO.d.ts} +211 -30
  6. package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
  7. package/dist/client-routes-JTbGtukf.js.map +1 -0
  8. package/dist/context-CTiSzQRc.js +27 -0
  9. package/dist/context-CTiSzQRc.js.map +1 -0
  10. package/dist/context-btHuB01Z.d.ts +42 -0
  11. package/dist/{cookies-Av5WFmcf.js → cookies-BzllthiF.js} +2 -1
  12. package/dist/cookies-BzllthiF.js.map +1 -0
  13. package/dist/defer-BbD7JQhj.js +56 -0
  14. package/dist/defer-BbD7JQhj.js.map +1 -0
  15. package/dist/devtools-CQgD7NPB.js +623 -0
  16. package/dist/devtools-CQgD7NPB.js.map +1 -0
  17. package/dist/devtools-panel-BVB-W5q4.js +1930 -0
  18. package/dist/devtools-panel-BVB-W5q4.js.map +1 -0
  19. package/dist/events-CSs7OwIC.js +85 -0
  20. package/dist/events-CSs7OwIC.js.map +1 -0
  21. package/dist/{files-DdT84mPy.js → files-BXSSrQgc.js} +34 -6
  22. package/dist/files-BXSSrQgc.js.map +1 -0
  23. package/dist/forms-Bg-CwGqX.js +406 -0
  24. package/dist/forms-Bg-CwGqX.js.map +1 -0
  25. package/dist/forms-Cl21hkHt.d.ts +281 -0
  26. package/dist/highlight.d.ts +17 -0
  27. package/dist/highlight.js +269 -0
  28. package/dist/highlight.js.map +1 -0
  29. package/dist/html-Bq1rFxX_.d.ts +92 -0
  30. package/dist/html-mNTKzaDD.js +241 -0
  31. package/dist/html-mNTKzaDD.js.map +1 -0
  32. package/dist/index.d.ts +123 -30
  33. package/dist/index.js +14 -6
  34. package/dist/index.js.map +1 -1
  35. package/dist/{inspect-BPchdWbU.js → inspect-BHpOw1LF.js} +1400 -121
  36. package/dist/inspect-BHpOw1LF.js.map +1 -0
  37. package/dist/{loader-Dc9OwY5I.js → loader-Dos_3NP0.js} +47 -11
  38. package/dist/loader-Dos_3NP0.js.map +1 -0
  39. package/dist/{navigate-CzLjnoPH.js → navigate-O78d_zGN.js} +115 -13
  40. package/dist/navigate-O78d_zGN.js.map +1 -0
  41. package/dist/produce-D0V0ICkz.d.ts +114 -0
  42. package/dist/produce-Doc91GkX.js +274 -0
  43. package/dist/produce-Doc91GkX.js.map +1 -0
  44. package/dist/routes-BZNt7DSZ.d.ts +38 -0
  45. package/dist/{rpc-9fSqL_YK.js → rpc-ygMRPmN4.js} +39 -23
  46. package/dist/rpc-ygMRPmN4.js.map +1 -0
  47. package/dist/runtime/batch.d.ts +23 -0
  48. package/dist/runtime/batch.js +69 -0
  49. package/dist/runtime/batch.js.map +1 -0
  50. package/dist/runtime/client.d.ts +5 -5
  51. package/dist/runtime/client.js +5 -1345
  52. package/dist/runtime/context.d.ts +2 -2
  53. package/dist/runtime/context.js +1 -1
  54. package/dist/runtime/devtools.d.ts +191 -5
  55. package/dist/runtime/devtools.js +1 -1
  56. package/dist/runtime/env.d.ts +44 -0
  57. package/dist/runtime/env.js +61 -0
  58. package/dist/runtime/env.js.map +1 -0
  59. package/dist/runtime/events.d.ts +42 -0
  60. package/dist/runtime/events.js +1 -0
  61. package/dist/runtime/forms.d.ts +2 -0
  62. package/dist/runtime/forms.js +1 -0
  63. package/dist/runtime/gather.d.ts +25 -0
  64. package/dist/runtime/gather.js +33 -0
  65. package/dist/runtime/gather.js.map +1 -0
  66. package/dist/runtime/hot.d.ts +1 -1
  67. package/dist/runtime/html.d.ts +2 -2
  68. package/dist/runtime/html.js +1 -1
  69. package/dist/runtime/loader.d.ts +2 -2
  70. package/dist/runtime/loader.js +2 -2
  71. package/dist/runtime/routes.d.ts +2 -21
  72. package/dist/runtime/routes.js +31 -1
  73. package/dist/runtime/routes.js.map +1 -1
  74. package/dist/runtime/server.d.ts +7 -5
  75. package/dist/runtime/server.js +6 -7
  76. package/dist/runtime/signals.d.ts +60 -3
  77. package/dist/runtime/signals.js +40 -2
  78. package/dist/runtime/signals.js.map +1 -1
  79. package/dist/runtime/static-loader.d.ts +2 -2
  80. package/dist/runtime/static-loader.js +1 -1
  81. package/dist/runtime/testing.d.ts +46 -5
  82. package/dist/runtime/testing.js +240 -33
  83. package/dist/runtime/testing.js.map +1 -1
  84. package/dist/runtime/values.d.ts +2 -0
  85. package/dist/runtime/values.js +24 -0
  86. package/dist/runtime/values.js.map +1 -0
  87. package/dist/secrets-BxagsJxJ.js +23 -0
  88. package/dist/secrets-BxagsJxJ.js.map +1 -0
  89. package/dist/server-CxVDYE_V.js +3417 -0
  90. package/dist/server-CxVDYE_V.js.map +1 -0
  91. package/dist/server-DuFYRXrd.d.ts +1460 -0
  92. package/dist/skew-FRmAy9iy.js +49 -0
  93. package/dist/skew-FRmAy9iy.js.map +1 -0
  94. package/dist/standard-schema-BNY82yX3.d.ts +63 -0
  95. package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-Drpr0AzI.d.ts} +2 -2
  96. package/dist/static-loader-nZssh66R.js +333 -0
  97. package/dist/static-loader-nZssh66R.js.map +1 -0
  98. package/dist/stream-DCYZO4IF.js +424 -0
  99. package/dist/stream-DCYZO4IF.js.map +1 -0
  100. package/dist/values-B8C7CLvG.d.ts +63 -0
  101. package/dist/vite.d.ts +49 -1
  102. package/dist/vite.js +598 -68
  103. package/dist/vite.js.map +1 -1
  104. package/forms/forms.brm.ts +141 -0
  105. package/package.json +45 -3
  106. package/types.d.ts +9 -1
  107. package/dist/client-routes-DakuM32C.js.map +0 -1
  108. package/dist/context-BG8KCF3v.js +0 -15
  109. package/dist/context-BG8KCF3v.js.map +0 -1
  110. package/dist/context-aeo9esY9.d.ts +0 -16
  111. package/dist/cookies-Av5WFmcf.js.map +0 -1
  112. package/dist/devtools-BKjnHrnv.js +0 -113
  113. package/dist/devtools-BKjnHrnv.js.map +0 -1
  114. package/dist/devtools-panel-AWOn0VK2.js +0 -434
  115. package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
  116. package/dist/files-DdT84mPy.js.map +0 -1
  117. package/dist/html-DEeoepg3.js +0 -152
  118. package/dist/html-DEeoepg3.js.map +0 -1
  119. package/dist/html-Du8jY2Cc.d.ts +0 -53
  120. package/dist/inspect-BPchdWbU.js.map +0 -1
  121. package/dist/loader-Dc9OwY5I.js.map +0 -1
  122. package/dist/navigate-CzLjnoPH.js.map +0 -1
  123. package/dist/produce-BRGHP7e0.js +0 -126
  124. package/dist/produce-BRGHP7e0.js.map +0 -1
  125. package/dist/produce-CtZ32UGG.d.ts +0 -60
  126. package/dist/rpc-9fSqL_YK.js.map +0 -1
  127. package/dist/runtime/client.js.map +0 -1
  128. package/dist/server-BxqjLUnV.d.ts +0 -753
  129. package/dist/server-DZsgnPKS.js +0 -1615
  130. package/dist/server-DZsgnPKS.js.map +0 -1
  131. package/dist/shared-CWYOd0H3.js +0 -40
  132. package/dist/shared-CWYOd0H3.js.map +0 -1
  133. package/dist/static-loader-ClNkHZGn.js +0 -185
  134. package/dist/static-loader-ClNkHZGn.js.map +0 -1
  135. package/dist/stream-bgNCMcaA.js +0 -280
  136. package/dist/stream-bgNCMcaA.js.map +0 -1
package/dist/vite.js CHANGED
@@ -1,12 +1,160 @@
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-BPchdWbU.js";
2
- import { s as toNodeHeaders } from "./cookies-Av5WFmcf.js";
3
- import { a as hasUseServer, c as serverModule, i as findServerFiles, l as serverStubs, n as findFiles, o as isScriptFile, r as findScripts, s as serverExports, t as defaultExclude } from "./files-DdT84mPy.js";
1
+ import { A as analyzeProject, C as isReactiveModule, E as originalPosition, F as parse, M as forEachNode, N as resolveRelative, O as entryClasses, R as getLocation, T as builtin, _ as functionId, a as scopeLabel, b as SHARED_QUERY, f as instanceScope, i as report, k as refreshedNames, n as formatReport, p as slotIndex, s as compile, t as anchorLabel, v as getComponentName, w as resolveFromDisk, x as generateShared, y as hash } from "./inspect-BHpOw1LF.js";
2
+ import { s as toNodeHeaders } from "./cookies-BzllthiF.js";
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-BXSSrQgc.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
- import { isRunnableDevEnvironment, normalizePath, searchForWorkspaceRoot, transformWithOxc } from "vite";
10
+ import { isFileLoadingAllowed, isRunnableDevEnvironment, normalizePath, searchForWorkspaceRoot, transformWithOxc, version } 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
+ let end = property.end;
64
+ if (next) end = next.start;
65
+ else if (comma !== -1 && comma < schema.end) end = comma + 1;
66
+ result.serverRange = {
67
+ start: property.start,
68
+ end
69
+ };
70
+ }
71
+ });
72
+ return result;
73
+ }
74
+ /**
75
+ * The copy of the file that the browser gets: the server schemas are gone,
76
+ * and the values of the public variables, read when the build or the dev
77
+ * server ran, are the source of the call. The public schemas check them in
78
+ * the browser, as the server's do on the server.
79
+ */
80
+ function clientEnvModule(source, filename, values) {
81
+ const file = parseEnvFile(source, filename);
82
+ if (file.hasOptions) throw new Error(`${DEFINE} in ${filename} takes no options, because the Vite plugin writes the values of the browser`);
83
+ const given = {};
84
+ for (const name of file.public) {
85
+ const value = values[name];
86
+ if (value !== void 0) given[name] = value;
87
+ }
88
+ const edits = [{
89
+ start: file.schemaEnd,
90
+ end: file.schemaEnd,
91
+ text: `, { source: ${JSON.stringify(given)} }`
92
+ }];
93
+ if (file.serverRange) edits.push({
94
+ ...file.serverRange,
95
+ text: ""
96
+ });
97
+ let result = "";
98
+ let position = 0;
99
+ for (const edit of edits.toSorted((a, b) => a.start - b.start)) {
100
+ result += source.slice(position, edit.start) + edit.text;
101
+ position = edit.end;
102
+ }
103
+ return result + source.slice(position);
104
+ }
105
+ //#endregion
106
+ //#region src/builds.ts
107
+ /** The file in the client build that names its build. */
108
+ const BUILD_FILE = ".brumate/build.json";
109
+ /** The file in the client build that lists the builds whose files are in it. */
110
+ const BUILDS_FILE = ".brumate/builds.json";
111
+ /** The directory of the client build, from the root and the prerender options. */
112
+ function clientBuildDirectory(root, prerender) {
113
+ const client = typeof prerender === "object" ? prerender.client : void 0;
114
+ return path.resolve(root, client ?? "dist/client");
115
+ }
116
+ /** The ID of the build in a client build directory, or undefined without one. */
117
+ function readBuildId(directory) {
118
+ const file = path.join(directory, BUILD_FILE);
119
+ if (!existsSync(file)) return;
120
+ try {
121
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
122
+ return typeof parsed.build === "string" ? parsed.build : void 0;
123
+ } catch {
124
+ return;
125
+ }
126
+ }
127
+ /**
128
+ * Writes the ID of a build to its client output, adds the build to the list
129
+ * of builds, and removes the files of builds older than the `keep` builds
130
+ * before this one, unless a kept build wrote the same file. Returns the IDs
131
+ * of the builds whose files went.
132
+ */
133
+ function pruneBuilds(directory, id, files, keep, now = Date.now()) {
134
+ const list = path.join(directory, BUILDS_FILE);
135
+ let builds = [];
136
+ if (existsSync(list)) try {
137
+ builds = JSON.parse(readFileSync(list, "utf8")).builds ?? [];
138
+ } catch {
139
+ builds = [];
140
+ }
141
+ builds = builds.filter((build) => build.id !== id);
142
+ builds.push({
143
+ id,
144
+ at: now,
145
+ files
146
+ });
147
+ builds.sort((a, b) => a.at - b.at);
148
+ const kept = builds.slice(Math.max(0, builds.length - 1 - keep));
149
+ const dropped = builds.slice(0, builds.length - kept.length);
150
+ const keptFiles = new Set(kept.flatMap((build) => build.files));
151
+ for (const build of dropped) for (const file of build.files) if (!keptFiles.has(file)) rmSync(path.join(directory, file), { force: true });
152
+ mkdirSync(path.join(directory, ".brumate"), { recursive: true });
153
+ writeFileSync(path.join(directory, BUILD_FILE), `${JSON.stringify({ build: id })}\n`);
154
+ writeFileSync(list, `${JSON.stringify({ builds: kept }, null, 2)}\n`);
155
+ return dropped.map((build) => build.id);
156
+ }
157
+ //#endregion
10
158
  //#region src/packages.ts
11
159
  const toPosix = (file) => file.split(path.sep).join("/");
12
160
  function readJson(file) {
@@ -219,6 +367,10 @@ function reachableFiles(packages, appFiles, read) {
219
367
  return reached;
220
368
  }
221
369
  //#endregion
370
+ //#region src/version.ts
371
+ /** The version of brumate, which the devtools show. `package.json` is next to `src` and `dist`. */
372
+ const BRUMATE_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
373
+ //#endregion
222
374
  //#region src/dev-error.ts
223
375
  /** The overlay payload of an error, with the file, line and lines around it for compile errors. */
224
376
  function errorPayload(error, root = process.cwd()) {
@@ -282,11 +434,20 @@ function errorPage(error, server) {
282
434
  <script type="module">
283
435
  import { createHotContext } from '${base}@vite/client';
284
436
  const error = ${json};
285
- const Overlay = customElements.get('vite-error-overlay');
286
- if (Overlay) {
287
- document.body.append(new Overlay(error));
288
- } else {
289
- document.getElementById('brumate-error').textContent = [error.message, error.frame, error.stack].filter(Boolean).join('\\n\\n');
437
+ // The Errors tab of the devtools shows the error with its code. Vite's overlay is the fallback.
438
+ try {
439
+ const devtools = await import('${base}@id/brumate/devtools');
440
+ devtools.reportError(devtools.installDevtools(undefined, undefined, ${JSON.stringify({
441
+ version: BRUMATE_VERSION,
442
+ vite: version
443
+ })}), error, 'server');
444
+ } catch {
445
+ const Overlay = customElements.get('vite-error-overlay');
446
+ if (Overlay) {
447
+ document.body.append(new Overlay(error));
448
+ } else {
449
+ document.getElementById('brumate-error').textContent = [error.message, error.frame, error.stack].filter(Boolean).join('\\n\\n');
450
+ }
290
451
  }
291
452
  // A component that updates in place, after a fix, loads the page again.
292
453
  const hot = createHotContext('/@brumate/error');
@@ -339,7 +500,8 @@ async function prerender(routes, root, base, options) {
339
500
  const { handle } = await import(pathToFileURL(routes).href);
340
501
  const document = {
341
502
  head: options.head?.(manifest) ?? "",
342
- scripts: `<script type="module" async src="${base}${entry.file}"><\/script>`
503
+ scripts: `<script type="module" async src="${base}${entry.file}"><\/script>`,
504
+ prerender: true
343
505
  };
344
506
  const queue = [...options.paths ?? ["/"]];
345
507
  const seen = new Set(queue);
@@ -426,7 +588,7 @@ function routeEntries(node, resolve, path = "", layouts = []) {
426
588
  return result;
427
589
  }
428
590
  /** Measures the client build. */
429
- function buildReport({ chunks: list, sources, routes, budget }) {
591
+ function buildReport({ chunks: list, sources, routes, events: handlers, budget, relative = (file) => file }) {
430
592
  const chunks = new Map(list.map((chunk) => [chunk.fileName, chunk]));
431
593
  const sizes = new Map(list.map((chunk) => [chunk.fileName, gzipSize(chunk.code)]));
432
594
  const sum = (names) => {
@@ -440,19 +602,46 @@ function buildReport({ chunks: list, sources, routes, budget }) {
440
602
  const coreChunks = coreChunk ? withImports(coreChunk.fileName, chunks) : /* @__PURE__ */ new Set();
441
603
  for (const name of loaderChunks) coreChunks.delete(name);
442
604
  const byFile = /* @__PURE__ */ new Map();
605
+ const byModule = /* @__PURE__ */ new Map();
606
+ const everyPage = /* @__PURE__ */ new Set([...loaderChunks, ...coreChunks]);
443
607
  for (const chunk of list) for (const id of chunk.moduleIds) {
444
608
  const file = /^(.*\.brm)\?brumate-client/.exec(id)?.[1];
445
609
  if (file) {
446
610
  const set = byFile.get(file) ?? /* @__PURE__ */ new Set();
447
611
  withImports(chunk.fileName, chunks, set);
448
612
  byFile.set(file, set);
613
+ byModule.set(id, chunk.fileName);
449
614
  }
450
615
  }
451
- for (const set of byFile.values()) for (const name of [...loaderChunks, ...coreChunks]) set.delete(name);
616
+ for (const set of byFile.values()) for (const name of everyPage) set.delete(name);
452
617
  const components = [...byFile].map(([file, names]) => ({
453
618
  file,
454
619
  bytes: sum(names)
455
620
  })).toSorted((a, b) => b.bytes - a.bytes);
621
+ const eventChunks = (event) => {
622
+ const names = /* @__PURE__ */ new Set();
623
+ const entry = byModule.get(`${event.file}?brumate-client`);
624
+ if (entry) withImports(entry, chunks, names);
625
+ for (const part of event.parts) {
626
+ const chunk = byModule.get(`${event.file}?brumate-client&part=${part}`);
627
+ if (chunk) withImports(chunk, chunks, names);
628
+ }
629
+ for (const name of everyPage) names.delete(name);
630
+ return names;
631
+ };
632
+ const measured = (handlers ?? partEvents(byModule.keys())).map((event) => {
633
+ const names = eventChunks(event);
634
+ return {
635
+ event,
636
+ names,
637
+ bytes: sum(names)
638
+ };
639
+ });
640
+ const events = measured.map(({ event, bytes }) => ({
641
+ file: event.file,
642
+ label: event.label,
643
+ bytes
644
+ })).toSorted((a, b) => b.bytes - a.bytes);
456
645
  const reachable = (files) => {
457
646
  const seen = /* @__PURE__ */ new Set();
458
647
  const visit = (file) => {
@@ -478,14 +667,39 @@ function buildReport({ chunks: list, sources, routes, budget }) {
478
667
  const overBudget = [];
479
668
  if (budget?.loader !== void 0 && loader > budget.loader) overBudget.push(`The loader is ${formatBytes(loader)}, over the budget of ${formatBytes(budget.loader)}.`);
480
669
  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)}.`);
670
+ 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)}.`);
671
+ for (const { event, names, bytes } of measured.toSorted((a, b) => b.bytes - a.bytes)) if (budget?.event !== void 0 && bytes > budget.event) {
672
+ const imports = largestImports(names, chunks);
673
+ 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(", ")}.` : ""}`);
674
+ }
481
675
  return {
482
676
  loader,
483
677
  core: sum(coreChunks),
484
678
  components,
485
679
  routes: routeSizes,
680
+ events,
486
681
  overBudget
487
682
  };
488
683
  }
684
+ /** Each part of a client module as a handler of its own, when the build does not name them. */
685
+ function partEvents(ids) {
686
+ const result = [];
687
+ for (const id of ids) {
688
+ const match = /^(.*\.brm)\?brumate-client&part=(.+)$/.exec(id);
689
+ if (match && match[2] !== "update" && match[2] !== "shared") result.push({
690
+ file: match[1],
691
+ label: `part ${match[2]}`,
692
+ parts: [match[2]]
693
+ });
694
+ }
695
+ return result;
696
+ }
697
+ /** The three largest modules in the chunks that are not client modules of components. */
698
+ function largestImports(names, chunks) {
699
+ const sizes = [];
700
+ 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]);
701
+ return sizes.toSorted((a, b) => b[1] - a[1]).slice(0, 3).map(([id]) => id);
702
+ }
489
703
  function formatBytes(bytes) {
490
704
  return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} kB`;
491
705
  }
@@ -504,6 +718,10 @@ function formatBuildReport(report, relative) {
504
718
  lines.push(" Components, largest first");
505
719
  for (const component of report.components) lines.push(` ${relative(component.file)}: ${formatBytes(component.bytes)}`);
506
720
  }
721
+ if (report.events.length > 0) {
722
+ lines.push(" What the first run of a handler loads, largest first");
723
+ for (const event of report.events.slice(0, 10)) lines.push(` ${relative(event.file)} ${event.label}: ${formatBytes(event.bytes)}`);
724
+ }
507
725
  return lines.join("\n");
508
726
  }
509
727
  //#endregion
@@ -568,10 +786,13 @@ function routeFiles(paths) {
568
786
  /**
569
787
  * Writes a route tree as module code, with an import for each file. `rpc`
570
788
  * is the URL prefix of server function calls, for forms that post to one.
789
+ * `middleware` is the path of the entry middleware, which runs for every
790
+ * request, when the app has one.
571
791
  */
572
- function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false) {
792
+ function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false, middleware, build, hints = []) {
573
793
  const imports = [];
574
794
  const load = (file) => {
795
+ if (dev) return `() => import(${JSON.stringify(resolve(file))})`;
575
796
  const name = `m${imports.length}`;
576
797
  imports.push(`import * as ${name} from ${JSON.stringify(resolve(file))};`);
577
798
  return `() => Promise.resolve(${name})`;
@@ -606,11 +827,12 @@ function routeModule(tree, resolve, rpc = "/_brumate", origins = [], dev = false
606
827
  const routes = write(tree);
607
828
  return [
608
829
  "import { handleRoute } from 'brumate/server';",
609
- "import { functions } from 'virtual:brumate/server';",
830
+ "import { functions, fileMiddleware } from 'virtual:brumate/server';",
831
+ ...middleware ? [`import middleware from ${JSON.stringify(middleware)};`] : [],
610
832
  ...imports,
611
833
  `export const routes = ${routes};`,
612
834
  "export function handle(request, options) {",
613
- ` return handleRoute(routes, request, { rpc: ${JSON.stringify(rpc)}, origins: ${JSON.stringify(origins)}, functions${dev ? ", dev: true" : ""}, ...options });`,
835
+ ` 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
836
  "}"
615
837
  ].join("\n");
616
838
  }
@@ -663,8 +885,14 @@ const RENDER_QUERY = "?brumate-render";
663
885
  const SERVER_QUERY = "?brumate-server";
664
886
  /** Exports `mount` from `brumate/testing`, with the loader of this project's client modules. */
665
887
  const TESTING = "virtual:brumate/testing";
888
+ /** The modules that every page loads early, in the client build. See `hints` of `handleRoute`. */
889
+ const HINTS_FILE = ".brumate/hints.json";
666
890
  /** The dev server answers the devtools panel about a component at this path. */
667
891
  const INSPECT = "/__brumate/inspect";
892
+ /** Maps a position of a module that the browser ran to its source, for the Errors tab. */
893
+ const POSITION = "/__brumate/position";
894
+ /** The dev server sends the source of a file for the Errors tab of the devtools at this path. */
895
+ const SOURCE = "/__brumate/source";
668
896
  /** What tells two lists of packages of components apart. */
669
897
  function packagesKey(list) {
670
898
  return JSON.stringify(list.map((item) => [
@@ -743,9 +971,77 @@ function buildFingerprint() {
743
971
  /** The Vite plugin for `.brm` files. */
744
972
  function brumate(options = {}) {
745
973
  const rpc = options.rpc ?? "/_brumate";
974
+ /** The entry middleware, when the app has one. */
975
+ const middlewareFile = () => {
976
+ if (options.middleware === false) return;
977
+ const file = normalizePath(path.resolve(root, options.middleware ?? "src/middleware.ts"));
978
+ if (!existsSync(file)) {
979
+ if (options.middleware !== void 0) throw new Error(`The middleware file ${options.middleware} does not exist`);
980
+ return;
981
+ }
982
+ return file;
983
+ };
984
+ /** The serial entry, when the app has one. */
985
+ const serialFile = () => {
986
+ if (options.serial === false) return;
987
+ const file = normalizePath(path.resolve(root, options.serial ?? "src/serial.ts"));
988
+ if (!existsSync(file)) {
989
+ if (options.serial !== void 0) throw new Error(`The serial entry ${options.serial} does not exist`);
990
+ return;
991
+ }
992
+ return file;
993
+ };
994
+ /** The classes that the plugins of the serial entry send, read from its `instanceof` checks. */
995
+ let serialRead;
996
+ const serialClasses = () => {
997
+ const file = serialFile();
998
+ if (!file) return [];
999
+ const source = readFileSync(file, "utf8");
1000
+ if (serialRead?.source !== source) {
1001
+ const { program } = parseSync(file, source, { lang: "ts" });
1002
+ serialRead = {
1003
+ source,
1004
+ classes: entryClasses(program)
1005
+ };
1006
+ }
1007
+ return serialRead.classes;
1008
+ };
1009
+ /** The lines that give the server the serial entry, before anything is written or read. */
1010
+ const serialImports = () => {
1011
+ const file = serialFile();
1012
+ return file ? [
1013
+ `import * as $$serial from ${JSON.stringify(file)};`,
1014
+ "import { useSerialEntry } from 'brumate/server';",
1015
+ "useSerialEntry($$serial);"
1016
+ ] : [];
1017
+ };
1018
+ /** The file of environment variables, when the app has one. */
1019
+ const envFile = () => {
1020
+ if (options.env === false) return;
1021
+ const file = normalizePath(path.resolve(root, options.env ?? "src/env.ts"));
1022
+ if (!existsSync(file)) {
1023
+ if (options.env !== void 0) throw new Error(`The env file ${options.env} does not exist`);
1024
+ return;
1025
+ }
1026
+ return file;
1027
+ };
1028
+ /** The names of the server variables, read from the env file, by its source. */
1029
+ let envKeys;
1030
+ const serverEnvKeys = () => {
1031
+ const file = envFile();
1032
+ if (!file) return;
1033
+ const source = readFileSync(file, "utf8");
1034
+ if (envKeys?.source !== source) envKeys = {
1035
+ source,
1036
+ server: parseEnvFile(source, file).server
1037
+ };
1038
+ return envKeys.server;
1039
+ };
746
1040
  const exclude = options.exclude ?? defaultExclude;
747
1041
  let root = process.cwd();
748
1042
  let outDir = "";
1043
+ /** The ID of the build, for skew protection. Undefined on the dev server. */
1044
+ let buildId;
749
1045
  let base = "/";
750
1046
  let isSsrBuild = false;
751
1047
  let isServe = false;
@@ -758,6 +1054,8 @@ function brumate(options = {}) {
758
1054
  const shapes = /* @__PURE__ */ new Map();
759
1055
  /** The props that parents can change, by absolute file path. */
760
1056
  let liveProps = /* @__PURE__ */ new Map();
1057
+ /** The names of the server functions that the app refreshes, or undefined before the first scan. */
1058
+ let refreshed;
761
1059
  /** The dependencies of the app that ship `.brm` files. See `packages.ts`. */
762
1060
  let packages = [];
763
1061
  const relative = (file) => normalizePath(path.relative(root, file));
@@ -841,37 +1139,69 @@ function brumate(options = {}) {
841
1139
  const contents = await Promise.all(list.map((file) => readFile(file, "utf8")));
842
1140
  const sources = new Map(list.map((file, index) => [file, contents[index]]));
843
1141
  liveProps = analyzeProject(sources, resolveComponent);
1142
+ const scripts = await findScripts(root, exclude);
1143
+ const scriptSources = await Promise.all([.../* @__PURE__ */ new Set([...scripts, ...serverFiles.values()])].map((file) => readFile(file, "utf8").catch(() => "")));
1144
+ refreshed = refreshedNames([...contents, ...scriptSources]);
844
1145
  compiled.clear();
845
1146
  };
1147
+ /** The options of the compile of a file. */
1148
+ const compileOptions = (file) => ({
1149
+ filename: nameOf(file),
1150
+ liveProps: liveProps.get(file),
1151
+ refreshed,
1152
+ path: file,
1153
+ merge: options.merge ?? 4096,
1154
+ a11y: options.a11y,
1155
+ hideNames: !isServe,
1156
+ sendableClasses: serialClasses(),
1157
+ serverImport: (specifier, name) => serverImport(file, specifier, name),
1158
+ resolveModule: (specifier, importer) => {
1159
+ const local = resolveFromDisk(specifier, importer);
1160
+ const found = local === void 0 && isPackageSpecifier(specifier) ? resolvePackageImport(specifier, importer) : void 0;
1161
+ return found ? {
1162
+ path: found,
1163
+ source: readFileSync(found, "utf8")
1164
+ } : local;
1165
+ }
1166
+ });
846
1167
  const compileFile = async (file) => {
847
1168
  const source = await readFile(file, "utf8");
848
1169
  let cached = compiled.get(file);
849
1170
  if (cached?.source !== source) {
850
1171
  cached = {
851
1172
  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
- })
1173
+ result: compile(source, compileOptions(file))
869
1174
  };
870
1175
  compiled.set(file, cached);
871
1176
  shapes.set(file, shapeOf(cached.result));
872
1177
  }
873
1178
  return cached;
874
1179
  };
1180
+ /** The compiles whose imports were checked for the env file. */
1181
+ const envChecked = /* @__PURE__ */ new WeakSet();
1182
+ /**
1183
+ * Compiles a component again with the server variables of the env file,
1184
+ * when one of its imports resolves to it, by any specifier, such as an
1185
+ * alias. The compile fails when code that runs in the browser reads one.
1186
+ */
1187
+ const checkEnvReads = async (file, { source, result }, resolve) => {
1188
+ const env = envFile();
1189
+ if (!env || envChecked.has(result)) return;
1190
+ const specifiers = /* @__PURE__ */ new Set();
1191
+ for (const declaration of result.plan.graph.model.declarations) if (declaration.imported) specifiers.add(declaration.imported.source);
1192
+ const resolved = await Promise.all([...specifiers].map(async (specifier) => {
1193
+ return (await resolve(specifier, file))?.id.split("?")[0] === env ? specifier : void 0;
1194
+ }));
1195
+ const imports = new Set(resolved.filter((specifier) => specifier !== void 0));
1196
+ if (imports.size > 0) {
1197
+ const server = serverEnvKeys() ?? [];
1198
+ compile(source, {
1199
+ ...compileOptions(file),
1200
+ envImport: (specifier) => imports.has(specifier) ? server : void 0
1201
+ });
1202
+ }
1203
+ envChecked.add(result);
1204
+ };
875
1205
  const manifest = async () => {
876
1206
  const list = [...files];
877
1207
  const needed = await Promise.all(list.map(async ([, file]) => isServe || (await compileFile(file)).result.clientCode));
@@ -900,23 +1230,45 @@ function brumate(options = {}) {
900
1230
  registered = packages.length > 0 ? reachable() : /* @__PURE__ */ new Set();
901
1231
  const keep = (file) => registered.has(file) || !packageOf(packages, file);
902
1232
  const components = [...files.values()].filter(keep);
903
- const imports = components.map((file, index) => `import * as m${index} from ${JSON.stringify(file + query)};`);
1233
+ const importAll = (prefix, list) => {
1234
+ if (!isServe) return list.map((file, index) => `import * as ${prefix}${index} from ${JSON.stringify(file + query)};`);
1235
+ if (list.length === 0) return [];
1236
+ const loads = list.map((file) => `import(${JSON.stringify(file + query)})`);
1237
+ return [`const [${list.map((_, index) => `${prefix}${index}`).join(", ")}] = (await Promise.allSettled([${loads.join(", ")}])).map((result) => (result.status === 'fulfilled' ? result.value : {}));`];
1238
+ };
1239
+ const imports = importAll("m", components);
904
1240
  const spreads = components.map((_, index) => ` ...m${index}.rpc,`);
905
1241
  const functionFiles = [...serverFiles.entries()].filter(([, file]) => keep(file));
906
- const fileImports = functionFiles.map(([, file], index) => `import * as f${index} from ${JSON.stringify(file + query)};`);
1242
+ const fileImports = importAll("f", functionFiles.map(([, file]) => file));
1243
+ const guards = [];
907
1244
  const fileSpreads = functionFiles.map(([id, file], index) => {
908
- return serverExports(readFileSync(file, "utf8"), file).map((name) => ` ${JSON.stringify(functionId(id, name, !isServe))}: f${index}[${JSON.stringify(name)}],`).join("\n");
1245
+ const source = readFileSync(file, "utf8");
1246
+ const names = serverExports(source, file);
1247
+ const guarded = hasServerMiddleware(source, file);
1248
+ return names.map((name) => {
1249
+ const key = JSON.stringify(functionId(id, name, !isServe));
1250
+ if (guarded) guards.push(` ${key}: f${index}.middleware,`);
1251
+ return ` ${key}: f${index}[${JSON.stringify(name)}],`;
1252
+ }).join("\n");
909
1253
  });
1254
+ const env = envFile();
1255
+ const entry = middlewareFile();
910
1256
  return [
1257
+ ...env ? [`import ${JSON.stringify(env)};`] : [],
1258
+ ...serialImports(),
911
1259
  "import { handleRequest } from 'brumate/server';",
1260
+ ...entry ? [`import middleware from ${JSON.stringify(entry)};`] : [],
912
1261
  ...imports,
913
1262
  ...fileImports,
914
1263
  "export const functions = {",
915
1264
  ...spreads,
916
1265
  ...fileSpreads,
917
1266
  "};",
918
- "export function handle(request) {",
919
- ` return handleRequest(functions, request, ${JSON.stringify(rpc)}, { origins: ${JSON.stringify(options.origins ?? [])} });`,
1267
+ "export const fileMiddleware = {",
1268
+ ...guards,
1269
+ "};",
1270
+ "export function handle(request, options) {",
1271
+ ` return handleRequest(functions, request, ${JSON.stringify(rpc)}, { origins: ${JSON.stringify(options.origins ?? [])}, ${entry ? "middleware, " : ""}fileMiddleware${buildId === void 0 ? "" : `, build: ${JSON.stringify(buildId)}`}, ...options });`,
920
1272
  "}"
921
1273
  ].join("\n");
922
1274
  };
@@ -934,7 +1286,25 @@ function brumate(options = {}) {
934
1286
  }
935
1287
  return routeFiles(paths);
936
1288
  };
937
- const routeTree = () => routeModule(currentRoutes(), (file) => `${routesDirectory()}/${file}`, rpc, options.origins, isServe);
1289
+ /**
1290
+ * The modules that every page loads early, which the client build wrote,
1291
+ * or none before a client build or in development.
1292
+ */
1293
+ const clientHints = () => {
1294
+ const file = path.join(clientBuildDirectory(root, options.prerender), HINTS_FILE);
1295
+ return !isServe && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : [];
1296
+ };
1297
+ /** The route tree module. A DOM test gets the server version of each component in it. */
1298
+ const routeTree = (server = false) => {
1299
+ const env = envFile();
1300
+ const code = routeModule(currentRoutes(), (file) => `${routesDirectory()}/${file}${server && file.endsWith(".brm") ? SERVER_QUERY : ""}`, rpc, options.origins, isServe, middlewareFile(), buildId, clientHints());
1301
+ const serial = serialImports().join("\n");
1302
+ return [
1303
+ env ? `import ${JSON.stringify(env)};` : "",
1304
+ serial,
1305
+ code
1306
+ ].filter(Boolean).join("\n");
1307
+ };
938
1308
  /** Writes the paths of the routes as types for `href`, when they changed. */
939
1309
  const writeRouteTypes = () => {
940
1310
  if (options.routeTypes === false || !existsSync(routesDirectory())) return;
@@ -949,9 +1319,16 @@ function brumate(options = {}) {
949
1319
  const { source, result } = await compileFile(file);
950
1320
  const { plan } = result;
951
1321
  const scopes = {};
1322
+ const siteLabel = (site) => {
1323
+ const at = result.locate(site.range.start);
1324
+ const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
1325
+ return where ? `${site.label} ${where.line}:${where.column}` : site.label;
1326
+ };
1327
+ const liveSites = new Set([...plan.graph.live].flatMap((node) => "site" in node ? [node.site] : []));
952
1328
  for (const layout of plan.scopes.values()) scopes[layout.scope.id] = {
953
1329
  label: scopeLabel(result.file.source, layout.scope),
954
- slots: layout.slots.map((slot) => slot.name)
1330
+ slots: layout.slots.map((slot) => slot.name),
1331
+ readers: layout.slots.map((slot) => [...new Set(slot.reads.filter((ref) => plan.graph.reached.has(ref.site) || liveSites.has(ref.site)).map((ref) => siteLabel(ref.site)))])
955
1332
  };
956
1333
  const nodes = plan.graph.nodes.filter((node) => plan.graph.live.has(node));
957
1334
  const indexes = new Map(nodes.map((node, index) => [node, index]));
@@ -973,11 +1350,41 @@ function brumate(options = {}) {
973
1350
  }),
974
1351
  edges: plan.graph.edges.filter((edge) => indexes.has(edge.from) && indexes.has(edge.to)).map((edge) => [indexes.get(edge.from), indexes.get(edge.to)])
975
1352
  };
1353
+ const anchors = {};
1354
+ for (const [target, index] of plan.anchors) {
1355
+ const scope = plan.anchorScopes.get(target);
1356
+ if (!scope) continue;
1357
+ const at = result.locate("range" in target ? target.range.start : target.start);
1358
+ const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
1359
+ const reads = /* @__PURE__ */ new Set();
1360
+ for (const edge of plan.graph.edges) {
1361
+ const node = edge.to;
1362
+ if (node.kind === "source" || node.kind === "memo") continue;
1363
+ const site = node.site;
1364
+ const range = !("range" in target) && target.kind === "insert" ? target : void 0;
1365
+ if (site === target || site.owner === target || site.block === target || range && site.range.start >= range.start && site.range.end <= range.end) {
1366
+ if (edge.from.kind === "source" || edge.from.kind === "memo") reads.add(edge.from.declaration.name);
1367
+ }
1368
+ }
1369
+ const known = anchors[scope.id]?.[index];
1370
+ if (known) {
1371
+ known.reads = [.../* @__PURE__ */ new Set([...known.reads, ...reads])];
1372
+ continue;
1373
+ }
1374
+ (anchors[scope.id] ??= {})[index] = {
1375
+ label: anchorLabel(target),
1376
+ ...where ? { at: `${where.line}:${where.column}` } : {},
1377
+ reads: [...reads]
1378
+ };
1379
+ }
976
1380
  const text = formatReport(report(source, result, liveProps.get(file)));
977
1381
  return {
978
1382
  name: plan.name,
979
1383
  file: nameOf(file),
1384
+ path: file,
1385
+ url: file.startsWith(`${normalizePath(root)}/`) ? file.slice(normalizePath(root).length) : `/@fs${file}`,
980
1386
  scopes,
1387
+ anchors,
981
1388
  graph,
982
1389
  text
983
1390
  };
@@ -997,13 +1404,15 @@ function brumate(options = {}) {
997
1404
  if (module) server.moduleGraph.invalidateModule(module);
998
1405
  }
999
1406
  try {
1000
- const { functions } = await server.ssrLoadModule(SERVER);
1001
- const { handleRequest } = await server.ssrLoadModule("brumate/server");
1002
- const answer = await handleRequest(functions, new Request(new URL(request.url ?? "/", "http://localhost"), {
1407
+ const { handle } = await server.ssrLoadModule(SERVER);
1408
+ const webRequest = new Request(new URL(request.url ?? "/", "http://localhost"), {
1003
1409
  method: "POST",
1004
1410
  headers: Object.entries(request.headers).flatMap(([name, value]) => value === void 0 ? [] : [[name, String(value)]]),
1005
1411
  body: new Uint8Array(await readBody(request))
1006
- }), rpc, { origins: options.origins });
1412
+ });
1413
+ const began = performance.now();
1414
+ const answer = await handle(webRequest, { address: request.socket.remoteAddress });
1415
+ answer.headers.append("server-timing", `brumate;dur=${(performance.now() - began).toFixed(1)};desc="server function"`);
1007
1416
  response.statusCode = answer.status;
1008
1417
  for (const [name, value] of Object.entries(toNodeHeaders(answer.headers))) response.setHeader(name, value);
1009
1418
  response.end(await answer.text());
@@ -1095,24 +1504,36 @@ function brumate(options = {}) {
1095
1504
  config(config, env) {
1096
1505
  packages = findPackages(path.resolve(config.root ?? process.cwd()));
1097
1506
  const shared = packageConfig(config);
1507
+ const hmr = config.server?.hmr;
1508
+ if (env.command === "serve" && options.devtools !== false && hmr !== false && (typeof hmr !== "object" || hmr.overlay === void 0)) shared.server = { hmr: { overlay: false } };
1098
1509
  if (!env.isSsrBuild) {
1099
1510
  const preload = config.build?.modulePreload;
1100
- if (preload === false) return shared;
1511
+ const keep = options.skew?.keep ? { build: { emptyOutDir: false } } : {};
1512
+ if (preload === false) return {
1513
+ ...shared,
1514
+ ...keep
1515
+ };
1101
1516
  const resolve = typeof preload === "object" ? preload.resolveDependencies : void 0;
1102
1517
  return {
1103
1518
  ...shared,
1104
- build: { modulePreload: { resolveDependencies(filename, deps, context) {
1105
- const list = resolve ? resolve(filename, deps, context) : deps;
1106
- if (context.hostId !== loaderChunk || !coreChunk) return list;
1107
- const rest = list.filter((dep) => dep !== coreChunk);
1108
- return rest.length === 1 && rest[0] === filename ? [] : rest;
1109
- } } }
1519
+ build: {
1520
+ ...keep.build,
1521
+ modulePreload: { resolveDependencies(filename, deps, context) {
1522
+ const list = resolve ? resolve(filename, deps, context) : deps;
1523
+ if (context.hostId !== loaderChunk || !coreChunk) return list;
1524
+ const rest = list.filter((dep) => dep !== coreChunk);
1525
+ return rest.length === 1 && rest[0] === filename ? [] : rest;
1526
+ } }
1527
+ }
1110
1528
  };
1111
1529
  }
1112
1530
  if (!options.prerender) return shared;
1113
1531
  const ssr = config.build?.ssr;
1114
1532
  const input = typeof ssr === "string" ? ssr : config.build?.rolldownOptions?.input;
1115
- const entries = typeof input === "string" ? { [path.basename(input).replace(/\.[^.]+$/, "")]: input } : Array.isArray(input) ? Object.fromEntries(input.map((item) => [path.basename(item).replace(/\.[^.]+$/, ""), item])) : { ...input };
1533
+ let entries;
1534
+ if (typeof input === "string") entries = { [path.basename(input).replace(/\.[^.]+$/, "")]: input };
1535
+ else if (Array.isArray(input)) entries = Object.fromEntries(input.map((item) => [path.basename(item).replace(/\.[^.]+$/, ""), item]));
1536
+ else entries = { ...input };
1116
1537
  return {
1117
1538
  ...shared,
1118
1539
  build: {
@@ -1150,10 +1571,23 @@ function brumate(options = {}) {
1150
1571
  code: item.code,
1151
1572
  isEntry: item.isEntry,
1152
1573
  imports: item.imports,
1153
- moduleIds: item.moduleIds
1574
+ moduleIds: item.moduleIds,
1575
+ modules: Object.fromEntries(Object.entries(item.modules).map(([id, module]) => [id, module.renderedLength]))
1154
1576
  });
1155
1577
  const list = [...files.values()];
1156
1578
  const contents = await Promise.all(list.map((file) => readFile(file, "utf8")));
1579
+ const events = [];
1580
+ for (const [file, { source, result }] of compiled) for (const [site, symbol] of result.plan.symbols) {
1581
+ const loads = result.loaders[symbol];
1582
+ if (loads) {
1583
+ const { line, column } = getLocation(source, site.range.start);
1584
+ events.push({
1585
+ file,
1586
+ label: `${site.label} (${line}:${column})`,
1587
+ parts: loads
1588
+ });
1589
+ }
1590
+ }
1157
1591
  const measured = buildReport({
1158
1592
  chunks,
1159
1593
  sources: new Map(list.map((file, index) => [file, contents[index]])),
@@ -1161,12 +1595,35 @@ function brumate(options = {}) {
1161
1595
  tree: currentRoutes(),
1162
1596
  resolve: (file) => `${routesDirectory()}/${file}`
1163
1597
  } : void 0,
1164
- budget: options.budget
1598
+ events,
1599
+ budget: options.budget,
1600
+ relative: nameOf
1165
1601
  });
1166
1602
  if (options.report) this.info(`\n${formatBuildReport(measured, nameOf)}`);
1167
1603
  if (measured.overBudget.length > 0) this.error(measured.overBudget.join("\n"));
1168
1604
  },
1169
1605
  async writeBundle(_output, bundle) {
1606
+ if (!isSsrBuild) {
1607
+ const chunks = new Map(Object.values(bundle).flatMap((item) => item.type === "chunk" ? [[item.fileName, item]] : []));
1608
+ const hints = /* @__PURE__ */ new Set();
1609
+ const add = (name) => {
1610
+ const chunk = name === void 0 ? void 0 : chunks.get(name);
1611
+ if (chunk && !hints.has(chunk.fileName)) {
1612
+ hints.add(chunk.fileName);
1613
+ chunk.imports.forEach(add);
1614
+ }
1615
+ };
1616
+ add(loaderChunk);
1617
+ add(coreChunk);
1618
+ await mkdir(path.join(outDir, ".brumate"), { recursive: true });
1619
+ await writeFile(path.join(outDir, HINTS_FILE), JSON.stringify([...hints].map((name) => `${base}${name}`)));
1620
+ if (buildId !== void 0) {
1621
+ const written = Object.values(bundle).map((item) => item.fileName);
1622
+ const removed = pruneBuilds(outDir, buildId, written, options.skew?.keep ?? 0);
1623
+ if (removed.length > 0) this.info(`Removed the files of ${removed.length} older builds`);
1624
+ }
1625
+ return;
1626
+ }
1170
1627
  if (!options.prerender || !isSsrBuild) return;
1171
1628
  const chunk = Object.values(bundle).find((item) => item.type === "chunk" && item.isEntry && item.name === PRERENDER_ENTRY);
1172
1629
  if (!chunk) return;
@@ -1175,13 +1632,30 @@ function brumate(options = {}) {
1175
1632
  this.info(`Prerendered ${written.length} pages`);
1176
1633
  },
1177
1634
  async buildStart() {
1635
+ if (!isServe) {
1636
+ if (isSsrBuild) {
1637
+ const client = clientBuildDirectory(root, options.prerender);
1638
+ buildId = process.env.BRUMATE_BUILD || readBuildId(client);
1639
+ 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`);
1640
+ } else buildId = process.env.BRUMATE_BUILD || `${Date.now().toString(36)}${hash(String(Math.random()))}`;
1641
+ }
1178
1642
  coreModule = isServe ? void 0 : (await this.resolve("brumate/client", path.join(root, "index.html")))?.id;
1179
1643
  await scan();
1180
1644
  writeRouteTypes();
1181
1645
  },
1182
1646
  async resolveId(id, importer, resolveOptions) {
1183
1647
  if (id === START || id === MANIFEST || id === SERVER || id === ROUTES || id === TESTING) return `\0${id}`;
1184
- if (resolveOptions?.ssr || !importer || !importer.includes(SERVER_QUERY) && importer !== `\0${SERVER}` || id.includes(SERVER_QUERY)) return;
1648
+ const env = resolveOptions?.ssr ? void 0 : envFile();
1649
+ const from = importer?.split("?")[0];
1650
+ if (env && importer && from && from !== env && isScriptFile(from) && !importer.startsWith("\0") && !importer.includes(SERVER_QUERY) && !importer.includes("/node_modules/")) {
1651
+ const resolved = await this.resolve(id, importer, {
1652
+ ...resolveOptions,
1653
+ skipSelf: true
1654
+ });
1655
+ 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.`);
1656
+ return resolved ?? void 0;
1657
+ }
1658
+ if (resolveOptions?.ssr || !importer || !importer.includes(SERVER_QUERY) && importer !== `\0${SERVER}` && importer !== `\0${ROUTES}` || id.includes(SERVER_QUERY)) return;
1185
1659
  const resolved = await this.resolve(id, importer, {
1186
1660
  ...resolveOptions,
1187
1661
  skipSelf: true
@@ -1213,20 +1687,34 @@ function brumate(options = {}) {
1213
1687
  options.navigate === false ? "import { startWithoutNavigation as start } from 'brumate/static-loader';" : "import { start } from 'brumate/loader';",
1214
1688
  `import { load } from ${JSON.stringify(MANIFEST)};`,
1215
1689
  ...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" : ""} });`,
1217
- ...isServe && options.devtools !== false ? [`import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}));`] : []
1690
+ `start({ load${isServe ? ": hotLoad(import.meta.hot, load)" : ""}${serialFile() ? `, serial: () => import(${JSON.stringify(serialFile())})` : ""}, rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)}${options.preload === false ? ", preload: false" : ""}${buildId === void 0 ? "" : `, build: ${JSON.stringify(buildId)}`} });`,
1691
+ ...isServe && options.devtools !== false ? [`import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}, ${JSON.stringify({
1692
+ version: BRUMATE_VERSION,
1693
+ vite: version
1694
+ })}, import.meta.hot));`] : []
1218
1695
  ].join("\n");
1219
1696
  if (id === `\0${MANIFEST}`) return await manifest();
1220
1697
  if (id === `\0${SERVER}`) return serverRegistry(!loadOptions?.ssr);
1221
- if (id === `\0${ROUTES}`) return routeTree();
1222
- if (id === `\0${TESTING}`) return [
1223
- "import { answerCalls as answer, createMount } from 'brumate/testing';",
1224
- `import { load } from ${JSON.stringify(MANIFEST)};`,
1225
- `export const mount = createMount({ load, rpc: ${JSON.stringify(rpc)} });`,
1226
- "export function answerCalls(options) {",
1227
- ` return answer(async () => (await import(${JSON.stringify(SERVER)})).functions, { rpc: ${JSON.stringify(rpc)}, ...options });`,
1228
- "}"
1229
- ].join("\n");
1698
+ if (id === `\0${ROUTES}`) return routeTree(!loadOptions?.ssr);
1699
+ if (id === `\0${TESTING}`) {
1700
+ const entry = middlewareFile();
1701
+ return [
1702
+ "import { answerCalls as answer, createMount, createVisit } from 'brumate/testing';",
1703
+ `import { load } from ${JSON.stringify(MANIFEST)};`,
1704
+ ...entry ? [`import middleware from ${JSON.stringify(entry)};`] : [],
1705
+ `export const mount = createMount({ load, rpc: ${JSON.stringify(rpc)} });`,
1706
+ "export const visit = createVisit({",
1707
+ " load,",
1708
+ ` rpc: ${JSON.stringify(rpc)},`,
1709
+ ` routes: async () => (await import(${JSON.stringify(ROUTES)})).handle,`,
1710
+ ` calls: async () => (await import(${JSON.stringify(SERVER)})).handle,`,
1711
+ "});",
1712
+ "export function answerCalls(options) {",
1713
+ ` const server = import(${JSON.stringify(SERVER)});`,
1714
+ ` return answer(async () => (await server).functions, { rpc: ${JSON.stringify(rpc)}, ${entry ? "middleware, " : ""}fileMiddleware: async () => (await server).fileMiddleware, ...options });`,
1715
+ "}"
1716
+ ].join("\n");
1717
+ }
1230
1718
  const [file, query] = id.split("?");
1231
1719
  if (!file?.endsWith(".brm")) return;
1232
1720
  const params = new URLSearchParams(query);
@@ -1236,6 +1724,7 @@ function brumate(options = {}) {
1236
1724
  let output;
1237
1725
  try {
1238
1726
  output = await compileFile(file);
1727
+ await checkEnvReads(file, output, (specifier, importer) => this.resolve(specifier, importer));
1239
1728
  } catch (error) {
1240
1729
  const { message, frame, loc } = errorPayload(error, root);
1241
1730
  this.error({
@@ -1285,6 +1774,14 @@ function brumate(options = {}) {
1285
1774
  },
1286
1775
  async transform(code, id, transformOptions) {
1287
1776
  const [file] = id.split("?");
1777
+ if (file && !transformOptions?.ssr && file === envFile()) try {
1778
+ return {
1779
+ code: clientEnvModule(code, file, process.env),
1780
+ map: null
1781
+ };
1782
+ } catch (error) {
1783
+ this.error(error.message);
1784
+ }
1288
1785
  if (file && isScriptFile(file) && hasUseServer(code)) try {
1289
1786
  const fileId = serverFileId(normalizePath(file));
1290
1787
  if (transformOptions?.ssr) return {
@@ -1292,8 +1789,11 @@ function brumate(options = {}) {
1292
1789
  map: null
1293
1790
  };
1294
1791
  if (id.includes(SERVER_QUERY)) {
1792
+ let lang = "jsx";
1793
+ if (/\.[cm]?ts$/.test(file)) lang = "ts";
1794
+ else if (file.endsWith(".tsx")) lang = "tsx";
1295
1795
  const result = await transformWithOxc(serverModule(code, file, fileId), file, {
1296
- lang: /\.[cm]?ts$/.test(file) ? "ts" : file.endsWith(".tsx") ? "tsx" : "jsx",
1796
+ lang,
1297
1797
  sourcemap: true
1298
1798
  });
1299
1799
  return {
@@ -1328,6 +1828,7 @@ function brumate(options = {}) {
1328
1828
  if (manifests.includes(normalizePath(file)) && packagesKey(findPackages(root)) !== packagesKey(packages)) server.restart();
1329
1829
  });
1330
1830
  server.watcher.on("all", (event, file) => {
1831
+ if (normalizePath(file) === envFile()) compiled.clear();
1331
1832
  for (const importer of dependents.get(normalizePath(file)) ?? []) {
1332
1833
  compiled.delete(importer);
1333
1834
  for (const module of server.moduleGraph.getModulesByFile(importer) ?? []) server.moduleGraph.invalidateModule(module);
@@ -1365,6 +1866,32 @@ function brumate(options = {}) {
1365
1866
  handleDevRPC(server, request, response);
1366
1867
  return;
1367
1868
  }
1869
+ if (request.method === "GET" && request.url?.startsWith(`${SOURCE}?`)) {
1870
+ const asked = new URL(request.url, "http://localhost").searchParams.get("file") ?? "";
1871
+ const file = normalizePath(path.isAbsolute(asked) && existsSync(asked) ? asked : path.join(server.config.root, asked));
1872
+ if (!existsSync(file) || !isFileLoadingAllowed(server.config, file)) {
1873
+ response.statusCode = 404;
1874
+ response.end();
1875
+ return;
1876
+ }
1877
+ response.setHeader("content-type", "text/plain; charset=utf-8");
1878
+ response.end(readFileSync(file, "utf8"));
1879
+ return;
1880
+ }
1881
+ if (request.method === "GET" && request.url?.startsWith(`${POSITION}?`)) {
1882
+ const params = new URL(request.url, "http://localhost").searchParams;
1883
+ server.environments.client.moduleGraph.getModuleByUrl(params.get("url") ?? "").then((module) => {
1884
+ const map = module?.transformResult?.map;
1885
+ const place = map && module?.file ? originalPosition(map, Number(params.get("line")), Number(params.get("column"))) : void 0;
1886
+ const file = place && normalizePath(place.source.startsWith("/") && !existsSync(place.source) ? path.join(server.config.root, place.source) : path.resolve(path.dirname(module.file), place.source));
1887
+ response.setHeader("content-type", "application/json");
1888
+ response.end(JSON.stringify(place ? {
1889
+ ...place,
1890
+ file
1891
+ } : null));
1892
+ }).catch(next);
1893
+ return;
1894
+ }
1368
1895
  if (request.method === "GET" && request.url?.startsWith(`${INSPECT}/`)) {
1369
1896
  inspectComponent(decodeURIComponent(request.url.slice(19))).then((info) => {
1370
1897
  response.statusCode = info ? 200 : 404;
@@ -1380,7 +1907,10 @@ function brumate(options = {}) {
1380
1907
  const environment = this.environment;
1381
1908
  if (environment.config.consumer === "client") return updateClient(file, server, timestamp);
1382
1909
  const normalized = normalizePath(file);
1383
- if (!file.endsWith(".brm") && !dependents.has(normalized)) return;
1910
+ if (!file.endsWith(".brm") && !dependents.has(normalized) && normalized !== middlewareFile() && normalized !== envFile()) {
1911
+ if (environment.moduleGraph.getModulesByFile(normalized)?.size) server.environments.client.hot.send({ type: "full-reload" });
1912
+ return;
1913
+ }
1384
1914
  const invalidated = /* @__PURE__ */ new Set();
1385
1915
  for (const module of environment.moduleGraph.idToModuleMap.values()) {
1386
1916
  const id = module.id ?? "";