@powerhousedao/desktop 6.2.3-dev.88 → 6.2.3-dev.90

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.
@@ -4,8 +4,9 @@ import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { z } from "zod";
6
6
  import { execSync, spawn, spawnSync } from "node:child_process";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import { normalizePluginEntries } from "@powerhousedao/host-core";
7
9
  import { isPassthroughImageRef } from "@powerhousedao/shared/connect/image-ref";
8
- import { pathToFileURL } from "node:url";
9
10
  //#region src/app-json.ts
10
11
  /**
11
12
  * `hosts/desktop/app.json` — the builder's desktop identity (phase 7, mode 1:
@@ -107,6 +108,10 @@ const shellSourceSchema = z.strictObject({
107
108
  const appJsonSchema = z.strictObject({
108
109
  identifier: identifierSchema,
109
110
  productName: z.string().min(1),
111
+ /** Ask who is using the app before anything runs: the stack then starts for
112
+ * that identity, with its own folder and as its admin. Off, the stack starts
113
+ * with the window, in one store. */
114
+ signIn: z.boolean().nullable().optional(),
110
115
  /** Single source image (square PNG, 1024×1024 recommended); the icon set
111
116
  * for every platform is generated from it via `tauri icon`. */
112
117
  icon: z.string().min(1),
@@ -171,11 +176,74 @@ function appSlug(app) {
171
176
  * package.json minimal, names the project
172
177
  * dist/ the package's build (ph build)
173
178
  * .ph/connect-build/dist/ the BUILT Connect (ph run connect build)
174
- * node_modules/ vendored @powerhousedao/ph-cli (hoisted,
179
+ * node_modules/ vendored @powerhousedao/ph-run (hoisted,
175
180
  * real files — computed-specifier imports and
176
181
  * PGlite wasm forbid bundling)
177
182
  */
178
183
  const CONNECT_BUILD_DIR = path.join(".ph", "connect-build", "dist");
184
+ const BROWSER_ONLY_IN_DIST = [
185
+ "__react__",
186
+ "__reactor_worker__",
187
+ "__vendor__",
188
+ "assets",
189
+ "browser"
190
+ ];
191
+ /** The package a module specifier belongs to. */
192
+ function packageOf$1(specifier) {
193
+ return specifier.split("/").slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
194
+ }
195
+ /** The packages to ship for a host's plugins. One that doesn't resolve is a
196
+ * browser built-in of Connect's, already in the built app, and resolves no
197
+ * better in the stack (host-core's plugins-resolve). */
198
+ function pluginPackagesOf(entries, where, resolves) {
199
+ return normalizePluginEntries(entries, where).filter((entry) => entry.enabled && !entry.module.startsWith(".")).filter((entry) => resolves(entry.module)).map((entry) => packageOf$1(entry.module));
200
+ }
201
+ /** Where a stack keeps the OAuth clients its config names. */
202
+ const OAUTH_CLIENTS_DIR = "oauth";
203
+ /** Where a stack keeps the AI demo key its config names. */
204
+ const AI_DIR = "ai";
205
+ /**
206
+ * The project's config, with its OAuth clients made the app's own. They sit
207
+ * outside the project, so a packaged app would find nothing at those paths. A
208
+ * desktop client ships with the app: it can't keep its secret, so sign-ins
209
+ * always use PKCE. A web client belongs to a server and never leaves the machine.
210
+ */
211
+ function stageConfig(projectRoot, stackDir, log) {
212
+ const source = path.join(projectRoot, "powerhouse.config.json");
213
+ if (!fs.existsSync(source)) return;
214
+ const config = JSON.parse(fs.readFileSync(source, "utf8"));
215
+ if (config.ai?.demoKeyFile) {
216
+ const from = path.resolve(projectRoot, config.ai.demoKeyFile);
217
+ delete config.ai.demoKeyFile;
218
+ if (fs.existsSync(from)) {
219
+ const file = path.basename(from);
220
+ fs.mkdirSync(path.join(stackDir, AI_DIR), { recursive: true });
221
+ fs.copyFileSync(from, path.join(stackDir, AI_DIR, file));
222
+ config.ai.demoKeyFile = `./${AI_DIR}/${file}`;
223
+ log(" AI demo key staged");
224
+ } else log(" no AI demo key: this build won't offer one");
225
+ }
226
+ for (const app of config.workflows?.oauthApps ?? []) {
227
+ if (!app.clients) continue;
228
+ const desktop = app.clients.desktop;
229
+ const from = desktop && path.resolve(projectRoot, desktop);
230
+ app.clients = {};
231
+ if (!from || !fs.existsSync(from)) {
232
+ log(` oauth app ${app.id}: no desktop client, so it can't sign in`);
233
+ continue;
234
+ }
235
+ const file = path.basename(from);
236
+ fs.mkdirSync(path.join(stackDir, OAUTH_CLIENTS_DIR), { recursive: true });
237
+ fs.copyFileSync(from, path.join(stackDir, OAUTH_CLIENTS_DIR, file));
238
+ app.clients.desktop = `./${OAUTH_CLIENTS_DIR}/${file}`;
239
+ log(` oauth app ${app.id}: desktop client staged`);
240
+ }
241
+ fs.writeFileSync(path.join(stackDir, "powerhouse.config.json"), `${JSON.stringify(config, null, 2)}
242
+ `);
243
+ }
244
+ /** What runs a stack: `ph run` without the tools that build one, which is
245
+ * most of ph-cli's dependencies. */
246
+ const RUN_PACKAGE = "@powerhousedao/ph-run";
179
247
  function copyIfExists(from, to) {
180
248
  if (!fs.existsSync(from)) return false;
181
249
  fs.cpSync(from, to, { recursive: true });
@@ -212,9 +280,10 @@ function readLocalPackages(dir) {
212
280
  const tarball = path.join(root, file);
213
281
  const manifest = spawnSync("tar", [
214
282
  "-xzOf",
215
- tarball,
283
+ file,
216
284
  "package/package.json"
217
285
  ], {
286
+ cwd: root,
218
287
  encoding: "utf8",
219
288
  windowsHide: true
220
289
  });
@@ -233,13 +302,15 @@ function readLocalPackages(dir) {
233
302
  function stackManifest(options) {
234
303
  const local = options.local ?? {};
235
304
  const spec = (pkg, fallback) => local[pkg] ?? fallback;
305
+ const plugins = (options.plugins ?? []).map((pkg) => [pkg, spec(pkg, options.version)]);
236
306
  return {
237
307
  name: options.name,
238
308
  private: true,
239
309
  type: "module",
240
310
  dependencies: {
241
- "@powerhousedao/ph-cli": spec("@powerhousedao/ph-cli", options.phCliSpec ?? options.version),
242
- "@powerhousedao/host-core": spec("@powerhousedao/host-core", options.version)
311
+ [RUN_PACKAGE]: spec(RUN_PACKAGE, options.phCliSpec ?? options.version),
312
+ "@powerhousedao/host-core": spec("@powerhousedao/host-core", options.version),
313
+ ...Object.fromEntries(plugins)
243
314
  },
244
315
  ...Object.keys(local).length > 0 ? { overrides: local } : {}
245
316
  };
@@ -250,6 +321,42 @@ function vendoredFromLocal(stackDir) {
250
321
  const lock = path.join(stackDir, "package-lock.json");
251
322
  return fs.existsSync(lock) && fs.readFileSync(lock, "utf8").includes("\"resolved\": \"file:");
252
323
  }
324
+ /** Types and source maps, which nothing reads at runtime. */
325
+ const UNREAD_FILE = /\.(d\.[cm]?ts|map)$/i;
326
+ const TEST_FILE = /\.(test|spec)\.[cm]?[jt]sx?$/;
327
+ /** Licences stay, as the packages' terms ask. */
328
+ const PACKAGE_NOTES = /^(readme|changelog|history)(\..*)?$/i;
329
+ /**
330
+ * Removes what a running app never reads. Windows creates and scans each file
331
+ * on its own, so these, over half the stack, were over half the install.
332
+ *
333
+ * @returns How many files went
334
+ */
335
+ function pruneStack(dir, inPackages = false) {
336
+ let removed = 0;
337
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
338
+ const full = path.join(dir, entry.name);
339
+ if (entry.isDirectory()) {
340
+ if (entry.name === "__tests__") {
341
+ removed += fs.readdirSync(full, {
342
+ recursive: true,
343
+ withFileTypes: true
344
+ }).filter((file) => file.isFile()).length;
345
+ fs.rmSync(full, {
346
+ recursive: true,
347
+ force: true
348
+ });
349
+ continue;
350
+ }
351
+ removed += pruneStack(full, inPackages || entry.name === "node_modules");
352
+ if (fs.readdirSync(full).length === 0) fs.rmdirSync(full);
353
+ } else if (entry.isFile() && (UNREAD_FILE.test(entry.name) || TEST_FILE.test(entry.name) || inPackages && PACKAGE_NOTES.test(entry.name))) {
354
+ fs.rmSync(full);
355
+ removed++;
356
+ }
357
+ }
358
+ return removed;
359
+ }
253
360
  function bundleStack(options) {
254
361
  const log = options.logger ?? console.log;
255
362
  const stackDir = path.join(options.shellProjectDir, "dist-stack");
@@ -258,6 +365,8 @@ function bundleStack(options) {
258
365
  "agents",
259
366
  "dist",
260
367
  ".ph",
368
+ OAUTH_CLIENTS_DIR,
369
+ AI_DIR,
261
370
  "powerhouse.config.json",
262
371
  "package.json"
263
372
  ]) fs.rmSync(path.join(stackDir, entry), {
@@ -266,11 +375,17 @@ function bundleStack(options) {
266
375
  });
267
376
  fs.mkdirSync(stackDir, { recursive: true });
268
377
  log(` hosts/ ${copyDirFiltered(path.join(options.projectRoot, "hosts"), path.join(stackDir, "hosts"), options.excludeDirs ?? []) ? "staged" : "absent — skipped"}`);
378
+ const localKey = fileURLToPath(new URL("./local-key/local-key.mjs", import.meta.url));
379
+ if (fs.existsSync(localKey)) fs.copyFileSync(localKey, path.join(stackDir, "local-key.mjs"));
269
380
  for (const dir of [
270
381
  "agents",
271
382
  "dist",
272
383
  CONNECT_BUILD_DIR
273
384
  ]) log(` ${dir}/ ${copyIfExists(path.join(options.projectRoot, dir), path.join(stackDir, dir)) ? "staged" : "absent — skipped"}`);
385
+ for (const dir of BROWSER_ONLY_IN_DIST) fs.rmSync(path.join(stackDir, "dist", dir), {
386
+ recursive: true,
387
+ force: true
388
+ });
274
389
  const stagedDesktopHost = path.join(stackDir, "hosts", "desktop", "host.js");
275
390
  if (fs.existsSync(stagedDesktopHost)) {
276
391
  const source = fs.readFileSync(stagedDesktopHost, "utf8");
@@ -279,7 +394,7 @@ function bundleStack(options) {
279
394
  log(" hosts/desktop/host.js: runner rewritten to the generic compound (staged copy)");
280
395
  }
281
396
  }
282
- copyIfExists(path.join(options.projectRoot, "powerhouse.config.json"), path.join(stackDir, "powerhouse.config.json"));
397
+ stageConfig(options.projectRoot, stackDir, log);
283
398
  if (typeof options.connectPort === "number") {
284
399
  fs.writeFileSync(path.join(stackDir, "shell.json"), `${JSON.stringify({ connectPort: options.connectPort }, null, 2)}\n`);
285
400
  log(` shell.json: connectPort ${options.connectPort}`);
@@ -287,26 +402,38 @@ function bundleStack(options) {
287
402
  const sourcePkg = JSON.parse(fs.readFileSync(path.join(options.projectRoot, "package.json"), "utf8"));
288
403
  const version = options.phCliVersion ?? "dev";
289
404
  const name = sourcePkg.name ?? "powerhouse-desktop-stack";
405
+ const project = {
406
+ ...sourcePkg.version ? { version: sourcePkg.version } : {},
407
+ ...sourcePkg.exports ? { exports: sourcePkg.exports } : {}
408
+ };
290
409
  const vendor = options.vendor !== false;
291
410
  const local = options.localPackagesDir ? readLocalPackages(options.localPackagesDir) : void 0;
292
411
  if (vendor && (local || vendoredFromLocal(stackDir))) for (const entry of ["node_modules", "package-lock.json"]) fs.rmSync(path.join(stackDir, entry), {
293
412
  recursive: true,
294
413
  force: true
295
414
  });
296
- fs.writeFileSync(path.join(stackDir, "package.json"), `${JSON.stringify(local ? stackManifest({
297
- name,
298
- version,
299
- phCliSpec: options.phCliSpec,
300
- local
301
- }) : {
302
- name,
303
- private: true,
304
- type: "module",
305
- dependencies: { "@powerhousedao/ph-cli": version }
415
+ fs.writeFileSync(path.join(stackDir, "package.json"), `${JSON.stringify({
416
+ ...local ? stackManifest({
417
+ name,
418
+ version,
419
+ phCliSpec: options.phCliSpec,
420
+ local,
421
+ plugins: options.plugins
422
+ }) : {
423
+ name,
424
+ private: true,
425
+ type: "module",
426
+ dependencies: { [RUN_PACKAGE]: version }
427
+ },
428
+ ...project
306
429
  }, null, 2)}\n`);
307
430
  let vendored = false;
308
431
  if (vendor) {
309
- const specs = local ? "" : `"${options.phCliSpec ?? `@powerhousedao/ph-cli@${version}`}" "@powerhousedao/host-core@${version}"`;
432
+ const specs = local ? "" : [
433
+ options.phCliSpec ?? `${RUN_PACKAGE}@${version}`,
434
+ `@powerhousedao/host-core@${version}`,
435
+ ...(options.plugins ?? []).map((pkg) => `${pkg}@${version}`)
436
+ ].map((spec) => `"${spec}"`).join(" ");
310
437
  log(local ? ` vendoring ${Object.keys(local).length} local packages from ${options.localPackagesDir} (hoisted, real files)…` : ` vendoring ${specs} (hoisted, real files)…`);
311
438
  const result = spawnSync(`npm install ${specs} --install-strategy=hoisted --omit=dev --no-audit --no-fund`, {
312
439
  cwd: stackDir,
@@ -317,6 +444,7 @@ function bundleStack(options) {
317
444
  if (result.status !== 0) throw new Error(`bundle-stack: vendoring failed (${result.status}):\n${result.stderr.toString().slice(-800)}`);
318
445
  vendored = true;
319
446
  } else log(" vendoring skipped (vendor: false) — existing tree left in place");
447
+ log(` ${pruneStack(stackDir)} files a running app never reads removed`);
320
448
  return {
321
449
  stackDir,
322
450
  vendored
@@ -409,11 +537,28 @@ fn main() {
409
537
  "take_launch_files",
410
538
  "read_launch_file",
411
539
  "log_from_webview",
540
+ "open_external",
541
+ "desktop_state",
542
+ "pick_root",
543
+ "save_renown_url",
544
+ "local_create",
545
+ "local_unlock",
546
+ "saved_credential",
547
+ "save_profile",
548
+ "adopt_old_data",
549
+ "start_stack",
550
+ "switch_identity",
412
551
  ]),
413
552
  ))
414
553
  .expect("failed to run tauri-build");
415
554
  }
416
555
  `;
556
+ /** The sign-in page's script (app.json `signIn`), beside the page. */
557
+ const SIGN_IN_SCRIPT = "sign-in.js";
558
+ /** That script as this package built it (tsdown.config.ts). */
559
+ function builtSignInScript() {
560
+ return fs.readFileSync(fileURLToPath(new URL(`./sign-in/${SIGN_IN_SCRIPT}`, import.meta.url)));
561
+ }
417
562
  /** The loading page's logo: app.json's icon SOURCE (1024² recommended), copied
418
563
  * beside ui/index.html — not one of the downsampled `tauri icon` outputs, so
419
564
  * it stays sharp on HiDPI screens. Generated, like the rest of ui/. */
@@ -425,7 +570,43 @@ const LOADING_SPLASH = "splash.png";
425
570
  const LOADING_SPLASH_DARK = "splash-dark.png";
426
571
  /** CSS size of the logo; the 1024² source keeps it crisp up to 8x DPR. */
427
572
  const LOGO_CSS_PX = 128;
428
- function loadingHtml(app, art) {
573
+ /** The sign-in page's own look, on the loading page's colours. */
574
+ const SIGN_IN_CSS = `
575
+ body { overflow: auto; height: auto; min-height: 100vh; }
576
+ #sign-in {
577
+ position: relative; z-index: 1; box-sizing: border-box;
578
+ width: min(420px, calc(100vw - 32px)); margin: 24px 0; padding: 32px;
579
+ display: flex; flex-direction: column; gap: 12px; text-align: left;
580
+ background: color-mix(in srgb, var(--bg) 92%, var(--fg));
581
+ border: 1px solid color-mix(in srgb, var(--fg) 14%, transparent);
582
+ border-radius: 14px;
583
+ }
584
+ #sign-in h1 { margin: 0 0 8px; font-size: 24px; line-height: 1.2; font-weight: 600; }
585
+ #sign-in p { margin: 0; }
586
+ #sign-in small { opacity: .7; }
587
+ #sign-in button, #sign-in input {
588
+ font: inherit; color: inherit; border-radius: 8px; padding: 10px 14px;
589
+ border: 1px solid color-mix(in srgb, var(--fg) 22%, transparent);
590
+ background: transparent; box-sizing: border-box; width: 100%;
591
+ }
592
+ #sign-in button { cursor: pointer; }
593
+ #sign-in button.primary { background: var(--accent); border-color: var(--accent); color: var(--bg); font-weight: 600; }
594
+ #sign-in button.link { width: auto; padding: 0; border: 0; text-decoration: underline; }
595
+ #sign-in label { display: grid; gap: 4px; }
596
+ #sign-in details { font-size: 14px; display: grid; gap: 8px; }
597
+ #sign-in .folder { font-size: 13px; overflow-wrap: anywhere; }
598
+ #sign-in .notice { padding: 10px 12px; border-radius: 8px; font-size: 14px; background: color-mix(in srgb, var(--accent) 16%, transparent); }
599
+ #sign-in .identities { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
600
+ #sign-in .identity { display: flex; gap: 12px; align-items: center; text-align: left; }
601
+ #sign-in .identity img, #sign-in .initial {
602
+ width: 36px; height: 36px; border-radius: 50%; object-fit: cover; flex: none;
603
+ display: grid; place-items: center; font-weight: 600;
604
+ background: color-mix(in srgb, var(--accent) 30%, transparent);
605
+ }
606
+ #sign-in .identity b, #sign-in .identity small { display: block; }
607
+ #sign-in .busy { display: flex; align-items: center; justify-content: center; }
608
+ #sign-in:has(> .busy) { background: none; border: 0; }`;
609
+ function loadingHtml(app, art, signIn = false) {
429
610
  const escape = (text) => text.replace(/[<&]/g, (c) => c === "<" ? "&lt;" : "&amp;");
430
611
  const name = escape(app.productName);
431
612
  const loading = app.loading;
@@ -503,13 +684,14 @@ function loadingHtml(app, art) {
503
684
  animation: pulse 1.2s ease-in-out infinite;
504
685
  }
505
686
  @keyframes pulse { 0%,100% { opacity: .35 } 50% { opacity: 1 } }
506
- @media (prefers-reduced-motion: reduce) { .dot { animation: none; } }
687
+ @media (prefers-reduced-motion: reduce) { .dot { animation: none; } }${signIn ? SIGN_IN_CSS : ""}
507
688
  </style>
508
689
  </head>
509
690
  <body>
510
- <div class="box">
691
+ ${signIn ? `<main id="sign-in"></main>
692
+ <script type="module" src="./sign-in.js"><\/script>` : `<div class="box">
511
693
  ${logoTag}<div><span class="dot"></span>${message}</div>
512
- </div>
694
+ </div>`}
513
695
  ${layersTag}${cornerTag}</body>
514
696
  </html>
515
697
  `;
@@ -605,7 +787,18 @@ function connectCapability(connectPort) {
605
787
  permissions: [
606
788
  "allow-take-launch-files",
607
789
  "allow-read-launch-file",
608
- "allow-log-from-webview"
790
+ "allow-log-from-webview",
791
+ "allow-open-external",
792
+ "allow-desktop-state",
793
+ "allow-pick-root",
794
+ "allow-save-renown-url",
795
+ "allow-local-create",
796
+ "allow-local-unlock",
797
+ "allow-saved-credential",
798
+ "allow-save-profile",
799
+ "allow-adopt-old-data",
800
+ "allow-start-stack",
801
+ "allow-switch-identity"
609
802
  ]
610
803
  }, null, 2) + "\n";
611
804
  }
@@ -619,6 +812,7 @@ const GITIGNORE = `# Generated tauri shell — only Cargo.lock and app-icon.png
619
812
  /ui/art.*
620
813
  /ui/art-dark.*
621
814
  /ui/bg-*
815
+ /ui/sign-in.*
622
816
  /dist-stack
623
817
  /binaries
624
818
  `;
@@ -707,9 +901,18 @@ function projectShell(input) {
707
901
  [".gitignore", GITIGNORE],
708
902
  ["dist-stack/README.md", DIST_STACK_README]
709
903
  ];
904
+ if (app.signIn) files.push(["ui/sign-in.html", loadingHtml(app, art, true)]);
710
905
  let changed = false;
711
906
  for (const [rel, content] of files) if (writeIfChanged(path.join(shellDir, rel), content)) changed = true;
907
+ if (!app.signIn) for (const file of ["sign-in.html", SIGN_IN_SCRIPT]) {
908
+ const stale = path.join(shellDir, "ui", file);
909
+ if (fs.existsSync(stale)) {
910
+ fs.rmSync(stale);
911
+ changed = true;
912
+ }
913
+ }
712
914
  const copies = [
915
+ [path.join(shellDir, "ui", SIGN_IN_SCRIPT), app.signIn ? input.signInScript ?? builtSignInScript() : null],
713
916
  [path.join(shellDir, ICON_SOURCE), iconBytes],
714
917
  [path.join(shellDir, "ui", LOADING_LOGO), iconBytes],
715
918
  [path.join(shellDir, "ui", LOADING_SPLASH), splashBytes],
@@ -956,6 +1159,363 @@ function launchShell(shell, envVars, options) {
956
1159
  });
957
1160
  }
958
1161
  //#endregion
959
- export { loadAppJson as S, bundleStack as _, tauriConfigPatch as a, appJsonSchema as b, nodeSidecarTarget as c, runTauriIcon as d, tauriBundlesForHost as f, projectShell as g, SHELL_DIR as h, shellEnv as i, preflightOrThrow as l, ICON_SOURCE as m, resolvePhCliEntry as n, detectToolchain as o, tauriSpawn as p, resolveShell as r, fetchNodeSidecar as s, launchShell as t, resolveTauriCommand as u, APP_JSON_FILE as v, appSlug as x, DEFAULT_SHELL_CRATE_VERSION as y };
1162
+ //#region src/bundle-backend.ts
1163
+ /**
1164
+ * A packaged stack is a node_modules folder, and Windows installs by the file:
1165
+ * tens of thousands of them take as long to install as to uninstall, and a
1166
+ * start spends most of a cold disk's time reading them. This folds the stack
1167
+ * into a few hundred files with Rolldown, in the staged copy only.
1168
+ *
1169
+ * What's loaded by name keeps working by name. Each package an add-on, a host
1170
+ * file or the project's own build may import stays in node_modules with its
1171
+ * \`exports\`, and each of those is a Rolldown entry, so an import of
1172
+ * \`document-model\` from anywhere reaches the one bundled copy. Two copies would
1173
+ * break \`instanceof\` and shared state, and without an error.
1174
+ *
1175
+ * What's found by path keeps its path. Chunks and the worker scripts go in one
1176
+ * package, so a chunk finds \`./entry.mjs\` beside it and the piece worker's walk
1177
+ * up to a package.json finds \`dist/worker-entry.js\`.
1178
+ */
1179
+ /** Holds the chunks. A package, so the piece worker's lookup stops at it. */
1180
+ const CHUNKS_DIR = ".stack";
1181
+ /** Packages reached by name, by something that isn't in the bundle. */
1182
+ const BY_NAME = [
1183
+ /^@powerhousedao\//,
1184
+ /^@renown\/sdk$/,
1185
+ /^document-model$/,
1186
+ /^graphql$/,
1187
+ /^graphql-tag$/,
1188
+ /^kysely$/,
1189
+ /^zod$/
1190
+ ];
1191
+ /**
1192
+ * Left as files. PGlite finds its wasm and data beside it. React is what an
1193
+ * add-on's editor imports, and a server never calls it. The rest is only loaded
1194
+ * on a path a running app never takes, or by a native addon.
1195
+ */
1196
+ const EXTERNAL = [
1197
+ /\.node$/,
1198
+ /^@electric-sql\/pglite/,
1199
+ /^pglite-(legacy|tools)/,
1200
+ /^react($|\/)/,
1201
+ /^react-dom($|\/)/,
1202
+ /^vite($|\/)/,
1203
+ /^@powerhousedao\/vetra($|\/)/,
1204
+ /^@originjs\//,
1205
+ /^devcert$/,
1206
+ /^pg-native$/,
1207
+ /^bufferutil$/,
1208
+ /^utf-8-validate$/,
1209
+ /^@pyroscope\//
1210
+ ];
1211
+ /** How Rolldown writes a require it can't fold. A plain `require(` in a chunk is
1212
+ * text: a package's comments, error messages and generated code. */
1213
+ const REQUIRE_CALL = /\b__require\(\s*["']([^"']+)["']\s*\)/g;
1214
+ /** Copied into a kept package as they are, since a path reaches them. */
1215
+ const KEEP_AS_FILES = [path.join("dist", "node", "pieces")];
1216
+ /** What a package exports for a server: node, then import, then default. */
1217
+ function serverTarget(target) {
1218
+ if (typeof target === "string") return target;
1219
+ if (target === null || target === void 0) return null;
1220
+ for (const condition of [
1221
+ "node",
1222
+ "import",
1223
+ "default"
1224
+ ]) if (condition in target) {
1225
+ const found = serverTarget(target[condition]);
1226
+ if (found) return found;
1227
+ }
1228
+ return null;
1229
+ }
1230
+ /** Every subpath a package offers a server, with a wildcard's matches listed. */
1231
+ function exportedFiles(packageDir, manifest) {
1232
+ const files = /* @__PURE__ */ new Map();
1233
+ const exports = typeof manifest.exports === "string" ? { ".": manifest.exports } : manifest.exports;
1234
+ if (!exports) {
1235
+ const main = manifest.module ?? manifest.main ?? "index.js";
1236
+ const file = [
1237
+ main,
1238
+ `${main}.js`,
1239
+ path.join(main, "index.js")
1240
+ ].find((candidate) => isFile(path.join(packageDir, candidate)));
1241
+ if (file) files.set(".", file.replace(/^\.\//, ""));
1242
+ return files;
1243
+ }
1244
+ for (const [subpath, target] of Object.entries(exports)) {
1245
+ if (subpath === "./package.json") continue;
1246
+ const file = serverTarget(target);
1247
+ if (!file) continue;
1248
+ if (!subpath.includes("*")) {
1249
+ if (isFile(path.join(packageDir, file))) files.set(subpath, file.replace(/^\.\//, ""));
1250
+ continue;
1251
+ }
1252
+ for (const [match, found] of wildcardMatches(packageDir, file)) files.set(subpath.replace("*", match), found);
1253
+ }
1254
+ return files;
1255
+ }
1256
+ function isFile(file) {
1257
+ return fs.existsSync(file) && fs.statSync(file).isFile();
1258
+ }
1259
+ function wildcardMatches(packageDir, target) {
1260
+ const [before, after = ""] = target.replace(/^\.\//, "").split("*");
1261
+ const parent = before.endsWith("/") ? before : path.posix.dirname(before);
1262
+ const prefix = before.slice(parent.length).replace(/^\//, "");
1263
+ const matches = [];
1264
+ const folder = path.join(packageDir, parent);
1265
+ if (!fs.existsSync(folder)) return matches;
1266
+ for (const entry of fs.readdirSync(folder, { withFileTypes: true })) {
1267
+ const name = entry.name;
1268
+ const match = after.startsWith("/") ? name : name.endsWith(after) && name.startsWith(prefix) ? name.slice(prefix.length, name.length - after.length) : null;
1269
+ if (!match) continue;
1270
+ const file = path.posix.join(parent, `${prefix}${match}${after}`);
1271
+ if (isFile(path.join(packageDir, file))) matches.push([match, file]);
1272
+ }
1273
+ return matches;
1274
+ }
1275
+ /** Where a subpath's entry lands in its package. */
1276
+ function entryNameOf(pkg, subpath) {
1277
+ return `${pkg}/${subpath === "." ? "index" : subpath.replace(/^\.\//, "").replaceAll("/", "__")}`;
1278
+ }
1279
+ /** The package.json of a package whose code is now in the bundle. */
1280
+ function keptManifest(manifest, entries) {
1281
+ const { name, version } = manifest;
1282
+ const exports = { "./package.json": "./package.json" };
1283
+ for (const [subpath, file] of entries) exports[subpath] = `./${file}`;
1284
+ return {
1285
+ name,
1286
+ version,
1287
+ type: "module",
1288
+ exports
1289
+ };
1290
+ }
1291
+ /** Nearest install of \`dependency\` as seen from \`from\`, by node's rules. */
1292
+ function resolveInLock(lock, from, dependency) {
1293
+ let at = from;
1294
+ for (;;) {
1295
+ const candidate = `${at ? `${at}/` : ""}node_modules/${dependency}`;
1296
+ if (lock[candidate]) return candidate;
1297
+ if (!at) return null;
1298
+ const cut = at.lastIndexOf("node_modules/");
1299
+ at = cut <= 0 ? "" : at.slice(0, cut - 1);
1300
+ }
1301
+ }
1302
+ /** The install paths of `names` and everything they depend on. */
1303
+ function closureOf(lock, names) {
1304
+ const kept = /* @__PURE__ */ new Set();
1305
+ const queue = [...names].map((name) => `node_modules/${name}`).filter((key) => lock[key]);
1306
+ while (queue.length > 0) {
1307
+ const key = queue.pop();
1308
+ if (kept.has(key)) continue;
1309
+ kept.add(key);
1310
+ const entry = lock[key];
1311
+ for (const dependency of Object.keys({
1312
+ ...entry.dependencies,
1313
+ ...entry.optionalDependencies
1314
+ })) {
1315
+ const target = resolveInLock(lock, key, dependency);
1316
+ if (target) queue.push(target);
1317
+ }
1318
+ }
1319
+ return kept;
1320
+ }
1321
+ /** The package a bare specifier belongs to, or null for a built-in or a path. */
1322
+ function packageOf(specifier) {
1323
+ if (specifier.startsWith(".") || specifier.startsWith("/")) return null;
1324
+ if (specifier.startsWith("node:") || /^[a-z]+:/i.test(specifier)) return null;
1325
+ const parts = specifier.split("/");
1326
+ return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
1327
+ }
1328
+ /** One file of every package's licence, as a bundle can't keep them beside
1329
+ * the code. Packages under the same text share it. */
1330
+ function licencesOf(modules, packages) {
1331
+ const byText = /* @__PURE__ */ new Map();
1332
+ let count = 0;
1333
+ for (const name of packages) {
1334
+ const dir = path.join(modules, name);
1335
+ if (!fs.existsSync(dir)) continue;
1336
+ const text = fs.readdirSync(dir).filter((file) => /^(licen[sc]e|copying|notice)/i.test(file) && isFile(path.join(dir, file))).sort().map((file) => fs.readFileSync(path.join(dir, file), "utf8").trim()).join("\n\n");
1337
+ const manifest = readJson(path.join(dir, "package.json"));
1338
+ const label = `${name}@${String(manifest.version ?? "")}`;
1339
+ const key = text || `License: ${JSON.stringify(manifest.license ?? "unknown")}`;
1340
+ byText.set(key, [...byText.get(key) ?? [], label]);
1341
+ count++;
1342
+ }
1343
+ return {
1344
+ text: [...byText.entries()].map(([text, labels]) => `${labels.join("\n")}\n\n${text}\n`).join(`\n${"-".repeat(72)}\n\n`),
1345
+ packages: count
1346
+ };
1347
+ }
1348
+ function readJson(file) {
1349
+ return JSON.parse(fs.readFileSync(file, "utf8"));
1350
+ }
1351
+ function packagesIn(modules) {
1352
+ const names = [];
1353
+ for (const entry of fs.readdirSync(modules, { withFileTypes: true })) {
1354
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
1355
+ if (!entry.name.startsWith("@")) {
1356
+ names.push(entry.name);
1357
+ continue;
1358
+ }
1359
+ for (const scoped of fs.readdirSync(path.join(modules, entry.name))) names.push(`${entry.name}/${scoped}`);
1360
+ }
1361
+ return names;
1362
+ }
1363
+ /** `__dirname` and `require` per chunk, as a banner collides with any code that
1364
+ * declares its own. */
1365
+ const nodeGlobals = {
1366
+ name: "ph:node-globals",
1367
+ renderChunk(code) {
1368
+ const declared = (name) => new RegExp(`\\b(?:const|let|var|function)\\s+${name}\\b`).test(code);
1369
+ const used = (name) => new RegExp(`(?<![.\\w$])${name}\\b`).test(code);
1370
+ const wanted = [
1371
+ "__filename",
1372
+ "__dirname",
1373
+ "require"
1374
+ ].filter((name) => used(name) && !declared(name));
1375
+ if (wanted.length === 0) return null;
1376
+ const lines = [`import { fileURLToPath as __ph_path } from "node:url";`];
1377
+ if (wanted.includes("__dirname")) {
1378
+ lines.push(`import { dirname as __ph_dir } from "node:path";`);
1379
+ lines.push(`const __dirname = __ph_dir(__ph_path(import.meta.url));`);
1380
+ }
1381
+ if (wanted.includes("__filename")) lines.push(`const __filename = __ph_path(import.meta.url);`);
1382
+ if (wanted.includes("require")) {
1383
+ lines.push(`import { createRequire as __ph_require } from "node:module";`);
1384
+ lines.push(`const require = __ph_require(import.meta.url);`);
1385
+ }
1386
+ return {
1387
+ code: `${lines.join("\n")}\n${code}`,
1388
+ map: null
1389
+ };
1390
+ }
1391
+ };
1392
+ /** Replaces a staged stack's node_modules with a bundle of it. */
1393
+ async function bundleBackend(options) {
1394
+ const log = options.logger ?? (() => void 0);
1395
+ const { stackDir } = options;
1396
+ const modules = path.join(stackDir, "node_modules");
1397
+ const output = path.join(stackDir, ".bundle-output");
1398
+ fs.rmSync(output, {
1399
+ recursive: true,
1400
+ force: true
1401
+ });
1402
+ const lock = readJson(path.join(stackDir, "package-lock.json")).packages;
1403
+ const installed = packagesIn(modules);
1404
+ const byName = installed.filter((name) => BY_NAME.some((pattern) => pattern.test(name)));
1405
+ const input = {};
1406
+ const entriesOf = /* @__PURE__ */ new Map();
1407
+ const kept = /* @__PURE__ */ new Map();
1408
+ for (const name of byName) {
1409
+ const dir = path.join(modules, name);
1410
+ const manifest = readJson(path.join(dir, "package.json"));
1411
+ kept.set(name, manifest);
1412
+ const entries = /* @__PURE__ */ new Map();
1413
+ for (const [subpath, file] of exportedFiles(dir, manifest)) {
1414
+ if (!/\.[cm]?js$/.test(file)) continue;
1415
+ const entry = entryNameOf(name, subpath);
1416
+ input[entry] = path.join(dir, file);
1417
+ entries.set(subpath, `${path.posix.basename(entry)}.mjs`);
1418
+ }
1419
+ entriesOf.set(name, entries);
1420
+ }
1421
+ input["@powerhousedao/ph-run/dist/cli"] = path.join(modules, "@powerhousedao/ph-run/dist/cli.mjs");
1422
+ input[`${CHUNKS_DIR}/entry`] = path.join(modules, "@powerhousedao/reactor-api/dist/src/pglite/worker/entry.mjs");
1423
+ input[`${CHUNKS_DIR}/dist/worker-entry`] = path.join(modules, "@powerhousedao/reactor-workflow/dist/worker-entry.js");
1424
+ for (const [entry, file] of Object.entries(input)) if (!fs.existsSync(file)) throw new Error(`no entry ${entry} at ${file}`);
1425
+ log(` bundling ${Object.keys(input).length} entries of ${byName.length} packages…`);
1426
+ const { rolldown } = await import("rolldown");
1427
+ const build = await rolldown({
1428
+ cwd: stackDir,
1429
+ input,
1430
+ platform: "node",
1431
+ external: EXTERNAL,
1432
+ onLog() {},
1433
+ plugins: [nodeGlobals]
1434
+ });
1435
+ const { output: written } = await build.write({
1436
+ dir: output,
1437
+ format: "esm",
1438
+ entryFileNames: (chunk) => chunk.name === `${CHUNKS_DIR}/dist/worker-entry` ? `${CHUNKS_DIR}/dist/worker-entry.js` : "[name].mjs",
1439
+ chunkFileNames: `${CHUNKS_DIR}/[name]-[hash].mjs`,
1440
+ keepNames: true,
1441
+ sourcemap: false
1442
+ });
1443
+ await build.close();
1444
+ const ownFiles = new Set(written.map((file) => file.fileName));
1445
+ const reached = /* @__PURE__ */ new Set();
1446
+ for (const file of written) {
1447
+ if (file.type !== "chunk") continue;
1448
+ for (const specifier of [...file.imports, ...file.dynamicImports]) {
1449
+ const name = ownFiles.has(specifier) ? null : packageOf(specifier);
1450
+ if (name) reached.add(name);
1451
+ }
1452
+ for (const [, specifier] of file.code.matchAll(REQUIRE_CALL)) {
1453
+ const name = packageOf(specifier);
1454
+ if (name && lock[`node_modules/${name}`]) reached.add(name);
1455
+ }
1456
+ }
1457
+ log(` left as files: ${[...reached].sort().join(", ")}`);
1458
+ const keepInstalled = closureOf(lock, reached);
1459
+ const bundled = new Set(byName);
1460
+ const removed = installed.filter((name) => !keepInstalled.has(`node_modules/${name}`) && !bundled.has(name));
1461
+ const licences = licencesOf(modules, [...removed, ...byName]);
1462
+ fs.writeFileSync(path.join(stackDir, "THIRD-PARTY-LICENSES.txt"), licences.text);
1463
+ for (const name of byName) {
1464
+ const dir = path.join(modules, name);
1465
+ const staged = path.join(output, name);
1466
+ fs.mkdirSync(staged, { recursive: true });
1467
+ for (const relative of KEEP_AS_FILES) {
1468
+ const from = path.join(dir, relative);
1469
+ if (fs.existsSync(from)) fs.cpSync(from, path.join(staged, relative), { recursive: true });
1470
+ }
1471
+ for (const file of fs.readdirSync(dir)) {
1472
+ const from = path.join(dir, file);
1473
+ if (/\.json$/.test(file) && file !== "package.json" && isFile(from)) fs.copyFileSync(from, path.join(staged, file));
1474
+ }
1475
+ const manifest = kept.get(name) ?? {};
1476
+ const entries = entriesOf.get(name) ?? /* @__PURE__ */ new Map();
1477
+ for (const [subpath, file] of exportedFiles(dir, manifest)) {
1478
+ if (/\.[cm]?js$/.test(file)) continue;
1479
+ const target = path.join(staged, file);
1480
+ if (!isFile(path.join(dir, file))) continue;
1481
+ fs.mkdirSync(path.dirname(target), { recursive: true });
1482
+ fs.copyFileSync(path.join(dir, file), target);
1483
+ entries.set(subpath, file);
1484
+ }
1485
+ fs.writeFileSync(path.join(staged, "package.json"), `${JSON.stringify(keptManifest(manifest, entries), null, 2)}\n`);
1486
+ }
1487
+ fs.writeFileSync(path.join(output, CHUNKS_DIR, "package.json"), `${JSON.stringify({
1488
+ name: "ph-stack-bundle",
1489
+ private: true,
1490
+ type: "module"
1491
+ })}\n`);
1492
+ for (const name of [...removed, ...byName]) fs.rmSync(path.join(modules, name), {
1493
+ recursive: true,
1494
+ force: true
1495
+ });
1496
+ fs.rmSync(path.join(modules, ".bin"), {
1497
+ recursive: true,
1498
+ force: true
1499
+ });
1500
+ for (const entry of fs.readdirSync(modules, { withFileTypes: true })) {
1501
+ if (!entry.name.startsWith("@") || !entry.isDirectory()) continue;
1502
+ const scope = path.join(modules, entry.name);
1503
+ if (fs.readdirSync(scope).length === 0) fs.rmdirSync(scope);
1504
+ }
1505
+ fs.cpSync(output, modules, { recursive: true });
1506
+ fs.rmSync(output, {
1507
+ recursive: true,
1508
+ force: true
1509
+ });
1510
+ const chunks = written.filter((file) => file.type === "chunk").length;
1511
+ log(` bundled into ${chunks} files; ${removed.length} packages folded in, ${reached.size} left as files, licences of ${licences.packages} written`);
1512
+ return {
1513
+ chunks,
1514
+ removedPackages: removed.length,
1515
+ keptPackages: keepInstalled.size
1516
+ };
1517
+ }
1518
+ //#endregion
1519
+ export { appJsonSchema as C, DEFAULT_SHELL_CRATE_VERSION as S, loadAppJson as T, projectShell as _, shellEnv as a, pruneStack as b, fetchNodeSidecar as c, resolveTauriCommand as d, runTauriIcon as f, SHELL_DIR as g, ICON_SOURCE as h, resolveShell as i, nodeSidecarTarget as l, tauriSpawn as m, launchShell as n, tauriConfigPatch as o, tauriBundlesForHost as p, resolvePhCliEntry as r, detectToolchain as s, bundleBackend as t, preflightOrThrow as u, bundleStack as v, appSlug as w, APP_JSON_FILE as x, pluginPackagesOf as y };
960
1520
 
961
- //# sourceMappingURL=shell-C6KfHzBa.mjs.map
1521
+ //# sourceMappingURL=bundle-backend-Dc-m4eRx.mjs.map