@powerhousedao/builder-tools 6.2.3-dev.7 → 6.2.3-dev.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,17 +1,21 @@
1
- import { createRequire } from "node:module";
2
- import { createHash, randomUUID } from "node:crypto";
3
- import fs, { createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
- import path, { dirname, extname, isAbsolute, join, resolve } from "node:path";
1
+ import { createRequire, registerHooks } from "node:module";
2
+ import fs, { chmodSync, cpSync, createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
3
+ import path, { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { createLogger, createServer, esmExternalRequirePlugin, loadEnv, normalizePath, searchForWorkspaceRoot } from "vite";
5
5
  import { exec, execSync, spawn } from "node:child_process";
6
- import { fileURLToPath } from "node:url";
7
- import MagicString from "magic-string";
8
6
  import { readFile, writeFile } from "node:fs/promises";
9
7
  import { cwd } from "node:process";
10
- import { DEFAULT_CONNECT_CONFIG, PWA_FILE_HANDLER_ACTION, buildRuntimeConfig, deepMerge, loadConnectEnv, mergeManifest, mergePwaConfig, normalizeBasePath, phConnectRuntimeConfigSchema, powerhousePackageSchema, setConnectEnv, unionStrings, withInferredCategory } from "@powerhousedao/shared/connect";
11
- import { getConfig } from "@powerhousedao/config/node";
8
+ import { Generator, getConfig } from "@tanstack/router-generator";
9
+ import { tanstackRouter } from "@tanstack/router-plugin/vite";
10
+ import { index, layout, physical, rootRoute, route } from "@tanstack/virtual-file-routes";
11
+ import { fileURLToPath, pathToFileURL } from "node:url";
12
+ import { DEFAULT_CONNECT_CONFIG, DYNAMIC_BASE_PLACEHOLDER, PWA_FILE_HANDLER_ACTION, buildRuntimeConfig, deepMerge, loadConnectEnv, mapBackgroundImages, mergeManifest, mergePwaConfig, normalizeBasePath, phConnectRuntimeConfigSchema, powerhousePackageSchema, resolveSourceConnect, setConnectEnv, unionStrings, validateBackground, withInferredCategory, workerPackageFileName, workflowsSettingConflict } from "@powerhousedao/shared/connect";
13
+ import { APP_ICON_VARIANT_SIZES, BACKGROUND_MAX_BYTES, PWA_ICON_VARIANT_SIZES, UI_ICON_MAX_BYTES, iconVariantPath, imageMimeType, isPassthroughImageRef, resolveImageRef } from "@powerhousedao/shared/connect/image-ref";
14
+ import { createHash, randomUUID } from "node:crypto";
15
+ import MagicString from "magic-string";
16
+ import { getConfig as getConfig$1 } from "@powerhousedao/config/node";
12
17
  import tailwind from "@tailwindcss/vite";
13
18
  import react from "@vitejs/plugin-react";
14
- import { createLogger, esmExternalRequirePlugin, loadEnv, searchForWorkspaceRoot } from "vite";
15
19
  import { createHtmlPlugin } from "vite-plugin-html";
16
20
  import { PwaConfigSchema } from "@powerhousedao/shared/document-model";
17
21
  import { toCdnUrl } from "@powerhousedao/shared/registry/urls";
@@ -22,6 +26,1262 @@ const IMPORT_SCRIPT_FILE = "external-packages.js";
22
26
  const LOCAL_PACKAGE_ID = "ph:local-package";
23
27
  const PH_DIR_NAME = ".ph";
24
28
  //#endregion
29
+ //#region connect-utils/helpers.ts
30
+ const DEFAULT_CONNECT_OUTDIR = ".ph/connect-build/dist/";
31
+ function resolveViteConfigPath(options) {
32
+ const { projectRoot = cwd(), viteConfigFile } = options;
33
+ return viteConfigFile || join(projectRoot, "vite.config.ts");
34
+ }
35
+ function resolvePackage(packageName, root = process.cwd()) {
36
+ return createRequire(root).resolve(packageName, { paths: [root] });
37
+ }
38
+ function resolveConnectPackageJson(root = process.cwd()) {
39
+ try {
40
+ const connectPackageJsonPath = resolvePackage("@powerhousedao/connect/package.json", root);
41
+ const fileContents = fs.readFileSync(connectPackageJsonPath, "utf-8");
42
+ return JSON.parse(fileContents);
43
+ } catch (error) {
44
+ console.error(`Error reading Connect package.json:`, error);
45
+ return null;
46
+ }
47
+ }
48
+ /**
49
+ * Finds the dist dir of Connect on the local machine
50
+ */
51
+ function resolveConnectBundle(root = process.cwd()) {
52
+ const connectIndexPath = resolvePackage("@powerhousedao/connect", root);
53
+ const connectRootPath = connectIndexPath.substring(0, connectIndexPath.indexOf("connect") + 7);
54
+ return join(connectRootPath, "dist/");
55
+ }
56
+ function resolveConnectPublicDir(root = process.cwd()) {
57
+ const connectIconPath = resolvePackage("@powerhousedao/connect/public/icon.ico", root);
58
+ return path.join(connectIconPath, "../");
59
+ }
60
+ /**
61
+ * Copies the Connect dist dir to the target path
62
+ */
63
+ function copyConnect(sourcePath, targetPath) {
64
+ try {
65
+ fs.rmSync(targetPath, {
66
+ recursive: true,
67
+ force: true
68
+ });
69
+ fs.cpSync(sourcePath, targetPath, { recursive: true });
70
+ } catch (error) {
71
+ console.error(`❌ Error copying ${sourcePath} to ${targetPath}:`, error);
72
+ }
73
+ }
74
+ /**
75
+ * Backs up the index.html file
76
+ *
77
+ * Needed when running the Connect Studio dev server on Windows
78
+ */
79
+ function backupIndexHtml(appPath, restore = false) {
80
+ const filePath = join(appPath, "index.html");
81
+ const backupPath = join(appPath, "index.html.bak");
82
+ const paths = restore ? [backupPath, filePath] : [filePath, backupPath];
83
+ if (fs.existsSync(paths[0])) fs.copyFileSync(paths[0], paths[1]);
84
+ }
85
+ function removeBase64EnvValues(appPath) {
86
+ backupIndexHtml(appPath);
87
+ const filePath = join(appPath, "index.html");
88
+ fs.readFile(filePath, "utf-8", (err, data) => {
89
+ if (err) {
90
+ console.error("Error reading file:", err);
91
+ return;
92
+ }
93
+ const modifiedData = data.replace(/"LOCAL_DOCUMENT_MODELS":\s*".*?",/, `"LOCAL_DOCUMENT_MODELS": "",`).replace(/"LOCAL_DOCUMENT_EDITORS":\s*".*?"/, `"LOCAL_DOCUMENT_EDITORS": ""`);
94
+ console.log("Modified data:", modifiedData);
95
+ fs.writeFile(filePath, modifiedData, "utf-8", (err) => {
96
+ if (err) {
97
+ console.error("Error writing file:", err);
98
+ return;
99
+ }
100
+ });
101
+ });
102
+ }
103
+ function readJsonFile(filePath) {
104
+ try {
105
+ const absolutePath = resolve(filePath);
106
+ const fileContents = fs.readFileSync(absolutePath, "utf-8");
107
+ return JSON.parse(fileContents);
108
+ } catch (_error) {
109
+ console.error(`Error reading file: ${filePath}`);
110
+ return null;
111
+ }
112
+ }
113
+ /**
114
+ * Takes a list of Powerhouse project packages and optionally local Powerhouse packages and outputs a js file which exports those packages for use in Connect Studio.
115
+ */
116
+ function makeImportScriptFromPackages(args) {
117
+ const { packages, localJsPath, localCssPath, importStyles = true } = args;
118
+ const imports = [];
119
+ const moduleNames = [];
120
+ let counter = 0;
121
+ for (const packageName of packages) {
122
+ const moduleName = `module${counter}`;
123
+ moduleNames.push(moduleName);
124
+ imports.push(`import * as ${moduleName} from '${packageName}';`);
125
+ if (importStyles) imports.push(`import '${packageName}/style.css';`);
126
+ counter++;
127
+ }
128
+ const exports = moduleNames.map((name, index) => `{
129
+ id: "${packages[index]}",
130
+ ...${name},
131
+ }`);
132
+ const hasModule = localJsPath !== void 0;
133
+ const hasStyles = importStyles && localCssPath !== void 0;
134
+ if (hasModule || hasStyles) {
135
+ if (hasStyles) imports.push(`import '${localCssPath}';`);
136
+ if (hasModule) {
137
+ const moduleName = `module${counter}`;
138
+ imports.push(`import * as ${moduleName} from '${localJsPath}';`);
139
+ exports.push(`{
140
+ id: "${LOCAL_PACKAGE_ID}",
141
+ ...${moduleName},
142
+ }`);
143
+ }
144
+ }
145
+ const exportStatement = `export default [${exports.length ? `
146
+ ${exports.join(",\n")}
147
+ ` : ""}];`;
148
+ return `${imports.join("\n")}\n\n${exportStatement}`;
149
+ }
150
+ function ensureNodeVersion(minVersion = "24") {
151
+ const version = process.versions.node;
152
+ if (!version) return;
153
+ if (version < minVersion) {
154
+ console.error(`Node version ${minVersion} or higher is required. Current version: ${version}`);
155
+ process.exit(1);
156
+ }
157
+ }
158
+ function runShellScriptPlugin(scriptName, connectPath) {
159
+ return {
160
+ name: "vite-plugin-run-shell-script",
161
+ buildStart() {
162
+ const scriptPath = join(connectPath, scriptName);
163
+ if (fs.existsSync(scriptPath)) exec(`sh ${scriptPath}`, (error, stdout, stderr) => {
164
+ if (error) {
165
+ console.error(`Error executing the script: ${error.message}`);
166
+ removeBase64EnvValues(connectPath);
167
+ return;
168
+ }
169
+ if (stderr) console.error(stderr);
170
+ });
171
+ }
172
+ };
173
+ }
174
+ /**
175
+ * Shared helper to modify the <head> tag of an HTML file by transforming its contents.
176
+ */
177
+ async function modifyHtmlHead(pathToHtml, contents, transform) {
178
+ if (!existsSync(pathToHtml)) throw new Error(`File ${pathToHtml} does not exist.`);
179
+ let html = await readFile(pathToHtml, "utf8");
180
+ html = transform(html, contents);
181
+ await writeFile(pathToHtml, html, "utf8");
182
+ }
183
+ /**
184
+ * Appends the contents to the <head> tag of the index.html file
185
+ */
186
+ async function appendToHtmlHead(pathToHtml, contents) {
187
+ return modifyHtmlHead(pathToHtml, contents, (html, contents) => {
188
+ if (!html.includes("</head>")) throw new Error("No </head> tag found in the HTML file.");
189
+ return html.replace("</head>", `\n${contents}\n</head>`);
190
+ });
191
+ }
192
+ /**
193
+ * Prepends the contents to the <head> tag of the index.html file
194
+ */
195
+ async function prependToHtmlHead(pathToHtml, contents) {
196
+ return modifyHtmlHead(pathToHtml, contents, (html, contents) => {
197
+ if (!html.includes("</head>")) throw new Error("No </head> tag found in the HTML file.");
198
+ return html.replace("<head>", `<head>\n${contents}\n`);
199
+ });
200
+ }
201
+ function runTsc(outDir) {
202
+ execSync(`npx tsc --outDir ${outDir}`, { stdio: "inherit" });
203
+ }
204
+ function stripVersionFromPackage(packageName) {
205
+ const trimmed = packageName.trim();
206
+ if (!trimmed) return "";
207
+ const lastAtIndex = trimmed.lastIndexOf("@");
208
+ if (lastAtIndex > 0) return trimmed.substring(0, lastAtIndex);
209
+ return trimmed;
210
+ }
211
+ //#endregion
212
+ //#region connect-utils/vite-plugins/connect-routes.ts
213
+ /** A project's routes for its Connect deployment, beside Connect's own. */
214
+ const HOST_ROUTES_DIR = "hosts/connect/routes";
215
+ /** The generated tree of Connect's and the project's routes. */
216
+ const CONNECT_ROUTES_GEN = ".ph/connect-routes.gen.ts";
217
+ /** Connect's dist imports its route tree by this specifier. */
218
+ const ROUTE_TREE_SPECIFIER = "@powerhousedao/connect/route-tree";
219
+ /** Core's types name the app's tree by this one; both resolve to one tree. */
220
+ const CORE_ROUTE_TREE_SPECIFIER = "@powerhousedao/connect-core/route-tree";
221
+ const ROUTE_TREE_FIND = new RegExp(`^(${[ROUTE_TREE_SPECIFIER, CORE_ROUTE_TREE_SPECIFIER].map(escapeRegExp).join("|")})$`);
222
+ /** A host's routes folder: `routes` (a host's `runner.routes`), relative to the
223
+ * project, else `hosts/connect/routes/`; undefined if none or `false`. */
224
+ function resolveConnectRoutesDir(projectRoot, routes) {
225
+ if (routes === false) return void 0;
226
+ if (routes !== void 0) {
227
+ const dir = resolve(projectRoot, routes);
228
+ if (!existsSync(dir)) throw new Error(`The routes folder ${routes} does not exist.`);
229
+ return dir;
230
+ }
231
+ const dir = join(projectRoot, HOST_ROUTES_DIR);
232
+ return existsSync(dir) ? dir : void 0;
233
+ }
234
+ const isDefaultRoutesDir = (projectRoot, routesDir) => resolve(routesDir) === join(resolve(projectRoot), HOST_ROUTES_DIR);
235
+ /** The tree generated from `routesDir`: `.ph/connect-routes.gen.ts` for
236
+ * `hosts/connect/routes/`, else `.ph/<folder>.gen.ts`. */
237
+ function connectRoutesTreeOf(projectRoot, routesDir) {
238
+ if (isDefaultRoutesDir(projectRoot, routesDir)) return join(projectRoot, CONNECT_ROUTES_GEN);
239
+ return join(projectRoot, ".ph", `${relative(projectRoot, routesDir)}.gen.ts`);
240
+ }
241
+ /** Connect's pathless sidebar layout; a project's routes in `_app/` render in it. */
242
+ const APP_LAYOUT = "_app";
243
+ function findRouteFile(dir, name) {
244
+ return [
245
+ ".tsx",
246
+ ".ts",
247
+ ".jsx",
248
+ ".js"
249
+ ].map((ext) => join(dir, `${name}${ext}`)).find((file) => existsSync(file));
250
+ }
251
+ /** Whether the project's `_app` replaces Connect's layout (and its chrome). */
252
+ function hasProjectAppLayout(routesDir) {
253
+ return !!routesDir && !!findRouteFile(routesDir, "_app");
254
+ }
255
+ /** Connect's route files: core's routes with Connect's views. */
256
+ function connectRoutesDirOf(connectDir) {
257
+ return join(connectDir, "src/routes");
258
+ }
259
+ const ROUTE_FILE = /\.[cm]?[jt]sx?$/;
260
+ const isRouteEntry = (name) => !name.startsWith(".") && !name.startsWith("-");
261
+ /** The route files under `dir`, by path relative to it. */
262
+ function routeFilesIn(dir, at = "") {
263
+ if (!existsSync(dir)) return [];
264
+ return readdirSync(join(dir, at), { withFileTypes: true }).filter((entry) => isRouteEntry(entry.name)).flatMap((entry) => {
265
+ const path = at ? `${at}/${entry.name}` : entry.name;
266
+ if (entry.isDirectory()) return routeFilesIn(dir, path);
267
+ return ROUTE_FILE.test(entry.name) ? [path] : [];
268
+ });
269
+ }
270
+ /** A route file's id below its folder: route groups and `route` files
271
+ * resolved, flat `a.b` names read as folders. */
272
+ function routeIdOf(file) {
273
+ const segments = file.replace(ROUTE_FILE, "").split("/").filter((segment) => !/^\(.+\)$/.test(segment));
274
+ if (segments.at(-1) === "route") segments.pop();
275
+ return segments.join("/").replaceAll(".", "/");
276
+ }
277
+ /** Connect's `_app/` route files that a project file at the same id replaces. */
278
+ function overriddenConnectRoutes(connectAppDir, projectAppDir) {
279
+ const projectIds = new Set(routeFilesIn(projectAppDir).map(routeIdOf));
280
+ return new Set(routeFilesIn(connectAppDir).filter((file) => projectIds.has(routeIdOf(file))));
281
+ }
282
+ const stemOf = (name) => name.replace(ROUTE_FILE, "");
283
+ /** Mounts Connect's routes in `dir` without the `overridden` files: a folder
284
+ * whole when none is in it, else file by file. */
285
+ function mountConnectRoutes(routesDirectory, dir, overridden, prefix = "") {
286
+ if (![...overridden].some((file) => file.startsWith(`${dir}/`))) return [physical(prefix, dir)];
287
+ const entries = readdirSync(join(routesDirectory, dir), { withFileTypes: true }).filter((entry) => isRouteEntry(entry.name));
288
+ const files = entries.filter((entry) => entry.isFile() && ROUTE_FILE.test(entry.name)).map((entry) => entry.name);
289
+ const folders = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
290
+ const at = (name) => prefix ? `${prefix}/${name}` : name;
291
+ const nodes = [];
292
+ for (const name of files) {
293
+ const file = `${dir}/${name}`;
294
+ const stem = stemOf(name);
295
+ const folder = folders.includes(stem) ? `${dir}/${stem}` : void 0;
296
+ if (overridden.has(file)) {
297
+ if (folder) nodes.push(physical(at(stem), folder));
298
+ continue;
299
+ }
300
+ const children = folder && mountConnectRoutes(routesDirectory, folder, overridden);
301
+ if (stem === "index") nodes.push(prefix ? route(`${prefix}/`, file) : index(file));
302
+ else if (!prefix && stem.startsWith("_")) nodes.push(layout(stem, file, children || []));
303
+ else nodes.push(children ? route(at(stem), file, children) : route(at(stem), file));
304
+ }
305
+ for (const name of folders) {
306
+ if (files.some((file) => stemOf(file) === name)) continue;
307
+ nodes.push(...mountConnectRoutes(routesDirectory, `${dir}/${name}`, overridden, at(name)));
308
+ }
309
+ return nodes;
310
+ }
311
+ /** The routes a package offers other Connects, as `ph build` publishes them
312
+ * (`./connect-routes`); generated beside the route tree. */
313
+ const PACKAGE_ROUTES_MODULE = ".ph/connect-routes.package.ts";
314
+ /** Writes the package's routes for registerPackageRoutes: its files but its
315
+ * `_app` layout and its overrides of Connect's `_app/` routes, parents first. */
316
+ function writePackageRoutesModule(projectRoot, projectRoutes, routeNodes, options) {
317
+ const module = join(projectRoot, PACKAGE_ROUTES_MODULE);
318
+ const appDir = join(projectRoutes, APP_LAYOUT);
319
+ const offered = routeNodes.map((node) => ({
320
+ node,
321
+ file: join(options.routesDirectory, node.filePath)
322
+ })).filter(({ node, file }) => {
323
+ if (!file.startsWith(`${projectRoutes}${sep}`)) return false;
324
+ if (node.routePath === `/_app`) return false;
325
+ if (!file.startsWith(`${appDir}${sep}`)) return true;
326
+ const id = routeIdOf(relative(appDir, file).split(sep).join("/"));
327
+ return !options.connectAppIds.has(id);
328
+ }).sort((a, b) => (a.node.routePath ?? "").split("/").length - (b.node.routePath ?? "").split("/").length);
329
+ if (offered.length === 0) {
330
+ rmSync(module, { force: true });
331
+ return;
332
+ }
333
+ const from = (file) => {
334
+ return relative(dirname(module), file).split(sep).join("/").replace(ROUTE_FILE, ".js");
335
+ };
336
+ const lines = [
337
+ "// Generated by ph build: the routes this package offers other Connects.",
338
+ "import type { PackageRoute } from \"@powerhousedao/connect-core/router\";",
339
+ ...offered.map(({ file }, i) => `import { Route as r${i} } from "${from(file)}";`),
340
+ "",
341
+ "export const connectRoutes: PackageRoute[] = [",
342
+ ...offered.map(({ node }, i) => {
343
+ const pathless = node._fsRouteType === "pathless_layout";
344
+ const entry = {
345
+ id: node.routePath,
346
+ ...pathless ? {} : { path: node.path },
347
+ parentId: node.parent?.routePath ?? "__root__"
348
+ };
349
+ return ` { route: r${i}, ${Object.entries(entry).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(", ")} },`;
350
+ }),
351
+ "];",
352
+ ""
353
+ ];
354
+ mkdirSync(dirname(module), { recursive: true });
355
+ const text = lines.join("\n");
356
+ if (!existsSync(module) || readFileSync(module, "utf8") !== text) writeFileSync(module, text);
357
+ }
358
+ /** The router plugin's config: Connect's root and routes, and the project's. */
359
+ function connectRoutesGeneratorConfig(connectDir, projectRoot, projectRoutes) {
360
+ const routesDirectory = connectRoutesDirOf(connectDir);
361
+ const fromRoutes = (path) => relative(routesDirectory, path);
362
+ const virtualRouteConfig = () => {
363
+ const appLayout = findRouteFile(projectRoutes, APP_LAYOUT);
364
+ const appRoutes = join(projectRoutes, APP_LAYOUT);
365
+ const overridden = new Set([...overriddenConnectRoutes(join(routesDirectory, APP_LAYOUT), appRoutes)].map((file) => `${APP_LAYOUT}/${file}`));
366
+ return rootRoute("__root.tsx", [layout(APP_LAYOUT, appLayout ? fromRoutes(appLayout) : `${APP_LAYOUT}.tsx`, [...mountConnectRoutes(routesDirectory, APP_LAYOUT, overridden), ...existsSync(appRoutes) ? [physical("", fromRoutes(appRoutes))] : []]), physical("", fromRoutes(projectRoutes))]);
367
+ };
368
+ const overrides = {
369
+ name: "ph-connect-route-overrides",
370
+ init: ({ generator }) => {
371
+ Object.defineProperty(generator.config, "virtualRouteConfig", {
372
+ get: virtualRouteConfig,
373
+ configurable: true,
374
+ enumerable: true
375
+ });
376
+ }
377
+ };
378
+ const offers = isDefaultRoutesDir(projectRoot, projectRoutes);
379
+ return getConfig({
380
+ target: "react",
381
+ routesDirectory,
382
+ generatedRouteTree: connectRoutesTreeOf(projectRoot, projectRoutes),
383
+ virtualRouteConfig: virtualRouteConfig(),
384
+ plugins: offers ? [overrides, {
385
+ name: "ph-connect-offered-routes",
386
+ onRouteTreeChanged: ({ routeNodes }) => {
387
+ writePackageRoutesModule(projectRoot, projectRoutes, routeNodes, {
388
+ routesDirectory,
389
+ connectAppIds: new Set(routeFilesIn(join(routesDirectory, APP_LAYOUT)).map(routeIdOf))
390
+ });
391
+ }
392
+ }] : [overrides],
393
+ routeFileIgnorePattern: `^${APP_LAYOUT}(\\.[cm]?[jt]sx?)?$`,
394
+ quoteStyle: "double",
395
+ semicolons: true,
396
+ addExtensions: "js",
397
+ autoCodeSplitting: true,
398
+ disableLogging: true,
399
+ routeTreeFileFooter: [
400
+ "import type { ConnectRouterFor } from \"@powerhousedao/connect/router\";",
401
+ "declare module \"@tanstack/react-router\" {",
402
+ " interface Register {",
403
+ " router: ConnectRouterFor<typeof routeTree>;",
404
+ " }",
405
+ "}"
406
+ ]
407
+ }, projectRoot);
408
+ }
409
+ /** Writes the route tree of Connect's and the project's routes; throws on a
410
+ * collision that is not an override, which the router plugin would only log. */
411
+ async function generateConnectRoutes(projectRoot, routesDir, config = connectRoutesGeneratorConfig(connectDirOf(projectRoot), projectRoot, routesDir)) {
412
+ mkdirSync(dirname(config.generatedRouteTree), { recursive: true });
413
+ try {
414
+ await new Generator({
415
+ config,
416
+ root: projectRoot
417
+ }).run();
418
+ assertNoDuplicateRoutes(config.generatedRouteTree);
419
+ importConnectRoutesByPackage(config.generatedRouteTree, config.routesDirectory);
420
+ } catch (error) {
421
+ const message = (Array.isArray(error) ? error : [error]).map((e) => e instanceof Error ? e.message : String(e)).join("\n");
422
+ const shown = relative(projectRoot, routesDir).split(sep).join("/");
423
+ throw new Error(`Connect could not mount the routes in ${shown}/:\n${message}`, { cause: error });
424
+ }
425
+ }
426
+ /** Connect's route files, as the generated tree imports them: by Connect's
427
+ * package name, which a project depends on. */
428
+ const CONNECT_ROUTES_SPECIFIER = "@powerhousedao/connect/routes";
429
+ function importConnectRoutesByPackage(treeFile, routesDirectory) {
430
+ const prefix = `"./${relative(dirname(treeFile), routesDirectory).split(sep).join("/")}/`;
431
+ const tree = readFileSync(treeFile, "utf8");
432
+ const rewritten = tree.replace(new RegExp(`${escapeRegExp(prefix)}([^"]+)\\.js"`, "g"), `"${CONNECT_ROUTES_SPECIFIER}/$1"`);
433
+ if (rewritten !== tree) writeFileSync(treeFile, rewritten);
434
+ }
435
+ function assertNoDuplicateRoutes(treeFile) {
436
+ const tree = readFileSync(treeFile, "utf8");
437
+ const files = /* @__PURE__ */ new Map();
438
+ for (const [, name, file] of tree.matchAll(/^import \{ Route as (\w+) \} from "([^"]+)";$/gm)) files.set(name, [...files.get(name) ?? [], file]);
439
+ const conflicts = [...files.values()].filter((list) => list.length > 1);
440
+ if (conflicts.length === 0) return;
441
+ throw new Error(`Conflicting configuration paths were found for a layout route.\nConflicting files: \n ${conflicts.flat().join("\n ")}\n`);
442
+ }
443
+ function escapeRegExp(text) {
444
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
445
+ }
446
+ /** Generates the tree when the project has routes, else drops a stale one. */
447
+ async function syncConnectRoutes(projectRoot, routesDir = resolveConnectRoutesDir(projectRoot)) {
448
+ if (routesDir) await generateConnectRoutes(projectRoot, routesDir);
449
+ else {
450
+ rmSync(join(projectRoot, CONNECT_ROUTES_GEN), { force: true });
451
+ rmSync(join(projectRoot, PACKAGE_ROUTES_MODULE), { force: true });
452
+ }
453
+ }
454
+ function connectDirOf(projectRoot) {
455
+ return dirname(resolvePackage("@powerhousedao/connect/package.json", projectRoot));
456
+ }
457
+ /** What Connect's route files import, besides each other. */
458
+ const CONNECT_ROUTE_FILE_DEPS = ["@tanstack/react-router", "@powerhousedao/connect-core/router"];
459
+ const IN_NODE_MODULES = /[\\/]node_modules[\\/]/;
460
+ /**
461
+ * The `optimizeDeps.include` entries an installed Connect's route files need.
462
+ *
463
+ * Connect and core ship their route files as `.tsx`, which Vite never
464
+ * pre-bundles, so the dev server serves them as they are. Vite also discovers
465
+ * no dependency for a module inside node_modules, so their bare imports load
466
+ * unbundled too, and the CommonJS packages under the router
467
+ * (use-sync-external-store, safe-stable-stringify) then fail in the browser.
468
+ * Pre-bundling these by Connect's name gives the route files the copies they
469
+ * resolve to; core need not be resolvable from the project. A Connect outside
470
+ * node_modules (the monorepo, a linked checkout) is source to Vite, so its
471
+ * imports are discovered and pre-bundled anyway.
472
+ */
473
+ function connectRouteFileDeps(connectDir) {
474
+ if (!IN_NODE_MODULES.test(connectDir)) return [];
475
+ return CONNECT_ROUTE_FILE_DEPS.map((dep) => `@powerhousedao/connect > ${dep}`);
476
+ }
477
+ /** Mounts a project's routes folder over Connect's routes; without one,
478
+ * Connect keeps its prebuilt tree and no router plugin runs. */
479
+ function connectRoutes(projectRoot, routesDir = resolveConnectRoutesDir(projectRoot)) {
480
+ const connectDir = connectDirOf(projectRoot);
481
+ const find = ROUTE_TREE_FIND;
482
+ const include = connectRouteFileDeps(connectDir);
483
+ if (!routesDir) {
484
+ if (!resolveConnectRoutesDir(projectRoot)) rmSync(join(projectRoot, CONNECT_ROUTES_GEN), { force: true });
485
+ return {
486
+ aliases: [{
487
+ find,
488
+ replacement: join(connectDir, "dist/route-tree.js")
489
+ }],
490
+ plugins: [],
491
+ dedupe: [],
492
+ include
493
+ };
494
+ }
495
+ const config = connectRoutesGeneratorConfig(connectDir, projectRoot, routesDir);
496
+ mkdirSync(dirname(config.generatedRouteTree), { recursive: true });
497
+ return {
498
+ aliases: [{
499
+ find,
500
+ replacement: config.generatedRouteTree
501
+ }, {
502
+ find: /^@powerhousedao\/connect\/route-views$/,
503
+ replacement: join(connectDir, "dist/route-views.js")
504
+ }],
505
+ plugins: [{
506
+ name: "ph-connect-routes-check",
507
+ buildStart: () => generateConnectRoutes(projectRoot, routesDir, config)
508
+ }, tanstackRouter(config)],
509
+ dedupe: ["@tanstack/react-router"],
510
+ include
511
+ };
512
+ }
513
+ const ROUTER_PACKAGES = /[\\/]node_modules[\\/]@tanstack[\\/](react-router|router-core|history|react-store|store)[\\/]/;
514
+ /** One chunk for the router and the project's route configs, which the split
515
+ * route components would otherwise spread over several shared chunks. */
516
+ function connectRouterChunkGroups(routesDir) {
517
+ const routes = routesDir && join(routesDir, sep);
518
+ return [
519
+ {
520
+ name: "preload-helper",
521
+ test: /vite[\\/]preload-helper/,
522
+ priority: 1
523
+ },
524
+ {
525
+ name: "use-sync-external-store",
526
+ test: /[\\/]node_modules[\\/]use-sync-external-store[\\/]/,
527
+ priority: 1
528
+ },
529
+ {
530
+ name: "router",
531
+ test: (id) => ROUTER_PACKAGES.test(id) || !!routes && id.startsWith(routes) && !id.includes("tsr-split")
532
+ }
533
+ ];
534
+ }
535
+ //#endregion
536
+ //#region connect-utils/vite-plugins/host-stylesheet.ts
537
+ /** The host's stylesheet, which may not exist yet: `style.css` beside its routes
538
+ * folder, so `hosts/connect/style.css` by default. `ph build` never reads it. */
539
+ function hostStylesheetPath(projectRoot, routesDir) {
540
+ const hostDir = routesDir ? dirname(routesDir) : join(projectRoot, dirname(HOST_ROUTES_DIR));
541
+ return join(hostDir, "style.css");
542
+ }
543
+ const importOf = (stylesheet, file) => `@import ${JSON.stringify(`./${normalizePath(relative(dirname(stylesheet), file))}`)};`;
544
+ /** The project's `style.css` with the host's stylesheet imported last when it
545
+ * exists (else `missing`), so the host's theme wins in the page's one build. */
546
+ function withHostStylesheet(css, stylesheet, hostStylesheet, missing) {
547
+ const file = hostStylesheet && existsSync(hostStylesheet) ? hostStylesheet : missing;
548
+ return file ? `${css}\n${importOf(stylesheet, file)}\n` : css;
549
+ }
550
+ /** Serves the project's `style.css` with the host's stylesheet in it. */
551
+ function hostStylesheetPlugin(projectRoot, hostStylesheet) {
552
+ const stylesheet = join(projectRoot, "style.css");
553
+ const stylesheetId = normalizePath(stylesheet);
554
+ const hostId = normalizePath(hostStylesheet);
555
+ let placeholder;
556
+ return {
557
+ name: "ph-host-stylesheet",
558
+ enforce: "pre",
559
+ configResolved(config) {
560
+ if (config.command !== "serve") return;
561
+ placeholder = join(config.cacheDir, "ph-host-stylesheet.css");
562
+ mkdirSync(dirname(placeholder), { recursive: true });
563
+ writeFileSync(placeholder, "/* Until the host's style.css exists. */\n");
564
+ },
565
+ load(id) {
566
+ if (normalizePath(id.split("?")[0]) !== stylesheetId) return null;
567
+ return withHostStylesheet(readFileSync(stylesheet, "utf8"), stylesheet, hostStylesheet, placeholder);
568
+ },
569
+ hotUpdate(ctx) {
570
+ if (normalizePath(ctx.file) !== hostId) return;
571
+ if (ctx.type === "create" && placeholder && existsSync(placeholder)) {
572
+ const now = /* @__PURE__ */ new Date();
573
+ utimesSync(placeholder, now, now);
574
+ }
575
+ const modules = this.environment.moduleGraph.getModulesByFile(stylesheetId);
576
+ return [...ctx.modules, ...modules ?? []];
577
+ }
578
+ };
579
+ }
580
+ //#endregion
581
+ //#region connect-utils/vite-plugins/node-dedupe.ts
582
+ /** `pkg` is installed for `root`: in a node_modules at or above it. */
583
+ function installedFor(root, pkg) {
584
+ for (let dir = root;; dir = dirname(dir)) {
585
+ if (existsSync(join(dir, "node_modules", pkg, "package.json"))) return true;
586
+ if (dirname(dir) === dir) return false;
587
+ }
588
+ }
589
+ /** `specifier` names `pkg` or one of its subpaths. */
590
+ function names(specifier, pkg) {
591
+ return specifier === pkg || specifier.startsWith(`${pkg}/`);
592
+ }
593
+ /**
594
+ * Runs `fn` with Node's resolution of `packages` (and subpaths) pinned to
595
+ * `root`'s copy. Vite's `resolve.dedupe` reaches only what Vite resolves; an
596
+ * SSR-externalized dependency is loaded by Node from its real path, which for
597
+ * a linked checkout is the checkout's node_modules: two Reacts, and the first
598
+ * hook fails with "reading 'useMemo'". A package `root` lacks keeps its usual
599
+ * resolution.
600
+ */
601
+ async function withNodeDedupe(root, packages, fn) {
602
+ const pinned = packages.filter((pkg) => installedFor(root, pkg));
603
+ if (pinned.length === 0) return fn();
604
+ const rootManifest = join(root, "package.json");
605
+ const parentURL = pathToFileURL(rootManifest).href;
606
+ const rootRequire = createRequire(rootManifest);
607
+ const hooks = registerHooks({ resolve(specifier, context, nextResolve) {
608
+ if (!(context.parentURL !== parentURL && pinned.some((pkg) => names(specifier, pkg)))) return nextResolve(specifier, context);
609
+ if (context.conditions.includes("require")) return {
610
+ url: pathToFileURL(rootRequire.resolve(specifier)).href,
611
+ shortCircuit: true
612
+ };
613
+ return nextResolve(specifier, {
614
+ ...context,
615
+ parentURL
616
+ });
617
+ } });
618
+ try {
619
+ return await fn();
620
+ } finally {
621
+ hooks.deregister();
622
+ }
623
+ }
624
+ //#endregion
625
+ //#region connect-utils/vite-plugins/project-brand.ts
626
+ /** `<meta name>` that tells Connect's loaders which image replaces the logo. */
627
+ const LOADER_META = "ph-loader";
628
+ /** `<meta name>` set when the project's `_app` replaces Connect's layout. */
629
+ const CUSTOM_SHELL_META = "ph-custom-shell";
630
+ const DEFAULT_LOADER_SIZE = 96;
631
+ const DEFAULT_BRANDING = DEFAULT_CONNECT_CONFIG.branding ?? {};
632
+ /**
633
+ * The branding in effect: defaults < source powerhouse.config.json <
634
+ * CLI / host override, applied in that order. In every layer `undefined`
635
+ * leaves the field alone and `null` resets it to the default, so a null in a
636
+ * later layer beats a value in an earlier one. Keys branding does not have
637
+ * (a `homeBackground` from before it moved to `connect.home`) are dropped.
638
+ */
639
+ function effectiveBranding(...layers) {
640
+ const out = { ...DEFAULT_BRANDING };
641
+ const defaults = DEFAULT_BRANDING;
642
+ for (const layer of layers) {
643
+ if (!layer) continue;
644
+ const entries = Object.entries(layer);
645
+ for (const [key, value] of entries) {
646
+ if (value === void 0 || !(key in defaults)) continue;
647
+ out[key] = value === null ? defaults[key] ?? null : value;
648
+ }
649
+ }
650
+ out.appName = (typeof out.appName === "string" ? out.appName.trim() : void 0) || DEFAULT_BRANDING.appName;
651
+ return out;
652
+ }
653
+ /**
654
+ * The `branding` block Connect reads at boot: the app icon reduced to its
655
+ * 64 px variant as a data URI (the in-app logo; a master would be ~1 MB of
656
+ * base64), the loader left out (it is served as a file and declared in
657
+ * index.html). Fields without a usable image end up null.
658
+ */
659
+ function resolveRuntimeBranding(projectRoot, branding, warn) {
660
+ const out = {
661
+ appName: branding.appName ?? DEFAULT_BRANDING.appName,
662
+ icon: null,
663
+ loader: null
664
+ };
665
+ if (branding.icon) {
666
+ const logo = iconVariantPath(projectRoot, branding.icon, 64);
667
+ out.icon = resolveImageRef(projectRoot, logo ?? branding.icon, {
668
+ maxBytes: UI_ICON_MAX_BYTES,
669
+ warn
670
+ }) ?? null;
671
+ }
672
+ return out;
673
+ }
674
+ /**
675
+ * A pane's background with every image, in both colour schemes, resolved to
676
+ * a data URI: a single image stays a single image, layers stay layers (a
677
+ * layer without a usable image is dropped). Problems the renderer cannot
678
+ * fix are warned about: a layer pinned to both edges of an axis, an SVG
679
+ * without a viewBox (its aspect is unknown, so it needs both dimensions).
680
+ */
681
+ function resolveBackground(projectRoot, background, warn) {
682
+ if (!background) return null;
683
+ for (const problem of validateBackground(background, "homeBackground")) warn?.(`[branding] ${problem}`);
684
+ const resolveOne = (ref) => {
685
+ if (!isPassthroughImageRef(ref) && extname(ref).toLowerCase() === ".svg") warnWithoutViewBox(projectRoot, ref, warn);
686
+ return resolveImageRef(projectRoot, ref, {
687
+ maxBytes: BACKGROUND_MAX_BYTES,
688
+ warn
689
+ });
690
+ };
691
+ if (typeof background === "string") return resolveOne(background) ?? null;
692
+ return mapBackgroundImages(background, resolveOne);
693
+ }
694
+ function warnWithoutViewBox(projectRoot, ref, warn) {
695
+ const file = resolve(projectRoot, ref);
696
+ if (!existsSync(file)) return;
697
+ const head = readFileSync(file, "utf8").slice(0, 4096);
698
+ if (!/<svg[^>]*\sviewBox\s*=/i.test(head)) warn?.(`[branding] ${ref} has no viewBox, so its aspect is unknown: give the layer both width and height.`);
699
+ }
700
+ const EXPLORER_ICON_KEYS = [
701
+ "localDrive",
702
+ "remoteDrive",
703
+ "folder",
704
+ "document"
705
+ ];
706
+ /**
707
+ * The drive explorer's icons with every path resolved to a data URI; a key
708
+ * without a usable image is dropped (the built-in icon), an empty or null
709
+ * set is null.
710
+ */
711
+ function resolveExplorerIcons(projectRoot, icons, warn) {
712
+ if (!icons) return null;
713
+ const ui = {
714
+ maxBytes: UI_ICON_MAX_BYTES,
715
+ warn
716
+ };
717
+ const out = {};
718
+ for (const key of EXPLORER_ICON_KEYS) {
719
+ const src = resolveImageRef(projectRoot, icons[key], ui);
720
+ if (src) out[key] = src;
721
+ }
722
+ if (icons.documents) {
723
+ const documents = {};
724
+ for (const [type, ref] of Object.entries(icons.documents)) {
725
+ const src = resolveImageRef(projectRoot, ref, ui);
726
+ if (src) documents[type] = src;
727
+ }
728
+ if (Object.keys(documents).length > 0) out.documents = documents;
729
+ }
730
+ return Object.keys(out).length > 0 ? out : null;
731
+ }
732
+ /** A generic plugin entry whose config carries images to resolve. */
733
+ function hasGenericImages(entry) {
734
+ return entry.module === "@powerhousedao/connect/plugins/generic" && entry.config !== void 0 && ("icons" in entry.config || "homeBackground" in entry.config);
735
+ }
736
+ /**
737
+ * A connect block with the generic plugin's images resolved, wherever they
738
+ * are declared: `drives.icons` and `home.background` (the classic source
739
+ * values) and the generic plugin entry's `icons` / `homeBackground` in a
740
+ * served composition (the owner under uniform runners). Unchanged when none
741
+ * is present.
742
+ */
743
+ function withResolvedGenericImages(projectRoot, connect, warn) {
744
+ if (!connect) return connect;
745
+ let out = connect;
746
+ if (connect.drives && "icons" in connect.drives) out = {
747
+ ...out,
748
+ drives: {
749
+ ...out.drives,
750
+ icons: resolveExplorerIcons(projectRoot, connect.drives.icons, warn)
751
+ }
752
+ };
753
+ if (connect.home && "background" in connect.home) out = {
754
+ ...out,
755
+ home: {
756
+ ...out.home,
757
+ background: resolveBackground(projectRoot, connect.home.background, warn)
758
+ }
759
+ };
760
+ if (connect.composition?.some(hasGenericImages)) out = {
761
+ ...out,
762
+ composition: connect.composition.map((entry) => {
763
+ if (!hasGenericImages(entry)) return entry;
764
+ const config = { ...entry.config };
765
+ if ("icons" in config) config.icons = resolveExplorerIcons(projectRoot, config.icons, warn);
766
+ if ("homeBackground" in config) config.homeBackground = resolveBackground(projectRoot, config.homeBackground, warn);
767
+ return {
768
+ ...entry,
769
+ config
770
+ };
771
+ })
772
+ };
773
+ return out;
774
+ }
775
+ const IMAGE_TYPES = {
776
+ ".png": "image/png",
777
+ ".svg": "image/svg+xml",
778
+ ".webp": "image/webp",
779
+ ".gif": "image/gif",
780
+ ".jpg": "image/jpeg",
781
+ ".jpeg": "image/jpeg"
782
+ };
783
+ function projectFile(projectRoot, ref) {
784
+ return isAbsolute(ref) ? ref : resolve(projectRoot, ref);
785
+ }
786
+ function asset(projectRoot, ref, fileName, warn) {
787
+ if (isPassthroughImageRef(ref)) {
788
+ warn?.(`[branding] ${ref}: use a project file path here, not a URL. Skipped.`);
789
+ return;
790
+ }
791
+ const file = projectFile(projectRoot, ref);
792
+ const ext = extname(file).toLowerCase();
793
+ const contentType = IMAGE_TYPES[ext];
794
+ if (!contentType) {
795
+ warn?.(`[branding] ${ref}: unsupported image type. Skipped.`);
796
+ return;
797
+ }
798
+ if (!existsSync(file)) {
799
+ warn?.(`[branding] ${ref}: file not found. Skipped.`);
800
+ return;
801
+ }
802
+ return {
803
+ fileName: fileName(ext),
804
+ file,
805
+ contentType
806
+ };
807
+ }
808
+ /** `branding.loader` as the build emits it; undefined keeps Connect's logo. */
809
+ function resolveProjectLoader(projectRoot, branding, warn) {
810
+ const loader = branding?.loader;
811
+ if (!loader) return void 0;
812
+ const spec = typeof loader === "string" ? { src: loader } : loader;
813
+ const found = asset(projectRoot, spec.src, (ext) => `ph-loader${ext}`, warn);
814
+ if (!found) return void 0;
815
+ return {
816
+ ...found,
817
+ animation: spec.animation ?? "pulse",
818
+ size: spec.size ?? DEFAULT_LOADER_SIZE
819
+ };
820
+ }
821
+ /** Width and height from a PNG's IHDR chunk. */
822
+ function pngSize(bytes) {
823
+ if (bytes.length < 24 || [
824
+ 137,
825
+ 80,
826
+ 78,
827
+ 71,
828
+ 13,
829
+ 10,
830
+ 26,
831
+ 10
832
+ ].some((b, i) => bytes[i] !== b)) return;
833
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
834
+ return [view.getUint32(16), view.getUint32(20)];
835
+ }
836
+ /** The installed app's name and icons, from `branding.appName` and
837
+ * `branding.icon`. Undefined members keep Connect's own. */
838
+ function resolveProjectPwaBrand(projectRoot, branding, warn) {
839
+ const brand = {};
840
+ const name = branding?.appName?.trim();
841
+ if (name && name !== DEFAULT_BRANDING.appName) brand.name = name;
842
+ const app = branding?.icon;
843
+ if (!app) return brand;
844
+ const ext = extname(app).toLowerCase();
845
+ if (ext === ".svg") {
846
+ const svg = asset(projectRoot, app, () => "pwa-app.svg", warn);
847
+ if (svg) brand.icons = [{
848
+ ...svg,
849
+ sizes: "any"
850
+ }];
851
+ return brand;
852
+ }
853
+ if (ext !== ".png") {
854
+ warn?.(`[branding] icon ${app}: the installed-app icon needs a PNG or SVG. Connect's icon stays.`);
855
+ return brand;
856
+ }
857
+ const icons = [];
858
+ const seen = /* @__PURE__ */ new Set();
859
+ const add = (ref) => {
860
+ const file = projectFile(projectRoot, ref);
861
+ if (!existsSync(file)) return;
862
+ const size = pngSize(readFileSync(file));
863
+ if (!size) return;
864
+ const sizes = `${size[0]}x${size[1]}`;
865
+ if (seen.has(sizes)) return;
866
+ seen.add(sizes);
867
+ icons.push({
868
+ fileName: `pwa-app-${sizes}.png`,
869
+ file,
870
+ contentType: "image/png",
871
+ sizes
872
+ });
873
+ };
874
+ const stem = app.slice(0, app.length - ext.length);
875
+ for (const size of PWA_ICON_VARIANT_SIZES) add(`${stem}_${size}x${size}${ext}`);
876
+ add(app);
877
+ if (icons.length === 0) {
878
+ warn?.(`[branding] icon ${app}: not a readable PNG. Connect's icon stays.`);
879
+ return brand;
880
+ }
881
+ brand.icons = icons;
882
+ return brand;
883
+ }
884
+ /**
885
+ * The favicons: the `_16x16` / `_32x32` / `_64x64` siblings of
886
+ * `branding.icon` (an SVG master is one scalable favicon). They replace
887
+ * Connect's static icon.ico link in index.html; none keeps it. A favicon
888
+ * named outright (`faviconPath`: `branding.favicon` or `--favicon`) wins: it
889
+ * is built as icon.ico, so the icon's siblings stand aside.
890
+ */
891
+ function resolveProjectFavicons(projectRoot, branding, warn, faviconPath) {
892
+ const app = branding?.icon;
893
+ if (!app || faviconPath) return [];
894
+ if (isPassthroughImageRef(app)) {
895
+ warn?.(`[branding] icon ${app}: use a project file path here, not a URL. Connect's favicon stays.`);
896
+ return [];
897
+ }
898
+ const ext = extname(app).toLowerCase();
899
+ if (ext === ".svg") {
900
+ const svg = asset(projectRoot, app, () => "favicon.svg", warn);
901
+ return svg ? [{
902
+ ...svg,
903
+ sizes: "any"
904
+ }] : [];
905
+ }
906
+ const out = [];
907
+ for (const size of APP_ICON_VARIANT_SIZES) {
908
+ const variant = iconVariantPath(projectRoot, app, size);
909
+ if (!variant) continue;
910
+ const file = projectFile(projectRoot, variant);
911
+ const contentType = imageMimeType(file);
912
+ if (!contentType) continue;
913
+ out.push({
914
+ fileName: `favicon-${size}x${size}${ext}`,
915
+ file,
916
+ contentType,
917
+ sizes: `${size}x${size}`
918
+ });
919
+ }
920
+ if (out.length === 0) warn?.(`[branding] icon ${app}: no _16x16 / _32x32 / _64x64 siblings found. Connect's favicon stays.`);
921
+ return out;
922
+ }
923
+ function escapeAttr(value) {
924
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
925
+ }
926
+ /** The `<meta>` tags Connect's loaders read. */
927
+ function brandMetaTags(options) {
928
+ const tags = [];
929
+ const { loader } = options;
930
+ if (loader) tags.push(`<meta name="${LOADER_META}" content="${escapeAttr(loader.fileName)}" data-animation="${loader.animation}" data-size="${loader.size}">`);
931
+ if (options.customShell) tags.push(`<meta name="${CUSTOM_SHELL_META}" content="true">`);
932
+ return tags.join("");
933
+ }
934
+ const ICON_LINK = /<link\b[^>]*\brel=["']?(?:shortcut )?icon["']?[^>]*>\s*/gi;
935
+ /** index.html with Connect's icon links replaced by the project's favicons
936
+ * (one sized link per variant, under `base`); unchanged without any. */
937
+ function withProjectFavicons(html, favicons, base = "/") {
938
+ if (favicons.length === 0) return html;
939
+ const prefix = base.endsWith("/") ? base : `${base}/`;
940
+ const links = favicons.map((icon) => `<link rel="icon" type="${icon.contentType}" sizes="${icon.sizes}" href="${escapeAttr(prefix + icon.fileName)}" />`).join("");
941
+ return html.replace(ICON_LINK, "").replace("</head>", `${links}</head>`);
942
+ }
943
+ /** Keyframes for the loader motions; shared by the shell and the app. */
944
+ const LOADER_KEYFRAMES = "@keyframes ph-loader-pulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.6;transform:scale(.94)}}@keyframes ph-loader-spin{to{transform:rotate(360deg)}}";
945
+ const LOADER_ANIMATION = {
946
+ pulse: "ph-loader-pulse 1.6s ease-in-out infinite",
947
+ spin: "ph-loader-spin 1.4s linear infinite",
948
+ none: "none"
949
+ };
950
+ /** The loader as static markup, for the prerendered shell's first paint. */
951
+ function loaderMarkup(loader, base = "/") {
952
+ const prefix = base.endsWith("/") ? base : `${base}/`;
953
+ const motion = LOADER_ANIMATION[loader.animation];
954
+ return `<style>${LOADER_KEYFRAMES}@media (prefers-reduced-motion:reduce){[data-ph-loader-img]{animation:none!important}}</style><img data-ph-loader-img src="${escapeAttr(prefix + loader.fileName)}" alt="" width="${loader.size}" style="width:${loader.size}px;height:auto;animation:${motion}">`;
955
+ }
956
+ /** The marked slot in Connect's prerendered shell that holds its logo. */
957
+ const LOADER_SLOT = /<div\b[^>]*\bdata-ph-loader-slot\b[^>]*>[\s\S]*?<\/div>/;
958
+ /** Swaps the shell's logo slot for the project's loader. */
959
+ function replaceShellLoader(shellBody, loader, base = "/") {
960
+ return shellBody.replace(LOADER_SLOT, () => loaderMarkup(loader, base));
961
+ }
962
+ /**
963
+ * Serves (dev) and emits (build) the branding files, and adds the tags
964
+ * index.html carries before any JavaScript: the loader and custom-shell
965
+ * meta tags, and the favicon links.
966
+ */
967
+ function connectProjectBrandPlugin(options) {
968
+ const favicons = options.favicons ?? [];
969
+ const files = [
970
+ ...options.loader ? [options.loader] : [],
971
+ ...options.pwaIcons ?? [],
972
+ ...favicons
973
+ ];
974
+ const meta = brandMetaTags(options);
975
+ let base = "/";
976
+ return {
977
+ name: "ph-connect-project-brand",
978
+ configResolved(config) {
979
+ base = config.base;
980
+ },
981
+ configureServer(server) {
982
+ for (const file of files) {
983
+ const handler = (_req, res, next) => {
984
+ try {
985
+ res.setHeader("Content-Type", file.contentType);
986
+ res.end(readFileSync(file.file));
987
+ } catch {
988
+ next();
989
+ }
990
+ };
991
+ const paths = /* @__PURE__ */ new Set([`${server.config.base}${file.fileName}`.replace(/\/{2,}/g, "/"), `/${file.fileName}`]);
992
+ for (const path of paths) server.middlewares.use(path, handler);
993
+ }
994
+ },
995
+ transformIndexHtml(html) {
996
+ return withProjectFavicons(meta ? html.replace("</head>", `${meta}</head>`) : html, favicons, base);
997
+ },
998
+ generateBundle(_options, bundle) {
999
+ for (const file of files) {
1000
+ if (file.fileName in bundle) continue;
1001
+ try {
1002
+ this.emitFile({
1003
+ type: "asset",
1004
+ fileName: file.fileName,
1005
+ source: readFileSync(file.file)
1006
+ });
1007
+ } catch {}
1008
+ }
1009
+ }
1010
+ };
1011
+ }
1012
+ //#endregion
1013
+ //#region connect-utils/vite-plugins/app-shell.ts
1014
+ /** On the prerendered shell's elements; marks an index.html that has it. */
1015
+ const APP_SHELL_MARKER = "data-ph-shell";
1016
+ /** In Connect's dist, and copied to a project's: the plugins that pick a shell. */
1017
+ const SHELL_PLUGINS_FILE = "shell-plugins.json";
1018
+ /** In a project's dist: every variant, for a server that swaps the shell to the served composition. */
1019
+ const APP_SHELLS_FILE = "app-shells.json";
1020
+ const SHELL_FILES = {
1021
+ generic: "shell",
1022
+ core: "shell-core"
1023
+ };
1024
+ /** The shell of the composition's first plugin that has one, else core's; no composition is classic.
1025
+ * Without `plugins` (an older Connect): core for a composition, generic for classic. */
1026
+ function appShellVariant(composition, plugins) {
1027
+ if (!plugins) return composition ? "core" : "generic";
1028
+ if (!composition) return Object.values(plugins)[0] ?? "core";
1029
+ for (const { module } of composition) if (Object.hasOwn(plugins, module)) return plugins[module];
1030
+ return "core";
1031
+ }
1032
+ function connectDistDir(projectRoot) {
1033
+ try {
1034
+ return join(dirname(resolvePackage("@powerhousedao/connect/package.json", projectRoot)), "dist");
1035
+ } catch {
1036
+ return;
1037
+ }
1038
+ }
1039
+ /** The plugins' shell manifest in `dir`, if there is a valid one. */
1040
+ function readShellPluginsIn(dir) {
1041
+ const file = join(dir, SHELL_PLUGINS_FILE);
1042
+ if (!existsSync(file)) return void 0;
1043
+ try {
1044
+ const manifest = JSON.parse(readFileSync(file, "utf8"));
1045
+ if (!manifest || typeof manifest !== "object") return void 0;
1046
+ const plugins = {};
1047
+ for (const [module, variant] of Object.entries(manifest)) if (variant === "generic" || variant === "core") plugins[module] = variant;
1048
+ return plugins;
1049
+ } catch {
1050
+ return;
1051
+ }
1052
+ }
1053
+ /** The shell manifest of the installed Connect, if it ships one. */
1054
+ function readShellPlugins(projectRoot) {
1055
+ const distDir = connectDistDir(projectRoot);
1056
+ return distDir ? readShellPluginsIn(distDir) : void 0;
1057
+ }
1058
+ /** The shell Connect's build prerendered, if the installed Connect ships one. */
1059
+ function readAppShell(projectRoot, variant = "generic") {
1060
+ const distDir = connectDistDir(projectRoot);
1061
+ if (!distDir) return void 0;
1062
+ const body = join(distDir, `${SHELL_FILES[variant]}.html`);
1063
+ const head = join(distDir, `${SHELL_FILES[variant]}-head.html`);
1064
+ if (!existsSync(body) || !existsSync(head)) return void 0;
1065
+ return {
1066
+ body: readFileSync(body, "utf8"),
1067
+ head: readFileSync(head, "utf8")
1068
+ };
1069
+ }
1070
+ /** Every variant the installed Connect ships. */
1071
+ function readAppShells(projectRoot) {
1072
+ const shells = {};
1073
+ for (const variant of Object.keys(SHELL_FILES)) {
1074
+ const shell = readAppShell(projectRoot, variant);
1075
+ if (shell) shells[variant] = shell;
1076
+ }
1077
+ return shells;
1078
+ }
1079
+ /** On the boot-recovery script; its sessionStorage key guards against reload loops. */
1080
+ const BOOT_RECOVER_MARKER = "data-ph-boot-recover";
1081
+ const BOOT_RECOVER_KEY = "ph:sw-recover";
1082
+ const BOOT_RECOVER_SCRIPT = `(function(){try{var K='${BOOT_RECOVER_KEY}',n=navigator.serviceWorker,done=0;if(!n||sessionStorage.getItem(K))return;var up=function(){return !document.querySelector('style[${APP_SHELL_MARKER}]')};var reload=function(){location.reload()};var skip=function(w){try{sessionStorage.setItem(K,'1')}catch(e){}n.addEventListener('controllerchange',reload);w.postMessage({type:'SKIP_WAITING'});setTimeout(reload,3000)};var watch=function(w){w.addEventListener('statechange',function(){if(w.state==='installed')skip(w)})};var go=function(){if(done||up())return;done=1;n.getRegistration().then(function(r){if(!r)return;if(r.waiting)return skip(r.waiting);if(r.installing)return watch(r.installing);r.addEventListener('updatefound',function(){if(r.installing)watch(r.installing)});return r.update()}).catch(function(){})};addEventListener('error',function(e){var t=e.target;if(e.error instanceof SyntaxError||e.error instanceof TypeError||(t&&t.tagName==='SCRIPT'))go()},true);addEventListener('unhandledrejection',function(e){if(e.reason instanceof SyntaxError||e.reason instanceof TypeError)go()});setTimeout(go,8000)}catch(e){}})();`;
1083
+ /** Prefixes the shell's root-relative links with the deploy base. */
1084
+ function rebaseShellLinks(body, base) {
1085
+ if (base === "/" || !base) return body;
1086
+ const prefix = base.endsWith("/") ? base : `${base}/`;
1087
+ return body.replace(/(\shref=")\/(?!\/)/g, `$1${prefix}`);
1088
+ }
1089
+ const STYLESHEET_LINK = /<link\b(?=[^>]*\brel=["']?stylesheet\b)[^>]*>/gi;
1090
+ function deferStylesheet(link) {
1091
+ return `${link.replace(/\brel=["']?stylesheet["']?/i, "rel=\"preload\" as=\"style\"").replace(/\/?>$/, ` onload="this.onload=null;this.rel='stylesheet'">`)}<noscript>${link}</noscript>`;
1092
+ }
1093
+ const region = (name, content) => `<!--ph-shell:${name}-->${content}<!--/ph-shell:${name}-->`;
1094
+ const REGION = (name) => new RegExp(`<!--ph-shell:${name}-->[\\s\\S]*?<!--/ph-shell:${name}-->`);
1095
+ /** The app's title without `connect.branding.appName`; core's `appTitle` fallback. */
1096
+ const DEFAULT_APP_NAME = "Connect";
1097
+ const APP_NAME = /(<!--ph-shell:app-name-->)[\s\S]*?(<!--\/ph-shell:app-name-->)/g;
1098
+ const escapeHtml = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1099
+ /** Fills the shell's app name as the app resolves it: the branding name, else the default. */
1100
+ function withShellAppName(html, appName) {
1101
+ const name = escapeHtml(appName || "Connect");
1102
+ return html.replace(APP_NAME, (_m, open, close) => [
1103
+ open,
1104
+ name,
1105
+ close
1106
+ ].join(""));
1107
+ }
1108
+ /** Inlines `shell` into an empty `#root`, adds its critical CSS and, unless
1109
+ * `deferStyles` is false, defers the stylesheets; React replaces the markup when the app renders. */
1110
+ function injectAppShell(html, shell, base = "/", { deferStyles = true, appName } = {}) {
1111
+ if (html.includes("data-ph-shell")) return html;
1112
+ const root = /<div id="root"><\/div>/;
1113
+ if (!root.test(html)) return html;
1114
+ const firstSheet = html.search(STYLESHEET_LINK);
1115
+ const at = firstSheet >= 0 ? firstSheet : html.indexOf("</head>");
1116
+ const recover = `<script ${BOOT_RECOVER_MARKER}>${BOOT_RECOVER_SCRIPT}<\/script>`;
1117
+ const body = withShellAppName(rebaseShellLinks(shell.body, base), appName);
1118
+ const withHead = html.slice(0, at) + region("head", shell.head) + recover + html.slice(at);
1119
+ return (deferStyles ? withHead.replace(STYLESHEET_LINK, deferStylesheet) : withHead).replace(root, () => `<div id="root">${region("body", body)}</div>`);
1120
+ }
1121
+ /** The variant an index.html carries, from its shell's marker value. */
1122
+ function appShellVariantOf(html) {
1123
+ const head = REGION("head").exec(html)?.[0];
1124
+ const value = head && new RegExp(`data-ph-shell="(\\w+)"`).exec(head);
1125
+ if (!value) return void 0;
1126
+ return value[1] === "core" ? "core" : "generic";
1127
+ }
1128
+ /** Replaces the shell an index.html carries with `shell`, titled `appName`; a page without one is unchanged. */
1129
+ function swapAppShell(html, shell, base = "/", appName) {
1130
+ if (!REGION("head").test(html) || !REGION("body").test(html)) return html;
1131
+ const body = withShellAppName(rebaseShellLinks(shell.body, base), appName);
1132
+ return html.replace(REGION("head"), () => region("head", shell.head)).replace(REGION("body"), () => region("body", body));
1133
+ }
1134
+ const DEV_SHELL_WAIT_MS = 1e4;
1135
+ const CONNECT_PACKAGES = ["@powerhousedao/connect", "@powerhousedao/connect-core"];
1136
+ async function renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet) {
1137
+ const server = await createServer({
1138
+ configFile: false,
1139
+ root: projectRoot,
1140
+ logLevel: "error",
1141
+ appType: "custom",
1142
+ server: {
1143
+ middlewareMode: true,
1144
+ hmr: false,
1145
+ ws: false
1146
+ },
1147
+ oxc: { jsx: { runtime: "automatic" } },
1148
+ resolve: {
1149
+ alias: routeAliases,
1150
+ dedupe: config.resolve.dedupe,
1151
+ tsconfigPaths: true
1152
+ },
1153
+ define: config.define,
1154
+ cacheDir: join(projectRoot, "node_modules/.vite-ph-prerender"),
1155
+ optimizeDeps: {
1156
+ noDiscovery: true,
1157
+ include: [],
1158
+ entries: []
1159
+ },
1160
+ ssr: {
1161
+ optimizeDeps: {
1162
+ noDiscovery: true,
1163
+ include: []
1164
+ },
1165
+ noExternal: CONNECT_PACKAGES
1166
+ }
1167
+ });
1168
+ try {
1169
+ return await withNodeDedupe(projectRoot, config.resolve.dedupe, async () => {
1170
+ const renderer = await server.ssrLoadModule("@powerhousedao/connect/prerender");
1171
+ const stylesheet = join(projectRoot, "style.css");
1172
+ const css = withHostStylesheet(readFileSync(stylesheet, "utf8"), stylesheet, hostStylesheet);
1173
+ return renderer.renderProjectShells(stylesheet, css);
1174
+ });
1175
+ } finally {
1176
+ await server.close();
1177
+ }
1178
+ }
1179
+ const sourceText = (source) => typeof source === "string" ? source : new TextDecoder().decode(source);
1180
+ /** Build: the composition's shell in #root and every variant in the dist, from
1181
+ * the project's routes when it has them. Dev: the shell from the project's routes
1182
+ * when it has them, else core's for a core composition. */
1183
+ function connectAppShellPlugin(projectRoot, { composition, appName, routeAliases, routesDir, loader, hostStylesheet } = {}) {
1184
+ let variant = "generic";
1185
+ let shells = {};
1186
+ let shellPlugins;
1187
+ let base = "/";
1188
+ let isBuild = true;
1189
+ let config;
1190
+ const withLoader = (from) => {
1191
+ if (!loader) return from;
1192
+ const out = {};
1193
+ for (const [name, shell] of Object.entries(from)) out[name] = {
1194
+ ...shell,
1195
+ body: replaceShellLoader(shell.body, loader, base)
1196
+ };
1197
+ return out;
1198
+ };
1199
+ const fromRoutes = () => isBuild && !!routeAliases;
1200
+ const shell = () => {
1201
+ if (fromRoutes()) return void 0;
1202
+ return isBuild || variant === "core" ? shells[variant] : void 0;
1203
+ };
1204
+ let devShells;
1205
+ let devRender;
1206
+ const renderDevShells = () => {
1207
+ if (!config || !routeAliases) return;
1208
+ const logger = config.logger;
1209
+ devShells = renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet).then(withLoader).catch((error) => {
1210
+ logger.warn(`[connect] the loading shell failed to render from the project's routes: ${String(error)}`);
1211
+ return {};
1212
+ });
1213
+ };
1214
+ const devShell = async () => {
1215
+ if (!devShells) return void 0;
1216
+ let timer;
1217
+ const wait = new Promise((resolve) => {
1218
+ timer = setTimeout(() => resolve(void 0), DEV_SHELL_WAIT_MS);
1219
+ });
1220
+ try {
1221
+ return (await Promise.race([devShells, wait]))?.[variant];
1222
+ } finally {
1223
+ clearTimeout(timer);
1224
+ }
1225
+ };
1226
+ return {
1227
+ name: "ph-connect-app-shell",
1228
+ configureServer(server) {
1229
+ if (!routeAliases) return;
1230
+ renderDevShells();
1231
+ const stylesheet = join(projectRoot, "style.css");
1232
+ const rerender = (file) => {
1233
+ if (!(file === stylesheet || file === hostStylesheet || !!routesDir && file.startsWith(`${routesDir}${sep}`))) return;
1234
+ clearTimeout(devRender);
1235
+ devRender = setTimeout(renderDevShells, 300);
1236
+ };
1237
+ server.watcher.on("change", rerender);
1238
+ server.watcher.on("add", rerender);
1239
+ server.watcher.on("unlink", rerender);
1240
+ },
1241
+ configResolved(resolved) {
1242
+ config = resolved;
1243
+ base = resolved.base;
1244
+ isBuild = resolved.command === "build";
1245
+ shells = withLoader(readAppShells(projectRoot));
1246
+ shellPlugins = readShellPlugins(projectRoot);
1247
+ variant = appShellVariant(composition, shellPlugins);
1248
+ },
1249
+ transformIndexHtml: {
1250
+ order: "post",
1251
+ handler: async (html) => {
1252
+ const current = !isBuild && routeAliases ? await devShell() : shell();
1253
+ return current ? injectAppShell(html, current, base, {
1254
+ deferStyles: isBuild,
1255
+ appName
1256
+ }) : html;
1257
+ }
1258
+ },
1259
+ generateBundle: {
1260
+ order: "post",
1261
+ async handler(_options, bundle) {
1262
+ if (!isBuild) return;
1263
+ if (fromRoutes() && config && routeAliases) {
1264
+ shells = withLoader(await renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet));
1265
+ const index = bundle["index.html"];
1266
+ const current = shells[variant];
1267
+ if (index?.type === "asset" && current) index.source = injectAppShell(sourceText(index.source), current, base, { appName });
1268
+ }
1269
+ if (!Object.keys(shells).length) return;
1270
+ this.emitFile({
1271
+ type: "asset",
1272
+ fileName: APP_SHELLS_FILE,
1273
+ source: JSON.stringify(shells)
1274
+ });
1275
+ if (shellPlugins) this.emitFile({
1276
+ type: "asset",
1277
+ fileName: SHELL_PLUGINS_FILE,
1278
+ source: JSON.stringify(shellPlugins)
1279
+ });
1280
+ }
1281
+ }
1282
+ };
1283
+ }
1284
+ //#endregion
25
1285
  //#region connect-utils/vite-plugins/build-hash.ts
26
1286
  /** Name of the build-identity file emitted into the build output. */
27
1287
  const BUILD_HASH_FILE = "build-hash.json";
@@ -44,7 +1304,8 @@ function computeBuildHash(input) {
44
1304
  */
45
1305
  function readConnectVersion(projectRoot) {
46
1306
  try {
47
- let dir = dirname(createRequire(join(projectRoot, "package.json")).resolve("@powerhousedao/connect", { paths: [projectRoot] }));
1307
+ const entry = createRequire(join(projectRoot, "package.json")).resolve("@powerhousedao/connect", { paths: [projectRoot] });
1308
+ let dir = dirname(entry);
48
1309
  for (;;) {
49
1310
  try {
50
1311
  const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
@@ -91,16 +1352,6 @@ function connectBuildHashPlugin(buildHash) {
91
1352
  //#endregion
92
1353
  //#region connect-utils/vite-plugins/dynamic-base.ts
93
1354
  /**
94
- * Placeholder base used when Connect is built in dynamic-base mode. The Vite
95
- * `base` option is set to this token; this plugin rewrites it in the emitted
96
- * output so the effective base is resolved at serve time from a global instead
97
- * of being baked at build time.
98
- *
99
- * Trailing slash matches `normalizeBasePath` output, so the token sits in the
100
- * same syntactic position as a concrete base would.
101
- */
102
- const DYNAMIC_BASE_PLACEHOLDER = "/__PH_DYNAMIC_BASE__/";
103
- /**
104
1355
  * Global the runtime (ph-clint proxy) must set before the entry bundle loads.
105
1356
  * Value is the normalized deploy base, e.g. "/myagent/" or "/". The JS rewrite
106
1357
  * below resolves all asset / lazy-chunk / BASE_URL references against it.
@@ -108,9 +1359,19 @@ const DYNAMIC_BASE_PLACEHOLDER = "/__PH_DYNAMIC_BASE__/";
108
1359
  const RUNTIME_GLOBAL = "globalThis.__PH_DYNAMIC_BASE__";
109
1360
  const BASE_EXPR = `(${RUNTIME_GLOBAL}||"/")`;
110
1361
  function workerPrelude(stripPrefix) {
111
- return `${RUNTIME_GLOBAL}=self.location.pathname.replace(/${escapeForRegExp(stripPrefix).replace(/\//g, "\\/")}assets\\/[^/]*$/,"");\n`;
1362
+ const prefix = escapeForRegExp(stripPrefix).replace(/\//g, "\\/");
1363
+ return `${RUNTIME_GLOBAL}=self.location.pathname.replace(/${prefix}assets\\/[^/]*$/,"");\n`;
112
1364
  }
113
1365
  const PLACEHOLDER_LITERAL = new RegExp(`(["'\`])${escapeForRegExp(DYNAMIC_BASE_PLACEHOLDER)}((?:(?!\\1)[^$])*)\\1`, "g");
1366
+ const PLACEHOLDER_CSS_URL = new RegExp(`url\\(\\s*(["']?)${escapeForRegExp(DYNAMIC_BASE_PLACEHOLDER)}([^"')]*)\\1\\s*\\)`, "g");
1367
+ /** Rewrites `url(<placeholder>assets/x)` relative to the stylesheet at `fileName`. */
1368
+ function relativeCssUrls(css, fileName) {
1369
+ const dir = path.posix.dirname(fileName);
1370
+ return css.replace(PLACEHOLDER_CSS_URL, (_match, quote, target) => {
1371
+ const relative = path.posix.relative(dir, target);
1372
+ return `url(${quote}${relative.startsWith(".") ? relative : `./${relative}`}${quote})`;
1373
+ });
1374
+ }
114
1375
  /**
115
1376
  * Rewrites the placeholder base in emitted JS chunks to a runtime expression so
116
1377
  * one built `dist/connect` serves under any subpath. Rolldown-native: per-match
@@ -135,16 +1396,16 @@ const PLACEHOLDER_LITERAL = new RegExp(`(["'\`])${escapeForRegExp(DYNAMIC_BASE_P
135
1396
  * (the same proxy also sets the runtime global for the JS rewrite). See the
136
1397
  * plugin's module doc / report for the exact serve-time contract.
137
1398
  *
138
- * CSS `url(...)` references resolve relative to the stylesheet's own URL, so
139
- * they need no rewrite once the stylesheet itself is loaded from the right
140
- * prefix (which the HTML substitution handles).
1399
+ * CSS `url(...)` references that Vite emits with the placeholder (e.g. bundled
1400
+ * fonts) are rewritten relative to the stylesheet, which the HTML substitution
1401
+ * already loads from the right prefix.
141
1402
  */
142
1403
  function connectDynamicBasePlugin(options = {}) {
143
1404
  return {
144
1405
  name: "ph-connect-dynamic-base",
145
1406
  enforce: "post",
146
1407
  renderChunk(code, chunk) {
147
- if (!code.includes("/__PH_DYNAMIC_BASE__/")) return null;
1408
+ if (!code.includes(DYNAMIC_BASE_PLACEHOLDER)) return null;
148
1409
  const s = new MagicString(code);
149
1410
  for (const match of code.matchAll(PLACEHOLDER_LITERAL)) {
150
1411
  const rest = match[2];
@@ -161,7 +1422,8 @@ function connectDynamicBasePlugin(options = {}) {
161
1422
  };
162
1423
  },
163
1424
  generateBundle(_options, bundle) {
164
- for (const file of Object.values(bundle)) if ((file.type === "chunk" ? file.code : file.fileName.endsWith(".css") && typeof file.source === "string" ? file.source : void 0)?.includes("/__PH_DYNAMIC_BASE__/")) this.error(`dynamic-base: unrewritten placeholder ${DYNAMIC_BASE_PLACEHOLDER} remains in ${file.fileName}`);
1425
+ for (const file of Object.values(bundle)) if (file.type === "asset" && file.fileName.endsWith(".css")) file.source = relativeCssUrls(String(file.source), file.fileName);
1426
+ for (const file of Object.values(bundle)) if ((file.type === "chunk" ? file.code : file.fileName.endsWith(".css") && typeof file.source === "string" ? file.source : void 0)?.includes(DYNAMIC_BASE_PLACEHOLDER)) this.error(`dynamic-base: unrewritten placeholder ${DYNAMIC_BASE_PLACEHOLDER} remains in ${file.fileName}`);
165
1427
  }
166
1428
  };
167
1429
  }
@@ -212,8 +1474,18 @@ const DEFAULT_VENDOR_INCLUDE = [
212
1474
  "zod",
213
1475
  "@powerhousedao/design-system/connect",
214
1476
  "@powerhousedao/reactor-browser",
215
- "@powerhousedao/document-engineering"
1477
+ "@powerhousedao/document-engineering",
1478
+ "@powerhousedao/connect-core",
1479
+ "@tanstack/react-router"
216
1480
  ];
1481
+ /** Never vendored: the route tree is the project's, the config path the app's
1482
+ * base, and SSR server-only. */
1483
+ const VENDOR_SKIP_SUBPATHS = /* @__PURE__ */ new Set([
1484
+ "@powerhousedao/connect-core/route-tree",
1485
+ "@powerhousedao/connect-core/runtime-config",
1486
+ "@tanstack/react-router/ssr/client",
1487
+ "@tanstack/react-router/ssr/server"
1488
+ ]);
217
1489
  /**
218
1490
  * React-family specifiers kept external to the vendor build. The vendor's chunks
219
1491
  * emit bare imports for these; `devReactImportmapPlugin`'s import map resolves
@@ -237,35 +1509,44 @@ const VENDOR_DYNAMIC_BASE = `${DYNAMIC_BASE_PLACEHOLDER}${VENDOR_URL_PREFIX.repl
237
1509
  */
238
1510
  async function prebuildConnectVendor(options) {
239
1511
  const include = expandIncludeSubpaths(options.dirname, options.include ?? DEFAULT_VENDOR_INCLUDE);
1512
+ const own = options.ownDeps ? resolveOwnDeps(options.ownDeps.from, options.ownDeps.specs) : {};
1513
+ for (const spec of Object.keys(own)) if (!include.includes(spec)) include.push(spec);
240
1514
  const external = options.external ?? VENDOR_EXTERNAL;
241
1515
  const vendorDir = options.vendorDir ?? join(options.dirname, "node_modules/.ph-vendor");
242
1516
  const importMapPath = join(vendorDir, "import-map.json");
243
- const versionDigest = resolveVersionDigest(options.dirname, [...include, ...external]);
1517
+ const stamps = /* @__PURE__ */ new Map();
1518
+ const versions = resolveDepVersions(options.dirname, [...include, ...external], stamps);
1519
+ const base = options.base ?? DYNAMIC_BASE_PLACEHOLDER;
1520
+ const nodeEnv = options.nodeEnv ?? "development";
1521
+ const versionDigest = resolveVersionDigest(versions, own, stamps, {
1522
+ base,
1523
+ nodeEnv
1524
+ });
244
1525
  try {
245
1526
  const hit = readCacheHit(importMapPath, include, external, versionDigest);
246
1527
  if (hit) return {
247
1528
  vendorDir,
248
- imports: hit
1529
+ ...hit
249
1530
  };
250
1531
  const lockDir = `${vendorDir}.lock`;
251
1532
  const lock = acquireLock(lockDir);
252
1533
  if (!lock) {
253
- const imports = await waitForCacheHit(importMapPath, include, external, versionDigest, lockDir);
254
- return imports ? {
1534
+ const hit = await waitForCacheHit(importMapPath, include, external, versionDigest, lockDir);
1535
+ return hit ? {
255
1536
  vendorDir,
256
- imports
1537
+ ...hit
257
1538
  } : null;
258
1539
  }
259
1540
  try {
260
1541
  const raced = readCacheHit(importMapPath, include, external, versionDigest);
261
1542
  if (raced) return {
262
1543
  vendorDir,
263
- imports: raced
1544
+ ...raced
264
1545
  };
265
- const imports = await buildVendorAtomic(options.dirname, vendorDir, include, external, versionDigest);
266
- return imports ? {
1546
+ const result = await buildVendorAtomic(options.dirname, vendorDir, include, external, versionDigest, versions, base, nodeEnv, own);
1547
+ return result ? {
267
1548
  vendorDir,
268
- imports
1549
+ ...result
269
1550
  } : null;
270
1551
  } finally {
271
1552
  releaseLock(lock);
@@ -279,27 +1560,105 @@ function readCacheHit(importMapPath, include, external, versionDigest) {
279
1560
  if (!existsSync(importMapPath)) return null;
280
1561
  try {
281
1562
  const cached = JSON.parse(readFileSync(importMapPath, "utf8"));
282
- if (sameSet(cached.include, include) && sameSet(cached.external, external) && cached.versionDigest === versionDigest) return cached.imports;
1563
+ if (sameSet(cached.include, include) && sameSet(cached.external, external) && cached.versionDigest === versionDigest && typeof cached.sharedDeps === "string") return {
1564
+ imports: cached.imports,
1565
+ versions: cached.versions ?? {},
1566
+ sharedDeps: cached.sharedDeps
1567
+ };
283
1568
  } catch {}
284
1569
  return null;
285
1570
  }
286
- function resolveVersionDigest(dirname, specs) {
287
- const seen = /* @__PURE__ */ new Map();
1571
+ const NON_RUNTIME_FILE = /\.(map|d\.[cm]?ts|tsbuildinfo)$/;
1572
+ function linkedBuildStamp(pkgRoot) {
1573
+ if (pkgRoot.split(/[\\/]/).includes("node_modules")) return "";
1574
+ let newest = 0;
1575
+ try {
1576
+ const entries = readdirSync(join(pkgRoot, "dist"), {
1577
+ recursive: true,
1578
+ withFileTypes: true
1579
+ });
1580
+ for (const entry of entries) {
1581
+ if (!entry.isFile() || NON_RUNTIME_FILE.test(entry.name)) continue;
1582
+ const { mtimeMs } = statSync(join(entry.parentPath, entry.name));
1583
+ if (mtimeMs > newest) newest = mtimeMs;
1584
+ }
1585
+ } catch {
1586
+ return "";
1587
+ }
1588
+ return newest ? `+dist.${Math.trunc(newest)}` : "";
1589
+ }
1590
+ function cachedStamp(stamps, pkgRoot) {
1591
+ let stamp = stamps.get(pkgRoot);
1592
+ if (stamp === void 0) {
1593
+ stamp = linkedBuildStamp(pkgRoot);
1594
+ stamps.set(pkgRoot, stamp);
1595
+ }
1596
+ return stamp;
1597
+ }
1598
+ /**
1599
+ * Resolve the installed version of each spec's owning package, deduped by
1600
+ * package name. Resolution order per spec:
1601
+ * 1. the project itself, when it IS the owning package (a self-vendoring
1602
+ * app has no node_modules self-link);
1603
+ * 2. the project's own node_modules link (works for pnpm-strict and
1604
+ * hoisted layouts alike, and — unlike `require.resolve` — for
1605
+ * ESM-only packages whose exports map has no CJS condition);
1606
+ * 3. Node's own module resolution (covers transitive installs), walking
1607
+ * the entry up to the owning package's package.json.
1608
+ * Unresolvable specs contribute a "missing" sentinel, unknown versions
1609
+ * "unknown".
1610
+ */
1611
+ function resolveDepVersions(dirname$3, specs, stamps = /* @__PURE__ */ new Map()) {
1612
+ const req = createRequire(join(dirname$3, "noop.js"));
1613
+ const seen = {};
1614
+ let selfMeta = null;
288
1615
  for (const spec of specs) {
289
1616
  const { pkg } = parsePkg(spec);
290
- if (seen.has(pkg)) continue;
291
- let version = "missing";
292
- try {
293
- const pkgRoot = realpathSync(join(dirname, "node_modules", pkg));
294
- const meta = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8"));
295
- version = String(meta.version ?? "unknown");
296
- } catch {}
297
- seen.set(pkg, version);
1617
+ if (pkg in seen) continue;
1618
+ if (selfMeta === null) try {
1619
+ selfMeta = JSON.parse(readFileSync(join(dirname$3, "package.json"), "utf8"));
1620
+ } catch {
1621
+ selfMeta = {};
1622
+ }
1623
+ let version;
1624
+ if (typeof selfMeta.name === "string" && selfMeta.name === pkg && typeof selfMeta.version === "string") version = selfMeta.version;
1625
+ else {
1626
+ version = "missing";
1627
+ try {
1628
+ const pkgRoot = realpathSync(join(dirname$3, "node_modules", pkg));
1629
+ const meta = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8"));
1630
+ version = String(meta.version ?? "unknown") + cachedStamp(stamps, pkgRoot);
1631
+ } catch {
1632
+ try {
1633
+ const entry = req.resolve(spec);
1634
+ let dir = dirname(entry);
1635
+ for (let depth = 0; depth < 8; depth++) {
1636
+ if (existsSync(join(dir, "package.json"))) {
1637
+ const meta = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
1638
+ version = String(meta.version ?? "unknown");
1639
+ break;
1640
+ }
1641
+ const parent = dirname(dir);
1642
+ if (parent === dir) break;
1643
+ dir = parent;
1644
+ }
1645
+ } catch {}
1646
+ }
1647
+ }
1648
+ seen[pkg] = version;
298
1649
  }
1650
+ return seen;
1651
+ }
1652
+ function resolveVersionDigest(versions, own, stamps, build) {
299
1653
  const h = createHash("sha256");
1654
+ h.update(`base:${build.base}\nnodeEnv:${build.nodeEnv}\n`);
300
1655
  const workerHash = createHash("sha256").update(VENDOR_BUILD_WORKER).digest("hex");
301
1656
  h.update(`worker:${workerHash}\n`);
302
- for (const pkg of [...seen.keys()].sort()) h.update(`${pkg}@${seen.get(pkg)}\n`);
1657
+ for (const pkg of Object.keys(versions).sort()) h.update(`${pkg}@${versions[pkg]}\n`);
1658
+ for (const spec of Object.keys(own).sort()) {
1659
+ const stamp = cachedStamp(stamps, ownPackageRoot(own[spec]));
1660
+ h.update(`own:${spec}=${own[spec]}${stamp}\n`);
1661
+ }
303
1662
  return h.digest("hex").slice(0, 16);
304
1663
  }
305
1664
  function sameSet(a, b) {
@@ -307,7 +1666,7 @@ function sameSet(a, b) {
307
1666
  const s = new Set(a);
308
1667
  return b.every((x) => s.has(x));
309
1668
  }
310
- const LOCK_STALE_MS = 5 * 6e4;
1669
+ const LOCK_STALE_MS = 3e5;
311
1670
  const LOCK_HEARTBEAT_MS = 6e4;
312
1671
  const ownerFile = (lockDir) => join(lockDir, "owner");
313
1672
  function lockIsStale(lockDir) {
@@ -384,6 +1743,62 @@ function importTarget$1(value) {
384
1743
  }
385
1744
  return null;
386
1745
  }
1746
+ /** The package root at or above `from` that Node would load `pkg` from, or null. */
1747
+ function findPackageRoot(from, pkg) {
1748
+ let dir = from;
1749
+ for (;;) {
1750
+ const candidate = join(dir, "node_modules", pkg);
1751
+ if (existsSync(join(candidate, "package.json"))) return realpathSync(candidate);
1752
+ const parent = dirname(dir);
1753
+ if (parent === dir) return null;
1754
+ dir = parent;
1755
+ }
1756
+ }
1757
+ function ownRoots(own) {
1758
+ const roots = /* @__PURE__ */ new Set();
1759
+ for (const file of Object.values(own)) {
1760
+ const root = ownPackageRoot(file);
1761
+ try {
1762
+ const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
1763
+ if (Object.keys(meta.dependencies ?? {}).length === 0) roots.add(root + sep);
1764
+ } catch {}
1765
+ }
1766
+ return [...roots];
1767
+ }
1768
+ function ownPackageRoot(file) {
1769
+ let dir = dirname(file);
1770
+ for (;;) {
1771
+ try {
1772
+ if (JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).name) return dir;
1773
+ } catch {}
1774
+ const parent = dirname(dir);
1775
+ if (parent === dir) return dir;
1776
+ dir = parent;
1777
+ }
1778
+ }
1779
+ /** Each spec's browser/import entry file when resolved from `from`; unresolvable specs are left out. */
1780
+ function resolveOwnDeps(from, specs) {
1781
+ const out = {};
1782
+ for (const spec of specs) {
1783
+ const { pkg, sub } = parsePkg(spec);
1784
+ const root = findPackageRoot(from, pkg);
1785
+ if (!root) continue;
1786
+ try {
1787
+ const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
1788
+ const key = sub ? `./${sub}` : ".";
1789
+ let target = null;
1790
+ if (meta.exports && typeof meta.exports === "object") {
1791
+ const exp = meta.exports;
1792
+ target = Object.keys(exp).some((k) => k.startsWith(".")) ? key in exp ? importTarget$1(exp[key]) : null : sub ? null : importTarget$1(exp);
1793
+ } else if (typeof meta.exports === "string") target = sub ? null : meta.exports;
1794
+ else if (!sub) target = meta.module ?? meta.main ?? null;
1795
+ if (!target || /\.(css|json|scss)$/.test(target)) continue;
1796
+ const file = join(root, target);
1797
+ if (existsSync(file)) out[spec] = realpathSync(file);
1798
+ } catch {}
1799
+ }
1800
+ return out;
1801
+ }
387
1802
  function parsePkg(spec) {
388
1803
  if (spec.startsWith("@")) {
389
1804
  const parts = spec.split("/");
@@ -406,11 +1821,16 @@ function parsePkg(spec) {
406
1821
  * `@powerhousedao/design-system/connect/toast`, `zod/v4/core`). Those bare
407
1822
  * imports need their own import-map entry, so expand each listed spec to its
408
1823
  * package's concrete (non-wildcard, JS) subpath exports that share the spec's
409
- * prefix. Unresolvable / CSS / JSON targets are skipped. Failures leave the
410
- * original spec untouched.
1824
+ * prefix. Unresolvable / CSS / JSON targets are skipped.
1825
+ *
1826
+ * A spec whose package isn't installed in `dirname` is dropped entirely
1827
+ * rather than kept for the worker: the worker cannot build an entry for a
1828
+ * missing package (its `await import` and the vite resolution both fail),
1829
+ * and a bare re-export entry would fail the whole vendor build. The
1830
+ * importer of a missing shared dep simply bundles its own copy.
411
1831
  */
412
1832
  function expandIncludeSubpaths(dirname, include) {
413
- const out = new Set(include);
1833
+ const out = /* @__PURE__ */ new Set();
414
1834
  for (const spec of include) {
415
1835
  const { pkg, sub } = parsePkg(spec);
416
1836
  let exp;
@@ -421,6 +1841,7 @@ function expandIncludeSubpaths(dirname, include) {
421
1841
  } catch {
422
1842
  continue;
423
1843
  }
1844
+ out.add(sub ? spec : pkg);
424
1845
  if (!exp || typeof exp !== "object") continue;
425
1846
  const expMap = exp;
426
1847
  const prefixKey = sub ? `./${sub}` : ".";
@@ -431,40 +1852,86 @@ function expandIncludeSubpaths(dirname, include) {
431
1852
  const target = importTarget$1(expMap[key]);
432
1853
  if (!target || /\.(css|json|scss)$/.test(target)) continue;
433
1854
  if (!existsSync(join(pkgRoot, target))) continue;
434
- out.add(key === "." ? pkg : pkg + key.slice(1));
1855
+ const expanded = key === "." ? pkg : pkg + key.slice(1);
1856
+ if (!VENDOR_SKIP_SUBPATHS.has(expanded)) out.add(expanded);
435
1857
  }
436
1858
  }
437
1859
  return [...out];
438
1860
  }
439
1861
  /**
1862
+ * The published specifiers whose entry file the vendor build never emitted.
1863
+ * URLs are base-less (`/__vendor__/x.js`) and resolve inside `vendorDir`.
1864
+ */
1865
+ function missingVendorEntries(vendorDir, imports) {
1866
+ const prefix = VENDOR_URL_PREFIX;
1867
+ return Object.entries(imports).filter(([, url]) => {
1868
+ const rel = url.startsWith(prefix) ? url.slice(12) : url;
1869
+ return !existsSync(join(vendorDir, rel));
1870
+ }).map(([spec, url]) => ({
1871
+ spec,
1872
+ url
1873
+ }));
1874
+ }
1875
+ /**
1876
+ * Rebase the vendor's base-less entry URLs (`/__vendor__/x.js`) onto the
1877
+ * deploy base, so a consumer that resolves them against the page origin lands
1878
+ * under that base rather than the server root. A dynamic-base build keeps its
1879
+ * placeholder, which the runtime substitutes.
1880
+ *
1881
+ * `base` is the app base from `prebuildConnectVendor` callers; a base that
1882
+ * already carries the vendor segment has it dropped first so it is never
1883
+ * doubled.
1884
+ */
1885
+ function withVendorBase(imports, base) {
1886
+ const segment = VENDOR_URL_PREFIX.replace(/^\/+/, "");
1887
+ const appBase = base.endsWith(segment) ? base.slice(0, base.length - segment.length) : base;
1888
+ return Object.fromEntries(Object.entries(imports).map(([spec, url]) => [spec, `${appBase}/${url}`.replace(/([^:])\/{2,}/g, "$1/").replace(/^\/{2,}/, "/")]));
1889
+ }
1890
+ /**
440
1891
  * Build the vendor into a unique temp dir, then atomically swap it into place,
441
1892
  * so a concurrent reader never sees a partial bundle or import-map.json. Runs
442
1893
  * the build in a throwaway subprocess (its peak memory is reclaimed on exit);
443
- * the parent augments the import map with the version digest and does the swap.
444
- * Returns the published import map, or null on failure.
1894
+ * the parent augments the import map with the version digest + the version
1895
+ * table, writes the runtime shared-deps module, and does the swap.
1896
+ * Returns the published import map + versions, or null on failure.
445
1897
  */
446
- async function buildVendorAtomic(dirname$2, vendorDir, include, external, versionDigest) {
1898
+ async function buildVendorAtomic(dirname$4, vendorDir, include, external, versionDigest, versions, base, nodeEnv, own = {}) {
447
1899
  const parent = dirname(vendorDir);
448
1900
  mkdirSync(parent, { recursive: true });
449
1901
  const tmpDir = mkdtempSync(join(parent, ".ph-vendor.tmp-"));
450
1902
  try {
451
- const { ok, stderr } = await runBuildWorker(dirname$2, tmpDir, include, external);
1903
+ const { ok, stderr } = await runBuildWorker(dirname$4, tmpDir, include, external, base, nodeEnv, own);
452
1904
  const tmpMap = join(tmpDir, "import-map.json");
453
1905
  if (!ok || !existsSync(tmpMap)) {
454
1906
  const detail = stderr.trim();
455
1907
  throw new Error(`vendor build failed${detail ? `:\n${detail}` : " (no output captured)"}`);
456
1908
  }
457
1909
  const meta = JSON.parse(readFileSync(tmpMap, "utf8"));
1910
+ const unbacked = missingVendorEntries(tmpDir, meta.imports);
1911
+ if (unbacked.length > 0) throw new Error(`vendor build published ${unbacked.length} import-map ${unbacked.length === 1 ? "entry" : "entries"} with no file behind ${unbacked.length === 1 ? "it" : "them"}:\n` + unbacked.map((e) => ` ${e.spec} -> ${e.url}`).join("\n"));
458
1912
  meta.versionDigest = versionDigest;
1913
+ meta.versions = versions;
1914
+ meta.base = base;
1915
+ meta.nodeEnv = nodeEnv;
1916
+ const sharedDepsSource = `export const imports = ${JSON.stringify(withVendorBase(meta.imports, base))};\nexport const versions = ${JSON.stringify(versions)};\n`;
1917
+ const sharedDepsFile = `shared-deps-${createHash("sha256").update(sharedDepsSource).digest("hex").slice(0, 12)}.js`;
1918
+ writeFileSync(join(tmpDir, sharedDepsFile), sharedDepsSource);
1919
+ writeFileSync(join(tmpDir, "shared-deps.js"), sharedDepsSource);
1920
+ meta.sharedDeps = VENDOR_URL_PREFIX + sharedDepsFile;
459
1921
  writeFileSync(tmpMap, JSON.stringify(meta, null, 2));
460
1922
  const oldDir = `${vendorDir}.old-${process.pid}-${Date.now()}`;
461
1923
  if (existsSync(vendorDir)) renameSync(vendorDir, oldDir);
462
1924
  renameSync(tmpDir, vendorDir);
1925
+ chmodSync(vendorDir, 493);
463
1926
  rmSync(oldDir, {
464
1927
  recursive: true,
465
1928
  force: true
466
1929
  });
467
- return meta.imports;
1930
+ return {
1931
+ imports: meta.imports,
1932
+ versions,
1933
+ sharedDeps: meta.sharedDeps
1934
+ };
468
1935
  } catch (err) {
469
1936
  rmSync(tmpDir, {
470
1937
  recursive: true,
@@ -473,16 +1940,29 @@ async function buildVendorAtomic(dirname$2, vendorDir, include, external, versio
473
1940
  throw err;
474
1941
  }
475
1942
  }
1943
+ function resolveSelfModulePath() {
1944
+ const selfPath = fileURLToPath(import.meta.url);
1945
+ if (!selfPath.endsWith(".ts")) return selfPath;
1946
+ let dir = dirname(selfPath);
1947
+ for (let depth = 0; depth < 4; depth++) {
1948
+ const candidate = join(dir, "dist", "index.mjs");
1949
+ if (existsSync(candidate)) return candidate;
1950
+ const parent = dirname(dir);
1951
+ if (parent === dir) break;
1952
+ dir = parent;
1953
+ }
1954
+ throw new Error("vendor build needs the built builder-tools bundle (dist/index.mjs); build the package first");
1955
+ }
476
1956
  /**
477
1957
  * Spawn a throwaway worker that generates one entry per specifier (CJS deps get
478
1958
  * explicit named re-exports, ESM deps `export *`), `vite build`s them into the
479
1959
  * given out dir, and writes the import map. Captures stdout/stderr so a failure
480
1960
  * is debuggable; the normal path stays quiet.
481
1961
  */
482
- function runBuildWorker(dirname, outDir, include, external) {
1962
+ function runBuildWorker(dirname, outDir, include, external, base, nodeEnv, own = {}) {
483
1963
  const workerPath = join(outDir, "build-worker.mjs");
484
1964
  writeFileSync(workerPath, VENDOR_BUILD_WORKER);
485
- const selfModulePath = fileURLToPath(import.meta.url);
1965
+ const selfModulePath = resolveSelfModulePath();
486
1966
  return new Promise((resolve) => {
487
1967
  const child = spawn(process.execPath, [
488
1968
  workerPath,
@@ -492,7 +1972,13 @@ function runBuildWorker(dirname, outDir, include, external) {
492
1972
  VENDOR_URL_PREFIX,
493
1973
  JSON.stringify(external),
494
1974
  VENDOR_DYNAMIC_BASE,
495
- selfModulePath
1975
+ selfModulePath,
1976
+ base,
1977
+ nodeEnv,
1978
+ JSON.stringify({
1979
+ files: own,
1980
+ roots: ownRoots(own)
1981
+ })
496
1982
  ], {
497
1983
  cwd: dirname,
498
1984
  stdio: [
@@ -522,14 +2008,27 @@ function runBuildWorker(dirname, outDir, include, external) {
522
2008
  * The vendor build worker, written to disk and run as a subprocess. Loads
523
2009
  * `vite` from the project and `connectDynamicBasePlugin` from builder-tools' own
524
2010
  * built bundle (selfModulePath). argv: dirname, vendorDir, includeJSON,
525
- * urlPrefix, externalJSON, dynamicBase, selfModulePath.
2011
+ * urlPrefix, externalJSON, dynamicBase, selfModulePath, base (app base),
2012
+ * nodeEnv.
526
2013
  */
527
2014
  const VENDOR_BUILD_WORKER = `
528
2015
  import { createRequire } from 'node:module';
529
2016
  import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
530
2017
  import { join, isAbsolute } from 'node:path';
531
2018
  import { fileURLToPath, pathToFileURL } from 'node:url';
532
- const [dirname, vendorDir, includeJSON, urlPrefix, externalJSON, dynamicBase, selfModulePath] = process.argv.slice(2);
2019
+ const [dirname, vendorDir, includeJSON, urlPrefix, externalJSON, dynamicBase, selfModulePath, baseArg, nodeEnvArg, ownJSON] = process.argv.slice(2);
2020
+ // ownDeps: spec -> absolute entry file, plus each one's package root.
2021
+ const { files: own = {}, roots: ownRootList = [] } = JSON.parse(ownJSON || '{}');
2022
+ // One chunk per own-dep package: split between an entry and a shared chunk, a
2023
+ // barrel can re-export from the entry and run before the classes it extends.
2024
+ const ownGroups = ownRootList.map((root, i) => ({ name: 'own-' + i, test: (id) => id.startsWith(root) }));
2025
+ // Trailing argv are optional (older callers): base defaults to the dynamic
2026
+ // placeholder behavior, nodeEnv to development. baseArg is the APP base —
2027
+ // the same string the app build uses; the build base appends the vendor
2028
+ // segment so emitted asset URLs land under <app-base>__vendor__/.
2029
+ const segment = urlPrefix.replace(/^\\/+/, '');
2030
+ const base = baseArg ? baseArg + segment : dynamicBase;
2031
+ const nodeEnv = nodeEnvArg ?? 'development';
533
2032
  const include = JSON.parse(includeJSON);
534
2033
  const external = JSON.parse(externalJSON ?? '[]');
535
2034
  const externalSet = new Set(external);
@@ -547,23 +2046,42 @@ const RESERVED = new Set('enum void null function in instanceof typeof new delet
547
2046
  const input = {};
548
2047
  for (const spec of include) {
549
2048
  const name = entryName(spec);
2049
+ const from = own[spec] ?? spec;
550
2050
  let src;
551
2051
  try {
552
2052
  // Import the bare spec (not reqProj.resolve(spec)) so Node picks the same
553
2053
  // import/browser-condition module the build resolves — resolving first can
554
2054
  // pick a CJS sibling whose default-export shape differs from the ESM build.
555
- const ns = await import(spec);
2055
+ const ns = await import(own[spec] ? pathToFileURL(own[spec]).href : spec);
556
2056
  // Only fall back to re-exporting from default when the module exposes NO
557
2057
  // top-level named exports (a true CJS-interop module). If it does (e.g. zod
558
2058
  // exposes \`z\`), \`export *\` captures them; destructuring default would miss
559
2059
  // top-level names that aren't keys of the default object.
560
2060
  const named = Object.keys(ns).filter((k) => k !== 'default');
561
2061
  const cjs = named.length === 0 && ns.default && typeof ns.default === 'object';
562
- if (cjs) {
2062
+ // A strict entry keeps every export, and zod's \`locales\` (also reachable via \`z\`) pins
2063
+ // ~50 locales; publish them without it. zod/locales stays its own entry.
2064
+ const zodNs = (spec === 'zod' || spec.startsWith('zod/')) && !spec.includes('locales') && named.includes('locales');
2065
+ if (zodNs) {
2066
+ const keep = named.filter((k) => k !== 'locales' && k !== 'z' && /^[A-Za-z_$][\\w$]*$/.test(k));
2067
+ // \`core\` is zod/v4/core's namespace, which exports locales too: rebuild it without them.
2068
+ const coreKeys = keep.includes('core') ? Object.keys(await import('zod/v4/core')).filter((k) => k !== 'locales' && k !== 'default') : [];
2069
+ const reexport = keep.filter((k) => !(k === 'core' && coreKeys.length));
2070
+ src = 'export { ' + reexport.join(', ') + ' } from ' + JSON.stringify(from) + ';\\n'
2071
+ + 'import { ' + reexport.map((k) => k + ' as __z_' + k).join(', ') + ' } from ' + JSON.stringify(from) + ';\\n';
2072
+ if (coreKeys.length) {
2073
+ src += 'import { ' + coreKeys.map((k) => k + ' as __c_' + k).join(', ') + ' } from "zod/v4/core";\\n'
2074
+ + 'const __z_core = Object.freeze({ ' + coreKeys.map((k) => JSON.stringify(k) + ': __c_' + k).join(', ') + ' });\\n'
2075
+ + 'export { __z_core as core };\\n';
2076
+ }
2077
+ src += 'const z = Object.freeze({ ' + keep.map((k) => JSON.stringify(k) + ': __z_' + k).join(', ') + ' });\\n'
2078
+ + (named.includes('z') ? 'export { z };\\n' : '')
2079
+ + (('default' in ns) && ns.default === ns.z ? 'export { z as default };\\n' : '');
2080
+ } else if (cjs) {
563
2081
  const names = Object.keys(ns.default).filter((k) => k !== 'default' && k !== '__esModule' && /^[A-Za-z_$][\\w$]*$/.test(k));
564
2082
  const plain = names.filter((n) => !RESERVED.has(n));
565
2083
  const reserved = names.filter((n) => RESERVED.has(n));
566
- src = 'import d from ' + JSON.stringify(spec) + ';\\nexport default d;\\n'
2084
+ src = 'import d from ' + JSON.stringify(from) + ';\\nexport default d;\\n'
567
2085
  + (plain.length ? 'export const { ' + plain.join(', ') + ' } = d;\\n' : '');
568
2086
  // reserved words are invalid as const-binding names but valid as export
569
2087
  // aliases (export { x as enum }).
@@ -571,11 +2089,11 @@ for (const spec of include) {
571
2089
  src += 'const __r' + i + ' = d[' + JSON.stringify(n) + '];\\nexport { __r' + i + ' as ' + n + ' };\\n';
572
2090
  });
573
2091
  } else {
574
- src = 'export * from ' + JSON.stringify(spec) + ';\\n'
575
- + (('default' in ns) ? 'export { default } from ' + JSON.stringify(spec) + ';\\n' : '');
2092
+ src = 'export * from ' + JSON.stringify(from) + ';\\n'
2093
+ + (('default' in ns) ? 'export { default } from ' + JSON.stringify(from) + ';\\n' : '');
576
2094
  }
577
2095
  } catch {
578
- src = 'export * from ' + JSON.stringify(spec) + ';\\n';
2096
+ src = 'export * from ' + JSON.stringify(from) + ';\\n';
579
2097
  }
580
2098
  const file = join(srcDir, name + '.js');
581
2099
  writeFileSync(file, src);
@@ -600,16 +2118,19 @@ const phVendorResolve = {
600
2118
  return resolved;
601
2119
  },
602
2120
  };
603
- await build({
2121
+ const result = await build({
604
2122
  root: dirname, configFile: false, logLevel: 'error',
605
- // Dynamic-base placeholder + vendor segment: connectDynamicBasePlugin rewrites
606
- // emitted chunk/asset URLs to resolve against the deploy base at serve time.
607
- base: dynamicBase,
2123
+ // Caller-provided build base (or the dynamic placeholder default):
2124
+ // connectDynamicBasePlugin rewrites emitted chunk/asset URLs to resolve
2125
+ // against the deploy base at serve time.
2126
+ base,
608
2127
  define: {
609
- 'process.env.NODE_ENV': '"development"',
2128
+ 'process.env.NODE_ENV': JSON.stringify(nodeEnv),
610
2129
  // BASE_URL resolves to the deploy base (not the vendor prefix) so vendored
611
2130
  // Connect's router basename + BASE_URL-relative fetches use the right path.
612
- 'import.meta.env.BASE_URL': JSON.stringify(DYNAMIC_BASE_PLACEHOLDER),
2131
+ // The app base when provided (concrete or placeholder), the placeholder
2132
+ // otherwise (dev flow — rewritten at serve time by the dynamic-base plugin).
2133
+ 'import.meta.env.BASE_URL': JSON.stringify(baseArg ?? DYNAMIC_BASE_PLACEHOLDER),
613
2134
  },
614
2135
  // phVendorResolve (pre) resolves bares from the worker; esmExternalRequirePlugin owns
615
2136
  // react/virtual externalization; connectDynamicBasePlugin (post) rewrites the placeholder base.
@@ -618,199 +2139,758 @@ await build({
618
2139
  // segment so the worker recovers the deploy base, not the vendor prefix.
619
2140
  worker: { format: 'es', plugins: () => [connectDynamicBasePlugin({ forWorker: true, workerStripPrefix: urlPrefix.replace(/^\\/+/, '') })] },
620
2141
  build: {
621
- outDir: vendorDir, emptyOutDir: false, minify: false, target: 'esnext', cssCodeSplit: true,
2142
+ // Production ships this to every visitor, so minify it like the app's own
2143
+ // chunks; dev keeps readable output and the faster build.
2144
+ outDir: vendorDir, emptyOutDir: false, minify: nodeEnv === 'production', target: 'esnext', cssCodeSplit: true,
622
2145
  rollupOptions: {
623
2146
  input, preserveEntrySignatures: 'strict',
624
- output: { format: 'es', entryFileNames: '[name].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },
2147
+ // Content-hashed entry names: each build's import map points at new URLs.
2148
+ output: { format: 'es', entryFileNames: '[name]-[hash].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]', ...(ownGroups.length ? { codeSplitting: { groups: ownGroups } } : {}) },
625
2149
  },
626
2150
  },
627
2151
  });
628
2152
  rmSync(srcDir, { recursive: true, force: true });
2153
+ const emitted = {};
2154
+ for (const out of Array.isArray(result) ? result : [result]) {
2155
+ for (const chunk of out?.output ?? []) {
2156
+ if (chunk.type === 'chunk' && chunk.isEntry) emitted[chunk.name] = chunk.fileName;
2157
+ }
2158
+ }
629
2159
  const imports = {};
630
- for (const spec of include) imports[spec] = urlPrefix + entryName(spec) + '.js';
2160
+ // An entry the build never emitted keeps its unhashed name; the caller reports it as missing.
2161
+ for (const spec of include) imports[spec] = urlPrefix + (emitted[entryName(spec)] ?? entryName(spec) + '.js');
631
2162
  writeFileSync(join(vendorDir, 'import-map.json'), JSON.stringify({ include, external, imports }, null, 2));
632
2163
  `;
633
2164
  //#endregion
634
- //#region connect-utils/helpers.ts
635
- const DEFAULT_CONNECT_OUTDIR = ".ph/connect-build/dist/";
636
- function resolveViteConfigPath(options) {
637
- const { projectRoot = cwd(), viteConfigFile } = options;
638
- return viteConfigFile || join(projectRoot, "vite.config.ts");
2165
+ //#region connect-utils/reactor-worker-build.ts
2166
+ /**
2167
+ * Prebuild Connect's reactor SharedWorker into a browser-loadable bundle.
2168
+ *
2169
+ * The published `@powerhousedao/connect` dist ships `reactor.worker.js` as a
2170
+ * library artifact: its dependencies are externalized onto bare specifiers
2171
+ * (`@powerhousedao/reactor`, `kysely`, ...). The page resolves those through
2172
+ * its `<script type="importmap">`, but import maps are a document feature —
2173
+ * a worker never inherits one and no Worker/SharedWorker constructor option
2174
+ * can supply one. A bare specifier inside a worker is unresolvable by the
2175
+ * platform, so the shipped file can never run as a worker script.
2176
+ *
2177
+ * This module builds the worker's module graph into a self-contained bundle
2178
+ * (one `vite build` in a throwaway subprocess, same pattern as the vendor
2179
+ * prebuild). Two modes:
2180
+ *
2181
+ * - With `vendorImports` (production builds that also ship the `__vendor__/`
2182
+ * bundle): specifiers present in the vendor import map are externalized and
2183
+ * rewritten to `../__vendor__/<entry>.js`. The worker bundle is served as a
2184
+ * sibling of `__vendor__/`, so those relative imports hit the exact URLs
2185
+ * the page's import map uses — one fetch and one HTTP-cache entry per
2186
+ * shared dep for the page and the worker together.
2187
+ * - Without (dev servers, `PH_CONNECT_VENDOR=0` builds): everything is
2188
+ * bundled; the worker is self-contained.
2189
+ *
2190
+ * The build uses Vite's relative base (`"./"`), so emitted chunk and asset
2191
+ * URLs resolve against the worker script's own URL. That sidesteps the
2192
+ * dynamic-base machinery entirely: the bundle works under any deploy base,
2193
+ * concrete or proxy-substituted, as long as it is served under
2194
+ * `<app-base>/__reactor_worker__/`.
2195
+ */
2196
+ /** URL prefix the worker bundle is served under, next to `__vendor__/`. */
2197
+ const REACTOR_WORKER_URL_PREFIX = "/__reactor_worker__/";
2198
+ /** Entry filename of the bundle; the tab constructs its SharedWorker from it. */
2199
+ const REACTOR_WORKER_ENTRY = "reactor.worker.js";
2200
+ /** Metadata file the cache check reads; lives inside the bundle dir. */
2201
+ const META_FILE = "worker-meta.json";
2202
+ /** Content-Type for the extensions the worker build emits; JS is the default. */
2203
+ const REACTOR_WORKER_MIME = {
2204
+ ".map": "application/json",
2205
+ ".json": "application/json",
2206
+ ".wasm": "application/wasm",
2207
+ ".data": "application/octet-stream"
2208
+ };
2209
+ /**
2210
+ * The installed Connect dist's worker entry, or null when the installed
2211
+ * version predates the worker (the feature is then unavailable, not broken).
2212
+ */
2213
+ function resolveReactorWorkerSource(dirname) {
2214
+ try {
2215
+ const candidate = join(realpathSync(join(dirname, "node_modules", "@powerhousedao/connect")), "dist", REACTOR_WORKER_ENTRY);
2216
+ return existsSync(candidate) ? candidate : null;
2217
+ } catch {
2218
+ return null;
2219
+ }
639
2220
  }
640
- function resolvePackage(packageName, root = process.cwd()) {
641
- return createRequire(root).resolve(packageName, { paths: [root] });
2221
+ /** `/__vendor__/<entry>.js` -> `../__vendor__/<entry>.js` (sibling dirs). */
2222
+ function vendorRelativePath(vendorUrl) {
2223
+ return `../__vendor__/${vendorUrl.slice(vendorUrl.lastIndexOf("/") + 1)}`;
642
2224
  }
643
- function resolveConnectPackageJson(root = process.cwd()) {
2225
+ const SPECIFIER_PATTERNS = [
2226
+ /(?<![.\w$])import\s*\(\s*["']([^"']+)["']/g,
2227
+ /(?<![.\w$])import\s*[^"'()]*?from\s*["']([^"']+)["']/g,
2228
+ /(?<![.\w$])export\s*[^"'()]*?from\s*["']([^"']+)["']/g,
2229
+ /(?<![.\w$])import\s*["']([^"']+)["']/g
2230
+ ];
2231
+ /**
2232
+ * Module specifiers a worker cannot resolve: anything that is not relative,
2233
+ * root-relative, or an http(s)/data/blob URL. Used as a post-build guard so a
2234
+ * leftover bare (or `node:`) import fails the build with a name instead of
2235
+ * shipping a worker that dies on its first import statement.
2236
+ *
2237
+ * Expects minified (comment-free) output: a raw-text scan cannot tell a real
2238
+ * import from a JSDoc code sample, and unminified kysely/viem are full of the
2239
+ * latter. The build below always minifies for exactly this reason.
2240
+ */
2241
+ function findDisallowedSpecifiers(code) {
2242
+ const found = /* @__PURE__ */ new Set();
2243
+ for (const pattern of SPECIFIER_PATTERNS) for (const match of code.matchAll(pattern)) {
2244
+ const spec = match[1];
2245
+ if (!spec.startsWith("./") && !spec.startsWith("../") && !spec.startsWith("/") && !/^(https?:|data:|blob:)/.test(spec)) found.add(spec);
2246
+ }
2247
+ return [...found].sort();
2248
+ }
2249
+ /**
2250
+ * Fallback list of packages whose BUILT dist shapes the worker bundle's output,
2251
+ * used only when the installed Connect's package.json cannot be read (see
2252
+ * {@link upstreamWorkerPackages}).
2253
+ */
2254
+ const FALLBACK_UPSTREAM_WORKER_PACKAGES = ["@powerhousedao/reactor", "@powerhousedao/reactor-browser"];
2255
+ /** Dependency scopes whose installed dist can change the bundle's output. */
2256
+ const UPSTREAM_SCOPES = ["@powerhousedao/", "@renown/"];
2257
+ /**
2258
+ * Packages whose BUILT dist shapes the worker bundle's output even when
2259
+ * connect's own dist/reactor.worker.js entry file did not change.
2260
+ *
2261
+ * That entry is a library artifact whose bare imports this build resolves
2262
+ * through node_modules at BUILD time, so a rebuilt dist anywhere in its
2263
+ * closure changes the bundle output without touching the entry file's own
2264
+ * size/mtime. The list is DERIVED from the installed Connect's own
2265
+ * dependencies rather than hardcoded: the bundle pulls `@renown/sdk`,
2266
+ * `@powerhousedao/powerhouse-vetra-packages` and `@powerhousedao/shared` out
2267
+ * of node_modules too, and a hardcoded pair left every one of those able to be
2268
+ * rebuilt behind a cache hit. Connect's dependency list is the cheap stand-in
2269
+ * for the resolved bundle graph: every workspace package the worker can reach
2270
+ * is reachable through it, and a package not in the bundle only costs a readdir.
2271
+ */
2272
+ function upstreamWorkerPackages(dirname) {
2273
+ const connectDir = resolveWorkspacePackageDir(dirname, "@powerhousedao/connect");
2274
+ if (!connectDir) return [...FALLBACK_UPSTREAM_WORKER_PACKAGES];
2275
+ let meta;
644
2276
  try {
645
- const connectPackageJsonPath = resolvePackage("@powerhousedao/connect/package.json", root);
646
- const fileContents = fs.readFileSync(connectPackageJsonPath, "utf-8");
647
- return JSON.parse(fileContents);
648
- } catch (error) {
649
- console.error(`Error reading Connect package.json:`, error);
2277
+ meta = JSON.parse(readFileSync(join(connectDir, "package.json"), "utf8"));
2278
+ } catch {
2279
+ return [...FALLBACK_UPSTREAM_WORKER_PACKAGES];
2280
+ }
2281
+ const names = Object.keys(meta.dependencies ?? {}).filter((name) => UPSTREAM_SCOPES.some((scope) => name.startsWith(scope)));
2282
+ for (const name of FALLBACK_UPSTREAM_WORKER_PACKAGES) if (!names.includes(name)) names.push(name);
2283
+ return names.sort();
2284
+ }
2285
+ /**
2286
+ * This module's own installed version, read by walking up from its file to
2287
+ * the nearest `package.json` named "@powerhousedao/builder-tools" (same
2288
+ * technique as `build-hash.ts`'s `readConnectVersion`: builder-tools'
2289
+ * `exports` map has no `./package.json` subpath, so node resolution can't
2290
+ * get there). Works whether this runs from source (tests, this monorepo) or
2291
+ * the built dist.
2292
+ */
2293
+ function resolveOwnPackageVersion() {
2294
+ try {
2295
+ let dir = dirname(fileURLToPath(import.meta.url));
2296
+ for (;;) {
2297
+ try {
2298
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
2299
+ if (pkg.name === "@powerhousedao/builder-tools") return pkg.version ?? "unknown";
2300
+ } catch {}
2301
+ const parent = dirname(dir);
2302
+ if (parent === dir) break;
2303
+ dir = parent;
2304
+ }
2305
+ } catch {}
2306
+ return "unknown";
2307
+ }
2308
+ /**
2309
+ * This package's own version, computed once. Folded into the worker bundle
2310
+ * cache key so a builder-tools release — which can change how the bundle is
2311
+ * built (anything in this module beyond {@link WORKER_BUILD_WORKER} itself,
2312
+ * e.g. `workerSafeVendorImports`, the resolve plugin) — invalidates bundles
2313
+ * a prior builder-tools version cached.
2314
+ */
2315
+ const BUILDER_TOOLS_VERSION = resolveOwnPackageVersion();
2316
+ /**
2317
+ * A workspace package's real directory, resolved the way Node's resolver
2318
+ * would (through `node_modules`), or null when it is not installed (e.g. a
2319
+ * non-monorepo consumer project — graceful, not an error). pnpm's
2320
+ * node_modules symlinks resolve to the real package directory, so this
2321
+ * reflects the monorepo's actual dist state, not a stale symlink target.
2322
+ */
2323
+ function resolveWorkspacePackageDir(dirname, pkgName) {
2324
+ try {
2325
+ return realpathSync(join(dirname, "node_modules", ...pkgName.split("/")));
2326
+ } catch {
650
2327
  return null;
651
2328
  }
652
2329
  }
653
2330
  /**
654
- * Finds the dist dir of Connect on the local machine
2331
+ * Cheap content fingerprint of a directory's immediate files: no file bytes
2332
+ * are read, just each entry's name/size/mtime, so it stays fast even for a
2333
+ * large dist. Sensitive to a rebuild in the common cases: Vite's
2334
+ * content-hashed chunk filenames change the name itself; a stable-named file
2335
+ * (an entry point) changes size or mtime. Bounded (`maxFiles`) so a
2336
+ * pathological directory cannot make this slow — deliberately not a
2337
+ * full-tree hash.
2338
+ *
2339
+ * The names are sorted BEFORE the bound is applied, so the subset the bound
2340
+ * keeps is the same subset on every run: readdir order is unspecified, and
2341
+ * truncating it first made the fingerprint of a directory past the bound a
2342
+ * function of whatever order the filesystem happened to report.
655
2343
  */
656
- function resolveConnectBundle(root = process.cwd()) {
657
- const connectIndexPath = resolvePackage("@powerhousedao/connect", root);
658
- return join(connectIndexPath.substring(0, connectIndexPath.indexOf("connect") + 7), "dist/");
2344
+ function distDirFingerprint(dir, maxFiles = 1e3) {
2345
+ try {
2346
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => e.name).sort().slice(0, maxFiles).map((name) => {
2347
+ const stat = statSync(join(dir, name));
2348
+ return `${name}:${stat.size}:${Math.round(stat.mtimeMs)}`;
2349
+ }).join("|");
2350
+ } catch {
2351
+ return "unreadable";
2352
+ }
659
2353
  }
660
- function resolveConnectPublicDir(root = process.cwd()) {
661
- const connectIconPath = resolvePackage("@powerhousedao/connect/public/icon.ico", root);
662
- return path.join(connectIconPath, "../");
2354
+ function computeSourceDigest(dirname, entryPath, vendorDir, builderToolsVersion = BUILDER_TOOLS_VERSION) {
2355
+ const h = createHash("sha256");
2356
+ h.update(`builder:${WORKER_BUILD_WORKER_HASH}\n`);
2357
+ h.update(`builder-tools:${builderToolsVersion}\n`);
2358
+ try {
2359
+ const pkgRoot = resolveWorkspacePackageDir(dirname, "@powerhousedao/connect");
2360
+ if (!pkgRoot) throw new Error("unresolved");
2361
+ const meta = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8"));
2362
+ h.update(`connect:${meta.version ?? "unknown"}\n`);
2363
+ } catch {
2364
+ h.update("connect:unresolved\n");
2365
+ }
2366
+ try {
2367
+ const stat = statSync(entryPath);
2368
+ h.update(`entry:${stat.size}:${Math.round(stat.mtimeMs)}\n`);
2369
+ } catch {
2370
+ h.update("entry:unstatable\n");
2371
+ }
2372
+ for (const pkg of upstreamWorkerPackages(dirname)) {
2373
+ const pkgDir = resolveWorkspacePackageDir(dirname, pkg);
2374
+ h.update(`${pkg}:${pkgDir ? distDirFingerprint(join(pkgDir, "dist")) : "unresolved"}\n`);
2375
+ }
2376
+ if (vendorDir) try {
2377
+ h.update(`vendor:${createHash("sha256").update(readFileSync(join(vendorDir, "import-map.json"))).digest("hex")}\n`);
2378
+ } catch {
2379
+ h.update("vendor:unreadable\n");
2380
+ }
2381
+ return h.digest("hex").slice(0, 16);
2382
+ }
2383
+ function vendorKeyOf(vendorImports) {
2384
+ const entries = Object.entries(vendorImports).sort(([a], [b]) => a.localeCompare(b));
2385
+ return createHash("sha256").update(JSON.stringify(entries)).digest("hex").slice(0, 16);
2386
+ }
2387
+ function readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv) {
2388
+ if (!existsSync(metaPath)) return false;
2389
+ try {
2390
+ const cached = JSON.parse(readFileSync(metaPath, "utf8"));
2391
+ return cached.sourceDigest === sourceDigest && cached.vendorKey === vendorKey && cached.nodeEnv === nodeEnv && existsSync(join(dirname(metaPath), "reactor.worker.js"));
2392
+ } catch {
2393
+ return false;
2394
+ }
2395
+ }
2396
+ /** Content digest of a directory tree (relative paths + bytes; source maps skipped). */
2397
+ function directoryContentDigest(dir) {
2398
+ const h = createHash("sha256");
2399
+ const files = readdirSync(dir, {
2400
+ recursive: true,
2401
+ withFileTypes: true
2402
+ }).filter((e) => e.isFile() && !e.name.endsWith(".map")).map((e) => join(e.parentPath, e.name)).sort();
2403
+ for (const file of files) {
2404
+ h.update(`${file.slice(dir.length).split("\\").join("/")}\n`);
2405
+ h.update(readFileSync(file));
2406
+ }
2407
+ return h.digest("hex").slice(0, 16);
2408
+ }
2409
+ async function waitForWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv, lockDir) {
2410
+ const deadline = Date.now() + LOCK_STALE_MS;
2411
+ while (Date.now() < deadline) {
2412
+ if (readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv)) return true;
2413
+ if (!existsSync(lockDir)) return readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv);
2414
+ await new Promise((r) => setTimeout(r, 250));
2415
+ }
2416
+ return false;
663
2417
  }
664
2418
  /**
665
- * Copies the Connect dist dir to the target path
2419
+ * Build the worker bundle (once, in a throwaway subprocess) into `outDir`.
2420
+ * Idempotent: reuses a cached bundle built from the same connect dist, vendor
2421
+ * mapping, and builder logic. Returns null on failure (`errorRef` carries the
2422
+ * cause) or when the installed Connect has no worker entry.
666
2423
  */
667
- function copyConnect(sourcePath, targetPath) {
2424
+ async function prebuildReactorWorker(options) {
2425
+ const entryPath = options.entryPath ?? resolveReactorWorkerSource(options.dirname);
2426
+ if (!entryPath) {
2427
+ if (options.errorRef) options.errorRef.message = "the installed @powerhousedao/connect ships no dist/reactor.worker.js";
2428
+ return null;
2429
+ }
2430
+ const vendorImports = options.vendor ? workerSafeVendorImports(options.vendor.dir, options.vendor.imports) : {};
2431
+ const nodeEnv = options.nodeEnv ?? "development";
2432
+ const outDir = options.outDir;
2433
+ const metaPath = join(outDir, META_FILE);
2434
+ const sourceDigest = computeSourceDigest(options.dirname, entryPath, options.vendor?.dir);
2435
+ const vendorKey = vendorKeyOf(vendorImports);
2436
+ const result = {
2437
+ outDir,
2438
+ entry: REACTOR_WORKER_ENTRY,
2439
+ sourceDigest,
2440
+ vendorImports
2441
+ };
668
2442
  try {
669
- fs.rmSync(targetPath, {
2443
+ if (readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv)) return result;
2444
+ const lockDir = `${outDir}.lock`;
2445
+ const lock = acquireLock(lockDir);
2446
+ if (!lock) return await waitForWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv, lockDir) ? result : null;
2447
+ try {
2448
+ if (readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv)) return result;
2449
+ await buildWorkerAtomic(options.dirname, outDir, entryPath, vendorImports, nodeEnv, {
2450
+ sourceDigest,
2451
+ vendorKey,
2452
+ nodeEnv
2453
+ });
2454
+ return result;
2455
+ } finally {
2456
+ releaseLock(lock);
2457
+ }
2458
+ } catch (err) {
2459
+ if (options.errorRef) options.errorRef.message = err instanceof Error ? err.message : String(err);
2460
+ return null;
2461
+ }
2462
+ }
2463
+ async function buildWorkerAtomic(dirname$2, outDir, entryPath, vendorImports, nodeEnv, meta) {
2464
+ const parent = dirname(outDir);
2465
+ mkdirSync(parent, { recursive: true });
2466
+ const tmpDir = mkdtempSync(join(parent, ".ph-reactor-worker.tmp-"));
2467
+ try {
2468
+ const { ok, stderr } = await runWorkerBuild(dirname$2, tmpDir, { "reactor.worker": entryPath }, vendorImports, nodeEnv);
2469
+ if (!ok || !existsSync(join(tmpDir, "reactor.worker.js"))) {
2470
+ const detail = stderr.trim();
2471
+ throw new Error(`reactor worker build failed${detail ? `:\n${detail}` : " (no output captured)"}`);
2472
+ }
2473
+ assertWorkerResolvable(tmpDir);
2474
+ writeFileSync(join(tmpDir, META_FILE), JSON.stringify(meta, null, 2));
2475
+ publishDirAtomic(tmpDir, outDir);
2476
+ } catch (err) {
2477
+ rmSync(tmpDir, {
670
2478
  recursive: true,
671
2479
  force: true
672
2480
  });
673
- fs.cpSync(sourcePath, targetPath, { recursive: true });
674
- } catch (error) {
675
- console.error(`❌ Error copying ${sourcePath} to ${targetPath}:`, error);
2481
+ throw err;
2482
+ }
2483
+ }
2484
+ /** Replace `outDir` with the finished `tmpDir`, old contents removed last. */
2485
+ function publishDirAtomic(tmpDir, outDir) {
2486
+ const oldDir = `${outDir}.old-${process.pid}-${Date.now()}`;
2487
+ if (existsSync(outDir)) renameSync(outDir, oldDir);
2488
+ renameSync(tmpDir, outDir);
2489
+ chmodSync(outDir, 493);
2490
+ rmSync(oldDir, {
2491
+ recursive: true,
2492
+ force: true
2493
+ });
2494
+ }
2495
+ const RELATIVE_SPECIFIER_PATTERNS = SPECIFIER_PATTERNS;
2496
+ function findRelativeSpecifiers(code) {
2497
+ const found = /* @__PURE__ */ new Set();
2498
+ for (const pattern of RELATIVE_SPECIFIER_PATTERNS) for (const match of code.matchAll(pattern)) {
2499
+ const spec = match[1];
2500
+ if (spec.startsWith("./") || spec.startsWith("../")) found.add(spec);
2501
+ }
2502
+ return [...found];
2503
+ }
2504
+ function normalizeBundlePath(fromFile, spec) {
2505
+ const segments = fromFile.split("/").slice(0, -1);
2506
+ for (const part of spec.split("/")) {
2507
+ if (part === "" || part === ".") continue;
2508
+ if (part === "..") {
2509
+ if (segments.length === 0) return "";
2510
+ segments.pop();
2511
+ continue;
2512
+ }
2513
+ segments.push(part);
2514
+ }
2515
+ return segments.join("/");
2516
+ }
2517
+ /**
2518
+ * Scan the emitted JS files REACHABLE from the entry via import statements
2519
+ * for specifiers a worker cannot resolve. Vendor externals were rewritten to
2520
+ * ../__vendor__/ relative paths, so anything bare that survives in the graph
2521
+ * is a real defect.
2522
+ *
2523
+ * Deliberately a graph walk, not a directory walk: the bundled reactor code
2524
+ * carries `new URL(..., import.meta.url)` references to its node
2525
+ * worker-thread entries (executor/projection workers), which Vite emits as
2526
+ * stray assets full of node-only imports. They are unreachable dead weight in
2527
+ * a browser bundle — the production vendor output tolerates the same files —
2528
+ * and must not fail the build.
2529
+ */
2530
+ function findBundleSpecifierOffenders(bundleDir, entry = REACTOR_WORKER_ENTRY) {
2531
+ const offenders = [];
2532
+ walkBundleGraph(bundleDir, entry, (file, code) => {
2533
+ const specs = findDisallowedSpecifiers(code);
2534
+ if (specs.length > 0) offenders.push({
2535
+ file,
2536
+ specs
2537
+ });
2538
+ return true;
2539
+ });
2540
+ return offenders;
2541
+ }
2542
+ function walkBundleGraph(bundleDir, entry, visit) {
2543
+ const seen = /* @__PURE__ */ new Set();
2544
+ const queue = [entry];
2545
+ while (queue.length > 0) {
2546
+ const rel = queue.shift();
2547
+ if (seen.has(rel)) continue;
2548
+ seen.add(rel);
2549
+ const full = join(bundleDir, rel);
2550
+ if (!existsSync(full) || statSync(full).isDirectory()) continue;
2551
+ if (!rel.endsWith(".js") && !rel.endsWith(".mjs")) continue;
2552
+ const code = readFileSync(full, "utf8");
2553
+ if (!visit(rel, code)) return false;
2554
+ for (const spec of findRelativeSpecifiers(code)) {
2555
+ const next = normalizeBundlePath(rel, spec);
2556
+ if (next) queue.push(next);
2557
+ }
2558
+ }
2559
+ return true;
2560
+ }
2561
+ function assertWorkerResolvable(bundleDir) {
2562
+ const offenders = findBundleSpecifierOffenders(bundleDir);
2563
+ if (offenders.length > 0) throw new Error("reactor worker bundle contains module specifiers a worker cannot resolve:\n" + offenders.map((o) => ` ${o.file}: ${o.specs.join(", ")}`).join("\n"));
2564
+ }
2565
+ const WORKER_UNSAFE_MARKERS = ["__PH_DYNAMIC_BASE__", "vite:preloadError"];
2566
+ /** The page-only markers present in `code`, in a fixed order. */
2567
+ function findWorkerUnsafeMarkers(code) {
2568
+ return WORKER_UNSAFE_MARKERS.filter((marker) => code.includes(marker));
2569
+ }
2570
+ /**
2571
+ * The subset of the vendor's entries a worker may import.
2572
+ *
2573
+ * The vendor build keeps the React family external: its chunks carry bare
2574
+ * `import "react"` statements that the PAGE resolves through its import map.
2575
+ * A worker resolves no import map, so externalizing a vendor spec whose chunk
2576
+ * closure reaches such an import would kill the worker on its first load —
2577
+ * and the chunk graph is shared across vendor entries, so even a React-free
2578
+ * module (e.g. an rpc subpath) can be entangled with React through a shared
2579
+ * chunk. The vendor is also built for the page: a dynamic-base build rewrites
2580
+ * its asset URLs onto a global only the page sets, and its dynamic imports go
2581
+ * through Vite's preload helper, which needs `document`. Each entry's own
2582
+ * closure inside the vendor dir decides: clean closure, worker-safe; anything
2583
+ * bare or page-only in it (see {@link findWorkerUnsafeMarkers}), or a missing
2584
+ * entry file, bundled into the worker instead.
2585
+ */
2586
+ function workerSafeVendorImports(vendorDir, vendorImports) {
2587
+ const safe = {};
2588
+ for (const [spec, url] of Object.entries(vendorImports)) {
2589
+ const entryFile = url.slice(url.lastIndexOf("/") + 1);
2590
+ if (!existsSync(join(vendorDir, entryFile))) continue;
2591
+ if (walkBundleGraph(vendorDir, entryFile, (_file, code) => findDisallowedSpecifiers(code).length === 0 && findWorkerUnsafeMarkers(code).length === 0)) safe[spec] = url;
2592
+ }
2593
+ return safe;
2594
+ }
2595
+ /**
2596
+ * Builds arbitrary worker-loadable entries with the worker build config.
2597
+ * Exported for the local-package bundles, which need the same self-contained
2598
+ * output and vendor externalization at a different depth.
2599
+ */
2600
+ function runWorkerBuildEntries(dirname, outDir, entries, vendorImports, nodeEnv, vendorPrefix = "../__vendor__/") {
2601
+ return runWorkerBuild(dirname, outDir, entries, vendorImports, nodeEnv, vendorPrefix);
2602
+ }
2603
+ function runWorkerBuild(dirname, outDir, entries, vendorImports, nodeEnv, vendorPrefix = "../__vendor__/") {
2604
+ const workerPath = join(outDir, "build-worker.mjs");
2605
+ writeFileSync(workerPath, WORKER_BUILD_WORKER);
2606
+ return new Promise((resolve) => {
2607
+ const child = spawn(process.execPath, [
2608
+ workerPath,
2609
+ dirname,
2610
+ outDir,
2611
+ JSON.stringify(entries),
2612
+ JSON.stringify(vendorImports),
2613
+ nodeEnv,
2614
+ resolveBuilderVite() ?? "",
2615
+ vendorPrefix
2616
+ ], {
2617
+ cwd: dirname,
2618
+ stdio: [
2619
+ "ignore",
2620
+ "pipe",
2621
+ "pipe"
2622
+ ]
2623
+ });
2624
+ let stderr = "";
2625
+ child.stdout.on("data", (d) => {
2626
+ stderr += String(d);
2627
+ });
2628
+ child.stderr.on("data", (d) => {
2629
+ stderr += String(d);
2630
+ });
2631
+ child.on("exit", (code) => {
2632
+ rmSync(workerPath, { force: true });
2633
+ resolve({
2634
+ ok: code === 0,
2635
+ stderr
2636
+ });
2637
+ });
2638
+ child.on("error", (e) => resolve({
2639
+ ok: false,
2640
+ stderr: String(e)
2641
+ }));
2642
+ });
2643
+ }
2644
+ /**
2645
+ * The vite installed next to this module. The subprocess must run the vite
2646
+ * this build config was written against: a consumer project can pin an older
2647
+ * vite/rolldown (overrides) whose bundler leaves unresolvable specifiers bare
2648
+ * instead of erroring and shims node builtins differently — the output guard
2649
+ * then correctly rejects the bundle. builder-tools declares vite as a direct
2650
+ * dependency, so this resolution works wherever builder-tools is installed.
2651
+ */
2652
+ function resolveBuilderVite() {
2653
+ try {
2654
+ return createRequire(import.meta.url).resolve("vite");
2655
+ } catch {
2656
+ return null;
676
2657
  }
677
2658
  }
678
2659
  /**
679
- * Backs up the index.html file
2660
+ * The build subprocess (same pattern as the vendor's). Loads builder-tools'
2661
+ * own vite (argv; project fallback) and builds the given entries with
2662
+ * relative base, so chunk/asset URLs resolve against each script's own URL
2663
+ * under any deploy base. argv: dirname, outDir, entriesJSON (name ->
2664
+ * absolute entry path), vendorImportsJSON, nodeEnv, vitePath, vendorPrefix
2665
+ * (relative path from the out dir to __vendor__/, e.g. "../__vendor__/").
2666
+ */
2667
+ const WORKER_BUILD_WORKER = `
2668
+ import { createRequire } from 'node:module';
2669
+ import { isAbsolute } from 'node:path';
2670
+ import { fileURLToPath, pathToFileURL } from 'node:url';
2671
+ const [dirname, outDir, entriesJSON, vendorImportsJSON, nodeEnvArg, vitePathArg, vendorPrefixArg] = process.argv.slice(2);
2672
+ const nodeEnv = nodeEnvArg ?? 'development';
2673
+ const entries = JSON.parse(entriesJSON);
2674
+ const vendorImports = JSON.parse(vendorImportsJSON ?? '{}');
2675
+ const vendorPrefix = vendorPrefixArg || '../__vendor__/';
2676
+ const externalSet = new Set(Object.keys(vendorImports));
2677
+ const vendorPath = (spec) => {
2678
+ const url = vendorImports[spec];
2679
+ return vendorPrefix + url.slice(url.lastIndexOf('/') + 1);
2680
+ };
2681
+ const reqProj = createRequire(dirname + '/noop.js');
2682
+ // pathToFileURL: on Windows import('D:\\\\...') parses "D:" as a URL scheme.
2683
+ const vitePath = vitePathArg || reqProj.resolve('vite');
2684
+ const { build } = await import(pathToFileURL(vitePath).href);
2685
+ // Resolve bare specifiers from the project (same plugin as the vendor build):
2686
+ // prefer the bundler's browser-condition-aware resolution, fall back to the
2687
+ // worker's own resolution for Rolldown's realpath-anchoring bug.
2688
+ const phResolveCache = new Map();
2689
+ const phWorkerResolve = {
2690
+ name: 'ph-reactor-worker-resolve', enforce: 'pre',
2691
+ async resolveId(source, importer, options) {
2692
+ if (externalSet.has(source)) return null;
2693
+ if (source[0] === '\\0' || source[0] === '.' || isAbsolute(source)) return null;
2694
+ if (source.startsWith('node:') || source.startsWith('data:')) return null;
2695
+ let viaBundler = null;
2696
+ try { viaBundler = await this.resolve(source, importer, { ...options, skipSelf: true }); } catch {}
2697
+ if (viaBundler) return viaBundler;
2698
+ if (phResolveCache.has(source)) return phResolveCache.get(source);
2699
+ let resolved = null;
2700
+ try { resolved = fileURLToPath(import.meta.resolve(source)); } catch {}
2701
+ phResolveCache.set(source, resolved);
2702
+ return resolved;
2703
+ },
2704
+ };
2705
+ // A worker has no window: on a failed dynamic import, the preload helper's
2706
+ // window.dispatchEvent would throw a ReferenceError in place of the real error.
2707
+ const PRELOAD_HELPER_ID = '\\0vite/preload-helper.js';
2708
+ const PRELOAD_DISPATCH = 'window.dispatchEvent(';
2709
+ const phWorkerPreloadHelper = {
2710
+ name: 'ph-reactor-worker-preload-helper',
2711
+ transform(code, id) {
2712
+ if (id !== PRELOAD_HELPER_ID) return null;
2713
+ if (code.split(PRELOAD_DISPATCH).length !== 2) {
2714
+ this.error('expected exactly one ' + PRELOAD_DISPATCH + ' in ' + PRELOAD_HELPER_ID);
2715
+ }
2716
+ return { code: code.replace(PRELOAD_DISPATCH, 'globalThis.dispatchEvent?.('), map: null };
2717
+ },
2718
+ };
2719
+ await build({
2720
+ root: dirname, configFile: false, logLevel: 'error',
2721
+ // The project's public/ dir belongs to the app build, not this bundle.
2722
+ publicDir: false,
2723
+ // Relative base: emitted chunk/asset URLs resolve against the worker
2724
+ // script's own URL, so the bundle works under any deploy base.
2725
+ base: './',
2726
+ define: {
2727
+ 'process.env.NODE_ENV': JSON.stringify(nodeEnv),
2728
+ 'import.meta.env.BASE_URL': JSON.stringify('./'),
2729
+ },
2730
+ plugins: [phWorkerResolve, phWorkerPreloadHelper],
2731
+ // pglite ships nested web workers as ES-module chunks.
2732
+ worker: { format: 'es' },
2733
+ build: {
2734
+ // Always minified, dev included: the bundle is browser-served output
2735
+ // (sourcemaps carry the debugging story), and minification strips the
2736
+ // JSDoc comments whose embedded code samples (kysely's, viem's) would
2737
+ // otherwise trip the bare-specifier guard below.
2738
+ outDir, emptyOutDir: false, minify: true, target: 'esnext', sourcemap: true,
2739
+ // No document in a worker: the module-preload polyfill and preload helper
2740
+ // touch the DOM, so dynamic imports must stay plain import().
2741
+ modulePreload: false,
2742
+ rollupOptions: {
2743
+ input: entries,
2744
+ // A models entry is pure re-exports; without this the bundler treats
2745
+ // its exports as unused and tree-shakes the whole file to nothing.
2746
+ // Harmless for the worker entry, which exports nothing to preserve.
2747
+ preserveEntrySignatures: 'strict',
2748
+ external: (id) => externalSet.has(id),
2749
+ output: {
2750
+ format: 'es', entryFileNames: '[name].js',
2751
+ // Chunks live at the bundle root, not a chunks/ subdir: the vendor
2752
+ // paths below are emitted VERBATIM into every chunk, so all modules
2753
+ // must sit at the same depth for ../__vendor__/ to resolve.
2754
+ chunkFileNames: '[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]',
2755
+ paths: (id) => (externalSet.has(id) ? vendorPath(id) : id),
2756
+ },
2757
+ },
2758
+ },
2759
+ });
2760
+ `;
2761
+ const WORKER_BUILD_WORKER_HASH = createHash("sha256").update(WORKER_BUILD_WORKER).digest("hex").slice(0, 16);
2762
+ //#endregion
2763
+ //#region connect-utils/worker-packages-build.ts
2764
+ /**
2765
+ * Prebuild a project's local packages into worker-loadable model bundles.
680
2766
  *
681
- * Needed when running the Connect Studio dev server on Windows
2767
+ * The reactor worker gets document models from the registry CDN or from what
2768
+ * Connect statically bundled. A project's own (`provider: "local"`) package is
2769
+ * in neither, so its document types have no reducer in the worker and their
2770
+ * load jobs fail. Dev solves this by pointing the worker at the dev server's
2771
+ * transformed models entry; a production deployment has no dev server, so the
2772
+ * entry is prebuilt here, next to the worker bundle it is loaded beside.
2773
+ *
2774
+ * Each package's `browser/document-models/index.js` (reducers only: no React,
2775
+ * no CSS, no editors) is built self-contained, with the worker-safe subset of
2776
+ * the vendor externalized onto `../../__vendor__/` - two levels up, since
2777
+ * these land in `__reactor_worker__/packages/`. A `manifest.json` names what
2778
+ * was built so the tab can turn it into package sources without guessing.
682
2779
  */
683
- function backupIndexHtml(appPath, restore = false) {
684
- const filePath = join(appPath, "index.html");
685
- const backupPath = join(appPath, "index.html.bak");
686
- const paths = restore ? [backupPath, filePath] : [filePath, backupPath];
687
- if (fs.existsSync(paths[0])) fs.copyFileSync(paths[0], paths[1]);
688
- }
689
- function removeBase64EnvValues(appPath) {
690
- backupIndexHtml(appPath);
691
- const filePath = join(appPath, "index.html");
692
- fs.readFile(filePath, "utf-8", (err, data) => {
693
- if (err) {
694
- console.error("Error reading file:", err);
695
- return;
696
- }
697
- const modifiedData = data.replace(/"LOCAL_DOCUMENT_MODELS":\s*".*?",/, `"LOCAL_DOCUMENT_MODELS": "",`).replace(/"LOCAL_DOCUMENT_EDITORS":\s*".*?"/, `"LOCAL_DOCUMENT_EDITORS": ""`);
698
- console.log("Modified data:", modifiedData);
699
- fs.writeFile(filePath, modifiedData, "utf-8", (err) => {
700
- if (err) {
701
- console.error("Error writing file:", err);
702
- return;
703
- }
704
- });
705
- });
706
- }
707
- function readJsonFile(filePath) {
2780
+ /** Served under `<base>__reactor_worker__/packages/`. */
2781
+ const WORKER_PACKAGES_MANIFEST = "manifest.json";
2782
+ /** Vendor is two levels up from `__reactor_worker__/packages/`. */
2783
+ const VENDOR_PREFIX = "../../__vendor__/";
2784
+ function readVersion(root) {
708
2785
  try {
709
- const absolutePath = resolve(filePath);
710
- const fileContents = fs.readFileSync(absolutePath, "utf-8");
711
- return JSON.parse(fileContents);
712
- } catch (_error) {
713
- console.error(`Error reading file: ${filePath}`);
714
- return null;
2786
+ const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
2787
+ return typeof meta.version === "string" ? meta.version : void 0;
2788
+ } catch {
2789
+ return;
715
2790
  }
716
2791
  }
717
2792
  /**
718
- * Takes a list of Powerhouse project packages and optionally local Powerhouse packages and outputs a js file which exports those packages for use in Connect Studio.
2793
+ * A package root's models entry, or null when it ships none.
2794
+ *
2795
+ * Two roots are possible and both are normal: an installed dependency under
2796
+ * `node_modules/<name>`, and the project itself - the vetra case, where the
2797
+ * project *is* the local package and has no self-link in node_modules.
719
2798
  */
720
- function makeImportScriptFromPackages(args) {
721
- const { packages, localJsPath, localCssPath, importStyles = true } = args;
722
- const imports = [];
723
- const moduleNames = [];
724
- let counter = 0;
725
- for (const packageName of packages) {
726
- const moduleName = `module${counter}`;
727
- moduleNames.push(moduleName);
728
- imports.push(`import * as ${moduleName} from '${packageName}';`);
729
- if (importStyles) imports.push(`import '${packageName}/style.css';`);
730
- counter++;
731
- }
732
- const exports = moduleNames.map((name, index) => `{
733
- id: "${packages[index]}",
734
- ...${name},
735
- }`);
736
- const hasModule = localJsPath !== void 0;
737
- const hasStyles = importStyles && localCssPath !== void 0;
738
- if (hasModule || hasStyles) {
739
- if (hasStyles) imports.push(`import '${localCssPath}';`);
740
- if (hasModule) {
741
- const moduleName = `module${counter}`;
742
- imports.push(`import * as ${moduleName} from '${localJsPath}';`);
743
- exports.push(`{
744
- id: "${LOCAL_PACKAGE_ID}",
745
- ...${moduleName},
746
- }`);
747
- }
2799
+ function resolvePackageModels(dirname, name) {
2800
+ const roots = [];
2801
+ try {
2802
+ roots.push(realpathSync(join(dirname, "node_modules", name)));
2803
+ } catch {}
2804
+ if (readProjectName(dirname) === name) roots.push(dirname);
2805
+ for (const root of roots) {
2806
+ const entryPath = join(root, "dist", "browser", "document-models", "index.js");
2807
+ if (existsSync(entryPath)) return {
2808
+ entryPath,
2809
+ version: readVersion(root)
2810
+ };
748
2811
  }
749
- const exportStatement = `export default [${exports.length ? `
750
- ${exports.join(",\n")}
751
- ` : ""}];`;
752
- return `${imports.join("\n")}\n\n${exportStatement}`;
2812
+ return null;
753
2813
  }
754
- function ensureNodeVersion(minVersion = "24") {
755
- const version = process.versions.node;
756
- if (!version) return;
757
- if (version < minVersion) {
758
- console.error(`Node version ${minVersion} or higher is required. Current version: ${version}`);
759
- process.exit(1);
2814
+ function readProjectName(dirname) {
2815
+ try {
2816
+ const meta = JSON.parse(readFileSync(join(dirname, "package.json"), "utf8"));
2817
+ return typeof meta.name === "string" ? meta.name : void 0;
2818
+ } catch {
2819
+ return;
760
2820
  }
761
2821
  }
762
- function runShellScriptPlugin(scriptName, connectPath) {
763
- return {
764
- name: "vite-plugin-run-shell-script",
765
- buildStart() {
766
- const scriptPath = join(connectPath, scriptName);
767
- if (fs.existsSync(scriptPath)) exec(`sh ${scriptPath}`, (error, stdout, stderr) => {
768
- if (error) {
769
- console.error(`Error executing the script: ${error.message}`);
770
- removeBase64EnvValues(connectPath);
771
- return;
772
- }
773
- if (stderr) console.error(stderr);
774
- });
775
- }
776
- };
777
- }
778
- /**
779
- * Shared helper to modify the <head> tag of an HTML file by transforming its contents.
780
- */
781
- async function modifyHtmlHead(pathToHtml, contents, transform) {
782
- if (!existsSync(pathToHtml)) throw new Error(`File ${pathToHtml} does not exist.`);
783
- let html = await readFile(pathToHtml, "utf8");
784
- html = transform(html, contents);
785
- await writeFile(pathToHtml, html, "utf8");
786
- }
787
2822
  /**
788
- * Appends the contents to the <head> tag of the index.html file
2823
+ * The project's own package name when it ships a models bundle, so a caller
2824
+ * can include it beside the configured `provider: "local"` packages. A vetra
2825
+ * project declares no package entry for itself, yet its models are exactly
2826
+ * the ones the worker is missing.
789
2827
  */
790
- async function appendToHtmlHead(pathToHtml, contents) {
791
- return modifyHtmlHead(pathToHtml, contents, (html, contents) => {
792
- if (!html.includes("</head>")) throw new Error("No </head> tag found in the HTML file.");
793
- return html.replace("</head>", `\n${contents}\n</head>`);
794
- });
2828
+ function ownProjectPackage(dirname) {
2829
+ const name = readProjectName(dirname);
2830
+ if (!name) return void 0;
2831
+ return resolvePackageModels(dirname, name) ? name : void 0;
795
2832
  }
796
2833
  /**
797
- * Prepends the contents to the <head> tag of the index.html file
2834
+ * Build each local package's models entry into `outDir` and write the
2835
+ * manifest the tab reads. Returns the manifest entries (empty when no local
2836
+ * package ships a models bundle), or null when the build itself failed -
2837
+ * `errorRef` then carries the cause. Both of those remove `outDir`, so a
2838
+ * previous build's bundles never outlive the packages they came from.
798
2839
  */
799
- async function prependToHtmlHead(pathToHtml, contents) {
800
- return modifyHtmlHead(pathToHtml, contents, (html, contents) => {
801
- if (!html.includes("</head>")) throw new Error("No </head> tag found in the HTML file.");
802
- return html.replace("<head>", `<head>\n${contents}\n`);
803
- });
804
- }
805
- function runTsc(outDir) {
806
- execSync(`npx tsc --outDir ${outDir}`, { stdio: "inherit" });
807
- }
808
- function stripVersionFromPackage(packageName) {
809
- const trimmed = packageName.trim();
810
- if (!trimmed) return "";
811
- const lastAtIndex = trimmed.lastIndexOf("@");
812
- if (lastAtIndex > 0) return trimmed.substring(0, lastAtIndex);
813
- return trimmed;
2840
+ async function prebuildWorkerPackages(options) {
2841
+ const nodeEnv = options.nodeEnv ?? "production";
2842
+ const resolved = [];
2843
+ for (const name of options.packages) {
2844
+ const models = resolvePackageModels(options.dirname, name);
2845
+ if (!models) continue;
2846
+ resolved.push({
2847
+ entry: {
2848
+ name,
2849
+ version: models.version,
2850
+ file: workerPackageFileName(name)
2851
+ },
2852
+ entryPath: models.entryPath
2853
+ });
2854
+ }
2855
+ if (resolved.length === 0) {
2856
+ rmSync(options.outDir, {
2857
+ recursive: true,
2858
+ force: true
2859
+ });
2860
+ return [];
2861
+ }
2862
+ const vendorImports = options.safeVendorImports ?? (options.vendor ? workerSafeVendorImports(options.vendor.dir, options.vendor.imports) : {});
2863
+ const entries = Object.fromEntries(resolved.map((item) => [item.entry.file.replace(/\.js$/, ""), item.entryPath]));
2864
+ const parent = dirname(options.outDir);
2865
+ mkdirSync(parent, { recursive: true });
2866
+ const tmpDir = mkdtempSync(join(parent, ".ph-worker-packages.tmp-"));
2867
+ try {
2868
+ const { ok, stderr } = await runWorkerBuildEntries(options.dirname, tmpDir, entries, vendorImports, nodeEnv, VENDOR_PREFIX);
2869
+ const missing = resolved.filter((item) => !existsSync(join(tmpDir, item.entry.file)));
2870
+ if (!ok || missing.length > 0) {
2871
+ const detail = stderr.trim();
2872
+ throw new Error(`worker package bundles failed to build${missing.length > 0 ? ` (missing: ${missing.map((m) => m.entry.name).join(", ")})` : ""}${detail ? `:\n${detail}` : ""}`);
2873
+ }
2874
+ for (const item of resolved) {
2875
+ const offenders = findBundleSpecifierOffenders(tmpDir, item.entry.file);
2876
+ if (offenders.length > 0) throw new Error(`worker package bundle for ${item.entry.name} contains module specifiers a worker cannot resolve:\n` + offenders.map((o) => ` ${o.file}: ${o.specs.join(", ")}`).join("\n"));
2877
+ }
2878
+ const manifest = resolved.map((item) => item.entry);
2879
+ writeFileSync(join(tmpDir, WORKER_PACKAGES_MANIFEST), JSON.stringify(manifest, null, 2));
2880
+ publishDirAtomic(tmpDir, options.outDir);
2881
+ return manifest;
2882
+ } catch (err) {
2883
+ rmSync(tmpDir, {
2884
+ recursive: true,
2885
+ force: true
2886
+ });
2887
+ rmSync(options.outDir, {
2888
+ recursive: true,
2889
+ force: true
2890
+ });
2891
+ if (options.errorRef) options.errorRef.message = err instanceof Error ? err.message : String(err);
2892
+ return null;
2893
+ }
814
2894
  }
815
2895
  //#endregion
816
2896
  //#region connect-utils/runtime-config-schema.ts
@@ -872,6 +2952,10 @@ function readBundledPackageVersion(projectRoot, name) {
872
2952
  return;
873
2953
  }
874
2954
  }
2955
+ function offeredRoutesFile(projectRoot, name) {
2956
+ const file = path.join(projectRoot, "node_modules", name, "dist/browser/connect-routes.js");
2957
+ return fs.existsSync(file) ? file : void 0;
2958
+ }
875
2959
  function makeRegisterModule(packages, projectRoot) {
876
2960
  if (packages.length === 0) return "export default () => {};\n";
877
2961
  const imports = [];
@@ -881,7 +2965,9 @@ function makeRegisterModule(packages, projectRoot) {
881
2965
  const version = readBundledPackageVersion(projectRoot, name);
882
2966
  imports.push(`import * as ${moduleName} from ${JSON.stringify(name)};`);
883
2967
  imports.push(`import ${JSON.stringify(`${name}/style.css`)};`);
884
- calls.push(` pm.addLocalPackage(${JSON.stringify(name)}, ${moduleName}, ${JSON.stringify(version)});`);
2968
+ const routesFile = offeredRoutesFile(projectRoot, name);
2969
+ const routes = routesFile ? `, () => import(${JSON.stringify(routesFile)})` : "";
2970
+ calls.push(` pm.addLocalPackage(${JSON.stringify(name)}, ${moduleName}, ${JSON.stringify(version)}${routes});`);
885
2971
  });
886
2972
  return `${imports.join("\n")}\n\nexport default function register(pm) {\n${calls.join("\n")}\n};\n`;
887
2973
  }
@@ -939,7 +3025,8 @@ const VENDOR_MIME = {
939
3025
  const VENDOR_MODE = process.env.PH_CONNECT_EXTERNALIZE_VENDOR === "1";
940
3026
  const VENDOR_EXTRA = (process.env.PH_CONNECT_VENDOR_EXTRA ?? "").split(",").map((s) => s.trim()).filter(Boolean);
941
3027
  const HEAVY_LIBS = [...DEFAULT_VENDOR_INCLUDE, ...VENDOR_EXTRA];
942
- function withBase(base, p) {
3028
+ const heavyLibsFor = (routesDir) => routesDir ? HEAVY_LIBS.filter((lib) => lib !== "@powerhousedao/connect") : HEAVY_LIBS;
3029
+ function withBase$1(base, p) {
943
3030
  return `${base}${p}`.replace(/\/{2,}/g, "/");
944
3031
  }
945
3032
  function externalizePlugin(externals) {
@@ -974,15 +3061,16 @@ function externalizePlugin(externals) {
974
3061
  * the React shims above → one React instance across Connect, the vendor, and
975
3062
  * CDN editors.
976
3063
  */
977
- async function devReactImportmapPlugin(projectRoot = process.cwd()) {
3064
+ async function devReactImportmapPlugin(projectRoot = process.cwd(), routesDir = resolveConnectRoutesDir(projectRoot)) {
978
3065
  let namedExports = /* @__PURE__ */ new Map();
979
3066
  let base = "/";
980
3067
  let vendor = null;
3068
+ const heavyLibs = heavyLibsFor(routesDir);
981
3069
  if (VENDOR_MODE) {
982
3070
  const errorRef = {};
983
3071
  vendor = await prebuildConnectVendor({
984
3072
  dirname: projectRoot,
985
- include: HEAVY_LIBS,
3073
+ include: heavyLibs,
986
3074
  errorRef
987
3075
  });
988
3076
  if (!vendor) {
@@ -1001,8 +3089,8 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1001
3089
  const include = new Set(cfg.optimizeDeps.include ?? []);
1002
3090
  REACT_DEPS.forEach((d) => include.add(d));
1003
3091
  if (vendorActive) {
1004
- HEAVY_LIBS.forEach((d) => include.delete(d));
1005
- cfg.optimizeDeps.exclude = [...new Set([...cfg.optimizeDeps.exclude ?? [], ...HEAVY_LIBS])];
3092
+ heavyLibs.forEach((d) => include.delete(d));
3093
+ cfg.optimizeDeps.exclude = [.../* @__PURE__ */ new Set([...cfg.optimizeDeps.exclude ?? [], ...heavyLibs])];
1006
3094
  }
1007
3095
  cfg.optimizeDeps.include = [...include];
1008
3096
  },
@@ -1021,7 +3109,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1021
3109
  }));
1022
3110
  if (vendorActive) {
1023
3111
  const vendorDir = vendor.vendorDir;
1024
- const vendorPrefixes = [withBase(base, VENDOR_URL_PREFIX), VENDOR_URL_PREFIX];
3112
+ const vendorPrefixes = [withBase$1(base, VENDOR_URL_PREFIX), VENDOR_URL_PREFIX];
1025
3113
  server.middlewares.use((req, res, next) => {
1026
3114
  const url = (req.url ?? "").split("?")[0];
1027
3115
  const prefix = vendorPrefixes.find((p) => url.startsWith(p));
@@ -1043,7 +3131,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1043
3131
  });
1044
3132
  });
1045
3133
  }
1046
- const shimPrefixes = [withBase(base, SHIM_PATH), `/${SHIM_PATH}`];
3134
+ const shimPrefixes = [withBase$1(base, SHIM_PATH), `/${SHIM_PATH}`];
1047
3135
  server.middlewares.use((req, res, next) => {
1048
3136
  const prefix = shimPrefixes.find((p) => req.url?.startsWith(p));
1049
3137
  if (!prefix) return next();
@@ -1057,7 +3145,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1057
3145
  return;
1058
3146
  }
1059
3147
  const browserHash = info.browserHash ?? optimizer.metadata.browserHash;
1060
- const depUrl = `${withBase(base, VITE_DEPS_PATH)}/${path.basename(info.file)}?v=${browserHash}`;
3148
+ const depUrl = `${withBase$1(base, VITE_DEPS_PATH)}/${path.basename(info.file)}?v=${browserHash}`;
1061
3149
  const names = namedExports.get(id) ?? [];
1062
3150
  res.setHeader("Content-Type", "application/javascript");
1063
3151
  res.end(`import * as M from ${JSON.stringify(depUrl)};\nconst ns = M.default ?? M;\nexport default ns;\n` + (names.length ? `export const { ${names.join(", ")} } = ns;\n` : ""));
@@ -1068,12 +3156,12 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1068
3156
  handler(html, ctx) {
1069
3157
  const browserHash = ctx.server?.environments.client.depsOptimizer?.metadata.browserHash;
1070
3158
  if (!browserHash) return;
1071
- const shimPrefix = withBase(base, SHIM_PATH);
3159
+ const shimPrefix = withBase$1(base, SHIM_PATH);
1072
3160
  const imports = Object.fromEntries(REACT_DEPS.map((id) => [id, `${shimPrefix}${id}.js?v=${browserHash}`]));
1073
3161
  let dynamicBaseScript = "";
1074
3162
  if (vendorActive) {
1075
- for (const [spec, url] of Object.entries(vendor.imports)) imports[spec] = withBase(base, url);
1076
- if (vendor.imports["@powerhousedao/connect"]) imports["ph-bundled-packages-virtual"] = withBase(base, BUNDLED_PACKAGES_DEV_URL);
3163
+ for (const [spec, url] of Object.entries(vendor.imports)) imports[spec] = withBase$1(base, url);
3164
+ if (vendor.imports["@powerhousedao/connect"]) imports["ph-bundled-packages-virtual"] = withBase$1(base, BUNDLED_PACKAGES_DEV_URL);
1077
3165
  dynamicBaseScript = `<script>globalThis.__PH_DYNAMIC_BASE__=${JSON.stringify(base)};<\/script>\n`;
1078
3166
  }
1079
3167
  return html.replace(/<script type="importmap">[\s\S]*?<\/script>/, `${dynamicBaseScript}<script type="importmap">${JSON.stringify({ imports }, null, 2)}<\/script>`);
@@ -1118,7 +3206,7 @@ function connectFaviconPlugin(opts = {}) {
1118
3206
  res.end(readFileSync(resolved.id));
1119
3207
  }).catch(() => next());
1120
3208
  };
1121
- const paths = new Set([faviconRoute, "/icon.ico"]);
3209
+ const paths = /* @__PURE__ */ new Set([faviconRoute, "/icon.ico"]);
1122
3210
  for (const path of paths) server.middlewares.use(path, handler);
1123
3211
  },
1124
3212
  async generateBundle(_options, bundle) {
@@ -1156,21 +3244,47 @@ function readProjectPackageInfo(projectRoot) {
1156
3244
  return null;
1157
3245
  }
1158
3246
  }
3247
+ /** `html` with its `<title>` text set to `appName`, when one is configured. */
3248
+ function withAppTitle(html, appName) {
3249
+ if (!appName) return html;
3250
+ const escaped = appName.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
3251
+ return html.replace(/<title>[^<]*<\/title>/, () => `<title>${escaped}</title>`);
3252
+ }
3253
+ /** `api.connect`: the connect config the app is served, for plugins that render
3254
+ * ahead of it; `api.favicon`: its `branding.favicon`, which it leaves out. */
1159
3255
  function phConfigPlugin(options) {
1160
3256
  const localPackage = readProjectPackageInfo(options.projectRoot ?? process.cwd());
1161
- const withDefaults = deepMerge(DEFAULT_CONNECT_CONFIG, options.connect ?? {});
3257
+ const sourceSettings = {
3258
+ connect: options.connect,
3259
+ workflows: options.workflows
3260
+ };
3261
+ const conflict = workflowsSettingConflict(sourceSettings);
3262
+ if (conflict) console.warn(`[powerhouse] ${conflict}`);
3263
+ const withDefaults = resolveSourceConnect(sourceSettings);
1162
3264
  const mergedConnect = options.cliConnectOverride ? deepMerge(withDefaults, options.cliConnectOverride) : withDefaults;
1163
- const runtimeConfig = buildRuntimeConfig({
3265
+ const { favicon, ...branding } = mergedConnect.branding ?? {};
3266
+ const source = {
1164
3267
  packages: options.packages,
1165
3268
  packageRegistryUrl: options.packageRegistryUrl,
1166
- connect: mergedConnect
1167
- }, localPackage);
3269
+ connect: options.branding ? {
3270
+ ...mergedConnect,
3271
+ branding: options.branding
3272
+ } : mergedConnect.branding ? {
3273
+ ...mergedConnect,
3274
+ branding
3275
+ } : mergedConnect
3276
+ };
3277
+ const runtimeConfig = buildRuntimeConfig(source, localPackage);
1168
3278
  const content = JSON.stringify({
1169
3279
  $schema: RUNTIME_CONFIG_SCHEMA_URL,
1170
3280
  ...runtimeConfig
1171
3281
  }, null, 2);
1172
3282
  return {
1173
3283
  name: "vite-plugin-ph-config",
3284
+ api: {
3285
+ connect: runtimeConfig.connect,
3286
+ favicon: favicon ?? void 0
3287
+ },
1174
3288
  configureServer(server) {
1175
3289
  server.middlewares.use((req, res, next) => {
1176
3290
  if (req.url?.endsWith("/powerhouse.config.json")) {
@@ -1191,6 +3305,9 @@ function phConfigPlugin(options) {
1191
3305
  });
1192
3306
  }
1193
3307
  },
3308
+ transformIndexHtml(html) {
3309
+ return withAppTitle(html, runtimeConfig.connect.branding?.appName ?? void 0);
3310
+ },
1194
3311
  generateBundle() {
1195
3312
  this.emitFile({
1196
3313
  type: "asset",
@@ -1217,11 +3334,13 @@ function toPwaContribution(manifest, fallbackLabel, onWarn) {
1217
3334
  if (!isPlainObject(manifest)) return null;
1218
3335
  const label = typeof manifest.name === "string" && manifest.name ? manifest.name : fallbackLabel;
1219
3336
  let config = {};
1220
- if (manifest.pwa !== void 0) if (!isPlainObject(manifest.pwa)) onWarn(`PWA config: ${label} declares a non-object 'pwa' field in its manifest; ignored.`);
1221
- else {
1222
- const parsed = PwaConfigSchema.safeParse(manifest.pwa);
1223
- if (!parsed.success) onWarn(`PWA config: ${label}'s pwa fragment is invalid; ignored. ${formatZodIssues(parsed.error)}`);
1224
- else config = parsed.data;
3337
+ if (manifest.pwa !== void 0) {
3338
+ if (!isPlainObject(manifest.pwa)) onWarn(`PWA config: ${label} declares a non-object 'pwa' field in its manifest; ignored.`);
3339
+ else {
3340
+ const parsed = PwaConfigSchema.safeParse(manifest.pwa);
3341
+ if (!parsed.success) onWarn(`PWA config: ${label}'s pwa fragment is invalid; ignored. ${formatZodIssues(parsed.error)}`);
3342
+ else config = parsed.data;
3343
+ }
1225
3344
  }
1226
3345
  config = withInferredCategory(config, manifest.category);
1227
3346
  if (Object.keys(config).length === 0) return null;
@@ -1330,7 +3449,8 @@ function collectProjectPwaContribution(options) {
1330
3449
  }
1331
3450
  if (!isPlainObject(manifest)) return null;
1332
3451
  const label = typeof manifest.name === "string" && manifest.name ? manifest.name : "project manifest";
1333
- const withCategory = withInferredCategory(manifest.pwa === void 0 ? {} : parsePwaConfigStrict(manifest.pwa, `pwa in ${manifestPath}`), manifest.category);
3452
+ const config = manifest.pwa === void 0 ? {} : parsePwaConfigStrict(manifest.pwa, `pwa in ${manifestPath}`);
3453
+ const withCategory = withInferredCategory(config, manifest.category);
1334
3454
  if (Object.keys(withCategory).length === 0) return null;
1335
3455
  return {
1336
3456
  source: label,
@@ -1461,6 +3581,28 @@ const BASE_MANIFEST = {
1461
3581
  launch_handler: { client_mode: "focus-existing" }
1462
3582
  };
1463
3583
  /**
3584
+ * The base manifest under the project's own name and icons (from
3585
+ * `connect.branding.appName` / `icons.app`), so an installed app is not
3586
+ * "Powerhouse Connect". Connect's description goes with its name; a project
3587
+ * that wants one sets `connect.pwa.manifest.description`, which — like the
3588
+ * rest of `connect.pwa` — is laid on top of this.
3589
+ */
3590
+ function brandManifest(base, brand) {
3591
+ if (!brand) return base;
3592
+ const manifest = { ...base };
3593
+ if (brand.name) {
3594
+ manifest.name = brand.name;
3595
+ manifest.short_name = brand.name;
3596
+ delete manifest.description;
3597
+ }
3598
+ if (brand.icons?.length) manifest.icons = brand.icons.map((icon) => ({
3599
+ src: icon.fileName,
3600
+ sizes: icon.sizes,
3601
+ type: icon.contentType
3602
+ }));
3603
+ return manifest;
3604
+ }
3605
+ /**
1464
3606
  * Connect's hardcoded precache config — the base layer for the `injectManifest`
1465
3607
  * precache. Overridable additively (extra globs) or by raising the size ceiling
1466
3608
  * via package/project `pwa` config. The rest of the old Workbox config
@@ -1471,12 +3613,13 @@ const BASE_MANIFEST = {
1471
3613
  * declarative runtimeCaching option.
1472
3614
  */
1473
3615
  const BASE_PRECACHE = {
1474
- maximumFileSizeToCacheInBytes: 16 * 1024 * 1024,
1475
- globPatterns: ["**/*.{js,css,html,wasm,data,ico,png,svg,webp,woff,woff2}"],
3616
+ maximumFileSizeToCacheInBytes: 16777216,
3617
+ globPatterns: ["**/*.{js,css,html,wasm,data,ico,png,svg,webp,woff,woff2}", "__reactor_worker__/**/*.json"],
1476
3618
  globIgnores: [
1477
3619
  "**/powerhouse.config.json",
1478
3620
  "**/*.map",
1479
- "index.html"
3621
+ "index.html",
3622
+ "**/*.gz"
1480
3623
  ]
1481
3624
  };
1482
3625
  const SW_FILENAME = "service-worker.ts";
@@ -1534,7 +3677,7 @@ function phSwConfigPlugin(data) {
1534
3677
  * clears its caches on the browser's next service-worker update check.
1535
3678
  */
1536
3679
  function connectPwaPlugins(options) {
1537
- const { offlineEnabled, pwa } = options;
3680
+ const { offlineEnabled, pwa, brand } = options;
1538
3681
  if (!offlineEnabled) return [VitePWA({
1539
3682
  selfDestroying: true,
1540
3683
  strategies: "generateSW",
@@ -1543,7 +3686,7 @@ function connectPwaPlugins(options) {
1543
3686
  devOptions: { enabled: false }
1544
3687
  })];
1545
3688
  const { manifest, precache } = applyPwaOverrides({
1546
- manifest: BASE_MANIFEST,
3689
+ manifest: brandManifest(BASE_MANIFEST, brand),
1547
3690
  precache: BASE_PRECACHE
1548
3691
  }, pwa ?? {});
1549
3692
  const swConfig = {
@@ -1613,17 +3756,40 @@ function resolveReactEntries(dirname$1) {
1613
3756
  }
1614
3757
  return out;
1615
3758
  }
3759
+ function reactImportMap(base, files) {
3760
+ const map = {};
3761
+ for (const [spec, file] of Object.entries(files)) {
3762
+ map[spec] = `${base}${REACT_URL_DIR}/${file}`;
3763
+ if (spec.includes("/")) map[`${spec}.js`] = map[spec];
3764
+ }
3765
+ return map;
3766
+ }
1616
3767
  function reactSelfHostPlugin(options) {
1617
3768
  const entries = resolveReactEntries(options.dirname);
1618
3769
  let absOutDir = resolve(options.dirname, "dist");
3770
+ let base = "/";
3771
+ let staging;
3772
+ let files = {};
1619
3773
  let importMap = {};
1620
3774
  return {
1621
3775
  name: "ph-react-self-host",
1622
3776
  apply: "build",
1623
3777
  configResolved(config) {
1624
3778
  absOutDir = resolve(config.root, config.build.outDir);
1625
- importMap = Object.fromEntries(Object.keys(entries).map((spec) => [spec, `${config.base}${REACT_URL_DIR}/${spec}.js`]));
1626
- for (const pkg of REACT_PACKAGES) importMap[`${pkg}/`] = `${config.base}${REACT_URL_DIR}/${pkg}/`;
3779
+ base = config.base;
3780
+ },
3781
+ async buildStart() {
3782
+ files = {};
3783
+ importMap = {};
3784
+ if (!Object.keys(entries).length) return;
3785
+ const stagingParent = join(options.dirname, "node_modules");
3786
+ staging = mkdtempSync(join(existsSync(stagingParent) ? stagingParent : options.dirname, ".ph-react-self-host-"));
3787
+ const { ok, stderr } = await runReactBuild(options.dirname, staging, entries, options.dev ? "development" : "production");
3788
+ if (!ok) this.error(`react self-host build failed${stderr.trim() ? `:\n${stderr.trim()}` : ""}`);
3789
+ const manifest = join(staging, FILES_MANIFEST);
3790
+ files = JSON.parse(readFileSync(manifest, "utf8"));
3791
+ rmSync(manifest, { force: true });
3792
+ importMap = reactImportMap(base, files);
1627
3793
  },
1628
3794
  transformIndexHtml() {
1629
3795
  if (!Object.keys(importMap).length) return;
@@ -1634,13 +3800,27 @@ function reactSelfHostPlugin(options) {
1634
3800
  injectTo: "head-prepend"
1635
3801
  }];
1636
3802
  },
1637
- async closeBundle() {
1638
- if (!Object.keys(entries).length) return;
1639
- const { ok, stderr } = await runReactBuild(options.dirname, join(absOutDir, REACT_URL_DIR), entries, options.dev ? "development" : "production");
1640
- if (!ok) this.error(`react self-host build failed${stderr.trim() ? `:\n${stderr.trim()}` : ""}`);
3803
+ closeBundle() {
3804
+ if (!staging) return;
3805
+ const dest = join(absOutDir, REACT_URL_DIR);
3806
+ rmSync(dest, {
3807
+ recursive: true,
3808
+ force: true
3809
+ });
3810
+ mkdirSync(absOutDir, { recursive: true });
3811
+ cpSync(staging, dest, { recursive: true });
3812
+ chmodSync(dest, 493);
3813
+ rmSync(staging, {
3814
+ recursive: true,
3815
+ force: true
3816
+ });
3817
+ staging = void 0;
3818
+ const missing = Object.entries(files).filter(([, file]) => !existsSync(join(dest, file)));
3819
+ if (missing.length) this.error(`react self-host: import map entries have no file in ${dest}:\n` + missing.map(([spec, file]) => ` ${spec} -> ${file}`).join("\n"));
1641
3820
  }
1642
3821
  };
1643
3822
  }
3823
+ const FILES_MANIFEST = "files.json";
1644
3824
  function runReactBuild(dirname, outDir, entries, nodeEnv) {
1645
3825
  mkdirSync(outDir, { recursive: true });
1646
3826
  const workerPath = join(outDir, "build-worker.mjs");
@@ -1715,7 +3895,7 @@ for (const [spec, file] of Object.entries(entries)) {
1715
3895
  input[spec] = entryFile;
1716
3896
  }
1717
3897
  try {
1718
- await build({
3898
+ const result = await build({
1719
3899
  root: dirname, configFile: false, logLevel: 'error',
1720
3900
  base: './', publicDir: false,
1721
3901
  define: { 'process.env.NODE_ENV': JSON.stringify(nodeEnv) },
@@ -1724,11 +3904,18 @@ try {
1724
3904
  outDir, emptyOutDir: false, minify: nodeEnv === 'production', target: 'esnext',
1725
3905
  rollupOptions: {
1726
3906
  input, preserveEntrySignatures: 'strict',
1727
- output: { format: 'es', entryFileNames: '[name].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },
3907
+ output: { format: 'es', entryFileNames: '[name]-[hash].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },
1728
3908
  },
1729
3909
  },
1730
3910
  });
1731
3911
  rmSync(srcDir, { recursive: true, force: true });
3912
+ const files = {};
3913
+ for (const out of Array.isArray(result) ? result : [result]) {
3914
+ for (const chunk of out?.output ?? []) {
3915
+ if (chunk.type === 'chunk' && chunk.isEntry) files[chunk.name] = chunk.fileName;
3916
+ }
3917
+ }
3918
+ writeFileSync(join(outDir, 'files.json'), JSON.stringify(files));
1732
3919
  // Force exit: rolldown can leave native worker threads alive that keep the
1733
3920
  // event loop open, hanging the parent's spawn() promise indefinitely.
1734
3921
  process.exit(0);
@@ -1738,6 +3925,91 @@ try {
1738
3925
  }
1739
3926
  `;
1740
3927
  //#endregion
3928
+ //#region connect-utils/vite-plugins/reactor-worker-dev.ts
3929
+ const DEV_BUNDLE_DIR = "node_modules/.ph-reactor-worker";
3930
+ function withBase(base, p) {
3931
+ return `${base}${p}`.replace(/\/{2,}/g, "/");
3932
+ }
3933
+ /**
3934
+ * Dev-only: serve Connect's reactor SharedWorker bundle under
3935
+ * `<base>__reactor_worker__/`, building it lazily on first request.
3936
+ *
3937
+ * The dev server serves Connect from its prebuilt dist in node_modules, where
3938
+ * `dist/reactor.worker.js` is a library artifact no worker can resolve. The
3939
+ * tab GETs `worker-meta.json` here (JSON, no-cache, written by
3940
+ * `prebuildReactorWorker`) to find the bundle and fold its `sourceDigest`
3941
+ * into its version fingerprint; without this plugin that GET fails and the
3942
+ * worker feature reports itself unavailable instead of dying opaquely.
3943
+ *
3944
+ * Lazy because it is a full `vite build` of the reactor + PGlite graph. The
3945
+ * result is cached in node_modules/.ph-reactor-worker until the installed
3946
+ * Connect, its upstream dists, or builder-tools change (`computeSourceDigest`).
3947
+ */
3948
+ function reactorWorkerDevPlugin(projectRoot) {
3949
+ let base = "/";
3950
+ let building = null;
3951
+ const ensureBuilt = () => {
3952
+ building ??= (async () => {
3953
+ const errorRef = {};
3954
+ const built = await prebuildReactorWorker({
3955
+ dirname: projectRoot,
3956
+ outDir: path.join(projectRoot, DEV_BUNDLE_DIR),
3957
+ nodeEnv: "development",
3958
+ errorRef
3959
+ });
3960
+ if (!built) {
3961
+ console.warn(`[connect] reactor worker bundle build failed${errorRef.message ? `: ${errorRef.message}` : ""}`);
3962
+ building = null;
3963
+ }
3964
+ return built;
3965
+ })();
3966
+ return building;
3967
+ };
3968
+ return {
3969
+ name: "ph-reactor-worker-dev",
3970
+ apply: "serve",
3971
+ configResolved(config) {
3972
+ base = config.base;
3973
+ },
3974
+ configureServer(server) {
3975
+ const prefixes = [withBase(base, REACTOR_WORKER_URL_PREFIX), REACTOR_WORKER_URL_PREFIX];
3976
+ server.middlewares.use((req, res, next) => {
3977
+ const url = (req.url ?? "").split("?")[0];
3978
+ const prefix = prefixes.find((p) => url.startsWith(p));
3979
+ if (!prefix) return next();
3980
+ const name = url.slice(prefix.length).replace(/^\/+/, "");
3981
+ if (!name) return next();
3982
+ (async () => {
3983
+ const built = await ensureBuilt();
3984
+ if (!built) {
3985
+ res.statusCode = 503;
3986
+ res.setHeader("Content-Type", "text/plain");
3987
+ res.end("reactor worker bundle unavailable (build failed; see server log)");
3988
+ return;
3989
+ }
3990
+ const file = path.join(built.outDir, name);
3991
+ const rel = path.relative(built.outDir, file);
3992
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
3993
+ next();
3994
+ return;
3995
+ }
3996
+ const stream = createReadStream(file);
3997
+ stream.on("error", () => {
3998
+ if (!res.headersSent) next();
3999
+ });
4000
+ stream.once("open", () => {
4001
+ const ext = file.slice(file.lastIndexOf("."));
4002
+ res.setHeader("Content-Type", REACTOR_WORKER_MIME[ext] ?? "text/javascript");
4003
+ const hashed = !name.startsWith("reactor.worker.js") && !name.endsWith(".json");
4004
+ res.setHeader("Cache-Control", hashed ? "public, max-age=31536000, immutable" : "no-cache");
4005
+ stream.pipe(res);
4006
+ });
4007
+ })();
4008
+ });
4009
+ }
4010
+ };
4011
+ }
4012
+ //#endregion
1741
4013
  //#region connect-utils/vite-plugins/theme-boot.ts
1742
4014
  /**
1743
4015
  * Marker attribute on the injected script. Serve-time injectors (e.g. the
@@ -1752,7 +4024,7 @@ const THEME_BOOT_MARKER = "data-ph-theme-boot";
1752
4024
  * Keep semantically identical to the runtime store in
1753
4025
  * `@powerhousedao/reactor-browser` (hooks/theme.ts).
1754
4026
  */
1755
- const THEME_BOOT_SCRIPT = "(function(){try{var p=new URLSearchParams(location.search).get('theme');if(p==='dark'||p==='light')localStorage.setItem('ph:theme',p);var s=localStorage.getItem('ph:theme');var d=s==='dark'||((!s||s==='system')&&matchMedia('(prefers-color-scheme: dark)').matches);document.documentElement.classList.toggle('dark',d);}catch(e){}})();";
4027
+ const THEME_BOOT_SCRIPT = "(function(){try{var p=new URLSearchParams(location.search).get('theme');if(p==='dark'||p==='light')localStorage.setItem('ph:theme',p);var s=localStorage.getItem('ph:theme');var m=matchMedia('(prefers-color-scheme: dark)');var d=s==='dark'||((!s||s==='system')&&m.matches);document.documentElement.classList.toggle('dark',d);if(!s||s==='system'){var f=function(){var t=localStorage.getItem('ph:theme');if(!t||t==='system')document.documentElement.classList.toggle('dark',m.matches);};m.addEventListener('change',f);requestAnimationFrame(f);}}catch(e){}})();";
1756
4028
  /**
1757
4029
  * Injects the theme boot script at the top of `<head>` of every emitted
1758
4030
  * index.html, so built Connect apps render the stored theme from first paint
@@ -1776,6 +4048,48 @@ function connectThemeBootPlugin() {
1776
4048
  };
1777
4049
  }
1778
4050
  //#endregion
4051
+ //#region connect-utils/vite-plugins/vendor-import-map.ts
4052
+ function extractImports(raw) {
4053
+ if (typeof raw !== "object" || raw === null) return {};
4054
+ const imports = "imports" in raw ? raw.imports : void 0;
4055
+ if (typeof imports !== "object" || imports === null) return {};
4056
+ const out = {};
4057
+ for (const [key, value] of Object.entries(imports)) if (typeof value === "string") out[key] = value;
4058
+ return out;
4059
+ }
4060
+ function parseImportMap(raw) {
4061
+ try {
4062
+ return extractImports(JSON.parse(raw));
4063
+ } catch {
4064
+ return {};
4065
+ }
4066
+ }
4067
+ const INLINE_IMPORTMAP = /<script type="importmap">([\s\S]*?)<\/script>/;
4068
+ function vendorImportMapPlugin(options) {
4069
+ const vendorEntries = Object.keys(options.imports).length;
4070
+ return {
4071
+ name: "ph-vendor-import-map",
4072
+ apply: "build",
4073
+ transformIndexHtml(html) {
4074
+ if (!vendorEntries) return;
4075
+ const match = INLINE_IMPORTMAP.exec(html);
4076
+ if (match) {
4077
+ const merged = { imports: {
4078
+ ...parseImportMap(match[1]),
4079
+ ...options.imports
4080
+ } };
4081
+ return html.replace(INLINE_IMPORTMAP, `<script type="importmap">${JSON.stringify(merged)}<\/script>`);
4082
+ }
4083
+ return [{
4084
+ tag: "script",
4085
+ attrs: { type: "importmap" },
4086
+ children: JSON.stringify({ imports: options.imports }),
4087
+ injectTo: "head-prepend"
4088
+ }];
4089
+ }
4090
+ };
4091
+ }
4092
+ //#endregion
1779
4093
  //#region connect-utils/vite-config.ts
1780
4094
  function getConnectHtmlTags(options = {}) {
1781
4095
  const { registryUrl, injectTo = "head" } = options;
@@ -1896,14 +4210,15 @@ function getLocalPackageNamesFromPowerhouseConfig({ packages }) {
1896
4210
  }
1897
4211
  function getConnectBaseViteConfig(options) {
1898
4212
  const mode = options.mode;
1899
- const fileEnv = loadEnv(mode, options.envDir ?? options.dirname, "PH_");
4213
+ const envDir = options.envDir ?? options.dirname;
4214
+ const fileEnv = loadEnv(mode, envDir, "PH_");
1900
4215
  const env = loadConnectEnv({
1901
4216
  processEnv: process.env,
1902
4217
  fileEnv
1903
4218
  });
1904
4219
  setConnectEnv(env);
1905
4220
  const phConfigPath = join(options.dirname, "powerhouse.config.json");
1906
- const phConfig = options.powerhouseConfig ?? getConfig(phConfigPath);
4221
+ const phConfig = options.powerhouseConfig ?? getConfig$1(phConfigPath);
1907
4222
  const packagesFromConfig = phConfig.packages ?? [];
1908
4223
  const localPackagesFromConfig = getLocalPackageNamesFromPowerhouseConfig(phConfig);
1909
4224
  const phPackagesStr = env.PH_PACKAGES;
@@ -1958,6 +4273,25 @@ function getConnectBaseViteConfig(options) {
1958
4273
  const projectPwa = validateProjectPwaConfig(deepMerge(phConfig.connect?.pwa ?? {}, options.cliConnectOverride?.pwa ?? {}), phConfigPath);
1959
4274
  const pwaWarn = (msg) => (customLogger ?? console).warn(msg);
1960
4275
  const pwaPackagesForFragments = mode === "production" ? phPackages : phPackages.filter((p) => p.provider === "local");
4276
+ const brandWarn = (msg) => (customLogger ?? console).warn(msg);
4277
+ const branding = effectiveBranding(phConfig.connect?.branding, options.cliConnectOverride?.branding);
4278
+ const projectLoader = resolveProjectLoader(options.dirname, branding, brandWarn);
4279
+ const projectBrand = resolveProjectPwaBrand(options.dirname, branding, brandWarn);
4280
+ const runtimeBranding = resolveRuntimeBranding(options.dirname, branding, brandWarn);
4281
+ const sourceConnect = withResolvedGenericImages(options.dirname, phConfig.connect, brandWarn);
4282
+ const connectOverride = withResolvedGenericImages(options.dirname, options.cliConnectOverride, brandWarn);
4283
+ const configPlugin = phConfigPlugin({
4284
+ packages: phPackages,
4285
+ projectRoot: options.dirname,
4286
+ connect: sourceConnect,
4287
+ workflows: phConfig.workflows,
4288
+ packageRegistryUrl: phPackageRegistryUrl ?? void 0,
4289
+ cliConnectOverride: connectOverride,
4290
+ branding: runtimeBranding
4291
+ });
4292
+ const servedConnect = configPlugin.api.connect;
4293
+ const faviconPath = options.favicon ?? configPlugin.api.favicon;
4294
+ const projectFavicons = resolveProjectFavicons(options.dirname, branding, brandWarn, faviconPath);
1961
4295
  const pwaPlugins = (async () => {
1962
4296
  if (!offlineEnabled) return connectPwaPlugins({ offlineEnabled });
1963
4297
  const contributions = await collectPackagePwaContributions({
@@ -1968,9 +4302,11 @@ function getConnectBaseViteConfig(options) {
1968
4302
  });
1969
4303
  const projectContribution = collectProjectPwaContribution({ projectRoot: options.dirname });
1970
4304
  if (projectContribution) contributions.push(projectContribution);
4305
+ const mergedPwa = mergePwaConfig(contributions, projectPwa, pwaWarn);
1971
4306
  return connectPwaPlugins({
1972
4307
  offlineEnabled,
1973
- pwa: mergePwaConfig(contributions, projectPwa, pwaWarn)
4308
+ pwa: mergedPwa,
4309
+ brand: projectBrand
1974
4310
  });
1975
4311
  })();
1976
4312
  const reactExternal = [
@@ -1990,6 +4326,10 @@ function getConnectBaseViteConfig(options) {
1990
4326
  return null;
1991
4327
  }
1992
4328
  }).filter((p) => p !== null);
4329
+ const routesDir = resolveConnectRoutesDir(options.dirname, options.routes) ?? false;
4330
+ const routes = connectRoutes(options.dirname, routesDir);
4331
+ const customShell = hasProjectAppLayout(routesDir || void 0);
4332
+ const hostStylesheet = hostStylesheetPath(options.dirname, routesDir);
1993
4333
  return {
1994
4334
  configFile: false,
1995
4335
  mode,
@@ -1999,12 +4339,19 @@ function getConnectBaseViteConfig(options) {
1999
4339
  fs: { allow: [searchForWorkspaceRoot(options.dirname), ...linkedRoots] }
2000
4340
  },
2001
4341
  resolve: {
2002
- dedupe: ["react", "react-dom"],
4342
+ alias: routes.aliases,
4343
+ dedupe: [
4344
+ "react",
4345
+ "react-dom",
4346
+ ...routes.dedupe
4347
+ ],
2003
4348
  tsconfigPaths: true
2004
4349
  },
2005
4350
  define: {
2006
4351
  PH_CONNECT_SENTRY_RELEASE: JSON.stringify(release || "unknown"),
2007
- PH_CONNECT_BUILD_HASH: JSON.stringify(buildHash)
4352
+ PH_CONNECT_BUILD_HASH: JSON.stringify(buildHash),
4353
+ ...options.vendor?.sharedDeps && mode === "production" ? { PH_CONNECT_SHARED_DEPS_URL: JSON.stringify(options.vendor.sharedDeps) } : {},
4354
+ ...options.reactorWorkerVersion ? { PH_CONNECT_REACTOR_WORKER_VERSION: JSON.stringify(options.reactorWorkerVersion) } : {}
2008
4355
  },
2009
4356
  customLogger,
2010
4357
  envPrefix: ["PH_CONNECT_"],
@@ -2014,31 +4361,44 @@ function getConnectBaseViteConfig(options) {
2014
4361
  "zod",
2015
4362
  "@powerhousedao/design-system/connect",
2016
4363
  "@powerhousedao/reactor-browser",
2017
- "@powerhousedao/document-engineering"
4364
+ "@powerhousedao/document-engineering",
4365
+ ...routes.include
2018
4366
  ],
2019
4367
  exclude: ["@electric-sql/pglite", "@electric-sql/pglite-tools"]
2020
4368
  },
2021
4369
  plugins: [
2022
- phConfigPlugin({
2023
- packages: phPackages,
2024
- projectRoot: options.dirname,
2025
- connect: phConfig.connect,
2026
- packageRegistryUrl: phPackageRegistryUrl ?? void 0,
2027
- cliConnectOverride: options.cliConnectOverride
2028
- }),
4370
+ configPlugin,
4371
+ hostStylesheetPlugin(options.dirname, hostStylesheet),
2029
4372
  phBundledPackagesPlugin({
2030
4373
  packages: localPackagesFromConfig,
2031
4374
  projectRoot: options.dirname
2032
4375
  }),
2033
- devReactImportmapPlugin(options.dirname),
4376
+ devReactImportmapPlugin(options.dirname, routesDir),
4377
+ reactorWorkerDevPlugin(options.dirname),
4378
+ ...routes.plugins,
2034
4379
  ...plugins,
2035
- esmExternalRequirePlugin({ external: reactExternal }),
4380
+ esmExternalRequirePlugin({ external: [...reactExternal, ...options.vendor && mode === "production" ? Object.keys(options.vendor.imports) : []] }),
2036
4381
  reactSelfHostPlugin({
2037
4382
  dirname: options.dirname,
2038
4383
  dev: mode !== "production" || isDebug
2039
4384
  }),
2040
- connectFaviconPlugin({ faviconPath: options.favicon }),
4385
+ ...options.vendor && mode === "production" ? [vendorImportMapPlugin({ imports: options.vendor.imports })] : [],
4386
+ connectFaviconPlugin({ faviconPath }),
2041
4387
  connectThemeBootPlugin(),
4388
+ connectAppShellPlugin(options.dirname, {
4389
+ composition: servedConnect.composition,
4390
+ appName: servedConnect.branding?.appName ?? void 0,
4391
+ routeAliases: routesDir ? routes.aliases : void 0,
4392
+ routesDir: routesDir || void 0,
4393
+ loader: projectLoader,
4394
+ hostStylesheet
4395
+ }),
4396
+ connectProjectBrandPlugin({
4397
+ loader: projectLoader,
4398
+ pwaIcons: offlineEnabled ? projectBrand.icons : void 0,
4399
+ favicons: projectFavicons,
4400
+ customShell
4401
+ }),
2042
4402
  connectBuildHashPlugin(buildHash),
2043
4403
  ...options.dynamicBase ? [connectDynamicBasePlugin()] : [],
2044
4404
  pwaPlugins
@@ -2047,10 +4407,16 @@ function getConnectBaseViteConfig(options) {
2047
4407
  format: "es",
2048
4408
  ...options.dynamicBase ? { plugins: () => [connectDynamicBasePlugin({ forWorker: true })] } : {}
2049
4409
  },
2050
- build: { sourcemap: true }
4410
+ build: {
4411
+ sourcemap: true,
4412
+ rolldownOptions: {
4413
+ shimMissingExports: true,
4414
+ output: { codeSplitting: { groups: connectRouterChunkGroups(routesDir) } }
4415
+ }
4416
+ }
2051
4417
  };
2052
4418
  }
2053
4419
  //#endregion
2054
- export { BUILD_HASH_FILE, DEFAULT_CONNECT_OUTDIR, DEFAULT_VENDOR_INCLUDE, DYNAMIC_BASE_PLACEHOLDER, EXTERNAL_PACKAGES_IMPORT, IMPORT_SCRIPT_FILE, LOCAL_PACKAGE_ID, PH_DIR_NAME, RUNTIME_CONFIG_SCHEMA_ID, RUNTIME_CONFIG_SCHEMA_URL, THEME_BOOT_MARKER, VENDOR_EXTERNAL, VENDOR_URL_PREFIX, appendToHtmlHead, backupIndexHtml, buildHashFromBuildOptions, computeBuildHash, connectBuildHashPlugin, connectDynamicBasePlugin, connectThemeBootPlugin, copyConnect, ensureNodeVersion, escapeForRegExp, getConnectBaseViteConfig, getConnectHtmlTags, makeImportScriptFromPackages, phConfigPlugin, prebuildConnectVendor, prependToHtmlHead, readJsonFile, removeBase64EnvValues, resolveConnectBundle, resolveConnectPackageJson, resolveConnectPublicDir, resolvePackage, resolveViteConfigPath, runShellScriptPlugin, runTsc, runtimeConfigSchema, stripVersionFromPackage };
4420
+ export { APP_LAYOUT, APP_SHELLS_FILE, APP_SHELL_MARKER, BOOT_RECOVER_KEY, BOOT_RECOVER_MARKER, BOOT_RECOVER_SCRIPT, BUILDER_TOOLS_VERSION, BUILD_HASH_FILE, CONNECT_ROUTES_GEN, CONNECT_ROUTES_SPECIFIER, CORE_ROUTE_TREE_SPECIFIER, DEFAULT_APP_NAME, DEFAULT_CONNECT_OUTDIR, DEFAULT_VENDOR_INCLUDE, DYNAMIC_BASE_PLACEHOLDER, EXTERNAL_PACKAGES_IMPORT, HOST_ROUTES_DIR, IMPORT_SCRIPT_FILE, LOCAL_PACKAGE_ID, LOCK_STALE_MS, PACKAGE_ROUTES_MODULE, PH_DIR_NAME, REACTOR_WORKER_ENTRY, REACTOR_WORKER_MIME, REACTOR_WORKER_URL_PREFIX, ROUTE_TREE_SPECIFIER, RUNTIME_CONFIG_SCHEMA_ID, RUNTIME_CONFIG_SCHEMA_URL, SHELL_PLUGINS_FILE, THEME_BOOT_MARKER, VENDOR_EXTERNAL, VENDOR_SKIP_SUBPATHS, VENDOR_URL_PREFIX, WORKER_PACKAGES_MANIFEST, acquireLock, appShellVariant, appShellVariantOf, appendToHtmlHead, backupIndexHtml, buildHashFromBuildOptions, computeBuildHash, computeSourceDigest, connectAppShellPlugin, connectBuildHashPlugin, connectDynamicBasePlugin, connectRouteFileDeps, connectRouterChunkGroups, connectRoutes, connectRoutesDirOf, connectRoutesGeneratorConfig, connectRoutesTreeOf, connectThemeBootPlugin, copyConnect, directoryContentDigest, distDirFingerprint, ensureNodeVersion, escapeForRegExp, findBundleSpecifierOffenders, findDisallowedSpecifiers, findPackageRoot, findWorkerUnsafeMarkers, generateConnectRoutes, getConnectBaseViteConfig, getConnectHtmlTags, hasProjectAppLayout, hostStylesheetPath, hostStylesheetPlugin, injectAppShell, linkedBuildStamp, makeImportScriptFromPackages, missingVendorEntries, overriddenConnectRoutes, ownProjectPackage, phConfigPlugin, prebuildConnectVendor, prebuildReactorWorker, prebuildWorkerPackages, prependToHtmlHead, publishDirAtomic, readAppShell, readAppShells, readJsonFile, readShellPlugins, readShellPluginsIn, rebaseShellLinks, relativeCssUrls, releaseLock, removeBase64EnvValues, resolveConnectBundle, resolveConnectPackageJson, resolveConnectPublicDir, resolveConnectRoutesDir, resolveOwnDeps, resolveOwnPackageVersion, resolvePackage, resolveReactorWorkerSource, resolveVersionDigest, resolveViteConfigPath, resolveWorkspacePackageDir, routeIdOf, runShellScriptPlugin, runTsc, runWorkerBuildEntries, runtimeConfigSchema, stripVersionFromPackage, swapAppShell, syncConnectRoutes, upstreamWorkerPackages, vendorImportMapPlugin, vendorRelativePath, withAppTitle, withHostStylesheet, withShellAppName, withVendorBase, workerSafeVendorImports };
2055
4421
 
2056
4422
  //# sourceMappingURL=index.mjs.map