@conloca/content-api 0.1.14 → 0.1.16

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 (183) hide show
  1. package/dist/asset-manifest.d.ts +23 -0
  2. package/dist/asset-manifest.d.ts.map +1 -0
  3. package/dist/asset-manifest.js +73 -0
  4. package/dist/asset-operations.d.ts +159 -0
  5. package/dist/asset-operations.d.ts.map +1 -0
  6. package/dist/asset-operations.js +736 -0
  7. package/dist/asset-types.d.ts +56 -0
  8. package/dist/asset-types.d.ts.map +1 -0
  9. package/dist/asset-types.js +7 -0
  10. package/dist/base-content-index.d.ts +57 -0
  11. package/dist/base-content-index.d.ts.map +1 -0
  12. package/dist/base-content-index.js +179 -0
  13. package/dist/block-index.d.ts +9 -0
  14. package/dist/block-index.d.ts.map +1 -0
  15. package/dist/block-index.js +11 -0
  16. package/dist/blocks.d.ts +16 -0
  17. package/dist/blocks.d.ts.map +1 -0
  18. package/dist/blocks.js +103 -0
  19. package/dist/cf-access.d.ts +31 -0
  20. package/dist/cf-access.d.ts.map +1 -0
  21. package/dist/cf-access.js +66 -0
  22. package/dist/component-registry.d.ts +50 -0
  23. package/dist/component-registry.d.ts.map +1 -0
  24. package/dist/component-registry.js +120 -0
  25. package/dist/component-registry.types-C0ctF9nh.d.mts +71 -0
  26. package/dist/component-registry.types-C0ctF9nh.d.mts.map +1 -0
  27. package/dist/component-registry.types.d.ts +11 -0
  28. package/dist/component-registry.types.d.ts.map +1 -0
  29. package/dist/component-registry.types.js +1 -0
  30. package/dist/content-api.interface.d.ts +64 -0
  31. package/dist/content-api.interface.d.ts.map +1 -0
  32. package/dist/content-api.interface.js +1 -0
  33. package/dist/content-filters.d.ts +31 -0
  34. package/dist/content-filters.d.ts.map +1 -0
  35. package/dist/content-filters.js +246 -0
  36. package/dist/content-index-D092_vk1.mjs +629 -0
  37. package/dist/content-index-D092_vk1.mjs.map +1 -0
  38. package/dist/content-index-D6IVMmAB.d.mts +127 -0
  39. package/dist/content-index-D6IVMmAB.d.mts.map +1 -0
  40. package/dist/content-index.d.ts +126 -0
  41. package/dist/content-index.d.ts.map +1 -0
  42. package/dist/content-index.js +418 -0
  43. package/dist/content-operations-DIbsxG5A.d.mts +354 -0
  44. package/dist/content-operations-DIbsxG5A.d.mts.map +1 -0
  45. package/dist/content-operations.d.ts +93 -0
  46. package/dist/content-operations.d.ts.map +1 -0
  47. package/dist/content-operations.js +275 -0
  48. package/dist/content-reader.d.ts +10 -0
  49. package/dist/content-reader.d.ts.map +1 -0
  50. package/dist/content-reader.js +13 -0
  51. package/dist/content-utils-fWNHTrPy.mjs +280 -0
  52. package/dist/content-utils-fWNHTrPy.mjs.map +1 -0
  53. package/dist/content-utils.d.ts +132 -0
  54. package/dist/content-utils.d.ts.map +1 -0
  55. package/dist/content-utils.js +352 -0
  56. package/dist/content-watcher.d.ts +43 -0
  57. package/dist/content-watcher.d.ts.map +1 -0
  58. package/dist/content-watcher.js +83 -0
  59. package/dist/data-DquNIEnQ.mjs +62 -0
  60. package/dist/data-DquNIEnQ.mjs.map +1 -0
  61. package/dist/data-index.d.ts +8 -0
  62. package/dist/data-index.d.ts.map +1 -0
  63. package/dist/data-index.js +7 -0
  64. package/dist/data.d.ts +43 -0
  65. package/dist/data.d.ts.map +1 -0
  66. package/dist/data.js +103 -0
  67. package/dist/etag-utils.d.ts +77 -0
  68. package/dist/etag-utils.d.ts.map +1 -0
  69. package/dist/etag-utils.js +160 -0
  70. package/dist/filesystem-content-api-B1KIQJfk.mjs +2 -0
  71. package/dist/filesystem-content-api-C0HIhqZi.mjs +1620 -0
  72. package/dist/filesystem-content-api-C0HIhqZi.mjs.map +1 -0
  73. package/dist/filesystem-content-api-DCdNi-co.d.mts +134 -0
  74. package/dist/filesystem-content-api-DCdNi-co.d.mts.map +1 -0
  75. package/dist/filesystem-content-api.d.ts +135 -0
  76. package/dist/filesystem-content-api.d.ts.map +1 -0
  77. package/dist/filesystem-content-api.js +2181 -0
  78. package/dist/git-operations.d.ts +49 -0
  79. package/dist/git-operations.d.ts.map +1 -0
  80. package/dist/git-operations.js +252 -0
  81. package/dist/header-parser.d.ts +37 -0
  82. package/dist/header-parser.d.ts.map +1 -0
  83. package/dist/header-parser.js +286 -0
  84. package/dist/in-memory-content-api.d.ts +35 -0
  85. package/dist/in-memory-content-api.d.ts.map +1 -0
  86. package/dist/in-memory-content-api.js +591 -0
  87. package/dist/index-DxVTFK66.d.mts +105 -0
  88. package/dist/index-DxVTFK66.d.mts.map +1 -0
  89. package/dist/index.d.mts +6 -4
  90. package/dist/index.d.mts.map +1 -1
  91. package/dist/index.d.ts +19 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +16 -0
  94. package/dist/index.mjs +37 -5
  95. package/dist/index.mjs.map +1 -1
  96. package/dist/indexing.d.mts +152 -0
  97. package/dist/indexing.d.mts.map +1 -0
  98. package/dist/indexing.d.ts +5 -0
  99. package/dist/indexing.d.ts.map +1 -0
  100. package/dist/indexing.js +7 -0
  101. package/dist/indexing.mjs +255 -0
  102. package/dist/indexing.mjs.map +1 -0
  103. package/dist/json-whitespace-view.d.ts +32 -0
  104. package/dist/json-whitespace-view.d.ts.map +1 -0
  105. package/dist/json-whitespace-view.js +152 -0
  106. package/dist/middleware.d.ts +20 -0
  107. package/dist/middleware.d.ts.map +1 -0
  108. package/dist/middleware.js +1031 -0
  109. package/dist/node.d.mts +28 -126
  110. package/dist/node.d.mts.map +1 -1
  111. package/dist/node.d.ts +25 -0
  112. package/dist/node.d.ts.map +1 -0
  113. package/dist/node.js +24 -0
  114. package/dist/node.mjs +199 -2890
  115. package/dist/node.mjs.map +1 -1
  116. package/dist/reader.d.mts +15 -0
  117. package/dist/reader.d.mts.map +1 -0
  118. package/dist/reader.d.ts +15 -0
  119. package/dist/reader.d.ts.map +1 -0
  120. package/dist/reader.js +13 -0
  121. package/dist/reader.mjs +22 -0
  122. package/dist/reader.mjs.map +1 -0
  123. package/dist/schemas/index.d.mts +2 -90
  124. package/dist/schemas/index.d.ts +102 -0
  125. package/dist/schemas/index.d.ts.map +1 -0
  126. package/dist/schemas/index.js +87 -0
  127. package/dist/schemas/index.mjs +2 -70
  128. package/dist/schemas-CFRD0FIQ.mjs +84 -0
  129. package/dist/schemas-CFRD0FIQ.mjs.map +1 -0
  130. package/dist/{types-BUG0Cfkg.mjs → site-8oaj1Q60.mjs} +20 -222
  131. package/dist/site-8oaj1Q60.mjs.map +1 -0
  132. package/dist/site-index-B_254bCc.d.mts +136 -0
  133. package/dist/site-index-B_254bCc.d.mts.map +1 -0
  134. package/dist/site-index.d.ts +60 -0
  135. package/dist/site-index.d.ts.map +1 -0
  136. package/dist/site-index.js +287 -0
  137. package/dist/site.d.ts +21 -0
  138. package/dist/site.d.ts.map +1 -0
  139. package/dist/site.js +168 -0
  140. package/dist/types-DOdldbfD.mjs +34 -0
  141. package/dist/types-DOdldbfD.mjs.map +1 -0
  142. package/dist/types-DjfhS272.d.mts +456 -0
  143. package/dist/types-DjfhS272.d.mts.map +1 -0
  144. package/dist/types.d.ts +453 -0
  145. package/dist/types.d.ts.map +1 -0
  146. package/dist/types.js +36 -0
  147. package/dist/url-safe-base64.d.ts +12 -0
  148. package/dist/url-safe-base64.d.ts.map +1 -0
  149. package/dist/url-safe-base64.js +40 -0
  150. package/dist/url-validation.d.ts +14 -0
  151. package/dist/url-validation.d.ts.map +1 -0
  152. package/dist/url-validation.js +81 -0
  153. package/dist/utils/atomic-write.d.ts +6 -0
  154. package/dist/utils/atomic-write.d.ts.map +1 -0
  155. package/dist/utils/atomic-write.js +20 -0
  156. package/dist/utils.d.ts +46 -0
  157. package/dist/utils.d.ts.map +1 -0
  158. package/dist/utils.js +70 -0
  159. package/dist/vite-plugin.d.ts +12 -0
  160. package/dist/vite-plugin.d.ts.map +1 -0
  161. package/dist/vite-plugin.js +29 -0
  162. package/dist/vxjson-qHrgLGip.mjs +555 -0
  163. package/dist/vxjson-qHrgLGip.mjs.map +1 -0
  164. package/dist/vxjson-serialize-geF6qvpn.mjs +34 -0
  165. package/dist/vxjson-serialize-geF6qvpn.mjs.map +1 -0
  166. package/dist/vxjson-serialize.d.mts +17 -0
  167. package/dist/vxjson-serialize.d.mts.map +1 -0
  168. package/dist/vxjson-serialize.d.ts +14 -0
  169. package/dist/vxjson-serialize.d.ts.map +1 -0
  170. package/dist/vxjson-serialize.js +50 -0
  171. package/dist/vxjson-serialize.mjs +2 -0
  172. package/dist/vxjson.d.ts +112 -0
  173. package/dist/vxjson.d.ts.map +1 -0
  174. package/dist/vxjson.js +391 -0
  175. package/dist/xxhash.d.ts +10 -0
  176. package/dist/xxhash.d.ts.map +1 -0
  177. package/dist/xxhash.js +31 -0
  178. package/package.json +88 -17
  179. package/dist/content-operations-BZLfJWqT.d.mts +0 -916
  180. package/dist/content-operations-BZLfJWqT.d.mts.map +0 -1
  181. package/dist/schemas/index.d.mts.map +0 -1
  182. package/dist/schemas/index.mjs.map +0 -1
  183. package/dist/types-BUG0Cfkg.mjs.map +0 -1
package/dist/node.mjs CHANGED
@@ -1,38 +1,19 @@
1
- import { C as normalizePathname, D as Blocks, E as serializeMdxWithFrontmatter, S as mapSiteNames, T as resolvePublishDate, _ as isMetadataTooLarge, a as buildLocaleVersion, b as localesOf, c as updatePublishDates, d as extractBlockName, f as formatFileSize, g as isContentPublished, h as getMetadataSize, i as analyzeUpdateScope, l as validateAndPrepareMetadata, m as getCurrentISODate, n as Site, o as buildPathnameHistory, p as generateContentId, r as UPDATE_SCOPE, s as shouldUpdateModifiedTimestamp, t as ErrorCodes, u as validateCreateContent, v as isValidBlockName, w as parseDate, x as mapLocales, y as isValidPathname } from "./types-BUG0Cfkg.mjs";
1
+ import { a as buildPathnameHistory, c as validateAndPrepareMetadata, i as buildLocaleVersion, l as validateCreateContent, n as UPDATE_SCOPE, o as shouldUpdateModifiedTimestamp, r as analyzeUpdateScope, s as updatePublishDates, t as Site, u as Blocks } from "./site-8oaj1Q60.mjs";
2
+ import { _ as serializeMdxWithFrontmatter, a as getMetadataSize, c as isValidBlockName, d as mapLocales, f as mapSiteNames, g as resolvePublishDate, h as parseDate, i as getCurrentISODate, l as isValidPathname, m as normalizePathname, n as formatFileSize, o as isContentPublished, p as normalizeAndValidatePathname, r as generateContentId, s as isMetadataTooLarge, t as extractBlockName, u as localesOf } from "./content-utils-fWNHTrPy.mjs";
3
+ import { t as ContentIndex } from "./content-index-D092_vk1.mjs";
4
+ import { t as ErrorCodes } from "./types-DOdldbfD.mjs";
5
+ import { n as calculateEtagsFromMdxBuffer, r as findMdxContentStartPosition, t as VXJSON } from "./vxjson-qHrgLGip.mjs";
6
+ import { i as atomicWriteFile, n as readSitesConfig, r as filterContentWithIndexes, t as FileSystemContentAPI } from "./filesystem-content-api-C0HIhqZi.mjs";
7
+ import { t as Data } from "./data-DquNIEnQ.mjs";
2
8
  import sortKeys from "sort-keys";
