@powerhousedao/builder-tools 6.2.3-dev.9 → 6.2.3-dev.91

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,498 +1,2762 @@
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
+ import { APP_SHELLS_FILE, SHELL_PLUGINS_FILE, appShellVariant, injectAppShell, readShellPluginsIn } from "@powerhousedao/shared/connect/app-shell";
5
6
  import { exec, execSync, spawn } from "node:child_process";
6
- import { fileURLToPath } from "node:url";
7
- import MagicString from "magic-string";
8
7
  import { readFile, writeFile } from "node:fs/promises";
9
8
  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";
9
+ import { Generator, getConfig } from "@tanstack/router-generator";
10
+ import { tanstackRouter } from "@tanstack/router-plugin/vite";
11
+ import { index, layout, physical, rootRoute, route } from "@tanstack/virtual-file-routes";
12
+ import { fileURLToPath, pathToFileURL } from "node:url";
13
+ 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";
14
+ 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";
15
+ import { createHash, randomUUID } from "node:crypto";
16
+ import MagicString from "magic-string";
17
+ import { initSync, parse } from "es-module-lexer";
18
+ import { getConfig as getConfig$1 } from "@powerhousedao/config/node";
12
19
  import tailwind from "@tailwindcss/vite";
13
20
  import react from "@vitejs/plugin-react";
14
- import { createLogger, esmExternalRequirePlugin, loadEnv, searchForWorkspaceRoot } from "vite";
15
- import { createHtmlPlugin } from "vite-plugin-html";
16
21
  import { PwaConfigSchema } from "@powerhousedao/shared/document-model";
17
22
  import { toCdnUrl } from "@powerhousedao/shared/registry/urls";
18
23
  import { VitePWA } from "vite-plugin-pwa";
24
+ export * from "@powerhousedao/shared/connect/app-shell";
19
25
  //#region connect-utils/constants.ts
20
26
  const EXTERNAL_PACKAGES_IMPORT = "PH:EXTERNAL_PACKAGES";
21
27
  const IMPORT_SCRIPT_FILE = "external-packages.js";
22
28
  const LOCAL_PACKAGE_ID = "ph:local-package";
23
29
  const PH_DIR_NAME = ".ph";
24
30
  //#endregion
25
- //#region connect-utils/vite-plugins/build-hash.ts
26
- /** Name of the build-identity file emitted into the build output. */
27
- const BUILD_HASH_FILE = "build-hash.json";
31
+ //#region connect-utils/helpers.ts
32
+ const DEFAULT_CONNECT_OUTDIR = ".ph/connect-build/dist/";
33
+ function resolveViteConfigPath(options) {
34
+ const { projectRoot = cwd(), viteConfigFile } = options;
35
+ return viteConfigFile || join(projectRoot, "vite.config.ts");
36
+ }
37
+ function resolvePackage(packageName, root = process.cwd()) {
38
+ return createRequire(root).resolve(packageName, { paths: [root] });
39
+ }
40
+ function resolveConnectPackageJson(root = process.cwd()) {
41
+ try {
42
+ const connectPackageJsonPath = resolvePackage("@powerhousedao/connect/package.json", root);
43
+ const fileContents = fs.readFileSync(connectPackageJsonPath, "utf-8");
44
+ return JSON.parse(fileContents);
45
+ } catch (error) {
46
+ console.error(`Error reading Connect package.json:`, error);
47
+ return null;
48
+ }
49
+ }
28
50
  /**
29
- * Deterministic identity of a Connect build. Differs whenever the deployed
30
- * content differs (published Connect version, project config, package list,
31
- * build options) so the SPA can detect "the server is serving a different
32
- * build than the one this bundle was built from" by comparing its baked copy
33
- * (define `PH_CONNECT_BUILD_HASH`) to `build-hash.json`, which the build
34
- * emits alongside the app and the server must serve no-cache.
51
+ * Finds the dist dir of Connect on the local machine
35
52
  */
36
- function computeBuildHash(input) {
37
- return createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 16);
53
+ function resolveConnectBundle(root = process.cwd()) {
54
+ const connectIndexPath = resolvePackage("@powerhousedao/connect", root);
55
+ const connectRootPath = connectIndexPath.substring(0, connectIndexPath.indexOf("connect") + 7);
56
+ return join(connectRootPath, "dist/");
57
+ }
58
+ function resolveConnectPublicDir(root = process.cwd()) {
59
+ const connectIconPath = resolvePackage("@powerhousedao/connect/public/icon.ico", root);
60
+ return path.join(connectIconPath, "../");
38
61
  }
39
62
  /**
40
- * Read the installed @powerhousedao/connect version. The package's `exports`
41
- * map does not expose a `./package.json` subpath, so `require.resolve(
42
- * "…/package.json")` throws — resolve the main entry and walk up to the
43
- * package root instead.
63
+ * Copies the Connect dist dir to the target path
44
64
  */
45
- function readConnectVersion(projectRoot) {
65
+ function copyConnect(sourcePath, targetPath) {
46
66
  try {
47
- let dir = dirname(createRequire(join(projectRoot, "package.json")).resolve("@powerhousedao/connect", { paths: [projectRoot] }));
48
- for (;;) {
49
- try {
50
- const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
51
- if (pkg.name === "@powerhousedao/connect") return pkg.version ?? "unknown";
52
- } catch {}
53
- const parent = dirname(dir);
54
- if (parent === dir) break;
55
- dir = parent;
56
- }
57
- } catch {}
58
- return "unknown";
67
+ fs.rmSync(targetPath, {
68
+ recursive: true,
69
+ force: true
70
+ });
71
+ fs.cpSync(sourcePath, targetPath, { recursive: true });
72
+ } catch (error) {
73
+ console.error(`❌ Error copying ${sourcePath} to ${targetPath}:`, error);
74
+ }
59
75
  }
