@powerhousedao/builder-tools 6.2.3-dev.8 → 6.2.3-dev.81

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,18 +1,22 @@
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, EXTERNALIZABLE_SHARED_SPECIFIERS, 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 { initSync, parse } from "es-module-lexer";
17
+ import { getConfig as getConfig$1 } from "@powerhousedao/config/node";
12
18
  import tailwind from "@tailwindcss/vite";
13
19
  import react from "@vitejs/plugin-react";
14
- import { createLogger, esmExternalRequirePlugin, loadEnv, searchForWorkspaceRoot } from "vite";
15
- import { createHtmlPlugin } from "vite-plugin-html";
16
20
  import { PwaConfigSchema } from "@powerhousedao/shared/document-model";
17
21
  import { toCdnUrl } from "@powerhousedao/shared/registry/urls";
18
22
  import { VitePWA } from "vite-plugin-pwa";
@@ -22,6 +26,1486 @@ 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
+ /** The dev watcher's filter for `.ph/`, which holds build output: ignored but
242
+ * for the host's route tree, rewritten as route files come and go. */
243
+ function ignoreDotPhButRouteTree(projectRoot, routesDir) {
244
+ const tree = routesDir && normalizePath(connectRoutesTreeOf(projectRoot, routesDir));
245
+ return (file) => {
246
+ const path = normalizePath(resolve(projectRoot, file));
247
+ if (!path.includes("/.ph/")) return false;
248
+ return !tree || path !== tree && !tree.startsWith(`${path}/`);
249
+ };
250
+ }
251
+ /**
252
+ * The dev watcher's filter for the project's build output: its own `dist/`
253
+ * and a Tauri shell's Rust `target/`. Nothing the dev server serves lives
254
+ * there, and on Windows every watched file costs a synchronous `fs.watch`
255
+ * at startup (over a minute for a built project with a built desktop shell).
256
+ */
257
+ function ignoreBuildOutput(projectRoot) {
258
+ const dist = `${normalizePath(resolve(projectRoot, "dist"))}/`;
259
+ return (file) => {
260
+ const path = normalizePath(resolve(projectRoot, file));
261
+ return path.startsWith(dist) || path.includes("/tauri-shell/target/") || path.includes("/src-tauri/target/");
262
+ };
263
+ }
264
+ /** Whether a watched path is in `routesDir` or is the folder itself. */
265
+ function inRoutesDir(projectRoot, routesDir) {
266
+ let watchedAs;
267
+ return (file) => {
268
+ watchedAs ??= [routesDir, join(realpathSync(projectRoot), relative(projectRoot, routesDir))];
269
+ const path = resolve(projectRoot, file);
270
+ return watchedAs.some((dir) => path === dir || path.startsWith(`${dir}${sep}`));
271
+ };
272
+ }
273
+ /** Connect's pathless sidebar layout; a project's routes in `_app/` render in it. */
274
+ const APP_LAYOUT = "_app";
275
+ function findRouteFile(dir, name) {
276
+ return [
277
+ ".tsx",
278
+ ".ts",
279
+ ".jsx",
280
+ ".js"
281
+ ].map((ext) => join(dir, `${name}${ext}`)).find((file) => existsSync(file));
282
+ }
283
+ /** Whether the project's `_app` replaces Connect's layout (and its chrome). */
284
+ function hasProjectAppLayout(routesDir) {
285
+ return !!routesDir && !!findRouteFile(routesDir, "_app");
286
+ }
287
+ /** Connect's route files: core's routes with Connect's views. */
288
+ function connectRoutesDirOf(connectDir) {
289
+ return join(connectDir, "src/routes");
290
+ }
291
+ const ROUTE_FILE = /\.[cm]?[jt]sx?$/;
292
+ const isRouteEntry = (name) => !name.startsWith(".") && !name.startsWith("-") && !/\.d\.[cm]?ts$/.test(name);
293
+ /** The route files under `dir`, by path relative to it. */
294
+ function routeFilesIn(dir, at = "") {
295
+ if (!existsSync(dir)) return [];
296
+ return readdirSync(join(dir, at), { withFileTypes: true }).filter((entry) => isRouteEntry(entry.name)).flatMap((entry) => {
297
+ const path = at ? `${at}/${entry.name}` : entry.name;
298
+ if (entry.isDirectory()) return routeFilesIn(dir, path);
299
+ return ROUTE_FILE.test(entry.name) ? [path] : [];
300
+ });
301
+ }
302
+ /** A route file's id below its folder: route groups and `route` files
303
+ * resolved, flat `a.b` names read as folders. */
304
+ function routeIdOf(file) {
305
+ const segments = file.replace(ROUTE_FILE, "").split("/").filter((segment) => !/^\(.+\)$/.test(segment));
306
+ if (segments.at(-1) === "route") segments.pop();
307
+ return segments.join("/").replaceAll(".", "/");
308
+ }
309
+ /** Connect's `_app/` route files that a project file at the same id replaces. */
310
+ function overriddenConnectRoutes(connectAppDir, projectAppDir) {
311
+ const projectIds = new Set(routeFilesIn(projectAppDir).map(routeIdOf));
312
+ return new Set(routeFilesIn(connectAppDir).filter((file) => projectIds.has(routeIdOf(file))));
313
+ }
314
+ const stemOf = (name) => name.replace(ROUTE_FILE, "");
315
+ /** Mounts Connect's routes in `dir` without the `overridden` files: a folder
316
+ * whole when none is in it, else file by file. */
317
+ function mountConnectRoutes(routesDirectory, dir, overridden, prefix = "") {
318
+ if (![...overridden].some((file) => file.startsWith(`${dir}/`))) return [physical(prefix, dir)];
319
+ const entries = readdirSync(join(routesDirectory, dir), { withFileTypes: true }).filter((entry) => isRouteEntry(entry.name));
320
+ const files = entries.filter((entry) => entry.isFile() && ROUTE_FILE.test(entry.name)).map((entry) => entry.name);
321
+ const folders = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
322
+ const at = (name) => prefix ? `${prefix}/${name}` : name;
323
+ const nodes = [];
324
+ for (const name of files) {
325
+ const file = `${dir}/${name}`;
326
+ const stem = stemOf(name);
327
+ const folder = folders.includes(stem) ? `${dir}/${stem}` : void 0;
328
+ if (overridden.has(file)) {
329
+ if (folder) nodes.push(physical(at(stem), folder));
330
+ continue;
331
+ }
332
+ const children = folder && mountConnectRoutes(routesDirectory, folder, overridden);
333
+ if (stem === "index") nodes.push(prefix ? route(`${prefix}/`, file) : index(file));
334
+ else if (!prefix && stem.startsWith("_")) nodes.push(layout(stem, file, children || []));
335
+ else nodes.push(children ? route(at(stem), file, children) : route(at(stem), file));
336
+ }
337
+ for (const name of folders) {
338
+ if (files.some((file) => stemOf(file) === name)) continue;
339
+ nodes.push(...mountConnectRoutes(routesDirectory, `${dir}/${name}`, overridden, at(name)));
340
+ }
341
+ return nodes;
342
+ }
343
+ /** The routes a package offers other Connects, as `ph build` publishes them
344
+ * (`./connect-routes`); generated beside the route tree. */
345
+ const PACKAGE_ROUTES_MODULE = ".ph/connect-routes.package.ts";
346
+ /** Writes the package's routes for registerPackageRoutes: its files but its
347
+ * `_app` layout and its overrides of Connect's `_app/` routes, parents first. */
348
+ function writePackageRoutesModule(projectRoot, projectRoutes, routeNodes, options) {
349
+ const module = join(projectRoot, PACKAGE_ROUTES_MODULE);
350
+ const appDir = join(projectRoutes, APP_LAYOUT);
351
+ const offered = routeNodes.map((node) => ({
352
+ node,
353
+ file: join(options.routesDirectory, node.filePath)
354
+ })).filter(({ node, file }) => {
355
+ if (!file.startsWith(`${projectRoutes}${sep}`)) return false;
356
+ if (node.routePath === `/_app`) return false;
357
+ if (!file.startsWith(`${appDir}${sep}`)) return true;
358
+ const id = routeIdOf(relative(appDir, file).split(sep).join("/"));
359
+ return !options.connectAppIds.has(id);
360
+ }).sort((a, b) => (a.node.routePath ?? "").split("/").length - (b.node.routePath ?? "").split("/").length);
361
+ if (offered.length === 0) {
362
+ rmSync(module, { force: true });
363
+ return;
364
+ }
365
+ const from = (file) => {
366
+ return relative(dirname(module), file).split(sep).join("/").replace(ROUTE_FILE, ".js");
367
+ };
368
+ const lines = [
369
+ "// Generated by ph build: the routes this package offers other Connects.",
370
+ "import type { PackageRoute } from \"@powerhousedao/connect-core/router\";",
371
+ ...offered.map(({ file }, i) => `import { Route as r${i} } from "${from(file)}";`),
372
+ "",
373
+ "export const connectRoutes: PackageRoute[] = [",
374
+ ...offered.map(({ node }, i) => {
375
+ const pathless = node._fsRouteType === "pathless_layout";
376
+ const entry = {
377
+ id: node.routePath,
378
+ ...pathless ? {} : { path: node.path },
379
+ parentId: node.parent?.routePath ?? "__root__"
380
+ };
381
+ return ` { route: r${i}, ${Object.entries(entry).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(", ")} },`;
382
+ }),
383
+ "];",
384
+ ""
385
+ ];
386
+ mkdirSync(dirname(module), { recursive: true });
387
+ const text = lines.join("\n");
388
+ if (!existsSync(module) || readFileSync(module, "utf8") !== text) writeFileSync(module, text);
389
+ }
390
+ /** The `_app/` paths of the generic plugin's code routes, e.g. its settings
391
+ * tabs: a project file at one is an override, never offered. */
392
+ function genericAppRouteIds(connectDir) {
393
+ const file = join(connectDir, "generic-routes.json");
394
+ if (!existsSync(file)) return [];
395
+ return JSON.parse(readFileSync(file, "utf8")).appRoutes ?? [];
396
+ }
397
+ /** The router plugin's config: Connect's root and routes, and the project's. */
398
+ function connectRoutesGeneratorConfig(connectDir, projectRoot, projectRoutes) {
399
+ const routesDirectory = connectRoutesDirOf(connectDir);
400
+ const fromRoutes = (path) => relative(routesDirectory, path);
401
+ const virtualRouteConfig = () => {
402
+ const appLayout = findRouteFile(projectRoutes, APP_LAYOUT);
403
+ const appRoutes = join(projectRoutes, APP_LAYOUT);
404
+ const overridden = new Set([...overriddenConnectRoutes(join(routesDirectory, APP_LAYOUT), appRoutes)].map((file) => `${APP_LAYOUT}/${file}`));
405
+ return rootRoute("__root.tsx", [layout(APP_LAYOUT, appLayout ? fromRoutes(appLayout) : `${APP_LAYOUT}.tsx`, [...mountConnectRoutes(routesDirectory, APP_LAYOUT, overridden), ...existsSync(appRoutes) ? [physical("", fromRoutes(appRoutes))] : []]), ...existsSync(projectRoutes) ? [physical("", fromRoutes(projectRoutes))] : []]);
406
+ };
407
+ const generatedRouteTree = connectRoutesTreeOf(projectRoot, projectRoutes);
408
+ const inProjectRoutes = inRoutesDir(projectRoot, projectRoutes);
409
+ const overrides = {
410
+ name: "ph-connect-route-overrides",
411
+ init: ({ generator }) => {
412
+ Object.defineProperty(generator.config, "virtualRouteConfig", {
413
+ get: virtualRouteConfig,
414
+ configurable: true,
415
+ enumerable: true
416
+ });
417
+ importConnectRoutesByPackage(generator, generatedRouteTree);
418
+ followProjectRoutes(generator, inProjectRoutes);
419
+ }
420
+ };
421
+ const offers = isDefaultRoutesDir(projectRoot, projectRoutes);
422
+ return getConfig({
423
+ target: "react",
424
+ routesDirectory,
425
+ generatedRouteTree,
426
+ virtualRouteConfig: virtualRouteConfig(),
427
+ plugins: offers ? [overrides, {
428
+ name: "ph-connect-offered-routes",
429
+ onRouteTreeChanged: ({ routeNodes }) => {
430
+ writePackageRoutesModule(projectRoot, projectRoutes, routeNodes, {
431
+ routesDirectory,
432
+ connectAppIds: /* @__PURE__ */ new Set([...routeFilesIn(join(routesDirectory, APP_LAYOUT)).map(routeIdOf), ...genericAppRouteIds(connectDir)])
433
+ });
434
+ }
435
+ }] : [overrides],
436
+ routeFileIgnorePattern: `^(${APP_LAYOUT}(\\.[cm]?[jt]sx?)?|.+\\.d\\.[cm]?ts)$`,
437
+ quoteStyle: "double",
438
+ semicolons: true,
439
+ addExtensions: "js",
440
+ autoCodeSplitting: true,
441
+ disableLogging: true,
442
+ routeTreeFileFooter: [
443
+ "import type { ConnectRouterFor } from \"@powerhousedao/connect/router\";",
444
+ "declare module \"@tanstack/react-router\" {",
445
+ " interface Register {",
446
+ " router: ConnectRouterFor<typeof routeTree>;",
447
+ " }",
448
+ "}"
449
+ ]
450
+ }, projectRoot);
451
+ }
452
+ const reported = /* @__PURE__ */ new Map();
453
+ function reportDrops(file, messages) {
454
+ const key = messages.join("\n");
455
+ if (reported.get(file) === key) return;
456
+ reported.set(file, key);
457
+ for (const message of messages) console.warn(`[connect] ${message}`);
458
+ }
459
+ /** Writes the route tree of Connect's and the project's routes; throws on a
460
+ * collision that is not an override, which the router plugin would only log. */
461
+ async function generateConnectRoutes(projectRoot, routesDir, config = connectRoutesGeneratorConfig(connectDirOf(projectRoot), projectRoot, routesDir), warn) {
462
+ mkdirSync(dirname(config.generatedRouteTree), { recursive: true });
463
+ let routeNodes = [];
464
+ const collect = {
465
+ name: "ph-connect-route-urls",
466
+ onRouteTreeChanged: (tree) => {
467
+ routeNodes = tree.routeNodes;
468
+ }
469
+ };
470
+ try {
471
+ await new Generator({
472
+ config: {
473
+ ...config,
474
+ plugins: [...config.plugins ?? [], collect]
475
+ },
476
+ root: projectRoot
477
+ }).run();
478
+ assertNoSharedUrls(routeNodes);
479
+ assertNoDuplicateRoutes(config.generatedRouteTree);
480
+ const drops = dropsContext(projectRoot, routesDir, config.routesDirectory);
481
+ for (const node of routeNodes) {
482
+ const found = dropsOf(node, drops);
483
+ if (!found) continue;
484
+ if (warn) found.messages.forEach(warn);
485
+ else reportDrops(found.file, found.messages);
486
+ }
487
+ } catch (error) {
488
+ const message = (Array.isArray(error) ? error : [error]).map((e) => e instanceof Error ? e.message : String(e)).join("\n");
489
+ const shown = relative(projectRoot, routesDir).split(sep).join("/");
490
+ throw new Error(`Connect could not mount the routes in ${shown}/:\n${message}`, { cause: error });
491
+ }
492
+ }
493
+ /** Connect's route files, as the generated tree imports them: by Connect's
494
+ * package name, which a project depends on. */
495
+ const CONNECT_ROUTES_SPECIFIER = "@powerhousedao/connect/routes";
496
+ function importConnectRoutesByPackage(generator, treeFile) {
497
+ const writer = generator;
498
+ const write = writer.safeFileWrite.bind(writer);
499
+ writer.safeFileWrite = (opts) => {
500
+ if (resolve(opts.filePath) !== resolve(treeFile)) return write(opts);
501
+ const prefix = `"./${relative(dirname(treeFile), writer.config.routesDirectory).split(sep).join("/")}/`;
502
+ const newContent = opts.newContent.replace(new RegExp(`${escapeRegExp(prefix)}([^"]+)\\.js"`, "g"), `"${CONNECT_ROUTES_SPECIFIER}/$1"`);
503
+ return write({
504
+ ...opts,
505
+ newContent
506
+ });
507
+ };
508
+ }
509
+ function followProjectRoutes(generator, inProjectRoutes) {
510
+ const checker = generator;
511
+ const relevant = checker.isFileRelevantForRouteTreeGeneration.bind(checker);
512
+ checker.isFileRelevantForRouteTreeGeneration = (file) => relevant(file) || inProjectRoutes(file);
513
+ }
514
+ function assertNoDuplicateRoutes(treeFile) {
515
+ const tree = readFileSync(treeFile, "utf8");
516
+ const files = /* @__PURE__ */ new Map();
517
+ for (const [, name, file] of tree.matchAll(/^import \{ Route as (\w+) \} from "([^"]+)";$/gm)) files.set(name, [...files.get(name) ?? [], file]);
518
+ const conflicts = [...files.values()].filter((list) => list.length > 1);
519
+ if (conflicts.length === 0) return;
520
+ throw new Error(`Conflicting configuration paths were found for a layout route.\nConflicting files: \n ${conflicts.flat().join("\n ")}\n`);
521
+ }
522
+ const urlOf = (routePath) => `/${routePath.split("/").filter((segment) => segment && !segment.startsWith("_")).join("/")}`;
523
+ function assertNoSharedUrls(routeNodes) {
524
+ const byUrl = /* @__PURE__ */ new Map();
525
+ for (const node of routeNodes) {
526
+ if (node._fsRouteType === "pathless_layout" || !node.routePath) continue;
527
+ const url = urlOf(node.routePath);
528
+ byUrl.set(url, [...byUrl.get(url) ?? [], node.fullPath]);
529
+ }
530
+ const shared = [...byUrl].filter(([, files]) => files.length > 1);
531
+ if (shared.length === 0) return;
532
+ throw new Error(shared.map(([url, files]) => `More than one route serves ${url}; override Connect's in _app/ instead:\n ${files.join("\n ")}`).join("\n"));
533
+ }
534
+ /** The object literal after `key:` in `source`, braces balanced; strings aren't parsed. */
535
+ function objectAfter(source, key) {
536
+ const start = source.search(new RegExp(`\\b${key}\\s*:\\s*\\{`));
537
+ if (start < 0) return void 0;
538
+ const open = source.indexOf("{", start);
539
+ let depth = 0;
540
+ for (let i = open; i < source.length; i++) if (source[i] === "{") depth++;
541
+ else if (source[i] === "}" && --depth === 0) return source.slice(open, i + 1);
542
+ }
543
+ function dropsContext(projectRoot, routesDir, routesDirectory) {
544
+ return {
545
+ projectRoot,
546
+ routesDir,
547
+ routesDirectory,
548
+ connectAppIds: new Set(routeFilesIn(join(routesDirectory, APP_LAYOUT)).map(routeIdOf)),
549
+ genericAppIds: new Set(genericAppRouteIds(dirname(dirname(routesDirectory))))
550
+ };
551
+ }
552
+ /** What the router drops from a project route file without a word: a nav item
553
+ * it can't link, and an override without the options of the route it replaces. */
554
+ function dropsOf(node, context) {
555
+ const file = join(context.routesDirectory, node.filePath);
556
+ if (!file.startsWith(`${context.routesDir}${sep}`) || !existsSync(file)) return;
557
+ const shown = relative(context.projectRoot, file).split(sep).join("/");
558
+ const source = readFileSync(file, "utf8");
559
+ const messages = [];
560
+ const staticData = objectAfter(source, "staticData");
561
+ if (node.routePath?.includes("$") && staticData?.match(/\bnav\s*:/)) messages.push(`${shown}: staticData.nav is ignored on ${node.routePath}, whose params the sidebar can't fill in.`);
562
+ const appDir = join(context.routesDir, APP_LAYOUT);
563
+ if (file.startsWith(`${appDir}${sep}`)) {
564
+ const id = routeIdOf(relative(appDir, file).split(sep).join("/"));
565
+ const connectFile = `@powerhousedao/connect/routes/${APP_LAYOUT}/${id}`;
566
+ if (context.connectAppIds.has(id) && !source.includes(`"${connectFile}"`)) messages.push(`${shown} replaces Connect's route without its options, so what Connect sets on it (loader, search params, pending view, title) is dropped; spread them: import { options } from "${connectFile}".`);
567
+ if (context.genericAppIds.has(id) && !source.includes("genericSettingsTabs")) {
568
+ const tab = id.split("/").at(-1);
569
+ messages.push(`${shown} replaces a settings tab without its options, so the tab isn't listed; spread genericSettingsTabs["${tab}"] from "@powerhousedao/connect/generic".`);
570
+ }
571
+ }
572
+ return {
573
+ file,
574
+ messages
575
+ };
576
+ }
577
+ /** Warns, as Studio regenerates the tree, about each route file it rewrites. */
578
+ function dropsPlugin(projectRoot, routesDir, routesDirectory) {
579
+ const context = dropsContext(projectRoot, routesDir, routesDirectory);
580
+ return {
581
+ name: "ph-connect-silent-drops",
582
+ afterTransform: ({ node }) => {
583
+ const found = dropsOf(node, context);
584
+ if (found) reportDrops(found.file, found.messages);
585
+ }
586
+ };
587
+ }
588
+ function escapeRegExp(text) {
589
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
590
+ }
591
+ /** Generates the tree when the project has routes. Without them, a tree there
592
+ * is rewritten with Connect's routes only, never removed: Studio routes
593
+ * through it, and a removed folder's routes leave it, as tsc needs. */
594
+ async function syncConnectRoutes(projectRoot, routesDir = resolveConnectRoutesDir(projectRoot)) {
595
+ if (routesDir) {
596
+ await generateConnectRoutes(projectRoot, routesDir);
597
+ return;
598
+ }
599
+ rmSync(join(projectRoot, PACKAGE_ROUTES_MODULE), { force: true });
600
+ if (existsSync(join(projectRoot, ".ph/connect-routes.gen.ts"))) await generateConnectRoutes(projectRoot, join(projectRoot, HOST_ROUTES_DIR));
601
+ }
602
+ function connectDirOf(projectRoot) {
603
+ return dirname(resolvePackage("@powerhousedao/connect/package.json", projectRoot));
604
+ }
605
+ /** What Connect's route files import, besides each other. */
606
+ const CONNECT_ROUTE_FILE_DEPS = [
607
+ "@tanstack/react-router",
608
+ "@powerhousedao/connect-core/router",
609
+ "@powerhousedao/connect/route-views"
610
+ ];
611
+ const IN_NODE_MODULES = /[\\/]node_modules[\\/]/;
612
+ /**
613
+ * The `optimizeDeps.include` entries an installed Connect's route files need.
614
+ *
615
+ * Connect and core ship their route files as `.tsx`, which Vite never
616
+ * pre-bundles, so the dev server serves them as they are. Vite also discovers
617
+ * no dependency for a module inside node_modules, so their bare imports load
618
+ * unbundled too, and the CommonJS packages under the router
619
+ * (use-sync-external-store, safe-stable-stringify) then fail in the browser.
620
+ * Pre-bundling these by Connect's name gives the route files the copies they
621
+ * resolve to; core need not be resolvable from the project. A Connect outside
622
+ * node_modules (the monorepo, a linked checkout) is source to Vite, so its
623
+ * imports are discovered and pre-bundled anyway.
624
+ */
625
+ function connectRouteFileDeps(connectDir) {
626
+ if (!IN_NODE_MODULES.test(connectDir)) return [];
627
+ return CONNECT_ROUTE_FILE_DEPS.map((dep) => `@powerhousedao/connect > ${dep}`);
628
+ }
629
+ /** Mounts a project's routes folder over Connect's routes; without one,
630
+ * Connect keeps its prebuilt tree and no router plugin runs. Dev may pass a
631
+ * folder that does not exist yet: it is mounted once it does. */
632
+ function connectRoutes(projectRoot, routesDir = resolveConnectRoutesDir(projectRoot)) {
633
+ const connectDir = connectDirOf(projectRoot);
634
+ const find = ROUTE_TREE_FIND;
635
+ const include = connectRouteFileDeps(connectDir);
636
+ if (!routesDir) return {
637
+ aliases: [{
638
+ find,
639
+ replacement: join(connectDir, "dist/route-tree.js")
640
+ }],
641
+ plugins: [],
642
+ dedupe: [],
643
+ include
644
+ };
645
+ const config = connectRoutesGeneratorConfig(connectDir, projectRoot, routesDir);
646
+ mkdirSync(dirname(config.generatedRouteTree), { recursive: true });
647
+ return {
648
+ aliases: [{
649
+ find,
650
+ replacement: config.generatedRouteTree
651
+ }, {
652
+ find: /^@powerhousedao\/connect\/route-views$/,
653
+ replacement: join(connectDir, "dist/route-views.js")
654
+ }],
655
+ plugins: [
656
+ {
657
+ name: "ph-connect-routes-check",
658
+ buildStart: () => generateConnectRoutes(projectRoot, routesDir, config)
659
+ },
660
+ tanstackRouter({
661
+ ...config,
662
+ plugins: [...config.plugins ?? [], dropsPlugin(projectRoot, routesDir, config.routesDirectory)]
663
+ }),
664
+ connectRoutesWatcher(projectRoot, routesDir, config)
665
+ ],
666
+ dedupe: ["@tanstack/react-router"],
667
+ include
668
+ };
669
+ }
670
+ /** Dev: rewrites the tree as files and folders under the routes folder come and
671
+ * go, the folder itself included; the router plugin follows the tree. */
672
+ function connectRoutesWatcher(projectRoot, routesDir, config) {
673
+ const inRoutes = inRoutesDir(projectRoot, routesDir);
674
+ return {
675
+ name: "ph-connect-routes-watcher",
676
+ apply: "serve",
677
+ configureServer(server) {
678
+ const { logger } = server.config;
679
+ let queue = Promise.resolve();
680
+ const onEvent = (file) => {
681
+ if (!inRoutes(file)) return;
682
+ queue = queue.then(() => generateConnectRoutes(projectRoot, routesDir, config)).catch((error) => logger.error(`[connect] ${error.message}`));
683
+ };
684
+ for (const event of [
685
+ "add",
686
+ "unlink",
687
+ "addDir",
688
+ "unlinkDir"
689
+ ]) server.watcher.on(event, onEvent);
690
+ }
691
+ };
692
+ }
693
+ const ROUTER_PACKAGES = /[\\/]node_modules[\\/]@tanstack[\\/](react-router|router-core|history|react-store|store)[\\/]/;
694
+ /** One chunk for the router and the project's route configs, which the split
695
+ * route components would otherwise spread over several shared chunks. */
696
+ function connectRouterChunkGroups(routesDir) {
697
+ const routes = routesDir && join(routesDir, sep);
698
+ return [
699
+ {
700
+ name: "preload-helper",
701
+ test: /vite[\\/]preload-helper/,
702
+ priority: 1
703
+ },
704
+ {
705
+ name: "use-sync-external-store",
706
+ test: /[\\/]node_modules[\\/]use-sync-external-store[\\/]/,
707
+ priority: 1
708
+ },
709
+ {
710
+ name: "router",
711
+ test: (id) => ROUTER_PACKAGES.test(id) || !!routes && id.startsWith(routes) && !id.includes("tsr-split")
712
+ }
713
+ ];
714
+ }
715
+ //#endregion
716
+ //#region connect-utils/vite-plugins/host-stylesheet.ts
717
+ /** The host's stylesheet, which may not exist yet: `style.css` beside its routes
718
+ * folder, so `hosts/connect/style.css` by default. `ph build` never reads it. */
719
+ function hostStylesheetPath(projectRoot, routesDir) {
720
+ const hostDir = routesDir ? dirname(routesDir) : join(projectRoot, dirname(HOST_ROUTES_DIR));
721
+ return join(hostDir, "style.css");
722
+ }
723
+ const importOf = (stylesheet, file) => `@import ${JSON.stringify(`./${normalizePath(relative(dirname(stylesheet), file))}`)};`;
724
+ /** The project's `style.css` with the host's stylesheet imported last when it
725
+ * exists (else `missing`), so the host's theme wins in the page's one build. */
726
+ function withHostStylesheet(css, stylesheet, hostStylesheet, missing) {
727
+ const file = hostStylesheet && existsSync(hostStylesheet) ? hostStylesheet : missing;
728
+ return file ? `${css}\n${importOf(stylesheet, file)}\n` : css;
729
+ }
730
+ /** Serves the project's `style.css` with the host's stylesheet in it. */
731
+ function hostStylesheetPlugin(projectRoot, hostStylesheet) {
732
+ const stylesheet = join(projectRoot, "style.css");
733
+ const stylesheetId = normalizePath(stylesheet);
734
+ const hostId = normalizePath(hostStylesheet);
735
+ let placeholder;
736
+ return {
737
+ name: "ph-host-stylesheet",
738
+ enforce: "pre",
739
+ configResolved(config) {
740
+ if (config.command !== "serve") return;
741
+ placeholder = join(config.cacheDir, "ph-host-stylesheet.css");
742
+ mkdirSync(dirname(placeholder), { recursive: true });
743
+ writeFileSync(placeholder, "/* Until the host's style.css exists. */\n");
744
+ },
745
+ load(id) {
746
+ if (normalizePath(id.split("?")[0]) !== stylesheetId) return null;
747
+ return withHostStylesheet(readFileSync(stylesheet, "utf8"), stylesheet, hostStylesheet, placeholder);
748
+ },
749
+ hotUpdate(ctx) {
750
+ if (normalizePath(ctx.file) !== hostId) return;
751
+ if (ctx.type === "create" && placeholder && existsSync(placeholder)) {
752
+ const now = /* @__PURE__ */ new Date();
753
+ utimesSync(placeholder, now, now);
754
+ }
755
+ const modules = this.environment.moduleGraph.getModulesByFile(stylesheetId);
756
+ return [...ctx.modules, ...modules ?? []];
757
+ }
758
+ };
759
+ }
760
+ //#endregion
761
+ //#region connect-utils/vite-plugins/node-dedupe.ts
762
+ /** `pkg` is installed for `root`: in a node_modules at or above it. */
763
+ function installedFor(root, pkg) {
764
+ for (let dir = root;; dir = dirname(dir)) {
765
+ if (existsSync(join(dir, "node_modules", pkg, "package.json"))) return true;
766
+ if (dirname(dir) === dir) return false;
767
+ }
768
+ }
769
+ /** `specifier` names `pkg` or one of its subpaths. */
770
+ function names(specifier, pkg) {
771
+ return specifier === pkg || specifier.startsWith(`${pkg}/`);
772
+ }
773
+ /**
774
+ * Runs `fn` with Node's resolution of `packages` (and subpaths) pinned to
775
+ * `root`'s copy. Vite's `resolve.dedupe` reaches only what Vite resolves; an
776
+ * SSR-externalized dependency is loaded by Node from its real path, which for
777
+ * a linked checkout is the checkout's node_modules: two Reacts, and the first
778
+ * hook fails with "reading 'useMemo'". A package `root` lacks keeps its usual
779
+ * resolution.
780
+ */
781
+ async function withNodeDedupe(root, packages, fn) {
782
+ const pinned = packages.filter((pkg) => installedFor(root, pkg));
783
+ if (pinned.length === 0) return fn();
784
+ const rootManifest = join(root, "package.json");
785
+ const parentURL = pathToFileURL(rootManifest).href;
786
+ const rootRequire = createRequire(rootManifest);
787
+ const hooks = registerHooks({ resolve(specifier, context, nextResolve) {
788
+ if (!(context.parentURL !== parentURL && pinned.some((pkg) => names(specifier, pkg)))) return nextResolve(specifier, context);
789
+ if (context.conditions.includes("require")) return {
790
+ url: pathToFileURL(rootRequire.resolve(specifier)).href,
791
+ shortCircuit: true
792
+ };
793
+ return nextResolve(specifier, {
794
+ ...context,
795
+ parentURL
796
+ });
797
+ } });
798
+ try {
799
+ return await fn();
800
+ } finally {
801
+ hooks.deregister();
802
+ }
803
+ }
804
+ //#endregion
805
+ //#region connect-utils/vite-plugins/project-brand.ts
806
+ /** `<meta name>` that tells Connect's loaders which image replaces the logo. */
807
+ const LOADER_META = "ph-loader";
808
+ /** `<meta name>` set when the project's `_app` replaces Connect's layout. */
809
+ const CUSTOM_SHELL_META = "ph-custom-shell";
810
+ const DEFAULT_LOADER_SIZE = 96;
811
+ const DEFAULT_BRANDING = DEFAULT_CONNECT_CONFIG.branding ?? {};
812
+ /**
813
+ * The branding in effect: defaults < source powerhouse.config.json <
814
+ * CLI / host override, applied in that order. In every layer `undefined`
815
+ * leaves the field alone and `null` resets it to the default, so a null in a
816
+ * later layer beats a value in an earlier one. Keys branding does not have
817
+ * (a `homeBackground` from before it moved to `connect.home`) are dropped.
818
+ */
819
+ function effectiveBranding(...layers) {
820
+ const out = { ...DEFAULT_BRANDING };
821
+ const defaults = DEFAULT_BRANDING;
822
+ for (const layer of layers) {
823
+ if (!layer) continue;
824
+ const entries = Object.entries(layer);
825
+ for (const [key, value] of entries) {
826
+ if (value === void 0 || !(key in defaults)) continue;
827
+ out[key] = value === null ? defaults[key] ?? null : value;
828
+ }
829
+ }
830
+ out.appName = (typeof out.appName === "string" ? out.appName.trim() : void 0) || DEFAULT_BRANDING.appName;
831
+ return out;
832
+ }
833
+ /**
834
+ * The `branding` block Connect reads at boot: the app icon reduced to its
835
+ * 64 px variant as a data URI (the in-app logo; a master would be ~1 MB of
836
+ * base64), the loader left out (it is served as a file and declared in
837
+ * index.html). Fields without a usable image end up null.
838
+ */
839
+ function resolveRuntimeBranding(projectRoot, branding, warn) {
840
+ const out = {
841
+ appName: branding.appName ?? DEFAULT_BRANDING.appName,
842
+ icon: null,
843
+ loader: null
844
+ };
845
+ if (branding.icon) {
846
+ const logo = iconVariantPath(projectRoot, branding.icon, 64);
847
+ out.icon = resolveImageRef(projectRoot, logo ?? branding.icon, {
848
+ maxBytes: UI_ICON_MAX_BYTES,
849
+ warn
850
+ }) ?? null;
851
+ }
852
+ return out;
853
+ }
854
+ /**
855
+ * A pane's background with every image, in both colour schemes, resolved to
856
+ * a data URI: a single image stays a single image, layers stay layers (a
857
+ * layer without a usable image is dropped). Problems the renderer cannot
858
+ * fix are warned about: a layer pinned to both edges of an axis, an SVG
859
+ * without a viewBox (its aspect is unknown, so it needs both dimensions).
860
+ */
861
+ function resolveBackground(projectRoot, background, warn) {
862
+ if (!background) return null;
863
+ for (const problem of validateBackground(background, "homeBackground")) warn?.(`[branding] ${problem}`);
864
+ const resolveOne = (ref) => {
865
+ if (!isPassthroughImageRef(ref) && extname(ref).toLowerCase() === ".svg") warnWithoutViewBox(projectRoot, ref, warn);
866
+ return resolveImageRef(projectRoot, ref, {
867
+ maxBytes: BACKGROUND_MAX_BYTES,
868
+ warn
869
+ });
870
+ };
871
+ if (typeof background === "string") return resolveOne(background) ?? null;
872
+ return mapBackgroundImages(background, resolveOne);
873
+ }
874
+ function warnWithoutViewBox(projectRoot, ref, warn) {
875
+ const file = resolve(projectRoot, ref);
876
+ if (!existsSync(file)) return;
877
+ const head = readFileSync(file, "utf8").slice(0, 4096);
878
+ 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.`);
879
+ }
880
+ const EXPLORER_ICON_KEYS = [
881
+ "localDrive",
882
+ "remoteDrive",
883
+ "folder",
884
+ "document"
885
+ ];
886
+ /**
887
+ * The drive explorer's icons with every path resolved to a data URI; a key
888
+ * without a usable image is dropped (the built-in icon), an empty or null
889
+ * set is null.
890
+ */
891
+ function resolveExplorerIcons(projectRoot, icons, warn) {
892
+ if (!icons) return null;
893
+ const ui = {
894
+ maxBytes: UI_ICON_MAX_BYTES,
895
+ warn
896
+ };
897
+ const out = {};
898
+ for (const key of EXPLORER_ICON_KEYS) {
899
+ const src = resolveImageRef(projectRoot, icons[key], ui);
900
+ if (src) out[key] = src;
901
+ }
902
+ if (icons.documents) {
903
+ const documents = {};
904
+ for (const [type, ref] of Object.entries(icons.documents)) {
905
+ const src = resolveImageRef(projectRoot, ref, ui);
906
+ if (src) documents[type] = src;
907
+ }
908
+ if (Object.keys(documents).length > 0) out.documents = documents;
909
+ }
910
+ return Object.keys(out).length > 0 ? out : null;
911
+ }
912
+ /** A generic plugin entry whose config carries images to resolve. */
913
+ function hasGenericImages(entry) {
914
+ return entry.module === "@powerhousedao/connect/plugins/generic" && entry.config !== void 0 && ("icons" in entry.config || "homeBackground" in entry.config);
915
+ }
916
+ /**
917
+ * A connect block with the generic plugin's images resolved, wherever they
918
+ * are declared: `drives.icons` and `home.background` (the classic source
919
+ * values) and the generic plugin entry's `icons` / `homeBackground` in a
920
+ * served composition (the owner under uniform runners). Unchanged when none
921
+ * is present.
922
+ */
923
+ function withResolvedGenericImages(projectRoot, connect, warn) {
924
+ if (!connect) return connect;
925
+ let out = connect;
926
+ if (connect.drives && "icons" in connect.drives) out = {
927
+ ...out,
928
+ drives: {
929
+ ...out.drives,
930
+ icons: resolveExplorerIcons(projectRoot, connect.drives.icons, warn)
931
+ }
932
+ };
933
+ if (connect.home && "background" in connect.home) out = {
934
+ ...out,
935
+ home: {
936
+ ...out.home,
937
+ background: resolveBackground(projectRoot, connect.home.background, warn)
938
+ }
939
+ };
940
+ if (connect.composition?.some(hasGenericImages)) out = {
941
+ ...out,
942
+ composition: connect.composition.map((entry) => {
943
+ if (!hasGenericImages(entry)) return entry;
944
+ const config = { ...entry.config };
945
+ if ("icons" in config) config.icons = resolveExplorerIcons(projectRoot, config.icons, warn);
946
+ if ("homeBackground" in config) config.homeBackground = resolveBackground(projectRoot, config.homeBackground, warn);
947
+ return {
948
+ ...entry,
949
+ config
950
+ };
951
+ })
952
+ };
953
+ return out;
954
+ }
955
+ const IMAGE_TYPES = {
956
+ ".png": "image/png",
957
+ ".svg": "image/svg+xml",
958
+ ".webp": "image/webp",
959
+ ".gif": "image/gif",
960
+ ".jpg": "image/jpeg",
961
+ ".jpeg": "image/jpeg"
962
+ };
963
+ function projectFile(projectRoot, ref) {
964
+ return isAbsolute(ref) ? ref : resolve(projectRoot, ref);
965
+ }
966
+ function asset(projectRoot, ref, fileName, warn) {
967
+ if (isPassthroughImageRef(ref)) {
968
+ warn?.(`[branding] ${ref}: use a project file path here, not a URL. Skipped.`);
969
+ return;
970
+ }
971
+ const file = projectFile(projectRoot, ref);
972
+ const ext = extname(file).toLowerCase();
973
+ const contentType = IMAGE_TYPES[ext];
974
+ if (!contentType) {
975
+ warn?.(`[branding] ${ref}: unsupported image type. Skipped.`);
976
+ return;
977
+ }
978
+ if (!existsSync(file)) {
979
+ warn?.(`[branding] ${ref}: file not found. Skipped.`);
980
+ return;
981
+ }
982
+ return {
983
+ fileName: fileName(ext),
984
+ file,
985
+ contentType
986
+ };
987
+ }
988
+ /** `branding.loader` as the build emits it; undefined keeps Connect's logo. */
989
+ function resolveProjectLoader(projectRoot, branding, warn) {
990
+ const loader = branding?.loader;
991
+ if (!loader) return void 0;
992
+ const spec = typeof loader === "string" ? { src: loader } : loader;
993
+ const found = asset(projectRoot, spec.src, (ext) => `ph-loader${ext}`, warn);
994
+ if (!found) return void 0;
995
+ return {
996
+ ...found,
997
+ animation: spec.animation ?? "pulse",
998
+ size: spec.size ?? DEFAULT_LOADER_SIZE
999
+ };
1000
+ }
1001
+ /** Width and height from a PNG's IHDR chunk. */
1002
+ function pngSize(bytes) {
1003
+ if (bytes.length < 24 || [
1004
+ 137,
1005
+ 80,
1006
+ 78,
1007
+ 71,
1008
+ 13,
1009
+ 10,
1010
+ 26,
1011
+ 10
1012
+ ].some((b, i) => bytes[i] !== b)) return;
1013
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1014
+ return [view.getUint32(16), view.getUint32(20)];
1015
+ }
1016
+ /** The installed app's name and icons, from `branding.appName` and
1017
+ * `branding.icon`. Undefined members keep Connect's own. */
1018
+ function resolveProjectPwaBrand(projectRoot, branding, warn) {
1019
+ const brand = {};
1020
+ const name = branding?.appName?.trim();
1021
+ if (name && name !== DEFAULT_BRANDING.appName) brand.name = name;
1022
+ const app = branding?.icon;
1023
+ if (!app) return brand;
1024
+ const ext = extname(app).toLowerCase();
1025
+ if (ext === ".svg") {
1026
+ const svg = asset(projectRoot, app, () => "pwa-app.svg", warn);
1027
+ if (svg) brand.icons = [{
1028
+ ...svg,
1029
+ sizes: "any"
1030
+ }];
1031
+ return brand;
1032
+ }
1033
+ if (ext !== ".png") {
1034
+ warn?.(`[branding] icon ${app}: the installed-app icon needs a PNG or SVG. Connect's icon stays.`);
1035
+ return brand;
1036
+ }
1037
+ const icons = [];
1038
+ const seen = /* @__PURE__ */ new Set();
1039
+ const add = (ref) => {
1040
+ const file = projectFile(projectRoot, ref);
1041
+ if (!existsSync(file)) return;
1042
+ const size = pngSize(readFileSync(file));
1043
+ if (!size) return;
1044
+ const sizes = `${size[0]}x${size[1]}`;
1045
+ if (seen.has(sizes)) return;
1046
+ seen.add(sizes);
1047
+ icons.push({
1048
+ fileName: `pwa-app-${sizes}.png`,
1049
+ file,
1050
+ contentType: "image/png",
1051
+ sizes
1052
+ });
1053
+ };
1054
+ const stem = app.slice(0, app.length - ext.length);
1055
+ for (const size of PWA_ICON_VARIANT_SIZES) add(`${stem}_${size}x${size}${ext}`);
1056
+ add(app);
1057
+ if (icons.length === 0) {
1058
+ warn?.(`[branding] icon ${app}: not a readable PNG. Connect's icon stays.`);
1059
+ return brand;
1060
+ }
1061
+ brand.icons = icons;
1062
+ return brand;
1063
+ }
1064
+ /**
1065
+ * The favicons: the `_16x16` / `_32x32` / `_64x64` siblings of
1066
+ * `branding.icon` (an SVG master is one scalable favicon). They replace
1067
+ * Connect's static icon.ico link in index.html; none keeps it. A favicon
1068
+ * named outright (`faviconPath`: `branding.favicon` or `--favicon`) wins: it
1069
+ * is built as icon.ico (or icon.svg, icon.png), so the icon's siblings stand aside.
1070
+ */
1071
+ function resolveProjectFavicons(projectRoot, branding, warn, faviconPath) {
1072
+ const app = branding?.icon;
1073
+ if (!app || faviconPath) return [];
1074
+ if (isPassthroughImageRef(app)) {
1075
+ warn?.(`[branding] icon ${app}: use a project file path here, not a URL. Connect's favicon stays.`);
1076
+ return [];
1077
+ }
1078
+ const ext = extname(app).toLowerCase();
1079
+ if (ext === ".svg") {
1080
+ const svg = asset(projectRoot, app, () => "favicon.svg", warn);
1081
+ return svg ? [{
1082
+ ...svg,
1083
+ sizes: "any"
1084
+ }] : [];
1085
+ }
1086
+ const out = [];
1087
+ for (const size of APP_ICON_VARIANT_SIZES) {
1088
+ const variant = iconVariantPath(projectRoot, app, size);
1089
+ if (!variant) continue;
1090
+ const file = projectFile(projectRoot, variant);
1091
+ const contentType = imageMimeType(file);
1092
+ if (!contentType) continue;
1093
+ out.push({
1094
+ fileName: `favicon-${size}x${size}${ext}`,
1095
+ file,
1096
+ contentType,
1097
+ sizes: `${size}x${size}`
1098
+ });
1099
+ }
1100
+ if (out.length === 0) warn?.(`[branding] icon ${app}: no _16x16 / _32x32 / _64x64 siblings found. Connect's favicon stays.`);
1101
+ return out;
1102
+ }
1103
+ function escapeAttr(value) {
1104
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
1105
+ }
1106
+ /** The `<meta>` tags Connect's loaders read. */
1107
+ function brandMetaTags(options) {
1108
+ const tags = [];
1109
+ const { loader } = options;
1110
+ if (loader) tags.push(`<meta name="${LOADER_META}" content="${escapeAttr(loader.fileName)}" data-animation="${loader.animation}" data-size="${loader.size}">`);
1111
+ if (options.customShell) tags.push(`<meta name="${CUSTOM_SHELL_META}" content="true">`);
1112
+ return tags.join("");
1113
+ }
1114
+ const ICON_LINK = /<link\b[^>]*\brel=["']?(?:shortcut )?icon["']?[^>]*>\s*/gi;
1115
+ /** index.html with Connect's icon links replaced by the project's favicons
1116
+ * (one sized link per variant, under `base`); unchanged without any. */
1117
+ function withProjectFavicons(html, favicons, base = "/") {
1118
+ if (favicons.length === 0) return html;
1119
+ const prefix = base.endsWith("/") ? base : `${base}/`;
1120
+ const links = favicons.map((icon) => `<link rel="icon" type="${icon.contentType}" sizes="${icon.sizes}" href="${escapeAttr(prefix + icon.fileName)}" />`).join("");
1121
+ return html.replace(ICON_LINK, "").replace("</head>", `${links}</head>`);
1122
+ }
1123
+ /** Keyframes for the loader motions; shared by the shell and the app. */
1124
+ 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)}}";
1125
+ const LOADER_ANIMATION = {
1126
+ pulse: "ph-loader-pulse 1.6s ease-in-out infinite",
1127
+ spin: "ph-loader-spin 1.4s linear infinite",
1128
+ none: "none"
1129
+ };
1130
+ /** The loader as static markup, for the prerendered shell's first paint. */
1131
+ function loaderMarkup(loader, base = "/") {
1132
+ const prefix = base.endsWith("/") ? base : `${base}/`;
1133
+ const motion = LOADER_ANIMATION[loader.animation];
1134
+ 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}">`;
1135
+ }
1136
+ /** The marked slot in Connect's prerendered shell that holds its logo. */
1137
+ const LOADER_SLOT = /<div\b[^>]*\bdata-ph-loader-slot\b[^>]*>[\s\S]*?<\/div>/;
1138
+ /** Swaps the shell's logo slot for the project's loader. */
1139
+ function replaceShellLoader(shellBody, loader, base = "/") {
1140
+ return shellBody.replace(LOADER_SLOT, () => loaderMarkup(loader, base));
1141
+ }
1142
+ /**
1143
+ * Serves (dev) and emits (build) the branding files, and adds the tags
1144
+ * index.html carries before any JavaScript: the loader and custom-shell
1145
+ * meta tags, and the favicon links.
1146
+ */
1147
+ function connectProjectBrandPlugin(options) {
1148
+ const favicons = options.favicons ?? [];
1149
+ const files = [
1150
+ ...options.loader ? [options.loader] : [],
1151
+ ...options.pwaIcons ?? [],
1152
+ ...favicons
1153
+ ];
1154
+ const meta = brandMetaTags(options);
1155
+ let base = "/";
1156
+ return {
1157
+ name: "ph-connect-project-brand",
1158
+ configResolved(config) {
1159
+ base = config.base;
1160
+ },
1161
+ configureServer(server) {
1162
+ for (const file of files) {
1163
+ const handler = (_req, res, next) => {
1164
+ try {
1165
+ res.setHeader("Content-Type", file.contentType);
1166
+ res.end(readFileSync(file.file));
1167
+ } catch {
1168
+ next();
1169
+ }
1170
+ };
1171
+ const paths = /* @__PURE__ */ new Set([`${server.config.base}${file.fileName}`.replace(/\/{2,}/g, "/"), `/${file.fileName}`]);
1172
+ for (const path of paths) server.middlewares.use(path, handler);
1173
+ }
1174
+ },
1175
+ transformIndexHtml(html) {
1176
+ return withProjectFavicons(meta ? html.replace("</head>", `${meta}</head>`) : html, favicons, base);
1177
+ },
1178
+ generateBundle(_options, bundle) {
1179
+ for (const file of files) {
1180
+ if (file.fileName in bundle) continue;
1181
+ try {
1182
+ this.emitFile({
1183
+ type: "asset",
1184
+ fileName: file.fileName,
1185
+ source: readFileSync(file.file)
1186
+ });
1187
+ } catch {}
1188
+ }
1189
+ }
1190
+ };
1191
+ }
1192
+ //#endregion
1193
+ //#region connect-utils/vite-plugins/app-shell.ts
1194
+ /** On the prerendered shell's elements; marks an index.html that has it. */
1195
+ const APP_SHELL_MARKER = "data-ph-shell";
1196
+ /** In Connect's dist, and copied to a project's: the plugins that pick a shell. */
1197
+ const SHELL_PLUGINS_FILE = "shell-plugins.json";
1198
+ /** In a project's dist: every variant, for a server that swaps the shell to the served composition. */
1199
+ const APP_SHELLS_FILE = "app-shells.json";
1200
+ const SHELL_FILES = {
1201
+ generic: "shell",
1202
+ core: "shell-core"
1203
+ };
1204
+ /** The shell of the composition's first plugin that has one, else core's; no composition is classic.
1205
+ * Without `plugins` (an older Connect): core for a composition, generic for classic. */
1206
+ function appShellVariant(composition, plugins) {
1207
+ if (!plugins) return composition ? "core" : "generic";
1208
+ if (!composition) return Object.values(plugins)[0] ?? "core";
1209
+ for (const { module } of composition) if (Object.hasOwn(plugins, module)) return plugins[module];
1210
+ return "core";
1211
+ }
1212
+ function connectDistDir(projectRoot) {
1213
+ try {
1214
+ return join(dirname(resolvePackage("@powerhousedao/connect/package.json", projectRoot)), "dist");
1215
+ } catch {
1216
+ return;
1217
+ }
1218
+ }
1219
+ /** The plugins' shell manifest in `dir`, if there is a valid one. */
1220
+ function readShellPluginsIn(dir) {
1221
+ const file = join(dir, SHELL_PLUGINS_FILE);
1222
+ if (!existsSync(file)) return void 0;
1223
+ try {
1224
+ const manifest = JSON.parse(readFileSync(file, "utf8"));
1225
+ if (!manifest || typeof manifest !== "object") return void 0;
1226
+ const plugins = {};
1227
+ for (const [module, variant] of Object.entries(manifest)) if (variant === "generic" || variant === "core") plugins[module] = variant;
1228
+ return plugins;
1229
+ } catch {
1230
+ return;
1231
+ }
1232
+ }
1233
+ /** The shell manifest of the installed Connect, if it ships one. */
1234
+ function readShellPlugins(projectRoot) {
1235
+ const distDir = connectDistDir(projectRoot);
1236
+ return distDir ? readShellPluginsIn(distDir) : void 0;
1237
+ }
1238
+ /** The shell Connect's build prerendered, if the installed Connect ships one. */
1239
+ function readAppShell(projectRoot, variant = "generic") {
1240
+ const distDir = connectDistDir(projectRoot);
1241
+ if (!distDir) return void 0;
1242
+ const body = join(distDir, `${SHELL_FILES[variant]}.html`);
1243
+ const head = join(distDir, `${SHELL_FILES[variant]}-head.html`);
1244
+ if (!existsSync(body) || !existsSync(head)) return void 0;
1245
+ return {
1246
+ body: readFileSync(body, "utf8"),
1247
+ head: readFileSync(head, "utf8")
1248
+ };
1249
+ }
1250
+ /** Every variant the installed Connect ships. */
1251
+ function readAppShells(projectRoot) {
1252
+ const shells = {};
1253
+ for (const variant of Object.keys(SHELL_FILES)) {
1254
+ const shell = readAppShell(projectRoot, variant);
1255
+ if (shell) shells[variant] = shell;
1256
+ }
1257
+ return shells;
1258
+ }
1259
+ /** On the boot-recovery script; its sessionStorage key guards against reload loops. */
1260
+ const BOOT_RECOVER_MARKER = "data-ph-boot-recover";
1261
+ const BOOT_RECOVER_KEY = "ph:sw-recover";
1262
+ 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){}})();`;
1263
+ /** Prefixes the shell's root-relative links with the deploy base. */
1264
+ function rebaseShellLinks(body, base) {
1265
+ if (base === "/" || !base) return body;
1266
+ const prefix = base.endsWith("/") ? base : `${base}/`;
1267
+ return body.replace(/(\shref=")\/(?!\/)/g, `$1${prefix}`);
1268
+ }
1269
+ const STYLESHEET_LINK = /<link\b(?=[^>]*\brel=["']?stylesheet\b)[^>]*>/gi;
1270
+ function deferStylesheet(link) {
1271
+ return `${link.replace(/\brel=["']?stylesheet["']?/i, "rel=\"preload\" as=\"style\"").replace(/\/?>$/, ` onload="this.onload=null;this.rel='stylesheet'">`)}<noscript>${link}</noscript>`;
1272
+ }
1273
+ const region = (name, content) => `<!--ph-shell:${name}-->${content}<!--/ph-shell:${name}-->`;
1274
+ const REGION = (name) => new RegExp(`<!--ph-shell:${name}-->[\\s\\S]*?<!--/ph-shell:${name}-->`);
1275
+ /** The app's title without `connect.branding.appName`; core's `appTitle` fallback. */
1276
+ const DEFAULT_APP_NAME = "Connect";
1277
+ const APP_NAME = /(<!--ph-shell:app-name-->)[\s\S]*?(<!--\/ph-shell:app-name-->)/g;
1278
+ const escapeHtml = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1279
+ /** Fills the shell's app name as the app resolves it: the branding name, else the default. */
1280
+ function withShellAppName(html, appName) {
1281
+ const name = escapeHtml(appName || "Connect");
1282
+ return html.replace(APP_NAME, (_m, open, close) => [
1283
+ open,
1284
+ name,
1285
+ close
1286
+ ].join(""));
1287
+ }
1288
+ /** Inlines `shell` into an empty `#root`, adds its critical CSS and, unless
1289
+ * `deferStyles` is false, defers the stylesheets; React replaces the markup when the app renders. */
1290
+ function injectAppShell(html, shell, base = "/", { deferStyles = true, appName } = {}) {
1291
+ if (html.includes("data-ph-shell")) return html;
1292
+ const root = /<div id="root"><\/div>/;
1293
+ if (!root.test(html)) return html;
1294
+ const firstSheet = html.search(STYLESHEET_LINK);
1295
+ const at = firstSheet >= 0 ? firstSheet : html.indexOf("</head>");
1296
+ const recover = `<script ${BOOT_RECOVER_MARKER}>${BOOT_RECOVER_SCRIPT}<\/script>`;
1297
+ const body = withShellAppName(rebaseShellLinks(shell.body, base), appName);
1298
+ const withHead = html.slice(0, at) + region("head", shell.head) + recover + html.slice(at);
1299
+ return (deferStyles ? withHead.replace(STYLESHEET_LINK, deferStylesheet) : withHead).replace(root, () => `<div id="root">${region("body", body)}</div>`);
1300
+ }
1301
+ /** The variant an index.html carries, from its shell's marker value. */
1302
+ function appShellVariantOf(html) {
1303
+ const head = REGION("head").exec(html)?.[0];
1304
+ const value = head && new RegExp(`data-ph-shell="(\\w+)"`).exec(head);
1305
+ if (!value) return void 0;
1306
+ return value[1] === "core" ? "core" : "generic";
1307
+ }
1308
+ /** Replaces the shell an index.html carries with `shell`, titled `appName`; a page without one is unchanged. */
1309
+ function swapAppShell(html, shell, base = "/", appName) {
1310
+ if (!REGION("head").test(html) || !REGION("body").test(html)) return html;
1311
+ const body = withShellAppName(rebaseShellLinks(shell.body, base), appName);
1312
+ return html.replace(REGION("head"), () => region("head", shell.head)).replace(REGION("body"), () => region("body", body));
1313
+ }
1314
+ const DEV_SHELL_WAIT_MS = 1e4;
1315
+ const CONNECT_PACKAGES = ["@powerhousedao/connect", "@powerhousedao/connect-core"];
1316
+ async function renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet) {
1317
+ const server = await createServer({
1318
+ configFile: false,
1319
+ root: projectRoot,
1320
+ logLevel: "error",
1321
+ appType: "custom",
1322
+ server: {
1323
+ middlewareMode: true,
1324
+ hmr: false,
1325
+ ws: false,
1326
+ watch: null
1327
+ },
1328
+ oxc: { jsx: { runtime: "automatic" } },
1329
+ resolve: {
1330
+ alias: routeAliases,
1331
+ dedupe: config.resolve.dedupe,
1332
+ tsconfigPaths: true
1333
+ },
1334
+ define: config.define,
1335
+ cacheDir: join(projectRoot, "node_modules/.vite-ph-prerender"),
1336
+ optimizeDeps: {
1337
+ noDiscovery: true,
1338
+ include: [],
1339
+ entries: []
1340
+ },
1341
+ ssr: {
1342
+ optimizeDeps: {
1343
+ noDiscovery: true,
1344
+ include: []
1345
+ },
1346
+ noExternal: CONNECT_PACKAGES
1347
+ }
1348
+ });
1349
+ try {
1350
+ return await withNodeDedupe(projectRoot, config.resolve.dedupe, async () => {
1351
+ const renderer = await server.ssrLoadModule("@powerhousedao/connect/prerender");
1352
+ const stylesheet = join(projectRoot, "style.css");
1353
+ const css = withHostStylesheet(readFileSync(stylesheet, "utf8"), stylesheet, hostStylesheet);
1354
+ try {
1355
+ return await renderer.renderProjectShells(stylesheet, css);
1356
+ } catch (error) {
1357
+ throw withSourceLocations(error, (stack) => server.ssrRewriteStacktrace(stack));
1358
+ }
1359
+ });
1360
+ } finally {
1361
+ await server.close();
1362
+ }
1363
+ }
1364
+ const RENDER_LOCATION = /\(at (\S+) \((.+?):(\d+):(\d+)\)\)/g;
1365
+ /** The prerender's error with each `(at <component> (<file>:<line>:<col>))` in
1366
+ * its message mapped back to the source, as React reports the transformed code. */
1367
+ function withSourceLocations(error, rewrite) {
1368
+ if (!(error instanceof Error)) return error;
1369
+ const before = error.message;
1370
+ const after = before.replace(RENDER_LOCATION, (found, name, file, line, column) => {
1371
+ const frame = /^ {4}at .*?\(?(\S+?):(\d+):(\d+)\)?$/.exec(rewrite(` at ${name} (${file}:${line}:${column})`));
1372
+ return frame ? `(at ${name} (${frame[1]}:${frame[2]}:${frame[3]}))` : found;
1373
+ });
1374
+ if (after !== before) {
1375
+ error.message = after;
1376
+ if (error.stack) error.stack = error.stack.replace(before, after);
1377
+ }
1378
+ return error;
1379
+ }
1380
+ /** Vite's error overlay over the page, for a failure no module request reports. */
1381
+ function withErrorOverlay(html, err, base) {
1382
+ const script = `<script type="module">import { ErrorOverlay } from "${base}@vite/client";document.body.appendChild(new ErrorOverlay(${JSON.stringify(err).replaceAll("<", "\\u003c")}));<\/script>`;
1383
+ return html.replace("</body>", `${script}</body>`);
1384
+ }
1385
+ const sourceText = (source) => typeof source === "string" ? source : new TextDecoder().decode(source);
1386
+ /** Build: the composition's shell in #root and every variant in the dist, from
1387
+ * the project's routes when it has them. Dev: the shell from the project's routes
1388
+ * when it has them, else core's for a core composition. */
1389
+ function connectAppShellPlugin(projectRoot, { composition, appName, routeAliases, routesDir, loader, hostStylesheet } = {}) {
1390
+ let variant = "generic";
1391
+ let shells = {};
1392
+ let shellPlugins;
1393
+ let base = "/";
1394
+ let isBuild = true;
1395
+ let config;
1396
+ const withLoader = (from) => {
1397
+ if (!loader) return from;
1398
+ const out = {};
1399
+ for (const [name, shell] of Object.entries(from)) out[name] = {
1400
+ ...shell,
1401
+ body: replaceShellLoader(shell.body, loader, base)
1402
+ };
1403
+ return out;
1404
+ };
1405
+ const fromRoutes = () => isBuild && !!routeAliases;
1406
+ const shell = () => {
1407
+ if (fromRoutes()) return void 0;
1408
+ return isBuild || variant === "core" ? shells[variant] : void 0;
1409
+ };
1410
+ let devShells;
1411
+ let devRender;
1412
+ let devShellError;
1413
+ let devServer;
1414
+ const renderDevShells = () => {
1415
+ if (!config || !routeAliases) return;
1416
+ const logger = config.logger;
1417
+ devShellError = void 0;
1418
+ devShells = renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet).then((rendered) => {
1419
+ devShellError = void 0;
1420
+ return withLoader(rendered);
1421
+ }, (error) => {
1422
+ const cause = error instanceof Error ? error : new Error(String(error));
1423
+ devShellError = {
1424
+ message: `The loading shell failed to render from the project's routes, and the build will fail on it:\n${cause.message}`,
1425
+ stack: cause.stack ?? "",
1426
+ plugin: "ph-connect-app-shell"
1427
+ };
1428
+ logger.error(`[connect] ${devShellError.message}`, { timestamp: true });
1429
+ devServer?.ws.send({
1430
+ type: "error",
1431
+ err: devShellError
1432
+ });
1433
+ return {};
1434
+ });
1435
+ };
1436
+ const devShell = async () => {
1437
+ if (!devShells) return void 0;
1438
+ let timer;
1439
+ const wait = new Promise((resolve) => {
1440
+ timer = setTimeout(() => resolve(void 0), DEV_SHELL_WAIT_MS);
1441
+ });
1442
+ try {
1443
+ return (await Promise.race([devShells, wait]))?.[variant];
1444
+ } finally {
1445
+ clearTimeout(timer);
1446
+ }
1447
+ };
1448
+ return {
1449
+ name: "ph-connect-app-shell",
1450
+ configureServer(server) {
1451
+ if (!routeAliases) return;
1452
+ devServer = server;
1453
+ renderDevShells();
1454
+ const stylesheet = join(projectRoot, "style.css");
1455
+ const rerender = (file) => {
1456
+ if (!(file === stylesheet || file === hostStylesheet || !!routesDir && file.startsWith(`${routesDir}${sep}`))) return;
1457
+ clearTimeout(devRender);
1458
+ devRender = setTimeout(renderDevShells, 300);
1459
+ };
1460
+ server.watcher.on("change", rerender);
1461
+ server.watcher.on("add", rerender);
1462
+ server.watcher.on("unlink", rerender);
1463
+ },
1464
+ configResolved(resolved) {
1465
+ config = resolved;
1466
+ base = resolved.base;
1467
+ isBuild = resolved.command === "build";
1468
+ shells = withLoader(readAppShells(projectRoot));
1469
+ shellPlugins = readShellPlugins(projectRoot);
1470
+ variant = appShellVariant(composition, shellPlugins);
1471
+ },
1472
+ transformIndexHtml: {
1473
+ order: "post",
1474
+ handler: async (html) => {
1475
+ const current = !isBuild && routeAliases ? await devShell() : shell();
1476
+ const page = current ? injectAppShell(html, current, base, {
1477
+ deferStyles: isBuild,
1478
+ appName
1479
+ }) : html;
1480
+ return devShellError ? withErrorOverlay(page, devShellError, base) : page;
1481
+ }
1482
+ },
1483
+ generateBundle: {
1484
+ order: "post",
1485
+ async handler(_options, bundle) {
1486
+ if (!isBuild) return;
1487
+ if (fromRoutes() && config && routeAliases) {
1488
+ shells = withLoader(await renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet));
1489
+ const index = bundle["index.html"];
1490
+ const current = shells[variant];
1491
+ if (index?.type === "asset" && current) index.source = injectAppShell(sourceText(index.source), current, base, { appName });
1492
+ }
1493
+ if (!Object.keys(shells).length) return;
1494
+ this.emitFile({
1495
+ type: "asset",
1496
+ fileName: APP_SHELLS_FILE,
1497
+ source: JSON.stringify(shells)
1498
+ });
1499
+ if (shellPlugins) this.emitFile({
1500
+ type: "asset",
1501
+ fileName: SHELL_PLUGINS_FILE,
1502
+ source: JSON.stringify(shellPlugins)
1503
+ });
1504
+ }
1505
+ }
1506
+ };
1507
+ }
1508
+ //#endregion
25
1509
  //#region connect-utils/vite-plugins/build-hash.ts
