@riebeckite/honox 0.0.35 → 0.0.36

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.js CHANGED
@@ -281,186 +281,281 @@ function isJavaScriptModule(filePath) {
281
281
  return /\.[cm]?[jt]sx?$/.test(filePath);
282
282
  }
283
283
 
284
- // src/ssg_plugin.ts
285
- import { rm as rm3 } from "node:fs/promises";
286
- import { join as join4, relative as relative3, resolve as resolve2 } from "node:path";
287
- import { buildOutputPlan, compareOutputPlan } from "@riebeckite/core";
288
- import { defaultExtensionMap, redirectPlugin, toSSG } from "hono/ssg";
289
- import {
290
- createServer
291
- } from "vite";
292
-
293
- // src/content_assets.ts
294
- import fs5 from "node:fs/promises";
295
- import path7 from "node:path";
296
- import { isImagePath as isImagePath2, normalizeContentPath as normalizeContentPath2 } from "@riebeckite/core";
297
- import { isIgnoredContentPath as isIgnoredContentPath2 } from "@riebeckite/node";
298
-
299
- // src/content_watch.ts
300
- import path6 from "node:path";
301
- import {
302
- isAttachmentPath,
303
- isImagePath,
304
- normalizeContentPath
305
- } from "@riebeckite/core";
306
- import { isIgnoredContentPath } from "@riebeckite/node";
284
+ // src/ssg/inventory.ts
285
+ import { createHash } from "node:crypto";
286
+ import { readdir, readFile } from "node:fs/promises";
287
+ import { dirname, join, relative as relative2 } from "node:path";
288
+ import { performance } from "node:perf_hooks";
307
289
 