60
- function buildHashFromBuildOptions(options) {
61
- return computeBuildHash({
62
- workspaceGitSha: process.env.WORKSPACE_GIT_SHA ?? "",
63
- workspaceVersion: process.env.WORKSPACE_VERSION ?? "",
64
- connectPackageVersion: readConnectVersion(options.dirname),
65
- projectConfig: options.phConfig,
66
- packages: options.packages.map((p) => `${p.packageName}@${p.version ?? ""}:${p.provider ?? ""}`),
67
- connectBasePath: options.connectBasePath ?? "",
68
- offlineEnabled: options.offlineEnabled,
69
- packageRegistryUrl: options.packageRegistryUrl ?? ""
76
+ /**
77
+ * Backs up the index.html file
78
+ *
79
+ * Needed when running the Connect Studio dev server on Windows
80
+ */
81
+ function backupIndexHtml(appPath, restore = false) {
82
+ const filePath = join(appPath, "index.html");
83
+ const backupPath = join(appPath, "index.html.bak");
84
+ const paths = restore ? [backupPath, filePath] : [filePath, backupPath];
85
+ if (fs.existsSync(paths[0])) fs.copyFileSync(paths[0], paths[1]);
86
+ }
87
+ function removeBase64EnvValues(appPath) {
88
+ backupIndexHtml(appPath);
89
+ const filePath = join(appPath, "index.html");
90
+ fs.readFile(filePath, "utf-8", (err, data) => {
91
+ if (err) {
92
+ console.error("Error reading file:", err);
93
+ return;
94
+ }
95
+ const modifiedData = data.replace(/"LOCAL_DOCUMENT_MODELS":\s*".*?",/, `"LOCAL_DOCUMENT_MODELS": "",`).replace(/"LOCAL_DOCUMENT_EDITORS":\s*".*?"/, `"LOCAL_DOCUMENT_EDITORS": ""`);
96
+ console.log("Modified data:", modifiedData);
97
+ fs.writeFile(filePath, modifiedData, "utf-8", (err) => {
98
+ if (err) {
99
+ console.error("Error writing file:", err);
100
+ return;
101
+ }
102
+ });
70
103
  });
71
104
  }
105
+ function readJsonFile(filePath) {
106
+ try {
107
+ const absolutePath = resolve(filePath);
108
+ const fileContents = fs.readFileSync(absolutePath, "utf-8");
109
+ return JSON.parse(fileContents);
110
+ } catch (_error) {
111
+ console.error(`Error reading file: ${filePath}`);
112
+ return null;
113
+ }
114
+ }
72
115
  /**
73
- * Emits `build-hash.json` (`{"hash": "<build id>"}`) into the build output.
74
- * Emitted as an asset so it lands at the deploy base like every other file.
75
- * Build-only: dev (studio) never runs generateBundle, and the SPA check
76
- * treats a missing file as "nothing to compare" and stays silent.
116
+ * 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.
77
117
  */
78
- function connectBuildHashPlugin(buildHash) {
118
+ function makeImportScriptFromPackages(args) {
119
+ const { packages, localJsPath, localCssPath, importStyles = true } = args;
120
+ const imports = [];
121
+ const moduleNames = [];
122
+ let counter = 0;
123
+ for (const packageName of packages) {
124
+ const moduleName = `module${counter}`;
125
+ moduleNames.push(moduleName);
126
+ imports.push(`import * as ${moduleName} from '${packageName}';`);
127
+ if (importStyles) imports.push(`import '${packageName}/style.css';`);
128
+ counter++;
129
+ }
130
+ const exports = moduleNames.map((name, index) => `{
131
+ id: "${packages[index]}",
132
+ ...${name},
133
+ }`);
134
+ const hasModule = localJsPath !== void 0;
135
+ const hasStyles = importStyles && localCssPath !== void 0;
136
+ if (hasModule || hasStyles) {
137
+ if (hasStyles) imports.push(`import '${localCssPath}';`);
138
+ if (hasModule) {
139
+ const moduleName = `module${counter}`;
140
+ imports.push(`import * as ${moduleName} from '${localJsPath}';`);
141
+ exports.push(`{
142
+ id: "${LOCAL_PACKAGE_ID}",
143
+ ...${moduleName},
144
+ }`);
145
+ }
146
+ }
147
+ const exportStatement = `export default [${exports.length ? `
148
+ ${exports.join(",\n")}
149
+ ` : ""}];`;
150
+ return `${imports.join("\n")}\n\n${exportStatement}`;
151
+ }
152
+ function ensureNodeVersion(minVersion = "24") {
153
+ const version = process.versions.node;
154
+ if (!version) return;
155
+ if (version < minVersion) {
156
+ console.error(`Node version ${minVersion} or higher is required. Current version: ${version}`);
157
+ process.exit(1);
158
+ }
159
+ }
160
+ function runShellScriptPlugin(scriptName, connectPath) {
79
161
  return {
80
- name: "ph-connect-build-hash",
81
- apply: "build",
82
- generateBundle() {
83
- this.emitFile({
84
- type: "asset",
85
- fileName: BUILD_HASH_FILE,
86
- source: `${JSON.stringify({ hash: buildHash }, null, 2)}\n`
162
+ name: "vite-plugin-run-shell-script",
163
+ buildStart() {
164
+ const scriptPath = join(connectPath, scriptName);
165
+ if (fs.existsSync(scriptPath)) exec(`sh ${scriptPath}`, (error, stdout, stderr) => {
166
+ if (error) {
167
+ console.error(`Error executing the script: ${error.message}`);
168
+ removeBase64EnvValues(connectPath);
169
+ return;
170
+ }
171
+ if (stderr) console.error(stderr);
87
172
  });
88
173
  }
89
174
  };
90
175
  }
91
- //#endregion
92
- //#region connect-utils/vite-plugins/dynamic-base.ts
93
176
  /**
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.
177
+ * Shared helper to modify the <head> tag of an HTML file by transforming its contents.
101
178
  */
102
- const DYNAMIC_BASE_PLACEHOLDER = "/__PH_DYNAMIC_BASE__/";
179
+ async function modifyHtmlHead(pathToHtml, contents, transform) {
180
+ if (!existsSync(pathToHtml)) throw new Error(`File ${pathToHtml} does not exist.`);
181
+ let html = await readFile(pathToHtml, "utf8");
182
+ html = transform(html, contents);
183
+ await writeFile(pathToHtml, html, "utf8");
184
+ }
103
185
  /**
104
- * Global the runtime (ph-clint proxy) must set before the entry bundle loads.
105
- * Value is the normalized deploy base, e.g. "/myagent/" or "/". The JS rewrite
106
- * below resolves all asset / lazy-chunk / BASE_URL references against it.
186
+ * Appends the contents to the <head> tag of the index.html file
107
187
  */
108
- const RUNTIME_GLOBAL = "globalThis.__PH_DYNAMIC_BASE__";
109
- const BASE_EXPR = `(${RUNTIME_GLOBAL}||"/")`;
110
- function workerPrelude(stripPrefix) {
111
- return `${RUNTIME_GLOBAL}=self.location.pathname.replace(/${escapeForRegExp(stripPrefix).replace(/\//g, "\\/")}assets\\/[^/]*$/,"");\n`;
188
+ async function appendToHtmlHead(pathToHtml, contents) {
189
+ return modifyHtmlHead(pathToHtml, contents, (html, contents) => {
190
+ if (!html.includes("</head>")) throw new Error("No </head> tag found in the HTML file.");
191
+ return html.replace("</head>", `\n${contents}\n</head>`);
192
+ });
112
193
  }
113
- const PLACEHOLDER_LITERAL = new RegExp(`(["'\`])${escapeForRegExp(DYNAMIC_BASE_PLACEHOLDER)}((?:(?!\\1)[^$])*)\\1`, "g");
114
194
  /**
115
- * Rewrites the placeholder base in emitted JS chunks to a runtime expression so
116
- * one built `dist/connect` serves under any subpath. Rolldown-native: per-match
117
- * MagicString edits in `renderChunk`, no AST splicing (the SWC byte-offset
118
- * splicing in vite-plugin-dynamic-base corrupts Rolldown chunks). Each edited
119
- * chunk returns a hires sourcemap that the bundler composes into the chunk's
120
- * map chain, so the emitted `.map` files track the rewrite (and the worker
121
- * prelude's line shift).
122
- *
123
- * What gets rewritten in JS, all of which emit the base as a quoted string
124
- * literal beginning with the placeholder:
125
- * - asset URLs (`new URL("/__PH_DYNAMIC_BASE__/assets/x.png", ...)`)
126
- * - dynamic-import / lazy-chunk preload URLs
127
- * - the inlined `import.meta.env.BASE_URL` (drives Connect's router basename
128
- * and BASE_URL-relative fetches such as `${BASE_URL}ph-packages.json`)
129
- *
130
- * A literal `"/__PH_DYNAMIC_BASE__/foo"` becomes `((globalThis.__PH_DYNAMIC_BASE__||"/")+"foo")`;
131
- * a bare `"/__PH_DYNAMIC_BASE__/"` (the BASE_URL value) becomes `(globalThis.__PH_DYNAMIC_BASE__||"/")`.
132
- *
133
- * HTML is left untouched: the entry `<script>`/`<link>` tags keep the literal
134
- * placeholder so the proxy substitutes it with the concrete base at serve time
135
- * (the same proxy also sets the runtime global for the JS rewrite). See the
136
- * plugin's module doc / report for the exact serve-time contract.
137
- *
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).
195
+ * Prepends the contents to the <head> tag of the index.html file
141
196
  */
142
- function connectDynamicBasePlugin(options = {}) {
143
- return {
144
- name: "ph-connect-dynamic-base",
145
- enforce: "post",
146
- renderChunk(code, chunk) {
147
- if (!code.includes("/__PH_DYNAMIC_BASE__/")) return null;
148
- const s = new MagicString(code);
149
- for (const match of code.matchAll(PLACEHOLDER_LITERAL)) {
150
- const rest = match[2];
151
- s.overwrite(match.index, match.index + match[0].length, rest.length === 0 ? BASE_EXPR : `(${BASE_EXPR}+${JSON.stringify(rest)})`);
152
- }
153
- if (options.forWorker) {
154
- s.prepend(workerPrelude(options.workerStripPrefix ?? ""));
155
- this.info(`dynamic-base: worker prelude prepended to ${chunk.fileName}`);
156
- }
157
- if (!s.hasChanged()) return null;
158
- return {
159
- code: s.toString(),
160
- map: s.generateMap({ hires: true })
161
- };
162
- },
163
- 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}`);
165
- }
166
- };
197
+ async function prependToHtmlHead(pathToHtml, contents) {
198
+ return modifyHtmlHead(pathToHtml, contents, (html, contents) => {
199
+ if (!html.includes("</head>")) throw new Error("No </head> tag found in the HTML file.");
200
+ return html.replace("<head>", `<head>\n${contents}\n`);
201
+ });
167
202
  }
168
- function escapeForRegExp(s) {
203
+ function runTsc(outDir) {
204
+ execSync(`npx tsc --outDir ${outDir}`, { stdio: "inherit" });
205
+ }
206
+ function stripVersionFromPackage(packageName) {
207
+ const trimmed = packageName.trim();
208
+ if (!trimmed) return "";
209
+ const lastAtIndex = trimmed.lastIndexOf("@");
210
+ if (lastAtIndex > 0) return trimmed.substring(0, lastAtIndex);
211
+ return trimmed;
212
+ }
213
+ //#endregion
214
+ //#region connect-utils/vite-plugins/connect-routes.ts
215
+ /** A project's routes for its Connect deployment, beside Connect's own. */
216
+ const HOST_ROUTES_DIR = "hosts/connect/routes";
217
+ /** The generated tree of Connect's and the project's routes. */
218
+ const CONNECT_ROUTES_GEN = ".ph/connect-routes.gen.ts";
219
+ /** Connect's dist imports its route tree by this specifier. */
220
+ const ROUTE_TREE_SPECIFIER = "@powerhousedao/connect/route-tree";
221
+ /** Core's types name the app's tree by this one; both resolve to one tree. */
222
+ const CORE_ROUTE_TREE_SPECIFIER = "@powerhousedao/connect-core/route-tree";
223
+ const ROUTE_TREE_FIND = new RegExp(`^(${[ROUTE_TREE_SPECIFIER, CORE_ROUTE_TREE_SPECIFIER].map(escapeRegExp).join("|")})$`);
224
+ /** A host's routes folder: `routes` (a host's `runner.routes`), relative to the
225
+ * project, else `hosts/connect/routes/`; undefined if none or `false`. */
226
+ function resolveConnectRoutesDir(projectRoot, routes) {
227
+ if (routes === false) return void 0;
228
+ if (routes !== void 0) {
229
+ const dir = resolve(projectRoot, routes);
230
+ if (!existsSync(dir)) throw new Error(`The routes folder ${routes} does not exist.`);
231
+ return dir;
232
+ }
233
+ const dir = join(projectRoot, HOST_ROUTES_DIR);
234
+ return existsSync(dir) ? dir : void 0;
235
+ }
236
+ const isDefaultRoutesDir = (projectRoot, routesDir) => resolve(routesDir) === join(resolve(projectRoot), HOST_ROUTES_DIR);
237
+ /** The tree generated from `routesDir`: `.ph/connect-routes.gen.ts` for
238
+ * `hosts/connect/routes/`, else `.ph/<folder>.gen.ts`. */
239
+ function connectRoutesTreeOf(projectRoot, routesDir) {
240
+ if (isDefaultRoutesDir(projectRoot, routesDir)) return join(projectRoot, CONNECT_ROUTES_GEN);
241
+ return join(projectRoot, ".ph", `${relative(projectRoot, routesDir)}.gen.ts`);
242
+ }
243
+ /** The dev watcher's filter for `.ph/`, which holds build output: ignored but
244
+ * for the host's route tree, rewritten as route files come and go. */
245
+ function ignoreDotPhButRouteTree(projectRoot, routesDir) {
246
+ const tree = routesDir && normalizePath(connectRoutesTreeOf(projectRoot, routesDir));
247
+ return (file) => {
248
+ const path = normalizePath(resolve(projectRoot, file));
249
+ if (!path.includes("/.ph/")) return false;
250
+ return !tree || path !== tree && !tree.startsWith(`${path}/`);
251
+ };
252
+ }
253
+ /**
254
+ * The dev watcher's filter for the project's build output: its own `dist/`
255
+ * and a Tauri shell's Rust `target/`. Nothing the dev server serves lives
256
+ * there, and on Windows every watched file costs a synchronous `fs.watch`
257
+ * at startup (over a minute for a built project with a built desktop shell).
258
+ */
259
+ function ignoreBuildOutput(projectRoot) {
260
+ const dist = `${normalizePath(resolve(projectRoot, "dist"))}/`;
261
+ return (file) => {
262
+ const path = normalizePath(resolve(projectRoot, file));
263
+ return path.startsWith(dist) || path.includes("/tauri-shell/target/") || path.includes("/src-tauri/target/");
264
+ };
265
+ }
266
+ /** Whether a watched path is in `routesDir` or is the folder itself. */
267
+ function inRoutesDir(projectRoot, routesDir) {
268
+ let watchedAs;
269
+ return (file) => {
270
+ watchedAs ??= [routesDir, join(realpathSync(projectRoot), relative(projectRoot, routesDir))];
271
+ const path = resolve(projectRoot, file);
272
+ return watchedAs.some((dir) => path === dir || path.startsWith(`${dir}${sep}`));
273
+ };
274
+ }
275
+ /** Connect's pathless sidebar layout; a project's routes in `_app/` render in it. */
276
+ const APP_LAYOUT = "_app";
277
+ function findRouteFile(dir, name) {
278
+ return [
279
+ ".tsx",
280
+ ".ts",
281
+ ".jsx",
282
+ ".js"
283
+ ].map((ext) => join(dir, `${name}${ext}`)).find((file) => existsSync(file));
284
+ }
285
+ /** Whether the project's `_app` replaces Connect's layout (and its chrome). */
286
+ function hasProjectAppLayout(routesDir) {
287
+ return !!routesDir && !!findRouteFile(routesDir, "_app");
288
+ }
289
+ /** Connect's route files: core's routes with Connect's views. */
290
+ function connectRoutesDirOf(connectDir) {
291
+ return join(connectDir, "src/routes");
292
+ }
293
+ const ROUTE_FILE = /\.[cm]?[jt]sx?$/;
294
+ const isRouteEntry = (name) => !name.startsWith(".") && !name.startsWith("-") && !/\.d\.[cm]?ts$/.test(name);
295
+ /** The route files under `dir`, by path relative to it. */
296
+ function routeFilesIn(dir, at = "") {
297
+ if (!existsSync(dir)) return [];
298
+ return readdirSync(join(dir, at), { withFileTypes: true }).filter((entry) => isRouteEntry(entry.name)).flatMap((entry) => {
299
+ const path = at ? `${at}/${entry.name}` : entry.name;
300
+ if (entry.isDirectory()) return routeFilesIn(dir, path);
301
+ return ROUTE_FILE.test(entry.name) ? [path] : [];
302
+ });
303
+ }
304
+ /** A route file's id below its folder: route groups and `route` files
305
+ * resolved, flat `a.b` names read as folders. */
306
+ function routeIdOf(file) {
307
+ const segments = file.replace(ROUTE_FILE, "").split("/").filter((segment) => !/^\(.+\)$/.test(segment));
308
+ if (segments.at(-1) === "route") segments.pop();
309
+ return segments.join("/").replaceAll(".", "/");
310
+ }
311
+ /** Connect's `_app/` route files that a project file at the same id replaces. */
312
+ function overriddenConnectRoutes(connectAppDir, projectAppDir) {
313
+ const projectIds = new Set(routeFilesIn(projectAppDir).map(routeIdOf));
314
+ return new Set(routeFilesIn(connectAppDir).filter((file) => projectIds.has(routeIdOf(file))));
315
+ }
316
+ const stemOf = (name) => name.replace(ROUTE_FILE, "");
317
+ /** Mounts Connect's routes in `dir` without the `overridden` files: a folder
318
+ * whole when none is in it, else file by file. */
319
+ function mountConnectRoutes(routesDirectory, dir, overridden, prefix = "") {
320
+ if (![...overridden].some((file) => file.startsWith(`${dir}/`))) return [physical(prefix, dir)];
321
+ const entries = readdirSync(join(routesDirectory, dir), { withFileTypes: true }).filter((entry) => isRouteEntry(entry.name));
322
+ const files = entries.filter((entry) => entry.isFile() && ROUTE_FILE.test(entry.name)).map((entry) => entry.name);
323
+ const folders = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
324
+ const at = (name) => prefix ? `${prefix}/${name}` : name;
325
+ const nodes = [];
326
+ for (const name of files) {
327
+ const file = `${dir}/${name}`;
328
+ const stem = stemOf(name);
329
+ const folder = folders.includes(stem) ? `${dir}/${stem}` : void 0;
330
+ if (overridden.has(file)) {
331
+ if (folder) nodes.push(physical(at(stem), folder));
332
+ continue;
333
+ }
334
+ const children = folder && mountConnectRoutes(routesDirectory, folder, overridden);
335
+ if (stem === "index") nodes.push(prefix ? route(`${prefix}/`, file) : index(file));
336
+ else if (!prefix && stem.startsWith("_")) nodes.push(layout(stem, file, children || []));
337
+ else nodes.push(children ? route(at(stem), file, children) : route(at(stem), file));
338
+ }
339
+ for (const name of folders) {
340
+ if (files.some((file) => stemOf(file) === name)) continue;
341
+ nodes.push(...mountConnectRoutes(routesDirectory, `${dir}/${name}`, overridden, at(name)));
342
+ }
343
+ return nodes;
344
+ }
345
+ /** The routes a package offers other Connects, as `ph build` publishes them
346
+ * (`./connect-routes`); generated beside the route tree. */
347
+ const PACKAGE_ROUTES_MODULE = ".ph/connect-routes.package.ts";
348
+ /** Writes the package's routes for registerPackageRoutes: its files but its
349
+ * `_app` layout and its overrides of Connect's `_app/` routes, parents first. */
350
+ function writePackageRoutesModule(projectRoot, projectRoutes, routeNodes, options) {
351
+ const module = join(projectRoot, PACKAGE_ROUTES_MODULE);
352
+ const appDir = join(projectRoutes, APP_LAYOUT);
353
+ const offered = routeNodes.map((node) => ({
354
+ node,
355
+ file: join(options.routesDirectory, node.filePath)
356
+ })).filter(({ node, file }) => {
357
+ if (!file.startsWith(`${projectRoutes}${sep}`)) return false;
358
+ if (node.routePath === `/_app`) return false;
359
+ if (!file.startsWith(`${appDir}${sep}`)) return true;
360
+ const id = routeIdOf(relative(appDir, file).split(sep).join("/"));
361
+ return !options.connectAppIds.has(id);
362
+ }).sort((a, b) => (a.node.routePath ?? "").split("/").length - (b.node.routePath ?? "").split("/").length);
363
+ if (offered.length === 0) {
364
+ rmSync(module, { force: true });
365
+ return;
366
+ }
367
+ const from = (file) => {
368
+ return relative(dirname(module), file).split(sep).join("/").replace(ROUTE_FILE, ".js");
369
+ };
370
+ const lines = [
371
+ "// Generated by ph build: the routes this package offers other Connects.",
372
+ "import type { PackageRoute } from \"@powerhousedao/connect-core/router\";",
373
+ ...offered.map(({ file }, i) => `import { Route as r${i} } from "${from(file)}";`),
374
+ "",
375
+ "export const connectRoutes: PackageRoute[] = [",
376
+ ...offered.map(({ node }, i) => {
377
+ const pathless = node._fsRouteType === "pathless_layout";
378
+ const entry = {
379
+ id: node.routePath,
380
+ ...pathless ? {} : { path: node.path },
381
+ parentId: node.parent?.routePath ?? "__root__"
382
+ };
383
+ return ` { route: r${i}, ${Object.entries(entry).map(([key, value]) => `${key}: ${JSON.stringify(value)}`).join(", ")} },`;
384
+ }),
385
+ "];",
386
+ ""
387
+ ];
388
+ mkdirSync(dirname(module), { recursive: true });
389
+ const text = lines.join("\n");
390
+ if (!existsSync(module) || readFileSync(module, "utf8") !== text) writeFileSync(module, text);
391
+ }
392
+ /** The `_app/` paths of the generic plugin's code routes, e.g. its settings
393
+ * tabs: a project file at one is an override, never offered. */
394
+ function genericAppRouteIds(connectDir) {
395
+ const file = join(connectDir, "generic-routes.json");
396
+ if (!existsSync(file)) return [];
397
+ return JSON.parse(readFileSync(file, "utf8")).appRoutes ?? [];
398
+ }
399
+ /** The router plugin's config: Connect's root and routes, and the project's. */
400
+ function connectRoutesGeneratorConfig(connectDir, projectRoot, projectRoutes) {
401
+ const routesDirectory = connectRoutesDirOf(connectDir);
402
+ const fromRoutes = (path) => relative(routesDirectory, path);
403
+ const virtualRouteConfig = () => {
404
+ const appLayout = findRouteFile(projectRoutes, APP_LAYOUT);
405
+ const appRoutes = join(projectRoutes, APP_LAYOUT);
406
+ const overridden = new Set([...overriddenConnectRoutes(join(routesDirectory, APP_LAYOUT), appRoutes)].map((file) => `${APP_LAYOUT}/${file}`));
407
+ 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))] : []]);
408
+ };
409
+ const generatedRouteTree = connectRoutesTreeOf(projectRoot, projectRoutes);
410
+ const inProjectRoutes = inRoutesDir(projectRoot, projectRoutes);
411
+ const overrides = {
412
+ name: "ph-connect-route-overrides",
413
+ init: ({ generator }) => {
414
+ Object.defineProperty(generator.config, "virtualRouteConfig", {
415
+ get: virtualRouteConfig,
416
+ configurable: true,
417
+ enumerable: true
418
+ });
419
+ importConnectRoutesByPackage(generator, generatedRouteTree);
420
+ followProjectRoutes(generator, inProjectRoutes);
421
+ }
422
+ };
423
+ const offers = isDefaultRoutesDir(projectRoot, projectRoutes);
424
+ return getConfig({
425
+ target: "react",
426
+ routesDirectory,
427
+ generatedRouteTree,
428
+ virtualRouteConfig: virtualRouteConfig(),
429
+ plugins: offers ? [overrides, {
430
+ name: "ph-connect-offered-routes",
431
+ onRouteTreeChanged: ({ routeNodes }) => {
432
+ writePackageRoutesModule(projectRoot, projectRoutes, routeNodes, {
433
+ routesDirectory,
434
+ connectAppIds: /* @__PURE__ */ new Set([...routeFilesIn(join(routesDirectory, APP_LAYOUT)).map(routeIdOf), ...genericAppRouteIds(connectDir)])
435
+ });
436
+ }
437
+ }] : [overrides],
438
+ routeFileIgnorePattern: `^(${APP_LAYOUT}(\\.[cm]?[jt]sx?)?|.+\\.d\\.[cm]?ts)$`,
439
+ quoteStyle: "double",
440
+ semicolons: true,
441
+ addExtensions: "js",
442
+ autoCodeSplitting: true,
443
+ disableLogging: true,
444
+ routeTreeFileFooter: [
445
+ "import type { ConnectRouterFor } from \"@powerhousedao/connect/router\";",
446
+ "declare module \"@tanstack/react-router\" {",
447
+ " interface Register {",
448
+ " router: ConnectRouterFor<typeof routeTree>;",
449
+ " }",
450
+ "}"
451
+ ]
452
+ }, projectRoot);
453
+ }
454
+ const reported = /* @__PURE__ */ new Map();
455
+ function reportDrops(file, messages) {
456
+ const key = messages.join("\n");
457
+ if (reported.get(file) === key) return;
458
+ reported.set(file, key);
459
+ for (const message of messages) console.warn(`[connect] ${message}`);
460
+ }
461
+ /** Writes the route tree of Connect's and the project's routes; throws on a
462
+ * collision that is not an override, which the router plugin would only log. */
463
+ async function generateConnectRoutes(projectRoot, routesDir, config = connectRoutesGeneratorConfig(connectDirOf(projectRoot), projectRoot, routesDir), warn) {
464
+ mkdirSync(dirname(config.generatedRouteTree), { recursive: true });
465
+ let routeNodes = [];
466
+ const collect = {
467
+ name: "ph-connect-route-urls",
468
+ onRouteTreeChanged: (tree) => {
469
+ routeNodes = tree.routeNodes;
470
+ }
471
+ };
472
+ try {
473
+ await new Generator({
474
+ config: {
475
+ ...config,
476
+ plugins: [...config.plugins ?? [], collect]
477
+ },
478
+ root: projectRoot
479
+ }).run();
480
+ assertNoSharedUrls(routeNodes);
481
+ assertNoDuplicateRoutes(config.generatedRouteTree);
482
+ const drops = dropsContext(projectRoot, routesDir, config.routesDirectory);
483
+ for (const node of routeNodes) {
484
+ const found = dropsOf(node, drops);
485
+ if (!found) continue;
486
+ if (warn) found.messages.forEach(warn);
487
+ else reportDrops(found.file, found.messages);
488
+ }
489
+ } catch (error) {
490
+ const message = (Array.isArray(error) ? error : [error]).map((e) => e instanceof Error ? e.message : String(e)).join("\n");
491
+ const shown = relative(projectRoot, routesDir).split(sep).join("/");
492
+ throw new Error(`Connect could not mount the routes in ${shown}/:\n${message}`, { cause: error });
493
+ }
494
+ }
495
+ /** Connect's route files, as the generated tree imports them: by Connect's
496
+ * package name, which a project depends on. */
497
+ const CONNECT_ROUTES_SPECIFIER = "@powerhousedao/connect/routes";
498
+ function importConnectRoutesByPackage(generator, treeFile) {
499
+ const writer = generator;
500
+ const write = writer.safeFileWrite.bind(writer);
501
+ writer.safeFileWrite = (opts) => {
502
+ if (resolve(opts.filePath) !== resolve(treeFile)) return write(opts);
503
+ const prefix = `"./${relative(dirname(treeFile), writer.config.routesDirectory).split(sep).join("/")}/`;
504
+ const newContent = opts.newContent.replace(new RegExp(`${escapeRegExp(prefix)}([^"]+)\\.js"`, "g"), `"${CONNECT_ROUTES_SPECIFIER}/$1"`);
505
+ return write({
506
+ ...opts,
507
+ newContent
508
+ });
509
+ };
510
+ }
511
+ function followProjectRoutes(generator, inProjectRoutes) {
512
+ const checker = generator;
513
+ const relevant = checker.isFileRelevantForRouteTreeGeneration.bind(checker);
514
+ checker.isFileRelevantForRouteTreeGeneration = (file) => relevant(file) || inProjectRoutes(file);
515
+ }
516
+ function assertNoDuplicateRoutes(treeFile) {
517
+ const tree = readFileSync(treeFile, "utf8");
518
+ const files = /* @__PURE__ */ new Map();
519
+ for (const [, name, file] of tree.matchAll(/^import \{ Route as (\w+) \} from "([^"]+)";$/gm)) files.set(name, [...files.get(name) ?? [], file]);
520
+ const conflicts = [...files.values()].filter((list) => list.length > 1);
521
+ if (conflicts.length === 0) return;
522
+ throw new Error(`Conflicting configuration paths were found for a layout route.\nConflicting files: \n ${conflicts.flat().join("\n ")}\n`);
523
+ }
524
+ const urlOf = (routePath) => `/${routePath.split("/").filter((segment) => segment && !segment.startsWith("_")).join("/")}`;
525
+ function assertNoSharedUrls(routeNodes) {
526
+ const byUrl = /* @__PURE__ */ new Map();
527
+ for (const node of routeNodes) {
528
+ if (node._fsRouteType === "pathless_layout" || !node.routePath) continue;
529
+ const url = urlOf(node.routePath);
530
+ byUrl.set(url, [...byUrl.get(url) ?? [], node.fullPath]);
531
+ }
532
+ const shared = [...byUrl].filter(([, files]) => files.length > 1);
533
+ if (shared.length === 0) return;
534
+ 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"));
535
+ }
536
+ /** The object literal after `key:` in `source`, braces balanced; strings aren't parsed. */
537
+ function objectAfter(source, key) {
538
+ const start = source.search(new RegExp(`\\b${key}\\s*:\\s*\\{`));
539
+ if (start < 0) return void 0;
540
+ const open = source.indexOf("{", start);
541
+ let depth = 0;
542
+ for (let i = open; i < source.length; i++) if (source[i] === "{") depth++;
543
+ else if (source[i] === "}" && --depth === 0) return source.slice(open, i + 1);
544
+ }
545
+ function dropsContext(projectRoot, routesDir, routesDirectory) {
546
+ return {
547
+ projectRoot,
548
+ routesDir,
549
+ routesDirectory,
550
+ connectAppIds: new Set(routeFilesIn(join(routesDirectory, APP_LAYOUT)).map(routeIdOf)),
551
+ genericAppIds: new Set(genericAppRouteIds(dirname(dirname(routesDirectory))))
552
+ };
553
+ }
554
+ /** What the router drops from a project route file without a word: a nav item
555
+ * it can't link, and an override without the options of the route it replaces. */
556
+ function dropsOf(node, context) {
557
+ const file = join(context.routesDirectory, node.filePath);
558
+ if (!file.startsWith(`${context.routesDir}${sep}`) || !existsSync(file)) return;
559
+ const shown = relative(context.projectRoot, file).split(sep).join("/");
560
+ const source = readFileSync(file, "utf8");
561
+ const messages = [];
562
+ const staticData = objectAfter(source, "staticData");
563
+ 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.`);
564
+ const appDir = join(context.routesDir, APP_LAYOUT);
565
+ if (file.startsWith(`${appDir}${sep}`)) {
566
+ const id = routeIdOf(relative(appDir, file).split(sep).join("/"));
567
+ const connectFile = `@powerhousedao/connect/routes/${APP_LAYOUT}/${id}`;
568
+ 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}".`);
569
+ if (context.genericAppIds.has(id) && !source.includes("genericSettingsTabs")) {
570
+ const tab = id.split("/").at(-1);
571
+ messages.push(`${shown} replaces a settings tab without its options, so the tab isn't listed; spread genericSettingsTabs["${tab}"] from "@powerhousedao/connect/generic".`);
572
+ }
573
+ }
574
+ return {
575
+ file,
576
+ messages
577
+ };
578
+ }
579
+ /** Warns, as Studio regenerates the tree, about each route file it rewrites. */
580
+ function dropsPlugin(projectRoot, routesDir, routesDirectory) {
581
+ const context = dropsContext(projectRoot, routesDir, routesDirectory);
582
+ return {
583
+ name: "ph-connect-silent-drops",
584
+ afterTransform: ({ node }) => {
585
+ const found = dropsOf(node, context);
586
+ if (found) reportDrops(found.file, found.messages);
587
+ }
588
+ };
589
+ }
590
+ function escapeRegExp(text) {
591
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
592
+ }
593
+ /** Generates the tree when the project has routes. Without them, a tree there
594
+ * is rewritten with Connect's routes only, never removed: Studio routes
595
+ * through it, and a removed folder's routes leave it, as tsc needs. */
596
+ async function syncConnectRoutes(projectRoot, routesDir = resolveConnectRoutesDir(projectRoot)) {
597
+ if (routesDir) {
598
+ await generateConnectRoutes(projectRoot, routesDir);
599
+ return;
600
+ }
601
+ rmSync(join(projectRoot, PACKAGE_ROUTES_MODULE), { force: true });
602
+ if (existsSync(join(projectRoot, ".ph/connect-routes.gen.ts"))) await generateConnectRoutes(projectRoot, join(projectRoot, HOST_ROUTES_DIR));
603
+ }
604
+ function connectDirOf(projectRoot) {
605
+ return dirname(resolvePackage("@powerhousedao/connect/package.json", projectRoot));
606
+ }
607
+ /** What Connect's route files import, besides each other. */
608
+ const CONNECT_ROUTE_FILE_DEPS = [
609
+ "@tanstack/react-router",
610
+ "@powerhousedao/connect-core/router",
611
+ "@powerhousedao/connect/route-views"
612
+ ];
613
+ const IN_NODE_MODULES = /[\\/]node_modules[\\/]/;
614
+ /**
615
+ * The `optimizeDeps.include` entries an installed Connect's route files need.
616
+ *
617
+ * Connect and core ship their route files as `.tsx`, which Vite never
618
+ * pre-bundles, so the dev server serves them as they are. Vite also discovers
619
+ * no dependency for a module inside node_modules, so their bare imports load
620
+ * unbundled too, and the CommonJS packages under the router
621
+ * (use-sync-external-store, safe-stable-stringify) then fail in the browser.
622
+ * Pre-bundling these by Connect's name gives the route files the copies they
623
+ * resolve to; core need not be resolvable from the project. A Connect outside
624
+ * node_modules (the monorepo, a linked checkout) is source to Vite, so its
625
+ * imports are discovered and pre-bundled anyway.
626
+ */
627
+ function connectRouteFileDeps(connectDir) {
628
+ if (!IN_NODE_MODULES.test(connectDir)) return [];
629
+ return CONNECT_ROUTE_FILE_DEPS.map((dep) => `@powerhousedao/connect > ${dep}`);
630
+ }
631
+ /** Mounts a project's routes folder over Connect's routes; without one,
632
+ * Connect keeps its prebuilt tree and no router plugin runs. Dev may pass a
633
+ * folder that does not exist yet: it is mounted once it does. */
634
+ function connectRoutes(projectRoot, routesDir = resolveConnectRoutesDir(projectRoot)) {
635
+ const connectDir = connectDirOf(projectRoot);
636
+ const find = ROUTE_TREE_FIND;
637
+ const include = connectRouteFileDeps(connectDir);
638
+ if (!routesDir) return {
639
+ aliases: [{
640
+ find,
641
+ replacement: join(connectDir, "dist/route-tree.js")
642
+ }],
643
+ plugins: [],
644
+ dedupe: [],
645
+ include
646
+ };
647
+ const config = connectRoutesGeneratorConfig(connectDir, projectRoot, routesDir);
648
+ mkdirSync(dirname(config.generatedRouteTree), { recursive: true });
649
+ return {
650
+ aliases: [{
651
+ find,
652
+ replacement: config.generatedRouteTree
653
+ }, {
654
+ find: /^@powerhousedao\/connect\/route-views$/,
655
+ replacement: join(connectDir, "dist/route-views.js")
656
+ }],
657
+ plugins: [
658
+ {
659
+ name: "ph-connect-routes-check",
660
+ buildStart: () => generateConnectRoutes(projectRoot, routesDir, config)
661
+ },
662
+ tanstackRouter({
663
+ ...config,
664
+ plugins: [...config.plugins ?? [], dropsPlugin(projectRoot, routesDir, config.routesDirectory)]
665
+ }),
666
+ connectRoutesWatcher(projectRoot, routesDir, config)
667
+ ],
668
+ dedupe: ["@tanstack/react-router"],
669
+ include
670
+ };
671
+ }
672
+ /** Dev: rewrites the tree as files and folders under the routes folder come and
673
+ * go, the folder itself included; the router plugin follows the tree. */
674
+ function connectRoutesWatcher(projectRoot, routesDir, config) {
675
+ const inRoutes = inRoutesDir(projectRoot, routesDir);
676
+ return {
677
+ name: "ph-connect-routes-watcher",
678
+ apply: "serve",
679
+ configureServer(server) {
680
+ const { logger } = server.config;
681
+ let queue = Promise.resolve();
682
+ const onEvent = (file) => {
683
+ if (!inRoutes(file)) return;
684
+ queue = queue.then(() => generateConnectRoutes(projectRoot, routesDir, config)).catch((error) => logger.error(`[connect] ${error.message}`));
685
+ };
686
+ for (const event of [
687
+ "add",
688
+ "unlink",
689
+ "addDir",
690
+ "unlinkDir"
691
+ ]) server.watcher.on(event, onEvent);
692
+ }
693
+ };
694
+ }
695
+ const ROUTER_PACKAGES = /[\\/]node_modules[\\/]@tanstack[\\/](react-router|router-core|history|react-store|store)[\\/]/;
696
+ /** One chunk for the router and the project's route configs, which the split
697
+ * route components would otherwise spread over several shared chunks. */
698
+ function connectRouterChunkGroups(routesDir) {
699
+ const routes = routesDir && join(routesDir, sep);
700
+ return [
701
+ {
702
+ name: "preload-helper",
703
+ test: /vite[\\/]preload-helper/,
704
+ priority: 1
705
+ },
706
+ {
707
+ name: "use-sync-external-store",
708
+ test: /[\\/]node_modules[\\/]use-sync-external-store[\\/]/,
709
+ priority: 1
710
+ },
711
+ {
712
+ name: "router",
713
+ test: (id) => ROUTER_PACKAGES.test(id) || !!routes && id.startsWith(routes) && !id.includes("tsr-split")
714
+ }
715
+ ];
716
+ }
717
+ //#endregion
718
+ //#region connect-utils/vite-plugins/host-stylesheet.ts
719
+ /** The host's stylesheet, which may not exist yet: `style.css` beside its routes
720
+ * folder, so `hosts/connect/style.css` by default. `ph build` never reads it. */
721
+ function hostStylesheetPath(projectRoot, routesDir) {
722
+ const hostDir = routesDir ? dirname(routesDir) : join(projectRoot, dirname(HOST_ROUTES_DIR));
723
+ return join(hostDir, "style.css");
724
+ }
725
+ const importOf = (stylesheet, file) => `@import ${JSON.stringify(`./${normalizePath(relative(dirname(stylesheet), file))}`)};`;
726
+ /** The project's `style.css` with the host's stylesheet imported last when it
727
+ * exists (else `missing`), so the host's theme wins in the page's one build. */
728
+ function withHostStylesheet(css, stylesheet, hostStylesheet, missing) {
729
+ const file = hostStylesheet && existsSync(hostStylesheet) ? hostStylesheet : missing;
730
+ return file ? `${css}\n${importOf(stylesheet, file)}\n` : css;
731
+ }
732
+ /** Serves the project's `style.css` with the host's stylesheet in it. */
733
+ function hostStylesheetPlugin(projectRoot, hostStylesheet) {
734
+ const stylesheet = join(projectRoot, "style.css");
735
+ const stylesheetId = normalizePath(stylesheet);
736
+ const hostId = normalizePath(hostStylesheet);
737
+ let placeholder;
738
+ return {
739
+ name: "ph-host-stylesheet",
740
+ enforce: "pre",
741
+ configResolved(config) {
742
+ if (config.command !== "serve") return;
743
+ placeholder = join(config.cacheDir, "ph-host-stylesheet.css");
744
+ mkdirSync(dirname(placeholder), { recursive: true });
745
+ writeFileSync(placeholder, "/* Until the host's style.css exists. */\n");
746
+ },
747
+ load(id) {
748
+ if (normalizePath(id.split("?")[0]) !== stylesheetId) return null;
749
+ return withHostStylesheet(readFileSync(stylesheet, "utf8"), stylesheet, hostStylesheet, placeholder);
750
+ },
751
+ hotUpdate(ctx) {
752
+ if (normalizePath(ctx.file) !== hostId) return;
753
+ if (ctx.type === "create" && placeholder && existsSync(placeholder)) {
754
+ const now = /* @__PURE__ */ new Date();
755
+ utimesSync(placeholder, now, now);
756
+ }
757
+ const modules = this.environment.moduleGraph.getModulesByFile(stylesheetId);
758
+ return [...ctx.modules, ...modules ?? []];
759
+ }
760
+ };
761
+ }
762
+ //#endregion
763
+ //#region connect-utils/vite-plugins/node-dedupe.ts
764
+ /** `pkg` is installed for `root`: in a node_modules at or above it. */
765
+ function installedFor(root, pkg) {
766
+ for (let dir = root;; dir = dirname(dir)) {
767
+ if (existsSync(join(dir, "node_modules", pkg, "package.json"))) return true;
768
+ if (dirname(dir) === dir) return false;
769
+ }
770
+ }
771
+ /** `specifier` names `pkg` or one of its subpaths. */
772
+ function names(specifier, pkg) {
773
+ return specifier === pkg || specifier.startsWith(`${pkg}/`);
774
+ }
775
+ /**
776
+ * Runs `fn` with Node's resolution of `packages` (and subpaths) pinned to
777
+ * `root`'s copy. Vite's `resolve.dedupe` reaches only what Vite resolves; an
778
+ * SSR-externalized dependency is loaded by Node from its real path, which for
779
+ * a linked checkout is the checkout's node_modules: two Reacts, and the first
780
+ * hook fails with "reading 'useMemo'". A package `root` lacks keeps its usual
781
+ * resolution.
782
+ */
783
+ async function withNodeDedupe(root, packages, fn) {
784
+ const pinned = packages.filter((pkg) => installedFor(root, pkg));
785
+ if (pinned.length === 0) return fn();
786
+ const rootManifest = join(root, "package.json");
787
+ const parentURL = pathToFileURL(rootManifest).href;
788
+ const rootRequire = createRequire(rootManifest);
789
+ const hooks = registerHooks({ resolve(specifier, context, nextResolve) {
790
+ if (!(context.parentURL !== parentURL && pinned.some((pkg) => names(specifier, pkg)))) return nextResolve(specifier, context);
791
+ if (context.conditions.includes("require")) return {
792
+ url: pathToFileURL(rootRequire.resolve(specifier)).href,
793
+ shortCircuit: true
794
+ };
795
+ return nextResolve(specifier, {
796
+ ...context,
797
+ parentURL
798
+ });
799
+ } });
800
+ try {
801
+ return await fn();
802
+ } finally {
803
+ hooks.deregister();
804
+ }
805
+ }
806
+ //#endregion
807
+ //#region connect-utils/vite-plugins/project-brand.ts
808
+ /** `<meta name>` that tells Connect's loaders which image replaces the logo. */
809
+ const LOADER_META = "ph-loader";
810
+ /** `<meta name>` set when the project's `_app` replaces Connect's layout. */
811
+ const CUSTOM_SHELL_META = "ph-custom-shell";
812
+ const DEFAULT_LOADER_SIZE = 96;
813
+ const DEFAULT_BRANDING = DEFAULT_CONNECT_CONFIG.branding ?? {};
814
+ /**
815
+ * The branding in effect: defaults < source powerhouse.config.json <
816
+ * CLI / host override, applied in that order. In every layer `undefined`
817
+ * leaves the field alone and `null` resets it to the default, so a null in a
818
+ * later layer beats a value in an earlier one. Keys branding does not have
819
+ * (a `homeBackground` from before it moved to `connect.home`) are dropped.
820
+ */
821
+ function effectiveBranding(...layers) {
822
+ const out = { ...DEFAULT_BRANDING };
823
+ const defaults = DEFAULT_BRANDING;
824
+ for (const layer of layers) {
825
+ if (!layer) continue;
826
+ const entries = Object.entries(layer);
827
+ for (const [key, value] of entries) {
828
+ if (value === void 0 || !(key in defaults)) continue;
829
+ out[key] = value === null ? defaults[key] ?? null : value;
830
+ }
831
+ }
832
+ out.appName = (typeof out.appName === "string" ? out.appName.trim() : void 0) || DEFAULT_BRANDING.appName;
833
+ return out;
834
+ }
835
+ /**
836
+ * The `branding` block Connect reads at boot: the app icon reduced to its
837
+ * 64 px variant as a data URI (the in-app logo; a master would be ~1 MB of
838
+ * base64), the loader left out (it is served as a file and declared in
839
+ * index.html). Fields without a usable image end up null.
840
+ */
841
+ function resolveRuntimeBranding(projectRoot, branding, warn) {
842
+ const out = {
843
+ appName: branding.appName ?? DEFAULT_BRANDING.appName,
844
+ icon: null,
845
+ loader: null
846
+ };
847
+ if (branding.icon) {
848
+ const logo = iconVariantPath(projectRoot, branding.icon, 64);
849
+ out.icon = resolveImageRef(projectRoot, logo ?? branding.icon, {
850
+ maxBytes: UI_ICON_MAX_BYTES,
851
+ warn
852
+ }) ?? null;
853
+ }
854
+ return out;
855
+ }
856
+ /**
857
+ * A pane's background with every image, in both colour schemes, resolved to
858
+ * a data URI: a single image stays a single image, layers stay layers (a
859
+ * layer without a usable image is dropped). Problems the renderer cannot
860
+ * fix are warned about: a layer pinned to both edges of an axis, an SVG
861
+ * without a viewBox (its aspect is unknown, so it needs both dimensions).
862
+ */
863
+ function resolveBackground(projectRoot, background, warn) {
864
+ if (!background) return null;
865
+ for (const problem of validateBackground(background, "homeBackground")) warn?.(`[branding] ${problem}`);
866
+ const resolveOne = (ref) => {
867
+ if (!isPassthroughImageRef(ref) && extname(ref).toLowerCase() === ".svg") warnWithoutViewBox(projectRoot, ref, warn);
868
+ return resolveImageRef(projectRoot, ref, {
869
+ maxBytes: BACKGROUND_MAX_BYTES,
870
+ warn
871
+ });
872
+ };
873
+ if (typeof background === "string") return resolveOne(background) ?? null;
874
+ return mapBackgroundImages(background, resolveOne);
875
+ }
876
+ function warnWithoutViewBox(projectRoot, ref, warn) {
877
+ const file = resolve(projectRoot, ref);
878
+ if (!existsSync(file)) return;
879
+ const head = readFileSync(file, "utf8").slice(0, 4096);
880
+ 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.`);
881
+ }
882
+ const EXPLORER_ICON_KEYS = [
883
+ "localDrive",
884
+ "remoteDrive",
885
+ "folder",
886
+ "document"
887
+ ];
888
+ /**
889
+ * The drive explorer's icons with every path resolved to a data URI; a key
890
+ * without a usable image is dropped (the built-in icon), an empty or null
891
+ * set is null.
892
+ */
893
+ function resolveExplorerIcons(projectRoot, icons, warn) {
894
+ if (!icons) return null;
895
+ const ui = {
896
+ maxBytes: UI_ICON_MAX_BYTES,
897
+ warn
898
+ };
899
+ const out = {};
900
+ for (const key of EXPLORER_ICON_KEYS) {
901
+ const src = resolveImageRef(projectRoot, icons[key], ui);
902
+ if (src) out[key] = src;
903
+ }
904
+ if (icons.documents) {
905
+ const documents = {};
906
+ for (const [type, ref] of Object.entries(icons.documents)) {
907
+ const src = resolveImageRef(projectRoot, ref, ui);
908
+ if (src) documents[type] = src;
909
+ }
910
+ if (Object.keys(documents).length > 0) out.documents = documents;
911
+ }
912
+ return Object.keys(out).length > 0 ? out : null;
913
+ }
914
+ /** A generic plugin entry whose config carries images to resolve. */
915
+ function hasGenericImages(entry) {
916
+ return entry.module === "@powerhousedao/connect/plugins/generic" && entry.config !== void 0 && ("icons" in entry.config || "homeBackground" in entry.config);
917
+ }
918
+ /**
919
+ * A connect block with the generic plugin's images resolved, wherever they
920
+ * are declared: `drives.icons` and `home.background` (the classic source
921
+ * values) and the generic plugin entry's `icons` / `homeBackground` in a
922
+ * served composition (the owner under uniform runners). Unchanged when none
923
+ * is present.
924
+ */
925
+ function withResolvedGenericImages(projectRoot, connect, warn) {
926
+ if (!connect) return connect;
927
+ let out = connect;
928
+ if (connect.drives && "icons" in connect.drives) out = {
929
+ ...out,
930
+ drives: {
931
+ ...out.drives,
932
+ icons: resolveExplorerIcons(projectRoot, connect.drives.icons, warn)
933
+ }
934
+ };
935
+ if (connect.home && "background" in connect.home) out = {
936
+ ...out,
937
+ home: {
938
+ ...out.home,
939
+ background: resolveBackground(projectRoot, connect.home.background, warn)
940
+ }
941
+ };
942
+ if (connect.composition?.some(hasGenericImages)) out = {
943
+ ...out,
944
+ composition: connect.composition.map((entry) => {
945
+ if (!hasGenericImages(entry)) return entry;
946
+ const config = { ...entry.config };
947
+ if ("icons" in config) config.icons = resolveExplorerIcons(projectRoot, config.icons, warn);
948
+ if ("homeBackground" in config) config.homeBackground = resolveBackground(projectRoot, config.homeBackground, warn);
949
+ return {
950
+ ...entry,
951
+ config
952
+ };
953
+ })
954
+ };
955
+ return out;
956
+ }
957
+ const IMAGE_TYPES = {
958
+ ".png": "image/png",
959
+ ".svg": "image/svg+xml",
960
+ ".webp": "image/webp",
961
+ ".gif": "image/gif",
962
+ ".jpg": "image/jpeg",
963
+ ".jpeg": "image/jpeg"
964
+ };
965
+ function projectFile(projectRoot, ref) {
966
+ return isAbsolute(ref) ? ref : resolve(projectRoot, ref);
967
+ }
968
+ function asset(projectRoot, ref, fileName, warn) {
969
+ if (isPassthroughImageRef(ref)) {
970
+ warn?.(`[branding] ${ref}: use a project file path here, not a URL. Skipped.`);
971
+ return;
972
+ }
973
+ const file = projectFile(projectRoot, ref);
974
+ const ext = extname(file).toLowerCase();
975
+ const contentType = IMAGE_TYPES[ext];
976
+ if (!contentType) {
977
+ warn?.(`[branding] ${ref}: unsupported image type. Skipped.`);
978
+ return;
979
+ }
980
+ if (!existsSync(file)) {
981
+ warn?.(`[branding] ${ref}: file not found. Skipped.`);
982
+ return;
983
+ }
984
+ return {
985
+ fileName: fileName(ext),
986
+ file,
987
+ contentType
988
+ };
989
+ }
990
+ /** `branding.loader` as the build emits it; undefined keeps Connect's logo. */
991
+ function resolveProjectLoader(projectRoot, branding, warn) {
992
+ const loader = branding?.loader;
993
+ if (!loader) return void 0;
994
+ const spec = typeof loader === "string" ? { src: loader } : loader;
995
+ const found = asset(projectRoot, spec.src, (ext) => `ph-loader${ext}`, warn);
996
+ if (!found) return void 0;
997
+ return {
998
+ ...found,
999
+ animation: spec.animation ?? "pulse",
1000
+ size: spec.size ?? DEFAULT_LOADER_SIZE
1001
+ };
1002
+ }
1003
+ /** Width and height from a PNG's IHDR chunk. */
1004
+ function pngSize(bytes) {
1005
+ if (bytes.length < 24 || [
1006
+ 137,
1007
+ 80,
1008
+ 78,
1009
+ 71,
1010
+ 13,
1011
+ 10,
1012
+ 26,
1013
+ 10
1014
+ ].some((b, i) => bytes[i] !== b)) return;
1015
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1016
+ return [view.getUint32(16), view.getUint32(20)];
1017
+ }
1018
+ /** The installed app's name and icons, from `branding.appName` and
1019
+ * `branding.icon`. Undefined members keep Connect's own. */
1020
+ function resolveProjectPwaBrand(projectRoot, branding, warn) {
1021
+ const brand = {};
1022
+ const name = branding?.appName?.trim();
1023
+ if (name && name !== DEFAULT_BRANDING.appName) brand.name = name;
1024
+ const app = branding?.icon;
1025
+ if (!app) return brand;
1026
+ const ext = extname(app).toLowerCase();
1027
+ if (ext === ".svg") {
1028
+ const svg = asset(projectRoot, app, () => "pwa-app.svg", warn);
1029
+ if (svg) brand.icons = [{
1030
+ ...svg,
1031
+ sizes: "any"
1032
+ }];
1033
+ return brand;
1034
+ }
1035
+ if (ext !== ".png") {
1036
+ warn?.(`[branding] icon ${app}: the installed-app icon needs a PNG or SVG. Connect's icon stays.`);
1037
+ return brand;
1038
+ }
1039
+ const icons = [];
1040
+ const seen = /* @__PURE__ */ new Set();
1041
+ const add = (ref) => {
1042
+ const file = projectFile(projectRoot, ref);
1043
+ if (!existsSync(file)) return;
1044
+ const size = pngSize(readFileSync(file));
1045
+ if (!size) return;
1046
+ const sizes = `${size[0]}x${size[1]}`;
1047
+ if (seen.has(sizes)) return;
1048
+ seen.add(sizes);
1049
+ icons.push({
1050
+ fileName: `pwa-app-${sizes}.png`,
1051
+ file,
1052
+ contentType: "image/png",
1053
+ sizes
1054
+ });
1055
+ };
1056
+ const stem = app.slice(0, app.length - ext.length);
1057
+ for (const size of PWA_ICON_VARIANT_SIZES) add(`${stem}_${size}x${size}${ext}`);
1058
+ add(app);
1059
+ if (icons.length === 0) {
1060
+ warn?.(`[branding] icon ${app}: not a readable PNG. Connect's icon stays.`);
1061
+ return brand;
1062
+ }
1063
+ brand.icons = icons;
1064
+ return brand;
1065
+ }
1066
+ /**
1067
+ * The favicons: the `_16x16` / `_32x32` / `_64x64` siblings of
1068
+ * `branding.icon` (an SVG master is one scalable favicon). They replace
1069
+ * Connect's static icon.ico link in index.html; none keeps it. A favicon
1070
+ * named outright (`faviconPath`: `branding.favicon` or `--favicon`) wins: it
1071
+ * is built as icon.ico (or icon.svg, icon.png), so the icon's siblings stand aside.
1072
+ */
1073
+ function resolveProjectFavicons(projectRoot, branding, warn, faviconPath) {
1074
+ const app = branding?.icon;
1075
+ if (!app || faviconPath) return [];
1076
+ if (isPassthroughImageRef(app)) {
1077
+ warn?.(`[branding] icon ${app}: use a project file path here, not a URL. Connect's favicon stays.`);
1078
+ return [];
1079
+ }
1080
+ const ext = extname(app).toLowerCase();
1081
+ if (ext === ".svg") {
1082
+ const svg = asset(projectRoot, app, () => "favicon.svg", warn);
1083
+ return svg ? [{
1084
+ ...svg,
1085
+ sizes: "any"
1086
+ }] : [];
1087
+ }
1088
+ const out = [];
1089
+ for (const size of APP_ICON_VARIANT_SIZES) {
1090
+ const variant = iconVariantPath(projectRoot, app, size);
1091
+ if (!variant) continue;
1092
+ const file = projectFile(projectRoot, variant);
1093
+ const contentType = imageMimeType(file);
1094
+ if (!contentType) continue;
1095
+ out.push({
1096
+ fileName: `favicon-${size}x${size}${ext}`,
1097
+ file,
1098
+ contentType,
1099
+ sizes: `${size}x${size}`
1100
+ });
1101
+ }
1102
+ if (out.length === 0) warn?.(`[branding] icon ${app}: no _16x16 / _32x32 / _64x64 siblings found. Connect's favicon stays.`);
1103
+ return out;
1104
+ }
1105
+ function escapeAttr(value) {
1106
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
1107
+ }
1108
+ /** The `<meta>` tags Connect's loaders read. */
1109
+ function brandMetaTags(options) {
1110
+ const tags = [];
1111
+ const { loader } = options;
1112
+ if (loader) tags.push(`<meta name="${LOADER_META}" content="${escapeAttr(loader.fileName)}" data-animation="${loader.animation}" data-size="${loader.size}">`);
1113
+ if (options.customShell) tags.push(`<meta name="${CUSTOM_SHELL_META}" content="true">`);
1114
+ return tags.join("");
1115
+ }
1116
+ const ICON_LINK = /<link\b[^>]*\brel=["']?(?:shortcut )?icon["']?[^>]*>\s*/gi;
1117
+ /** index.html with Connect's icon links replaced by the project's favicons
1118
+ * (one sized link per variant, under `base`); unchanged without any. */
1119
+ function withProjectFavicons(html, favicons, base = "/") {
1120
+ if (favicons.length === 0) return html;
1121
+ const prefix = base.endsWith("/") ? base : `${base}/`;
1122
+ const links = favicons.map((icon) => `<link rel="icon" type="${icon.contentType}" sizes="${icon.sizes}" href="${escapeAttr(prefix + icon.fileName)}" />`).join("");
1123
+ return html.replace(ICON_LINK, "").replace("</head>", `${links}</head>`);
1124
+ }
1125
+ /** index.html with the icon an iPhone puts on its home screen: the first
1126
+ * installed-app icon covering its 180 px. Unchanged without one, as with
1127
+ * Connect's own icons or an SVG, which iOS can't use here. */
1128
+ function withAppleTouchIcon(html, icons = [], base = "/") {
1129
+ const icon = icons.find((candidate) => parseInt(candidate.sizes) >= 180);
1130
+ if (!icon) return html;
1131
+ const prefix = base.endsWith("/") ? base : `${base}/`;
1132
+ return html.replace("</head>", `<link rel="apple-touch-icon" href="${escapeAttr(prefix + icon.fileName)}" /></head>`);
1133
+ }
1134
+ /** Keyframes for the loader motions; shared by the shell and the app. */
1135
+ 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)}}";
1136
+ const LOADER_ANIMATION = {
1137
+ pulse: "ph-loader-pulse 1.6s ease-in-out infinite",
1138
+ spin: "ph-loader-spin 1.4s linear infinite",
1139
+ none: "none"
1140
+ };
1141
+ /** The loader as static markup, for the prerendered shell's first paint. */
1142
+ function loaderMarkup(loader, base = "/") {
1143
+ const prefix = base.endsWith("/") ? base : `${base}/`;
1144
+ const motion = LOADER_ANIMATION[loader.animation];
1145
+ 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}">`;
1146
+ }
1147
+ /** The marked slot in Connect's prerendered shell that holds its logo. */
1148
+ const LOADER_SLOT = /<div\b[^>]*\bdata-ph-loader-slot\b[^>]*>[\s\S]*?<\/div>/;
1149
+ /** Swaps the shell's logo slot for the project's loader. */
1150
+ function replaceShellLoader(shellBody, loader, base = "/") {
1151
+ return shellBody.replace(LOADER_SLOT, () => loaderMarkup(loader, base));
1152
+ }
1153
+ /**
1154
+ * Serves (dev) and emits (build) the branding files, and adds the tags
1155
+ * index.html carries before any JavaScript: the loader and custom-shell
1156
+ * meta tags, the favicon links and the iPhone's home-screen icon.
1157
+ */
1158
+ function connectProjectBrandPlugin(options) {
1159
+ const favicons = options.favicons ?? [];
1160
+ const files = [
1161
+ ...options.loader ? [options.loader] : [],
1162
+ ...options.pwaIcons ?? [],
1163
+ ...favicons
1164
+ ];
1165
+ const meta = brandMetaTags(options);
1166
+ let base = "/";
1167
+ return {
1168
+ name: "ph-connect-project-brand",
1169
+ configResolved(config) {
1170
+ base = config.base;
1171
+ },
1172
+ configureServer(server) {
1173
+ for (const file of files) {
1174
+ const handler = (_req, res, next) => {
1175
+ try {
1176
+ res.setHeader("Content-Type", file.contentType);
1177
+ res.end(readFileSync(file.file));
1178
+ } catch {
1179
+ next();
1180
+ }
1181
+ };
1182
+ const paths = /* @__PURE__ */ new Set([`${server.config.base}${file.fileName}`.replace(/\/{2,}/g, "/"), `/${file.fileName}`]);
1183
+ for (const path of paths) server.middlewares.use(path, handler);
1184
+ }
1185
+ },
1186
+ transformIndexHtml(html) {
1187
+ return withAppleTouchIcon(withProjectFavicons(meta ? html.replace("</head>", `${meta}</head>`) : html, favicons, base), options.pwaIcons, base);
1188
+ },
1189
+ generateBundle(_options, bundle) {
1190
+ for (const file of files) {
1191
+ if (file.fileName in bundle) continue;
1192
+ try {
1193
+ this.emitFile({
1194
+ type: "asset",
1195
+ fileName: file.fileName,
1196
+ source: readFileSync(file.file)
1197
+ });
1198
+ } catch {}
1199
+ }
1200
+ }
1201
+ };
1202
+ }
1203
+ //#endregion
1204
+ //#region connect-utils/vite-plugins/app-shell.ts
1205
+ const SHELL_FILES = {
1206
+ generic: "shell",
1207
+ core: "shell-core"
1208
+ };
1209
+ function connectDistDir(projectRoot) {
1210
+ try {
1211
+ return join(dirname(resolvePackage("@powerhousedao/connect/package.json", projectRoot)), "dist");
1212
+ } catch {
1213
+ return;
1214
+ }
1215
+ }
1216
+ /** The shell manifest of the installed Connect, if it ships one. */
1217
+ function readShellPlugins(projectRoot) {
1218
+ const distDir = connectDistDir(projectRoot);
1219
+ return distDir ? readShellPluginsIn(distDir) : void 0;
1220
+ }
1221
+ /** The shell Connect's build prerendered, if the installed Connect ships one. */
1222
+ function readAppShell(projectRoot, variant = "generic") {
1223
+ const distDir = connectDistDir(projectRoot);
1224
+ if (!distDir) return void 0;
1225
+ const body = join(distDir, `${SHELL_FILES[variant]}.html`);
1226
+ const head = join(distDir, `${SHELL_FILES[variant]}-head.html`);
1227
+ if (!existsSync(body) || !existsSync(head)) return void 0;
1228
+ return {
1229
+ body: readFileSync(body, "utf8"),
1230
+ head: readFileSync(head, "utf8")
1231
+ };
1232
+ }
1233
+ /** Every variant the installed Connect ships. */
1234
+ function readAppShells(projectRoot) {
1235
+ const shells = {};
1236
+ for (const variant of Object.keys(SHELL_FILES)) {
1237
+ const shell = readAppShell(projectRoot, variant);
1238
+ if (shell) shells[variant] = shell;
1239
+ }
1240
+ return shells;
1241
+ }
1242
+ const DEV_SHELL_WAIT_MS = 1e4;
1243
+ const CONNECT_PACKAGES = ["@powerhousedao/connect", "@powerhousedao/connect-core"];
1244
+ async function renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet) {
1245
+ const server = await createServer({
1246
+ configFile: false,
1247
+ root: projectRoot,
1248
+ logLevel: "error",
1249
+ appType: "custom",
1250
+ server: {
1251
+ middlewareMode: true,
1252
+ hmr: false,
1253
+ ws: false,
1254
+ watch: null
1255
+ },
1256
+ oxc: { jsx: { runtime: "automatic" } },
1257
+ resolve: {
1258
+ alias: routeAliases,
1259
+ dedupe: config.resolve.dedupe,
1260
+ tsconfigPaths: true
1261
+ },
1262
+ define: config.define,
1263
+ cacheDir: join(projectRoot, "node_modules/.vite-ph-prerender"),
1264
+ optimizeDeps: {
1265
+ noDiscovery: true,
1266
+ include: [],
1267
+ entries: []
1268
+ },
1269
+ ssr: {
1270
+ optimizeDeps: {
1271
+ noDiscovery: true,
1272
+ include: []
1273
+ },
1274
+ noExternal: CONNECT_PACKAGES
1275
+ }
1276
+ });
1277
+ try {
1278
+ return await withNodeDedupe(projectRoot, config.resolve.dedupe, async () => {
1279
+ const renderer = await server.ssrLoadModule("@powerhousedao/connect/prerender");
1280
+ const stylesheet = join(projectRoot, "style.css");
1281
+ const css = withHostStylesheet(readFileSync(stylesheet, "utf8"), stylesheet, hostStylesheet);
1282
+ try {
1283
+ return await renderer.renderProjectShells(stylesheet, css);
1284
+ } catch (error) {
1285
+ throw withSourceLocations(error, (stack) => server.ssrRewriteStacktrace(stack));
1286
+ }
1287
+ });
1288
+ } finally {
1289
+ await server.close();
1290
+ }
1291
+ }
1292
+ const RENDER_LOCATION = /\(at (\S+) \((.+?):(\d+):(\d+)\)\)/g;
1293
+ /** The prerender's error with each `(at <component> (<file>:<line>:<col>))` in
1294
+ * its message mapped back to the source, as React reports the transformed code. */
1295
+ function withSourceLocations(error, rewrite) {
1296
+ if (!(error instanceof Error)) return error;
1297
+ const before = error.message;
1298
+ const after = before.replace(RENDER_LOCATION, (found, name, file, line, column) => {
1299
+ const frame = /^ {4}at .*?\(?(\S+?):(\d+):(\d+)\)?$/.exec(rewrite(` at ${name} (${file}:${line}:${column})`));
1300
+ return frame ? `(at ${name} (${frame[1]}:${frame[2]}:${frame[3]}))` : found;
1301
+ });
1302
+ if (after !== before) {
1303
+ error.message = after;
1304
+ if (error.stack) error.stack = error.stack.replace(before, after);
1305
+ }
1306
+ return error;
1307
+ }
1308
+ /** Vite's error overlay over the page, for a failure no module request reports. */
1309
+ function withErrorOverlay(html, err, base) {
1310
+ const script = `<script type="module">import { ErrorOverlay } from "${base}@vite/client";document.body.appendChild(new ErrorOverlay(${JSON.stringify(err).replaceAll("<", "\\u003c")}));<\/script>`;
1311
+ return html.replace("</body>", `${script}</body>`);
1312
+ }
1313
+ const sourceText = (source) => typeof source === "string" ? source : new TextDecoder().decode(source);
1314
+ /** Build: the composition's shell in #root and every variant in the dist, from
1315
+ * the project's routes when it has them. Dev: the shell from the project's routes
1316
+ * when it has them, else core's for a core composition. */
1317
+ function connectAppShellPlugin(projectRoot, { composition, appName, routeAliases, routesDir, loader, hostStylesheet } = {}) {
1318
+ let variant = "generic";
1319
+ let shells = {};
1320
+ let shellPlugins;
1321
+ let base = "/";
1322
+ let isBuild = true;
1323
+ let config;
1324
+ const withLoader = (from) => {
1325
+ if (!loader) return from;
1326
+ const out = {};
1327
+ for (const [name, shell] of Object.entries(from)) out[name] = {
1328
+ ...shell,
1329
+ body: replaceShellLoader(shell.body, loader, base)
1330
+ };
1331
+ return out;
1332
+ };
1333
+ const fromRoutes = () => isBuild && !!routeAliases;
1334
+ const shell = () => {
1335
+ if (fromRoutes()) return void 0;
1336
+ return isBuild || variant === "core" ? shells[variant] : void 0;
1337
+ };
1338
+ let devShells;
1339
+ let devRender;
1340
+ let devShellError;
1341
+ let devServer;
1342
+ const renderDevShells = () => {
1343
+ if (!config || !routeAliases) return;
1344
+ const logger = config.logger;
1345
+ devShellError = void 0;
1346
+ devShells = renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet).then((rendered) => {
1347
+ devShellError = void 0;
1348
+ return withLoader(rendered);
1349
+ }, (error) => {
1350
+ const cause = error instanceof Error ? error : new Error(String(error));
1351
+ devShellError = {
1352
+ message: `The loading shell failed to render from the project's routes, and the build will fail on it:\n${cause.message}`,
1353
+ stack: cause.stack ?? "",
1354
+ plugin: "ph-connect-app-shell"
1355
+ };
1356
+ logger.error(`[connect] ${devShellError.message}`, { timestamp: true });
1357
+ devServer?.ws.send({
1358
+ type: "error",
1359
+ err: devShellError
1360
+ });
1361
+ return {};
1362
+ });
1363
+ };
1364
+ const devShell = async () => {
1365
+ if (!devShells) return void 0;
1366
+ let timer;
1367
+ const wait = new Promise((resolve) => {
1368
+ timer = setTimeout(() => resolve(void 0), DEV_SHELL_WAIT_MS);
1369
+ });
1370
+ try {
1371
+ return (await Promise.race([devShells, wait]))?.[variant];
1372
+ } finally {
1373
+ clearTimeout(timer);
1374
+ }
1375
+ };
1376
+ return {
1377
+ name: "ph-connect-app-shell",
1378
+ configureServer(server) {
1379
+ if (!routeAliases) return;
1380
+ devServer = server;
1381
+ renderDevShells();
1382
+ const stylesheet = join(projectRoot, "style.css");
1383
+ const rerender = (file) => {
1384
+ if (!(file === stylesheet || file === hostStylesheet || !!routesDir && file.startsWith(`${routesDir}${sep}`))) return;
1385
+ clearTimeout(devRender);
1386
+ devRender = setTimeout(renderDevShells, 300);
1387
+ };
1388
+ server.watcher.on("change", rerender);
1389
+ server.watcher.on("add", rerender);
1390
+ server.watcher.on("unlink", rerender);
1391
+ },
1392
+ configResolved(resolved) {
1393
+ config = resolved;
1394
+ base = resolved.base;
1395
+ isBuild = resolved.command === "build";
1396
+ shells = withLoader(readAppShells(projectRoot));
1397
+ shellPlugins = readShellPlugins(projectRoot);
1398
+ variant = appShellVariant(composition, shellPlugins);
1399
+ },
1400
+ transformIndexHtml: {
1401
+ order: "post",
1402
+ handler: async (html) => {
1403
+ const current = !isBuild && routeAliases ? await devShell() : shell();
1404
+ const page = current ? injectAppShell(html, current, base, {
1405
+ deferStyles: isBuild,
1406
+ appName
1407
+ }) : html;
1408
+ return devShellError ? withErrorOverlay(page, devShellError, base) : page;
1409
+ }
1410
+ },
1411
+ generateBundle: {
1412
+ order: "post",
1413
+ async handler(_options, bundle) {
1414
+ if (!isBuild) return;
1415
+ if (fromRoutes() && config && routeAliases) {
1416
+ shells = withLoader(await renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet));
1417
+ const index = bundle["index.html"];
1418
+ const current = shells[variant];
1419
+ if (index?.type === "asset" && current) index.source = injectAppShell(sourceText(index.source), current, base, { appName });
1420
+ }
1421
+ if (!Object.keys(shells).length) return;
1422
+ this.emitFile({
1423
+ type: "asset",
1424
+ fileName: APP_SHELLS_FILE,
1425
+ source: JSON.stringify(shells)
1426
+ });
1427
+ if (shellPlugins) this.emitFile({
1428
+ type: "asset",
1429
+ fileName: SHELL_PLUGINS_FILE,
1430
+ source: JSON.stringify(shellPlugins)
1431
+ });
1432
+ }
1433
+ }
1434
+ };
1435
+ }
1436
+ //#endregion
1437
+ //#region connect-utils/vite-plugins/build-hash.ts
1438
+ /** Name of the build-identity file emitted into the build output. */
1439
+ const BUILD_HASH_FILE = "build-hash.json";
1440
+ /**
1441
+ * Deterministic identity of a Connect build. Differs whenever the deployed
1442
+ * content differs (published Connect version, project config, package list,
1443
+ * build options) so the SPA can detect "the server is serving a different
1444
+ * build than the one this bundle was built from" by comparing its baked copy
1445
+ * (define `PH_CONNECT_BUILD_HASH`) to `build-hash.json`, which the build
1446
+ * emits alongside the app and the server must serve no-cache.
1447
+ */
1448
+ function computeBuildHash(input) {
1449
+ return createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 16);
1450
+ }
1451
+ /**
1452
+ * Read the installed @powerhousedao/connect version. The package's `exports`
1453
+ * map does not expose a `./package.json` subpath, so `require.resolve(
1454
+ * "…/package.json")` throws — resolve the main entry and walk up to the
1455
+ * package root instead.
1456
+ */
1457
+ function readConnectVersion(projectRoot) {
1458
+ try {
1459
+ const entry = createRequire(join(projectRoot, "package.json")).resolve("@powerhousedao/connect", { paths: [projectRoot] });
1460
+ let dir = dirname(entry);
1461
+ for (;;) {
1462
+ try {
1463
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
1464
+ if (pkg.name === "@powerhousedao/connect") return pkg.version ?? "unknown";
1465
+ } catch {}
1466
+ const parent = dirname(dir);
1467
+ if (parent === dir) break;
1468
+ dir = parent;
1469
+ }
1470
+ } catch {}
1471
+ return "unknown";
1472
+ }
1473
+ function buildHashFromBuildOptions(options) {
1474
+ return computeBuildHash({
1475
+ workspaceGitSha: process.env.WORKSPACE_GIT_SHA ?? "",
1476
+ workspaceVersion: process.env.WORKSPACE_VERSION ?? "",
1477
+ connectPackageVersion: readConnectVersion(options.dirname),
1478
+ projectConfig: options.phConfig,
1479
+ packages: options.packages.map((p) => `${p.packageName}@${p.version ?? ""}:${p.provider ?? ""}`),
1480
+ connectBasePath: options.connectBasePath ?? "",
1481
+ offlineEnabled: options.offlineEnabled,
1482
+ packageRegistryUrl: options.packageRegistryUrl ?? ""
1483
+ });
1484
+ }
1485
+ /**
1486
+ * Emits `build-hash.json` (`{"hash": "<build id>"}`) into the build output.
1487
+ * Emitted as an asset so it lands at the deploy base like every other file.
1488
+ * Build-only: dev (studio) never runs generateBundle, and the SPA check
1489
+ * treats a missing file as "nothing to compare" and stays silent.
1490
+ */
1491
+ function connectBuildHashPlugin(buildHash) {
1492
+ return {
1493
+ name: "ph-connect-build-hash",
1494
+ apply: "build",
1495
+ generateBundle() {
1496
+ this.emitFile({
1497
+ type: "asset",
1498
+ fileName: BUILD_HASH_FILE,
1499
+ source: `${JSON.stringify({ hash: buildHash }, null, 2)}\n`
1500
+ });
1501
+ }
1502
+ };
1503
+ }
1504
+ //#endregion
1505
+ //#region connect-utils/vite-plugins/dynamic-base.ts
1506
+ /**
1507
+ * Global the runtime (ph-clint proxy) must set before the entry bundle loads.
1508
+ * Value is the normalized deploy base, e.g. "/myagent/" or "/". The JS rewrite
1509
+ * below resolves all asset / lazy-chunk / BASE_URL references against it.
1510
+ */
1511
+ const RUNTIME_GLOBAL = "globalThis.__PH_DYNAMIC_BASE__";
1512
+ const BASE_EXPR = `(${RUNTIME_GLOBAL}||"/")`;
1513
+ function workerPrelude(stripPrefix) {
1514
+ const prefix = escapeForRegExp(stripPrefix).replace(/\//g, "\\/");
1515
+ return `${RUNTIME_GLOBAL}=self.location.pathname.replace(/${prefix}assets\\/[^/]*$/,"");\n`;
1516
+ }
1517
+ const PLACEHOLDER_LITERAL = new RegExp(`(["'\`])${escapeForRegExp(DYNAMIC_BASE_PLACEHOLDER)}((?:(?!\\1)[^$])*)\\1`, "g");
1518
+ const PLACEHOLDER_CSS_URL = new RegExp(`url\\(\\s*(["']?)${escapeForRegExp(DYNAMIC_BASE_PLACEHOLDER)}([^"')]*)\\1\\s*\\)`, "g");
1519
+ /** Rewrites `url(<placeholder>assets/x)` relative to the stylesheet at `fileName`. */
1520
+ function relativeCssUrls(css, fileName) {
1521
+ const dir = path.posix.dirname(fileName);
1522
+ return css.replace(PLACEHOLDER_CSS_URL, (_match, quote, target) => {
1523
+ const relative = path.posix.relative(dir, target);
1524
+ return `url(${quote}${relative.startsWith(".") ? relative : `./${relative}`}${quote})`;
1525
+ });
1526
+ }
1527
+ /**
1528
+ * Rewrites the placeholder base in emitted JS chunks to a runtime expression so
1529
+ * one built `dist/connect` serves under any subpath. Rolldown-native: per-match
1530
+ * MagicString edits in `renderChunk`, no AST splicing (the SWC byte-offset
1531
+ * splicing in vite-plugin-dynamic-base corrupts Rolldown chunks). Each edited
1532
+ * chunk returns a hires sourcemap that the bundler composes into the chunk's
1533
+ * map chain, so the emitted `.map` files track the rewrite (and the worker
1534
+ * prelude's line shift).
1535
+ *
1536
+ * What gets rewritten in JS, all of which emit the base as a quoted string
1537
+ * literal beginning with the placeholder:
1538
+ * - asset URLs (`new URL("/__PH_DYNAMIC_BASE__/assets/x.png", ...)`)
1539
+ * - dynamic-import / lazy-chunk preload URLs
1540
+ * - the inlined `import.meta.env.BASE_URL` (drives Connect's router basename
1541
+ * and BASE_URL-relative fetches such as `${BASE_URL}ph-packages.json`)
1542
+ *
1543
+ * A literal `"/__PH_DYNAMIC_BASE__/foo"` becomes `((globalThis.__PH_DYNAMIC_BASE__||"/")+"foo")`;
1544
+ * a bare `"/__PH_DYNAMIC_BASE__/"` (the BASE_URL value) becomes `(globalThis.__PH_DYNAMIC_BASE__||"/")`.
1545
+ *
1546
+ * HTML is left untouched: the entry `<script>`/`<link>` tags keep the literal
1547
+ * placeholder so the proxy substitutes it with the concrete base at serve time
1548
+ * (the same proxy also sets the runtime global for the JS rewrite). See the
1549
+ * plugin's module doc / report for the exact serve-time contract.
1550
+ *
1551
+ * CSS `url(...)` references that Vite emits with the placeholder (e.g. bundled
1552
+ * fonts) are rewritten relative to the stylesheet, which the HTML substitution
1553
+ * already loads from the right prefix.
1554
+ */
1555
+ function connectDynamicBasePlugin(options = {}) {
1556
+ return {
1557
+ name: "ph-connect-dynamic-base",
1558
+ enforce: "post",
1559
+ renderChunk(code, chunk) {
1560
+ if (!code.includes(DYNAMIC_BASE_PLACEHOLDER)) return null;
1561
+ const s = new MagicString(code);
1562
+ for (const match of code.matchAll(PLACEHOLDER_LITERAL)) {
1563
+ const rest = match[2];
1564
+ s.overwrite(match.index, match.index + match[0].length, rest.length === 0 ? BASE_EXPR : `(${BASE_EXPR}+${JSON.stringify(rest)})`);
1565
+ }
1566
+ if (options.forWorker) {
1567
+ s.prepend(workerPrelude(options.workerStripPrefix ?? ""));
1568
+ this.info(`dynamic-base: worker prelude prepended to ${chunk.fileName}`);
1569
+ }
1570
+ if (!s.hasChanged()) return null;
1571
+ return {
1572
+ code: s.toString(),
1573
+ map: s.generateMap({ hires: true })
1574
+ };
1575
+ },
1576
+ generateBundle(_options, bundle) {
1577
+ for (const file of Object.values(bundle)) if (file.type === "asset" && file.fileName.endsWith(".css")) file.source = relativeCssUrls(String(file.source), file.fileName);
1578
+ 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}`);
1579
+ }
1580
+ };
1581
+ }
1582
+ function escapeForRegExp(s) {
169
1583
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
170
1584
  }
171
1585
  //#endregion
172
- //#region connect-utils/externalize-vendor.ts
1586
+ //#region connect-utils/externalize-vendor.ts
1587
+ /**
1588
+ * Prebuild the heavy, stable Connect dependencies into a static ESM "vendor"
1589
+ * bundle so the dev server never runs (or holds) the dependency optimizer /
1590
+ * module graph for them.
1591
+ *
1592
+ * The reactor-project preview dev-optimizes a large UI graph (Connect itself,
1593
+ * design-system, document-engineering, reactor-browser, …) every session —
1594
+ * ~1–2 GB resident — even though those libs don't change; only the project's
1595
+ * editors do. This module builds them ONCE with `vite build` (in a throwaway
1596
+ * subprocess that exits, freeing the build's peak memory): `vite build` handles
1597
+ * CSS/asset imports, web workers, and WASM (Connect's in-browser PGlite ships
1598
+ * all three), and a multi-entry build with `preserveEntrySignatures: 'strict'`
1599
+ * dedupes shared code into shared chunks. Entries for CJS deps re-export the
1600
+ * module's named API explicitly (so `import { createRoot }` works); ESM deps
1601
+ * use `export *`. The build runs under a dynamic-base placeholder + vendor
1602
+ * segment (`connectDynamicBasePlugin`), so emitted asset/chunk URLs
1603
+ * (`new URL(…, import.meta.url)` for .wasm/.data/workers) carry the placeholder
1604
+ * and resolve at serve time to `<deploy-base>__vendor__/`, while the vendored
1605
+ * Connect's `import.meta.env.BASE_URL` resolves to the deploy base.
1606
+ *
1607
+ * The React family stays EXTERNAL (see `VENDOR_EXTERNAL`); `esmExternalRequirePlugin`
1608
+ * owns that externalization and rewrites CJS `require("react")` → import. Vendor
1609
+ * chunks keep bare React imports, which the dev import map resolves to Vite's
1610
+ * pre-bundled React (`devReactImportmapPlugin`) — one React instance across the
1611
+ * vendor, the project's editors, and CDN-loaded editors.
1612
+ *
1613
+ * `devReactImportmapPlugin` consumes the result: it externalizes these
1614
+ * specifiers in the long-lived dev server, points the page import map at the
1615
+ * vendor URLs, and serves the bundle. With Connect vendored, the dev server only
1616
+ * processes the project's own `main` + local package; HMR for them is unaffected.
1617
+ */
1618
+ /**
1619
+ * The stable Connect libraries worth prebuilding. The React family is NOT here —
1620
+ * it's externalized from the build (see `VENDOR_EXTERNAL`) so the vendor shares
1621
+ * the dev server's single React instance via the import map.
1622
+ */
1623
+ const DEFAULT_VENDOR_INCLUDE = [
1624
+ "@powerhousedao/connect",
1625
+ "document-model",
1626
+ "zod",
1627
+ "@powerhousedao/design-system/connect",
1628
+ "@powerhousedao/reactor-browser",
1629
+ "@powerhousedao/document-engineering",
1630
+ "@powerhousedao/connect-core",
1631
+ "@tanstack/react-router"
1632
+ ];
1633
+ /** Never vendored: the route tree is the project's, the config path the app's
1634
+ * base, and SSR server-only. */
1635
+ const VENDOR_SKIP_SUBPATHS = /* @__PURE__ */ new Set([
1636
+ "@powerhousedao/connect-core/route-tree",
1637
+ "@powerhousedao/connect-core/runtime-config",
1638
+ "@tanstack/react-router/ssr/client",
1639
+ "@tanstack/react-router/ssr/server"
1640
+ ]);
1641
+ /**
1642
+ * React-family specifiers kept external to the vendor build. The vendor's chunks
1643
+ * emit bare imports for these; `devReactImportmapPlugin`'s import map resolves
1644
+ * them to Vite's pre-bundled React, so there is exactly one React instance.
1645
+ */
1646
+ const VENDOR_EXTERNAL = [
1647
+ "react",
1648
+ "react-dom",
1649
+ "react-dom/client",
1650
+ "react/jsx-runtime",
1651
+ "react/jsx-dev-runtime",
1652
+ "ph-bundled-packages-virtual"
1653
+ ];
1654
+ /** URL prefix the vendor bundle is served under by the dev middleware. */
1655
+ const VENDOR_URL_PREFIX = "/__vendor__/";
1656
+ const VENDOR_DYNAMIC_BASE = `${DYNAMIC_BASE_PLACEHOLDER}${VENDOR_URL_PREFIX.replace(/^\/+/, "")}`;
1657
+ /**
1658
+ * Build the prebuilt vendor (once, in a throwaway subprocess) and return its dir
1659
+ * + import map. Idempotent: reuses a cached vendor built for the same dep set.
1660
+ * Returns null on any failure (caller falls back to a normal dev server).
1661
+ */
1662
+ async function prebuildConnectVendor(options) {
1663
+ const include = expandIncludeSubpaths(options.dirname, options.include ?? DEFAULT_VENDOR_INCLUDE);
1664
+ const own = options.ownDeps ? resolveOwnDeps(options.ownDeps.from, options.ownDeps.specs) : {};
1665
+ for (const spec of Object.keys(own)) if (!include.includes(spec)) include.push(spec);
1666
+ const external = options.external ?? VENDOR_EXTERNAL;
1667
+ const vendorDir = options.vendorDir ?? join(options.dirname, "node_modules/.ph-vendor");
1668
+ const importMapPath = join(vendorDir, "import-map.json");
1669
+ const stamps = /* @__PURE__ */ new Map();
1670
+ const versions = resolveDepVersions(options.dirname, [...include, ...external], stamps);
1671
+ const base = options.base ?? DYNAMIC_BASE_PLACEHOLDER;
1672
+ const nodeEnv = options.nodeEnv ?? "development";
1673
+ const versionDigest = resolveVersionDigest(versions, own, stamps, {
1674
+ base,
1675
+ nodeEnv
1676
+ });
1677
+ try {
1678
+ const hit = readCacheHit(importMapPath, include, external, versionDigest);
1679
+ if (hit) return {
1680
+ vendorDir,
1681
+ ...hit
1682
+ };
1683
+ const lockDir = `${vendorDir}.lock`;
1684
+ const lock = acquireLock(lockDir);
1685
+ if (!lock) {
1686
+ const hit = await waitForCacheHit(importMapPath, include, external, versionDigest, lockDir);
1687
+ return hit ? {
1688
+ vendorDir,
1689
+ ...hit
1690
+ } : null;
1691
+ }
1692
+ try {
1693
+ const raced = readCacheHit(importMapPath, include, external, versionDigest);
1694
+ if (raced) return {
1695
+ vendorDir,
1696
+ ...raced
1697
+ };
1698
+ const result = await buildVendorAtomic(options.dirname, vendorDir, include, external, versionDigest, versions, base, nodeEnv, own);
1699
+ return result ? {
1700
+ vendorDir,
1701
+ ...result
1702
+ } : null;
1703
+ } finally {
1704
+ releaseLock(lock);
1705
+ }
1706
+ } catch (err) {
1707
+ if (options.errorRef) options.errorRef.message = err instanceof Error ? err.message : String(err);
1708
+ return null;
1709
+ }
1710
+ }
1711
+ function readCacheHit(importMapPath, include, external, versionDigest) {
1712
+ if (!existsSync(importMapPath)) return null;
1713
+ try {
1714
+ const cached = JSON.parse(readFileSync(importMapPath, "utf8"));
1715
+ if (sameSet(cached.include, include) && sameSet(cached.external, external) && cached.versionDigest === versionDigest && typeof cached.sharedDeps === "string") return {
1716
+ imports: cached.imports,
1717
+ versions: cached.versions ?? {},
1718
+ sharedDeps: cached.sharedDeps
1719
+ };
1720
+ } catch {}
1721
+ return null;
1722
+ }
1723
+ const NON_RUNTIME_FILE = /\.(map|d\.[cm]?ts|tsbuildinfo)$/;
1724
+ function linkedBuildStamp(pkgRoot) {
1725
+ if (pkgRoot.split(/[\\/]/).includes("node_modules")) return "";
1726
+ let newest = 0;
1727
+ try {
1728
+ const entries = readdirSync(join(pkgRoot, "dist"), {
1729
+ recursive: true,
1730
+ withFileTypes: true
1731
+ });
1732
+ for (const entry of entries) {
1733
+ if (!entry.isFile() || NON_RUNTIME_FILE.test(entry.name)) continue;
1734
+ const { mtimeMs } = statSync(join(entry.parentPath, entry.name));
1735
+ if (mtimeMs > newest) newest = mtimeMs;
1736
+ }
1737
+ } catch {
1738
+ return "";
1739
+ }
1740
+ return newest ? `+dist.${Math.trunc(newest)}` : "";
1741
+ }
1742
+ function cachedStamp(stamps, pkgRoot) {
1743
+ let stamp = stamps.get(pkgRoot);
1744
+ if (stamp === void 0) {
1745
+ stamp = linkedBuildStamp(pkgRoot);
1746
+ stamps.set(pkgRoot, stamp);
1747
+ }
1748
+ return stamp;
1749
+ }
1750
+ /**
1751
+ * Resolve the installed version of each spec's owning package, deduped by
1752
+ * package name. Resolution order per spec:
1753
+ * 1. the project itself, when it IS the owning package (a self-vendoring
1754
+ * app has no node_modules self-link);
1755
+ * 2. the project's own node_modules link (works for pnpm-strict and
1756
+ * hoisted layouts alike, and — unlike `require.resolve` — for
1757
+ * ESM-only packages whose exports map has no CJS condition);
1758
+ * 3. Node's own module resolution (covers transitive installs), walking
1759
+ * the entry up to the owning package's package.json.
1760
+ * Unresolvable specs contribute a "missing" sentinel, unknown versions
1761
+ * "unknown".
1762
+ */
1763
+ function resolveDepVersions(dirname$3, specs, stamps = /* @__PURE__ */ new Map()) {
1764
+ const req = createRequire(join(dirname$3, "noop.js"));
1765
+ const seen = {};
1766
+ let selfMeta = null;
1767
+ for (const spec of specs) {
1768
+ const { pkg } = parsePkg(spec);
1769
+ if (pkg in seen) continue;
1770
+ if (selfMeta === null) try {
1771
+ selfMeta = JSON.parse(readFileSync(join(dirname$3, "package.json"), "utf8"));
1772
+ } catch {
1773
+ selfMeta = {};
1774
+ }
1775
+ let version;
1776
+ if (typeof selfMeta.name === "string" && selfMeta.name === pkg && typeof selfMeta.version === "string") version = selfMeta.version;
1777
+ else {
1778
+ version = "missing";
1779
+ try {
1780
+ const pkgRoot = realpathSync(join(dirname$3, "node_modules", pkg));
1781
+ const meta = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8"));
1782
+ version = String(meta.version ?? "unknown") + cachedStamp(stamps, pkgRoot);
1783
+ } catch {
1784
+ try {
1785
+ const entry = req.resolve(spec);
1786
+ let dir = dirname(entry);
1787
+ for (let depth = 0; depth < 8; depth++) {
1788
+ if (existsSync(join(dir, "package.json"))) {
1789
+ const meta = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
1790
+ version = String(meta.version ?? "unknown");
1791
+ break;
1792
+ }
1793
+ const parent = dirname(dir);
1794
+ if (parent === dir) break;
1795
+ dir = parent;
1796
+ }
1797
+ } catch {}
1798
+ }
1799
+ }
1800
+ seen[pkg] = version;
1801
+ }
1802
+ return seen;
1803
+ }
1804
+ function resolveVersionDigest(versions, own, stamps, build) {
1805
+ const h = createHash("sha256");
1806
+ h.update(`base:${build.base}\nnodeEnv:${build.nodeEnv}\n`);
1807
+ const workerHash = createHash("sha256").update(VENDOR_BUILD_WORKER).digest("hex");
1808
+ h.update(`worker:${workerHash}\n`);
1809
+ for (const pkg of Object.keys(versions).sort()) h.update(`${pkg}@${versions[pkg]}\n`);
1810
+ for (const spec of Object.keys(own).sort()) {
1811
+ const stamp = cachedStamp(stamps, ownPackageRoot(own[spec]));
1812
+ h.update(`own:${spec}=${own[spec]}${stamp}\n`);
1813
+ }
1814
+ return h.digest("hex").slice(0, 16);
1815
+ }
1816
+ function sameSet(a, b) {
1817
+ if (!a || a.length !== b.length) return false;
1818
+ const s = new Set(a);
1819
+ return b.every((x) => s.has(x));
1820
+ }
1821
+ const LOCK_STALE_MS = 3e5;
1822
+ const LOCK_HEARTBEAT_MS = 6e4;
1823
+ const ownerFile = (lockDir) => join(lockDir, "owner");
1824
+ function lockIsStale(lockDir) {
1825
+ try {
1826
+ return Date.now() - statSync(ownerFile(lockDir)).mtimeMs > LOCK_STALE_MS;
1827
+ } catch {
1828
+ return false;
1829
+ }
1830
+ }
1831
+ function acquireLock(lockDir) {
1832
+ let made = false;
1833
+ try {
1834
+ mkdirSync(lockDir);
1835
+ made = true;
1836
+ } catch {
1837
+ if (lockIsStale(lockDir)) try {
1838
+ rmSync(lockDir, {
1839
+ recursive: true,
1840
+ force: true
1841
+ });
1842
+ mkdirSync(lockDir);
1843
+ made = true;
1844
+ } catch {}
1845
+ }
1846
+ if (!made) return null;
1847
+ const token = `${process.pid}-${randomUUID()}`;
1848
+ writeFileSync(ownerFile(lockDir), token);
1849
+ const timer = setInterval(() => {
1850
+ try {
1851
+ if (readFileSync(ownerFile(lockDir), "utf8") === token) writeFileSync(ownerFile(lockDir), token);
1852
+ else clearInterval(timer);
1853
+ } catch {
1854
+ clearInterval(timer);
1855
+ }
1856
+ }, LOCK_HEARTBEAT_MS);
1857
+ timer.unref();
1858
+ return {
1859
+ dir: lockDir,
1860
+ token,
1861
+ timer
1862
+ };
1863
+ }
1864
+ function releaseLock(lock) {
1865
+ clearInterval(lock.timer);
1866
+ try {
1867
+ if (readFileSync(ownerFile(lock.dir), "utf8") === lock.token) rmSync(lock.dir, {
1868
+ recursive: true,
1869
+ force: true
1870
+ });
1871
+ } catch {}
1872
+ }
1873
+ async function waitForCacheHit(importMapPath, include, external, versionDigest, lockDir) {
1874
+ const deadline = Date.now() + LOCK_STALE_MS;
1875
+ while (Date.now() < deadline) {
1876
+ const hit = readCacheHit(importMapPath, include, external, versionDigest);
1877
+ if (hit) return hit;
1878
+ if (!existsSync(lockDir)) return readCacheHit(importMapPath, include, external, versionDigest);
1879
+ await new Promise((r) => setTimeout(r, 250));
1880
+ }
1881
+ return null;
1882
+ }
1883
+ function importTarget$1(value) {
1884
+ if (typeof value === "string") return value;
1885
+ if (!value || typeof value !== "object") return null;
1886
+ const o = value;
1887
+ for (const c of [
1888
+ "browser",
1889
+ "import",
1890
+ "module",
1891
+ "default"
1892
+ ]) if (c in o) {
1893
+ const t = importTarget$1(o[c]);
1894
+ if (t) return t;
1895
+ }
1896
+ return null;
1897
+ }
1898
+ /** The package root at or above `from` that Node would load `pkg` from, or null. */
1899
+ function findPackageRoot(from, pkg) {
1900
+ let dir = from;
1901
+ for (;;) {
1902
+ const candidate = join(dir, "node_modules", pkg);
1903
+ if (existsSync(join(candidate, "package.json"))) return realpathSync(candidate);
1904
+ const parent = dirname(dir);
1905
+ if (parent === dir) return null;
1906
+ dir = parent;
1907
+ }
1908
+ }
1909
+ function ownRoots(own) {
1910
+ const roots = /* @__PURE__ */ new Set();
1911
+ for (const file of Object.values(own)) {
1912
+ const root = ownPackageRoot(file);
1913
+ try {
1914
+ const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
1915
+ if (Object.keys(meta.dependencies ?? {}).length === 0) roots.add(root + sep);
1916
+ } catch {}
1917
+ }
1918
+ return [...roots];
1919
+ }
1920
+ function ownPackageRoot(file) {
1921
+ let dir = dirname(file);
1922
+ for (;;) {
1923
+ try {
1924
+ if (JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).name) return dir;
1925
+ } catch {}
1926
+ const parent = dirname(dir);
1927
+ if (parent === dir) return dir;
1928
+ dir = parent;
1929
+ }
1930
+ }
1931
+ /** Each spec's browser/import entry file when resolved from `from`; unresolvable specs are left out. */
1932
+ function resolveOwnDeps(from, specs) {
1933
+ const out = {};
1934
+ for (const spec of specs) {
1935
+ const { pkg, sub } = parsePkg(spec);
1936
+ const root = findPackageRoot(from, pkg);
1937
+ if (!root) continue;
1938
+ try {
1939
+ const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
1940
+ const key = sub ? `./${sub}` : ".";
1941
+ let target = null;
1942
+ if (meta.exports && typeof meta.exports === "object") {
1943
+ const exp = meta.exports;
1944
+ target = Object.keys(exp).some((k) => k.startsWith(".")) ? key in exp ? importTarget$1(exp[key]) : null : sub ? null : importTarget$1(exp);
1945
+ } else if (typeof meta.exports === "string") target = sub ? null : meta.exports;
1946
+ else if (!sub) target = meta.module ?? meta.main ?? null;
1947
+ if (!target || /\.(css|json|scss)$/.test(target)) continue;
1948
+ const file = join(root, target);
1949
+ if (existsSync(file)) out[spec] = realpathSync(file);
1950
+ } catch {}
1951
+ }
1952
+ return out;
1953
+ }
1954
+ function parsePkg(spec) {
1955
+ if (spec.startsWith("@")) {
1956
+ const parts = spec.split("/");
1957
+ return {
1958
+ pkg: parts.slice(0, 2).join("/"),
1959
+ sub: parts.slice(2).join("/")
1960
+ };
1961
+ }
1962
+ const i = spec.indexOf("/");
1963
+ return i === -1 ? {
1964
+ pkg: spec,
1965
+ sub: ""
1966
+ } : {
1967
+ pkg: spec.slice(0, i),
1968
+ sub: spec.slice(i + 1)
1969
+ };
1970
+ }
1971
+ /**
1972
+ * Connect imports the heavy libs by subpath too (e.g.
1973
+ * `@powerhousedao/design-system/connect/toast`, `zod/v4/core`). Those bare
1974
+ * imports need their own import-map entry, so expand each listed spec to its
1975
+ * package's concrete (non-wildcard, JS) subpath exports that share the spec's
1976
+ * prefix. Unresolvable / CSS / JSON targets are skipped.
1977
+ *
1978
+ * A spec whose package isn't installed in `dirname` is dropped entirely
1979
+ * rather than kept for the worker: the worker cannot build an entry for a
1980
+ * missing package (its `await import` and the vite resolution both fail),
1981
+ * and a bare re-export entry would fail the whole vendor build. The
1982
+ * importer of a missing shared dep simply bundles its own copy.
1983
+ */
1984
+ function expandIncludeSubpaths(dirname, include) {
1985
+ const out = /* @__PURE__ */ new Set();
1986
+ for (const spec of include) {
1987
+ const { pkg, sub } = parsePkg(spec);
1988
+ let exp;
1989
+ let pkgRoot;
1990
+ try {
1991
+ pkgRoot = realpathSync(join(dirname, "node_modules", pkg));
1992
+ exp = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8")).exports;
1993
+ } catch {
1994
+ continue;
1995
+ }
1996
+ out.add(sub ? spec : pkg);
1997
+ if (!exp || typeof exp !== "object") continue;
1998
+ const expMap = exp;
1999
+ const prefixKey = sub ? `./${sub}` : ".";
2000
+ for (const key of Object.keys(expMap)) {
2001
+ if (key.includes("*") || key === "./package.json") continue;
2002
+ if (/\.(css|json|scss)$/.test(key)) continue;
2003
+ if (!(prefixKey === "." ? key === "." || key.startsWith("./") : key === prefixKey || key.startsWith(`${prefixKey}/`))) continue;
2004
+ const target = importTarget$1(expMap[key]);
2005
+ if (!target || /\.(css|json|scss)$/.test(target)) continue;
2006
+ if (!existsSync(join(pkgRoot, target))) continue;
2007
+ const expanded = key === "." ? pkg : pkg + key.slice(1);
2008
+ if (!VENDOR_SKIP_SUBPATHS.has(expanded)) out.add(expanded);
2009
+ }
2010
+ }
2011
+ return [...out];
2012
+ }
2013
+ /**
2014
+ * The published specifiers whose entry file the vendor build never emitted.
2015
+ * URLs are base-less (`/__vendor__/x.js`) and resolve inside `vendorDir`.
2016
+ */
2017
+ function missingVendorEntries(vendorDir, imports) {
2018
+ const prefix = VENDOR_URL_PREFIX;
2019
+ return Object.entries(imports).filter(([, url]) => {
2020
+ const rel = url.startsWith(prefix) ? url.slice(12) : url;
2021
+ return !existsSync(join(vendorDir, rel));
2022
+ }).map(([spec, url]) => ({
2023
+ spec,
2024
+ url
2025
+ }));
2026
+ }
2027
+ /**
2028
+ * Rebase the vendor's base-less entry URLs (`/__vendor__/x.js`) onto the
2029
+ * deploy base, so a consumer that resolves them against the page origin lands
2030
+ * under that base rather than the server root. A dynamic-base build keeps its
2031
+ * placeholder, which the runtime substitutes.
2032
+ *
2033
+ * `base` is the app base from `prebuildConnectVendor` callers; a base that
2034
+ * already carries the vendor segment has it dropped first so it is never
2035
+ * doubled.
2036
+ */
2037
+ function withVendorBase(imports, base) {
2038
+ const segment = VENDOR_URL_PREFIX.replace(/^\/+/, "");
2039
+ const appBase = base.endsWith(segment) ? base.slice(0, base.length - segment.length) : base;
2040
+ return Object.fromEntries(Object.entries(imports).map(([spec, url]) => [spec, `${appBase}/${url}`.replace(/([^:])\/{2,}/g, "$1/").replace(/^\/{2,}/, "/")]));
2041
+ }
2042
+ /**
2043
+ * Build the vendor into a unique temp dir, then atomically swap it into place,
2044
+ * so a concurrent reader never sees a partial bundle or import-map.json. Runs
2045
+ * the build in a throwaway subprocess (its peak memory is reclaimed on exit);
2046
+ * the parent augments the import map with the version digest + the version
2047
+ * table, writes the runtime shared-deps module, and does the swap.
2048
+ * Returns the published import map + versions, or null on failure.
2049
+ */
2050
+ async function buildVendorAtomic(dirname$4, vendorDir, include, external, versionDigest, versions, base, nodeEnv, own = {}) {
2051
+ const parent = dirname(vendorDir);
2052
+ mkdirSync(parent, { recursive: true });
2053
+ const tmpDir = mkdtempSync(join(parent, ".ph-vendor.tmp-"));
2054
+ try {
2055
+ const { ok, stderr } = await runBuildWorker(dirname$4, tmpDir, include, external, base, nodeEnv, own);
2056
+ const tmpMap = join(tmpDir, "import-map.json");
2057
+ if (!ok || !existsSync(tmpMap)) {
2058
+ const detail = stderr.trim();
2059
+ throw new Error(`vendor build failed${detail ? `:\n${detail}` : " (no output captured)"}`);
2060
+ }
2061
+ const meta = JSON.parse(readFileSync(tmpMap, "utf8"));
2062
+ const unbacked = missingVendorEntries(tmpDir, meta.imports);
2063
+ 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"));
2064
+ meta.versionDigest = versionDigest;
2065
+ meta.versions = versions;
2066
+ meta.base = base;
2067
+ meta.nodeEnv = nodeEnv;
2068
+ const sharedDepsSource = `export const imports = ${JSON.stringify(withVendorBase(meta.imports, base))};\nexport const versions = ${JSON.stringify(versions)};\n`;
2069
+ const sharedDepsFile = `shared-deps-${createHash("sha256").update(sharedDepsSource).digest("hex").slice(0, 12)}.js`;
2070
+ writeFileSync(join(tmpDir, sharedDepsFile), sharedDepsSource);
2071
+ writeFileSync(join(tmpDir, "shared-deps.js"), sharedDepsSource);
2072
+ meta.sharedDeps = VENDOR_URL_PREFIX + sharedDepsFile;
2073
+ writeFileSync(tmpMap, JSON.stringify(meta, null, 2));
2074
+ const oldDir = `${vendorDir}.old-${process.pid}-${Date.now()}`;
2075
+ if (existsSync(vendorDir)) renameSync(vendorDir, oldDir);
2076
+ renameSync(tmpDir, vendorDir);
2077
+ chmodSync(vendorDir, 493);
2078
+ rmSync(oldDir, {
2079
+ recursive: true,
2080
+ force: true
2081
+ });
2082
+ return {
2083
+ imports: meta.imports,
2084
+ versions,
2085
+ sharedDeps: meta.sharedDeps
2086
+ };
2087
+ } catch (err) {
2088
+ rmSync(tmpDir, {
2089
+ recursive: true,
2090
+ force: true
2091
+ });
2092
+ throw err;
2093
+ }
2094
+ }
2095
+ function resolveSelfModulePath() {
2096
+ const selfPath = fileURLToPath(import.meta.url);
2097
+ if (!selfPath.endsWith(".ts")) return selfPath;
2098
+ let dir = dirname(selfPath);
2099
+ for (let depth = 0; depth < 4; depth++) {
2100
+ const candidate = join(dir, "dist", "index.mjs");
2101
+ if (existsSync(candidate)) return candidate;
2102
+ const parent = dirname(dir);
2103
+ if (parent === dir) break;
2104
+ dir = parent;
2105
+ }
2106
+ throw new Error("vendor build needs the built builder-tools bundle (dist/index.mjs); build the package first");
2107
+ }
2108
+ /**
2109
+ * Spawn a throwaway worker that generates one entry per specifier (CJS deps get
2110
+ * explicit named re-exports, ESM deps `export *`), `vite build`s them into the
2111
+ * given out dir, and writes the import map. Captures stdout/stderr so a failure
2112
+ * is debuggable; the normal path stays quiet.
2113
+ */
2114
+ function runBuildWorker(dirname, outDir, include, external, base, nodeEnv, own = {}) {
2115
+ const workerPath = join(outDir, "build-worker.mjs");
2116
+ writeFileSync(workerPath, VENDOR_BUILD_WORKER);
2117
+ const selfModulePath = resolveSelfModulePath();
2118
+ return new Promise((resolve) => {
2119
+ const child = spawn(process.execPath, [
2120
+ workerPath,
2121
+ dirname,
2122
+ outDir,
2123
+ JSON.stringify(include),
2124
+ VENDOR_URL_PREFIX,
2125
+ JSON.stringify(external),
2126
+ VENDOR_DYNAMIC_BASE,
2127
+ selfModulePath,
2128
+ base,
2129
+ nodeEnv,
2130
+ JSON.stringify({
2131
+ files: own,
2132
+ roots: ownRoots(own)
2133
+ })
2134
+ ], {
2135
+ cwd: dirname,
2136
+ stdio: [
2137
+ "ignore",
2138
+ "pipe",
2139
+ "pipe"
2140
+ ]
2141
+ });
2142
+ let stderr = "";
2143
+ child.stdout.on("data", (d) => {
2144
+ stderr += String(d);
2145
+ });
2146
+ child.stderr.on("data", (d) => {
2147
+ stderr += String(d);
2148
+ });
2149
+ child.on("exit", (code) => resolve({
2150
+ ok: code === 0,
2151
+ stderr
2152
+ }));
2153
+ child.on("error", (e) => resolve({
2154
+ ok: false,
2155
+ stderr: String(e)
2156
+ }));
2157
+ });
2158
+ }
2159
+ /**
2160
+ * The vendor build worker, written to disk and run as a subprocess. Loads
2161
+ * `vite` from the project and `connectDynamicBasePlugin` from builder-tools' own
2162
+ * built bundle (selfModulePath). argv: dirname, vendorDir, includeJSON,
2163
+ * urlPrefix, externalJSON, dynamicBase, selfModulePath, base (app base),
2164
+ * nodeEnv.
2165
+ */
2166
+ const VENDOR_BUILD_WORKER = `
2167
+ import { createRequire } from 'node:module';
2168
+ import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
2169
+ import { join, isAbsolute } from 'node:path';
2170
+ import { fileURLToPath, pathToFileURL } from 'node:url';
2171
+ const [dirname, vendorDir, includeJSON, urlPrefix, externalJSON, dynamicBase, selfModulePath, baseArg, nodeEnvArg, ownJSON] = process.argv.slice(2);
2172
+ // ownDeps: spec -> absolute entry file, plus each one's package root.
2173
+ const { files: own = {}, roots: ownRootList = [] } = JSON.parse(ownJSON || '{}');
2174
+ // One chunk per own-dep package: split between an entry and a shared chunk, a
2175
+ // barrel can re-export from the entry and run before the classes it extends.
2176
+ const ownGroups = ownRootList.map((root, i) => ({ name: 'own-' + i, test: (id) => id.startsWith(root) }));
2177
+ // Trailing argv are optional (older callers): base defaults to the dynamic
2178
+ // placeholder behavior, nodeEnv to development. baseArg is the APP base —
2179
+ // the same string the app build uses; the build base appends the vendor
2180
+ // segment so emitted asset URLs land under <app-base>__vendor__/.
2181
+ const segment = urlPrefix.replace(/^\\/+/, '');
2182
+ const base = baseArg ? baseArg + segment : dynamicBase;
2183
+ const nodeEnv = nodeEnvArg ?? 'development';
2184
+ const include = JSON.parse(includeJSON);
2185
+ const external = JSON.parse(externalJSON ?? '[]');
2186
+ const externalSet = new Set(external);
2187
+ const reqProj = createRequire(join(dirname, 'noop.js'));
2188
+ // pathToFileURL: require.resolve returns an absolute path, and on Windows
2189
+ // import('D:\\...') parses "D:" as a URL scheme (ERR_UNSUPPORTED_ESM_URL_SCHEME).
2190
+ const { build, esmExternalRequirePlugin } = await import(pathToFileURL(reqProj.resolve('vite')).href);
2191
+ // Load the dynamic-base plugin from builder-tools' own built bundle (passed as
2192
+ // an absolute path) — it isn't resolvable as a bare specifier from the worker.
2193
+ const { connectDynamicBasePlugin, DYNAMIC_BASE_PLACEHOLDER } = await import(pathToFileURL(selfModulePath));
2194
+ const srcDir = join(vendorDir, '.entries');
2195
+ mkdirSync(srcDir, { recursive: true });
2196
+ const entryName = (spec) => spec.replace(/[^\\w]+/g, '_');
2197
+ const RESERVED = new Set('enum void null function in instanceof typeof new delete do if else return switch case break continue for while this true false class const let var default export import extends super with yield debugger finally throw try catch await implements interface package private protected public static eval arguments'.split(' '));
2198
+ const input = {};
2199
+ for (const spec of include) {
2200
+ const name = entryName(spec);
2201
+ const from = own[spec] ?? spec;
2202
+ let src;
2203
+ try {
2204
+ // Import the bare spec (not reqProj.resolve(spec)) so Node picks the same
2205
+ // import/browser-condition module the build resolves — resolving first can
2206
+ // pick a CJS sibling whose default-export shape differs from the ESM build.
2207
+ const ns = await import(own[spec] ? pathToFileURL(own[spec]).href : spec);
2208
+ // Only fall back to re-exporting from default when the module exposes NO
2209
+ // top-level named exports (a true CJS-interop module). If it does (e.g. zod
2210
+ // exposes \`z\`), \`export *\` captures them; destructuring default would miss
2211
+ // top-level names that aren't keys of the default object.
2212
+ const named = Object.keys(ns).filter((k) => k !== 'default');
2213
+ const cjs = named.length === 0 && ns.default && typeof ns.default === 'object';
2214
+ // A strict entry keeps every export, and zod's \`locales\` (also reachable via \`z\`) pins
2215
+ // ~50 locales; publish them without it. zod/locales stays its own entry.
2216
+ const zodNs = (spec === 'zod' || spec.startsWith('zod/')) && !spec.includes('locales') && named.includes('locales');
2217
+ if (zodNs) {
2218
+ const keep = named.filter((k) => k !== 'locales' && k !== 'z' && /^[A-Za-z_$][\\w$]*$/.test(k));
2219
+ // \`core\` is zod/v4/core's namespace, which exports locales too: rebuild it without them.
2220
+ const coreKeys = keep.includes('core') ? Object.keys(await import('zod/v4/core')).filter((k) => k !== 'locales' && k !== 'default') : [];
2221
+ const reexport = keep.filter((k) => !(k === 'core' && coreKeys.length));
2222
+ src = 'export { ' + reexport.join(', ') + ' } from ' + JSON.stringify(from) + ';\\n'
2223
+ + 'import { ' + reexport.map((k) => k + ' as __z_' + k).join(', ') + ' } from ' + JSON.stringify(from) + ';\\n';
2224
+ if (coreKeys.length) {
2225
+ src += 'import { ' + coreKeys.map((k) => k + ' as __c_' + k).join(', ') + ' } from "zod/v4/core";\\n'
2226
+ + 'const __z_core = Object.freeze({ ' + coreKeys.map((k) => JSON.stringify(k) + ': __c_' + k).join(', ') + ' });\\n'
2227
+ + 'export { __z_core as core };\\n';
2228
+ }
2229
+ src += 'const z = Object.freeze({ ' + keep.map((k) => JSON.stringify(k) + ': __z_' + k).join(', ') + ' });\\n'
2230
+ + (named.includes('z') ? 'export { z };\\n' : '')
2231
+ + (('default' in ns) && ns.default === ns.z ? 'export { z as default };\\n' : '');
2232
+ } else if (cjs) {
2233
+ const names = Object.keys(ns.default).filter((k) => k !== 'default' && k !== '__esModule' && /^[A-Za-z_$][\\w$]*$/.test(k));
2234
+ const plain = names.filter((n) => !RESERVED.has(n));
2235
+ const reserved = names.filter((n) => RESERVED.has(n));
2236
+ src = 'import d from ' + JSON.stringify(from) + ';\\nexport default d;\\n'
2237
+ + (plain.length ? 'export const { ' + plain.join(', ') + ' } = d;\\n' : '');
2238
+ // reserved words are invalid as const-binding names but valid as export
2239
+ // aliases (export { x as enum }).
2240
+ reserved.forEach((n, i) => {
2241
+ src += 'const __r' + i + ' = d[' + JSON.stringify(n) + '];\\nexport { __r' + i + ' as ' + n + ' };\\n';
2242
+ });
2243
+ } else {
2244
+ src = 'export * from ' + JSON.stringify(from) + ';\\n'
2245
+ + (('default' in ns) ? 'export { default } from ' + JSON.stringify(from) + ';\\n' : '');
2246
+ }
2247
+ } catch {
2248
+ src = 'export * from ' + JSON.stringify(from) + ';\\n';
2249
+ }
2250
+ const file = join(srcDir, name + '.js');
2251
+ writeFileSync(file, src);
2252
+ input[name] = file;
2253
+ }
2254
+ // Prefer the bundler's browser-condition-aware resolution; fall back to resolving
2255
+ // from the worker (real install path) only for Rolldown's realpath-anchoring bug.
2256
+ const phResolveCache = new Map();
2257
+ const phVendorResolve = {
2258
+ name: 'ph-vendor-resolve', enforce: 'pre',
2259
+ async resolveId(source, importer, options) {
2260
+ if (externalSet.has(source)) return null;
2261
+ if (source[0] === '\\0' || source[0] === '.' || isAbsolute(source)) return null;
2262
+ if (source.startsWith('node:') || source.startsWith('data:')) return null;
2263
+ let viaBundler = null;
2264
+ try { viaBundler = await this.resolve(source, importer, { ...options, skipSelf: true }); } catch {}
2265
+ if (viaBundler) return viaBundler;
2266
+ if (phResolveCache.has(source)) return phResolveCache.get(source);
2267
+ let resolved = null;
2268
+ try { resolved = fileURLToPath(import.meta.resolve(source)); } catch {}
2269
+ phResolveCache.set(source, resolved);
2270
+ return resolved;
2271
+ },
2272
+ };
2273
+ const result = await build({
2274
+ root: dirname, configFile: false, logLevel: 'error',
2275
+ // Caller-provided build base (or the dynamic placeholder default):
2276
+ // connectDynamicBasePlugin rewrites emitted chunk/asset URLs to resolve
2277
+ // against the deploy base at serve time.
2278
+ base,
2279
+ define: {
2280
+ 'process.env.NODE_ENV': JSON.stringify(nodeEnv),
2281
+ // BASE_URL resolves to the deploy base (not the vendor prefix) so vendored
2282
+ // Connect's router basename + BASE_URL-relative fetches use the right path.
2283
+ // The app base when provided (concrete or placeholder), the placeholder
2284
+ // otherwise (dev flow — rewritten at serve time by the dynamic-base plugin).
2285
+ 'import.meta.env.BASE_URL': JSON.stringify(baseArg ?? DYNAMIC_BASE_PLACEHOLDER),
2286
+ },
2287
+ // phVendorResolve (pre) resolves bares from the worker; esmExternalRequirePlugin owns
2288
+ // react/virtual externalization; connectDynamicBasePlugin (post) rewrites the placeholder base.
2289
+ plugins: [phVendorResolve, esmExternalRequirePlugin({ external }), connectDynamicBasePlugin()],
2290
+ // pglite ships web workers as ES-module chunks. workerStripPrefix is the vendor
2291
+ // segment so the worker recovers the deploy base, not the vendor prefix.
2292
+ worker: { format: 'es', plugins: () => [connectDynamicBasePlugin({ forWorker: true, workerStripPrefix: urlPrefix.replace(/^\\/+/, '') })] },
2293
+ build: {
2294
+ // Production ships this to every visitor, so minify it like the app's own
2295
+ // chunks; dev keeps readable output and the faster build.
2296
+ outDir: vendorDir, emptyOutDir: false, minify: nodeEnv === 'production', target: 'esnext', cssCodeSplit: true,
2297
+ rollupOptions: {
2298
+ input, preserveEntrySignatures: 'strict',
2299
+ // Content-hashed entry names: each build's import map points at new URLs.
2300
+ output: { format: 'es', entryFileNames: '[name]-[hash].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]', ...(ownGroups.length ? { codeSplitting: { groups: ownGroups } } : {}) },
2301
+ },
2302
+ },
2303
+ });
2304
+ rmSync(srcDir, { recursive: true, force: true });
2305
+ const emitted = {};
2306
+ for (const out of Array.isArray(result) ? result : [result]) {
2307
+ for (const chunk of out?.output ?? []) {
2308
+ if (chunk.type === 'chunk' && chunk.isEntry) emitted[chunk.name] = chunk.fileName;
2309
+ }
2310
+ }
2311
+ const imports = {};
2312
+ // An entry the build never emitted keeps its unhashed name; the caller reports it as missing.
2313
+ for (const spec of include) imports[spec] = urlPrefix + (emitted[entryName(spec)] ?? entryName(spec) + '.js');
2314
+ writeFileSync(join(vendorDir, 'import-map.json'), JSON.stringify({ include, external, imports }, null, 2));
2315
+ `;
2316
+ //#endregion
2317
+ //#region connect-utils/reactor-worker-build.ts
173
2318
  /**
174
- * Prebuild the heavy, stable Connect dependencies into a static ESM "vendor"
175
- * bundle so the dev server never runs (or holds) the dependency optimizer /
176
- * module graph for them.
2319
+ * Prebuild Connect's reactor SharedWorker into a browser-loadable bundle.
177
2320
  *
178
- * The reactor-project preview dev-optimizes a large UI graph (Connect itself,
179
- * design-system, document-engineering, reactor-browser, …) every session —
180
- * ~1–2 GB resident — even though those libs don't change; only the project's
181
- * editors do. This module builds them ONCE with `vite build` (in a throwaway
182
- * subprocess that exits, freeing the build's peak memory): `vite build` handles
183
- * CSS/asset imports, web workers, and WASM (Connect's in-browser PGlite ships
184
- * all three), and a multi-entry build with `preserveEntrySignatures: 'strict'`
185
- * dedupes shared code into shared chunks. Entries for CJS deps re-export the
186
- * module's named API explicitly (so `import { createRoot }` works); ESM deps
187
- * use `export *`. The build runs under a dynamic-base placeholder + vendor
188
- * segment (`connectDynamicBasePlugin`), so emitted asset/chunk URLs
189
- * (`new URL(…, import.meta.url)` for .wasm/.data/workers) carry the placeholder
190
- * and resolve at serve time to `<deploy-base>__vendor__/`, while the vendored
191
- * Connect's `import.meta.env.BASE_URL` resolves to the deploy base.
2321
+ * The published `@powerhousedao/connect` dist ships `reactor.worker.js` as a
2322
+ * library artifact: its dependencies are externalized onto bare specifiers
2323
+ * (`@powerhousedao/reactor`, `kysely`, ...). The page resolves those through
2324
+ * its `<script type="importmap">`, but import maps are a document feature —
2325
+ * a worker never inherits one and no Worker/SharedWorker constructor option
2326
+ * can supply one. A bare specifier inside a worker is unresolvable by the
2327
+ * platform, so the shipped file can never run as a worker script.
192
2328
  *
193
- * The React family stays EXTERNAL (see `VENDOR_EXTERNAL`); `esmExternalRequirePlugin`
194
- * owns that externalization and rewrites CJS `require("react")` → import. Vendor
195
- * chunks keep bare React imports, which the dev import map resolves to Vite's
196
- * pre-bundled React (`devReactImportmapPlugin`) — one React instance across the
197
- * vendor, the project's editors, and CDN-loaded editors.
2329
+ * This module builds the worker's module graph into a self-contained bundle
2330
+ * (one `vite build` in a throwaway subprocess, same pattern as the vendor
2331
+ * prebuild). Two modes:
198
2332
  *
199
- * `devReactImportmapPlugin` consumes the result: it externalizes these
200
- * specifiers in the long-lived dev server, points the page import map at the
201
- * vendor URLs, and serves the bundle. With Connect vendored, the dev server only
202
- * processes the project's own `main` + local package; HMR for them is unaffected.
2333
+ * - With `vendorImports` (production builds that also ship the `__vendor__/`
2334
+ * bundle): specifiers present in the vendor import map are externalized and
2335
+ * rewritten to `../__vendor__/<entry>.js`. The worker bundle is served as a
2336
+ * sibling of `__vendor__/`, so those relative imports hit the exact URLs
2337
+ * the page's import map uses — one fetch and one HTTP-cache entry per
2338
+ * shared dep for the page and the worker together.
2339
+ * - Without (dev servers, `PH_CONNECT_VENDOR=0` builds): everything is
2340
+ * bundled; the worker is self-contained.
2341
+ *
2342
+ * The build uses Vite's relative base (`"./"`), so emitted chunk and asset
2343
+ * URLs resolve against the worker script's own URL. That sidesteps the
2344
+ * dynamic-base machinery entirely: the bundle works under any deploy base,
2345
+ * concrete or proxy-substituted, as long as it is served under
2346
+ * `<app-base>/__reactor_worker__/`.
2347
+ */
2348
+ /** URL prefix the worker bundle is served under, next to `__vendor__/`. */
2349
+ const REACTOR_WORKER_URL_PREFIX = "/__reactor_worker__/";
2350
+ /** Entry filename of the bundle; the tab constructs its SharedWorker from it. */
2351
+ const REACTOR_WORKER_ENTRY = "reactor.worker.js";
2352
+ /** Metadata file the cache check reads; lives inside the bundle dir. */
2353
+ const META_FILE = "worker-meta.json";
2354
+ /** Content-Type for the extensions the worker build emits; JS is the default. */
2355
+ const REACTOR_WORKER_MIME = {
2356
+ ".map": "application/json",
2357
+ ".json": "application/json",
2358
+ ".wasm": "application/wasm",
2359
+ ".data": "application/octet-stream"
2360
+ };
2361
+ /**
2362
+ * The installed Connect dist's worker entry, or null when the installed
2363
+ * version predates the worker (the feature is then unavailable, not broken).
2364
+ */
2365
+ function resolveReactorWorkerSource(dirname) {
2366
+ try {
2367
+ const candidate = join(realpathSync(join(dirname, "node_modules", "@powerhousedao/connect")), "dist", REACTOR_WORKER_ENTRY);
2368
+ return existsSync(candidate) ? candidate : null;
2369
+ } catch {
2370
+ return null;
2371
+ }
2372
+ }
2373
+ /** `/__vendor__/<entry>.js` -> `../__vendor__/<entry>.js` (sibling dirs). */
2374
+ function vendorRelativePath(vendorUrl) {
2375
+ return `../__vendor__/${vendorUrl.slice(vendorUrl.lastIndexOf("/") + 1)}`;
2376
+ }
2377
+ function importSpecifiers(code) {
2378
+ initSync();
2379
+ const [imports] = parse(code);
2380
+ return imports.flatMap((specifier) => specifier.d === -2 || specifier.n === void 0 ? [] : [specifier.n]);
2381
+ }
2382
+ /**
2383
+ * Module specifiers a worker cannot resolve: anything that is not relative,
2384
+ * root-relative, or an http(s)/data/blob URL. Used as a post-build guard so a
2385
+ * leftover bare (or `node:`) import fails the build with a name instead of
2386
+ * shipping a worker that dies on its first import statement.
203
2387
  */
2388
+ function findDisallowedSpecifiers(code) {
2389
+ const found = /* @__PURE__ */ new Set();
2390
+ for (const spec of importSpecifiers(code)) if (!spec.startsWith("./") && !spec.startsWith("../") && !spec.startsWith("/") && !/^(https?:|data:|blob:)/.test(spec)) found.add(spec);
2391
+ return [...found].sort();
2392
+ }
204
2393
  /**
205
- * The stable Connect libraries worth prebuilding. The React family is NOT here —
206
- * it's externalized from the build (see `VENDOR_EXTERNAL`) so the vendor shares
207
- * the dev server's single React instance via the import map.
2394
+ * Fallback list of packages whose BUILT dist shapes the worker bundle's output,
2395
+ * used only when the installed Connect's package.json cannot be read (see
2396
+ * {@link upstreamWorkerPackages}).
208
2397
  */
209
- const DEFAULT_VENDOR_INCLUDE = [
210
- "@powerhousedao/connect",
211
- "document-model",
212
- "zod",
213
- "@powerhousedao/design-system/connect",
214
- "@powerhousedao/reactor-browser",
215
- "@powerhousedao/document-engineering"
216
- ];
2398
+ const FALLBACK_UPSTREAM_WORKER_PACKAGES = ["@powerhousedao/reactor", "@powerhousedao/reactor-browser"];
2399
+ /** Dependency scopes whose installed dist can change the bundle's output. */
2400
+ const UPSTREAM_SCOPES = ["@powerhousedao/", "@renown/"];
217
2401
  /**
218
- * React-family specifiers kept external to the vendor build. The vendor's chunks
219
- * emit bare imports for these; `devReactImportmapPlugin`'s import map resolves
220
- * them to Vite's pre-bundled React, so there is exactly one React instance.
2402
+ * Packages whose BUILT dist shapes the worker bundle's output even when
2403
+ * connect's own dist/reactor.worker.js entry file did not change.
2404
+ *
2405
+ * That entry is a library artifact whose bare imports this build resolves
2406
+ * through node_modules at BUILD time, so a rebuilt dist anywhere in its
2407
+ * closure changes the bundle output without touching the entry file's own
2408
+ * size/mtime. The list is DERIVED from the installed Connect's own
2409
+ * dependencies rather than hardcoded: the bundle pulls `@renown/sdk`,
2410
+ * `@powerhousedao/powerhouse-vetra-packages` and `@powerhousedao/shared` out
2411
+ * of node_modules too, and a hardcoded pair left every one of those able to be
2412
+ * rebuilt behind a cache hit. Connect's dependency list is the cheap stand-in
2413
+ * for the resolved bundle graph: every workspace package the worker can reach
2414
+ * is reachable through it, and a package not in the bundle only costs a readdir.
221
2415
  */
222
- const VENDOR_EXTERNAL = [
223
- "react",
224
- "react-dom",
225
- "react-dom/client",
226
- "react/jsx-runtime",
227
- "react/jsx-dev-runtime",
228
- "ph-bundled-packages-virtual"
229
- ];
230
- /** URL prefix the vendor bundle is served under by the dev middleware. */
231
- const VENDOR_URL_PREFIX = "/__vendor__/";
232
- const VENDOR_DYNAMIC_BASE = `${DYNAMIC_BASE_PLACEHOLDER}${VENDOR_URL_PREFIX.replace(/^\/+/, "")}`;
2416
+ function upstreamWorkerPackages(dirname) {
2417
+ const connectDir = resolveWorkspacePackageDir(dirname, "@powerhousedao/connect");
2418
+ if (!connectDir) return [...FALLBACK_UPSTREAM_WORKER_PACKAGES];
2419
+ let meta;
2420
+ try {
2421
+ meta = JSON.parse(readFileSync(join(connectDir, "package.json"), "utf8"));
2422
+ } catch {
2423
+ return [...FALLBACK_UPSTREAM_WORKER_PACKAGES];
2424
+ }
2425
+ const names = Object.keys(meta.dependencies ?? {}).filter((name) => UPSTREAM_SCOPES.some((scope) => name.startsWith(scope)));
2426
+ for (const name of FALLBACK_UPSTREAM_WORKER_PACKAGES) if (!names.includes(name)) names.push(name);
2427
+ return names.sort();
2428
+ }
233
2429
  /**
234
- * Build the prebuilt vendor (once, in a throwaway subprocess) and return its dir
235
- * + import map. Idempotent: reuses a cached vendor built for the same dep set.
236
- * Returns null on any failure (caller falls back to a normal dev server).
2430
+ * This module's own installed version, read by walking up from its file to
2431
+ * the nearest `package.json` named "@powerhousedao/builder-tools" (same
2432
+ * technique as `build-hash.ts`'s `readConnectVersion`: builder-tools'
2433
+ * `exports` map has no `./package.json` subpath, so node resolution can't
2434
+ * get there). Works whether this runs from source (tests, this monorepo) or
2435
+ * the built dist.
237
2436
  */
238
- async function prebuildConnectVendor(options) {
239
- const include = expandIncludeSubpaths(options.dirname, options.include ?? DEFAULT_VENDOR_INCLUDE);
240
- const external = options.external ?? VENDOR_EXTERNAL;
241
- const vendorDir = options.vendorDir ?? join(options.dirname, "node_modules/.ph-vendor");
242
- const importMapPath = join(vendorDir, "import-map.json");
243
- const versionDigest = resolveVersionDigest(options.dirname, [...include, ...external]);
2437
+ function resolveOwnPackageVersion() {
244
2438
  try {
245
- const hit = readCacheHit(importMapPath, include, external, versionDigest);
246
- if (hit) return {
247
- vendorDir,
248
- imports: hit
249
- };
250
- const lockDir = `${vendorDir}.lock`;
251
- const lock = acquireLock(lockDir);
252
- if (!lock) {
253
- const imports = await waitForCacheHit(importMapPath, include, external, versionDigest, lockDir);
254
- return imports ? {
255
- vendorDir,
256
- imports
257
- } : null;
258
- }
259
- try {
260
- const raced = readCacheHit(importMapPath, include, external, versionDigest);
261
- if (raced) return {
262
- vendorDir,
263
- imports: raced
264
- };
265
- const imports = await buildVendorAtomic(options.dirname, vendorDir, include, external, versionDigest);
266
- return imports ? {
267
- vendorDir,
268
- imports
269
- } : null;
270
- } finally {
271
- releaseLock(lock);
2439
+ let dir = dirname(fileURLToPath(import.meta.url));
2440
+ for (;;) {
2441
+ try {
2442
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
2443
+ if (pkg.name === "@powerhousedao/builder-tools") return pkg.version ?? "unknown";
2444
+ } catch {}
2445
+ const parent = dirname(dir);
2446
+ if (parent === dir) break;
2447
+ dir = parent;
272
2448
  }
273
- } catch (err) {
274
- if (options.errorRef) options.errorRef.message = err instanceof Error ? err.message : String(err);
2449
+ } catch {}
2450
+ return "unknown";
2451
+ }
2452
+ /**
2453
+ * This package's own version, computed once. Folded into the worker bundle
2454
+ * cache key so a builder-tools release — which can change how the bundle is
2455
+ * built (anything in this module beyond {@link WORKER_BUILD_WORKER} itself,
2456
+ * e.g. `workerSafeVendorImports`, the resolve plugin) — invalidates bundles
2457
+ * a prior builder-tools version cached.
2458
+ */
2459
+ const BUILDER_TOOLS_VERSION = resolveOwnPackageVersion();
2460
+ /**
2461
+ * A workspace package's real directory, resolved the way Node's resolver
2462
+ * would (through `node_modules`), or null when it is not installed (e.g. a
2463
+ * non-monorepo consumer project — graceful, not an error). pnpm's
2464
+ * node_modules symlinks resolve to the real package directory, so this
2465
+ * reflects the monorepo's actual dist state, not a stale symlink target.
2466
+ */
2467
+ function resolveWorkspacePackageDir(dirname, pkgName) {
2468
+ try {
2469
+ return realpathSync(join(dirname, "node_modules", ...pkgName.split("/")));
2470
+ } catch {
275
2471
  return null;
276
2472
  }
277
2473
  }
278
- function readCacheHit(importMapPath, include, external, versionDigest) {
279
- if (!existsSync(importMapPath)) return null;
2474
+ /**
2475
+ * Cheap content fingerprint of a directory's immediate files: no file bytes
2476
+ * are read, just each entry's name/size/mtime, so it stays fast even for a
2477
+ * large dist. Sensitive to a rebuild in the common cases: Vite's
2478
+ * content-hashed chunk filenames change the name itself; a stable-named file
2479
+ * (an entry point) changes size or mtime. Bounded (`maxFiles`) so a
2480
+ * pathological directory cannot make this slow — deliberately not a
2481
+ * full-tree hash.
2482
+ *
2483
+ * The names are sorted BEFORE the bound is applied, so the subset the bound
2484
+ * keeps is the same subset on every run: readdir order is unspecified, and
2485
+ * truncating it first made the fingerprint of a directory past the bound a
2486
+ * function of whatever order the filesystem happened to report.
2487
+ */
2488
+ function distDirFingerprint(dir, maxFiles = 1e3) {
280
2489
  try {
281
- const cached = JSON.parse(readFileSync(importMapPath, "utf8"));
282
- if (sameSet(cached.include, include) && sameSet(cached.external, external) && cached.versionDigest === versionDigest) return cached.imports;
283
- } catch {}
284
- return null;
285
- }
286
- function resolveVersionDigest(dirname, specs) {
287
- const seen = /* @__PURE__ */ new Map();
288
- for (const spec of specs) {
289
- 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);
2490
+ return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => e.name).sort().slice(0, maxFiles).map((name) => {
2491
+ const stat = statSync(join(dir, name));
2492
+ return `${name}:${stat.size}:${Math.round(stat.mtimeMs)}`;
2493
+ }).join("|");
2494
+ } catch {
2495
+ return "unreadable";
298
2496
  }
2497
+ }
2498
+ function computeSourceDigest(dirname, entryPath, vendorDir, builderToolsVersion = BUILDER_TOOLS_VERSION) {
299
2499
  const h = createHash("sha256");
300
- const workerHash = createHash("sha256").update(VENDOR_BUILD_WORKER).digest("hex");
301
- h.update(`worker:${workerHash}\n`);
302
- for (const pkg of [...seen.keys()].sort()) h.update(`${pkg}@${seen.get(pkg)}\n`);
2500
+ h.update(`builder:${WORKER_BUILD_WORKER_HASH}\n`);
2501
+ h.update(`builder-tools:${builderToolsVersion}\n`);
2502
+ try {
2503
+ const pkgRoot = resolveWorkspacePackageDir(dirname, "@powerhousedao/connect");
2504
+ if (!pkgRoot) throw new Error("unresolved");
2505
+ const meta = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8"));
2506
+ h.update(`connect:${meta.version ?? "unknown"}\n`);
2507
+ } catch {
2508
+ h.update("connect:unresolved\n");
2509
+ }
2510
+ try {
2511
+ const stat = statSync(entryPath);
2512
+ h.update(`entry:${stat.size}:${Math.round(stat.mtimeMs)}\n`);
2513
+ } catch {
2514
+ h.update("entry:unstatable\n");
2515
+ }
2516
+ for (const pkg of upstreamWorkerPackages(dirname)) {
2517
+ const pkgDir = resolveWorkspacePackageDir(dirname, pkg);
2518
+ h.update(`${pkg}:${pkgDir ? distDirFingerprint(join(pkgDir, "dist")) : "unresolved"}\n`);
2519
+ }
2520
+ if (vendorDir) try {
2521
+ h.update(`vendor:${createHash("sha256").update(readFileSync(join(vendorDir, "import-map.json"))).digest("hex")}\n`);
2522
+ } catch {
2523
+ h.update("vendor:unreadable\n");
2524
+ }
303
2525
  return h.digest("hex").slice(0, 16);
304
2526
  }
305
- function sameSet(a, b) {
306
- if (!a || a.length !== b.length) return false;
307
- const s = new Set(a);
308
- return b.every((x) => s.has(x));
2527
+ function vendorKeyOf(vendorImports) {
2528
+ const entries = Object.entries(vendorImports).sort(([a], [b]) => a.localeCompare(b));
2529
+ return createHash("sha256").update(JSON.stringify(entries)).digest("hex").slice(0, 16);
309
2530
  }
310
- const LOCK_STALE_MS = 5 * 6e4;
311
- const LOCK_HEARTBEAT_MS = 6e4;
312
- const ownerFile = (lockDir) => join(lockDir, "owner");
313
- function lockIsStale(lockDir) {
2531
+ function readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv) {
2532
+ if (!existsSync(metaPath)) return false;
314
2533
  try {
315
- return Date.now() - statSync(ownerFile(lockDir)).mtimeMs > LOCK_STALE_MS;
2534
+ const cached = JSON.parse(readFileSync(metaPath, "utf8"));
2535
+ return cached.sourceDigest === sourceDigest && cached.vendorKey === vendorKey && cached.nodeEnv === nodeEnv && existsSync(join(dirname(metaPath), "reactor.worker.js"));
316
2536
  } catch {
317
2537
  return false;
318
2538
  }
319
2539
  }
320
- function acquireLock(lockDir) {
321
- let made = false;
322
- try {
323
- mkdirSync(lockDir);
324
- made = true;
325
- } catch {
326
- if (lockIsStale(lockDir)) try {
327
- rmSync(lockDir, {
328
- recursive: true,
329
- force: true
330
- });
331
- mkdirSync(lockDir);
332
- made = true;
333
- } catch {}
2540
+ /** Content digest of a directory tree (relative paths + bytes; source maps skipped). */
2541
+ function directoryContentDigest(dir) {
2542
+ const h = createHash("sha256");
2543
+ const files = readdirSync(dir, {
2544
+ recursive: true,
2545
+ withFileTypes: true
2546
+ }).filter((e) => e.isFile() && !e.name.endsWith(".map")).map((e) => join(e.parentPath, e.name)).sort();
2547
+ for (const file of files) {
2548
+ h.update(`${file.slice(dir.length).split("\\").join("/")}\n`);
2549
+ h.update(readFileSync(file));
334
2550
  }
335
- if (!made) return null;
336
- const token = `${process.pid}-${randomUUID()}`;
337
- writeFileSync(ownerFile(lockDir), token);
338
- const timer = setInterval(() => {
339
- try {
340
- if (readFileSync(ownerFile(lockDir), "utf8") === token) writeFileSync(ownerFile(lockDir), token);
341
- else clearInterval(timer);
342
- } catch {
343
- clearInterval(timer);
344
- }
345
- }, LOCK_HEARTBEAT_MS);
346
- timer.unref();
347
- return {
348
- dir: lockDir,
349
- token,
350
- timer
351
- };
352
- }
353
- function releaseLock(lock) {
354
- clearInterval(lock.timer);
355
- try {
356
- if (readFileSync(ownerFile(lock.dir), "utf8") === lock.token) rmSync(lock.dir, {
357
- recursive: true,
358
- force: true
359
- });
360
- } catch {}
2551
+ return h.digest("hex").slice(0, 16);
361
2552
  }
362
- async function waitForCacheHit(importMapPath, include, external, versionDigest, lockDir) {
2553
+ async function waitForWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv, lockDir) {
363
2554
  const deadline = Date.now() + LOCK_STALE_MS;
364
2555
  while (Date.now() < deadline) {
365
- const hit = readCacheHit(importMapPath, include, external, versionDigest);
366
- if (hit) return hit;
367
- if (!existsSync(lockDir)) return readCacheHit(importMapPath, include, external, versionDigest);
2556
+ if (readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv)) return true;
2557
+ if (!existsSync(lockDir)) return readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv);
368
2558
  await new Promise((r) => setTimeout(r, 250));
369
2559
  }
370
- return null;
371
- }
372
- function importTarget$1(value) {
373
- if (typeof value === "string") return value;
374
- if (!value || typeof value !== "object") return null;
375
- const o = value;
376
- for (const c of [
377
- "browser",
378
- "import",
379
- "module",
380
- "default"
381
- ]) if (c in o) {
382
- const t = importTarget$1(o[c]);
383
- if (t) return t;
384
- }
385
- return null;
386
- }
387
- function parsePkg(spec) {
388
- if (spec.startsWith("@")) {
389
- const parts = spec.split("/");
390
- return {
391
- pkg: parts.slice(0, 2).join("/"),
392
- sub: parts.slice(2).join("/")
393
- };
394
- }
395
- const i = spec.indexOf("/");
396
- return i === -1 ? {
397
- pkg: spec,
398
- sub: ""
399
- } : {
400
- pkg: spec.slice(0, i),
401
- sub: spec.slice(i + 1)
402
- };
2560
+ return false;
403
2561
  }
404
2562
  /**
405
- * Connect imports the heavy libs by subpath too (e.g.
406
- * `@powerhousedao/design-system/connect/toast`, `zod/v4/core`). Those bare
407
- * imports need their own import-map entry, so expand each listed spec to its
408
- * 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.
2563
+ * Build the worker bundle (once, in a throwaway subprocess) into `outDir`.
2564
+ * Idempotent: reuses a cached bundle built from the same connect dist, vendor
2565
+ * mapping, and builder logic. Returns null on failure (`errorRef` carries the
2566
+ * cause) or when the installed Connect has no worker entry.
411
2567
  */
412
- function expandIncludeSubpaths(dirname, include) {
413
- const out = new Set(include);
414
- for (const spec of include) {
415
- const { pkg, sub } = parsePkg(spec);
416
- let exp;
417
- let pkgRoot;
2568
+ async function prebuildReactorWorker(options) {
2569
+ const entryPath = options.entryPath ?? resolveReactorWorkerSource(options.dirname);
2570
+ if (!entryPath) {
2571
+ if (options.errorRef) options.errorRef.message = "the installed @powerhousedao/connect ships no dist/reactor.worker.js";
2572
+ return null;
2573
+ }
2574
+ const vendorImports = options.vendor ? workerSafeVendorImports(options.vendor.dir, options.vendor.imports) : {};
2575
+ const nodeEnv = options.nodeEnv ?? "development";
2576
+ const outDir = options.outDir;
2577
+ const metaPath = join(outDir, META_FILE);
2578
+ const sourceDigest = computeSourceDigest(options.dirname, entryPath, options.vendor?.dir);
2579
+ const vendorKey = vendorKeyOf(vendorImports);
2580
+ const result = {
2581
+ outDir,
2582
+ entry: REACTOR_WORKER_ENTRY,
2583
+ sourceDigest,
2584
+ vendorImports
2585
+ };
2586
+ try {
2587
+ if (readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv)) return result;
2588
+ const lockDir = `${outDir}.lock`;
2589
+ const lock = acquireLock(lockDir);
2590
+ if (!lock) return await waitForWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv, lockDir) ? result : null;
418
2591
  try {
419
- pkgRoot = realpathSync(join(dirname, "node_modules", pkg));
420
- exp = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8")).exports;
421
- } catch {
422
- continue;
423
- }
424
- if (!exp || typeof exp !== "object") continue;
425
- const expMap = exp;
426
- const prefixKey = sub ? `./${sub}` : ".";
427
- for (const key of Object.keys(expMap)) {
428
- if (key.includes("*") || key === "./package.json") continue;
429
- if (/\.(css|json|scss)$/.test(key)) continue;
430
- if (!(prefixKey === "." ? key === "." || key.startsWith("./") : key === prefixKey || key.startsWith(`${prefixKey}/`))) continue;
431
- const target = importTarget$1(expMap[key]);
432
- if (!target || /\.(css|json|scss)$/.test(target)) continue;
433
- if (!existsSync(join(pkgRoot, target))) continue;
434
- out.add(key === "." ? pkg : pkg + key.slice(1));
2592
+ if (readWorkerCacheHit(metaPath, sourceDigest, vendorKey, nodeEnv)) return result;
2593
+ await buildWorkerAtomic(options.dirname, outDir, entryPath, vendorImports, nodeEnv, {
2594
+ sourceDigest,
2595
+ vendorKey,
2596
+ nodeEnv
2597
+ });
2598
+ return result;
2599
+ } finally {
2600
+ releaseLock(lock);
435
2601
  }
2602
+ } catch (err) {
2603
+ if (options.errorRef) options.errorRef.message = err instanceof Error ? err.message : String(err);
2604
+ return null;
436
2605
  }
437
- return [...out];
438
2606
  }
439
- /**
440
- * Build the vendor into a unique temp dir, then atomically swap it into place,
441
- * so a concurrent reader never sees a partial bundle or import-map.json. Runs
442
- * 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.
445
- */
446
- async function buildVendorAtomic(dirname$2, vendorDir, include, external, versionDigest) {
447
- const parent = dirname(vendorDir);
2607
+ async function buildWorkerAtomic(dirname$2, outDir, entryPath, vendorImports, nodeEnv, meta) {
2608
+ const parent = dirname(outDir);
448
2609
  mkdirSync(parent, { recursive: true });
449
- const tmpDir = mkdtempSync(join(parent, ".ph-vendor.tmp-"));
2610
+ const tmpDir = mkdtempSync(join(parent, ".ph-reactor-worker.tmp-"));
450
2611
  try {
451
- const { ok, stderr } = await runBuildWorker(dirname$2, tmpDir, include, external);
452
- const tmpMap = join(tmpDir, "import-map.json");
453
- if (!ok || !existsSync(tmpMap)) {
2612
+ const { ok, stderr } = await runWorkerBuild(dirname$2, tmpDir, { "reactor.worker": entryPath }, vendorImports, nodeEnv);
2613
+ if (!ok || !existsSync(join(tmpDir, "reactor.worker.js"))) {
454
2614
  const detail = stderr.trim();
455
- throw new Error(`vendor build failed${detail ? `:\n${detail}` : " (no output captured)"}`);
2615
+ throw new Error(`reactor worker build failed${detail ? `:\n${detail}` : " (no output captured)"}`);
456
2616
  }
457
- const meta = JSON.parse(readFileSync(tmpMap, "utf8"));
458
- meta.versionDigest = versionDigest;
459
- writeFileSync(tmpMap, JSON.stringify(meta, null, 2));
460
- const oldDir = `${vendorDir}.old-${process.pid}-${Date.now()}`;
461
- if (existsSync(vendorDir)) renameSync(vendorDir, oldDir);
462
- renameSync(tmpDir, vendorDir);
463
- rmSync(oldDir, {
464
- recursive: true,
465
- force: true
466
- });
467
- return meta.imports;
2617
+ assertWorkerResolvable(tmpDir);
2618
+ writeFileSync(join(tmpDir, META_FILE), JSON.stringify(meta, null, 2));
2619
+ publishDirAtomic(tmpDir, outDir);
468
2620
  } catch (err) {
469
2621
  rmSync(tmpDir, {
470
2622
  recursive: true,
471
2623
  force: true
472
2624
  });
473
- throw err;
2625
+ throw err;
2626
+ }
2627
+ }
2628
+ /** Replace `outDir` with the finished `tmpDir`, old contents removed last. */
2629
+ function publishDirAtomic(tmpDir, outDir) {
2630
+ const oldDir = `${outDir}.old-${process.pid}-${Date.now()}`;
2631
+ if (existsSync(outDir)) renameSync(outDir, oldDir);
2632
+ renameSync(tmpDir, outDir);
2633
+ chmodSync(outDir, 493);
2634
+ rmSync(oldDir, {
2635
+ recursive: true,
2636
+ force: true
2637
+ });
2638
+ }
2639
+ function findRelativeSpecifiers(code) {
2640
+ return [...new Set(importSpecifiers(code).filter((spec) => spec.startsWith("./") || spec.startsWith("../")))];
2641
+ }
2642
+ function normalizeBundlePath(fromFile, spec) {
2643
+ const segments = fromFile.split("/").slice(0, -1);
2644
+ for (const part of spec.split("/")) {
2645
+ if (part === "" || part === ".") continue;
2646
+ if (part === "..") {
2647
+ if (segments.length === 0) return "";
2648
+ segments.pop();
2649
+ continue;
2650
+ }
2651
+ segments.push(part);
2652
+ }
2653
+ return segments.join("/");
2654
+ }
2655
+ /**
2656
+ * Scan the emitted JS files REACHABLE from the entry via import statements
2657
+ * for specifiers a worker cannot resolve. Vendor externals were rewritten to
2658
+ * ../__vendor__/ relative paths, so anything bare that survives in the graph
2659
+ * is a real defect.
2660
+ *
2661
+ * Deliberately a graph walk, not a directory walk: the bundled reactor code
2662
+ * carries `new URL(..., import.meta.url)` references to its node
2663
+ * worker-thread entries (executor/projection workers), which Vite emits as
2664
+ * stray assets full of node-only imports. They are unreachable dead weight in
2665
+ * a browser bundle — the production vendor output tolerates the same files —
2666
+ * and must not fail the build.
2667
+ */
2668
+ function findBundleSpecifierOffenders(bundleDir, entry = REACTOR_WORKER_ENTRY) {
2669
+ const offenders = [];
2670
+ walkBundleGraph(bundleDir, entry, (file, code) => {
2671
+ const specs = findDisallowedSpecifiers(code);
2672
+ if (specs.length > 0) offenders.push({
2673
+ file,
2674
+ specs
2675
+ });
2676
+ return true;
2677
+ });
2678
+ return offenders;
2679
+ }
2680
+ function walkBundleGraph(bundleDir, entry, visit) {
2681
+ const seen = /* @__PURE__ */ new Set();
2682
+ const queue = [entry];
2683
+ while (queue.length > 0) {
2684
+ const rel = queue.shift();
2685
+ if (seen.has(rel)) continue;
2686
+ seen.add(rel);
2687
+ const full = join(bundleDir, rel);
2688
+ if (!existsSync(full) || statSync(full).isDirectory()) continue;
2689
+ if (!rel.endsWith(".js") && !rel.endsWith(".mjs")) continue;
2690
+ const code = readFileSync(full, "utf8");
2691
+ if (!visit(rel, code)) return false;
2692
+ for (const spec of findRelativeSpecifiers(code)) {
2693
+ const next = normalizeBundlePath(rel, spec);
2694
+ if (next) queue.push(next);
2695
+ }
474
2696
  }
2697
+ return true;
2698
+ }
2699
+ function assertWorkerResolvable(bundleDir) {
2700
+ const offenders = findBundleSpecifierOffenders(bundleDir);
2701
+ 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"));
2702
+ }
2703
+ const WORKER_UNSAFE_MARKERS = ["__PH_DYNAMIC_BASE__", "vite:preloadError"];
2704
+ /** The page-only markers present in `code`, in a fixed order. */
2705
+ function findWorkerUnsafeMarkers(code) {
2706
+ return WORKER_UNSAFE_MARKERS.filter((marker) => code.includes(marker));
475
2707
  }
476
2708
  /**
477
- * Spawn a throwaway worker that generates one entry per specifier (CJS deps get
478
- * explicit named re-exports, ESM deps `export *`), `vite build`s them into the
479
- * given out dir, and writes the import map. Captures stdout/stderr so a failure
480
- * is debuggable; the normal path stays quiet.
2709
+ * The subset of the vendor's entries a worker may import.
2710
+ *
2711
+ * The vendor build keeps the React family external: its chunks carry bare
2712
+ * `import "react"` statements that the PAGE resolves through its import map.
2713
+ * A worker resolves no import map, so externalizing a vendor spec whose chunk
2714
+ * closure reaches such an import would kill the worker on its first load —
2715
+ * and the chunk graph is shared across vendor entries, so even a React-free
2716
+ * module (e.g. an rpc subpath) can be entangled with React through a shared
2717
+ * chunk. The vendor is also built for the page: a dynamic-base build rewrites
2718
+ * its asset URLs onto a global only the page sets, and its dynamic imports go
2719
+ * through Vite's preload helper, which needs `document`. Each entry's own
2720
+ * closure inside the vendor dir decides: clean closure, worker-safe; anything
2721
+ * bare or page-only in it (see {@link findWorkerUnsafeMarkers}), or a missing
2722
+ * entry file, bundled into the worker instead.
2723
+ */
2724
+ function workerSafeVendorImports(vendorDir, vendorImports) {
2725
+ const safe = {};
2726
+ for (const [spec, url] of Object.entries(vendorImports)) {
2727
+ const entryFile = url.slice(url.lastIndexOf("/") + 1);
2728
+ if (!existsSync(join(vendorDir, entryFile))) continue;
2729
+ if (walkBundleGraph(vendorDir, entryFile, (_file, code) => {
2730
+ try {
2731
+ return findDisallowedSpecifiers(code).length === 0 && findWorkerUnsafeMarkers(code).length === 0;
2732
+ } catch {
2733
+ return false;
2734
+ }
2735
+ })) safe[spec] = url;
2736
+ }
2737
+ return safe;
2738
+ }
2739
+ /**
2740
+ * Builds arbitrary worker-loadable entries with the worker build config.
2741
+ * Exported for the local-package bundles, which need the same self-contained
2742
+ * output and vendor externalization at a different depth.
481
2743
  */
482
- function runBuildWorker(dirname, outDir, include, external) {
2744
+ function runWorkerBuildEntries(dirname, outDir, entries, vendorImports, nodeEnv, vendorPrefix = "../__vendor__/") {
2745
+ return runWorkerBuild(dirname, outDir, entries, vendorImports, nodeEnv, vendorPrefix);
2746
+ }
2747
+ function runWorkerBuild(dirname, outDir, entries, vendorImports, nodeEnv, vendorPrefix = "../__vendor__/") {
483
2748
  const workerPath = join(outDir, "build-worker.mjs");
484
- writeFileSync(workerPath, VENDOR_BUILD_WORKER);
485
- const selfModulePath = fileURLToPath(import.meta.url);
2749
+ writeFileSync(workerPath, WORKER_BUILD_WORKER);
486
2750
  return new Promise((resolve) => {
487
2751
  const child = spawn(process.execPath, [
488
2752
  workerPath,
489
2753
  dirname,
490
2754
  outDir,
491
- JSON.stringify(include),
492
- VENDOR_URL_PREFIX,
493
- JSON.stringify(external),
494
- VENDOR_DYNAMIC_BASE,
495
- selfModulePath
2755
+ JSON.stringify(entries),
2756
+ JSON.stringify(vendorImports),
2757
+ nodeEnv,
2758
+ resolveBuilderVite() ?? "",
2759
+ vendorPrefix
496
2760
  ], {
497
2761
  cwd: dirname,
498
2762
  stdio: [
@@ -508,10 +2772,13 @@ function runBuildWorker(dirname, outDir, include, external) {
508
2772
  child.stderr.on("data", (d) => {
509
2773
  stderr += String(d);
510
2774
  });
511
- child.on("exit", (code) => resolve({
512
- ok: code === 0,
513
- stderr
514
- }));
2775
+ child.on("exit", (code) => {
2776
+ rmSync(workerPath, { force: true });
2777
+ resolve({
2778
+ ok: code === 0,
2779
+ stderr
2780
+ });
2781
+ });
515
2782
  child.on("error", (e) => resolve({
516
2783
  ok: false,
517
2784
  stderr: String(e)
@@ -519,73 +2786,52 @@ function runBuildWorker(dirname, outDir, include, external) {
519
2786
  });
520
2787
  }
521
2788
  /**
522
- * The vendor build worker, written to disk and run as a subprocess. Loads
523
- * `vite` from the project and `connectDynamicBasePlugin` from builder-tools' own
524
- * built bundle (selfModulePath). argv: dirname, vendorDir, includeJSON,
525
- * urlPrefix, externalJSON, dynamicBase, selfModulePath.
2789
+ * The vite installed next to this module. The subprocess must run the vite
2790
+ * this build config was written against: a consumer project can pin an older
2791
+ * vite/rolldown (overrides) whose bundler leaves unresolvable specifiers bare
2792
+ * instead of erroring and shims node builtins differently — the output guard
2793
+ * then correctly rejects the bundle. builder-tools declares vite as a direct
2794
+ * dependency, so this resolution works wherever builder-tools is installed.
526
2795
  */
527
- const VENDOR_BUILD_WORKER = `
2796
+ function resolveBuilderVite() {
2797
+ try {
2798
+ return createRequire(import.meta.url).resolve("vite");
2799
+ } catch {
2800
+ return null;
2801
+ }
2802
+ }
2803
+ /**
2804
+ * The build subprocess (same pattern as the vendor's). Loads builder-tools'
2805
+ * own vite (argv; project fallback) and builds the given entries with
2806
+ * relative base, so chunk/asset URLs resolve against each script's own URL
2807
+ * under any deploy base. argv: dirname, outDir, entriesJSON (name ->
2808
+ * absolute entry path), vendorImportsJSON, nodeEnv, vitePath, vendorPrefix
2809
+ * (relative path from the out dir to __vendor__/, e.g. "../__vendor__/").
2810
+ */
2811
+ const WORKER_BUILD_WORKER = `
528
2812
  import { createRequire } from 'node:module';
529
- import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
530
- import { join, isAbsolute } from 'node:path';
2813
+ import { isAbsolute } from 'node:path';
531
2814
  import { fileURLToPath, pathToFileURL } from 'node:url';
532
- const [dirname, vendorDir, includeJSON, urlPrefix, externalJSON, dynamicBase, selfModulePath] = process.argv.slice(2);
533
- const include = JSON.parse(includeJSON);
534
- const external = JSON.parse(externalJSON ?? '[]');
535
- const externalSet = new Set(external);
536
- const reqProj = createRequire(join(dirname, 'noop.js'));
537
- // pathToFileURL: require.resolve returns an absolute path, and on Windows
538
- // import('D:\\...') parses "D:" as a URL scheme (ERR_UNSUPPORTED_ESM_URL_SCHEME).
539
- const { build, esmExternalRequirePlugin } = await import(pathToFileURL(reqProj.resolve('vite')).href);
540
- // Load the dynamic-base plugin from builder-tools' own built bundle (passed as
541
- // an absolute path) — it isn't resolvable as a bare specifier from the worker.
542
- const { connectDynamicBasePlugin, DYNAMIC_BASE_PLACEHOLDER } = await import(pathToFileURL(selfModulePath));
543
- const srcDir = join(vendorDir, '.entries');
544
- mkdirSync(srcDir, { recursive: true });
545
- const entryName = (spec) => spec.replace(/[^\\w]+/g, '_');
546
- const RESERVED = new Set('enum void null function in instanceof typeof new delete do if else return switch case break continue for while this true false class const let var default export import extends super with yield debugger finally throw try catch await implements interface package private protected public static eval arguments'.split(' '));
547
- const input = {};
548
- for (const spec of include) {
549
- const name = entryName(spec);
550
- let src;
551
- try {
552
- // Import the bare spec (not reqProj.resolve(spec)) so Node picks the same
553
- // import/browser-condition module the build resolves — resolving first can
554
- // pick a CJS sibling whose default-export shape differs from the ESM build.
555
- const ns = await import(spec);
556
- // Only fall back to re-exporting from default when the module exposes NO
557
- // top-level named exports (a true CJS-interop module). If it does (e.g. zod
558
- // exposes \`z\`), \`export *\` captures them; destructuring default would miss
559
- // top-level names that aren't keys of the default object.
560
- const named = Object.keys(ns).filter((k) => k !== 'default');
561
- const cjs = named.length === 0 && ns.default && typeof ns.default === 'object';
562
- if (cjs) {
563
- const names = Object.keys(ns.default).filter((k) => k !== 'default' && k !== '__esModule' && /^[A-Za-z_$][\\w$]*$/.test(k));
564
- const plain = names.filter((n) => !RESERVED.has(n));
565
- const reserved = names.filter((n) => RESERVED.has(n));
566
- src = 'import d from ' + JSON.stringify(spec) + ';\\nexport default d;\\n'
567
- + (plain.length ? 'export const { ' + plain.join(', ') + ' } = d;\\n' : '');
568
- // reserved words are invalid as const-binding names but valid as export
569
- // aliases (export { x as enum }).
570
- reserved.forEach((n, i) => {
571
- src += 'const __r' + i + ' = d[' + JSON.stringify(n) + '];\\nexport { __r' + i + ' as ' + n + ' };\\n';
572
- });
573
- } else {
574
- src = 'export * from ' + JSON.stringify(spec) + ';\\n'
575
- + (('default' in ns) ? 'export { default } from ' + JSON.stringify(spec) + ';\\n' : '');
576
- }
577
- } catch {
578
- src = 'export * from ' + JSON.stringify(spec) + ';\\n';
579
- }
580
- const file = join(srcDir, name + '.js');
581
- writeFileSync(file, src);
582
- input[name] = file;
583
- }
584
- // Prefer the bundler's browser-condition-aware resolution; fall back to resolving
585
- // from the worker (real install path) only for Rolldown's realpath-anchoring bug.
2815
+ const [dirname, outDir, entriesJSON, vendorImportsJSON, nodeEnvArg, vitePathArg, vendorPrefixArg] = process.argv.slice(2);
2816
+ const nodeEnv = nodeEnvArg ?? 'development';
2817
+ const entries = JSON.parse(entriesJSON);
2818
+ const vendorImports = JSON.parse(vendorImportsJSON ?? '{}');
2819
+ const vendorPrefix = vendorPrefixArg || '../__vendor__/';
2820
+ const externalSet = new Set(Object.keys(vendorImports));
2821
+ const vendorPath = (spec) => {
2822
+ const url = vendorImports[spec];
2823
+ return vendorPrefix + url.slice(url.lastIndexOf('/') + 1);
2824
+ };
2825
+ const reqProj = createRequire(dirname + '/noop.js');
2826
+ // pathToFileURL: on Windows import('D:\\\\...') parses "D:" as a URL scheme.
2827
+ const vitePath = vitePathArg || reqProj.resolve('vite');
2828
+ const { build } = await import(pathToFileURL(vitePath).href);
2829
+ // Resolve bare specifiers from the project (same plugin as the vendor build):
2830
+ // prefer the bundler's browser-condition-aware resolution, fall back to the
2831
+ // worker's own resolution for Rolldown's realpath-anchoring bug.
586
2832
  const phResolveCache = new Map();
587
- const phVendorResolve = {
588
- name: 'ph-vendor-resolve', enforce: 'pre',
2833
+ const phWorkerResolve = {
2834
+ name: 'ph-reactor-worker-resolve', enforce: 'pre',
589
2835
  async resolveId(source, importer, options) {
590
2836
  if (externalSet.has(source)) return null;
591
2837
  if (source[0] === '\\0' || source[0] === '.' || isAbsolute(source)) return null;
@@ -600,217 +2846,195 @@ const phVendorResolve = {
600
2846
  return resolved;
601
2847
  },
602
2848
  };
2849
+ // A worker has no window: on a failed dynamic import, the preload helper's
2850
+ // window.dispatchEvent would throw a ReferenceError in place of the real error.
2851
+ const PRELOAD_HELPER_ID = '\\0vite/preload-helper.js';
2852
+ const PRELOAD_DISPATCH = 'window.dispatchEvent(';
2853
+ const phWorkerPreloadHelper = {
2854
+ name: 'ph-reactor-worker-preload-helper',
2855
+ transform(code, id) {
2856
+ if (id !== PRELOAD_HELPER_ID) return null;
2857
+ if (code.split(PRELOAD_DISPATCH).length !== 2) {
2858
+ this.error('expected exactly one ' + PRELOAD_DISPATCH + ' in ' + PRELOAD_HELPER_ID);
2859
+ }
2860
+ return { code: code.replace(PRELOAD_DISPATCH, 'globalThis.dispatchEvent?.('), map: null };
2861
+ },
2862
+ };
603
2863
  await build({
604
2864
  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,
2865
+ // The project's public/ dir belongs to the app build, not this bundle.
2866
+ publicDir: false,
2867
+ // Relative base: emitted chunk/asset URLs resolve against the worker
2868
+ // script's own URL, so the bundle works under any deploy base.
2869
+ base: './',
608
2870
  define: {
609
- 'process.env.NODE_ENV': '"development"',
610
- // BASE_URL resolves to the deploy base (not the vendor prefix) so vendored
611
- // Connect's router basename + BASE_URL-relative fetches use the right path.
612
- 'import.meta.env.BASE_URL': JSON.stringify(DYNAMIC_BASE_PLACEHOLDER),
2871
+ 'process.env.NODE_ENV': JSON.stringify(nodeEnv),
2872
+ 'import.meta.env.BASE_URL': JSON.stringify('./'),
613
2873
  },
614
- // phVendorResolve (pre) resolves bares from the worker; esmExternalRequirePlugin owns
615
- // react/virtual externalization; connectDynamicBasePlugin (post) rewrites the placeholder base.
616
- plugins: [phVendorResolve, esmExternalRequirePlugin({ external }), connectDynamicBasePlugin()],
617
- // pglite ships web workers as ES-module chunks. workerStripPrefix is the vendor
618
- // segment so the worker recovers the deploy base, not the vendor prefix.
619
- worker: { format: 'es', plugins: () => [connectDynamicBasePlugin({ forWorker: true, workerStripPrefix: urlPrefix.replace(/^\\/+/, '') })] },
2874
+ plugins: [phWorkerResolve, phWorkerPreloadHelper],
2875
+ // pglite ships nested web workers as ES-module chunks.
2876
+ worker: { format: 'es' },
620
2877
  build: {
621
- outDir: vendorDir, emptyOutDir: false, minify: false, target: 'esnext', cssCodeSplit: true,
2878
+ // Always minified, dev included: the bundle is browser-served output
2879
+ // (sourcemaps carry the debugging story), and minification strips the
2880
+ // JSDoc comments whose embedded code samples (kysely's, viem's) would
2881
+ // otherwise trip the bare-specifier guard below.
2882
+ outDir, emptyOutDir: false, minify: true, target: 'esnext', sourcemap: true,
2883
+ // No document in a worker: the module-preload polyfill and preload helper
2884
+ // touch the DOM, so dynamic imports must stay plain import().
2885
+ modulePreload: false,
622
2886
  rollupOptions: {
623
- input, preserveEntrySignatures: 'strict',
624
- output: { format: 'es', entryFileNames: '[name].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },
2887
+ input: entries,
2888
+ // A models entry is pure re-exports; without this the bundler treats
2889
+ // its exports as unused and tree-shakes the whole file to nothing.
2890
+ // Harmless for the worker entry, which exports nothing to preserve.
2891
+ preserveEntrySignatures: 'strict',
2892
+ external: (id) => externalSet.has(id),
2893
+ output: {
2894
+ format: 'es', entryFileNames: '[name].js',
2895
+ // Chunks live at the bundle root, not a chunks/ subdir: the vendor
2896
+ // paths below are emitted VERBATIM into every chunk, so all modules
2897
+ // must sit at the same depth for ../__vendor__/ to resolve.
2898
+ chunkFileNames: '[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]',
2899
+ paths: (id) => (externalSet.has(id) ? vendorPath(id) : id),
2900
+ },
625
2901
  },
626
2902
  },
627
2903
  });
628
- rmSync(srcDir, { recursive: true, force: true });
629
- const imports = {};
630
- for (const spec of include) imports[spec] = urlPrefix + entryName(spec) + '.js';
631
- writeFileSync(join(vendorDir, 'import-map.json'), JSON.stringify({ include, external, imports }, null, 2));
632
2904
  `;
2905
+ const WORKER_BUILD_WORKER_HASH = createHash("sha256").update(WORKER_BUILD_WORKER).digest("hex").slice(0, 16);
633
2906
  //#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");
639
- }
640
- function resolvePackage(packageName, root = process.cwd()) {
641
- return createRequire(root).resolve(packageName, { paths: [root] });
642
- }
643
- function resolveConnectPackageJson(root = process.cwd()) {
644
- 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);
650
- return null;
651
- }
652
- }
653
- /**
654
- * Finds the dist dir of Connect on the local machine
655
- */
656
- function resolveConnectBundle(root = process.cwd()) {
657
- const connectIndexPath = resolvePackage("@powerhousedao/connect", root);
658
- return join(connectIndexPath.substring(0, connectIndexPath.indexOf("connect") + 7), "dist/");
659
- }
660
- function resolveConnectPublicDir(root = process.cwd()) {
661
- const connectIconPath = resolvePackage("@powerhousedao/connect/public/icon.ico", root);
662
- return path.join(connectIconPath, "../");
663
- }
664
- /**
665
- * Copies the Connect dist dir to the target path
666
- */
667
- function copyConnect(sourcePath, targetPath) {
668
- try {
669
- fs.rmSync(targetPath, {
670
- recursive: true,
671
- force: true
672
- });
673
- fs.cpSync(sourcePath, targetPath, { recursive: true });
674
- } catch (error) {
675
- console.error(`❌ Error copying ${sourcePath} to ${targetPath}:`, error);
676
- }
677
- }
678
- /**
679
- * Backs up the index.html file
680
- *
681
- * Needed when running the Connect Studio dev server on Windows
682
- */
683
- function backupIndexHtml(appPath, restore = false) {
684
- const filePath = join(appPath, "index.html");
685
- const backupPath = join(appPath, "index.html.bak");
686
- const paths = restore ? [backupPath, filePath] : [filePath, backupPath];
687
- if (fs.existsSync(paths[0])) fs.copyFileSync(paths[0], paths[1]);
688
- }
689
- function removeBase64EnvValues(appPath) {
690
- backupIndexHtml(appPath);
691
- const filePath = join(appPath, "index.html");
692
- fs.readFile(filePath, "utf-8", (err, data) => {
693
- if (err) {
694
- console.error("Error reading file:", err);
695
- return;
696
- }
697
- const modifiedData = data.replace(/"LOCAL_DOCUMENT_MODELS":\s*".*?",/, `"LOCAL_DOCUMENT_MODELS": "",`).replace(/"LOCAL_DOCUMENT_EDITORS":\s*".*?"/, `"LOCAL_DOCUMENT_EDITORS": ""`);
698
- console.log("Modified data:", modifiedData);
699
- fs.writeFile(filePath, modifiedData, "utf-8", (err) => {
700
- if (err) {
701
- console.error("Error writing file:", err);
702
- return;
703
- }
704
- });
705
- });
706
- }
707
- function readJsonFile(filePath) {
708
- 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;
715
- }
716
- }
717
- /**
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.
719
- */
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
- }
748
- }
749
- const exportStatement = `export default [${exports.length ? `
750
- ${exports.join(",\n")}
751
- ` : ""}];`;
752
- return `${imports.join("\n")}\n\n${exportStatement}`;
753
- }
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);
760
- }
761
- }
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
- }
2907
+ //#region connect-utils/worker-packages-build.ts
778
2908
  /**
779
- * Shared helper to modify the <head> tag of an HTML file by transforming its contents.
2909
+ * Prebuild a project's local packages into worker-loadable model bundles.
2910
+ *
2911
+ * The reactor worker gets document models from the registry CDN or from what
2912
+ * Connect statically bundled. A project's own (`provider: "local"`) package is
2913
+ * in neither, so its document types have no reducer in the worker and their
2914
+ * load jobs fail. Dev solves this by pointing the worker at the dev server's
2915
+ * transformed models entry; a production deployment has no dev server, so the
2916
+ * entry is prebuilt here, next to the worker bundle it is loaded beside.
2917
+ *
2918
+ * Each package's `browser/document-models/index.js` (reducers only: no React,
2919
+ * no CSS, no editors) is built self-contained, with the worker-safe subset of
2920
+ * the vendor externalized onto `../../__vendor__/` - two levels up, since
2921
+ * these land in `__reactor_worker__/packages/`. A `manifest.json` names what
2922
+ * was built so the tab can turn it into package sources without guessing.
780
2923
  */
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");
2924
+ /** Served under `<base>__reactor_worker__/packages/`. */
2925
+ const WORKER_PACKAGES_MANIFEST = "manifest.json";
2926
+ /** Vendor is two levels up from `__reactor_worker__/packages/`. */
2927
+ const VENDOR_PREFIX = "../../__vendor__/";
2928
+ function readVersion(root) {
2929
+ try {
2930
+ const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
2931
+ return typeof meta.version === "string" ? meta.version : void 0;
2932
+ } catch {
2933
+ return;
2934
+ }
786
2935
  }
