@powerhousedao/builder-tools 6.2.3-staging.0 → 6.3.0-dev.1

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