3
- import { access, mkdir, open, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
4
- import { dirname, extname, join, parse, resolve } from "node:path";
9
+ import { access, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
10
+ import { dirname, extname, join, normalize, parse, resolve } from "node:path";
5
11
  import { imageSize } from "image-size";
6
12
  import { spawn } from "node:child_process";
7
13
  import { createRemoteJWKSet, jwtVerify } from "jose";
8
- import { dirname as dirname$1, join as join$1, normalize, resolve as resolve$1 } from "path";
9
- import { xxh3 } from "@node-rs/xxhash";
10
- import matter from "gray-matter";
11
- import { createHash } from "crypto";
12
14
  import { Hono } from "hono";
13
15
  import { cors } from "hono/cors";
14
16
  import { getRequestListener } from "@hono/node-server";
15
-
16
- //#region src/utils/atomic-write.ts
17
- /**
18
- * Write file atomically via temp file + rename to prevent corruption on crash.
19
- * Callers are responsible for ensuring the parent directory exists.
20
- */
21
- async function atomicWriteFile(filePath, content) {
22
- const hrtime = process.hrtime.bigint();
23
- const tempFile = `${filePath}.tmp.${process.pid}.${hrtime}`;
24
- try {
25
- await writeFile(tempFile, content);
26
- await rename(tempFile, filePath);
27
- } catch (error) {
28
- try {
29
- await unlink(tempFile);
30
- } catch {}
31
- throw error;
32
- }
33
- }
34
-
35
- //#endregion
36
17
  //#region src/asset-manifest.ts
37
18
  const MANIFEST_FILENAME = ".asset-manifest.json";
38
19
  var AssetManifest = class {
@@ -97,7 +78,6 @@ var AssetManifest = class {
97
78
  };
98
79
  }
99
80
  };
100
-
101
81
  //#endregion
102
82
  //#region src/git-operations.ts
103
83
  function runGitCommand(cwd, args) {
@@ -387,14 +367,13 @@ async function setupGitLfsAttributes(contentRoot) {
387
367
  if (missingPatterns.length === 0) return;
388
368
  await writeFile(gitattributesPath, existing ? `${existing.trimEnd()}\n${missingPatterns.join("\n")}\n` : `${missingPatterns.join("\n")}\n`, "utf-8");
389
369
  }
390
-
391
370
  //#endregion
392
371
  //#region src/url-validation.ts
393
372
  /**
394
373
  * URL validation for SSRF prevention in server-side fetch operations.
395
374
  * Blocks private/reserved IP addresses and non-http(s) schemes.
396
375
  */
397
- const BLOCKED_HOSTNAMES = new Set(["localhost"]);
376
+ const BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set(["localhost"]);
398
377
  /** Check if an IPv4 address string points to a private/reserved range */
399
378
  function isPrivateIPv4(hostname) {
400
379
  const parts = hostname.split(".");
@@ -436,7 +415,6 @@ function validateFetchUrl(url) {
436
415
  if (isPrivateIPv6(hostname)) throw new Error("URL points to a private/reserved IP address");
437
416
  return parsed;
438
417
  }
439
-
440
418
  //#endregion
441
419
  //#region src/asset-operations.ts
442
420
  const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
@@ -461,7 +439,7 @@ const MIME_MAP = {
461
439
  ico: "image/x-icon"
462
440
  };
463
441
  /** Recognized web image extensions for filesystem scanning */
464
- const RECOGNIZED_IMAGE_EXTENSIONS = new Set([
442
+ const RECOGNIZED_IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
465
443
  "jpg",
466
444
  "jpeg",
467
445
  "png",
@@ -472,7 +450,7 @@ const RECOGNIZED_IMAGE_EXTENSIONS = new Set([
472
450
  "ico"
473
451
  ]);
474
452
  /** System files to skip during filesystem scanning */
475
- const SYSTEM_FILES = new Set([
453
+ const SYSTEM_FILES = /* @__PURE__ */ new Set([
476
454
  ".ds_store",
477
455
  "thumbs.db",
478
456
  ".gitkeep",
@@ -680,8 +658,10 @@ var AssetOperations = class {
680
658
  for (const entry of entries) {
681
659
  if (isSystemFile(entry.name) || entry.isSymbolicLink()) continue;
682
660
  const entryPath = join(folderPath, entry.name);
683
- if (entry.isDirectory()) await scanFolder(entryPath, folder === "/" ? `/${entry.name}` : `${folder}/${entry.name}`);
684
- else if (entry.isFile() && isRecognizedImageExtension(entry.name)) {
661
+ if (entry.isDirectory()) {
662
+ const subFolder = folder === "/" ? `/${entry.name}` : `${folder}/${entry.name}`;
663
+ await scanFolder(entryPath, subFolder);
664
+ } else if (entry.isFile() && isRecognizedImageExtension(entry.name)) {
685
665
  const assetEntry = await this.buildAssetEntry(entry, folder, manifestData);
686
666
  assets.push(assetEntry);
687
667
  }
@@ -694,9 +674,9 @@ var AssetOperations = class {
694
674
  * Get asset by filename and optional folder
695
675
  */
696
676
  async getAsset(filename, folder = "/") {
697
- if (folder === "/") folder = await this.resolveFolder(filename);
698
- const relativePath = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
699
- const fullPath = this.getAssetPath(filename, folder);
677
+ const resolvedFolder = folder === "/" ? await this.resolveFolder(filename) : folder;
678
+ const relativePath = resolvedFolder === "/" ? filename : `${resolvedFolder.slice(1)}/${filename}`;
679
+ const fullPath = this.getAssetPath(filename, resolvedFolder);
700
680
  let stats;
701
681
  try {
702
682
  stats = await stat(fullPath);
@@ -723,7 +703,7 @@ var AssetOperations = class {
723
703
  alt: manifestEntry?.alt,
724
704
  uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),
725
705
  uploadedBy: manifestEntry?.uploadedBy,
726
- folder,
706
+ folder: resolvedFolder,
727
707
  tags: manifestEntry?.tags
728
708
  };
729
709
  }
@@ -731,9 +711,9 @@ var AssetOperations = class {
731
711
  * Delete asset file and manifest entry
732
712
  */
733
713
  async delete(filename, folder = "/") {
734
- if (folder === "/") folder = await this.resolveFolder(filename);
735
- const relativePath = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
736
- const filePath = this.getAssetPath(filename, folder);
714
+ const resolvedFolder = folder === "/" ? await this.resolveFolder(filename) : folder;
715
+ const relativePath = resolvedFolder === "/" ? filename : `${resolvedFolder.slice(1)}/${filename}`;
716
+ const filePath = this.getAssetPath(filename, resolvedFolder);
737
717
  try {
738
718
  await unlink(filePath);
739
719
  } catch {}
@@ -849,9 +829,9 @@ var AssetOperations = class {
849
829
  * @param folder Optional folder path (default '/')
850
830
  */
851
831
  async updateMetadata(filename, updates, folder = "/") {
852
- if (folder === "/") folder = await this.resolveFolder(filename);
853
- const relativePath = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
854
- const fullPath = this.getAssetPath(filename, folder);
832
+ const resolvedFolder = folder === "/" ? await this.resolveFolder(filename) : folder;
833
+ const relativePath = resolvedFolder === "/" ? filename : `${resolvedFolder.slice(1)}/${filename}`;
834
+ const fullPath = this.getAssetPath(filename, resolvedFolder);
855
835
  try {
856
836
  await stat(fullPath);
857
837
  } catch {
@@ -865,7 +845,7 @@ var AssetOperations = class {
865
845
  ...updates
866
846
  };
867
847
  await this.manifest.add(relativePath, merged);
868
- const asset = await this.getAsset(filename, folder);
848
+ const asset = await this.getAsset(filename, resolvedFolder);
869
849
  if (!asset) return {
870
850
  success: false,
871
851
  error: "Failed to retrieve updated asset"
@@ -1094,7 +1074,6 @@ var AssetOperations = class {
1094
1074
  }];
1095
1075
  }
1096
1076
  };
1097
-
1098
1077
  //#endregion
1099
1078
  //#region src/cf-access.ts
1100
1079
  /**
@@ -1143,2810 +1122,121 @@ async function validateCFAccessRequest(request) {
1143
1122
  return {
1144
1123
  valid: true,
1145
1124
  required: true,
1146
- user: {
1147
- email: typeof payload.email === "string" && payload.email ? payload.email : void 0,
1148
- sub: typeof payload.sub === "string" && payload.sub ? payload.sub : void 0
1149
- }
1150
- };
1151
- } catch (error) {
1152
- return {
1153
- valid: false,
1154
- required: true,
1155
- error: error instanceof Error ? error.message : "Validation failed"
1156
- };
1157
- }
1158
- }
1159
-
1160
- //#endregion
1161
- //#region src/component-registry.ts
1162
- /**
1163
- * Component Registry for managing linked and unlinked components
1164
- *
1165
- * Registry is stored at {canvasDir}/components/registry.json
1166
- * Component IDs must follow the format: vx-{uuid}
1167
- */
1168
- var ComponentRegistry = class {
1169
- registryPath;
1170
- registry = {};
1171
- initialized = false;
1172
- constructor(canvasDir) {
1173
- this.registryPath = join(canvasDir, "components", "registry.json");
1174
- }
1175
- /**
1176
- * Initialize the registry by loading from disk or creating new
1177
- */
1178
- async initialize() {
1179
- if (this.initialized) return;
1180
- try {
1181
- const content = await readFile(this.registryPath, "utf-8");
1182
- this.registry = JSON.parse(content);
1183
- } catch (error) {
1184
- if (error.code === "ENOENT") await this.save();
1185
- else throw error;
1186
- }
1187
- this.initialized = true;
1188
- }
1189
- /**
1190
- * Validate component ID format (vx-{uuid})
1191
- */
1192
- validateComponentId(id) {
1193
- if (!/^vx-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) throw new Error("Invalid component ID format. Expected: vx-{uuid}");
1194
- }
1195
- /**
1196
- * Save registry to disk atomically
1197
- */
1198
- async save() {
1199
- await mkdir(dirname(this.registryPath), { recursive: true });
1200
- const sorted = sortKeys(this.registry, { deep: true });
1201
- const content = JSON.stringify(sorted, null, 2);
1202
- await atomicWriteFile(this.registryPath, content);
1203
- }
1204
- /**
1205
- * Register a new component or update existing
1206
- */
1207
- async register(id, entry) {
1208
- await this.initialize();
1209
- this.validateComponentId(id);
1210
- this.registry[id] = {
1211
- displayName: entry.displayName,
1212
- path: entry.path
1213
- };
1214
- await this.save();
1215
- }
1216
- /**
1217
- * Get a component entry by ID
1218
- */
1219
- async get(id) {
1220
- await this.initialize();
1221
- return this.registry[id] || null;
1222
- }
1223
- /**
1224
- * Link a component to a path
1225
- */
1226
- async link(id, path) {
1227
- await this.initialize();
1228
- const entry = this.registry[id];
1229
- if (!entry) throw new Error(`Component ${id} not found in registry`);
1230
- entry.path = path;
1231
- await this.save();
1232
- }
1233
- /**
1234
- * Unlink a component (set path to null)
1235
- */
1236
- async unlink(id) {
1237
- await this.initialize();
1238
- const entry = this.registry[id];
1239
- if (!entry) throw new Error(`Component ${id} not found in registry`);
1240
- entry.path = null;
1241
- await this.save();
1242
- }
1243
- /**
1244
- * List all components
1245
- */
1246
- async list() {
1247
- await this.initialize();
1248
- return Object.entries(this.registry).map(([id, entry]) => ({
1249
- id,
1250
- ...entry
1251
- }));
1252
- }
1253
- /**
1254
- * Delete a component from registry
1255
- */
1256
- async delete(id) {
1257
- await this.initialize();
1258
- delete this.registry[id];
1259
- await this.save();
1260
- }
1261
- };
1262
-
1263
- //#endregion
1264
- //#region src/content-filters.ts
1265
- /**
1266
- * Apply filters to a single content manifest
1267
- * Pure function that checks if a manifest matches all provided filters
1268
- */
1269
- function applyContentFilters(manifest, filters) {
1270
- if (filters.site && manifest.site !== filters.site) return false;
1271
- if (filters.collection && manifest.collection !== filters.collection) return false;
1272
- if (filters.type && manifest.type !== filters.type) return false;
1273
- if (filters.kind && manifest.kind !== filters.kind) return false;
1274
- if (filters.locales && filters.locales.length > 0) {
1275
- if (!filters.locales.some((locale) => manifest.locales[locale])) return false;
1276
- }
1277
- if (filters.missingLocales && filters.missingLocales.length > 0) {
1278
- if (filters.missingLocales.some((locale) => manifest.locales[locale])) return false;
1279
- }
1280
- if (filters.published !== void 0) {
1281
- let hasPublishedLocale = false;
1282
- for (const localeVersion of localesOf(manifest)) {
1283
- if (!localeVersion.unpublishAt) {
1284
- hasPublishedLocale = true;
1285
- break;
1286
- }
1287
- if (new Date(localeVersion.unpublishAt) > /* @__PURE__ */ new Date()) {
1288
- hasPublishedLocale = true;
1289
- break;
1290
- }
1291
- }
1292
- if (filters.published !== hasPublishedLocale) return false;
1293
- }
1294
- return true;
1295
- }
1296
- /**
1297
- * Generator that yields manifests after applying all filters
1298
- * This is the main entry point for filtering content using indexes efficiently
1299
- */
1300
- function* filterContentWithIndexes(contentIndex, filters, sitesConfig) {
1301
- if (!filters) {
1302
- yield* contentIndex.listAllContent();
1303
- return;
1304
- }
1305
- if (filters.kind === "page" && filters.site && filters.collection) {
1306
- if (!contentIndex.getCollectionsForSite(filters.site).has(filters.collection)) return;
1307
- } else if (filters.kind === "block" && filters.collection) {
1308
- if (!contentIndex.getBlockCollections().has(filters.collection)) return;
1309
- }
1310
- let generator;
1311
- if (filters.kind === "page" && filters.site && filters.collection) generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);
1312
- else if (filters.kind === "block" && filters.collection) generator = contentIndex.getManifestsForCollection(filters.collection);
1313
- else if (filters.kind) generator = contentIndex.getManifestsForKind(filters.kind);
1314
- else if (filters.site && filters.collection) generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);
1315
- else if (filters.site && filters.locales?.length === 1) generator = contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0]);
1316
- else if (filters.site) generator = contentIndex.getManifestsForSite(filters.site);
1317
- else if (filters.collection) generator = contentIndex.getManifestsForCollection(filters.collection);
1318
- else if (filters.locales?.length === 1) generator = contentIndex.getManifestsForLocale(filters.locales[0]);
1319
- else generator = contentIndex.listAllContent();
1320
- for (const manifest of generator) {
1321
- if (!applyContentFilters(manifest, filters)) continue;
1322
- if (filters.localization) {
1323
- if (filters.localization === "complete" && filters.missingLocales?.length) continue;
1324
- const siteLocales = filters.site && manifest.kind === "page" ? sitesConfig.sites[filters.site]?.locales || sitesConfig.globalLocales : sitesConfig.globalLocales;
1325
- const localeCount = Object.keys(manifest.locales).length;
1326
- const hasLocales = siteLocales.filter((l) => manifest.locales[l]).length;
1327
- const totalLocales = siteLocales.length;
1328
- if (filters.localization === "complete" && hasLocales !== totalLocales) continue;
1329
- if (filters.localization === "partial" && (localeCount <= 1 || hasLocales === totalLocales)) continue;
1330
- if (filters.localization === "one" && localeCount !== 1) continue;
1331
- }
1332
- yield manifest;
1333
- }
1334
- }
1335
-
1336
- //#endregion
1337
- //#region src/base-content-index.ts
1338
- /**
1339
- * Base class for content indexes (blocks, data)
1340
- * Maintains collection->name->locale lookups with V8-optimized structures
1341
- */
1342
- var BaseContentIndex = class {
1343
- index = /* @__PURE__ */ new Map();
1344
- contentCache = /* @__PURE__ */ new Map();
1345
- nameIndex = /* @__PURE__ */ new Map();
1346
- collections = /* @__PURE__ */ new Set();
1347
- /**
1348
- * Add or update content in the index
1349
- * Merges manifest locales and updates content cache if provided
1350
- */
1351
- addContent(identity, localeVersion, content) {
1352
- const existing = this.index.get(identity.id);
1353
- const locale = localeVersion.locale;
1354
- if (existing) {
1355
- const existingLocale = existing.locales[locale];
1356
- if (!existingLocale || existingLocale.etag !== localeVersion.etag) existing.locales[locale] = localeVersion;
1357
- } else {
1358
- const newManifest = {
1359
- id: identity.id,
1360
- type: identity.type,
1361
- kind: identity.kind,
1362
- site: identity.site,
1363
- collection: identity.collection,
1364
- locales: { [locale]: localeVersion }
1365
- };
1366
- this.index.set(identity.id, newManifest);
1367
- this.collections.add(identity.collection);
1368
- }
1369
- if (content !== void 0) {
1370
- const existingCache = this.contentCache.get(identity.id);
1371
- if (existingCache) existingCache[locale] = content;
1372
- else this.contentCache.set(identity.id, { [locale]: content });
1373
- }
1374
- const manifestToIndex = existing || this.index.get(identity.id);
1375
- if (localeVersion.name) {
1376
- if (!this.nameIndex.has(identity.collection)) this.nameIndex.set(identity.collection, /* @__PURE__ */ new Map());
1377
- this.nameIndex.get(identity.collection).set(localeVersion.name, manifestToIndex);
1378
- }
1379
- }
1380
- /**
1381
- * Remove a specific locale from an entry
1382
- */
1383
- removeLocale(id, locale) {
1384
- const manifest = this.index.get(id);
1385
- if (!manifest || !manifest.locales[locale]) return;
1386
- manifest.locales[locale] = void 0;
1387
- const contentCache = this.contentCache.get(id);
1388
- if (contentCache) delete contentCache[locale];
1389
- if (Object.values(manifest.locales).filter((v) => v !== void 0).length === 0) this.removeEntry(id);
1390
- }
1391
- /**
1392
- * Remove an entry from the index
1393
- */
1394
- removeEntry(id) {
1395
- const manifest = this.index.get(id);
1396
- if (!manifest) return;
1397
- for (const localeVersion of localesOf(manifest)) if (localeVersion.name) {
1398
- const collectionMap = this.nameIndex.get(manifest.collection);
1399
- if (collectionMap) collectionMap.delete(localeVersion.name);
1400
- break;
1401
- }
1402
- this.index.delete(id);
1403
- this.contentCache.delete(id);
1404
- }
1405
- /**
1406
- * Get cached content for a specific locale
1407
- */
1408
- getCachedContent(id, locale) {
1409
- return this.contentCache.get(id)?.[locale] || null;
1410
- }
1411
- /**
1412
- * Get content manifest
1413
- */
1414
- getManifest(id) {
1415
- return this.index.get(id) || null;
1416
- }
1417
- /**
1418
- * Find entry by name
1419
- */
1420
- getByName(collection, name, locale) {
1421
- const collectionMap = this.nameIndex.get(collection);
1422
- if (!collectionMap) return null;
1423
- const manifest = collectionMap.get(name);
1424
- if (!manifest) return null;
1425
- if (locale && !manifest.locales[locale]) return null;
1426
- return manifest;
1427
- }
1428
- /**
1429
- * Generator for all manifests
1430
- */
1431
- *getAllManifests() {
1432
- for (const manifest of this.index.values()) yield manifest;
1433
- }
1434
- /**
1435
- * Generator for manifests by locale
1436
- */
1437
- *getManifestsByLocale(locale) {
1438
- for (const manifest of this.index.values()) if (manifest.locales[locale]) yield manifest;
1439
- }
1440
- /**
1441
- * Generator for manifests by collection
1442
- */
1443
- *getManifestsByCollection(collection) {
1444
- for (const manifest of this.index.values()) if (manifest.collection === collection) yield manifest;
1445
- }
1446
- /**
1447
- * Get the count of indexed content entries (unique IDs)
1448
- */
1449
- get entryCount() {
1450
- return this.index.size;
1451
- }
1452
- /**
1453
- * Clear all indexes
1454
- */
1455
- clear() {
1456
- this.index.clear();
1457
- this.contentCache.clear();
1458
- this.nameIndex.clear();
1459
- this.collections.clear();
1460
- }
1461
- };
1462
-
1463
- //#endregion
1464
- //#region src/block-index.ts
1465
- /**
1466
- * V8-optimized index for blocks
1467
- * Maintains collection->name->locale lookups
1468
- */
1469
- var BlockIndex = class extends BaseContentIndex {
1470
- constructor(locales) {
1471
- super();
1472
- }
1473
- };
1474
-
1475
- //#endregion
1476
- //#region src/data-index.ts
1477
- /**
1478
- * V8-optimized index for data collections
1479
- * Maintains collection->name->locale lookups
1480
- */
1481
- var DataIndex = class extends BaseContentIndex {};
1482
-
1483
- //#endregion
1484
- //#region src/site-index.ts
1485
- /**
1486
- * V8-optimized index for a single site
1487
- * Maintains pathname lookups and collections for one site only
1488
- */
1489
- var SiteIndex = class {
1490
- index = /* @__PURE__ */ new Map();
1491
- contentCache = /* @__PURE__ */ new Map();
1492
- pathnameIndex;
1493
- previousPathnameIndex;
1494
- collections = /* @__PURE__ */ new Set();
1495
- constructor(siteName, locales) {
1496
- this.locales = locales;
1497
- this.pathnameIndex = mapLocales(locales, () => /* @__PURE__ */ new Map());
1498
- this.previousPathnameIndex = mapLocales(locales, () => /* @__PURE__ */ new Map());
1499
- }
1500
- /**
1501
- * Add or update content in the index
1502
- * Merges manifest locales and updates content cache if provided
1503
- */
1504
- addContent(identity, localeVersion, content) {
1505
- const existing = this.index.get(identity.id);
1506
- const locale = localeVersion.locale;
1507
- if (existing) {
1508
- const existingLocale = existing.locales[locale];
1509
- let oldPathname;
1510
- for (const [pathname, indexedManifest] of this.pathnameIndex[locale].entries()) if (indexedManifest === existing && pathname !== localeVersion.pathname) {
1511
- oldPathname = pathname;
1512
- break;
1513
- }
1514
- if (!oldPathname && existingLocale?.pathname && existingLocale.pathname !== localeVersion.pathname) oldPathname = existingLocale.pathname;
1515
- const hadExistingLocale = !!existingLocale;
1516
- let deletedOldPathname = false;
1517
- let addedNewPathname = false;
1518
- const addedPreviousPathnames = [];
1519
- if (!existingLocale || existingLocale.etag !== localeVersion.etag || existingLocale.modified !== localeVersion.modified || oldPathname && oldPathname !== localeVersion.pathname) try {
1520
- existing.locales[locale] = localeVersion;
1521
- if (localeVersion.pathname) {
1522
- if (oldPathname && oldPathname !== localeVersion.pathname) {
1523
- this.pathnameIndex[locale].delete(oldPathname);
1524
- deletedOldPathname = true;
1525
- if (isContentPublished(localeVersion)) {
1526
- this.previousPathnameIndex[locale].set(oldPathname, existing);
1527
- addedPreviousPathnames.push(oldPathname);
1528
- }
1529
- }
1530
- this.pathnameIndex[locale].set(localeVersion.pathname, existing);
1531
- addedNewPathname = true;
1532
- }
1533
- if (localeVersion.previousPathnames) {
1534
- for (const prevPath of Object.keys(localeVersion.previousPathnames)) if (!this.previousPathnameIndex[locale].has(prevPath)) {
1535
- this.previousPathnameIndex[locale].set(prevPath, existing);
1536
- addedPreviousPathnames.push(prevPath);
1537
- }
1538
- }
1539
- } catch (error) {
1540
- if (hadExistingLocale) existing.locales[locale] = existingLocale;
1541
- else existing.locales[locale] = void 0;
1542
- if (deletedOldPathname && oldPathname) this.pathnameIndex[locale].set(oldPathname, existing);
1543
- if (addedNewPathname && localeVersion.pathname) this.pathnameIndex[locale].delete(localeVersion.pathname);
1544
- for (const prevPath of addedPreviousPathnames) this.previousPathnameIndex[locale].delete(prevPath);
1545
- throw error;
1546
- }
1547
- } else {
1548
- const newManifest = {
1549
- id: identity.id,
1550
- type: identity.type,
1551
- kind: identity.kind,
1552
- site: identity.site,
1553
- collection: identity.collection,
1554
- locales: { [locale]: localeVersion }
1555
- };
1556
- this.index.set(identity.id, newManifest);
1557
- this.collections.add(identity.collection);
1558
- if (localeVersion.pathname) this.pathnameIndex[locale].set(localeVersion.pathname, newManifest);
1559
- if (localeVersion.previousPathnames) for (const prevPath of Object.keys(localeVersion.previousPathnames)) this.previousPathnameIndex[locale].set(prevPath, newManifest);
1560
- }
1561
- if (content !== void 0) {
1562
- const existingCache = this.contentCache.get(identity.id);
1563
- if (existingCache) existingCache[locale] = content;
1564
- else this.contentCache.set(identity.id, { [locale]: content });
1565
- }
1566
- }
1567
- /**
1568
- * Remove a specific locale from an entry
1569
- */
1570
- removeLocale(id, locale) {
1571
- const manifest = this.index.get(id);
1572
- if (!manifest || !manifest.locales[locale]) return;
1573
- const localeVersion = manifest.locales[locale];
1574
- if (localeVersion.pathname) this.pathnameIndex[locale].delete(localeVersion.pathname);
1575
- if (localeVersion.previousPathnames) for (const prevPath of Object.keys(localeVersion.previousPathnames)) this.previousPathnameIndex[locale].delete(prevPath);
1576
- manifest.locales[locale] = void 0;
1577
- const contentCache = this.contentCache.get(id);
1578
- if (contentCache) delete contentCache[locale];
1579
- if (Object.keys(manifest.locales).length === 0) this.removeEntry(id);
1580
- }
1581
- /**
1582
- * Remove an entry from the index
1583
- */
1584
- removeEntry(id) {
1585
- const manifest = this.index.get(id);
1586
- if (!manifest) return;
1587
- for (const localeVersion of localesOf(manifest)) {
1588
- const { locale } = localeVersion;
1589
- if (localeVersion.pathname) this.pathnameIndex[locale].delete(localeVersion.pathname);
1590
- if (localeVersion.previousPathnames) for (const prevPath of Object.keys(localeVersion.previousPathnames)) this.previousPathnameIndex[locale].delete(prevPath);
1591
- }
1592
- this.index.delete(id);
1593
- this.contentCache.delete(id);
1594
- }
1595
- /**
1596
- * Get cached content for a specific locale
1597
- */
1598
- getCachedContent(id, locale) {
1599
- return this.contentCache.get(id)?.[locale] || null;
1600
- }
1601
- /**
1602
- * Get content manifest
1603
- */
1604
- getManifest(id) {
1605
- return this.index.get(id) || null;
1606
- }
1607
- /**
1608
- * Find content by pathname
1609
- */
1610
- getByPathname(pathname, locale) {
1611
- if (locale) return this.pathnameIndex[locale]?.get(pathname) || null;
1612
- for (const locale of this.locales) {
1613
- const manifest = this.pathnameIndex[locale].get(pathname);
1614
- if (manifest) return manifest;
1615
- }
1616
- return null;
1617
- }
1618
- /**
1619
- * Find content by previous pathname (for redirects)
1620
- */
1621
- getByPreviousPathname(pathname, locale) {
1622
- if (locale) return this.previousPathnameIndex[locale]?.get(pathname) || null;
1623
- for (const locale of this.locales) {
1624
- const manifest = this.previousPathnameIndex[locale].get(pathname);
1625
- if (manifest) return manifest;
1626
- }
1627
- return null;
1628
- }
1629
- /**
1630
- * Generator for all manifests
1631
- */
1632
- *getAllManifests() {
1633
- for (const manifest of this.index.values()) yield manifest;
1634
- }
1635
- /**
1636
- * Generator for manifests by locale
1637
- */
1638
- *getManifestsByLocale(locale) {
1639
- for (const manifest of this.index.values()) if (manifest.locales[locale]) yield manifest;
1640
- }
1641
- /**
1642
- * Get the count of indexed content entries (unique IDs)
1643
- */
1644
- get entryCount() {
1645
- return this.index.size;
1646
- }
1647
- /**
1648
- * Clear all indexes
1649
- */
1650
- clear() {
1651
- this.index.clear();
1652
- this.contentCache.clear();
1653
- for (const locale of this.locales) {
1654
- this.pathnameIndex[locale].clear();
1655
- this.previousPathnameIndex[locale].clear();
1656
- }
1657
- this.collections.clear();
1658
- }
1659
- };
1660
-
1661
- //#endregion
1662
- //#region src/content-index.ts
1663
- /**
1664
- * ContentIndex coordinates between per-site indexes and the block index
1665
- * This provides efficient filtering by routing to the appropriate specialized index
1666
- */
1667
- const globalCache = globalThis.__CONLOCA_CONTENT_INDEX_CACHE__ || {};
1668
- if (!globalThis.__CONLOCA_CONTENT_INDEX_CACHE__) globalThis.__CONLOCA_CONTENT_INDEX_CACHE__ = globalCache;
1669
- var ContentIndex = class ContentIndex {
1670
- static get cache() {
1671
- return globalCache;
1672
- }
1673
- siteIndexes;
1674
- blockIndex;
1675
- dataIndex;
1676
- constructor(sitesConfig) {
1677
- this.sitesConfig = sitesConfig;
1678
- this.blockIndex = new BlockIndex(sitesConfig.globalLocales);
1679
- this.dataIndex = new DataIndex();
1680
- this.siteIndexes = mapSiteNames(sitesConfig, (siteName) => {
1681
- const siteConfig = sitesConfig.sites[siteName];
1682
- return new SiteIndex(siteName, siteConfig.locales);
1683
- });
1684
- }
1685
- /**
1686
- * Get cached index or create a new one
1687
- */
1688
- static async getCachedOrCreate(contentRoot, sitesConfig) {
1689
- if (!ContentIndex.cache[contentRoot]) ContentIndex.cache[contentRoot] = new ContentIndex(sitesConfig);
1690
- return ContentIndex.cache[contentRoot];
1691
- }
1692
- /**
1693
- * Clear all cached indexes
1694
- */
1695
- static clearCache() {
1696
- Object.keys(globalCache).forEach((key) => delete globalCache[key]);
1697
- }
1698
- /**
1699
- * Create a new index without caching - for testing
1700
- */
1701
- static createUncached(sitesConfig) {
1702
- return new ContentIndex(sitesConfig);
1703
- }
1704
- /**
1705
- * Add or update content in the appropriate index
1706
- * Updates a single locale's manifest and content cache if provided
1707
- */
1708
- addContent(identity, localeVersion, content) {
1709
- if ((identity.kind === "block" || identity.kind === "data") && identity.site) throw new Error(`${identity.kind} cannot have a site property`);
1710
- if (identity.kind === "page" && !identity.site) throw new Error("Pages must have a site property");
1711
- if (identity.kind === "block") this.blockIndex.addContent(identity, localeVersion, content);
1712
- else if (identity.kind === "data") this.dataIndex.addContent(identity, localeVersion, content);
1713
- else {
1714
- const siteIndex = this.siteIndexes[identity.site];
1715
- if (siteIndex) siteIndex.addContent(identity, localeVersion, content);
1716
- }
1717
- }
1718
- /**
1719
- * Remove a specific locale from content
1720
- */
1721
- removeLocale(id, locale) {
1722
- const manifest = this.getManifest(id);
1723
- if (!manifest) return;
1724
- if (manifest.kind === "block") this.blockIndex.removeLocale(id, locale);
1725
- else if (manifest.kind === "data") this.dataIndex.removeLocale(id, locale);
1726
- else {
1727
- const siteIndex = this.siteIndexes[manifest.site];
1728
- if (siteIndex) siteIndex.removeLocale(id, locale);
1729
- }
1730
- }
1731
- /**
1732
- * Get cached content
1733
- */
1734
- getCachedContent(id, locale) {
1735
- const manifest = this.getManifest(id);
1736
- if (!manifest) return null;
1737
- if (manifest.kind === "block") return this.blockIndex.getCachedContent(id, locale);
1738
- if (manifest.kind === "data") return this.dataIndex.getCachedContent(id, locale);
1739
- const siteIndex = this.siteIndexes[manifest.site];
1740
- return siteIndex ? siteIndex.getCachedContent(id, locale) : null;
1741
- }
1742
- /**
1743
- * Remove an entry from all indexes
1744
- */
1745
- removeEntry(id) {
1746
- this.blockIndex.removeEntry(id);
1747
- this.dataIndex.removeEntry(id);
1748
- for (const site in this.siteIndexes) {
1749
- const siteIndex = this.siteIndexes[site];
1750
- if (siteIndex) siteIndex.removeEntry(id);
1751
- }
1752
- }
1753
- /**
1754
- * Get content manifest for a content ID
1755
- */
1756
- getManifest(id) {
1757
- let manifest = this.blockIndex.getManifest(id);
1758
- if (manifest) return manifest;
1759
- manifest = this.dataIndex.getManifest(id);
1760
- if (manifest) return manifest;
1761
- for (const site in this.siteIndexes) {
1762
- const siteIndex = this.siteIndexes[site];
1763
- if (siteIndex) {
1764
- manifest = siteIndex.getManifest(id);
1765
- if (manifest) return manifest;
1766
- }
1767
- }
1768
- return null;
1769
- }
1770
- /**
1771
- * Get a specific locale manifest
1772
- */
1773
- getLocaleVersion(id, locale) {
1774
- const manifest = this.getManifest(id);
1775
- if (!manifest) return null;
1776
- return manifest.locales[locale] || null;
1777
- }
1778
- /**
1779
- * Get site index
1780
- */
1781
- getSiteIndex(site) {
1782
- return this.siteIndexes[site] || null;
1783
- }
1784
- /**
1785
- * Get block index
1786
- */
1787
- getBlockIndex() {
1788
- return this.blockIndex;
1789
- }
1790
- /**
1791
- * Find content by pathname (delegates to site indexes)
1792
- */
1793
- getByPathname(site, pathname, locale) {
1794
- const siteIndex = this.siteIndexes[site];
1795
- return siteIndex ? siteIndex.getByPathname(pathname, locale) : null;
1796
- }
1797
- /**
1798
- * Find content by previous pathname (for redirects)
1799
- */
1800
- getByPreviousPathname(site, pathname, locale) {
1801
- const siteIndex = this.siteIndexes[site];
1802
- return siteIndex ? siteIndex.getByPreviousPathname(pathname, locale) : null;
1803
- }
1804
- /**
1805
- * Find block by name
1806
- */
1807
- getBlockByName(collection, name, locale) {
1808
- return this.blockIndex.getByName(collection, name, locale);
1809
- }
1810
- /**
1811
- * Get data index
1812
- */
1813
- getDataIndex() {
1814
- return this.dataIndex;
1815
- }
1816
- /**
1817
- * Find data entry by name
1818
- */
1819
- getDataByName(collection, name, locale) {
1820
- return this.dataIndex.getByName(collection, name, locale);
1821
- }
1822
- /**
1823
- * Get all collections for data
1824
- */
1825
- getDataCollections() {
1826
- return this.dataIndex.collections;
1827
- }
1828
- /**
1829
- * List all content (for iteration)
1830
- */
1831
- *listAllContent() {
1832
- yield* this.blockIndex.getAllManifests();
1833
- yield* this.dataIndex.getAllManifests();
1834
- for (const site in this.siteIndexes) {
1835
- const siteIndex = this.siteIndexes[site];
1836
- if (siteIndex) yield* siteIndex.getAllManifests();
1837
- }
1838
- }
1839
- /**
1840
- * Generator for all sites
1841
- */
1842
- *allSites() {
1843
- for (const site in this.siteIndexes) if (this.siteIndexes[site]) yield site;
1844
- }
1845
- /**
1846
- * Get all collections for a site
1847
- */
1848
- getCollectionsForSite(site) {
1849
- const siteIndex = this.siteIndexes[site];
1850
- return siteIndex ? siteIndex.collections : /* @__PURE__ */ new Set();
1851
- }
1852
- /**
1853
- * Get all collections for blocks
1854
- */
1855
- getBlockCollections() {
1856
- return this.blockIndex.collections;
1857
- }
1858
- /**
1859
- * Get default locale for a site
1860
- */
1861
- getDefaultLocale(site) {
1862
- if (!site) return this.sitesConfig.globalLocales[0];
1863
- return this.sitesConfig.sites[site]?.defaultLocale || this.sitesConfig.globalLocales[0];
1864
- }
1865
- /**
1866
- * Find content missing a specific locale
1867
- */
1868
- *findUntranslatedContent(targetLocale, options) {
1869
- for (const manifest of this.blockIndex.getAllManifests()) if (!manifest.locales[targetLocale]) {
1870
- if (!options?.includeUnpublished) {
1871
- let hasPublishedLocale = false;
1872
- for (const locale of localesOf(manifest)) if (!locale.unpublishAt || new Date(locale.unpublishAt) > /* @__PURE__ */ new Date()) {
1873
- hasPublishedLocale = true;
1874
- break;
1875
- }
1876
- if (!hasPublishedLocale) continue;
1877
- }
1878
- yield manifest;
1879
- }
1880
- for (const siteName in this.siteIndexes) {
1881
- const siteIndex = this.siteIndexes[siteName];
1882
- if (!siteIndex || options?.excludeSites?.includes(siteName)) continue;
1883
- for (const manifest of siteIndex.getAllManifests()) if (!manifest.locales[targetLocale]) {
1884
- if (!options?.includeUnpublished) {
1885
- let hasPublishedLocale = false;
1886
- for (const locale of localesOf(manifest)) if (!locale.unpublishAt || new Date(locale.unpublishAt) > /* @__PURE__ */ new Date()) {
1887
- hasPublishedLocale = true;
1888
- break;
1889
- }
1890
- if (!hasPublishedLocale) continue;
1891
- }
1892
- yield manifest;
1893
- }
1894
- }
1895
- }
1896
- /**
1897
- * Generators for efficient filtering
1898
- */
1899
- *getManifestsForKind(kind) {
1900
- if (kind === "block") yield* this.blockIndex.getAllManifests();
1901
- else if (kind === "data") yield* this.dataIndex.getAllManifests();
1902
- else for (const site in this.siteIndexes) {
1903
- const siteIndex = this.siteIndexes[site];
1904
- if (siteIndex) yield* siteIndex.getAllManifests();
1905
- }
1906
- }
1907
- *getManifestsForSite(site) {
1908
- const siteIndex = this.siteIndexes[site];
1909
- if (siteIndex) yield* siteIndex.getAllManifests();
1910
- }
1911
- *getManifestsForSiteLocale(site, locale) {
1912
- const siteIndex = this.siteIndexes[site];
1913
- if (siteIndex) yield* siteIndex.getManifestsByLocale(locale);
1914
- }
1915
- *getManifestsForSiteCollection(site, collection) {
1916
- const siteIndex = this.siteIndexes[site];
1917
- if (siteIndex) {
1918
- for (const manifest of siteIndex.getAllManifests()) if (manifest.collection === collection) yield manifest;
1919
- }
1920
- }
1921
- *getManifestsForLocale(locale) {
1922
- yield* this.blockIndex.getManifestsByLocale(locale);
1923
- yield* this.dataIndex.getManifestsByLocale(locale);
1924
- for (const site in this.siteIndexes) {
1925
- const siteIndex = this.siteIndexes[site];
1926
- if (siteIndex) yield* siteIndex.getManifestsByLocale(locale);
1927
- }
1928
- }
1929
- *getManifestsForCollection(collection) {
1930
- yield* this.blockIndex.getManifestsByCollection(collection);
1931
- yield* this.dataIndex.getManifestsByCollection(collection);
1932
- for (const site in this.siteIndexes) {
1933
- const siteIndex = this.siteIndexes[site];
1934
- if (siteIndex) {
1935
- for (const manifest of siteIndex.getAllManifests()) if (manifest.collection === collection) yield manifest;
1936
- }
1937
- }
1938
- }
1939
- /**
1940
- * Get the count of indexed content entries
1941
- */
1942
- get entryCount() {
1943
- let count = this.blockIndex.entryCount;
1944
- count += this.dataIndex.entryCount;
1945
- for (const site in this.siteIndexes) {
1946
- const siteIndex = this.siteIndexes[site];
1947
- if (siteIndex) count += siteIndex.entryCount;
1948
- }
1949
- return count;
1950
- }
1951
- /**
1952
- * Clear all indexes
1953
- */
1954
- clear() {
1955
- this.blockIndex.clear();
1956
- this.dataIndex.clear();
1957
- for (const site in this.siteIndexes) {
1958
- const siteIndex = this.siteIndexes[site];
1959
- if (siteIndex) siteIndex.clear();
1960
- }
1961
- }
1962
- };
1963
-
1964
- //#endregion
1965
- //#region src/data.ts
1966
- var Data = class {
1967
- constructor(api, dataIndex) {
1968
- this.api = api;
1969
- this.dataIndex = dataIndex;
1970
- }
1971
- *listContent(filters) {
1972
- if (filters?.collection) if (filters.locales && filters.locales.length > 0) {
1973
- for (const manifest of this.dataIndex.getManifestsByCollection(filters.collection)) if (filters.locales.some((locale) => manifest.locales[locale])) yield manifest;
1974
- } else yield* this.dataIndex.getManifestsByCollection(filters.collection);
1975
- else if (filters?.locales && filters.locales.length > 0) {
1976
- for (const manifest of this.dataIndex.getAllManifests()) if (filters.locales.some((locale) => manifest.locales[locale])) yield manifest;
1977
- } else yield* this.dataIndex.getAllManifests();
1978
- }
1979
- get collections() {
1980
- return this.dataIndex.collections;
1981
- }
1982
- getByName(collection, name, locale) {
1983
- return this.dataIndex.getByName(collection, name, locale);
1984
- }
1985
- isNameAvailable(collection, name, excludeId) {
1986
- const existing = this.getByName(collection, name);
1987
- return !existing || existing.id === excludeId;
1988
- }
1989
- getNameConflict(collection, name, excludeId) {
1990
- const existing = this.getByName(collection, name);
1991
- if (existing && existing.id !== excludeId) return existing.id;
1992
- return null;
1993
- }
1994
- isDataNameValid(dataName) {
1995
- if (!dataName || dataName.trim() === "") return false;
1996
- if (dataName.includes(".")) return false;
1997
- if (dataName.includes("/") || dataName.includes("\\")) return false;
1998
- return /^[a-zA-Z0-9_-]+$/.test(dataName);
1999
- }
2000
- async create(input) {
2001
- if (!this.isDataNameValid(input.name)) return {
2002
- success: false,
2003
- reason: "invalid_name",
2004
- error: /* @__PURE__ */ new Error(`Invalid data name: ${input.name}`)
2005
- };
2006
- if (this.getByName(input.collection, input.name)) return {
2007
- success: false,
2008
- reason: "name_taken",
2009
- error: /* @__PURE__ */ new Error(`Data name ${input.name} already exists in collection ${input.collection}`)
2010
- };
2011
- return this.api.createContent({
2012
- kind: "data",
2013
- collection: input.collection,
2014
- type: "json",
2015
- name: input.name,
2016
- meta: input.meta,
2017
- locales: input.locales
2018
- });
2019
- }
2020
- };
2021
-
2022
- //#endregion
2023
- //#region src/json-whitespace-view.ts
2024
- /**
2025
- * Zero-allocation JSON whitespace-skipping stream transform
2026
- * Skips whitespace outside of JSON strings, preserving whitespace inside strings
2027
- * Optimized to process multiple bytes at once when possible
2028
- */
2029
- var JsonWhitespaceSkippingView = class {
2030
- inString = false;
2031
- escaped = false;
2032
- singleByte = new Uint8Array(1);
2033
- constructor(downstream) {
2034
- this.downstream = downstream;
2035
- }
2036
- /**
2037
- * Process a single byte from JSON stream
2038
- * @param byte - The byte to process
2039
- */
2040
- updateByte(byte) {
2041
- let shouldInclude = false;
2042
- if (this.inString) {
2043
- shouldInclude = true;
2044
- if (this.escaped) this.escaped = false;
2045
- else if (byte === 92) this.escaped = true;
2046
- else if (byte === 34) this.inString = false;
2047
- } else if (byte === 34) {
2048
- this.inString = true;
2049
- shouldInclude = true;
2050
- } else if (byte !== 9 && byte !== 32 && byte !== 10 && byte !== 13) shouldInclude = true;
2051
- if (shouldInclude) {
2052
- this.singleByte[0] = byte;
2053
- this.downstream.update(this.singleByte);
2054
- }
2055
- }
2056
- /**
2057
- * Process a buffer range with simple batching
2058
- * Collects consecutive bytes that should be included
2059
- * @param buffer - The buffer to process
2060
- * @param start - Start position (inclusive)
2061
- * @param end - End position (exclusive)
2062
- */
2063
- updateBuffer(buffer, start = 0, end = buffer.length) {
2064
- let pos = start;
2065
- let runStart = start;
2066
- while (pos < end) {
2067
- const byte = buffer[pos];
2068
- let shouldInclude = false;
2069
- if (this.inString) {
2070
- shouldInclude = true;
2071
- if (this.escaped) this.escaped = false;
2072
- else if (byte === 92) this.escaped = true;
2073
- else if (byte === 34) this.inString = false;
2074
- else {
2075
- pos++;
2076
- let searchPos = pos;
2077
- while (searchPos < end) {
2078
- const quotePos = buffer.indexOf(34, searchPos);
2079
- if (quotePos === -1 || quotePos >= end) {
2080
- pos = end;
2081
- break;
2082
- }
2083
- let backslashCount = 0;
2084
- let checkPos = quotePos - 1;
2085
- while (checkPos >= 0 && buffer[checkPos] === 92) {
2086
- backslashCount++;
2087
- checkPos--;
2088
- }
2089
- if (backslashCount % 2 === 0) {
2090
- pos = quotePos + 1;
2091
- this.inString = false;
2092
- break;
2093
- }
2094
- searchPos = quotePos + 1;
2095
- }
2096
- continue;
2097
- }
2098
- } else if (byte === 34) {
2099
- this.inString = true;
2100
- shouldInclude = true;
2101
- } else if (byte !== 9 && byte !== 32 && byte !== 10 && byte !== 13) shouldInclude = true;
2102
- if (shouldInclude) pos++;
2103
- else {
2104
- if (pos > runStart) this.downstream.update(buffer.subarray(runStart, pos));
2105
- pos++;
2106
- runStart = pos;
2107
- }
2108
- }
2109
- if (pos > runStart) this.downstream.update(buffer.subarray(runStart, pos));
2110
- }
2111
- /**
2112
- * Reset the parser state
2113
- */
2114
- reset() {
2115
- this.inString = false;
2116
- this.escaped = false;
2117
- }
2118
- };
2119
-
2120
- //#endregion
2121
- //#region src/url-safe-base64.ts
2122
- /**
2123
- * Convert bytes to URL-safe base64
2124
- * Replaces + with -, / with _, and removes = padding
2125
- */
2126
- function toUrlSafeBase64(bytes) {
2127
- const b64 = Buffer.from(bytes).toString("base64");
2128
- const buf = Buffer.from(b64, "ascii");
2129
- let write = 0;
2130
- for (let read = 0; read < buf.length; read++) {
2131
- const c = buf[read];
2132
- if (c === 43) buf[write++] = 45;
2133
- else if (c === 47) buf[write++] = 95;
2134
- else if (c === 61) {} else buf[write++] = c;
2135
- }
2136
- return buf.subarray(0, write).toString("ascii");
2137
- }
2138
- /**
2139
- * Convert BigInt to URL-safe base64
2140
- * @param value - The BigInt value to convert
2141
- * @returns URL-safe base64 string representation
2142
- */
2143
- function bigintToUrlSafeBase64(value) {
2144
- const hashBuffer = new Uint8Array(8);
2145
- new DataView(hashBuffer.buffer).setBigUint64(0, value, false);
2146
- return toUrlSafeBase64(hashBuffer);
2147
- }
2148
-
2149
- //#endregion
2150
- //#region src/etag-utils.ts
2151
- /**
2152
- * Calculate content ETag using SHA256 from buffer view
2153
- * @param buffer - The file buffer view
2154
- * @param start - Start position (inclusive)
2155
- * @param end - End position (exclusive), or -1 for entire buffer
2156
- */
2157
- function calculateContentEtagFromBuffer(buffer, start = 0, end = -1) {
2158
- const actualEnd = end === -1 ? buffer.length : end;
2159
- const hasher = createHash("sha256");
2160
- new JsonWhitespaceSkippingView(hasher).updateBuffer(buffer, start, actualEnd);
2161
- return toUrlSafeBase64(hasher.digest());
2162
- }
2163
- const dashCode = "-".charCodeAt(0);
2164
- const newlineCode = "\n".charCodeAt(0);
2165
- /**
2166
- * Find the content start position in MDX buffer (after second ---)
2167
- * @param buffer - The MDX content buffer
2168
- * @returns Position where content starts, or -1 if not found
2169
- */
2170
- function findMdxContentStartPosition(buffer) {
2171
- let dashCount = 0;
2172
- let i = 0;
2173
- while (i < buffer.length - 4) if (buffer[i] === dashCode && buffer[i + 1] === dashCode && buffer[i + 2] === dashCode && buffer[i + 3] === newlineCode) {
2174
- dashCount++;
2175
- if (dashCount === 2) {
2176
- i += 4;
2177
- if (i < buffer.length && buffer[i] === newlineCode) return i + 1;
2178
- return i;
2179
- }
2180
- i += 4;
2181
- } else {
2182
- const nextDashPos = buffer.indexOf(dashCode, i + 1);
2183
- if (nextDashPos === -1) break;
2184
- i = nextDashPos;
2185
- }
2186
- return -1;
2187
- }
2188
- /**
2189
- * Calculate both ETags from an MDX buffer
2190
- *
2191
- * MDX files use YAML frontmatter which has different characteristics than JSON:
2192
- * - YAML does not require quotes around keys or string values
2193
- * - YAML allows multiple formatting styles (flow vs block style)
2194
- * - YAML field order is not significant for parsing
2195
- *
2196
- * Unlike VXJSON which requires "content" to be the last field and needs special
2197
- * parsing to validate structure, YAML frontmatter can be hashed as-is because:
2198
- * 1. The frontmatter boundaries are clearly delimited by ---
2199
- * 2. Different YAML formatting of the same data SHOULD produce different hashes
2200
- * (e.g., flow style [a,b] vs block style with dashes)
2201
- * 3. There's no requirement to validate field ordering
2202
- *
2203
- * This means we can directly hash the YAML bytes without any whitespace
2204
- * normalization or parsing, which is both simpler and more correct.
2205
- *
2206
- * @param buffer - The complete file buffer
2207
- * @param contentStartPos - Position where content starts (after second ---), or -1 if no content
2208
- */
2209
- function calculateEtagsFromMdxBuffer(buffer, contentStartPos) {
2210
- if (contentStartPos === -1) {
2211
- const hasher = xxh3.Xxh3.withSeed(0n);
2212
- hasher.update(buffer);
2213
- return {
2214
- metaEtag: bigintToUrlSafeBase64(hasher.digest()),
2215
- contentEtag: calculateContentEtagFromBuffer(new Uint8Array(0))
2216
- };
2217
- }
2218
- const metaHasher = xxh3.Xxh3.withSeed(0n);
2219
- metaHasher.update(buffer.subarray(0, contentStartPos));
2220
- const metaEtag = bigintToUrlSafeBase64(metaHasher.digest());
2221
- const contentHasher = createHash("sha256");
2222
- contentHasher.update(buffer.subarray(contentStartPos));
2223
- return {
2224
- metaEtag,
2225
- contentEtag: toUrlSafeBase64(contentHasher.digest())
2226
- };
2227
- }
2228
- /**
2229
- * Parse dual ETags from query string: "meta.content"
2230
- */
2231
- function parseDualEtag(etag) {
2232
- const parts = etag.split(".");
2233
- if (parts.length !== 2) return null;
2234
- return {
2235
- meta: parts[0],
2236
- content: parts[1]
2237
- };
2238
- }
2239
-
2240
- //#endregion
2241
- //#region src/vxjson.ts
2242
- const textDecoder$1 = new TextDecoder();
2243
- const CONTENT_MARKER = new TextEncoder().encode("\"content\":");
2244
- /**
2245
- * Calculate metadata ETag using xxHash from buffer view
2246
- * @param buffer - The file buffer view
2247
- * @param start - Start position (inclusive)
2248
- * @param end - End position (exclusive), or -1 for entire buffer
2249
- */
2250
- function calculateMetaEtagFromBuffer(buffer, start = 0, end = -1) {
2251
- const actualEnd = end === -1 ? buffer.length : end;
2252
- const hasher = xxh3.Xxh3.withSeed(0n);
2253
- new JsonWhitespaceSkippingView(hasher).updateBuffer(buffer, start, actualEnd);
2254
- return bigintToUrlSafeBase64(hasher.digest());
2255
- }
2256
- /**
2257
- * Calculate both ETags from a VXJSON buffer using views
2258
- * Finds the "content" field position and validates it's the last field
2259
- * @param buffer - The complete file buffer
2260
- * @returns Result with ETags or validation error
2261
- */
2262
- function calculateEtagsFromVXJSONBuffer(buffer, allowTruncated = false) {
2263
- let pos = 0;
2264
- let depth = 0;
2265
- let inString = false;
2266
- let escaped = false;
2267
- let contentStartPos = -1;
2268
- let foundContentAtRoot = false;
2269
- let expectingKey = false;
2270
- let expectingValue = false;
2271
- let keyStart = -1;
2272
- while (pos < buffer.length && (buffer[pos] === 32 || buffer[pos] === 9 || buffer[pos] === 10 || buffer[pos] === 13)) pos++;
2273
- if (pos >= buffer.length || buffer[pos] !== 123) return {
2274
- success: false,
2275
- error: "invalid_json"
2276
- };
2277
- depth = 1;
2278
- expectingKey = true;
2279
- pos++;
2280
- while (pos < buffer.length && depth > 0) {
2281
- const byte = buffer[pos];
2282
- if (inString) {
2283
- if (escaped) escaped = false;
2284
- else if (byte === 92) escaped = true;
2285
- else if (byte === 34) {
2286
- inString = false;
2287
- if (depth === 1 && expectingKey && keyStart >= 0) {
2288
- const keyLength = pos - keyStart + 1;
2289
- if (foundContentAtRoot) {
2290
- if (keyLength === 9) {
2291
- let isContent = true;
2292
- for (let i = 0; i < 7; i++) if (buffer[keyStart + 1 + i] !== CONTENT_MARKER[i + 1]) {
2293
- isContent = false;
2294
- break;
2295
- }
2296
- if (isContent) return {
2297
- success: false,
2298
- error: "invalid_json"
2299
- };
2300
- }
2301
- return {
2302
- success: false,
2303
- error: "content_not_last"
2304
- };
2305
- }
2306
- if (keyLength === 9) {
2307
- let isContent = true;
2308
- for (let i = 0; i < 7; i++) if (buffer[keyStart + 1 + i] !== CONTENT_MARKER[i + 1]) {
2309
- isContent = false;
2310
- break;
2311
- }
2312
- if (isContent) {
2313
- foundContentAtRoot = true;
2314
- contentStartPos = keyStart;
2315
- }
2316
- }
2317
- expectingKey = false;
2318
- expectingValue = true;
2319
- keyStart = -1;
2320
- }
2321
- }
2322
- } else if (byte === 34) {
2323
- inString = true;
2324
- if (depth === 1 && expectingKey) keyStart = pos;
2325
- } else if (byte === 123 || byte === 91) {
2326
- depth++;
2327
- if (depth === 1 && expectingValue) expectingValue = false;
2328
- } else if (byte === 125 || byte === 93) {
2329
- depth--;
2330
- if (depth === 0) break;
2331
- } else if (byte === 58 && depth === 1) {
2332
- if (!expectingValue) return {
2333
- success: false,
2334
- error: "invalid_json"
2335
- };
2336
- } else if (byte === 44 && depth === 1) {
2337
- expectingKey = true;
2338
- expectingValue = false;
2339
- } else if (depth === 1 && expectingValue && byte !== 32 && byte !== 9 && byte !== 10 && byte !== 13) expectingValue = false;
2340
- pos++;
2341
- }
2342
- const isTruncated = depth !== 0;
2343
- if (isTruncated && !allowTruncated) return {
2344
- success: false,
2345
- error: "invalid_json"
2346
- };
2347
- if (contentStartPos === -1) return {
2348
- success: true,
2349
- metaEtag: calculateMetaEtagFromBuffer(buffer),
2350
- contentStartPos: -1
2351
- };
2352
- if (isTruncated) return {
2353
- success: true,
2354
- metaEtag: calculateMetaEtagFromBuffer(buffer, 0, contentStartPos),
2355
- contentStartPos
2356
- };
2357
- let metaEnd = contentStartPos - 1;
2358
- while (metaEnd > 0) {
2359
- const byte = buffer[metaEnd];
2360
- if (byte === 44 || byte === 32 || byte === 9 || byte === 10 || byte === 13) metaEnd--;
2361
- else break;
2362
- }
2363
- const metaHasher = xxh3.Xxh3.withSeed(0n);
2364
- const metaView = new JsonWhitespaceSkippingView(metaHasher);
2365
- const openBrace = new Uint8Array([123]);
2366
- const closeBrace = new Uint8Array([125]);
2367
- metaHasher.update(openBrace);
2368
- metaView.updateBuffer(buffer, 1, metaEnd);
2369
- metaHasher.update(closeBrace);
2370
- const metaEtag = bigintToUrlSafeBase64(metaHasher.digest());
2371
- const contentHasher = createHash("sha256");
2372
- const contentView = new JsonWhitespaceSkippingView(contentHasher);
2373
- contentHasher.update(openBrace);
2374
- contentView.updateBuffer(buffer, contentStartPos, buffer.length - 1);
2375
- contentHasher.update(closeBrace);
2376
- return {
2377
- success: true,
2378
- metaEtag,
2379
- contentEtag: toUrlSafeBase64(contentHasher.digest()),
2380
- contentStartPos
2381
- };
2382
- }
2383
- /**
2384
- * VXJSON (Variant JSON) module for parsing and serializing VXJSON files
2385
- *
2386
- * VXJSON is a specialized JSON format that guarantees:
2387
- * 1. The root is always an object (never an array or primitive)
2388
- * 2. The "content" field always comes last in the object
2389
- * 3. Field order is deterministic for consistent ETag calculation
2390
- * 4. Metadata fits within 4085 bytes, ensuring "content" field is found within first 4KB
2391
- * 5. First 4KB must either be complete JSON OR end exactly with '"content":'
2392
- *
2393
- * This format enables efficient 4KB parsing where only the first 4KB of a file
2394
- * needs to be read to extract all metadata and locate the content position.
2395
- * The constraint that 4KB reads must end with '"content":' ensures reliable parsing.
2396
- *
2397
- * This module centralizes all VXJSON-specific logic including:
2398
- * - Parsing partial buffers (first 4KB for indexing)
2399
- * - Finding content position for ETag calculation
2400
- * - Serializing with proper field ordering and size validation
2401
- * - Calculating ETags from buffers
2402
- */
2403
- /**
2404
- * VXJSON static utilities for parsing and validating VXJSON files
2405
- */
2406
- var VXJSON = class VXJSON {
2407
- /**
2408
- * Parse first 4KB of VXJSON content from buffer
2409
- * Used during indexing to extract metadata without loading full content
2410
- *
2411
- * VXJSON format requirement: first 4KB must either be complete JSON OR end with '"content":'
2412
- * This ensures reliable parsing and validation.
2413
- */
2414
- static parse4KB(buffer, bytesRead) {
2415
- if (bytesRead < 4096 || buffer[bytesRead - 1] === 125) {
2416
- const partialContent = textDecoder$1.decode(buffer.subarray(0, bytesRead));
2417
- const data = JSON.parse(partialContent);
2418
- let contentStartPos = -1;
2419
- if (data.content !== void 0) {
2420
- const etagResult = calculateEtagsFromVXJSONBuffer(buffer.subarray(0, bytesRead));
2421
- if (etagResult.success) contentStartPos = etagResult.contentStartPos;
2422
- }
2423
- return {
2424
- id: data.id,
2425
- created: data.created,
2426
- modified: data.modified,
2427
- publishAt: data.publishAt,
2428
- unpublishAt: data.unpublishAt,
2429
- previousPathnames: data.previousPathnames,
2430
- pathname: data.pathname,
2431
- name: data.name,
2432
- meta: data.meta || {},
2433
- content: data.content,
2434
- contentStartPos
2435
- };
2436
- }
2437
- const etagResult = calculateEtagsFromVXJSONBuffer(buffer.subarray(0, bytesRead), true);
2438
- if (!etagResult.success) throw new Error(`Invalid VXJSON format: ${etagResult.error}. This violates the VXJSON specification.`);
2439
- const contentStartPos = etagResult.contentStartPos;
2440
- let metadataEnd = contentStartPos;
2441
- while (metadataEnd > 0) {
2442
- const byte = buffer[metadataEnd - 1];
2443
- if (byte === 44) {
2444
- metadataEnd--;
2445
- break;
2446
- }
2447
- if (byte === 32 || byte === 9 || byte === 10 || byte === 13) metadataEnd--;
2448
- else break;
2449
- }
2450
- const metadataBuffer = new Uint8Array(metadataEnd + 1);
2451
- metadataBuffer.set(buffer.subarray(0, metadataEnd));
2452
- metadataBuffer[metadataEnd] = 125;
2453
- const partialContent = textDecoder$1.decode(metadataBuffer);
2454
- const data = JSON.parse(partialContent);
2455
- return {
2456
- id: data.id,
2457
- created: data.created,
2458
- modified: data.modified,
2459
- publishAt: data.publishAt,
2460
- unpublishAt: data.unpublishAt,
2461
- previousPathnames: data.previousPathnames,
2462
- pathname: data.pathname,
2463
- name: data.name,
2464
- meta: data.meta || {},
2465
- contentStartPos
2466
- };
2467
- }
2468
- /**
2469
- * Find the position of the "content" field in a VXJSON buffer
2470
- * Returns -1 if not found
2471
- */
2472
- static findContentPosition(buffer) {
2473
- const etagResult = calculateEtagsFromVXJSONBuffer(buffer);
2474
- if (etagResult.success) return etagResult.contentStartPos;
2475
- return -1;
2476
- }
2477
- /**
2478
- * Calculate ETags for a VXJSON buffer
2479
- * Returns null if the buffer is not valid VXJSON
2480
- */
2481
- static calculateEtagsOnly(buffer) {
2482
- const result = calculateEtagsFromVXJSONBuffer(buffer);
2483
- if (!result.success) return null;
2484
- return {
2485
- metaEtag: result.metaEtag,
2486
- contentEtag: result.contentEtag
2487
- };
2488
- }
2489
- /**
2490
- * Create a dual ETag string from a VXJSON buffer
2491
- * Returns null if the buffer is not valid VXJSON
2492
- */
2493
- static createEtag(buffer) {
2494
- const etags = VXJSON.calculateEtagsOnly(buffer);
2495
- if (!etags) return null;
2496
- return etags.contentEtag ? `${etags.metaEtag}.${etags.contentEtag}` : etags.metaEtag;
2497
- }
2498
- /**
2499
- * Validate that a VXJSON buffer has the correct structure
2500
- * (content field must be last)
2501
- */
2502
- static isValid(buffer) {
2503
- return calculateEtagsFromVXJSONBuffer(buffer).success;
2504
- }
2505
- /**
2506
- * Parse a complete VXJSON file from string
2507
- */
2508
- static parse(content) {
2509
- return JSON.parse(content);
2510
- }
2511
- /**
2512
- * Parse a complete VXJSON file from buffer
2513
- */
2514
- static parseBuffer(buffer) {
2515
- const content = textDecoder$1.decode(buffer);
2516
- return VXJSON.parse(content);
2517
- }
2518
- /**
2519
- * Calculate both ETags from a VXJSON buffer using views
2520
- * Finds the "content" field position and validates it's the last field
2521
- * @param buffer - The complete file buffer
2522
- * @returns Result with ETags or validation error
2523
- */
2524
- static calculateETags = calculateEtagsFromVXJSONBuffer;
2525
- /**
2526
- * Calculate a simple single etag from the entire buffer
2527
- * Used for data files that don't follow the content-last convention
2528
- */
2529
- static calculateSimpleEtag(buffer) {
2530
- return calculateMetaEtagFromBuffer(buffer);
2531
- }
2532
- /**
2533
- * Serialize a VXJSONFile to VXJSON format string
2534
- * Ensures content field is last and enforces 4KB constraint efficiently
2535
- */
2536
- static serialize(data) {
2537
- const { content, ...metadataFields } = data;
2538
- if (content === void 0 || content === null) throw new Error("VXJSON format requires a \"content\" field");
2539
- const sortedMetadata = sortKeys(metadataFields, { deep: true });
2540
- const metadataJson = JSON.stringify(sortedMetadata, (_key, value) => {
2541
- if (value === "") return;
2542
- return value;
2543
- }, " ");
2544
- const wrappedContent = JSON.stringify({ c: sortKeys(content, { deep: true }) }, null, " ");
2545
- const contentJson = wrappedContent.slice(wrappedContent.indexOf(": ") + 2, -2);
2546
- const metadataWithoutClosing = metadataJson.slice(0, -2);
2547
- const contentFieldPrefix = ",\n \"content\": ";
2548
- const contentKeyPosition = metadataWithoutClosing.length + 1 + 2;
2549
- const maxContentKeyPosition = 4086;
2550
- if (contentKeyPosition > maxContentKeyPosition) throw new Error(`VXJSON format violation: metadata too large. "content" field would start at position ${contentKeyPosition}, but must start within ${maxContentKeyPosition} bytes. Reduce metadata size by ${contentKeyPosition - maxContentKeyPosition} bytes.`);
2551
- return `${metadataWithoutClosing}${contentFieldPrefix}${contentJson}\n}`;
2552
- }
2553
- };
2554
-
2555
- //#endregion
2556
- //#region src/filesystem-content-api.ts
2557
- function ensureError(error) {
2558
- if (error instanceof Error) return error;
2559
- return new Error(String(error));
2560
- }
2561
- const textDecoder = new TextDecoder();
2562
- function parse4KBMDX(buffer, bytesRead) {
2563
- const { data: frontmatter } = matter(textDecoder.decode(buffer.subarray(0, bytesRead)));
2564
- const delimiter = new TextEncoder().encode("---");
2565
- let delimiterCount = 0;
2566
- let contentStartPos = -1;
2567
- for (let i = 0; i <= bytesRead - delimiter.length; i++) {
2568
- let match = true;
2569
- for (let j = 0; j < delimiter.length; j++) if (buffer[i + j] !== delimiter[j]) {
2570
- match = false;
2571
- break;
2572
- }
2573
- if (match) {
2574
- delimiterCount++;
2575
- if (delimiterCount === 2) {
2576
- contentStartPos = i + delimiter.length;
2577
- while (contentStartPos < bytesRead && (buffer[contentStartPos] === 10 || buffer[contentStartPos] === 13)) contentStartPos++;
2578
- break;
2579
- }
2580
- }
2581
- }
2582
- const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
2583
- return {
2584
- id,
2585
- created,
2586
- modified,
2587
- publishAt,
2588
- unpublishAt,
2589
- meta: metaFields,
2590
- contentStartPos
2591
- };
2592
- }
2593
- /**
2594
- * FileSystem-based Content API Implementation
2595
- *
2596
- * Stores content as files on disk in a git-friendly format:
2597
- * - Pages: /{site}/pages/{filename}.{locale}.vxjson
2598
- * - Blocks: /blocks/{collection}/{filename}.{locale}.{mdx|vxjson}
2599
- *
2600
- * ## Indexing
2601
- *
2602
- * Content is indexed at startup for performance. The index is cached per
2603
- * content root path and cleared when the process restarts.
2604
- *
2605
- * ## Read-Repair
2606
- *
2607
- * Since files can be modified externally (git, editors), this implementation:
2608
- *
2609
- * 1. Repairs invalid VXJSON files (ensures "content" field is last)
2610
- * 2. Adds missing required fields (id, created, modified)
2611
- * 3. Handles files added after initial indexing
2612
- * 4. Updates the index when files are repaired or discovered
2613
- *
2614
- * ## Performance
2615
- *
2616
- * - Initial indexing reads only first 4KB of each file
2617
- * - Full content is loaded on demand
2618
- * - ETags are calculated using streaming for efficiency
2619
- */
2620
- var FileSystemContentAPI = class FileSystemContentAPI {
2621
- contentRoot;
2622
- absoluteContentRoot;
2623
- contentIndex;
2624
- sitesConfig;
2625
- blocks;
2626
- data;
2627
- sites;
2628
- get normalizedContentRoot() {
2629
- return this.contentRoot;
2630
- }
2631
- constructor(contentRoot, canvasDir, sitesConfig, contentIndex) {
2632
- if (contentRoot.startsWith("./")) this.contentRoot = contentRoot.slice(2);
2633
- else if (contentRoot.startsWith("/")) this.contentRoot = contentRoot;
2634
- else this.contentRoot = contentRoot;
2635
- this.absoluteContentRoot = resolve$1(this.contentRoot);
2636
- this.sitesConfig = sitesConfig;
2637
- this.contentIndex = contentIndex;
2638
- this.blocks = new Blocks(this, this.contentIndex.getBlockIndex());
2639
- this.data = new Data(this, this.contentIndex.getDataIndex());
2640
- this.sites = mapSiteNames(sitesConfig, (siteName) => {
2641
- const siteIndex = this.contentIndex.getSiteIndex(siteName);
2642
- if (!siteIndex) throw new Error(`Site index not found for ${siteName}`);
2643
- return new Site(siteName, this, siteIndex);
2644
- });
2645
- }
2646
- static async create(options) {
2647
- const { canvasDir } = options;
2648
- const contentRoot = options.contentRoot;
2649
- const sitesPath = join$1(resolve$1(contentRoot), "sites.json");
2650
- let sitesConfig;
2651
- try {
2652
- const content = await readFile(sitesPath, "utf-8");
2653
- const parsed = JSON.parse(content);
2654
- if (!parsed.sites || typeof parsed.sites !== "object") {
2655
- console.warn(`Warning: sites.json has invalid structure at ${sitesPath}. Expected 'sites' property. Using default configuration.`);
2656
- sitesConfig = {
2657
- sites: {},
2658
- globalLocales: ["en"]
2659
- };
2660
- } else if (!parsed.globalLocales || !Array.isArray(parsed.globalLocales)) {
2661
- console.warn(`Warning: sites.json is missing 'globalLocales' array at ${sitesPath}. Using default global locales.`);
2662
- sitesConfig = {
2663
- sites: parsed.sites,
2664
- globalLocales: ["en"]
2665
- };
2666
- } else sitesConfig = parsed;
2667
- } catch (error) {
2668
- console.warn(`Warning: sites.json is missing at ${sitesPath}. Using empty configuration.`);
2669
- sitesConfig = {
2670
- sites: {},
2671
- globalLocales: ["en"]
2672
- };
2673
- }
2674
- const normalizedContentRoot = contentRoot.startsWith("./") ? contentRoot.slice(2) : contentRoot;
2675
- const contentIndex = await ContentIndex.getCachedOrCreate(normalizedContentRoot, sitesConfig);
2676
- const api = new FileSystemContentAPI(contentRoot, canvasDir, sitesConfig, contentIndex);
2677
- if (contentIndex.entryCount === 0) await api.indexAllContent();
2678
- return api;
2679
- }
2680
- /**
2681
- * Clear all caches - useful for testing
2682
- */
2683
- static clearCaches() {
2684
- ContentIndex.clearCache();
2685
- }
2686
- async indexAllContent() {
2687
- this.contentIndex.clear();
2688
- const files = await this.scanContentFiles();
2689
- const OPTIMAL_BATCH_SIZE = 1e3;
2690
- console.log(`Indexing ${files.length} content files...`);
2691
- const bufferCount = Math.min(files.length, OPTIMAL_BATCH_SIZE);
2692
- const buffers = Array.from({ length: bufferCount }, () => new Uint8Array(4096));
2693
- for (let i = 0; i < files.length; i += OPTIMAL_BATCH_SIZE) {
2694
- const batch = files.slice(i, i + OPTIMAL_BATCH_SIZE);
2695
- await Promise.all(batch.map(async (filePath, index) => {
2696
- try {
2697
- const result = await this.parseFileHeaderWithRepair(filePath, buffers[index]);
2698
- if (result) {
2699
- const { manifest, localeVersion, content } = result;
2700
- this.contentIndex.addContent(manifest, localeVersion, content);
2701
- }
2702
- } catch (error) {
2703
- console.error(`Failed to index ${filePath}:`, error);
2704
- }
2705
- }));
2706
- }
2707
- }
2708
- async parseFileHeaderWithRepair(originalFilePath, buffer) {
2709
- let handle;
2710
- let bytesRead = 0;
2711
- let filePath = originalFilePath;
2712
- try {
2713
- handle = await open(filePath, "r");
2714
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
2715
- } catch (error) {
2716
- console.error(`Error reading ${filePath}:`, error);
2717
- throw error;
2718
- } finally {
2719
- await handle?.close();
2720
- }
2721
- try {
2722
- let relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
2723
- let parts = relativePath.split("/");
2724
- let site;
2725
- let collection;
2726
- let locale = "en";
2727
- let name;
2728
- let pathname;
2729
- let parsedData = {};
2730
- let kind;
2731
- if (parts[0] === "blocks") {
2732
- kind = "block";
2733
- if (parts.length === 2) {
2734
- collection = "general";
2735
- const filename = parts[1];
2736
- const generalDir = join$1(this.absoluteContentRoot, "blocks", "general");
2737
- try {
2738
- await mkdir(generalDir, { recursive: true });
2739
- } catch (error) {}
2740
- const newFilePath = join$1(generalDir, filename);
2741
- try {
2742
- await handle?.close();
2743
- handle = void 0;
2744
- try {
2745
- await (await open(newFilePath, "r")).close();
2746
- console.warn(`Cannot move ${filename} to blocks/general/: target file already exists`);
2747
- } catch (error) {
2748
- await rename(filePath, newFilePath);
2749
- console.log(`Repaired: Moved ${filename} to blocks/general/ collection`);
2750
- filePath = newFilePath;
2751
- relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
2752
- parts = relativePath.split("/");
2753
- handle = await open(filePath, "r");
2754
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
2755
- }
2756
- } catch (moveError) {
2757
- console.error(`Failed to move ${filename} to general collection:`, moveError);
2758
- handle = await open(filePath, "r");
2759
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
2760
- }
2761
- } else collection = parts[1];
2762
- const filename = parts[parts.length - 1];
2763
- const matchWithLocale = filename.match(/^(.+)\.(\w+)\.(mdx|vxjson)$/);
2764
- const matchWithoutLocale = filename.match(/^(.+)\.(mdx|vxjson)$/);
2765
- if (matchWithLocale) {
2766
- name = matchWithLocale[1];
2767
- locale = matchWithLocale[2];
2768
- } else if (matchWithoutLocale) {
2769
- name = matchWithoutLocale[1];
2770
- locale = this.contentIndex.getDefaultLocale("");
2771
- console.log(`Found file without locale suffix: ${filename}`);
2772
- const extension = matchWithoutLocale[2];
2773
- const newFilename = `${name}.${locale}.${extension}`;
2774
- const newFilePath = join$1(dirname$1(filePath), newFilename);
2775
- console.log(`Will rename to: ${newFilename} at ${newFilePath}`);
2776
- try {
2777
- await handle?.close();
2778
- handle = void 0;
2779
- await (await open(newFilePath, "r")).close();
2780
- console.warn(`Cannot rename ${filename} to ${newFilename}: target file already exists`);
2781
- } catch (error) {
2782
- console.log(`Target file doesn't exist, proceeding with rename`);
2783
- try {
2784
- await rename(filePath, newFilePath);
2785
- console.log(`Successfully renamed ${filename} to ${newFilename}`);
2786
- filePath = newFilePath;
2787
- relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
2788
- parts = relativePath.split("/");
2789
- handle = await open(filePath, "r");
2790
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
2791
- } catch (renameError) {
2792
- console.error(`Failed to rename ${filename}:`, renameError);
2793
- handle = await open(filePath, "r");
2794
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
2795
- }
2796
- }
2797
- }
2798
- if (filePath.endsWith(".mdx")) parsedData = parse4KBMDX(buffer, bytesRead);
2799
- else parsedData = VXJSON.parse4KB(buffer, bytesRead);
2800
- } else if (parts[0] === "data") {
2801
- kind = "data";
2802
- collection = parts[1];
2803
- const match = parts[parts.length - 1].match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.json$/);
2804
- if (match) {
2805
- name = match[1];
2806
- locale = match[2];
2807
- }
2808
- const content = textDecoder.decode(buffer.subarray(0, bytesRead));
2809
- try {
2810
- const jsonData = JSON.parse(content);
2811
- parsedData = {
2812
- id: jsonData.id,
2813
- type: "json",
2814
- created: jsonData.created,
2815
- modified: jsonData.modified,
2816
- publishAt: jsonData.publishAt,
2817
- unpublishAt: jsonData.unpublishAt,
2818
- meta: jsonData.meta || { title: name || "Untitled" },
2819
- data: jsonData.data,
2820
- name
2821
- };
2822
- } catch (error) {
2823
- console.error(`Failed to parse JSON data file ${filePath}:`, error);
2824
- return null;
2825
- }
2826
- } else {
2827
- kind = "page";
2828
- site = parts[0];
2829
- collection = parts[1];
2830
- const pathParts = parts.slice(2);
2831
- const match = pathParts[pathParts.length - 1].match(/^(.+)\.(\w+)\.vxjson$/);
2832
- if (match) {
2833
- locale = match[2];
2834
- pathParts[pathParts.length - 1] = match[1];
2835
- pathname = pathParts[pathParts.length - 1] === "index" ? "/" + pathParts.slice(0, -1).join("/") || "/" : "/" + pathParts.join("/");
2836
- }
2837
- parsedData = VXJSON.parse4KB(buffer, bytesRead);
2838
- }
2839
- const needsRepair = !parsedData.id || !parsedData.created || !parsedData.modified;
2840
- const id = parsedData.id || generateContentId();
2841
- const localeVersion = {
2842
- locale,
2843
- etag: "",
2844
- created: parsedData.created || (/* @__PURE__ */ new Date()).toISOString(),
2845
- modified: parsedData.modified || (/* @__PURE__ */ new Date()).toISOString(),
2846
- ...parsedData.publishAt && { publishAt: parsedData.publishAt },
2847
- ...parsedData.unpublishAt && { unpublishAt: parsedData.unpublishAt },
2848
- ...pathname && { pathname },
2849
- ...parsedData.previousPathnames && { previousPathnames: parsedData.previousPathnames },
2850
- ...name && { name },
2851
- meta: parsedData.meta || { title: name || "Untitled" }
2852
- };
2853
- const manifest = {
2854
- id,
2855
- type: parsedData.type || (filePath.endsWith(".mdx") ? "mdx" : filePath.endsWith(".json") ? "json" : "puck"),
2856
- kind,
2857
- site,
2858
- collection,
2859
- locales: { [locale]: localeVersion }
2860
- };
2861
- let content;
2862
- if (needsRepair) {
2863
- const repairedData = await this.performReadRepair(filePath, manifest, locale);
2864
- if (repairedData) {
2865
- content = repairedData.content;
2866
- localeVersion.etag = repairedData.etag;
2867
- localeVersion.modified = repairedData.modified;
2868
- return {
2869
- manifest,
2870
- locale,
2871
- localeVersion,
2872
- bytesRead,
2873
- content
2874
- };
2875
- }
2876
- console.error(`Failed to repair ${filePath}, skipping`);
2877
- return null;
2878
- }
2879
- if (bytesRead < 4096 || filePath.endsWith(".vxjson") && buffer[bytesRead - 1] === 125 || filePath.endsWith(".json") && buffer[bytesRead - 1] === 125) {
2880
- if (filePath.endsWith(".mdx")) {
2881
- const { content: mdx } = matter(textDecoder.decode(buffer.subarray(0, bytesRead)));
2882
- content = { mdx };
2883
- } else if (filePath.endsWith(".json")) {
2884
- const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
2885
- content = { data: JSON.parse(fullContent).data };
2886
- } else {
2887
- const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
2888
- content = JSON.parse(fullContent).content || {};
2889
- }
2890
- const validBuffer = buffer.subarray(0, bytesRead);
2891
- if (filePath.endsWith(".mdx")) {
2892
- const etags = calculateEtagsFromMdxBuffer(validBuffer, parsedData.contentStartPos || -1);
2893
- localeVersion.etag = `${etags.metaEtag}.${etags.contentEtag}`;
2894
- } else if (filePath.endsWith(".json")) localeVersion.etag = VXJSON.calculateSimpleEtag(validBuffer);
2895
- else {
2896
- const etagResult = VXJSON.calculateETags(validBuffer);
2897
- if (!etagResult.success) {
2898
- const repairedData = await this.performReadRepair(filePath, manifest, locale);
2899
- if (repairedData) {
2900
- content = repairedData.content;
2901
- localeVersion.etag = repairedData.etag;
2902
- localeVersion.modified = repairedData.modified;
2903
- return {
2904
- manifest,
2905
- locale,
2906
- localeVersion,
2907
- bytesRead,
2908
- content
2909
- };
2910
- }
2911
- console.error(`Failed to repair ${filePath}, skipping`);
2912
- return null;
2913
- }
2914
- localeVersion.etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
2915
- }
2916
- }
2917
- return {
2918
- manifest,
2919
- locale,
2920
- localeVersion,
2921
- bytesRead,
2922
- content
2923
- };
2924
- } catch (error) {
2925
- console.error(`Error indexing ${originalFilePath}:`, error);
2926
- return null;
2927
- }
2928
- }
2929
- /**
2930
- * Perform read-repair by writing back the file with missing fields
2931
- * This ensures stable IDs and timestamps across restarts
2932
- */
2933
- async performReadRepair(filePath, manifest, locale) {
2934
- try {
2935
- const now = (/* @__PURE__ */ new Date()).toISOString();
2936
- let needsWrite = false;
2937
- if (manifest.type === "mdx") {
2938
- const parsed = matter(await readFile(filePath, "utf-8"));
2939
- if (!parsed.data.id) {
2940
- parsed.data.id = manifest.id;
2941
- needsWrite = true;
2942
- }
2943
- if (!parsed.data.created) {
2944
- parsed.data.created = now;
2945
- needsWrite = true;
2946
- }
2947
- if (!parsed.data.modified) {
2948
- parsed.data.modified = now;
2949
- needsWrite = true;
2950
- }
2951
- if (needsWrite) {
2952
- const updatedContent = matter.stringify(parsed.content, parsed.data);
2953
- await writeFile(filePath, updatedContent);
2954
- console.log(`Repaired MDX file: ${filePath} (added missing fields)`);
2955
- const etags = calculateEtagsFromMdxBuffer(Buffer.from(updatedContent, "utf-8"), updatedContent.indexOf("\n---\n") + 5);
2956
- const etag = `${etags.metaEtag}.${etags.contentEtag}`;
2957
- return {
2958
- content: { mdx: parsed.content },
2959
- etag,
2960
- modified: parsed.data.modified || now
2961
- };
2962
- }
2963
- } else {
2964
- const content = await readFile(filePath, "utf-8");
2965
- const data = JSON.parse(content);
2966
- if (!data.id) {
2967
- data.id = manifest.id;
2968
- needsWrite = true;
2969
- }
2970
- if (!data.created) {
2971
- data.created = now;
2972
- needsWrite = true;
2973
- }
2974
- if (!data.modified) {
2975
- data.modified = now;
2976
- needsWrite = true;
2977
- }
2978
- needsWrite = true;
2979
- if (needsWrite) {
2980
- const vxjsonData = {
2981
- id: data.id,
2982
- type: data.type,
2983
- created: data.created,
2984
- modified: data.modified,
2985
- publishAt: data.publishAt,
2986
- unpublishAt: data.unpublishAt,
2987
- previousPathnames: data.previousPathnames,
2988
- meta: data.meta || {},
2989
- content: data.content || {}
2990
- };
2991
- const repairedJson = VXJSON.serialize(vxjsonData);
2992
- await writeFile(filePath, repairedJson);
2993
- console.log(`Repaired VXJSON file: ${filePath} (fixed field order or added missing fields)`);
2994
- const repairedBuffer = Buffer.from(repairedJson, "utf-8");
2995
- const etagResult = VXJSON.calculateETags(repairedBuffer);
2996
- if (!etagResult.success) {
2997
- console.error(`Failed to calculate ETags after repair: ${filePath}`);
2998
- return null;
2999
- }
3000
- const etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
3001
- return {
3002
- content: vxjsonData.content,
3003
- etag,
3004
- modified: vxjsonData.modified
3005
- };
3006
- }
3007
- }
3008
- return null;
3009
- } catch (error) {
3010
- console.error(`Failed to perform read-repair on ${filePath}:`, error);
3011
- return null;
3012
- }
3013
- }
3014
- async scanContentFiles() {
3015
- const files = [];
3016
- const contentRoot = this.absoluteContentRoot;
3017
- async function scan(dir, inDataDir = false) {
3018
- try {
3019
- const entries = await readdir(dir, { withFileTypes: true });
3020
- for (const entry of entries) {
3021
- const fullPath = join$1(dir, entry.name);
3022
- if (entry.isDirectory()) {
3023
- const isDataDir = dir === contentRoot && entry.name === "data";
3024
- await scan(fullPath, inDataDir || isDataDir);
3025
- } else if (entry.isFile()) {
3026
- if (entry.name.endsWith(".vxjson") || entry.name.endsWith(".mdx")) files.push(fullPath);
3027
- else if (inDataDir && entry.name.endsWith(".json")) files.push(fullPath);
3028
- }
3029
- }
3030
- } catch (error) {}
3031
- }
3032
- await scan(this.absoluteContentRoot);
3033
- return files;
3034
- }
3035
- getFilePath(manifest, { locale, name, pathname }) {
3036
- if (manifest.kind === "block") {
3037
- const ext = manifest.type === "mdx" ? "mdx" : "vxjson";
3038
- return join$1(this.absoluteContentRoot, "blocks", manifest.collection, `${name}.${locale}.${ext}`);
3039
- }
3040
- if (manifest.kind === "data") return join$1(this.absoluteContentRoot, "data", manifest.collection, `${name}.${locale}.json`);
3041
- if (manifest.kind === "page" && pathname && manifest.site) {
3042
- const basePath = pathname.replace(/^\//, "").replace(/\/$/, "") || "index";
3043
- return join$1(this.absoluteContentRoot, manifest.site, manifest.collection, `${basePath}.${locale}.vxjson`);
3044
- }
3045
- throw new Error(`Invalid manifest: ${JSON.stringify(manifest, null, 2)}`);
3046
- }
3047
- /**
3048
- * Parse a file path back into its components for checking against the path index
3049
- * Returns null if the path doesn't match expected patterns
3050
- */
3051
- parseFilePath(filePath) {
3052
- const parts = filePath.replace(this.absoluteContentRoot + "/", "").split("/");
3053
- const filename = parts[parts.length - 1];
3054
- if (parts[0] === "data" && parts.length === 3) {
3055
- const dataMatch = filename.match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.json$/);
3056
- if (!dataMatch) return null;
3057
- const [, name, locale] = dataMatch;
3058
- return {
3059
- kind: "data",
3060
- collection: parts[1],
3061
- name,
3062
- locale
3063
- };
3064
- }
3065
- const match = filename.match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.(?:vxjson|mdx)$/);
3066
- if (!match) return null;
3067
- const [, nameOrPath, locale] = match;
3068
- if (parts[0] === "blocks" && parts.length === 3) return {
3069
- kind: "block",
3070
- collection: parts[1],
3071
- name: nameOrPath,
3072
- locale
3073
- };
3074
- if (parts.length >= 3 && parts[0] !== "blocks") {
3075
- const site = parts[0];
3076
- const collection = parts[1];
3077
- const pathParts = parts.slice(2, -1);
3078
- pathParts.push(nameOrPath);
3079
- return {
3080
- kind: "page",
3081
- site,
3082
- collection,
3083
- pathname: "/" + pathParts.join("/"),
3084
- locale
3085
- };
3086
- }
3087
- return null;
3088
- }
3089
- async getContent(id) {
3090
- const manifest = this.contentIndex.getManifest(id);
3091
- if (!manifest) return null;
3092
- const readPromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {
3093
- const filePath = this.getFilePath(manifest, localeVersion);
3094
- return {
3095
- localeVersion,
3096
- content: await this.readLocaleFile(filePath, localeVersion.locale)
3097
- };
3098
- });
3099
- const results = await Promise.all(readPromises);
3100
- const locales = {};
3101
- for (const { localeVersion, content } of results) if (content) locales[localeVersion.locale] = {
3102
- ...localeVersion,
3103
- etag: content.etag,
3104
- content: content.content
3105
- };
3106
- return {
3107
- id: manifest.id,
3108
- site: manifest.site,
3109
- collection: manifest.collection,
3110
- type: manifest.type,
3111
- kind: manifest.kind,
3112
- locales
3113
- };
3114
- }
3115
- async getLocalized(id, locale) {
3116
- const manifest = this.contentIndex.getManifest(id);
3117
- if (!manifest) {
3118
- await this.reindex();
3119
- const updatedManifest = this.contentIndex.getManifest(id);
3120
- if (!updatedManifest || !updatedManifest.locales[locale]) return null;
3121
- return this.getLocalized(id, locale);
3122
- }
3123
- const localeVersion = manifest.locales[locale];
3124
- if (!localeVersion) return null;
3125
- const filePath = this.getFilePath(manifest, localeVersion);
3126
- const localeData = await this.readLocaleFile(filePath, locale);
3127
- if (!localeData) return null;
3128
- return {
3129
- id: manifest.id,
3130
- site: manifest.site,
3131
- collection: manifest.collection,
3132
- type: manifest.type,
3133
- kind: manifest.kind,
3134
- localized: {
3135
- ...localeVersion,
3136
- etag: localeData.etag,
3137
- content: localeData.content
3138
- }
3139
- };
3140
- }
3141
- async readLocaleFile(filePath, locale) {
3142
- try {
3143
- const buffer = await readFile(filePath);
3144
- const content = textDecoder.decode(buffer);
3145
- if (filePath.endsWith(".mdx")) {
3146
- const { data: frontmatter } = matter(content);
3147
- const etags = calculateEtagsFromMdxBuffer(buffer, findMdxContentStartPosition(buffer));
3148
- const etag = `${etags.metaEtag}.${etags.contentEtag}`;
3149
- const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
3150
- const result = {
3151
- locale,
3152
- etag,
3153
- created,
3154
- modified,
3155
- meta: metaFields,
3156
- content: { mdx: content }
3157
- };
3158
- if (frontmatter.publishAt !== void 0) result.publishAt = frontmatter.publishAt;
3159
- if (frontmatter.unpublishAt !== void 0) result.unpublishAt = frontmatter.unpublishAt;
3160
- return result;
3161
- }
3162
- const data = JSON.parse(content);
3163
- if (data.type === "json") {
3164
- const result = {
3165
- locale,
3166
- etag: VXJSON.calculateSimpleEtag(buffer),
3167
- created: data.created,
3168
- modified: data.modified,
3169
- meta: data.meta || {},
3170
- content: { data: data.data || {} }
3171
- };
3172
- if (data.publishAt !== void 0) result.publishAt = data.publishAt;
3173
- if (data.unpublishAt !== void 0) result.unpublishAt = data.unpublishAt;
3174
- return result;
3175
- }
3176
- const etagResult = VXJSON.calculateETags(buffer);
3177
- if (!etagResult.success) {
3178
- const repairedData = {
3179
- id: data.id,
3180
- type: data.type,
3181
- created: data.created,
3182
- modified: data.modified,
3183
- publishAt: data.publishAt,
3184
- unpublishAt: data.unpublishAt,
3185
- previousPathnames: data.previousPathnames,
3186
- meta: data.meta || {},
3187
- content: data.content || {}
3188
- };
3189
- const repairedJson = VXJSON.serialize(repairedData);
3190
- await writeFile(filePath, repairedJson);
3191
- const repairedBuffer = Buffer.from(repairedJson, "utf-8");
3192
- const repairedEtagResult = VXJSON.calculateETags(repairedBuffer);
3193
- if (!repairedEtagResult.success) throw new Error(`Failed to repair VXJSON file: ${filePath}`);
3194
- const etag = repairedEtagResult.contentEtag ? `${repairedEtagResult.metaEtag}.${repairedEtagResult.contentEtag}` : repairedEtagResult.metaEtag;
3195
- console.log(`Repaired VXJSON file: ${filePath}`);
3196
- const result = {
3197
- locale,
3198
- etag,
3199
- created: data.created,
3200
- modified: data.modified,
3201
- meta: data.meta || {},
3202
- content: data.content || {}
3203
- };
3204
- if (data.publishAt !== void 0) result.publishAt = data.publishAt;
3205
- if (data.unpublishAt !== void 0) result.unpublishAt = data.unpublishAt;
3206
- if (data.previousPathnames !== void 0) result.previousPathnames = data.previousPathnames;
3207
- return result;
3208
- }
3209
- const result = {
3210
- locale,
3211
- etag: etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag,
3212
- created: data.created,
3213
- modified: data.modified,
3214
- meta: data.meta || {},
3215
- content: data.content || {}
3216
- };
3217
- if (data.publishAt !== void 0) result.publishAt = data.publishAt;
3218
- if (data.unpublishAt !== void 0) result.unpublishAt = data.unpublishAt;
3219
- if (data.previousPathnames !== void 0) result.previousPathnames = data.previousPathnames;
3220
- return result;
3221
- } catch (error) {
3222
- return null;
3223
- }
3224
- }
3225
- async createContent(data) {
3226
- const validation = validateCreateContent(data, this.sites, this.blocks, this.data);
3227
- if (!validation.valid) return {
3228
- success: false,
3229
- reason: validation.reason,
3230
- error: validation.error ? new Error(validation.error) : void 0,
3231
- existingId: validation.existingId
3232
- };
3233
- const id = generateContentId();
3234
- const now = data.created || (/* @__PURE__ */ new Date()).toISOString();
3235
- try {
3236
- const manifest = {
3237
- id,
3238
- type: data.type,
3239
- kind: data.kind,
3240
- site: data.site,
3241
- collection: data.collection,
3242
- locales: {}
3243
- };
3244
- const contentCache = {};
3245
- for (const [locale, localeData] of Object.entries(data.locales)) {
3246
- const content = localeData.content;
3247
- const title = localeData.meta?.title || data.meta?.title;
3248
- if (!title) return {
3249
- success: false,
3250
- reason: "write_error",
3251
- error: /* @__PURE__ */ new Error("Title is required in metadata")
3252
- };
3253
- const meta = {
3254
- title,
3255
- ...data.meta,
3256
- ...localeData.meta
3257
- };
3258
- const fileData = {
3259
- id,
3260
- type: data.type,
3261
- created: now,
3262
- modified: now,
3263
- publishAt: localeData.publishAt && typeof localeData.publishAt === "string" ? localeData.publishAt : void 0,
3264
- unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === "string" ? localeData.unpublishAt : void 0,
3265
- meta,
3266
- content
3267
- };
3268
- const filePath = this.getFilePath(manifest, {
3269
- locale,
3270
- name: data.name,
3271
- pathname: localeData.pathname
3272
- });
3273
- await mkdir(dirname$1(filePath), { recursive: true });
3274
- let etag;
3275
- if (data.type === "mdx") {
3276
- const mdxContent = serializeMdxWithFrontmatter({
3277
- id,
3278
- created: now,
3279
- modified: now,
3280
- ...localeData.publishAt && { publishAt: localeData.publishAt },
3281
- ...localeData.unpublishAt && { unpublishAt: localeData.unpublishAt },
3282
- ...meta
3283
- }, content.mdx || "");
3284
- await writeFile(filePath, mdxContent);
3285
- const mdxBuffer = new TextEncoder().encode(mdxContent);
3286
- const contentStartMarker = new TextEncoder().encode("---\n\n");
3287
- let contentPos = -1;
3288
- for (let i = 0; i <= mdxBuffer.length - contentStartMarker.length; i++) {
3289
- let match = true;
3290
- for (let j = 0; j < contentStartMarker.length; j++) if (mdxBuffer[i + j] !== contentStartMarker[j]) {
3291
- match = false;
3292
- break;
3293
- }
3294
- if (match) {
3295
- contentPos = i + contentStartMarker.length;
3296
- break;
3297
- }
3298
- }
3299
- const etags = calculateEtagsFromMdxBuffer(mdxBuffer, contentPos);
3300
- etag = `${etags.metaEtag}.${etags.contentEtag}`;
3301
- } else if (data.type === "json") {
3302
- const dataFileContent = {
3303
- id,
3304
- type: "json",
3305
- created: now,
3306
- modified: now,
3307
- ...localeData.publishAt && typeof localeData.publishAt === "string" && { publishAt: localeData.publishAt },
3308
- ...localeData.unpublishAt && typeof localeData.unpublishAt === "string" && { unpublishAt: localeData.unpublishAt },
3309
- meta,
3310
- data: content.data || {}
3311
- };
3312
- const jsonContent = JSON.stringify(sortKeys(dataFileContent, { deep: true }), null, " ");
3313
- await writeFile(filePath, jsonContent);
3314
- const jsonBuffer = new TextEncoder().encode(jsonContent);
3315
- etag = VXJSON.calculateSimpleEtag(jsonBuffer);
3316
- } else {
3317
- const jsonContent = VXJSON.serialize(fileData);
3318
- const jsonBuffer = new TextEncoder().encode(jsonContent);
3319
- const etagResult = VXJSON.calculateETags(jsonBuffer);
3320
- if (!etagResult.success) throw new Error(`Invalid VXJSON format when creating content: ${etagResult.error}`);
3321
- etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
3322
- await writeFile(filePath, jsonContent);
3323
- }
3324
- const localeVersion = buildLocaleVersion({
3325
- locale,
3326
- etag,
3327
- created: now,
3328
- modified: now,
3329
- meta,
3330
- kind: data.kind,
3331
- pathname: data.kind === "page" ? localeData.pathname : void 0,
3332
- name: data.kind === "block" || data.kind === "data" ? data.name : void 0,
3333
- publishAt: localeData.publishAt && typeof localeData.publishAt === "string" ? localeData.publishAt : void 0,
3334
- unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === "string" ? localeData.unpublishAt : void 0
3335
- });
3336
- manifest.locales[locale] = localeVersion;
3337
- contentCache[locale] = content;
3338
- }
3339
- for (const localeVersion of localesOf(manifest)) {
3340
- const { locale } = localeVersion;
3341
- this.contentIndex.addContent(manifest, localeVersion, contentCache[locale]);
3342
- }
3343
- return {
3344
- success: true,
3345
- id
3346
- };
3347
- } catch (error) {
3348
- return {
3349
- success: false,
3350
- reason: "write_error",
3351
- error: ensureError(error)
3352
- };
3353
- }
3354
- }
3355
- async updateLocalized(input) {
3356
- const { id, locale, data, etag } = input;
3357
- const manifest = this.contentIndex.getManifest(id);
3358
- if (!manifest) return {
3359
- success: false,
3360
- reason: "not_found"
3361
- };
3362
- const localeVersion = manifest.locales[locale];
3363
- if (!localeVersion) return {
3364
- success: false,
3365
- reason: "not_found"
3366
- };
3367
- const filePath = this.getFilePath(manifest, localeVersion);
3368
- const current = await this.readLocaleFile(filePath, locale);
3369
- if (!current) return {
3370
- success: false,
3371
- reason: "not_found"
3372
- };
3373
- const currentEtag = current.etag;
3374
- if (manifest.kind === "data") {
3375
- if (etag !== currentEtag) return {
3376
- success: false,
3377
- reason: "stale_write",
3378
- currentEtag
3379
- };
3380
- } else {
3381
- const etagParts = parseDualEtag(etag);
3382
- const currentParts = parseDualEtag(currentEtag);
3383
- if (!etagParts || !currentParts) return {
3384
- success: false,
3385
- reason: "stale_write",
3386
- currentEtag
3387
- };
3388
- const updateScope = analyzeUpdateScope(data);
3389
- const updatingMeta = (updateScope & UPDATE_SCOPE.META) !== 0;
3390
- const updatingContent = (updateScope & UPDATE_SCOPE.CONTENT) !== 0;
3391
- if (updatingMeta && etagParts.meta !== currentParts.meta) return {
3392
- success: false,
3393
- reason: "stale_write",
3394
- currentEtag
3395
- };
3396
- if (updatingContent && etagParts.content !== currentParts.content) return {
3397
- success: false,
3398
- reason: "stale_write",
3399
- currentEtag
3400
- };
3401
- }
3402
- let modified;
3403
- if (shouldUpdateModifiedTimestamp(data)) modified = data.modified || (/* @__PURE__ */ new Date()).toISOString();
3404
- else if (data.modified) modified = data.modified;
3405
- else modified = current.modified;
3406
- const { sortedMeta: newMeta, valid: metaValid, error: metaError } = validateAndPrepareMetadata({
3407
- ...current.meta,
3408
- ...data.meta ? data.meta : {}
3409
- });
3410
- if (!newMeta || !metaValid) return {
3411
- success: false,
3412
- reason: "write_error",
3413
- error: new Error(metaError)
3414
- };
3415
- const newContent = data.content ? {
3416
- ...current.content,
3417
- ...data.content
3418
- } : current.content;
3419
- if (data.pathname && manifest.kind === "page" && manifest.site) {
3420
- const site = this.sites[manifest.site];
3421
- if (site) {
3422
- const existingId = site.getPathnameConflict(data.pathname, locale, id);
3423
- if (existingId) return {
3424
- success: false,
3425
- reason: "write_error",
3426
- error: /* @__PURE__ */ new Error(`Pathname ${data.pathname} is already taken by content ${existingId}`)
3427
- };
3428
- }
3429
- }
3430
- if (data.name && (manifest.kind === "block" || manifest.kind === "data")) {
3431
- const existing = (manifest.kind === "block" ? this.contentIndex.getBlockIndex() : this.contentIndex.getDataIndex()).getByName(manifest.collection, data.name);
3432
- if (existing && existing.id !== id) {
3433
- const existingTitle = Object.values(existing.locales).find((lv) => lv !== void 0)?.meta?.title;
3434
- const kindLabel = manifest.kind === "block" ? "Block" : "Data";
3435
- return {
3436
- success: false,
3437
- reason: "write_error",
3438
- error: /* @__PURE__ */ new Error(`${kindLabel} name "${data.name}" is already in use${existingTitle ? ` by "${existingTitle}"` : ""}`)
3439
- };
3440
- }
3441
- }
3442
- const pathnameHistory = buildPathnameHistory(localeVersion.pathname, data.pathname, isContentPublished({
3443
- publishAt: resolvePublishDate(data.publishAt, current.publishAt),
3444
- unpublishAt: resolvePublishDate(data.unpublishAt, current.unpublishAt)
3445
- }), (/* @__PURE__ */ new Date()).toISOString());
3446
- try {
3447
- let targetFilePath = filePath;
3448
- if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname && manifest.site) {
3449
- const newLocaleVersion = {
3450
- ...localeVersion,
3451
- pathname: data.pathname
3452
- };
3453
- targetFilePath = this.getFilePath(manifest, newLocaleVersion);
3454
- await mkdir(dirname$1(targetFilePath), { recursive: true });
3455
- } else if (data.name && localeVersion.name && data.name !== localeVersion.name && manifest.kind === "block") {
3456
- const newLocaleVersion = {
3457
- ...localeVersion,
3458
- name: data.name
3459
- };
3460
- targetFilePath = this.getFilePath(manifest, newLocaleVersion);
3461
- await mkdir(dirname$1(targetFilePath), { recursive: true });
3462
- }
3463
- if (targetFilePath.endsWith(".mdx")) {
3464
- const publishAt = resolvePublishDate(data.publishAt, current.publishAt);
3465
- const unpublishAt = resolvePublishDate(data.unpublishAt, current.unpublishAt);
3466
- const frontmatterData = {
3467
- id: manifest.id,
3468
- created: current.created,
3469
- modified,
3470
- ...publishAt && { publishAt },
3471
- ...unpublishAt && { unpublishAt },
3472
- ...newMeta
3473
- };
3474
- let mdxContentPart = newContent.mdx || "";
3475
- if (mdxContentPart.startsWith("---")) {
3476
- const { content: contentOnly } = matter(mdxContentPart);
3477
- mdxContentPart = contentOnly;
3478
- }
3479
- const mdxContent = serializeMdxWithFrontmatter(frontmatterData, mdxContentPart);
3480
- await atomicWriteFile(targetFilePath, mdxContent);
3481
- } else if (targetFilePath.endsWith(".json")) {
3482
- const fileContent = JSON.parse(await readFile(filePath, "utf-8"));
3483
- const updatedFile = {
3484
- id: fileContent.id,
3485
- type: "json",
3486
- created: fileContent.created,
3487
- modified,
3488
- ...fileContent.publishAt && { publishAt: fileContent.publishAt },
3489
- ...fileContent.unpublishAt && { unpublishAt: fileContent.unpublishAt },
3490
- meta: newMeta,
3491
- data: sortKeys(newContent.data || {}, { deep: true })
3492
- };
3493
- if ("publishAt" in data) if (data.publishAt) updatedFile.publishAt = data.publishAt;
3494
- else delete updatedFile.publishAt;
3495
- if ("unpublishAt" in data) if (data.unpublishAt) updatedFile.unpublishAt = data.unpublishAt;
3496
- else delete updatedFile.unpublishAt;
3497
- const serializedContent = JSON.stringify(sortKeys(updatedFile, { deep: true }), null, " ");
3498
- await atomicWriteFile(targetFilePath, serializedContent);
3499
- } else {
3500
- const fileContent = JSON.parse(await readFile(filePath, "utf-8"));
3501
- const updatedFile = {
3502
- id: fileContent.id,
3503
- type: fileContent.type,
3504
- created: fileContent.created,
3505
- modified,
3506
- publishAt: fileContent.publishAt,
3507
- unpublishAt: fileContent.unpublishAt,
3508
- previousPathnames: fileContent.previousPathnames,
3509
- meta: newMeta,
3510
- content: sortKeys(newContent, { deep: true })
3511
- };
3512
- if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname) {
3513
- if (isContentPublished(current)) {
3514
- if (!updatedFile.previousPathnames) updatedFile.previousPathnames = {};
3515
- updatedFile.previousPathnames[localeVersion.pathname] = modified;
3516
- }
3517
- }
3518
- if ("publishAt" in data) if (data.publishAt) updatedFile.publishAt = data.publishAt;
3519
- else delete updatedFile.publishAt;
3520
- if ("unpublishAt" in data) if (data.unpublishAt) updatedFile.unpublishAt = data.unpublishAt;
3521
- else delete updatedFile.unpublishAt;
3522
- const serializedContent = VXJSON.serialize(updatedFile);
3523
- await atomicWriteFile(targetFilePath, serializedContent);
3524
- }
3525
- const writtenBuffer = await readFile(targetFilePath);
3526
- let newEtag;
3527
- if (targetFilePath.endsWith(".mdx")) {
3528
- const contentStartMarker = new TextEncoder().encode("---\n\n");
3529
- let contentPos = -1;
3530
- for (let i = 0; i <= writtenBuffer.length - contentStartMarker.length; i++) {
3531
- let match = true;
3532
- for (let j = 0; j < contentStartMarker.length; j++) if (writtenBuffer[i + j] !== contentStartMarker[j]) {
3533
- match = false;
3534
- break;
3535
- }
3536
- if (match) {
3537
- contentPos = i + contentStartMarker.length;
3538
- break;
3539
- }
3540
- }
3541
- const etags = calculateEtagsFromMdxBuffer(writtenBuffer, contentPos);
3542
- newEtag = `${etags.metaEtag}.${etags.contentEtag}`;
3543
- } else if (targetFilePath.endsWith(".json")) newEtag = VXJSON.calculateSimpleEtag(writtenBuffer);
3544
- else {
3545
- const etagResult = VXJSON.calculateETags(writtenBuffer);
3546
- if (!etagResult.success) throw new Error(`Invalid VXJSON format when updating content: ${etagResult.error}`);
3547
- newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
3548
- }
3549
- const updatedLocaleVersion = {
3550
- ...localeVersion,
3551
- etag: newEtag,
3552
- modified,
3553
- meta: newMeta,
3554
- ...data.pathname && { pathname: data.pathname },
3555
- ...data.name && { name: data.name }
3556
- };
3557
- if (current.publishAt && !("publishAt" in data)) updatedLocaleVersion.publishAt = current.publishAt;
3558
- if (current.unpublishAt && !("unpublishAt" in data)) updatedLocaleVersion.unpublishAt = current.unpublishAt;
3559
- updatePublishDates(updatedLocaleVersion, data);
3560
- if (Object.keys(pathnameHistory).length > 0) updatedLocaleVersion.previousPathnames = {
3561
- ...localeVersion.previousPathnames,
3562
- ...pathnameHistory
3563
- };
3564
- else {
3565
- const existingPreviousPathnames = localeVersion.previousPathnames;
3566
- if (existingPreviousPathnames && Object.keys(existingPreviousPathnames).length > 0) updatedLocaleVersion.previousPathnames = existingPreviousPathnames;
3567
- else delete updatedLocaleVersion.previousPathnames;
3568
- }
3569
- const oldLocaleVersion = manifest.locales[locale];
3570
- try {
3571
- manifest.locales[locale] = updatedLocaleVersion;
3572
- this.contentIndex.addContent(manifest, updatedLocaleVersion, newContent);
3573
- if (targetFilePath !== filePath) try {
3574
- await unlink(filePath);
3575
- } catch (error) {
3576
- console.warn(`Failed to delete old file ${filePath}:`, error);
3577
- }
3578
- } catch (error) {
3579
- manifest.locales[locale] = oldLocaleVersion;
3580
- if (targetFilePath !== filePath) try {
3581
- await unlink(targetFilePath);
3582
- } catch {}
3583
- throw error;
1125
+ user: {
1126
+ email: typeof payload.email === "string" && payload.email ? payload.email : void 0,
1127
+ sub: typeof payload.sub === "string" && payload.sub ? payload.sub : void 0
3584
1128
  }
3585
- return {
3586
- success: true,
3587
- etag: newEtag,
3588
- modified: /* @__PURE__ */ new Date()
3589
- };
3590
- } catch (error) {
3591
- return {
3592
- success: false,
3593
- reason: "write_error",
3594
- error: ensureError(error)
3595
- };
3596
- }
3597
- }
3598
- async deleteContent(id, etag) {
3599
- const manifest = this.contentIndex.getManifest(id);
3600
- if (!manifest) return {
3601
- success: false,
3602
- reason: "not_found",
3603
- error: /* @__PURE__ */ new Error("Content not found")
3604
1129
  };
3605
- let matchingLocale;
3606
- for (const localeVersion of localesOf(manifest)) if (localeVersion.etag === etag) {
3607
- matchingLocale = localeVersion;
3608
- break;
3609
- }
3610
- if (!matchingLocale) return {
3611
- success: false,
3612
- reason: "stale_write",
3613
- currentEtag: Array.from(localesOf(manifest))[0]?.etag || "",
3614
- error: /* @__PURE__ */ new Error("Invalid etag - must match at least one locale")
1130
+ } catch (error) {
1131
+ return {
1132
+ valid: false,
1133
+ required: true,
1134
+ error: error instanceof Error ? error.message : "Validation failed"
3615
1135
  };
3616
- try {
3617
- const deletePromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {
3618
- await unlink(this.getFilePath(manifest, localeVersion));
3619
- });
3620
- await Promise.all(deletePromises);
3621
- this.contentIndex.removeEntry(id);
3622
- return { success: true };
3623
- } catch (error) {
3624
- return {
3625
- success: false,
3626
- error: ensureError(error)
3627
- };
3628
- }
3629
1136
  }
3630
- async deleteLocalized(input) {
3631
- const { id, locale, etag } = input;
3632
- const manifest = this.contentIndex.getManifest(id);
3633
- if (!manifest) return {
3634
- success: false,
3635
- reason: "not_found",
3636
- error: /* @__PURE__ */ new Error("Content not found")
3637
- };
3638
- const localeVersion = manifest.locales[locale];
3639
- if (!localeVersion) return {
3640
- success: false,
3641
- reason: "not_found",
3642
- error: /* @__PURE__ */ new Error("Locale not found")
3643
- };
3644
- if (localeVersion.etag !== etag) return {
3645
- success: false,
3646
- reason: "stale_write",
3647
- currentEtag: localeVersion.etag,
3648
- error: /* @__PURE__ */ new Error("Invalid etag for locale")
3649
- };
3650
- if (Object.keys(manifest.locales).length === 1) return {
3651
- success: false,
3652
- error: /* @__PURE__ */ new Error("Cannot delete the last locale. Use deleteContent to delete all content.")
3653
- };
1137
+ }
1138
+ //#endregion
1139
+ //#region src/component-registry.ts
1140
+ /**
1141
+ * Component Registry for managing linked and unlinked components
1142
+ *
1143
+ * Registry is stored at {canvasDir}/components/registry.json
1144
+ * Component IDs must follow the format: vx-{uuid}
1145
+ */
1146
+ var ComponentRegistry = class {
1147
+ registryPath;
1148
+ registry = {};
1149
+ initialized = false;
1150
+ constructor(canvasDir) {
1151
+ this.registryPath = join(canvasDir, "components", "registry.json");
1152
+ }
1153
+ /**
1154
+ * Initialize the registry by loading from disk or creating new
1155
+ */
1156
+ async initialize() {
1157
+ if (this.initialized) return;
3654
1158
  try {
3655
- await unlink(this.getFilePath(manifest, localeVersion));
3656
- manifest.locales[locale] = void 0;
3657
- this.contentIndex.removeLocale(manifest.id, locale);
3658
- return { success: true };
1159
+ const content = await readFile(this.registryPath, "utf-8");
1160
+ this.registry = JSON.parse(content);
3659
1161
  } catch (error) {
3660
- return {
3661
- success: false,
3662
- error: ensureError(error)
3663
- };
1162
+ if (error.code === "ENOENT") await this.save();
1163
+ else throw error;
3664
1164
  }
1165
+ this.initialized = true;
3665
1166
  }
3666
- getSite(siteName) {
3667
- if (siteName === "blocks") throw new Error("Use `blocks` property instead of getSite(\"blocks\")");
3668
- return this.sites[siteName] || null;
3669
- }
3670
- *listAllContent(filters) {
3671
- yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);
1167
+ /**
1168
+ * Validate component ID format (vx-{uuid})
1169
+ */
1170
+ validateComponentId(id) {
1171
+ if (!/^vx-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) throw new Error("Invalid component ID format. Expected: vx-{uuid}");
3672
1172
  }
3673
- *findUntranslatedContent(targetLocale, options) {
3674
- yield* this.contentIndex.findUntranslatedContent(targetLocale, options);
1173
+ /**
1174
+ * Save registry to disk atomically
1175
+ */
1176
+ async save() {
1177
+ await mkdir(dirname(this.registryPath), { recursive: true });
1178
+ const sorted = sortKeys(this.registry, { deep: true });
1179
+ const content = JSON.stringify(sorted, null, 2);
1180
+ await atomicWriteFile(this.registryPath, content);
3675
1181
  }
3676
1182
  /**
3677
- * Reindex files that were added or changed after initial creation
3678
- *
3679
- * This method:
3680
- * 1. Either scans for all content files or processes specific paths
3681
- * 2. Uses the path index to check if files are already indexed
3682
- * 3. Indexes new files or force-reindexes specified files
3683
- * 4. Optionally handles file deletions
3684
- *
3685
- * @param paths - Optional array of specific file paths to reindex. If not provided, scans all content files.
3686
- * @param options - Options for reindexing behavior
3687
- * @returns Statistics about the reindexing operation
1183
+ * Register a new component or update existing
3688
1184
  */
3689
- async reindex(paths, options) {
3690
- const filesToProcess = paths || await this.scanContentFiles();
3691
- let filesSkipped = 0;
3692
- let filesProcessed = 0;
3693
- let filesDeleted = 0;
3694
- let errors = 0;
3695
- const filesToIndex = [];
3696
- const updated = [];
3697
- const deleted = [];
3698
- for (const filePath of filesToProcess) {
3699
- if (options?.handleDeletions && paths) try {
3700
- await readFile(filePath);
3701
- } catch (error) {
3702
- const parsed = this.parseFilePath(filePath);
3703
- if (parsed) {
3704
- let manifest = null;
3705
- if (parsed.kind === "block" && parsed.name) manifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
3706
- else if (parsed.kind === "data" && parsed.name) manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
3707
- else if (parsed.kind === "page" && parsed.site && parsed.pathname) manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
3708
- if (manifest) {
3709
- deleted.push({
3710
- id: manifest.id,
3711
- locale: parsed.locale,
3712
- kind: parsed.kind
3713
- });
3714
- if (Object.keys(manifest.locales).length === 1) this.contentIndex.removeEntry(manifest.id);
3715
- else {
3716
- manifest.locales[parsed.locale] = void 0;
3717
- this.contentIndex.removeLocale(manifest.id, parsed.locale);
3718
- }
3719
- filesDeleted++;
3720
- }
3721
- }
3722
- continue;
3723
- }
3724
- const parsed = this.parseFilePath(filePath);
3725
- if (!parsed) {
3726
- console.warn(`Skipping unrecognized file pattern: ${filePath}`);
3727
- errors++;
3728
- continue;
3729
- }
3730
- let isIndexed = false;
3731
- if (parsed.kind === "block" && parsed.name) isIndexed = !!this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
3732
- else if (parsed.kind === "page" && parsed.site && parsed.pathname) isIndexed = !!this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
3733
- else if (parsed.kind === "data" && parsed.name) isIndexed = !!this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
3734
- if (isIndexed) if (!paths) filesSkipped++;
3735
- else {
3736
- const fileStats = await readFile(filePath);
3737
- let currentManifest = null;
3738
- if (parsed.kind === "block" && parsed.name) currentManifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
3739
- else if (parsed.kind === "data" && parsed.name) currentManifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
3740
- else if (parsed.kind === "page" && parsed.site && parsed.pathname) currentManifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
3741
- if (currentManifest) {
3742
- const buffer = fileStats;
3743
- let currentEtag;
3744
- if (filePath.endsWith(".mdx")) {
3745
- const etags = calculateEtagsFromMdxBuffer(buffer, findMdxContentStartPosition(buffer));
3746
- currentEtag = `${etags.metaEtag}.${etags.contentEtag}`;
3747
- } else if (filePath.endsWith(".vxjson")) {
3748
- const etagResult = VXJSON.calculateETags(buffer);
3749
- if (!etagResult.success) {
3750
- filesToIndex.push(filePath);
3751
- continue;
3752
- }
3753
- currentEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
3754
- } else if (filePath.endsWith(".json")) currentEtag = xxh3.xxh64(buffer).toString(16);
3755
- else {
3756
- filesSkipped++;
3757
- continue;
3758
- }
3759
- if (currentManifest.locales[parsed.locale]?.etag === currentEtag) {
3760
- const relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
3761
- console.log(`[Content] skip ${relativePath} (unchanged)`);
3762
- filesSkipped++;
3763
- } else filesToIndex.push(filePath);
3764
- } else filesToIndex.push(filePath);
3765
- }
3766
- else filesToIndex.push(filePath);
3767
- }
3768
- const buffers = Array.from({ length: Math.min(filesToIndex.length, 100) }, () => new Uint8Array(4096));
3769
- for (let i = 0; i < filesToIndex.length; i++) {
3770
- const filePath = filesToIndex[i];
3771
- const bufferIndex = i % buffers.length;
3772
- try {
3773
- const result = await this.parseFileHeaderWithRepair(filePath, buffers[bufferIndex]);
3774
- if (result) {
3775
- const { manifest, localeVersion, content } = result;
3776
- this.contentIndex.addContent(manifest, localeVersion, content);
3777
- filesProcessed++;
3778
- const localizedManifest = {
3779
- id: manifest.id,
3780
- type: manifest.type,
3781
- kind: manifest.kind,
3782
- site: manifest.site,
3783
- collection: manifest.collection,
3784
- localized: localeVersion
3785
- };
3786
- updated.push(localizedManifest);
3787
- }
3788
- } catch (error) {
3789
- console.error(`Failed to reindex ${filePath}:`, error);
3790
- errors++;
3791
- }
3792
- }
3793
- const result = {
3794
- filesProcessed,
3795
- filesSkipped,
3796
- updated
1185
+ async register(id, entry) {
1186
+ await this.initialize();
1187
+ this.validateComponentId(id);
1188
+ this.registry[id] = {
1189
+ displayName: entry.displayName,
1190
+ path: entry.path
3797
1191
  };
3798
- if (options?.handleDeletions && deleted.length > 0) {
3799
- result.filesDeleted = filesDeleted;
3800
- result.deleted = deleted;
3801
- }
3802
- if (errors > 0) result.errors = errors;
3803
- return result;
1192
+ await this.save();
3804
1193
  }
3805
1194
  /**
3806
- * Read content directly from cache
3807
- * For testing purposes - returns null if not cached
1195
+ * Get a component entry by ID
3808
1196
  */
3809
- async readFromCache(id, locale) {
3810
- return this.contentIndex.getCachedContent(id, locale);
1197
+ async get(id) {
1198
+ await this.initialize();
1199
+ return this.registry[id] || null;
3811
1200
  }
3812
- async getContentAsBuffer(id, locale) {
3813
- const manifest = this.contentIndex.getManifest(id);
3814
- if (!manifest || !manifest.locales[locale]) return null;
3815
- const localeVersion = manifest.locales[locale];
3816
- const filePath = this.getFilePath(manifest, localeVersion);
3817
- const buffer = await readFile(filePath);
3818
- const contentType = filePath.endsWith(".mdx") ? "text/mdx" : "application/json";
3819
- let etag;
3820
- if (contentType === "text/mdx") {
3821
- const contentStartMarker = new TextEncoder().encode("---\n\n");
3822
- let contentPos = -1;
3823
- for (let i = 0; i <= buffer.length - contentStartMarker.length; i++) {
3824
- let match = true;
3825
- for (let j = 0; j < contentStartMarker.length; j++) if (buffer[i + j] !== contentStartMarker[j]) {
3826
- match = false;
3827
- break;
3828
- }
3829
- if (match) {
3830
- contentPos = i + contentStartMarker.length;
3831
- break;
3832
- }
3833
- }
3834
- const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
3835
- etag = `${etags.metaEtag}.${etags.contentEtag}`;
3836
- } else {
3837
- const etagResult = VXJSON.calculateETags(buffer);
3838
- if (!etagResult.success) throw new Error(`Invalid VXJSON format in getContentAsBuffer: ${etagResult.error}`);
3839
- etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
3840
- }
3841
- return {
3842
- buffer,
3843
- etag,
3844
- contentType
3845
- };
1201
+ /**
1202
+ * Link a component to a path
1203
+ */
1204
+ async link(id, path) {
1205
+ await this.initialize();
1206
+ const entry = this.registry[id];
1207
+ if (!entry) throw new Error(`Component ${id} not found in registry`);
1208
+ entry.path = path;
1209
+ await this.save();
3846
1210
  }
3847
- async batchUpdate(operations) {
3848
- const validationResults = [];
3849
- for (const op of operations) {
3850
- const manifest = this.contentIndex.getManifest(op.id);
3851
- if (!manifest) return {
3852
- operations: operations.map((o) => ({
3853
- id: o.id,
3854
- locale: o.locale,
3855
- updated: false,
3856
- error: /* @__PURE__ */ new Error("Content not found")
3857
- })),
3858
- success: false,
3859
- updated: 0,
3860
- failed: operations.length
3861
- };
3862
- const localeVersion = manifest.locales[op.locale];
3863
- if (!localeVersion) return {
3864
- operations: operations.map((o) => ({
3865
- id: o.id,
3866
- locale: o.locale,
3867
- updated: false,
3868
- error: /* @__PURE__ */ new Error("Locale not found")
3869
- })),
3870
- success: false,
3871
- updated: 0,
3872
- failed: operations.length
3873
- };
3874
- if (localeVersion.etag !== op.etag) return {
3875
- operations: operations.map((o) => ({
3876
- id: o.id,
3877
- locale: o.locale,
3878
- updated: false,
3879
- error: /* @__PURE__ */ new Error("Stale write")
3880
- })),
3881
- success: false,
3882
- updated: 0,
3883
- failed: operations.length
3884
- };
3885
- const filePath = this.getFilePath(manifest, localeVersion);
3886
- const current = await this.readLocaleFile(filePath, op.locale);
3887
- if (!current) return {
3888
- operations: operations.map((o) => ({
3889
- id: o.id,
3890
- locale: o.locale,
3891
- updated: false,
3892
- error: /* @__PURE__ */ new Error("Failed to read content")
3893
- })),
3894
- success: false,
3895
- updated: 0,
3896
- failed: operations.length
3897
- };
3898
- if (op.data.meta) {
3899
- const validation = validateAndPrepareMetadata({
3900
- ...current.meta,
3901
- ...op.data.meta
3902
- });
3903
- if (!validation.valid) return {
3904
- operations: operations.map((o) => ({
3905
- id: o.id,
3906
- locale: o.locale,
3907
- updated: false,
3908
- error: new Error(validation.error)
3909
- })),
3910
- success: false,
3911
- updated: 0,
3912
- failed: operations.length
3913
- };
3914
- }
3915
- validationResults.push({
3916
- op,
3917
- manifest,
3918
- localeVersion,
3919
- current
3920
- });
3921
- }
3922
- const results = [];
3923
- let updated = 0;
3924
- for (const { op } of validationResults) {
3925
- const result = await this.updateLocalized(op);
3926
- if (result.success) {
3927
- updated++;
3928
- results.push({
3929
- id: op.id,
3930
- locale: op.locale,
3931
- updated: true,
3932
- etag: result.etag
3933
- });
3934
- } else results.push({
3935
- id: op.id,
3936
- locale: op.locale,
3937
- updated: false,
3938
- error: result.error
3939
- });
3940
- }
3941
- return {
3942
- operations: results,
3943
- success: updated === operations.length,
3944
- updated,
3945
- failed: operations.length - updated
3946
- };
1211
+ /**
1212
+ * Unlink a component (set path to null)
1213
+ */
1214
+ async unlink(id) {
1215
+ await this.initialize();
1216
+ const entry = this.registry[id];
1217
+ if (!entry) throw new Error(`Component ${id} not found in registry`);
1218
+ entry.path = null;
1219
+ await this.save();
1220
+ }
1221
+ /**
1222
+ * List all components
1223
+ */
1224
+ async list() {
1225
+ await this.initialize();
1226
+ return Object.entries(this.registry).map(([id, entry]) => ({
1227
+ id,
1228
+ ...entry
1229
+ }));
1230
+ }
1231
+ /**
1232
+ * Delete a component from registry
1233
+ */
1234
+ async delete(id) {
1235
+ await this.initialize();
1236
+ delete this.registry[id];
1237
+ await this.save();
3947
1238
  }
3948
1239
  };
3949
-
3950
1240
  //#endregion
3951
1241
  //#region src/content-watcher.ts
3952
1242
  /**
@@ -3954,22 +1244,26 @@ var FileSystemContentAPI = class FileSystemContentAPI {
3954
1244
  */
3955
1245
  async function createContentAPI(options) {
3956
1246
  return await FileSystemContentAPI.create({
3957
- contentRoot: options.contentRoot,
1247
+ ...options,
3958
1248
  canvasDir: options.canvasDir || "./canvas"
3959
1249
  });
3960
1250
  }
3961
1251
  /**
3962
1252
  * Creates file change handlers for content watching
3963
1253
  */
3964
- function createContentWatchHandlers(contentApi, options, ws) {
1254
+ function createContentWatchHandlers(contentApi, options, ws, onReindexed) {
3965
1255
  const handleFileChange = async (file, action) => {
3966
1256
  const isContentFile = file.endsWith(".mdx") || file.endsWith(".vxjson");
3967
1257
  const isDataFile = file.endsWith(".json") && file.includes("/data/");
3968
1258
  if (!isContentFile && !isDataFile) return;
3969
- const normalizedFile = normalize(resolve$1(file));
3970
- const normalizedRoot = normalize(resolve$1(options.contentRoot));
3971
- if (normalizedFile.startsWith(normalizedRoot)) {
3972
- const relativePath = normalizedFile.replace(normalizedRoot + "/", "");
1259
+ const normalizedFile = normalize(resolve(file));
1260
+ const normalizedRoot = normalize(resolve(options.contentRoot));
1261
+ const normalizedMdxRoot = options.mdxPagesRoot ? normalize(resolve(options.mdxPagesRoot)) : null;
1262
+ const inContentRoot = normalizedFile === normalizedRoot || normalizedFile.startsWith(normalizedRoot + "/");
1263
+ const inMdxRoot = !!normalizedMdxRoot && (normalizedFile === normalizedMdxRoot || normalizedFile.startsWith(normalizedMdxRoot + "/"));
1264
+ if (inContentRoot || inMdxRoot) {
1265
+ const matchedRoot = inContentRoot ? normalizedRoot : normalizedMdxRoot;
1266
+ const relativePath = normalizedFile.replace(matchedRoot + "/", "");
3973
1267
  console.log(`[Content] ${action}: ${relativePath}`);
3974
1268
  try {
3975
1269
  const reindexOptions = action === "delete" ? { handleDeletions: true } : void 0;
@@ -3997,6 +1291,16 @@ function createContentWatchHandlers(contentApi, options, ws) {
3997
1291
  console.error("[Content Watcher] Reindex failed:", error);
3998
1292
  return;
3999
1293
  }
1294
+ try {
1295
+ await onReindexed?.({
1296
+ file: normalizedFile,
1297
+ action,
1298
+ inMdxRoot,
1299
+ inContentRoot
1300
+ });
1301
+ } catch (error) {
1302
+ console.error("[Content Watcher] onReindexed callback failed:", error);
1303
+ }
4000
1304
  }
4001
1305
  };
4002
1306
  return {
@@ -4005,7 +1309,6 @@ function createContentWatchHandlers(contentApi, options, ws) {
4005
1309
  onUnlink: (file) => handleFileChange(file, "delete")
4006
1310
  };
4007
1311
  }
4008
-
4009
1312
  //#endregion
4010
1313
  //#region src/in-memory-content-api.ts
4011
1314
  /**
@@ -4046,27 +1349,10 @@ var InMemoryContentAPI = class {
4046
1349
  for (const localeVersion of localesOf(manifest)) {
4047
1350
  const { locale } = localeVersion;
4048
1351
  const cachedContent = this.contentIndex.getCachedContent(id, locale);
4049
- if (cachedContent) {
4050
- let contentToReturn = cachedContent;
4051
- if (manifest.type === "mdx" && cachedContent.mdx) {
4052
- const frontmatterData = {
4053
- id: manifest.id,
4054
- created: localeVersion.created,
4055
- modified: localeVersion.modified,
4056
- ...localeVersion.publishAt && { publishAt: localeVersion.publishAt },
4057
- ...localeVersion.unpublishAt && { unpublishAt: localeVersion.unpublishAt },
4058
- ...localeVersion.meta
4059
- };
4060
- contentToReturn = {
4061
- ...cachedContent,
4062
- mdx: serializeMdxWithFrontmatter(frontmatterData, cachedContent.mdx)
4063
- };
4064
- }
4065
- contentEntry.locales[locale] = {
4066
- ...localeVersion,
4067
- content: contentToReturn
4068
- };
4069
- }
1352
+ if (cachedContent) contentEntry.locales[locale] = {
1353
+ ...localeVersion,
1354
+ content: cachedContent
1355
+ };
4070
1356
  }
4071
1357
  return contentEntry;
4072
1358
  }
@@ -4076,21 +1362,7 @@ var InMemoryContentAPI = class {
4076
1362
  const localeVersion = manifest.locales[locale];
4077
1363
  const cachedContent = this.contentIndex.getCachedContent(id, locale);
4078
1364
  if (!cachedContent) return null;
4079
- let contentToReturn = { ...cachedContent };
4080
- if (manifest.type === "mdx" && cachedContent.mdx) {
4081
- const frontmatterData = {
4082
- id: manifest.id,
4083
- created: localeVersion.created,
4084
- modified: localeVersion.modified,
4085
- ...localeVersion.publishAt && { publishAt: localeVersion.publishAt },
4086
- ...localeVersion.unpublishAt && { unpublishAt: localeVersion.unpublishAt },
4087
- ...localeVersion.meta
4088
- };
4089
- contentToReturn = {
4090
- ...cachedContent,
4091
- mdx: serializeMdxWithFrontmatter(frontmatterData, cachedContent.mdx)
4092
- };
4093
- }
1365
+ const contentToReturn = { ...cachedContent };
4094
1366
  return {
4095
1367
  id,
4096
1368
  site: manifest.site,
@@ -4473,7 +1745,6 @@ var InMemoryContentAPI = class {
4473
1745
  };
4474
1746
  }
4475
1747
  };
4476
-
4477
1748
  //#endregion
4478
1749
  //#region src/middleware.ts
4479
1750
  /**
@@ -4493,6 +1764,9 @@ function logAndCreateErrorResponse(error, code, message, details) {
4493
1764
  console.error(`[Content API] ${message}:`, error);
4494
1765
  return errorResponse(code, message, details);
4495
1766
  }
1767
+ function errorMessage(error, fallback) {
1768
+ return error instanceof Error ? error.message : fallback;
1769
+ }
4496
1770
  function createContentAPIRouter(api, options) {
4497
1771
  const app = new Hono();
4498
1772
  app.use("/*", cors());
@@ -4511,10 +1785,14 @@ function createContentAPIRouter(api, options) {
4511
1785
  app.get("/content/collections", async (c) => {
4512
1786
  try {
4513
1787
  const allCollections = /* @__PURE__ */ new Set();
4514
- api.blocks.collections.forEach((c) => allCollections.add(c));
1788
+ const blockCollections = api.blocks.collections;
1789
+ for (const collection of blockCollections) allCollections.add(collection);
4515
1790
  for (const siteName of Object.keys(api.sitesConfig.sites)) {
4516
1791
  const site = api.getSite(siteName);
4517
- if (site) site.collections.forEach((c) => allCollections.add(c));
1792
+ if (site) {
1793
+ const siteCollections = site.collections;
1794
+ for (const collection of siteCollections) allCollections.add(collection);
1795
+ }
4518
1796
  }
4519
1797
  return c.json({ collections: Array.from(allCollections).sort() });
4520
1798
  } catch (error) {
@@ -4576,10 +1854,35 @@ function createContentAPIRouter(api, options) {
4576
1854
  const data = await c.req.json();
4577
1855
  const result = await api.createContent(data);
4578
1856
  if (!result.success) {
4579
- if (result.reason === "already_exists") return c.json(result, 409);
4580
- if (result.reason === "pathname_taken") return c.json(result, 409);
4581
- if (result.reason === "metadata_too_large") return c.json(result, 400);
4582
- return c.json(result, 500);
1857
+ const errMessage = (result.error instanceof Error ? result.error.message : void 0) ?? "";
1858
+ if (result.reason === "already_exists") return c.json({
1859
+ ...result,
1860
+ ...errorResponse(ErrorCodes.ALREADY_EXISTS, errMessage || "Content already exists")
1861
+ }, 409);
1862
+ if (result.reason === "name_taken") return c.json({
1863
+ ...result,
1864
+ ...errorResponse(ErrorCodes.NAME_TAKEN, errMessage || "A block with that name already exists")
1865
+ }, 409);
1866
+ if (result.reason === "pathname_taken") return c.json({
1867
+ ...result,
1868
+ ...errorResponse(ErrorCodes.PATHNAME_TAKEN, errMessage || "Pathname already taken")
1869
+ }, 409);
1870
+ if (result.reason === "invalid_name") return c.json({
1871
+ ...result,
1872
+ ...errorResponse(ErrorCodes.INVALID_REQUEST, errMessage || "Invalid name")
1873
+ }, 400);
1874
+ if (result.reason === "invalid_pathname") return c.json({
1875
+ ...result,
1876
+ ...errorResponse(ErrorCodes.INVALID_PATHNAME, errMessage || "Invalid pathname")
1877
+ }, 400);
1878
+ if (result.reason === "metadata_too_large") return c.json({
1879
+ ...result,
1880
+ ...errorResponse(ErrorCodes.METADATA_TOO_LARGE, errMessage || "Metadata too large")
1881
+ }, 400);
1882
+ return c.json({
1883
+ ...result,
1884
+ ...errorResponse(ErrorCodes.WRITE_ERROR, errMessage || "Failed to create content")
1885
+ }, 500);
4583
1886
  }
4584
1887
  return c.json(result, 201);
4585
1888
  } catch (error) {
@@ -4587,7 +1890,7 @@ function createContentAPIRouter(api, options) {
4587
1890
  return c.json({
4588
1891
  success: false,
4589
1892
  reason: "write_error",
4590
- error: error instanceof Error ? error.message : "Unknown error"
1893
+ ...errorResponse(ErrorCodes.WRITE_ERROR, errorMessage(error, "Failed to create content"))
4591
1894
  }, 500);
4592
1895
  }
4593
1896
  });
@@ -4947,10 +2250,17 @@ function createContentAPIRouter(api, options) {
4947
2250
  if (!pathname) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "pathname query parameter is required", { field: "pathname" }), 400);
4948
2251
  try {
4949
2252
  if (site === "blocks") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "Blocks do not have pathnames. This endpoint is only for page content."), 400);
2253
+ const validation = normalizeAndValidatePathname(pathname);
2254
+ if (!validation.valid) return c.json({
2255
+ available: false,
2256
+ reason: "invalid_pathname",
2257
+ message: validation.message
2258
+ });
2259
+ const normalized = validation.value;
4950
2260
  const siteObj = api.getSite(site);
4951
2261
  if (!siteObj) return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
4952
- if (siteObj.isPathnameAvailable(pathname, locale, excludeId)) return c.json({ available: true });
4953
- const existingId = siteObj.getPathnameConflict(pathname, locale, excludeId);
2262
+ if (siteObj.isPathnameAvailable(normalized, locale, excludeId)) return c.json({ available: true });
2263
+ const existingId = siteObj.getPathnameConflict(normalized, locale, excludeId);
4954
2264
  return c.json({
4955
2265
  available: false,
4956
2266
  existingId
@@ -5195,8 +2505,8 @@ function createContentAPIRouter(api, options) {
5195
2505
  * Create middleware for backwards compatibility with existing code
5196
2506
  * This wraps the Hono app to work with Node.js IncomingMessage/ServerResponse
5197
2507
  */
5198
- function createContentMiddleware(contentApi) {
5199
- const app = createContentAPIRouter(contentApi);
2508
+ function createContentMiddleware(contentApi, options) {
2509
+ const app = createContentAPIRouter(contentApi, options);
5200
2510
  return async (req, res, next) => {
5201
2511
  const url = new URL(req.url, `http://${req.headers.host}`);
5202
2512
  const basePath = url.pathname.startsWith("/__cms/api") ? "/__cms/api" : "/__conloca/api";
@@ -5233,7 +2543,6 @@ function readBody(req) {
5233
2543
  req.on("error", reject);
5234
2544
  });
5235
2545
  }
5236
-
5237
2546
  //#endregion
5238
2547
  //#region src/vite-plugin.ts
5239
2548
  /**
@@ -5257,7 +2566,7 @@ function conlocaContent(options) {
5257
2566
  }
5258
2567
  };
5259
2568
  }
5260
-
5261
2569
  //#endregion
5262
- export { AssetManifest, AssetOperations, Blocks, ComponentRegistry, ErrorCodes, FileSystemContentAPI, InMemoryContentAPI, Site, UPDATE_SCOPE, analyzeUpdateScope, buildLocaleVersion, buildPathnameHistory, conlocaContent, createContentAPI, createContentAPIRouter, createContentMiddleware, createContentWatchHandlers, extractBlockName, extractCFAccessToken, formatFileSize, generateContentId, getCurrentISODate, getMetadataSize, isContentPublished, isMetadataTooLarge, isValidBlockName, isValidPathname, localesOf, mapLocales, mapSiteNames, normalizePathname, parseDate, resolvePublishDate, serializeMdxWithFrontmatter, shouldUpdateModifiedTimestamp, updatePublishDates, validateAndPrepareMetadata, validateCFAccessRequest, validateCreateContent };
2570
+ export { AssetManifest, AssetOperations, Blocks, ComponentRegistry, ErrorCodes, FileSystemContentAPI, InMemoryContentAPI, Site, UPDATE_SCOPE, analyzeUpdateScope, buildLocaleVersion, buildPathnameHistory, conlocaContent, createContentAPI, createContentAPIRouter, createContentMiddleware, createContentWatchHandlers, extractBlockName, extractCFAccessToken, formatFileSize, generateContentId, getCurrentISODate, getMetadataSize, isContentPublished, isMetadataTooLarge, isValidBlockName, isValidPathname, localesOf, mapLocales, mapSiteNames, normalizeAndValidatePathname, normalizePathname, parseDate, readSitesConfig, resolvePublishDate, serializeMdxWithFrontmatter, shouldUpdateModifiedTimestamp, updatePublishDates, validateAndPrepareMetadata, validateCFAccessRequest, validateCreateContent };
2571
+
5263
2572
  //# sourceMappingURL=node.mjs.map