787
2936
  /**
788
- * Appends the contents to the <head> tag of the index.html file
2937
+ * A package root's models entry, or null when it ships none.
2938
+ *
2939
+ * Two roots are possible and both are normal: an installed dependency under
2940
+ * `node_modules/<name>`, and the project itself - the vetra case, where the
2941
+ * project *is* the local package and has no self-link in node_modules.
789
2942
  */
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
- });
2943
+ function resolvePackageModels(dirname, name) {
2944
+ const roots = [];
2945
+ try {
2946
+ roots.push(realpathSync(join(dirname, "node_modules", name)));
2947
+ } catch {}
2948
+ if (readProjectName(dirname) === name) roots.push(dirname);
2949
+ for (const root of roots) {
2950
+ const entryPath = join(root, "dist", "browser", "document-models", "index.js");
2951
+ if (existsSync(entryPath)) return {
2952
+ entryPath,
2953
+ version: readVersion(root)
2954
+ };
2955
+ }
2956
+ return null;
2957
+ }
2958
+ function readProjectName(dirname) {
2959
+ try {
2960
+ const meta = JSON.parse(readFileSync(join(dirname, "package.json"), "utf8"));
2961
+ return typeof meta.name === "string" ? meta.name : void 0;
2962
+ } catch {
2963
+ return;
2964
+ }
795
2965
  }
