@riebeckite/honox 0.0.45 → 0.0.48

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.
Files changed (45) hide show
  1. package/dist/index.js +2204 -1778
  2. package/dist/runtime.js +30 -0
  3. package/dist/server.js +80 -49
  4. package/dist/src/client_module.d.ts +1 -3
  5. package/dist/src/client_module_part1.d.ts +5 -0
  6. package/dist/src/client_module_part2.d.ts +2 -0
  7. package/dist/src/content_route.d.ts +3 -88
  8. package/dist/src/content_route_part1.d.ts +37 -0
  9. package/dist/src/content_route_part2.d.ts +8 -0
  10. package/dist/src/runtime_modules.d.ts +1 -0
  11. package/dist/src/spa_diagnostics.d.ts +4 -0
  12. package/dist/src/ssg/output_cache.d.ts +5 -37
  13. package/dist/src/ssg/output_cache_decision.d.ts +9 -0
  14. package/dist/src/ssg/output_cache_entries.d.ts +5 -0
  15. package/dist/src/ssg/output_cache_fastpath.d.ts +12 -0
  16. package/dist/src/ssg/output_cache_load.d.ts +8 -0
  17. package/dist/src/ssg/output_cache_paths.d.ts +13 -0
  18. package/dist/src/ssg/output_cache_replace.d.ts +6 -0
  19. package/dist/src/ssg/output_cache_save.d.ts +2 -0
  20. package/dist/src/ssg/output_cache_types.d.ts +33 -0
  21. package/dist/src/ssg/output_cache_validate.d.ts +8 -0
  22. package/dist/src/ssg/standalone.d.ts +1 -0
  23. package/dist/src/ssg_plugin.d.ts +3 -12
  24. package/dist/src/ssg_plugin_cleanup.d.ts +3 -0
  25. package/dist/src/ssg_plugin_close.d.ts +2 -0
  26. package/dist/src/ssg_plugin_generate_finalize.d.ts +3 -0
  27. package/dist/src/ssg_plugin_generate_prepare.d.ts +52 -0
  28. package/dist/src/ssg_plugin_generate_run.d.ts +3 -0
  29. package/dist/src/ssg_plugin_helpers.d.ts +21 -0
  30. package/dist/src/ssg_plugin_setup.d.ts +20 -0
  31. package/dist/src/ssg_plugin_state.d.ts +52 -0
  32. package/dist/src/ui/primitives.d.ts +4 -126
  33. package/dist/src/ui/primitives.js +110 -88
  34. package/dist/src/ui/primitives_article.d.ts +9 -0
  35. package/dist/src/ui/primitives_head.d.ts +8 -0
  36. package/dist/src/ui/primitives_page.d.ts +3 -0
  37. package/dist/src/ui/primitives_theme.d.ts +7 -0
  38. package/dist/src/ui/primitives_types.d.ts +82 -0
  39. package/dist/src/virtual_modules.d.ts +4 -0
  40. package/dist/src/vite_plugin.d.ts +4 -9
  41. package/dist/src/vite_plugin_helpers.d.ts +12 -0
  42. package/dist/src/vite_runner.d.ts +3 -36
  43. package/dist/src/vite_runner_helpers.d.ts +40 -0
  44. package/package.json +11 -11
  45. package/style.css +6 -1
