@powerhousedao/builder-tools 6.2.3-dev.69 → 6.2.3-dev.70

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,20 +1,20 @@
1
1
  import { createRequire } from "node:module";
2
- import react from "@vitejs/plugin-react";
3
- import fs, { chmodSync, cpSync, createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import fs, { chmodSync, cpSync, createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
4
3
  import path, { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
- import { createLogger, createServer, esmExternalRequirePlugin, loadEnv, searchForWorkspaceRoot } from "vite";
4
+ import { createLogger, createServer, esmExternalRequirePlugin, loadEnv, normalizePath, searchForWorkspaceRoot } from "vite";
6
5
  import { exec, execSync, spawn } from "node:child_process";
7
6
  import { readFile, writeFile } from "node:fs/promises";
8
7
  import { cwd } from "node:process";
9
- import { createHash, randomUUID } from "node:crypto";
10
8
  import { Generator, getConfig } from "@tanstack/router-generator";
11
9
  import { tanstackRouter } from "@tanstack/router-plugin/vite";
12
10
  import { index, layout, physical, rootRoute, route } from "@tanstack/virtual-file-routes";
11
+ import { createHash, randomUUID } from "node:crypto";
13
12
  import { fileURLToPath } from "node:url";
14
13
  import { DYNAMIC_BASE_PLACEHOLDER, PWA_FILE_HANDLER_ACTION, buildRuntimeConfig, deepMerge, loadConnectEnv, mergeManifest, mergePwaConfig, normalizeBasePath, phConnectRuntimeConfigSchema, powerhousePackageSchema, resolveSourceConnect, setConnectEnv, unionStrings, withInferredCategory, workerPackageFileName, workflowsSettingConflict } from "@powerhousedao/shared/connect";
15
14
  import MagicString from "magic-string";
16
15
  import { getConfig as getConfig$1 } from "@powerhousedao/config/node";
17
16
  import tailwind from "@tailwindcss/vite";
17
+ import react from "@vitejs/plugin-react";
18
18
  import { createHtmlPlugin } from "vite-plugin-html";
19
19
  import { PwaConfigSchema } from "@powerhousedao/shared/document-model";
20
20
  import { toCdnUrl } from "@powerhousedao/shared/registry/urls";
@@ -208,412 +208,100 @@ function stripVersionFromPackage(packageName) {
208
208
  return trimmed;
209
209
  }
210
210
  //#endregion
211
- //#region connect-utils/vite-plugins/app-shell.ts
212
- /** On the prerendered shell's elements; marks an index.html that has it. */
213
- const APP_SHELL_MARKER = "data-ph-shell";
214
- /** In Connect's dist, and copied to a project's: the plugins that pick a shell. */
215
- const SHELL_PLUGINS_FILE = "shell-plugins.json";
216
- /** In a project's dist: every variant, for a server that swaps the shell to the served composition. */
217
- const APP_SHELLS_FILE = "app-shells.json";
218
- const SHELL_FILES = {
219
- generic: "shell",
220
- core: "shell-core"
221
- };
222
- /** The shell of the composition's first plugin that has one, else core's; no composition is classic.
223
- * Without `plugins` (an older Connect): core for a composition, generic for classic. */
224
- function appShellVariant(composition, plugins) {
225
- if (!plugins) return composition ? "core" : "generic";
226
- if (!composition) return Object.values(plugins)[0] ?? "core";
227
- for (const { module } of composition) if (Object.hasOwn(plugins, module)) return plugins[module];
228
- return "core";
229
- }
230
- function connectDistDir(projectRoot) {
231
- try {
232
- return join(dirname(resolvePackage("@powerhousedao/connect/package.json", projectRoot)), "dist");
233
- } catch {
234
- return;
235
- }
236
- }
237
- /** The plugins' shell manifest in `dir`, if there is a valid one. */
238
- function readShellPluginsIn(dir) {
239
- const file = join(dir, SHELL_PLUGINS_FILE);
240
- if (!existsSync(file)) return void 0;
241
- try {
242
- const manifest = JSON.parse(readFileSync(file, "utf8"));
243
- if (!manifest || typeof manifest !== "object") return void 0;
244
- const plugins = {};
245
- for (const [module, variant] of Object.entries(manifest)) if (variant === "generic" || variant === "core") plugins[module] = variant;
246
- return plugins;
247
- } catch {
248
- return;
249
- }
250
- }
251
- /** The shell manifest of the installed Connect, if it ships one. */
252
- function readShellPlugins(projectRoot) {
253
- const distDir = connectDistDir(projectRoot);
254
- return distDir ? readShellPluginsIn(distDir) : void 0;
255
- }
256
- /** The shell Connect's build prerendered, if the installed Connect ships one. */
257
- function readAppShell(projectRoot, variant = "generic") {
258
- const distDir = connectDistDir(projectRoot);
259
- if (!distDir) return void 0;
260
- const body = join(distDir, `${SHELL_FILES[variant]}.html`);
261
- const head = join(distDir, `${SHELL_FILES[variant]}-head.html`);
262
- if (!existsSync(body) || !existsSync(head)) return void 0;
263
- return {
264
- body: readFileSync(body, "utf8"),
265
- head: readFileSync(head, "utf8")
266
- };
267
- }
268
- /** Every variant the installed Connect ships. */
269
- function readAppShells(projectRoot) {
270
- const shells = {};
271
- for (const variant of Object.keys(SHELL_FILES)) {
272
- const shell = readAppShell(projectRoot, variant);
273
- if (shell) shells[variant] = shell;
211
+ //#region connect-utils/vite-plugins/connect-routes.ts
212
+ /** A project's routes for its Connect deployment, beside Connect's own. */
213
+ const HOST_ROUTES_DIR = "hosts/connect/routes";
214
+ /** The generated tree of Connect's and the project's routes. */
215
+ const CONNECT_ROUTES_GEN = ".ph/connect-routes.gen.ts";
216
+ /** Connect's dist imports its route tree by this specifier. */
217
+ const ROUTE_TREE_SPECIFIER = "@powerhousedao/connect/route-tree";
218
+ /** Core's types name the app's tree by this one; both resolve to one tree. */
219
+ const CORE_ROUTE_TREE_SPECIFIER = "@powerhousedao/connect-core/route-tree";
220
+ const ROUTE_TREE_FIND = new RegExp(`^(${[ROUTE_TREE_SPECIFIER, CORE_ROUTE_TREE_SPECIFIER].map(escapeRegExp).join("|")})$`);
221
+ /** A host's routes folder: `routes` (a host's `runner.routes`), relative to the
222
+ * project, else `hosts/connect/routes/`; undefined if none or `false`. */
223
+ function resolveConnectRoutesDir(projectRoot, routes) {
224
+ if (routes === false) return void 0;
225
+ if (routes !== void 0) {
226
+ const dir = resolve(projectRoot, routes);
227
+ if (!existsSync(dir)) throw new Error(`The routes folder ${routes} does not exist.`);
228
+ return dir;
274
229
  }
275
- return shells;
230
+ const dir = join(projectRoot, HOST_ROUTES_DIR);
231
+ return existsSync(dir) ? dir : void 0;
276
232
  }
277
- /** On the boot-recovery script; its sessionStorage key guards against reload loops. */
278
- const BOOT_RECOVER_MARKER = "data-ph-boot-recover";
279
- const BOOT_RECOVER_KEY = "ph:sw-recover";
280
- const BOOT_RECOVER_SCRIPT = `(function(){try{var K='${BOOT_RECOVER_KEY}',n=navigator.serviceWorker,done=0;if(!n||sessionStorage.getItem(K))return;var up=function(){return !document.querySelector('style[${APP_SHELL_MARKER}]')};var reload=function(){location.reload()};var skip=function(w){try{sessionStorage.setItem(K,'1')}catch(e){}n.addEventListener('controllerchange',reload);w.postMessage({type:'SKIP_WAITING'});setTimeout(reload,3000)};var watch=function(w){w.addEventListener('statechange',function(){if(w.state==='installed')skip(w)})};var go=function(){if(done||up())return;done=1;n.getRegistration().then(function(r){if(!r)return;if(r.waiting)return skip(r.waiting);if(r.installing)return watch(r.installing);r.addEventListener('updatefound',function(){if(r.installing)watch(r.installing)});return r.update()}).catch(function(){})};addEventListener('error',function(e){var t=e.target;if(e.error instanceof SyntaxError||e.error instanceof TypeError||(t&&t.tagName==='SCRIPT'))go()},true);addEventListener('unhandledrejection',function(e){if(e.reason instanceof SyntaxError||e.reason instanceof TypeError)go()});setTimeout(go,8000)}catch(e){}})();`;
281
- /** Prefixes the shell's root-relative links with the deploy base. */
282
- function rebaseShellLinks(body, base) {
283
- if (base === "/" || !base) return body;
284
- const prefix = base.endsWith("/") ? base : `${base}/`;
285
- return body.replace(/(\shref=")\/(?!\/)/g, `$1${prefix}`);
233
+ const isDefaultRoutesDir = (projectRoot, routesDir) => resolve(routesDir) === join(resolve(projectRoot), HOST_ROUTES_DIR);
234
+ /** The tree generated from `routesDir`: `.ph/connect-routes.gen.ts` for
235
+ * `hosts/connect/routes/`, else `.ph/<folder>.gen.ts`. */
236
+ function connectRoutesTreeOf(projectRoot, routesDir) {
237
+ if (isDefaultRoutesDir(projectRoot, routesDir)) return join(projectRoot, CONNECT_ROUTES_GEN);
238
+ return join(projectRoot, ".ph", `${relative(projectRoot, routesDir)}.gen.ts`);
286
239
  }
287
- const STYLESHEET_LINK = /<link\b(?=[^>]*\brel=["']?stylesheet\b)[^>]*>/gi;
288
- function deferStylesheet(link) {
289
- return `${link.replace(/\brel=["']?stylesheet["']?/i, "rel=\"preload\" as=\"style\"").replace(/\/?>$/, ` onload="this.onload=null;this.rel='stylesheet'">`)}<noscript>${link}</noscript>`;
240
+ /** Connect's pathless sidebar layout; a project's routes in `_app/` render in it. */
241
+ const APP_LAYOUT = "_app";
242
+ function findRouteFile(dir, name) {
243
+ return [
244
+ ".tsx",
245
+ ".ts",
246
+ ".jsx",
247
+ ".js"
248
+ ].map((ext) => join(dir, `${name}${ext}`)).find((file) => existsSync(file));
290
249
  }
291
- const region = (name, content) => `<!--ph-shell:${name}-->${content}<!--/ph-shell:${name}-->`;
292
- const REGION = (name) => new RegExp(`<!--ph-shell:${name}-->[\\s\\S]*?<!--/ph-shell:${name}-->`);
293
- /** The app's title without `connect.branding.appName`; core's `appTitle` fallback. */
294
- const DEFAULT_APP_NAME = "Connect";
295
- const APP_NAME = /(<!--ph-shell:app-name-->)[\s\S]*?(<!--\/ph-shell:app-name-->)/g;
296
- const escapeHtml = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
297
- /** Fills the shell's app name as the app resolves it: the branding name, else the default. */
298
- function withShellAppName(html, appName) {
299
- const name = escapeHtml(appName || "Connect");
300
- return html.replace(APP_NAME, (_m, open, close) => [
301
- open,
302
- name,
303
- close
304
- ].join(""));
250
+ /** Connect's route files: core's routes with Connect's views. */
251
+ function connectRoutesDirOf(connectDir) {
252
+ return join(connectDir, "src/routes");
305
253
  }
306
- /** Inlines `shell` into an empty `#root`, adds its critical CSS and, unless
307
- * `deferStyles` is false, defers the stylesheets; React replaces the markup when the app renders. */
308
- function injectAppShell(html, shell, base = "/", { deferStyles = true, appName } = {}) {
309
- if (html.includes("data-ph-shell")) return html;
310
- const root = /<div id="root"><\/div>/;
311
- if (!root.test(html)) return html;
312
- const firstSheet = html.search(STYLESHEET_LINK);
313
- const at = firstSheet >= 0 ? firstSheet : html.indexOf("</head>");
314
- const recover = `<script ${BOOT_RECOVER_MARKER}>${BOOT_RECOVER_SCRIPT}<\/script>`;
315
- const body = withShellAppName(rebaseShellLinks(shell.body, base), appName);
316
- const withHead = html.slice(0, at) + region("head", shell.head) + recover + html.slice(at);
317
- return (deferStyles ? withHead.replace(STYLESHEET_LINK, deferStylesheet) : withHead).replace(root, () => `<div id="root">${region("body", body)}</div>`);
254
+ const ROUTE_FILE = /\.[cm]?[jt]sx?$/;
255
+ const isRouteEntry = (name) => !name.startsWith(".") && !name.startsWith("-");
256
+ /** The route files under `dir`, by path relative to it. */
257
+ function routeFilesIn(dir, at = "") {
258
+ if (!existsSync(dir)) return [];
259
+ return readdirSync(join(dir, at), { withFileTypes: true }).filter((entry) => isRouteEntry(entry.name)).flatMap((entry) => {
260
+ const path = at ? `${at}/${entry.name}` : entry.name;
261
+ if (entry.isDirectory()) return routeFilesIn(dir, path);
262
+ return ROUTE_FILE.test(entry.name) ? [path] : [];
263
+ });
318
264
  }
319
- /** The variant an index.html carries, from its shell's marker value. */
320
- function appShellVariantOf(html) {
321
- const head = REGION("head").exec(html)?.[0];
322
- const value = head && new RegExp(`data-ph-shell="(\\w+)"`).exec(head);
323
- if (!value) return void 0;
324
- return value[1] === "core" ? "core" : "generic";
265
+ /** A route file's id below its folder: route groups and `route` files
266
+ * resolved, flat `a.b` names read as folders. */
267
+ function routeIdOf(file) {
268
+ const segments = file.replace(ROUTE_FILE, "").split("/").filter((segment) => !/^\(.+\)$/.test(segment));
269
+ if (segments.at(-1) === "route") segments.pop();
270
+ return segments.join("/").replaceAll(".", "/");
325
271
  }
326
- /** Replaces the shell an index.html carries with `shell`, titled `appName`; a page without one is unchanged. */
327
- function swapAppShell(html, shell, base = "/", appName) {
328
- if (!REGION("head").test(html) || !REGION("body").test(html)) return html;
329
- const body = withShellAppName(rebaseShellLinks(shell.body, base), appName);
330
- return html.replace(REGION("head"), () => region("head", shell.head)).replace(REGION("body"), () => region("body", body));
272
+ /** Connect's `_app/` route files that a project file at the same id replaces. */
273
+ function overriddenConnectRoutes(connectAppDir, projectAppDir) {
274
+ const projectIds = new Set(routeFilesIn(projectAppDir).map(routeIdOf));
275
+ return new Set(routeFilesIn(connectAppDir).filter((file) => projectIds.has(routeIdOf(file))));
331
276
  }
332
- const DEV_SHELL_WAIT_MS = 1e4;
333
- async function renderProjectAppShells(projectRoot, config, routeAliases) {
334
- const server = await createServer({
335
- configFile: false,
336
- root: projectRoot,
337
- logLevel: "error",
338
- appType: "custom",
339
- server: {
340
- middlewareMode: true,
341
- hmr: false,
342
- ws: false
343
- },
344
- plugins: [react()],
345
- resolve: {
346
- alias: routeAliases,
347
- dedupe: config.resolve.dedupe,
348
- tsconfigPaths: true
349
- },
350
- define: config.define
351
- });
352
- try {
353
- return await (await server.ssrLoadModule("@powerhousedao/connect/prerender")).renderProjectShells(join(projectRoot, "style.css"));
354
- } finally {
355
- await server.close();
277
+ const stemOf = (name) => name.replace(ROUTE_FILE, "");
278
+ /** Mounts Connect's routes in `dir` without the `overridden` files: a folder
279
+ * whole when none is in it, else file by file. */
280
+ function mountConnectRoutes(routesDirectory, dir, overridden, prefix = "") {
281
+ if (![...overridden].some((file) => file.startsWith(`${dir}/`))) return [physical(prefix, dir)];
282
+ const entries = readdirSync(join(routesDirectory, dir), { withFileTypes: true }).filter((entry) => isRouteEntry(entry.name));
283
+ const files = entries.filter((entry) => entry.isFile() && ROUTE_FILE.test(entry.name)).map((entry) => entry.name);
284
+ const folders = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
285
+ const at = (name) => prefix ? `${prefix}/${name}` : name;
286
+ const nodes = [];
287
+ for (const name of files) {
288
+ const file = `${dir}/${name}`;
289
+ const stem = stemOf(name);
290
+ const folder = folders.includes(stem) ? `${dir}/${stem}` : void 0;
291
+ if (overridden.has(file)) {
292
+ if (folder) nodes.push(physical(at(stem), folder));
293
+ continue;
294
+ }
295
+ const children = folder && mountConnectRoutes(routesDirectory, folder, overridden);
296
+ if (stem === "index") nodes.push(prefix ? route(`${prefix}/`, file) : index(file));
297
+ else if (!prefix && stem.startsWith("_")) nodes.push(layout(stem, file, children || []));
298
+ else nodes.push(children ? route(at(stem), file, children) : route(at(stem), file));
299
+ }
300
+ for (const name of folders) {
301
+ if (files.some((file) => stemOf(file) === name)) continue;
302
+ nodes.push(...mountConnectRoutes(routesDirectory, `${dir}/${name}`, overridden, at(name)));
356
303
  }
357
- }
358
- const sourceText = (source) => typeof source === "string" ? source : new TextDecoder().decode(source);
359
- /** Build: the composition's shell in #root and every variant in the dist, from
360
- * the project's routes when it has them. Dev: the shell from the project's routes
361
- * when it has them, else core's for a core composition. */
362
- function connectAppShellPlugin(projectRoot, { composition, appName, routeAliases, routesDir } = {}) {
363
- let variant = "generic";
364
- let shells = {};
365
- let shellPlugins;
366
- let base = "/";
367
- let isBuild = true;
368
- let config;
369
- const fromRoutes = () => isBuild && !!routeAliases;
370
- const shell = () => {
371
- if (fromRoutes()) return void 0;
372
- return isBuild || variant === "core" ? shells[variant] : void 0;
373
- };
374
- let devShells;
375
- let devRender;
376
- const renderDevShells = () => {
377
- if (!config || !routeAliases) return;
378
- const logger = config.logger;
379
- devShells = renderProjectAppShells(projectRoot, config, routeAliases).catch((error) => {
380
- logger.warn(`[connect] the loading shell failed to render from the project's routes: ${String(error)}`);
381
- return {};
382
- });
383
- };
384
- const devShell = async () => {
385
- if (!devShells) return void 0;
386
- let timer;
387
- const wait = new Promise((resolve) => {
388
- timer = setTimeout(() => resolve(void 0), DEV_SHELL_WAIT_MS);
389
- });
390
- try {
391
- return (await Promise.race([devShells, wait]))?.[variant];
392
- } finally {
393
- clearTimeout(timer);
394
- }
395
- };
396
- return {
397
- name: "ph-connect-app-shell",
398
- configureServer(server) {
399
- if (!routeAliases) return;
400
- renderDevShells();
401
- const stylesheet = join(projectRoot, "style.css");
402
- const rerender = (file) => {
403
- if (!(file === stylesheet || !!routesDir && file.startsWith(`${routesDir}${sep}`))) return;
404
- clearTimeout(devRender);
405
- devRender = setTimeout(renderDevShells, 300);
406
- };
407
- server.watcher.on("change", rerender);
408
- server.watcher.on("add", rerender);
409
- server.watcher.on("unlink", rerender);
410
- },
411
- configResolved(resolved) {
412
- config = resolved;
413
- base = resolved.base;
414
- isBuild = resolved.command === "build";
415
- shells = readAppShells(projectRoot);
416
- shellPlugins = readShellPlugins(projectRoot);
417
- variant = appShellVariant(composition, shellPlugins);
418
- },
419
- transformIndexHtml: {
420
- order: "post",
421
- handler: async (html) => {
422
- const current = !isBuild && routeAliases ? await devShell() : shell();
423
- return current ? injectAppShell(html, current, base, {
424
- deferStyles: isBuild,
425
- appName
426
- }) : html;
427
- }
428
- },
429
- generateBundle: {
430
- order: "post",
431
- async handler(_options, bundle) {
432
- if (!isBuild) return;
433
- if (fromRoutes() && config && routeAliases) {
434
- shells = await renderProjectAppShells(projectRoot, config, routeAliases);
435
- const index = bundle["index.html"];
436
- const current = shells[variant];
437
- if (index?.type === "asset" && current) index.source = injectAppShell(sourceText(index.source), current, base, { appName });
438
- }
439
- if (!Object.keys(shells).length) return;
440
- this.emitFile({
441
- type: "asset",
442
- fileName: APP_SHELLS_FILE,
443
- source: JSON.stringify(shells)
444
- });
445
- if (shellPlugins) this.emitFile({
446
- type: "asset",
447
- fileName: SHELL_PLUGINS_FILE,
448
- source: JSON.stringify(shellPlugins)
449
- });
450
- }
451
- }
452
- };
453
- }
454
- //#endregion
455
- //#region connect-utils/vite-plugins/build-hash.ts
456
- /** Name of the build-identity file emitted into the build output. */
457
- const BUILD_HASH_FILE = "build-hash.json";
458
- /**
459
- * Deterministic identity of a Connect build. Differs whenever the deployed
460
- * content differs (published Connect version, project config, package list,
461
- * build options) so the SPA can detect "the server is serving a different
462
- * build than the one this bundle was built from" by comparing its baked copy
463
- * (define `PH_CONNECT_BUILD_HASH`) to `build-hash.json`, which the build
464
- * emits alongside the app and the server must serve no-cache.
465
- */
466
- function computeBuildHash(input) {
467
- return createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 16);
468
- }
469
- /**
470
- * Read the installed @powerhousedao/connect version. The package's `exports`
471
- * map does not expose a `./package.json` subpath, so `require.resolve(
472
- * "…/package.json")` throws — resolve the main entry and walk up to the
473
- * package root instead.
474
- */
475
- function readConnectVersion(projectRoot) {
476
- try {
477
- const entry = createRequire(join(projectRoot, "package.json")).resolve("@powerhousedao/connect", { paths: [projectRoot] });
478
- let dir = dirname(entry);
479
- for (;;) {
480
- try {
481
- const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
482
- if (pkg.name === "@powerhousedao/connect") return pkg.version ?? "unknown";
483
- } catch {}
484
- const parent = dirname(dir);
485
- if (parent === dir) break;
486
- dir = parent;
487
- }
488
- } catch {}
489
- return "unknown";
490
- }
491
- function buildHashFromBuildOptions(options) {
492
- return computeBuildHash({
493
- workspaceGitSha: process.env.WORKSPACE_GIT_SHA ?? "",
494
- workspaceVersion: process.env.WORKSPACE_VERSION ?? "",
495
- connectPackageVersion: readConnectVersion(options.dirname),
496
- projectConfig: options.phConfig,
497
- packages: options.packages.map((p) => `${p.packageName}@${p.version ?? ""}:${p.provider ?? ""}`),
498
- connectBasePath: options.connectBasePath ?? "",
499
- offlineEnabled: options.offlineEnabled,
500
- packageRegistryUrl: options.packageRegistryUrl ?? ""
501
- });
502
- }
503
- /**
504
- * Emits `build-hash.json` (`{"hash": "<build id>"}`) into the build output.
505
- * Emitted as an asset so it lands at the deploy base like every other file.
506
- * Build-only: dev (studio) never runs generateBundle, and the SPA check
507
- * treats a missing file as "nothing to compare" and stays silent.
508
- */
509
- function connectBuildHashPlugin(buildHash) {
510
- return {
511
- name: "ph-connect-build-hash",
512
- apply: "build",
513
- generateBundle() {
514
- this.emitFile({
515
- type: "asset",
516
- fileName: BUILD_HASH_FILE,
517
- source: `${JSON.stringify({ hash: buildHash }, null, 2)}\n`
518
- });
519
- }
520
- };
521
- }
522
- //#endregion
523
- //#region connect-utils/vite-plugins/connect-routes.ts
524
- /** A project's routes for its Connect deployment, beside Connect's own. */
525
- const HOST_ROUTES_DIR = "hosts/connect/routes";
526
- /** The generated tree of Connect's and the project's routes. */
527
- const CONNECT_ROUTES_GEN = ".ph/connect-routes.gen.ts";
528
- /** Connect's dist imports its route tree by this specifier. */
529
- const ROUTE_TREE_SPECIFIER = "@powerhousedao/connect/route-tree";
530
- /** Core's types name the app's tree by this one; both resolve to one tree. */
531
- const CORE_ROUTE_TREE_SPECIFIER = "@powerhousedao/connect-core/route-tree";
532
- const ROUTE_TREE_FIND = new RegExp(`^(${[ROUTE_TREE_SPECIFIER, CORE_ROUTE_TREE_SPECIFIER].map(escapeRegExp).join("|")})$`);
533
- /** A host's routes folder: `routes` (a host's `runner.routes`), relative to the
534
- * project, else `hosts/connect/routes/`; undefined if none or `false`. */
535
- function resolveConnectRoutesDir(projectRoot, routes) {
536
- if (routes === false) return void 0;
537
- if (routes !== void 0) {
538
- const dir = resolve(projectRoot, routes);
539
- if (!existsSync(dir)) throw new Error(`The routes folder ${routes} does not exist.`);
540
- return dir;
541
- }
542
- const dir = join(projectRoot, HOST_ROUTES_DIR);
543
- return existsSync(dir) ? dir : void 0;
544
- }
545
- const isDefaultRoutesDir = (projectRoot, routesDir) => resolve(routesDir) === join(resolve(projectRoot), HOST_ROUTES_DIR);
546
- /** The tree generated from `routesDir`: `.ph/connect-routes.gen.ts` for
547
- * `hosts/connect/routes/`, else `.ph/<folder>.gen.ts`. */
548
- function connectRoutesTreeOf(projectRoot, routesDir) {
549
- if (isDefaultRoutesDir(projectRoot, routesDir)) return join(projectRoot, CONNECT_ROUTES_GEN);
550
- return join(projectRoot, ".ph", `${relative(projectRoot, routesDir)}.gen.ts`);
551
- }
552
- /** Connect's pathless sidebar layout; a project's routes in `_app/` render in it. */
553
- const APP_LAYOUT = "_app";
554
- function findRouteFile(dir, name) {
555
- return [
556
- ".tsx",
557
- ".ts",
558
- ".jsx",
559
- ".js"
560
- ].map((ext) => join(dir, `${name}${ext}`)).find((file) => existsSync(file));
561
- }
562
- /** Connect's route files: core's routes with Connect's views. */
563
- function connectRoutesDirOf(connectDir) {
564
- return join(connectDir, "src/routes");
565
- }
566
- const ROUTE_FILE = /\.[cm]?[jt]sx?$/;
567
- const isRouteEntry = (name) => !name.startsWith(".") && !name.startsWith("-");
568
- /** The route files under `dir`, by path relative to it. */
569
- function routeFilesIn(dir, at = "") {
570
- if (!existsSync(dir)) return [];
571
- return readdirSync(join(dir, at), { withFileTypes: true }).filter((entry) => isRouteEntry(entry.name)).flatMap((entry) => {
572
- const path = at ? `${at}/${entry.name}` : entry.name;
573
- if (entry.isDirectory()) return routeFilesIn(dir, path);
574
- return ROUTE_FILE.test(entry.name) ? [path] : [];
575
- });
576
- }
577
- /** A route file's id below its folder: route groups and `route` files
578
- * resolved, flat `a.b` names read as folders. */
579
- function routeIdOf(file) {
580
- const segments = file.replace(ROUTE_FILE, "").split("/").filter((segment) => !/^\(.+\)$/.test(segment));
581
- if (segments.at(-1) === "route") segments.pop();
582
- return segments.join("/").replaceAll(".", "/");
583
- }
584
- /** Connect's `_app/` route files that a project file at the same id replaces. */
585
- function overriddenConnectRoutes(connectAppDir, projectAppDir) {
586
- const projectIds = new Set(routeFilesIn(projectAppDir).map(routeIdOf));
587
- return new Set(routeFilesIn(connectAppDir).filter((file) => projectIds.has(routeIdOf(file))));
588
- }
589
- const stemOf = (name) => name.replace(ROUTE_FILE, "");
590
- /** Mounts Connect's routes in `dir` without the `overridden` files: a folder
591
- * whole when none is in it, else file by file. */
592
- function mountConnectRoutes(routesDirectory, dir, overridden, prefix = "") {
593
- if (![...overridden].some((file) => file.startsWith(`${dir}/`))) return [physical(prefix, dir)];
594
- const entries = readdirSync(join(routesDirectory, dir), { withFileTypes: true }).filter((entry) => isRouteEntry(entry.name));
595
- const files = entries.filter((entry) => entry.isFile() && ROUTE_FILE.test(entry.name)).map((entry) => entry.name);
596
- const folders = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
597
- const at = (name) => prefix ? `${prefix}/${name}` : name;
598
- const nodes = [];
599
- for (const name of files) {
600
- const file = `${dir}/${name}`;
601
- const stem = stemOf(name);
602
- const folder = folders.includes(stem) ? `${dir}/${stem}` : void 0;
603
- if (overridden.has(file)) {
604
- if (folder) nodes.push(physical(at(stem), folder));
605
- continue;
606
- }
607
- const children = folder && mountConnectRoutes(routesDirectory, folder, overridden);
608
- if (stem === "index") nodes.push(prefix ? route(`${prefix}/`, file) : index(file));
609
- else if (!prefix && stem.startsWith("_")) nodes.push(layout(stem, file, children || []));
610
- else nodes.push(children ? route(at(stem), file, children) : route(at(stem), file));
611
- }
612
- for (const name of folders) {
613
- if (files.some((file) => stemOf(file) === name)) continue;
614
- nodes.push(...mountConnectRoutes(routesDirectory, `${dir}/${name}`, overridden, at(name)));
615
- }
616
- return nodes;
304
+ return nodes;
617
305
  }
618
306
  /** The routes a package offers other Connects, as `ph build` publishes them
619
307
  * (`./connect-routes`); generated beside the route tree. */
@@ -817,6 +505,376 @@ function connectRouterChunkGroups(routesDir) {
817
505
  ];
818
506
  }
819
507
  //#endregion
508
+ //#region connect-utils/vite-plugins/host-stylesheet.ts
509
+ /** The host's stylesheet, which may not exist yet: `style.css` beside its routes
510
+ * folder, so `hosts/connect/style.css` by default. `ph build` never reads it. */
511
+ function hostStylesheetPath(projectRoot, routesDir) {
512
+ const hostDir = routesDir ? dirname(routesDir) : join(projectRoot, dirname(HOST_ROUTES_DIR));
513
+ return join(hostDir, "style.css");
514
+ }
515
+ const importOf = (stylesheet, file) => `@import ${JSON.stringify(`./${normalizePath(relative(dirname(stylesheet), file))}`)};`;
516
+ /** The project's `style.css` with the host's stylesheet imported last when it
517
+ * exists (else `missing`), so the host's theme wins in the page's one build. */
518
+ function withHostStylesheet(css, stylesheet, hostStylesheet, missing) {
519
+ const file = hostStylesheet && existsSync(hostStylesheet) ? hostStylesheet : missing;
520
+ return file ? `${css}\n${importOf(stylesheet, file)}\n` : css;
521
+ }
522
+ /** Serves the project's `style.css` with the host's stylesheet in it. */
523
+ function hostStylesheetPlugin(projectRoot, hostStylesheet) {
524
+ const stylesheet = join(projectRoot, "style.css");
525
+ const stylesheetId = normalizePath(stylesheet);
526
+ const hostId = normalizePath(hostStylesheet);
527
+ let placeholder;
528
+ return {
529
+ name: "ph-host-stylesheet",
530
+ enforce: "pre",
531
+ configResolved(config) {
532
+ if (config.command !== "serve") return;
533
+ placeholder = join(config.cacheDir, "ph-host-stylesheet.css");
534
+ mkdirSync(dirname(placeholder), { recursive: true });
535
+ writeFileSync(placeholder, "/* Until the host's style.css exists. */\n");
536
+ },
537
+ load(id) {
538
+ if (normalizePath(id.split("?")[0]) !== stylesheetId) return null;
539
+ return withHostStylesheet(readFileSync(stylesheet, "utf8"), stylesheet, hostStylesheet, placeholder);
540
+ },
541
+ hotUpdate(ctx) {
542
+ if (normalizePath(ctx.file) !== hostId) return;
543
+ if (ctx.type === "create" && placeholder && existsSync(placeholder)) {
544
+ const now = /* @__PURE__ */ new Date();
545
+ utimesSync(placeholder, now, now);
546
+ }
547
+ const modules = this.environment.moduleGraph.getModulesByFile(stylesheetId);
548
+ return [...ctx.modules, ...modules ?? []];
549
+ }
550
+ };
551
+ }
552
+ //#endregion
553
+ //#region connect-utils/vite-plugins/app-shell.ts
554
+ /** On the prerendered shell's elements; marks an index.html that has it. */
555
+ const APP_SHELL_MARKER = "data-ph-shell";
556
+ /** In Connect's dist, and copied to a project's: the plugins that pick a shell. */
557
+ const SHELL_PLUGINS_FILE = "shell-plugins.json";
558
+ /** In a project's dist: every variant, for a server that swaps the shell to the served composition. */
559
+ const APP_SHELLS_FILE = "app-shells.json";
560
+ const SHELL_FILES = {
561
+ generic: "shell",
562
+ core: "shell-core"
563
+ };
564
+ /** The shell of the composition's first plugin that has one, else core's; no composition is classic.
565
+ * Without `plugins` (an older Connect): core for a composition, generic for classic. */
566
+ function appShellVariant(composition, plugins) {
567
+ if (!plugins) return composition ? "core" : "generic";
568
+ if (!composition) return Object.values(plugins)[0] ?? "core";
569
+ for (const { module } of composition) if (Object.hasOwn(plugins, module)) return plugins[module];
570
+ return "core";
571
+ }
572
+ function connectDistDir(projectRoot) {
573
+ try {
574
+ return join(dirname(resolvePackage("@powerhousedao/connect/package.json", projectRoot)), "dist");
575
+ } catch {
576
+ return;
577
+ }
578
+ }
579
+ /** The plugins' shell manifest in `dir`, if there is a valid one. */
580
+ function readShellPluginsIn(dir) {
581
+ const file = join(dir, SHELL_PLUGINS_FILE);
582
+ if (!existsSync(file)) return void 0;
583
+ try {
584
+ const manifest = JSON.parse(readFileSync(file, "utf8"));
585
+ if (!manifest || typeof manifest !== "object") return void 0;
586
+ const plugins = {};
587
+ for (const [module, variant] of Object.entries(manifest)) if (variant === "generic" || variant === "core") plugins[module] = variant;
588
+ return plugins;
589
+ } catch {
590
+ return;
591
+ }
592
+ }
593
+ /** The shell manifest of the installed Connect, if it ships one. */
594
+ function readShellPlugins(projectRoot) {
595
+ const distDir = connectDistDir(projectRoot);
596
+ return distDir ? readShellPluginsIn(distDir) : void 0;
597
+ }
598
+ /** The shell Connect's build prerendered, if the installed Connect ships one. */
599
+ function readAppShell(projectRoot, variant = "generic") {
600
+ const distDir = connectDistDir(projectRoot);
601
+ if (!distDir) return void 0;
602
+ const body = join(distDir, `${SHELL_FILES[variant]}.html`);
603
+ const head = join(distDir, `${SHELL_FILES[variant]}-head.html`);
604
+ if (!existsSync(body) || !existsSync(head)) return void 0;
605
+ return {
606
+ body: readFileSync(body, "utf8"),
607
+ head: readFileSync(head, "utf8")
608
+ };
609
+ }
610
+ /** Every variant the installed Connect ships. */
611
+ function readAppShells(projectRoot) {
612
+ const shells = {};
613
+ for (const variant of Object.keys(SHELL_FILES)) {
614
+ const shell = readAppShell(projectRoot, variant);
615
+ if (shell) shells[variant] = shell;
616
+ }
617
+ return shells;
618
+ }
619
+ /** On the boot-recovery script; its sessionStorage key guards against reload loops. */
620
+ const BOOT_RECOVER_MARKER = "data-ph-boot-recover";
621
+ const BOOT_RECOVER_KEY = "ph:sw-recover";
622
+ const BOOT_RECOVER_SCRIPT = `(function(){try{var K='${BOOT_RECOVER_KEY}',n=navigator.serviceWorker,done=0;if(!n||sessionStorage.getItem(K))return;var up=function(){return !document.querySelector('style[${APP_SHELL_MARKER}]')};var reload=function(){location.reload()};var skip=function(w){try{sessionStorage.setItem(K,'1')}catch(e){}n.addEventListener('controllerchange',reload);w.postMessage({type:'SKIP_WAITING'});setTimeout(reload,3000)};var watch=function(w){w.addEventListener('statechange',function(){if(w.state==='installed')skip(w)})};var go=function(){if(done||up())return;done=1;n.getRegistration().then(function(r){if(!r)return;if(r.waiting)return skip(r.waiting);if(r.installing)return watch(r.installing);r.addEventListener('updatefound',function(){if(r.installing)watch(r.installing)});return r.update()}).catch(function(){})};addEventListener('error',function(e){var t=e.target;if(e.error instanceof SyntaxError||e.error instanceof TypeError||(t&&t.tagName==='SCRIPT'))go()},true);addEventListener('unhandledrejection',function(e){if(e.reason instanceof SyntaxError||e.reason instanceof TypeError)go()});setTimeout(go,8000)}catch(e){}})();`;
623
+ /** Prefixes the shell's root-relative links with the deploy base. */
624
+ function rebaseShellLinks(body, base) {
625
+ if (base === "/" || !base) return body;
626
+ const prefix = base.endsWith("/") ? base : `${base}/`;
627
+ return body.replace(/(\shref=")\/(?!\/)/g, `$1${prefix}`);
628
+ }
629
+ const STYLESHEET_LINK = /<link\b(?=[^>]*\brel=["']?stylesheet\b)[^>]*>/gi;
630
+ function deferStylesheet(link) {
631
+ return `${link.replace(/\brel=["']?stylesheet["']?/i, "rel=\"preload\" as=\"style\"").replace(/\/?>$/, ` onload="this.onload=null;this.rel='stylesheet'">`)}<noscript>${link}</noscript>`;
632
+ }
633
+ const region = (name, content) => `<!--ph-shell:${name}-->${content}<!--/ph-shell:${name}-->`;
634
+ const REGION = (name) => new RegExp(`<!--ph-shell:${name}-->[\\s\\S]*?<!--/ph-shell:${name}-->`);
635
+ /** The app's title without `connect.branding.appName`; core's `appTitle` fallback. */
636
+ const DEFAULT_APP_NAME = "Connect";
637
+ const APP_NAME = /(<!--ph-shell:app-name-->)[\s\S]*?(<!--\/ph-shell:app-name-->)/g;
638
+ const escapeHtml = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
639
+ /** Fills the shell's app name as the app resolves it: the branding name, else the default. */
640
+ function withShellAppName(html, appName) {
641
+ const name = escapeHtml(appName || "Connect");
642
+ return html.replace(APP_NAME, (_m, open, close) => [
643
+ open,
644
+ name,
645
+ close
646
+ ].join(""));
647
+ }
648
+ /** Inlines `shell` into an empty `#root`, adds its critical CSS and, unless
649
+ * `deferStyles` is false, defers the stylesheets; React replaces the markup when the app renders. */
650
+ function injectAppShell(html, shell, base = "/", { deferStyles = true, appName } = {}) {
651
+ if (html.includes("data-ph-shell")) return html;
652
+ const root = /<div id="root"><\/div>/;
653
+ if (!root.test(html)) return html;
654
+ const firstSheet = html.search(STYLESHEET_LINK);
655
+ const at = firstSheet >= 0 ? firstSheet : html.indexOf("</head>");
656
+ const recover = `<script ${BOOT_RECOVER_MARKER}>${BOOT_RECOVER_SCRIPT}<\/script>`;
657
+ const body = withShellAppName(rebaseShellLinks(shell.body, base), appName);
658
+ const withHead = html.slice(0, at) + region("head", shell.head) + recover + html.slice(at);
659
+ return (deferStyles ? withHead.replace(STYLESHEET_LINK, deferStylesheet) : withHead).replace(root, () => `<div id="root">${region("body", body)}</div>`);
660
+ }
661
+ /** The variant an index.html carries, from its shell's marker value. */
662
+ function appShellVariantOf(html) {
663
+ const head = REGION("head").exec(html)?.[0];
664
+ const value = head && new RegExp(`data-ph-shell="(\\w+)"`).exec(head);
665
+ if (!value) return void 0;
666
+ return value[1] === "core" ? "core" : "generic";
667
+ }
668
+ /** Replaces the shell an index.html carries with `shell`, titled `appName`; a page without one is unchanged. */
669
+ function swapAppShell(html, shell, base = "/", appName) {
670
+ if (!REGION("head").test(html) || !REGION("body").test(html)) return html;
671
+ const body = withShellAppName(rebaseShellLinks(shell.body, base), appName);
672
+ return html.replace(REGION("head"), () => region("head", shell.head)).replace(REGION("body"), () => region("body", body));
673
+ }
674
+ const DEV_SHELL_WAIT_MS = 1e4;
675
+ async function renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet) {
676
+ const server = await createServer({
677
+ configFile: false,
678
+ root: projectRoot,
679
+ logLevel: "error",
680
+ appType: "custom",
681
+ server: {
682
+ middlewareMode: true,
683
+ hmr: false,
684
+ ws: false
685
+ },
686
+ oxc: { jsx: { runtime: "automatic" } },
687
+ resolve: {
688
+ alias: routeAliases,
689
+ dedupe: config.resolve.dedupe,
690
+ tsconfigPaths: true
691
+ },
692
+ define: config.define,
693
+ cacheDir: join(projectRoot, "node_modules/.vite-ph-prerender"),
694
+ optimizeDeps: {
695
+ noDiscovery: true,
696
+ include: [],
697
+ entries: []
698
+ },
699
+ ssr: { optimizeDeps: {
700
+ noDiscovery: true,
701
+ include: []
702
+ } }
703
+ });
704
+ try {
705
+ const renderer = await server.ssrLoadModule("@powerhousedao/connect/prerender");
706
+ const stylesheet = join(projectRoot, "style.css");
707
+ const css = withHostStylesheet(readFileSync(stylesheet, "utf8"), stylesheet, hostStylesheet);
708
+ return await renderer.renderProjectShells(stylesheet, css);
709
+ } finally {
710
+ await server.close();
711
+ }
712
+ }
713
+ const sourceText = (source) => typeof source === "string" ? source : new TextDecoder().decode(source);
714
+ /** Build: the composition's shell in #root and every variant in the dist, from
715
+ * the project's routes when it has them. Dev: the shell from the project's routes
716
+ * when it has them, else core's for a core composition. */
717
+ function connectAppShellPlugin(projectRoot, { composition, appName, routeAliases, routesDir, hostStylesheet } = {}) {
718
+ let variant = "generic";
719
+ let shells = {};
720
+ let shellPlugins;
721
+ let base = "/";
722
+ let isBuild = true;
723
+ let config;
724
+ const fromRoutes = () => isBuild && !!routeAliases;
725
+ const shell = () => {
726
+ if (fromRoutes()) return void 0;
727
+ return isBuild || variant === "core" ? shells[variant] : void 0;
728
+ };
729
+ let devShells;
730
+ let devRender;
731
+ const renderDevShells = () => {
732
+ if (!config || !routeAliases) return;
733
+ const logger = config.logger;
734
+ devShells = renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet).catch((error) => {
735
+ logger.warn(`[connect] the loading shell failed to render from the project's routes: ${String(error)}`);
736
+ return {};
737
+ });
738
+ };
739
+ const devShell = async () => {
740
+ if (!devShells) return void 0;
741
+ let timer;
742
+ const wait = new Promise((resolve) => {
743
+ timer = setTimeout(() => resolve(void 0), DEV_SHELL_WAIT_MS);
744
+ });
745
+ try {
746
+ return (await Promise.race([devShells, wait]))?.[variant];
747
+ } finally {
748
+ clearTimeout(timer);
749
+ }
750
+ };
751
+ return {
752
+ name: "ph-connect-app-shell",
753
+ configureServer(server) {
754
+ if (!routeAliases) return;
755
+ renderDevShells();
756
+ const stylesheet = join(projectRoot, "style.css");
757
+ const rerender = (file) => {
758
+ if (!(file === stylesheet || file === hostStylesheet || !!routesDir && file.startsWith(`${routesDir}${sep}`))) return;
759
+ clearTimeout(devRender);
760
+ devRender = setTimeout(renderDevShells, 300);
761
+ };
762
+ server.watcher.on("change", rerender);
763
+ server.watcher.on("add", rerender);
764
+ server.watcher.on("unlink", rerender);
765
+ },
766
+ configResolved(resolved) {
767
+ config = resolved;
768
+ base = resolved.base;
769
+ isBuild = resolved.command === "build";
770
+ shells = readAppShells(projectRoot);
771
+ shellPlugins = readShellPlugins(projectRoot);
772
+ variant = appShellVariant(composition, shellPlugins);
773
+ },
774
+ transformIndexHtml: {
775
+ order: "post",
776
+ handler: async (html) => {
777
+ const current = !isBuild && routeAliases ? await devShell() : shell();
778
+ return current ? injectAppShell(html, current, base, {
779
+ deferStyles: isBuild,
780
+ appName
781
+ }) : html;
782
+ }
783
+ },
784
+ generateBundle: {
785
+ order: "post",
786
+ async handler(_options, bundle) {
787
+ if (!isBuild) return;
788
+ if (fromRoutes() && config && routeAliases) {
789
+ shells = await renderProjectAppShells(projectRoot, config, routeAliases, hostStylesheet);
790
+ const index = bundle["index.html"];
791
+ const current = shells[variant];
792
+ if (index?.type === "asset" && current) index.source = injectAppShell(sourceText(index.source), current, base, { appName });
793
+ }
794
+ if (!Object.keys(shells).length) return;
795
+ this.emitFile({
796
+ type: "asset",
797
+ fileName: APP_SHELLS_FILE,
798
+ source: JSON.stringify(shells)
799
+ });
800
+ if (shellPlugins) this.emitFile({
801
+ type: "asset",
802
+ fileName: SHELL_PLUGINS_FILE,
803
+ source: JSON.stringify(shellPlugins)
804
+ });
805
+ }
806
+ }
807
+ };
808
+ }
809
+ //#endregion
810
+ //#region connect-utils/vite-plugins/build-hash.ts
811
+ /** Name of the build-identity file emitted into the build output. */
812
+ const BUILD_HASH_FILE = "build-hash.json";
813
+ /**
814
+ * Deterministic identity of a Connect build. Differs whenever the deployed
815
+ * content differs (published Connect version, project config, package list,
816
+ * build options) so the SPA can detect "the server is serving a different
817
+ * build than the one this bundle was built from" by comparing its baked copy
818
+ * (define `PH_CONNECT_BUILD_HASH`) to `build-hash.json`, which the build
819
+ * emits alongside the app and the server must serve no-cache.
820
+ */
821
+ function computeBuildHash(input) {
822
+ return createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 16);
823
+ }
824
+ /**
825
+ * Read the installed @powerhousedao/connect version. The package's `exports`
826
+ * map does not expose a `./package.json` subpath, so `require.resolve(
827
+ * "…/package.json")` throws — resolve the main entry and walk up to the
828
+ * package root instead.
829
+ */
830
+ function readConnectVersion(projectRoot) {
831
+ try {
832
+ const entry = createRequire(join(projectRoot, "package.json")).resolve("@powerhousedao/connect", { paths: [projectRoot] });
833
+ let dir = dirname(entry);
834
+ for (;;) {
835
+ try {
836
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
837
+ if (pkg.name === "@powerhousedao/connect") return pkg.version ?? "unknown";
838
+ } catch {}
839
+ const parent = dirname(dir);
840
+ if (parent === dir) break;
841
+ dir = parent;
842
+ }
843
+ } catch {}
844
+ return "unknown";
845
+ }
846
+ function buildHashFromBuildOptions(options) {
847
+ return computeBuildHash({
848
+ workspaceGitSha: process.env.WORKSPACE_GIT_SHA ?? "",
849
+ workspaceVersion: process.env.WORKSPACE_VERSION ?? "",
850
+ connectPackageVersion: readConnectVersion(options.dirname),
851
+ projectConfig: options.phConfig,
852
+ packages: options.packages.map((p) => `${p.packageName}@${p.version ?? ""}:${p.provider ?? ""}`),
853
+ connectBasePath: options.connectBasePath ?? "",
854
+ offlineEnabled: options.offlineEnabled,
855
+ packageRegistryUrl: options.packageRegistryUrl ?? ""
856
+ });
857
+ }
858
+ /**
859
+ * Emits `build-hash.json` (`{"hash": "<build id>"}`) into the build output.
860
+ * Emitted as an asset so it lands at the deploy base like every other file.
861
+ * Build-only: dev (studio) never runs generateBundle, and the SPA check
862
+ * treats a missing file as "nothing to compare" and stays silent.
863
+ */
864
+ function connectBuildHashPlugin(buildHash) {
865
+ return {
866
+ name: "ph-connect-build-hash",
867
+ apply: "build",
868
+ generateBundle() {
869
+ this.emitFile({
870
+ type: "asset",
871
+ fileName: BUILD_HASH_FILE,
872
+ source: `${JSON.stringify({ hash: buildHash }, null, 2)}\n`
873
+ });
874
+ }
875
+ };
876
+ }
877
+ //#endregion
820
878
  //#region connect-utils/vite-plugins/dynamic-base.ts
821
879
  /**
822
880
  * Global the runtime (ph-clint proxy) must set before the entry bundle loads.
@@ -3759,6 +3817,7 @@ function getConnectBaseViteConfig(options) {
3759
3817
  }).filter((p) => p !== null);
3760
3818
  const routesDir = resolveConnectRoutesDir(options.dirname, options.routes) ?? false;
3761
3819
  const routes = connectRoutes(options.dirname, routesDir);
3820
+ const hostStylesheet = hostStylesheetPath(options.dirname, routesDir);
3762
3821
  return {
3763
3822
  configFile: false,
3764
3823
  mode,
@@ -3796,6 +3855,7 @@ function getConnectBaseViteConfig(options) {
3796
3855
  },
3797
3856
  plugins: [
3798
3857
  configPlugin,
3858
+ hostStylesheetPlugin(options.dirname, hostStylesheet),
3799
3859
  phBundledPackagesPlugin({
3800
3860
  packages: localPackagesFromConfig,
3801
3861
  projectRoot: options.dirname
@@ -3816,7 +3876,8 @@ function getConnectBaseViteConfig(options) {
3816
3876
  composition: servedConnect.composition,
3817
3877
  appName: servedConnect.branding?.appName,
3818
3878
  routeAliases: routesDir ? routes.aliases : void 0,
3819
- routesDir: routesDir || void 0
3879
+ routesDir: routesDir || void 0,
3880
+ hostStylesheet
3820
3881
  }),
3821
3882
  connectBuildHashPlugin(buildHash),
3822
3883
  ...options.dynamicBase ? [connectDynamicBasePlugin()] : [],
@@ -3836,6 +3897,6 @@ function getConnectBaseViteConfig(options) {
3836
3897
  };
3837
3898
  }
3838
3899
  //#endregion
3839
- export { APP_LAYOUT, APP_SHELLS_FILE, APP_SHELL_MARKER, BOOT_RECOVER_KEY, BOOT_RECOVER_MARKER, BOOT_RECOVER_SCRIPT, BUILDER_TOOLS_VERSION, BUILD_HASH_FILE, CONNECT_ROUTES_GEN, CONNECT_ROUTES_SPECIFIER, CORE_ROUTE_TREE_SPECIFIER, DEFAULT_APP_NAME, DEFAULT_CONNECT_OUTDIR, DEFAULT_VENDOR_INCLUDE, DYNAMIC_BASE_PLACEHOLDER, EXTERNAL_PACKAGES_IMPORT, HOST_ROUTES_DIR, IMPORT_SCRIPT_FILE, LOCAL_PACKAGE_ID, LOCK_STALE_MS, PACKAGE_ROUTES_MODULE, PH_DIR_NAME, REACTOR_WORKER_ENTRY, REACTOR_WORKER_MIME, REACTOR_WORKER_URL_PREFIX, ROUTE_TREE_SPECIFIER, RUNTIME_CONFIG_SCHEMA_ID, RUNTIME_CONFIG_SCHEMA_URL, SHELL_PLUGINS_FILE, THEME_BOOT_MARKER, VENDOR_EXTERNAL, VENDOR_SKIP_SUBPATHS, VENDOR_URL_PREFIX, WORKER_PACKAGES_MANIFEST, acquireLock, appShellVariant, appShellVariantOf, appendToHtmlHead, backupIndexHtml, buildHashFromBuildOptions, computeBuildHash, computeSourceDigest, connectAppShellPlugin, connectBuildHashPlugin, connectDynamicBasePlugin, connectRouterChunkGroups, connectRoutes, connectRoutesDirOf, connectRoutesGeneratorConfig, connectRoutesTreeOf, connectThemeBootPlugin, copyConnect, directoryContentDigest, distDirFingerprint, ensureNodeVersion, escapeForRegExp, findBundleSpecifierOffenders, findDisallowedSpecifiers, findPackageRoot, findWorkerUnsafeMarkers, generateConnectRoutes, getConnectBaseViteConfig, getConnectHtmlTags, injectAppShell, linkedBuildStamp, makeImportScriptFromPackages, missingVendorEntries, overriddenConnectRoutes, ownProjectPackage, phConfigPlugin, prebuildConnectVendor, prebuildReactorWorker, prebuildWorkerPackages, prependToHtmlHead, publishDirAtomic, readAppShell, readAppShells, readJsonFile, readShellPlugins, readShellPluginsIn, rebaseShellLinks, relativeCssUrls, releaseLock, removeBase64EnvValues, resolveConnectBundle, resolveConnectPackageJson, resolveConnectPublicDir, resolveConnectRoutesDir, resolveOwnDeps, resolveOwnPackageVersion, resolvePackage, resolveReactorWorkerSource, resolveVersionDigest, resolveViteConfigPath, resolveWorkspacePackageDir, routeIdOf, runShellScriptPlugin, runTsc, runWorkerBuildEntries, runtimeConfigSchema, stripVersionFromPackage, swapAppShell, syncConnectRoutes, upstreamWorkerPackages, vendorImportMapPlugin, vendorRelativePath, withAppTitle, withShellAppName, withVendorBase, workerSafeVendorImports };
3900
+ export { APP_LAYOUT, APP_SHELLS_FILE, APP_SHELL_MARKER, BOOT_RECOVER_KEY, BOOT_RECOVER_MARKER, BOOT_RECOVER_SCRIPT, BUILDER_TOOLS_VERSION, BUILD_HASH_FILE, CONNECT_ROUTES_GEN, CONNECT_ROUTES_SPECIFIER, CORE_ROUTE_TREE_SPECIFIER, DEFAULT_APP_NAME, DEFAULT_CONNECT_OUTDIR, DEFAULT_VENDOR_INCLUDE, DYNAMIC_BASE_PLACEHOLDER, EXTERNAL_PACKAGES_IMPORT, HOST_ROUTES_DIR, IMPORT_SCRIPT_FILE, LOCAL_PACKAGE_ID, LOCK_STALE_MS, PACKAGE_ROUTES_MODULE, PH_DIR_NAME, REACTOR_WORKER_ENTRY, REACTOR_WORKER_MIME, REACTOR_WORKER_URL_PREFIX, ROUTE_TREE_SPECIFIER, RUNTIME_CONFIG_SCHEMA_ID, RUNTIME_CONFIG_SCHEMA_URL, SHELL_PLUGINS_FILE, THEME_BOOT_MARKER, VENDOR_EXTERNAL, VENDOR_SKIP_SUBPATHS, VENDOR_URL_PREFIX, WORKER_PACKAGES_MANIFEST, acquireLock, appShellVariant, appShellVariantOf, appendToHtmlHead, backupIndexHtml, buildHashFromBuildOptions, computeBuildHash, computeSourceDigest, connectAppShellPlugin, connectBuildHashPlugin, connectDynamicBasePlugin, connectRouterChunkGroups, connectRoutes, connectRoutesDirOf, connectRoutesGeneratorConfig, connectRoutesTreeOf, connectThemeBootPlugin, copyConnect, directoryContentDigest, distDirFingerprint, ensureNodeVersion, escapeForRegExp, findBundleSpecifierOffenders, findDisallowedSpecifiers, findPackageRoot, findWorkerUnsafeMarkers, generateConnectRoutes, getConnectBaseViteConfig, getConnectHtmlTags, hostStylesheetPath, hostStylesheetPlugin, injectAppShell, linkedBuildStamp, makeImportScriptFromPackages, missingVendorEntries, overriddenConnectRoutes, ownProjectPackage, phConfigPlugin, prebuildConnectVendor, prebuildReactorWorker, prebuildWorkerPackages, prependToHtmlHead, publishDirAtomic, readAppShell, readAppShells, readJsonFile, readShellPlugins, readShellPluginsIn, rebaseShellLinks, relativeCssUrls, releaseLock, removeBase64EnvValues, resolveConnectBundle, resolveConnectPackageJson, resolveConnectPublicDir, resolveConnectRoutesDir, resolveOwnDeps, resolveOwnPackageVersion, resolvePackage, resolveReactorWorkerSource, resolveVersionDigest, resolveViteConfigPath, resolveWorkspacePackageDir, routeIdOf, runShellScriptPlugin, runTsc, runWorkerBuildEntries, runtimeConfigSchema, stripVersionFromPackage, swapAppShell, syncConnectRoutes, upstreamWorkerPackages, vendorImportMapPlugin, vendorRelativePath, withAppTitle, withHostStylesheet, withShellAppName, withVendorBase, workerSafeVendorImports };
3840
3901
 
3841
3902
  //# sourceMappingURL=index.mjs.map