796
2966
  /**
797
- * Prepends the contents to the <head> tag of the index.html file
2967
+ * The project's own package name when it ships a models bundle, so a caller
2968
+ * can include it beside the configured `provider: "local"` packages. A vetra
2969
+ * project declares no package entry for itself, yet its models are exactly
2970
+ * the ones the worker is missing.
798
2971
  */
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" });
2972
+ function ownProjectPackage(dirname) {
2973
+ const name = readProjectName(dirname);
2974
+ if (!name) return void 0;
2975
+ return resolvePackageModels(dirname, name) ? name : void 0;
807
2976
  }
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;
2977
+ /**
2978
+ * Build each local package's models entry into `outDir` and write the
2979
+ * manifest the tab reads. Returns the manifest entries (empty when no local
2980
+ * package ships a models bundle), or null when the build itself failed -
2981
+ * `errorRef` then carries the cause. Both of those remove `outDir`, so a
2982
+ * previous build's bundles never outlive the packages they came from.
2983
+ */
2984
+ async function prebuildWorkerPackages(options) {
2985
+ const nodeEnv = options.nodeEnv ?? "production";
2986
+ const resolved = [];
2987
+ for (const name of options.packages) {
2988
+ const models = resolvePackageModels(options.dirname, name);
2989
+ if (!models) continue;
2990
+ resolved.push({
2991
+ entry: {
2992
+ name,
2993
+ version: models.version,
2994
+ file: workerPackageFileName(name)
2995
+ },
2996
+ entryPath: models.entryPath
2997
+ });
2998
+ }
2999
+ if (resolved.length === 0) {
3000
+ rmSync(options.outDir, {
3001
+ recursive: true,
3002
+ force: true
3003
+ });
3004
+ return [];
3005
+ }
3006
+ const vendorImports = options.safeVendorImports ?? (options.vendor ? workerSafeVendorImports(options.vendor.dir, options.vendor.imports) : {});
3007
+ const entries = Object.fromEntries(resolved.map((item) => [item.entry.file.replace(/\.js$/, ""), item.entryPath]));
3008
+ const parent = dirname(options.outDir);
3009
+ mkdirSync(parent, { recursive: true });
3010
+ const tmpDir = mkdtempSync(join(parent, ".ph-worker-packages.tmp-"));
3011
+ try {
3012
+ const { ok, stderr } = await runWorkerBuildEntries(options.dirname, tmpDir, entries, vendorImports, nodeEnv, VENDOR_PREFIX);
3013
+ const missing = resolved.filter((item) => !existsSync(join(tmpDir, item.entry.file)));
3014
+ if (!ok || missing.length > 0) {
3015
+ const detail = stderr.trim();
3016
+ throw new Error(`worker package bundles failed to build${missing.length > 0 ? ` (missing: ${missing.map((m) => m.entry.name).join(", ")})` : ""}${detail ? `:\n${detail}` : ""}`);
3017
+ }
3018
+ for (const item of resolved) {
3019
+ const offenders = findBundleSpecifierOffenders(tmpDir, item.entry.file);
3020
+ 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"));
3021
+ }
3022
+ const manifest = resolved.map((item) => item.entry);
3023
+ writeFileSync(join(tmpDir, WORKER_PACKAGES_MANIFEST), JSON.stringify(manifest, null, 2));
3024
+ publishDirAtomic(tmpDir, options.outDir);
3025
+ return manifest;
3026
+ } catch (err) {
3027
+ rmSync(tmpDir, {
3028
+ recursive: true,
3029
+ force: true
3030
+ });
3031
+ rmSync(options.outDir, {
3032
+ recursive: true,
3033
+ force: true
3034
+ });
3035
+ if (options.errorRef) options.errorRef.message = err instanceof Error ? err.message : String(err);
3036
+ return null;
3037
+ }
814
3038
  }
