@powerhousedao/builder-tools 6.2.3-dev.10 → 6.2.3-dev.101

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