brumate 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +43 -72
  2. package/dist/boot-DN1ZU8Hg.d.ts +37 -0
  3. package/dist/cli.js +2 -2
  4. package/dist/{client-DuDTDePF.d.ts → client-DwJInP_a.d.ts} +133 -44
  5. package/dist/client-routes-DakuM32C.js +94 -0
  6. package/dist/client-routes-DakuM32C.js.map +1 -0
  7. package/dist/{cookies-rgIAc8IE.js → cookies-Av5WFmcf.js} +18 -8
  8. package/dist/cookies-Av5WFmcf.js.map +1 -0
  9. package/dist/{devtools-Bm8cS7hX.js → devtools-BKjnHrnv.js} +10 -5
  10. package/dist/devtools-BKjnHrnv.js.map +1 -0
  11. package/dist/{devtools-panel-CTbDSBBA.js → devtools-panel-AWOn0VK2.js} +23 -26
  12. package/dist/devtools-panel-AWOn0VK2.js.map +1 -0
  13. package/dist/{files-D_JUcSU5.js → files-DdT84mPy.js} +22 -3
  14. package/dist/{files-D_JUcSU5.js.map → files-DdT84mPy.js.map} +1 -1
  15. package/dist/{html-CxWpXngy.js → html-DEeoepg3.js} +47 -10
  16. package/dist/html-DEeoepg3.js.map +1 -0
  17. package/dist/{html-DV-Tezgq.d.ts → html-Du8jY2Cc.d.ts} +14 -2
  18. package/dist/index.d.ts +65 -6
  19. package/dist/index.js +20 -4
  20. package/dist/index.js.map +1 -1
  21. package/dist/{inspect-CGCWfaEx.js → inspect-BPchdWbU.js} +887 -172
  22. package/dist/inspect-BPchdWbU.js.map +1 -0
  23. package/dist/loader-Dc9OwY5I.js +101 -0
  24. package/dist/loader-Dc9OwY5I.js.map +1 -0
  25. package/dist/{navigate-C5dP89YL.js → navigate-CzLjnoPH.js} +112 -59
  26. package/dist/navigate-CzLjnoPH.js.map +1 -0
  27. package/dist/{produce-BjQGMpqL.d.ts → produce-CtZ32UGG.d.ts} +13 -3
  28. package/dist/{rpc-B86KKjzx.js → rpc-9fSqL_YK.js} +57 -12
  29. package/dist/rpc-9fSqL_YK.js.map +1 -0
  30. package/dist/runtime/client.d.ts +4 -4
  31. package/dist/runtime/client.js +599 -306
  32. package/dist/runtime/client.js.map +1 -1
  33. package/dist/runtime/devtools.d.ts +3 -1
  34. package/dist/runtime/devtools.js +1 -1
  35. package/dist/runtime/hot.d.ts +1 -1
  36. package/dist/runtime/hot.js +9 -5
  37. package/dist/runtime/hot.js.map +1 -1
  38. package/dist/runtime/html.d.ts +2 -2
  39. package/dist/runtime/html.js +1 -1
  40. package/dist/runtime/loader.d.ts +12 -2
  41. package/dist/runtime/loader.js +3 -1
  42. package/dist/runtime/server.d.ts +4 -4
  43. package/dist/runtime/server.js +5 -5
  44. package/dist/runtime/signals.d.ts +2 -2
  45. package/dist/runtime/signals.js +5 -5
  46. package/dist/runtime/signals.js.map +1 -1
  47. package/dist/runtime/static-loader.d.ts +3 -0
  48. package/dist/runtime/static-loader.js +1 -0
  49. package/dist/runtime/testing.d.ts +21 -2
  50. package/dist/runtime/testing.js +83 -7
  51. package/dist/runtime/testing.js.map +1 -1
  52. package/dist/{server-sQCvduOz.d.ts → server-BxqjLUnV.d.ts} +211 -20
  53. package/dist/{server-CX3JnPCs.js → server-DZsgnPKS.js} +595 -185
  54. package/dist/server-DZsgnPKS.js.map +1 -0
  55. package/dist/shared-CWYOd0H3.js +40 -0
  56. package/dist/shared-CWYOd0H3.js.map +1 -0
  57. package/dist/static-loader-BcFh4ebX.d.ts +11 -0
  58. package/dist/static-loader-ClNkHZGn.js +185 -0
  59. package/dist/static-loader-ClNkHZGn.js.map +1 -0
  60. package/dist/stream-bgNCMcaA.js +280 -0
  61. package/dist/stream-bgNCMcaA.js.map +1 -0
  62. package/dist/vite.d.ts +30 -5
  63. package/dist/vite.js +501 -62
  64. package/dist/vite.js.map +1 -1
  65. package/package.json +7 -2
  66. package/types.d.ts +5 -0
  67. package/dist/cookies-rgIAc8IE.js.map +0 -1
  68. package/dist/devtools-Bm8cS7hX.js.map +0 -1
  69. package/dist/devtools-panel-CTbDSBBA.js.map +0 -1
  70. package/dist/html-CxWpXngy.js.map +0 -1
  71. package/dist/inspect-CGCWfaEx.js.map +0 -1
  72. package/dist/loader-BUhNqDHw.d.ts +0 -30
  73. package/dist/loader-py4qu6tQ.js +0 -215
  74. package/dist/loader-py4qu6tQ.js.map +0 -1
  75. package/dist/navigate-C5dP89YL.js.map +0 -1
  76. package/dist/rpc-B86KKjzx.js.map +0 -1
  77. package/dist/server-CX3JnPCs.js.map +0 -1
  78. package/dist/shared-BE_oBSDM.js +0 -176
  79. package/dist/shared-BE_oBSDM.js.map +0 -1
  80. package/dist/stream-cvhqOzfs.js +0 -145
  81. package/dist/stream-cvhqOzfs.js.map +0 -1