815
3039
  //#endregion
816
3040
  //#region connect-utils/runtime-config-schema.ts
@@ -861,6 +3085,31 @@ const runtimeConfigSchema = {
861
3085
  connect: phConnectRuntimeConfigSchema
862
3086
  }
863
3087
  };
3088
+ //#endregion
3089
+ //#region connect-utils/dev-deps.ts
3090
+ /** The outermost node_modules in a package's real path; null outside one. */
3091
+ function dependencyStoreOf(realPath) {
3092
+ const parts = realPath.split(sep);
3093
+ const at = parts.indexOf("node_modules");
3094
+ return at > 0 ? parts.slice(0, at + 1).join(sep) : null;
3095
+ }
3096
+ /** Pre-bundled deps for Connect's dev server, scanning the project's routes. */
3097
+ function connectOptimizeDeps(projectRoot, routesDir, routeFileDeps) {
3098
+ const routes = routesDir && relative(projectRoot, routesDir).replaceAll("\\", "/");
3099
+ return {
3100
+ ...routes ? { entries: ["index.html", `${routes}/**/*.{js,jsx,ts,tsx}`] } : {},
3101
+ include: [
3102
+ "document-model",
3103
+ "zod",
3104
+ "@powerhousedao/design-system/connect",
3105
+ "@powerhousedao/reactor-browser",
3106
+ "@powerhousedao/document-engineering",
3107
+ ...routeFileDeps
3108
+ ],
3109
+ exclude: ["@electric-sql/pglite", "@electric-sql/pglite-tools"],
3110
+ rolldownOptions: { external: [ROUTE_TREE_SPECIFIER, CORE_ROUTE_TREE_SPECIFIER] }
3111
+ };
3112
+ }
864
3113
  const RESOLVED_VIRTUAL_ID = "\0virtual:ph-bundled-packages-virtual";