26
1510
  /** Name of the build-identity file emitted into the build output. */
27
1511
  const BUILD_HASH_FILE = "build-hash.json";
@@ -44,7 +1528,8 @@ function computeBuildHash(input) {
44
1528
  */
45
1529
  function readConnectVersion(projectRoot) {
46
1530
  try {
47
- let dir = dirname(createRequire(join(projectRoot, "package.json")).resolve("@powerhousedao/connect", { paths: [projectRoot] }));
1531
+ const entry = createRequire(join(projectRoot, "package.json")).resolve("@powerhousedao/connect", { paths: [projectRoot] });
1532
+ let dir = dirname(entry);
48
1533
  for (;;) {
49
1534
  try {
50
1535
  const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
@@ -91,16 +1576,6 @@ function connectBuildHashPlugin(buildHash) {
91
1576
  //#endregion
92
1577
  //#region connect-utils/vite-plugins/dynamic-base.ts
93
1578
  /**
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
1579
  * Global the runtime (ph-clint proxy) must set before the entry bundle loads.
105
1580
  * Value is the normalized deploy base, e.g. "/myagent/" or "/". The JS rewrite
106
1581
  * below resolves all asset / lazy-chunk / BASE_URL references against it.
@@ -108,9 +1583,19 @@ const DYNAMIC_BASE_PLACEHOLDER = "/__PH_DYNAMIC_BASE__/";
108
1583
  const RUNTIME_GLOBAL = "globalThis.__PH_DYNAMIC_BASE__";
109
1584
  const BASE_EXPR = `(${RUNTIME_GLOBAL}||"/")`;
110
1585
  function workerPrelude(stripPrefix) {
111
- return `${RUNTIME_GLOBAL}=self.location.pathname.replace(/${escapeForRegExp(stripPrefix).replace(/\//g, "\\/")}assets\\/[^/]*$/,"");\n`;
1586
+ const prefix = escapeForRegExp(stripPrefix).replace(/\//g, "\\/");
1587
+ return `${RUNTIME_GLOBAL}=self.location.pathname.replace(/${prefix}assets\\/[^/]*$/,"");\n`;
112
1588
  }
113
1589
  const PLACEHOLDER_LITERAL = new RegExp(`(["'\`])${escapeForRegExp(DYNAMIC_BASE_PLACEHOLDER)}((?:(?!\\1)[^$])*)\\1`, "g");
1590
+ const PLACEHOLDER_CSS_URL = new RegExp(`url\\(\\s*(["']?)${escapeForRegExp(DYNAMIC_BASE_PLACEHOLDER)}([^"')]*)\\1\\s*\\)`, "g");
1591
+ /** Rewrites `url(<placeholder>assets/x)` relative to the stylesheet at `fileName`. */
1592
+ function relativeCssUrls(css, fileName) {
1593
+ const dir = path.posix.dirname(fileName);
1594
+ return css.replace(PLACEHOLDER_CSS_URL, (_match, quote, target) => {
1595
+ const relative = path.posix.relative(dir, target);
1596
+ return `url(${quote}${relative.startsWith(".") ? relative : `./${relative}`}${quote})`;
1597
+ });
1598
+ }
114
1599
  /**
115
1600
  * Rewrites the placeholder base in emitted JS chunks to a runtime expression so
116
1601
  * one built `dist/connect` serves under any subpath. Rolldown-native: per-match
@@ -135,16 +1620,16 @@ const PLACEHOLDER_LITERAL = new RegExp(`(["'\`])${escapeForRegExp(DYNAMIC_BASE_P
135
1620
  * (the same proxy also sets the runtime global for the JS rewrite). See the
136
1621
  * plugin's module doc / report for the exact serve-time contract.
137
1622
  *
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).
1623
+ * CSS `url(...)` references that Vite emits with the placeholder (e.g. bundled
1624
+ * fonts) are rewritten relative to the stylesheet, which the HTML substitution
1625
+ * already loads from the right prefix.
141
1626
  */
142
1627
  function connectDynamicBasePlugin(options = {}) {
143
1628
  return {
144
1629
  name: "ph-connect-dynamic-base",
145
1630
  enforce: "post",
146
1631
  renderChunk(code, chunk) {
147
- if (!code.includes("/__PH_DYNAMIC_BASE__/")) return null;
1632
+ if (!code.includes(DYNAMIC_BASE_PLACEHOLDER)) return null;
148
1633
  const s = new MagicString(code);
149
1634
  for (const match of code.matchAll(PLACEHOLDER_LITERAL)) {
150
1635
  const rest = match[2];
@@ -161,7 +1646,8 @@ function connectDynamicBasePlugin(options = {}) {
161
1646
  };
162
1647
  },
163
1648
  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}`);
1649
+ for (const file of Object.values(bundle)) if (file.type === "asset" && file.fileName.endsWith(".css")) file.source = relativeCssUrls(String(file.source), file.fileName);
1650
+ 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
1651
  }
166
1652
  };
167
1653
  }
@@ -212,8 +1698,18 @@ const DEFAULT_VENDOR_INCLUDE = [
212
1698
  "zod",
213
1699
  "@powerhousedao/design-system/connect",
214
1700
  "@powerhousedao/reactor-browser",
215
- "@powerhousedao/document-engineering"
1701
+ "@powerhousedao/document-engineering",
1702
+ "@powerhousedao/connect-core",
1703
+ "@tanstack/react-router"
216
1704
  ];
1705
+ /** Never vendored: the route tree is the project's, the config path the app's
1706
+ * base, and SSR server-only. */
1707
+ const VENDOR_SKIP_SUBPATHS = /* @__PURE__ */ new Set([
1708
+ "@powerhousedao/connect-core/route-tree",
1709
+ "@powerhousedao/connect-core/runtime-config",
1710
+ "@tanstack/react-router/ssr/client",
1711
+ "@tanstack/react-router/ssr/server"
1712
+ ]);
217
1713
  /**
218
1714
  * React-family specifiers kept external to the vendor build. The vendor's chunks
219
1715
  * emit bare imports for these; `devReactImportmapPlugin`'s import map resolves
@@ -237,35 +1733,44 @@ const VENDOR_DYNAMIC_BASE = `${DYNAMIC_BASE_PLACEHOLDER}${VENDOR_URL_PREFIX.repl
237
1733
  */
238
1734
  async function prebuildConnectVendor(options) {
239
1735
  const include = expandIncludeSubpaths(options.dirname, options.include ?? DEFAULT_VENDOR_INCLUDE);
1736
+ const own = options.ownDeps ? resolveOwnDeps(options.ownDeps.from, options.ownDeps.specs) : {};
1737
+ for (const spec of Object.keys(own)) if (!include.includes(spec)) include.push(spec);
240
1738
  const external = options.external ?? VENDOR_EXTERNAL;
241
1739
  const vendorDir = options.vendorDir ?? join(options.dirname, "node_modules/.ph-vendor");
242
1740
  const importMapPath = join(vendorDir, "import-map.json");
243
- const versionDigest = resolveVersionDigest(options.dirname, [...include, ...external]);
1741
+ const stamps = /* @__PURE__ */ new Map();
1742
+ const versions = resolveDepVersions(options.dirname, [...include, ...external], stamps);
1743
+ const base = options.base ?? DYNAMIC_BASE_PLACEHOLDER;
1744
+ const nodeEnv = options.nodeEnv ?? "development";
1745
+ const versionDigest = resolveVersionDigest(versions, own, stamps, {
1746
+ base,
1747
+ nodeEnv
1748
+ });
244
1749
  try {
245
1750
  const hit = readCacheHit(importMapPath, include, external, versionDigest);
246
1751
  if (hit) return {
247
1752
  vendorDir,
248
- imports: hit
1753
+ ...hit
249
1754
  };
250
1755
  const lockDir = `${vendorDir}.lock`;
251
1756
  const lock = acquireLock(lockDir);
252
1757
  if (!lock) {
253
- const imports = await waitForCacheHit(importMapPath, include, external, versionDigest, lockDir);
254
- return imports ? {
1758
+ const hit = await waitForCacheHit(importMapPath, include, external, versionDigest, lockDir);
1759
+ return hit ? {
255
1760
  vendorDir,
256
- imports
1761
+ ...hit
257
1762
  } : null;
258
1763
  }
259
1764
  try {
260
1765
  const raced = readCacheHit(importMapPath, include, external, versionDigest);
261
1766
  if (raced) return {
262
1767
  vendorDir,
263
- imports: raced
1768
+ ...raced
264
1769
  };
265
- const imports = await buildVendorAtomic(options.dirname, vendorDir, include, external, versionDigest);
266
- return imports ? {
1770
+ const result = await buildVendorAtomic(options.dirname, vendorDir, include, external, versionDigest, versions, base, nodeEnv, own);
1771
+ return result ? {
267
1772
  vendorDir,
268
- imports
1773
+ ...result
269
1774
  } : null;
270
1775
  } finally {
271
1776
  releaseLock(lock);
@@ -279,27 +1784,105 @@ function readCacheHit(importMapPath, include, external, versionDigest) {
279
1784
  if (!existsSync(importMapPath)) return null;
280
1785
  try {
281
1786
  const cached = JSON.parse(readFileSync(importMapPath, "utf8"));
282
- if (sameSet(cached.include, include) && sameSet(cached.external, external) && cached.versionDigest === versionDigest) return cached.imports;
1787
+ if (sameSet(cached.include, include) && sameSet(cached.external, external) && cached.versionDigest === versionDigest && typeof cached.sharedDeps === "string") return {
1788
+ imports: cached.imports,
1789
+ versions: cached.versions ?? {},
1790
+ sharedDeps: cached.sharedDeps
1791
+ };
283
1792
  } catch {}
284
1793
  return null;
285
1794
  }
286
- function resolveVersionDigest(dirname, specs) {
287
- const seen = /* @__PURE__ */ new Map();
1795
+ const NON_RUNTIME_FILE = /\.(map|d\.[cm]?ts|tsbuildinfo)$/;
1796
+ function linkedBuildStamp(pkgRoot) {
1797
+ if (pkgRoot.split(/[\\/]/).includes("node_modules")) return "";
1798
+ let newest = 0;
1799
+ try {
1800
+ const entries = readdirSync(join(pkgRoot, "dist"), {
1801
+ recursive: true,
1802
+ withFileTypes: true
1803
+ });
1804
+ for (const entry of entries) {
1805
+ if (!entry.isFile() || NON_RUNTIME_FILE.test(entry.name)) continue;
1806
+ const { mtimeMs } = statSync(join(entry.parentPath, entry.name));
1807
+ if (mtimeMs > newest) newest = mtimeMs;
1808
+ }
1809
+ } catch {
1810
+ return "";
1811
+ }
1812
+ return newest ? `+dist.${Math.trunc(newest)}` : "";
1813
+ }
1814
+ function cachedStamp(stamps, pkgRoot) {
1815
+ let stamp = stamps.get(pkgRoot);
1816
+ if (stamp === void 0) {
1817
+ stamp = linkedBuildStamp(pkgRoot);
1818
+ stamps.set(pkgRoot, stamp);
1819
+ }
1820
+ return stamp;
1821
+ }
1822
+ /**
1823
+ * Resolve the installed version of each spec's owning package, deduped by
1824
+ * package name. Resolution order per spec:
1825
+ * 1. the project itself, when it IS the owning package (a self-vendoring
1826
+ * app has no node_modules self-link);
1827
+ * 2. the project's own node_modules link (works for pnpm-strict and
1828
+ * hoisted layouts alike, and — unlike `require.resolve` — for
1829
+ * ESM-only packages whose exports map has no CJS condition);
1830
+ * 3. Node's own module resolution (covers transitive installs), walking
1831
+ * the entry up to the owning package's package.json.
1832
+ * Unresolvable specs contribute a "missing" sentinel, unknown versions
1833
+ * "unknown".
1834
+ */
1835
+ function resolveDepVersions(dirname$3, specs, stamps = /* @__PURE__ */ new Map()) {
1836
+ const req = createRequire(join(dirname$3, "noop.js"));
1837
+ const seen = {};
1838
+ let selfMeta = null;
288
1839
  for (const spec of specs) {
289
1840
  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);
1841
+ if (pkg in seen) continue;
1842
+ if (selfMeta === null) try {
1843
+ selfMeta = JSON.parse(readFileSync(join(dirname$3, "package.json"), "utf8"));
1844
+ } catch {
1845
+ selfMeta = {};
1846
+ }
1847
+ let version;
1848
+ if (typeof selfMeta.name === "string" && selfMeta.name === pkg && typeof selfMeta.version === "string") version = selfMeta.version;
1849
+ else {
1850
+ version = "missing";
1851
+ try {
1852
+ const pkgRoot = realpathSync(join(dirname$3, "node_modules", pkg));
1853
+ const meta = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8"));
1854
+ version = String(meta.version ?? "unknown") + cachedStamp(stamps, pkgRoot);
1855
+ } catch {
1856
+ try {
1857
+ const entry = req.resolve(spec);
1858
+ let dir = dirname(entry);
1859
+ for (let depth = 0; depth < 8; depth++) {
1860
+ if (existsSync(join(dir, "package.json"))) {
1861
+ const meta = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
1862
+ version = String(meta.version ?? "unknown");
1863
+ break;
1864
+ }
1865
+ const parent = dirname(dir);
1866
+ if (parent === dir) break;
1867
+ dir = parent;
1868
+ }
1869
+ } catch {}
1870
+ }
1871
+ }
1872
+ seen[pkg] = version;
298
1873
  }
1874
+ return seen;
1875
+ }
1876
+ function resolveVersionDigest(versions, own, stamps, build) {
299
1877
  const h = createHash("sha256");
1878
+ h.update(`base:${build.base}\nnodeEnv:${build.nodeEnv}\n`);
300
1879
  const workerHash = createHash("sha256").update(VENDOR_BUILD_WORKER).digest("hex");
301
1880
  h.update(`worker:${workerHash}\n`);
302
- for (const pkg of [...seen.keys()].sort()) h.update(`${pkg}@${seen.get(pkg)}\n`);
1881
+ for (const pkg of Object.keys(versions).sort()) h.update(`${pkg}@${versions[pkg]}\n`);
1882
+ for (const spec of Object.keys(own).sort()) {
1883
+ const stamp = cachedStamp(stamps, ownPackageRoot(own[spec]));
1884
+ h.update(`own:${spec}=${own[spec]}${stamp}\n`);
1885
+ }
303
1886
  return h.digest("hex").slice(0, 16);
304
1887
  }
305
1888
  function sameSet(a, b) {
@@ -307,7 +1890,7 @@ function sameSet(a, b) {
307
1890
  const s = new Set(a);
308
1891
  return b.every((x) => s.has(x));
309
1892
  }
310
- const LOCK_STALE_MS = 5 * 6e4;
1893
+ const LOCK_STALE_MS = 3e5;
311
1894
  const LOCK_HEARTBEAT_MS = 6e4;
312
1895
  const ownerFile = (lockDir) => join(lockDir, "owner");
313
1896
  function lockIsStale(lockDir) {
@@ -382,7 +1965,63 @@ function importTarget$1(value) {
382
1965
  const t = importTarget$1(o[c]);
383
1966
  if (t) return t;
384
1967
  }
385
- return null;
1968
+ return null;
1969
+ }
1970
+ /** The package root at or above `from` that Node would load `pkg` from, or null. */
1971
+ function findPackageRoot(from, pkg) {
1972
+ let dir = from;
1973
+ for (;;) {
1974
+ const candidate = join(dir, "node_modules", pkg);
1975
+ if (existsSync(join(candidate, "package.json"))) return realpathSync(candidate);
1976
+ const parent = dirname(dir);
1977
+ if (parent === dir) return null;
1978
+ dir = parent;
1979
+ }
1980
+ }
1981
+ function ownRoots(own) {
1982
+ const roots = /* @__PURE__ */ new Set();
1983
+ for (const file of Object.values(own)) {
1984
+ const root = ownPackageRoot(file);
1985
+ try {
1986
+ const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
1987
+ if (Object.keys(meta.dependencies ?? {}).length === 0) roots.add(root + sep);
1988
+ } catch {}
1989
+ }
1990
+ return [...roots];
1991
+ }
1992
+ function ownPackageRoot(file) {
1993
+ let dir = dirname(file);
1994
+ for (;;) {
1995
+ try {
1996
+ if (JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).name) return dir;
1997
+ } catch {}
1998
+ const parent = dirname(dir);
1999
+ if (parent === dir) return dir;
2000
+ dir = parent;
2001
+ }
2002
+ }
2003
+ /** Each spec's browser/import entry file when resolved from `from`; unresolvable specs are left out. */
2004
+ function resolveOwnDeps(from, specs) {
2005
+ const out = {};
2006
+ for (const spec of specs) {
2007
+ const { pkg, sub } = parsePkg(spec);
2008
+ const root = findPackageRoot(from, pkg);
2009
+ if (!root) continue;
2010
+ try {
2011
+ const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
2012
+ const key = sub ? `./${sub}` : ".";
2013
+ let target = null;
2014
+ if (meta.exports && typeof meta.exports === "object") {
2015
+ const exp = meta.exports;
2016
+ target = Object.keys(exp).some((k) => k.startsWith(".")) ? key in exp ? importTarget$1(exp[key]) : null : sub ? null : importTarget$1(exp);
2017
+ } else if (typeof meta.exports === "string") target = sub ? null : meta.exports;
2018
+ else if (!sub) target = meta.module ?? meta.main ?? null;
2019
+ if (!target || /\.(css|json|scss)$/.test(target)) continue;
2020
+ const file = join(root, target);
2021
+ if (existsSync(file)) out[spec] = realpathSync(file);
2022
+ } catch {}
2023
+ }
2024
+ return out;
386
2025
  }
387
2026
  function parsePkg(spec) {
388
2027
  if (spec.startsWith("@")) {
@@ -406,11 +2045,16 @@ function parsePkg(spec) {
406
2045
  * `@powerhousedao/design-system/connect/toast`, `zod/v4/core`). Those bare
407
2046
  * imports need their own import-map entry, so expand each listed spec to its
408
2047
  * 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.
2048
+ * prefix. Unresolvable / CSS / JSON targets are skipped.
2049
+ *
2050
+ * A spec whose package isn't installed in `dirname` is dropped entirely
2051
+ * rather than kept for the worker: the worker cannot build an entry for a
2052
+ * missing package (its `await import` and the vite resolution both fail),
2053
+ * and a bare re-export entry would fail the whole vendor build. The
2054
+ * importer of a missing shared dep simply bundles its own copy.
411
2055
  */
412
2056
  function expandIncludeSubpaths(dirname, include) {
413
- const out = new Set(include);
2057
+ const out = /* @__PURE__ */ new Set();
414
2058
  for (const spec of include) {
415
2059
  const { pkg, sub } = parsePkg(spec);
416
2060
  let exp;
@@ -421,6 +2065,7 @@ function expandIncludeSubpaths(dirname, include) {
421
2065
  } catch {
422
2066
  continue;
423
2067
  }
2068
+ out.add(sub ? spec : pkg);
424
2069
  if (!exp || typeof exp !== "object") continue;
425
2070
  const expMap = exp;
426
2071
  const prefixKey = sub ? `./${sub}` : ".";
@@ -431,40 +2076,86 @@ function expandIncludeSubpaths(dirname, include) {
431
2076
  const target = importTarget$1(expMap[key]);
432
2077
  if (!target || /\.(css|json|scss)$/.test(target)) continue;
433
2078
  if (!existsSync(join(pkgRoot, target))) continue;
434
- out.add(key === "." ? pkg : pkg + key.slice(1));
2079
+ const expanded = key === "." ? pkg : pkg + key.slice(1);
2080
+ if (!VENDOR_SKIP_SUBPATHS.has(expanded)) out.add(expanded);
435
2081
  }
436
2082
  }
437
2083
  return [...out];
438
2084
  }
439
2085
  /**
2086
+ * The published specifiers whose entry file the vendor build never emitted.
2087
+ * URLs are base-less (`/__vendor__/x.js`) and resolve inside `vendorDir`.
2088
+ */
2089
+ function missingVendorEntries(vendorDir, imports) {
2090
+ const prefix = VENDOR_URL_PREFIX;
2091
+ return Object.entries(imports).filter(([, url]) => {
2092
+ const rel = url.startsWith(prefix) ? url.slice(12) : url;
2093
+ return !existsSync(join(vendorDir, rel));
2094
+ }).map(([spec, url]) => ({
2095
+ spec,
2096
+ url
2097
+ }));
2098
+ }
2099
+ /**
2100
+ * Rebase the vendor's base-less entry URLs (`/__vendor__/x.js`) onto the
2101
+ * deploy base, so a consumer that resolves them against the page origin lands
2102
+ * under that base rather than the server root. A dynamic-base build keeps its
2103
+ * placeholder, which the runtime substitutes.
2104
+ *
2105
+ * `base` is the app base from `prebuildConnectVendor` callers; a base that
2106
+ * already carries the vendor segment has it dropped first so it is never
2107
+ * doubled.
2108
+ */
2109
+ function withVendorBase(imports, base) {
2110
+ const segment = VENDOR_URL_PREFIX.replace(/^\/+/, "");
2111
+ const appBase = base.endsWith(segment) ? base.slice(0, base.length - segment.length) : base;
2112
+ return Object.fromEntries(Object.entries(imports).map(([spec, url]) => [spec, `${appBase}/${url}`.replace(/([^:])\/{2,}/g, "$1/").replace(/^\/{2,}/, "/")]));
2113
+ }
2114
+ /**
440
2115
  * Build the vendor into a unique temp dir, then atomically swap it into place,
441
2116
  * so a concurrent reader never sees a partial bundle or import-map.json. Runs
442
2117
  * 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.
2118
+ * the parent augments the import map with the version digest + the version
2119
+ * table, writes the runtime shared-deps module, and does the swap.
2120
+ * Returns the published import map + versions, or null on failure.
445
2121
  */
446
- async function buildVendorAtomic(dirname$2, vendorDir, include, external, versionDigest) {
2122
+ async function buildVendorAtomic(dirname$4, vendorDir, include, external, versionDigest, versions, base, nodeEnv, own = {}) {
447
2123
  const parent = dirname(vendorDir);
448
2124
  mkdirSync(parent, { recursive: true });
449
2125
  const tmpDir = mkdtempSync(join(parent, ".ph-vendor.tmp-"));
450
2126
  try {
451
- const { ok, stderr } = await runBuildWorker(dirname$2, tmpDir, include, external);
2127
+ const { ok, stderr } = await runBuildWorker(dirname$4, tmpDir, include, external, base, nodeEnv, own);
452
2128
  const tmpMap = join(tmpDir, "import-map.json");
453
2129
  if (!ok || !existsSync(tmpMap)) {
454
2130
  const detail = stderr.trim();
455
2131
  throw new Error(`vendor build failed${detail ? `:\n${detail}` : " (no output captured)"}`);
456
2132
  }
457
2133
  const meta = JSON.parse(readFileSync(tmpMap, "utf8"));
2134
+ const unbacked = missingVendorEntries(tmpDir, meta.imports);
2135
+ 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
2136
  meta.versionDigest = versionDigest;
2137
+ meta.versions = versions;
2138
+ meta.base = base;
2139
+ meta.nodeEnv = nodeEnv;
2140
+ const sharedDepsSource = `export const imports = ${JSON.stringify(withVendorBase(meta.imports, base))};\nexport const versions = ${JSON.stringify(versions)};\n`;
2141
+ const sharedDepsFile = `shared-deps-${createHash("sha256").update(sharedDepsSource).digest("hex").slice(0, 12)}.js`;
2142
+ writeFileSync(join(tmpDir, sharedDepsFile), sharedDepsSource);
2143
+ writeFileSync(join(tmpDir, "shared-deps.js"), sharedDepsSource);
2144
+ meta.sharedDeps = VENDOR_URL_PREFIX + sharedDepsFile;
459
2145
  writeFileSync(tmpMap, JSON.stringify(meta, null, 2));
460
2146
  const oldDir = `${vendorDir}.old-${process.pid}-${Date.now()}`;
461
2147
  if (existsSync(vendorDir)) renameSync(vendorDir, oldDir);
462
2148
  renameSync(tmpDir, vendorDir);
2149
+ chmodSync(vendorDir, 493);
463
2150
  rmSync(oldDir, {
464
2151
  recursive: true,
465
2152
  force: true
466
2153
  });
467
- return meta.imports;
2154
+ return {
2155
+ imports: meta.imports,
2156
+ versions,
2157
+ sharedDeps: meta.sharedDeps
2158
+ };
468
2159
  } catch (err) {
469
2160
  rmSync(tmpDir, {
470
2161
  recursive: true,
@@ -473,16 +2164,29 @@ async function buildVendorAtomic(dirname$2, vendorDir, include, external, versio
473
2164
  throw err;
474
2165
  }
475
2166
  }
2167
+ function resolveSelfModulePath() {
2168
+ const selfPath = fileURLToPath(import.meta.url);
2169
+ if (!selfPath.endsWith(".ts")) return selfPath;
2170
+ let dir = dirname(selfPath);
2171
+ for (let depth = 0; depth < 4; depth++) {
2172
+ const candidate = join(dir, "dist", "index.mjs");
2173
+ if (existsSync(candidate)) return candidate;
2174
+ const parent = dirname(dir);
2175
+ if (parent === dir) break;
2176
+ dir = parent;
2177
+ }
2178
+ throw new Error("vendor build needs the built builder-tools bundle (dist/index.mjs); build the package first");
2179
+ }
476
2180
  /**
477
2181
  * Spawn a throwaway worker that generates one entry per specifier (CJS deps get
478
2182
  * explicit named re-exports, ESM deps `export *`), `vite build`s them into the
479
2183
  * given out dir, and writes the import map. Captures stdout/stderr so a failure
480
2184
  * is debuggable; the normal path stays quiet.
481
2185
  */
482
- function runBuildWorker(dirname, outDir, include, external) {
2186
+ function runBuildWorker(dirname, outDir, include, external, base, nodeEnv, own = {}) {
483
2187
  const workerPath = join(outDir, "build-worker.mjs");
484
2188
  writeFileSync(workerPath, VENDOR_BUILD_WORKER);
485
- const selfModulePath = fileURLToPath(import.meta.url);
2189
+ const selfModulePath = resolveSelfModulePath();
486
2190
  return new Promise((resolve) => {
487
2191
  const child = spawn(process.execPath, [
488
2192
  workerPath,
@@ -492,7 +2196,13 @@ function runBuildWorker(dirname, outDir, include, external) {
492
2196
  VENDOR_URL_PREFIX,
493
2197
  JSON.stringify(external),
494
2198
  VENDOR_DYNAMIC_BASE,
495
- selfModulePath
2199
+ selfModulePath,
2200
+ base,
2201
+ nodeEnv,
2202
+ JSON.stringify({
2203
+ files: own,
2204
+ roots: ownRoots(own)
2205
+ })
496
2206
  ], {
497
2207
  cwd: dirname,
498
2208
  stdio: [
@@ -522,14 +2232,27 @@ function runBuildWorker(dirname, outDir, include, external) {
522
2232
  * The vendor build worker, written to disk and run as a subprocess. Loads
523
2233
  * `vite` from the project and `connectDynamicBasePlugin` from builder-tools' own
524
2234
  * built bundle (selfModulePath). argv: dirname, vendorDir, includeJSON,
525
- * urlPrefix, externalJSON, dynamicBase, selfModulePath.
2235
+ * urlPrefix, externalJSON, dynamicBase, selfModulePath, base (app base),
2236
+ * nodeEnv.
526
2237
  */
527
2238
  const VENDOR_BUILD_WORKER = `
528
2239
  import { createRequire } from 'node:module';
529
2240
  import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
530
2241
  import { join, isAbsolute } from 'node:path';
531
2242
  import { fileURLToPath, pathToFileURL } from 'node:url';
532
- const [dirname, vendorDir, includeJSON, urlPrefix, externalJSON, dynamicBase, selfModulePath] = process.argv.slice(2);
2243
+ const [dirname, vendorDir, includeJSON, urlPrefix, externalJSON, dynamicBase, selfModulePath, baseArg, nodeEnvArg, ownJSON] = process.argv.slice(2);
2244
+ // ownDeps: spec -> absolute entry file, plus each one's package root.
2245
+ const { files: own = {}, roots: ownRootList = [] } = JSON.parse(ownJSON || '{}');
2246
+ // One chunk per own-dep package: split between an entry and a shared chunk, a
2247
+ // barrel can re-export from the entry and run before the classes it extends.
2248
+ const ownGroups = ownRootList.map((root, i) => ({ name: 'own-' + i, test: (id) => id.startsWith(root) }));
2249
+ // Trailing argv are optional (older callers): base defaults to the dynamic
2250
+ // placeholder behavior, nodeEnv to development. baseArg is the APP base —
2251
+ // the same string the app build uses; the build base appends the vendor
2252
+ // segment so emitted asset URLs land under <app-base>__vendor__/.
2253
+ const segment = urlPrefix.replace(/^\\/+/, '');
2254
+ const base = baseArg ? baseArg + segment : dynamicBase;
2255
+ const nodeEnv = nodeEnvArg ?? 'development';
533
2256
  const include = JSON.parse(includeJSON);
534
2257
  const external = JSON.parse(externalJSON ?? '[]');
535
2258
  const externalSet = new Set(external);
@@ -547,23 +2270,42 @@ const RESERVED = new Set('enum void null function in instanceof typeof new delet
547
2270
  const input = {};
548
2271
  for (const spec of include) {
549
2272
  const name = entryName(spec);
2273
+ const from = own[spec] ?? spec;
550
2274
  let src;
551
2275
  try {
552
2276
  // Import the bare spec (not reqProj.resolve(spec)) so Node picks the same
553
2277
  // import/browser-condition module the build resolves — resolving first can
554
2278
  // pick a CJS sibling whose default-export shape differs from the ESM build.
555
- const ns = await import(spec);
2279
+ const ns = await import(own[spec] ? pathToFileURL(own[spec]).href : spec);
556
2280
  // Only fall back to re-exporting from default when the module exposes NO
557
2281
  // top-level named exports (a true CJS-interop module). If it does (e.g. zod
558
2282
  // exposes \`z\`), \`export *\` captures them; destructuring default would miss
559
2283
  // top-level names that aren't keys of the default object.
560
2284
  const named = Object.keys(ns).filter((k) => k !== 'default');
561
2285
  const cjs = named.length === 0 && ns.default && typeof ns.default === 'object';
562
- if (cjs) {
2286
+ // A strict entry keeps every export, and zod's \`locales\` (also reachable via \`z\`) pins
2287
+ // ~50 locales; publish them without it. zod/locales stays its own entry.
2288
+ const zodNs = (spec === 'zod' || spec.startsWith('zod/')) && !spec.includes('locales') && named.includes('locales');
2289
+ if (zodNs) {
2290
+ const keep = named.filter((k) => k !== 'locales' && k !== 'z' && /^[A-Za-z_$][\\w$]*$/.test(k));
2291
+ // \`core\` is zod/v4/core's namespace, which exports locales too: rebuild it without them.
2292
+ const coreKeys = keep.includes('core') ? Object.keys(await import('zod/v4/core')).filter((k) => k !== 'locales' && k !== 'default') : [];
2293
+ const reexport = keep.filter((k) => !(k === 'core' && coreKeys.length));
2294
+ src = 'export { ' + reexport.join(', ') + ' } from ' + JSON.stringify(from) + ';\\n'
2295
+ + 'import { ' + reexport.map((k) => k + ' as __z_' + k).join(', ') + ' } from ' + JSON.stringify(from) + ';\\n';
2296
+ if (coreKeys.length) {
2297
+ src += 'import { ' + coreKeys.map((k) => k + ' as __c_' + k).join(', ') + ' } from "zod/v4/core";\\n'
2298
+ + 'const __z_core = Object.freeze({ ' + coreKeys.map((k) => JSON.stringify(k) + ': __c_' + k).join(', ') + ' });\\n'
2299
+ + 'export { __z_core as core };\\n';
2300
+ }
2301
+ src += 'const z = Object.freeze({ ' + keep.map((k) => JSON.stringify(k) + ': __z_' + k).join(', ') + ' });\\n'
2302
+ + (named.includes('z') ? 'export { z };\\n' : '')
2303
+ + (('default' in ns) && ns.default === ns.z ? 'export { z as default };\\n' : '');
2304
+ } else if (cjs) {
563
2305
  const names = Object.keys(ns.default).filter((k) => k !== 'default' && k !== '__esModule' && /^[A-Za-z_$][\\w$]*$/.test(k));
564
2306
  const plain = names.filter((n) => !RESERVED.has(n));
565
2307
  const reserved = names.filter((n) => RESERVED.has(n));
566
- src = 'import d from ' + JSON.stringify(spec) + ';\\nexport default d;\\n'
2308
+ src = 'import d from ' + JSON.stringify(from) + ';\\nexport default d;\\n'
567
2309
  + (plain.length ? 'export const { ' + plain.join(', ') + ' } = d;\\n' : '');
568
2310
  // reserved words are invalid as const-binding names but valid as export
569
2311
  // aliases (export { x as enum }).
@@ -571,11 +2313,11 @@ for (const spec of include) {
571
2313
  src += 'const __r' + i + ' = d[' + JSON.stringify(n) + '];\\nexport { __r' + i + ' as ' + n + ' };\\n';
572
2314
  });
573
2315
  } else {
574
- src = 'export * from ' + JSON.stringify(spec) + ';\\n'
575
- + (('default' in ns) ? 'export { default } from ' + JSON.stringify(spec) + ';\\n' : '');
2316
+ src = 'export * from ' + JSON.stringify(from) + ';\\n'
2317
+ + (('default' in ns) ? 'export { default } from ' + JSON.stringify(from) + ';\\n' : '');
576
2318
  }
577
2319
  } catch {
578
- src = 'export * from ' + JSON.stringify(spec) + ';\\n';
2320
+ src = 'export * from ' + JSON.stringify(from) + ';\\n';
579
2321
  }
580
2322
  const file = join(srcDir, name + '.js');
581
2323
  writeFileSync(file, src);
@@ -600,16 +2342,19 @@ const phVendorResolve = {
600
2342
  return resolved;
601
2343
  },
602
2344
  };
603
- await build({
2345
+ const result = await build({
604
2346
  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,
2347
+ // Caller-provided build base (or the dynamic placeholder default):
2348
+ // connectDynamicBasePlugin rewrites emitted chunk/asset URLs to resolve
2349
+ // against the deploy base at serve time.
2350
+ base,
608
2351
  define: {
609
- 'process.env.NODE_ENV': '"development"',
2352
+ 'process.env.NODE_ENV': JSON.stringify(nodeEnv),
610
2353
  // BASE_URL resolves to the deploy base (not the vendor prefix) so vendored
611
2354
  // Connect's router basename + BASE_URL-relative fetches use the right path.
612
- 'import.meta.env.BASE_URL': JSON.stringify(DYNAMIC_BASE_PLACEHOLDER),
2355
+ // The app base when provided (concrete or placeholder), the placeholder
2356
+ // otherwise (dev flow — rewritten at serve time by the dynamic-base plugin).
2357
+ 'import.meta.env.BASE_URL': JSON.stringify(baseArg ?? DYNAMIC_BASE_PLACEHOLDER),
613
2358
  },
614
2359
  // phVendorResolve (pre) resolves bares from the worker; esmExternalRequirePlugin owns
615
2360
  // react/virtual externalization; connectDynamicBasePlugin (post) rewrites the placeholder base.
@@ -618,199 +2363,750 @@ await build({
618
2363
  // segment so the worker recovers the deploy base, not the vendor prefix.
619
2364
  worker: { format: 'es', plugins: () => [connectDynamicBasePlugin({ forWorker: true, workerStripPrefix: urlPrefix.replace(/^\\/+/, '') })] },
620
2365
  build: {
621
- outDir: vendorDir, emptyOutDir: false, minify: false, target: 'esnext', cssCodeSplit: true,
2366
+ // Production ships this to every visitor, so minify it like the app's own
2367
+ // chunks; dev keeps readable output and the faster build.
2368
+ outDir: vendorDir, emptyOutDir: false, minify: nodeEnv === 'production', target: 'esnext', cssCodeSplit: true,
622
2369
  rollupOptions: {
623
2370
  input, preserveEntrySignatures: 'strict',
624
- output: { format: 'es', entryFileNames: '[name].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },
2371
+ // Content-hashed entry names: each build's import map points at new URLs.
2372
+ output: { format: 'es', entryFileNames: '[name]-[hash].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]', ...(ownGroups.length ? { codeSplitting: { groups: ownGroups } } : {}) },
625
2373
  },
626
2374
  },
627
2375
  });
628
2376
  rmSync(srcDir, { recursive: true, force: true });
2377
+ const emitted = {};
2378
+ for (const out of Array.isArray(result) ? result : [result]) {
2379
+ for (const chunk of out?.output ?? []) {
2380
+ if (chunk.type === 'chunk' && chunk.isEntry) emitted[chunk.name] = chunk.fileName;
2381
+ }
2382
+ }
629
2383
  const imports = {};
630
- for (const spec of include) imports[spec] = urlPrefix + entryName(spec) + '.js';
2384
+ // An entry the build never emitted keeps its unhashed name; the caller reports it as missing.
2385
+ for (const spec of include) imports[spec] = urlPrefix + (emitted[entryName(spec)] ?? entryName(spec) + '.js');
631
2386
  writeFileSync(join(vendorDir, 'import-map.json'), JSON.stringify({ include, external, imports }, null, 2));
632
2387
  `;
633
2388
  //#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");
2389
+ //#region connect-utils/reactor-worker-build.ts
2390
+ /**
2391
+ * Prebuild Connect's reactor SharedWorker into a browser-loadable bundle.
2392
+ *
2393
+ * The published `@powerhousedao/connect` dist ships `reactor.worker.js` as a
2394
+ * library artifact: its dependencies are externalized onto bare specifiers
2395
+ * (`@powerhousedao/reactor`, `kysely`, ...). The page resolves those through
2396
+ * its `<script type="importmap">`, but import maps are a document feature —
2397
+ * a worker never inherits one and no Worker/SharedWorker constructor option
2398
+ * can supply one. A bare specifier inside a worker is unresolvable by the
2399
+ * platform, so the shipped file can never run as a worker script.
2400
+ *
2401
+ * This module builds the worker's module graph into a self-contained bundle
2402
+ * (one `vite build` in a throwaway subprocess, same pattern as the vendor
2403
+ * prebuild). Two modes:
2404
+ *
2405
+ * - With `vendorImports` (production builds that also ship the `__vendor__/`
2406
+ * bundle): specifiers present in the vendor import map are externalized and
2407
+ * rewritten to `../__vendor__/<entry>.js`. The worker bundle is served as a
2408
+ * sibling of `__vendor__/`, so those relative imports hit the exact URLs
2409
+ * the page's import map uses — one fetch and one HTTP-cache entry per
2410
+ * shared dep for the page and the worker together.
2411
+ * - Without (dev servers, `PH_CONNECT_VENDOR=0` builds): everything is
2412
+ * bundled; the worker is self-contained.
2413
+ *
2414
+ * The build uses Vite's relative base (`"./"`), so emitted chunk and asset
2415
+ * URLs resolve against the worker script's own URL. That sidesteps the
2416
+ * dynamic-base machinery entirely: the bundle works under any deploy base,
2417
+ * concrete or proxy-substituted, as long as it is served under
2418
+ * `<app-base>/__reactor_worker__/`.
2419
+ */
2420
+ /** URL prefix the worker bundle is served under, next to `__vendor__/`. */
2421
+ const REACTOR_WORKER_URL_PREFIX = "/__reactor_worker__/";
2422
+ /** Entry filename of the bundle; the tab constructs its SharedWorker from it. */
2423
+ const REACTOR_WORKER_ENTRY = "reactor.worker.js";
2424
+ /** Metadata file the cache check reads; lives inside the bundle dir. */
2425
+ const META_FILE = "worker-meta.json";
2426
+ /** Content-Type for the extensions the worker build emits; JS is the default. */
2427
+ const REACTOR_WORKER_MIME = {
2428
+ ".map": "application/json",
2429
+ ".json": "application/json",
2430
+ ".wasm": "application/wasm",
2431
+ ".data": "application/octet-stream"
2432
+ };
2433
+ /**
2434
+ * The installed Connect dist's worker entry, or null when the installed
2435
+ * version predates the worker (the feature is then unavailable, not broken).
2436
+ */
2437
+ function resolveReactorWorkerSource(dirname) {
2438
+ try {
2439
+ const candidate = join(realpathSync(join(dirname, "node_modules", "@powerhousedao/connect")), "dist", REACTOR_WORKER_ENTRY);
2440
+ return existsSync(candidate) ? candidate : null;
2441
+ } catch {
2442
+ return null;
2443
+ }
639
2444
  }
640
- function resolvePackage(packageName, root = process.cwd()) {
641
- return createRequire(root).resolve(packageName, { paths: [root] });
2445
+ /** `/__vendor__/<entry>.js` -> `../__vendor__/<entry>.js` (sibling dirs). */
2446
+ function vendorRelativePath(vendorUrl) {
2447
+ return `../__vendor__/${vendorUrl.slice(vendorUrl.lastIndexOf("/") + 1)}`;
642
2448
  }
643
- function resolveConnectPackageJson(root = process.cwd()) {
2449
+ function importSpecifiers(code) {
2450
+ initSync();
2451
+ const [imports] = parse(code);
2452
+ return imports.flatMap((specifier) => specifier.d === -2 || specifier.n === void 0 ? [] : [specifier.n]);
2453
+ }
2454
+ /**
2455
+ * Module specifiers a worker cannot resolve: anything that is not relative,
2456
+ * root-relative, or an http(s)/data/blob URL. Used as a post-build guard so a
2457
+ * leftover bare (or `node:`) import fails the build with a name instead of
2458
+ * shipping a worker that dies on its first import statement.
2459
+ */
2460
+ function findDisallowedSpecifiers(code) {
2461
+ const found = /* @__PURE__ */ new Set();
2462
+ for (const spec of importSpecifiers(code)) if (!spec.startsWith("./") && !spec.startsWith("../") && !spec.startsWith("/") && !/^(https?:|data:|blob:)/.test(spec)) found.add(spec);
2463
+ return [...found].sort();
2464
+ }
2465
+ /**
2466
+ * Fallback list of packages whose BUILT dist shapes the worker bundle's output,
2467
+ * used only when the installed Connect's package.json cannot be read (see
2468
+ * {@link upstreamWorkerPackages}).
2469
+ */
2470
+ const FALLBACK_UPSTREAM_WORKER_PACKAGES = ["@powerhousedao/reactor", "@powerhousedao/reactor-browser"];
2471
+ /** Dependency scopes whose installed dist can change the bundle's output. */
2472
+ const UPSTREAM_SCOPES = ["@powerhousedao/", "@renown/"];
2473
+ /**
2474
+ * Packages whose BUILT dist shapes the worker bundle's output even when
2475
+ * connect's own dist/reactor.worker.js entry file did not change.
2476
+ *
2477
+ * That entry is a library artifact whose bare imports this build resolves
2478
+ * through node_modules at BUILD time, so a rebuilt dist anywhere in its
2479
+ * closure changes the bundle output without touching the entry file's own
2480
+ * size/mtime. The list is DERIVED from the installed Connect's own
2481
+ * dependencies rather than hardcoded: the bundle pulls `@renown/sdk`,
2482
+ * `@powerhousedao/powerhouse-vetra-packages` and `@powerhousedao/shared` out
2483
+ * of node_modules too, and a hardcoded pair left every one of those able to be
2484
+ * rebuilt behind a cache hit. Connect's dependency list is the cheap stand-in
2485
+ * for the resolved bundle graph: every workspace package the worker can reach
2486
+ * is reachable through it, and a package not in the bundle only costs a readdir.
2487
+ */
2488
+ function upstreamWorkerPackages(dirname) {
2489
+ const connectDir = resolveWorkspacePackageDir(dirname, "@powerhousedao/connect");
2490
+ if (!connectDir) return [...FALLBACK_UPSTREAM_WORKER_PACKAGES];
2491
+ let meta;
644
2492
  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);
2493
+ meta = JSON.parse(readFileSync(join(connectDir, "package.json"), "utf8"));
2494
+ } catch {
2495
+ return [...FALLBACK_UPSTREAM_WORKER_PACKAGES];
2496
+ }
2497
+ const names = Object.keys(meta.dependencies ?? {}).filter((name) => UPSTREAM_SCOPES.some((scope) => name.startsWith(scope)));
2498
+ for (const name of FALLBACK_UPSTREAM_WORKER_PACKAGES) if (!names.includes(name)) names.push(name);
2499
+ return names.sort();
2500
+ }
2501
+ /**
2502
+ * This module's own installed version, read by walking up from its file to
2503
+ * the nearest `package.json` named "@powerhousedao/builder-tools" (same
2504
+ * technique as `build-hash.ts`'s `readConnectVersion`: builder-tools'
2505
+ * `exports` map has no `./package.json` subpath, so node resolution can't
2506
+ * get there). Works whether this runs from source (tests, this monorepo) or
2507
+ * the built dist.
2508
+ */
2509
+ function resolveOwnPackageVersion() {
2510
+ try {
2511
+ let dir = dirname(fileURLToPath(import.meta.url));
2512
+ for (;;) {
2513
+ try {
2514
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
2515
+ if (pkg.name === "@powerhousedao/builder-tools") return pkg.version ?? "unknown";
2516
+ } catch {}
2517
+ const parent = dirname(dir);
2518
+ if (parent === dir) break;
2519
+ dir = parent;
2520
+ }
2521
+ } catch {}
2522
+ return "unknown";
2523
+ }
2524
+ /**
2525
+ * This package's own version, computed once. Folded into the worker bundle
2526
+ * cache key so a builder-tools release — which can change how the bundle is
2527
+ * built (anything in this module beyond {@link WORKER_BUILD_WORKER} itself,
2528
+ * e.g. `workerSafeVendorImports`, the resolve plugin) — invalidates bundles
2529
+ * a prior builder-tools version cached.
2530
+ */
2531
+ const BUILDER_TOOLS_VERSION = resolveOwnPackageVersion();
2532
+ /**
2533
+ * A workspace package's real directory, resolved the way Node's resolver
2534
+ * would (through `node_modules`), or null when it is not installed (e.g. a
2535
+ * non-monorepo consumer project — graceful, not an error). pnpm's
2536
+ * node_modules symlinks resolve to the real package directory, so this
2537
+ * reflects the monorepo's actual dist state, not a stale symlink target.
2538
+ */
2539
+ function resolveWorkspacePackageDir(dirname, pkgName) {
2540
+ try {
2541
+ return realpathSync(join(dirname, "node_modules", ...pkgName.split("/")));
2542
+ } catch {
650
2543
  return null;
651
2544
  }
652
2545
  }
653
2546
  /**
654
- * Finds the dist dir of Connect on the local machine
2547
+ * Cheap content fingerprint of a directory's immediate files: no file bytes
2548
+ * are read, just each entry's name/size/mtime, so it stays fast even for a
2549
+ * large dist. Sensitive to a rebuild in the common cases: Vite's
2550
+ * content-hashed chunk filenames change the name itself; a stable-named file
2551
+ * (an entry point) changes size or mtime. Bounded (`maxFiles`) so a
2552
+ * pathological directory cannot make this slow — deliberately not a
2553
+ * full-tree hash.
2554
+ *
2555
+ * The names are sorted BEFORE the bound is applied, so the subset the bound
2556
+ * keeps is the same subset on every run: readdir order is unspecified, and
2557
+ * truncating it first made the fingerprint of a directory past the bound a
2558
+ * function of whatever order the filesystem happened to report.
655
2559
  */
656
- function resolveConnectBundle(root = process.cwd()) {
657
- const connectIndexPath = resolvePackage("@powerhousedao/connect", root);
658
- return join(connectIndexPath.substring(0, connectIndexPath.indexOf("connect") + 7), "dist/");
2560
+ function distDirFingerprint(dir, maxFiles = 1e3) {
2561
+ try {
2562
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => e.name).sort().slice(0, maxFiles).map((name) => {
2563
+ const stat = statSync(join(dir, name));
2564
+ return `${name}:${stat.size}:${Math.round(stat.mtimeMs)}`;
2565
+ }).join("|");
2566
+ } catch {
2567
+ return "unreadable";
2568
+ }
659
2569
  }
660
- function resolveConnectPublicDir(root = process.cwd()) {
661
- const connectIconPath = resolvePackage("@powerhousedao/connect/public/icon.ico", root);
662
- return path.join(connectIconPath, "../");
2570
+ function computeSourceDigest(dirname, entryPath, vendorDir, builderToolsVersion = BUILDER_TOOLS_VERSION) {
2571
+ const h = createHash("sha256");
2572
+ h.update(`builder:${WORKER_BUILD_WORKER_HASH}\n`);
2573
+ h.update(`builder-tools:${builderToolsVersion}\n`);
2574
+ try {
2575
+ const pkgRoot = resolveWorkspacePackageDir(dirname, "@powerhousedao/connect");
2576
+ if (!pkgRoot) throw new Error("unresolved");
2577
+ const meta = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8"));
2578
+ h.update(`connect:${meta.version ?? "unknown"}\n`);
2579
+ } catch {
2580
+ h.update("connect:unresolved\n");
2581
+ }
2582
+ try {
2583
+ const stat = statSync(entryPath);
2584
+ h.update(`entry:${stat.size}:${Math.round(stat.mtimeMs)}\n`);
2585
+ } catch {
2586
+ h.update("entry:unstatable\n");
2587
+ }
2588
+ for (const pkg of upstreamWorkerPackages(dirname)) {
2589
+ const pkgDir = resolveWorkspacePackageDir(dirname, pkg);
2590
+ h.update(`${pkg}:${pkgDir ? distDirFingerprint(join(pkgDir, "dist")) : "unresolved"}\n`);
2591
+ }
2592
+ if (vendorDir) try {
2593
+ h.update(`vendor:${createHash("sha256").update(readFileSync(join(vendorDir, "import-map.json"))).digest("hex")}\n`);
2594
+ } catch {
2595
+ h.update("vendor:unreadable\n");
2596
+ }
2597
+ return h.digest("hex").slice(0, 16);
2598
+ }
2599
+ function vendorKeyOf(vendorImports) {
2600
+ const entries = Object.entries(vendorImports).sort(([a], [b]) => a.localeCompare(b));
2601
+ return createHash("sha256").update(JSON.stringify(entries)).digest("hex").slice(0, 16);
2602
+ }
2603
+ function readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv) {
2604
+ if (!existsSync(metaPath)) return false;
2605
+ try {
2606
+ const cached = JSON.parse(readFileSync(metaPath, "utf8"));
2607
+ return cached.sourceDigest === sourceDigest && cached.vendorKey === vendorKey && cached.nodeEnv === nodeEnv && existsSync(join(dirname(metaPath), "reactor.worker.js"));
2608
+ } catch {
2609
+ return false;
2610
+ }
2611
+ }
2612
+ /** Content digest of a directory tree (relative paths + bytes; source maps skipped). */
2613
+ function directoryContentDigest(dir) {
2614
+ const h = createHash("sha256");
2615
+ const files = readdirSync(dir, {
2616
+ recursive: true,
2617
+ withFileTypes: true
2618
+ }).filter((e) => e.isFile() && !e.name.endsWith(".map")).map((e) => join(e.parentPath, e.name)).sort();
2619
+ for (const file of files) {
2620
+ h.update(`${file.slice(dir.length).split("\\").join("/")}\n`);
2621
+ h.update(readFileSync(file));
2622
+ }
2623
+ return h.digest("hex").slice(0, 16);
2624
+ }
2625
+ async function waitForWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv, lockDir) {
2626
+ const deadline = Date.now() + LOCK_STALE_MS;
2627
+ while (Date.now() < deadline) {
2628
+ if (readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv)) return true;
2629
+ if (!existsSync(lockDir)) return readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv);
2630
+ await new Promise((r) => setTimeout(r, 250));
2631
+ }
2632
+ return false;
663
2633
  }
664
2634
  /**
665
- * Copies the Connect dist dir to the target path
2635
+ * Build the worker bundle (once, in a throwaway subprocess) into `outDir`.
2636
+ * Idempotent: reuses a cached bundle built from the same connect dist, vendor
2637
+ * mapping, and builder logic. Returns null on failure (`errorRef` carries the
2638
+ * cause) or when the installed Connect has no worker entry.
666
2639
  */
667
- function copyConnect(sourcePath, targetPath) {
2640
+ async function prebuildReactorWorker(options) {
2641
+ const entryPath = options.entryPath ?? resolveReactorWorkerSource(options.dirname);
2642
+ if (!entryPath) {
2643
+ if (options.errorRef) options.errorRef.message = "the installed @powerhousedao/connect ships no dist/reactor.worker.js";
2644
+ return null;
2645
+ }
2646
+ const vendorImports = options.vendor ? workerSafeVendorImports(options.vendor.dir, options.vendor.imports) : {};
2647
+ const nodeEnv = options.nodeEnv ?? "development";
2648
+ const outDir = options.outDir;
2649
+ const metaPath = join(outDir, META_FILE);
2650
+ const sourceDigest = computeSourceDigest(options.dirname, entryPath, options.vendor?.dir);
2651
+ const vendorKey = vendorKeyOf(vendorImports);
2652
+ const result = {
2653
+ outDir,
2654
+ entry: REACTOR_WORKER_ENTRY,
2655
+ sourceDigest,
2656
+ vendorImports
2657
+ };
668
2658
  try {
669
- fs.rmSync(targetPath, {
2659
+ if (readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv)) return result;
2660
+ const lockDir = `${outDir}.lock`;
2661
+ const lock = acquireLock(lockDir);
2662
+ if (!lock) return await waitForWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv, lockDir) ? result : null;
2663
+ try {
2664
+ if (readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv)) return result;
2665
+ await buildWorkerAtomic(options.dirname, outDir, entryPath, vendorImports, nodeEnv, {
2666
+ sourceDigest,
2667
+ vendorKey,
2668
+ nodeEnv
2669
+ });
2670
+ return result;
2671
+ } finally {
2672
+ releaseLock(lock);
2673
+ }
2674
+ } catch (err) {
2675
+ if (options.errorRef) options.errorRef.message = err instanceof Error ? err.message : String(err);
2676
+ return null;
2677
+ }
2678
+ }
2679
+ async function buildWorkerAtomic(dirname$2, outDir, entryPath, vendorImports, nodeEnv, meta) {
2680
+ const parent = dirname(outDir);
2681
+ mkdirSync(parent, { recursive: true });
2682
+ const tmpDir = mkdtempSync(join(parent, ".ph-reactor-worker.tmp-"));
2683
+ try {
2684
+ const { ok, stderr } = await runWorkerBuild(dirname$2, tmpDir, { "reactor.worker": entryPath }, vendorImports, nodeEnv);
2685
+ if (!ok || !existsSync(join(tmpDir, "reactor.worker.js"))) {
2686
+ const detail = stderr.trim();
2687
+ throw new Error(`reactor worker build failed${detail ? `:\n${detail}` : " (no output captured)"}`);
2688
+ }
2689
+ assertWorkerResolvable(tmpDir);
2690
+ writeFileSync(join(tmpDir, META_FILE), JSON.stringify(meta, null, 2));
2691
+ publishDirAtomic(tmpDir, outDir);
2692
+ } catch (err) {
2693
+ rmSync(tmpDir, {
670
2694
  recursive: true,
671
2695
  force: true
672
2696
  });
673
- fs.cpSync(sourcePath, targetPath, { recursive: true });
674
- } catch (error) {
675
- console.error(`❌ Error copying ${sourcePath} to ${targetPath}:`, error);
2697
+ throw err;
2698
+ }
2699
+ }
2700
+ /** Replace `outDir` with the finished `tmpDir`, old contents removed last. */
2701
+ function publishDirAtomic(tmpDir, outDir) {
2702
+ const oldDir = `${outDir}.old-${process.pid}-${Date.now()}`;
2703
+ if (existsSync(outDir)) renameSync(outDir, oldDir);
2704
+ renameSync(tmpDir, outDir);
2705
+ chmodSync(outDir, 493);
2706
+ rmSync(oldDir, {
2707
+ recursive: true,
2708
+ force: true
2709
+ });
2710
+ }
2711
+ function findRelativeSpecifiers(code) {
2712
+ return [...new Set(importSpecifiers(code).filter((spec) => spec.startsWith("./") || spec.startsWith("../")))];
2713
+ }
2714
+ function normalizeBundlePath(fromFile, spec) {
2715
+ const segments = fromFile.split("/").slice(0, -1);
2716
+ for (const part of spec.split("/")) {
2717
+ if (part === "" || part === ".") continue;
2718
+ if (part === "..") {
2719
+ if (segments.length === 0) return "";
2720
+ segments.pop();
2721
+ continue;
2722
+ }
2723
+ segments.push(part);
676
2724
  }
2725
+ return segments.join("/");
677
2726
  }
678
2727
  /**
679
- * Backs up the index.html file
2728
+ * Scan the emitted JS files REACHABLE from the entry via import statements
2729
+ * for specifiers a worker cannot resolve. Vendor externals were rewritten to
2730
+ * ../__vendor__/ relative paths, so anything bare that survives in the graph
2731
+ * is a real defect.
680
2732
  *
681
- * Needed when running the Connect Studio dev server on Windows
2733
+ * Deliberately a graph walk, not a directory walk: the bundled reactor code
2734
+ * carries `new URL(..., import.meta.url)` references to its node
2735
+ * worker-thread entries (executor/projection workers), which Vite emits as
2736
+ * stray assets full of node-only imports. They are unreachable dead weight in
2737
+ * a browser bundle — the production vendor output tolerates the same files —
2738
+ * and must not fail the build.
682
2739
  */
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]);
2740
+ function findBundleSpecifierOffenders(bundleDir, entry = REACTOR_WORKER_ENTRY) {
2741
+ const offenders = [];
2742
+ walkBundleGraph(bundleDir, entry, (file, code) => {
2743
+ const specs = findDisallowedSpecifiers(code);
2744
+ if (specs.length > 0) offenders.push({
2745
+ file,
2746
+ specs
2747
+ });
2748
+ return true;
2749
+ });
2750
+ return offenders;
688
2751
  }
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;
2752
+ function walkBundleGraph(bundleDir, entry, visit) {
2753
+ const seen = /* @__PURE__ */ new Set();
2754
+ const queue = [entry];
2755
+ while (queue.length > 0) {
2756
+ const rel = queue.shift();
2757
+ if (seen.has(rel)) continue;
2758
+ seen.add(rel);
2759
+ const full = join(bundleDir, rel);
2760
+ if (!existsSync(full) || statSync(full).isDirectory()) continue;
2761
+ if (!rel.endsWith(".js") && !rel.endsWith(".mjs")) continue;
2762
+ const code = readFileSync(full, "utf8");
2763
+ if (!visit(rel, code)) return false;
2764
+ for (const spec of findRelativeSpecifiers(code)) {
2765
+ const next = normalizeBundlePath(rel, spec);
2766
+ if (next) queue.push(next);
696
2767
  }
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;
2768
+ }
2769
+ return true;
2770
+ }
2771
+ function assertWorkerResolvable(bundleDir) {
2772
+ const offenders = findBundleSpecifierOffenders(bundleDir);
2773
+ 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"));
2774
+ }
2775
+ const WORKER_UNSAFE_MARKERS = ["__PH_DYNAMIC_BASE__", "vite:preloadError"];
2776
+ /** The page-only markers present in `code`, in a fixed order. */
2777
+ function findWorkerUnsafeMarkers(code) {
2778
+ return WORKER_UNSAFE_MARKERS.filter((marker) => code.includes(marker));
2779
+ }
2780
+ /**
2781
+ * The subset of the vendor's entries a worker may import.
2782
+ *
2783
+ * The vendor build keeps the React family external: its chunks carry bare
2784
+ * `import "react"` statements that the PAGE resolves through its import map.
2785
+ * A worker resolves no import map, so externalizing a vendor spec whose chunk
2786
+ * closure reaches such an import would kill the worker on its first load —
2787
+ * and the chunk graph is shared across vendor entries, so even a React-free
2788
+ * module (e.g. an rpc subpath) can be entangled with React through a shared
2789
+ * chunk. The vendor is also built for the page: a dynamic-base build rewrites
2790
+ * its asset URLs onto a global only the page sets, and its dynamic imports go
2791
+ * through Vite's preload helper, which needs `document`. Each entry's own
2792
+ * closure inside the vendor dir decides: clean closure, worker-safe; anything
2793
+ * bare or page-only in it (see {@link findWorkerUnsafeMarkers}), or a missing
2794
+ * entry file, bundled into the worker instead.
2795
+ */
2796
+ function workerSafeVendorImports(vendorDir, vendorImports) {
2797
+ const safe = {};
2798
+ for (const [spec, url] of Object.entries(vendorImports)) {
2799
+ const entryFile = url.slice(url.lastIndexOf("/") + 1);
2800
+ if (!existsSync(join(vendorDir, entryFile))) continue;
2801
+ if (walkBundleGraph(vendorDir, entryFile, (_file, code) => {
2802
+ try {
2803
+ return findDisallowedSpecifiers(code).length === 0 && findWorkerUnsafeMarkers(code).length === 0;
2804
+ } catch {
2805
+ return false;
703
2806
  }
2807
+ })) safe[spec] = url;
2808
+ }
2809
+ return safe;
2810
+ }
2811
+ /**
2812
+ * Builds arbitrary worker-loadable entries with the worker build config.
2813
+ * Exported for the local-package bundles, which need the same self-contained
2814
+ * output and vendor externalization at a different depth.
2815
+ */
2816
+ function runWorkerBuildEntries(dirname, outDir, entries, vendorImports, nodeEnv, vendorPrefix = "../__vendor__/") {
2817
+ return runWorkerBuild(dirname, outDir, entries, vendorImports, nodeEnv, vendorPrefix);
2818
+ }
2819
+ function runWorkerBuild(dirname, outDir, entries, vendorImports, nodeEnv, vendorPrefix = "../__vendor__/") {
2820
+ const workerPath = join(outDir, "build-worker.mjs");
2821
+ writeFileSync(workerPath, WORKER_BUILD_WORKER);
2822
+ return new Promise((resolve) => {
2823
+ const child = spawn(process.execPath, [
2824
+ workerPath,
2825
+ dirname,
2826
+ outDir,
2827
+ JSON.stringify(entries),
2828
+ JSON.stringify(vendorImports),
2829
+ nodeEnv,
2830
+ resolveBuilderVite() ?? "",
2831
+ vendorPrefix
2832
+ ], {
2833
+ cwd: dirname,
2834
+ stdio: [
2835
+ "ignore",
2836
+ "pipe",
2837
+ "pipe"
2838
+ ]
2839
+ });
2840
+ let stderr = "";
2841
+ child.stdout.on("data", (d) => {
2842
+ stderr += String(d);
704
2843
  });
2844
+ child.stderr.on("data", (d) => {
2845
+ stderr += String(d);
2846
+ });
2847
+ child.on("exit", (code) => {
2848
+ rmSync(workerPath, { force: true });
2849
+ resolve({
2850
+ ok: code === 0,
2851
+ stderr
2852
+ });
2853
+ });
2854
+ child.on("error", (e) => resolve({
2855
+ ok: false,
2856
+ stderr: String(e)
2857
+ }));
705
2858
  });
706
2859
  }
707
- function readJsonFile(filePath) {
2860
+ /**
2861
+ * The vite installed next to this module. The subprocess must run the vite
2862
+ * this build config was written against: a consumer project can pin an older
2863
+ * vite/rolldown (overrides) whose bundler leaves unresolvable specifiers bare
2864
+ * instead of erroring and shims node builtins differently — the output guard
2865
+ * then correctly rejects the bundle. builder-tools declares vite as a direct
2866
+ * dependency, so this resolution works wherever builder-tools is installed.
2867
+ */
2868
+ function resolveBuilderVite() {
2869
+ try {
2870
+ return createRequire(import.meta.url).resolve("vite");
2871
+ } catch {
2872
+ return null;
2873
+ }
2874
+ }
2875
+ /**
2876
+ * The build subprocess (same pattern as the vendor's). Loads builder-tools'
2877
+ * own vite (argv; project fallback) and builds the given entries with
2878
+ * relative base, so chunk/asset URLs resolve against each script's own URL
2879
+ * under any deploy base. argv: dirname, outDir, entriesJSON (name ->
2880
+ * absolute entry path), vendorImportsJSON, nodeEnv, vitePath, vendorPrefix
2881
+ * (relative path from the out dir to __vendor__/, e.g. "../__vendor__/").
2882
+ */
2883
+ const WORKER_BUILD_WORKER = `
2884
+ import { createRequire } from 'node:module';
2885
+ import { isAbsolute } from 'node:path';
2886
+ import { fileURLToPath, pathToFileURL } from 'node:url';
2887
+ const [dirname, outDir, entriesJSON, vendorImportsJSON, nodeEnvArg, vitePathArg, vendorPrefixArg] = process.argv.slice(2);
2888
+ const nodeEnv = nodeEnvArg ?? 'development';
2889
+ const entries = JSON.parse(entriesJSON);
2890
+ const vendorImports = JSON.parse(vendorImportsJSON ?? '{}');
2891
+ const vendorPrefix = vendorPrefixArg || '../__vendor__/';
2892
+ const externalSet = new Set(Object.keys(vendorImports));
2893
+ const vendorPath = (spec) => {
2894
+ const url = vendorImports[spec];
2895
+ return vendorPrefix + url.slice(url.lastIndexOf('/') + 1);
2896
+ };
2897
+ const reqProj = createRequire(dirname + '/noop.js');
2898
+ // pathToFileURL: on Windows import('D:\\\\...') parses "D:" as a URL scheme.
2899
+ const vitePath = vitePathArg || reqProj.resolve('vite');
2900
+ const { build } = await import(pathToFileURL(vitePath).href);
2901
+ // Resolve bare specifiers from the project (same plugin as the vendor build):
2902
+ // prefer the bundler's browser-condition-aware resolution, fall back to the
2903
+ // worker's own resolution for Rolldown's realpath-anchoring bug.
2904
+ const phResolveCache = new Map();
2905
+ const phWorkerResolve = {
2906
+ name: 'ph-reactor-worker-resolve', enforce: 'pre',
2907
+ async resolveId(source, importer, options) {
2908
+ if (externalSet.has(source)) return null;
2909
+ if (source[0] === '\\0' || source[0] === '.' || isAbsolute(source)) return null;
2910
+ if (source.startsWith('node:') || source.startsWith('data:')) return null;
2911
+ let viaBundler = null;
2912
+ try { viaBundler = await this.resolve(source, importer, { ...options, skipSelf: true }); } catch {}
2913
+ if (viaBundler) return viaBundler;
2914
+ if (phResolveCache.has(source)) return phResolveCache.get(source);
2915
+ let resolved = null;
2916
+ try { resolved = fileURLToPath(import.meta.resolve(source)); } catch {}
2917
+ phResolveCache.set(source, resolved);
2918
+ return resolved;
2919
+ },
2920
+ };
2921
+ // A worker has no window: on a failed dynamic import, the preload helper's
2922
+ // window.dispatchEvent would throw a ReferenceError in place of the real error.
2923
+ const PRELOAD_HELPER_ID = '\\0vite/preload-helper.js';
2924
+ const PRELOAD_DISPATCH = 'window.dispatchEvent(';
2925
+ const phWorkerPreloadHelper = {
2926
+ name: 'ph-reactor-worker-preload-helper',
2927
+ transform(code, id) {
2928
+ if (id !== PRELOAD_HELPER_ID) return null;
2929
+ if (code.split(PRELOAD_DISPATCH).length !== 2) {
2930
+ this.error('expected exactly one ' + PRELOAD_DISPATCH + ' in ' + PRELOAD_HELPER_ID);
2931
+ }
2932
+ return { code: code.replace(PRELOAD_DISPATCH, 'globalThis.dispatchEvent?.('), map: null };
2933
+ },
2934
+ };
2935
+ await build({
2936
+ root: dirname, configFile: false, logLevel: 'error',
2937
+ // The project's public/ dir belongs to the app build, not this bundle.
2938
+ publicDir: false,
2939
+ // Relative base: emitted chunk/asset URLs resolve against the worker
2940
+ // script's own URL, so the bundle works under any deploy base.
2941
+ base: './',
2942
+ define: {
2943
+ 'process.env.NODE_ENV': JSON.stringify(nodeEnv),
2944
+ 'import.meta.env.BASE_URL': JSON.stringify('./'),
2945
+ },
2946
+ plugins: [phWorkerResolve, phWorkerPreloadHelper],
2947
+ // pglite ships nested web workers as ES-module chunks.
2948
+ worker: { format: 'es' },
2949
+ build: {
2950
+ // Always minified, dev included: the bundle is browser-served output
2951
+ // (sourcemaps carry the debugging story), and minification strips the
2952
+ // JSDoc comments whose embedded code samples (kysely's, viem's) would
2953
+ // otherwise trip the bare-specifier guard below.
2954
+ outDir, emptyOutDir: false, minify: true, target: 'esnext', sourcemap: true,
2955
+ // No document in a worker: the module-preload polyfill and preload helper
2956
+ // touch the DOM, so dynamic imports must stay plain import().
2957
+ modulePreload: false,
2958
+ rollupOptions: {
2959
+ input: entries,
2960
+ // A models entry is pure re-exports; without this the bundler treats
2961
+ // its exports as unused and tree-shakes the whole file to nothing.
2962
+ // Harmless for the worker entry, which exports nothing to preserve.
2963
+ preserveEntrySignatures: 'strict',
2964
+ external: (id) => externalSet.has(id),
2965
+ output: {
2966
+ format: 'es', entryFileNames: '[name].js',
2967
+ // Chunks live at the bundle root, not a chunks/ subdir: the vendor
2968
+ // paths below are emitted VERBATIM into every chunk, so all modules
2969
+ // must sit at the same depth for ../__vendor__/ to resolve.
2970
+ chunkFileNames: '[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]',
2971
+ paths: (id) => (externalSet.has(id) ? vendorPath(id) : id),
2972
+ },
2973
+ },
2974
+ },
2975
+ });
2976
+ `;
2977
+ const WORKER_BUILD_WORKER_HASH = createHash("sha256").update(WORKER_BUILD_WORKER).digest("hex").slice(0, 16);
2978
+ //#endregion
2979
+ //#region connect-utils/worker-packages-build.ts
2980
+ /**
2981
+ * Prebuild a project's local packages into worker-loadable model bundles.
2982
+ *
2983
+ * The reactor worker gets document models from the registry CDN or from what
2984
+ * Connect statically bundled. A project's own (`provider: "local"`) package is
2985
+ * in neither, so its document types have no reducer in the worker and their
2986
+ * load jobs fail. Dev solves this by pointing the worker at the dev server's
2987
+ * transformed models entry; a production deployment has no dev server, so the
2988
+ * entry is prebuilt here, next to the worker bundle it is loaded beside.
2989
+ *
2990
+ * Each package's `browser/document-models/index.js` (reducers only: no React,
2991
+ * no CSS, no editors) is built self-contained, with the worker-safe subset of
2992
+ * the vendor externalized onto `../../__vendor__/` - two levels up, since
2993
+ * these land in `__reactor_worker__/packages/`. A `manifest.json` names what
2994
+ * was built so the tab can turn it into package sources without guessing.
2995
+ */
2996
+ /** Served under `<base>__reactor_worker__/packages/`. */
2997
+ const WORKER_PACKAGES_MANIFEST = "manifest.json";
2998
+ /** Vendor is two levels up from `__reactor_worker__/packages/`. */
2999
+ const VENDOR_PREFIX = "../../__vendor__/";
3000
+ function readVersion(root) {
708
3001
  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;
3002
+ const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
3003
+ return typeof meta.version === "string" ? meta.version : void 0;
3004
+ } catch {
3005
+ return;
715
3006
  }
716
3007
  }
717
3008
  /**
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.
3009
+ * A package root's models entry, or null when it ships none.
3010
+ *
3011
+ * Two roots are possible and both are normal: an installed dependency under
3012
+ * `node_modules/<name>`, and the project itself - the vetra case, where the
3013
+ * project *is* the local package and has no self-link in node_modules.
719
3014
  */
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
- }
3015
+ function resolvePackageModels(dirname, name) {
3016
+ const roots = [];
3017
+ try {
3018
+ roots.push(realpathSync(join(dirname, "node_modules", name)));
3019
+ } catch {}
3020
+ if (readProjectName(dirname) === name) roots.push(dirname);
3021
+ for (const root of roots) {
3022
+ const entryPath = join(root, "dist", "browser", "document-models", "index.js");
3023
+ if (existsSync(entryPath)) return {
3024
+ entryPath,
3025
+ version: readVersion(root)
3026
+ };
748
3027
  }
749
- const exportStatement = `export default [${exports.length ? `
750
- ${exports.join(",\n")}
751
- ` : ""}];`;
752
- return `${imports.join("\n")}\n\n${exportStatement}`;
3028
+ return null;
753
3029
  }
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);
3030
+ function readProjectName(dirname) {
3031
+ try {
3032
+ const meta = JSON.parse(readFileSync(join(dirname, "package.json"), "utf8"));
3033
+ return typeof meta.name === "string" ? meta.name : void 0;
3034
+ } catch {
3035
+ return;
760
3036
  }
761
3037
  }
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
3038
  /**
788
- * Appends the contents to the <head> tag of the index.html file
3039
+ * The project's own package name when it ships a models bundle, so a caller
3040
+ * can include it beside the configured `provider: "local"` packages. A vetra
3041
+ * project declares no package entry for itself, yet its models are exactly
3042
+ * the ones the worker is missing.
789
3043
  */
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
- });
3044
+ function ownProjectPackage(dirname) {
3045
+ const name = readProjectName(dirname);
3046
+ if (!name) return void 0;
3047
+ return resolvePackageModels(dirname, name) ? name : void 0;
795
3048
  }
796
3049
  /**
797
- * Prepends the contents to the <head> tag of the index.html file
3050
+ * Build each local package's models entry into `outDir` and write the
3051
+ * manifest the tab reads. Returns the manifest entries (empty when no local
3052
+ * package ships a models bundle), or null when the build itself failed -
3053
+ * `errorRef` then carries the cause. Both of those remove `outDir`, so a
3054
+ * previous build's bundles never outlive the packages they came from.
798
3055
  */
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;
3056
+ async function prebuildWorkerPackages(options) {
3057
+ const nodeEnv = options.nodeEnv ?? "production";
3058
+ const resolved = [];
3059
+ for (const name of options.packages) {
3060
+ const models = resolvePackageModels(options.dirname, name);
3061
+ if (!models) continue;
3062
+ resolved.push({
3063
+ entry: {
3064
+ name,
3065
+ version: models.version,
3066
+ file: workerPackageFileName(name)
3067
+ },
3068
+ entryPath: models.entryPath
3069
+ });
3070
+ }
3071
+ if (resolved.length === 0) {
3072
+ rmSync(options.outDir, {
3073
+ recursive: true,
3074
+ force: true
3075
+ });
3076
+ return [];
3077
+ }
3078
+ const vendorImports = options.safeVendorImports ?? (options.vendor ? workerSafeVendorImports(options.vendor.dir, options.vendor.imports) : {});
3079
+ const entries = Object.fromEntries(resolved.map((item) => [item.entry.file.replace(/\.js$/, ""), item.entryPath]));
3080
+ const parent = dirname(options.outDir);
3081
+ mkdirSync(parent, { recursive: true });
3082
+ const tmpDir = mkdtempSync(join(parent, ".ph-worker-packages.tmp-"));
3083
+ try {
3084
+ const { ok, stderr } = await runWorkerBuildEntries(options.dirname, tmpDir, entries, vendorImports, nodeEnv, VENDOR_PREFIX);
3085
+ const missing = resolved.filter((item) => !existsSync(join(tmpDir, item.entry.file)));
3086
+ if (!ok || missing.length > 0) {
3087
+ const detail = stderr.trim();
3088
+ throw new Error(`worker package bundles failed to build${missing.length > 0 ? ` (missing: ${missing.map((m) => m.entry.name).join(", ")})` : ""}${detail ? `:\n${detail}` : ""}`);
3089
+ }
3090
+ for (const item of resolved) {
3091
+ const offenders = findBundleSpecifierOffenders(tmpDir, item.entry.file);
3092
+ 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"));
3093
+ }
3094
+ const manifest = resolved.map((item) => item.entry);
3095
+ writeFileSync(join(tmpDir, WORKER_PACKAGES_MANIFEST), JSON.stringify(manifest, null, 2));
3096
+ publishDirAtomic(tmpDir, options.outDir);
3097
+ return manifest;
3098
+ } catch (err) {
3099
+ rmSync(tmpDir, {
3100
+ recursive: true,
3101
+ force: true
3102
+ });
3103
+ rmSync(options.outDir, {
3104
+ recursive: true,
3105
+ force: true
3106
+ });
3107
+ if (options.errorRef) options.errorRef.message = err instanceof Error ? err.message : String(err);
3108
+ return null;
3109
+ }
814
3110
  }
815
3111
  //#endregion
816
3112
  //#region connect-utils/runtime-config-schema.ts
@@ -861,6 +3157,31 @@ const runtimeConfigSchema = {
861
3157
  connect: phConnectRuntimeConfigSchema
862
3158
  }
863
3159
  };
3160
+ //#endregion
3161
+ //#region connect-utils/dev-deps.ts
3162
+ /** The outermost node_modules in a package's real path; null outside one. */
3163
+ function dependencyStoreOf(realPath) {
3164
+ const parts = realPath.split(sep);
3165
+ const at = parts.indexOf("node_modules");
3166
+ return at > 0 ? parts.slice(0, at + 1).join(sep) : null;
3167
+ }
3168
+ /** Pre-bundled deps for Connect's dev server, scanning the project's routes. */
3169
+ function connectOptimizeDeps(projectRoot, routesDir, routeFileDeps) {
3170
+ const routes = routesDir && relative(projectRoot, routesDir).replaceAll("\\", "/");
3171
+ return {
3172
+ ...routes ? { entries: ["index.html", `${routes}/**/*.{js,jsx,ts,tsx}`] } : {},
3173
+ include: [
3174
+ "document-model",
3175
+ "zod",
3176
+ "@powerhousedao/design-system/connect",
3177
+ "@powerhousedao/reactor-browser",
3178
+ "@powerhousedao/document-engineering",
3179
+ ...routeFileDeps
3180
+ ],
3181
+ exclude: ["@electric-sql/pglite", "@electric-sql/pglite-tools"],
3182
+ rolldownOptions: { external: [ROUTE_TREE_SPECIFIER, CORE_ROUTE_TREE_SPECIFIER] }
3183
+ };
3184
+ }
864
3185
  const RESOLVED_VIRTUAL_ID = "\0virtual:ph-bundled-packages-virtual";
865
3186
  const BUNDLED_PACKAGES_DEV_URL = "@id/" + RESOLVED_VIRTUAL_ID.replace("\0", "__x00__");
866
3187
  function readBundledPackageVersion(projectRoot, name) {
@@ -872,6 +3193,10 @@ function readBundledPackageVersion(projectRoot, name) {
872
3193
  return;
873
3194
  }
874
3195
  }
3196
+ function offeredRoutesFile(projectRoot, name) {
3197
+ const file = path.join(projectRoot, "node_modules", name, "dist/browser/connect-routes.js");
3198
+ return fs.existsSync(file) ? file : void 0;
3199
+ }
875
3200
  function makeRegisterModule(packages, projectRoot) {
876
3201
  if (packages.length === 0) return "export default () => {};\n";
877
3202
  const imports = [];
@@ -881,7 +3206,9 @@ function makeRegisterModule(packages, projectRoot) {
881
3206
  const version = readBundledPackageVersion(projectRoot, name);
882
3207
  imports.push(`import * as ${moduleName} from ${JSON.stringify(name)};`);
883
3208
  imports.push(`import ${JSON.stringify(`${name}/style.css`)};`);
884
- calls.push(` pm.addLocalPackage(${JSON.stringify(name)}, ${moduleName}, ${JSON.stringify(version)});`);
3209
+ const routesFile = offeredRoutesFile(projectRoot, name);
3210
+ const routes = routesFile ? `, () => import(${JSON.stringify(routesFile)})` : "";
3211
+ calls.push(` pm.addLocalPackage(${JSON.stringify(name)}, ${moduleName}, ${JSON.stringify(version)}${routes});`);
885
3212
  });
886
3213
  return `${imports.join("\n")}\n\nexport default function register(pm) {\n${calls.join("\n")}\n};\n`;
887
3214
  }
@@ -919,7 +3246,13 @@ const REACT_DEPS = [
919
3246
  "react-dom/client"
920
3247
  ];
921
3248
  const SHIM_PATH = "__ph/dev-react-shim/";
922
- const VITE_DEPS_PATH = "node_modules/.vite/deps";
3249
+ const SHARED_SHIM = "ph-shared:";
3250
+ const SHARED_DEPS = EXTERNALIZABLE_SHARED_SPECIFIERS.filter((spec) => !REACT_DEPS.includes(spec));
3251
+ /** The page's import map entries for the shared deps: each root and its subpaths. */
3252
+ function sharedDepImports(base) {
3253
+ const url = (spec) => withBase$1(base, `@id/__x00__${SHARED_SHIM}${spec}`);
3254
+ return Object.fromEntries(SHARED_DEPS.flatMap((spec) => [[spec, url(spec)], [`${spec}/`, `${url(spec)}/`]]));
3255
+ }
923
3256
  const VENDOR_MIME = {
924
3257
  ".css": "text/css",
925
3258
  ".map": "application/json",
@@ -939,7 +3272,21 @@ const VENDOR_MIME = {
939
3272
  const VENDOR_MODE = process.env.PH_CONNECT_EXTERNALIZE_VENDOR === "1";
940
3273
  const VENDOR_EXTRA = (process.env.PH_CONNECT_VENDOR_EXTRA ?? "").split(",").map((s) => s.trim()).filter(Boolean);
941
3274
  const HEAVY_LIBS = [...DEFAULT_VENDOR_INCLUDE, ...VENDOR_EXTRA];
942
- function withBase(base, p) {
3275
+ const heavyLibsFor = (routesDir) => routesDir ? HEAVY_LIBS.filter((lib) => lib !== "@powerhousedao/connect") : HEAVY_LIBS;
3276
+ /** The dev server's URL for a file: under the root, else through `/@fs/`. */
3277
+ function devUrlOf(root, file) {
3278
+ const relativePath = path.relative(root, file);
3279
+ return relativePath.startsWith("..") || path.isAbsolute(relativePath) ? `/@fs/${file.split(path.sep).join("/").replace(/^\/+/, "")}` : relativePath.split(path.sep).join("/");
3280
+ }
3281
+ /** A file of Connect's package, else the root: where Connect's own imports resolve from. */
3282
+ function connectImporter(root) {
3283
+ try {
3284
+ return createRequire(path.join(root, "package.json")).resolve("@powerhousedao/connect/package.json");
3285
+ } catch {
3286
+ return path.join(root, "index.html");
3287
+ }
3288
+ }
3289
+ function withBase$1(base, p) {
943
3290
  return `${base}${p}`.replace(/\/{2,}/g, "/");
944
3291
  }
945
3292
  function externalizePlugin(externals) {
@@ -974,15 +3321,17 @@ function externalizePlugin(externals) {
974
3321
  * the React shims above → one React instance across Connect, the vendor, and
975
3322
  * CDN editors.
976
3323
  */
977
- async function devReactImportmapPlugin(projectRoot = process.cwd()) {
3324
+ async function devReactImportmapPlugin(projectRoot = process.cwd(), routesDir = resolveConnectRoutesDir(projectRoot)) {
978
3325
  let namedExports = /* @__PURE__ */ new Map();
979
3326
  let base = "/";
3327
+ let root = projectRoot;
980
3328
  let vendor = null;
3329
+ const heavyLibs = heavyLibsFor(routesDir);
981
3330
  if (VENDOR_MODE) {
982
3331
  const errorRef = {};
983
3332
  vendor = await prebuildConnectVendor({
984
3333
  dirname: projectRoot,
985
- include: HEAVY_LIBS,
3334
+ include: heavyLibs,
986
3335
  errorRef
987
3336
  });
988
3337
  if (!vendor) {
@@ -996,18 +3345,29 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
996
3345
  const main = {
997
3346
  name: "ph-dev-react-importmap",
998
3347
  apply: "serve",
3348
+ async resolveId(source, importer) {
3349
+ if (source.startsWith(SHARED_SHIM)) return `\0${source}`;
3350
+ if (source.startsWith(`\0${SHARED_SHIM}`)) return source;
3351
+ if (importer?.startsWith(`\0${SHARED_SHIM}`)) return this.resolve(source, connectImporter(root), { skipSelf: true });
3352
+ },
3353
+ load(id) {
3354
+ if (!id.startsWith(`\0${SHARED_SHIM}`)) return void 0;
3355
+ const spec = JSON.stringify(id.slice(11));
3356
+ return `export * from ${spec};\nimport * as M from ${spec};\nexport default M.default;\n`;
3357
+ },
999
3358
  config(cfg) {
1000
3359
  cfg.optimizeDeps ??= {};
1001
3360
  const include = new Set(cfg.optimizeDeps.include ?? []);
1002
3361
  REACT_DEPS.forEach((d) => include.add(d));
1003
3362
  if (vendorActive) {
1004
- HEAVY_LIBS.forEach((d) => include.delete(d));
1005
- cfg.optimizeDeps.exclude = [...new Set([...cfg.optimizeDeps.exclude ?? [], ...HEAVY_LIBS])];
3363
+ heavyLibs.forEach((d) => include.delete(d));
3364
+ cfg.optimizeDeps.exclude = [.../* @__PURE__ */ new Set([...cfg.optimizeDeps.exclude ?? [], ...heavyLibs])];
1006
3365
  }
1007
3366
  cfg.optimizeDeps.include = [...include];
1008
3367
  },
1009
3368
  configResolved(config) {
1010
3369
  base = config.base;
3370
+ root = config.root;
1011
3371
  },
1012
3372
  configureServer(server) {
1013
3373
  const requireFromRoot = createRequire(path.join(server.config.root, "package.json"));
@@ -1021,7 +3381,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1021
3381
  }));
1022
3382
  if (vendorActive) {
1023
3383
  const vendorDir = vendor.vendorDir;
1024
- const vendorPrefixes = [withBase(base, VENDOR_URL_PREFIX), VENDOR_URL_PREFIX];
3384
+ const vendorPrefixes = [withBase$1(base, VENDOR_URL_PREFIX), VENDOR_URL_PREFIX];
1025
3385
  server.middlewares.use((req, res, next) => {
1026
3386
  const url = (req.url ?? "").split("?")[0];
1027
3387
  const prefix = vendorPrefixes.find((p) => url.startsWith(p));
@@ -1043,7 +3403,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1043
3403
  });
1044
3404
  });
1045
3405
  }
1046
- const shimPrefixes = [withBase(base, SHIM_PATH), `/${SHIM_PATH}`];
3406
+ const shimPrefixes = [withBase$1(base, SHIM_PATH), `/${SHIM_PATH}`];
1047
3407
  server.middlewares.use((req, res, next) => {
1048
3408
  const prefix = shimPrefixes.find((p) => req.url?.startsWith(p));
1049
3409
  if (!prefix) return next();
@@ -1057,7 +3417,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1057
3417
  return;
1058
3418
  }
1059
3419
  const browserHash = info.browserHash ?? optimizer.metadata.browserHash;
1060
- const depUrl = `${withBase(base, VITE_DEPS_PATH)}/${path.basename(info.file)}?v=${browserHash}`;
3420
+ const depUrl = `${withBase$1(base, devUrlOf(root, info.file))}?v=${browserHash}`;
1061
3421
  const names = namedExports.get(id) ?? [];
1062
3422
  res.setHeader("Content-Type", "application/javascript");
1063
3423
  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 +3428,13 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1068
3428
  handler(html, ctx) {
1069
3429
  const browserHash = ctx.server?.environments.client.depsOptimizer?.metadata.browserHash;
1070
3430
  if (!browserHash) return;
1071
- const shimPrefix = withBase(base, SHIM_PATH);
3431
+ const shimPrefix = withBase$1(base, SHIM_PATH);
1072
3432
  const imports = Object.fromEntries(REACT_DEPS.map((id) => [id, `${shimPrefix}${id}.js?v=${browserHash}`]));
3433
+ Object.assign(imports, sharedDepImports(base));
1073
3434
  let dynamicBaseScript = "";
1074
3435
  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);
3436
+ for (const [spec, url] of Object.entries(vendor.imports)) imports[spec] = withBase$1(base, url);
3437
+ if (vendor.imports["@powerhousedao/connect"]) imports["ph-bundled-packages-virtual"] = withBase$1(base, BUNDLED_PACKAGES_DEV_URL);
1077
3438
  dynamicBaseScript = `<script>globalThis.__PH_DYNAMIC_BASE__=${JSON.stringify(base)};<\/script>\n`;
1078
3439
  }
1079
3440
  return html.replace(/<script type="importmap">[\s\S]*?<\/script>/, `${dynamicBaseScript}<script type="importmap">${JSON.stringify({ imports }, null, 2)}<\/script>`);
@@ -1092,16 +3453,20 @@ const CONTENT_TYPE_BY_EXT = {
1092
3453
  /**
1093
3454
  * Vite plugin to serve the Connect favicon (icon.ico) from the connect package,
1094
3455
  * or from a caller-supplied file when `faviconPath` is set (e.g. `ph connect
1095
- * build --favicon`). The served/emitted name is always `icon.ico` so the static
1096
- * `<link rel="icon" href="%BASE_URL%icon.ico">` in index.html stays valid.
3456
+ * build --favicon`). An .svg or .png keeps its type as icon.svg or icon.png,
3457
+ * and index.html's `<link rel="icon">` is rewritten to it; browsers decode a
3458
+ * file named icon.ico as an ICO.
1097
3459
  */
1098
3460
  function connectFaviconPlugin(opts = {}) {
1099
3461
  const customPath = opts.faviconPath ? isAbsolute(opts.faviconPath) ? opts.faviconPath : resolve(process.cwd(), opts.faviconPath) : void 0;
1100
- const customContentType = customPath ? CONTENT_TYPE_BY_EXT[extname(customPath).toLowerCase()] ?? "image/x-icon" : "image/x-icon";
3462
+ const ext = customPath ? extname(customPath).toLowerCase() : ".ico";
3463
+ const customContentType = CONTENT_TYPE_BY_EXT[ext] ?? "image/x-icon";
3464
+ const fileName = ext === ".svg" || ext === ".png" ? `icon${ext}` : "icon.ico";
1101
3465
  return {
1102
3466
  name: "copy-connect-favicon",
1103
3467
  configureServer(server) {
1104
- const faviconRoute = `${server.config.base}icon.ico`.replace(/\/{2,}/g, "/");
3468
+ const base = server.config.base;
3469
+ const route = (name) => `${base}${name}`.replace(/\/{2,}/g, "/");
1105
3470
  const handler = (_req, res, next) => {
1106
3471
  if (customPath) {
1107
3472
  try {
@@ -1118,12 +3483,21 @@ function connectFaviconPlugin(opts = {}) {
1118
3483
  res.end(readFileSync(resolved.id));
1119
3484
  }).catch(() => next());
1120
3485
  };
1121
- const paths = new Set([faviconRoute, "/icon.ico"]);
3486
+ const paths = /* @__PURE__ */ new Set([
3487
+ route(fileName),
3488
+ `/${fileName}`,
3489
+ route("icon.ico"),
3490
+ "/icon.ico"
3491
+ ]);
1122
3492
  for (const path of paths) server.middlewares.use(path, handler);
1123
3493
  },
3494
+ transformIndexHtml(html) {
3495
+ if (fileName === "icon.ico") return html;
3496
+ return html.replace(/<link rel="icon" href="([^"]*)icon\.ico"\s*\/?>/, `<link rel="icon" type="${customContentType}" href="$1${fileName}" />`);
3497
+ },
1124
3498
  async generateBundle(_options, bundle) {
1125
3499
  try {
1126
- if ("icon.ico" in bundle) return;
3500
+ if (fileName in bundle) return;
1127
3501
  let source;
1128
3502
  if (customPath) source = readFileSync(customPath);
1129
3503
  else {
@@ -1133,7 +3507,7 @@ function connectFaviconPlugin(opts = {}) {
1133
3507
  if (!source) return;
1134
3508
  this.emitFile({
1135
3509
  type: "asset",
1136
- fileName: "icon.ico",
3510
+ fileName,
1137
3511
  source
1138
3512
  });
1139
3513
  } catch {}
@@ -1156,21 +3530,47 @@ function readProjectPackageInfo(projectRoot) {
1156
3530
  return null;
1157
3531
  }
1158
3532
  }
3533
+ /** `html` with its `<title>` text set to `appName`, when one is configured. */
3534
+ function withAppTitle(html, appName) {
3535
+ if (!appName) return html;
3536
+ const escaped = appName.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
3537
+ return html.replace(/<title>[^<]*<\/title>/, () => `<title>${escaped}</title>`);
3538
+ }
3539
+ /** `api.connect`: the connect config the app is served, for plugins that render
3540
+ * ahead of it; `api.favicon`: its `branding.favicon`, which it leaves out. */
1159
3541
  function phConfigPlugin(options) {
1160
3542
  const localPackage = readProjectPackageInfo(options.projectRoot ?? process.cwd());
1161
- const withDefaults = deepMerge(DEFAULT_CONNECT_CONFIG, options.connect ?? {});
3543
+ const sourceSettings = {
3544
+ connect: options.connect,
3545
+ workflows: options.workflows
3546
+ };
3547
+ const conflict = workflowsSettingConflict(sourceSettings);
3548
+ if (conflict) console.warn(`[powerhouse] ${conflict}`);
3549
+ const withDefaults = resolveSourceConnect(sourceSettings);
1162
3550
  const mergedConnect = options.cliConnectOverride ? deepMerge(withDefaults, options.cliConnectOverride) : withDefaults;
1163
- const runtimeConfig = buildRuntimeConfig({
3551
+ const { favicon, ...branding } = mergedConnect.branding ?? {};
3552
+ const source = {
1164
3553
  packages: options.packages,
1165
3554
  packageRegistryUrl: options.packageRegistryUrl,
1166
- connect: mergedConnect
1167
- }, localPackage);
3555
+ connect: options.branding ? {
3556
+ ...mergedConnect,
3557
+ branding: options.branding
3558
+ } : mergedConnect.branding ? {
3559
+ ...mergedConnect,
3560
+ branding
3561
+ } : mergedConnect
3562
+ };
3563
+ const runtimeConfig = buildRuntimeConfig(source, localPackage);
1168
3564
  const content = JSON.stringify({
1169
3565
  $schema: RUNTIME_CONFIG_SCHEMA_URL,
1170
3566
  ...runtimeConfig
1171
3567
  }, null, 2);
1172
3568
  return {
1173
3569
  name: "vite-plugin-ph-config",
3570
+ api: {
3571
+ connect: runtimeConfig.connect,
3572
+ favicon: favicon ?? void 0
3573
+ },
1174
3574
  configureServer(server) {
1175
3575
  server.middlewares.use((req, res, next) => {
1176
3576
  if (req.url?.endsWith("/powerhouse.config.json")) {
@@ -1191,6 +3591,9 @@ function phConfigPlugin(options) {
1191
3591
  });
1192
3592
  }
1193
3593
  },
3594
+ transformIndexHtml(html) {
3595
+ return withAppTitle(html, runtimeConfig.connect.branding?.appName ?? void 0);
3596
+ },
1194
3597
  generateBundle() {
1195
3598
  this.emitFile({
1196
3599
  type: "asset",
@@ -1217,11 +3620,13 @@ function toPwaContribution(manifest, fallbackLabel, onWarn) {
1217
3620
  if (!isPlainObject(manifest)) return null;
1218
3621
  const label = typeof manifest.name === "string" && manifest.name ? manifest.name : fallbackLabel;
1219
3622
  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;
3623
+ if (manifest.pwa !== void 0) {
3624
+ if (!isPlainObject(manifest.pwa)) onWarn(`PWA config: ${label} declares a non-object 'pwa' field in its manifest; ignored.`);
3625
+ else {
3626
+ const parsed = PwaConfigSchema.safeParse(manifest.pwa);
3627
+ if (!parsed.success) onWarn(`PWA config: ${label}'s pwa fragment is invalid; ignored. ${formatZodIssues(parsed.error)}`);
3628
+ else config = parsed.data;
3629
+ }
1225
3630
  }
1226
3631
  config = withInferredCategory(config, manifest.category);
1227
3632
  if (Object.keys(config).length === 0) return null;
@@ -1330,7 +3735,8 @@ function collectProjectPwaContribution(options) {
1330
3735
  }
1331
3736
  if (!isPlainObject(manifest)) return null;
1332
3737
  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);
3738
+ const config = manifest.pwa === void 0 ? {} : parsePwaConfigStrict(manifest.pwa, `pwa in ${manifestPath}`);
3739
+ const withCategory = withInferredCategory(config, manifest.category);
1334
3740
  if (Object.keys(withCategory).length === 0) return null;
1335
3741
  return {
1336
3742
  source: label,
@@ -1461,6 +3867,28 @@ const BASE_MANIFEST = {
1461
3867
  launch_handler: { client_mode: "focus-existing" }
1462
3868
  };
1463
3869
  /**
3870
+ * The base manifest under the project's own name and icons (from
3871
+ * `connect.branding.appName` / `icons.app`), so an installed app is not
3872
+ * "Powerhouse Connect". Connect's description goes with its name; a project
3873
+ * that wants one sets `connect.pwa.manifest.description`, which — like the
3874
+ * rest of `connect.pwa` — is laid on top of this.
3875
+ */
3876
+ function brandManifest(base, brand) {
3877
+ if (!brand) return base;
3878
+ const manifest = { ...base };
3879
+ if (brand.name) {
3880
+ manifest.name = brand.name;
3881
+ manifest.short_name = brand.name;
3882
+ delete manifest.description;
3883
+ }
3884
+ if (brand.icons?.length) manifest.icons = brand.icons.map((icon) => ({
3885
+ src: icon.fileName,
3886
+ sizes: icon.sizes,
3887
+ type: icon.contentType
3888
+ }));
3889
+ return manifest;
3890
+ }
3891
+ /**
1464
3892
  * Connect's hardcoded precache config — the base layer for the `injectManifest`
1465
3893
  * precache. Overridable additively (extra globs) or by raising the size ceiling
1466
3894
  * via package/project `pwa` config. The rest of the old Workbox config
@@ -1471,14 +3899,23 @@ const BASE_MANIFEST = {
1471
3899
  * declarative runtimeCaching option.
1472
3900
  */
1473
3901
  const BASE_PRECACHE = {
1474
- maximumFileSizeToCacheInBytes: 16 * 1024 * 1024,
1475
- globPatterns: ["**/*.{js,css,html,wasm,data,ico,png,svg,webp,woff,woff2}"],
3902
+ maximumFileSizeToCacheInBytes: 16777216,
3903
+ globPatterns: ["**/*.{js,css,html,wasm,data,ico,png,svg,webp,woff,woff2}", "__reactor_worker__/**/*.json"],
1476
3904
  globIgnores: [
1477
3905
  "**/powerhouse.config.json",
1478
3906
  "**/*.map",
1479
- "index.html"
3907
+ "index.html",
3908
+ "**/*.gz"
1480
3909
  ]
1481
3910
  };
3911
+ /** The files under `dir` (a project's public/), by path relative to it. */
3912
+ function staticFilesIn(dir) {
3913
+ if (!existsSync(dir)) return [];
3914
+ return readdirSync(dir, {
3915
+ recursive: true,
3916
+ withFileTypes: true
3917
+ }).filter((entry) => entry.isFile()).map((entry) => join(entry.parentPath, entry.name).slice(dir.length + 1).replaceAll("\\", "/"));
3918
+ }
1482
3919
  const SW_FILENAME = "service-worker.ts";
1483
3920
  /**
1484
3921
  * Absolute directory holding the hand-written service-worker source. Resolved
@@ -1534,7 +3971,7 @@ function phSwConfigPlugin(data) {
1534
3971
  * clears its caches on the browser's next service-worker update check.
1535
3972
  */
1536
3973
  function connectPwaPlugins(options) {
1537
- const { offlineEnabled, pwa } = options;
3974
+ const { offlineEnabled, pwa, brand, staticFiles = [] } = options;
1538
3975
  if (!offlineEnabled) return [VitePWA({
1539
3976
  selfDestroying: true,
1540
3977
  strategies: "generateSW",
@@ -1543,13 +3980,14 @@ function connectPwaPlugins(options) {
1543
3980
  devOptions: { enabled: false }
1544
3981
  })];
1545
3982
  const { manifest, precache } = applyPwaOverrides({
1546
- manifest: BASE_MANIFEST,
3983
+ manifest: brandManifest(BASE_MANIFEST, brand),
1547
3984
  precache: BASE_PRECACHE
1548
3985
  }, pwa ?? {});
1549
3986
  const swConfig = {
1550
3987
  EMBEDDED_BASE_MANIFEST: manifest,
1551
3988
  EXTRA_RUNTIME_CACHING: pwa?.runtimeCaching ?? [],
1552
- NAVIGATE_FALLBACK_DENYLIST_EXTRA: pwa?.navigateFallbackDenylist ?? []
3989
+ NAVIGATE_FALLBACK_DENYLIST_EXTRA: pwa?.navigateFallbackDenylist ?? [],
3990
+ STATIC_FILES: staticFiles
1553
3991
  };
1554
3992
  return [connectPwaIconsPlugin(), VitePWA({
1555
3993
  strategies: "injectManifest",
@@ -1613,17 +4051,40 @@ function resolveReactEntries(dirname$1) {
1613
4051
  }
1614
4052
  return out;
1615
4053
  }
4054
+ function reactImportMap(base, files) {
4055
+ const map = {};
4056
+ for (const [spec, file] of Object.entries(files)) {
4057
+ map[spec] = `${base}${REACT_URL_DIR}/${file}`;
4058
+ if (spec.includes("/")) map[`${spec}.js`] = map[spec];
4059
+ }
4060
+ return map;
4061
+ }
1616
4062
  function reactSelfHostPlugin(options) {
1617
4063
  const entries = resolveReactEntries(options.dirname);
1618
4064
  let absOutDir = resolve(options.dirname, "dist");
4065
+ let base = "/";
4066
+ let staging;
4067
+ let files = {};
1619
4068
  let importMap = {};
1620
4069
  return {
1621
4070
  name: "ph-react-self-host",
1622
4071
  apply: "build",
1623
4072
  configResolved(config) {
1624
4073
  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}/`;
4074
+ base = config.base;
4075
+ },
4076
+ async buildStart() {
4077
+ files = {};
4078
+ importMap = {};
4079
+ if (!Object.keys(entries).length) return;
4080
+ const stagingParent = join(options.dirname, "node_modules");
4081
+ staging = mkdtempSync(join(existsSync(stagingParent) ? stagingParent : options.dirname, ".ph-react-self-host-"));
4082
+ const { ok, stderr } = await runReactBuild(options.dirname, staging, entries, options.dev ? "development" : "production");
4083
+ if (!ok) this.error(`react self-host build failed${stderr.trim() ? `:\n${stderr.trim()}` : ""}`);
4084
+ const manifest = join(staging, FILES_MANIFEST);
4085
+ files = JSON.parse(readFileSync(manifest, "utf8"));
4086
+ rmSync(manifest, { force: true });
4087
+ importMap = reactImportMap(base, files);
1627
4088
  },
1628
4089
  transformIndexHtml() {
1629
4090
  if (!Object.keys(importMap).length) return;
@@ -1634,13 +4095,27 @@ function reactSelfHostPlugin(options) {
1634
4095
  injectTo: "head-prepend"
1635
4096
  }];
1636
4097
  },
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()}` : ""}`);
4098
+ closeBundle() {
4099
+ if (!staging) return;
4100
+ const dest = join(absOutDir, REACT_URL_DIR);
4101
+ rmSync(dest, {
4102
+ recursive: true,
4103
+ force: true
4104
+ });
4105
+ mkdirSync(absOutDir, { recursive: true });
4106
+ cpSync(staging, dest, { recursive: true });
4107
+ chmodSync(dest, 493);
4108
+ rmSync(staging, {
4109
+ recursive: true,
4110
+ force: true
4111
+ });
4112
+ staging = void 0;
4113
+ const missing = Object.entries(files).filter(([, file]) => !existsSync(join(dest, file)));
4114
+ 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
4115
  }
1642
4116
  };
1643
4117
  }
4118
+ const FILES_MANIFEST = "files.json";
1644
4119
  function runReactBuild(dirname, outDir, entries, nodeEnv) {
1645
4120
  mkdirSync(outDir, { recursive: true });
1646
4121
  const workerPath = join(outDir, "build-worker.mjs");
@@ -1715,7 +4190,7 @@ for (const [spec, file] of Object.entries(entries)) {
1715
4190
  input[spec] = entryFile;
1716
4191
  }
1717
4192
  try {
1718
- await build({
4193
+ const result = await build({
1719
4194
  root: dirname, configFile: false, logLevel: 'error',
1720
4195
  base: './', publicDir: false,
1721
4196
  define: { 'process.env.NODE_ENV': JSON.stringify(nodeEnv) },
@@ -1724,11 +4199,18 @@ try {
1724
4199
  outDir, emptyOutDir: false, minify: nodeEnv === 'production', target: 'esnext',
1725
4200
  rollupOptions: {
1726
4201
  input, preserveEntrySignatures: 'strict',
1727
- output: { format: 'es', entryFileNames: '[name].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },
4202
+ output: { format: 'es', entryFileNames: '[name]-[hash].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },
1728
4203
  },
1729
4204
  },
1730
4205
  });
1731
4206
  rmSync(srcDir, { recursive: true, force: true });
4207
+ const files = {};
4208
+ for (const out of Array.isArray(result) ? result : [result]) {
4209
+ for (const chunk of out?.output ?? []) {
4210
+ if (chunk.type === 'chunk' && chunk.isEntry) files[chunk.name] = chunk.fileName;
4211
+ }
4212
+ }
4213
+ writeFileSync(join(outDir, 'files.json'), JSON.stringify(files));
1732
4214
  // Force exit: rolldown can leave native worker threads alive that keep the
1733
4215
  // event loop open, hanging the parent's spawn() promise indefinitely.
1734
4216
  process.exit(0);
@@ -1738,6 +4220,91 @@ try {
1738
4220
  }
1739
4221
  `;
1740
4222
  //#endregion
4223
+ //#region connect-utils/vite-plugins/reactor-worker-dev.ts
4224
+ const DEV_BUNDLE_DIR = "node_modules/.ph-reactor-worker";
4225
+ function withBase(base, p) {
4226
+ return `${base}${p}`.replace(/\/{2,}/g, "/");
4227
+ }
4228
+ /**
4229
+ * Dev-only: serve Connect's reactor SharedWorker bundle under
4230
+ * `<base>__reactor_worker__/`, building it lazily on first request.
4231
+ *
4232
+ * The dev server serves Connect from its prebuilt dist in node_modules, where
4233
+ * `dist/reactor.worker.js` is a library artifact no worker can resolve. The
4234
+ * tab GETs `worker-meta.json` here (JSON, no-cache, written by
4235
+ * `prebuildReactorWorker`) to find the bundle and fold its `sourceDigest`
4236
+ * into its version fingerprint; without this plugin that GET fails and the
4237
+ * worker feature reports itself unavailable instead of dying opaquely.
4238
+ *
4239
+ * Lazy because it is a full `vite build` of the reactor + PGlite graph. The
4240
+ * result is cached in node_modules/.ph-reactor-worker until the installed
4241
+ * Connect, its upstream dists, or builder-tools change (`computeSourceDigest`).
4242
+ */
4243
+ function reactorWorkerDevPlugin(projectRoot) {
4244
+ let base = "/";
4245
+ let building = null;
4246
+ const ensureBuilt = () => {
4247
+ building ??= (async () => {
4248
+ const errorRef = {};
4249
+ const built = await prebuildReactorWorker({
4250
+ dirname: projectRoot,
4251
+ outDir: path.join(projectRoot, DEV_BUNDLE_DIR),
4252
+ nodeEnv: "development",
4253
+ errorRef
4254
+ });
4255
+ if (!built) {
4256
+ console.warn(`[connect] reactor worker bundle build failed${errorRef.message ? `: ${errorRef.message}` : ""}`);
4257
+ building = null;
4258
+ }
4259
+ return built;
4260
+ })();
4261
+ return building;
4262
+ };
4263
+ return {
4264
+ name: "ph-reactor-worker-dev",
4265
+ apply: "serve",
4266
+ configResolved(config) {
4267
+ base = config.base;
4268
+ },
4269
+ configureServer(server) {
4270
+ const prefixes = [withBase(base, REACTOR_WORKER_URL_PREFIX), REACTOR_WORKER_URL_PREFIX];
4271
+ server.middlewares.use((req, res, next) => {
4272
+ const url = (req.url ?? "").split("?")[0];
4273
+ const prefix = prefixes.find((p) => url.startsWith(p));
4274
+ if (!prefix) return next();
4275
+ const name = url.slice(prefix.length).replace(/^\/+/, "");
4276
+ if (!name) return next();
4277
+ (async () => {
4278
+ const built = await ensureBuilt();
4279
+ if (!built) {
4280
+ res.statusCode = 503;
4281
+ res.setHeader("Content-Type", "text/plain");
4282
+ res.end("reactor worker bundle unavailable (build failed; see server log)");
4283
+ return;
4284
+ }
4285
+ const file = path.join(built.outDir, name);
4286
+ const rel = path.relative(built.outDir, file);
4287
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
4288
+ next();
4289
+ return;
4290
+ }
4291
+ const stream = createReadStream(file);
4292
+ stream.on("error", () => {
4293
+ if (!res.headersSent) next();
4294
+ });
4295
+ stream.once("open", () => {
4296
+ const ext = file.slice(file.lastIndexOf("."));
4297
+ res.setHeader("Content-Type", REACTOR_WORKER_MIME[ext] ?? "text/javascript");
4298
+ const hashed = !name.startsWith("reactor.worker.js") && !name.endsWith(".json");
4299
+ res.setHeader("Cache-Control", hashed ? "public, max-age=31536000, immutable" : "no-cache");
4300
+ stream.pipe(res);
4301
+ });
4302
+ })();
4303
+ });
4304
+ }
4305
+ };
4306
+ }
4307
+ //#endregion
1741
4308
  //#region connect-utils/vite-plugins/theme-boot.ts
1742
4309
  /**
1743
4310
  * Marker attribute on the injected script. Serve-time injectors (e.g. the
@@ -1752,7 +4319,7 @@ const THEME_BOOT_MARKER = "data-ph-theme-boot";
1752
4319
  * Keep semantically identical to the runtime store in
1753
4320
  * `@powerhousedao/reactor-browser` (hooks/theme.ts).
1754
4321
  */
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){}})();";
4322
+ 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
4323
  /**
1757
4324
  * Injects the theme boot script at the top of `<head>` of every emitted
1758
4325
  * index.html, so built Connect apps render the stored theme from first paint
@@ -1776,6 +4343,48 @@ function connectThemeBootPlugin() {
1776
4343
  };
1777
4344
  }
1778
4345
  //#endregion
4346
+ //#region connect-utils/vite-plugins/vendor-import-map.ts
4347
+ function extractImports(raw) {
4348
+ if (typeof raw !== "object" || raw === null) return {};
4349
+ const imports = "imports" in raw ? raw.imports : void 0;
4350
+ if (typeof imports !== "object" || imports === null) return {};
4351
+ const out = {};
4352
+ for (const [key, value] of Object.entries(imports)) if (typeof value === "string") out[key] = value;
4353
+ return out;
4354
+ }
4355
+ function parseImportMap(raw) {
4356
+ try {
4357
+ return extractImports(JSON.parse(raw));
4358
+ } catch {
4359
+ return {};
4360
+ }
4361
+ }
4362
+ const INLINE_IMPORTMAP = /<script type="importmap">([\s\S]*?)<\/script>/;
4363
+ function vendorImportMapPlugin(options) {
4364
+ const vendorEntries = Object.keys(options.imports).length;
4365
+ return {
4366
+ name: "ph-vendor-import-map",
4367
+ apply: "build",
4368
+ transformIndexHtml(html) {
4369
+ if (!vendorEntries) return;
4370
+ const match = INLINE_IMPORTMAP.exec(html);
4371
+ if (match) {
4372
+ const merged = { imports: {
4373
+ ...parseImportMap(match[1]),
4374
+ ...options.imports
4375
+ } };
4376
+ return html.replace(INLINE_IMPORTMAP, `<script type="importmap">${JSON.stringify(merged)}<\/script>`);
4377
+ }
4378
+ return [{
4379
+ tag: "script",
4380
+ attrs: { type: "importmap" },
4381
+ children: JSON.stringify({ imports: options.imports }),
4382
+ injectTo: "head-prepend"
4383
+ }];
4384
+ }
4385
+ };
4386
+ }
4387
+ //#endregion
1779
4388
  //#region connect-utils/vite-config.ts
1780
4389
  function getConnectHtmlTags(options = {}) {
1781
4390
  const { registryUrl, injectTo = "head" } = options;
@@ -1896,14 +4505,15 @@ function getLocalPackageNamesFromPowerhouseConfig({ packages }) {
1896
4505
  }
1897
4506
  function getConnectBaseViteConfig(options) {
1898
4507
  const mode = options.mode;
1899
- const fileEnv = loadEnv(mode, options.envDir ?? options.dirname, "PH_");
4508
+ const envDir = options.envDir ?? options.dirname;
4509
+ const fileEnv = loadEnv(mode, envDir, "PH_");
1900
4510
  const env = loadConnectEnv({
1901
4511
  processEnv: process.env,
1902
4512
  fileEnv
1903
4513
  });
1904
4514
  setConnectEnv(env);
1905
4515
  const phConfigPath = join(options.dirname, "powerhouse.config.json");
1906
- const phConfig = options.powerhouseConfig ?? getConfig(phConfigPath);
4516
+ const phConfig = options.powerhouseConfig ?? getConfig$1(phConfigPath);
1907
4517
  const packagesFromConfig = phConfig.packages ?? [];
1908
4518
  const localPackagesFromConfig = getLocalPackageNamesFromPowerhouseConfig(phConfig);
1909
4519
  const phPackagesStr = env.PH_PACKAGES;
@@ -1934,10 +4544,13 @@ function getConnectBaseViteConfig(options) {
1934
4544
  const plugins = [
1935
4545
  tailwind(),
1936
4546
  react(),
1937
- createHtmlPlugin({
1938
- minify: false,
1939
- inject: { tags: [...connectHtmlTags, ...devImportmapTag] }
1940
- })
4547
+ {
4548
+ name: "ph-connect-html-tags",
4549
+ transformIndexHtml: {
4550
+ order: "pre",
4551
+ handler: () => [...connectHtmlTags, ...devImportmapTag]
4552
+ }
4553
+ }
1941
4554
  ];
1942
4555
  if (uploadSentrySourcemaps) plugins.push(import("@sentry/vite-plugin").then(({ sentryVitePlugin }) => sentryVitePlugin({
1943
4556
  release: {
@@ -1958,6 +4571,25 @@ function getConnectBaseViteConfig(options) {
1958
4571
  const projectPwa = validateProjectPwaConfig(deepMerge(phConfig.connect?.pwa ?? {}, options.cliConnectOverride?.pwa ?? {}), phConfigPath);
1959
4572
  const pwaWarn = (msg) => (customLogger ?? console).warn(msg);
1960
4573
  const pwaPackagesForFragments = mode === "production" ? phPackages : phPackages.filter((p) => p.provider === "local");
4574
+ const brandWarn = (msg) => (customLogger ?? console).warn(msg);
4575
+ const branding = effectiveBranding(phConfig.connect?.branding, options.cliConnectOverride?.branding);
4576
+ const projectLoader = resolveProjectLoader(options.dirname, branding, brandWarn);
4577
+ const projectBrand = resolveProjectPwaBrand(options.dirname, branding, brandWarn);
4578
+ const runtimeBranding = resolveRuntimeBranding(options.dirname, branding, brandWarn);
4579
+ const sourceConnect = withResolvedGenericImages(options.dirname, phConfig.connect, brandWarn);
4580
+ const connectOverride = withResolvedGenericImages(options.dirname, options.cliConnectOverride, brandWarn);
4581
+ const configPlugin = phConfigPlugin({
4582
+ packages: phPackages,
4583
+ projectRoot: options.dirname,
4584
+ connect: sourceConnect,
4585
+ workflows: phConfig.workflows,
4586
+ packageRegistryUrl: phPackageRegistryUrl ?? void 0,
4587
+ cliConnectOverride: connectOverride,
4588
+ branding: runtimeBranding
4589
+ });
4590
+ const servedConnect = configPlugin.api.connect;
4591
+ const faviconPath = options.favicon ?? configPlugin.api.favicon;
4592
+ const projectFavicons = resolveProjectFavicons(options.dirname, branding, brandWarn, faviconPath);
1961
4593
  const pwaPlugins = (async () => {
1962
4594
  if (!offlineEnabled) return connectPwaPlugins({ offlineEnabled });
1963
4595
  const contributions = await collectPackagePwaContributions({
@@ -1968,9 +4600,12 @@ function getConnectBaseViteConfig(options) {
1968
4600
  });
1969
4601
  const projectContribution = collectProjectPwaContribution({ projectRoot: options.dirname });
1970
4602
  if (projectContribution) contributions.push(projectContribution);
4603
+ const mergedPwa = mergePwaConfig(contributions, projectPwa, pwaWarn);
1971
4604
  return connectPwaPlugins({
1972
4605
  offlineEnabled,
1973
- pwa: mergePwaConfig(contributions, projectPwa, pwaWarn)
4606
+ pwa: mergedPwa,
4607
+ brand: projectBrand,
4608
+ staticFiles: staticFilesIn(join(options.dirname, "public"))
1974
4609
  });
1975
4610
  })();
1976
4611
  const reactExternal = [
@@ -1983,62 +4618,86 @@ function getConnectBaseViteConfig(options) {
1983
4618
  "@powerhousedao/reactor-browser",
1984
4619
  "@powerhousedao/connect",
1985
4620
  "@electric-sql/pglite"
1986
- ].map((pkg) => {
4621
+ ].flatMap((pkg) => {
4622
+ let real;
1987
4623
  try {
1988
- return searchForWorkspaceRoot(realpathSync(join(options.dirname, "node_modules", pkg)));
4624
+ real = realpathSync(join(options.dirname, "node_modules", pkg));
1989
4625
  } catch {
1990
- return null;
4626
+ return [];
1991
4627
  }
1992
- }).filter((p) => p !== null);
4628
+ const store = dependencyStoreOf(real);
4629
+ return [searchForWorkspaceRoot(real), ...store ? [store] : []];
4630
+ });
4631
+ const routesDir = resolveConnectRoutesDir(options.dirname, options.routes) ?? false;
4632
+ const mountedRoutesDir = routesDir || (mode === "development" && options.routes === void 0 ? join(options.dirname, "hosts/connect/routes") : false);
4633
+ const routes = connectRoutes(options.dirname, mountedRoutesDir);
4634
+ const customShell = hasProjectAppLayout(routesDir || void 0);
4635
+ const hostStylesheet = hostStylesheetPath(options.dirname, routesDir);
1993
4636
  return {
1994
4637
  configFile: false,
1995
4638
  mode,
4639
+ cacheDir: options.cacheDir,
1996
4640
  base: options.dynamicBase ? DYNAMIC_BASE_PLACEHOLDER : connectBasePath ? normalizeBasePath(connectBasePath) : void 0,
1997
4641
  server: {
1998
- watch: { ignored: ["**/backup-documents/**", "**/.ph/**"] },
4642
+ watch: { ignored: [
4643
+ "**/backup-documents/**",
4644
+ "**/coverage/**",
4645
+ ignoreDotPhButRouteTree(options.dirname, mountedRoutesDir),
4646
+ ignoreBuildOutput(options.dirname)
4647
+ ] },
1999
4648
  fs: { allow: [searchForWorkspaceRoot(options.dirname), ...linkedRoots] }
2000
4649
  },
2001
4650
  resolve: {
2002
- dedupe: ["react", "react-dom"],
4651
+ alias: routes.aliases,
4652
+ dedupe: [
4653
+ "react",
4654
+ "react-dom",
4655
+ ...routes.dedupe
4656
+ ],
2003
4657
  tsconfigPaths: true
2004
4658
  },
2005
4659
  define: {
2006
4660
  PH_CONNECT_SENTRY_RELEASE: JSON.stringify(release || "unknown"),
2007
- PH_CONNECT_BUILD_HASH: JSON.stringify(buildHash)
4661
+ PH_CONNECT_BUILD_HASH: JSON.stringify(buildHash),
4662
+ ...options.vendor?.sharedDeps && mode === "production" ? { PH_CONNECT_SHARED_DEPS_URL: JSON.stringify(options.vendor.sharedDeps) } : {},
4663
+ ...options.reactorWorkerVersion ? { PH_CONNECT_REACTOR_WORKER_VERSION: JSON.stringify(options.reactorWorkerVersion) } : {}
2008
4664
  },
2009
4665
  customLogger,
2010
4666
  envPrefix: ["PH_CONNECT_"],
2011
- optimizeDeps: {
2012
- include: [
2013
- "document-model",
2014
- "zod",
2015
- "@powerhousedao/design-system/connect",
2016
- "@powerhousedao/reactor-browser",
2017
- "@powerhousedao/document-engineering"
2018
- ],
2019
- exclude: ["@electric-sql/pglite", "@electric-sql/pglite-tools"]
2020
- },
4667
+ optimizeDeps: connectOptimizeDeps(options.dirname, mountedRoutesDir, routes.include),
2021
4668
  plugins: [
2022
- phConfigPlugin({
2023
- packages: phPackages,
2024
- projectRoot: options.dirname,
2025
- connect: phConfig.connect,
2026
- packageRegistryUrl: phPackageRegistryUrl ?? void 0,
2027
- cliConnectOverride: options.cliConnectOverride
2028
- }),
4669
+ configPlugin,
4670
+ hostStylesheetPlugin(options.dirname, hostStylesheet),
2029
4671
  phBundledPackagesPlugin({
2030
4672
  packages: localPackagesFromConfig,
2031
4673
  projectRoot: options.dirname
2032
4674
  }),
2033
- devReactImportmapPlugin(options.dirname),
4675
+ devReactImportmapPlugin(options.dirname, mountedRoutesDir),
4676
+ reactorWorkerDevPlugin(options.dirname),
4677
+ ...routes.plugins,
2034
4678
  ...plugins,
2035
- esmExternalRequirePlugin({ external: reactExternal }),
4679
+ esmExternalRequirePlugin({ external: [...reactExternal, ...options.vendor && mode === "production" ? Object.keys(options.vendor.imports) : []] }),
2036
4680
  reactSelfHostPlugin({
2037
4681
  dirname: options.dirname,
2038
4682
  dev: mode !== "production" || isDebug
2039
4683
  }),
2040
- connectFaviconPlugin({ faviconPath: options.favicon }),
4684
+ ...options.vendor && mode === "production" ? [vendorImportMapPlugin({ imports: options.vendor.imports })] : [],
4685
+ connectFaviconPlugin({ faviconPath }),
2041
4686
  connectThemeBootPlugin(),
4687
+ connectAppShellPlugin(options.dirname, {
4688
+ composition: servedConnect.composition,
4689
+ appName: servedConnect.branding?.appName ?? void 0,
4690
+ routeAliases: routesDir ? routes.aliases : void 0,
4691
+ routesDir: routesDir || void 0,
4692
+ loader: projectLoader,
4693
+ hostStylesheet
4694
+ }),
4695
+ connectProjectBrandPlugin({
4696
+ loader: projectLoader,
4697
+ pwaIcons: offlineEnabled ? projectBrand.icons : void 0,
4698
+ favicons: projectFavicons,
4699
+ customShell
4700
+ }),
2042
4701
  connectBuildHashPlugin(buildHash),
2043
4702
  ...options.dynamicBase ? [connectDynamicBasePlugin()] : [],
2044
4703
  pwaPlugins
@@ -2047,10 +4706,16 @@ function getConnectBaseViteConfig(options) {
2047
4706
  format: "es",
2048
4707
  ...options.dynamicBase ? { plugins: () => [connectDynamicBasePlugin({ forWorker: true })] } : {}
2049
4708
  },
2050
- build: { sourcemap: true }
4709
+ build: {
4710
+ sourcemap: true,
4711
+ rolldownOptions: {
4712
+ shimMissingExports: true,
4713
+ output: { codeSplitting: { groups: connectRouterChunkGroups(routesDir) } }
4714
+ }
4715
+ }
2051
4716
  };
2052
4717
  }
2053
4718
  //#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 };
4719
+ 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, CONNECT_ROUTE_FILE_DEPS, 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, connectRoutesWatcher, connectThemeBootPlugin, copyConnect, directoryContentDigest, distDirFingerprint, ensureNodeVersion, escapeForRegExp, findBundleSpecifierOffenders, findDisallowedSpecifiers, findPackageRoot, findWorkerUnsafeMarkers, generateConnectRoutes, getConnectBaseViteConfig, getConnectHtmlTags, hasProjectAppLayout, hostStylesheetPath, hostStylesheetPlugin, ignoreBuildOutput, ignoreDotPhButRouteTree, 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, withErrorOverlay, withHostStylesheet, withShellAppName, withSourceLocations, withVendorBase, workerSafeVendorImports };
2055
4720
 
2056
4721
  //# sourceMappingURL=index.mjs.map