package/dist/vite.js CHANGED
@@ -1,11 +1,224 @@
1
- import { D as resolveRelative, E as forEachNode, M as getLocation, S as builtin, _ as hash, d as slotIndex, g as getComponentName, h as functionId, i as scopeLabel, k as parse, o as compile, r as report, t as formatReport, u as instanceScope, v as SHARED_QUERY, w as analyzeProject, x as isReactiveModule, y as generateShared } from "./inspect-CGCWfaEx.js";
2
- import { s as toNodeHeaders } from "./cookies-rgIAc8IE.js";
3
- import { a as isScriptFile, c as serverStubs, i as hasUseServer, n as findFiles, o as serverExports, r as findServerFiles, s as serverModule, t as defaultExclude } from "./files-D_JUcSU5.js";
4
- import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
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";
4
+ import { createHash } from "node:crypto";
5
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
5
6
  import { mkdir, readFile, writeFile } from "node:fs/promises";
6
7
  import path, { resolve } from "node:path";
7
- import { isRunnableDevEnvironment, normalizePath, transformWithOxc } from "vite";
8
- import { pathToFileURL } from "node:url";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import { isRunnableDevEnvironment, normalizePath, searchForWorkspaceRoot, transformWithOxc } from "vite";
10
+ //#region src/packages.ts
11
+ const toPosix = (file) => file.split(path.sep).join("/");
12
+ function readJson(file) {
13
+ try {
14
+ return JSON.parse(readFileSync(file, "utf8"));
15
+ } catch {
16
+ return;
17
+ }
18
+ }
19
+ /** The real directory of a package that code in `from` can import, or undefined. */
20
+ function findPackageDirectory(name, from) {
21
+ for (let directory = from;; directory = path.dirname(directory)) {
22
+ const candidate = path.join(directory, "node_modules", name);
23
+ if (existsSync(path.join(candidate, "package.json"))) return toPosix(realpathSync(candidate));
24
+ if (path.dirname(directory) === directory) return;
25
+ }
26
+ }
27
+ /** The directory of the nearest package.json at or above a directory. */
28
+ function packageRoot(directory) {
29
+ for (let current = directory;; current = path.dirname(current)) {
30
+ if (existsSync(path.join(current, "package.json"))) return current;
31
+ if (path.dirname(current) === current) return;
32
+ }
33
+ }
34
+ /** The directories that the `brumate` field names, or undefined when the package does not opt in. */
35
+ function directoriesOf(root, field, name) {
36
+ if (field === true) return [root];
37
+ if (typeof field === "object" && field !== null) {
38
+ const { dir, version = 1 } = field;
39
+ if (version !== 1) throw new Error(`The package ${name} has "brumate": { "version": ${version} }, but this version of brumate reads version 1. Install a version of ${name} or of brumate that matches.`);
40
+ if (dir === void 0) return [root];
41
+ return (Array.isArray(dir) ? dir : [dir]).map((item) => toPosix(path.resolve(root, item)));
42
+ }
43
+ }
44
+ /**
45
+ * Finds the dependencies of the app at `root` that ship `.brm` files, and
46
+ * theirs. The app's dependencies come from its package.json: `dependencies`,
47
+ * `devDependencies`, `optionalDependencies` and `peerDependencies`. A package
48
+ * opts in with `"brumate": true`, or `"brumate": { "dir": "src" }` to search
49
+ * only that directory. Symbolic links, such as those of pnpm, resolve to the
50
+ * real directory.
51
+ */
52
+ function findPackages(root) {
53
+ const app = packageRoot(path.resolve(root));
54
+ if (!app) return [];
55
+ const found = /* @__PURE__ */ new Map();
56
+ const visit = (directory, json, own) => {
57
+ const names = /* @__PURE__ */ new Set([
58
+ ...Object.keys(json.dependencies ?? {}),
59
+ ...Object.keys(json.optionalDependencies ?? {}),
60
+ ...Object.keys(json.peerDependencies ?? {}),
61
+ ...own ? Object.keys(json.devDependencies ?? {}) : []
62
+ ]);
63
+ for (const name of [...names].toSorted()) {
64
+ const real = findPackageDirectory(name, directory);
65
+ if (!real || found.has(real)) continue;
66
+ const dependency = readJson(`${real}/package.json`);
67
+ const directories = dependency && directoriesOf(real, dependency.brumate, name);
68
+ if (!dependency || !directories) continue;
69
+ found.set(real, {
70
+ name: dependency.name ?? name,
71
+ version: dependency.version ?? "0.0.0",
72
+ root: real,
73
+ directories,
74
+ linked: !real.includes("/node_modules/")
75
+ });
76
+ visit(real, dependency, false);
77
+ }
78
+ };
79
+ visit(app, readJson(path.join(app, "package.json")) ?? {}, true);
80
+ const list = [...found.values()];
81
+ const versions = /* @__PURE__ */ new Map();
82
+ for (const item of list) versions.set(item.name, (versions.get(item.name) ?? /* @__PURE__ */ new Set()).add(item.version));
83
+ return list.map((item) => Object.assign(item, { prefix: versions.get(item.name).size > 1 ? `${item.name}@${item.version}` : item.name }));
84
+ }
85
+ /** The package that a file belongs to, or undefined for a file of the app. */
86
+ function packageOf(packages, file) {
87
+ return packages.find((item) => file.startsWith(`${item.root}/`));
88
+ }
89
+ /**
90
+ * The name of a file of a package, which its IDs come from: the prefix of
91
+ * the package and the path of the file in it, such as `@acme/ui/src/Button.brm`.
92
+ * It is the same wherever the package is installed.
93
+ */
94
+ function packageFileName(item, file) {
95
+ return `${item.prefix}/${file.slice(item.root.length + 1)}`;
96
+ }
97
+ /** The name and the subpath of a bare specifier, such as `@acme/ui` and `./Button.brm`. */
98
+ function splitSpecifier(specifier) {
99
+ if (specifier.startsWith(".") || specifier.startsWith("/") || /^[a-z]+:/i.test(specifier)) return;
100
+ const parts = specifier.split("/");
101
+ const count = specifier.startsWith("@") ? 2 : 1;
102
+ if (parts.length < count || parts.slice(0, count).some((part) => part === "")) return;
103
+ const rest = parts.slice(count).join("/");
104
+ return {
105
+ name: parts.slice(0, count).join("/"),
106
+ subpath: rest ? `./${rest}` : "."
107
+ };
108
+ }
109
+ /** The conditions of `exports` that a `.brm` file or a source module can be under. */
110
+ const CONDITIONS = /* @__PURE__ */ new Set([
111
+ "brumate",
112
+ "import",
113
+ "module",
114
+ "node",
115
+ "browser",
116
+ "default"
117
+ ]);
118
+ function resolveTarget(target, star) {
119
+ if (typeof target === "string") return target.replaceAll("*", star);
120
+ if (Array.isArray(target)) {
121
+ for (const item of target) {
122
+ const result = resolveTarget(item, star);
123
+ if (result) return result;
124
+ }
125
+ return;
126
+ }
127
+ if (typeof target === "object" && target !== null) {
128
+ for (const [condition, value] of Object.entries(target)) if (CONDITIONS.has(condition)) {
129
+ const result = resolveTarget(value, star);
130
+ if (result) return result;
131
+ }
132
+ }
133
+ }
134
+ /** Resolves a subpath through the `exports` of a package.json, or undefined if it does not export it. */
135
+ function resolveExports(exports, subpath) {
136
+ const map = typeof exports === "object" && exports !== null && !Array.isArray(exports) && Object.keys(exports).some((key) => key.startsWith(".")) ? exports : { ".": exports };
137
+ if (subpath in map) return resolveTarget(map[subpath], "");
138
+ let best;
139
+ for (const key of Object.keys(map)) {
140
+ const index = key.indexOf("*");
141
+ if (index === -1) continue;
142
+ const before = key.slice(0, index);
143
+ const after = key.slice(index + 1);
144
+ if (subpath.startsWith(before) && subpath.endsWith(after) && subpath.length >= key.length - 1 && (!best || before.length > best.key.indexOf("*"))) best = {
145
+ key,
146
+ star: subpath.slice(before.length, subpath.length - after.length)
147
+ };
148
+ }
149
+ return best && resolveTarget(map[best.key], best.star);
150
+ }
151
+ /**
152
+ * Resolves a bare specifier, such as `@acme/ui/Button.brm`, to the real path
153
+ * of the file, through the `exports` of the package. Returns undefined when
154
+ * it is not a bare specifier or names no file.
155
+ */
156
+ function resolvePackageImport(specifier, importer) {
157
+ const split = splitSpecifier(specifier);
158
+ if (!split) return;
159
+ const directory = findPackageDirectory(split.name, path.dirname(importer));
160
+ if (!directory) return;
161
+ const json = readJson(`${directory}/package.json`);
162
+ const target = json?.exports === void 0 ? split.subpath : resolveExports(json.exports, split.subpath);
163
+ if (!target) return;
164
+ const file = path.resolve(directory, target);
165
+ return existsSync(file) ? toPosix(realpathSync(file)) : void 0;
166
+ }
167
+ /** The specifiers that a file imports or exports from, found by a pattern, so it can only find more. */
168
+ function importSpecifiers(source) {
169
+ const result = [];
170
+ for (const match of source.matchAll(/(?:\bfrom|\bimport\s*\(?)\s*(['"])([^'"\n]+)\1/g)) result.push(match[2]);
171
+ return result;
172
+ }
173
+ /** The extensions that an import without one can name. */
174
+ const EXTENSIONS = [
175
+ "",
176
+ ".ts",
177
+ ".tsx",
178
+ ".js",
179
+ ".mjs",
180
+ "/index.ts",
181
+ "/index.js"
182
+ ];
183
+ /**
184
+ * The files of packages that the app reaches: the files of packages that
185
+ * files of the app import, and the files of packages that those import, and
186
+ * so on. Only these become server functions of the app.
187
+ */
188
+ function reachableFiles(packages, appFiles, read) {
189
+ const reached = /* @__PURE__ */ new Set();
190
+ const names = new Set(packages.map((item) => item.name));
191
+ const pending = [];
192
+ const add = (file) => {
193
+ if (file && !reached.has(file) && packageOf(packages, file)) {
194
+ reached.add(file);
195
+ pending.push(file);
196
+ }
197
+ };
198
+ const resolve = (specifier, importer) => {
199
+ if (specifier.startsWith(".")) {
200
+ const stem = path.resolve(path.dirname(importer), specifier.split("?")[0]);
201
+ const found = EXTENSIONS.map((extension) => stem + extension).find((candidate) => statSync(candidate, { throwIfNoEntry: false })?.isFile());
202
+ return found && toPosix(realpathSync(found));
203
+ }
204
+ const name = splitSpecifier(specifier)?.name;
205
+ return name && names.has(name) ? resolvePackageImport(specifier.split("?")[0], importer) : void 0;
206
+ };
207
+ const visit = (file, own) => {
208
+ const source = read(file);
209
+ if (source === void 0) return;
210
+ for (const specifier of importSpecifiers(source)) {
211
+ if (own && specifier.startsWith(".")) continue;
212
+ try {
213
+ add(resolve(specifier, file));
214
+ } catch {}
215
+ }
216
+ };
217
+ for (const file of appFiles) visit(file, true);
218
+ while (pending.length > 0) visit(pending.pop(), false);
219
+ return reached;
220
+ }
221
+ //#endregion
9
222
  //#region src/dev-error.ts
10
223
  /** The overlay payload of an error, with the file, line and lines around it for compile errors. */
11
224
  function errorPayload(error, root = process.cwd()) {
@@ -103,6 +316,18 @@ function links(html, base) {
103
316
  return result;
104
317
  }
105
318
  /**
319
+ * Returns the hashes of the inline scripts of a page, as `sha256-<base64>`,
320
+ * in the order of the page. A browser hashes the text between the tags.
321
+ */
322
+ function scriptHashes(html) {
323
+ const hashes = [];
324
+ for (const match of html.matchAll(/<script\b([^>]*)>([^]*?)<\/script>/gi)) {
325
+ if (/\ssrc\s*=/i.test(match[1])) continue;
326
+ hashes.push(`sha256-${createHash("sha256").update(match[2], "utf8").digest("base64")}`);
327
+ }
328
+ return hashes;
329
+ }
330
+ /**
106
331
  * Renders pages with the route handler of the server build, and writes them
107
332
  * into the client build. Returns the paths that it wrote.
108
333
  */
@@ -119,6 +344,7 @@ async function prerender(routes, root, base, options) {
119
344
  const queue = [...options.paths ?? ["/"]];
120
345
  const seen = new Set(queue);
121
346
  const written = [];
347
+ const pages = {};
122
348
  while (queue.length > 0) {
123
349
  const pathname = queue.shift();
124
350
  const response = await handle(new Request(`http://localhost${pathname}`), document);
@@ -128,6 +354,10 @@ async function prerender(routes, root, base, options) {
128
354
  await mkdir(path.dirname(file), { recursive: true });
129
355
  await writeFile(file, html);
130
356
  written.push(pathname);
357
+ pages[pathname] = {
358
+ file: fileOf(pathname),
359
+ scripts: scriptHashes(html)
360
+ };
131
361
  if (options.crawl !== false) {
132
362
  for (const link of links(html, base)) if (!seen.has(link)) {
133
363
  seen.add(link);
@@ -137,9 +367,20 @@ async function prerender(routes, root, base, options) {
137
367
  }
138
368
  const missing = await handle(new Request("http://localhost/__brumate_not_found__"), document);
139
369
  if (missing?.status === 404 && missing.headers.get("content-type")?.includes("text/html")) {
140
- await writeFile(path.join(client, "404.html"), await missing.text());
370
+ const html = await missing.text();
371
+ await writeFile(path.join(client, "404.html"), html);
141
372
  written.push("404");
373
+ pages["404"] = {
374
+ file: "404.html",
375
+ scripts: scriptHashes(html)
376
+ };
142
377
  }
378
+ const result = {
379
+ pages,
380
+ scripts: [...new Set(Object.values(pages).flatMap((page) => page.scripts))]
381
+ };
382
+ await mkdir(path.join(client, ".brumate"), { recursive: true });
383
+ await writeFile(path.join(client, ".brumate/prerender.json"), `${JSON.stringify(result, null, 2)}\n`);
143
384
  return written;
144
385
  }
145
386
  //#endregion
@@ -424,6 +665,18 @@ const SERVER_QUERY = "?brumate-server";
424
665
  const TESTING = "virtual:brumate/testing";
425
666
  /** The dev server answers the devtools panel about a component at this path. */
426
667
  const INSPECT = "/__brumate/inspect";
668
+ /** What tells two lists of packages of components apart. */
669
+ function packagesKey(list) {
670
+ return JSON.stringify(list.map((item) => [
671
+ item.prefix,
672
+ item.root,
673
+ item.directories
674
+ ]));
675
+ }
676
+ /** Skips the `node_modules` and hidden directories of a package of components. */
677
+ function packageExclude(directory) {
678
+ return directory === "node_modules" || directory.startsWith(".");
679
+ }
427
680
  /** Reads a request body as bytes, so files in form data stay intact. */
428
681
  async function readBody(request) {
429
682
  const chunks = [];
@@ -457,19 +710,35 @@ function shapeOf(result) {
457
710
  const layouts = [...result.plan.scopes.values()];
458
711
  return {
459
712
  layout: JSON.stringify([
460
- result.client,
713
+ result.table,
461
714
  slots,
462
715
  markupOf(result)
463
716
  ]),
464
717
  css: result.css,
465
- code: JSON.stringify(result.parts),
718
+ code: JSON.stringify([result.client, result.parts]),
466
719
  slots: Object.fromEntries(layouts.map((layout) => [layout.scope.id, layout.slots.map((slot) => slot.name)])),
467
720
  signals: layouts.flatMap((layout) => layout.slots.filter((slot) => slot.kind === "signal").map((slot) => slot.name))
468
721
  };
469
722
  }
470
- /** The functions of a file of server functions, by their IDs, for a module of it. */
471
- function fileFunctions(id, module, hideNames) {
472
- return Object.fromEntries(Object.entries(module).filter(([, value]) => typeof value === "function").map(([name, value]) => [functionId(id, name, hideNames), value]));
723
+ let fingerprint;
724
+ /**
725
+ * A hash of the code of this build of brumate. A new build can compile the
726
+ * same `.brm` file to other code, so the hash is part of Vitest's cache key.
727
+ */
728
+ function buildFingerprint() {
729
+ if (fingerprint === void 0) {
730
+ const digest = createHash("sha1");
731
+ const visit = (directory) => {
732
+ for (const entry of readdirSync(directory, { withFileTypes: true }).toSorted((a, b) => a.name < b.name ? -1 : 1)) {
733
+ const file = path.join(directory, entry.name);
734
+ if (entry.isDirectory()) visit(file);
735
+ else if (/\.[jt]s$/.test(entry.name) && !entry.name.endsWith(".d.ts")) digest.update(entry.name).update(readFileSync(file));
736
+ }
737
+ };
738
+ visit(path.dirname(fileURLToPath(import.meta.url)));
739
+ fingerprint = digest.digest("hex").slice(0, 16);
740
+ }
741
+ return fingerprint;
473
742
  }
474
743
  /** The Vite plugin for `.brm` files. */
475
744
  function brumate(options = {}) {
@@ -489,12 +758,37 @@ function brumate(options = {}) {
489
758
  const shapes = /* @__PURE__ */ new Map();
490
759
  /** The props that parents can change, by absolute file path. */
491
760
  let liveProps = /* @__PURE__ */ new Map();
761
+ /** The dependencies of the app that ship `.brm` files. See `packages.ts`. */
762
+ let packages = [];
492
763
  const relative = (file) => normalizePath(path.relative(root, file));
764
+ /**
765
+ * The name of a file, which its IDs come from: its path relative to the root,
766
+ * or for a file of a package, the name of the package and its path in it.
767
+ */
768
+ const nameOf = (file) => {
769
+ let normalized = normalizePath(file);
770
+ let owner = packageOf(packages, normalized);
771
+ if (!owner && normalized.includes("/node_modules/") && existsSync(normalized)) {
772
+ normalized = normalizePath(realpathSync(normalized));
773
+ owner = packageOf(packages, normalized);
774
+ }
775
+ return owner ? packageFileName(owner, normalized) : relative(file);
776
+ };
777
+ /** True for a bare specifier that names a package of components. */
778
+ const isPackageSpecifier = (specifier) => {
779
+ const name = splitSpecifier(specifier)?.name;
780
+ return name !== void 0 && packages.some((item) => item.name === name);
781
+ };
493
782
  /** Files of server functions: scripts whose first statement is `'use server'`, by ID. */
494
783
  const serverFiles = /* @__PURE__ */ new Map();
784
+ /** The scripts of the app, when it uses packages of components. */
785
+ let appScripts = [];
495
786
  /** The ID of a function that a component imports from a 'use server' file, by a relative path. */
496
787
  const serverImport = (importer, specifier, name) => {
497
- if (!specifier.startsWith(".")) return;
788
+ if (!specifier.startsWith(".")) {
789
+ const file = isPackageSpecifier(specifier) ? resolvePackageImport(specifier, importer) : void 0;
790
+ return file && isScriptFile(file) && hasUseServer(readFileSync(file, "utf8")) ? functionId(serverFileId(file), name, !isServe) : void 0;
791
+ }
498
792
  const stem = path.resolve(path.dirname(importer), specifier);
499
793
  const found = [stem, ...[
500
794
  ".ts",
@@ -504,23 +798,49 @@ function brumate(options = {}) {
504
798
  ].map((extension) => stem + extension)].find((candidate) => isScriptFile(candidate) && existsSync(candidate) && hasUseServer(readFileSync(candidate, "utf8")));
505
799
  return found && functionId(serverFileId(normalizePath(found)), name, !isServe);
506
800
  };
507
- const serverFileId = (file) => `${path.basename(file).replace(/\.[^.]+$/, "")}_${hash(relative(file))}`;
801
+ const serverFileId = (file) => `${path.basename(file).replace(/\.[^.]+$/, "")}_${hash(nameOf(file))}`;
508
802
  const componentId = (file) => {
509
- const filename = relative(file);
803
+ const filename = nameOf(file);
510
804
  return `${getComponentName(filename)}_${hash(filename)}`;
511
805
  };
512
806
  const scan = async () => {
807
+ const directories = packages.flatMap((item) => item.directories.filter((directory) => existsSync(directory)));
808
+ const ownFile = (file) => !packageOf(packages, file);
809
+ const [own, ownServer, ...found] = await Promise.all([
810
+ findFiles(root, exclude),
811
+ findServerFiles(root, exclude),
812
+ ...directories.flatMap((directory) => [findFiles(directory, packageExclude), findServerFiles(directory, packageExclude)])
813
+ ]);
814
+ appScripts = packages.length > 0 ? (await findScripts(root, exclude)).filter(ownFile) : [];
513
815
  files.clear();
514
- for (const file of await findFiles(root, exclude)) files.set(componentId(file), file);
515
816
  serverFiles.clear();
516
- for (const file of await findServerFiles(root, exclude)) serverFiles.set(serverFileId(file), file);
817
+ for (const file of own.filter(ownFile)) files.set(componentId(file), file);
818
+ for (const file of ownServer.filter(ownFile)) serverFiles.set(serverFileId(file), file);
819
+ for (const [index, list] of found.entries()) for (const file of list) if (index % 2 === 0) files.set(componentId(file), file);
820
+ else serverFiles.set(serverFileId(file), file);
517
821
  await analyze();
518
822
  };
823
+ /**
824
+ * The files of packages that the app reaches through its imports. A server
825
+ * function of a package becomes an endpoint of the app only when the app
826
+ * reaches its file, so installing a package does not expose all of them.
827
+ */
828
+ const reachable = () => reachableFiles(packages, [...[...files.values()].filter((file) => !packageOf(packages, file)), ...appScripts], (file) => {
829
+ try {
830
+ return readFileSync(file, "utf8");
831
+ } catch {
832
+ return;
833
+ }
834
+ });
835
+ /** The files of packages in the last server registry. */
836
+ let registered = /* @__PURE__ */ new Set();
837
+ /** Resolves a `.brm` file that a component imports: next to it, or from a package of components. */
838
+ const resolveComponent = (specifier, importer) => resolveRelative(specifier, importer) ?? (specifier.endsWith(".brm") && isPackageSpecifier(specifier) ? resolvePackageImport(specifier, importer) : void 0);
519
839
  const analyze = async () => {
520
840
  const list = [...files.values()];
521
841
  const contents = await Promise.all(list.map((file) => readFile(file, "utf8")));
522
842
  const sources = new Map(list.map((file, index) => [file, contents[index]]));
523
- liveProps = analyzeProject(sources);
843
+ liveProps = analyzeProject(sources, resolveComponent);
524
844
  compiled.clear();
525
845
  };
526
846
  const compileFile = async (file) => {
@@ -530,13 +850,21 @@ function brumate(options = {}) {
530
850
  cached = {
531
851
  source,
532
852
  result: compile(source, {
533
- filename: relative(file),
853
+ filename: nameOf(file),
534
854
  liveProps: liveProps.get(file),
535
855
  path: file,
536
- merge: options.merge ?? 2048,
856
+ merge: options.merge ?? 4096,
537
857
  a11y: options.a11y,
538
858
  hideNames: !isServe,
539
- serverImport: (specifier, name) => serverImport(file, specifier, name)
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
+ }
540
868
  })
541
869
  };
542
870
  compiled.set(file, cached);
@@ -544,25 +872,39 @@ function brumate(options = {}) {
544
872
  }
545
873
  return cached;
546
874
  };
547
- const manifest = () => {
875
+ const manifest = async () => {
876
+ const list = [...files];
877
+ const needed = await Promise.all(list.map(async ([, file]) => isServe || (await compileFile(file)).result.clientCode));
548
878
  return [
549
879
  "const modules = {",
550
- ...[...files].map(([id, file]) => ` ${JSON.stringify(id)}: () => import(${JSON.stringify(`${file}${CLIENT_QUERY}`)}),`),
880
+ ...list.filter((_, index) => needed[index]).map(([id, file]) => ` ${JSON.stringify(id)}: () => import(${JSON.stringify(`${file}${CLIENT_QUERY}`)}),`),
551
881
  "};",
552
882
  "export function load(id) {",
553
- " const module = modules[id];",
554
- " if (!module) {",
555
- " throw new Error(`Unknown component \"${id}\"`);",
556
- " }",
557
- " return module();",
883
+ ...isServe ? [
884
+ " const module = modules[id];",
885
+ " if (!module) {",
886
+ " throw new Error(`Unknown component \"${id}\"`);",
887
+ " }",
888
+ " return module();"
889
+ ] : [" return modules[id]?.();"],
558
890
  "}"
559
891
  ].join("\n");
560
892
  };
561
- const serverRegistry = () => {
562
- const imports = [...files.values()].map((file, index) => `import * as m${index} from ${JSON.stringify(file)};`);
563
- const spreads = [...files.values()].map((_, index) => ` ...m${index}.rpc,`);
564
- const fileImports = [...serverFiles.values()].map((file, index) => `import * as f${index} from ${JSON.stringify(file)};`);
565
- const fileSpreads = [...serverFiles.entries()].map(([id, file], index) => {
893
+ /**
894
+ * The module of every server function of the app, by ID. With `server`, in
895
+ * a DOM test, it imports the server code of each file, which that
896
+ * environment would give as browser code.
897
+ */
898
+ const serverRegistry = (server = false) => {
899
+ const query = server ? SERVER_QUERY : "";
900
+ registered = packages.length > 0 ? reachable() : /* @__PURE__ */ new Set();
901
+ const keep = (file) => registered.has(file) || !packageOf(packages, file);
902
+ const components = [...files.values()].filter(keep);
903
+ const imports = components.map((file, index) => `import * as m${index} from ${JSON.stringify(file + query)};`);
904
+ const spreads = components.map((_, index) => ` ...m${index}.rpc,`);
905
+ const functionFiles = [...serverFiles.entries()].filter(([, file]) => keep(file));
906
+ const fileImports = functionFiles.map(([, file], index) => `import * as f${index} from ${JSON.stringify(file + query)};`);
907
+ const fileSpreads = functionFiles.map(([id, file], index) => {
566
908
  return serverExports(readFileSync(file, "utf8"), file).map((name) => ` ${JSON.stringify(functionId(id, name, !isServe))}: f${index}[${JSON.stringify(name)}],`).join("\n");
567
909
  });
568
910
  return [
@@ -634,7 +976,7 @@ function brumate(options = {}) {
634
976
  const text = formatReport(report(source, result, liveProps.get(file)));
635
977
  return {
636
978
  name: plan.name,
637
- file: relative(file),
979
+ file: nameOf(file),
638
980
  scopes,
639
981
  graph,
640
982
  text
@@ -644,20 +986,24 @@ function brumate(options = {}) {
644
986
  const id = decodeURIComponent((request.url ?? "").slice(rpc.length + 1).split("?")[0]);
645
987
  const owner = id.split("#")[0];
646
988
  const file = files.get(owner) ?? serverFiles.get(owner);
647
- if (!file) {
989
+ const reached = file && packageOf(packages, file) ? reachable() : void 0;
990
+ if (!file || reached && !reached.has(file)) {
648
991
  response.statusCode = 404;
649
992
  response.end(`Unknown server function "${id}"`);
650
993
  return;
651
994
  }
995
+ if (reached && !registered.has(file)) {
996
+ const module = server.moduleGraph.getModuleById(`\0${SERVER}`);
997
+ if (module) server.moduleGraph.invalidateModule(module);
998
+ }
652
999
  try {
653
- const module = await server.ssrLoadModule(file);
1000
+ const { functions } = await server.ssrLoadModule(SERVER);
654
1001
  const { handleRequest } = await server.ssrLoadModule("brumate/server");
655
- const webRequest = new Request(new URL(request.url ?? "/", "http://localhost"), {
1002
+ const answer = await handleRequest(functions, new Request(new URL(request.url ?? "/", "http://localhost"), {
656
1003
  method: "POST",
657
1004
  headers: Object.entries(request.headers).flatMap(([name, value]) => value === void 0 ? [] : [[name, String(value)]]),
658
1005
  body: new Uint8Array(await readBody(request))
659
- });
660
- const answer = await handleRequest(serverFiles.has(owner) ? fileFunctions(owner, module, !isServe) : module.rpc ?? {}, webRequest, rpc, { origins: options.origins });
1006
+ }), rpc, { origins: options.origins });
661
1007
  response.statusCode = answer.status;
662
1008
  for (const [name, value] of Object.entries(toNodeHeaders(answer.headers))) response.setHeader(name, value);
663
1009
  response.end(await answer.text());
@@ -721,20 +1067,65 @@ function brumate(options = {}) {
721
1067
  });
722
1068
  return [];
723
1069
  }
1070
+ /**
1071
+ * The config that packages of components need. Vite must not pre-bundle them,
1072
+ * or their `.brm` and `'use server'` files would not reach this plugin, and the
1073
+ * server build compiles them instead of importing them from `node_modules`.
1074
+ */
1075
+ const packageConfig = (config) => {
1076
+ if (packages.length === 0) return {};
1077
+ const names = [...new Set(packages.map((item) => item.name))];
1078
+ const result = {
1079
+ optimizeDeps: { exclude: names },
1080
+ ssr: { noExternal: names },
1081
+ resolve: { dedupe: ["brumate"] }
1082
+ };
1083
+ const workspace = normalizePath(searchForWorkspaceRoot(path.resolve(config.root ?? ".")));
1084
+ const outside = packages.filter((item) => item.root !== workspace && !item.root.startsWith(`${workspace}/`)).map((item) => item.root);
1085
+ if (outside.length > 0) result.server = { fs: { allow: [workspace, ...outside] } };
1086
+ return result;
1087
+ };
1088
+ /** The module ID of `brumate/client`, and the chunks of the loader and the core in a client build. */
1089
+ let coreModule;
1090
+ let loaderChunk;
1091
+ let coreChunk;
724
1092
  return {
725
1093
  name: "brumate",
726
1094
  enforce: "pre",
727
1095
  config(config, env) {
728
- if (!options.prerender || !env.isSsrBuild) return;
1096
+ packages = findPackages(path.resolve(config.root ?? process.cwd()));
1097
+ const shared = packageConfig(config);
1098
+ if (!env.isSsrBuild) {
1099
+ const preload = config.build?.modulePreload;
1100
+ if (preload === false) return shared;
1101
+ const resolve = typeof preload === "object" ? preload.resolveDependencies : void 0;
1102
+ return {
1103
+ ...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
+ } } }
1110
+ };
1111
+ }
1112
+ if (!options.prerender) return shared;
729
1113
  const ssr = config.build?.ssr;
730
1114
  const input = typeof ssr === "string" ? ssr : config.build?.rolldownOptions?.input;
731
- return { build: {
732
- ssr: true,
733
- rolldownOptions: { input: {
734
- ...typeof input === "string" ? { [path.basename(input).replace(/\.[^.]+$/, "")]: input } : Array.isArray(input) ? Object.fromEntries(input.map((item) => [path.basename(item).replace(/\.[^.]+$/, ""), item])) : { ...input },
735
- [PRERENDER_ENTRY]: ROUTES
736
- } }
737
- } };
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 };
1116
+ return {
1117
+ ...shared,
1118
+ build: {
1119
+ ssr: true,
1120
+ rolldownOptions: { input: {
1121
+ ...entries,
1122
+ [PRERENDER_ENTRY]: ROUTES
1123
+ } }
1124
+ }
1125
+ };
1126
+ },
1127
+ configureVitest(context) {
1128
+ (context.defineCacheKeyGenerator ?? context.experimental_defineCacheKeyGenerator)?.(buildFingerprint);
738
1129
  },
739
1130
  configResolved(config) {
740
1131
  root = config.root;
@@ -744,7 +1135,15 @@ function brumate(options = {}) {
744
1135
  isSsrBuild = Boolean(config.build.ssr);
745
1136
  },
746
1137
  async generateBundle(_output, bundle) {
747
- if (isSsrBuild || !options.report && !options.budget) return;
1138
+ if (isSsrBuild) return;
1139
+ loaderChunk = void 0;
1140
+ coreChunk = void 0;
1141
+ for (const item of Object.values(bundle)) {
1142
+ if (item.type !== "chunk") continue;
1143
+ if (item.moduleIds.includes(`\0${MANIFEST}`)) loaderChunk = item.fileName;
1144
+ if (coreModule && item.moduleIds.includes(coreModule)) coreChunk = item.fileName;
1145
+ }
1146
+ if (!options.report && !options.budget) return;
748
1147
  const chunks = [];
749
1148
  for (const item of Object.values(bundle)) if (item.type === "chunk") chunks.push({
750
1149
  fileName: item.fileName,
@@ -764,7 +1163,7 @@ function brumate(options = {}) {
764
1163
  } : void 0,
765
1164
  budget: options.budget
766
1165
  });
767
- if (options.report) this.info(`\n${formatBuildReport(measured, relative)}`);
1166
+ if (options.report) this.info(`\n${formatBuildReport(measured, nameOf)}`);
768
1167
  if (measured.overBudget.length > 0) this.error(measured.overBudget.join("\n"));
769
1168
  },
770
1169
  async writeBundle(_output, bundle) {
@@ -776,11 +1175,23 @@ function brumate(options = {}) {
776
1175
  this.info(`Prerendered ${written.length} pages`);
777
1176
  },
778
1177
  async buildStart() {
1178
+ coreModule = isServe ? void 0 : (await this.resolve("brumate/client", path.join(root, "index.html")))?.id;
779
1179
  await scan();
780
1180
  writeRouteTypes();
781
1181
  },
782
- resolveId(id) {
1182
+ async resolveId(id, importer, resolveOptions) {
783
1183
  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;
1185
+ const resolved = await this.resolve(id, importer, {
1186
+ ...resolveOptions,
1187
+ skipSelf: true
1188
+ });
1189
+ if (!resolved || resolved.external || resolved.id.includes("?") || resolved.id.includes("/node_modules/") && !packageOf(packages, resolved.id)) return resolved;
1190
+ const file = resolved.id;
1191
+ return isScriptFile(file) && existsSync(file) && hasUseServer(readFileSync(file, "utf8")) ? {
1192
+ ...resolved,
1193
+ id: `${file}${SERVER_QUERY}`
1194
+ } : resolved;
784
1195
  },
785
1196
  async load(id, loadOptions) {
786
1197
  if (id.endsWith("?brumate-shared")) {
@@ -799,18 +1210,22 @@ function brumate(options = {}) {
799
1210
  };
800
1211
  }
801
1212
  if (id === `\0${START}`) return [
802
- "import { start } from 'brumate/loader';",
1213
+ options.navigate === false ? "import { startWithoutNavigation as start } from 'brumate/static-loader';" : "import { start } from 'brumate/loader';",
803
1214
  `import { load } from ${JSON.stringify(MANIFEST)};`,
804
- ...isServe ? ["import { hotLoad } from 'brumate/hot';", `start({ load: hotLoad(import.meta.hot, load), rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)} });`] : [`start({ load, rpc: ${JSON.stringify(rpc)}, navigate: ${JSON.stringify(options.navigate ?? true)} });`],
1215
+ ...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" : ""} });`,
805
1217
  ...isServe && options.devtools !== false ? [`import('brumate/devtools').then((m) => m.installDevtools(${JSON.stringify(INSPECT)}, ${JSON.stringify(rpc)}));`] : []
806
1218
  ].join("\n");
807
- if (id === `\0${MANIFEST}`) return manifest();
808
- if (id === `\0${SERVER}`) return serverRegistry();
1219
+ if (id === `\0${MANIFEST}`) return await manifest();
1220
+ if (id === `\0${SERVER}`) return serverRegistry(!loadOptions?.ssr);
809
1221
  if (id === `\0${ROUTES}`) return routeTree();
810
1222
  if (id === `\0${TESTING}`) return [
811
- "import { createMount } from 'brumate/testing';",
1223
+ "import { answerCalls as answer, createMount } from 'brumate/testing';",
812
1224
  `import { load } from ${JSON.stringify(MANIFEST)};`,
813
- `export const mount = createMount({ load, rpc: ${JSON.stringify(rpc)} });`
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
+ "}"
814
1229
  ].join("\n");
815
1230
  const [file, query] = id.split("?");
816
1231
  if (!file?.endsWith(".brm")) return;
@@ -826,7 +1241,10 @@ function brumate(options = {}) {
826
1241
  this.error({
827
1242
  message,
828
1243
  frame,
829
- loc,
1244
+ loc: loc && {
1245
+ ...loc,
1246
+ file
1247
+ },
830
1248
  id: file
831
1249
  });
832
1250
  }
@@ -839,7 +1257,7 @@ function brumate(options = {}) {
839
1257
  }
840
1258
  for (const warning of isClient && !params.has("part") ? result.warnings : []) {
841
1259
  const { line, column } = getLocation(source, warning.range.start);
842
- this.warn(`${warning.message} (${relative(file)}:${line}:${column})`);
1260
+ this.warn(`${warning.message} (${nameOf(file)}:${line}:${column})`);
843
1261
  }
844
1262
  const part = params.get("part");
845
1263
  let code;
@@ -869,12 +1287,22 @@ function brumate(options = {}) {
869
1287
  const [file] = id.split("?");
870
1288
  if (file && isScriptFile(file) && hasUseServer(code)) try {
871
1289
  const fileId = serverFileId(normalizePath(file));
872
- const stubs = serverStubs(code, file, fileId, !isServe);
873
- return transformOptions?.ssr ? {
1290
+ if (transformOptions?.ssr) return {
874
1291
  code: serverModule(code, file, fileId),
875
1292
  map: null
876
- } : {
877
- code: stubs,
1293
+ };
1294
+ if (id.includes(SERVER_QUERY)) {
1295
+ const result = await transformWithOxc(serverModule(code, file, fileId), file, {
1296
+ lang: /\.[cm]?ts$/.test(file) ? "ts" : file.endsWith(".tsx") ? "tsx" : "jsx",
1297
+ sourcemap: true
1298
+ });
1299
+ return {
1300
+ code: result.code,
1301
+ map: result.map
1302
+ };
1303
+ }
1304
+ return {
1305
+ code: serverStubs(code, file, fileId, !isServe),
878
1306
  map: null
879
1307
  };
880
1308
  } catch (error) {
@@ -892,6 +1320,13 @@ function brumate(options = {}) {
892
1320
  };
893
1321
  },
894
1322
  configureServer(server) {
1323
+ const linked = packages.filter((item) => item.linked).flatMap((item) => item.directories);
1324
+ if (linked.length > 0) server.watcher.add(linked);
1325
+ const manifests = [path.join(root, "package.json"), ...packages.map((item) => `${item.root}/package.json`)].map((file) => normalizePath(file));
1326
+ server.watcher.add(manifests);
1327
+ server.watcher.on("change", (file) => {
1328
+ if (manifests.includes(normalizePath(file)) && packagesKey(findPackages(root)) !== packagesKey(packages)) server.restart();
1329
+ });
895
1330
  server.watcher.on("all", (event, file) => {
896
1331
  for (const importer of dependents.get(normalizePath(file)) ?? []) {
897
1332
  compiled.delete(importer);
@@ -903,6 +1338,10 @@ function brumate(options = {}) {
903
1338
  }
904
1339
  if (isScriptFile(file)) {
905
1340
  const normalized = normalizePath(file);
1341
+ if (packages.length > 0 && !packageOf(packages, normalized)) {
1342
+ appScripts = appScripts.filter((item) => item !== normalized);
1343
+ if (event !== "unlink") appScripts.push(normalized);
1344
+ }
906
1345
  const id = serverFileId(normalized);
907
1346
  const before = serverFiles.has(id);
908
1347
  const after = event !== "unlink" && existsSync(file) && hasUseServer(readFileSync(file, "utf8"));