865
3114
  const BUNDLED_PACKAGES_DEV_URL = "@id/" + RESOLVED_VIRTUAL_ID.replace("\0", "__x00__");
866
3115
  function readBundledPackageVersion(projectRoot, name) {
@@ -872,6 +3121,10 @@ function readBundledPackageVersion(projectRoot, name) {
872
3121
  return;
873
3122
  }
874
3123
  }
3124
+ function offeredRoutesFile(projectRoot, name) {
3125
+ const file = path.join(projectRoot, "node_modules", name, "dist/browser/connect-routes.js");
3126
+ return fs.existsSync(file) ? file : void 0;
3127
+ }
875
3128
  function makeRegisterModule(packages, projectRoot) {
876
3129
  if (packages.length === 0) return "export default () => {};\n";
877
3130
  const imports = [];
@@ -881,7 +3134,9 @@ function makeRegisterModule(packages, projectRoot) {
881
3134
  const version = readBundledPackageVersion(projectRoot, name);
882
3135
  imports.push(`import * as ${moduleName} from ${JSON.stringify(name)};`);
883
3136
  imports.push(`import ${JSON.stringify(`${name}/style.css`)};`);
884
- calls.push(` pm.addLocalPackage(${JSON.stringify(name)}, ${moduleName}, ${JSON.stringify(version)});`);
3137
+ const routesFile = offeredRoutesFile(projectRoot, name);
3138
+ const routes = routesFile ? `, () => import(${JSON.stringify(routesFile)})` : "";
3139
+ calls.push(` pm.addLocalPackage(${JSON.stringify(name)}, ${moduleName}, ${JSON.stringify(version)}${routes});`);
885
3140
  });