package/dist/index.js CHANGED
@@ -131,9 +131,39 @@ function resolveExportTarget(target) {
131
131
 
132
132
  // src/resolved_config.ts
133
133
  import path3 from "node:path";
134
+
135
+ // src/spa_diagnostics.ts
136
+ import {
137
+ definePlugin
138
+ } from "@riebeckite/core";
139
+ var SPA_DIAGNOSTICS_PLUGIN_NAME = "riebeckite:spa-diagnostics";
140
+ var MAIN_CONTENT_PATTERN = /<main\b[^>]*\bid=["']main-content["']/iu;
141
+ var REDIRECT_PATTERN = /<meta\b[^>]*\bhttp-equiv=["']refresh["'][^>]*\bcontent=["'][^"']*\burl=/iu;
142
+ function inspectSpaPage(page) {
143
+ if (REDIRECT_PATTERN.test(page.html)) return [];
144
+ if (MAIN_CONTENT_PATTERN.test(page.html)) return [];
145
+ return [
146
+ {
147
+ code: "spa-missing-main-content",
148
+ severity: "error",
149
+ message: 'SPA navigation is enabled but this page has no <main id="main-content">. Add one to the page layout, or disable SPA for the site.',
150
+ filePath: page.path,
151
+ suggestion: 'Render <main id="main-content" tabindex={-1}> around the page body.'
152
+ }
153
+ ];
154
+ }
155
+ function spaDiagnostics() {
156
+ return definePlugin({
157
+ name: SPA_DIAGNOSTICS_PLUGIN_NAME,
158
+ inspectGeneratedHtml: inspectSpaPage
159
+ });
160
+ }
161
+
162
+ // src/resolved_config.ts
134
163
  function resolveHonoxConfig(config, appRoot) {
135
164
  return {
136
165
  ...config,
166
+ plugins: config.spa === void 0 ? config.plugins : [...config.plugins, spaDiagnostics()],
137
167
  buildDirectory: path3.join(appRoot, ".riebeckite"),
138
168
  outputDirectory: path3.join(appRoot, "dist"),
139
169
  content: {
@@ -296,8 +326,8 @@ function isMissingDirectoryError(error) {
296
326
  function isNotFoundError(error) {
297
327
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
298
328
  }
299
- function isAbsolutePath(path12) {
300
- return /^([a-z]:)?[\\/]/iu.test(path12);
329
+ function isAbsolutePath(path14) {
330
+ return /^([a-z]:)?[\\/]/iu.test(path14);
301
331
  }
302
332
  function resolveWithinDirectory(directory, relativePath, label) {
303
333
  if (!relativePath || relativePath.includes("\0") || isAbsolutePath(relativePath)) {
@@ -374,10 +404,10 @@ async function fingerprintDirectory(directory) {
374
404
  }
375
405
  function fingerprintOutputInventory(inventory) {
376
406
  const hash = createHash("sha256");
377
- for (const [path12, checksum] of Object.entries(inventory).sort(
407
+ for (const [path14, checksum] of Object.entries(inventory).sort(
378
408
  ([left], [right]) => left.localeCompare(right)
379
409
  )) {
380
- hash.update(path12).update("\0").update(checksum).update("\0");
410
+ hash.update(path14).update("\0").update(checksum).update("\0");
381
411
  }
382
412
  return hash.digest("hex");
383
413
  }
@@ -432,7 +462,7 @@ async function fingerprintOutputDirectory(directory, relativeDirectory = "", met
432
462
  function inventoriesEqual(left, right) {
433
463
  const leftPaths = Object.keys(left);
434
464
  const rightPaths = Object.keys(right);
435
- return leftPaths.length === rightPaths.length && leftPaths.every((path12) => left[path12] === right[path12]);
465
+ return leftPaths.length === rightPaths.length && leftPaths.every((path14) => left[path14] === right[path14]);
436
466
  }
437
467
  async function collectAppFiles(directory, files) {
438
468
  const entries = await readdir(directory, { withFileTypes: true }).catch(
@@ -553,463 +583,157 @@ async function collectPackageFiles(directory, files) {
553
583
  await collectAppFiles(directory, files);
554
584
  }
555
585
 
556
- // src/ssg_plugin.ts
557
- import { randomUUID as randomUUID4 } from "node:crypto";
558
- import { lstat as lstat3, mkdir as mkdir5, rm as rm4, writeFile as writeFile4 } from "node:fs/promises";
559
- import { dirname as dirname5, join as join5, relative as relative4, resolve as resolve4 } from "node:path";
560
- import {
561
- BUILD_OUTPUT_MARKER_FILE,
562
- buildOutputPlan,
563
- compareOutputPlan,
564
- createBuildOutputMarker,
565
- publicationFingerprint as fingerprintPublication,
566
- isDeferredGeneratedOutput,
567
- publicationEntriesFromManifest,
568
- publicationOutputsFromManifest,
569
- publicationRedirectsFromManifest,
570
- serializeBuildOutputMarker
571
- } from "@riebeckite/core";
572
-
573
- // src/content_assets.ts
574
- import fs5 from "node:fs/promises";
575
- import path7 from "node:path";
576
- import { isImagePath, normalizeContentPath } from "@riebeckite/core";
577
- import { isIgnoredContentPath, isPathInsideDirectory } from "@riebeckite/node";
578
-
579
- // src/content_module.ts
580
- import path6 from "node:path";
581
- function contentModuleEntry(appRoot) {
582
- return path6.join(appRoot, "app", "server.ts");
586
+ // src/ssg/standalone.ts
587
+ import { mkdir } from "node:fs/promises";
588
+ import { createRequire } from "node:module";
589
+ import { relative as relative3, resolve as resolve2 } from "node:path";
590
+ import { pathToFileURL } from "node:url";
591
+ import { build } from "vite";
592
+ var standaloneSsgMode = "riebeckite-ssr";
593
+ var frameworkRequire = createRequire(import.meta.url);
594
+ async function loadStandaloneSsgBundle(input) {
595
+ const root = resolve2(input.root);
596
+ const outputDirectory = resolve2(input.outputDirectory);
597
+ await mkdir(outputDirectory, { recursive: true });
598
+ await build({
599
+ root,
600
+ configFile: input.config ? false : void 0,
601
+ mode: standaloneSsgMode,
602
+ ...input.config ? {
603
+ define: input.config.define,
604
+ oxc: input.config.oxc,
605
+ plugins: [
606
+ ...input.config.plugins.filter(
607
+ (plugin) => plugin.name !== "riebeckite-ssg" && plugin.name !== "riebeckite-ssr-externals" && !plugin.name.startsWith("@hono/vite-build/")
608
+ ),
609
+ createFrameworkResolutionPlugin(),
610
+ createRuntimeExternalPlugin(),
611
+ ...input.clientOutputDirectory ? [createClientManifestPlugin(root, input.clientOutputDirectory)] : []
612
+ ],
613
+ resolve: {
614
+ ...input.config.resolve,
615
+ external: []
616
+ }
617
+ } : {},
618
+ build: {
619
+ emptyOutDir: false,
620
+ outDir: outputDirectory,
621
+ ssr: true,
622
+ rollupOptions: {
623
+ input: input.entry,
624
+ output: { entryFileNames: "ssg-server.mjs", format: "es" }
625
+ }
626
+ },
627
+ environments: { ssr: { resolve: { noExternal: true } } }
628
+ });
629
+ const module = await import(standaloneSsgModuleUrl(outputDirectory));
630
+ if (!module.default) {
631
+ throw new Error(`Failed to find a default export from ${input.entry}.`);
632
+ }
633
+ return { app: module.default, module };
583
634
  }
584
- function isContentModuleLoaded(server, appRoot) {
585
- const entry = contentModuleEntry(appRoot);
586
- const moduleGraph = server.environments?.ssr?.moduleGraph;
587
- return Boolean(
588
- moduleGraph?.getModuleById(entry) ?? [...moduleGraph?.idToModuleMap?.values() ?? []].find(
589
- (module) => module.file && path6.resolve(module.file) === path6.resolve(entry)
590
- )
591
- );
635
+ function standaloneSsgModuleUrl(outputDirectory) {
636
+ return pathToFileURL(resolve2(outputDirectory, "ssg-server.mjs")).href;
592
637
  }
593
- async function loadContentModule(server, appRoot) {
594
- return await server.ssrLoadModule(
595
- contentModuleEntry(appRoot)
596
- );
638
+ function createFrameworkResolutionPlugin() {
639
+ return {
640
+ name: "riebeckite-ssg-framework-resolution",
641
+ enforce: "pre",
642
+ resolveId(source) {
643
+ if (!(source === "hono" || source.startsWith("hono/") || source === "honox" || source.startsWith("honox/"))) {
644
+ return void 0;
645
+ }
646
+ return frameworkRequire.resolve(source);
647
+ }
648
+ };
597
649
  }
598
-
599
- // src/content_assets.ts
600
- var IMAGE_CONTENT_TYPES = {
601
- png: "image/png",
602
- jpg: "image/jpeg",
603
- jpeg: "image/jpeg",
604
- gif: "image/gif",
605
- svg: "image/svg+xml",
606
- webp: "image/webp",
607
- bmp: "image/bmp"
608
- };
609
- function riebeckiteContentAssets(options) {
650
+ var runtimeExternalPackages = /* @__PURE__ */ new Set([
651
+ "@d2lang/d2",
652
+ "@marp-team/marp-core",
653
+ "@riebeckite/og-image"
654
+ ]);
655
+ function createRuntimeExternalPlugin() {
610
656
  return {
611
- name: "riebeckite-content-assets",
612
- apply: "serve",
657
+ name: "riebeckite-ssg-runtime-externals",
613
658
  enforce: "pre",
614
- configureServer(server) {
615
- const contentRoot = options.contentRoot();
616
- const base = server.config.base;
617
- const publicDir = server.config.publicDir;
618
- let cachedManifest;
619
- let cachedPaths = /* @__PURE__ */ new Set();
620
- const resolvePublicImagePaths = async () => {
621
- const module = await loadContentModule(server, options.appRoot());
622
- const manifest = await module.content?.getManifest?.();
623
- if (!manifest) return /* @__PURE__ */ new Set();
624
- if (manifest !== cachedManifest) {
625
- cachedManifest = manifest;
626
- cachedPaths = collectPublicImagePaths(manifest);
627
- }
628
- return cachedPaths;
629
- };
630
- const middleware = async (request, response, next) => {
631
- try {
632
- if (request.method !== "GET" && request.method !== "HEAD") {
633
- next();
634
- return;
635
- }
636
- const logicalPath = toContentPath(request.url, base);
637
- if (!logicalPath || !isImagePath(logicalPath)) {
638
- next();
639
- return;
640
- }
641
- if (isIgnoredContentPath(logicalPath)) {
642
- next();
643
- return;
644
- }
645
- const contentType = imageContentType(logicalPath);
646
- if (!contentType) {
647
- next();
648
- return;
649
- }
650
- const available = await resolvePublicImagePaths();
651
- if (!available.has(logicalPath)) {
652
- next();
653
- return;
654
- }
655
- const file = path7.join(contentRoot, logicalPath);
656
- if (!isPathInsideDirectory(contentRoot, file)) {
657
- next();
658
- return;
659
- }
660
- if (await hasSiteOwnedFile(publicDir, logicalPath)) {
661
- next();
662
- return;
663
- }
664
- const content = await fs5.readFile(file);
665
- response.statusCode = 200;
666
- response.setHeader("Content-Type", contentType);
667
- response.setHeader("Content-Length", String(content.byteLength));
668
- response.setHeader("Cache-Control", "no-cache");
669
- if (request.method === "HEAD") {
670
- response.end();
671
- return;
672
- }
673
- response.end(content);
674
- return;
675
- } catch {
676
- next();
677
- }
678
- };
679
- server.middlewares.use((request, response, next) => {
680
- void middleware(
681
- request,
682
- response,
683
- next
684
- );
685
- });
659
+ async resolveId(source, importer) {
660
+ if (!runtimeExternalPackages.has(source)) return void 0;
661
+ const resolved = await this.resolve(source, importer, { skipSelf: true });
662
+ return resolved ? { id: pathToFileURL(resolved.id).href, external: true } : void 0;
686
663
  }
687
664
  };
688
665
  }
689
- function collectPublicImagePaths(manifest) {
690
- const paths = /* @__PURE__ */ new Set();
691
- for (const entry of manifest.publicEntries ?? []) {
692
- for (const asset of entry.assets ?? []) {
693
- const normalized = normalizeContentPath(asset.path);
694
- if (isImagePath(normalized)) paths.add(normalized);
666
+ function createClientManifestPlugin(root, clientOutputDirectory) {
667
+ const manifestPath = `/${relative3(root, clientOutputDirectory).replaceAll("\\", "/")}/.vite/manifest.json`;
668
+ return {
669
+ name: "riebeckite-client-manifest",
670
+ enforce: "pre",
671
+ transform(code, id) {
672
+ return id.includes("honox/dist/server/components/") ? code.replaceAll("/dist/.vite/manifest.json", manifestPath) : void 0;
695
673
  }
696
- }
697
- return paths;
674
+ };
698
675
  }
699
- async function collectSiteOwnedOutputPaths(publicDir) {
700
- const paths = /* @__PURE__ */ new Set();
701
- if (!publicDir) return paths;
702
- const root = path7.resolve(publicDir);
703
- const walk = async (directory) => {
704
- const entries = await fs5.readdir(directory, { withFileTypes: true }).catch(() => void 0);
705
- if (!entries) return;
706
- for (const entry of entries) {
707
- const full = path7.join(directory, entry.name);
676
+
677
+ // src/ssg_plugin_cleanup.ts
678
+ import { rm as rm2 } from "node:fs/promises";
679
+
680
+ // src/ssg/build_output.ts
681
+ import { createHash as createHash2, randomUUID } from "node:crypto";
682
+ import { mkdir as mkdir2, readdir as readdir2, readFile as readFile2, rename, rm, stat } from "node:fs/promises";
683
+ import { dirname as dirname2, join as join2 } from "node:path";
684
+ var CLOUDFLARE_WORKER_ASSET_LIMIT = 25 * 1024 * 1024;
685
+ async function findOversizedAssets(directory, relativeDirectory = "") {
686
+ const entries = await readdir2(directory, { withFileTypes: true }).catch(
687
+ (error) => {
688
+ if (isMissingDirectoryError(error)) return [];
689
+ throw error;
690
+ }
691
+ );
692
+ const nestedAssets = await Promise.all(
693
+ entries.map(async (entry) => {
694
+ const path14 = join2(directory, entry.name);
695
+ const relativePath = join2(relativeDirectory, entry.name).replaceAll(
696
+ "\\",
697
+ "/"
698
+ );
708
699
  if (entry.isDirectory()) {
709
- await walk(full);
710
- } else {
711
- paths.add(path7.relative(root, full).replaceAll("\\", "/"));
700
+ return findOversizedAssets(path14, relativePath);
712
701
  }
702
+ if (!entry.isFile()) return [];
703
+ const size = (await stat(path14)).size;
704
+ return size > CLOUDFLARE_WORKER_ASSET_LIMIT ? [{ path: relativePath, size }] : [];
705
+ })
706
+ );
707
+ return nestedAssets.flat();
708
+ }
709
+ function formatBytes(bytes) {
710
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
711
+ }
712
+ async function emptyBuildOutputDirectory(outDir) {
713
+ const entries = await readdir2(outDir, { withFileTypes: true }).catch(
714
+ (error) => {
715
+ if (isMissingDirectoryError(error)) return [];
716
+ throw error;
713
717
  }
714
- };
715
- await walk(root);
716
- return paths;
717
- }
718
- function toContentPath(url, base) {
719
- if (!url) return void 0;
720
- const withoutQuery = url.split("?")[0]?.split("#")[0];
721
- if (!withoutQuery) return void 0;
722
- let decoded = withoutQuery;
723
- try {
724
- decoded = decodeURIComponent(withoutQuery);
725
- } catch {
726
- return void 0;
727
- }
728
- let pathname = normalizeContentPath(decoded);
729
- if (base && base !== "/" && pathname.startsWith(base)) {
730
- pathname = normalizeContentPath(pathname.slice(base.length));
731
- }
732
- const logicalPath = pathname.replace(/^\/+/, "");
733
- if (!logicalPath) return void 0;
734
- if (logicalPath.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) {
735
- return void 0;
736
- }
737
- return logicalPath;
738
- }
739
- function imageContentType(logicalPath) {
740
- const extension = logicalPath.split("/").at(-1)?.split(".").at(-1);
741
- if (!extension) return void 0;
742
- return IMAGE_CONTENT_TYPES[extension.toLowerCase()];
743
- }
744
- async function hasSiteOwnedFile(publicDir, logicalPath) {
745
- if (!publicDir) return false;
746
- const file = path7.join(publicDir, logicalPath);
747
- try {
748
- return (await fs5.stat(file)).isFile();
749
- } catch {
750
- return false;
751
- }
752
- }
753
-
754
- // src/ssg/artifact_writer.ts
755
- import { randomUUID } from "node:crypto";
756
- import { constants } from "node:fs";
757
- import {
758
- copyFile,
759
- cp,
760
- link,
761
- lstat,
762
- mkdir,
763
- readFile as readFile2,
764
- rename,
765
- rm,
766
- writeFile
767
- } from "node:fs/promises";
768
- import { dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";
769
- async function createBuildArtifactWriter(input) {
770
- const outputDirectory = input.outputDirectory;
771
- await recoverPendingPublication(outputDirectory);
772
- const stagingDirectory = input.stagingDirectory ?? join2(
773
- dirname2(outputDirectory),
774
- ".riebeckite",
775
- `build-output-${randomUUID()}`
776
- );
777
- if (resolve2(stagingDirectory) === resolve2(outputDirectory)) {
778
- throw new Error(
779
- "Build artifact staging directory must differ from output."
780
- );
781
- }
782
- if (input.clearStagingDirectory !== false) {
783
- await rm(stagingDirectory, { force: true, recursive: true });
784
- }
785
- await mkdir(stagingDirectory, { recursive: true });
786
- let completed = false;
787
- return {
788
- directory: stagingDirectory,
789
- async copyFrom(source) {
790
- ensureOpen(completed);
791
- await cp(source, stagingDirectory, { recursive: true });
792
- },
793
- async remove(path12) {
794
- ensureOpen(completed);
795
- await rm(resolveArtifactPath(stagingDirectory, path12), {
796
- force: true,
797
- recursive: true
798
- });
799
- },
800
- async write(path12, data) {
801
- ensureOpen(completed);
802
- const target = resolveArtifactPath(stagingDirectory, path12);
803
- await mkdir(dirname2(target), { recursive: true });
804
- await replaceArtifactFile(target, data);
805
- },
806
- async copyFileFrom(source, path12) {
807
- ensureOpen(completed);
808
- const target = resolveArtifactPath(stagingDirectory, path12);
809
- await mkdir(dirname2(target), { recursive: true });
810
- await rm(target, { force: true });
811
- try {
812
- await link(source, target);
813
- } catch {
814
- await copyFile(source, target, constants.COPYFILE_FICLONE);
815
- }
816
- },
817
- async publish() {
818
- ensureOpen(completed);
819
- await publishDirectory(stagingDirectory, outputDirectory);
820
- completed = true;
821
- },
822
- async discard() {
823
- if (completed) return;
824
- completed = true;
825
- await rm(stagingDirectory, { force: true, recursive: true });
826
- }
827
- };
828
- }
829
- function ensureOpen(completed) {
830
- if (completed) throw new Error("Build artifact writer is already closed.");
831
- }
832
- async function replaceArtifactFile(target, data) {
833
- const temporaryPath = `${target}.${randomUUID()}.tmp`;
834
- try {
835
- await writeFile(temporaryPath, data);
836
- try {
837
- await rename(temporaryPath, target);
838
- } catch {
839
- await rm(target, { force: true });
840
- await rename(temporaryPath, target);
841
- }
842
- } catch (error) {
843
- await rm(temporaryPath, { force: true }).catch(() => void 0);
844
- throw error;
845
- }
846
- }
847
- function resolveArtifactPath(directory, path12) {
848
- return resolveWithinDirectory(directory, path12, "Build artifact path");
849
- }
850
- async function publishDirectory(stagingDirectory, outputDirectory) {
851
- const backupDirectory = join2(
852
- dirname2(outputDirectory),
853
- ".riebeckite",
854
- `build-output-backup-${randomUUID()}`
855
- );
856
- const previousOutputExists = await isDirectory(outputDirectory);
857
- let previousOutputMoved = false;
858
- const journalPath = publicationJournalPath(outputDirectory);
859
- await writeJournal(journalPath, {
860
- backupDirectory,
861
- outputDirectory,
862
- stagingDirectory,
863
- state: "staged"
864
- });
865
- try {
866
- if (previousOutputExists) {
867
- await moveWithRetry(outputDirectory, backupDirectory);
868
- previousOutputMoved = true;
869
- await writeJournal(journalPath, {
870
- backupDirectory,
871
- outputDirectory,
872
- stagingDirectory,
873
- state: "previous-output-moved"
874
- });
875
- }
876
- await moveWithRetry(stagingDirectory, outputDirectory);
877
- await writeJournal(journalPath, {
878
- backupDirectory,
879
- outputDirectory,
880
- stagingDirectory,
881
- state: "published"
882
- });
883
- } catch (error) {
884
- if (previousOutputMoved) {
885
- await rm(outputDirectory, { force: true, recursive: true });
886
- await moveWithRetry(backupDirectory, outputDirectory);
887
- }
888
- await rm(journalPath, { force: true });
889
- throw error;
890
- }
891
- await rm(backupDirectory, { force: true, recursive: true });
892
- await rm(journalPath, { force: true });
893
- }
894
- function publicationJournalPath(outputDirectory) {
895
- return join2(dirname2(outputDirectory), ".riebeckite", "build-output.json");
896
- }
897
- async function writeJournal(path12, journal) {
898
- await mkdir(dirname2(path12), { recursive: true });
899
- await writeFile(path12, JSON.stringify(journal));
900
- }
901
- async function recoverPendingPublication(outputDirectory) {
902
- const path12 = publicationJournalPath(outputDirectory);
903
- let journal;
904
- try {
905
- journal = JSON.parse(await readFile2(path12, "utf8"));
906
- } catch (error) {
907
- if (isNotFoundError2(error)) return;
908
- await rm(path12, { force: true });
909
- return;
910
- }
911
- if (journal.outputDirectory !== outputDirectory || !isPublicationJournalState(journal.state)) {
912
- await rm(path12, { force: true });
913
- return;
914
- }
915
- if (journal.state === "previous-output-moved" && !await isDirectory(outputDirectory) && await isDirectory(journal.backupDirectory)) {
916
- await moveWithRetry(journal.backupDirectory, outputDirectory);
917
- }
918
- await rm(journal.backupDirectory, { force: true, recursive: true });
919
- await rm(journal.stagingDirectory, { force: true, recursive: true });
920
- await rm(path12, { force: true });
921
- }
922
- function isPublicationJournalState(value) {
923
- return value === "staged" || value === "previous-output-moved" || value === "published";
924
- }
925
- async function isDirectory(path12) {
926
- try {
927
- return (await lstat(path12)).isDirectory();
928
- } catch (error) {
929
- if (isNotFoundError2(error)) return false;
930
- throw error;
931
- }
932
- }
933
- async function moveWithRetry(source, destination) {
934
- let error;
935
- for (let attempt = 0; attempt < 3; attempt += 1) {
936
- try {
937
- await rename(source, destination);
938
- return;
939
- } catch (nextError) {
940
- error = nextError;
941
- if (!isRetryableRenameError(nextError) || attempt === 2) break;
942
- await new Promise((resolve5) => setTimeout(resolve5, (attempt + 1) * 25));
943
- }
944
- }
945
- throw error;
946
- }
947
- function isNotFoundError2(error) {
948
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
949
- }
950
- function isRetryableRenameError(error) {
951
- return typeof error === "object" && error !== null && "code" in error && ["EBUSY", "EPERM", "EACCES"].includes(
952
- error.code
953
- );
954
- }
955
-
956
- // src/ssg/build_output.ts
957
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
958
- import { mkdir as mkdir2, readdir as readdir2, readFile as readFile3, rename as rename2, rm as rm2, stat } from "node:fs/promises";
959
- import { dirname as dirname3, join as join3 } from "node:path";
960
- var CLOUDFLARE_WORKER_ASSET_LIMIT = 25 * 1024 * 1024;
961
- async function findOversizedAssets(directory, relativeDirectory = "") {
962
- const entries = await readdir2(directory, { withFileTypes: true }).catch(
963
- (error) => {
964
- if (isMissingDirectoryError(error)) return [];
965
- throw error;
966
- }
967
- );
968
- const nestedAssets = await Promise.all(
969
- entries.map(async (entry) => {
970
- const path12 = join3(directory, entry.name);
971
- const relativePath = join3(relativeDirectory, entry.name).replaceAll(
972
- "\\",
973
- "/"
974
- );
975
- if (entry.isDirectory()) {
976
- return findOversizedAssets(path12, relativePath);
977
- }
978
- if (!entry.isFile()) return [];
979
- const size = (await stat(path12)).size;
980
- return size > CLOUDFLARE_WORKER_ASSET_LIMIT ? [{ path: relativePath, size }] : [];
981
- })
982
- );
983
- return nestedAssets.flat();
984
- }
985
- function formatBytes(bytes) {
986
- return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
987
- }
988
- async function emptyBuildOutputDirectory(outDir) {
989
- const entries = await readdir2(outDir, { withFileTypes: true }).catch(
990
- (error) => {
991
- if (isMissingDirectoryError(error)) return [];
992
- throw error;
993
- }
994
- );
995
- for (const entry of entries) {
996
- await rm2(join3(outDir, entry.name), { recursive: true, force: true });
997
- }
718
+ );
719
+ for (const entry of entries) {
720
+ await rm(join2(outDir, entry.name), { recursive: true, force: true });
721
+ }
998
722
  }
999
723
  async function preserveClientBuildArtifacts(outDir) {
1000
724
  const manifestPath = ".vite/manifest.json";
1001
725
  let manifestSource;
1002
726
  try {
1003
- manifestSource = await readFile3(join3(outDir, manifestPath), "utf8");
727
+ manifestSource = await readFile2(join2(outDir, manifestPath), "utf8");
1004
728
  } catch (error) {
1005
729
  if (isNotFoundError(error)) return void 0;
1006
730
  throw error;
1007
731
  }
1008
732
  const paths = [manifestPath, ...collectClientAssetPaths(manifestSource)];
1009
- const stagingDirectory = join3(
1010
- dirname3(outDir),
733
+ const stagingDirectory = join2(
734
+ dirname2(outDir),
1011
735
  ".riebeckite",
1012
- `client-build-${randomUUID2()}`
736
+ `client-build-${randomUUID()}`
1013
737
  );
1014
738
  for (const relativePath of paths) {
1015
739
  const source = resolveBuildArtifactPath(outDir, relativePath);
@@ -1017,8 +741,8 @@ async function preserveClientBuildArtifacts(outDir) {
1017
741
  stagingDirectory,
1018
742
  relativePath
1019
743
  );
1020
- await mkdir2(dirname3(destination), { recursive: true });
1021
- await rename2(source, destination);
744
+ await mkdir2(dirname2(destination), { recursive: true });
745
+ await rename(source, destination);
1022
746
  }
1023
747
  return {
1024
748
  stagingDirectory,
@@ -1034,13 +758,13 @@ async function restoreClientBuildArtifacts(outDir, artifacts) {
1034
758
  relativePath
1035
759
  );
1036
760
  const destination = resolveBuildArtifactPath(outDir, relativePath);
1037
- await mkdir2(dirname3(destination), { recursive: true });
1038
- await rename2(source, destination);
761
+ await mkdir2(dirname2(destination), { recursive: true });
762
+ await rename(source, destination);
1039
763
  }
1040
764
  }
1041
765
  async function discardClientBuildArtifacts(artifacts) {
1042
766
  if (!artifacts) return;
1043
- await rm2(artifacts.stagingDirectory, { recursive: true, force: true });
767
+ await rm(artifacts.stagingDirectory, { recursive: true, force: true });
1044
768
  }
1045
769
  async function collectBuildOutputPaths(directory, relativeDirectory = "") {
1046
770
  const entries = await readdir2(directory, { withFileTypes: true }).catch(
@@ -1052,14 +776,14 @@ async function collectBuildOutputPaths(directory, relativeDirectory = "") {
1052
776
  if (!entries) return [];
1053
777
  const paths = [];
1054
778
  for (const entry of entries) {
1055
- const relativePath = join3(relativeDirectory, entry.name).replaceAll(
779
+ const relativePath = join2(relativeDirectory, entry.name).replaceAll(
1056
780
  "\\",
1057
781
  "/"
1058
782
  );
1059
783
  if (entry.isDirectory()) {
1060
784
  paths.push(
1061
785
  ...await collectBuildOutputPaths(
1062
- join3(directory, entry.name),
786
+ join2(directory, entry.name),
1063
787
  relativePath
1064
788
  )
1065
789
  );
@@ -1073,7 +797,7 @@ async function verifyClientBuildArtifacts(input) {
1073
797
  const manifestPath = ".vite/manifest.json";
1074
798
  let manifestSource;
1075
799
  try {
1076
- manifestSource = await readFile3(
800
+ manifestSource = await readFile2(
1077
801
  resolveBuildArtifactPath(input.outDir, manifestPath),
1078
802
  "utf8"
1079
803
  );
@@ -1086,7 +810,7 @@ async function verifyClientBuildArtifacts(input) {
1086
810
  if (!expectedChecksum) return false;
1087
811
  try {
1088
812
  const actualChecksum = createHash2("sha256").update(
1089
- await readFile3(resolveBuildArtifactPath(input.outDir, relativePath))
813
+ await readFile2(resolveBuildArtifactPath(input.outDir, relativePath))
1090
814
  ).digest("hex");
1091
815
  if (actualChecksum !== expectedChecksum) return false;
1092
816
  } catch {
@@ -1124,7 +848,7 @@ function addClientAssetPath(paths, value) {
1124
848
  }
1125
849
  function addClientAssetPaths(paths, value) {
1126
850
  if (!Array.isArray(value)) return;
1127
- for (const path12 of value) addClientAssetPath(paths, path12);
851
+ for (const path14 of value) addClientAssetPath(paths, path14);
1128
852
  }
1129
853
  function resolveBuildArtifactPath(directory, relativePath) {
1130
854
  return resolveWithinDirectory(
@@ -1134,80 +858,115 @@ function resolveBuildArtifactPath(directory, relativePath) {
1134
858
  );
1135
859
  }
1136
860
 
1137
- // src/ssg/diagnostics.ts
1138
- function formatSsrNoExternal() {
1139
- return "/^honox(?:\\/.*)?$/";
861
+ // src/ssg_plugin_cleanup.ts
862
+ async function cleanupSsgGeneration(ctx, state) {
863
+ await rm2(ctx.bundleDirectory, { recursive: true, force: true });
864
+ await discardClientBuildArtifacts(state.clientBuildArtifacts);
865
+ if (state.clientOutputDirectory) {
866
+ await rm2(state.clientOutputDirectory, { recursive: true, force: true });
867
+ }
868
+ state.clientBuildArtifacts = void 0;
1140
869
  }
1141
- function logSsgDiagnostics(logger, message) {
1142
- if (process.env.RIEBECKITE_SSG_DIAGNOSTICS !== "1") return;
1143
- logger.info(`[riebeckite-ssg] ${message}`);
870
+
871
+ // src/ssg_plugin_close.ts
872
+ import { resolve as resolve3 } from "node:path";
873
+ import { buildOutputPlan, compareOutputPlan } from "@riebeckite/core";
874
+
875
+ // src/ssg/output_cache_decision.ts
876
+ import { join as join4 } from "node:path";
877
+ import { performance as performance3 } from "node:perf_hooks";
878
+
879
+ // src/ssg/output_cache_fastpath.ts
880
+ import { randomUUID as randomUUID3 } from "node:crypto";
881
+ import { lstat as lstat3, mkdir as mkdir4, readFile as readFile4, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
882
+ import { dirname as dirname3 } from "node:path";
883
+
884
+ // src/ssg/output_cache_paths.ts
885
+ import { createHash as createHash3 } from "node:crypto";
886
+ import { lstat, mkdir as mkdir3, readFile as readFile3 } from "node:fs/promises";
887
+ function outputCacheEntriesPath(outputCachePath) {
888
+ return outputCachePath.replace(/\.json$/, ".entries");
1144
889
  }
1145
- function logGeneratedHtmlAssetDiagnostics(logger, pages) {
1146
- if (process.env.RIEBECKITE_SSG_DIAGNOSTICS !== "1") return;
1147
- const renderedPages = pages.filter(
1148
- (page) => !/<meta\b[^>]*\bhttp-equiv=["']refresh["'][^>]*\bcontent=["'][^"']*\burl=/iu.test(
1149
- page.html
1150
- )
1151
- );
1152
- const cssPages = renderedPages.filter(
1153
- (page) => /<link\b[^>]*\brel=["'][^"']*\bstylesheet\b[^"']*["']/iu.test(page.html)
1154
- );
1155
- const scriptPages = renderedPages.filter(
1156
- (page) => /<script\b[^>]*\bsrc=["'][^"']+["']/iu.test(page.html)
1157
- );
1158
- const missingCss = renderedPages.filter((page) => !cssPages.includes(page)).map((page) => page.path);
1159
- const missingScript = renderedPages.filter((page) => !scriptPages.includes(page)).map((page) => page.path);
1160
- logger.info(
1161
- `[riebeckite-ssg] rendered HTML assets: ${pages.length} documents (${renderedPages.length} pages, ${pages.length - renderedPages.length} redirects) · CSS ${cssPages.length} · JavaScript ${scriptPages.length} · missing CSS ${missingCss.length} · missing JavaScript ${missingScript.length}`
890
+ function resolveOutputCacheEntryPath(outputCachePath, entry) {
891
+ return resolveOutputCacheFile(
892
+ outputCacheEntriesPath(outputCachePath),
893
+ entry.cachePath
1162
894
  );
1163
- if (missingCss.length > 0 || missingScript.length > 0) {
1164
- logger.info(
1165
- `[riebeckite-ssg] missing asset references: CSS ${missingCss.join(", ") || "none"} · JavaScript ${missingScript.join(", ") || "none"}`
1166
- );
1167
- }
1168
895
  }
1169
- function inspectGeneratedHtmlPages(module, pages, log) {
1170
- const diagnostics = [];
1171
- const plugins = module.config?.plugins ?? [];
1172
- for (const plugin of plugins) {
1173
- const inspector = plugin.inspectGeneratedHtml;
1174
- if (typeof inspector !== "function") continue;
1175
- for (const page of pages) {
1176
- for (const diagnostic of inspector(page) ?? []) {
1177
- const label = `[${plugin.name ?? "plugin"}] ${page.path}: ${diagnostic.message}`;
1178
- if (diagnostic.severity === "info") log.info(label);
1179
- else log.warn(label);
1180
- diagnostics.push({
1181
- code: diagnostic.code ?? "generated-html",
1182
- severity: diagnostic.severity,
1183
- message: diagnostic.message,
1184
- pluginName: plugin.name,
1185
- filePath: diagnostic.filePath ?? page.path
1186
- });
1187
- }
1188
- }
896
+ function resolveOutputCacheFile(directory, relativePath) {
897
+ return resolveWithinDirectory(
898
+ directory,
899
+ relativePath,
900
+ "SSG output cache path"
901
+ );
902
+ }
903
+ function isSafeLogicalOutputPath(path14) {
904
+ if (typeof path14 !== "string" || !path14 || path14.includes("\\") || path14.includes("\0") || isAbsolutePath(path14)) {
905
+ return false;
906
+ }
907
+ try {
908
+ resolveOutputCacheFile("/riebeckite-output-root", path14);
909
+ return true;
910
+ } catch {
911
+ return false;
912
+ }
913
+ }
914
+ function assertSafeLogicalOutputPath(path14) {
915
+ if (!isSafeLogicalOutputPath(path14)) {
916
+ throw new Error(`Invalid SSG output path: ${path14}`);
917
+ }
918
+ }
919
+ function outputCacheEntryName(outputPath) {
920
+ return createHash3("sha256").update(outputPath).digest("hex");
921
+ }
922
+ async function ensureOutputCacheEntriesDirectory(directory) {
923
+ await mkdir3(directory, { recursive: true });
924
+ if (!await isSafeOutputCacheEntriesDirectory(directory)) {
925
+ throw new Error(`Unsafe SSG output cache entries directory: ${directory}`);
926
+ }
927
+ }
928
+ async function isSafeOutputCacheDirectory(directory) {
929
+ try {
930
+ const info = await lstat(directory);
931
+ return info.isDirectory() && !info.isSymbolicLink();
932
+ } catch {
933
+ return false;
934
+ }
935
+ }
936
+ async function isSafeCacheFileTarget(path14) {
937
+ try {
938
+ return !(await lstat(path14)).isSymbolicLink();
939
+ } catch (error) {
940
+ return isNotFoundError(error);
941
+ }
942
+ }
943
+ async function isSafeOutputCacheEntriesDirectory(directory) {
944
+ return isSafeOutputCacheDirectory(directory);
945
+ }
946
+ async function isRegularFile(path14) {
947
+ try {
948
+ const info = await lstat(path14);
949
+ return info.isFile() && !info.isSymbolicLink();
950
+ } catch {
951
+ return false;
1189
952
  }
1190
- return diagnostics;
1191
953
  }
1192
954
 
1193
- // src/ssg/output_cache.ts
1194
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
955
+ // src/ssg/output_cache_replace.ts
956
+ import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
1195
957
  import { createReadStream } from "node:fs";
1196
958
  import {
1197
- copyFile as copyFile2,
959
+ copyFile,
1198
960
  lstat as lstat2,
1199
- mkdir as mkdir3,
1200
961
  readdir as readdir3,
1201
- readFile as readFile4,
1202
- rename as rename3,
962
+ rename as rename2,
1203
963
  rm as rm3,
1204
- writeFile as writeFile3
964
+ writeFile as writeFile2
1205
965
  } from "node:fs/promises";
1206
- import { dirname as dirname4, join as join4 } from "node:path";
1207
- import { performance as performance3 } from "node:perf_hooks";
966
+ import { join as join3 } from "node:path";
1208
967
 
1209
968
  // src/ssg/runtime_metrics.ts
1210
- import { writeFile as writeFile2 } from "node:fs/promises";
969
+ import { writeFile } from "node:fs/promises";
1211
970
  import { performance as performance2 } from "node:perf_hooks";
1212
971
  async function measure(timingsMs, name, fn) {
1213
972
  if (!timingsMs) return await fn();
@@ -1215,8 +974,7 @@ async function measure(timingsMs, name, fn) {
1215
974
  try {
1216
975
  return await fn();
1217
976
  } finally {
1218
- if (timingsMs)
1219
- timingsMs[name] = (timingsMs[name] ?? 0) + performance2.now() - start;
977
+ timingsMs[name] = (timingsMs[name] ?? 0) + performance2.now() - start;
1220
978
  }
1221
979
  }
1222
980
  function measureSync(timingsMs, name, fn) {
@@ -1225,198 +983,98 @@ function measureSync(timingsMs, name, fn) {
1225
983
  try {
1226
984
  return fn();
1227
985
  } finally {
1228
- if (timingsMs)
1229
- timingsMs[name] = (timingsMs[name] ?? 0) + performance2.now() - start;
986
+ timingsMs[name] = (timingsMs[name] ?? 0) + performance2.now() - start;
1230
987
  }
1231
988
  }
1232
989
  async function writeSsgOutputMetrics(metrics) {
1233
990
  const file = process.env.RIEBECKITE_SSG_METRICS_FILE;
1234
991
  if (!file) return;
1235
- await writeFile2(file, `${JSON.stringify(metrics)}
992
+ await writeFile(file, `${JSON.stringify(metrics)}
1236
993
  `, "utf8");
1237
994
  }
1238
995
 
1239
- // src/ssg/output_cache.ts
1240
- var outputCacheValidationConcurrency = 12;
1241
- function decideOutputCacheRejection(decision) {
1242
- if (!decision.changeSetPresent) return "change-set-unavailable";
1243
- if (decision.changeSetRequiresFullRegeneration)
1244
- return "full-regeneration-required";
1245
- if (!decision.outputCacheLoaded) return "output-cache-missing-or-invalid";
1246
- if (!decision.appFingerprintMatch) return "app-fingerprint-changed";
1247
- if (!decision.clientManifestFingerprintMatch)
1248
- return "client-manifest-fingerprint-changed";
1249
- if (decision.uncoveredUnchangedCount > 0)
1250
- return "unchanged-output-not-cached";
1251
- return void 0;
1252
- }
1253
- function createNoChangeFastPathOutputMetrics() {
1254
- return {
1255
- outputInventoryValidationDurationMs: 0,
1256
- outputHashValidationDurationMs: 0,
1257
- outputFilesHashed: 0,
1258
- outputBytesHashed: 0
1259
- };
1260
- }
1261
- async function verifyNoChangeFastPath(input) {
1262
- const outputCachePath = join4(
1263
- input.root,
1264
- ".riebeckite",
1265
- "ssg-output-cache.json"
1266
- );
1267
- const cache = await loadFastPathCache(fastPathCachePath(outputCachePath));
1268
- if (!cache)
1269
- return { used: false, blockReason: "output-cache-missing-or-invalid" };
1270
- if (cache.outputCacheChecksum !== await checksumFile(outputCachePath)) {
1271
- return { used: false, blockReason: "output-cache-missing-or-invalid" };
1272
- }
1273
- if (cache.appFingerprint !== await computeAppFingerprint(input.root, cache.configFile)) {
1274
- return { used: false, blockReason: "app-fingerprint-changed" };
1275
- }
1276
- if (cache.publicDirectory && cache.publicFingerprint !== await fingerprintDirectory(cache.publicDirectory)) {
1277
- return { used: false, blockReason: "static-assets-changed" };
1278
- }
1279
- if (input.expectedOutputPaths.some(
1280
- (output) => !cache.outputPaths.includes(output) || !cache.finalOutputInventory[output]
1281
- )) {
1282
- return { used: false, blockReason: "output-cache-incomplete" };
1283
- }
1284
- const knownChecksums = await matchingOutputChecksums(
1285
- input.outputDirectory,
1286
- cache.finalOutputInventory,
1287
- cache.finalOutputStats
1288
- );
1289
- const inventoryStartedAt = performance3.now();
1290
- const currentInventory = await fingerprintOutputDirectory(
1291
- input.outputDirectory,
1292
- "",
1293
- input.metrics,
1294
- knownChecksums
1295
- );
1296
- if (input.metrics)
1297
- input.metrics.outputInventoryValidationDurationMs += performance3.now() - inventoryStartedAt;
1298
- if (!inventoriesEqual(cache.finalOutputInventory, currentInventory)) {
1299
- return { used: false, blockReason: "output-inventory-mismatch" };
1300
- }
1301
- const currentStats = await collectOutputFileStats(
1302
- input.outputDirectory,
1303
- cache.finalOutputInventory
1304
- );
1305
- if (!outputStatsEqual(cache.finalOutputStats, currentStats)) {
1306
- await saveFastPathCache(fastPathCachePath(outputCachePath), {
1307
- ...cache,
1308
- finalOutputStats: currentStats
1309
- }).catch(() => void 0);
1310
- }
1311
- return { used: true };
1312
- }
1313
- async function loadOutputCacheMetadata(path12, timingsMs, log = () => {
1314
- }) {
1315
- if (!await isSafeOutputCacheDirectory(dirname4(path12))) {
1316
- log("SSG output cache directory is unsafe and will be ignored.");
1317
- return void 0;
1318
- }
1319
- if (!await isRegularFile(path12)) {
1320
- return void 0;
1321
- }
1322
- let raw;
996
+ // src/ssg/output_cache_replace.ts
997
+ async function checksumFile(path14) {
998
+ const hash = createHash4("sha256");
1323
999
  try {
1324
- raw = await measure(
1325
- timingsMs,
1326
- "outputCacheRead",
1327
- () => readFile4(path12, "utf8")
1328
- );
1329
- } catch (error) {
1330
- if (isNotFoundError(error)) return void 0;
1331
- log(
1332
- `SSG output cache could not be read; the build regenerates every output. ${error instanceof Error ? error.message : String(error)}`
1333
- );
1000
+ for await (const chunk of createReadStream(path14)) hash.update(chunk);
1001
+ return hash.digest("hex");
1002
+ } catch {
1334
1003
  return void 0;
1335
1004
  }
1336
- let parsed;
1005
+ }
1006
+ async function replaceFile(temporaryPath, targetPath) {
1337
1007
  try {
1338
- parsed = measureSync(timingsMs, "outputCacheParse", () => JSON.parse(raw));
1008
+ await rename2(temporaryPath, targetPath);
1339
1009
  } catch (error) {
1340
- log(
1341
- `SSG output cache is corrupted and will be rebuilt. ${error instanceof Error ? error.message : String(error)}`
1342
- );
1343
- return void 0;
1344
- }
1345
- if (!isOutputCacheState(parsed)) {
1346
- log("SSG output cache uses an unsupported format and will be rebuilt.");
1347
- return void 0;
1010
+ if (!isReplacementFailure(error)) throw error;
1011
+ await rm3(targetPath, { force: true });
1012
+ await rename2(temporaryPath, targetPath);
1348
1013
  }
1349
- return timingsMs ? { ...parsed, fileSizeBytes: Buffer.byteLength(raw) } : parsed;
1350
- }
1351
- async function validateOutputCache(cache, path12, timingsMs, log = () => {
1352
- }) {
1353
- const entriesAreValid = await measure(
1354
- timingsMs,
1355
- "outputCacheEntriesValidate",
1356
- () => validateOutputCacheEntries(path12, cache.outputs, timingsMs)
1357
- );
1358
- if (entriesAreValid) return true;
1359
- log("SSG output cache entries are corrupted and will be rebuilt.");
1360
- return false;
1361
1014
  }
1362
- async function saveOutputCache(path12, state, outputDirectory, timingsMs) {
1363
- const directory = dirname4(path12);
1364
- await mkdir3(directory, { recursive: true });
1365
- if (!await isSafeOutputCacheDirectory(directory)) {
1366
- throw new Error(`Unsafe SSG output cache directory: ${directory}`);
1015
+ function isReplacementFailure(error) {
1016
+ if (typeof error !== "object" || error === null || !("code" in error)) {
1017
+ return false;
1367
1018
  }
1368
- if (!await isSafeCacheFileTarget(path12)) {
1369
- throw new Error(`Unsafe SSG output cache file: ${path12}`);
1019
+ const code = String(error.code);
1020
+ return code === "EPERM" || code === "EEXIST" || code === "EACCES";
1021
+ }
1022
+ async function replaceOutputCacheEntry(source, destination, timingsMs) {
1023
+ if ((await lstat2(destination).catch(() => void 0))?.isSymbolicLink()) {
1024
+ throw new Error(`Unsafe SSG output cache entry: ${destination}`);
1370
1025
  }
1371
- const entriesPath = outputCacheEntriesPath(path12);
1372
- const temporaryPath = `${path12}.${randomUUID3()}.tmp`;
1026
+ const temporaryPath = `${destination}.${randomUUID2()}.tmp`;
1373
1027
  try {
1374
- const outputs = await measure(
1375
- timingsMs,
1376
- "outputCacheEntriesWrite",
1377
- () => saveOutputCacheEntries(
1378
- entriesPath,
1379
- outputDirectory,
1380
- state.outputs,
1381
- state.finalOutputInventory,
1382
- timingsMs
1383
- )
1384
- );
1385
- const serialized = measureSync(
1028
+ await measure(
1386
1029
  timingsMs,
1387
- "outputCacheSerialize",
1388
- () => `${JSON.stringify({ ...state, outputs })}
1389
- `
1030
+ "outputCacheEntryWrite",
1031
+ () => writeFile2(temporaryPath, new Uint8Array())
1390
1032
  );
1391
1033
  await measure(
1392
1034
  timingsMs,
1393
- "outputCacheWrite",
1394
- () => writeFile3(temporaryPath, serialized, "utf8")
1035
+ "outputCacheEntryCopy",
1036
+ () => copyFile(source, temporaryPath)
1395
1037
  );
1396
1038
  await measure(
1397
1039
  timingsMs,
1398
- "outputCacheRename",
1399
- () => replaceFile(temporaryPath, path12)
1400
- );
1401
- const checksum = createHash3("sha256").update(serialized).digest("hex");
1402
- if (state.finalOutputInventory && state.configFile) {
1403
- await saveFastPathCache(
1404
- fastPathCachePath(path12),
1405
- await createFastPathCacheState(state, checksum, outputDirectory),
1406
- timingsMs
1407
- );
1408
- }
1409
- await collectUnreferencedOutputCacheEntries(
1410
- outputCacheEntriesPath(path12),
1411
- outputs,
1412
- timingsMs
1040
+ "outputCacheEntryRename",
1041
+ () => replaceFile(temporaryPath, destination)
1413
1042
  );
1414
- return checksum;
1415
1043
  } catch (error) {
1416
1044
  await rm3(temporaryPath, { force: true }).catch(() => void 0);
1417
1045
  throw error;
1418
1046
  }
1419
1047
  }
1048
+ async function collectUnreferencedOutputCacheEntries(directory, outputs, timingsMs) {
1049
+ try {
1050
+ if (!await isSafeOutputCacheEntriesDirectory(directory)) return;
1051
+ const referenced = new Set(
1052
+ Object.values(outputs).map((entry) => entry.cachePath)
1053
+ );
1054
+ const entries = await measure(
1055
+ timingsMs,
1056
+ "outputCacheGcScan",
1057
+ () => readdir3(directory, { withFileTypes: true })
1058
+ );
1059
+ for (const entry of entries) {
1060
+ if (!/^[a-f0-9]{64}$/u.test(entry.name) || referenced.has(entry.name)) {
1061
+ continue;
1062
+ }
1063
+ const path14 = join3(directory, entry.name);
1064
+ if (await isRegularFile(path14)) {
1065
+ await measure(
1066
+ timingsMs,
1067
+ "outputCacheGcDelete",
1068
+ () => rm3(path14, { force: true })
1069
+ );
1070
+ }
1071
+ }
1072
+ } catch {
1073
+ return;
1074
+ }
1075
+ }
1076
+
1077
+ // src/ssg/output_cache_validate.ts
1420
1078
  function isOutputCacheState(value) {
1421
1079
  if (typeof value !== "object" || value === null) return false;
1422
1080
  const candidate = value;
@@ -1443,114 +1101,18 @@ function isOutputCacheEntries(value) {
1443
1101
  function isOptionalNonNegativeNumber(value) {
1444
1102
  return value === void 0 || typeof value === "number" && Number.isFinite(value) && value >= 0;
1445
1103
  }
1446
- function outputCacheEntriesPath(outputCachePath) {
1447
- return outputCachePath.replace(/\.json$/, ".entries");
1448
- }
1449
- async function saveOutputCacheEntries(directory, outputDirectory, outputs, finalOutputInventory, timingsMs) {
1450
- await ensureOutputCacheEntriesDirectory(directory);
1451
- const entries = {};
1452
- for (const outputPath of Object.keys(outputs).sort()) {
1453
- assertSafeLogicalOutputPath(outputPath);
1454
- const existing = outputs[outputPath];
1455
- if (existing.cachePath && existing.checksum) {
1456
- if (existing.cachePath !== outputCacheEntryName(outputPath) || !isChecksum(existing.checksum)) {
1457
- throw new Error(`Invalid SSG output cache entry: ${outputPath}`);
1458
- }
1459
- const cached = await existingOutputCacheEntry(
1460
- existing,
1461
- join4(directory, existing.cachePath)
1462
- );
1463
- if (cached) {
1464
- entries[outputPath] = cached;
1465
- continue;
1466
- }
1467
- }
1468
- const source = resolveOutputCacheFile(outputDirectory, outputPath);
1469
- const cachePath = outputCacheEntryName(outputPath);
1470
- const destination = join4(directory, cachePath);
1471
- await replaceOutputCacheEntry(source, destination, timingsMs);
1472
- const checksum = finalOutputInventory?.[outputPath];
1473
- if (!checksum) {
1474
- const cachedChecksum = await checksumFile(destination);
1475
- if (!cachedChecksum) {
1476
- throw new Error(`Could not checksum cached output: ${outputPath}`);
1477
- }
1478
- entries[outputPath] = await withOutputCacheEntryStat(
1479
- { cachePath, checksum: cachedChecksum },
1480
- destination
1481
- );
1482
- continue;
1483
- }
1484
- entries[outputPath] = await withOutputCacheEntryStat(
1485
- { cachePath, checksum },
1486
- destination
1487
- );
1488
- }
1489
- return entries;
1490
- }
1491
- async function withOutputCacheEntryStat(entry, path12) {
1492
- const info = await lstat2(path12).catch(() => void 0);
1493
- if (!info?.isFile() || info.isSymbolicLink()) return entry;
1494
- return { ...entry, size: info.size, modifiedAtMs: info.mtimeMs };
1495
- }
1496
- async function existingOutputCacheEntry(entry, path12) {
1497
- const info = await lstat2(path12).catch(() => void 0);
1498
- if (!info?.isFile() || info.isSymbolicLink()) return void 0;
1499
- return { ...entry, size: info.size, modifiedAtMs: info.mtimeMs };
1104
+ function isFastPathCacheState(value) {
1105
+ if (typeof value !== "object" || value === null) return false;
1106
+ const candidate = value;
1107
+ return candidate.version === 1 && typeof candidate.outputCacheChecksum === "string" && (candidate.appFingerprint === void 0 || typeof candidate.appFingerprint === "string") && isOutputInventory(candidate.finalOutputInventory) && (candidate.finalOutputStats === void 0 || isOutputFileStats(candidate.finalOutputStats)) && (candidate.publicDirectory === void 0 || typeof candidate.publicDirectory === "string") && (candidate.publicFingerprint === void 0 || typeof candidate.publicFingerprint === "string") && typeof candidate.configFile === "string" && Array.isArray(candidate.outputPaths) && candidate.outputPaths.every(isSafeLogicalOutputPath) && candidate.outputPaths.every(
1108
+ (path14, index, paths) => index === 0 || paths[index - 1] < path14
1109
+ );
1500
1110
  }
1501
- async function validateOutputCacheEntries(outputCachePath, entries, timingsMs) {
1502
- try {
1503
- const directory = outputCacheEntriesPath(outputCachePath);
1504
- if (!await isSafeOutputCacheEntriesDirectory(directory)) return false;
1505
- const entriesToValidate = Object.entries(entries);
1506
- let nextEntryIndex = 0;
1507
- let valid = true;
1508
- const validateEntry = async () => {
1509
- while (valid) {
1510
- const next = entriesToValidate[nextEntryIndex++];
1511
- if (!next) return;
1512
- const [outputPath, entry] = next;
1513
- if (!isSafeLogicalOutputPath(outputPath) || entry.cachePath !== outputCacheEntryName(outputPath) || !isChecksum(entry.checksum)) {
1514
- valid = false;
1515
- return;
1516
- }
1517
- const path12 = resolveOutputCacheFile(directory, entry.cachePath);
1518
- const info = await lstat2(path12).catch(() => void 0);
1519
- if (!info?.isFile() || info.isSymbolicLink()) {
1520
- valid = false;
1521
- return;
1522
- }
1523
- if (entry.size === info.size && entry.modifiedAtMs === info.mtimeMs) {
1524
- continue;
1525
- }
1526
- if (await measure(
1527
- timingsMs,
1528
- "outputCacheEntryChecksum",
1529
- () => checksumFile(path12)
1530
- ) !== entry.checksum) {
1531
- valid = false;
1532
- return;
1533
- }
1534
- entry.size = info.size;
1535
- entry.modifiedAtMs = info.mtimeMs;
1536
- }
1537
- };
1538
- await Promise.all(
1539
- Array.from(
1540
- {
1541
- length: Math.min(
1542
- outputCacheValidationConcurrency,
1543
- entriesToValidate.length
1544
- )
1545
- },
1546
- validateEntry
1547
- )
1548
- );
1549
- return valid;
1550
- } catch {
1551
- return false;
1552
- }
1111
+ function isChecksum(value) {
1112
+ return typeof value === "string" && /^[a-f0-9]{64}$/u.test(value);
1553
1113
  }
1114
+
1115
+ // src/ssg/output_cache_fastpath.ts
1554
1116
  function fastPathCachePath(outputCachePath) {
1555
1117
  return outputCachePath.replace(/\.json$/, ".fast-path.json");
1556
1118
  }
@@ -1579,7 +1141,7 @@ async function matchingOutputChecksums(outputDirectory, inventory, stats) {
1579
1141
  for (const [outputPath, checksum] of Object.entries(inventory)) {
1580
1142
  const expected = stats[outputPath];
1581
1143
  if (!expected) continue;
1582
- const info = await lstat2(
1144
+ const info = await lstat3(
1583
1145
  resolveWithinDirectory(
1584
1146
  outputDirectory,
1585
1147
  outputPath,
@@ -1595,7 +1157,7 @@ async function matchingOutputChecksums(outputDirectory, inventory, stats) {
1595
1157
  async function collectOutputFileStats(outputDirectory, inventory) {
1596
1158
  const stats = {};
1597
1159
  for (const outputPath of Object.keys(inventory)) {
1598
- const info = await lstat2(
1160
+ const info = await lstat3(
1599
1161
  resolveWithinDirectory(
1600
1162
  outputDirectory,
1601
1163
  outputPath,
@@ -1619,19 +1181,19 @@ function outputStatsEqual(left, right) {
1619
1181
  const paths = Object.keys(left);
1620
1182
  if (paths.length !== Object.keys(right).length) return false;
1621
1183
  return paths.every(
1622
- (path12) => right[path12] !== void 0 && left[path12]?.size === right[path12].size && left[path12]?.modifiedAtMs === right[path12].modifiedAtMs
1184
+ (path14) => right[path14] !== void 0 && left[path14]?.size === right[path14].size && left[path14]?.modifiedAtMs === right[path14].modifiedAtMs
1623
1185
  );
1624
1186
  }
1625
- async function saveFastPathCache(path12, state, timingsMs) {
1626
- const directory = dirname4(path12);
1627
- await mkdir3(directory, { recursive: true });
1187
+ async function saveFastPathCache(path14, state, timingsMs) {
1188
+ const directory = dirname3(path14);
1189
+ await mkdir4(directory, { recursive: true });
1628
1190
  if (!await isSafeOutputCacheDirectory(directory)) {
1629
1191
  throw new Error(`Unsafe SSG fast-path cache directory: ${directory}`);
1630
1192
  }
1631
- if (!await isSafeCacheFileTarget(path12)) {
1632
- throw new Error(`Unsafe SSG fast-path cache file: ${path12}`);
1193
+ if (!await isSafeCacheFileTarget(path14)) {
1194
+ throw new Error(`Unsafe SSG fast-path cache file: ${path14}`);
1633
1195
  }
1634
- const temporaryPath = `${path12}.${randomUUID3()}.tmp`;
1196
+ const temporaryPath = `${path14}.${randomUUID3()}.tmp`;
1635
1197
  try {
1636
1198
  await measure(
1637
1199
  timingsMs,
@@ -1642,177 +1204,1050 @@ async function saveFastPathCache(path12, state, timingsMs) {
1642
1204
  await measure(
1643
1205
  timingsMs,
1644
1206
  "sidecarRename",
1645
- () => replaceFile(temporaryPath, path12)
1207
+ () => replaceFile(temporaryPath, path14)
1646
1208
  );
1647
1209
  } catch (error) {
1648
- await rm3(temporaryPath, { force: true }).catch(() => void 0);
1210
+ await rm4(temporaryPath, { force: true }).catch(() => void 0);
1649
1211
  throw error;
1650
1212
  }
1651
1213
  }
1652
- async function loadFastPathCache(path12) {
1214
+ async function loadFastPathCache(path14) {
1653
1215
  try {
1654
- if (!await isSafeOutputCacheDirectory(dirname4(path12))) return void 0;
1655
- if (!await isRegularFile(path12)) return void 0;
1656
- const candidate = JSON.parse(await readFile4(path12, "utf8"));
1216
+ if (!await isSafeOutputCacheDirectory(dirname3(path14))) return void 0;
1217
+ if (!await isRegularFile(path14)) return void 0;
1218
+ const candidate = JSON.parse(await readFile4(path14, "utf8"));
1657
1219
  return isFastPathCacheState(candidate) ? candidate : void 0;
1658
1220
  } catch {
1659
1221
  return void 0;
1660
1222
  }
1661
1223
  }
1662
- function isFastPathCacheState(value) {
1663
- if (typeof value !== "object" || value === null) return false;
1664
- const candidate = value;
1665
- return candidate.version === 1 && typeof candidate.outputCacheChecksum === "string" && (candidate.appFingerprint === void 0 || typeof candidate.appFingerprint === "string") && isOutputInventory(candidate.finalOutputInventory) && (candidate.finalOutputStats === void 0 || isOutputFileStats(candidate.finalOutputStats)) && (candidate.publicDirectory === void 0 || typeof candidate.publicDirectory === "string") && (candidate.publicFingerprint === void 0 || typeof candidate.publicFingerprint === "string") && typeof candidate.configFile === "string" && Array.isArray(candidate.outputPaths) && candidate.outputPaths.every(isSafeLogicalOutputPath) && candidate.outputPaths.every(
1666
- (path12, index, paths) => index === 0 || paths[index - 1] < path12
1667
- );
1224
+
1225
+ // src/ssg/output_cache_decision.ts
1226
+ function decideOutputCacheRejection(decision) {
1227
+ if (!decision.changeSetPresent) return "change-set-unavailable";
1228
+ if (decision.changeSetRequiresFullRegeneration)
1229
+ return "full-regeneration-required";
1230
+ if (!decision.outputCacheLoaded) return "output-cache-missing-or-invalid";
1231
+ if (!decision.appFingerprintMatch) return "app-fingerprint-changed";
1232
+ if (!decision.clientManifestFingerprintMatch)
1233
+ return "client-manifest-fingerprint-changed";
1234
+ if (decision.uncoveredUnchangedCount > 0)
1235
+ return "unchanged-output-not-cached";
1236
+ return void 0;
1668
1237
  }
1669
- async function checksumFile(path12) {
1670
- const hash = createHash3("sha256");
1671
- try {
1672
- for await (const chunk of createReadStream(path12)) hash.update(chunk);
1673
- return hash.digest("hex");
1674
- } catch {
1675
- return void 0;
1676
- }
1238
+ function createNoChangeFastPathOutputMetrics() {
1239
+ return {
1240
+ outputInventoryValidationDurationMs: 0,
1241
+ outputHashValidationDurationMs: 0,
1242
+ outputFilesHashed: 0,
1243
+ outputBytesHashed: 0
1244
+ };
1677
1245
  }
1678
- async function replaceFile(temporaryPath, targetPath) {
1679
- try {
1680
- await rename3(temporaryPath, targetPath);
1681
- } catch (error) {
1682
- if (!isReplacementFailure(error)) throw error;
1683
- await rm3(targetPath, { force: true });
1684
- await rename3(temporaryPath, targetPath);
1246
+ async function verifyNoChangeFastPath(input) {
1247
+ const outputCachePath = join4(
1248
+ input.root,
1249
+ ".riebeckite",
1250
+ "ssg-output-cache.json"
1251
+ );
1252
+ const cache = await loadFastPathCache(fastPathCachePath(outputCachePath));
1253
+ if (!cache)
1254
+ return { used: false, blockReason: "output-cache-missing-or-invalid" };
1255
+ if (cache.outputCacheChecksum !== await checksumFile(outputCachePath)) {
1256
+ return { used: false, blockReason: "output-cache-missing-or-invalid" };
1685
1257
  }
1686
- }
1687
- function isReplacementFailure(error) {
1688
- if (typeof error !== "object" || error === null || !("code" in error)) {
1689
- return false;
1258
+ if (cache.appFingerprint !== await computeAppFingerprint(input.root, cache.configFile)) {
1259
+ return { used: false, blockReason: "app-fingerprint-changed" };
1690
1260
  }
1691
- const code = String(error.code);
1692
- return code === "EPERM" || code === "EEXIST" || code === "EACCES";
1693
- }
1694
- function resolveOutputCacheEntryPath(outputCachePath, entry) {
1695
- return resolveOutputCacheFile(
1696
- outputCacheEntriesPath(outputCachePath),
1697
- entry.cachePath
1261
+ if (cache.publicDirectory && cache.publicFingerprint !== await fingerprintDirectory(cache.publicDirectory)) {
1262
+ return { used: false, blockReason: "static-assets-changed" };
1263
+ }
1264
+ if (input.expectedOutputPaths.some(
1265
+ (output) => !cache.outputPaths.includes(output) || !cache.finalOutputInventory[output]
1266
+ )) {
1267
+ return { used: false, blockReason: "output-cache-incomplete" };
1268
+ }
1269
+ const knownChecksums = await matchingOutputChecksums(
1270
+ input.outputDirectory,
1271
+ cache.finalOutputInventory,
1272
+ cache.finalOutputStats
1698
1273
  );
1699
- }
1700
- function resolveOutputCacheFile(directory, relativePath) {
1701
- return resolveWithinDirectory(
1702
- directory,
1703
- relativePath,
1704
- "SSG output cache path"
1274
+ const inventoryStartedAt = performance3.now();
1275
+ const currentInventory = await fingerprintOutputDirectory(
1276
+ input.outputDirectory,
1277
+ "",
1278
+ input.metrics,
1279
+ knownChecksums
1705
1280
  );
1706
- }
1707
- function isSafeLogicalOutputPath(path12) {
1708
- if (typeof path12 !== "string" || !path12 || path12.includes("\\") || path12.includes("\0") || isAbsolutePath(path12)) {
1709
- return false;
1281
+ if (input.metrics)
1282
+ input.metrics.outputInventoryValidationDurationMs += performance3.now() - inventoryStartedAt;
1283
+ if (!inventoriesEqual(cache.finalOutputInventory, currentInventory)) {
1284
+ return { used: false, blockReason: "output-inventory-mismatch" };
1710
1285
  }
1711
- try {
1712
- resolveOutputCacheFile("/riebeckite-output-root", path12);
1713
- return true;
1714
- } catch {
1715
- return false;
1286
+ const currentStats = await collectOutputFileStats(
1287
+ input.outputDirectory,
1288
+ cache.finalOutputInventory
1289
+ );
1290
+ if (!outputStatsEqual(cache.finalOutputStats, currentStats)) {
1291
+ await saveFastPathCache(fastPathCachePath(outputCachePath), {
1292
+ ...cache,
1293
+ finalOutputStats: currentStats
1294
+ }).catch(() => void 0);
1716
1295
  }
1296
+ return { used: true };
1717
1297
  }
1718
- function assertSafeLogicalOutputPath(path12) {
1719
- if (!isSafeLogicalOutputPath(path12)) {
1720
- throw new Error(`Invalid SSG output path: ${path12}`);
1298
+
1299
+ // src/ssg/output_cache_load.ts
1300
+ import { readFile as readFile5 } from "node:fs/promises";
1301
+ import { dirname as dirname4 } from "node:path";
1302
+
1303
+ // src/ssg/output_cache_entries.ts
1304
+ import { lstat as lstat4 } from "node:fs/promises";
1305
+ import { join as join5 } from "node:path";
1306
+
1307
+ // src/ssg/output_cache_types.ts
1308
+ var outputCacheValidationConcurrency = 12;
1309
+
1310
+ // src/ssg/output_cache_entries.ts
1311
+ async function saveOutputCacheEntries(directory, outputDirectory, outputs, finalOutputInventory, timingsMs) {
1312
+ await ensureOutputCacheEntriesDirectory(directory);
1313
+ const entries = {};
1314
+ for (const outputPath of Object.keys(outputs).sort()) {
1315
+ assertSafeLogicalOutputPath(outputPath);
1316
+ const existing = outputs[outputPath];
1317
+ if (existing.cachePath && existing.checksum) {
1318
+ if (existing.cachePath !== outputCacheEntryName(outputPath) || !isChecksum(existing.checksum)) {
1319
+ throw new Error(`Invalid SSG output cache entry: ${outputPath}`);
1320
+ }
1321
+ const cached = await existingOutputCacheEntry(
1322
+ existing,
1323
+ join5(directory, existing.cachePath)
1324
+ );
1325
+ if (cached) {
1326
+ entries[outputPath] = cached;
1327
+ continue;
1328
+ }
1329
+ }
1330
+ const source = resolveOutputCacheFile(outputDirectory, outputPath);
1331
+ const cachePath = outputCacheEntryName(outputPath);
1332
+ const destination = join5(directory, cachePath);
1333
+ await replaceOutputCacheEntry(source, destination, timingsMs);
1334
+ const checksum = finalOutputInventory?.[outputPath];
1335
+ if (!checksum) {
1336
+ const cachedChecksum = await checksumFile(destination);
1337
+ if (!cachedChecksum) {
1338
+ throw new Error(`Could not checksum cached output: ${outputPath}`);
1339
+ }
1340
+ entries[outputPath] = await withOutputCacheEntryStat(
1341
+ { cachePath, checksum: cachedChecksum },
1342
+ destination
1343
+ );
1344
+ continue;
1345
+ }
1346
+ entries[outputPath] = await withOutputCacheEntryStat(
1347
+ { cachePath, checksum },
1348
+ destination
1349
+ );
1721
1350
  }
1351
+ return entries;
1722
1352
  }
1723
- function outputCacheEntryName(outputPath) {
1724
- return createHash3("sha256").update(outputPath).digest("hex");
1353
+ async function withOutputCacheEntryStat(entry, path14) {
1354
+ const info = await lstat4(path14).catch(() => void 0);
1355
+ if (!info?.isFile() || info.isSymbolicLink()) return entry;
1356
+ return { ...entry, size: info.size, modifiedAtMs: info.mtimeMs };
1725
1357
  }
1726
- function isChecksum(value) {
1727
- return typeof value === "string" && /^[a-f0-9]{64}$/u.test(value);
1728
- }
1729
- async function ensureOutputCacheEntriesDirectory(directory) {
1730
- await mkdir3(directory, { recursive: true });
1731
- if (!await isSafeOutputCacheEntriesDirectory(directory)) {
1732
- throw new Error(`Unsafe SSG output cache entries directory: ${directory}`);
1733
- }
1358
+ async function existingOutputCacheEntry(entry, path14) {
1359
+ const info = await lstat4(path14).catch(() => void 0);
1360
+ if (!info?.isFile() || info.isSymbolicLink()) return void 0;
1361
+ return { ...entry, size: info.size, modifiedAtMs: info.mtimeMs };
1734
1362
  }
1735
- async function isSafeOutputCacheDirectory(directory) {
1363
+ async function validateOutputCacheEntries(outputCachePath, entries, timingsMs) {
1736
1364
  try {
1737
- const info = await lstat2(directory);
1738
- return info.isDirectory() && !info.isSymbolicLink();
1365
+ const directory = outputCacheEntriesPath(outputCachePath);
1366
+ if (!await isSafeOutputCacheEntriesDirectory(directory)) return false;
1367
+ const entriesToValidate = Object.entries(entries);
1368
+ let nextEntryIndex = 0;
1369
+ let valid = true;
1370
+ const validateEntry = async () => {
1371
+ while (valid) {
1372
+ const next = entriesToValidate[nextEntryIndex++];
1373
+ if (!next) return;
1374
+ const [outputPath, entry] = next;
1375
+ if (!isSafeLogicalOutputPath(outputPath) || entry.cachePath !== outputCacheEntryName(outputPath) || !isChecksum(entry.checksum)) {
1376
+ valid = false;
1377
+ return;
1378
+ }
1379
+ const path14 = resolveOutputCacheFile(directory, entry.cachePath);
1380
+ const info = await lstat4(path14).catch(() => void 0);
1381
+ if (!info?.isFile() || info.isSymbolicLink()) {
1382
+ valid = false;
1383
+ return;
1384
+ }
1385
+ if (entry.size === info.size && entry.modifiedAtMs === info.mtimeMs) {
1386
+ continue;
1387
+ }
1388
+ if (await measure(
1389
+ timingsMs,
1390
+ "outputCacheEntryChecksum",
1391
+ () => checksumFile(path14)
1392
+ ) !== entry.checksum) {
1393
+ valid = false;
1394
+ return;
1395
+ }
1396
+ entry.size = info.size;
1397
+ entry.modifiedAtMs = info.mtimeMs;
1398
+ }
1399
+ };
1400
+ await Promise.all(
1401
+ Array.from(
1402
+ {
1403
+ length: Math.min(
1404
+ outputCacheValidationConcurrency,
1405
+ entriesToValidate.length
1406
+ )
1407
+ },
1408
+ validateEntry
1409
+ )
1410
+ );
1411
+ return valid;
1739
1412
  } catch {
1740
1413
  return false;
1741
1414
  }
1742
1415
  }
1743
- async function isSafeCacheFileTarget(path12) {
1416
+
1417
+ // src/ssg/output_cache_load.ts
1418
+ async function loadOutputCacheMetadata(path14, timingsMs, log = () => {
1419
+ }) {
1420
+ if (!await isSafeOutputCacheDirectory(dirname4(path14))) {
1421
+ log("SSG output cache directory is unsafe and will be ignored.");
1422
+ return void 0;
1423
+ }
1424
+ if (!await isRegularFile(path14)) {
1425
+ return void 0;
1426
+ }
1427
+ let raw;
1744
1428
  try {
1745
- return !(await lstat2(path12)).isSymbolicLink();
1429
+ raw = await measure(
1430
+ timingsMs,
1431
+ "outputCacheRead",
1432
+ () => readFile5(path14, "utf8")
1433
+ );
1746
1434
  } catch (error) {
1747
- return isNotFoundError(error);
1435
+ if (isNotFoundError(error)) return void 0;
1436
+ log(
1437
+ `SSG output cache could not be read; the build regenerates every output. ${error instanceof Error ? error.message : String(error)}`
1438
+ );
1439
+ return void 0;
1748
1440
  }
1749
- }
1750
- async function isSafeOutputCacheEntriesDirectory(directory) {
1751
- return isSafeOutputCacheDirectory(directory);
1752
- }
1753
- async function isRegularFile(path12) {
1441
+ let parsed;
1754
1442
  try {
1755
- const info = await lstat2(path12);
1756
- return info.isFile() && !info.isSymbolicLink();
1757
- } catch {
1758
- return false;
1443
+ parsed = measureSync(timingsMs, "outputCacheParse", () => JSON.parse(raw));
1444
+ } catch (error) {
1445
+ log(
1446
+ `SSG output cache is corrupted and will be rebuilt. ${error instanceof Error ? error.message : String(error)}`
1447
+ );
1448
+ return void 0;
1759
1449
  }
1450
+ if (!isOutputCacheState(parsed)) {
1451
+ log("SSG output cache uses an unsupported format and will be rebuilt.");
1452
+ return void 0;
1453
+ }
1454
+ return timingsMs ? { ...parsed, fileSizeBytes: Buffer.byteLength(raw) } : parsed;
1760
1455
  }
1761
- async function replaceOutputCacheEntry(source, destination, timingsMs) {
1762
- if ((await lstat2(destination).catch(() => void 0))?.isSymbolicLink()) {
1763
- throw new Error(`Unsafe SSG output cache entry: ${destination}`);
1456
+ async function validateOutputCache(cache, path14, timingsMs, log = () => {
1457
+ }) {
1458
+ const entriesAreValid = await measure(
1459
+ timingsMs,
1460
+ "outputCacheEntriesValidate",
1461
+ () => validateOutputCacheEntries(path14, cache.outputs, timingsMs)
1462
+ );
1463
+ if (entriesAreValid) return true;
1464
+ log("SSG output cache entries are corrupted and will be rebuilt.");
1465
+ return false;
1466
+ }
1467
+
1468
+ // src/ssg/output_cache_save.ts
1469
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
1470
+ import { mkdir as mkdir5, rm as rm5, writeFile as writeFile4 } from "node:fs/promises";
1471
+ import { dirname as dirname5 } from "node:path";
1472
+ async function saveOutputCache(path14, state, outputDirectory, timingsMs) {
1473
+ const directory = dirname5(path14);
1474
+ await mkdir5(directory, { recursive: true });
1475
+ if (!await isSafeOutputCacheDirectory(directory)) {
1476
+ throw new Error(`Unsafe SSG output cache directory: ${directory}`);
1764
1477
  }
1765
- const temporaryPath = `${destination}.${randomUUID3()}.tmp`;
1478
+ if (!await isSafeCacheFileTarget(path14)) {
1479
+ throw new Error(`Unsafe SSG output cache file: ${path14}`);
1480
+ }
1481
+ const entriesPath = outputCacheEntriesPath(path14);
1482
+ const temporaryPath = `${path14}.${randomUUID4()}.tmp`;
1766
1483
  try {
1767
- await measure(
1484
+ const outputs = await measure(
1768
1485
  timingsMs,
1769
- "outputCacheEntryWrite",
1770
- () => writeFile3(temporaryPath, new Uint8Array())
1486
+ "outputCacheEntriesWrite",
1487
+ () => saveOutputCacheEntries(
1488
+ entriesPath,
1489
+ outputDirectory,
1490
+ state.outputs,
1491
+ state.finalOutputInventory,
1492
+ timingsMs
1493
+ )
1494
+ );
1495
+ const serialized = measureSync(
1496
+ timingsMs,
1497
+ "outputCacheSerialize",
1498
+ () => `${JSON.stringify({ ...state, outputs })}
1499
+ `
1771
1500
  );
1772
1501
  await measure(
1773
1502
  timingsMs,
1774
- "outputCacheEntryCopy",
1775
- () => copyFile2(source, temporaryPath)
1503
+ "outputCacheWrite",
1504
+ () => writeFile4(temporaryPath, serialized, "utf8")
1776
1505
  );
1777
1506
  await measure(
1778
1507
  timingsMs,
1779
- "outputCacheEntryRename",
1780
- () => replaceFile(temporaryPath, destination)
1508
+ "outputCacheRename",
1509
+ () => replaceFile(temporaryPath, path14)
1510
+ );
1511
+ const checksum = createHash5("sha256").update(serialized).digest("hex");
1512
+ if (state.finalOutputInventory && state.configFile) {
1513
+ await saveFastPathCache(
1514
+ fastPathCachePath(path14),
1515
+ await createFastPathCacheState(state, checksum, outputDirectory),
1516
+ timingsMs
1517
+ );
1518
+ }
1519
+ await collectUnreferencedOutputCacheEntries(
1520
+ outputCacheEntriesPath(path14),
1521
+ outputs,
1522
+ timingsMs
1523
+ );
1524
+ return checksum;
1525
+ } catch (error) {
1526
+ await rm5(temporaryPath, { force: true }).catch(() => void 0);
1527
+ throw error;
1528
+ }
1529
+ }
1530
+
1531
+ // src/ssg_plugin_helpers.ts
1532
+ import { lstat as lstat5, mkdir as mkdir6, writeFile as writeFile5 } from "node:fs/promises";
1533
+ import { dirname as dirname6, join as join6 } from "node:path";
1534
+ import {
1535
+ BUILD_OUTPUT_MARKER_FILE,
1536
+ createBuildOutputMarker,
1537
+ isDeferredGeneratedOutput,
1538
+ serializeBuildOutputMarker
1539
+ } from "@riebeckite/core";
1540
+ async function isDirectory(path14) {
1541
+ try {
1542
+ return (await lstat5(path14)).isDirectory();
1543
+ } catch (error) {
1544
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
1545
+ return false;
1546
+ }
1547
+ throw error;
1548
+ }
1549
+ }
1550
+ function findBuildOutputSiteCollisions(buildOutputPaths, siteOwnedOutputPaths) {
1551
+ const collisions = /* @__PURE__ */ new Set();
1552
+ for (const path14 of buildOutputPaths) {
1553
+ if (siteOwnedOutputPaths.has(path14)) collisions.add(path14);
1554
+ }
1555
+ return [...collisions].sort();
1556
+ }
1557
+ function assertRequiredOutputsWereGenerated(comparison) {
1558
+ if (comparison.missingInDist.length === 0) return;
1559
+ throw new Error(
1560
+ `SSG did not generate required output: ${comparison.missingInDist.join(", ")}`
1561
+ );
1562
+ }
1563
+ function outputCacheEntryFor(previous, path14, checksum) {
1564
+ const cached = previous?.outputs[path14];
1565
+ return cached?.checksum === checksum ? cached : { cachePath: "", checksum: "" };
1566
+ }
1567
+ async function emitGeneratedOutputs(module, emit, affectedPaths, shadowedPaths, onShadowed) {
1568
+ const content = module.content;
1569
+ if (!content) return 0;
1570
+ if (affectedPaths?.size === 0) return 0;
1571
+ const manifest = await content.getManifest();
1572
+ let count = 0;
1573
+ for (const output of manifest.generatedOutputs ?? []) {
1574
+ if (affectedPaths && !affectedPaths.has(output.path)) continue;
1575
+ if (shadowedPaths?.has(output.path)) {
1576
+ onShadowed?.(output.path);
1577
+ continue;
1578
+ }
1579
+ const source = isDeferredGeneratedOutput(output) ? await output.generate() : output.content;
1580
+ await emit({
1581
+ type: "asset",
1582
+ fileName: output.path,
1583
+ source
1584
+ });
1585
+ count += 1;
1586
+ }
1587
+ return count;
1588
+ }
1589
+ function removeVirtualEntryChunk(bundle, virtualEntryId) {
1590
+ for (const chunk of Object.values(bundle)) {
1591
+ if (chunk.type === "chunk" && chunk.moduleIds?.includes(virtualEntryId)) {
1592
+ delete bundle[chunk.fileName];
1593
+ }
1594
+ }
1595
+ }
1596
+ async function writePublicationMarker(input) {
1597
+ const path14 = join6(input.root, ".riebeckite", BUILD_OUTPUT_MARKER_FILE);
1598
+ try {
1599
+ await mkdir6(dirname6(path14), { recursive: true });
1600
+ await writeFile5(
1601
+ path14,
1602
+ serializeBuildOutputMarker(
1603
+ createBuildOutputMarker({
1604
+ outputDirectory: input.outputDirectory,
1605
+ ...input.publicationFingerprint === void 0 ? {} : { publicationFingerprint: input.publicationFingerprint },
1606
+ ...input.artifactFingerprint === void 0 ? {} : { artifactFingerprint: input.artifactFingerprint },
1607
+ completedAt: /* @__PURE__ */ new Date()
1608
+ })
1609
+ ),
1610
+ "utf8"
1611
+ );
1612
+ } catch (error) {
1613
+ input.warn(
1614
+ `Could not write the publication marker; publish will rebuild before deploying. ${error instanceof Error ? error.message : String(error)}`
1615
+ );
1616
+ }
1617
+ }
1618
+
1619
+ // src/ssg_plugin_close.ts
1620
+ async function closeSsgBundle(plugin, state) {
1621
+ if (!state.resolvedConfig) return;
1622
+ if (state.resolvedConfig.mode === "client") return;
1623
+ const outputDirectory = state.publicationOutputDirectory;
1624
+ if (!outputDirectory) {
1625
+ throw new Error(
1626
+ "Riebeckite SSG could not resolve the publication output directory."
1627
+ );
1628
+ }
1629
+ const outDir = resolve3(
1630
+ state.resolvedConfig.root,
1631
+ state.resolvedConfig.build.outDir
1632
+ );
1633
+ const oversizedAssets = await findOversizedAssets(outDir);
1634
+ for (const asset of oversizedAssets) {
1635
+ plugin.warn(
1636
+ `Generated asset ${asset.path} is ${formatBytes(asset.size)}, exceeding Cloudflare Workers' ${formatBytes(CLOUDFLARE_WORKER_ASSET_LIMIT)} asset limit.`
1637
+ );
1638
+ }
1639
+ const outputCache = state.pendingOutputCache;
1640
+ if (!outputCache) return;
1641
+ let published = false;
1642
+ try {
1643
+ if (!state.artifactWriter) {
1644
+ throw new Error("Riebeckite SSG artifact writer was not initialized.");
1645
+ }
1646
+ outputCache.state.finalOutputInventory = await measure(
1647
+ outputCache.timingsMs,
1648
+ "outputInventory",
1649
+ () => fingerprintOutputDirectory(
1650
+ outputCache.outDir,
1651
+ "",
1652
+ void 0,
1653
+ state.outputChecksums
1654
+ )
1655
+ );
1656
+ const finalOutputInventory = outputCache.state.finalOutputInventory;
1657
+ const artifactFingerprint = fingerprintOutputInventory(finalOutputInventory);
1658
+ if (outputCache.provenance && outputCache.content) {
1659
+ await outputCache.content.attachFinalOutputArtifacts(
1660
+ outputCache.provenance.buildId,
1661
+ finalOutputInventory,
1662
+ outputCache.reusablePaths
1663
+ );
1664
+ }
1665
+ const outputPlanRssBefore = process.memoryUsage().rss;
1666
+ const outputPlan = measureSync(
1667
+ outputCache.timingsMs,
1668
+ "outputPlan",
1669
+ () => buildOutputPlan({
1670
+ ...outputCache.outputPlanInput
1671
+ })
1672
+ );
1673
+ const outputPlanComparison = measureSync(
1674
+ outputCache.timingsMs,
1675
+ "outputPlanComparison",
1676
+ () => compareOutputPlan(outputPlan, Object.keys(finalOutputInventory))
1677
+ );
1678
+ outputCache.metrics.plannedOutputCount = outputPlan.entries.length;
1679
+ outputCache.metrics.actualOutputCount = Object.keys(finalOutputInventory).length;
1680
+ outputCache.metrics.matchedOutputCount = outputPlanComparison.matched.length;
1681
+ outputCache.metrics.missingInPlanCount = outputPlanComparison.missingInPlan.length;
1682
+ outputCache.metrics.missingInDistCount = outputPlanComparison.missingInDist.length;
1683
+ outputCache.metrics.unknownOutputCount = outputPlanComparison.unknown.length;
1684
+ outputCache.metrics.ownerConflictCount = outputPlanComparison.ownerConflicts.length;
1685
+ outputCache.metrics.publicationViolationCount = outputPlanComparison.publicationViolations.length;
1686
+ outputCache.metrics.plannedGenerateOutputCount = outputPlan.entries.filter(
1687
+ (entry) => entry.action === "generate"
1688
+ ).length;
1689
+ outputCache.metrics.plannedReuseOutputCount = outputPlan.entries.filter(
1690
+ (entry) => entry.action === "reuse"
1691
+ ).length;
1692
+ outputCache.metrics.plannedRemoveOutputCount = outputPlan.entries.filter(
1693
+ (entry) => entry.action === "remove"
1694
+ ).length;
1695
+ outputCache.metrics.plannedUnknownOutputCount = outputPlan.entries.filter(
1696
+ (entry) => entry.action === "unknown"
1697
+ ).length;
1698
+ outputCache.metrics.outputPlanMemoryDeltaBytes = Math.max(
1699
+ 0,
1700
+ process.memoryUsage().rss - outputPlanRssBefore
1701
+ );
1702
+ assertRequiredOutputsWereGenerated(outputPlanComparison);
1703
+ const publicDir = outputCache.publicDir;
1704
+ outputCache.state.publicDirectory = publicDir ? resolve3(publicDir) : void 0;
1705
+ outputCache.state.publicFingerprint = publicDir ? await measure(
1706
+ outputCache.timingsMs,
1707
+ "publicFingerprint",
1708
+ () => fingerprintDirectory(resolve3(publicDir))
1709
+ ) : void 0;
1710
+ try {
1711
+ await saveOutputCache(
1712
+ outputCache.path,
1713
+ outputCache.state,
1714
+ outputCache.outDir,
1715
+ outputCache.timingsMs
1716
+ );
1717
+ } catch (error) {
1718
+ plugin.warn(
1719
+ `SSG output cache could not be saved; the next build regenerates every output. ${error instanceof Error ? error.message : String(error)}`
1720
+ );
1721
+ }
1722
+ await state.artifactWriter.publish();
1723
+ published = true;
1724
+ await writePublicationMarker({
1725
+ root: state.resolvedConfig.root,
1726
+ outputDirectory,
1727
+ publicationFingerprint: outputCache.publicationFingerprint,
1728
+ artifactFingerprint,
1729
+ warn: (message) => plugin.warn(message)
1730
+ });
1731
+ } finally {
1732
+ if (!published) await state.artifactWriter?.discard();
1733
+ await writeSsgOutputMetrics(outputCache.metrics);
1734
+ state.pendingOutputCache = void 0;
1735
+ state.artifactWriter = void 0;
1736
+ }
1737
+ }
1738
+
1739
+ // src/ssg_plugin_generate_finalize.ts
1740
+ import {
1741
+ publicationFingerprint as fingerprintPublication,
1742
+ publicationEntriesFromManifest,
1743
+ publicationOutputsFromManifest,
1744
+ publicationRedirectsFromManifest
1745
+ } from "@riebeckite/core";
1746
+
1747
+ // src/ssg/diagnostics.ts
1748
+ function formatSsrNoExternal() {
1749
+ return "/^honox(?:\\/.*)?$/";
1750
+ }
1751
+ function logSsgDiagnostics(logger, message) {
1752
+ if (process.env.RIEBECKITE_SSG_DIAGNOSTICS !== "1") return;
1753
+ logger.info(`[riebeckite-ssg] ${message}`);
1754
+ }
1755
+ function logGeneratedHtmlAssetDiagnostics(logger, pages) {
1756
+ if (process.env.RIEBECKITE_SSG_DIAGNOSTICS !== "1") return;
1757
+ const renderedPages = pages.filter(
1758
+ (page) => !/<meta\b[^>]*\bhttp-equiv=["']refresh["'][^>]*\bcontent=["'][^"']*\burl=/iu.test(
1759
+ page.html
1760
+ )
1761
+ );
1762
+ const cssPages = renderedPages.filter(
1763
+ (page) => /<link\b[^>]*\brel=["'][^"']*\bstylesheet\b[^"']*["']/iu.test(page.html)
1764
+ );
1765
+ const scriptPages = renderedPages.filter(
1766
+ (page) => /<script\b[^>]*\bsrc=["'][^"']+["']/iu.test(page.html)
1767
+ );
1768
+ const missingCss = renderedPages.filter((page) => !cssPages.includes(page)).map((page) => page.path);
1769
+ const missingScript = renderedPages.filter((page) => !scriptPages.includes(page)).map((page) => page.path);
1770
+ logger.info(
1771
+ `[riebeckite-ssg] rendered HTML assets: ${pages.length} documents (${renderedPages.length} pages, ${pages.length - renderedPages.length} redirects) · CSS ${cssPages.length} · JavaScript ${scriptPages.length} · missing CSS ${missingCss.length} · missing JavaScript ${missingScript.length}`
1772
+ );
1773
+ if (missingCss.length > 0 || missingScript.length > 0) {
1774
+ logger.info(
1775
+ `[riebeckite-ssg] missing asset references: CSS ${missingCss.join(", ") || "none"} · JavaScript ${missingScript.join(", ") || "none"}`
1776
+ );
1777
+ }
1778
+ }
1779
+ function inspectGeneratedHtmlPages(module, pages, log) {
1780
+ const diagnostics = [];
1781
+ const plugins = module.config?.plugins ?? [];
1782
+ for (const plugin of plugins) {
1783
+ const inspector = plugin.inspectGeneratedHtml;
1784
+ if (typeof inspector !== "function") continue;
1785
+ for (const page of pages) {
1786
+ for (const diagnostic of inspector(page) ?? []) {
1787
+ const label = `[${plugin.name ?? "plugin"}] ${page.path}: ${diagnostic.message}`;
1788
+ if (diagnostic.severity === "info") log.info(label);
1789
+ else log.warn(label);
1790
+ diagnostics.push({
1791
+ code: diagnostic.code ?? "generated-html",
1792
+ severity: diagnostic.severity,
1793
+ message: diagnostic.message,
1794
+ pluginName: plugin.name,
1795
+ filePath: diagnostic.filePath ?? page.path
1796
+ });
1797
+ }
1798
+ }
1799
+ }
1800
+ return diagnostics;
1801
+ }
1802
+
1803
+ // src/ssg_plugin_generate_finalize.ts
1804
+ async function finalizeSsgGeneration(plugin, ctx, state) {
1805
+ ctx.metrics.shadowedOutputCount = ctx.shadowedOutputs.size;
1806
+ if (ctx.shadowedOutputs.size > 0) {
1807
+ plugin.warn(
1808
+ `Site public assets take precedence over generated outputs: ${[
1809
+ ...ctx.shadowedOutputs
1810
+ ].sort().join(", ")}`
1811
+ );
1812
+ }
1813
+ ctx.metrics.cacheEntriesSerialized = Object.keys(
1814
+ ctx.nextOutputCache.outputs
1815
+ ).length;
1816
+ const manifest = await ctx.module.content?.getManifest();
1817
+ const publicationFingerprint = manifest ? fingerprintPublication(
1818
+ publicationEntriesFromManifest(manifest),
1819
+ publicationRedirectsFromManifest(manifest),
1820
+ publicationOutputsFromManifest(manifest)
1821
+ ) : void 0;
1822
+ state.pendingOutputCache = {
1823
+ path: ctx.outputCachePath,
1824
+ state: ctx.nextOutputCache,
1825
+ metrics: ctx.metrics,
1826
+ timingsMs: ctx.timingsMs,
1827
+ outDir: ctx.outDir,
1828
+ publicDir: ctx.config.publicDir,
1829
+ configFile: ctx.config.configFile,
1830
+ ...publicationFingerprint === void 0 ? {} : { publicationFingerprint },
1831
+ outputPlanInput: {
1832
+ inventory: ctx.inventory,
1833
+ affectedPaths: new Set(
1834
+ (ctx.outputChangeSet?.affected ?? []).map((output) => output.path)
1835
+ ),
1836
+ removed: ctx.outputChangeSet?.removed ?? [],
1837
+ cacheAvailable: ctx.canUseIncremental,
1838
+ honoStaticRoutePaths: ctx.honoStaticRoutePaths,
1839
+ viteClientAssetPaths: new Set(ctx.viteClientAssetPaths),
1840
+ sitePublicAssetPaths: ctx.siteOwnedOutputPaths
1841
+ },
1842
+ provenance: ctx.module.content?.getProvenance(),
1843
+ content: ctx.module.content,
1844
+ reusablePaths: new Set(
1845
+ [...ctx.reusablePaths].filter(
1846
+ (path14) => !ctx.siteOwnedOutputPaths.has(path14)
1847
+ )
1848
+ )
1849
+ };
1850
+ plugin.info(
1851
+ `SSG outputs: ${ctx.metrics.renderedOutputCount} rendered · ${ctx.metrics.reusedOutputCount} reused · ${ctx.metrics.deletedOutputCount} removed`
1852
+ );
1853
+ const generatedHtmlDiagnostics = inspectGeneratedHtmlPages(
1854
+ ctx.module,
1855
+ ctx.generatedHtml,
1856
+ {
1857
+ warn: (message) => plugin.warn(message),
1858
+ info: (message) => plugin.info(message)
1859
+ }
1860
+ );
1861
+ ctx.module.content?.recordFinalHtmlDiagnostics?.(generatedHtmlDiagnostics);
1862
+ logGeneratedHtmlAssetDiagnostics(plugin, ctx.generatedHtml);
1863
+ }
1864
+
1865
+ // src/ssg_plugin_generate_prepare.ts
1866
+ import { randomUUID as randomUUID5 } from "node:crypto";
1867
+ import { join as join7, resolve as resolve4 } from "node:path";
1868
+
1869
+ // src/content_assets.ts
1870
+ import fs5 from "node:fs/promises";
1871
+ import path7 from "node:path";
1872
+ import { isImagePath, normalizeContentPath } from "@riebeckite/core";
1873
+ import { isIgnoredContentPath, isPathInsideDirectory } from "@riebeckite/node";
1874
+
1875
+ // src/content_module.ts
1876
+ import path6 from "node:path";
1877
+ function contentModuleEntry(appRoot) {
1878
+ return path6.join(appRoot, "app", "server.ts");
1879
+ }
1880
+ function isContentModuleLoaded(server, appRoot) {
1881
+ const entry = contentModuleEntry(appRoot);
1882
+ const moduleGraph = server.environments?.ssr?.moduleGraph;
1883
+ return Boolean(
1884
+ moduleGraph?.getModuleById(entry) ?? [...moduleGraph?.idToModuleMap?.values() ?? []].find(
1885
+ (module) => module.file && path6.resolve(module.file) === path6.resolve(entry)
1886
+ )
1887
+ );
1888
+ }
1889
+ async function loadContentModule(server, appRoot) {
1890
+ return await server.ssrLoadModule(
1891
+ contentModuleEntry(appRoot)
1892
+ );
1893
+ }
1894
+
1895
+ // src/content_assets.ts
1896
+ var IMAGE_CONTENT_TYPES = {
1897
+ png: "image/png",
1898
+ jpg: "image/jpeg",
1899
+ jpeg: "image/jpeg",
1900
+ gif: "image/gif",
1901
+ svg: "image/svg+xml",
1902
+ webp: "image/webp",
1903
+ bmp: "image/bmp"
1904
+ };
1905
+ function riebeckiteContentAssets(options) {
1906
+ return {
1907
+ name: "riebeckite-content-assets",
1908
+ apply: "serve",
1909
+ enforce: "pre",
1910
+ configureServer(server) {
1911
+ const contentRoot = options.contentRoot();
1912
+ const base = server.config.base;
1913
+ const publicDir = server.config.publicDir;
1914
+ let cachedManifest;
1915
+ let cachedPaths = /* @__PURE__ */ new Set();
1916
+ const resolvePublicImagePaths = async () => {
1917
+ const module = await loadContentModule(server, options.appRoot());
1918
+ const manifest = await module.content?.getManifest?.();
1919
+ if (!manifest) return /* @__PURE__ */ new Set();
1920
+ if (manifest !== cachedManifest) {
1921
+ cachedManifest = manifest;
1922
+ cachedPaths = collectPublicImagePaths(manifest);
1923
+ }
1924
+ return cachedPaths;
1925
+ };
1926
+ const middleware = async (request, response, next) => {
1927
+ try {
1928
+ if (request.method !== "GET" && request.method !== "HEAD") {
1929
+ next();
1930
+ return;
1931
+ }
1932
+ const logicalPath = toContentPath(request.url, base);
1933
+ if (!logicalPath || !isImagePath(logicalPath)) {
1934
+ next();
1935
+ return;
1936
+ }
1937
+ if (isIgnoredContentPath(logicalPath)) {
1938
+ next();
1939
+ return;
1940
+ }
1941
+ const contentType = imageContentType(logicalPath);
1942
+ if (!contentType) {
1943
+ next();
1944
+ return;
1945
+ }
1946
+ const available = await resolvePublicImagePaths();
1947
+ if (!available.has(logicalPath)) {
1948
+ next();
1949
+ return;
1950
+ }
1951
+ const file = path7.join(contentRoot, logicalPath);
1952
+ if (!isPathInsideDirectory(contentRoot, file)) {
1953
+ next();
1954
+ return;
1955
+ }
1956
+ if (await hasSiteOwnedFile(publicDir, logicalPath)) {
1957
+ next();
1958
+ return;
1959
+ }
1960
+ const content = await fs5.readFile(file);
1961
+ response.statusCode = 200;
1962
+ response.setHeader("Content-Type", contentType);
1963
+ response.setHeader("Content-Length", String(content.byteLength));
1964
+ response.setHeader("Cache-Control", "no-cache");
1965
+ if (request.method === "HEAD") {
1966
+ response.end();
1967
+ return;
1968
+ }
1969
+ response.end(content);
1970
+ return;
1971
+ } catch {
1972
+ next();
1973
+ }
1974
+ };
1975
+ server.middlewares.use((request, response, next) => {
1976
+ void middleware(request, response, next);
1977
+ });
1978
+ }
1979
+ };
1980
+ }
1981
+ function collectPublicImagePaths(manifest) {
1982
+ const paths = /* @__PURE__ */ new Set();
1983
+ for (const entry of manifest.publicEntries ?? []) {
1984
+ for (const asset of entry.assets ?? []) {
1985
+ const normalized = normalizeContentPath(asset.path);
1986
+ if (isImagePath(normalized)) paths.add(normalized);
1987
+ }
1988
+ }
1989
+ return paths;
1990
+ }
1991
+ async function collectSiteOwnedOutputPaths(publicDir) {
1992
+ const paths = /* @__PURE__ */ new Set();
1993
+ if (!publicDir) return paths;
1994
+ const root = path7.resolve(publicDir);
1995
+ const walk = async (directory) => {
1996
+ const entries = await fs5.readdir(directory, { withFileTypes: true }).catch(() => void 0);
1997
+ if (!entries) return;
1998
+ for (const entry of entries) {
1999
+ const full = path7.join(directory, entry.name);
2000
+ if (entry.isDirectory()) {
2001
+ await walk(full);
2002
+ } else {
2003
+ paths.add(path7.relative(root, full).replaceAll("\\", "/"));
2004
+ }
2005
+ }
2006
+ };
2007
+ await walk(root);
2008
+ return paths;
2009
+ }
2010
+ function toContentPath(url, base) {
2011
+ if (!url) return void 0;
2012
+ const withoutQuery = url.split("?")[0]?.split("#")[0];
2013
+ if (!withoutQuery) return void 0;
2014
+ let decoded = withoutQuery;
2015
+ try {
2016
+ decoded = decodeURIComponent(withoutQuery);
2017
+ } catch {
2018
+ return void 0;
2019
+ }
2020
+ let pathname = normalizeContentPath(decoded);
2021
+ if (base && base !== "/" && pathname.startsWith(base)) {
2022
+ pathname = normalizeContentPath(pathname.slice(base.length));
2023
+ }
2024
+ const logicalPath = pathname.replace(/^\/+/, "");
2025
+ if (!logicalPath) return void 0;
2026
+ if (logicalPath.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) {
2027
+ return void 0;
2028
+ }
2029
+ return logicalPath;
2030
+ }
2031
+ function imageContentType(logicalPath) {
2032
+ const extension = logicalPath.split("/").at(-1)?.split(".").at(-1);
2033
+ if (!extension) return void 0;
2034
+ return IMAGE_CONTENT_TYPES[extension.toLowerCase()];
2035
+ }
2036
+ async function hasSiteOwnedFile(publicDir, logicalPath) {
2037
+ if (!publicDir) return false;
2038
+ const file = path7.join(publicDir, logicalPath);
2039
+ try {
2040
+ return (await fs5.stat(file)).isFile();
2041
+ } catch {
2042
+ return false;
2043
+ }
2044
+ }
2045
+
2046
+ // src/ssg_plugin_generate_prepare.ts
2047
+ async function prepareSsgGeneration(plugin, state, bundle) {
2048
+ const config = state.resolvedConfig;
2049
+ const timingsMs = process.env.RIEBECKITE_SSG_METRICS_FILE ? {} : void 0;
2050
+ const outDir = resolve4(config.root, config.build.outDir);
2051
+ let viteClientAssetPaths = [];
2052
+ removeVirtualEntryChunk(bundle, state.resolvedVirtualId);
2053
+ const bundleDirectory = join7(
2054
+ config.root,
2055
+ ".riebeckite",
2056
+ `ssg-bundle-${randomUUID5()}`
2057
+ );
2058
+ await restoreClientBuildArtifacts(outDir, state.clientBuildArtifacts);
2059
+ viteClientAssetPaths = await collectBuildOutputPaths(outDir);
2060
+ logSsgDiagnostics(
2061
+ plugin,
2062
+ `SSR noExternal=${formatSsrNoExternal()} · client manifest ${state.clientBuildArtifacts ? "restored" : "not found"}`
2063
+ );
2064
+ const { app, module } = await measure(
2065
+ timingsMs,
2066
+ "ssrModuleLoad",
2067
+ () => loadStandaloneSsgBundle({
2068
+ root: config.root,
2069
+ entry: state.entry,
2070
+ outputDirectory: bundleDirectory,
2071
+ clientOutputDirectory: outDir,
2072
+ config
2073
+ })
2074
+ );
2075
+ const outputChangeSet = await measure(
2076
+ timingsMs,
2077
+ "outputDependencyResolution",
2078
+ async () => module.content?.getOutputChangeSet()
2079
+ );
2080
+ const previousOutputDirectory = state.publicationOutputDirectory;
2081
+ if (!state.clientBuildArtifacts && state.artifactWriter && previousOutputDirectory && await isDirectory(previousOutputDirectory)) {
2082
+ await state.artifactWriter.copyFrom(previousOutputDirectory);
2083
+ }
2084
+ const appFingerprint = await measure(
2085
+ timingsMs,
2086
+ "appFingerprint",
2087
+ () => computeAppFingerprint(config.root, config.configFile)
2088
+ );
2089
+ const bundleFingerprint = await measure(
2090
+ timingsMs,
2091
+ "bundleFingerprint",
2092
+ () => computeBundleFingerprint(config.root, config.configFile)
2093
+ );
2094
+ const outputCachePath = join7(
2095
+ config.root,
2096
+ ".riebeckite",
2097
+ "ssg-output-cache.json"
2098
+ );
2099
+ let previousOutputCache = await loadOutputCacheMetadata(
2100
+ outputCachePath,
2101
+ timingsMs,
2102
+ (message) => plugin.warn(message)
2103
+ );
2104
+ const siteOwnedOutputPaths = await measure(
2105
+ timingsMs,
2106
+ "siteOwnedOutputs",
2107
+ () => collectSiteOwnedOutputPaths(config.publicDir)
2108
+ );
2109
+ viteClientAssetPaths = [
2110
+ .../* @__PURE__ */ new Set([...viteClientAssetPaths, ...Object.keys(bundle)])
2111
+ ].filter((outputPath) => !siteOwnedOutputPaths.has(outputPath)).sort();
2112
+ const siteOutputCollisions = findBuildOutputSiteCollisions(
2113
+ Object.keys(bundle),
2114
+ siteOwnedOutputPaths
2115
+ );
2116
+ if (siteOutputCollisions.length > 0) {
2117
+ plugin.warn(
2118
+ `Build outputs take precedence over site public assets: ${siteOutputCollisions.join(", ")}`
1781
2119
  );
1782
- } catch (error) {
1783
- await rm3(temporaryPath, { force: true }).catch(() => void 0);
1784
- throw error;
1785
2120
  }
1786
- }
1787
- async function collectUnreferencedOutputCacheEntries(directory, outputs, timingsMs) {
1788
- try {
1789
- if (!await isSafeOutputCacheEntriesDirectory(directory)) return;
1790
- const referenced = new Set(
1791
- Object.values(outputs).map((entry) => entry.cachePath)
1792
- );
1793
- const entries = await measure(
1794
- timingsMs,
1795
- "outputCacheGcScan",
1796
- () => readdir3(directory, { withFileTypes: true })
1797
- );
1798
- for (const entry of entries) {
1799
- if (!/^[a-f0-9]{64}$/u.test(entry.name) || referenced.has(entry.name)) {
1800
- continue;
1801
- }
1802
- const path12 = join4(directory, entry.name);
1803
- if (await isRegularFile(path12)) {
1804
- await measure(
1805
- timingsMs,
1806
- "outputCacheGcDelete",
1807
- () => rm3(path12, { force: true })
1808
- );
1809
- }
1810
- }
1811
- } catch {
1812
- return;
2121
+ const uncoveredUnchangedCount = outputChangeSet ? outputChangeSet.unchanged.filter(
2122
+ (output) => !siteOwnedOutputPaths.has(output.path) && !previousOutputCache?.outputs[output.path]
2123
+ ).length : 0;
2124
+ let outputCacheDecision = {
2125
+ changeSetPresent: outputChangeSet !== void 0,
2126
+ changeSetRequiresFullRegeneration: outputChangeSet?.fullRegenerationRequired ?? true,
2127
+ outputCacheLoaded: previousOutputCache !== void 0,
2128
+ appFingerprintMatch: previousOutputCache?.appFingerprint === appFingerprint,
2129
+ clientManifestFingerprintMatch: previousOutputCache?.clientManifestFingerprint === state.clientBuildArtifacts?.manifestFingerprint,
2130
+ uncoveredUnchangedCount
2131
+ };
2132
+ let outputCacheRejectionReason = decideOutputCacheRejection(outputCacheDecision);
2133
+ if (outputCacheRejectionReason === void 0 && previousOutputCache && !await validateOutputCache(
2134
+ previousOutputCache,
2135
+ outputCachePath,
2136
+ timingsMs,
2137
+ (message) => plugin.warn(message)
2138
+ )) {
2139
+ previousOutputCache = void 0;
2140
+ outputCacheDecision = {
2141
+ ...outputCacheDecision,
2142
+ outputCacheLoaded: false
2143
+ };
2144
+ outputCacheRejectionReason = decideOutputCacheRejection(outputCacheDecision);
1813
2145
  }
2146
+ const canUseIncremental = outputCacheRejectionReason === void 0;
2147
+ const reusablePaths = new Set(
2148
+ canUseIncremental ? (outputChangeSet?.unchanged ?? []).map((output) => output.path) : []
2149
+ );
2150
+ const inventory = [
2151
+ ...outputChangeSet?.affected ?? [],
2152
+ ...outputChangeSet?.unchanged ?? []
2153
+ ];
2154
+ const inventoryPaths = new Set(inventory.map((output) => output.path));
2155
+ const honoStaticRoutePaths = /* @__PURE__ */ new Set();
2156
+ logSsgDiagnostics(
2157
+ plugin,
2158
+ `output cache ${canUseIncremental ? "hit" : `miss (${outputCacheRejectionReason})`} · ${reusablePaths.size} reusable outputs`
2159
+ );
2160
+ const shadowedOutputs = /* @__PURE__ */ new Set();
2161
+ const skippedRouteCount = canUseIncremental ? (outputChangeSet?.unchanged ?? []).filter(
2162
+ (output) => output.kind !== "generated"
2163
+ ).length : 0;
2164
+ const generatedHtml = [];
2165
+ const nextOutputCache = {
2166
+ version: 4,
2167
+ appFingerprint,
2168
+ bundleFingerprint,
2169
+ clientManifestFingerprint: state.clientBuildArtifacts?.manifestFingerprint,
2170
+ outputs: {},
2171
+ configFile: config.configFile
2172
+ };
2173
+ const metrics = {
2174
+ processedContentCount: 0,
2175
+ reusedContentCount: 0,
2176
+ candidateOutputCount: outputChangeSet?.candidateOutputCount ?? 0,
2177
+ affectedOutputCount: outputChangeSet?.affectedOutputCount ?? 0,
2178
+ removedOutputCount: outputChangeSet?.removedOutputCount ?? 0,
2179
+ unchangedOutputCount: outputChangeSet?.unchangedOutputCount ?? 0,
2180
+ renderedOutputCount: 0,
2181
+ emittedOutputCount: 0,
2182
+ reusedOutputCount: 0,
2183
+ deletedOutputCount: 0,
2184
+ shadowedOutputCount: 0,
2185
+ fullRegenerationRequired: !canUseIncremental,
2186
+ htmlOutputCount: 0,
2187
+ assetOutputCount: 0,
2188
+ cacheFileSizeBytes: previousOutputCache?.fileSizeBytes ?? null,
2189
+ cacheEntriesRead: previousOutputCache ? Object.keys(previousOutputCache.outputs).length : 0,
2190
+ cacheEntriesSerialized: 0,
2191
+ enumeratedRouteCount: 0,
2192
+ renderedRouteCount: 0,
2193
+ skippedRouteCount,
2194
+ manifestHooksExecuted: 0,
2195
+ manifestHooksReused: 0,
2196
+ manifestHookCacheHit: 0,
2197
+ manifestHookCacheMiss: 0,
2198
+ manifestHookDurationMs: 0,
2199
+ manifestHookPlugins: {},
2200
+ plannedOutputCount: 0,
2201
+ actualOutputCount: 0,
2202
+ matchedOutputCount: 0,
2203
+ missingInPlanCount: 0,
2204
+ missingInDistCount: 0,
2205
+ unknownOutputCount: 0,
2206
+ ownerConflictCount: 0,
2207
+ publicationViolationCount: 0,
2208
+ plannedGenerateOutputCount: 0,
2209
+ plannedReuseOutputCount: 0,
2210
+ plannedRemoveOutputCount: 0,
2211
+ plannedUnknownOutputCount: 0,
2212
+ outputPlanMemoryDeltaBytes: 0,
2213
+ outputCacheDecision,
2214
+ outputCacheRejectionReason: outputCacheRejectionReason ?? null,
2215
+ timingsMs: timingsMs ?? {}
2216
+ };
2217
+ return {
2218
+ config,
2219
+ timingsMs,
2220
+ outDir,
2221
+ viteClientAssetPaths,
2222
+ bundleDirectory,
2223
+ app,
2224
+ module,
2225
+ outputChangeSet,
2226
+ appFingerprint,
2227
+ bundleFingerprint,
2228
+ outputCachePath,
2229
+ previousOutputCache,
2230
+ siteOwnedOutputPaths,
2231
+ outputCacheDecision,
2232
+ outputCacheRejectionReason,
2233
+ canUseIncremental,
2234
+ reusablePaths,
2235
+ inventory,
2236
+ inventoryPaths,
2237
+ honoStaticRoutePaths,
2238
+ shadowedOutputs,
2239
+ skippedRouteCount,
2240
+ generatedHtml,
2241
+ nextOutputCache,
2242
+ metrics,
2243
+ artifactWriter: state.artifactWriter,
2244
+ outputChecksums: state.outputChecksums
2245
+ };
1814
2246
  }
1815
2247
 
2248
+ // src/ssg_plugin_generate_run.ts
2249
+ import { relative as relative4 } from "node:path";
2250
+
1816
2251
  // src/ssg/runner.ts
1817
2252
  import { defaultExtensionMap, redirectPlugin, toSSG } from "hono/ssg";
1818
2253
  async function runSsg(options) {
@@ -1873,764 +2308,486 @@ function restoreEnvironmentVariable(name, value) {
1873
2308
  else process.env[name] = value;
1874
2309
  }
1875
2310
 
1876
- // src/ssg/standalone.ts
1877
- import { mkdir as mkdir4 } from "node:fs/promises";
1878
- import { createRequire } from "node:module";
1879
- import { relative as relative3, resolve as resolve3 } from "node:path";
1880
- import { pathToFileURL } from "node:url";
1881
- import { build } from "vite";
1882
- var standaloneSsgMode = "riebeckite-ssr";
1883
- var frameworkRequire = createRequire(import.meta.url);
1884
- async function loadStandaloneSsgBundle(input) {
1885
- const root = resolve3(input.root);
1886
- const outputDirectory = resolve3(input.outputDirectory);
1887
- await mkdir4(outputDirectory, { recursive: true });
1888
- await build({
1889
- root,
1890
- configFile: input.config ? false : void 0,
1891
- mode: standaloneSsgMode,
1892
- ...input.config ? {
1893
- define: input.config.define,
1894
- oxc: input.config.oxc,
1895
- plugins: [
1896
- ...input.config.plugins.filter(
1897
- (plugin) => plugin.name !== "riebeckite-ssg" && plugin.name !== "riebeckite-ssr-externals" && !plugin.name.startsWith("@hono/vite-build/")
1898
- ),
1899
- createFrameworkResolutionPlugin(),
1900
- createRuntimeExternalPlugin(),
1901
- ...input.clientOutputDirectory ? [createClientManifestPlugin(root, input.clientOutputDirectory)] : []
1902
- ],
1903
- resolve: {
1904
- ...input.config.resolve,
1905
- external: []
2311
+ // src/ssg_plugin_generate_run.ts
2312
+ async function runSsgGeneration(_plugin, ctx, options) {
2313
+ const outputChangeSet = ctx.outputChangeSet;
2314
+ const previousOutputCache = ctx.previousOutputCache;
2315
+ const result = await measure(
2316
+ ctx.timingsMs,
2317
+ "toSSG",
2318
+ () => runSsg({
2319
+ app: ctx.app,
2320
+ outDir: ctx.outDir,
2321
+ incremental: ctx.canUseIncremental,
2322
+ plugins: options.plugins,
2323
+ extensionMap: options.extensionMap,
2324
+ ...options.concurrency === void 0 ? {} : { concurrency: options.concurrency },
2325
+ write: async (filePath, data) => {
2326
+ const fileName = relative4(ctx.outDir, filePath).replaceAll("\\", "/");
2327
+ if (!ctx.inventoryPaths.has(fileName)) {
2328
+ ctx.honoStaticRoutePaths.add(fileName);
2329
+ }
2330
+ if (ctx.siteOwnedOutputPaths.has(fileName)) {
2331
+ ctx.shadowedOutputs.add(fileName);
2332
+ return;
2333
+ }
2334
+ if (ctx.canUseIncremental && ctx.reusablePaths.has(fileName)) {
2335
+ return;
2336
+ }
2337
+ if (fileName.endsWith(".html") && typeof data === "string") {
2338
+ ctx.metrics.renderedOutputCount += 1;
2339
+ ctx.metrics.renderedRouteCount += 1;
2340
+ ctx.metrics.htmlOutputCount += 1;
2341
+ ctx.generatedHtml.push({ path: fileName, html: data });
2342
+ } else {
2343
+ ctx.metrics.assetOutputCount += 1;
2344
+ }
2345
+ if (!ctx.artifactWriter) {
2346
+ throw new Error(
2347
+ "Riebeckite SSG artifact writer was not initialized."
2348
+ );
2349
+ }
2350
+ const writer = ctx.artifactWriter;
2351
+ await measure(
2352
+ ctx.timingsMs,
2353
+ "outputWrite",
2354
+ () => writer.write(fileName, data)
2355
+ );
2356
+ const checksum = fingerprintOutputContent(data);
2357
+ ctx.outputChecksums.set(fileName, checksum);
2358
+ ctx.metrics.emittedOutputCount += 1;
2359
+ ctx.nextOutputCache.outputs[fileName] = outputCacheEntryFor(
2360
+ previousOutputCache,
2361
+ fileName,
2362
+ checksum
2363
+ );
1906
2364
  }
1907
- } : {},
1908
- build: {
1909
- emptyOutDir: false,
1910
- outDir: outputDirectory,
1911
- ssr: true,
1912
- rollupOptions: {
1913
- input: input.entry,
1914
- output: { entryFileNames: "ssg-server.mjs", format: "es" }
2365
+ })
2366
+ );
2367
+ ctx.metrics.enumeratedRouteCount = result.files.length;
2368
+ if (!result.success) throw result.error;
2369
+ ctx.metrics.processedContentCount = ctx.module.content?.getProcessedContentCount() ?? 0;
2370
+ ctx.metrics.reusedContentCount = ctx.module.content?.getReusedContentCount() ?? 0;
2371
+ const manifestHookMetrics = ctx.module.content?.getManifestHookMetrics();
2372
+ ctx.metrics.manifestHooksExecuted = manifestHookMetrics?.manifestHooksExecuted ?? 0;
2373
+ ctx.metrics.manifestHooksReused = manifestHookMetrics?.manifestHooksReused ?? 0;
2374
+ ctx.metrics.manifestHookCacheHit = manifestHookMetrics?.manifestHookCacheHit ?? 0;
2375
+ ctx.metrics.manifestHookCacheMiss = manifestHookMetrics?.manifestHookCacheMiss ?? 0;
2376
+ ctx.metrics.manifestHookDurationMs = manifestHookMetrics?.manifestHookDurationMs ?? 0;
2377
+ ctx.metrics.manifestHookPlugins = manifestHookMetrics?.byPlugin ?? {};
2378
+ const emittedGeneratedOutputCount = await measure(
2379
+ ctx.timingsMs,
2380
+ "generatedOutputs",
2381
+ () => emitGeneratedOutputs(
2382
+ ctx.module,
2383
+ async (asset) => {
2384
+ if (!ctx.artifactWriter) {
2385
+ throw new Error(
2386
+ "Riebeckite SSG artifact writer was not initialized."
2387
+ );
2388
+ }
2389
+ const writer = ctx.artifactWriter;
2390
+ await measure(
2391
+ ctx.timingsMs,
2392
+ "outputWrite",
2393
+ () => writer.write(asset.fileName, asset.source)
2394
+ );
2395
+ const checksum = fingerprintOutputContent(asset.source);
2396
+ ctx.outputChecksums.set(asset.fileName, checksum);
2397
+ ctx.metrics.emittedOutputCount += 1;
2398
+ ctx.nextOutputCache.outputs[asset.fileName] = outputCacheEntryFor(
2399
+ previousOutputCache,
2400
+ asset.fileName,
2401
+ checksum
2402
+ );
2403
+ },
2404
+ ctx.canUseIncremental ? new Set(
2405
+ (outputChangeSet?.affected ?? []).filter((output) => output.kind === "generated").map((output) => output.path)
2406
+ ) : void 0,
2407
+ ctx.siteOwnedOutputPaths,
2408
+ (path14) => ctx.shadowedOutputs.add(path14)
2409
+ )
2410
+ );
2411
+ if (!outputChangeSet)
2412
+ ctx.metrics.candidateOutputCount = result.files.length + emittedGeneratedOutputCount;
2413
+ if (ctx.canUseIncremental && outputChangeSet && previousOutputCache) {
2414
+ await measure(ctx.timingsMs, "unchangedOutputReuse", async () => {
2415
+ for (const output of outputChangeSet.unchanged) {
2416
+ const path14 = output.path;
2417
+ if (ctx.siteOwnedOutputPaths.has(path14)) {
2418
+ ctx.shadowedOutputs.add(path14);
2419
+ continue;
2420
+ }
2421
+ const cached = previousOutputCache.outputs[path14];
2422
+ if (!cached) continue;
2423
+ if (!ctx.artifactWriter) {
2424
+ throw new Error(
2425
+ "Riebeckite SSG artifact writer was not initialized."
2426
+ );
2427
+ }
2428
+ const writer = ctx.artifactWriter;
2429
+ await measure(
2430
+ ctx.timingsMs,
2431
+ "outputWrite",
2432
+ () => writer.copyFileFrom(
2433
+ resolveOutputCacheEntryPath(ctx.outputCachePath, cached),
2434
+ path14
2435
+ )
2436
+ );
2437
+ ctx.outputChecksums.set(path14, cached.checksum);
2438
+ ctx.metrics.emittedOutputCount += 1;
2439
+ ctx.metrics.reusedOutputCount += 1;
2440
+ ctx.nextOutputCache.outputs[path14] = cached;
2441
+ }
2442
+ });
2443
+ }
2444
+ if (outputChangeSet) {
2445
+ for (const output of outputChangeSet.removed) {
2446
+ if (ctx.siteOwnedOutputPaths.has(output.path)) continue;
2447
+ if (!ctx.artifactWriter) {
2448
+ throw new Error("Riebeckite SSG artifact writer was not initialized.");
2449
+ }
2450
+ await ctx.artifactWriter.remove(output.path);
2451
+ ctx.metrics.deletedOutputCount += 1;
2452
+ }
2453
+ }
2454
+ }
2455
+
2456
+ // src/ssg_plugin_setup.ts
2457
+ import { join as join9, resolve as resolve6 } from "node:path";
2458
+
2459
+ // src/ssg/artifact_writer.ts
2460
+ import { randomUUID as randomUUID6 } from "node:crypto";
2461
+ import { constants } from "node:fs";
2462
+ import {
2463
+ copyFile as copyFile2,
2464
+ cp,
2465
+ link,
2466
+ lstat as lstat6,
2467
+ mkdir as mkdir7,
2468
+ readFile as readFile6,
2469
+ rename as rename3,
2470
+ rm as rm6,
2471
+ writeFile as writeFile6
2472
+ } from "node:fs/promises";
2473
+ import { dirname as dirname7, join as join8, resolve as resolve5 } from "node:path";
2474
+ async function createBuildArtifactWriter(input) {
2475
+ const outputDirectory = input.outputDirectory;
2476
+ await recoverPendingPublication(outputDirectory);
2477
+ const stagingDirectory = input.stagingDirectory ?? join8(
2478
+ dirname7(outputDirectory),
2479
+ ".riebeckite",
2480
+ `build-output-${randomUUID6()}`
2481
+ );
2482
+ if (resolve5(stagingDirectory) === resolve5(outputDirectory)) {
2483
+ throw new Error(
2484
+ "Build artifact staging directory must differ from output."
2485
+ );
2486
+ }
2487
+ if (input.clearStagingDirectory !== false) {
2488
+ await rm6(stagingDirectory, { force: true, recursive: true });
2489
+ }
2490
+ await mkdir7(stagingDirectory, { recursive: true });
2491
+ let completed = false;
2492
+ return {
2493
+ directory: stagingDirectory,
2494
+ async copyFrom(source) {
2495
+ ensureOpen(completed);
2496
+ await cp(source, stagingDirectory, { recursive: true });
2497
+ },
2498
+ async remove(path14) {
2499
+ ensureOpen(completed);
2500
+ await rm6(resolveArtifactPath(stagingDirectory, path14), {
2501
+ force: true,
2502
+ recursive: true
2503
+ });
2504
+ },
2505
+ async write(path14, data) {
2506
+ ensureOpen(completed);
2507
+ const target = resolveArtifactPath(stagingDirectory, path14);
2508
+ await mkdir7(dirname7(target), { recursive: true });
2509
+ await replaceArtifactFile(target, data);
2510
+ },
2511
+ async copyFileFrom(source, path14) {
2512
+ ensureOpen(completed);
2513
+ const target = resolveArtifactPath(stagingDirectory, path14);
2514
+ await mkdir7(dirname7(target), { recursive: true });
2515
+ await rm6(target, { force: true });
2516
+ try {
2517
+ await link(source, target);
2518
+ } catch {
2519
+ await copyFile2(source, target, constants.COPYFILE_FICLONE);
1915
2520
  }
1916
2521
  },
1917
- environments: { ssr: { resolve: { noExternal: true } } }
2522
+ async publish() {
2523
+ ensureOpen(completed);
2524
+ await publishDirectory(stagingDirectory, outputDirectory);
2525
+ completed = true;
2526
+ },
2527
+ async discard() {
2528
+ if (completed) return;
2529
+ completed = true;
2530
+ await rm6(stagingDirectory, { force: true, recursive: true });
2531
+ }
2532
+ };
2533
+ }
2534
+ function ensureOpen(completed) {
2535
+ if (completed) throw new Error("Build artifact writer is already closed.");
2536
+ }
2537
+ async function replaceArtifactFile(target, data) {
2538
+ const temporaryPath = `${target}.${randomUUID6()}.tmp`;
2539
+ try {
2540
+ await writeFile6(temporaryPath, data);
2541
+ try {
2542
+ await rename3(temporaryPath, target);
2543
+ } catch {
2544
+ await rm6(target, { force: true });
2545
+ await rename3(temporaryPath, target);
2546
+ }
2547
+ } catch (error) {
2548
+ await rm6(temporaryPath, { force: true }).catch(() => void 0);
2549
+ throw error;
2550
+ }
2551
+ }
2552
+ function resolveArtifactPath(directory, path14) {
2553
+ return resolveWithinDirectory(directory, path14, "Build artifact path");
2554
+ }
2555
+ async function publishDirectory(stagingDirectory, outputDirectory) {
2556
+ const backupDirectory = join8(
2557
+ dirname7(outputDirectory),
2558
+ ".riebeckite",
2559
+ `build-output-backup-${randomUUID6()}`
2560
+ );
2561
+ const previousOutputExists = await isDirectory2(outputDirectory);
2562
+ let previousOutputMoved = false;
2563
+ const journalPath = publicationJournalPath(outputDirectory);
2564
+ await writeJournal(journalPath, {
2565
+ backupDirectory,
2566
+ outputDirectory,
2567
+ stagingDirectory,
2568
+ state: "staged"
1918
2569
  });
1919
- const module = await import(`${pathToFileURL(resolve3(outputDirectory, "ssg-server.mjs")).href}?v=${Date.now()}`);
1920
- if (!module.default) {
1921
- throw new Error(`Failed to find a default export from ${input.entry}.`);
2570
+ try {
2571
+ if (previousOutputExists) {
2572
+ await moveWithRetry(outputDirectory, backupDirectory);
2573
+ previousOutputMoved = true;
2574
+ await writeJournal(journalPath, {
2575
+ backupDirectory,
2576
+ outputDirectory,
2577
+ stagingDirectory,
2578
+ state: "previous-output-moved"
2579
+ });
2580
+ }
2581
+ await moveWithRetry(stagingDirectory, outputDirectory);
2582
+ await writeJournal(journalPath, {
2583
+ backupDirectory,
2584
+ outputDirectory,
2585
+ stagingDirectory,
2586
+ state: "published"
2587
+ });
2588
+ } catch (error) {
2589
+ if (previousOutputMoved) {
2590
+ await rm6(outputDirectory, { force: true, recursive: true });
2591
+ await moveWithRetry(backupDirectory, outputDirectory);
2592
+ }
2593
+ await rm6(journalPath, { force: true });
2594
+ throw error;
2595
+ }
2596
+ await rm6(backupDirectory, { force: true, recursive: true });
2597
+ await rm6(journalPath, { force: true });
2598
+ }
2599
+ function publicationJournalPath(outputDirectory) {
2600
+ return join8(dirname7(outputDirectory), ".riebeckite", "build-output.json");
2601
+ }
2602
+ async function writeJournal(path14, journal) {
2603
+ await mkdir7(dirname7(path14), { recursive: true });
2604
+ await writeFile6(path14, JSON.stringify(journal));
2605
+ }
2606
+ async function recoverPendingPublication(outputDirectory) {
2607
+ const path14 = publicationJournalPath(outputDirectory);
2608
+ let journal;
2609
+ try {
2610
+ journal = JSON.parse(await readFile6(path14, "utf8"));
2611
+ } catch (error) {
2612
+ if (isNotFoundError2(error)) return;
2613
+ await rm6(path14, { force: true });
2614
+ return;
2615
+ }
2616
+ if (journal.outputDirectory !== outputDirectory || !isPublicationJournalState(journal.state)) {
2617
+ await rm6(path14, { force: true });
2618
+ return;
2619
+ }
2620
+ if (journal.state === "previous-output-moved" && !await isDirectory2(outputDirectory) && await isDirectory2(journal.backupDirectory)) {
2621
+ await moveWithRetry(journal.backupDirectory, outputDirectory);
2622
+ }
2623
+ await rm6(journal.backupDirectory, { force: true, recursive: true });
2624
+ await rm6(journal.stagingDirectory, { force: true, recursive: true });
2625
+ await rm6(path14, { force: true });
2626
+ }
2627
+ function isPublicationJournalState(value) {
2628
+ return value === "staged" || value === "previous-output-moved" || value === "published";
2629
+ }
2630
+ async function isDirectory2(path14) {
2631
+ try {
2632
+ return (await lstat6(path14)).isDirectory();
2633
+ } catch (error) {
2634
+ if (isNotFoundError2(error)) return false;
2635
+ throw error;
2636
+ }
2637
+ }
2638
+ async function moveWithRetry(source, destination) {
2639
+ let error;
2640
+ for (let attempt = 0; attempt < 3; attempt += 1) {
2641
+ try {
2642
+ await rename3(source, destination);
2643
+ return;
2644
+ } catch (nextError) {
2645
+ error = nextError;
2646
+ if (!isRetryableRenameError(nextError) || attempt === 2) break;
2647
+ await new Promise((resolve7) => setTimeout(resolve7, (attempt + 1) * 25));
2648
+ }
1922
2649
  }
1923
- return { app: module.default, module };
2650
+ throw error;
1924
2651
  }
1925
- function createFrameworkResolutionPlugin() {
1926
- return {
1927
- name: "riebeckite-ssg-framework-resolution",
1928
- enforce: "pre",
1929
- resolveId(source) {
1930
- if (!(source === "hono" || source.startsWith("hono/") || source === "honox" || source.startsWith("honox/"))) {
1931
- return void 0;
2652
+ function isNotFoundError2(error) {
2653
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
2654
+ }
2655
+ function isRetryableRenameError(error) {
2656
+ return typeof error === "object" && error !== null && "code" in error && ["EBUSY", "EPERM", "EACCES"].includes(
2657
+ error.code
2658
+ );
2659
+ }
2660
+
2661
+ // src/ssg_plugin_setup.ts
2662
+ function createSsgConfigHook(state) {
2663
+ return (config, env) => {
2664
+ const root = resolve6(config.root ?? process.cwd());
2665
+ state.publicationOutputDirectory = resolve6(
2666
+ root,
2667
+ config.build?.outDir ?? "dist"
2668
+ );
2669
+ state.clientOutputDirectory = join9(
2670
+ root,
2671
+ ".riebeckite",
2672
+ "build-output-client"
2673
+ );
2674
+ return {
2675
+ build: {
2676
+ outDir: env.mode === "client" ? state.clientOutputDirectory : join9(root, ".riebeckite", "build-output"),
2677
+ ...env.mode === "client" ? {} : { rollupOptions: { input: [state.virtualId] } }
1932
2678
  }
1933
- return frameworkRequire.resolve(source);
1934
- }
2679
+ };
1935
2680
  };
1936
2681
  }
1937
- var runtimeExternalPackages = /* @__PURE__ */ new Set([
1938
- "@d2lang/d2",
1939
- "@marp-team/marp-core",
1940
- "@riebeckite/og-image"
1941
- ]);
1942
- function createRuntimeExternalPlugin() {
1943
- return {
1944
- name: "riebeckite-ssg-runtime-externals",
1945
- enforce: "pre",
1946
- async resolveId(source, importer) {
1947
- if (!runtimeExternalPackages.has(source)) return void 0;
1948
- const resolved = await this.resolve(source, importer, { skipSelf: true });
1949
- return resolved ? { id: pathToFileURL(resolved.id).href, external: true } : void 0;
1950
- }
1951
- };
2682
+ async function resolveSsgConfig(state, config) {
2683
+ state.resolvedConfig = config;
2684
+ if (config.mode === "client") {
2685
+ state.clientOutputDirectory = resolve6(config.root, config.build.outDir);
2686
+ return;
2687
+ }
2688
+ await emptyBuildOutputDirectory(resolve6(config.root, config.build.outDir));
1952
2689
  }
1953
- function createClientManifestPlugin(root, clientOutputDirectory) {
1954
- const manifestPath = `/${relative3(root, clientOutputDirectory).replaceAll("\\", "/")}/.vite/manifest.json`;
1955
- return {
1956
- name: "riebeckite-client-manifest",
1957
- enforce: "pre",
1958
- transform(code, id) {
1959
- return id.includes("honox/dist/server/components/") ? code.replaceAll("/dist/.vite/manifest.json", manifestPath) : void 0;
1960
- }
1961
- };
2690
+ async function startSsgBuild(state, plugin) {
2691
+ const config = state.resolvedConfig;
2692
+ if (!config || config.mode === "client") return;
2693
+ state.outputChecksums.clear();
2694
+ if (!state.publicationOutputDirectory) {
2695
+ throw new Error(
2696
+ "Riebeckite SSG could not resolve the publication output directory."
2697
+ );
2698
+ }
2699
+ state.artifactWriter = await createBuildArtifactWriter({
2700
+ outputDirectory: state.publicationOutputDirectory,
2701
+ stagingDirectory: resolve6(config.root, config.build.outDir)
2702
+ });
2703
+ const outDir = resolve6(config.root, config.build.outDir);
2704
+ state.clientBuildArtifacts = state.clientOutputDirectory ? await preserveClientBuildArtifacts(state.clientOutputDirectory) : void 0;
2705
+ if (!state.clientBuildArtifacts) {
2706
+ state.clientBuildArtifacts = await preserveClientBuildArtifacts(
2707
+ state.publicationOutputDirectory
2708
+ );
2709
+ }
2710
+ if (!state.clientBuildArtifacts) {
2711
+ return;
2712
+ }
2713
+ logSsgDiagnostics(
2714
+ plugin,
2715
+ `client manifest ${state.clientBuildArtifacts ? `preserved (${state.clientBuildArtifacts.paths.length} files)` : "not found"}`
2716
+ );
2717
+ await emptyBuildOutputDirectory(outDir);
2718
+ }
2719
+ function resolveSsgId(state, id) {
2720
+ return id === state.virtualId ? state.resolvedVirtualId : void 0;
2721
+ }
2722
+ function loadSsgEntry(state, id) {
2723
+ return id === state.resolvedVirtualId ? 'console.log("suppress empty chunk message")' : void 0;
2724
+ }
2725
+ async function endSsgBuild(state, error) {
2726
+ if (!error || !state.artifactWriter) return;
2727
+ await state.artifactWriter.discard();
2728
+ state.artifactWriter = void 0;
2729
+ state.pendingOutputCache = void 0;
1962
2730
  }
1963
2731
 
1964
2732
  // src/ssg_plugin.ts
1965
2733
  var defaultEntry = "./src/index.tsx";
1966
2734
  function riebeckiteSsg(options = {}) {
1967
- const virtualId = "virtual:riebeckite-ssg-void-entry";
1968
- const resolvedVirtualId = `\0${virtualId}`;
1969
- const entry = options.entry ?? defaultEntry;
1970
- let resolvedConfig;
1971
- let publicationOutputDirectory;
1972
- let clientOutputDirectory;
1973
- let artifactWriter;
1974
- let pendingOutputCache;
1975
- let clientBuildArtifacts;
1976
- const outputChecksums = /* @__PURE__ */ new Map();
2735
+ const state = {
2736
+ virtualId: "virtual:riebeckite-ssg-void-entry",
2737
+ resolvedVirtualId: "\0virtual:riebeckite-ssg-void-entry",
2738
+ entry: options.entry ?? defaultEntry,
2739
+ resolvedConfig: void 0,
2740
+ publicationOutputDirectory: void 0,
2741
+ clientOutputDirectory: void 0,
2742
+ artifactWriter: void 0,
2743
+ pendingOutputCache: void 0,
2744
+ clientBuildArtifacts: void 0,
2745
+ outputChecksums: /* @__PURE__ */ new Map()
2746
+ };
1977
2747
  return {
1978
2748
  name: "riebeckite-ssg",
1979
2749
  apply: (_config, env) => env.command === "build",
1980
2750
  enforce: "post",
1981
- config(config, env) {
1982
- const root = resolve4(config.root ?? process.cwd());
1983
- publicationOutputDirectory = resolve4(
1984
- root,
1985
- config.build?.outDir ?? "dist"
1986
- );
1987
- clientOutputDirectory = join5(root, ".riebeckite", "build-output-client");
1988
- return {
1989
- build: {
1990
- outDir: env.mode === "client" ? clientOutputDirectory : join5(root, ".riebeckite", "build-output"),
1991
- ...env.mode === "client" ? {} : { rollupOptions: { input: [virtualId] } }
1992
- }
1993
- };
1994
- },
2751
+ config: createSsgConfigHook(state),
1995
2752
  async configResolved(config) {
1996
- resolvedConfig = config;
1997
- if (config.mode === "client") {
1998
- clientOutputDirectory = resolve4(config.root, config.build.outDir);
1999
- return;
2000
- }
2001
- await emptyBuildOutputDirectory(
2002
- resolve4(config.root, config.build.outDir)
2003
- );
2753
+ await resolveSsgConfig(state, config);
2004
2754
  },
2005
2755
  async buildStart() {
2006
- const config = resolvedConfig;
2007
- if (!config || config.mode === "client") return;
2008
- outputChecksums.clear();
2009
- if (!publicationOutputDirectory) {
2010
- throw new Error(
2011
- "Riebeckite SSG could not resolve the publication output directory."
2012
- );
2013
- }
2014
- artifactWriter = await createBuildArtifactWriter({
2015
- outputDirectory: publicationOutputDirectory,
2016
- stagingDirectory: resolve4(config.root, config.build.outDir)
2017
- });
2018
- const outDir = resolve4(config.root, config.build.outDir);
2019
- clientBuildArtifacts = clientOutputDirectory ? await preserveClientBuildArtifacts(clientOutputDirectory) : void 0;
2020
- if (!clientBuildArtifacts) {
2021
- clientBuildArtifacts = await preserveClientBuildArtifacts(
2022
- publicationOutputDirectory
2023
- );
2024
- }
2025
- if (!clientBuildArtifacts) {
2026
- return;
2027
- }
2028
- logSsgDiagnostics(
2029
- this,
2030
- `client manifest ${clientBuildArtifacts ? `preserved (${clientBuildArtifacts.paths.length} files)` : "not found"}`
2031
- );
2032
- await emptyBuildOutputDirectory(outDir);
2756
+ await startSsgBuild(state, this);
2033
2757
  },
2034
2758
  resolveId(id) {
2035
- return id === virtualId ? resolvedVirtualId : void 0;
2759
+ return resolveSsgId(state, id);
2036
2760
  },
2037
2761
  load(id) {
2038
- return id === resolvedVirtualId ? 'console.log("suppress empty chunk message")' : void 0;
2762
+ return loadSsgEntry(state, id);
2039
2763
  },
2040
2764
  async generateBundle(_outputOptions, bundle) {
2041
- const config = resolvedConfig;
2765
+ const config = state.resolvedConfig;
2042
2766
  if (config?.mode === "client") return;
2043
2767
  if (!config) {
2044
2768
  throw new Error(
2045
2769
  "Riebeckite SSG could not resolve the Vite configuration."
2046
2770
  );
2047
2771
  }
2048
- const timingsMs = process.env.RIEBECKITE_SSG_METRICS_FILE ? {} : void 0;
2049
- const outDir = resolve4(config.root, config.build.outDir);
2050
- let viteClientAssetPaths = [];
2051
- removeVirtualEntryChunk(bundle, resolvedVirtualId);
2052
- const bundleDirectory = join5(
2053
- config.root,
2054
- ".riebeckite",
2055
- `ssg-bundle-${randomUUID4()}`
2056
- );
2772
+ const ctx = await prepareSsgGeneration(this, state, bundle);
2057
2773
  try {
2058
- await restoreClientBuildArtifacts(outDir, clientBuildArtifacts);
2059
- viteClientAssetPaths = await collectBuildOutputPaths(outDir);
2060
- logSsgDiagnostics(
2061
- this,
2062
- `SSR noExternal=${formatSsrNoExternal()} · client manifest ${clientBuildArtifacts ? "restored" : "not found"}`
2063
- );
2064
- const { app, module } = await measure(
2065
- timingsMs,
2066
- "ssrModuleLoad",
2067
- () => loadStandaloneSsgBundle({
2068
- root: config.root,
2069
- entry,
2070
- outputDirectory: bundleDirectory,
2071
- clientOutputDirectory: outDir,
2072
- config
2073
- })
2074
- );
2075
- const outputChangeSet = await measure(
2076
- timingsMs,
2077
- "outputDependencyResolution",
2078
- async () => module.content?.getOutputChangeSet()
2079
- );
2080
- const previousOutputDirectory = publicationOutputDirectory;
2081
- if (!clientBuildArtifacts && artifactWriter && previousOutputDirectory && await isDirectory2(previousOutputDirectory)) {
2082
- await artifactWriter.copyFrom(previousOutputDirectory);
2083
- }
2084
- const appFingerprint = await measure(
2085
- timingsMs,
2086
- "appFingerprint",
2087
- () => computeAppFingerprint(config.root, config.configFile)
2088
- );
2089
- const bundleFingerprint = await measure(
2090
- timingsMs,
2091
- "bundleFingerprint",
2092
- () => computeBundleFingerprint(config.root, config.configFile)
2093
- );
2094
- const outputCachePath = join5(
2095
- config.root,
2096
- ".riebeckite",
2097
- "ssg-output-cache.json"
2098
- );
2099
- let previousOutputCache = await loadOutputCacheMetadata(
2100
- outputCachePath,
2101
- timingsMs,
2102
- (message) => this.warn(message)
2103
- );
2104
- const siteOwnedOutputPaths = await measure(
2105
- timingsMs,
2106
- "siteOwnedOutputs",
2107
- () => collectSiteOwnedOutputPaths(config.publicDir)
2108
- );
2109
- viteClientAssetPaths = [
2110
- .../* @__PURE__ */ new Set([...viteClientAssetPaths, ...Object.keys(bundle)])
2111
- ].filter((outputPath) => !siteOwnedOutputPaths.has(outputPath)).sort();
2112
- const siteOutputCollisions = findBuildOutputSiteCollisions(
2113
- Object.keys(bundle),
2114
- siteOwnedOutputPaths
2115
- );
2116
- if (siteOutputCollisions.length > 0) {
2117
- this.warn(
2118
- `Build outputs take precedence over site public assets: ${siteOutputCollisions.join(", ")}`
2119
- );
2120
- }
2121
- const uncoveredUnchangedCount = outputChangeSet ? outputChangeSet.unchanged.filter(
2122
- (output) => !siteOwnedOutputPaths.has(output.path) && !previousOutputCache?.outputs[output.path]
2123
- ).length : 0;
2124
- let outputCacheDecision = {
2125
- changeSetPresent: outputChangeSet !== void 0,
2126
- changeSetRequiresFullRegeneration: outputChangeSet?.fullRegenerationRequired ?? true,
2127
- outputCacheLoaded: previousOutputCache !== void 0,
2128
- appFingerprintMatch: previousOutputCache?.appFingerprint === appFingerprint,
2129
- clientManifestFingerprintMatch: previousOutputCache?.clientManifestFingerprint === clientBuildArtifacts?.manifestFingerprint,
2130
- uncoveredUnchangedCount
2131
- };
2132
- let outputCacheRejectionReason = decideOutputCacheRejection(outputCacheDecision);
2133
- if (outputCacheRejectionReason === void 0 && previousOutputCache && !await validateOutputCache(
2134
- previousOutputCache,
2135
- outputCachePath,
2136
- timingsMs,
2137
- (message) => this.warn(message)
2138
- )) {
2139
- previousOutputCache = void 0;
2140
- outputCacheDecision = {
2141
- ...outputCacheDecision,
2142
- outputCacheLoaded: false
2143
- };
2144
- outputCacheRejectionReason = decideOutputCacheRejection(outputCacheDecision);
2145
- }
2146
- const canUseIncremental = outputCacheRejectionReason === void 0;
2147
- const reusablePaths = new Set(
2148
- canUseIncremental ? (outputChangeSet?.unchanged ?? []).map((output) => output.path) : []
2149
- );
2150
- const inventory = [
2151
- ...outputChangeSet?.affected ?? [],
2152
- ...outputChangeSet?.unchanged ?? []
2153
- ];
2154
- const inventoryPaths = new Set(inventory.map((output) => output.path));
2155
- const honoStaticRoutePaths = /* @__PURE__ */ new Set();
2156
- logSsgDiagnostics(
2157
- this,
2158
- `output cache ${canUseIncremental ? "hit" : `miss (${outputCacheRejectionReason})`} · ${reusablePaths.size} reusable outputs`
2159
- );
2160
- const shadowedOutputs = /* @__PURE__ */ new Set();
2161
- const skippedRouteCount = canUseIncremental ? (outputChangeSet?.unchanged ?? []).filter(
2162
- (output) => output.kind !== "generated"
2163
- ).length : 0;
2164
- const generatedHtml = [];
2165
- const nextOutputCache = {
2166
- version: 4,
2167
- appFingerprint,
2168
- bundleFingerprint,
2169
- clientManifestFingerprint: clientBuildArtifacts?.manifestFingerprint,
2170
- outputs: {},
2171
- configFile: config.configFile
2172
- };
2173
- const metrics = {
2174
- processedContentCount: 0,
2175
- reusedContentCount: 0,
2176
- candidateOutputCount: outputChangeSet?.candidateOutputCount ?? 0,
2177
- affectedOutputCount: outputChangeSet?.affectedOutputCount ?? 0,
2178
- removedOutputCount: outputChangeSet?.removedOutputCount ?? 0,
2179
- unchangedOutputCount: outputChangeSet?.unchangedOutputCount ?? 0,
2180
- renderedOutputCount: 0,
2181
- emittedOutputCount: 0,
2182
- reusedOutputCount: 0,
2183
- deletedOutputCount: 0,
2184
- shadowedOutputCount: 0,
2185
- fullRegenerationRequired: !canUseIncremental,
2186
- htmlOutputCount: 0,
2187
- assetOutputCount: 0,
2188
- cacheFileSizeBytes: previousOutputCache?.fileSizeBytes ?? null,
2189
- cacheEntriesRead: previousOutputCache ? Object.keys(previousOutputCache.outputs).length : 0,
2190
- cacheEntriesSerialized: 0,
2191
- enumeratedRouteCount: 0,
2192
- renderedRouteCount: 0,
2193
- skippedRouteCount,
2194
- manifestHooksExecuted: 0,
2195
- manifestHooksReused: 0,
2196
- manifestHookCacheHit: 0,
2197
- manifestHookCacheMiss: 0,
2198
- manifestHookDurationMs: 0,
2199
- manifestHookPlugins: {},
2200
- plannedOutputCount: 0,
2201
- actualOutputCount: 0,
2202
- matchedOutputCount: 0,
2203
- missingInPlanCount: 0,
2204
- missingInDistCount: 0,
2205
- unknownOutputCount: 0,
2206
- ownerConflictCount: 0,
2207
- publicationViolationCount: 0,
2208
- plannedGenerateOutputCount: 0,
2209
- plannedReuseOutputCount: 0,
2210
- plannedRemoveOutputCount: 0,
2211
- plannedUnknownOutputCount: 0,
2212
- outputPlanMemoryDeltaBytes: 0,
2213
- outputCacheDecision,
2214
- outputCacheRejectionReason: outputCacheRejectionReason ?? null,
2215
- timingsMs: timingsMs ?? {}
2216
- };
2217
- const result = await measure(
2218
- timingsMs,
2219
- "toSSG",
2220
- () => runSsg({
2221
- app,
2222
- outDir,
2223
- incremental: canUseIncremental,
2224
- plugins: options.plugins,
2225
- extensionMap: options.extensionMap,
2226
- ...options.concurrency === void 0 ? {} : { concurrency: options.concurrency },
2227
- write: async (filePath, data) => {
2228
- const fileName = relative4(outDir, filePath).replaceAll("\\", "/");
2229
- if (!inventoryPaths.has(fileName)) {
2230
- honoStaticRoutePaths.add(fileName);
2231
- }
2232
- if (siteOwnedOutputPaths.has(fileName)) {
2233
- shadowedOutputs.add(fileName);
2234
- return;
2235
- }
2236
- if (canUseIncremental && reusablePaths.has(fileName)) {
2237
- return;
2238
- }
2239
- if (fileName.endsWith(".html") && typeof data === "string") {
2240
- metrics.renderedOutputCount += 1;
2241
- metrics.renderedRouteCount += 1;
2242
- metrics.htmlOutputCount += 1;
2243
- generatedHtml.push({ path: fileName, html: data });
2244
- } else {
2245
- metrics.assetOutputCount += 1;
2246
- }
2247
- if (!artifactWriter) {
2248
- throw new Error(
2249
- "Riebeckite SSG artifact writer was not initialized."
2250
- );
2251
- }
2252
- const writer = artifactWriter;
2253
- await measure(
2254
- timingsMs,
2255
- "outputWrite",
2256
- () => writer.write(fileName, data)
2257
- );
2258
- const checksum = fingerprintOutputContent(data);
2259
- outputChecksums.set(fileName, checksum);
2260
- metrics.emittedOutputCount += 1;
2261
- nextOutputCache.outputs[fileName] = outputCacheEntryFor(
2262
- previousOutputCache,
2263
- fileName,
2264
- checksum
2265
- );
2266
- }
2267
- })
2268
- );
2269
- metrics.enumeratedRouteCount = result.files.length;
2270
- if (!result.success) throw result.error;
2271
- metrics.processedContentCount = module.content?.getProcessedContentCount() ?? 0;
2272
- metrics.reusedContentCount = module.content?.getReusedContentCount() ?? 0;
2273
- const manifestHookMetrics = module.content?.getManifestHookMetrics();
2274
- metrics.manifestHooksExecuted = manifestHookMetrics?.manifestHooksExecuted ?? 0;
2275
- metrics.manifestHooksReused = manifestHookMetrics?.manifestHooksReused ?? 0;
2276
- metrics.manifestHookCacheHit = manifestHookMetrics?.manifestHookCacheHit ?? 0;
2277
- metrics.manifestHookCacheMiss = manifestHookMetrics?.manifestHookCacheMiss ?? 0;
2278
- metrics.manifestHookDurationMs = manifestHookMetrics?.manifestHookDurationMs ?? 0;
2279
- metrics.manifestHookPlugins = manifestHookMetrics?.byPlugin ?? {};
2280
- const emittedGeneratedOutputCount = await measure(
2281
- timingsMs,
2282
- "generatedOutputs",
2283
- () => emitGeneratedOutputs(
2284
- module,
2285
- async (asset) => {
2286
- if (!artifactWriter) {
2287
- throw new Error(
2288
- "Riebeckite SSG artifact writer was not initialized."
2289
- );
2290
- }
2291
- const writer = artifactWriter;
2292
- await measure(
2293
- timingsMs,
2294
- "outputWrite",
2295
- () => writer.write(asset.fileName, asset.source)
2296
- );
2297
- const checksum = fingerprintOutputContent(asset.source);
2298
- outputChecksums.set(asset.fileName, checksum);
2299
- metrics.emittedOutputCount += 1;
2300
- nextOutputCache.outputs[asset.fileName] = outputCacheEntryFor(
2301
- previousOutputCache,
2302
- asset.fileName,
2303
- checksum
2304
- );
2305
- },
2306
- canUseIncremental ? new Set(
2307
- (outputChangeSet?.affected ?? []).filter((output) => output.kind === "generated").map((output) => output.path)
2308
- ) : void 0,
2309
- siteOwnedOutputPaths,
2310
- (path12) => shadowedOutputs.add(path12)
2311
- )
2312
- );
2313
- if (!outputChangeSet)
2314
- metrics.candidateOutputCount = result.files.length + emittedGeneratedOutputCount;
2315
- if (canUseIncremental && outputChangeSet && previousOutputCache) {
2316
- await measure(timingsMs, "unchangedOutputReuse", async () => {
2317
- for (const output of outputChangeSet.unchanged) {
2318
- const path12 = output.path;
2319
- if (siteOwnedOutputPaths.has(path12)) {
2320
- shadowedOutputs.add(path12);
2321
- continue;
2322
- }
2323
- const cached = previousOutputCache.outputs[path12];
2324
- if (!cached) continue;
2325
- if (!artifactWriter) {
2326
- throw new Error(
2327
- "Riebeckite SSG artifact writer was not initialized."
2328
- );
2329
- }
2330
- const writer = artifactWriter;
2331
- await measure(
2332
- timingsMs,
2333
- "outputWrite",
2334
- () => writer.copyFileFrom(
2335
- resolveOutputCacheEntryPath(outputCachePath, cached),
2336
- path12
2337
- )
2338
- );
2339
- outputChecksums.set(path12, cached.checksum);
2340
- metrics.emittedOutputCount += 1;
2341
- metrics.reusedOutputCount += 1;
2342
- nextOutputCache.outputs[path12] = cached;
2343
- }
2344
- });
2345
- }
2346
- if (outputChangeSet) {
2347
- for (const output of outputChangeSet.removed) {
2348
- if (siteOwnedOutputPaths.has(output.path)) continue;
2349
- if (!artifactWriter) {
2350
- throw new Error(
2351
- "Riebeckite SSG artifact writer was not initialized."
2352
- );
2353
- }
2354
- await artifactWriter.remove(output.path);
2355
- metrics.deletedOutputCount += 1;
2356
- }
2357
- }
2358
- metrics.shadowedOutputCount = shadowedOutputs.size;
2359
- if (shadowedOutputs.size > 0) {
2360
- this.warn(
2361
- `Site public assets take precedence over generated outputs: ${[
2362
- ...shadowedOutputs
2363
- ].sort().join(", ")}`
2364
- );
2365
- }
2366
- metrics.cacheEntriesSerialized = Object.keys(
2367
- nextOutputCache.outputs
2368
- ).length;
2369
- const manifest = await module.content?.getManifest();
2370
- const publicationFingerprint = manifest ? fingerprintPublication(
2371
- publicationEntriesFromManifest(manifest),
2372
- publicationRedirectsFromManifest(manifest),
2373
- publicationOutputsFromManifest(manifest)
2374
- ) : void 0;
2375
- pendingOutputCache = {
2376
- path: outputCachePath,
2377
- state: nextOutputCache,
2378
- metrics,
2379
- timingsMs,
2380
- outDir,
2381
- publicDir: config.publicDir,
2382
- configFile: config.configFile,
2383
- ...publicationFingerprint === void 0 ? {} : { publicationFingerprint },
2384
- outputPlanInput: {
2385
- inventory,
2386
- affectedPaths: new Set(
2387
- (outputChangeSet?.affected ?? []).map((output) => output.path)
2388
- ),
2389
- removed: outputChangeSet?.removed ?? [],
2390
- cacheAvailable: canUseIncremental,
2391
- honoStaticRoutePaths,
2392
- viteClientAssetPaths: new Set(viteClientAssetPaths),
2393
- sitePublicAssetPaths: siteOwnedOutputPaths
2394
- },
2395
- provenance: module.content?.getProvenance(),
2396
- content: module.content,
2397
- reusablePaths: new Set(
2398
- [...reusablePaths].filter(
2399
- (path12) => !siteOwnedOutputPaths.has(path12)
2400
- )
2401
- )
2402
- };
2403
- this.info(
2404
- `SSG outputs: ${metrics.renderedOutputCount} rendered · ${metrics.reusedOutputCount} reused · ${metrics.deletedOutputCount} removed`
2405
- );
2406
- const generatedHtmlDiagnostics = inspectGeneratedHtmlPages(
2407
- module,
2408
- generatedHtml,
2409
- {
2410
- warn: (message) => this.warn(message),
2411
- info: (message) => this.info(message)
2412
- }
2413
- );
2414
- module.content?.recordFinalHtmlDiagnostics?.(generatedHtmlDiagnostics);
2415
- logGeneratedHtmlAssetDiagnostics(this, generatedHtml);
2774
+ await runSsgGeneration(this, ctx, options);
2775
+ await finalizeSsgGeneration(this, ctx, state);
2416
2776
  } finally {
2417
- await rm4(bundleDirectory, { recursive: true, force: true });
2418
- await discardClientBuildArtifacts(clientBuildArtifacts);
2419
- if (clientOutputDirectory) {
2420
- await rm4(clientOutputDirectory, { recursive: true, force: true });
2421
- }
2422
- clientBuildArtifacts = void 0;
2777
+ await cleanupSsgGeneration(ctx, state);
2423
2778
  }
2424
2779
  },
2425
2780
  closeBundle: {
2426
2781
  order: "post",
2427
2782
  async handler() {
2428
- if (!resolvedConfig) return;
2429
- if (resolvedConfig.mode === "client") return;
2430
- const outputDirectory = publicationOutputDirectory;
2431
- if (!outputDirectory) {
2432
- throw new Error(
2433
- "Riebeckite SSG could not resolve the publication output directory."
2434
- );
2435
- }
2436
- const outDir = resolve4(
2437
- resolvedConfig.root,
2438
- resolvedConfig.build.outDir
2439
- );
2440
- const oversizedAssets = await findOversizedAssets(outDir);
2441
- for (const asset of oversizedAssets) {
2442
- this.warn(
2443
- `Generated asset ${asset.path} is ${formatBytes(asset.size)}, exceeding Cloudflare Workers' ${formatBytes(CLOUDFLARE_WORKER_ASSET_LIMIT)} asset limit.`
2444
- );
2445
- }
2446
- const outputCache = pendingOutputCache;
2447
- if (!outputCache) return;
2448
- let published = false;
2449
- try {
2450
- if (!artifactWriter) {
2451
- throw new Error(
2452
- "Riebeckite SSG artifact writer was not initialized."
2453
- );
2454
- }
2455
- outputCache.state.finalOutputInventory = await measure(
2456
- outputCache.timingsMs,
2457
- "outputInventory",
2458
- () => fingerprintOutputDirectory(
2459
- outputCache.outDir,
2460
- "",
2461
- void 0,
2462
- outputChecksums
2463
- )
2464
- );
2465
- const finalOutputInventory = outputCache.state.finalOutputInventory;
2466
- const artifactFingerprint = fingerprintOutputInventory(finalOutputInventory);
2467
- if (outputCache.provenance && outputCache.content) {
2468
- await outputCache.content.attachFinalOutputArtifacts(
2469
- outputCache.provenance.buildId,
2470
- finalOutputInventory,
2471
- outputCache.reusablePaths
2472
- );
2473
- }
2474
- const outputPlanRssBefore = process.memoryUsage().rss;
2475
- const outputPlan = measureSync(
2476
- outputCache.timingsMs,
2477
- "outputPlan",
2478
- () => buildOutputPlan({
2479
- ...outputCache.outputPlanInput
2480
- })
2481
- );
2482
- const outputPlanComparison = measureSync(
2483
- outputCache.timingsMs,
2484
- "outputPlanComparison",
2485
- () => compareOutputPlan(outputPlan, Object.keys(finalOutputInventory))
2486
- );
2487
- outputCache.metrics.plannedOutputCount = outputPlan.entries.length;
2488
- outputCache.metrics.actualOutputCount = Object.keys(finalOutputInventory).length;
2489
- outputCache.metrics.matchedOutputCount = outputPlanComparison.matched.length;
2490
- outputCache.metrics.missingInPlanCount = outputPlanComparison.missingInPlan.length;
2491
- outputCache.metrics.missingInDistCount = outputPlanComparison.missingInDist.length;
2492
- outputCache.metrics.unknownOutputCount = outputPlanComparison.unknown.length;
2493
- outputCache.metrics.ownerConflictCount = outputPlanComparison.ownerConflicts.length;
2494
- outputCache.metrics.publicationViolationCount = outputPlanComparison.publicationViolations.length;
2495
- outputCache.metrics.plannedGenerateOutputCount = outputPlan.entries.filter(
2496
- (entry2) => entry2.action === "generate"
2497
- ).length;
2498
- outputCache.metrics.plannedReuseOutputCount = outputPlan.entries.filter(
2499
- (entry2) => entry2.action === "reuse"
2500
- ).length;
2501
- outputCache.metrics.plannedRemoveOutputCount = outputPlan.entries.filter(
2502
- (entry2) => entry2.action === "remove"
2503
- ).length;
2504
- outputCache.metrics.plannedUnknownOutputCount = outputPlan.entries.filter(
2505
- (entry2) => entry2.action === "unknown"
2506
- ).length;
2507
- outputCache.metrics.outputPlanMemoryDeltaBytes = Math.max(
2508
- 0,
2509
- process.memoryUsage().rss - outputPlanRssBefore
2510
- );
2511
- assertRequiredOutputsWereGenerated(outputPlanComparison);
2512
- const publicDir = outputCache.publicDir;
2513
- outputCache.state.publicDirectory = publicDir ? resolve4(publicDir) : void 0;
2514
- outputCache.state.publicFingerprint = publicDir ? await measure(
2515
- outputCache.timingsMs,
2516
- "publicFingerprint",
2517
- () => fingerprintDirectory(resolve4(publicDir))
2518
- ) : void 0;
2519
- try {
2520
- await saveOutputCache(
2521
- outputCache.path,
2522
- outputCache.state,
2523
- outputCache.outDir,
2524
- outputCache.timingsMs
2525
- );
2526
- } catch (error) {
2527
- this.warn(
2528
- `SSG output cache could not be saved; the next build regenerates every output. ${error instanceof Error ? error.message : String(error)}`
2529
- );
2530
- }
2531
- await artifactWriter.publish();
2532
- published = true;
2533
- await writePublicationMarker({
2534
- root: resolvedConfig.root,
2535
- outputDirectory,
2536
- publicationFingerprint: outputCache.publicationFingerprint,
2537
- artifactFingerprint,
2538
- warn: (message) => this.warn(message)
2539
- });
2540
- } finally {
2541
- if (!published) await artifactWriter?.discard();
2542
- await writeSsgOutputMetrics(outputCache.metrics);
2543
- pendingOutputCache = void 0;
2544
- artifactWriter = void 0;
2545
- }
2783
+ await closeSsgBundle(this, state);
2546
2784
  }
2547
2785
  },
2548
2786
  async buildEnd(error) {
2549
- if (!error || !artifactWriter) return;
2550
- await artifactWriter.discard();
2551
- artifactWriter = void 0;
2552
- pendingOutputCache = void 0;
2787
+ await endSsgBuild(state, error);
2553
2788
  }
2554
2789
  };
2555
2790
  }
2556
- async function isDirectory2(path12) {
2557
- try {
2558
- return (await lstat3(path12)).isDirectory();
2559
- } catch (error) {
2560
- if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
2561
- return false;
2562
- }
2563
- throw error;
2564
- }
2565
- }
2566
- function findBuildOutputSiteCollisions(buildOutputPaths, siteOwnedOutputPaths) {
2567
- const collisions = /* @__PURE__ */ new Set();
2568
- for (const path12 of buildOutputPaths) {
2569
- if (siteOwnedOutputPaths.has(path12)) collisions.add(path12);
2570
- }
2571
- return [...collisions].sort();
2572
- }
2573
- function assertRequiredOutputsWereGenerated(comparison) {
2574
- if (comparison.missingInDist.length === 0) return;
2575
- throw new Error(
2576
- `SSG did not generate required output: ${comparison.missingInDist.join(", ")}`
2577
- );
2578
- }
2579
- function outputCacheEntryFor(previous, path12, checksum) {
2580
- const cached = previous?.outputs[path12];
2581
- return cached?.checksum === checksum ? cached : { cachePath: "", checksum: "" };
2582
- }
2583
- async function emitGeneratedOutputs(module, emit, affectedPaths, shadowedPaths, onShadowed) {
2584
- const content = module.content;
2585
- if (!content) return 0;
2586
- if (affectedPaths?.size === 0) return 0;
2587
- const manifest = await content.getManifest();
2588
- let count = 0;
2589
- for (const output of manifest.generatedOutputs ?? []) {
2590
- if (affectedPaths && !affectedPaths.has(output.path)) continue;
2591
- if (shadowedPaths?.has(output.path)) {
2592
- onShadowed?.(output.path);
2593
- continue;
2594
- }
2595
- const source = isDeferredGeneratedOutput(output) ? await output.generate() : output.content;
2596
- await emit({
2597
- type: "asset",
2598
- fileName: output.path,
2599
- source
2600
- });
2601
- count += 1;
2602
- }
2603
- return count;
2604
- }
2605
- function removeVirtualEntryChunk(bundle, virtualEntryId) {
2606
- for (const chunk of Object.values(bundle)) {
2607
- if (chunk.type === "chunk" && chunk.moduleIds?.includes(virtualEntryId)) {
2608
- delete bundle[chunk.fileName];
2609
- }
2610
- }
2611
- }
2612
- async function writePublicationMarker(input) {
2613
- const path12 = join5(input.root, ".riebeckite", BUILD_OUTPUT_MARKER_FILE);
2614
- try {
2615
- await mkdir5(dirname5(path12), { recursive: true });
2616
- await writeFile4(
2617
- path12,
2618
- serializeBuildOutputMarker(
2619
- createBuildOutputMarker({
2620
- outputDirectory: input.outputDirectory,
2621
- ...input.publicationFingerprint === void 0 ? {} : { publicationFingerprint: input.publicationFingerprint },
2622
- ...input.artifactFingerprint === void 0 ? {} : { artifactFingerprint: input.artifactFingerprint },
2623
- completedAt: /* @__PURE__ */ new Date()
2624
- })
2625
- ),
2626
- "utf8"
2627
- );
2628
- } catch (error) {
2629
- input.warn(
2630
- `Could not write the publication marker; publish will rebuild before deploying. ${error instanceof Error ? error.message : String(error)}`
2631
- );
2632
- }
2633
- }
2634
2791
 
2635
2792
  // src/ssg.ts
2636
2793
  var defaultSsgEntry = "./app/server.ts";
@@ -2657,13 +2814,17 @@ function createRiebeckiteSsg(options = {}) {
2657
2814
  }
2658
2815
 
2659
2816
  // src/vite_plugin.ts
2660
- import path11 from "node:path";
2817
+ import path13 from "node:path";
2818
+ import {
2819
+ createContentFormatRegistry
2820
+ } from "@riebeckite/core";
2661
2821
  import {
2662
2822
  invalidateDevelopmentInspector,
2663
2823
  invalidateRiebeckiteBridge,
2664
2824
  riebeckiteBridge,
2665
2825
  riebeckiteDevelopmentInspector
2666
2826
  } from "@riebeckite/dev-inspector";
2827
+ import { mergeConfig } from "vite";
2667
2828
 
2668
2829
  // src/asset_entries.ts
2669
2830
  import fs6 from "node:fs";
@@ -2683,13 +2844,15 @@ function createFrameworkStylesEntry() {
2683
2844
  function createPluginStylesEntry(config) {
2684
2845
  return createStylesheetEntry(
2685
2846
  collectPluginStyleSpecifiers(config),
2686
- "Plugin default styles, in resolved plugin order. Generated by @riebeckite/honox; do not edit. Import this before the theme stylesheet so a theme can override plugin defaults."
2847
+ "Plugin default styles in the rb-plugins cascade layer, in resolved plugin order. Generated by @riebeckite/honox; do not edit.",
2848
+ "rb-plugins"
2687
2849
  );
2688
2850
  }
2689
2851
  function createThemeStylesEntry(config) {
2690
2852
  return createStylesheetEntry(
2691
2853
  config.theme.styles.map((style) => style.moduleSpecifier),
2692
- "Theme styles. Generated by @riebeckite/honox; do not edit. Import this after the plugin stylesheet so the theme wins the plugin/theme cascade."
2854
+ "Theme styles in the rb-theme cascade layer. Generated by @riebeckite/honox; do not edit.",
2855
+ "rb-theme"
2693
2856
  );
2694
2857
  }
2695
2858
  function collectPluginStyleSpecifiers(config) {
@@ -2697,8 +2860,10 @@ function collectPluginStyleSpecifiers(config) {
2697
2860
  (plugin) => (plugin.assets ?? []).filter((asset) => asset.kind === "style").map((asset) => asset.moduleSpecifier)
2698
2861
  );
2699
2862
  }
2700
- function createStylesheetEntry(moduleSpecifiers, banner) {
2701
- const imports = uniqueStrings(moduleSpecifiers).map((specifier) => `@import ${JSON.stringify(specifier)};`).join("\n");
2863
+ function createStylesheetEntry(moduleSpecifiers, banner, layer) {
2864
+ const imports = uniqueStrings(moduleSpecifiers).map(
2865
+ (specifier) => `@import ${JSON.stringify(specifier)}${layer ? ` layer(${layer})` : ""};`
2866
+ ).join("\n");
2702
2867
  if (!banner) return imports;
2703
2868
  const header = `/* ${banner.replace(/\*\//g, "* /")} */`;
2704
2869
  return imports ? `${header}
@@ -2706,51 +2871,41 @@ ${imports}
2706
2871
  ` : `${header}
2707
2872
  `;
2708
2873
  }
2709
- function writeGeneratedFile(filePath, contents) {
2710
- if (readGeneratedFile(filePath) === contents) return;
2711
- fs6.mkdirSync(path8.dirname(filePath), { recursive: true });
2712
- fs6.writeFileSync(filePath, contents);
2713
- }
2714
- function readGeneratedFile(filePath) {
2715
- try {
2716
- return fs6.readFileSync(filePath, "utf8");
2717
- } catch (error) {
2718
- if (isNotFoundError3(error)) return void 0;
2719
- throw error;
2720
- }
2721
- }
2722
- function isNotFoundError3(error) {
2723
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
2724
- }
2725
-
2726
- // src/client_module.ts
2727
- import { serializePublicClientConfig } from "@riebeckite/core";
2728
- var clientModuleId = "virtual:riebeckite/client";
2729
- var resolvedClientModuleId = `\0${clientModuleId}`;
2730
- function riebeckiteClientModule(getConfig) {
2731
- let development = false;
2732
- return {
2733
- name: "riebeckite-client-module",
2734
- config(_config, environment) {
2735
- development = environment.command === "serve";
2736
- },
2737
- resolveId(id) {
2738
- if (id === clientModuleId) return resolvedClientModuleId;
2739
- return null;
2740
- },
2741
- load(id) {
2742
- if (id !== resolvedClientModuleId) return null;
2743
- return createClientModule(getConfig(), development);
2744
- }
2745
- };
2874
+ function writeGeneratedFile(filePath, contents) {
2875
+ if (readGeneratedFile(filePath) === contents) return;
2876
+ fs6.mkdirSync(path8.dirname(filePath), { recursive: true });
2877
+ fs6.writeFileSync(filePath, contents);
2878
+ }
2879
+ function readGeneratedFile(filePath) {
2880
+ try {
2881
+ return fs6.readFileSync(filePath, "utf8");
2882
+ } catch (error) {
2883
+ if (isNotFoundError3(error)) return void 0;
2884
+ throw error;
2885
+ }
2746
2886
  }
2887
+ function isNotFoundError3(error) {
2888
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
2889
+ }
2890
+
2891
+ // src/client_module_part2.ts
2892
+ import {
2893
+ serializePublicClientConfig
2894
+ } from "@riebeckite/core";
2747
2895
  function createClientModule(config, development) {
2748
2896
  const imports = [];
2749
2897
  const appInitializers = [];
2898
+ const appConditionalInitializers = [];
2750
2899
  const pageInitializers = [];
2751
2900
  const clientEntries = config.plugins.flatMap(
2752
2901
  (plugin) => plugin.clientEntries ?? []
2753
2902
  );
2903
+ const markdownComponents = config.plugins.flatMap(
2904
+ (plugin) => plugin.markdownComponents ?? []
2905
+ );
2906
+ const interactiveMarkdownComponents = markdownComponents.filter(
2907
+ (component) => component.client !== void 0
2908
+ );
2754
2909
  const runtimeEntries = /* @__PURE__ */ new Map();
2755
2910
  for (const entry of clientEntries) {
2756
2911
  for (const runtime of entry.runtimeEntries ?? []) {
@@ -2766,6 +2921,10 @@ function createClientModule(config, development) {
2766
2921
  }
2767
2922
  const hasRuntimes = runtimeEntries.size > 0;
2768
2923
  imports.push('import { ClientLifecycle } from "@riebeckite/core/client";');
2924
+ if (interactiveMarkdownComponents.length > 0) {
2925
+ imports.push('import { hydrateRoot } from "hono/jsx/dom/client";');
2926
+ imports.push('import { jsx } from "hono/jsx/jsx-runtime";');
2927
+ }
2769
2928
  if (hasRuntimes) {
2770
2929
  imports.push(
2771
2930
  'import { createClientRuntimeHost, InteractiveRuntimeRegistry } from "@riebeckite/runtime/client";'
@@ -2799,19 +2958,25 @@ function createClientModule(config, development) {
2799
2958
  const ensureRuntimes = runtimeIds.length > 0 ? `await ensurePluginRuntimes(${serializedRuntimeIds}); ` : "";
2800
2959
  const initializerWrapper = runtimeIds.length > 0 ? `async (context) => { ${ensureRuntimes}return ${initializer}; }` : `(context) => ${initializer}`;
2801
2960
  const runtimeArguments = hasRuntimes ? `${serializedRuntimeIds}, ${initializerWrapper}` : initializerWrapper;
2802
- const initializers = entry.scope === "app" ? appInitializers : pageInitializers;
2961
+ const scope = entry.scope ?? "page";
2962
+ const rootMode = entry.root ?? "page";
2803
2963
  if (entry.presenceSelector === void 0) {
2964
+ const initializers = scope === "app" ? appInitializers : pageInitializers;
2804
2965
  initializers.push(
2805
- `mountPluginClientInitializer(${JSON.stringify(entry.scope ?? "page")}, ${JSON.stringify(entry.moduleSpecifier)}, root, ${serializedConfig}, ${runtimeArguments})`
2966
+ `mountPluginClientInitializer(${JSON.stringify(scope)}, ${JSON.stringify(entry.moduleSpecifier)}, resolveClientEntryRoot(${JSON.stringify(scope)}, root, ${JSON.stringify(rootMode)}), ${serializedConfig}, ${runtimeArguments})`
2806
2967
  );
2807
2968
  continue;
2808
2969
  }
2809
2970
  const dynamicInitializer = entry.initializerArguments === "context" ? `initializer(context)` : entry.initializerArguments === "root" ? `initializer(context.root)` : `initializer(context.config)`;
2810
2971
  const dynamicWrapper = runtimeIds.length > 0 ? `async (context) => { ${ensureRuntimes}return ${dynamicInitializer}; }` : `(context) => ${dynamicInitializer}`;
2811
- initializers.push(
2812
- `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}; })`
2972
+ const conditionalInitializers = scope === "app" ? appConditionalInitializers : pageInitializers;
2973
+ conditionalInitializers.push(
2974
+ `mountConditionalPluginClientInitializer(${JSON.stringify(scope)}, ${JSON.stringify(entry.moduleSpecifier)}, root, ${serializedConfig}, ${JSON.stringify(entry.presenceSelector)}, ${JSON.stringify(rootMode)}, ${hasRuntimes ? `${serializedRuntimeIds}, ` : ""}async () => { const { ${entry.exportName ?? "default"}: initializer } = await import(${JSON.stringify(entry.moduleSpecifier)}); return ${dynamicWrapper}; })`
2813
2975
  );
2814
2976
  }
2977
+ if (interactiveMarkdownComponents.length > 0) {
2978
+ pageInitializers.push("mountMarkdownComponents(root)");
2979
+ }
2815
2980
  const runtimeSupport = hasRuntimes ? `const pluginRuntimeRegistry = new InteractiveRuntimeRegistry();
2816
2981
  const pluginRuntimeLoads = new Map();
2817
2982
  const pluginRuntimeEntries = {
@@ -2850,17 +3015,43 @@ function createPluginRuntimeHost(root, ids) {
2850
3015
  return `${imports.join("\n")}
2851
3016
 
2852
3017
  const lifecycle = new ClientLifecycle();
2853
- ${runtimeSupport}let stopSpaNavigation;
3018
+ ${runtimeSupport}const clientModuleDevelopment = ${development ? "true" : "false"};
3019
+ const conditionalInitializerLoads = new Map();
3020
+ const warnedConditionalMarkers = new Set();
3021
+ let stopSpaNavigation;
3022
+
3023
+ function resolveClientEntryRoot(scope, pageRoot, rootMode) {
3024
+ return scope === "app" || rootMode === "document" ? document : pageRoot;
3025
+ }
2854
3026
 
2855
3027
  function mountPluginClientInitializer(scope, name, root, config, ${hasRuntimes ? "runtimeIds, " : ""}initialize) {
2856
3028
  void lifecycle.mount({ scope, name, root, config, ${hasRuntimes ? "runtimes: createPluginRuntimeHost(root, runtimeIds), " : ""}initialize }).catch((error) => console.error("[riebeckite] Client initializer failed: " + name, error));
2857
3029
  }
2858
3030
 
2859
- function mountConditionalPluginClientInitializer(scope, name, root, config, presenceSelector, ${hasRuntimes ? "runtimeIds, " : ""}load) {
2860
- if (!root.querySelector(presenceSelector)) return;
2861
- void load().then((initialize) => {
3031
+ function loadConditionalPluginClientInitializer(name, load) {
3032
+ let pending = conditionalInitializerLoads.get(name);
3033
+ if (!pending) {
3034
+ pending = load().catch((error) => {
3035
+ conditionalInitializerLoads.delete(name);
3036
+ throw error;
3037
+ });
3038
+ conditionalInitializerLoads.set(name, pending);
3039
+ }
3040
+ return pending;
3041
+ }
3042
+
3043
+ function mountConditionalPluginClientInitializer(scope, name, pageRoot, config, presenceSelector, rootMode, ${hasRuntimes ? "runtimeIds, " : ""}load) {
3044
+ const marker = document.querySelector(presenceSelector);
3045
+ if (!marker) return;
3046
+ const root = resolveClientEntryRoot(scope, pageRoot, rootMode);
3047
+ if (clientModuleDevelopment && scope === "page" && "contains" in root && !root.contains(marker) && !warnedConditionalMarkers.has(name)) {
3048
+ warnedConditionalMarkers.add(name);
3049
+ console.warn('[riebeckite] Client initializer "' + name + '" has a presence marker outside its page root; set root: "document" or use context.marker.');
3050
+ }
3051
+ void loadConditionalPluginClientInitializer(name, load).then((initialize) => {
3052
+ if (!marker.isConnected) return;
2862
3053
  if ("isConnected" in root && !root.isConnected) return;
2863
- void lifecycle.mount({ scope, name, root, config, ${hasRuntimes ? "runtimes: createPluginRuntimeHost(root, runtimeIds), " : ""}initialize }).catch((error) => console.error("[riebeckite] Client initializer failed: " + name, error));
3054
+ void lifecycle.mount({ scope, name, root, marker, config, ${hasRuntimes ? "runtimes: createPluginRuntimeHost(root, runtimeIds), " : ""}initialize }).catch((error) => console.error("[riebeckite] Client initializer failed: " + name, error));
2864
3055
  }, (error) => console.error("[riebeckite] Client initializer module failed: " + name, error));
2865
3056
  }
2866
3057
 
@@ -2868,13 +3059,47 @@ function mountAppClientInitializers(root) {
2868
3059
  ${appInitializers.map((initializer) => ` ${initializer};`).join("\n")}
2869
3060
  }
2870
3061
 
3062
+ function mountAppConditionalClientInitializers(root) {
3063
+ ${appConditionalInitializers.map((initializer) => ` ${initializer};`).join("\n")}
3064
+ }
3065
+
2871
3066
  function mountPageClientInitializers(root) {
2872
3067
  ${pageInitializers.map((initializer) => ` ${initializer};`).join("\n")}
2873
3068
  }
2874
3069
 
3070
+ ${interactiveMarkdownComponents.length === 0 ? "" : `function mountMarkdownComponents(root) {
3071
+ mountPluginClientInitializer("page", "plugin-markdown-components", root, undefined, ${hasRuntimes ? "[], " : ""}async (context) => {
3072
+ const roots = [...context.root.querySelectorAll("[data-riebeckite-component-interactive]")];
3073
+ const results = await Promise.allSettled(roots.map(async (element) => {
3074
+ const name = element.getAttribute("data-riebeckite-component");
3075
+ const props = element.getAttribute("data-riebeckite-component-props");
3076
+ if (!name || props === null) return undefined;
3077
+ const entry = markdownComponentEntries[name];
3078
+ if (!entry) return undefined;
3079
+ const module = await entry.load();
3080
+ const Component = module[entry.exportName];
3081
+ if (typeof Component !== "function" || context.signal.aborted || !element.isConnected) return undefined;
3082
+ return hydrateRoot(element, jsx(Component, JSON.parse(props)));
3083
+ }));
3084
+ const cleanups = results.flatMap((result) => {
3085
+ if (result.status === "fulfilled") return result.value ? [result.value] : [];
3086
+ console.error("[riebeckite] Markdown component failed", result.reason);
3087
+ return [];
3088
+ });
3089
+ return () => cleanups.forEach((root) => root.unmount());
3090
+ });
3091
+ }
3092
+
3093
+ const markdownComponentEntries = {
3094
+ ${interactiveMarkdownComponents.map(
3095
+ (component) => ` ${JSON.stringify(component.name)}: { exportName: ${JSON.stringify(component.client?.exportName ?? "default")}, load: () => import(${JSON.stringify(component.client?.moduleSpecifier)}) }`
3096
+ ).join(",\n")}
3097
+ };`}
3098
+
2875
3099
  export function initRiebeckiteClient() {
2876
3100
  mountAppClientInitializers(document);
2877
3101
  mountPageClientInitializers(document.querySelector("#main-content") ?? document);
3102
+ mountAppConditionalClientInitializers(document);
2878
3103
  ${config.spa === void 0 ? "" : ` stopSpaNavigation ??= startSpaNavigation({
2879
3104
  ...${serializePublicClientConfig(config.spa)},
2880
3105
  onBeforePageCommit: () => lifecycle.unmount("page"),
@@ -2883,6 +3108,7 @@ ${config.spa === void 0 ? "" : ` stopSpaNavigation ??= startSpaNavigation({
2883
3108
  await createClient();
2884
3109
  if (signal.aborted || !root.isConnected) return;
2885
3110
  mountPageClientInitializers(root);
3111
+ mountAppConditionalClientInitializers(root);
2886
3112
  },
2887
3113
  });`}
2888
3114
  }
@@ -2890,6 +3116,7 @@ ${config.spa === void 0 ? "" : ` stopSpaNavigation ??= startSpaNavigation({
2890
3116
  export async function remountRiebeckitePage(root) {
2891
3117
  await lifecycle.unmount("page");
2892
3118
  mountPageClientInitializers(root);
3119
+ mountAppConditionalClientInitializers(root);
2893
3120
  }
2894
3121
 
2895
3122
  export async function disposeRiebeckiteClient() {
@@ -2900,6 +3127,27 @@ export async function disposeRiebeckiteClient() {
2900
3127
  `;
2901
3128
  }
2902
3129
 
3130
+ // src/client_module_part1.ts
3131
+ var clientModuleId = "virtual:riebeckite/client";
3132
+ var resolvedClientModuleId = `\0${clientModuleId}`;
3133
+ function riebeckiteClientModule(getConfig) {
3134
+ let development = false;
3135
+ return {
3136
+ name: "riebeckite-client-module",
3137
+ config(_config, environment) {
3138
+ development = environment.command === "serve";
3139
+ },
3140
+ resolveId(id) {
3141
+ if (id === clientModuleId) return resolvedClientModuleId;
3142
+ return null;
3143
+ },
3144
+ load(id) {
3145
+ if (id !== resolvedClientModuleId) return null;
3146
+ return createClientModule(getConfig(), development);
3147
+ }
3148
+ };
3149
+ }
3150
+
2903
3151
  // src/content_watch.ts
2904
3152
  import path9 from "node:path";
2905
3153
  import { isAttachmentPath, isImagePath as isImagePath2 } from "@riebeckite/core";
@@ -2912,12 +3160,15 @@ import {
2912
3160
  // src/runtime_modules.ts
2913
3161
  var riebeckiteConfigModuleId = "virtual:riebeckite/config";
2914
3162
  var riebeckiteContentModuleId = "virtual:riebeckite/content";
3163
+ var riebeckiteContentRenderersModuleId = "virtual:riebeckite/content-renderers";
2915
3164
  var runtimeModuleIds = [
2916
3165
  riebeckiteConfigModuleId,
2917
- riebeckiteContentModuleId
3166
+ riebeckiteContentModuleId,
3167
+ riebeckiteContentRenderersModuleId
2918
3168
  ];
2919
3169
  var resolvedConfigModuleId = `\0${riebeckiteConfigModuleId}`;
2920
3170
  var resolvedContentModuleId = `\0${riebeckiteContentModuleId}`;
3171
+ var resolvedContentRenderersModuleId = `\0${riebeckiteContentRenderersModuleId}`;
2921
3172
  function riebeckiteRuntimeModules(getApplication) {
2922
3173
  let development = false;
2923
3174
  return {
@@ -2928,6 +3179,8 @@ function riebeckiteRuntimeModules(getApplication) {
2928
3179
  resolveId(id) {
2929
3180
  if (id === riebeckiteConfigModuleId) return resolvedConfigModuleId;
2930
3181
  if (id === riebeckiteContentModuleId) return resolvedContentModuleId;
3182
+ if (id === riebeckiteContentRenderersModuleId)
3183
+ return resolvedContentRenderersModuleId;
2931
3184
  return null;
2932
3185
  },
2933
3186
  load(id) {
@@ -2937,10 +3190,61 @@ function riebeckiteRuntimeModules(getApplication) {
2937
3190
  }
2938
3191
  if (id === resolvedContentModuleId)
2939
3192
  return createContentModule(development);
3193
+ if (id === resolvedContentRenderersModuleId)
3194
+ return createContentRenderersModule(getApplication().config);
2940
3195
  return null;
2941
3196
  }
2942
3197
  };
2943
3198
  }
3199
+ function createContentRenderersModule(config) {
3200
+ const formats = config.plugins.flatMap(
3201
+ (plugin) => plugin.contentFormats ?? []
3202
+ );
3203
+ const renderers = formats.filter((format) => format.rendererModule);
3204
+ const imports = renderers.map(
3205
+ (format, index) => `import renderer${index} from ${JSON.stringify(format.rendererModule)};`
3206
+ ).join("\n");
3207
+ const entries = renderers.map(
3208
+ (format, index) => `{ extension: ${JSON.stringify(format.extension)}, renderer: renderer${index}, options: formats[${formats.indexOf(format)}]?.rendererOptions }`
3209
+ ).join(",\n");
3210
+ return `import { prepareMarkdownComponent } from "@riebeckite/core";
3211
+ import { jsx } from "hono/jsx/jsx-runtime";
3212
+ import { config } from ${JSON.stringify(riebeckiteConfigModuleId)};
3213
+ ${imports}
3214
+ const formats = config.plugins.flatMap((plugin) => plugin.contentFormats ?? []);
3215
+ const renderers = [${entries}];
3216
+ const markdownComponents = config.plugins.flatMap((plugin) => plugin.markdownComponents ?? []);
3217
+
3218
+ function createMarkdownComponent(component) {
3219
+ return async (props) => {
3220
+ const prepared = await prepareMarkdownComponent(
3221
+ component,
3222
+ props && typeof props === "object" ? props : {},
3223
+ );
3224
+ return jsx("div", {
3225
+ "data-riebeckite-component": prepared.name,
3226
+ "data-riebeckite-component-props": prepared.props,
3227
+ ...(prepared.interactive ? { "data-riebeckite-component-interactive": "true" } : {}),
3228
+ dangerouslySetInnerHTML: { __html: prepared.content },
3229
+ });
3230
+ };
3231
+ }
3232
+
3233
+ const registeredComponents = Object.fromEntries(
3234
+ markdownComponents.map((component) => [component.name, createMarkdownComponent(component)]),
3235
+ );
3236
+
3237
+ export function renderContent(sourcePath) {
3238
+ const entry = renderers.find((renderer) => sourcePath.toLowerCase().endsWith(renderer.extension));
3239
+ if (!entry) return undefined;
3240
+ const options = entry.options && typeof entry.options === "object" ? entry.options : {};
3241
+ return entry.renderer(sourcePath, {
3242
+ ...options,
3243
+ components: { ...registeredComponents, ...(options.components ?? {}) },
3244
+ });
3245
+ }
3246
+ `;
3247
+ }
2944
3248
  function isRiebeckiteRuntimeModuleId(id) {
2945
3249
  if (!id) return false;
2946
3250
  return runtimeModuleIds.some(
@@ -3072,11 +3376,47 @@ function suppressRestartOnContentEvents(server, isContentFile) {
3072
3376
  }
3073
3377
  }
3074
3378
 
3379
+ // src/vite_plugin_helpers.ts
3380
+ import path10 from "node:path";
3381
+ var defaultSsrExternals = [
3382
+ "hono",
3383
+ "hono/html",
3384
+ "hono/jsx",
3385
+ "hono/jsx/jsx-runtime",
3386
+ "extend",
3387
+ "debug",
3388
+ "node:fs/promises",
3389
+ "node:path",
3390
+ "parse-numeric-range",
3391
+ "slugify",
3392
+ "vfile-matter",
3393
+ "yaml"
3394
+ ];
3395
+ function isBareImport(source) {
3396
+ return !source.startsWith(".") && !path10.isAbsolute(source) && !source.startsWith("\0") && !source.startsWith("node:");
3397
+ }
3398
+ function isInDirectory2(filePath, directory) {
3399
+ const relative5 = path10.relative(directory, filePath);
3400
+ return relative5 !== "" && !relative5.startsWith("..") && !path10.isAbsolute(relative5);
3401
+ }
3402
+ async function callPluginHook(hook, context, ...arguments_) {
3403
+ const handler = typeof hook === "function" ? hook : typeof hook === "object" && hook !== null && "handler" in hook ? hook.handler : void 0;
3404
+ return typeof handler === "function" ? handler.call(context, ...arguments_) : void 0;
3405
+ }
3406
+ function callPluginHookSynchronously(hook, context) {
3407
+ const handler = typeof hook === "function" ? hook : typeof hook === "object" && hook !== null && "handler" in hook ? hook.handler : void 0;
3408
+ return typeof handler === "function" ? handler.call(context, context) : void 0;
3409
+ }
3410
+
3075
3411
  // src/vite_runner.ts
3076
- import fs7 from "node:fs/promises";
3412
+ import fs8 from "node:fs/promises";
3077
3413
  import os from "node:os";
3078
- import path10 from "node:path";
3414
+ import path12 from "node:path";
3079
3415
  import { build as build2, createServer } from "vite";
3416
+
3417
+ // src/vite_runner_helpers.ts
3418
+ import fs7 from "node:fs/promises";
3419
+ import path11 from "node:path";
3080
3420
  var viteConfigFileNames = [
3081
3421
  "vite.config.ts",
3082
3422
  "vite.config.js",
@@ -3090,6 +3430,66 @@ var ignoredApplicationRootDirectoryNames = /* @__PURE__ */ new Set([
3090
3430
  "tests",
3091
3431
  "templates"
3092
3432
  ]);
3433
+ var HonoxApplicationRootError = class extends Error {
3434
+ constructor(message) {
3435
+ super(message);
3436
+ this.name = "HonoxApplicationRootError";
3437
+ }
3438
+ };
3439
+ async function findWorkspaceRoot2(configRoot) {
3440
+ try {
3441
+ const workspaceConfig = await fs7.readFile(
3442
+ path11.join(configRoot, "pnpm-workspace.yaml"),
3443
+ "utf8"
3444
+ );
3445
+ return /^packages\s*:/m.test(workspaceConfig) ? configRoot : void 0;
3446
+ } catch {
3447
+ return void 0;
3448
+ }
3449
+ }
3450
+ async function canReuseClientBuild(input) {
3451
+ const root = path11.resolve(input.root);
3452
+ const cache = await loadOutputCacheMetadata(
3453
+ path11.join(root, ".riebeckite", "ssg-output-cache.json")
3454
+ );
3455
+ if (!cache?.bundleFingerprint || !cache.configFile) return false;
3456
+ if (cache.bundleFingerprint !== await computeBundleFingerprint(root, cache.configFile)) {
3457
+ return false;
3458
+ }
3459
+ return await verifyClientBuildArtifacts({
3460
+ outDir: input.outputDirectory,
3461
+ expectedInventory: cache.finalOutputInventory ?? {}
3462
+ });
3463
+ }
3464
+ async function reportSsgTimings(tracer, metricsFile) {
3465
+ try {
3466
+ const metrics = JSON.parse(await fs7.readFile(metricsFile, "utf8"));
3467
+ if (!metrics || typeof metrics !== "object") return;
3468
+ const timings = metrics.timingsMs;
3469
+ if (!timings || typeof timings !== "object") return;
3470
+ for (const [name, durationMs] of Object.entries(timings)) {
3471
+ if (typeof durationMs !== "number" || !Number.isFinite(durationMs))
3472
+ continue;
3473
+ tracer.event("integration.timing", {
3474
+ name: `integration.honox.server_build.ssg.${name}`,
3475
+ durationMs
3476
+ });
3477
+ }
3478
+ } catch {
3479
+ }
3480
+ }
3481
+ async function withWorkingDirectory(root, task) {
3482
+ const previousDirectory = process.cwd();
3483
+ if (previousDirectory === root) return await task();
3484
+ process.chdir(root);
3485
+ try {
3486
+ return await task();
3487
+ } finally {
3488
+ process.chdir(previousDirectory);
3489
+ }
3490
+ }
3491
+
3492
+ // src/vite_runner.ts
3093
3493
  async function resolveHonoxApplicationRoot(configRoot, startDirectory) {
3094
3494
  const roots = await findViteApplicationRoots(configRoot, startDirectory);
3095
3495
  if (roots.length === 1) return roots[0];
@@ -3102,17 +3502,11 @@ async function resolveHonoxApplicationRoot(configRoot, startDirectory) {
3102
3502
  `Found multiple Vite applications under ${configRoot}: ${roots.join(", ")}.`
3103
3503
  );
3104
3504
  }
3105
- var HonoxApplicationRootError = class extends Error {
3106
- constructor(message) {
3107
- super(message);
3108
- this.name = "HonoxApplicationRootError";
3109
- }
3110
- };
3111
3505
  async function resolveHonoxApplication(options) {
3112
- const configRoot = path10.resolve(options.configRoot);
3113
- const appRoot = options.appRoot ? path10.resolve(options.appRoot) : await resolveHonoxApplicationRoot(configRoot, options.startDirectory);
3506
+ const configRoot = path12.resolve(options.configRoot);
3507
+ const appRoot = options.appRoot ? path12.resolve(options.appRoot) : await resolveHonoxApplicationRoot(configRoot, options.startDirectory);
3114
3508
  const workspaceRoot = options.workspaceRoot ?? await findWorkspaceRoot2(configRoot);
3115
- const configFile = path10.resolve(
3509
+ const configFile = path12.resolve(
3116
3510
  configRoot,
3117
3511
  options.configFile ?? "riebeckite.config.ts"
3118
3512
  );
@@ -3130,19 +3524,8 @@ async function resolveHonoxApplication(options) {
3130
3524
  contentRoot: config.content.directory
3131
3525
  };
3132
3526
  }
3133
- async function findWorkspaceRoot2(configRoot) {
3134
- try {
3135
- const workspaceConfig = await fs7.readFile(
3136
- path10.join(configRoot, "pnpm-workspace.yaml"),
3137
- "utf8"
3138
- );
3139
- return /^packages\s*:/m.test(workspaceConfig) ? configRoot : void 0;
3140
- } catch {
3141
- return void 0;
3142
- }
3143
- }
3144
3527
  async function startHonoxDevServer(options) {
3145
- const root = path10.resolve(options.root);
3528
+ const root = path12.resolve(options.root);
3146
3529
  await withWorkingDirectory(root, async () => {
3147
3530
  const previousBridgeToken = process.env.RIEBECKITE_BRIDGE_TOKEN;
3148
3531
  if (options.bridgeToken) {
@@ -3160,12 +3543,12 @@ async function startHonoxDevServer(options) {
3160
3543
  }
3161
3544
  })();
3162
3545
  const restartFiles = new Set(
3163
- options.restartOnChange?.map((file) => path10.resolve(file))
3546
+ options.restartOnChange?.map((file) => path12.resolve(file))
3164
3547
  );
3165
3548
  if (restartFiles.size > 0) {
3166
3549
  server.watcher.add([...restartFiles]);
3167
3550
  server.watcher.on("change", (file) => {
3168
- if (!restartFiles.has(path10.resolve(file))) return;
3551
+ if (!restartFiles.has(path12.resolve(file))) return;
3169
3552
  void (async () => {
3170
3553
  await options.onRestart?.();
3171
3554
  await server.restart();
@@ -3194,9 +3577,9 @@ async function startHonoxDevServer(options) {
3194
3577
  });
3195
3578
  }
3196
3579
  async function buildHonoxApplication(options) {
3197
- const root = path10.resolve(options.root);
3580
+ const root = path12.resolve(options.root);
3198
3581
  await withWorkingDirectory(root, async () => {
3199
- const clientOutputDirectory = path10.join(
3582
+ const clientOutputDirectory = path12.join(
3200
3583
  root,
3201
3584
  ".riebeckite",
3202
3585
  "build-output-client"
@@ -3208,28 +3591,28 @@ async function buildHonoxApplication(options) {
3208
3591
  () => build2({ root, mode: "client" })
3209
3592
  );
3210
3593
  }
3211
- const stableClientDirectory = path10.join(
3594
+ const stableClientDirectory = path12.join(
3212
3595
  root,
3213
3596
  ".riebeckite",
3214
3597
  "client-build"
3215
3598
  );
3216
- await fs7.rm(stableClientDirectory, { recursive: true, force: true });
3217
- const sourceManifest = options.reuseClientBuild ? path10.join(
3218
- path10.resolve(options.outputDirectory ?? path10.join(root, "dist")),
3599
+ await fs8.rm(stableClientDirectory, { recursive: true, force: true });
3600
+ const sourceManifest = options.reuseClientBuild ? path12.join(
3601
+ path12.resolve(options.outputDirectory ?? path12.join(root, "dist")),
3219
3602
  ".vite",
3220
3603
  "manifest.json"
3221
- ) : path10.join(clientOutputDirectory, ".vite", "manifest.json");
3604
+ ) : path12.join(clientOutputDirectory, ".vite", "manifest.json");
3222
3605
  try {
3223
- await fs7.mkdir(path10.join(stableClientDirectory, ".vite"), {
3606
+ await fs8.mkdir(path12.join(stableClientDirectory, ".vite"), {
3224
3607
  recursive: true
3225
3608
  });
3226
- await fs7.copyFile(
3609
+ await fs8.copyFile(
3227
3610
  sourceManifest,
3228
- path10.join(stableClientDirectory, ".vite", "manifest.json")
3611
+ path12.join(stableClientDirectory, ".vite", "manifest.json")
3229
3612
  );
3230
3613
  } catch (error) {
3231
3614
  if (error.code !== "ENOENT") throw error;
3232
- await fs7.rm(stableClientDirectory, { recursive: true, force: true });
3615
+ await fs8.rm(stableClientDirectory, { recursive: true, force: true });
3233
3616
  }
3234
3617
  await runTraced(
3235
3618
  options.tracer,
@@ -3240,28 +3623,14 @@ async function buildHonoxApplication(options) {
3240
3623
  );
3241
3624
  });
3242
3625
  }
3243
- async function canReuseClientBuild(input) {
3244
- const root = path10.resolve(input.root);
3245
- const cache = await loadOutputCacheMetadata(
3246
- path10.join(root, ".riebeckite", "ssg-output-cache.json")
3247
- );
3248
- if (!cache?.bundleFingerprint || !cache.configFile) return false;
3249
- if (cache.bundleFingerprint !== await computeBundleFingerprint(root, cache.configFile)) {
3250
- return false;
3251
- }
3252
- return await verifyClientBuildArtifacts({
3253
- outDir: input.outputDirectory,
3254
- expectedInventory: cache.finalOutputInventory ?? {}
3255
- });
3256
- }
3257
3626
  async function buildServerWithMetrics(root, tracer, plugins = []) {
3258
3627
  if (!tracer) {
3259
3628
  await build2({ root, plugins });
3260
3629
  return;
3261
3630
  }
3262
3631
  const previousMetricsFile = process.env.RIEBECKITE_SSG_METRICS_FILE;
3263
- const metricsDirectory = previousMetricsFile ? void 0 : await fs7.mkdtemp(path10.join(os.tmpdir(), "riebeckite-ssg-metrics-"));
3264
- const metricsFile = previousMetricsFile ?? path10.join(metricsDirectory, "metrics.json");
3632
+ const metricsDirectory = previousMetricsFile ? void 0 : await fs8.mkdtemp(path12.join(os.tmpdir(), "riebeckite-ssg-metrics-"));
3633
+ const metricsFile = previousMetricsFile ?? path12.join(metricsDirectory, "metrics.json");
3265
3634
  if (!previousMetricsFile)
3266
3635
  process.env.RIEBECKITE_SSG_METRICS_FILE = metricsFile;
3267
3636
  try {
@@ -3272,50 +3641,23 @@ async function buildServerWithMetrics(root, tracer, plugins = []) {
3272
3641
  delete process.env.RIEBECKITE_SSG_METRICS_FILE;
3273
3642
  }
3274
3643
  if (metricsDirectory)
3275
- await fs7.rm(metricsDirectory, { recursive: true, force: true });
3276
- }
3277
- }
3278
- async function reportSsgTimings(tracer, metricsFile) {
3279
- try {
3280
- const metrics = JSON.parse(await fs7.readFile(metricsFile, "utf8"));
3281
- if (!metrics || typeof metrics !== "object") return;
3282
- const timings = metrics.timingsMs;
3283
- if (!timings || typeof timings !== "object") return;
3284
- for (const [name, durationMs] of Object.entries(timings)) {
3285
- if (typeof durationMs !== "number" || !Number.isFinite(durationMs))
3286
- continue;
3287
- tracer.event("integration.timing", {
3288
- name: `integration.honox.server_build.ssg.${name}`,
3289
- durationMs
3290
- });
3291
- }
3292
- } catch {
3293
- }
3294
- }
3295
- async function withWorkingDirectory(root, task) {
3296
- const previousDirectory = process.cwd();
3297
- if (previousDirectory === root) return await task();
3298
- process.chdir(root);
3299
- try {
3300
- return await task();
3301
- } finally {
3302
- process.chdir(previousDirectory);
3644
+ await fs8.rm(metricsDirectory, { recursive: true, force: true });
3303
3645
  }
3304
3646
  }
3305
3647
  async function runTraced(tracer, name, buildTask) {
3306
3648
  return tracer ? await tracer.span(name, {}, buildTask) : await buildTask();
3307
3649
  }
3308
3650
  function waitForShutdown(server) {
3309
- let resolve5 = () => {
3651
+ let resolve7 = () => {
3310
3652
  };
3311
3653
  let closing = false;
3312
3654
  const close = () => {
3313
3655
  if (closing) return;
3314
3656
  closing = true;
3315
- void server.close().finally(resolve5);
3657
+ void server.close().finally(resolve7);
3316
3658
  };
3317
3659
  const promise = new Promise((resolvePromise) => {
3318
- resolve5 = resolvePromise;
3660
+ resolve7 = resolvePromise;
3319
3661
  });
3320
3662
  process.once("SIGINT", close);
3321
3663
  process.once("SIGTERM", close);
@@ -3337,34 +3679,34 @@ async function findViteApplicationRoots(root, startDirectory) {
3337
3679
  const directory = directories.pop();
3338
3680
  if (!directory) continue;
3339
3681
  if (await hasViteConfig(directory)) applicationRoots.push(directory);
3340
- const entries = await fs7.readdir(directory, { withFileTypes: true });
3682
+ const entries = await fs8.readdir(directory, { withFileTypes: true });
3341
3683
  for (const entry of entries) {
3342
3684
  if (!entry.isDirectory() || ignoredApplicationRootDirectoryNames.has(entry.name)) {
3343
3685
  continue;
3344
3686
  }
3345
- directories.push(path10.join(directory, entry.name));
3687
+ directories.push(path12.join(directory, entry.name));
3346
3688
  }
3347
3689
  }
3348
3690
  return applicationRoots;
3349
3691
  }
3350
3692
  async function findViteApplicationRootFrom(startDirectory, configRoot) {
3351
- let directory = path10.resolve(startDirectory);
3693
+ let directory = path12.resolve(startDirectory);
3352
3694
  while (isWithin(configRoot, directory)) {
3353
3695
  if (await hasViteConfig(directory)) return directory;
3354
- const parent = path10.dirname(directory);
3696
+ const parent = path12.dirname(directory);
3355
3697
  if (parent === directory) return void 0;
3356
3698
  directory = parent;
3357
3699
  }
3358
3700
  return void 0;
3359
3701
  }
3360
3702
  function isWithin(parent, target) {
3361
- const relative5 = path10.relative(parent, target);
3362
- return relative5 === "" || !relative5.startsWith("..") && !path10.isAbsolute(relative5);
3703
+ const relative5 = path12.relative(parent, target);
3704
+ return relative5 === "" || !relative5.startsWith("..") && !path12.isAbsolute(relative5);
3363
3705
  }
3364
3706
  async function hasViteConfig(directory) {
3365
3707
  for (const fileName of viteConfigFileNames) {
3366
3708
  try {
3367
- if ((await fs7.stat(path10.join(directory, fileName))).isFile()) return true;
3709
+ if ((await fs8.stat(path12.join(directory, fileName))).isFile()) return true;
3368
3710
  } catch {
3369
3711
  }
3370
3712
  }
@@ -3372,23 +3714,10 @@ async function hasViteConfig(directory) {
3372
3714
  }
3373
3715
 
3374
3716
  // src/vite_plugin.ts
3375
- var defaultSsrExternals = [
3376
- "hono",
3377
- "hono/html",
3378
- "hono/jsx",
3379
- "hono/jsx/jsx-runtime",
3380
- "extend",
3381
- "debug",
3382
- "node:fs/promises",
3383
- "node:path",
3384
- "parse-numeric-range",
3385
- "slugify",
3386
- "vfile-matter",
3387
- "yaml"
3388
- ];
3389
3717
  function riebeckite(options = {}, onApplicationResolved) {
3390
3718
  let resolvedConfig;
3391
3719
  let application;
3720
+ let contentVitePlugins = [];
3392
3721
  const getConfig = () => {
3393
3722
  if (!resolvedConfig) {
3394
3723
  throw new Error("Riebeckite config has not been loaded yet.");
@@ -3399,7 +3728,7 @@ function riebeckite(options = {}, onApplicationResolved) {
3399
3728
  {
3400
3729
  name: "riebeckite-host-integration",
3401
3730
  async config(userConfig) {
3402
- const root = userConfig.root ? path11.resolve(userConfig.root) : process.cwd();
3731
+ const root = userConfig.root ? path13.resolve(userConfig.root) : process.cwd();
3403
3732
  const appRoot = options.appRoot ?? root;
3404
3733
  const resolvedApplication = await resolveHonoxApplication({
3405
3734
  configRoot: options.configRoot ?? appRoot,
@@ -3408,15 +3737,21 @@ function riebeckite(options = {}, onApplicationResolved) {
3408
3737
  workspaceRoot: options.workspaceRoot
3409
3738
  });
3410
3739
  resolvedConfig = resolvedApplication.config;
3740
+ const resolved = resolvedConfig;
3741
+ contentVitePlugins = resolved.plugins.flatMap(
3742
+ (plugin) => plugin.vitePlugins?.({
3743
+ contentDirectory: resolved.content.directory
3744
+ }) ?? []
3745
+ );
3411
3746
  application = resolvedApplication;
3412
3747
  onApplicationResolved?.(resolvedApplication);
3413
3748
  writeRiebeckiteAssetEntries(resolvedConfig, {
3414
- frameworkStyles: path11.join(
3749
+ frameworkStyles: path13.join(
3415
3750
  appRoot,
3416
3751
  "app/.riebeckite/framework-styles.css"
3417
3752
  ),
3418
- pluginStyles: path11.join(appRoot, "app/.riebeckite/plugin-styles.css"),
3419
- themeStyles: path11.join(appRoot, "app/.riebeckite/theme-styles.css")
3753
+ pluginStyles: path13.join(appRoot, "app/.riebeckite/plugin-styles.css"),
3754
+ themeStyles: path13.join(appRoot, "app/.riebeckite/theme-styles.css")
3420
3755
  });
3421
3756
  return {
3422
3757
  define: {
@@ -3439,6 +3774,8 @@ function riebeckite(options = {}, onApplicationResolved) {
3439
3774
  };
3440
3775
  }
3441
3776
  },
3777
+ contentVitePluginBridge(() => contentVitePlugins),
3778
+ contentBareImportResolver(() => requireApplication(application)),
3442
3779
  riebeckiteClientModule(getConfig),
3443
3780
  riebeckiteRuntimeModules(() => requireApplication(application)),
3444
3781
  riebeckiteContentAssets({
@@ -3467,6 +3804,7 @@ function riebeckite(options = {}, onApplicationResolved) {
3467
3804
  mutationToken: process.env.RIEBECKITE_BRIDGE_MUTATION_TOKEN,
3468
3805
  mutationApprovalToken: process.env.RIEBECKITE_BRIDGE_MUTATION_APPROVAL_TOKEN,
3469
3806
  contentRoot: () => requireApplication(application).contentRoot,
3807
+ contentFormats: () => createContentFormatRegistry(getConfig().plugins),
3470
3808
  publicOrigin: () => getConfig().site.baseUrl || void 0,
3471
3809
  async getSnapshot(server) {
3472
3810
  const { appRoot } = requireApplication(application);
@@ -3477,6 +3815,94 @@ function riebeckite(options = {}, onApplicationResolved) {
3477
3815
  })
3478
3816
  ];
3479
3817
  }
3818
+ function contentBareImportResolver(getApplication) {
3819
+ return {
3820
+ name: "riebeckite-content-bare-imports",
3821
+ async resolveId(source, importer) {
3822
+ if (!importer || !isBareImport(source)) return null;
3823
+ const { appRoot, contentRoot } = getApplication();
3824
+ if (!isInDirectory2(importer, contentRoot)) return null;
3825
+ return await this.resolve(source, path13.join(appRoot, "package.json"), {
3826
+ skipSelf: true
3827
+ });
3828
+ }
3829
+ };
3830
+ }
3831
+ function contentVitePluginBridge(getPlugins) {
3832
+ return {
3833
+ name: "riebeckite-content-vite-plugins",
3834
+ async config(config, environment) {
3835
+ let result;
3836
+ for (const plugin of getPlugins()) {
3837
+ const next = await callPluginHook(
3838
+ plugin.config,
3839
+ this,
3840
+ config,
3841
+ environment
3842
+ );
3843
+ if (next !== void 0) {
3844
+ result = mergeConfig(result ?? {}, next);
3845
+ }
3846
+ }
3847
+ return result;
3848
+ },
3849
+ async resolveId(source, importer, options) {
3850
+ for (const plugin of getPlugins()) {
3851
+ const result = await callPluginHook(
3852
+ plugin.resolveId,
3853
+ this,
3854
+ source,
3855
+ importer,
3856
+ options
3857
+ );
3858
+ if (result != null) return result;
3859
+ }
3860
+ return null;
3861
+ },
3862
+ async load(id, options) {
3863
+ for (const plugin of getPlugins()) {
3864
+ const result = await callPluginHook(plugin.load, this, id, options);
3865
+ if (result != null) return result;
3866
+ }
3867
+ return null;
3868
+ },
3869
+ async transform(code, id, options) {
3870
+ let current = code;
3871
+ let map;
3872
+ let transformed = false;
3873
+ for (const plugin of getPlugins()) {
3874
+ const result = await callPluginHook(
3875
+ plugin.transform,
3876
+ this,
3877
+ current,
3878
+ id,
3879
+ options
3880
+ );
3881
+ if (result == null) continue;
3882
+ if (typeof result === "string") {
3883
+ current = result;
3884
+ map = null;
3885
+ transformed = true;
3886
+ continue;
3887
+ }
3888
+ const next = result;
3889
+ if (typeof next.code !== "string") continue;
3890
+ current = next.code;
3891
+ map = next.map;
3892
+ transformed = true;
3893
+ }
3894
+ return transformed ? { code: current, map } : null;
3895
+ },
3896
+ configureServer(server) {
3897
+ const postHooks = getPlugins().map(
3898
+ (plugin) => callPluginHookSynchronously(plugin.configureServer, server)
3899
+ ).filter((hook) => typeof hook === "function");
3900
+ return () => {
3901
+ for (const hook of postHooks) hook();
3902
+ };
3903
+ }
3904
+ };
3905
+ }
3480
3906
  function requireApplication(application) {
3481
3907
  if (!application) {
3482
3908
  throw new Error("Riebeckite application has not been resolved yet.");