308
- // src/runtime_modules.ts
309
- var riebeckiteConfigModuleId = "virtual:riebeckite/config";
310
- var riebeckiteContentModuleId = "virtual:riebeckite/content";
311
- var runtimeModuleIds = [
312
- riebeckiteConfigModuleId,
313
- riebeckiteContentModuleId
314
- ];
315
- var resolvedConfigModuleId = `\0${riebeckiteConfigModuleId}`;
316
- var resolvedContentModuleId = `\0${riebeckiteContentModuleId}`;
317
- function riebeckiteRuntimeModules(getApplication) {
318
- return {
319
- name: "riebeckite-runtime-modules",
320
- resolveId(id) {
321
- if (id === riebeckiteConfigModuleId) return resolvedConfigModuleId;
322
- if (id === riebeckiteContentModuleId) return resolvedContentModuleId;
323
- return null;
324
- },
325
- load(id) {
326
- if (id === resolvedConfigModuleId) {
327
- const { appRoot, configFile } = getApplication();
328
- return createConfigModule(appRoot, configFile);
329
- }
330
- if (id === resolvedContentModuleId) return createContentModule();
331
- return null;
332
- }
333
- };
290
+ // src/ssg/file_system.ts
291
+ import { relative, resolve } from "node:path";
292
+ function isMissingDirectoryError(error) {
293
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
334
294
  }
335
- function isRiebeckiteRuntimeModuleId(id) {
336
- if (!id) return false;
337
- return runtimeModuleIds.some(
338
- (moduleId) => id === moduleId || id === `\0${moduleId}`
339
- );
295
+ function isNotFoundError(error) {
296
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
340
297
  }
341
- function createConfigModule(appRoot, configFile) {
342
- const configSpecifier = configFile.replace(/\\/g, "/");
343
- return `import * as rawConfigModule from ${JSON.stringify(configSpecifier)};
344
- import { resolveConfigModule } from "@riebeckite/core";
345
- import { resolveHonoxConfig } from "@riebeckite/honox/runtime";
346
-
347
- export const config = resolveHonoxConfig(
348
- resolveConfigModule(rawConfigModule),
349
- ${JSON.stringify(appRoot)},
350
- );
351
- `;
298
+ function isAbsolutePath(path11) {
299
+ return /^([a-z]:)?[\\/]/iu.test(path11);
352
300
  }
353
- function createContentModule() {
354
- return `import { ContentManager } from "@riebeckite/core";
355
- import { FileSystemContentSource } from "@riebeckite/node";
356
- import { config } from ${JSON.stringify(riebeckiteConfigModuleId)};
357
-
358
- export const content = new ContentManager(
359
- config.content.source ?? new FileSystemContentSource(
360
- config.content.directory,
361
- config.content.exclude,
362
- ),
363
- [],
364
- { config, plugins: config.plugins },
365
- );
366
- `;
301
+ function resolveWithinDirectory(directory, relativePath, label) {
302
+ if (!relativePath || relativePath.includes("\0") || isAbsolutePath(relativePath)) {
303
+ throw new Error(`Invalid ${label}: ${relativePath}`);
304
+ }
305
+ const file = resolve(directory, relativePath);
306
+ const relativePathFromDirectory = relative(directory, file);
307
+ if (relativePathFromDirectory.startsWith("..") || relativePathFromDirectory === "" || isAbsolutePath(relativePathFromDirectory)) {
308
+ throw new Error(`Unsafe ${label}: ${relativePath}`);
309
+ }
310
+ return file;
367
311
  }
368
312
 
369
- // src/content_watch.ts
370
- var CONTENT_RELOAD_DEBOUNCE_MS = 60;
371
- var configuredWatchers = /* @__PURE__ */ new WeakSet();
372
- function riebeckiteContentWatch(options) {
373
- return {
374
- name: "riebeckite-content-watch",
375
- apply: "serve",
376
- enforce: "post",
377
- configureServer(server) {
378
- if (configuredWatchers.has(server.watcher)) return;
379
- configuredWatchers.add(server.watcher);
380
- const appRoot = options.appRoot();
381
- const contentRoot = options.contentRoot();
382
- const exclude = options.exclude();
383
- const isContentFile = (file) => isPathInsideDirectory(contentRoot, file);
384
- server.watcher.add(contentRoot);
385
- suppressRestartOnContentEvents(server, isContentFile);
386
- let timer;
387
- const invalidate = () => {
388
- if (timer) clearTimeout(timer);
389
- timer = setTimeout(() => {
390
- timer = void 0;
391
- invalidateApplicationRuntime(server, appRoot);
392
- server.hot.send({ type: "full-reload" });
393
- }, CONTENT_RELOAD_DEBOUNCE_MS);
394
- };
395
- server.httpServer?.once("close", () => {
396
- if (timer) clearTimeout(timer);
397
- });
398
- const handle = (event) => (file) => {
399
- if (!isContentFile(file)) return;
400
- const logicalPath = toLogicalPath(contentRoot, file);
401
- if (isIgnoredContentPath(logicalPath, exclude)) return;
402
- if (event === "change" && isSiteAssetPath(logicalPath)) {
403
- server.hot.send({ type: "full-reload" });
404
- return;
405
- }
406
- invalidate();
407
- };
408
- server.watcher.on("add", handle("add"));
409
- server.watcher.on("change", handle("change"));
410
- server.watcher.on("unlink", handle("unlink"));
313
+ // src/ssg/inventory.ts
314
+ var APP_FINGERPRINT_IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
315
+ "node_modules",
316
+ ".riebeckite",
317
+ "dist"
318
+ ]);
319
+ var APP_FINGERPRINT_CONFIG_FILES = [
320
+ "riebeckite.config.ts",
321
+ "riebeckite.config.mts",
322
+ "riebeckite.config.cts",
323
+ "riebeckite.config.js",
324
+ "riebeckite.config.mjs",
325
+ "riebeckite.config.cjs"
326
+ ];
327
+ async function computeAppFingerprint(root, configFile) {
328
+ const files = [];
329
+ await collectAppFiles(join(root, "app"), files);
330
+ if (configFile) files.push(configFile);
331
+ for (const name of APP_FINGERPRINT_CONFIG_FILES) {
332
+ files.push(join(root, name));
333
+ }
334
+ files.sort();
335
+ const hash = createHash("sha256");
336
+ for (const file of files) {
337
+ let content;
338
+ try {
339
+ content = await readFile(file);
340
+ } catch {
341
+ continue;
411
342
  }
412
- };
343
+ hash.update(relative2(root, file).replaceAll("\\", "/"));
344
+ hash.update("\0");
345
+ hash.update(content);
346
+ hash.update("\0");
347
+ }
348
+ return hash.digest("hex");
413
349
  }
414
- function isSiteAssetPath(logicalPath) {
415
- return isImagePath(logicalPath) || isAttachmentPath(logicalPath);
350
+ async function computeBundleFingerprint(root, configFile) {
351
+ const hash = createHash("sha256");
352
+ hash.update(await computeAppFingerprint(root, configFile));
353
+ const files = [
354
+ ...await findBundleInputFiles(root),
355
+ ...await findLocalPackageInputFiles(root)
356
+ ].sort();
357
+ for (const file of files) {
358
+ try {
359
+ hash.update(file).update("\0").update(await readFile(file)).update("\0");
360
+ } catch {
361
+ }
362
+ }
363
+ for (const [name, value] of Object.entries(process.env).filter(([name2]) => name2 === "NODE_ENV" || name2.startsWith("VITE_")).sort(([left], [right]) => left.localeCompare(right))) {
364
+ if (value === void 0) continue;
365
+ hash.update(name).update("\0").update(value).update("\0");
366
+ }
367
+ return hash.digest("hex");
368
+ }
369
+ async function fingerprintDirectory(directory) {
370
+ const inventory = await fingerprintOutputDirectory(directory);
371
+ const hash = createHash("sha256");
372
+ for (const [path11, checksum] of Object.entries(inventory).sort(
373
+ ([left], [right]) => left.localeCompare(right)
374
+ )) {
375
+ hash.update(path11).update("\0").update(checksum).update("\0");
376
+ }
377
+ return hash.digest("hex");
378
+ }
379
+ async function fingerprintOutputDirectory(directory, relativeDirectory = "", metrics) {
380
+ const entries = await readdir(directory, { withFileTypes: true }).catch(
381
+ (error) => {
382
+ if (isMissingDirectoryError(error)) return void 0;
383
+ throw error;
384
+ }
385
+ );
386
+ if (!entries) return {};
387
+ const inventory = {};
388
+ for (const entry of entries) {
389
+ const file = join(directory, entry.name);
390
+ const relativePath = join(relativeDirectory, entry.name).replaceAll(
391
+ "\\",
392
+ "/"
393
+ );
394
+ if (entry.isDirectory()) {
395
+ Object.assign(
396
+ inventory,
397
+ await fingerprintOutputDirectory(file, relativePath, metrics)
398
+ );
399
+ continue;
400
+ }
401
+ if (entry.isFile()) {
402
+ const hashedAt = performance.now();
403
+ const content = await readFile(file);
404
+ inventory[relativePath] = createHash("sha256").update(content).digest("hex");
405
+ if (metrics) {
406
+ metrics.outputHashValidationDurationMs += performance.now() - hashedAt;
407
+ metrics.outputFilesHashed += 1;
408
+ metrics.outputBytesHashed += content.length;
409
+ }
410
+ }
411
+ }
412
+ return inventory;
416
413
  }
417
- function isPathInsideDirectory(directory, file) {
418
- const root = normalizeForCompare(directory).replace(/\/+$/, "");
419
- if (!root) return false;
420
- const target = normalizeForCompare(file);
421
- return target === root || target.startsWith(`${root}/`);
414
+ function inventoriesEqual(left, right) {
415
+ const leftPaths = Object.keys(left);
416
+ const rightPaths = Object.keys(right);
417
+ return leftPaths.length === rightPaths.length && leftPaths.every((path11) => left[path11] === right[path11]);
422
418
  }
423
- function toLogicalPath(directory, file) {
424
- return normalizeContentPath(
425
- path6.relative(normalizeContentPath(directory), normalizeContentPath(file))
419
+ async function collectAppFiles(directory, files) {
420
+ const entries = await readdir(directory, { withFileTypes: true }).catch(
421
+ () => void 0
426
422
  );
423
+ if (!entries) return;
424
+ for (const entry of entries) {
425
+ const full = join(directory, entry.name);
426
+ if (entry.isDirectory()) {
427
+ if (APP_FINGERPRINT_IGNORED_DIRECTORIES.has(entry.name)) continue;
428
+ await collectAppFiles(full, files);
429
+ } else if (entry.isFile()) {
430
+ files.push(full);
431
+ }
432
+ }
427
433
  }
428
- function invalidateApplicationRuntime(server, appRoot) {
429
- const moduleGraph = server.environments?.ssr?.moduleGraph;
430
- if (!moduleGraph) return 0;
431
- const appDirectory = path6.join(appRoot, "app") + path6.sep;
432
- const seen = /* @__PURE__ */ new Set();
433
- const timestamp = Date.now();
434
- let invalidated = 0;
435
- for (const mod of moduleGraph.idToModuleMap.values()) {
436
- if (!isApplicationRuntimeModule(mod, appDirectory)) continue;
437
- moduleGraph.invalidateModule(mod, seen, timestamp);
438
- invalidated += 1;
434
+ async function findBundleInputFiles(root) {
435
+ const files = [];
436
+ for (let directory = root; ; directory = dirname(directory)) {
437
+ for (const name of [
438
+ "package.json",
439
+ "pnpm-lock.yaml",
440
+ "package-lock.json",
441
+ "yarn.lock"
442
+ ]) {
443
+ files.push(join(directory, name));
444
+ }
445
+ const parent = dirname(directory);
446
+ if (parent === directory) return files;
439
447
  }
440
- return invalidated;
441
448
  }
442
- function isApplicationRuntimeModule(mod, appDirectory) {
443
- if (mod.file && isPathInsideDirectory(appDirectory, mod.file)) return true;
444
- return isRiebeckiteRuntimeModuleId(mod.id);
449
+ async function findLocalPackageInputFiles(root) {
450
+ const packageFile = join(root, "package.json");
451
+ let packageSource;
452
+ try {
453
+ packageSource = await readFile(packageFile, "utf8");
454
+ } catch {
455
+ return [];
456
+ }
457
+ let packageJson;
458
+ try {
459
+ packageJson = JSON.parse(packageSource);
460
+ } catch {
461
+ return [];
462
+ }
463
+ if (!packageJson || typeof packageJson !== "object") return [];
464
+ const files = [];
465
+ const workspaceDependencies = /* @__PURE__ */ new Set();
466
+ for (const dependencyGroup of [
467
+ "dependencies",
468
+ "devDependencies",
469
+ "optionalDependencies"
470
+ ]) {
471
+ const dependencies = packageJson[dependencyGroup];
472
+ if (!dependencies || typeof dependencies !== "object") continue;
473
+ for (const [name, specifier] of Object.entries(dependencies)) {
474
+ if (typeof specifier !== "string") continue;
475
+ const directory = localPackageDirectory(root, specifier);
476
+ if (directory) {
477
+ await collectPackageFiles(directory, files);
478
+ continue;
479
+ }
480
+ if (specifier.startsWith("workspace:")) workspaceDependencies.add(name);
481
+ }
482
+ }
483
+ const workspaceRoot = await findWorkspaceRoot(root);
484
+ if (workspaceRoot && workspaceDependencies.size > 0) {
485
+ for (const directory of await findWorkspacePackageDirectories2(
486
+ workspaceRoot,
487
+ workspaceDependencies
488
+ )) {
489
+ await collectPackageFiles(directory, files);
490
+ }
491
+ }
492
+ return files;
445
493
  }
446
- function suppressRestartOnContentEvents(server, isContentFile) {
447
- for (const event of ["add", "unlink"]) {
448
- const listeners = server.watcher.rawListeners(event).slice();
449
- server.watcher.removeAllListeners(event);
450
- for (const listener of listeners) {
451
- server.watcher.on(event, (file) => {
452
- if (isContentFile(file)) return;
453
- listener(file);
454
- });
494
+ function localPackageDirectory(root, specifier) {
495
+ if (specifier.startsWith("file:")) return join(root, specifier.slice(5));
496
+ if (specifier.startsWith("link:")) return join(root, specifier.slice(5));
497
+ return void 0;
498
+ }
499
+ async function findWorkspaceRoot(root) {
500
+ for (let directory = root; ; directory = dirname(directory)) {
501
+ try {
502
+ await readFile(join(directory, "pnpm-workspace.yaml"));
503
+ return directory;
504
+ } catch {
505
+ }
506
+ const parent = dirname(directory);
507
+ if (parent === directory) return void 0;
508
+ }
509
+ }
510
+ async function findWorkspacePackageDirectories2(directory, names) {
511
+ const entries = await readdir(directory, { withFileTypes: true }).catch(
512
+ () => []
513
+ );
514
+ const matches = [];
515
+ for (const entry of entries) {
516
+ if (!entry.isDirectory() || APP_FINGERPRINT_IGNORED_DIRECTORIES.has(entry.name))
517
+ continue;
518
+ const child = join(directory, entry.name);
519
+ try {
520
+ const packageJson = JSON.parse(
521
+ await readFile(join(child, "package.json"), "utf8")
522
+ );
523
+ if (typeof packageJson.name === "string" && names.has(packageJson.name)) {
524
+ matches.push(child);
525
+ continue;
526
+ }
527
+ } catch {
455
528
  }
529
+ matches.push(...await findWorkspacePackageDirectories2(child, names));
456
530
  }
531
+ return matches;
457
532
  }
458
- function normalizeForCompare(value) {
459
- const normalized = normalizeContentPath(value);
460
- return process.platform === "win32" ? normalized.toLowerCase() : normalized;
533
+ async function collectPackageFiles(directory, files) {
534
+ files.push(join(directory, "package.json"));
535
+ await collectAppFiles(directory, files);
461
536
  }
462
537
 
538
+ // src/ssg_plugin.ts
539
+ import { randomUUID as randomUUID4 } from "node:crypto";
540
+ import { lstat as lstat3, mkdir as mkdir5, rm as rm4, writeFile as writeFile4 } from "node:fs/promises";
541
+ import { dirname as dirname5, join as join5, relative as relative4, resolve as resolve4 } from "node:path";
542
+ import {
543
+ BUILD_OUTPUT_MARKER_FILE,
544
+ buildOutputPlan,
545
+ compareOutputPlan,
546
+ createBuildOutputMarker,
547
+ publicationFingerprint as fingerprintPublication,
548
+ publicationEntriesFromManifest,
549
+ publicationOutputsFromManifest,
550
+ publicationRedirectsFromManifest,
551
+ serializeBuildOutputMarker
552
+ } from "@riebeckite/core";
553
+
463
554
  // src/content_assets.ts
555
+ import fs5 from "node:fs/promises";
556
+ import path6 from "node:path";
557
+ import { isImagePath, normalizeContentPath } from "@riebeckite/core";
558
+ import { isIgnoredContentPath, isPathInsideDirectory } from "@riebeckite/node";
464
559
  var IMAGE_CONTENT_TYPES = {
465
560
  png: "image/png",
466
561
  jpg: "image/jpeg",
@@ -477,7 +572,7 @@ function riebeckiteContentAssets(options) {
477
572
  enforce: "pre",
478
573
  configureServer(server) {
479
574
  const contentRoot = options.contentRoot();
480
- const entry = path7.join(options.appRoot(), "app", "server.ts");
575
+ const entry = path6.join(options.appRoot(), "app", "server.ts");
481
576
  const base = server.config.base;
482
577
  const publicDir = server.config.publicDir;
483
578
  let cachedManifest;
@@ -499,11 +594,11 @@ function riebeckiteContentAssets(options) {
499
594
  return;
500
595
  }
501
596
  const logicalPath = toContentPath(request.url, base);
502
- if (!logicalPath || !isImagePath2(logicalPath)) {
597
+ if (!logicalPath || !isImagePath(logicalPath)) {
503
598
  next();
504
599
  return;
505
600
  }
506
- if (isIgnoredContentPath2(logicalPath)) {
601
+ if (isIgnoredContentPath(logicalPath)) {
507
602
  next();
508
603
  return;
509
604
  }
@@ -517,7 +612,7 @@ function riebeckiteContentAssets(options) {
517
612
  next();
518
613
  return;
519
614
  }
520
- const file = path7.join(contentRoot, logicalPath);
615
+ const file = path6.join(contentRoot, logicalPath);
521
616
  if (!isPathInsideDirectory(contentRoot, file)) {
522
617
  next();
523
618
  return;
@@ -555,8 +650,8 @@ function collectPublicImagePaths(manifest) {
555
650
  const paths = /* @__PURE__ */ new Set();
556
651
  for (const entry of manifest.publicEntries ?? []) {
557
652
  for (const asset of entry.assets ?? []) {
558
- const normalized = normalizeContentPath2(asset.path);
559
- if (isImagePath2(normalized)) paths.add(normalized);
653
+ const normalized = normalizeContentPath(asset.path);
654
+ if (isImagePath(normalized)) paths.add(normalized);
560
655
  }
561
656
  }
562
657
  return paths;
@@ -564,16 +659,16 @@ function collectPublicImagePaths(manifest) {
564
659
  async function collectSiteOwnedOutputPaths(publicDir) {
565
660
  const paths = /* @__PURE__ */ new Set();
566
661
  if (!publicDir) return paths;
567
- const root = path7.resolve(publicDir);
662
+ const root = path6.resolve(publicDir);
568
663
  const walk = async (directory) => {
569
664
  const entries = await fs5.readdir(directory, { withFileTypes: true }).catch(() => void 0);
570
665
  if (!entries) return;
571
666
  for (const entry of entries) {
572
- const full = path7.join(directory, entry.name);
667
+ const full = path6.join(directory, entry.name);
573
668
  if (entry.isDirectory()) {
574
669
  await walk(full);
575
670
  } else {
576
- paths.add(path7.relative(root, full).replaceAll("\\", "/"));
671
+ paths.add(path6.relative(root, full).replaceAll("\\", "/"));
577
672
  }
578
673
  }
579
674
  };
@@ -590,9 +685,9 @@ function toContentPath(url, base) {
590
685
  } catch {
591
686
  return void 0;
592
687
  }
593
- let pathname = normalizeContentPath2(decoded);
688
+ let pathname = normalizeContentPath(decoded);
594
689
  if (base && base !== "/" && pathname.startsWith(base)) {
595
- pathname = normalizeContentPath2(pathname.slice(base.length));
690
+ pathname = normalizeContentPath(pathname.slice(base.length));
596
691
  }
597
692
  const logicalPath = pathname.replace(/^\/+/, "");
598
693
  if (!logicalPath) return void 0;
@@ -608,7 +703,7 @@ function imageContentType(logicalPath) {
608
703
  }
609
704
  async function hasSiteOwnedFile(publicDir, logicalPath) {
610
705
  if (!publicDir) return false;
611
- const file = path7.join(publicDir, logicalPath);
706
+ const file = path6.join(publicDir, logicalPath);
612
707
  try {
613
708
  return (await fs5.stat(file)).isFile();
614
709
  } catch {
@@ -616,38 +711,186 @@ async function hasSiteOwnedFile(publicDir, logicalPath) {
616
711
  }
617
712
  }
618
713
 
619
- // src/ssg/build_output.ts
620
- import { createHash, randomUUID } from "node:crypto";
621
- import { mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
622
- import { dirname, join } from "node:path";
623
-
624
- // src/ssg/file_system.ts
625
- import { relative, resolve } from "node:path";
626
- function isMissingDirectoryError(error) {
627
- return error instanceof Error && "code" in error && error.code === "ENOENT";
714
+ // src/ssg/artifact_writer.ts
715
+ import { randomUUID } from "node:crypto";
716
+ import {
717
+ cp,
718
+ lstat,
719
+ mkdir,
720
+ readFile as readFile2,
721
+ rename,
722
+ rm,
723
+ writeFile
724
+ } from "node:fs/promises";
725
+ import { dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";
726
+ async function createBuildArtifactWriter(input) {
727
+ const outputDirectory = input.outputDirectory;
728
+ await recoverPendingPublication(outputDirectory);
729
+ const stagingDirectory = input.stagingDirectory ?? join2(
730
+ dirname2(outputDirectory),
731
+ ".riebeckite",
732
+ `build-output-${randomUUID()}`
733
+ );
734
+ if (resolve2(stagingDirectory) === resolve2(outputDirectory)) {
735
+ throw new Error(
736
+ "Build artifact staging directory must differ from output."
737
+ );
738
+ }
739
+ if (input.clearStagingDirectory !== false) {
740
+ await rm(stagingDirectory, { force: true, recursive: true });
741
+ }
742
+ await mkdir(stagingDirectory, { recursive: true });
743
+ let completed = false;
744
+ return {
745
+ directory: stagingDirectory,
746
+ async copyFrom(source) {
747
+ ensureOpen(completed);
748
+ await cp(source, stagingDirectory, { recursive: true });
749
+ },
750
+ async remove(path11) {
751
+ ensureOpen(completed);
752
+ await rm(resolveArtifactPath(stagingDirectory, path11), {
753
+ force: true,
754
+ recursive: true
755
+ });
756
+ },
757
+ async write(path11, data) {
758
+ ensureOpen(completed);
759
+ const target = resolveArtifactPath(stagingDirectory, path11);
760
+ await mkdir(dirname2(target), { recursive: true });
761
+ await writeFile(target, data);
762
+ },
763
+ async publish() {
764
+ ensureOpen(completed);
765
+ await publishDirectory(stagingDirectory, outputDirectory);
766
+ completed = true;
767
+ },
768
+ async discard() {
769
+ if (completed) return;
770
+ completed = true;
771
+ await rm(stagingDirectory, { force: true, recursive: true });
772
+ }
773
+ };
628
774
  }
629
- function isNotFoundError(error) {
630
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
775
+ function ensureOpen(completed) {
776
+ if (completed) throw new Error("Build artifact writer is already closed.");
631
777
  }
632
- function isAbsolutePath(path11) {
633
- return /^([a-z]:)?[\\/]/iu.test(path11);
778
+ function resolveArtifactPath(directory, path11) {
779
+ return resolveWithinDirectory(directory, path11, "Build artifact path");
780
+ }
781
+ async function publishDirectory(stagingDirectory, outputDirectory) {
782
+ const backupDirectory = join2(
783
+ dirname2(outputDirectory),
784
+ ".riebeckite",
785
+ `build-output-backup-${randomUUID()}`
786
+ );
787
+ const previousOutputExists = await isDirectory(outputDirectory);
788
+ let previousOutputMoved = false;
789
+ const journalPath = publicationJournalPath(outputDirectory);
790
+ await writeJournal(journalPath, {
791
+ backupDirectory,
792
+ outputDirectory,
793
+ stagingDirectory,
794
+ state: "staged"
795
+ });
796
+ try {
797
+ if (previousOutputExists) {
798
+ await moveWithRetry(outputDirectory, backupDirectory);
799
+ previousOutputMoved = true;
800
+ await writeJournal(journalPath, {
801
+ backupDirectory,
802
+ outputDirectory,
803
+ stagingDirectory,
804
+ state: "previous-output-moved"
805
+ });
806
+ }
807
+ await moveWithRetry(stagingDirectory, outputDirectory);
808
+ await writeJournal(journalPath, {
809
+ backupDirectory,
810
+ outputDirectory,
811
+ stagingDirectory,
812
+ state: "published"
813
+ });
814
+ } catch (error) {
815
+ if (previousOutputMoved) {
816
+ await rm(outputDirectory, { force: true, recursive: true });
817
+ await moveWithRetry(backupDirectory, outputDirectory);
818
+ }
819
+ await rm(journalPath, { force: true });
820
+ throw error;
821
+ }
822
+ await rm(backupDirectory, { force: true, recursive: true });
823
+ await rm(journalPath, { force: true });
824
+ }
825
+ function publicationJournalPath(outputDirectory) {
826
+ return join2(dirname2(outputDirectory), ".riebeckite", "build-output.json");
827
+ }
828
+ async function writeJournal(path11, journal) {
829
+ await mkdir(dirname2(path11), { recursive: true });
830
+ await writeFile(path11, JSON.stringify(journal));
831
+ }
832
+ async function recoverPendingPublication(outputDirectory) {
833
+ const path11 = publicationJournalPath(outputDirectory);
834
+ let journal;
835
+ try {
836
+ journal = JSON.parse(await readFile2(path11, "utf8"));
837
+ } catch (error) {
838
+ if (isNotFoundError2(error)) return;
839
+ await rm(path11, { force: true });
840
+ return;
841
+ }
842
+ if (journal.outputDirectory !== outputDirectory || !isPublicationJournalState(journal.state)) {
843
+ await rm(path11, { force: true });
844
+ return;
845
+ }
846
+ if (journal.state === "previous-output-moved" && !await isDirectory(outputDirectory) && await isDirectory(journal.backupDirectory)) {
847
+ await moveWithRetry(journal.backupDirectory, outputDirectory);
848
+ }
849
+ await rm(journal.backupDirectory, { force: true, recursive: true });
850
+ await rm(journal.stagingDirectory, { force: true, recursive: true });
851
+ await rm(path11, { force: true });
634
852
  }
635
- function resolveWithinDirectory(directory, relativePath, label) {
636
- if (!relativePath || relativePath.includes("\0") || isAbsolutePath(relativePath)) {
637
- throw new Error(`Invalid ${label}: ${relativePath}`);
853
+ function isPublicationJournalState(value) {
854
+ return value === "staged" || value === "previous-output-moved" || value === "published";
855
+ }
856
+ async function isDirectory(path11) {
857
+ try {
858
+ return (await lstat(path11)).isDirectory();
859
+ } catch (error) {
860
+ if (isNotFoundError2(error)) return false;
861
+ throw error;
638
862
  }
639
- const file = resolve(directory, relativePath);
640
- const relativePathFromDirectory = relative(directory, file);
641
- if (relativePathFromDirectory.startsWith("..") || relativePathFromDirectory === "" || isAbsolutePath(relativePathFromDirectory)) {
642
- throw new Error(`Unsafe ${label}: ${relativePath}`);
863
+ }
864
+ async function moveWithRetry(source, destination) {
865
+ let error;
866
+ for (let attempt = 0; attempt < 3; attempt += 1) {
867
+ try {
868
+ await rename(source, destination);
869
+ return;
870
+ } catch (nextError) {
871
+ error = nextError;
872
+ if (!isRetryableRenameError(nextError) || attempt === 2) break;
873
+ await new Promise((resolve5) => setTimeout(resolve5, (attempt + 1) * 25));
874
+ }
643
875
  }
644
- return file;
876
+ throw error;
877
+ }
878
+ function isNotFoundError2(error) {
879
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
880
+ }
881
+ function isRetryableRenameError(error) {
882
+ return typeof error === "object" && error !== null && "code" in error && ["EBUSY", "EPERM", "EACCES"].includes(
883
+ error.code
884
+ );
645
885
  }
646
886
 
647
887
  // src/ssg/build_output.ts
888
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
889
+ import { mkdir as mkdir2, readdir as readdir2, readFile as readFile3, rename as rename2, rm as rm2, stat } from "node:fs/promises";
890
+ import { dirname as dirname3, join as join3 } from "node:path";
648
891
  var CLOUDFLARE_WORKER_ASSET_LIMIT = 25 * 1024 * 1024;
649
892
  async function findOversizedAssets(directory, relativeDirectory = "") {
650
- const entries = await readdir(directory, { withFileTypes: true }).catch(
893
+ const entries = await readdir2(directory, { withFileTypes: true }).catch(
651
894
  (error) => {
652
895
  if (isMissingDirectoryError(error)) return [];
653
896
  throw error;
@@ -655,8 +898,8 @@ async function findOversizedAssets(directory, relativeDirectory = "") {
655
898
  );
656
899
  const nestedAssets = await Promise.all(
657
900
  entries.map(async (entry) => {
658
- const path11 = join(directory, entry.name);
659
- const relativePath = join(relativeDirectory, entry.name).replaceAll(
901
+ const path11 = join3(directory, entry.name);
902
+ const relativePath = join3(relativeDirectory, entry.name).replaceAll(
660
903
  "\\",
661
904
  "/"
662
905
  );
@@ -674,30 +917,30 @@ function formatBytes(bytes) {
674
917
  return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
675
918
  }
676
919
  async function emptyBuildOutputDirectory(outDir) {
677
- const entries = await readdir(outDir, { withFileTypes: true }).catch(
920
+ const entries = await readdir2(outDir, { withFileTypes: true }).catch(
678
921
  (error) => {
679
922
  if (isMissingDirectoryError(error)) return [];
680
923
  throw error;
681
924
  }
682
925
  );
683
926
  for (const entry of entries) {
684
- await rm(join(outDir, entry.name), { recursive: true, force: true });
927
+ await rm2(join3(outDir, entry.name), { recursive: true, force: true });
685
928
  }
686
929
  }
687
930
  async function preserveClientBuildArtifacts(outDir) {
688
931
  const manifestPath = ".vite/manifest.json";
689
932
  let manifestSource;
690
933
  try {
691
- manifestSource = await readFile(join(outDir, manifestPath), "utf8");
934
+ manifestSource = await readFile3(join3(outDir, manifestPath), "utf8");
692
935
  } catch (error) {
693
936
  if (isNotFoundError(error)) return void 0;
694
937
  throw error;
695
938
  }
696
939
  const paths = [manifestPath, ...collectClientAssetPaths(manifestSource)];
697
- const stagingDirectory = join(
698
- dirname(outDir),
940
+ const stagingDirectory = join3(
941
+ dirname3(outDir),
699
942
  ".riebeckite",
700
- `client-build-${randomUUID()}`
943
+ `client-build-${randomUUID2()}`
701
944
  );
702
945
  for (const relativePath of paths) {
703
946
  const source = resolveBuildArtifactPath(outDir, relativePath);
@@ -705,13 +948,13 @@ async function preserveClientBuildArtifacts(outDir) {
705
948
  stagingDirectory,
706
949
  relativePath
707
950
  );
708
- await mkdir(dirname(destination), { recursive: true });
709
- await rename(source, destination);
951
+ await mkdir2(dirname3(destination), { recursive: true });
952
+ await rename2(source, destination);
710
953
  }
711
954
  return {
712
955
  stagingDirectory,
713
956
  paths,
714
- manifestFingerprint: createHash("sha256").update(manifestSource).digest("hex")
957
+ manifestFingerprint: createHash2("sha256").update(manifestSource).digest("hex")
715
958
  };
716
959
  }
717
960
  async function restoreClientBuildArtifacts(outDir, artifacts) {
@@ -722,16 +965,16 @@ async function restoreClientBuildArtifacts(outDir, artifacts) {
722
965
  relativePath
723
966
  );
724
967
  const destination = resolveBuildArtifactPath(outDir, relativePath);
725
- await mkdir(dirname(destination), { recursive: true });
726
- await rename(source, destination);
968
+ await mkdir2(dirname3(destination), { recursive: true });
969
+ await rename2(source, destination);
727
970
  }
728
971
  }
729
972
  async function discardClientBuildArtifacts(artifacts) {
730
973
  if (!artifacts) return;
731
- await rm(artifacts.stagingDirectory, { recursive: true, force: true });
974
+ await rm2(artifacts.stagingDirectory, { recursive: true, force: true });
732
975
  }
733
976
  async function collectBuildOutputPaths(directory, relativeDirectory = "") {
734
- const entries = await readdir(directory, { withFileTypes: true }).catch(
977
+ const entries = await readdir2(directory, { withFileTypes: true }).catch(
735
978
  (error) => {
736
979
  if (isMissingDirectoryError(error)) return void 0;
737
980
  throw error;
@@ -740,14 +983,14 @@ async function collectBuildOutputPaths(directory, relativeDirectory = "") {
740
983
  if (!entries) return [];
741
984
  const paths = [];
742
985
  for (const entry of entries) {
743
- const relativePath = join(relativeDirectory, entry.name).replaceAll(
986
+ const relativePath = join3(relativeDirectory, entry.name).replaceAll(
744
987
  "\\",
745
988
  "/"
746
989
  );
747
990
  if (entry.isDirectory()) {
748
991
  paths.push(
749
992
  ...await collectBuildOutputPaths(
750
- join(directory, entry.name),
993
+ join3(directory, entry.name),
751
994
  relativePath
752
995
  )
753
996
  );
@@ -757,6 +1000,32 @@ async function collectBuildOutputPaths(directory, relativeDirectory = "") {
757
1000
  }
758
1001
  return paths.sort();
759
1002
  }
1003
+ async function verifyClientBuildArtifacts(input) {
1004
+ const manifestPath = ".vite/manifest.json";
1005
+ let manifestSource;
1006
+ try {
1007
+ manifestSource = await readFile3(
1008
+ resolveBuildArtifactPath(input.outDir, manifestPath),
1009
+ "utf8"
1010
+ );
1011
+ } catch {
1012
+ return false;
1013
+ }
1014
+ const paths = [manifestPath, ...collectClientAssetPaths(manifestSource)];
1015
+ for (const relativePath of paths) {
1016
+ const expectedChecksum = input.expectedInventory[relativePath];
1017
+ if (!expectedChecksum) return false;
1018
+ try {
1019
+ const actualChecksum = createHash2("sha256").update(
1020
+ await readFile3(resolveBuildArtifactPath(input.outDir, relativePath))
1021
+ ).digest("hex");
1022
+ if (actualChecksum !== expectedChecksum) return false;
1023
+ } catch {
1024
+ return false;
1025
+ }
1026
+ }
1027
+ return true;
1028
+ }
760
1029
  function collectClientAssetPaths(manifestSource) {
761
1030
  let manifest;
762
1031
  try {
@@ -843,131 +1112,24 @@ function inspectGeneratedHtmlPages(module, pages, log) {
843
1112
  }
844
1113
  }
845
1114
 
846
- // src/ssg/inventory.ts
847
- import { createHash as createHash2 } from "node:crypto";
848
- import { readdir as readdir2, readFile as readFile2 } from "node:fs/promises";
849
- import { join as join2, relative as relative2 } from "node:path";
850
- import { performance } from "node:perf_hooks";
851
- var APP_FINGERPRINT_IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
852
- "node_modules",
853
- ".riebeckite",
854
- "dist"
855
- ]);
856
- var APP_FINGERPRINT_CONFIG_FILES = [
857
- "riebeckite.config.ts",
858
- "riebeckite.config.mts",
859
- "riebeckite.config.cts",
860
- "riebeckite.config.js",
861
- "riebeckite.config.mjs",
862
- "riebeckite.config.cjs"
863
- ];
864
- async function computeAppFingerprint(root, configFile) {
865
- const files = [];
866
- await collectAppFiles(join2(root, "app"), files);
867
- if (configFile) files.push(configFile);
868
- for (const name of APP_FINGERPRINT_CONFIG_FILES) {
869
- files.push(join2(root, name));
870
- }
871
- files.sort();
872
- const hash = createHash2("sha256");
873
- for (const file of files) {
874
- let content;
875
- try {
876
- content = await readFile2(file);
877
- } catch {
878
- continue;
879
- }
880
- hash.update(relative2(root, file).replaceAll("\\", "/"));
881
- hash.update("\0");
882
- hash.update(content);
883
- hash.update("\0");
884
- }
885
- return hash.digest("hex");
886
- }
887
- async function fingerprintDirectory(directory) {
888
- const inventory = await fingerprintOutputDirectory(directory);
889
- const hash = createHash2("sha256");
890
- for (const [path11, checksum] of Object.entries(inventory).sort(
891
- ([left], [right]) => left.localeCompare(right)
892
- )) {
893
- hash.update(path11).update("\0").update(checksum).update("\0");
894
- }
895
- return hash.digest("hex");
896
- }
897
- async function fingerprintOutputDirectory(directory, relativeDirectory = "", metrics) {
898
- const entries = await readdir2(directory, { withFileTypes: true }).catch(
899
- (error) => {
900
- if (isMissingDirectoryError(error)) return void 0;
901
- throw error;
902
- }
903
- );
904
- if (!entries) return {};
905
- const inventory = {};
906
- for (const entry of entries) {
907
- const file = join2(directory, entry.name);
908
- const relativePath = join2(relativeDirectory, entry.name).replaceAll(
909
- "\\",
910
- "/"
911
- );
912
- if (entry.isDirectory()) {
913
- Object.assign(
914
- inventory,
915
- await fingerprintOutputDirectory(file, relativePath, metrics)
916
- );
917
- continue;
918
- }
919
- if (entry.isFile()) {
920
- const hashedAt = performance.now();
921
- const content = await readFile2(file);
922
- inventory[relativePath] = createHash2("sha256").update(content).digest("hex");
923
- if (metrics) {
924
- metrics.outputHashValidationDurationMs += performance.now() - hashedAt;
925
- metrics.outputFilesHashed += 1;
926
- metrics.outputBytesHashed += content.length;
927
- }
928
- }
929
- }
930
- return inventory;
931
- }
932
- function inventoriesEqual(left, right) {
933
- const leftPaths = Object.keys(left);
934
- const rightPaths = Object.keys(right);
935
- return leftPaths.length === rightPaths.length && leftPaths.every((path11) => left[path11] === right[path11]);
936
- }
937
- async function collectAppFiles(directory, files) {
938
- const entries = await readdir2(directory, { withFileTypes: true }).catch(
939
- () => void 0
940
- );
941
- if (!entries) return;
942
- for (const entry of entries) {
943
- const full = join2(directory, entry.name);
944
- if (entry.isDirectory()) {
945
- if (APP_FINGERPRINT_IGNORED_DIRECTORIES.has(entry.name)) continue;
946
- await collectAppFiles(full, files);
947
- } else if (entry.isFile()) {
948
- files.push(full);
949
- }
950
- }
951
- }
952
-
953
1115
  // src/ssg/output_cache.ts
954
- import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
1116
+ import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
955
1117
  import { createReadStream } from "node:fs";
956
1118
  import {
957
1119
  copyFile,
958
- lstat,
959
- mkdir as mkdir2,
1120
+ lstat as lstat2,
1121
+ mkdir as mkdir3,
960
1122
  readdir as readdir3,
961
- readFile as readFile3,
962
- rename as rename2,
963
- rm as rm2,
964
- writeFile as writeFile2
1123
+ readFile as readFile4,
1124
+ rename as rename3,
1125
+ rm as rm3,
1126
+ writeFile as writeFile3
965
1127
  } from "node:fs/promises";
966
- import { dirname as dirname2, join as join3 } from "node:path";
1128
+ import { dirname as dirname4, join as join4 } from "node:path";
967
1129
  import { performance as performance3 } from "node:perf_hooks";
968
1130
 
969
1131
  // src/ssg/runtime_metrics.ts
970
- import { writeFile } from "node:fs/promises";
1132
+ import { writeFile as writeFile2 } from "node:fs/promises";
971
1133
  import { performance as performance2 } from "node:perf_hooks";
972
1134
  async function measure(timingsMs, name, fn) {
973
1135
  if (!timingsMs) return await fn();
@@ -992,7 +1154,7 @@ function measureSync(timingsMs, name, fn) {
992
1154
  async function writeSsgOutputMetrics(metrics) {
993
1155
  const file = process.env.RIEBECKITE_SSG_METRICS_FILE;
994
1156
  if (!file) return;
995
- await writeFile(file, `${JSON.stringify(metrics)}
1157
+ await writeFile2(file, `${JSON.stringify(metrics)}
996
1158
  `, "utf8");
997
1159
  }
998
1160
 
@@ -1019,7 +1181,7 @@ function createNoChangeFastPathOutputMetrics() {
1019
1181
  };
1020
1182
  }
1021
1183
  async function verifyNoChangeFastPath(input) {
1022
- const outputCachePath = join3(
1184
+ const outputCachePath = join4(
1023
1185
  input.root,
1024
1186
  ".riebeckite",
1025
1187
  "ssg-output-cache.json"
@@ -1054,9 +1216,9 @@ async function verifyNoChangeFastPath(input) {
1054
1216
  }
1055
1217
  return { used: true };
1056
1218
  }
1057
- async function loadOutputCache(path11, timingsMs, log = () => {
1219
+ async function loadOutputCacheMetadata(path11, timingsMs, log = () => {
1058
1220
  }) {
1059
- if (!await isSafeOutputCacheDirectory(dirname2(path11))) {
1221
+ if (!await isSafeOutputCacheDirectory(dirname4(path11))) {
1060
1222
  log("SSG output cache directory is unsafe and will be ignored.");
1061
1223
  return void 0;
1062
1224
  }
@@ -1068,7 +1230,7 @@ async function loadOutputCache(path11, timingsMs, log = () => {
1068
1230
  raw = await measure(
1069
1231
  timingsMs,
1070
1232
  "outputCacheRead",
1071
- () => readFile3(path11, "utf8")
1233
+ () => readFile4(path11, "utf8")
1072
1234
  );
1073
1235
  } catch (error) {
1074
1236
  if (isNotFoundError(error)) return void 0;
@@ -1090,20 +1252,22 @@ async function loadOutputCache(path11, timingsMs, log = () => {
1090
1252
  log("SSG output cache uses an unsupported format and will be rebuilt.");
1091
1253
  return void 0;
1092
1254
  }
1255
+ return timingsMs ? { ...parsed, fileSizeBytes: Buffer.byteLength(raw) } : parsed;
1256
+ }
1257
+ async function validateOutputCache(cache, path11, timingsMs, log = () => {
1258
+ }) {
1093
1259
  const entriesAreValid = await measure(
1094
1260
  timingsMs,
1095
1261
  "outputCacheEntriesValidate",
1096
- () => validateOutputCacheEntries(path11, parsed.outputs, timingsMs)
1262
+ () => validateOutputCacheEntries(path11, cache.outputs, timingsMs)
1097
1263
  );
1098
- if (!entriesAreValid) {
1099
- log("SSG output cache entries are corrupted and will be rebuilt.");
1100
- return void 0;
1101
- }
1102
- return timingsMs ? { ...parsed, fileSizeBytes: Buffer.byteLength(raw) } : parsed;
1264
+ if (entriesAreValid) return true;
1265
+ log("SSG output cache entries are corrupted and will be rebuilt.");
1266
+ return false;
1103
1267
  }
1104
1268
  async function saveOutputCache(path11, state, outputDirectory, timingsMs) {
1105
- const directory = dirname2(path11);
1106
- await mkdir2(directory, { recursive: true });
1269
+ const directory = dirname4(path11);
1270
+ await mkdir3(directory, { recursive: true });
1107
1271
  if (!await isSafeOutputCacheDirectory(directory)) {
1108
1272
  throw new Error(`Unsafe SSG output cache directory: ${directory}`);
1109
1273
  }
@@ -1111,7 +1275,7 @@ async function saveOutputCache(path11, state, outputDirectory, timingsMs) {
1111
1275
  throw new Error(`Unsafe SSG output cache file: ${path11}`);
1112
1276
  }
1113
1277
  const entriesPath = outputCacheEntriesPath(path11);
1114
- const temporaryPath = `${path11}.${randomUUID2()}.tmp`;
1278
+ const temporaryPath = `${path11}.${randomUUID3()}.tmp`;
1115
1279
  try {
1116
1280
  const outputs = await measure(
1117
1281
  timingsMs,
@@ -1133,7 +1297,7 @@ async function saveOutputCache(path11, state, outputDirectory, timingsMs) {
1133
1297
  await measure(
1134
1298
  timingsMs,
1135
1299
  "outputCacheWrite",
1136
- () => writeFile2(temporaryPath, serialized, "utf8")
1300
+ () => writeFile3(temporaryPath, serialized, "utf8")
1137
1301
  );
1138
1302
  await measure(
1139
1303
  timingsMs,
@@ -1155,18 +1319,18 @@ async function saveOutputCache(path11, state, outputDirectory, timingsMs) {
1155
1319
  );
1156
1320
  return checksum;
1157
1321
  } catch (error) {
1158
- await rm2(temporaryPath, { force: true }).catch(() => void 0);
1322
+ await rm3(temporaryPath, { force: true }).catch(() => void 0);
1159
1323
  throw error;
1160
1324
  }
1161
1325
  }
1162
1326
  function isOutputCacheState(value) {
1163
1327
  if (typeof value !== "object" || value === null) return false;
1164
1328
  const candidate = value;
1165
- return candidate.version === 4 && (candidate.appFingerprint === void 0 || typeof candidate.appFingerprint === "string") && (candidate.clientManifestFingerprint === void 0 || typeof candidate.clientManifestFingerprint === "string") && isOutputCacheEntries(candidate.outputs) && (candidate.finalOutputInventory === void 0 || isOutputInventory(candidate.finalOutputInventory)) && (candidate.publicDirectory === void 0 || typeof candidate.publicDirectory === "string") && (candidate.publicFingerprint === void 0 || typeof candidate.publicFingerprint === "string") && (candidate.configFile === void 0 || typeof candidate.configFile === "string");
1329
+ return candidate.version === 4 && (candidate.appFingerprint === void 0 || typeof candidate.appFingerprint === "string") && (candidate.bundleFingerprint === void 0 || typeof candidate.bundleFingerprint === "string") && (candidate.clientManifestFingerprint === void 0 || typeof candidate.clientManifestFingerprint === "string") && isOutputCacheEntries(candidate.outputs) && (candidate.finalOutputInventory === void 0 || isOutputInventory(candidate.finalOutputInventory)) && (candidate.publicDirectory === void 0 || typeof candidate.publicDirectory === "string") && (candidate.publicFingerprint === void 0 || typeof candidate.publicFingerprint === "string") && (candidate.configFile === void 0 || typeof candidate.configFile === "string");
1166
1330
  }
1167
1331
  function isOutputInventory(value) {
1168
1332
  return typeof value === "object" && value !== null && !Array.isArray(value) && Object.entries(value).every(
1169
- ([outputPath2, checksum]) => isSafeLogicalOutputPath(outputPath2) && isChecksum(checksum)
1333
+ ([outputPath, checksum]) => isSafeLogicalOutputPath(outputPath) && isChecksum(checksum)
1170
1334
  );
1171
1335
  }
1172
1336
  function isOutputCacheEntries(value) {
@@ -1174,7 +1338,7 @@ function isOutputCacheEntries(value) {
1174
1338
  return false;
1175
1339
  }
1176
1340
  return Object.entries(value).every(
1177
- ([outputPath2, entry]) => isSafeLogicalOutputPath(outputPath2) && typeof entry === "object" && entry !== null && typeof entry.cachePath === "string" && entry.cachePath === outputCacheEntryName(outputPath2) && isChecksum(entry.checksum)
1341
+ ([outputPath, entry]) => isSafeLogicalOutputPath(outputPath) && typeof entry === "object" && entry !== null && typeof entry.cachePath === "string" && entry.cachePath === outputCacheEntryName(outputPath) && isChecksum(entry.checksum)
1178
1342
  );
1179
1343
  }
1180
1344
  function outputCacheEntriesPath(outputCachePath) {
@@ -1183,30 +1347,30 @@ function outputCacheEntriesPath(outputCachePath) {
1183
1347
  async function saveOutputCacheEntries(directory, outputDirectory, outputs, finalOutputInventory, timingsMs) {
1184
1348
  await ensureOutputCacheEntriesDirectory(directory);
1185
1349
  const entries = {};
1186
- for (const outputPath2 of Object.keys(outputs).sort()) {
1187
- assertSafeLogicalOutputPath(outputPath2);
1188
- const existing = outputs[outputPath2];
1350
+ for (const outputPath of Object.keys(outputs).sort()) {
1351
+ assertSafeLogicalOutputPath(outputPath);
1352
+ const existing = outputs[outputPath];
1189
1353
  if (existing.cachePath && existing.checksum) {
1190
- if (existing.cachePath !== outputCacheEntryName(outputPath2) || !isChecksum(existing.checksum)) {
1191
- throw new Error(`Invalid SSG output cache entry: ${outputPath2}`);
1354
+ if (existing.cachePath !== outputCacheEntryName(outputPath) || !isChecksum(existing.checksum)) {
1355
+ throw new Error(`Invalid SSG output cache entry: ${outputPath}`);
1192
1356
  }
1193
- entries[outputPath2] = existing;
1357
+ entries[outputPath] = existing;
1194
1358
  continue;
1195
1359
  }
1196
- const source = resolveOutputCacheFile(outputDirectory, outputPath2);
1197
- const cachePath = outputCacheEntryName(outputPath2);
1198
- const destination = join3(directory, cachePath);
1360
+ const source = resolveOutputCacheFile(outputDirectory, outputPath);
1361
+ const cachePath = outputCacheEntryName(outputPath);
1362
+ const destination = join4(directory, cachePath);
1199
1363
  await replaceOutputCacheEntry(source, destination, timingsMs);
1200
- const checksum = finalOutputInventory?.[outputPath2];
1364
+ const checksum = finalOutputInventory?.[outputPath];
1201
1365
  if (!checksum) {
1202
1366
  const cachedChecksum = await checksumFile(destination);
1203
1367
  if (!cachedChecksum) {
1204
- throw new Error(`Could not checksum cached output: ${outputPath2}`);
1368
+ throw new Error(`Could not checksum cached output: ${outputPath}`);
1205
1369
  }
1206
- entries[outputPath2] = { cachePath, checksum: cachedChecksum };
1370
+ entries[outputPath] = { cachePath, checksum: cachedChecksum };
1207
1371
  continue;
1208
1372
  }
1209
- entries[outputPath2] = { cachePath, checksum };
1373
+ entries[outputPath] = { cachePath, checksum };
1210
1374
  }
1211
1375
  return entries;
1212
1376
  }
@@ -1221,8 +1385,8 @@ async function validateOutputCacheEntries(outputCachePath, entries, timingsMs) {
1221
1385
  while (valid) {
1222
1386
  const next = entriesToValidate[nextEntryIndex++];
1223
1387
  if (!next) return;
1224
- const [outputPath2, entry] = next;
1225
- if (!isSafeLogicalOutputPath(outputPath2) || entry.cachePath !== outputCacheEntryName(outputPath2) || !isChecksum(entry.checksum)) {
1388
+ const [outputPath, entry] = next;
1389
+ if (!isSafeLogicalOutputPath(outputPath) || entry.cachePath !== outputCacheEntryName(outputPath) || !isChecksum(entry.checksum)) {
1226
1390
  valid = false;
1227
1391
  return;
1228
1392
  }
@@ -1274,20 +1438,20 @@ function createFastPathCacheState(state, outputCacheChecksum) {
1274
1438
  };
1275
1439
  }
1276
1440
  async function saveFastPathCache(path11, state, timingsMs) {
1277
- const directory = dirname2(path11);
1278
- await mkdir2(directory, { recursive: true });
1441
+ const directory = dirname4(path11);
1442
+ await mkdir3(directory, { recursive: true });
1279
1443
  if (!await isSafeOutputCacheDirectory(directory)) {
1280
1444
  throw new Error(`Unsafe SSG fast-path cache directory: ${directory}`);
1281
1445
  }
1282
1446
  if (!await isSafeCacheFileTarget(path11)) {
1283
1447
  throw new Error(`Unsafe SSG fast-path cache file: ${path11}`);
1284
1448
  }
1285
- const temporaryPath = `${path11}.${randomUUID2()}.tmp`;
1449
+ const temporaryPath = `${path11}.${randomUUID3()}.tmp`;
1286
1450
  try {
1287
1451
  await measure(
1288
1452
  timingsMs,
1289
1453
  "sidecarWrite",
1290
- () => writeFile2(temporaryPath, `${JSON.stringify(state)}
1454
+ () => writeFile3(temporaryPath, `${JSON.stringify(state)}
1291
1455
  `, "utf8")
1292
1456
  );
1293
1457
  await measure(
@@ -1296,15 +1460,15 @@ async function saveFastPathCache(path11, state, timingsMs) {
1296
1460
  () => replaceFile(temporaryPath, path11)
1297
1461
  );
1298
1462
  } catch (error) {
1299
- await rm2(temporaryPath, { force: true }).catch(() => void 0);
1463
+ await rm3(temporaryPath, { force: true }).catch(() => void 0);
1300
1464
  throw error;
1301
1465
  }
1302
1466
  }
1303
1467
  async function loadFastPathCache(path11) {
1304
1468
  try {
1305
- if (!await isSafeOutputCacheDirectory(dirname2(path11))) return void 0;
1469
+ if (!await isSafeOutputCacheDirectory(dirname4(path11))) return void 0;
1306
1470
  if (!await isRegularFile(path11)) return void 0;
1307
- const candidate = JSON.parse(await readFile3(path11, "utf8"));
1471
+ const candidate = JSON.parse(await readFile4(path11, "utf8"));
1308
1472
  return isFastPathCacheState(candidate) ? candidate : void 0;
1309
1473
  } catch {
1310
1474
  return void 0;
@@ -1328,11 +1492,11 @@ async function checksumFile(path11) {
1328
1492
  }
1329
1493
  async function replaceFile(temporaryPath, targetPath) {
1330
1494
  try {
1331
- await rename2(temporaryPath, targetPath);
1495
+ await rename3(temporaryPath, targetPath);
1332
1496
  } catch (error) {
1333
1497
  if (!isReplacementFailure(error)) throw error;
1334
- await rm2(targetPath, { force: true });
1335
- await rename2(temporaryPath, targetPath);
1498
+ await rm3(targetPath, { force: true });
1499
+ await rename3(temporaryPath, targetPath);
1336
1500
  }
1337
1501
  }
1338
1502
  function isReplacementFailure(error) {
@@ -1347,7 +1511,7 @@ async function decodeOutput(outputCachePath, entry) {
1347
1511
  outputCacheEntriesPath(outputCachePath),
1348
1512
  entry.cachePath
1349
1513
  );
1350
- const content = await readFile3(file);
1514
+ const content = await readFile4(file);
1351
1515
  const checksum = createHash3("sha256").update(content).digest("hex");
1352
1516
  if (checksum !== entry.checksum) {
1353
1517
  throw new Error("SSG output cache entry checksum mismatch.");
@@ -1377,21 +1541,21 @@ function assertSafeLogicalOutputPath(path11) {
1377
1541
  throw new Error(`Invalid SSG output path: ${path11}`);
1378
1542
  }
1379
1543
  }
1380
- function outputCacheEntryName(outputPath2) {
1381
- return createHash3("sha256").update(outputPath2).digest("hex");
1544
+ function outputCacheEntryName(outputPath) {
1545
+ return createHash3("sha256").update(outputPath).digest("hex");
1382
1546
  }
1383
1547
  function isChecksum(value) {
1384
1548
  return typeof value === "string" && /^[a-f0-9]{64}$/u.test(value);
1385
1549
  }
1386
1550
  async function ensureOutputCacheEntriesDirectory(directory) {
1387
- await mkdir2(directory, { recursive: true });
1551
+ await mkdir3(directory, { recursive: true });
1388
1552
  if (!await isSafeOutputCacheEntriesDirectory(directory)) {
1389
1553
  throw new Error(`Unsafe SSG output cache entries directory: ${directory}`);
1390
1554
  }
1391
1555
  }
1392
1556
  async function isSafeOutputCacheDirectory(directory) {
1393
1557
  try {
1394
- const info = await lstat(directory);
1558
+ const info = await lstat2(directory);
1395
1559
  return info.isDirectory() && !info.isSymbolicLink();
1396
1560
  } catch {
1397
1561
  return false;
@@ -1399,7 +1563,7 @@ async function isSafeOutputCacheDirectory(directory) {
1399
1563
  }
1400
1564
  async function isSafeCacheFileTarget(path11) {
1401
1565
  try {
1402
- return !(await lstat(path11)).isSymbolicLink();
1566
+ return !(await lstat2(path11)).isSymbolicLink();
1403
1567
  } catch (error) {
1404
1568
  return isNotFoundError(error);
1405
1569
  }
@@ -1409,22 +1573,22 @@ async function isSafeOutputCacheEntriesDirectory(directory) {
1409
1573
  }
1410
1574
  async function isRegularFile(path11) {
1411
1575
  try {
1412
- const info = await lstat(path11);
1576
+ const info = await lstat2(path11);
1413
1577
  return info.isFile() && !info.isSymbolicLink();
1414
1578
  } catch {
1415
1579
  return false;
1416
1580
  }
1417
1581
  }
1418
1582
  async function replaceOutputCacheEntry(source, destination, timingsMs) {
1419
- if ((await lstat(destination).catch(() => void 0))?.isSymbolicLink()) {
1583
+ if ((await lstat2(destination).catch(() => void 0))?.isSymbolicLink()) {
1420
1584
  throw new Error(`Unsafe SSG output cache entry: ${destination}`);
1421
1585
  }
1422
- const temporaryPath = `${destination}.${randomUUID2()}.tmp`;
1586
+ const temporaryPath = `${destination}.${randomUUID3()}.tmp`;
1423
1587
  try {
1424
1588
  await measure(
1425
1589
  timingsMs,
1426
1590
  "outputCacheEntryWrite",
1427
- () => writeFile2(temporaryPath, new Uint8Array())
1591
+ () => writeFile3(temporaryPath, new Uint8Array())
1428
1592
  );
1429
1593
  await measure(
1430
1594
  timingsMs,
@@ -1437,7 +1601,7 @@ async function replaceOutputCacheEntry(source, destination, timingsMs) {
1437
1601
  () => replaceFile(temporaryPath, destination)
1438
1602
  );
1439
1603
  } catch (error) {
1440
- await rm2(temporaryPath, { force: true }).catch(() => void 0);
1604
+ await rm3(temporaryPath, { force: true }).catch(() => void 0);
1441
1605
  throw error;
1442
1606
  }
1443
1607
  }
@@ -1456,12 +1620,12 @@ async function collectUnreferencedOutputCacheEntries(directory, outputs, timings
1456
1620
  if (!/^[a-f0-9]{64}$/u.test(entry.name) || referenced.has(entry.name)) {
1457
1621
  continue;
1458
1622
  }
1459
- const path11 = join3(directory, entry.name);
1623
+ const path11 = join4(directory, entry.name);
1460
1624
  if (await isRegularFile(path11)) {
1461
1625
  await measure(
1462
1626
  timingsMs,
1463
1627
  "outputCacheGcDelete",
1464
- () => rm2(path11, { force: true })
1628
+ () => rm3(path11, { force: true })
1465
1629
  );
1466
1630
  }
1467
1631
  }
@@ -1470,6 +1634,118 @@ async function collectUnreferencedOutputCacheEntries(directory, outputs, timings
1470
1634
  }
1471
1635
  }
1472
1636
 
1637
+ // src/ssg/runner.ts
1638
+ import { defaultExtensionMap, redirectPlugin, toSSG } from "hono/ssg";
1639
+ async function runSsg(options) {
1640
+ return await withSsgRenderEnvironment(
1641
+ options.incremental,
1642
+ () => toSSG(
1643
+ options.app,
1644
+ {
1645
+ writeFile: options.write,
1646
+ mkdir: async () => {
1647
+ }
1648
+ },
1649
+ {
1650
+ dir: options.outDir,
1651
+ plugins: [redirectPlugin(), ...options.plugins ?? []],
1652
+ extensionMap: options.extensionMap ?? defaultExtensionMap
1653
+ }
1654
+ )
1655
+ );
1656
+ }
1657
+ async function withSsgRenderEnvironment(incremental, operation) {
1658
+ const previousFullRegeneration = process.env.RIEBECKITE_SSG_FULL_REGENERATION;
1659
+ const previousSkipUnchanged = process.env.RIEBECKITE_SSG_SKIP_UNCHANGED;
1660
+ process.env.RIEBECKITE_SSG_FULL_REGENERATION = incremental ? "" : "1";
1661
+ process.env.RIEBECKITE_SSG_SKIP_UNCHANGED = incremental ? "1" : "";
1662
+ try {
1663
+ return await operation();
1664
+ } finally {
1665
+ restoreEnvironmentVariable(
1666
+ "RIEBECKITE_SSG_FULL_REGENERATION",
1667
+ previousFullRegeneration
1668
+ );
1669
+ restoreEnvironmentVariable(
1670
+ "RIEBECKITE_SSG_SKIP_UNCHANGED",
1671
+ previousSkipUnchanged
1672
+ );
1673
+ }
1674
+ }
1675
+ function restoreEnvironmentVariable(name, value) {
1676
+ if (value === void 0) delete process.env[name];
1677
+ else process.env[name] = value;
1678
+ }
1679
+
1680
+ // src/ssg/standalone.ts
1681
+ import { mkdir as mkdir4 } from "node:fs/promises";
1682
+ import { relative as relative3, resolve as resolve3 } from "node:path";
1683
+ import { pathToFileURL } from "node:url";
1684
+ import { build } from "vite";
1685
+ var standaloneSsgMode = "riebeckite-ssr";
1686
+ async function loadStandaloneSsgBundle(input) {
1687
+ const root = resolve3(input.root);
1688
+ const outputDirectory = resolve3(input.outputDirectory);
1689
+ await mkdir4(outputDirectory, { recursive: true });
1690
+ await build({
1691
+ root,
1692
+ configFile: input.config ? false : void 0,
1693
+ mode: standaloneSsgMode,
1694
+ ...input.config ? {
1695
+ define: input.config.define,
1696
+ oxc: input.config.oxc,
1697
+ plugins: [
1698
+ ...input.config.plugins.filter(
1699
+ (plugin) => plugin.name !== "riebeckite-ssg" && plugin.name !== "riebeckite-ssr-externals" && !plugin.name.startsWith("@hono/vite-build/")
1700
+ ),
1701
+ createRuntimeExternalPlugin(),
1702
+ ...input.clientOutputDirectory ? [createClientManifestPlugin(root, input.clientOutputDirectory)] : []
1703
+ ],
1704
+ resolve: {
1705
+ ...input.config.resolve,
1706
+ external: []
1707
+ }
1708
+ } : {},
1709
+ build: {
1710
+ emptyOutDir: false,
1711
+ outDir: outputDirectory,
1712
+ ssr: true,
1713
+ rollupOptions: {
1714
+ input: input.entry,
1715
+ output: { entryFileNames: "ssg-server.mjs", format: "es" }
1716
+ }
1717
+ },
1718
+ environments: { ssr: { resolve: { noExternal: true } } }
1719
+ });
1720
+ const module = await import(`${pathToFileURL(resolve3(outputDirectory, "ssg-server.mjs")).href}?v=${Date.now()}`);
1721
+ if (!module.default) {
1722
+ throw new Error(`Failed to find a default export from ${input.entry}.`);
1723
+ }
1724
+ return { app: module.default, module };
1725
+ }
1726
+ var runtimeExternalPackages = /* @__PURE__ */ new Set(["@d2lang/d2", "@marp-team/marp-core"]);
1727
+ function createRuntimeExternalPlugin() {
1728
+ return {
1729
+ name: "riebeckite-ssg-runtime-externals",
1730
+ enforce: "pre",
1731
+ async resolveId(source, importer) {
1732
+ if (!runtimeExternalPackages.has(source)) return void 0;
1733
+ const resolved = await this.resolve(source, importer, { skipSelf: true });
1734
+ return resolved ? { id: pathToFileURL(resolved.id).href, external: true } : void 0;
1735
+ }
1736
+ };
1737
+ }
1738
+ function createClientManifestPlugin(root, clientOutputDirectory) {
1739
+ const manifestPath = `/${relative3(root, clientOutputDirectory).replaceAll("\\", "/")}/.vite/manifest.json`;
1740
+ return {
1741
+ name: "riebeckite-client-manifest",
1742
+ enforce: "pre",
1743
+ transform(code, id) {
1744
+ return id.includes("honox/dist/server/components/") ? code.replaceAll("/dist/.vite/manifest.json", manifestPath) : void 0;
1745
+ }
1746
+ };
1747
+ }
1748
+
1473
1749
  // src/ssg_plugin.ts
1474
1750
  var defaultEntry = "./src/index.tsx";
1475
1751
  function riebeckiteSsg(options = {}) {
@@ -1477,34 +1753,60 @@ function riebeckiteSsg(options = {}) {
1477
1753
  const resolvedVirtualId = `\0${virtualId}`;
1478
1754
  const entry = options.entry ?? defaultEntry;
1479
1755
  let resolvedConfig;
1756
+ let publicationOutputDirectory;
1757
+ let clientOutputDirectory;
1758
+ let artifactWriter;
1480
1759
  let pendingOutputCache;
1481
1760
  let clientBuildArtifacts;
1482
1761
  return {
1483
1762
  name: "riebeckite-ssg",
1484
- apply: shouldApplyRiebeckiteSsg,
1763
+ apply: (_config, env) => env.command === "build",
1485
1764
  enforce: "post",
1486
- config() {
1765
+ config(config, env) {
1766
+ const root = resolve4(config.root ?? process.cwd());
1767
+ publicationOutputDirectory = resolve4(
1768
+ root,
1769
+ config.build?.outDir ?? "dist"
1770
+ );
1771
+ clientOutputDirectory = join5(root, ".riebeckite", "build-output-client");
1487
1772
  return {
1488
1773
  build: {
1489
- rollupOptions: {
1490
- input: [virtualId]
1491
- }
1774
+ outDir: env.mode === "client" ? clientOutputDirectory : join5(root, ".riebeckite", "build-output"),
1775
+ ...env.mode === "client" ? {} : { rollupOptions: { input: [virtualId] } }
1492
1776
  }
1493
1777
  };
1494
1778
  },
1495
1779
  configResolved(config) {
1496
1780
  resolvedConfig = config;
1781
+ if (config.mode === "client") {
1782
+ clientOutputDirectory = resolve4(config.root, config.build.outDir);
1783
+ }
1497
1784
  },
1498
1785
  async buildStart() {
1499
1786
  const config = resolvedConfig;
1500
- if (!config) return;
1501
- if (!config.plugins.some(
1502
- (plugin) => plugin.name.startsWith("@hono/vite-build/")
1503
- )) {
1787
+ if (!config || config.mode === "client") return;
1788
+ if (!publicationOutputDirectory) {
1789
+ throw new Error(
1790
+ "Riebeckite SSG could not resolve the publication output directory."
1791
+ );
1792
+ }
1793
+ artifactWriter = await createBuildArtifactWriter({
1794
+ outputDirectory: publicationOutputDirectory,
1795
+ stagingDirectory: resolve4(config.root, config.build.outDir)
1796
+ });
1797
+ const outDir = resolve4(config.root, config.build.outDir);
1798
+ clientBuildArtifacts = clientOutputDirectory ? await preserveClientBuildArtifacts(clientOutputDirectory) : void 0;
1799
+ if (!clientBuildArtifacts) {
1800
+ clientBuildArtifacts = await preserveClientBuildArtifacts(
1801
+ publicationOutputDirectory
1802
+ );
1803
+ }
1804
+ if (!clientBuildArtifacts) {
1805
+ if (await isDirectory2(publicationOutputDirectory)) {
1806
+ await artifactWriter.copyFrom(publicationOutputDirectory);
1807
+ }
1504
1808
  return;
1505
1809
  }
1506
- const outDir = resolve2(config.root, config.build.outDir);
1507
- clientBuildArtifacts = await preserveClientBuildArtifacts(outDir);
1508
1810
  logSsgDiagnostics(
1509
1811
  this,
1510
1812
  `client manifest ${clientBuildArtifacts ? `preserved (${clientBuildArtifacts.paths.length} files)` : "not found"}`
@@ -1519,42 +1821,20 @@ function riebeckiteSsg(options = {}) {
1519
1821
  },
1520
1822
  async generateBundle(_outputOptions, bundle) {
1521
1823
  const config = resolvedConfig;
1824
+ if (config?.mode === "client") return;
1522
1825
  if (!config) {
1523
1826
  throw new Error(
1524
1827
  "Riebeckite SSG could not resolve the Vite configuration."
1525
1828
  );
1526
1829
  }
1527
1830
  const timingsMs = process.env.RIEBECKITE_SSG_METRICS_FILE ? {} : void 0;
1528
- const outDir = resolve2(config.root, config.build.outDir);
1831
+ const outDir = resolve4(config.root, config.build.outDir);
1529
1832
  let viteClientAssetPaths = [];
1530
1833
  removeVirtualEntryChunk(bundle, resolvedVirtualId);
1531
- const server = await measure(
1532
- timingsMs,
1533
- "ssgSetup",
1534
- () => createServer({
1535
- root: config.root,
1536
- define: config.define,
1537
- resolve: {
1538
- ...config.resolve,
1539
- builtins: [...config.resolve.builtins, /^node:/]
1540
- },
1541
- plugins: [
1542
- {
1543
- name: "riebeckite-ssg-package-resolution",
1544
- enforce: "post",
1545
- configResolved(runtimeConfig) {
1546
- runtimeConfig.resolve.alias = [];
1547
- }
1548
- }
1549
- ],
1550
- build: { ssr: true },
1551
- oxc: { jsx: { runtime: "automatic", importSource: "hono/jsx" } },
1552
- environments: {
1553
- ssr: { resolve: { noExternal: [/^honox(?:\/.*)?$/] } }
1554
- },
1555
- mode: config.mode,
1556
- server: { watch: null }
1557
- })
1834
+ const bundleDirectory = join5(
1835
+ config.root,
1836
+ ".riebeckite",
1837
+ `ssg-bundle-${randomUUID4()}`
1558
1838
  );
1559
1839
  try {
1560
1840
  await restoreClientBuildArtifacts(outDir, clientBuildArtifacts);
@@ -1563,15 +1843,17 @@ function riebeckiteSsg(options = {}) {
1563
1843
  this,
1564
1844
  `SSR noExternal=${formatSsrNoExternal()} · client manifest ${clientBuildArtifacts ? "restored" : "not found"}`
1565
1845
  );
1566
- const module = await measure(
1846
+ const { app, module } = await measure(
1567
1847
  timingsMs,
1568
1848
  "ssrModuleLoad",
1569
- () => server.ssrLoadModule(entry)
1849
+ () => loadStandaloneSsgBundle({
1850
+ root: config.root,
1851
+ entry,
1852
+ outputDirectory: bundleDirectory,
1853
+ clientOutputDirectory: outDir,
1854
+ config
1855
+ })
1570
1856
  );
1571
- const app = module.default;
1572
- if (!app) {
1573
- throw new Error(`Failed to find a default export from ${entry}.`);
1574
- }
1575
1857
  const outputChangeSet = await measure(
1576
1858
  timingsMs,
1577
1859
  "outputDependencyResolution",
@@ -1582,12 +1864,17 @@ function riebeckiteSsg(options = {}) {
1582
1864
  "appFingerprint",
1583
1865
  () => computeAppFingerprint(config.root, config.configFile)
1584
1866
  );
1585
- const outputCachePath = join4(
1867
+ const bundleFingerprint = await measure(
1868
+ timingsMs,
1869
+ "bundleFingerprint",
1870
+ () => computeBundleFingerprint(config.root, config.configFile)
1871
+ );
1872
+ const outputCachePath = join5(
1586
1873
  config.root,
1587
1874
  ".riebeckite",
1588
1875
  "ssg-output-cache.json"
1589
1876
  );
1590
- const previousOutputCache = await loadOutputCache(
1877
+ let previousOutputCache = await loadOutputCacheMetadata(
1591
1878
  outputCachePath,
1592
1879
  timingsMs,
1593
1880
  (message) => this.warn(message)
@@ -1599,7 +1886,7 @@ function riebeckiteSsg(options = {}) {
1599
1886
  );
1600
1887
  viteClientAssetPaths = [
1601
1888
  .../* @__PURE__ */ new Set([...viteClientAssetPaths, ...Object.keys(bundle)])
1602
- ].filter((outputPath2) => !siteOwnedOutputPaths.has(outputPath2)).sort();
1889
+ ].filter((outputPath) => !siteOwnedOutputPaths.has(outputPath)).sort();
1603
1890
  const siteOutputCollisions = findBuildOutputSiteCollisions(
1604
1891
  Object.keys(bundle),
1605
1892
  siteOwnedOutputPaths
@@ -1612,7 +1899,7 @@ function riebeckiteSsg(options = {}) {
1612
1899
  const uncoveredUnchangedCount = outputChangeSet ? outputChangeSet.unchanged.filter(
1613
1900
  (output) => !siteOwnedOutputPaths.has(output.path) && !previousOutputCache?.outputs[output.path]
1614
1901
  ).length : 0;
1615
- const outputCacheDecision = {
1902
+ let outputCacheDecision = {
1616
1903
  changeSetPresent: outputChangeSet !== void 0,
1617
1904
  changeSetRequiresFullRegeneration: outputChangeSet?.fullRegenerationRequired ?? true,
1618
1905
  outputCacheLoaded: previousOutputCache !== void 0,
@@ -1620,7 +1907,20 @@ function riebeckiteSsg(options = {}) {
1620
1907
  clientManifestFingerprintMatch: previousOutputCache?.clientManifestFingerprint === clientBuildArtifacts?.manifestFingerprint,
1621
1908
  uncoveredUnchangedCount
1622
1909
  };
1623
- const outputCacheRejectionReason = decideOutputCacheRejection(outputCacheDecision);
1910
+ let outputCacheRejectionReason = decideOutputCacheRejection(outputCacheDecision);
1911
+ if (outputCacheRejectionReason === void 0 && previousOutputCache && !await validateOutputCache(
1912
+ previousOutputCache,
1913
+ outputCachePath,
1914
+ timingsMs,
1915
+ (message) => this.warn(message)
1916
+ )) {
1917
+ previousOutputCache = void 0;
1918
+ outputCacheDecision = {
1919
+ ...outputCacheDecision,
1920
+ outputCacheLoaded: false
1921
+ };
1922
+ outputCacheRejectionReason = decideOutputCacheRejection(outputCacheDecision);
1923
+ }
1624
1924
  const canUseIncremental = outputCacheRejectionReason === void 0;
1625
1925
  const reusablePaths = new Set(
1626
1926
  canUseIncremental ? (outputChangeSet?.unchanged ?? []).map((output) => output.path) : []
@@ -1643,6 +1943,7 @@ function riebeckiteSsg(options = {}) {
1643
1943
  const nextOutputCache = {
1644
1944
  version: 4,
1645
1945
  appFingerprint,
1946
+ bundleFingerprint,
1646
1947
  clientManifestFingerprint: clientBuildArtifacts?.manifestFingerprint,
1647
1948
  outputs: {},
1648
1949
  configFile: config.configFile
@@ -1691,64 +1992,54 @@ function riebeckiteSsg(options = {}) {
1691
1992
  outputCacheRejectionReason: outputCacheRejectionReason ?? null,
1692
1993
  timingsMs: timingsMs ?? {}
1693
1994
  };
1694
- process.env.RIEBECKITE_SSG_FULL_REGENERATION = canUseIncremental ? "" : "1";
1695
- process.env.RIEBECKITE_SSG_SKIP_UNCHANGED = canUseIncremental ? "1" : "";
1696
1995
  const result = await measure(
1697
1996
  timingsMs,
1698
1997
  "toSSG",
1699
- () => toSSG(
1998
+ () => runSsg({
1700
1999
  app,
1701
- {
1702
- writeFile: async (filePath, data) => {
1703
- const fileName = relative3(outDir, filePath).replaceAll(
1704
- "\\",
1705
- "/"
1706
- );
1707
- if (!inventoryPaths.has(fileName)) {
1708
- honoStaticRoutePaths.add(fileName);
1709
- }
1710
- if (siteOwnedOutputPaths.has(fileName)) {
1711
- shadowedOutputs.add(fileName);
1712
- return;
1713
- }
1714
- if (canUseIncremental && reusablePaths.has(fileName)) {
1715
- return;
1716
- }
1717
- if (fileName.endsWith(".html") && typeof data === "string") {
1718
- metrics.renderedOutputCount += 1;
1719
- metrics.renderedRouteCount += 1;
1720
- metrics.htmlOutputCount += 1;
1721
- generatedHtml.push({ path: fileName, html: data });
1722
- } else {
1723
- metrics.assetOutputCount += 1;
1724
- }
1725
- measureSync(
1726
- timingsMs,
1727
- "outputWrite",
1728
- () => this.emitFile({
1729
- type: "asset",
1730
- fileName,
1731
- source: data
1732
- })
2000
+ outDir,
2001
+ incremental: canUseIncremental,
2002
+ plugins: options.plugins,
2003
+ extensionMap: options.extensionMap,
2004
+ write: async (filePath, data) => {
2005
+ const fileName = relative4(outDir, filePath).replaceAll("\\", "/");
2006
+ if (!inventoryPaths.has(fileName)) {
2007
+ honoStaticRoutePaths.add(fileName);
2008
+ }
2009
+ if (siteOwnedOutputPaths.has(fileName)) {
2010
+ shadowedOutputs.add(fileName);
2011
+ return;
2012
+ }
2013
+ if (canUseIncremental && reusablePaths.has(fileName)) {
2014
+ return;
2015
+ }
2016
+ if (fileName.endsWith(".html") && typeof data === "string") {
2017
+ metrics.renderedOutputCount += 1;
2018
+ metrics.renderedRouteCount += 1;
2019
+ metrics.htmlOutputCount += 1;
2020
+ generatedHtml.push({ path: fileName, html: data });
2021
+ } else {
2022
+ metrics.assetOutputCount += 1;
2023
+ }
2024
+ if (!artifactWriter) {
2025
+ throw new Error(
2026
+ "Riebeckite SSG artifact writer was not initialized."
1733
2027
  );
1734
- metrics.emittedOutputCount += 1;
1735
- nextOutputCache.outputs[fileName] = {
1736
- cachePath: "",
1737
- checksum: ""
1738
- };
1739
- },
1740
- async mkdir() {
1741
2028
  }
1742
- },
1743
- {
1744
- dir: outDir,
1745
- plugins: [redirectPlugin(), ...options.plugins ?? []],
1746
- extensionMap: options.extensionMap ?? defaultExtensionMap
2029
+ const writer = artifactWriter;
2030
+ await measure(
2031
+ timingsMs,
2032
+ "outputWrite",
2033
+ () => writer.write(fileName, data)
2034
+ );
2035
+ metrics.emittedOutputCount += 1;
2036
+ nextOutputCache.outputs[fileName] = {
2037
+ cachePath: "",
2038
+ checksum: ""
2039
+ };
1747
2040
  }
1748
- )
2041
+ })
1749
2042
  );
1750
- delete process.env.RIEBECKITE_SSG_FULL_REGENERATION;
1751
- delete process.env.RIEBECKITE_SSG_SKIP_UNCHANGED;
1752
2043
  metrics.enumeratedRouteCount = result.files.length;
1753
2044
  if (!result.success) throw result.error;
1754
2045
  metrics.processedContentCount = module.content?.getProcessedContentCount() ?? 0;
@@ -1765,11 +2056,17 @@ function riebeckiteSsg(options = {}) {
1765
2056
  "generatedOutputs",
1766
2057
  () => emitGeneratedOutputs(
1767
2058
  module,
1768
- (asset) => {
1769
- measureSync(
2059
+ async (asset) => {
2060
+ if (!artifactWriter) {
2061
+ throw new Error(
2062
+ "Riebeckite SSG artifact writer was not initialized."
2063
+ );
2064
+ }
2065
+ const writer = artifactWriter;
2066
+ await measure(
1770
2067
  timingsMs,
1771
2068
  "outputWrite",
1772
- () => this.emitFile(asset)
2069
+ () => writer.write(asset.fileName, asset.source)
1773
2070
  );
1774
2071
  metrics.emittedOutputCount += 1;
1775
2072
  nextOutputCache.outputs[asset.fileName] = {
@@ -1796,11 +2093,17 @@ function riebeckiteSsg(options = {}) {
1796
2093
  }
1797
2094
  const cached = previousOutputCache.outputs[path11];
1798
2095
  if (!cached) continue;
1799
- this.emitFile({
1800
- type: "asset",
1801
- fileName: path11,
1802
- source: await decodeOutput(outputCachePath, cached)
1803
- });
2096
+ if (!artifactWriter) {
2097
+ throw new Error(
2098
+ "Riebeckite SSG artifact writer was not initialized."
2099
+ );
2100
+ }
2101
+ const writer = artifactWriter;
2102
+ await measure(
2103
+ timingsMs,
2104
+ "outputWrite",
2105
+ async () => writer.write(path11, await decodeOutput(outputCachePath, cached))
2106
+ );
1804
2107
  metrics.emittedOutputCount += 1;
1805
2108
  metrics.reusedOutputCount += 1;
1806
2109
  nextOutputCache.outputs[path11] = cached;
@@ -1810,9 +2113,12 @@ function riebeckiteSsg(options = {}) {
1810
2113
  if (outputChangeSet) {
1811
2114
  for (const output of outputChangeSet.removed) {
1812
2115
  if (siteOwnedOutputPaths.has(output.path)) continue;
1813
- await rm3(join4(outDir, output.path), {
1814
- force: true
1815
- });
2116
+ if (!artifactWriter) {
2117
+ throw new Error(
2118
+ "Riebeckite SSG artifact writer was not initialized."
2119
+ );
2120
+ }
2121
+ await artifactWriter.remove(output.path);
1816
2122
  metrics.deletedOutputCount += 1;
1817
2123
  }
1818
2124
  }
@@ -1827,6 +2133,12 @@ function riebeckiteSsg(options = {}) {
1827
2133
  metrics.cacheEntriesSerialized = Object.keys(
1828
2134
  nextOutputCache.outputs
1829
2135
  ).length;
2136
+ const manifest = await module.content?.getManifest();
2137
+ const publicationFingerprint = manifest ? fingerprintPublication(
2138
+ publicationEntriesFromManifest(manifest),
2139
+ publicationRedirectsFromManifest(manifest),
2140
+ publicationOutputsFromManifest(manifest)
2141
+ ) : void 0;
1830
2142
  pendingOutputCache = {
1831
2143
  path: outputCachePath,
1832
2144
  state: nextOutputCache,
@@ -1835,6 +2147,7 @@ function riebeckiteSsg(options = {}) {
1835
2147
  outDir,
1836
2148
  publicDir: config.publicDir,
1837
2149
  configFile: config.configFile,
2150
+ ...publicationFingerprint === void 0 ? {} : { publicationFingerprint },
1838
2151
  outputPlanInput: {
1839
2152
  inventory,
1840
2153
  affectedPaths: new Set(
@@ -1845,7 +2158,14 @@ function riebeckiteSsg(options = {}) {
1845
2158
  honoStaticRoutePaths,
1846
2159
  viteClientAssetPaths: new Set(viteClientAssetPaths),
1847
2160
  sitePublicAssetPaths: siteOwnedOutputPaths
1848
- }
2161
+ },
2162
+ provenance: module.content?.getProvenance(),
2163
+ content: module.content,
2164
+ reusablePaths: new Set(
2165
+ [...reusablePaths].filter(
2166
+ (path11) => !siteOwnedOutputPaths.has(path11)
2167
+ )
2168
+ )
1849
2169
  };
1850
2170
  this.info(
1851
2171
  `SSG outputs: ${metrics.renderedOutputCount} rendered · ${metrics.reusedOutputCount} reused · ${metrics.deletedOutputCount} removed`
@@ -1856,8 +2176,11 @@ function riebeckiteSsg(options = {}) {
1856
2176
  });
1857
2177
  logGeneratedHtmlAssetDiagnostics(this, generatedHtml);
1858
2178
  } finally {
1859
- await server.close();
2179
+ await rm4(bundleDirectory, { recursive: true, force: true });
1860
2180
  await discardClientBuildArtifacts(clientBuildArtifacts);
2181
+ if (clientOutputDirectory) {
2182
+ await rm4(clientOutputDirectory, { recursive: true, force: true });
2183
+ }
1861
2184
  clientBuildArtifacts = void 0;
1862
2185
  }
1863
2186
  },
@@ -1865,7 +2188,14 @@ function riebeckiteSsg(options = {}) {
1865
2188
  order: "post",
1866
2189
  async handler() {
1867
2190
  if (!resolvedConfig) return;
1868
- const outDir = resolve2(
2191
+ if (resolvedConfig.mode === "client") return;
2192
+ const outputDirectory = publicationOutputDirectory;
2193
+ if (!outputDirectory) {
2194
+ throw new Error(
2195
+ "Riebeckite SSG could not resolve the publication output directory."
2196
+ );
2197
+ }
2198
+ const outDir = resolve4(
1869
2199
  resolvedConfig.root,
1870
2200
  resolvedConfig.build.outDir
1871
2201
  );
@@ -1877,13 +2207,26 @@ function riebeckiteSsg(options = {}) {
1877
2207
  }
1878
2208
  const outputCache = pendingOutputCache;
1879
2209
  if (!outputCache) return;
2210
+ let published = false;
1880
2211
  try {
2212
+ if (!artifactWriter) {
2213
+ throw new Error(
2214
+ "Riebeckite SSG artifact writer was not initialized."
2215
+ );
2216
+ }
1881
2217
  outputCache.state.finalOutputInventory = await measure(
1882
2218
  outputCache.timingsMs,
1883
2219
  "outputInventory",
1884
2220
  () => fingerprintOutputDirectory(outputCache.outDir)
1885
2221
  );
1886
2222
  const finalOutputInventory = outputCache.state.finalOutputInventory;
2223
+ if (outputCache.provenance && outputCache.content) {
2224
+ await outputCache.content.attachFinalOutputArtifacts(
2225
+ outputCache.provenance.buildId,
2226
+ finalOutputInventory,
2227
+ outputCache.reusablePaths
2228
+ );
2229
+ }
1887
2230
  const outputPlanRssBefore = process.memoryUsage().rss;
1888
2231
  const outputPlan = measureSync(
1889
2232
  outputCache.timingsMs,
@@ -1922,32 +2265,57 @@ function riebeckiteSsg(options = {}) {
1922
2265
  process.memoryUsage().rss - outputPlanRssBefore
1923
2266
  );
1924
2267
  const publicDir = outputCache.publicDir;
1925
- outputCache.state.publicDirectory = publicDir ? resolve2(publicDir) : void 0;
2268
+ outputCache.state.publicDirectory = publicDir ? resolve4(publicDir) : void 0;
1926
2269
  outputCache.state.publicFingerprint = publicDir ? await measure(
1927
2270
  outputCache.timingsMs,
1928
2271
  "publicFingerprint",
1929
- () => fingerprintDirectory(resolve2(publicDir))
2272
+ () => fingerprintDirectory(resolve4(publicDir))
1930
2273
  ) : void 0;
1931
- await saveOutputCache(
1932
- outputCache.path,
1933
- outputCache.state,
1934
- outputCache.outDir,
1935
- outputCache.timingsMs
1936
- );
1937
- } catch (error) {
1938
- this.warn(
1939
- `SSG output cache could not be saved; the next build regenerates every output. ${error instanceof Error ? error.message : String(error)}`
1940
- );
2274
+ try {
2275
+ await saveOutputCache(
2276
+ outputCache.path,
2277
+ outputCache.state,
2278
+ outputCache.outDir,
2279
+ outputCache.timingsMs
2280
+ );
2281
+ } catch (error) {
2282
+ this.warn(
2283
+ `SSG output cache could not be saved; the next build regenerates every output. ${error instanceof Error ? error.message : String(error)}`
2284
+ );
2285
+ }
2286
+ await artifactWriter.publish();
2287
+ published = true;
2288
+ await writePublicationMarker({
2289
+ root: resolvedConfig.root,
2290
+ outputDirectory,
2291
+ publicationFingerprint: outputCache.publicationFingerprint,
2292
+ warn: (message) => this.warn(message)
2293
+ });
1941
2294
  } finally {
2295
+ if (!published) await artifactWriter?.discard();
1942
2296
  await writeSsgOutputMetrics(outputCache.metrics);
1943
2297
  pendingOutputCache = void 0;
2298
+ artifactWriter = void 0;
1944
2299
  }
1945
2300
  }
2301
+ },
2302
+ async buildEnd(error) {
2303
+ if (!error || !artifactWriter) return;
2304
+ await artifactWriter.discard();
2305
+ artifactWriter = void 0;
2306
+ pendingOutputCache = void 0;
1946
2307
  }
1947
2308
  };
1948
2309
  }
1949
- function shouldApplyRiebeckiteSsg(_config, env) {
1950
- return env.command === "build" && env.mode !== "client";
2310
+ async function isDirectory2(path11) {
2311
+ try {
2312
+ return (await lstat3(path11)).isDirectory();
2313
+ } catch (error) {
2314
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
2315
+ return false;
2316
+ }
2317
+ throw error;
2318
+ }
1951
2319
  }
1952
2320
  function findBuildOutputSiteCollisions(buildOutputPaths, siteOwnedOutputPaths) {
1953
2321
  const collisions = /* @__PURE__ */ new Set();
@@ -1968,7 +2336,7 @@ async function emitGeneratedOutputs(module, emit, affectedPaths, shadowedPaths,
1968
2336
  onShadowed?.(output.path);
1969
2337
  continue;
1970
2338
  }
1971
- emit({
2339
+ await emit({
1972
2340
  type: "asset",
1973
2341
  fileName: output.path,
1974
2342
  source: output.content
@@ -1984,6 +2352,27 @@ function removeVirtualEntryChunk(bundle, virtualEntryId) {
1984
2352
  }
1985
2353
  }
1986
2354
  }
2355
+ async function writePublicationMarker(input) {
2356
+ const path11 = join5(input.root, ".riebeckite", BUILD_OUTPUT_MARKER_FILE);
2357
+ try {
2358
+ await mkdir5(dirname5(path11), { recursive: true });
2359
+ await writeFile4(
2360
+ path11,
2361
+ serializeBuildOutputMarker(
2362
+ createBuildOutputMarker({
2363
+ outputDirectory: input.outputDirectory,
2364
+ ...input.publicationFingerprint === void 0 ? {} : { publicationFingerprint: input.publicationFingerprint },
2365
+ completedAt: /* @__PURE__ */ new Date()
2366
+ })
2367
+ ),
2368
+ "utf8"
2369
+ );
2370
+ } catch (error) {
2371
+ input.warn(
2372
+ `Could not write the publication marker; publish will rebuild before deploying. ${error instanceof Error ? error.message : String(error)}`
2373
+ );
2374
+ }
2375
+ }
1987
2376
 
1988
2377
  // src/ssg.ts
1989
2378
  var defaultSsgEntry = "./app/server.ts";
@@ -2011,10 +2400,11 @@ function createRiebeckiteSsg(options = {}) {
2011
2400
 
2012
2401
  // src/vite_plugin.ts
2013
2402
  import path10 from "node:path";
2403
+ import { riebeckiteDevelopmentInspector } from "@riebeckite/honox-inspector";
2014
2404
 
2015
2405
  // src/asset_entries.ts
2016
2406
  import fs6 from "node:fs";
2017
- import path8 from "node:path";
2407
+ import path7 from "node:path";
2018
2408
  import { uniqueStrings } from "@riebeckite/core";
2019
2409
  function writeRiebeckiteAssetEntries(config, paths) {
2020
2410
  writeGeneratedFile(paths.frameworkStyles, createFrameworkStylesEntry());
@@ -2055,18 +2445,18 @@ ${imports}
2055
2445
  }
2056
2446
  function writeGeneratedFile(filePath, contents) {
2057
2447
  if (readGeneratedFile(filePath) === contents) return;
2058
- fs6.mkdirSync(path8.dirname(filePath), { recursive: true });
2448
+ fs6.mkdirSync(path7.dirname(filePath), { recursive: true });
2059
2449
  fs6.writeFileSync(filePath, contents);
2060
2450
  }
2061
2451
  function readGeneratedFile(filePath) {
2062
2452
  try {
2063
2453
  return fs6.readFileSync(filePath, "utf8");
2064
2454
  } catch (error) {
2065
- if (isNotFoundError2(error)) return void 0;
2455
+ if (isNotFoundError3(error)) return void 0;
2066
2456
  throw error;
2067
2457
  }
2068
2458
  }
2069
- function isNotFoundError2(error) {
2459
+ function isNotFoundError3(error) {
2070
2460
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
2071
2461
  }
2072
2462
 
@@ -2095,7 +2485,29 @@ function createClientModule(config, development) {
2095
2485
  const imports = [];
2096
2486
  const appInitializers = [];
2097
2487
  const pageInitializers = [];
2488
+ const clientEntries = config.plugins.flatMap(
2489
+ (plugin) => plugin.clientEntries ?? []
2490
+ );
2491
+ const runtimeEntries = /* @__PURE__ */ new Map();
2492
+ for (const entry of clientEntries) {
2493
+ for (const runtime of entry.runtimeEntries ?? []) {
2494
+ if (runtimeEntries.has(runtime.id)) {
2495
+ throw new Error(`Duplicate plugin runtime id: ${runtime.id}`);
2496
+ }
2497
+ runtimeEntries.set(runtime.id, {
2498
+ moduleSpecifier: runtime.moduleSpecifier,
2499
+ exportName: runtime.exportName,
2500
+ options: runtime.options
2501
+ });
2502
+ }
2503
+ }
2504
+ const hasRuntimes = runtimeEntries.size > 0;
2098
2505
  imports.push('import { ClientLifecycle } from "@riebeckite/core/client";');
2506
+ if (hasRuntimes) {
2507
+ imports.push(
2508
+ 'import { createClientRuntimeHost, InteractiveRuntimeRegistry } from "@riebeckite/runtime/client";'
2509
+ );
2510
+ }
2099
2511
  if (config.spa !== void 0) {
2100
2512
  imports.push('import { createClient } from "honox/client";');
2101
2513
  imports.push('import { startSpaNavigation } from "@riebeckite/spa";');
@@ -2106,8 +2518,12 @@ function createClientModule(config, development) {
2106
2518
  );
2107
2519
  appInitializers.push("initDevelopmentInspector()");
2108
2520
  }
2109
- for (const [index, entry] of config.plugins.flatMap((plugin) => plugin.clientEntries ?? []).entries()) {
2521
+ for (const [index, entry] of clientEntries.entries()) {
2110
2522
  const localName = `pluginClientInitializer${index}`;
2523
+ const runtimeIds = (entry.runtimeEntries ?? []).map(
2524
+ (runtime) => runtime.id
2525
+ );
2526
+ const serializedRuntimeIds = serializePublicClientConfig(runtimeIds);
2111
2527
  const importTarget = entry.exportName ? `{ ${entry.exportName} as ${localName} }` : localName;
2112
2528
  if (entry.presenceSelector === void 0) {
2113
2529
  imports.push(
@@ -2117,32 +2533,71 @@ function createClientModule(config, development) {
2117
2533
  const publicConfig = entry.publicConfig;
2118
2534
  const serializedConfig = publicConfig === void 0 ? "undefined" : serializePublicClientConfig(publicConfig);
2119
2535
  const initializer = entry.initializerArguments === "context" ? `${localName}(context)` : entry.initializerArguments === "root" ? `${localName}(context.root)` : `${localName}(context.config)`;
2536
+ const ensureRuntimes = runtimeIds.length > 0 ? `await ensurePluginRuntimes(${serializedRuntimeIds}); ` : "";
2537
+ const initializerWrapper = runtimeIds.length > 0 ? `async (context) => { ${ensureRuntimes}return ${initializer}; }` : `(context) => ${initializer}`;
2538
+ const runtimeArguments = hasRuntimes ? `${serializedRuntimeIds}, ${initializerWrapper}` : initializerWrapper;
2120
2539
  const initializers = entry.scope === "app" ? appInitializers : pageInitializers;
2121
2540
  if (entry.presenceSelector === void 0) {
2122
2541
  initializers.push(
2123
- `mountPluginClientInitializer(${JSON.stringify(entry.scope ?? "page")}, ${JSON.stringify(entry.moduleSpecifier)}, root, ${serializedConfig}, (context) => ${initializer})`
2542
+ `mountPluginClientInitializer(${JSON.stringify(entry.scope ?? "page")}, ${JSON.stringify(entry.moduleSpecifier)}, root, ${serializedConfig}, ${runtimeArguments})`
2124
2543
  );
2125
2544
  continue;
2126
2545
  }
2127
2546
  const dynamicInitializer = entry.initializerArguments === "context" ? `initializer(context)` : entry.initializerArguments === "root" ? `initializer(context.root)` : `initializer(context.config)`;
2547
+ const dynamicWrapper = runtimeIds.length > 0 ? `async (context) => { ${ensureRuntimes}return ${dynamicInitializer}; }` : `(context) => ${dynamicInitializer}`;
2128
2548
  initializers.push(
2129
- `mountConditionalPluginClientInitializer(${JSON.stringify(entry.scope ?? "page")}, ${JSON.stringify(entry.moduleSpecifier)}, root, ${serializedConfig}, ${JSON.stringify(entry.presenceSelector)}, async () => { const { ${entry.exportName ?? "default"}: initializer } = await import(${JSON.stringify(entry.moduleSpecifier)}); return (context) => ${dynamicInitializer}; })`
2549
+ `mountConditionalPluginClientInitializer(${JSON.stringify(entry.scope ?? "page")}, ${JSON.stringify(entry.moduleSpecifier)}, root, ${serializedConfig}, ${JSON.stringify(entry.presenceSelector)}, ${hasRuntimes ? `${serializedRuntimeIds}, ` : ""}async () => { const { ${entry.exportName ?? "default"}: initializer } = await import(${JSON.stringify(entry.moduleSpecifier)}); return ${dynamicWrapper}; })`
2130
2550
  );
2131
2551
  }
2552
+ const runtimeSupport = hasRuntimes ? `const pluginRuntimeRegistry = new InteractiveRuntimeRegistry();
2553
+ const pluginRuntimeLoads = new Map();
2554
+ const pluginRuntimeEntries = {
2555
+ ${[...runtimeEntries.entries()].map(
2556
+ ([id, runtime]) => ` ${JSON.stringify(id)}: { moduleSpecifier: ${JSON.stringify(runtime.moduleSpecifier)}, exportName: ${JSON.stringify(runtime.exportName ?? "default")}, load: () => import(${JSON.stringify(runtime.moduleSpecifier)})${runtime.options === void 0 ? "" : `, options: ${serializePublicClientConfig(runtime.options)}`} }`
2557
+ ).join(",\n")}
2558
+ };
2559
+
2560
+ async function ensurePluginRuntimes(ids) {
2561
+ await Promise.all(ids.map(async (id) => {
2562
+ let load = pluginRuntimeLoads.get(id);
2563
+ if (!load) {
2564
+ const entry = pluginRuntimeEntries[id];
2565
+ if (!entry) throw new Error("Unknown plugin runtime: " + id);
2566
+ load = entry.load().then((module) => {
2567
+ const factory = module[entry.exportName];
2568
+ if (typeof factory !== "function") throw new Error("Plugin runtime \\"" + id + "\\" did not export a factory.");
2569
+ const definition = factory(entry.options);
2570
+ if (!definition || definition.id !== id) throw new Error("Plugin runtime \\"" + id + "\\" returned a mismatched definition.");
2571
+ pluginRuntimeRegistry.register(definition);
2572
+ }).catch((error) => {
2573
+ pluginRuntimeLoads.delete(id);
2574
+ throw error;
2575
+ });
2576
+ pluginRuntimeLoads.set(id, load);
2577
+ }
2578
+ await load;
2579
+ }));
2580
+ }
2581
+
2582
+ function createPluginRuntimeHost(root, ids) {
2583
+ if (ids.length === 0) return undefined;
2584
+ return createClientRuntimeHost({ registry: pluginRuntimeRegistry, root });
2585
+ }
2586
+ ` : "";
2132
2587
  return `${imports.join("\n")}
2133
2588
 
2134
2589
  const lifecycle = new ClientLifecycle();
2135
- let stopSpaNavigation;
2590
+ ${runtimeSupport}let stopSpaNavigation;
2136
2591
 
2137
- function mountPluginClientInitializer(scope, name, root, config, initialize) {
2138
- void lifecycle.mount({ scope, name, root, config, initialize });
2592
+ function mountPluginClientInitializer(scope, name, root, config, ${hasRuntimes ? "runtimeIds, " : ""}initialize) {
2593
+ void lifecycle.mount({ scope, name, root, config, ${hasRuntimes ? "runtimes: createPluginRuntimeHost(root, runtimeIds), " : ""}initialize }).catch((error) => console.error("[riebeckite] Client initializer failed: " + name, error));
2139
2594
  }
2140
2595
 
2141
- function mountConditionalPluginClientInitializer(scope, name, root, config, presenceSelector, load) {
2596
+ function mountConditionalPluginClientInitializer(scope, name, root, config, presenceSelector, ${hasRuntimes ? "runtimeIds, " : ""}load) {
2142
2597
  if (!root.querySelector(presenceSelector)) return;
2143
2598
  void load().then((initialize) => {
2144
2599
  if ("isConnected" in root && !root.isConnected) return;
2145
- void lifecycle.mount({ scope, name, root, config, initialize });
2600
+ void lifecycle.mount({ scope, name, root, config, ${hasRuntimes ? "runtimes: createPluginRuntimeHost(root, runtimeIds), " : ""}initialize }).catch((error) => console.error("[riebeckite] Client initializer failed: " + name, error));
2146
2601
  }, (error) => console.error("[riebeckite] Client initializer module failed: " + name, error));
2147
2602
  }
2148
2603
 
@@ -2182,522 +2637,182 @@ export async function disposeRiebeckiteClient() {
2182
2637
  `;
2183
2638
  }
2184
2639
 
2185
- // src/development_inspector.ts
2186
- import {
2187
- buildOutputPlan as buildOutputPlan2,
2188
- ContentManager
2189
- } from "@riebeckite/core";
2640
+ // src/content_watch.ts
2641
+ import path8 from "node:path";
2642
+ import { isAttachmentPath, isImagePath as isImagePath2 } from "@riebeckite/core";
2190
2643
  import {
2191
- collectDevelopmentDiagnostics,
2192
- diagnoseOutputPlan,
2193
- sortDevelopmentDiagnostics
2194
- } from "@riebeckite/diagnostics";
2195
- import { FileSystemContentSource } from "@riebeckite/node";
2196
- var clientModuleId2 = "virtual:riebeckite/development-inspector";
2197
- var resolvedClientModuleId2 = `\0${clientModuleId2}`;
2198
- var reportPath = "/__riebeckite/inspector/report";
2199
- var outputPath = "/__riebeckite/inspector/output";
2200
- var listedOutputLimit = 20;
2201
- function riebeckiteDevelopmentInspector(getApplication) {
2202
- let revision = 0;
2203
- let inspection = null;
2204
- const inspectApplication = (application, currentRevision) => {
2205
- if (inspection?.revision === currentRevision && inspection.application === application) {
2206
- return inspection;
2207
- }
2208
- if (inspection) {
2209
- const previous = inspection;
2210
- const disposePrevious = () => {
2211
- void previous.dispose().catch(() => {
2212
- });
2213
- };
2214
- void Promise.allSettled([previous.report, previous.output]).then(
2215
- disposePrevious
2216
- );
2217
- inspection = null;
2218
- }
2219
- const content = createInspectionContent(application);
2220
- let disposed = false;
2221
- const dispose = async () => {
2222
- if (disposed) return;
2223
- disposed = true;
2224
- await content.dispose();
2225
- };
2226
- const report = collectDevelopmentDiagnostics({
2227
- config: application.config,
2228
- content,
2229
- revision: currentRevision,
2230
- includeOutput: false
2231
- });
2232
- const output = report.then(
2233
- () => inspectContentOutputs(content),
2234
- () => inspectContentOutputs(content)
2235
- );
2236
- const entry = {
2237
- application,
2238
- revision: currentRevision,
2239
- report,
2240
- output,
2241
- dispose
2242
- };
2243
- inspection = entry;
2244
- void report.catch(() => {
2245
- if (inspection === entry) inspection = null;
2246
- void output.then(dispose, dispose);
2247
- });
2248
- return entry;
2249
- };
2644
+ isIgnoredContentPath as isIgnoredContentPath2,
2645
+ isPathInsideDirectory as isPathInsideDirectory2,
2646
+ toLogicalPath
2647
+ } from "@riebeckite/node";
2648
+
2649
+ // src/runtime_modules.ts
2650
+ var riebeckiteConfigModuleId = "virtual:riebeckite/config";
2651
+ var riebeckiteContentModuleId = "virtual:riebeckite/content";
2652
+ var runtimeModuleIds = [
2653
+ riebeckiteConfigModuleId,
2654
+ riebeckiteContentModuleId
2655
+ ];
2656
+ var resolvedConfigModuleId = `\0${riebeckiteConfigModuleId}`;
2657
+ var resolvedContentModuleId = `\0${riebeckiteContentModuleId}`;
2658
+ function riebeckiteRuntimeModules(getApplication) {
2659
+ let development = false;
2250
2660
  return {
2251
- name: "riebeckite-development-inspector",
2252
- apply: "serve",
2253
- enforce: "pre",
2661
+ name: "riebeckite-runtime-modules",
2662
+ configResolved(config) {
2663
+ development = config.command === "serve";
2664
+ },
2254
2665
  resolveId(id) {
2255
- return id === clientModuleId2 ? resolvedClientModuleId2 : null;
2666
+ if (id === riebeckiteConfigModuleId) return resolvedConfigModuleId;
2667
+ if (id === riebeckiteContentModuleId) return resolvedContentModuleId;
2668
+ return null;
2256
2669
  },
2257
2670
  load(id) {
2258
- return id === resolvedClientModuleId2 ? inspectorClientModule() : null;
2259
- },
2260
- configureServer(server) {
2261
- const reportMiddleware = async (request, response) => {
2262
- if (!isLocalRequest(request.headers.host, server)) {
2263
- response.statusCode = 403;
2264
- response.end();
2265
- return;
2266
- }
2267
- try {
2268
- const application = getApplication();
2269
- const report = await inspectApplication(application, revision).report;
2270
- response.setHeader("content-type", "application/json; charset=utf-8");
2271
- response.setHeader("cache-control", "no-store");
2272
- response.end(
2273
- JSON.stringify({
2274
- ...report,
2275
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2276
- currentPage: currentPageFromRequest(request.url),
2277
- theme: application.config.theme.name,
2278
- plugins: application.config.plugins.map((plugin) => plugin.name)
2279
- })
2280
- );
2281
- } catch {
2282
- response.statusCode = 500;
2283
- response.setHeader("content-type", "application/json; charset=utf-8");
2284
- response.end(JSON.stringify({ code: "INSPECTOR_REPORT_FAILED" }));
2285
- }
2286
- };
2287
- const outputMiddleware = async (request, response) => {
2288
- if (!isLocalRequest(request.headers.host, server)) {
2289
- response.statusCode = 403;
2290
- response.end();
2291
- return;
2292
- }
2293
- try {
2294
- const application = getApplication();
2295
- const entry = inspectApplication(application, revision);
2296
- const result = await entry.output;
2297
- response.setHeader("content-type", "application/json; charset=utf-8");
2298
- response.setHeader("cache-control", "no-store");
2299
- response.end(
2300
- JSON.stringify({
2301
- version: 1,
2302
- revision: entry.revision,
2303
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2304
- ...result,
2305
- diagnostics: sortDevelopmentDiagnostics(result.diagnostics)
2306
- })
2307
- );
2308
- } catch {
2309
- response.statusCode = 500;
2310
- response.setHeader("content-type", "application/json; charset=utf-8");
2311
- response.end(JSON.stringify({ code: "INSPECTOR_OUTPUT_FAILED" }));
2312
- }
2313
- };
2314
- server.middlewares.use(reportPath, reportMiddleware);
2315
- server.middlewares.use(outputPath, outputMiddleware);
2316
- return () => {
2317
- prioritizeMiddleware(server, outputMiddleware, outputPath);
2318
- prioritizeMiddleware(server, reportMiddleware, reportPath);
2319
- };
2320
- },
2321
- handleHotUpdate({ server }) {
2322
- revision += 1;
2323
- server.hot.send({ type: "custom", event: "riebeckite:inspector" });
2671
+ if (id === resolvedConfigModuleId) {
2672
+ const { appRoot, configFile } = getApplication();
2673
+ return createConfigModule(appRoot, configFile);
2674
+ }
2675
+ if (id === resolvedContentModuleId)
2676
+ return createContentModule(development);
2677
+ return null;
2324
2678
  }
2325
2679
  };
2326
2680
  }
2327
- function createInspectionContent(application) {
2328
- const { config, contentRoot } = application;
2329
- return new ContentManager(
2330
- config.content.source ?? new FileSystemContentSource(contentRoot, config.content.exclude),
2331
- config.content.exclude,
2332
- { config, commitBuildState: false }
2681
+ function isRiebeckiteRuntimeModuleId(id) {
2682
+ if (!id) return false;
2683
+ return runtimeModuleIds.some(
2684
+ (moduleId) => id === moduleId || id === `\0${moduleId}`
2333
2685
  );
2334
2686
  }
2335
- async function inspectContentOutputs(content) {
2336
- try {
2337
- const changes = await content.getOutputChangeSet();
2338
- const plan = buildOutputPlan2({
2339
- inventory: [...changes.affected, ...changes.unchanged],
2340
- removed: changes.removed,
2341
- affectedPaths: new Set(changes.affected.map((output) => output.path)),
2342
- cacheAvailable: changes.unchanged.length > 0
2343
- });
2344
- return {
2345
- output: inspectOutput(changes, plan),
2346
- dependencies: inspectDependencies(changes),
2347
- diagnostics: diagnoseOutputPlan(plan)
2348
- };
2349
- } catch {
2350
- return {
2351
- output: {
2352
- status: "unavailable",
2353
- reason: "output inspection failed"
2354
- },
2355
- dependencies: {
2356
- status: "unavailable",
2357
- reason: "dependency inspection failed"
2358
- },
2359
- diagnostics: []
2360
- };
2361
- }
2362
- }
2363
- function inspectOutput(changes, plan) {
2364
- return {
2365
- status: "available",
2366
- candidateOutputCount: changes.candidateOutputCount,
2367
- affectedOutputCount: changes.affectedOutputCount,
2368
- unchangedOutputCount: changes.unchangedOutputCount,
2369
- removedOutputCount: changes.removedOutputCount,
2370
- fullRegenerationRequired: changes.fullRegenerationRequired,
2371
- conflicts: plan.conflicts.map((conflict) => ({
2372
- path: conflict.path,
2373
- owners: conflict.owners
2374
- })),
2375
- affected: changes.affected.slice(0, listedOutputLimit).map(listOutput),
2376
- hiddenAffectedCount: Math.max(
2377
- 0,
2378
- changes.affected.length - listedOutputLimit
2379
- ),
2380
- removed: changes.removed.slice(0, listedOutputLimit).map(listOutput),
2381
- hiddenRemovedCount: Math.max(0, changes.removed.length - listedOutputLimit)
2382
- };
2383
- }
2384
- function inspectDependencies(changes) {
2385
- const outputs = [...changes.affected, ...changes.unchanged];
2386
- const kinds = /* @__PURE__ */ new Map();
2387
- const listed = [];
2388
- let dependencyCount = 0;
2389
- let dependentOutputCount = 0;
2390
- let unknownOutputCount = 0;
2391
- let hiddenOutputCount = 0;
2392
- for (const output of outputs) {
2393
- for (const dependency of output.dependencies) {
2394
- dependencyCount += 1;
2395
- kinds.set(dependency.type, (kinds.get(dependency.type) ?? 0) + 1);
2396
- }
2397
- if (output.dependencies.some(({ type }) => type === "unknown")) {
2398
- unknownOutputCount += 1;
2399
- }
2400
- if (output.dependencies.length === 0) continue;
2401
- dependentOutputCount += 1;
2402
- if (listed.length < listedOutputLimit) {
2403
- listed.push({
2404
- path: output.path,
2405
- dependencies: output.dependencies.map(dependencyLabel)
2406
- });
2407
- } else {
2408
- hiddenOutputCount += 1;
2409
- }
2410
- }
2411
- return {
2412
- status: "available",
2413
- outputCount: outputs.length,
2414
- dependentOutputCount,
2415
- dependencyCount,
2416
- unknownOutputCount,
2417
- kinds: [...kinds.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([kind, count]) => ({ kind, count })),
2418
- outputs: listed,
2419
- hiddenOutputCount
2420
- };
2421
- }
2422
- function listOutput(output) {
2423
- return {
2424
- path: output.path,
2425
- kind: output.kind,
2426
- producer: output.producer
2427
- };
2428
- }
2429
- function dependencyLabel(dependency) {
2430
- switch (dependency.type) {
2431
- case "content":
2432
- return `content:${dependency.slug}`;
2433
- case "tag":
2434
- return `tag:${dependency.tag}`;
2435
- case "folder":
2436
- return `folder:${dependency.folder}`;
2437
- case "file":
2438
- return `file:${dependency.path}`;
2439
- case "public-location":
2440
- return `public-location:${dependency.pathname}`;
2441
- case "projection":
2442
- return `projection:${dependency.projection}`;
2443
- case "external":
2444
- return `external:${dependency.id}`;
2445
- case "content-query":
2446
- return `content-query:${dependency.properties.join(",")}${dependency.unknown ? "?" : ""}`;
2447
- case "global":
2448
- return "global";
2449
- case "unknown":
2450
- return "unknown";
2451
- }
2452
- }
2453
- function currentPageFromRequest(url) {
2454
- const value = new URL(url ?? reportPath, "http://localhost").searchParams.get(
2455
- "path"
2456
- );
2457
- return value?.startsWith("/") && !value.startsWith("//") ? value : "/";
2458
- }
2459
- function prioritizeMiddleware(server, middleware, path11) {
2460
- const stack = server.middlewares.stack;
2461
- const index = stack?.findIndex(
2462
- (layer) => layer.handle === middleware || layer.route === path11
2463
- ) ?? -1;
2464
- if (index > 0 && stack) stack.unshift(...stack.splice(index, 1));
2465
- }
2466
- function isLocalRequest(host, server) {
2467
- if (!host) return false;
2468
- const hostname = host.replace(/:\d+$/, "").toLowerCase();
2469
- if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]")
2470
- return true;
2471
- const address = server.httpServer?.address();
2472
- return typeof address === "object" && address?.address === hostname;
2473
- }
2474
- function inspectorClientModule() {
2475
- return `
2476
- const reportEndpoint = ${JSON.stringify(reportPath)};
2477
- const outputEndpoint = ${JSON.stringify(outputPath)};
2478
- const panelId = "riebeckite-development-inspector";
2687
+ function createConfigModule(appRoot, configFile) {
2688
+ const configSpecifier = configFile.replace(/\\/g, "/");
2689
+ return `import * as rawConfigModule from ${JSON.stringify(configSpecifier)};
2690
+ import { resolveConfigModule } from "@riebeckite/core";
2691
+ import { resolveHonoxConfig } from "@riebeckite/honox/runtime";
2479
2692
 
2480
- export function initDevelopmentInspector() {
2481
- let panel;
2482
- let launcher;
2483
- let controller;
2484
- let generation = 0;
2485
- let report;
2486
- let activeTab = 0;
2487
- let refreshing = false;
2488
- let pendingRefresh = false;
2489
- let loadingTimer;
2490
- const tabs = ["Overview", "Diagnostics", "Dependencies", "Plugins", "Output"];
2491
- const refresh = async () => {
2492
- if (!panel?.isConnected) return;
2493
- if (refreshing) {
2494
- pendingRefresh = true;
2495
- return;
2496
- }
2497
- refreshing = true;
2498
- controller?.abort();
2499
- controller = new AbortController();
2500
- const current = ++generation;
2501
- try {
2502
- const response = await fetch(reportEndpoint + "?path=" + encodeURIComponent(location.pathname), { cache: "no-store", signal: controller.signal });
2503
- if (!response.ok) throw new Error("Inspector report is unavailable.");
2504
- const next = await response.json();
2505
- if (current !== generation || !panel?.isConnected) return;
2506
- report = next;
2507
- render();
2508
- void loadOutput(current);
2509
- } catch (error) {
2510
- if (error.name === "AbortError" || current !== generation) return;
2511
- clearInterval(loadingTimer);
2512
- renderFailure(panel.shadowRoot, error instanceof Error ? error.message : String(error));
2513
- panel.shadowRoot.querySelector("[data-close]").addEventListener("click", close);
2514
- } finally {
2515
- refreshing = false;
2516
- if (pendingRefresh) {
2517
- pendingRefresh = false;
2518
- void refresh();
2519
- }
2520
- }
2521
- };
2522
- const loadOutput = async (current) => {
2523
- try {
2524
- const response = await fetch(outputEndpoint, { cache: "no-store", signal: controller.signal });
2525
- if (!response.ok) throw new Error("Inspector output is unavailable.");
2526
- const next = await response.json();
2527
- if (current !== generation || !panel?.isConnected) return;
2528
- report.output = next.output;
2529
- report.dependencies = next.dependencies;
2530
- report.diagnostics = report.diagnostics.concat(next.diagnostics);
2531
- report.summary = summarize(report.diagnostics);
2532
- render();
2533
- } catch (error) {
2534
- if (error.name === "AbortError" || current !== generation) return;
2535
- report.output = { status: "unavailable", reason: "output inspection failed" };
2536
- report.dependencies = { status: "unavailable", reason: "dependency inspection failed" };
2537
- render();
2538
- }
2539
- };
2540
- const open = () => {
2541
- if (!panel) {
2542
- panel = document.createElement("div");
2543
- panel.id = panelId;
2544
- panel.attachShadow({ mode: "open" });
2545
- }
2546
- if (!panel.isConnected) document.body.append(panel);
2547
- showLoading();
2548
- void refresh();
2549
- };
2550
- const close = () => {
2551
- generation += 1;
2552
- pendingRefresh = false;
2553
- controller?.abort();
2554
- clearInterval(loadingTimer);
2555
- panel?.remove();
2556
- launcher?.focus();
2557
- };
2558
- const showLoading = () => {
2559
- if (!panel) return;
2560
- clearInterval(loadingTimer);
2561
- panel.shadowRoot.innerHTML = '<style>' + styles + '</style><section role="dialog" aria-modal="false" aria-labelledby="rb-loading-title"><header><strong id="rb-loading-title">Riebeckite Inspector</strong><button type="button" data-close aria-label="Close inspector">Close</button></header><p class="status" aria-live="polite">Loading inspector report…</p></section>';
2562
- const status = panel.shadowRoot.querySelector(".status");
2563
- const started = Date.now();
2564
- loadingTimer = setInterval(() => {
2565
- if (status?.isConnected) status.textContent = 'Loading inspector report… ' + Math.round((Date.now() - started) / 1000) + 's';
2566
- }, 1000);
2567
- panel.shadowRoot.querySelector("[data-close]").addEventListener("click", close);
2568
- };
2569
- launcher = document.createElement("button");
2570
- launcher.type = "button";
2571
- launcher.textContent = "Inspector";
2572
- launcher.setAttribute("aria-label", "Open Riebeckite Development Inspector");
2573
- launcher.style.cssText = "position:fixed;right:16px;bottom:16px;z-index:2147483647;border:1px solid #434343;border-radius:4px;background:#171717;color:#fff;padding:8px 12px;font:600 12px system-ui;cursor:pointer";
2574
- launcher.addEventListener("click", open);
2575
- document.body.append(launcher);
2576
- window.addEventListener("keydown", (event) => {
2577
- const editable = event.target instanceof HTMLElement && (event.target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(event.target.tagName));
2578
- if (event.key === "Escape" && panel?.isConnected) {
2579
- event.preventDefault();
2580
- close();
2581
- } else if (event.key.toLowerCase() === "r" && event.ctrlKey && event.altKey && !editable) {
2582
- event.preventDefault();
2583
- panel?.isConnected ? close() : open();
2584
- }
2585
- });
2586
- import.meta.hot?.on("riebeckite:inspector", refresh);
2693
+ export const config = resolveHonoxConfig(
2694
+ resolveConfigModule(rawConfigModule),
2695
+ ${JSON.stringify(appRoot)},
2696
+ );
2697
+ `;
2698
+ }
2699
+ function createContentModule(development) {
2700
+ if (!development) {
2701
+ return `import { ContentManager } from "@riebeckite/core";
2702
+ import { createContentSource } from "@riebeckite/node";
2703
+ import { config } from ${JSON.stringify(riebeckiteConfigModuleId)};
2587
2704
 
2588
- function render() {
2589
- clearInterval(loadingTimer);
2590
- const root = panel.shadowRoot;
2591
- root.innerHTML = '<style>' + styles + '</style><section role="dialog" aria-modal="false" aria-labelledby="rb-title" tabindex="-1"><header><div><strong id="rb-title">Riebeckite Inspector</strong><p>Ctrl+Alt+R</p></div><button type="button" data-close aria-label="Close inspector">Close</button></header><div class="summary"><b>' + report.summary.errors + '</b> errors <b>' + report.summary.warnings + '</b> warnings <b>' + report.summary.info + '</b> info</div><div role="tablist" aria-label="Inspector sections">' + tabs.map((tab, index) => '<button id="rb-tab-' + index + '" role="tab" aria-controls="rb-panel-' + index + '" aria-selected="' + (index === activeTab) + '" tabindex="' + (index === activeTab ? 0 : -1) + '" data-tab="' + index + '">' + tab + '</button>').join("") + '</div><div id="rb-panel-' + activeTab + '" role="tabpanel" aria-labelledby="rb-tab-' + activeTab + '" tabindex="0">' + panelContent() + '</div><p class="status" aria-live="polite">' + (report.output ? "Inspector report updated" : "Inspector report updated · loading output plan…") + '</p></section>';
2592
- root.querySelector("[data-close]").addEventListener("click", close);
2593
- root.querySelectorAll("[data-tab]").forEach((button) => button.addEventListener("click", () => { activeTab = Number(button.dataset.tab); render(); }));
2594
- root.querySelector("[role=tablist]").addEventListener("keydown", (event) => {
2595
- if (event.key === "Home") activeTab = 0;
2596
- else if (event.key === "End") activeTab = tabs.length - 1;
2597
- else if (event.key === "ArrowRight" || event.key === "ArrowDown") activeTab = (activeTab + 1) % tabs.length;
2598
- else if (event.key === "ArrowLeft" || event.key === "ArrowUp") activeTab = (activeTab + tabs.length - 1) % tabs.length;
2599
- else return;
2600
- event.preventDefault(); render(); root.querySelector('[data-tab="' + activeTab + '"]').focus();
2601
- });
2602
- }
2603
- function panelContent() {
2604
- if (activeTab === 0) return '<dl><dt>Page</dt><dd>' + escapeHtml(report.currentPage) + '</dd><dt>Theme</dt><dd>' + escapeHtml(report.theme) + '</dd><dt>Revision</dt><dd>' + escapeHtml(report.revision) + '</dd></dl>';
2605
- if (activeTab === 1) return diagnosticList(report.diagnostics);
2606
- if (activeTab === 2) return dependencyReport(report.dependencies);
2607
- if (activeTab === 3) return '<ul>' + (report.plugins.map((plugin) => '<li>' + escapeHtml(plugin) + '</li>').join("") || "<li>No plugins configured.</li>") + '</ul>';
2608
- return outputReport(report.output);
2705
+ export const content = new ContentManager(
2706
+ createContentSource(config.content),
2707
+ [],
2708
+ { config, plugins: config.plugins, isDevelopment: import.meta.env.DEV },
2709
+ );
2710
+ `;
2609
2711
  }
2712
+ return `import { ContentManager } from "@riebeckite/core";
2713
+ import { createContentSource } from "@riebeckite/node";
2714
+ import { createDevelopmentTrace } from "@riebeckite/honox/runtime";
2715
+ import { config } from ${JSON.stringify(riebeckiteConfigModuleId)};
2716
+
2717
+ const trace = createDevelopmentTrace();
2718
+ export const content = new ContentManager(
2719
+ createContentSource(config.content),
2720
+ [],
2721
+ {
2722
+ config,
2723
+ plugins: config.plugins,
2724
+ isDevelopment: true,
2725
+ observability: trace.observability,
2726
+ traceRecorder: trace,
2727
+ },
2728
+ );
2729
+ `;
2610
2730
  }
2611
2731
 
2612
- function summarize(diagnostics) {
2732
+ // src/content_watch.ts
2733
+ var CONTENT_RELOAD_DEBOUNCE_MS = 60;
2734
+ var configuredWatchers = /* @__PURE__ */ new WeakSet();
2735
+ function riebeckiteContentWatch(options) {
2613
2736
  return {
2614
- errors: diagnostics.filter((diagnostic) => diagnostic.severity === "error").length,
2615
- warnings: diagnostics.filter((diagnostic) => diagnostic.severity === "warning").length,
2616
- info: diagnostics.filter((diagnostic) => diagnostic.severity === "info").length,
2737
+ name: "riebeckite-content-watch",
2738
+ apply: "serve",
2739
+ enforce: "post",
2740
+ configureServer(server) {
2741
+ if (configuredWatchers.has(server.watcher)) return;
2742
+ configuredWatchers.add(server.watcher);
2743
+ const appRoot = options.appRoot();
2744
+ const contentRoot = options.contentRoot();
2745
+ const exclude = options.exclude();
2746
+ const isContentFile = (file) => isPathInsideDirectory2(contentRoot, file);
2747
+ server.watcher.add(contentRoot);
2748
+ suppressRestartOnContentEvents(server, isContentFile);
2749
+ let timer;
2750
+ const invalidate = () => {
2751
+ if (timer) clearTimeout(timer);
2752
+ timer = setTimeout(() => {
2753
+ timer = void 0;
2754
+ invalidateApplicationRuntime(server, appRoot);
2755
+ server.hot.send({ type: "full-reload" });
2756
+ }, CONTENT_RELOAD_DEBOUNCE_MS);
2757
+ };
2758
+ server.httpServer?.once("close", () => {
2759
+ if (timer) clearTimeout(timer);
2760
+ });
2761
+ const handle = (event) => (file) => {
2762
+ if (!isContentFile(file)) return;
2763
+ const logicalPath = toLogicalPath(contentRoot, file);
2764
+ if (isIgnoredContentPath2(logicalPath, exclude)) return;
2765
+ if (event === "change" && isSiteAssetPath(logicalPath)) {
2766
+ server.hot.send({ type: "full-reload" });
2767
+ return;
2768
+ }
2769
+ invalidate();
2770
+ };
2771
+ server.watcher.on("add", handle("add"));
2772
+ server.watcher.on("change", handle("change"));
2773
+ server.watcher.on("unlink", handle("unlink"));
2774
+ }
2617
2775
  };
2618
2776
  }
2619
-
2620
- function diagnosticList(diagnostics) {
2621
- return '<ul>' + (diagnostics.map((diagnostic) =>
2622
- '<li data-severity="' + escapeHtml(diagnostic.severity) + '"><b>' + escapeHtml(diagnostic.code) + '</b> ' + escapeHtml(diagnostic.message) + location(diagnostic) + '</li>'
2623
- ).join("") || "<li>No diagnostic findings.</li>") + '</ul>';
2624
- }
2625
-
2626
- function outputReport(output) {
2627
- if (!output) return '<p class="status" aria-live="polite">Loading output plan…</p>';
2628
- if (output.status !== "available") return unavailable("Output", output.reason);
2629
- return '<dl>' +
2630
- '<dt>Candidate</dt><dd>' + output.candidateOutputCount + '</dd>' +
2631
- '<dt>Affected</dt><dd>' + output.affectedOutputCount + '</dd>' +
2632
- '<dt>Unchanged</dt><dd>' + output.unchangedOutputCount + '</dd>' +
2633
- '<dt>Removed</dt><dd>' + output.removedOutputCount + '</dd>' +
2634
- '<dt>Full regeneration</dt><dd>' + (output.fullRegenerationRequired ? "required" : "not required") + '</dd>' +
2635
- '<dt>Owner conflicts</dt><dd>' + output.conflicts.length + '</dd>' +
2636
- '</dl>' +
2637
- listedOutputs("Affected outputs", output.affected, output.hiddenAffectedCount) +
2638
- listedOutputs("Removed outputs", output.removed, output.hiddenRemovedCount) +
2639
- conflictList(output.conflicts);
2640
- }
2641
-
2642
- function listedOutputs(title, outputs, hiddenCount) {
2643
- if (outputs.length === 0) return "";
2644
- return '<h3>' + escapeHtml(title) + '</h3><ul>' + outputs.map((output) =>
2645
- '<li><code>' + escapeHtml(output.path) + '</code> <small>' + escapeHtml(output.kind) + ' · ' + escapeHtml(output.producer) + '</small></li>'
2646
- ).join("") + '</ul>' + (hiddenCount > 0 ? '<p class="more">' + hiddenCount + ' more not shown.</p>' : "");
2647
- }
2648
-
2649
- function conflictList(conflicts) {
2650
- if (conflicts.length === 0) return "";
2651
- return '<h3>Owner conflicts</h3><ul>' + conflicts.map((conflict) =>
2652
- '<li><code>' + escapeHtml(conflict.path) + '</code> <small>' + escapeHtml(conflict.owners.join(", ")) + '</small></li>'
2653
- ).join("") + '</ul>';
2654
- }
2655
-
2656
- function dependencyReport(dependencies) {
2657
- if (!dependencies) return '<p class="status" aria-live="polite">Loading dependencies…</p>';
2658
- if (dependencies.status !== "available") return unavailable("Dependencies", dependencies.reason);
2659
- return '<dl>' +
2660
- '<dt>Outputs</dt><dd>' + dependencies.outputCount + '</dd>' +
2661
- '<dt>With dependencies</dt><dd>' + dependencies.dependentOutputCount + '</dd>' +
2662
- '<dt>Dependencies</dt><dd>' + dependencies.dependencyCount + '</dd>' +
2663
- '<dt>Unknown outputs</dt><dd>' + dependencies.unknownOutputCount + '</dd>' +
2664
- '</dl>' +
2665
- (dependencies.kinds.length === 0 ? "<p>No output dependencies.</p>" :
2666
- '<h3>Kinds</h3><ul>' + dependencies.kinds.map((kind) =>
2667
- '<li>' + escapeHtml(kind.kind) + ' <small>' + kind.count + '</small></li>'
2668
- ).join("") + '</ul>') +
2669
- (dependencies.outputs.length === 0 ? "" :
2670
- '<h3>Outputs</h3><ul>' + dependencies.outputs.map((output) =>
2671
- '<li><code>' + escapeHtml(output.path) + '</code><br><small>' + escapeHtml(output.dependencies.join(", ")) + '</small></li>'
2672
- ).join("") + '</ul>') +
2673
- (dependencies.hiddenOutputCount > 0 ? '<p class="more">' + dependencies.hiddenOutputCount + ' more outputs not shown.</p>' : "");
2674
- }
2675
-
2676
- function unavailable(subject, capability) {
2677
- return '<p class="partial">' + escapeHtml(subject) + ' unavailable: ' + escapeHtml(capability) + '.</p>';
2678
- }
2679
-
2680
- function renderFailure(root, message) {
2681
- root.innerHTML = '<style>' + styles + '</style><section role="dialog" aria-modal="false" aria-labelledby="rb-failure-title"><header><strong id="rb-failure-title">Riebeckite Inspector</strong><button type="button" data-close aria-label="Close inspector">Close</button></header><p class="failure" aria-live="polite">' + escapeHtml(message) + '</p></section>';
2777
+ function isSiteAssetPath(logicalPath) {
2778
+ return isImagePath2(logicalPath) || isAttachmentPath(logicalPath);
2682
2779
  }
2683
-
2684
- function location(diagnostic) {
2685
- const location = diagnostic.location;
2686
- return location?.file ? ' <small>(' + escapeHtml(location.file) + (location.line ? ':' + location.line : '') + ')</small>' : '';
2780
+ function invalidateApplicationRuntime(server, appRoot) {
2781
+ const moduleGraph = server.environments?.ssr?.moduleGraph;
2782
+ if (!moduleGraph) return 0;
2783
+ const appDirectory = path8.join(appRoot, "app") + path8.sep;
2784
+ const seen = /* @__PURE__ */ new Set();
2785
+ const timestamp = Date.now();
2786
+ let invalidated = 0;
2787
+ for (const mod of moduleGraph.idToModuleMap.values()) {
2788
+ if (!isApplicationRuntimeModule(mod, appDirectory)) continue;
2789
+ moduleGraph.invalidateModule(mod, seen, timestamp);
2790
+ invalidated += 1;
2791
+ }
2792
+ return invalidated;
2687
2793
  }
2688
-
2689
- function escapeHtml(value) {
2690
- return String(value).replace(/[&<>"]/g, (character) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[character]);
2794
+ function isApplicationRuntimeModule(mod, appDirectory) {
2795
+ if (mod.file && isPathInsideDirectory2(appDirectory, mod.file)) return true;
2796
+ return isRiebeckiteRuntimeModuleId(mod.id);
2691
2797
  }
2692
-
2693
- const styles = ':host{all:initial}section{position:fixed;right:16px;bottom:56px;z-index:2147483647;width:min(540px,calc(100vw - 32px));max-height:70vh;overflow:auto;background:#171717;color:#f4f4f4;border:1px solid #555;padding:16px;font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;box-shadow:0 8px 24px #0006}header{display:flex;justify-content:space-between;gap:16px;border-bottom:1px solid #555;padding-bottom:8px}header p,.status,small{color:#b8b8b8;margin:2px 0}.summary{margin:12px 0}button{border:1px solid #666;background:#242424;color:#fff;padding:6px 8px;cursor:pointer}button[aria-selected="true"]{border-color:#e2c57b;color:#ffe08a}.partial{color:#e2c57b}.more{color:#b8b8b8;margin:4px 0}h3{color:#b8b8b8;font-size:12px;margin:12px 0 4px;text-transform:uppercase}ul{margin:12px 0;padding-left:20px}li{margin:8px 0}li[data-severity="error"]{color:#ff9797}li[data-severity="warning"]{color:#ffe08a}dl{display:grid;grid-template-columns:max-content 1fr;gap:8px 16px}dt{color:#b8b8b8}.failure{color:#ff9797}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}@media(max-width:560px){section{right:8px;bottom:52px;width:calc(100vw - 32px);max-height:75vh}}';
2694
- `;
2798
+ function suppressRestartOnContentEvents(server, isContentFile) {
2799
+ for (const event of ["add", "unlink"]) {
2800
+ const listeners = server.watcher.rawListeners(event).slice();
2801
+ server.watcher.removeAllListeners(event);
2802
+ for (const listener of listeners) {
2803
+ server.watcher.on(event, (file) => {
2804
+ if (isContentFile(file)) return;
2805
+ listener(file);
2806
+ });
2807
+ }
2808
+ }
2695
2809
  }
2696
2810
 
2697
2811
  // src/vite_runner.ts
2698
2812
  import fs7 from "node:fs/promises";
2813
+ import os from "node:os";
2699
2814
  import path9 from "node:path";
2700
- import { build, createServer as createServer2 } from "vite";
2815
+ import { build as build2, createServer } from "vite";
2701
2816
  var viteConfigFileNames = [
2702
2817
  "vite.config.ts",
2703
2818
  "vite.config.js",
@@ -2732,7 +2847,7 @@ var HonoxApplicationRootError = class extends Error {
2732
2847
  async function resolveHonoxApplication(options) {
2733
2848
  const configRoot = path9.resolve(options.configRoot);
2734
2849
  const appRoot = options.appRoot ? path9.resolve(options.appRoot) : await resolveHonoxApplicationRoot(configRoot, options.startDirectory);
2735
- const workspaceRoot = options.workspaceRoot ?? await findWorkspaceRoot(configRoot);
2850
+ const workspaceRoot = options.workspaceRoot ?? await findWorkspaceRoot2(configRoot);
2736
2851
  const configFile = path9.resolve(
2737
2852
  configRoot,
2738
2853
  options.configFile ?? "riebeckite.config.ts"
@@ -2751,7 +2866,7 @@ async function resolveHonoxApplication(options) {
2751
2866
  contentRoot: config.content.directory
2752
2867
  };
2753
2868
  }
2754
- async function findWorkspaceRoot(configRoot) {
2869
+ async function findWorkspaceRoot2(configRoot) {
2755
2870
  try {
2756
2871
  const workspaceConfig = path9.join(configRoot, "pnpm-workspace.yaml");
2757
2872
  return (await fs7.stat(workspaceConfig)).isFile() ? configRoot : void 0;
@@ -2762,7 +2877,7 @@ async function findWorkspaceRoot(configRoot) {
2762
2877
  async function startHonoxDevServer(options) {
2763
2878
  const root = path9.resolve(options.root);
2764
2879
  await withWorkingDirectory(root, async () => {
2765
- const server = await createServer2({ root, server: options.server });
2880
+ const server = await createServer({ root, server: options.server });
2766
2881
  const restartFiles = new Set(
2767
2882
  options.restartOnChange?.map((file) => path9.resolve(file))
2768
2883
  );
@@ -2796,18 +2911,72 @@ async function startHonoxDevServer(options) {
2796
2911
  async function buildHonoxApplication(options) {
2797
2912
  const root = path9.resolve(options.root);
2798
2913
  await withWorkingDirectory(root, async () => {
2799
- await runTraced(
2800
- options.tracer,
2801
- "integration.honox.client_build",
2802
- () => build({ root, mode: "client" })
2803
- );
2914
+ if (!options.reuseClientBuild) {
2915
+ await runTraced(
2916
+ options.tracer,
2917
+ "integration.honox.client_build",
2918
+ () => build2({ root, mode: "client" })
2919
+ );
2920
+ }
2804
2921
  await runTraced(
2805
2922
  options.tracer,
2806
2923
  "integration.honox.server_build",
2807
- () => build({ root })
2924
+ () => buildServerWithMetrics(root, options.tracer)
2808
2925
  );
2809
2926
  });
2810
2927
  }
2928
+ async function canReuseClientBuild(input) {
2929
+ const root = path9.resolve(input.root);
2930
+ const cache = await loadOutputCacheMetadata(
2931
+ path9.join(root, ".riebeckite", "ssg-output-cache.json")
2932
+ );
2933
+ if (!cache?.bundleFingerprint || !cache.configFile) return false;
2934
+ if (cache.bundleFingerprint !== await computeBundleFingerprint(root, cache.configFile)) {
2935
+ return false;
2936
+ }
2937
+ return await verifyClientBuildArtifacts({
2938
+ outDir: input.outputDirectory,
2939
+ expectedInventory: cache.finalOutputInventory ?? {}
2940
+ });
2941
+ }
2942
+ async function buildServerWithMetrics(root, tracer) {
2943
+ if (!tracer) {
2944
+ await build2({ root });
2945
+ return;
2946
+ }
2947
+ const previousMetricsFile = process.env.RIEBECKITE_SSG_METRICS_FILE;
2948
+ const metricsDirectory = previousMetricsFile ? void 0 : await fs7.mkdtemp(path9.join(os.tmpdir(), "riebeckite-ssg-metrics-"));
2949
+ const metricsFile = previousMetricsFile ?? path9.join(metricsDirectory, "metrics.json");
2950
+ if (!previousMetricsFile)
2951
+ process.env.RIEBECKITE_SSG_METRICS_FILE = metricsFile;
2952
+ try {
2953
+ await build2({ root });
2954
+ await reportSsgTimings(tracer, metricsFile);
2955
+ } finally {
2956
+ if (previousMetricsFile === void 0) {
2957
+ delete process.env.RIEBECKITE_SSG_METRICS_FILE;
2958
+ }
2959
+ if (metricsDirectory)
2960
+ await fs7.rm(metricsDirectory, { recursive: true, force: true });
2961
+ }
2962
+ }
2963
+ async function reportSsgTimings(tracer, metricsFile) {
2964
+ try {
2965
+ const metrics = JSON.parse(await fs7.readFile(metricsFile, "utf8"));
2966
+ if (!metrics || typeof metrics !== "object") return;
2967
+ const timings = metrics.timingsMs;
2968
+ if (!timings || typeof timings !== "object") return;
2969
+ for (const [name, durationMs] of Object.entries(timings)) {
2970
+ if (typeof durationMs !== "number" || !Number.isFinite(durationMs))
2971
+ continue;
2972
+ tracer.event("integration.timing", {
2973
+ name: `integration.honox.server_build.ssg.${name}`,
2974
+ durationMs
2975
+ });
2976
+ }
2977
+ } catch {
2978
+ }
2979
+ }
2811
2980
  async function withWorkingDirectory(root, task) {
2812
2981
  const previousDirectory = process.cwd();
2813
2982
  if (previousDirectory === root) return await task();
@@ -2822,16 +2991,16 @@ async function runTraced(tracer, name, buildTask) {
2822
2991
  return tracer ? await tracer.span(name, {}, buildTask) : await buildTask();
2823
2992
  }
2824
2993
  function waitForShutdown(server) {
2825
- let resolve3 = () => {
2994
+ let resolve5 = () => {
2826
2995
  };
2827
2996
  let closing = false;
2828
2997
  const close = () => {
2829
2998
  if (closing) return;
2830
2999
  closing = true;
2831
- void server.close().finally(resolve3);
3000
+ void server.close().finally(resolve5);
2832
3001
  };
2833
3002
  const promise = new Promise((resolvePromise) => {
2834
- resolve3 = resolvePromise;
3003
+ resolve5 = resolvePromise;
2835
3004
  });
2836
3005
  process.once("SIGINT", close);
2837
3006
  process.once("SIGTERM", close);
@@ -2874,8 +3043,8 @@ async function findViteApplicationRootFrom(startDirectory, configRoot) {
2874
3043
  return void 0;
2875
3044
  }
2876
3045
  function isWithin(parent, target) {
2877
- const relative4 = path9.relative(parent, target);
2878
- return relative4 === "" || !relative4.startsWith("..") && !path9.isAbsolute(relative4);
3046
+ const relative5 = path9.relative(parent, target);
3047
+ return relative5 === "" || !relative5.startsWith("..") && !path9.isAbsolute(relative5);
2879
3048
  }
2880
3049
  async function hasViteConfig(directory) {
2881
3050
  for (const fileName of viteConfigFileNames) {
@@ -3009,10 +3178,13 @@ function riebeckiteSsrExternals(externals, siteExternals = () => []) {
3009
3178
  }
3010
3179
  export {
3011
3180
  buildHonoxApplication,
3181
+ canReuseClientBuild,
3012
3182
  createNoChangeFastPathOutputMetrics,
3013
3183
  createRiebeckiteSsg,
3014
3184
  defaultSsgEntry,
3015
3185
  defaultSsrExternals,
3186
+ fingerprintDirectory,
3187
+ fingerprintOutputDirectory,
3016
3188
  loadRiebeckiteConfig,
3017
3189
  replaceHonoxIslandDependencyPlugin,
3018
3190
  resolveHonoxApplication,