886
3141
  return `${imports.join("\n")}\n\nexport default function register(pm) {\n${calls.join("\n")}\n};\n`;
887
3142
  }
@@ -919,7 +3174,13 @@ const REACT_DEPS = [
919
3174
  "react-dom/client"
920
3175
  ];
921
3176
  const SHIM_PATH = "__ph/dev-react-shim/";
922
- const VITE_DEPS_PATH = "node_modules/.vite/deps";
3177
+ const SHARED_SHIM = "ph-shared:";
3178
+ const SHARED_DEPS = EXTERNALIZABLE_SHARED_SPECIFIERS.filter((spec) => !REACT_DEPS.includes(spec));
3179
+ /** The page's import map entries for the shared deps: each root and its subpaths. */
3180
+ function sharedDepImports(base) {
3181
+ const url = (spec) => withBase$1(base, `@id/__x00__${SHARED_SHIM}${spec}`);
3182
+ return Object.fromEntries(SHARED_DEPS.flatMap((spec) => [[spec, url(spec)], [`${spec}/`, `${url(spec)}/`]]));
3183
+ }
923
3184
  const VENDOR_MIME = {
924
3185
  ".css": "text/css",
925
3186
  ".map": "application/json",
@@ -939,7 +3200,21 @@ const VENDOR_MIME = {
939
3200
  const VENDOR_MODE = process.env.PH_CONNECT_EXTERNALIZE_VENDOR === "1";
940
3201
  const VENDOR_EXTRA = (process.env.PH_CONNECT_VENDOR_EXTRA ?? "").split(",").map((s) => s.trim()).filter(Boolean);
941
3202
  const HEAVY_LIBS = [...DEFAULT_VENDOR_INCLUDE, ...VENDOR_EXTRA];
942
- function withBase(base, p) {
3203
+ const heavyLibsFor = (routesDir) => routesDir ? HEAVY_LIBS.filter((lib) => lib !== "@powerhousedao/connect") : HEAVY_LIBS;
3204
+ /** The dev server's URL for a file: under the root, else through `/@fs/`. */
3205
+ function devUrlOf(root, file) {
3206
+ const relativePath = path.relative(root, file);
3207
+ return relativePath.startsWith("..") || path.isAbsolute(relativePath) ? `/@fs/${file.split(path.sep).join("/").replace(/^\/+/, "")}` : relativePath.split(path.sep).join("/");
3208
+ }
3209
+ /** A file of Connect's package, else the root: where Connect's own imports resolve from. */
3210
+ function connectImporter(root) {
3211
+ try {
3212
+ return createRequire(path.join(root, "package.json")).resolve("@powerhousedao/connect/package.json");
3213
+ } catch {
3214
+ return path.join(root, "index.html");
3215
+ }
3216
+ }
3217
+ function withBase$1(base, p) {
943
3218
  return `${base}${p}`.replace(/\/{2,}/g, "/");
944
3219
  }
945
3220
  function externalizePlugin(externals) {
@@ -974,15 +3249,17 @@ function externalizePlugin(externals) {
974
3249
  * the React shims above → one React instance across Connect, the vendor, and
975
3250
  * CDN editors.
976
3251
  */
977
- async function devReactImportmapPlugin(projectRoot = process.cwd()) {
3252
+ async function devReactImportmapPlugin(projectRoot = process.cwd(), routesDir = resolveConnectRoutesDir(projectRoot)) {
978
3253
  let namedExports = /* @__PURE__ */ new Map();
979
3254
  let base = "/";
3255
+ let root = projectRoot;
980
3256
  let vendor = null;
3257
+ const heavyLibs = heavyLibsFor(routesDir);
981
3258
  if (VENDOR_MODE) {
982
3259
  const errorRef = {};
983
3260
  vendor = await prebuildConnectVendor({
984
3261
  dirname: projectRoot,
985
- include: HEAVY_LIBS,
3262
+ include: heavyLibs,
986
3263
  errorRef
987
3264
  });
988
3265
  if (!vendor) {
@@ -996,18 +3273,29 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
996
3273
  const main = {
997
3274
  name: "ph-dev-react-importmap",
998
3275
  apply: "serve",
3276
+ async resolveId(source, importer) {
3277
+ if (source.startsWith(SHARED_SHIM)) return `\0${source}`;
3278
+ if (source.startsWith(`\0${SHARED_SHIM}`)) return source;
3279
+ if (importer?.startsWith(`\0${SHARED_SHIM}`)) return this.resolve(source, connectImporter(root), { skipSelf: true });
3280
+ },
3281
+ load(id) {
3282
+ if (!id.startsWith(`\0${SHARED_SHIM}`)) return void 0;
3283
+ const spec = JSON.stringify(id.slice(11));
3284
+ return `export * from ${spec};\nimport * as M from ${spec};\nexport default M.default;\n`;
3285
+ },
999
3286
  config(cfg) {
1000
3287
  cfg.optimizeDeps ??= {};
1001
3288
  const include = new Set(cfg.optimizeDeps.include ?? []);
1002
3289
  REACT_DEPS.forEach((d) => include.add(d));
1003
3290
  if (vendorActive) {
1004
- HEAVY_LIBS.forEach((d) => include.delete(d));
1005
- cfg.optimizeDeps.exclude = [...new Set([...cfg.optimizeDeps.exclude ?? [], ...HEAVY_LIBS])];
3291
+ heavyLibs.forEach((d) => include.delete(d));
3292
+ cfg.optimizeDeps.exclude = [.../* @__PURE__ */ new Set([...cfg.optimizeDeps.exclude ?? [], ...heavyLibs])];
1006
3293
  }
1007
3294
  cfg.optimizeDeps.include = [...include];
1008
3295
  },
1009
3296
  configResolved(config) {
1010
3297
  base = config.base;
3298
+ root = config.root;
1011
3299
  },
1012
3300
  configureServer(server) {
1013
3301
  const requireFromRoot = createRequire(path.join(server.config.root, "package.json"));
@@ -1021,7 +3309,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1021
3309
  }));
1022
3310
  if (vendorActive) {
1023
3311
  const vendorDir = vendor.vendorDir;
1024
- const vendorPrefixes = [withBase(base, VENDOR_URL_PREFIX), VENDOR_URL_PREFIX];
3312
+ const vendorPrefixes = [withBase$1(base, VENDOR_URL_PREFIX), VENDOR_URL_PREFIX];
1025
3313
  server.middlewares.use((req, res, next) => {
1026
3314
  const url = (req.url ?? "").split("?")[0];
1027
3315
  const prefix = vendorPrefixes.find((p) => url.startsWith(p));
@@ -1043,7 +3331,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1043
3331
  });
1044
3332
  });
1045
3333
  }
1046
- const shimPrefixes = [withBase(base, SHIM_PATH), `/${SHIM_PATH}`];
3334
+ const shimPrefixes = [withBase$1(base, SHIM_PATH), `/${SHIM_PATH}`];
1047
3335
  server.middlewares.use((req, res, next) => {
1048
3336
  const prefix = shimPrefixes.find((p) => req.url?.startsWith(p));
1049
3337
  if (!prefix) return next();
@@ -1057,7 +3345,7 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1057
3345
  return;
1058
3346
  }
1059
3347
  const browserHash = info.browserHash ?? optimizer.metadata.browserHash;
1060
- const depUrl = `${withBase(base, VITE_DEPS_PATH)}/${path.basename(info.file)}?v=${browserHash}`;
3348
+ const depUrl = `${withBase$1(base, devUrlOf(root, info.file))}?v=${browserHash}`;
1061
3349
  const names = namedExports.get(id) ?? [];
1062
3350
  res.setHeader("Content-Type", "application/javascript");
1063
3351
  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 +3356,13 @@ async function devReactImportmapPlugin(projectRoot = process.cwd()) {
1068
3356
  handler(html, ctx) {
1069
3357
  const browserHash = ctx.server?.environments.client.depsOptimizer?.metadata.browserHash;
1070
3358
  if (!browserHash) return;
1071
- const shimPrefix = withBase(base, SHIM_PATH);
3359
+ const shimPrefix = withBase$1(base, SHIM_PATH);
1072
3360
  const imports = Object.fromEntries(REACT_DEPS.map((id) => [id, `${shimPrefix}${id}.js?v=${browserHash}`]));
3361
+ Object.assign(imports, sharedDepImports(base));
1073
3362
  let dynamicBaseScript = "";
1074
3363
  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);
3364
+ for (const [spec, url] of Object.entries(vendor.imports)) imports[spec] = withBase$1(base, url);
3365
+ if (vendor.imports["@powerhousedao/connect"]) imports["ph-bundled-packages-virtual"] = withBase$1(base, BUNDLED_PACKAGES_DEV_URL);
1077
3366
  dynamicBaseScript = `<script>globalThis.__PH_DYNAMIC_BASE__=${JSON.stringify(base)};<\/script>\n`;
1078
3367
  }
1079
3368
  return html.replace(/<script type="importmap">[\s\S]*?<\/script>/, `${dynamicBaseScript}<script type="importmap">${JSON.stringify({ imports }, null, 2)}<\/script>`);
@@ -1092,16 +3381,20 @@ const CONTENT_TYPE_BY_EXT = {
1092
3381
  /**
1093
3382
  * Vite plugin to serve the Connect favicon (icon.ico) from the connect package,
1094
3383
  * 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.
3384
+ * build --favicon`). An .svg or .png keeps its type as icon.svg or icon.png,
3385
+ * and index.html's `<link rel="icon">` is rewritten to it; browsers decode a
3386
+ * file named icon.ico as an ICO.
1097
3387
  */
1098
3388
  function connectFaviconPlugin(opts = {}) {
1099
3389
  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";
3390
+ const ext = customPath ? extname(customPath).toLowerCase() : ".ico";
3391
+ const customContentType = CONTENT_TYPE_BY_EXT[ext] ?? "image/x-icon";
3392
+ const fileName = ext === ".svg" || ext === ".png" ? `icon${ext}` : "icon.ico";
1101
3393
  return {
1102
3394
  name: "copy-connect-favicon",
1103
3395
  configureServer(server) {
1104
- const faviconRoute = `${server.config.base}icon.ico`.replace(/\/{2,}/g, "/");
3396
+ const base = server.config.base;
3397
+ const route = (name) => `${base}${name}`.replace(/\/{2,}/g, "/");
1105
3398
  const handler = (_req, res, next) => {
1106
3399
  if (customPath) {
1107
3400
  try {
@@ -1118,12 +3411,21 @@ function connectFaviconPlugin(opts = {}) {
1118
3411
  res.end(readFileSync(resolved.id));
1119
3412
  }).catch(() => next());
1120
3413
  };
1121
- const paths = new Set([faviconRoute, "/icon.ico"]);
3414
+ const paths = /* @__PURE__ */ new Set([
3415
+ route(fileName),
3416
+ `/${fileName}`,
3417
+ route("icon.ico"),
3418
+ "/icon.ico"
3419
+ ]);
1122
3420
  for (const path of paths) server.middlewares.use(path, handler);
1123
3421
  },
3422
+ transformIndexHtml(html) {
3423
+ if (fileName === "icon.ico") return html;
3424
+ return html.replace(/<link rel="icon" href="([^"]*)icon\.ico"\s*\/?>/, `<link rel="icon" type="${customContentType}" href="$1${fileName}" />`);
3425
+ },
1124
3426
  async generateBundle(_options, bundle) {
1125
3427
  try {
1126
- if ("icon.ico" in bundle) return;
3428
+ if (fileName in bundle) return;
1127
3429
  let source;
1128
3430
  if (customPath) source = readFileSync(customPath);
1129
3431
  else {
@@ -1133,7 +3435,7 @@ function connectFaviconPlugin(opts = {}) {
1133
3435
  if (!source) return;
1134
3436
  this.emitFile({
1135
3437
  type: "asset",
1136
- fileName: "icon.ico",
3438
+ fileName,
1137
3439
  source
1138
3440
  });
1139
3441
  } catch {}
@@ -1156,21 +3458,47 @@ function readProjectPackageInfo(projectRoot) {
1156
3458
  return null;
1157
3459
  }
1158
3460
  }
3461
+ /** `html` with its `<title>` text set to `appName`, when one is configured. */
3462
+ function withAppTitle(html, appName) {
3463
+ if (!appName) return html;
3464
+ const escaped = appName.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
3465
+ return html.replace(/<title>[^<]*<\/title>/, () => `<title>${escaped}</title>`);
3466
+ }
3467
+ /** `api.connect`: the connect config the app is served, for plugins that render
3468
+ * ahead of it; `api.favicon`: its `branding.favicon`, which it leaves out. */
1159
3469
  function phConfigPlugin(options) {
1160
3470
  const localPackage = readProjectPackageInfo(options.projectRoot ?? process.cwd());
1161
- const withDefaults = deepMerge(DEFAULT_CONNECT_CONFIG, options.connect ?? {});
3471
+ const sourceSettings = {
3472
+ connect: options.connect,
3473
+ workflows: options.workflows
3474
+ };
3475
+ const conflict = workflowsSettingConflict(sourceSettings);
3476
+ if (conflict) console.warn(`[powerhouse] ${conflict}`);
3477
+ const withDefaults = resolveSourceConnect(sourceSettings);
1162
3478
  const mergedConnect = options.cliConnectOverride ? deepMerge(withDefaults, options.cliConnectOverride) : withDefaults;
1163
- const runtimeConfig = buildRuntimeConfig({
3479
+ const { favicon, ...branding } = mergedConnect.branding ?? {};
3480
+ const source = {
1164
3481
  packages: options.packages,
1165
3482
  packageRegistryUrl: options.packageRegistryUrl,
1166
- connect: mergedConnect
1167
- }, localPackage);
3483
+ connect: options.branding ? {
3484
+ ...mergedConnect,
3485
+ branding: options.branding
3486
+ } : mergedConnect.branding ? {
3487
+ ...mergedConnect,
3488
+ branding
3489
+ } : mergedConnect
3490
+ };
3491
+ const runtimeConfig = buildRuntimeConfig(source, localPackage);
1168
3492
  const content = JSON.stringify({
1169
3493
  $schema: RUNTIME_CONFIG_SCHEMA_URL,
1170
3494
  ...runtimeConfig
1171
3495
  }, null, 2);
1172
3496
  return {
1173
3497
  name: "vite-plugin-ph-config",
3498
+ api: {
3499
+ connect: runtimeConfig.connect,
3500
+ favicon: favicon ?? void 0
3501
+ },
1174
3502
  configureServer(server) {
1175
3503
  server.middlewares.use((req, res, next) => {
1176
3504
  if (req.url?.endsWith("/powerhouse.config.json")) {
@@ -1191,6 +3519,9 @@ function phConfigPlugin(options) {
1191
3519
  });
1192
3520
  }
1193
3521
  },
3522
+ transformIndexHtml(html) {
3523
+ return withAppTitle(html, runtimeConfig.connect.branding?.appName ?? void 0);
3524
+ },
1194
3525
  generateBundle() {
1195
3526
  this.emitFile({
1196
3527
  type: "asset",
@@ -1217,11 +3548,13 @@ function toPwaContribution(manifest, fallbackLabel, onWarn) {
1217
3548
  if (!isPlainObject(manifest)) return null;
1218
3549
  const label = typeof manifest.name === "string" && manifest.name ? manifest.name : fallbackLabel;
1219
3550
  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;
3551
+ if (manifest.pwa !== void 0) {
3552
+ if (!isPlainObject(manifest.pwa)) onWarn(`PWA config: ${label} declares a non-object 'pwa' field in its manifest; ignored.`);
3553
+ else {
3554
+ const parsed = PwaConfigSchema.safeParse(manifest.pwa);
3555
+ if (!parsed.success) onWarn(`PWA config: ${label}'s pwa fragment is invalid; ignored. ${formatZodIssues(parsed.error)}`);
3556
+ else config = parsed.data;
3557
+ }
1225
3558
  }
1226
3559
  config = withInferredCategory(config, manifest.category);
1227
3560
  if (Object.keys(config).length === 0) return null;
@@ -1330,7 +3663,8 @@ function collectProjectPwaContribution(options) {
1330
3663
  }
1331
3664
  if (!isPlainObject(manifest)) return null;
1332
3665
  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);
3666
+ const config = manifest.pwa === void 0 ? {} : parsePwaConfigStrict(manifest.pwa, `pwa in ${manifestPath}`);
3667
+ const withCategory = withInferredCategory(config, manifest.category);
1334
3668
  if (Object.keys(withCategory).length === 0) return null;
1335
3669
  return {
1336
3670
  source: label,
@@ -1368,6 +3702,15 @@ const PWA_ICONS = [
1368
3702
  function connectPwaIconsPlugin() {
1369
3703
  return {
1370
3704
  name: "copy-connect-pwa-icons",
3705
+ configureServer(server) {
3706
+ for (const icon of PWA_ICONS) server.middlewares.use(`${server.config.base}${icon}`, (_req, res, next) => {
3707
+ server.pluginContainer.resolveId(`@powerhousedao/connect/assets/${icon}`).then((resolved) => {
3708
+ if (!resolved) return next();
3709
+ res.setHeader("Content-Type", "image/png");
3710
+ res.end(readFileSync(resolved.id));
3711
+ }).catch(() => next());
3712
+ });
3713
+ },
1371
3714
  async generateBundle(_options, bundle) {
1372
3715
  for (const icon of PWA_ICONS) try {
1373
3716
  if (icon in bundle) continue;
@@ -1461,6 +3804,28 @@ const BASE_MANIFEST = {
1461
3804
  launch_handler: { client_mode: "focus-existing" }
1462
3805
  };
1463
3806
  /**
3807
+ * The base manifest under the project's own name and icons (from
3808
+ * `connect.branding.appName` / `icons.app`), so an installed app is not
3809
+ * "Powerhouse Connect". Connect's description goes with its name; a project
3810
+ * that wants one sets `connect.pwa.manifest.description`, which — like the
3811
+ * rest of `connect.pwa` — is laid on top of this.
3812
+ */
3813
+ function brandManifest(base, brand) {
3814
+ if (!brand) return base;
3815
+ const manifest = { ...base };
3816
+ if (brand.name) {
3817
+ manifest.name = brand.name;
3818
+ manifest.short_name = brand.name;
3819
+ delete manifest.description;
3820
+ }
3821
+ if (brand.icons?.length) manifest.icons = brand.icons.map((icon) => ({
3822
+ src: icon.fileName,
3823
+ sizes: icon.sizes,
3824
+ type: icon.contentType
3825
+ }));
3826
+ return manifest;
3827
+ }
3828
+ /**
1464
3829
  * Connect's hardcoded precache config — the base layer for the `injectManifest`
1465
3830
  * precache. Overridable additively (extra globs) or by raising the size ceiling
1466
3831
  * via package/project `pwa` config. The rest of the old Workbox config
@@ -1471,14 +3836,23 @@ const BASE_MANIFEST = {
1471
3836
  * declarative runtimeCaching option.
1472
3837
  */
1473
3838
  const BASE_PRECACHE = {
1474
- maximumFileSizeToCacheInBytes: 16 * 1024 * 1024,
1475
- globPatterns: ["**/*.{js,css,html,wasm,data,ico,png,svg,webp,woff,woff2}"],
3839
+ maximumFileSizeToCacheInBytes: 16777216,
3840
+ globPatterns: ["**/*.{js,css,html,wasm,data,ico,png,svg,webp,woff,woff2}", "__reactor_worker__/**/*.json"],
1476
3841
  globIgnores: [
1477
3842
  "**/powerhouse.config.json",
1478
3843
  "**/*.map",
1479
- "index.html"
3844
+ "index.html",
3845
+ "**/*.gz"
1480
3846
  ]
1481
3847
  };
3848
+ /** The files under `dir` (a project's public/), by path relative to it. */
3849
+ function staticFilesIn(dir) {
3850
+ if (!existsSync(dir)) return [];
3851
+ return readdirSync(dir, {
3852
+ recursive: true,
3853
+ withFileTypes: true
3854
+ }).filter((entry) => entry.isFile()).map((entry) => join(entry.parentPath, entry.name).slice(dir.length + 1).replaceAll("\\", "/"));
3855
+ }
1482
3856
  const SW_FILENAME = "service-worker.ts";
1483
3857
  /**
1484
3858
  * Absolute directory holding the hand-written service-worker source. Resolved
@@ -1515,6 +3889,24 @@ function phSwConfigPlugin(data) {
1515
3889
  };
1516
3890
  }
1517
3891
  /**
3892
+ * Connect's `?ph-manifest-rev` link (pwa-manifest-link.ts) is the service
3893
+ * worker's to ignore. The dev server has none, and vite-plugin-pwa matches the
3894
+ * whole URL there, so without this the link would get index.html.
3895
+ */
3896
+ function devManifestRevisionPlugin() {
3897
+ return {
3898
+ name: "ph-connect-pwa-dev-manifest-revision",
3899
+ apply: "serve",
3900
+ configureServer(server) {
3901
+ const manifestUrl = `${server.config.base}manifest.webmanifest`;
3902
+ server.middlewares.use((req, _res, next) => {
3903
+ if (req.url?.startsWith(`${manifestUrl}?`)) req.url = manifestUrl;
3904
+ next();
3905
+ });
3906
+ }
3907
+ };
3908
+ }
3909
+ /**
1518
3910
  * Service-worker / PWA support for Connect, gated by `connect.app.offline`.
1519
3911
  *
1520
3912
  * When enabled (the default), Workbox `injectManifest` bundles Connect's
@@ -1534,7 +3926,7 @@ function phSwConfigPlugin(data) {
1534
3926
  * clears its caches on the browser's next service-worker update check.
1535
3927
  */
1536
3928
  function connectPwaPlugins(options) {
1537
- const { offlineEnabled, pwa } = options;
3929
+ const { offlineEnabled, pwa, brand, staticFiles = [] } = options;
1538
3930
  if (!offlineEnabled) return [VitePWA({
1539
3931
  selfDestroying: true,
1540
3932
  strategies: "generateSW",
@@ -1543,30 +3935,35 @@ function connectPwaPlugins(options) {
1543
3935
  devOptions: { enabled: false }
1544
3936
  })];
1545
3937
  const { manifest, precache } = applyPwaOverrides({
1546
- manifest: BASE_MANIFEST,
3938
+ manifest: brandManifest(BASE_MANIFEST, brand),
1547
3939
  precache: BASE_PRECACHE
1548
3940
  }, pwa ?? {});
1549
3941
  const swConfig = {
1550
3942
  EMBEDDED_BASE_MANIFEST: manifest,
1551
3943
  EXTRA_RUNTIME_CACHING: pwa?.runtimeCaching ?? [],
1552
- NAVIGATE_FALLBACK_DENYLIST_EXTRA: pwa?.navigateFallbackDenylist ?? []
3944
+ NAVIGATE_FALLBACK_DENYLIST_EXTRA: pwa?.navigateFallbackDenylist ?? [],
3945
+ STATIC_FILES: staticFiles
1553
3946
  };
1554
- return [connectPwaIconsPlugin(), VitePWA({
1555
- strategies: "injectManifest",
1556
- srcDir: resolveServiceWorkerDir(),
1557
- filename: SW_FILENAME,
1558
- registerType: "prompt",
1559
- injectRegister: null,
1560
- devOptions: { enabled: false },
1561
- includeManifestIcons: false,
1562
- manifest,
1563
- injectManifest: {
1564
- globPatterns: precache.globPatterns,
1565
- globIgnores: [...precache.globIgnores, "**/manifest.webmanifest"],
1566
- maximumFileSizeToCacheInBytes: precache.maximumFileSizeToCacheInBytes,
1567
- buildPlugins: { vite: [phSwConfigPlugin(swConfig)] }
1568
- }
1569
- })];
3947
+ return [
3948
+ connectPwaIconsPlugin(),
3949
+ devManifestRevisionPlugin(),
3950
+ VitePWA({
3951
+ strategies: "injectManifest",
3952
+ srcDir: resolveServiceWorkerDir(),
3953
+ filename: SW_FILENAME,
3954
+ registerType: "prompt",
3955
+ injectRegister: null,
3956
+ devOptions: { enabled: true },
3957
+ includeManifestIcons: false,
3958
+ manifest,
3959
+ injectManifest: {
3960
+ globPatterns: precache.globPatterns,
3961
+ globIgnores: [...precache.globIgnores, "**/manifest.webmanifest"],
3962
+ maximumFileSizeToCacheInBytes: precache.maximumFileSizeToCacheInBytes,
3963
+ buildPlugins: { vite: [phSwConfigPlugin(swConfig)] }
3964
+ }
3965
+ })
3966
+ ];
1570
3967
  }
1571
3968
  //#endregion
1572
3969
  //#region connect-utils/vite-plugins/react-self-host.ts
@@ -1613,17 +4010,40 @@ function resolveReactEntries(dirname$1) {
1613
4010
  }
1614
4011
  return out;
1615
4012
  }
4013
+ function reactImportMap(base, files) {
4014
+ const map = {};
4015
+ for (const [spec, file] of Object.entries(files)) {
4016
+ map[spec] = `${base}${REACT_URL_DIR}/${file}`;
4017
+ if (spec.includes("/")) map[`${spec}.js`] = map[spec];
4018
+ }
4019
+ return map;
4020
+ }
1616
4021
  function reactSelfHostPlugin(options) {
1617
4022
  const entries = resolveReactEntries(options.dirname);
1618
4023
  let absOutDir = resolve(options.dirname, "dist");
4024
+ let base = "/";
4025
+ let staging;
4026
+ let files = {};
1619
4027
  let importMap = {};
1620
4028
  return {
1621
4029
  name: "ph-react-self-host",
1622
4030
  apply: "build",
1623
4031
  configResolved(config) {
1624
4032
  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}/`;
4033
+ base = config.base;
4034
+ },
4035
+ async buildStart() {
4036
+ files = {};
4037
+ importMap = {};
4038
+ if (!Object.keys(entries).length) return;
4039
+ const stagingParent = join(options.dirname, "node_modules");
4040
+ staging = mkdtempSync(join(existsSync(stagingParent) ? stagingParent : options.dirname, ".ph-react-self-host-"));
4041
+ const { ok, stderr } = await runReactBuild(options.dirname, staging, entries, options.dev ? "development" : "production");
4042
+ if (!ok) this.error(`react self-host build failed${stderr.trim() ? `:\n${stderr.trim()}` : ""}`);
4043
+ const manifest = join(staging, FILES_MANIFEST);
4044
+ files = JSON.parse(readFileSync(manifest, "utf8"));
4045
+ rmSync(manifest, { force: true });
4046
+ importMap = reactImportMap(base, files);
1627
4047
  },
1628
4048
  transformIndexHtml() {
1629
4049
  if (!Object.keys(importMap).length) return;
@@ -1634,13 +4054,27 @@ function reactSelfHostPlugin(options) {
1634
4054
  injectTo: "head-prepend"
1635
4055
  }];
1636
4056
  },
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()}` : ""}`);
4057
+ closeBundle() {
4058
+ if (!staging) return;
4059
+ const dest = join(absOutDir, REACT_URL_DIR);
4060
+ rmSync(dest, {
4061
+ recursive: true,
4062
+ force: true
4063
+ });
4064
+ mkdirSync(absOutDir, { recursive: true });
4065
+ cpSync(staging, dest, { recursive: true });
4066
+ chmodSync(dest, 493);
4067
+ rmSync(staging, {
4068
+ recursive: true,
4069
+ force: true
4070
+ });
4071
+ staging = void 0;
4072
+ const missing = Object.entries(files).filter(([, file]) => !existsSync(join(dest, file)));
4073
+ 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
4074
  }
1642
4075
  };
1643
4076
  }
4077
+ const FILES_MANIFEST = "files.json";
1644
4078
  function runReactBuild(dirname, outDir, entries, nodeEnv) {
1645
4079
  mkdirSync(outDir, { recursive: true });
1646
4080
  const workerPath = join(outDir, "build-worker.mjs");
@@ -1715,7 +4149,7 @@ for (const [spec, file] of Object.entries(entries)) {
1715
4149
  input[spec] = entryFile;
1716
4150
  }
1717
4151
  try {
1718
- await build({
4152
+ const result = await build({
1719
4153
  root: dirname, configFile: false, logLevel: 'error',
1720
4154
  base: './', publicDir: false,
1721
4155
  define: { 'process.env.NODE_ENV': JSON.stringify(nodeEnv) },
@@ -1724,11 +4158,18 @@ try {
1724
4158
  outDir, emptyOutDir: false, minify: nodeEnv === 'production', target: 'esnext',
1725
4159
  rollupOptions: {
1726
4160
  input, preserveEntrySignatures: 'strict',
1727
- output: { format: 'es', entryFileNames: '[name].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },
4161
+ output: { format: 'es', entryFileNames: '[name]-[hash].js', chunkFileNames: 'chunks/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]' },
1728
4162
  },
1729
4163
  },
1730
4164
  });
1731
4165
  rmSync(srcDir, { recursive: true, force: true });
4166
+ const files = {};
4167
+ for (const out of Array.isArray(result) ? result : [result]) {
4168
+ for (const chunk of out?.output ?? []) {
4169
+ if (chunk.type === 'chunk' && chunk.isEntry) files[chunk.name] = chunk.fileName;
4170
+ }
4171
+ }
4172
+ writeFileSync(join(outDir, 'files.json'), JSON.stringify(files));
1732
4173
  // Force exit: rolldown can leave native worker threads alive that keep the
1733
4174
  // event loop open, hanging the parent's spawn() promise indefinitely.
1734
4175
  process.exit(0);
@@ -1738,6 +4179,91 @@ try {
1738
4179
  }
1739
4180
  `;
1740
4181
  //#endregion
4182
+ //#region connect-utils/vite-plugins/reactor-worker-dev.ts
4183
+ const DEV_BUNDLE_DIR = "node_modules/.ph-reactor-worker";
4184
+ function withBase(base, p) {
4185
+ return `${base}${p}`.replace(/\/{2,}/g, "/");
4186
+ }
4187
+ /**
4188
+ * Dev-only: serve Connect's reactor SharedWorker bundle under
4189
+ * `<base>__reactor_worker__/`, building it lazily on first request.
4190
+ *
4191
+ * The dev server serves Connect from its prebuilt dist in node_modules, where
4192
+ * `dist/reactor.worker.js` is a library artifact no worker can resolve. The
4193
+ * tab GETs `worker-meta.json` here (JSON, no-cache, written by
4194
+ * `prebuildReactorWorker`) to find the bundle and fold its `sourceDigest`
4195
+ * into its version fingerprint; without this plugin that GET fails and the
4196
+ * worker feature reports itself unavailable instead of dying opaquely.
4197
+ *
4198
+ * Lazy because it is a full `vite build` of the reactor + PGlite graph. The
4199
+ * result is cached in node_modules/.ph-reactor-worker until the installed
4200
+ * Connect, its upstream dists, or builder-tools change (`computeSourceDigest`).
4201
+ */
4202
+ function reactorWorkerDevPlugin(projectRoot) {
4203
+ let base = "/";
4204
+ let building = null;
4205
+ const ensureBuilt = () => {
4206
+ building ??= (async () => {
4207
+ const errorRef = {};
4208
+ const built = await prebuildReactorWorker({
4209
+ dirname: projectRoot,
4210
+ outDir: path.join(projectRoot, DEV_BUNDLE_DIR),
4211
+ nodeEnv: "development",
4212
+ errorRef
4213
+ });
4214
+ if (!built) {
4215
+ console.warn(`[connect] reactor worker bundle build failed${errorRef.message ? `: ${errorRef.message}` : ""}`);
4216
+ building = null;
4217
+ }
4218
+ return built;
4219
+ })();
4220
+ return building;
4221
+ };
4222
+ return {
4223
+ name: "ph-reactor-worker-dev",
4224
+ apply: "serve",
4225
+ configResolved(config) {
4226
+ base = config.base;
4227
+ },
4228
+ configureServer(server) {
4229
+ const prefixes = [withBase(base, REACTOR_WORKER_URL_PREFIX), REACTOR_WORKER_URL_PREFIX];
4230
+ server.middlewares.use((req, res, next) => {
4231
+ const url = (req.url ?? "").split("?")[0];
4232
+ const prefix = prefixes.find((p) => url.startsWith(p));
4233
+ if (!prefix) return next();
4234
+ const name = url.slice(prefix.length).replace(/^\/+/, "");
4235
+ if (!name) return next();
4236
+ (async () => {
4237
+ const built = await ensureBuilt();
4238
+ if (!built) {
4239
+ res.statusCode = 503;
4240
+ res.setHeader("Content-Type", "text/plain");
4241
+ res.end("reactor worker bundle unavailable (build failed; see server log)");
4242
+ return;
4243
+ }
4244
+ const file = path.join(built.outDir, name);
4245
+ const rel = path.relative(built.outDir, file);
4246
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
4247
+ next();
4248
+ return;
4249
+ }
4250
+ const stream = createReadStream(file);
4251
+ stream.on("error", () => {
4252
+ if (!res.headersSent) next();
4253
+ });
4254
+ stream.once("open", () => {
4255
+ const ext = file.slice(file.lastIndexOf("."));
4256
+ res.setHeader("Content-Type", REACTOR_WORKER_MIME[ext] ?? "text/javascript");
4257
+ const hashed = !name.startsWith("reactor.worker.js") && !name.endsWith(".json");
4258
+ res.setHeader("Cache-Control", hashed ? "public, max-age=31536000, immutable" : "no-cache");
4259
+ stream.pipe(res);
4260
+ });
4261
+ })();
4262
+ });
4263
+ }
4264
+ };
4265
+ }
4266
+ //#endregion
1741
4267
  //#region connect-utils/vite-plugins/theme-boot.ts
1742
4268
  /**
1743
4269
  * Marker attribute on the injected script. Serve-time injectors (e.g. the
@@ -1752,7 +4278,7 @@ const THEME_BOOT_MARKER = "data-ph-theme-boot";
1752
4278
  * Keep semantically identical to the runtime store in
1753
4279
  * `@powerhousedao/reactor-browser` (hooks/theme.ts).
1754
4280
  */
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){}})();";
4281
+ 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
4282
  /**
1757
4283
  * Injects the theme boot script at the top of `<head>` of every emitted
1758
4284
  * index.html, so built Connect apps render the stored theme from first paint
@@ -1776,90 +4302,135 @@ function connectThemeBootPlugin() {
1776
4302
  };
1777
4303
  }
1778
4304
  //#endregion
4305
+ //#region connect-utils/vite-plugins/vendor-import-map.ts
4306
+ function extractImports(raw) {
4307
+ if (typeof raw !== "object" || raw === null) return {};
4308
+ const imports = "imports" in raw ? raw.imports : void 0;
4309
+ if (typeof imports !== "object" || imports === null) return {};
4310
+ const out = {};
4311
+ for (const [key, value] of Object.entries(imports)) if (typeof value === "string") out[key] = value;
4312
+ return out;
4313
+ }
4314
+ function parseImportMap(raw) {
4315
+ try {
4316
+ return extractImports(JSON.parse(raw));
4317
+ } catch {
4318
+ return {};
4319
+ }
4320
+ }
4321
+ const INLINE_IMPORTMAP = /<script type="importmap">([\s\S]*?)<\/script>/;
4322
+ function vendorImportMapPlugin(options) {
4323
+ const vendorEntries = Object.keys(options.imports).length;
4324
+ return {
4325
+ name: "ph-vendor-import-map",
4326
+ apply: "build",
4327
+ transformIndexHtml(html) {
4328
+ if (!vendorEntries) return;
4329
+ const match = INLINE_IMPORTMAP.exec(html);
4330
+ if (match) {
4331
+ const merged = { imports: {
4332
+ ...parseImportMap(match[1]),
4333
+ ...options.imports
4334
+ } };
4335
+ return html.replace(INLINE_IMPORTMAP, `<script type="importmap">${JSON.stringify(merged)}<\/script>`);
4336
+ }
4337
+ return [{
4338
+ tag: "script",
4339
+ attrs: { type: "importmap" },
4340
+ children: JSON.stringify({ imports: options.imports }),
4341
+ injectTo: "head-prepend"
4342
+ }];
4343
+ }
4344
+ };
4345
+ }
4346
+ //#endregion
1779
4347
  //#region connect-utils/vite-config.ts
1780
4348
  function getConnectHtmlTags(options = {}) {
1781
- const { registryUrl, injectTo = "head" } = options;
1782
- return [
4349
+ const { registryUrl, appName, injectTo = "head" } = options;
4350
+ const connectCard = appName ? [] : [
1783
4351
  {
1784
4352
  tag: "meta",
1785
4353
  attrs: {
1786
- "http-equiv": "Content-Security-Policy",
1787
- content: `script-src 'self' 'unsafe-inline' 'unsafe-eval'${registryUrl ? " " + registryUrl : ""}; worker-src 'self' blob:; object-src 'none'; base-uri 'self';`
4354
+ property: "og:url",
4355
+ content: "https://apps.powerhouse.io/powerhouse/connect/"
1788
4356
  },
1789
4357
  injectTo
1790
4358
  },
1791
4359
  {
1792
4360
  tag: "meta",
1793
4361
  attrs: {
1794
- property: "og:title",
1795
- content: "Connect"
4362
+ property: "og:description",
4363
+ content: "Navigate your organisation’s toughest operational challenges and steer your contributors to success with Connect. A navigation, collaboration and reporting tool for decentralised and open organisation."
1796
4364
  },
1797
4365
  injectTo
1798
4366
  },
1799
4367
  {
1800
4368
  tag: "meta",
1801
4369
  attrs: {
1802
- property: "og:type",
1803
- content: "website"
4370
+ property: "og:image",
4371
+ content: "https://cf-ipfs.com/ipfs/bafkreigrmclndf2jpbolaq22535q2sw5t44uad3az3dpvkzrnt4lpjt63e"
1804
4372
  },
1805
4373
  injectTo
1806
4374
  },
1807
4375
  {
1808
4376
  tag: "meta",
1809
4377
  attrs: {
1810
- property: "og:url",
1811
- content: "https://apps.powerhouse.io/powerhouse/connect/"
4378
+ name: "twitter:card",
4379
+ content: "summary_large_image"
1812
4380
  },
1813
4381
  injectTo
1814
4382
  },
1815
4383
  {
1816
4384
  tag: "meta",
1817
4385
  attrs: {
1818
- property: "og:description",
1819
- content: "Navigate your organisation’s toughest operational challenges and steer your contributors to success with Connect. A navigation, collaboration and reporting tool for decentralised and open organisation."
4386
+ name: "twitter:image",
4387
+ content: "https://cf-ipfs.com/ipfs/bafkreigrmclndf2jpbolaq22535q2sw5t44uad3az3dpvkzrnt4lpjt63e"
1820
4388
  },
1821
4389
  injectTo
1822
4390
  },
1823
4391
  {
1824
4392
  tag: "meta",
1825
4393
  attrs: {
1826
- property: "og:image",
1827
- content: "https://cf-ipfs.com/ipfs/bafkreigrmclndf2jpbolaq22535q2sw5t44uad3az3dpvkzrnt4lpjt63e"
4394
+ name: "twitter:description",
4395
+ content: "Navigate your organisation’s toughest operational challenges and steer your contributors to success with Connect. A navigation, collaboration and reporting tool for decentralised and open organisation."
1828
4396
  },
1829
4397
  injectTo
1830
- },
4398
+ }
4399
+ ];
4400
+ return [
1831
4401
  {
1832
4402
  tag: "meta",
1833
4403
  attrs: {
1834
- name: "twitter:card",
1835
- content: "summary_large_image"
4404
+ "http-equiv": "Content-Security-Policy",
4405
+ content: `script-src 'self' 'unsafe-inline' 'unsafe-eval'${registryUrl ? " " + registryUrl : ""}; worker-src 'self' blob:; object-src 'none'; base-uri 'self';`
1836
4406
  },
1837
4407
  injectTo
1838
4408
  },
1839
4409
  {
1840
4410
  tag: "meta",
1841
4411
  attrs: {
1842
- name: "twitter:image",
1843
- content: "https://cf-ipfs.com/ipfs/bafkreigrmclndf2jpbolaq22535q2sw5t44uad3az3dpvkzrnt4lpjt63e"
4412
+ property: "og:title",
4413
+ content: appName ?? "Connect"
1844
4414
  },
1845
4415
  injectTo
1846
4416
  },
1847
4417
  {
1848
4418
  tag: "meta",
1849
4419
  attrs: {
1850
- name: "twitter:title",
1851
- content: "Connect"
4420
+ property: "og:type",
4421
+ content: "website"
1852
4422
  },
1853
4423
  injectTo
1854
4424
  },
1855
4425
  {
1856
4426
  tag: "meta",
1857
4427
  attrs: {
1858
- name: "twitter:description",
1859
- content: "Navigate your organisation’s toughest operational challenges and steer your contributors to success with Connect. A navigation, collaboration and reporting tool for decentralised and open organisation."
4428
+ name: "twitter:title",
4429
+ content: appName ?? "Connect"
1860
4430
  },
1861
4431
  injectTo
1862
- }
4432
+ },
4433
+ ...connectCard
1863
4434
  ];
1864
4435
  }
1865
4436
  function viteLogger({ silence }) {
@@ -1896,14 +4467,15 @@ function getLocalPackageNamesFromPowerhouseConfig({ packages }) {
1896
4467
  }
1897
4468
  function getConnectBaseViteConfig(options) {
1898
4469
  const mode = options.mode;
1899
- const fileEnv = loadEnv(mode, options.envDir ?? options.dirname, "PH_");
4470
+ const envDir = options.envDir ?? options.dirname;
4471
+ const fileEnv = loadEnv(mode, envDir, "PH_");
1900
4472
  const env = loadConnectEnv({
1901
4473
  processEnv: process.env,
1902
4474
  fileEnv
1903
4475
  });
1904
4476
  setConnectEnv(env);
1905
4477
  const phConfigPath = join(options.dirname, "powerhouse.config.json");
1906
- const phConfig = options.powerhouseConfig ?? getConfig(phConfigPath);
4478
+ const phConfig = options.powerhouseConfig ?? getConfig$1(phConfigPath);
1907
4479
  const packagesFromConfig = phConfig.packages ?? [];
1908
4480
  const localPackagesFromConfig = getLocalPackageNamesFromPowerhouseConfig(phConfig);
1909
4481
  const phPackagesStr = env.PH_PACKAGES;
@@ -1924,7 +4496,6 @@ function getConnectBaseViteConfig(options) {
1924
4496
  offlineEnabled,
1925
4497
  packageRegistryUrl: phPackageRegistryUrl
1926
4498
  });
1927
- const connectHtmlTags = getConnectHtmlTags({ registryUrl: phPackageRegistryUrl });
1928
4499
  const devImportmapTag = mode === "development" ? [{
1929
4500
  tag: "script",
1930
4501
  attrs: { type: "importmap" },
@@ -1934,10 +4505,16 @@ function getConnectBaseViteConfig(options) {
1934
4505
  const plugins = [
1935
4506
  tailwind(),
1936
4507
  react(),
1937
- createHtmlPlugin({
1938
- minify: false,
1939
- inject: { tags: [...connectHtmlTags, ...devImportmapTag] }
1940
- })
4508
+ {
4509
+ name: "ph-connect-html-tags",
4510
+ transformIndexHtml: {
4511
+ order: "pre",
4512
+ handler: () => [...getConnectHtmlTags({
4513
+ registryUrl: phPackageRegistryUrl,
4514
+ appName: projectBrand.name
4515
+ }), ...devImportmapTag]
4516
+ }
4517
+ }
1941
4518
  ];
1942
4519
  if (uploadSentrySourcemaps) plugins.push(import("@sentry/vite-plugin").then(({ sentryVitePlugin }) => sentryVitePlugin({
1943
4520
  release: {
@@ -1958,6 +4535,25 @@ function getConnectBaseViteConfig(options) {
1958
4535
  const projectPwa = validateProjectPwaConfig(deepMerge(phConfig.connect?.pwa ?? {}, options.cliConnectOverride?.pwa ?? {}), phConfigPath);
1959
4536
  const pwaWarn = (msg) => (customLogger ?? console).warn(msg);
1960
4537
  const pwaPackagesForFragments = mode === "production" ? phPackages : phPackages.filter((p) => p.provider === "local");
4538
+ const brandWarn = (msg) => (customLogger ?? console).warn(msg);
4539
+ const branding = effectiveBranding(phConfig.connect?.branding, options.cliConnectOverride?.branding);
4540
+ const projectLoader = resolveProjectLoader(options.dirname, branding, brandWarn);
4541
+ const projectBrand = resolveProjectPwaBrand(options.dirname, branding, brandWarn);
4542
+ const runtimeBranding = resolveRuntimeBranding(options.dirname, branding, brandWarn);
4543
+ const sourceConnect = withResolvedGenericImages(options.dirname, phConfig.connect, brandWarn);
4544
+ const connectOverride = withResolvedGenericImages(options.dirname, options.cliConnectOverride, brandWarn);
4545
+ const configPlugin = phConfigPlugin({
4546
+ packages: phPackages,
4547
+ projectRoot: options.dirname,
4548
+ connect: sourceConnect,
4549
+ workflows: phConfig.workflows,
4550
+ packageRegistryUrl: phPackageRegistryUrl ?? void 0,
4551
+ cliConnectOverride: connectOverride,
4552
+ branding: runtimeBranding
4553
+ });
4554
+ const servedConnect = configPlugin.api.connect;
4555
+ const faviconPath = options.favicon ?? configPlugin.api.favicon;
4556
+ const projectFavicons = resolveProjectFavicons(options.dirname, branding, brandWarn, faviconPath);
1961
4557
  const pwaPlugins = (async () => {
1962
4558
  if (!offlineEnabled) return connectPwaPlugins({ offlineEnabled });
1963
4559
  const contributions = await collectPackagePwaContributions({
@@ -1968,9 +4564,12 @@ function getConnectBaseViteConfig(options) {
1968
4564
  });
1969
4565
  const projectContribution = collectProjectPwaContribution({ projectRoot: options.dirname });
1970
4566
  if (projectContribution) contributions.push(projectContribution);
4567
+ const mergedPwa = mergePwaConfig(contributions, projectPwa, pwaWarn);
1971
4568
  return connectPwaPlugins({
1972
4569
  offlineEnabled,
1973
- pwa: mergePwaConfig(contributions, projectPwa, pwaWarn)
4570
+ pwa: mergedPwa,
4571
+ brand: projectBrand,
4572
+ staticFiles: staticFilesIn(join(options.dirname, "public"))
1974
4573
  });
1975
4574
  })();
1976
4575
  const reactExternal = [
@@ -1983,62 +4582,86 @@ function getConnectBaseViteConfig(options) {
1983
4582
  "@powerhousedao/reactor-browser",
1984
4583
  "@powerhousedao/connect",
1985
4584
  "@electric-sql/pglite"
1986
- ].map((pkg) => {
4585
+ ].flatMap((pkg) => {
4586
+ let real;
1987
4587
  try {
1988
- return searchForWorkspaceRoot(realpathSync(join(options.dirname, "node_modules", pkg)));
4588
+ real = realpathSync(join(options.dirname, "node_modules", pkg));
1989
4589
  } catch {
1990
- return null;
4590
+ return [];
1991
4591
  }
1992
- }).filter((p) => p !== null);
4592
+ const store = dependencyStoreOf(real);
4593
+ return [searchForWorkspaceRoot(real), ...store ? [store] : []];
4594
+ });
4595
+ const routesDir = resolveConnectRoutesDir(options.dirname, options.routes) ?? false;
4596
+ const mountedRoutesDir = routesDir || (mode === "development" && options.routes === void 0 ? join(options.dirname, "hosts/connect/routes") : false);
4597
+ const routes = connectRoutes(options.dirname, mountedRoutesDir);
4598
+ const customShell = hasProjectAppLayout(routesDir || void 0);
4599
+ const hostStylesheet = hostStylesheetPath(options.dirname, routesDir);
1993
4600
  return {
1994
4601
  configFile: false,
1995
4602
  mode,
4603
+ cacheDir: options.cacheDir,
1996
4604
  base: options.dynamicBase ? DYNAMIC_BASE_PLACEHOLDER : connectBasePath ? normalizeBasePath(connectBasePath) : void 0,
1997
4605
  server: {
1998
- watch: { ignored: ["**/backup-documents/**", "**/.ph/**"] },
4606
+ watch: { ignored: [
4607
+ "**/backup-documents/**",
4608
+ "**/coverage/**",
4609
+ ignoreDotPhButRouteTree(options.dirname, mountedRoutesDir),
4610
+ ignoreBuildOutput(options.dirname)
4611
+ ] },
1999
4612
  fs: { allow: [searchForWorkspaceRoot(options.dirname), ...linkedRoots] }
2000
4613
  },
2001
4614
  resolve: {
2002
- dedupe: ["react", "react-dom"],
4615
+ alias: routes.aliases,
4616
+ dedupe: [
4617
+ "react",
4618
+ "react-dom",
4619
+ ...routes.dedupe
4620
+ ],
2003
4621
  tsconfigPaths: true
2004
4622
  },
2005
4623
  define: {
2006
4624
  PH_CONNECT_SENTRY_RELEASE: JSON.stringify(release || "unknown"),
2007
- PH_CONNECT_BUILD_HASH: JSON.stringify(buildHash)
4625
+ PH_CONNECT_BUILD_HASH: JSON.stringify(buildHash),
4626
+ ...options.vendor?.sharedDeps && mode === "production" ? { PH_CONNECT_SHARED_DEPS_URL: JSON.stringify(options.vendor.sharedDeps) } : {},
4627
+ ...options.reactorWorkerVersion ? { PH_CONNECT_REACTOR_WORKER_VERSION: JSON.stringify(options.reactorWorkerVersion) } : {}
2008
4628
  },
2009
4629
  customLogger,
2010
4630
  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
- },
4631
+ optimizeDeps: connectOptimizeDeps(options.dirname, mountedRoutesDir, routes.include),
2021
4632
  plugins: [
2022
- phConfigPlugin({
2023
- packages: phPackages,
2024
- projectRoot: options.dirname,
2025
- connect: phConfig.connect,
2026
- packageRegistryUrl: phPackageRegistryUrl ?? void 0,
2027
- cliConnectOverride: options.cliConnectOverride
2028
- }),
4633
+ configPlugin,
4634
+ hostStylesheetPlugin(options.dirname, hostStylesheet),
2029
4635
  phBundledPackagesPlugin({
2030
4636
  packages: localPackagesFromConfig,
2031
4637
  projectRoot: options.dirname
2032
4638
  }),
2033
- devReactImportmapPlugin(options.dirname),
4639
+ devReactImportmapPlugin(options.dirname, mountedRoutesDir),
4640
+ reactorWorkerDevPlugin(options.dirname),
4641
+ ...routes.plugins,
2034
4642
  ...plugins,
2035
- esmExternalRequirePlugin({ external: reactExternal }),
4643
+ esmExternalRequirePlugin({ external: [...reactExternal, ...options.vendor && mode === "production" ? Object.keys(options.vendor.imports) : []] }),
2036
4644
  reactSelfHostPlugin({
2037
4645
  dirname: options.dirname,
2038
4646
  dev: mode !== "production" || isDebug
2039
4647
  }),
2040
- connectFaviconPlugin({ faviconPath: options.favicon }),
4648
+ ...options.vendor && mode === "production" ? [vendorImportMapPlugin({ imports: options.vendor.imports })] : [],
4649
+ connectFaviconPlugin({ faviconPath }),
2041
4650
  connectThemeBootPlugin(),
4651
+ connectAppShellPlugin(options.dirname, {
4652
+ composition: servedConnect.composition,
4653
+ appName: servedConnect.branding?.appName ?? void 0,
4654
+ routeAliases: routesDir ? routes.aliases : void 0,
4655
+ routesDir: routesDir || void 0,
4656
+ loader: projectLoader,
4657
+ hostStylesheet
4658
+ }),
4659
+ connectProjectBrandPlugin({
4660
+ loader: projectLoader,
4661
+ pwaIcons: offlineEnabled ? projectBrand.icons : void 0,
4662
+ favicons: projectFavicons,
4663
+ customShell
4664
+ }),
2042
4665
  connectBuildHashPlugin(buildHash),
2043
4666
  ...options.dynamicBase ? [connectDynamicBasePlugin()] : [],
2044
4667
  pwaPlugins
@@ -2047,10 +4670,16 @@ function getConnectBaseViteConfig(options) {
2047
4670
  format: "es",
2048
4671
  ...options.dynamicBase ? { plugins: () => [connectDynamicBasePlugin({ forWorker: true })] } : {}
2049
4672
  },
2050
- build: { sourcemap: true }
4673
+ build: {
4674
+ sourcemap: true,
4675
+ rolldownOptions: {
4676
+ shimMissingExports: true,
4677
+ output: { codeSplitting: { groups: connectRouterChunkGroups(routesDir) } }
4678
+ }
4679
+ }
2051
4680
  };
2052
4681
  }
2053
4682
  //#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 };
4683
+ export { APP_LAYOUT, BUILDER_TOOLS_VERSION, BUILD_HASH_FILE, CONNECT_ROUTES_GEN, CONNECT_ROUTES_SPECIFIER, CONNECT_ROUTE_FILE_DEPS, CORE_ROUTE_TREE_SPECIFIER, 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, THEME_BOOT_MARKER, VENDOR_EXTERNAL, VENDOR_SKIP_SUBPATHS, VENDOR_URL_PREFIX, WORKER_PACKAGES_MANIFEST, acquireLock, 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, linkedBuildStamp, makeImportScriptFromPackages, missingVendorEntries, overriddenConnectRoutes, ownProjectPackage, phConfigPlugin, prebuildConnectVendor, prebuildReactorWorker, prebuildWorkerPackages, prependToHtmlHead, publishDirAtomic, readAppShell, readAppShells, readJsonFile, readShellPlugins, relativeCssUrls, releaseLock, removeBase64EnvValues, resolveConnectBundle, resolveConnectPackageJson, resolveConnectPublicDir, resolveConnectRoutesDir, resolveOwnDeps, resolveOwnPackageVersion, resolvePackage, resolveReactorWorkerSource, resolveVersionDigest, resolveViteConfigPath, resolveWorkspacePackageDir, routeIdOf, runShellScriptPlugin, runTsc, runWorkerBuildEntries, runtimeConfigSchema, stripVersionFromPackage, syncConnectRoutes, upstreamWorkerPackages, vendorImportMapPlugin, vendorRelativePath, withAppTitle, withErrorOverlay, withHostStylesheet, withSourceLocations, withVendorBase, workerSafeVendorImports };
2055
4684
 
2056
4685
  //# sourceMappingURL=index.mjs.map