@conloca/content-api 0.1.13 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.mjs CHANGED
@@ -1,16 +1,18 @@
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 findMdxContentStartPosition, c as atomicWriteFile, i as calculateEtagsFromMdxBuffer, o as ContentIndex, r as VXJSON, s as filterContentWithIndexes, t as FileSystemContentAPI } from "./filesystem-content-api-kxKY5IUw.mjs";
2
+ import { C as parseDate, E as Blocks, S as normalizePathname, T as serializeMdxWithFrontmatter, _ as isValidBlockName, a as buildPathnameHistory, b as mapLocales, c as validateAndPrepareMetadata, d as formatFileSize, f as generateContentId, g as isMetadataTooLarge, h as isContentPublished, i as buildLocaleVersion, l as validateCreateContent, m as getMetadataSize, n as UPDATE_SCOPE, o as shouldUpdateModifiedTimestamp, p as getCurrentISODate, r as analyzeUpdateScope, s as updatePublishDates, t as Site, u as extractBlockName, v as isValidPathname, w as resolvePublishDate, x as mapSiteNames, y as localesOf } from "./site-vNtJ5jCh.mjs";
3
+ import { t as ErrorCodes } from "./types-DWt912tu.mjs";
4
+ import { t as Data } from "./data-Db1Iv9T0.mjs";
2
5
  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";
5
- import { existsSync } from "node:fs";
6
+ import { access, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
7
+ import { dirname, extname, join, normalize, parse, resolve } from "node:path";
6
8
  import { imageSize } from "image-size";
7
9
  import { spawn } from "node:child_process";
8
10
  import { createRemoteJWKSet, jwtVerify } from "jose";
9
- import { mkdir as mkdir$1, readFile as readFile$1, rename as rename$1, unlink as unlink$1, writeFile as writeFile$1 } from "fs/promises";
10
- import { dirname as dirname$1, join as join$1, normalize, resolve as resolve$1 } from "path";
11
- import { xxh3 } from "@node-rs/xxhash";
12
11
  import matter from "gray-matter";
13
- import { createHash } from "crypto";
12
+ import { compile } from "@mdx-js/mdx";
13
+ import remarkFrontmatter from "remark-frontmatter";
14
+ import remarkGfm from "remark-gfm";
15
+ import remarkMdxFrontmatter from "remark-mdx-frontmatter";
14
16
  import { Hono } from "hono";
15
17
  import { cors } from "hono/cors";
16
18
  import { getRequestListener } from "@hono/node-server";
@@ -19,6 +21,7 @@ import { getRequestListener } from "@hono/node-server";
19
21
  const MANIFEST_FILENAME = ".asset-manifest.json";
20
22
  var AssetManifest = class {
21
23
  manifestPath;
24
+ _lock = Promise.resolve();
22
25
  constructor(assetsPath) {
23
26
  this.manifestPath = join(assetsPath, MANIFEST_FILENAME);
24
27
  }
@@ -31,19 +34,37 @@ var AssetManifest = class {
31
34
  }
32
35
  }
33
36
  async write(data) {
34
- await writeFile(this.manifestPath, JSON.stringify(data, null, 2), "utf-8");
37
+ await atomicWriteFile(this.manifestPath, JSON.stringify(data, null, 2));
38
+ }
39
+ /** Atomic read-modify-write with promise-based mutex to prevent concurrent corruption */
40
+ async withManifest(fn) {
41
+ const prev = this._lock;
42
+ let release;
43
+ this._lock = new Promise((r) => {
44
+ release = r;
45
+ });
46
+ await prev;
47
+ try {
48
+ const updated = fn(await this.read());
49
+ await this.write(updated);
50
+ } finally {
51
+ release();
52
+ }
35
53
  }
36
54
  async add(relativePath, data) {
37
- const manifest = await this.read();
38
- manifest[relativePath] = data;
39
- await this.write(manifest);
55
+ await this.withManifest((manifest) => {
56
+ manifest[relativePath] = data;
57
+ return manifest;
58
+ });
40
59
  }
41
60
  async remove(relativePath) {
42
- const manifest = await this.read();
43
- if (!(relativePath in manifest)) return false;
44
- delete manifest[relativePath];
45
- await this.write(manifest);
46
- return true;
61
+ let existed = false;
62
+ await this.withManifest((manifest) => {
63
+ existed = relativePath in manifest;
64
+ if (existed) delete manifest[relativePath];
65
+ return manifest;
66
+ });
67
+ return existed;
47
68
  }
48
69
  async get(relativePath) {
49
70
  return (await this.read())[relativePath];
@@ -106,10 +127,15 @@ async function resolveRepoRoot(contentPath) {
106
127
  */
107
128
  function createGitOperations(config) {
108
129
  const { contentPath, branch } = config;
130
+ let cachedRepoRoot;
131
+ async function getCachedRepoRoot() {
132
+ if (cachedRepoRoot === void 0) cachedRepoRoot = await resolveRepoRoot(contentPath);
133
+ return cachedRepoRoot;
134
+ }
109
135
  return {
110
136
  async getStatus() {
111
137
  try {
112
- const repoRoot = await resolveRepoRoot(contentPath);
138
+ const repoRoot = await getCachedRepoRoot();
113
139
  if (!repoRoot) return {
114
140
  isRepo: false,
115
141
  hasChanges: false,
@@ -124,7 +150,12 @@ function createGitOperations(config) {
124
150
  "HEAD"
125
151
  ]);
126
152
  const currentBranch = branchResult.exitCode === 0 ? branchResult.stdout : "unknown";
127
- const statusResult = await runGitCommand(repoRoot, ["status", "--porcelain"]);
153
+ const statusResult = await runGitCommand(repoRoot, [
154
+ "status",
155
+ "--porcelain",
156
+ "--",
157
+ contentPath
158
+ ]);
128
159
  const changedFiles = (statusResult.stdout ? statusResult.stdout.split("\n").filter((l) => l.trim()) : []).length;
129
160
  const hasChanges = changedFiles > 0;
130
161
  const remoteConfigured = (await runGitCommand(repoRoot, [
@@ -169,12 +200,17 @@ function createGitOperations(config) {
169
200
  },
170
201
  async commitAll(message, author) {
171
202
  try {
172
- const repoRoot = await resolveRepoRoot(contentPath);
203
+ const repoRoot = await getCachedRepoRoot();
173
204
  if (!repoRoot) return {
174
205
  success: false,
175
206
  error: "Not a git repository"
176
207
  };
177
- const addResult = await runGitCommand(repoRoot, ["add", "-A"]);
208
+ const addResult = await runGitCommand(repoRoot, [
209
+ "add",
210
+ "-A",
211
+ "--",
212
+ contentPath
213
+ ]);
178
214
  if (addResult.exitCode !== 0) return {
179
215
  success: false,
180
216
  error: addResult.stderr || "Failed to stage changes"
@@ -182,7 +218,9 @@ function createGitOperations(config) {
182
218
  if ((await runGitCommand(repoRoot, [
183
219
  "diff",
184
220
  "--cached",
185
- "--quiet"
221
+ "--quiet",
222
+ "--",
223
+ contentPath
186
224
  ])).exitCode === 0) return {
187
225
  success: false,
188
226
  error: "No changes to commit"
@@ -190,7 +228,9 @@ function createGitOperations(config) {
190
228
  const diffStatResult = await runGitCommand(repoRoot, [
191
229
  "diff",
192
230
  "--cached",
193
- "--numstat"
231
+ "--numstat",
232
+ "--",
233
+ contentPath
194
234
  ]);
195
235
  const fileCount = diffStatResult.stdout ? diffStatResult.stdout.split("\n").filter((l) => l.trim()).length : 0;
196
236
  const commitArgs = [
@@ -218,7 +258,7 @@ function createGitOperations(config) {
218
258
  },
219
259
  async pushOrigin() {
220
260
  try {
221
- const repoRoot = await resolveRepoRoot(contentPath);
261
+ const repoRoot = await getCachedRepoRoot();
222
262
  if (!repoRoot) return {
223
263
  success: false,
224
264
  error: "Not a git repository"
@@ -271,7 +311,7 @@ function createGitOperations(config) {
271
311
  },
272
312
  async pull() {
273
313
  try {
274
- const repoRoot = await resolveRepoRoot(contentPath);
314
+ const repoRoot = await getCachedRepoRoot();
275
315
  if (!repoRoot) return {
276
316
  success: false,
277
317
  error: "Not a git repository"
@@ -332,6 +372,55 @@ async function setupGitLfsAttributes(contentRoot) {
332
372
  await writeFile(gitattributesPath, existing ? `${existing.trimEnd()}\n${missingPatterns.join("\n")}\n` : `${missingPatterns.join("\n")}\n`, "utf-8");
333
373
  }
334
374
 
375
+ //#endregion
376
+ //#region src/url-validation.ts
377
+ /**
378
+ * URL validation for SSRF prevention in server-side fetch operations.
379
+ * Blocks private/reserved IP addresses and non-http(s) schemes.
380
+ */
381
+ const BLOCKED_HOSTNAMES = new Set(["localhost"]);
382
+ /** Check if an IPv4 address string points to a private/reserved range */
383
+ function isPrivateIPv4(hostname) {
384
+ const parts = hostname.split(".");
385
+ if (parts.length !== 4) return false;
386
+ const octets = parts.map((p) => Number.parseInt(p, 10));
387
+ if (octets.some((o) => Number.isNaN(o) || o < 0 || o > 255)) return false;
388
+ const [first, second] = octets;
389
+ if (first === 0) return true;
390
+ if (first === 10) return true;
391
+ if (first === 127) return true;
392
+ if (first === 169 && second === 254) return true;
393
+ if (first === 172 && second >= 16 && second <= 31) return true;
394
+ if (first === 192 && second === 168) return true;
395
+ return false;
396
+ }
397
+ /** Check if an IPv6 address string points to a private/reserved range */
398
+ function isPrivateIPv6(hostname) {
399
+ const lower = hostname.toLowerCase();
400
+ if (lower === "::1") return true;
401
+ if (lower === "::") return true;
402
+ if (lower.startsWith("fe80:") || lower.startsWith("fe80%")) return true;
403
+ if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
404
+ return false;
405
+ }
406
+ /**
407
+ * Validate that a URL is safe to fetch server-side.
408
+ * Blocks private/reserved IP addresses and non-http(s) schemes.
409
+ *
410
+ * @param url The URL string to validate
411
+ * @returns The parsed URL object if valid
412
+ * @throws Error if the URL is invalid, uses a blocked scheme, or points to a private IP
413
+ */
414
+ function validateFetchUrl(url) {
415
+ const parsed = new URL(url);
416
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error("URL scheme must be http or https");
417
+ const hostname = parsed.hostname.replace(/^\[|\]$/g, "");
418
+ if (BLOCKED_HOSTNAMES.has(hostname.toLowerCase())) throw new Error("URL points to a private/reserved IP address");
419
+ if (isPrivateIPv4(hostname)) throw new Error("URL points to a private/reserved IP address");
420
+ if (isPrivateIPv6(hostname)) throw new Error("URL points to a private/reserved IP address");
421
+ return parsed;
422
+ }
423
+
335
424
  //#endregion
336
425
  //#region src/asset-operations.ts
337
426
  const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
@@ -426,16 +515,19 @@ var AssetOperations = class {
426
515
  * @param originalName Original filename
427
516
  * @param folder Optional folder path (relative to assets root)
428
517
  */
429
- resolveFilename(originalName, folder) {
518
+ async resolveFilename(originalName, folder) {
430
519
  const { name, ext } = parse(originalName);
431
520
  const sanitized = name.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
432
521
  const safeExt = ext.toLowerCase();
433
522
  const baseDir = folder && folder !== "/" ? join(this.config.assetsPath, folder.replace(/^\/+|\/+$/g, "")) : this.config.assetsPath;
434
523
  let candidate = `${sanitized}${safeExt}`;
435
524
  let counter = 0;
436
- while (existsSync(join(baseDir, candidate))) {
525
+ while (true) try {
526
+ await access(join(baseDir, candidate));
437
527
  counter++;
438
528
  candidate = `${sanitized}-${counter}${safeExt}`;
529
+ } catch {
530
+ break;
439
531
  }
440
532
  return candidate;
441
533
  }
@@ -525,7 +617,7 @@ var AssetOperations = class {
525
617
  await setupGitLfsAttributes(this.config.assetsPath);
526
618
  this.lfsSetup = true;
527
619
  }
528
- const filename = this.resolveFilename(file.name, folder);
620
+ const filename = await this.resolveFilename(file.name, folder);
529
621
  const filePath = folder !== "/" ? join(this.config.assetsPath, folder.replace(/^\//, ""), filename) : join(this.config.assetsPath, filename);
530
622
  const arrayBuffer = await file.arrayBuffer();
531
623
  await writeFile(filePath, new Uint8Array(arrayBuffer));
@@ -634,24 +726,46 @@ var AssetOperations = class {
634
726
  }
635
727
  /**
636
728
  * Import an image from a URL (server-side fetch, no CORS issues)
729
+ * Validates URL against SSRF, enforces 30s timeout, and checks response size.
637
730
  */
638
731
  async importFromUrl(url, metadata) {
732
+ try {
733
+ validateFetchUrl(url);
734
+ } catch (err) {
735
+ return {
736
+ success: false,
737
+ error: err instanceof Error ? err.message : "Invalid URL"
738
+ };
739
+ }
740
+ const controller = new AbortController();
741
+ const timeout = setTimeout(() => controller.abort(), 3e4);
639
742
  let response;
640
743
  try {
641
- response = await fetch(url);
744
+ response = await fetch(url, { signal: controller.signal });
642
745
  } catch {
643
746
  return {
644
747
  success: false,
645
748
  error: "Failed to fetch URL"
646
749
  };
750
+ } finally {
751
+ clearTimeout(timeout);
647
752
  }
648
753
  if (!response.ok) return {
649
754
  success: false,
650
755
  error: `Fetch failed with status ${response.status}`
651
756
  };
757
+ const contentLength = response.headers.get("content-length");
758
+ if (contentLength && Number.parseInt(contentLength, 10) > this.config.maxFileSize) return {
759
+ success: false,
760
+ error: `Remote file too large. Maximum: ${Math.round(this.config.maxFileSize / (1024 * 1024))}MB`
761
+ };
652
762
  const contentType = response.headers.get("content-type") || "";
653
763
  const urlFilename = new URL(url).pathname.split("/").pop() || "imported-image.jpg";
654
764
  const arrayBuffer = await response.arrayBuffer();
765
+ if (arrayBuffer.byteLength > this.config.maxFileSize) return {
766
+ success: false,
767
+ error: `Remote file too large. Maximum: ${Math.round(this.config.maxFileSize / (1024 * 1024))}MB`
768
+ };
655
769
  const file = new File([new Uint8Array(arrayBuffer)], urlFilename, { type: contentType });
656
770
  return this.upload(file, metadata);
657
771
  }
@@ -887,7 +1001,7 @@ var AssetOperations = class {
887
1001
  error: "Target folder does not exist"
888
1002
  };
889
1003
  }
890
- let movedCount = 0;
1004
+ const moves = [];
891
1005
  for (const filename of filenames) {
892
1006
  const sourceFile = join(sourcePath, filename);
893
1007
  const targetFile = join(targetPath, filename);
@@ -895,19 +1009,27 @@ var AssetOperations = class {
895
1009
  const newRelativePath = normalizedTarget === "/" ? filename : `${normalizedTarget.slice(1)}/${filename}`;
896
1010
  try {
897
1011
  await rename(sourceFile, targetFile);
898
- const oldEntry = (await this.manifest.read())[oldRelativePath];
899
- if (oldEntry) {
900
- await this.manifest.remove(oldRelativePath);
901
- await this.manifest.add(newRelativePath, oldEntry);
902
- }
903
- movedCount++;
1012
+ moves.push({
1013
+ oldPath: oldRelativePath,
1014
+ newPath: newRelativePath
1015
+ });
904
1016
  } catch (err) {
905
1017
  console.error(`[AssetOperations] Failed to move ${filename}:`, err);
906
1018
  }
907
1019
  }
1020
+ if (moves.length > 0) await this.manifest.withManifest((data) => {
1021
+ for (const { oldPath, newPath } of moves) {
1022
+ const entry = data[oldPath];
1023
+ if (entry) {
1024
+ delete data[oldPath];
1025
+ data[newPath] = entry;
1026
+ }
1027
+ }
1028
+ return data;
1029
+ });
908
1030
  return {
909
1031
  success: true,
910
- moved: movedCount
1032
+ moved: moves.length
911
1033
  };
912
1034
  }
913
1035
  /**
@@ -989,2861 +1111,136 @@ function extractCFAccessToken(request) {
989
1111
  async function validateCFAccessRequest(request) {
990
1112
  if (!CF_ACCESS_TEAM_NAME || !CF_ACCESS_AUD || !JWKS) return {
991
1113
  valid: true,
992
- required: false
993
- };
994
- const token = extractCFAccessToken(request);
995
- if (!token) return {
996
- valid: false,
997
- required: true,
998
- error: "No token provided"
999
- };
1000
- try {
1001
- const { payload } = await jwtVerify(token, JWKS, {
1002
- issuer: `https://${CF_ACCESS_TEAM_NAME}.cloudflareaccess.com`,
1003
- audience: CF_ACCESS_AUD
1004
- });
1005
- return {
1006
- valid: true,
1007
- required: true,
1008
- user: {
1009
- email: payload.email || "",
1010
- sub: payload.sub || ""
1011
- }
1012
- };
1013
- } catch (error) {
1014
- return {
1015
- valid: false,
1016
- required: true,
1017
- error: error instanceof Error ? error.message : "Validation failed"
1018
- };
1019
- }
1020
- }
1021
-
1022
- //#endregion
1023
- //#region src/component-registry.ts
1024
- /**
1025
- * Component Registry for managing linked and unlinked components
1026
- *
1027
- * Registry is stored at {canvasDir}/components/registry.json
1028
- * Component IDs must follow the format: vx-{uuid}
1029
- */
1030
- var ComponentRegistry = class {
1031
- registryPath;
1032
- registry = {};
1033
- initialized = false;
1034
- constructor(canvasDir) {
1035
- this.registryPath = join$1(canvasDir, "components", "registry.json");
1036
- }
1037
- /**
1038
- * Initialize the registry by loading from disk or creating new
1039
- */
1040
- async initialize() {
1041
- if (this.initialized) return;
1042
- try {
1043
- const content = await readFile$1(this.registryPath, "utf-8");
1044
- this.registry = JSON.parse(content);
1045
- } catch (error) {
1046
- if (error.code === "ENOENT") await this.save();
1047
- else throw error;
1048
- }
1049
- this.initialized = true;
1050
- }
1051
- /**
1052
- * Validate component ID format (vx-{uuid})
1053
- */
1054
- validateComponentId(id) {
1055
- 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}");
1056
- }
1057
- /**
1058
- * Save registry to disk atomically
1059
- */
1060
- async save() {
1061
- const tempPath = `${this.registryPath}.tmp.${Date.now()}.${Math.random().toString(36).substring(2, 9)}`;
1062
- try {
1063
- await mkdir$1(dirname$1(this.registryPath), { recursive: true });
1064
- const sorted = sortKeys(this.registry, { deep: true });
1065
- await writeFile$1(tempPath, JSON.stringify(sorted, null, 2));
1066
- await rename$1(tempPath, this.registryPath);
1067
- } catch (error) {
1068
- try {
1069
- await unlink$1(tempPath);
1070
- } catch {}
1071
- throw error;
1072
- }
1073
- }
1074
- /**
1075
- * Register a new component or update existing
1076
- */
1077
- async register(id, entry) {
1078
- await this.initialize();
1079
- this.validateComponentId(id);
1080
- this.registry[id] = {
1081
- displayName: entry.displayName,
1082
- path: entry.path
1083
- };
1084
- await this.save();
1085
- }
1086
- /**
1087
- * Get a component entry by ID
1088
- */
1089
- async get(id) {
1090
- await this.initialize();
1091
- return this.registry[id] || null;
1092
- }
1093
- /**
1094
- * Link a component to a path
1095
- */
1096
- async link(id, path) {
1097
- await this.initialize();
1098
- const entry = this.registry[id];
1099
- if (!entry) throw new Error(`Component ${id} not found in registry`);
1100
- entry.path = path;
1101
- await this.save();
1102
- }
1103
- /**
1104
- * Unlink a component (set path to null)
1105
- */
1106
- async unlink(id) {
1107
- await this.initialize();
1108
- const entry = this.registry[id];
1109
- if (!entry) throw new Error(`Component ${id} not found in registry`);
1110
- entry.path = null;
1111
- await this.save();
1112
- }
1113
- /**
1114
- * List all components
1115
- */
1116
- async list() {
1117
- await this.initialize();
1118
- return Object.entries(this.registry).map(([id, entry]) => ({
1119
- id,
1120
- ...entry
1121
- }));
1122
- }
1123
- /**
1124
- * Delete a component from registry
1125
- */
1126
- async delete(id) {
1127
- await this.initialize();
1128
- delete this.registry[id];
1129
- await this.save();
1130
- }
1131
- };
1132
-
1133
- //#endregion
1134
- //#region src/content-filters.ts
1135
- /**
1136
- * Apply filters to a single content manifest
1137
- * Pure function that checks if a manifest matches all provided filters
1138
- */
1139
- function applyContentFilters(manifest, filters) {
1140
- if (filters.site && manifest.site !== filters.site) return false;
1141
- if (filters.collection && manifest.collection !== filters.collection) return false;
1142
- if (filters.type && manifest.type !== filters.type) return false;
1143
- if (filters.kind && manifest.kind !== filters.kind) return false;
1144
- if (filters.locales && filters.locales.length > 0) {
1145
- if (!filters.locales.some((locale) => manifest.locales[locale])) return false;
1146
- }
1147
- if (filters.missingLocales && filters.missingLocales.length > 0) {
1148
- if (filters.missingLocales.some((locale) => manifest.locales[locale])) return false;
1149
- }
1150
- if (filters.published !== void 0) {
1151
- let hasPublishedLocale = false;
1152
- for (const localeVersion of localesOf(manifest)) {
1153
- if (!localeVersion.unpublishAt) {
1154
- hasPublishedLocale = true;
1155
- break;
1156
- }
1157
- if (new Date(localeVersion.unpublishAt) > /* @__PURE__ */ new Date()) {
1158
- hasPublishedLocale = true;
1159
- break;
1160
- }
1161
- }
1162
- if (filters.published !== hasPublishedLocale) return false;
1163
- }
1164
- return true;
1165
- }
1166
- /**
1167
- * Generator that yields manifests after applying all filters
1168
- * This is the main entry point for filtering content using indexes efficiently
1169
- */
1170
- function* filterContentWithIndexes(contentIndex, filters, sitesConfig) {
1171
- if (!filters) {
1172
- yield* contentIndex.listAllContent();
1173
- return;
1174
- }
1175
- if (filters.kind === "page" && filters.site && filters.collection) {
1176
- if (!contentIndex.getCollectionsForSite(filters.site).has(filters.collection)) return;
1177
- } else if (filters.kind === "block" && filters.collection) {
1178
- if (!contentIndex.getBlockCollections().has(filters.collection)) return;
1179
- }
1180
- let generator;
1181
- if (filters.kind === "page" && filters.site && filters.collection) generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);
1182
- else if (filters.kind === "block" && filters.collection) generator = contentIndex.getManifestsForCollection(filters.collection);
1183
- else if (filters.kind) generator = contentIndex.getManifestsForKind(filters.kind);
1184
- else if (filters.site && filters.collection) generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);
1185
- else if (filters.site && filters.locales?.length === 1) generator = contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0]);
1186
- else if (filters.site) generator = contentIndex.getManifestsForSite(filters.site);
1187
- else if (filters.collection) generator = contentIndex.getManifestsForCollection(filters.collection);
1188
- else if (filters.locales?.length === 1) generator = contentIndex.getManifestsForLocale(filters.locales[0]);
1189
- else generator = contentIndex.listAllContent();
1190
- for (const manifest of generator) {
1191
- if (!applyContentFilters(manifest, filters)) continue;
1192
- if (filters.localization) {
1193
- if (filters.localization === "complete" && filters.missingLocales?.length) continue;
1194
- const siteLocales = filters.site && manifest.kind === "page" ? sitesConfig.sites[filters.site]?.locales || sitesConfig.globalLocales : sitesConfig.globalLocales;
1195
- const localeCount = Object.keys(manifest.locales).length;
1196
- const hasLocales = siteLocales.filter((l) => manifest.locales[l]).length;
1197
- const totalLocales = siteLocales.length;
1198
- if (filters.localization === "complete" && hasLocales !== totalLocales) continue;
1199
- if (filters.localization === "partial" && (localeCount <= 1 || hasLocales === totalLocales)) continue;
1200
- if (filters.localization === "one" && localeCount !== 1) continue;
1201
- }
1202
- yield manifest;
1203
- }
1204
- }
1205
-
1206
- //#endregion
1207
- //#region src/base-content-index.ts
1208
- /**
1209
- * Base class for content indexes (blocks, data)
1210
- * Maintains collection->name->locale lookups with V8-optimized structures
1211
- */
1212
- var BaseContentIndex = class {
1213
- index = /* @__PURE__ */ new Map();
1214
- contentCache = /* @__PURE__ */ new Map();
1215
- nameIndex = /* @__PURE__ */ new Map();
1216
- collections = /* @__PURE__ */ new Set();
1217
- /**
1218
- * Add or update content in the index
1219
- * Merges manifest locales and updates content cache if provided
1220
- */
1221
- addContent(identity, localeVersion, content) {
1222
- const existing = this.index.get(identity.id);
1223
- const locale = localeVersion.locale;
1224
- if (existing) {
1225
- const existingLocale = existing.locales[locale];
1226
- if (!existingLocale || existingLocale.etag !== localeVersion.etag) existing.locales[locale] = localeVersion;
1227
- } else {
1228
- const newManifest = {
1229
- id: identity.id,
1230
- type: identity.type,
1231
- kind: identity.kind,
1232
- site: identity.site,
1233
- collection: identity.collection,
1234
- locales: { [locale]: localeVersion }
1235
- };
1236
- this.index.set(identity.id, newManifest);
1237
- this.collections.add(identity.collection);
1238
- }
1239
- if (content !== void 0) {
1240
- const existingCache = this.contentCache.get(identity.id);
1241
- if (existingCache) existingCache[locale] = content;
1242
- else this.contentCache.set(identity.id, { [locale]: content });
1243
- }
1244
- const manifestToIndex = existing || this.index.get(identity.id);
1245
- if (localeVersion.name) {
1246
- if (!this.nameIndex.has(identity.collection)) this.nameIndex.set(identity.collection, /* @__PURE__ */ new Map());
1247
- this.nameIndex.get(identity.collection).set(localeVersion.name, manifestToIndex);
1248
- }
1249
- }
1250
- /**
1251
- * Remove a specific locale from an entry
1252
- */
1253
- removeLocale(id, locale) {
1254
- const manifest = this.index.get(id);
1255
- if (!manifest || !manifest.locales[locale]) return;
1256
- manifest.locales[locale] = void 0;
1257
- const contentCache = this.contentCache.get(id);
1258
- if (contentCache) delete contentCache[locale];
1259
- if (Object.values(manifest.locales).filter((v) => v !== void 0).length === 0) this.removeEntry(id);
1260
- }
1261
- /**
1262
- * Remove an entry from the index
1263
- */
1264
- removeEntry(id) {
1265
- const manifest = this.index.get(id);
1266
- if (!manifest) return;
1267
- for (const localeVersion of localesOf(manifest)) if (localeVersion.name) {
1268
- const collectionMap = this.nameIndex.get(manifest.collection);
1269
- if (collectionMap) collectionMap.delete(localeVersion.name);
1270
- break;
1271
- }
1272
- this.index.delete(id);
1273
- this.contentCache.delete(id);
1274
- }
1275
- /**
1276
- * Get cached content for a specific locale
1277
- */
1278
- getCachedContent(id, locale) {
1279
- return this.contentCache.get(id)?.[locale] || null;
1280
- }
1281
- /**
1282
- * Get content manifest
1283
- */
1284
- getManifest(id) {
1285
- return this.index.get(id) || null;
1286
- }
1287
- /**
1288
- * Find entry by name
1289
- */
1290
- getByName(collection, name, locale) {
1291
- const collectionMap = this.nameIndex.get(collection);
1292
- if (!collectionMap) return null;
1293
- const manifest = collectionMap.get(name);
1294
- if (!manifest) return null;
1295
- if (locale && !manifest.locales[locale]) return null;
1296
- return manifest;
1297
- }
1298
- /**
1299
- * Generator for all manifests
1300
- */
1301
- *getAllManifests() {
1302
- for (const manifest of this.index.values()) yield manifest;
1303
- }
1304
- /**
1305
- * Generator for manifests by locale
1306
- */
1307
- *getManifestsByLocale(locale) {
1308
- for (const manifest of this.index.values()) if (manifest.locales[locale]) yield manifest;
1309
- }
1310
- /**
1311
- * Generator for manifests by collection
1312
- */
1313
- *getManifestsByCollection(collection) {
1314
- for (const manifest of this.index.values()) if (manifest.collection === collection) yield manifest;
1315
- }
1316
- /**
1317
- * Get the count of indexed content entries (unique IDs)
1318
- */
1319
- get entryCount() {
1320
- return this.index.size;
1321
- }
1322
- /**
1323
- * Clear all indexes
1324
- */
1325
- clear() {
1326
- this.index.clear();
1327
- this.contentCache.clear();
1328
- this.nameIndex.clear();
1329
- this.collections.clear();
1330
- }
1331
- };
1332
-
1333
- //#endregion
1334
- //#region src/block-index.ts
1335
- /**
1336
- * V8-optimized index for blocks
1337
- * Maintains collection->name->locale lookups
1338
- */
1339
- var BlockIndex = class extends BaseContentIndex {
1340
- constructor(locales) {
1341
- super();
1342
- }
1343
- };
1344
-
1345
- //#endregion
1346
- //#region src/data-index.ts
1347
- /**
1348
- * V8-optimized index for data collections
1349
- * Maintains collection->name->locale lookups
1350
- */
1351
- var DataIndex = class extends BaseContentIndex {};
1352
-
1353
- //#endregion
1354
- //#region src/site-index.ts
1355
- /**
1356
- * V8-optimized index for a single site
1357
- * Maintains pathname lookups and collections for one site only
1358
- */
1359
- var SiteIndex = class {
1360
- index = /* @__PURE__ */ new Map();
1361
- contentCache = /* @__PURE__ */ new Map();
1362
- pathnameIndex;
1363
- previousPathnameIndex;
1364
- collections = /* @__PURE__ */ new Set();
1365
- constructor(siteName, locales) {
1366
- this.locales = locales;
1367
- this.pathnameIndex = mapLocales(locales, () => /* @__PURE__ */ new Map());
1368
- this.previousPathnameIndex = mapLocales(locales, () => /* @__PURE__ */ new Map());
1369
- }
1370
- /**
1371
- * Add or update content in the index
1372
- * Merges manifest locales and updates content cache if provided
1373
- */
1374
- addContent(identity, localeVersion, content) {
1375
- const existing = this.index.get(identity.id);
1376
- const locale = localeVersion.locale;
1377
- if (existing) {
1378
- const existingLocale = existing.locales[locale];
1379
- let oldPathname;
1380
- for (const [pathname, indexedManifest] of this.pathnameIndex[locale].entries()) if (indexedManifest === existing && pathname !== localeVersion.pathname) {
1381
- oldPathname = pathname;
1382
- break;
1383
- }
1384
- if (!oldPathname && existingLocale?.pathname && existingLocale.pathname !== localeVersion.pathname) oldPathname = existingLocale.pathname;
1385
- const hadExistingLocale = !!existingLocale;
1386
- let deletedOldPathname = false;
1387
- let addedNewPathname = false;
1388
- const addedPreviousPathnames = [];
1389
- if (!existingLocale || existingLocale.etag !== localeVersion.etag || existingLocale.modified !== localeVersion.modified || oldPathname && oldPathname !== localeVersion.pathname) try {
1390
- existing.locales[locale] = localeVersion;
1391
- if (localeVersion.pathname) {
1392
- if (oldPathname && oldPathname !== localeVersion.pathname) {
1393
- this.pathnameIndex[locale].delete(oldPathname);
1394
- deletedOldPathname = true;
1395
- if (isContentPublished(localeVersion)) {
1396
- this.previousPathnameIndex[locale].set(oldPathname, existing);
1397
- addedPreviousPathnames.push(oldPathname);
1398
- }
1399
- }
1400
- this.pathnameIndex[locale].set(localeVersion.pathname, existing);
1401
- addedNewPathname = true;
1402
- }
1403
- if (localeVersion.previousPathnames) {
1404
- for (const prevPath of Object.keys(localeVersion.previousPathnames)) if (!this.previousPathnameIndex[locale].has(prevPath)) {
1405
- this.previousPathnameIndex[locale].set(prevPath, existing);
1406
- addedPreviousPathnames.push(prevPath);
1407
- }
1408
- }
1409
- } catch (error) {
1410
- if (hadExistingLocale) existing.locales[locale] = existingLocale;
1411
- else existing.locales[locale] = void 0;
1412
- if (deletedOldPathname && oldPathname) this.pathnameIndex[locale].set(oldPathname, existing);
1413
- if (addedNewPathname && localeVersion.pathname) this.pathnameIndex[locale].delete(localeVersion.pathname);
1414
- for (const prevPath of addedPreviousPathnames) this.previousPathnameIndex[locale].delete(prevPath);
1415
- throw error;
1416
- }
1417
- } else {
1418
- const newManifest = {
1419
- id: identity.id,
1420
- type: identity.type,
1421
- kind: identity.kind,
1422
- site: identity.site,
1423
- collection: identity.collection,
1424
- locales: { [locale]: localeVersion }
1425
- };
1426
- this.index.set(identity.id, newManifest);
1427
- this.collections.add(identity.collection);
1428
- if (localeVersion.pathname) this.pathnameIndex[locale].set(localeVersion.pathname, newManifest);
1429
- if (localeVersion.previousPathnames) for (const prevPath of Object.keys(localeVersion.previousPathnames)) this.previousPathnameIndex[locale].set(prevPath, newManifest);
1430
- }
1431
- if (content !== void 0) {
1432
- const existingCache = this.contentCache.get(identity.id);
1433
- if (existingCache) existingCache[locale] = content;
1434
- else this.contentCache.set(identity.id, { [locale]: content });
1435
- }
1436
- }
1437
- /**
1438
- * Remove a specific locale from an entry
1439
- */
1440
- removeLocale(id, locale) {
1441
- const manifest = this.index.get(id);
1442
- if (!manifest || !manifest.locales[locale]) return;
1443
- const localeVersion = manifest.locales[locale];
1444
- if (localeVersion.pathname) this.pathnameIndex[locale].delete(localeVersion.pathname);
1445
- if (localeVersion.previousPathnames) for (const prevPath of Object.keys(localeVersion.previousPathnames)) this.previousPathnameIndex[locale].delete(prevPath);
1446
- manifest.locales[locale] = void 0;
1447
- const contentCache = this.contentCache.get(id);
1448
- if (contentCache) delete contentCache[locale];
1449
- if (Object.keys(manifest.locales).length === 0) this.removeEntry(id);
1450
- }
1451
- /**
1452
- * Remove an entry from the index
1453
- */
1454
- removeEntry(id) {
1455
- const manifest = this.index.get(id);
1456
- if (!manifest) return;
1457
- for (const localeVersion of localesOf(manifest)) {
1458
- const { locale } = localeVersion;
1459
- if (localeVersion.pathname) this.pathnameIndex[locale].delete(localeVersion.pathname);
1460
- if (localeVersion.previousPathnames) for (const prevPath of Object.keys(localeVersion.previousPathnames)) this.previousPathnameIndex[locale].delete(prevPath);
1461
- }
1462
- this.index.delete(id);
1463
- this.contentCache.delete(id);
1464
- }
1465
- /**
1466
- * Get cached content for a specific locale
1467
- */
1468
- getCachedContent(id, locale) {
1469
- return this.contentCache.get(id)?.[locale] || null;
1470
- }
1471
- /**
1472
- * Get content manifest
1473
- */
1474
- getManifest(id) {
1475
- return this.index.get(id) || null;
1476
- }
1477
- /**
1478
- * Find content by pathname
1479
- */
1480
- getByPathname(pathname, locale) {
1481
- if (locale) return this.pathnameIndex[locale]?.get(pathname) || null;
1482
- for (const locale of this.locales) {
1483
- const manifest = this.pathnameIndex[locale].get(pathname);
1484
- if (manifest) return manifest;
1485
- }
1486
- return null;
1487
- }
1488
- /**
1489
- * Find content by previous pathname (for redirects)
1490
- */
1491
- getByPreviousPathname(pathname, locale) {
1492
- if (locale) return this.previousPathnameIndex[locale]?.get(pathname) || null;
1493
- for (const locale of this.locales) {
1494
- const manifest = this.previousPathnameIndex[locale].get(pathname);
1495
- if (manifest) return manifest;
1496
- }
1497
- return null;
1498
- }
1499
- /**
1500
- * Generator for all manifests
1501
- */
1502
- *getAllManifests() {
1503
- for (const manifest of this.index.values()) yield manifest;
1504
- }
1505
- /**
1506
- * Generator for manifests by locale
1507
- */
1508
- *getManifestsByLocale(locale) {
1509
- for (const manifest of this.index.values()) if (manifest.locales[locale]) yield manifest;
1510
- }
1511
- /**
1512
- * Get the count of indexed content entries (unique IDs)
1513
- */
1514
- get entryCount() {
1515
- return this.index.size;
1516
- }
1517
- /**
1518
- * Clear all indexes
1519
- */
1520
- clear() {
1521
- this.index.clear();
1522
- this.contentCache.clear();
1523
- for (const locale of this.locales) {
1524
- this.pathnameIndex[locale].clear();
1525
- this.previousPathnameIndex[locale].clear();
1526
- }
1527
- this.collections.clear();
1528
- }
1529
- };
1530
-
1531
- //#endregion
1532
- //#region src/content-index.ts
1533
- /**
1534
- * ContentIndex coordinates between per-site indexes and the block index
1535
- * This provides efficient filtering by routing to the appropriate specialized index
1536
- */
1537
- const globalCache = globalThis.__CONLOCA_CONTENT_INDEX_CACHE__ || {};
1538
- if (!globalThis.__CONLOCA_CONTENT_INDEX_CACHE__) globalThis.__CONLOCA_CONTENT_INDEX_CACHE__ = globalCache;
1539
- var ContentIndex = class ContentIndex {
1540
- static get cache() {
1541
- return globalCache;
1542
- }
1543
- siteIndexes;
1544
- blockIndex;
1545
- dataIndex;
1546
- constructor(sitesConfig) {
1547
- this.sitesConfig = sitesConfig;
1548
- this.blockIndex = new BlockIndex(sitesConfig.globalLocales);
1549
- this.dataIndex = new DataIndex();
1550
- this.siteIndexes = mapSiteNames(sitesConfig, (siteName) => {
1551
- const siteConfig = sitesConfig.sites[siteName];
1552
- return new SiteIndex(siteName, siteConfig.locales);
1553
- });
1554
- }
1555
- /**
1556
- * Get cached index or create a new one
1557
- */
1558
- static async getCachedOrCreate(contentRoot, sitesConfig) {
1559
- if (!ContentIndex.cache[contentRoot]) ContentIndex.cache[contentRoot] = new ContentIndex(sitesConfig);
1560
- return ContentIndex.cache[contentRoot];
1561
- }
1562
- /**
1563
- * Clear all cached indexes
1564
- */
1565
- static clearCache() {
1566
- Object.keys(globalCache).forEach((key) => delete globalCache[key]);
1567
- }
1568
- /**
1569
- * Create a new index without caching - for testing
1570
- */
1571
- static createUncached(sitesConfig) {
1572
- return new ContentIndex(sitesConfig);
1573
- }
1574
- /**
1575
- * Add or update content in the appropriate index
1576
- * Updates a single locale's manifest and content cache if provided
1577
- */
1578
- addContent(identity, localeVersion, content) {
1579
- if ((identity.kind === "block" || identity.kind === "data") && identity.site) throw new Error(`${identity.kind} cannot have a site property`);
1580
- if (identity.kind === "page" && !identity.site) throw new Error("Pages must have a site property");
1581
- if (identity.kind === "block") this.blockIndex.addContent(identity, localeVersion, content);
1582
- else if (identity.kind === "data") this.dataIndex.addContent(identity, localeVersion, content);
1583
- else {
1584
- const siteIndex = this.siteIndexes[identity.site];
1585
- if (siteIndex) siteIndex.addContent(identity, localeVersion, content);
1586
- }
1587
- }
1588
- /**
1589
- * Remove a specific locale from content
1590
- */
1591
- removeLocale(id, locale) {
1592
- const manifest = this.getManifest(id);
1593
- if (!manifest) return;
1594
- if (manifest.kind === "block") this.blockIndex.removeLocale(id, locale);
1595
- else if (manifest.kind === "data") this.dataIndex.removeLocale(id, locale);
1596
- else {
1597
- const siteIndex = this.siteIndexes[manifest.site];
1598
- if (siteIndex) siteIndex.removeLocale(id, locale);
1599
- }
1600
- }
1601
- /**
1602
- * Get cached content
1603
- */
1604
- getCachedContent(id, locale) {
1605
- const manifest = this.getManifest(id);
1606
- if (!manifest) return null;
1607
- if (manifest.kind === "block") return this.blockIndex.getCachedContent(id, locale);
1608
- if (manifest.kind === "data") return this.dataIndex.getCachedContent(id, locale);
1609
- const siteIndex = this.siteIndexes[manifest.site];
1610
- return siteIndex ? siteIndex.getCachedContent(id, locale) : null;
1611
- }
1612
- /**
1613
- * Remove an entry from all indexes
1614
- */
1615
- removeEntry(id) {
1616
- this.blockIndex.removeEntry(id);
1617
- this.dataIndex.removeEntry(id);
1618
- for (const site in this.siteIndexes) {
1619
- const siteIndex = this.siteIndexes[site];
1620
- if (siteIndex) siteIndex.removeEntry(id);
1621
- }
1622
- }
1623
- /**
1624
- * Get content manifest for a content ID
1625
- */
1626
- getManifest(id) {
1627
- let manifest = this.blockIndex.getManifest(id);
1628
- if (manifest) return manifest;
1629
- manifest = this.dataIndex.getManifest(id);
1630
- if (manifest) return manifest;
1631
- for (const site in this.siteIndexes) {
1632
- const siteIndex = this.siteIndexes[site];
1633
- if (siteIndex) {
1634
- manifest = siteIndex.getManifest(id);
1635
- if (manifest) return manifest;
1636
- }
1637
- }
1638
- return null;
1639
- }
1640
- /**
1641
- * Get a specific locale manifest
1642
- */
1643
- getLocaleVersion(id, locale) {
1644
- const manifest = this.getManifest(id);
1645
- if (!manifest) return null;
1646
- return manifest.locales[locale] || null;
1647
- }
1648
- /**
1649
- * Get site index
1650
- */
1651
- getSiteIndex(site) {
1652
- return this.siteIndexes[site] || null;
1653
- }
1654
- /**
1655
- * Get block index
1656
- */
1657
- getBlockIndex() {
1658
- return this.blockIndex;
1659
- }
1660
- /**
1661
- * Find content by pathname (delegates to site indexes)
1662
- */
1663
- getByPathname(site, pathname, locale) {
1664
- const siteIndex = this.siteIndexes[site];
1665
- return siteIndex ? siteIndex.getByPathname(pathname, locale) : null;
1666
- }
1667
- /**
1668
- * Find content by previous pathname (for redirects)
1669
- */
1670
- getByPreviousPathname(site, pathname, locale) {
1671
- const siteIndex = this.siteIndexes[site];
1672
- return siteIndex ? siteIndex.getByPreviousPathname(pathname, locale) : null;
1673
- }
1674
- /**
1675
- * Find block by name
1676
- */
1677
- getBlockByName(collection, name, locale) {
1678
- return this.blockIndex.getByName(collection, name, locale);
1679
- }
1680
- /**
1681
- * Get data index
1682
- */
1683
- getDataIndex() {
1684
- return this.dataIndex;
1685
- }
1686
- /**
1687
- * Find data entry by name
1688
- */
1689
- getDataByName(collection, name, locale) {
1690
- return this.dataIndex.getByName(collection, name, locale);
1691
- }
1692
- /**
1693
- * Get all collections for data
1694
- */
1695
- getDataCollections() {
1696
- return this.dataIndex.collections;
1697
- }
1698
- /**
1699
- * List all content (for iteration)
1700
- */
1701
- *listAllContent() {
1702
- yield* this.blockIndex.getAllManifests();
1703
- yield* this.dataIndex.getAllManifests();
1704
- for (const site in this.siteIndexes) {
1705
- const siteIndex = this.siteIndexes[site];
1706
- if (siteIndex) yield* siteIndex.getAllManifests();
1707
- }
1708
- }
1709
- /**
1710
- * Generator for all sites
1711
- */
1712
- *allSites() {
1713
- for (const site in this.siteIndexes) if (this.siteIndexes[site]) yield site;
1714
- }
1715
- /**
1716
- * Get all collections for a site
1717
- */
1718
- getCollectionsForSite(site) {
1719
- const siteIndex = this.siteIndexes[site];
1720
- return siteIndex ? siteIndex.collections : /* @__PURE__ */ new Set();
1721
- }
1722
- /**
1723
- * Get all collections for blocks
1724
- */
1725
- getBlockCollections() {
1726
- return this.blockIndex.collections;
1727
- }
1728
- /**
1729
- * Get default locale for a site
1730
- */
1731
- getDefaultLocale(site) {
1732
- if (!site) return this.sitesConfig.globalLocales[0];
1733
- return this.sitesConfig.sites[site]?.defaultLocale || this.sitesConfig.globalLocales[0];
1734
- }
1735
- /**
1736
- * Find content missing a specific locale
1737
- */
1738
- *findUntranslatedContent(targetLocale, options) {
1739
- for (const manifest of this.blockIndex.getAllManifests()) if (!manifest.locales[targetLocale]) {
1740
- if (!options?.includeUnpublished) {
1741
- let hasPublishedLocale = false;
1742
- for (const locale of localesOf(manifest)) if (!locale.unpublishAt || new Date(locale.unpublishAt) > /* @__PURE__ */ new Date()) {
1743
- hasPublishedLocale = true;
1744
- break;
1745
- }
1746
- if (!hasPublishedLocale) continue;
1747
- }
1748
- yield manifest;
1749
- }
1750
- for (const siteName in this.siteIndexes) {
1751
- const siteIndex = this.siteIndexes[siteName];
1752
- if (!siteIndex || options?.excludeSites?.includes(siteName)) continue;
1753
- for (const manifest of siteIndex.getAllManifests()) if (!manifest.locales[targetLocale]) {
1754
- if (!options?.includeUnpublished) {
1755
- let hasPublishedLocale = false;
1756
- for (const locale of localesOf(manifest)) if (!locale.unpublishAt || new Date(locale.unpublishAt) > /* @__PURE__ */ new Date()) {
1757
- hasPublishedLocale = true;
1758
- break;
1759
- }
1760
- if (!hasPublishedLocale) continue;
1761
- }
1762
- yield manifest;
1763
- }
1764
- }
1765
- }
1766
- /**
1767
- * Generators for efficient filtering
1768
- */
1769
- *getManifestsForKind(kind) {
1770
- if (kind === "block") yield* this.blockIndex.getAllManifests();
1771
- else if (kind === "data") yield* this.dataIndex.getAllManifests();
1772
- else for (const site in this.siteIndexes) {
1773
- const siteIndex = this.siteIndexes[site];
1774
- if (siteIndex) yield* siteIndex.getAllManifests();
1775
- }
1776
- }
1777
- *getManifestsForSite(site) {
1778
- const siteIndex = this.siteIndexes[site];
1779
- if (siteIndex) yield* siteIndex.getAllManifests();
1780
- }
1781
- *getManifestsForSiteLocale(site, locale) {
1782
- const siteIndex = this.siteIndexes[site];
1783
- if (siteIndex) yield* siteIndex.getManifestsByLocale(locale);
1784
- }
1785
- *getManifestsForSiteCollection(site, collection) {
1786
- const siteIndex = this.siteIndexes[site];
1787
- if (siteIndex) {
1788
- for (const manifest of siteIndex.getAllManifests()) if (manifest.collection === collection) yield manifest;
1789
- }
1790
- }
1791
- *getManifestsForLocale(locale) {
1792
- yield* this.blockIndex.getManifestsByLocale(locale);
1793
- yield* this.dataIndex.getManifestsByLocale(locale);
1794
- for (const site in this.siteIndexes) {
1795
- const siteIndex = this.siteIndexes[site];
1796
- if (siteIndex) yield* siteIndex.getManifestsByLocale(locale);
1797
- }
1798
- }
1799
- *getManifestsForCollection(collection) {
1800
- yield* this.blockIndex.getManifestsByCollection(collection);
1801
- yield* this.dataIndex.getManifestsByCollection(collection);
1802
- for (const site in this.siteIndexes) {
1803
- const siteIndex = this.siteIndexes[site];
1804
- if (siteIndex) {
1805
- for (const manifest of siteIndex.getAllManifests()) if (manifest.collection === collection) yield manifest;
1806
- }
1807
- }
1808
- }
1809
- /**
1810
- * Get the count of indexed content entries
1811
- */
1812
- get entryCount() {
1813
- let count = this.blockIndex.entryCount;
1814
- count += this.dataIndex.entryCount;
1815
- for (const site in this.siteIndexes) {
1816
- const siteIndex = this.siteIndexes[site];
1817
- if (siteIndex) count += siteIndex.entryCount;
1818
- }
1819
- return count;
1820
- }
1821
- /**
1822
- * Clear all indexes
1823
- */
1824
- clear() {
1825
- this.blockIndex.clear();
1826
- this.dataIndex.clear();
1827
- for (const site in this.siteIndexes) {
1828
- const siteIndex = this.siteIndexes[site];
1829
- if (siteIndex) siteIndex.clear();
1830
- }
1831
- }
1832
- };
1833
-
1834
- //#endregion
1835
- //#region src/data.ts
1836
- var Data = class {
1837
- constructor(api, dataIndex) {
1838
- this.api = api;
1839
- this.dataIndex = dataIndex;
1840
- }
1841
- *listContent(filters) {
1842
- if (filters?.collection) if (filters.locales && filters.locales.length > 0) {
1843
- for (const manifest of this.dataIndex.getManifestsByCollection(filters.collection)) if (filters.locales.some((locale) => manifest.locales[locale])) yield manifest;
1844
- } else yield* this.dataIndex.getManifestsByCollection(filters.collection);
1845
- else if (filters?.locales && filters.locales.length > 0) {
1846
- for (const manifest of this.dataIndex.getAllManifests()) if (filters.locales.some((locale) => manifest.locales[locale])) yield manifest;
1847
- } else yield* this.dataIndex.getAllManifests();
1848
- }
1849
- get collections() {
1850
- return this.dataIndex.collections;
1851
- }
1852
- getByName(collection, name, locale) {
1853
- return this.dataIndex.getByName(collection, name, locale);
1854
- }
1855
- isNameAvailable(collection, name, excludeId) {
1856
- const existing = this.getByName(collection, name);
1857
- return !existing || existing.id === excludeId;
1858
- }
1859
- getNameConflict(collection, name, excludeId) {
1860
- const existing = this.getByName(collection, name);
1861
- if (existing && existing.id !== excludeId) return existing.id;
1862
- return null;
1863
- }
1864
- isDataNameValid(dataName) {
1865
- if (!dataName || dataName.trim() === "") return false;
1866
- if (dataName.includes(".")) return false;
1867
- if (dataName.includes("/") || dataName.includes("\\")) return false;
1868
- return /^[a-zA-Z0-9_-]+$/.test(dataName);
1869
- }
1870
- async create(input) {
1871
- if (!this.isDataNameValid(input.name)) return {
1872
- success: false,
1873
- reason: "invalid_name",
1874
- error: /* @__PURE__ */ new Error(`Invalid data name: ${input.name}`)
1875
- };
1876
- if (this.getByName(input.collection, input.name)) return {
1877
- success: false,
1878
- reason: "name_taken",
1879
- error: /* @__PURE__ */ new Error(`Data name ${input.name} already exists in collection ${input.collection}`)
1880
- };
1881
- return this.api.createContent({
1882
- kind: "data",
1883
- collection: input.collection,
1884
- type: "json",
1885
- name: input.name,
1886
- meta: input.meta,
1887
- locales: input.locales
1888
- });
1889
- }
1890
- };
1891
-
1892
- //#endregion
1893
- //#region src/json-whitespace-view.ts
1894
- /**
1895
- * Zero-allocation JSON whitespace-skipping stream transform
1896
- * Skips whitespace outside of JSON strings, preserving whitespace inside strings
1897
- * Optimized to process multiple bytes at once when possible
1898
- */
1899
- var JsonWhitespaceSkippingView = class {
1900
- inString = false;
1901
- escaped = false;
1902
- singleByte = new Uint8Array(1);
1903
- constructor(downstream) {
1904
- this.downstream = downstream;
1905
- }
1906
- /**
1907
- * Process a single byte from JSON stream
1908
- * @param byte - The byte to process
1909
- */
1910
- updateByte(byte) {
1911
- let shouldInclude = false;
1912
- if (this.inString) {
1913
- shouldInclude = true;
1914
- if (this.escaped) this.escaped = false;
1915
- else if (byte === 92) this.escaped = true;
1916
- else if (byte === 34) this.inString = false;
1917
- } else if (byte === 34) {
1918
- this.inString = true;
1919
- shouldInclude = true;
1920
- } else if (byte !== 9 && byte !== 32 && byte !== 10 && byte !== 13) shouldInclude = true;
1921
- if (shouldInclude) {
1922
- this.singleByte[0] = byte;
1923
- this.downstream.update(this.singleByte);
1924
- }
1925
- }
1926
- /**
1927
- * Process a buffer range with simple batching
1928
- * Collects consecutive bytes that should be included
1929
- * @param buffer - The buffer to process
1930
- * @param start - Start position (inclusive)
1931
- * @param end - End position (exclusive)
1932
- */
1933
- updateBuffer(buffer, start = 0, end = buffer.length) {
1934
- let pos = start;
1935
- let runStart = start;
1936
- while (pos < end) {
1937
- const byte = buffer[pos];
1938
- let shouldInclude = false;
1939
- if (this.inString) {
1940
- shouldInclude = true;
1941
- if (this.escaped) this.escaped = false;
1942
- else if (byte === 92) this.escaped = true;
1943
- else if (byte === 34) this.inString = false;
1944
- else {
1945
- pos++;
1946
- let searchPos = pos;
1947
- while (searchPos < end) {
1948
- const quotePos = buffer.indexOf(34, searchPos);
1949
- if (quotePos === -1 || quotePos >= end) {
1950
- pos = end;
1951
- break;
1952
- }
1953
- let backslashCount = 0;
1954
- let checkPos = quotePos - 1;
1955
- while (checkPos >= 0 && buffer[checkPos] === 92) {
1956
- backslashCount++;
1957
- checkPos--;
1958
- }
1959
- if (backslashCount % 2 === 0) {
1960
- pos = quotePos + 1;
1961
- this.inString = false;
1962
- break;
1963
- }
1964
- searchPos = quotePos + 1;
1965
- }
1966
- continue;
1967
- }
1968
- } else if (byte === 34) {
1969
- this.inString = true;
1970
- shouldInclude = true;
1971
- } else if (byte !== 9 && byte !== 32 && byte !== 10 && byte !== 13) shouldInclude = true;
1972
- if (shouldInclude) pos++;
1973
- else {
1974
- if (pos > runStart) this.downstream.update(buffer.subarray(runStart, pos));
1975
- pos++;
1976
- runStart = pos;
1977
- }
1978
- }
1979
- if (pos > runStart) this.downstream.update(buffer.subarray(runStart, pos));
1980
- }
1981
- /**
1982
- * Reset the parser state
1983
- */
1984
- reset() {
1985
- this.inString = false;
1986
- this.escaped = false;
1987
- }
1988
- };
1989
-
1990
- //#endregion
1991
- //#region src/url-safe-base64.ts
1992
- /**
1993
- * Convert bytes to URL-safe base64
1994
- * Replaces + with -, / with _, and removes = padding
1995
- */
1996
- function toUrlSafeBase64(bytes) {
1997
- const b64 = Buffer.from(bytes).toString("base64");
1998
- const buf = Buffer.from(b64, "ascii");
1999
- let write = 0;
2000
- for (let read = 0; read < buf.length; read++) {
2001
- const c = buf[read];
2002
- if (c === 43) buf[write++] = 45;
2003
- else if (c === 47) buf[write++] = 95;
2004
- else if (c === 61) {} else buf[write++] = c;
2005
- }
2006
- return buf.subarray(0, write).toString("ascii");
2007
- }
2008
- /**
2009
- * Convert BigInt to URL-safe base64
2010
- * @param value - The BigInt value to convert
2011
- * @returns URL-safe base64 string representation
2012
- */
2013
- function bigintToUrlSafeBase64(value) {
2014
- const hashBuffer = new Uint8Array(8);
2015
- new DataView(hashBuffer.buffer).setBigUint64(0, value, false);
2016
- return toUrlSafeBase64(hashBuffer);
2017
- }
2018
-
2019
- //#endregion
2020
- //#region src/etag-utils.ts
2021
- /**
2022
- * Calculate content ETag using SHA256 from buffer view
2023
- * @param buffer - The file buffer view
2024
- * @param start - Start position (inclusive)
2025
- * @param end - End position (exclusive), or -1 for entire buffer
2026
- */
2027
- function calculateContentEtagFromBuffer(buffer, start = 0, end = -1) {
2028
- const actualEnd = end === -1 ? buffer.length : end;
2029
- const hasher = createHash("sha256");
2030
- new JsonWhitespaceSkippingView(hasher).updateBuffer(buffer, start, actualEnd);
2031
- return toUrlSafeBase64(hasher.digest());
2032
- }
2033
- const dashCode = "-".charCodeAt(0);
2034
- const newlineCode = "\n".charCodeAt(0);
2035
- /**
2036
- * Find the content start position in MDX buffer (after second ---)
2037
- * @param buffer - The MDX content buffer
2038
- * @returns Position where content starts, or -1 if not found
2039
- */
2040
- function findMdxContentStartPosition(buffer) {
2041
- let dashCount = 0;
2042
- let i = 0;
2043
- while (i < buffer.length - 4) if (buffer[i] === dashCode && buffer[i + 1] === dashCode && buffer[i + 2] === dashCode && buffer[i + 3] === newlineCode) {
2044
- dashCount++;
2045
- if (dashCount === 2) {
2046
- i += 4;
2047
- if (i < buffer.length && buffer[i] === newlineCode) return i + 1;
2048
- return i;
2049
- }
2050
- i += 4;
2051
- } else {
2052
- const nextDashPos = buffer.indexOf(dashCode, i + 1);
2053
- if (nextDashPos === -1) break;
2054
- i = nextDashPos;
2055
- }
2056
- return -1;
2057
- }
2058
- /**
2059
- * Calculate both ETags from an MDX buffer
2060
- *
2061
- * MDX files use YAML frontmatter which has different characteristics than JSON:
2062
- * - YAML does not require quotes around keys or string values
2063
- * - YAML allows multiple formatting styles (flow vs block style)
2064
- * - YAML field order is not significant for parsing
2065
- *
2066
- * Unlike VXJSON which requires "content" to be the last field and needs special
2067
- * parsing to validate structure, YAML frontmatter can be hashed as-is because:
2068
- * 1. The frontmatter boundaries are clearly delimited by ---
2069
- * 2. Different YAML formatting of the same data SHOULD produce different hashes
2070
- * (e.g., flow style [a,b] vs block style with dashes)
2071
- * 3. There's no requirement to validate field ordering
2072
- *
2073
- * This means we can directly hash the YAML bytes without any whitespace
2074
- * normalization or parsing, which is both simpler and more correct.
2075
- *
2076
- * @param buffer - The complete file buffer
2077
- * @param contentStartPos - Position where content starts (after second ---), or -1 if no content
2078
- */
2079
- function calculateEtagsFromMdxBuffer(buffer, contentStartPos) {
2080
- if (contentStartPos === -1) {
2081
- const hasher = xxh3.Xxh3.withSeed(0n);
2082
- hasher.update(buffer);
2083
- return {
2084
- metaEtag: bigintToUrlSafeBase64(hasher.digest()),
2085
- contentEtag: calculateContentEtagFromBuffer(new Uint8Array(0))
2086
- };
2087
- }
2088
- const metaHasher = xxh3.Xxh3.withSeed(0n);
2089
- metaHasher.update(buffer.subarray(0, contentStartPos));
2090
- const metaEtag = bigintToUrlSafeBase64(metaHasher.digest());
2091
- const contentHasher = createHash("sha256");
2092
- contentHasher.update(buffer.subarray(contentStartPos));
2093
- return {
2094
- metaEtag,
2095
- contentEtag: toUrlSafeBase64(contentHasher.digest())
2096
- };
2097
- }
2098
- /**
2099
- * Parse dual ETags from query string: "meta.content"
2100
- */
2101
- function parseDualEtag(etag) {
2102
- const parts = etag.split(".");
2103
- if (parts.length !== 2) return null;
2104
- return {
2105
- meta: parts[0],
2106
- content: parts[1]
2107
- };
2108
- }
2109
-
2110
- //#endregion
2111
- //#region src/vxjson.ts
2112
- const textDecoder$1 = new TextDecoder();
2113
- const CONTENT_MARKER = new TextEncoder().encode("\"content\":");
2114
- /**
2115
- * Calculate metadata ETag using xxHash from buffer view
2116
- * @param buffer - The file buffer view
2117
- * @param start - Start position (inclusive)
2118
- * @param end - End position (exclusive), or -1 for entire buffer
2119
- */
2120
- function calculateMetaEtagFromBuffer(buffer, start = 0, end = -1) {
2121
- const actualEnd = end === -1 ? buffer.length : end;
2122
- const hasher = xxh3.Xxh3.withSeed(0n);
2123
- new JsonWhitespaceSkippingView(hasher).updateBuffer(buffer, start, actualEnd);
2124
- return bigintToUrlSafeBase64(hasher.digest());
2125
- }
2126
- /**
2127
- * Calculate both ETags from a VXJSON buffer using views
2128
- * Finds the "content" field position and validates it's the last field
2129
- * @param buffer - The complete file buffer
2130
- * @returns Result with ETags or validation error
2131
- */
2132
- function calculateEtagsFromVXJSONBuffer(buffer, allowTruncated = false) {
2133
- let pos = 0;
2134
- let depth = 0;
2135
- let inString = false;
2136
- let escaped = false;
2137
- let contentStartPos = -1;
2138
- let foundContentAtRoot = false;
2139
- let expectingKey = false;
2140
- let expectingValue = false;
2141
- let keyStart = -1;
2142
- while (pos < buffer.length && (buffer[pos] === 32 || buffer[pos] === 9 || buffer[pos] === 10 || buffer[pos] === 13)) pos++;
2143
- if (pos >= buffer.length || buffer[pos] !== 123) return {
2144
- success: false,
2145
- error: "invalid_json"
2146
- };
2147
- depth = 1;
2148
- expectingKey = true;
2149
- pos++;
2150
- while (pos < buffer.length && depth > 0) {
2151
- const byte = buffer[pos];
2152
- if (inString) {
2153
- if (escaped) escaped = false;
2154
- else if (byte === 92) escaped = true;
2155
- else if (byte === 34) {
2156
- inString = false;
2157
- if (depth === 1 && expectingKey && keyStart >= 0) {
2158
- const keyLength = pos - keyStart + 1;
2159
- if (foundContentAtRoot) {
2160
- if (keyLength === 9) {
2161
- let isContent = true;
2162
- for (let i = 0; i < 7; i++) if (buffer[keyStart + 1 + i] !== CONTENT_MARKER[i + 1]) {
2163
- isContent = false;
2164
- break;
2165
- }
2166
- if (isContent) return {
2167
- success: false,
2168
- error: "invalid_json"
2169
- };
2170
- }
2171
- return {
2172
- success: false,
2173
- error: "content_not_last"
2174
- };
2175
- }
2176
- if (keyLength === 9) {
2177
- let isContent = true;
2178
- for (let i = 0; i < 7; i++) if (buffer[keyStart + 1 + i] !== CONTENT_MARKER[i + 1]) {
2179
- isContent = false;
2180
- break;
2181
- }
2182
- if (isContent) {
2183
- foundContentAtRoot = true;
2184
- contentStartPos = keyStart;
2185
- }
2186
- }
2187
- expectingKey = false;
2188
- expectingValue = true;
2189
- keyStart = -1;
2190
- }
2191
- }
2192
- } else if (byte === 34) {
2193
- inString = true;
2194
- if (depth === 1 && expectingKey) keyStart = pos;
2195
- } else if (byte === 123 || byte === 91) {
2196
- depth++;
2197
- if (depth === 1 && expectingValue) expectingValue = false;
2198
- } else if (byte === 125 || byte === 93) {
2199
- depth--;
2200
- if (depth === 0) break;
2201
- } else if (byte === 58 && depth === 1) {
2202
- if (!expectingValue) return {
2203
- success: false,
2204
- error: "invalid_json"
2205
- };
2206
- } else if (byte === 44 && depth === 1) {
2207
- expectingKey = true;
2208
- expectingValue = false;
2209
- } else if (depth === 1 && expectingValue && byte !== 32 && byte !== 9 && byte !== 10 && byte !== 13) expectingValue = false;
2210
- pos++;
2211
- }
2212
- const isTruncated = depth !== 0;
2213
- if (isTruncated && !allowTruncated) return {
2214
- success: false,
2215
- error: "invalid_json"
2216
- };
2217
- if (contentStartPos === -1) return {
2218
- success: true,
2219
- metaEtag: calculateMetaEtagFromBuffer(buffer),
2220
- contentStartPos: -1
2221
- };
2222
- if (isTruncated) return {
2223
- success: true,
2224
- metaEtag: calculateMetaEtagFromBuffer(buffer, 0, contentStartPos),
2225
- contentStartPos
2226
- };
2227
- let metaEnd = contentStartPos - 1;
2228
- while (metaEnd > 0) {
2229
- const byte = buffer[metaEnd];
2230
- if (byte === 44 || byte === 32 || byte === 9 || byte === 10 || byte === 13) metaEnd--;
2231
- else break;
2232
- }
2233
- const metaHasher = xxh3.Xxh3.withSeed(0n);
2234
- const metaView = new JsonWhitespaceSkippingView(metaHasher);
2235
- const openBrace = new Uint8Array([123]);
2236
- const closeBrace = new Uint8Array([125]);
2237
- metaHasher.update(openBrace);
2238
- metaView.updateBuffer(buffer, 1, metaEnd);
2239
- metaHasher.update(closeBrace);
2240
- const metaEtag = bigintToUrlSafeBase64(metaHasher.digest());
2241
- const contentHasher = createHash("sha256");
2242
- const contentView = new JsonWhitespaceSkippingView(contentHasher);
2243
- contentHasher.update(openBrace);
2244
- contentView.updateBuffer(buffer, contentStartPos, buffer.length - 1);
2245
- contentHasher.update(closeBrace);
2246
- return {
2247
- success: true,
2248
- metaEtag,
2249
- contentEtag: toUrlSafeBase64(contentHasher.digest()),
2250
- contentStartPos
2251
- };
2252
- }
2253
- /**
2254
- * VXJSON (Variant JSON) module for parsing and serializing VXJSON files
2255
- *
2256
- * VXJSON is a specialized JSON format that guarantees:
2257
- * 1. The root is always an object (never an array or primitive)
2258
- * 2. The "content" field always comes last in the object
2259
- * 3. Field order is deterministic for consistent ETag calculation
2260
- * 4. Metadata fits within 4085 bytes, ensuring "content" field is found within first 4KB
2261
- * 5. First 4KB must either be complete JSON OR end exactly with '"content":'
2262
- *
2263
- * This format enables efficient 4KB parsing where only the first 4KB of a file
2264
- * needs to be read to extract all metadata and locate the content position.
2265
- * The constraint that 4KB reads must end with '"content":' ensures reliable parsing.
2266
- *
2267
- * This module centralizes all VXJSON-specific logic including:
2268
- * - Parsing partial buffers (first 4KB for indexing)
2269
- * - Finding content position for ETag calculation
2270
- * - Serializing with proper field ordering and size validation
2271
- * - Calculating ETags from buffers
2272
- */
2273
- /**
2274
- * VXJSON static utilities for parsing and validating VXJSON files
2275
- */
2276
- var VXJSON = class VXJSON {
2277
- /**
2278
- * Parse first 4KB of VXJSON content from buffer
2279
- * Used during indexing to extract metadata without loading full content
2280
- *
2281
- * VXJSON format requirement: first 4KB must either be complete JSON OR end with '"content":'
2282
- * This ensures reliable parsing and validation.
2283
- */
2284
- static parse4KB(buffer, bytesRead) {
2285
- if (bytesRead < 4096 || buffer[bytesRead - 1] === 125) {
2286
- const partialContent = textDecoder$1.decode(buffer.subarray(0, bytesRead));
2287
- const data = JSON.parse(partialContent);
2288
- let contentStartPos = -1;
2289
- if (data.content !== void 0) {
2290
- const etagResult = calculateEtagsFromVXJSONBuffer(buffer.subarray(0, bytesRead));
2291
- if (etagResult.success) contentStartPos = etagResult.contentStartPos;
2292
- }
2293
- return {
2294
- id: data.id,
2295
- created: data.created,
2296
- modified: data.modified,
2297
- publishAt: data.publishAt,
2298
- unpublishAt: data.unpublishAt,
2299
- previousPathnames: data.previousPathnames,
2300
- pathname: data.pathname,
2301
- name: data.name,
2302
- meta: data.meta || {},
2303
- content: data.content,
2304
- contentStartPos
2305
- };
2306
- }
2307
- const etagResult = calculateEtagsFromVXJSONBuffer(buffer.subarray(0, bytesRead), true);
2308
- if (!etagResult.success) throw new Error(`Invalid VXJSON format: ${etagResult.error}. This violates the VXJSON specification.`);
2309
- const contentStartPos = etagResult.contentStartPos;
2310
- let metadataEnd = contentStartPos;
2311
- while (metadataEnd > 0) {
2312
- const byte = buffer[metadataEnd - 1];
2313
- if (byte === 44) {
2314
- metadataEnd--;
2315
- break;
2316
- }
2317
- if (byte === 32 || byte === 9 || byte === 10 || byte === 13) metadataEnd--;
2318
- else break;
2319
- }
2320
- const metadataBuffer = new Uint8Array(metadataEnd + 1);
2321
- metadataBuffer.set(buffer.subarray(0, metadataEnd));
2322
- metadataBuffer[metadataEnd] = 125;
2323
- const partialContent = textDecoder$1.decode(metadataBuffer);
2324
- const data = JSON.parse(partialContent);
2325
- return {
2326
- id: data.id,
2327
- created: data.created,
2328
- modified: data.modified,
2329
- publishAt: data.publishAt,
2330
- unpublishAt: data.unpublishAt,
2331
- previousPathnames: data.previousPathnames,
2332
- pathname: data.pathname,
2333
- name: data.name,
2334
- meta: data.meta || {},
2335
- contentStartPos
2336
- };
2337
- }
2338
- /**
2339
- * Find the position of the "content" field in a VXJSON buffer
2340
- * Returns -1 if not found
2341
- */
2342
- static findContentPosition(buffer) {
2343
- const etagResult = calculateEtagsFromVXJSONBuffer(buffer);
2344
- if (etagResult.success) return etagResult.contentStartPos;
2345
- return -1;
2346
- }
2347
- /**
2348
- * Calculate ETags for a VXJSON buffer
2349
- * Returns null if the buffer is not valid VXJSON
2350
- */
2351
- static calculateEtagsOnly(buffer) {
2352
- const result = calculateEtagsFromVXJSONBuffer(buffer);
2353
- if (!result.success) return null;
2354
- return {
2355
- metaEtag: result.metaEtag,
2356
- contentEtag: result.contentEtag
2357
- };
2358
- }
2359
- /**
2360
- * Create a dual ETag string from a VXJSON buffer
2361
- * Returns null if the buffer is not valid VXJSON
2362
- */
2363
- static createEtag(buffer) {
2364
- const etags = VXJSON.calculateEtagsOnly(buffer);
2365
- if (!etags) return null;
2366
- return etags.contentEtag ? `${etags.metaEtag}.${etags.contentEtag}` : etags.metaEtag;
2367
- }
2368
- /**
2369
- * Validate that a VXJSON buffer has the correct structure
2370
- * (content field must be last)
2371
- */
2372
- static isValid(buffer) {
2373
- return calculateEtagsFromVXJSONBuffer(buffer).success;
2374
- }
2375
- /**
2376
- * Parse a complete VXJSON file from string
2377
- */
2378
- static parse(content) {
2379
- return JSON.parse(content);
2380
- }
2381
- /**
2382
- * Parse a complete VXJSON file from buffer
2383
- */
2384
- static parseBuffer(buffer) {
2385
- const content = textDecoder$1.decode(buffer);
2386
- return VXJSON.parse(content);
2387
- }
2388
- /**
2389
- * Calculate both ETags from a VXJSON buffer using views
2390
- * Finds the "content" field position and validates it's the last field
2391
- * @param buffer - The complete file buffer
2392
- * @returns Result with ETags or validation error
2393
- */
2394
- static calculateETags = calculateEtagsFromVXJSONBuffer;
2395
- /**
2396
- * Calculate a simple single etag from the entire buffer
2397
- * Used for data files that don't follow the content-last convention
2398
- */
2399
- static calculateSimpleEtag(buffer) {
2400
- return calculateMetaEtagFromBuffer(buffer);
2401
- }
2402
- /**
2403
- * Serialize a VXJSONFile to VXJSON format string
2404
- * Ensures content field is last and enforces 4KB constraint efficiently
2405
- */
2406
- static serialize(data) {
2407
- const { content, ...metadataFields } = data;
2408
- if (content === void 0 || content === null) throw new Error("VXJSON format requires a \"content\" field");
2409
- const sortedMetadata = sortKeys(metadataFields, { deep: true });
2410
- const metadataJson = JSON.stringify(sortedMetadata, (_key, value) => {
2411
- if (value === "") return;
2412
- return value;
2413
- }, " ");
2414
- const wrappedContent = JSON.stringify({ c: sortKeys(content, { deep: true }) }, null, " ");
2415
- const contentJson = wrappedContent.slice(wrappedContent.indexOf(": ") + 2, -2);
2416
- const metadataWithoutClosing = metadataJson.slice(0, -2);
2417
- const contentFieldPrefix = ",\n \"content\": ";
2418
- const contentKeyPosition = metadataWithoutClosing.length + 1 + 2;
2419
- const maxContentKeyPosition = 4086;
2420
- 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.`);
2421
- return `${metadataWithoutClosing}${contentFieldPrefix}${contentJson}\n}`;
2422
- }
2423
- };
2424
-
2425
- //#endregion
2426
- //#region src/filesystem-content-api.ts
2427
- function ensureError(error) {
2428
- if (error instanceof Error) return error;
2429
- return new Error(String(error));
2430
- }
2431
- const textDecoder = new TextDecoder();
2432
- function parse4KBMDX(buffer, bytesRead) {
2433
- const { data: frontmatter } = matter(textDecoder.decode(buffer.subarray(0, bytesRead)));
2434
- const delimiter = new TextEncoder().encode("---");
2435
- let delimiterCount = 0;
2436
- let contentStartPos = -1;
2437
- for (let i = 0; i <= bytesRead - delimiter.length; i++) {
2438
- let match = true;
2439
- for (let j = 0; j < delimiter.length; j++) if (buffer[i + j] !== delimiter[j]) {
2440
- match = false;
2441
- break;
2442
- }
2443
- if (match) {
2444
- delimiterCount++;
2445
- if (delimiterCount === 2) {
2446
- contentStartPos = i + delimiter.length;
2447
- while (contentStartPos < bytesRead && (buffer[contentStartPos] === 10 || buffer[contentStartPos] === 13)) contentStartPos++;
2448
- break;
2449
- }
2450
- }
2451
- }
2452
- const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
2453
- return {
2454
- id,
2455
- created,
2456
- modified,
2457
- publishAt,
2458
- unpublishAt,
2459
- meta: metaFields,
2460
- contentStartPos
2461
- };
2462
- }
2463
- /**
2464
- * FileSystem-based Content API Implementation
2465
- *
2466
- * Stores content as files on disk in a git-friendly format:
2467
- * - Pages: /{site}/pages/{filename}.{locale}.vxjson
2468
- * - Blocks: /blocks/{collection}/{filename}.{locale}.{mdx|vxjson}
2469
- *
2470
- * ## Indexing
2471
- *
2472
- * Content is indexed at startup for performance. The index is cached per
2473
- * content root path and cleared when the process restarts.
2474
- *
2475
- * ## Read-Repair
2476
- *
2477
- * Since files can be modified externally (git, editors), this implementation:
2478
- *
2479
- * 1. Repairs invalid VXJSON files (ensures "content" field is last)
2480
- * 2. Adds missing required fields (id, created, modified)
2481
- * 3. Handles files added after initial indexing
2482
- * 4. Updates the index when files are repaired or discovered
2483
- *
2484
- * ## Performance
2485
- *
2486
- * - Initial indexing reads only first 4KB of each file
2487
- * - Full content is loaded on demand
2488
- * - ETags are calculated using streaming for efficiency
2489
- */
2490
- var FileSystemContentAPI = class FileSystemContentAPI {
2491
- contentRoot;
2492
- absoluteContentRoot;
2493
- contentIndex;
2494
- sitesConfig;
2495
- blocks;
2496
- data;
2497
- sites;
2498
- get normalizedContentRoot() {
2499
- return this.contentRoot;
2500
- }
2501
- constructor(contentRoot, canvasDir, sitesConfig, contentIndex) {
2502
- if (contentRoot.startsWith("./")) this.contentRoot = contentRoot.slice(2);
2503
- else if (contentRoot.startsWith("/")) this.contentRoot = contentRoot;
2504
- else this.contentRoot = contentRoot;
2505
- this.absoluteContentRoot = resolve$1(this.contentRoot);
2506
- this.sitesConfig = sitesConfig;
2507
- this.contentIndex = contentIndex;
2508
- this.blocks = new Blocks(this, this.contentIndex.getBlockIndex());
2509
- this.data = new Data(this, this.contentIndex.getDataIndex());
2510
- this.sites = mapSiteNames(sitesConfig, (siteName) => {
2511
- const siteIndex = this.contentIndex.getSiteIndex(siteName);
2512
- if (!siteIndex) throw new Error(`Site index not found for ${siteName}`);
2513
- return new Site(siteName, this, siteIndex);
2514
- });
2515
- }
2516
- static async create(options) {
2517
- const { canvasDir } = options;
2518
- const contentRoot = options.contentRoot;
2519
- const sitesPath = join$1(resolve$1(contentRoot), "sites.json");
2520
- let sitesConfig;
2521
- try {
2522
- const content = await readFile(sitesPath, "utf-8");
2523
- const parsed = JSON.parse(content);
2524
- if (!parsed.sites || typeof parsed.sites !== "object") {
2525
- console.warn(`Warning: sites.json has invalid structure at ${sitesPath}. Expected 'sites' property. Using default configuration.`);
2526
- sitesConfig = {
2527
- sites: {},
2528
- globalLocales: ["en"]
2529
- };
2530
- } else if (!parsed.globalLocales || !Array.isArray(parsed.globalLocales)) {
2531
- console.warn(`Warning: sites.json is missing 'globalLocales' array at ${sitesPath}. Using default global locales.`);
2532
- sitesConfig = {
2533
- sites: parsed.sites,
2534
- globalLocales: ["en"]
2535
- };
2536
- } else sitesConfig = parsed;
2537
- } catch (error) {
2538
- console.warn(`Warning: sites.json is missing at ${sitesPath}. Using empty configuration.`);
2539
- sitesConfig = {
2540
- sites: {},
2541
- globalLocales: ["en"]
2542
- };
2543
- }
2544
- const normalizedContentRoot = contentRoot.startsWith("./") ? contentRoot.slice(2) : contentRoot;
2545
- const contentIndex = await ContentIndex.getCachedOrCreate(normalizedContentRoot, sitesConfig);
2546
- const api = new FileSystemContentAPI(contentRoot, canvasDir, sitesConfig, contentIndex);
2547
- if (contentIndex.entryCount === 0) await api.indexAllContent();
2548
- return api;
2549
- }
2550
- /**
2551
- * Clear all caches - useful for testing
2552
- */
2553
- static clearCaches() {
2554
- ContentIndex.clearCache();
2555
- }
2556
- async indexAllContent() {
2557
- this.contentIndex.clear();
2558
- const files = await this.scanContentFiles();
2559
- const OPTIMAL_BATCH_SIZE = 1e3;
2560
- console.log(`Indexing ${files.length} content files...`);
2561
- const bufferCount = Math.min(files.length, OPTIMAL_BATCH_SIZE);
2562
- const buffers = Array.from({ length: bufferCount }, () => new Uint8Array(4096));
2563
- for (let i = 0; i < files.length; i += OPTIMAL_BATCH_SIZE) {
2564
- const batch = files.slice(i, i + OPTIMAL_BATCH_SIZE);
2565
- await Promise.all(batch.map(async (filePath, index) => {
2566
- try {
2567
- const result = await this.parseFileHeaderWithRepair(filePath, buffers[index]);
2568
- if (result) {
2569
- const { manifest, localeVersion, content } = result;
2570
- this.contentIndex.addContent(manifest, localeVersion, content);
2571
- }
2572
- } catch (error) {
2573
- console.error(`Failed to index ${filePath}:`, error);
2574
- }
2575
- }));
2576
- }
2577
- }
2578
- async parseFileHeaderWithRepair(originalFilePath, buffer) {
2579
- let handle;
2580
- let bytesRead = 0;
2581
- let filePath = originalFilePath;
2582
- try {
2583
- handle = await open(filePath, "r");
2584
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
2585
- } catch (error) {
2586
- console.error(`Error reading ${filePath}:`, error);
2587
- throw error;
2588
- } finally {
2589
- await handle?.close();
2590
- }
2591
- try {
2592
- let relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
2593
- let parts = relativePath.split("/");
2594
- let site;
2595
- let collection;
2596
- let locale = "en";
2597
- let name;
2598
- let pathname;
2599
- let parsedData = {};
2600
- let kind;
2601
- if (parts[0] === "blocks") {
2602
- kind = "block";
2603
- if (parts.length === 2) {
2604
- collection = "general";
2605
- const filename = parts[1];
2606
- const generalDir = join$1(this.absoluteContentRoot, "blocks", "general");
2607
- try {
2608
- await mkdir(generalDir, { recursive: true });
2609
- } catch (error) {}
2610
- const newFilePath = join$1(generalDir, filename);
2611
- try {
2612
- await handle?.close();
2613
- handle = void 0;
2614
- try {
2615
- await (await open(newFilePath, "r")).close();
2616
- console.warn(`Cannot move ${filename} to blocks/general/: target file already exists`);
2617
- } catch (error) {
2618
- await rename(filePath, newFilePath);
2619
- console.log(`Repaired: Moved ${filename} to blocks/general/ collection`);
2620
- filePath = newFilePath;
2621
- relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
2622
- parts = relativePath.split("/");
2623
- handle = await open(filePath, "r");
2624
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
2625
- }
2626
- } catch (moveError) {
2627
- console.error(`Failed to move ${filename} to general collection:`, moveError);
2628
- handle = await open(filePath, "r");
2629
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
2630
- }
2631
- } else collection = parts[1];
2632
- const filename = parts[parts.length - 1];
2633
- const matchWithLocale = filename.match(/^(.+)\.(\w+)\.(mdx|vxjson)$/);
2634
- const matchWithoutLocale = filename.match(/^(.+)\.(mdx|vxjson)$/);
2635
- if (matchWithLocale) {
2636
- name = matchWithLocale[1];
2637
- locale = matchWithLocale[2];
2638
- } else if (matchWithoutLocale) {
2639
- name = matchWithoutLocale[1];
2640
- locale = this.contentIndex.getDefaultLocale("");
2641
- console.log(`Found file without locale suffix: ${filename}`);
2642
- const extension = matchWithoutLocale[2];
2643
- const newFilename = `${name}.${locale}.${extension}`;
2644
- const newFilePath = join$1(dirname$1(filePath), newFilename);
2645
- console.log(`Will rename to: ${newFilename} at ${newFilePath}`);
2646
- try {
2647
- await handle?.close();
2648
- handle = void 0;
2649
- await (await open(newFilePath, "r")).close();
2650
- console.warn(`Cannot rename ${filename} to ${newFilename}: target file already exists`);
2651
- } catch (error) {
2652
- console.log(`Target file doesn't exist, proceeding with rename`);
2653
- try {
2654
- await rename(filePath, newFilePath);
2655
- console.log(`Successfully renamed ${filename} to ${newFilename}`);
2656
- filePath = newFilePath;
2657
- relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
2658
- parts = relativePath.split("/");
2659
- handle = await open(filePath, "r");
2660
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
2661
- } catch (renameError) {
2662
- console.error(`Failed to rename ${filename}:`, renameError);
2663
- handle = await open(filePath, "r");
2664
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
2665
- }
2666
- }
2667
- }
2668
- if (filePath.endsWith(".mdx")) parsedData = parse4KBMDX(buffer, bytesRead);
2669
- else parsedData = VXJSON.parse4KB(buffer, bytesRead);
2670
- } else if (parts[0] === "data") {
2671
- kind = "data";
2672
- collection = parts[1];
2673
- const match = parts[parts.length - 1].match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.json$/);
2674
- if (match) {
2675
- name = match[1];
2676
- locale = match[2];
2677
- }
2678
- const content = textDecoder.decode(buffer.subarray(0, bytesRead));
2679
- try {
2680
- const jsonData = JSON.parse(content);
2681
- parsedData = {
2682
- id: jsonData.id,
2683
- type: "json",
2684
- created: jsonData.created,
2685
- modified: jsonData.modified,
2686
- publishAt: jsonData.publishAt,
2687
- unpublishAt: jsonData.unpublishAt,
2688
- meta: jsonData.meta || { title: name || "Untitled" },
2689
- data: jsonData.data,
2690
- name
2691
- };
2692
- } catch (error) {
2693
- console.error(`Failed to parse JSON data file ${filePath}:`, error);
2694
- return null;
2695
- }
2696
- } else {
2697
- kind = "page";
2698
- site = parts[0];
2699
- collection = parts[1];
2700
- const pathParts = parts.slice(2);
2701
- const match = pathParts[pathParts.length - 1].match(/^(.+)\.(\w+)\.vxjson$/);
2702
- if (match) {
2703
- locale = match[2];
2704
- pathParts[pathParts.length - 1] = match[1];
2705
- pathname = pathParts[pathParts.length - 1] === "index" ? "/" + pathParts.slice(0, -1).join("/") || "/" : "/" + pathParts.join("/");
2706
- }
2707
- parsedData = VXJSON.parse4KB(buffer, bytesRead);
2708
- }
2709
- const needsRepair = !parsedData.id || !parsedData.created || !parsedData.modified;
2710
- const id = parsedData.id || generateContentId();
2711
- const localeVersion = {
2712
- locale,
2713
- etag: "",
2714
- created: parsedData.created || (/* @__PURE__ */ new Date()).toISOString(),
2715
- modified: parsedData.modified || (/* @__PURE__ */ new Date()).toISOString(),
2716
- ...parsedData.publishAt && { publishAt: parsedData.publishAt },
2717
- ...parsedData.unpublishAt && { unpublishAt: parsedData.unpublishAt },
2718
- ...pathname && { pathname },
2719
- ...parsedData.previousPathnames && { previousPathnames: parsedData.previousPathnames },
2720
- ...name && { name },
2721
- meta: parsedData.meta || { title: name || "Untitled" }
2722
- };
2723
- const manifest = {
2724
- id,
2725
- type: parsedData.type || (filePath.endsWith(".mdx") ? "mdx" : filePath.endsWith(".json") ? "json" : "puck"),
2726
- kind,
2727
- site,
2728
- collection,
2729
- locales: { [locale]: localeVersion }
2730
- };
2731
- let content;
2732
- if (needsRepair) {
2733
- const repairedData = await this.performReadRepair(filePath, manifest, locale);
2734
- if (repairedData) {
2735
- content = repairedData.content;
2736
- localeVersion.etag = repairedData.etag;
2737
- localeVersion.modified = repairedData.modified;
2738
- return {
2739
- manifest,
2740
- locale,
2741
- localeVersion,
2742
- bytesRead,
2743
- content
2744
- };
2745
- }
2746
- console.error(`Failed to repair ${filePath}, skipping`);
2747
- return null;
2748
- }
2749
- if (bytesRead < 4096 || filePath.endsWith(".vxjson") && buffer[bytesRead - 1] === 125 || filePath.endsWith(".json") && buffer[bytesRead - 1] === 125) {
2750
- if (filePath.endsWith(".mdx")) {
2751
- const { content: mdx } = matter(textDecoder.decode(buffer.subarray(0, bytesRead)));
2752
- content = { mdx };
2753
- } else if (filePath.endsWith(".json")) {
2754
- const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
2755
- content = { data: JSON.parse(fullContent).data };
2756
- } else {
2757
- const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
2758
- content = JSON.parse(fullContent).content || {};
2759
- }
2760
- const validBuffer = buffer.subarray(0, bytesRead);
2761
- if (filePath.endsWith(".mdx")) {
2762
- const etags = calculateEtagsFromMdxBuffer(validBuffer, parsedData.contentStartPos || -1);
2763
- localeVersion.etag = `${etags.metaEtag}.${etags.contentEtag}`;
2764
- } else if (filePath.endsWith(".json")) localeVersion.etag = VXJSON.calculateSimpleEtag(validBuffer);
2765
- else {
2766
- const etagResult = VXJSON.calculateETags(validBuffer);
2767
- if (!etagResult.success) {
2768
- const repairedData = await this.performReadRepair(filePath, manifest, locale);
2769
- if (repairedData) {
2770
- content = repairedData.content;
2771
- localeVersion.etag = repairedData.etag;
2772
- localeVersion.modified = repairedData.modified;
2773
- return {
2774
- manifest,
2775
- locale,
2776
- localeVersion,
2777
- bytesRead,
2778
- content
2779
- };
2780
- }
2781
- console.error(`Failed to repair ${filePath}, skipping`);
2782
- return null;
2783
- }
2784
- localeVersion.etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
2785
- }
2786
- }
2787
- return {
2788
- manifest,
2789
- locale,
2790
- localeVersion,
2791
- bytesRead,
2792
- content
2793
- };
2794
- } catch (error) {
2795
- console.error(`Error indexing ${originalFilePath}:`, error);
2796
- return null;
2797
- }
2798
- }
2799
- /**
2800
- * Perform read-repair by writing back the file with missing fields
2801
- * This ensures stable IDs and timestamps across restarts
2802
- */
2803
- async performReadRepair(filePath, manifest, locale) {
2804
- try {
2805
- const now = (/* @__PURE__ */ new Date()).toISOString();
2806
- let needsWrite = false;
2807
- if (manifest.type === "mdx") {
2808
- const parsed = matter(await readFile(filePath, "utf-8"));
2809
- if (!parsed.data.id) {
2810
- parsed.data.id = manifest.id;
2811
- needsWrite = true;
2812
- }
2813
- if (!parsed.data.created) {
2814
- parsed.data.created = now;
2815
- needsWrite = true;
2816
- }
2817
- if (!parsed.data.modified) {
2818
- parsed.data.modified = now;
2819
- needsWrite = true;
2820
- }
2821
- if (needsWrite) {
2822
- const updatedContent = matter.stringify(parsed.content, parsed.data);
2823
- await writeFile(filePath, updatedContent);
2824
- console.log(`Repaired MDX file: ${filePath} (added missing fields)`);
2825
- const etags = calculateEtagsFromMdxBuffer(Buffer.from(updatedContent, "utf-8"), updatedContent.indexOf("\n---\n") + 5);
2826
- const etag = `${etags.metaEtag}.${etags.contentEtag}`;
2827
- return {
2828
- content: { mdx: parsed.content },
2829
- etag,
2830
- modified: parsed.data.modified || now
2831
- };
2832
- }
2833
- } else {
2834
- const content = await readFile(filePath, "utf-8");
2835
- const data = JSON.parse(content);
2836
- if (!data.id) {
2837
- data.id = manifest.id;
2838
- needsWrite = true;
2839
- }
2840
- if (!data.created) {
2841
- data.created = now;
2842
- needsWrite = true;
2843
- }
2844
- if (!data.modified) {
2845
- data.modified = now;
2846
- needsWrite = true;
2847
- }
2848
- needsWrite = true;
2849
- if (needsWrite) {
2850
- const vxjsonData = {
2851
- id: data.id,
2852
- type: data.type,
2853
- created: data.created,
2854
- modified: data.modified,
2855
- publishAt: data.publishAt,
2856
- unpublishAt: data.unpublishAt,
2857
- previousPathnames: data.previousPathnames,
2858
- meta: data.meta || {},
2859
- content: data.content || {}
2860
- };
2861
- const repairedJson = VXJSON.serialize(vxjsonData);
2862
- await writeFile(filePath, repairedJson);
2863
- console.log(`Repaired VXJSON file: ${filePath} (fixed field order or added missing fields)`);
2864
- const repairedBuffer = Buffer.from(repairedJson, "utf-8");
2865
- const etagResult = VXJSON.calculateETags(repairedBuffer);
2866
- if (!etagResult.success) {
2867
- console.error(`Failed to calculate ETags after repair: ${filePath}`);
2868
- return null;
2869
- }
2870
- const etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
2871
- return {
2872
- content: vxjsonData.content,
2873
- etag,
2874
- modified: vxjsonData.modified
2875
- };
2876
- }
2877
- }
2878
- return null;
2879
- } catch (error) {
2880
- console.error(`Failed to perform read-repair on ${filePath}:`, error);
2881
- return null;
2882
- }
2883
- }
2884
- async scanContentFiles() {
2885
- const files = [];
2886
- const contentRoot = this.absoluteContentRoot;
2887
- async function scan(dir, inDataDir = false) {
2888
- try {
2889
- const entries = await readdir(dir, { withFileTypes: true });
2890
- for (const entry of entries) {
2891
- const fullPath = join$1(dir, entry.name);
2892
- if (entry.isDirectory()) {
2893
- const isDataDir = dir === contentRoot && entry.name === "data";
2894
- await scan(fullPath, inDataDir || isDataDir);
2895
- } else if (entry.isFile()) {
2896
- if (entry.name.endsWith(".vxjson") || entry.name.endsWith(".mdx")) files.push(fullPath);
2897
- else if (inDataDir && entry.name.endsWith(".json")) files.push(fullPath);
2898
- }
2899
- }
2900
- } catch (error) {}
2901
- }
2902
- await scan(this.absoluteContentRoot);
2903
- return files;
2904
- }
2905
- getFilePath(manifest, { locale, name, pathname }) {
2906
- if (manifest.kind === "block") {
2907
- const ext = manifest.type === "mdx" ? "mdx" : "vxjson";
2908
- return join$1(this.absoluteContentRoot, "blocks", manifest.collection, `${name}.${locale}.${ext}`);
2909
- }
2910
- if (manifest.kind === "data") return join$1(this.absoluteContentRoot, "data", manifest.collection, `${name}.${locale}.json`);
2911
- if (manifest.kind === "page" && pathname && manifest.site) {
2912
- const basePath = pathname.replace(/^\//, "").replace(/\/$/, "") || "index";
2913
- return join$1(this.absoluteContentRoot, manifest.site, manifest.collection, `${basePath}.${locale}.vxjson`);
2914
- }
2915
- throw new Error(`Invalid manifest: ${JSON.stringify(manifest, null, 2)}`);
2916
- }
2917
- /**
2918
- * Parse a file path back into its components for checking against the path index
2919
- * Returns null if the path doesn't match expected patterns
2920
- */
2921
- parseFilePath(filePath) {
2922
- const parts = filePath.replace(this.absoluteContentRoot + "/", "").split("/");
2923
- const filename = parts[parts.length - 1];
2924
- if (parts[0] === "data" && parts.length === 3) {
2925
- const dataMatch = filename.match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.json$/);
2926
- if (!dataMatch) return null;
2927
- const [, name, locale] = dataMatch;
2928
- return {
2929
- kind: "data",
2930
- collection: parts[1],
2931
- name,
2932
- locale
2933
- };
2934
- }
2935
- const match = filename.match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.(?:vxjson|mdx)$/);
2936
- if (!match) return null;
2937
- const [, nameOrPath, locale] = match;
2938
- if (parts[0] === "blocks" && parts.length === 3) return {
2939
- kind: "block",
2940
- collection: parts[1],
2941
- name: nameOrPath,
2942
- locale
2943
- };
2944
- if (parts.length >= 3 && parts[0] !== "blocks") {
2945
- const site = parts[0];
2946
- const collection = parts[1];
2947
- const pathParts = parts.slice(2, -1);
2948
- pathParts.push(nameOrPath);
2949
- return {
2950
- kind: "page",
2951
- site,
2952
- collection,
2953
- pathname: "/" + pathParts.join("/"),
2954
- locale
2955
- };
2956
- }
2957
- return null;
2958
- }
2959
- async getContent(id) {
2960
- const manifest = this.contentIndex.getManifest(id);
2961
- if (!manifest) return null;
2962
- const readPromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {
2963
- const filePath = this.getFilePath(manifest, localeVersion);
2964
- return {
2965
- localeVersion,
2966
- content: await this.readLocaleFile(filePath, localeVersion.locale)
2967
- };
2968
- });
2969
- const results = await Promise.all(readPromises);
2970
- const locales = {};
2971
- for (const { localeVersion, content } of results) if (content) locales[localeVersion.locale] = {
2972
- ...localeVersion,
2973
- etag: content.etag,
2974
- content: content.content
2975
- };
2976
- return {
2977
- id: manifest.id,
2978
- site: manifest.site,
2979
- collection: manifest.collection,
2980
- type: manifest.type,
2981
- kind: manifest.kind,
2982
- locales
2983
- };
2984
- }
2985
- async getLocalized(id, locale) {
2986
- const manifest = this.contentIndex.getManifest(id);
2987
- if (!manifest) {
2988
- await this.reindex();
2989
- const updatedManifest = this.contentIndex.getManifest(id);
2990
- if (!updatedManifest || !updatedManifest.locales[locale]) return null;
2991
- return this.getLocalized(id, locale);
2992
- }
2993
- const localeVersion = manifest.locales[locale];
2994
- if (!localeVersion) return null;
2995
- const filePath = this.getFilePath(manifest, localeVersion);
2996
- const localeData = await this.readLocaleFile(filePath, locale);
2997
- if (!localeData) return null;
2998
- return {
2999
- id: manifest.id,
3000
- site: manifest.site,
3001
- collection: manifest.collection,
3002
- type: manifest.type,
3003
- kind: manifest.kind,
3004
- localized: {
3005
- ...localeVersion,
3006
- etag: localeData.etag,
3007
- content: localeData.content
3008
- }
3009
- };
3010
- }
3011
- async readLocaleFile(filePath, locale) {
3012
- try {
3013
- const buffer = await readFile(filePath);
3014
- const content = textDecoder.decode(buffer);
3015
- if (filePath.endsWith(".mdx")) {
3016
- const { data: frontmatter } = matter(content);
3017
- const etags = calculateEtagsFromMdxBuffer(buffer, findMdxContentStartPosition(buffer));
3018
- const etag = `${etags.metaEtag}.${etags.contentEtag}`;
3019
- const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
3020
- const result = {
3021
- locale,
3022
- etag,
3023
- created,
3024
- modified,
3025
- meta: metaFields,
3026
- content: { mdx: content }
3027
- };
3028
- if (frontmatter.publishAt !== void 0) result.publishAt = frontmatter.publishAt;
3029
- if (frontmatter.unpublishAt !== void 0) result.unpublishAt = frontmatter.unpublishAt;
3030
- return result;
3031
- }
3032
- const data = JSON.parse(content);
3033
- if (data.type === "json") {
3034
- const result = {
3035
- locale,
3036
- etag: VXJSON.calculateSimpleEtag(buffer),
3037
- created: data.created,
3038
- modified: data.modified,
3039
- meta: data.meta || {},
3040
- content: { data: data.data || {} }
3041
- };
3042
- if (data.publishAt !== void 0) result.publishAt = data.publishAt;
3043
- if (data.unpublishAt !== void 0) result.unpublishAt = data.unpublishAt;
3044
- return result;
3045
- }
3046
- const etagResult = VXJSON.calculateETags(buffer);
3047
- if (!etagResult.success) {
3048
- const repairedData = {
3049
- id: data.id,
3050
- type: data.type,
3051
- created: data.created,
3052
- modified: data.modified,
3053
- publishAt: data.publishAt,
3054
- unpublishAt: data.unpublishAt,
3055
- previousPathnames: data.previousPathnames,
3056
- meta: data.meta || {},
3057
- content: data.content || {}
3058
- };
3059
- const repairedJson = VXJSON.serialize(repairedData);
3060
- await writeFile(filePath, repairedJson);
3061
- const repairedBuffer = Buffer.from(repairedJson, "utf-8");
3062
- const repairedEtagResult = VXJSON.calculateETags(repairedBuffer);
3063
- if (!repairedEtagResult.success) throw new Error(`Failed to repair VXJSON file: ${filePath}`);
3064
- const etag = repairedEtagResult.contentEtag ? `${repairedEtagResult.metaEtag}.${repairedEtagResult.contentEtag}` : repairedEtagResult.metaEtag;
3065
- console.log(`Repaired VXJSON file: ${filePath}`);
3066
- const result = {
3067
- locale,
3068
- etag,
3069
- created: data.created,
3070
- modified: data.modified,
3071
- meta: data.meta || {},
3072
- content: data.content || {}
3073
- };
3074
- if (data.publishAt !== void 0) result.publishAt = data.publishAt;
3075
- if (data.unpublishAt !== void 0) result.unpublishAt = data.unpublishAt;
3076
- if (data.previousPathnames !== void 0) result.previousPathnames = data.previousPathnames;
3077
- return result;
3078
- }
3079
- const result = {
3080
- locale,
3081
- etag: etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag,
3082
- created: data.created,
3083
- modified: data.modified,
3084
- meta: data.meta || {},
3085
- content: data.content || {}
3086
- };
3087
- if (data.publishAt !== void 0) result.publishAt = data.publishAt;
3088
- if (data.unpublishAt !== void 0) result.unpublishAt = data.unpublishAt;
3089
- if (data.previousPathnames !== void 0) result.previousPathnames = data.previousPathnames;
3090
- return result;
3091
- } catch (error) {
3092
- return null;
3093
- }
3094
- }
3095
- async createContent(data) {
3096
- const validation = validateCreateContent(data, this.sites, this.blocks, this.data);
3097
- if (!validation.valid) return {
3098
- success: false,
3099
- reason: validation.reason,
3100
- error: validation.error ? new Error(validation.error) : void 0,
3101
- existingId: validation.existingId
3102
- };
3103
- const id = generateContentId();
3104
- const now = data.created || (/* @__PURE__ */ new Date()).toISOString();
3105
- try {
3106
- const manifest = {
3107
- id,
3108
- type: data.type,
3109
- kind: data.kind,
3110
- site: data.site,
3111
- collection: data.collection,
3112
- locales: {}
3113
- };
3114
- const contentCache = {};
3115
- for (const [locale, localeData] of Object.entries(data.locales)) {
3116
- const content = localeData.content;
3117
- const title = localeData.meta?.title || data.meta?.title;
3118
- if (!title) return {
3119
- success: false,
3120
- reason: "write_error",
3121
- error: /* @__PURE__ */ new Error("Title is required in metadata")
3122
- };
3123
- const meta = {
3124
- title,
3125
- ...data.meta,
3126
- ...localeData.meta
3127
- };
3128
- const fileData = {
3129
- id,
3130
- type: data.type,
3131
- created: now,
3132
- modified: now,
3133
- publishAt: localeData.publishAt && typeof localeData.publishAt === "string" ? localeData.publishAt : void 0,
3134
- unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === "string" ? localeData.unpublishAt : void 0,
3135
- meta,
3136
- content
3137
- };
3138
- const filePath = this.getFilePath(manifest, {
3139
- locale,
3140
- name: data.name,
3141
- pathname: localeData.pathname
3142
- });
3143
- await mkdir(dirname$1(filePath), { recursive: true });
3144
- let etag;
3145
- if (data.type === "mdx") {
3146
- const mdxContent = serializeMdxWithFrontmatter({
3147
- id,
3148
- created: now,
3149
- modified: now,
3150
- ...localeData.publishAt && { publishAt: localeData.publishAt },
3151
- ...localeData.unpublishAt && { unpublishAt: localeData.unpublishAt },
3152
- ...meta
3153
- }, content.mdx || "");
3154
- await writeFile(filePath, mdxContent);
3155
- const mdxBuffer = new TextEncoder().encode(mdxContent);
3156
- const contentStartMarker = new TextEncoder().encode("---\n\n");
3157
- let contentPos = -1;
3158
- for (let i = 0; i <= mdxBuffer.length - contentStartMarker.length; i++) {
3159
- let match = true;
3160
- for (let j = 0; j < contentStartMarker.length; j++) if (mdxBuffer[i + j] !== contentStartMarker[j]) {
3161
- match = false;
3162
- break;
3163
- }
3164
- if (match) {
3165
- contentPos = i + contentStartMarker.length;
3166
- break;
3167
- }
3168
- }
3169
- const etags = calculateEtagsFromMdxBuffer(mdxBuffer, contentPos);
3170
- etag = `${etags.metaEtag}.${etags.contentEtag}`;
3171
- } else if (data.type === "json") {
3172
- const dataFileContent = {
3173
- id,
3174
- type: "json",
3175
- created: now,
3176
- modified: now,
3177
- ...localeData.publishAt && typeof localeData.publishAt === "string" && { publishAt: localeData.publishAt },
3178
- ...localeData.unpublishAt && typeof localeData.unpublishAt === "string" && { unpublishAt: localeData.unpublishAt },
3179
- meta,
3180
- data: content.data || {}
3181
- };
3182
- const jsonContent = JSON.stringify(sortKeys(dataFileContent, { deep: true }), null, " ");
3183
- await writeFile(filePath, jsonContent);
3184
- const jsonBuffer = new TextEncoder().encode(jsonContent);
3185
- etag = VXJSON.calculateSimpleEtag(jsonBuffer);
3186
- } else {
3187
- const jsonContent = VXJSON.serialize(fileData);
3188
- const jsonBuffer = new TextEncoder().encode(jsonContent);
3189
- const etagResult = VXJSON.calculateETags(jsonBuffer);
3190
- if (!etagResult.success) throw new Error(`Invalid VXJSON format when creating content: ${etagResult.error}`);
3191
- etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
3192
- await writeFile(filePath, jsonContent);
3193
- }
3194
- const localeVersion = buildLocaleVersion({
3195
- locale,
3196
- etag,
3197
- created: now,
3198
- modified: now,
3199
- meta,
3200
- kind: data.kind,
3201
- pathname: data.kind === "page" ? localeData.pathname : void 0,
3202
- name: data.kind === "block" || data.kind === "data" ? data.name : void 0,
3203
- publishAt: localeData.publishAt && typeof localeData.publishAt === "string" ? localeData.publishAt : void 0,
3204
- unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === "string" ? localeData.unpublishAt : void 0
3205
- });
3206
- manifest.locales[locale] = localeVersion;
3207
- contentCache[locale] = content;
3208
- }
3209
- for (const localeVersion of localesOf(manifest)) {
3210
- const { locale } = localeVersion;
3211
- this.contentIndex.addContent(manifest, localeVersion, contentCache[locale]);
3212
- }
3213
- return {
3214
- success: true,
3215
- id
3216
- };
3217
- } catch (error) {
3218
- return {
3219
- success: false,
3220
- reason: "write_error",
3221
- error: ensureError(error)
3222
- };
3223
- }
3224
- }
3225
- async updateLocalized(input) {
3226
- const { id, locale, data, etag } = input;
3227
- const manifest = this.contentIndex.getManifest(id);
3228
- if (!manifest) return {
3229
- success: false,
3230
- reason: "not_found"
3231
- };
3232
- const localeVersion = manifest.locales[locale];
3233
- if (!localeVersion) return {
3234
- success: false,
3235
- reason: "not_found"
3236
- };
3237
- const filePath = this.getFilePath(manifest, localeVersion);
3238
- const current = await this.readLocaleFile(filePath, locale);
3239
- if (!current) return {
3240
- success: false,
3241
- reason: "not_found"
3242
- };
3243
- const currentEtag = current.etag;
3244
- if (manifest.kind === "data") {
3245
- if (etag !== currentEtag) return {
3246
- success: false,
3247
- reason: "stale_write",
3248
- currentEtag
3249
- };
3250
- } else {
3251
- const etagParts = parseDualEtag(etag);
3252
- const currentParts = parseDualEtag(currentEtag);
3253
- if (!etagParts || !currentParts) return {
3254
- success: false,
3255
- reason: "stale_write",
3256
- currentEtag
3257
- };
3258
- const updateScope = analyzeUpdateScope(data);
3259
- const updatingMeta = (updateScope & UPDATE_SCOPE.META) !== 0;
3260
- const updatingContent = (updateScope & UPDATE_SCOPE.CONTENT) !== 0;
3261
- if (updatingMeta && etagParts.meta !== currentParts.meta) return {
3262
- success: false,
3263
- reason: "stale_write",
3264
- currentEtag
3265
- };
3266
- if (updatingContent && etagParts.content !== currentParts.content) return {
3267
- success: false,
3268
- reason: "stale_write",
3269
- currentEtag
3270
- };
3271
- }
3272
- let modified;
3273
- if (shouldUpdateModifiedTimestamp(data)) modified = data.modified || (/* @__PURE__ */ new Date()).toISOString();
3274
- else if (data.modified) modified = data.modified;
3275
- else modified = current.modified;
3276
- const { sortedMeta: newMeta, valid: metaValid, error: metaError } = validateAndPrepareMetadata({
3277
- ...current.meta,
3278
- ...data.meta ? data.meta : {}
3279
- });
3280
- if (!newMeta || !metaValid) return {
3281
- success: false,
3282
- reason: "write_error",
3283
- error: new Error(metaError)
3284
- };
3285
- const newContent = data.content ? {
3286
- ...current.content,
3287
- ...data.content
3288
- } : current.content;
3289
- if (data.pathname && manifest.kind === "page" && manifest.site) {
3290
- const site = this.sites[manifest.site];
3291
- if (site) {
3292
- const existingId = site.getPathnameConflict(data.pathname, locale, id);
3293
- if (existingId) return {
3294
- success: false,
3295
- reason: "write_error",
3296
- error: /* @__PURE__ */ new Error(`Pathname ${data.pathname} is already taken by content ${existingId}`)
3297
- };
3298
- }
3299
- }
3300
- if (data.name && (manifest.kind === "block" || manifest.kind === "data")) {
3301
- const existing = (manifest.kind === "block" ? this.contentIndex.getBlockIndex() : this.contentIndex.getDataIndex()).getByName(manifest.collection, data.name);
3302
- if (existing && existing.id !== id) {
3303
- const existingTitle = Object.values(existing.locales).find((lv) => lv !== void 0)?.meta?.title;
3304
- const kindLabel = manifest.kind === "block" ? "Block" : "Data";
3305
- return {
3306
- success: false,
3307
- reason: "write_error",
3308
- error: /* @__PURE__ */ new Error(`${kindLabel} name "${data.name}" is already in use${existingTitle ? ` by "${existingTitle}"` : ""}`)
3309
- };
3310
- }
3311
- }
3312
- const pathnameHistory = buildPathnameHistory(localeVersion.pathname, data.pathname, isContentPublished({
3313
- publishAt: resolvePublishDate(data.publishAt, current.publishAt),
3314
- unpublishAt: resolvePublishDate(data.unpublishAt, current.unpublishAt)
3315
- }), (/* @__PURE__ */ new Date()).toISOString());
3316
- try {
3317
- let targetFilePath = filePath;
3318
- if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname && manifest.site) {
3319
- const newLocaleVersion = {
3320
- ...localeVersion,
3321
- pathname: data.pathname
3322
- };
3323
- targetFilePath = this.getFilePath(manifest, newLocaleVersion);
3324
- await mkdir(dirname$1(targetFilePath), { recursive: true });
3325
- } else if (data.name && localeVersion.name && data.name !== localeVersion.name && manifest.kind === "block") {
3326
- const newLocaleVersion = {
3327
- ...localeVersion,
3328
- name: data.name
3329
- };
3330
- targetFilePath = this.getFilePath(manifest, newLocaleVersion);
3331
- await mkdir(dirname$1(targetFilePath), { recursive: true });
3332
- }
3333
- if (targetFilePath.endsWith(".mdx")) {
3334
- const publishAt = resolvePublishDate(data.publishAt, current.publishAt);
3335
- const unpublishAt = resolvePublishDate(data.unpublishAt, current.unpublishAt);
3336
- const frontmatterData = {
3337
- id: manifest.id,
3338
- created: current.created,
3339
- modified,
3340
- ...publishAt && { publishAt },
3341
- ...unpublishAt && { unpublishAt },
3342
- ...newMeta
3343
- };
3344
- let mdxContentPart = newContent.mdx || "";
3345
- if (mdxContentPart.startsWith("---")) {
3346
- const { content: contentOnly } = matter(mdxContentPart);
3347
- mdxContentPart = contentOnly;
3348
- }
3349
- const mdxContent = serializeMdxWithFrontmatter(frontmatterData, mdxContentPart);
3350
- const hrtime = process.hrtime.bigint();
3351
- const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;
3352
- try {
3353
- await writeFile(tempFile, mdxContent);
3354
- await rename(tempFile, targetFilePath);
3355
- } catch (error) {
3356
- try {
3357
- await unlink(tempFile);
3358
- } catch {}
3359
- throw error;
3360
- }
3361
- } else if (targetFilePath.endsWith(".json")) {
3362
- const fileContent = JSON.parse(await readFile(filePath, "utf-8"));
3363
- const updatedFile = {
3364
- id: fileContent.id,
3365
- type: "json",
3366
- created: fileContent.created,
3367
- modified,
3368
- ...fileContent.publishAt && { publishAt: fileContent.publishAt },
3369
- ...fileContent.unpublishAt && { unpublishAt: fileContent.unpublishAt },
3370
- meta: newMeta,
3371
- data: sortKeys(newContent.data || {}, { deep: true })
3372
- };
3373
- if ("publishAt" in data) if (data.publishAt) updatedFile.publishAt = data.publishAt;
3374
- else delete updatedFile.publishAt;
3375
- if ("unpublishAt" in data) if (data.unpublishAt) updatedFile.unpublishAt = data.unpublishAt;
3376
- else delete updatedFile.unpublishAt;
3377
- const serializedContent = JSON.stringify(sortKeys(updatedFile, { deep: true }), null, " ");
3378
- const hrtime = process.hrtime.bigint();
3379
- const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;
3380
- try {
3381
- await writeFile(tempFile, serializedContent);
3382
- await rename(tempFile, targetFilePath);
3383
- } catch (error) {
3384
- try {
3385
- await unlink(tempFile);
3386
- } catch {}
3387
- throw error;
3388
- }
3389
- } else {
3390
- const fileContent = JSON.parse(await readFile(filePath, "utf-8"));
3391
- const updatedFile = {
3392
- id: fileContent.id,
3393
- type: fileContent.type,
3394
- created: fileContent.created,
3395
- modified,
3396
- publishAt: fileContent.publishAt,
3397
- unpublishAt: fileContent.unpublishAt,
3398
- previousPathnames: fileContent.previousPathnames,
3399
- meta: newMeta,
3400
- content: sortKeys(newContent, { deep: true })
3401
- };
3402
- if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname) {
3403
- if (isContentPublished(current)) {
3404
- if (!updatedFile.previousPathnames) updatedFile.previousPathnames = {};
3405
- updatedFile.previousPathnames[localeVersion.pathname] = modified;
3406
- }
3407
- }
3408
- if ("publishAt" in data) if (data.publishAt) updatedFile.publishAt = data.publishAt;
3409
- else delete updatedFile.publishAt;
3410
- if ("unpublishAt" in data) if (data.unpublishAt) updatedFile.unpublishAt = data.unpublishAt;
3411
- else delete updatedFile.unpublishAt;
3412
- const serializedContent = VXJSON.serialize(updatedFile);
3413
- const hrtime = process.hrtime.bigint();
3414
- const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;
3415
- try {
3416
- await writeFile(tempFile, serializedContent);
3417
- await rename(tempFile, targetFilePath);
3418
- } catch (error) {
3419
- try {
3420
- await unlink(tempFile);
3421
- } catch {}
3422
- throw error;
3423
- }
3424
- }
3425
- const writtenBuffer = await readFile(targetFilePath);
3426
- let newEtag;
3427
- if (targetFilePath.endsWith(".mdx")) {
3428
- const contentStartMarker = new TextEncoder().encode("---\n\n");
3429
- let contentPos = -1;
3430
- for (let i = 0; i <= writtenBuffer.length - contentStartMarker.length; i++) {
3431
- let match = true;
3432
- for (let j = 0; j < contentStartMarker.length; j++) if (writtenBuffer[i + j] !== contentStartMarker[j]) {
3433
- match = false;
3434
- break;
3435
- }
3436
- if (match) {
3437
- contentPos = i + contentStartMarker.length;
3438
- break;
3439
- }
3440
- }
3441
- const etags = calculateEtagsFromMdxBuffer(writtenBuffer, contentPos);
3442
- newEtag = `${etags.metaEtag}.${etags.contentEtag}`;
3443
- } else if (targetFilePath.endsWith(".json")) newEtag = VXJSON.calculateSimpleEtag(writtenBuffer);
3444
- else {
3445
- const etagResult = VXJSON.calculateETags(writtenBuffer);
3446
- if (!etagResult.success) throw new Error(`Invalid VXJSON format when updating content: ${etagResult.error}`);
3447
- newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
3448
- }
3449
- const updatedLocaleVersion = {
3450
- ...localeVersion,
3451
- etag: newEtag,
3452
- modified,
3453
- meta: newMeta,
3454
- ...data.pathname && { pathname: data.pathname },
3455
- ...data.name && { name: data.name }
3456
- };
3457
- if (current.publishAt && !("publishAt" in data)) updatedLocaleVersion.publishAt = current.publishAt;
3458
- if (current.unpublishAt && !("unpublishAt" in data)) updatedLocaleVersion.unpublishAt = current.unpublishAt;
3459
- updatePublishDates(updatedLocaleVersion, data);
3460
- if (Object.keys(pathnameHistory).length > 0) updatedLocaleVersion.previousPathnames = {
3461
- ...localeVersion.previousPathnames,
3462
- ...pathnameHistory
3463
- };
3464
- else {
3465
- const existingPreviousPathnames = localeVersion.previousPathnames;
3466
- if (existingPreviousPathnames && Object.keys(existingPreviousPathnames).length > 0) updatedLocaleVersion.previousPathnames = existingPreviousPathnames;
3467
- else delete updatedLocaleVersion.previousPathnames;
3468
- }
3469
- const oldLocaleVersion = manifest.locales[locale];
3470
- try {
3471
- manifest.locales[locale] = updatedLocaleVersion;
3472
- this.contentIndex.addContent(manifest, updatedLocaleVersion, newContent);
3473
- if (targetFilePath !== filePath) try {
3474
- await unlink(filePath);
3475
- } catch (error) {
3476
- console.warn(`Failed to delete old file ${filePath}:`, error);
3477
- }
3478
- } catch (error) {
3479
- manifest.locales[locale] = oldLocaleVersion;
3480
- if (targetFilePath !== filePath) try {
3481
- await unlink(targetFilePath);
3482
- } catch {}
3483
- throw error;
1114
+ required: false
1115
+ };
1116
+ const token = extractCFAccessToken(request);
1117
+ if (!token) return {
1118
+ valid: false,
1119
+ required: true,
1120
+ error: "No token provided"
1121
+ };
1122
+ try {
1123
+ const { payload } = await jwtVerify(token, JWKS, {
1124
+ issuer: `https://${CF_ACCESS_TEAM_NAME}.cloudflareaccess.com`,
1125
+ audience: CF_ACCESS_AUD
1126
+ });
1127
+ return {
1128
+ valid: true,
1129
+ required: true,
1130
+ user: {
1131
+ email: typeof payload.email === "string" && payload.email ? payload.email : void 0,
1132
+ sub: typeof payload.sub === "string" && payload.sub ? payload.sub : void 0
3484
1133
  }
3485
- return {
3486
- success: true,
3487
- etag: newEtag,
3488
- modified: /* @__PURE__ */ new Date()
3489
- };
3490
- } catch (error) {
3491
- return {
3492
- success: false,
3493
- reason: "write_error",
3494
- error: ensureError(error)
3495
- };
3496
- }
3497
- }
3498
- async deleteContent(id, etag) {
3499
- const manifest = this.contentIndex.getManifest(id);
3500
- if (!manifest) return {
3501
- success: false,
3502
- reason: "not_found",
3503
- error: /* @__PURE__ */ new Error("Content not found")
3504
1134
  };
3505
- let matchingLocale;
3506
- for (const localeVersion of localesOf(manifest)) if (localeVersion.etag === etag) {
3507
- matchingLocale = localeVersion;
3508
- break;
3509
- }
3510
- if (!matchingLocale) return {
3511
- success: false,
3512
- reason: "stale_write",
3513
- currentEtag: Array.from(localesOf(manifest))[0]?.etag || "",
3514
- error: /* @__PURE__ */ new Error("Invalid etag - must match at least one locale")
1135
+ } catch (error) {
1136
+ return {
1137
+ valid: false,
1138
+ required: true,
1139
+ error: error instanceof Error ? error.message : "Validation failed"
3515
1140
  };
3516
- try {
3517
- const deletePromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {
3518
- await unlink(this.getFilePath(manifest, localeVersion));
3519
- });
3520
- await Promise.all(deletePromises);
3521
- this.contentIndex.removeEntry(id);
3522
- return { success: true };
3523
- } catch (error) {
3524
- return {
3525
- success: false,
3526
- error: ensureError(error)
3527
- };
3528
- }
3529
1141
  }
3530
- async deleteLocalized(input) {
3531
- const { id, locale, etag } = input;
3532
- const manifest = this.contentIndex.getManifest(id);
3533
- if (!manifest) return {
3534
- success: false,
3535
- reason: "not_found",
3536
- error: /* @__PURE__ */ new Error("Content not found")
3537
- };
3538
- const localeVersion = manifest.locales[locale];
3539
- if (!localeVersion) return {
3540
- success: false,
3541
- reason: "not_found",
3542
- error: /* @__PURE__ */ new Error("Locale not found")
3543
- };
3544
- if (localeVersion.etag !== etag) return {
3545
- success: false,
3546
- reason: "stale_write",
3547
- currentEtag: localeVersion.etag,
3548
- error: /* @__PURE__ */ new Error("Invalid etag for locale")
3549
- };
3550
- if (Object.keys(manifest.locales).length === 1) return {
3551
- success: false,
3552
- error: /* @__PURE__ */ new Error("Cannot delete the last locale. Use deleteContent to delete all content.")
3553
- };
1142
+ }
1143
+
1144
+ //#endregion
1145
+ //#region src/component-registry.ts
1146
+ /**
1147
+ * Component Registry for managing linked and unlinked components
1148
+ *
1149
+ * Registry is stored at {canvasDir}/components/registry.json
1150
+ * Component IDs must follow the format: vx-{uuid}
1151
+ */
1152
+ var ComponentRegistry = class {
1153
+ registryPath;
1154
+ registry = {};
1155
+ initialized = false;
1156
+ constructor(canvasDir) {
1157
+ this.registryPath = join(canvasDir, "components", "registry.json");
1158
+ }
1159
+ /**
1160
+ * Initialize the registry by loading from disk or creating new
1161
+ */
1162
+ async initialize() {
1163
+ if (this.initialized) return;
3554
1164
  try {
3555
- await unlink(this.getFilePath(manifest, localeVersion));
3556
- manifest.locales[locale] = void 0;
3557
- this.contentIndex.removeLocale(manifest.id, locale);
3558
- return { success: true };
1165
+ const content = await readFile(this.registryPath, "utf-8");
1166
+ this.registry = JSON.parse(content);
3559
1167
  } catch (error) {
3560
- return {
3561
- success: false,
3562
- error: ensureError(error)
3563
- };
1168
+ if (error.code === "ENOENT") await this.save();
1169
+ else throw error;
3564
1170
  }
1171
+ this.initialized = true;
3565
1172
  }
3566
- getSite(siteName) {
3567
- if (siteName === "blocks") throw new Error("Use `blocks` property instead of getSite(\"blocks\")");
3568
- return this.sites[siteName] || null;
3569
- }
3570
- *listAllContent(filters) {
3571
- yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);
1173
+ /**
1174
+ * Validate component ID format (vx-{uuid})
1175
+ */
1176
+ validateComponentId(id) {
1177
+ 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}");
3572
1178
  }
3573
- *findUntranslatedContent(targetLocale, options) {
3574
- yield* this.contentIndex.findUntranslatedContent(targetLocale, options);
1179
+ /**
1180
+ * Save registry to disk atomically
1181
+ */
1182
+ async save() {
1183
+ await mkdir(dirname(this.registryPath), { recursive: true });
1184
+ const sorted = sortKeys(this.registry, { deep: true });
1185
+ const content = JSON.stringify(sorted, null, 2);
1186
+ await atomicWriteFile(this.registryPath, content);
3575
1187
  }
3576
1188
  /**
3577
- * Reindex files that were added or changed after initial creation
3578
- *
3579
- * This method:
3580
- * 1. Either scans for all content files or processes specific paths
3581
- * 2. Uses the path index to check if files are already indexed
3582
- * 3. Indexes new files or force-reindexes specified files
3583
- * 4. Optionally handles file deletions
3584
- *
3585
- * @param paths - Optional array of specific file paths to reindex. If not provided, scans all content files.
3586
- * @param options - Options for reindexing behavior
3587
- * @returns Statistics about the reindexing operation
1189
+ * Register a new component or update existing
3588
1190
  */
3589
- async reindex(paths, options) {
3590
- const filesToProcess = paths || await this.scanContentFiles();
3591
- let filesSkipped = 0;
3592
- let filesProcessed = 0;
3593
- let filesDeleted = 0;
3594
- let errors = 0;
3595
- const filesToIndex = [];
3596
- const updated = [];
3597
- const deleted = [];
3598
- for (const filePath of filesToProcess) {
3599
- if (options?.handleDeletions && paths) try {
3600
- await readFile(filePath);
3601
- } catch (error) {
3602
- const parsed = this.parseFilePath(filePath);
3603
- if (parsed) {
3604
- let manifest = null;
3605
- if (parsed.kind === "block" && parsed.name) manifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
3606
- else if (parsed.kind === "data" && parsed.name) manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
3607
- else if (parsed.kind === "page" && parsed.site && parsed.pathname) manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
3608
- if (manifest) {
3609
- deleted.push({
3610
- id: manifest.id,
3611
- locale: parsed.locale,
3612
- kind: parsed.kind
3613
- });
3614
- if (Object.keys(manifest.locales).length === 1) this.contentIndex.removeEntry(manifest.id);
3615
- else {
3616
- manifest.locales[parsed.locale] = void 0;
3617
- this.contentIndex.removeLocale(manifest.id, parsed.locale);
3618
- }
3619
- filesDeleted++;
3620
- }
3621
- }
3622
- continue;
3623
- }
3624
- const parsed = this.parseFilePath(filePath);
3625
- if (!parsed) {
3626
- console.warn(`Skipping unrecognized file pattern: ${filePath}`);
3627
- errors++;
3628
- continue;
3629
- }
3630
- let isIndexed = false;
3631
- if (parsed.kind === "block" && parsed.name) isIndexed = !!this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
3632
- else if (parsed.kind === "page" && parsed.site && parsed.pathname) isIndexed = !!this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
3633
- else if (parsed.kind === "data" && parsed.name) isIndexed = !!this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
3634
- if (isIndexed) if (!paths) filesSkipped++;
3635
- else {
3636
- const fileStats = await readFile(filePath);
3637
- let currentManifest = null;
3638
- if (parsed.kind === "block" && parsed.name) currentManifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
3639
- else if (parsed.kind === "data" && parsed.name) currentManifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
3640
- else if (parsed.kind === "page" && parsed.site && parsed.pathname) currentManifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
3641
- if (currentManifest) {
3642
- const buffer = fileStats;
3643
- let currentEtag;
3644
- if (filePath.endsWith(".mdx")) {
3645
- const etags = calculateEtagsFromMdxBuffer(buffer, findMdxContentStartPosition(buffer));
3646
- currentEtag = `${etags.metaEtag}.${etags.contentEtag}`;
3647
- } else if (filePath.endsWith(".vxjson")) {
3648
- const etagResult = VXJSON.calculateETags(buffer);
3649
- if (!etagResult.success) {
3650
- filesToIndex.push(filePath);
3651
- continue;
3652
- }
3653
- currentEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
3654
- } else if (filePath.endsWith(".json")) currentEtag = xxh3.xxh64(buffer).toString(16);
3655
- else {
3656
- filesSkipped++;
3657
- continue;
3658
- }
3659
- if (currentManifest.locales[parsed.locale]?.etag === currentEtag) {
3660
- const relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
3661
- console.log(`[Content] skip ${relativePath} (unchanged)`);
3662
- filesSkipped++;
3663
- } else filesToIndex.push(filePath);
3664
- } else filesToIndex.push(filePath);
3665
- }
3666
- else filesToIndex.push(filePath);
3667
- }
3668
- const buffers = Array.from({ length: Math.min(filesToIndex.length, 100) }, () => new Uint8Array(4096));
3669
- for (let i = 0; i < filesToIndex.length; i++) {
3670
- const filePath = filesToIndex[i];
3671
- const bufferIndex = i % buffers.length;
3672
- try {
3673
- const result = await this.parseFileHeaderWithRepair(filePath, buffers[bufferIndex]);
3674
- if (result) {
3675
- const { manifest, localeVersion, content } = result;
3676
- this.contentIndex.addContent(manifest, localeVersion, content);
3677
- filesProcessed++;
3678
- const localizedManifest = {
3679
- id: manifest.id,
3680
- type: manifest.type,
3681
- kind: manifest.kind,
3682
- site: manifest.site,
3683
- collection: manifest.collection,
3684
- localized: localeVersion
3685
- };
3686
- updated.push(localizedManifest);
3687
- }
3688
- } catch (error) {
3689
- console.error(`Failed to reindex ${filePath}:`, error);
3690
- errors++;
3691
- }
3692
- }
3693
- const result = {
3694
- filesProcessed,
3695
- filesSkipped,
3696
- updated
1191
+ async register(id, entry) {
1192
+ await this.initialize();
1193
+ this.validateComponentId(id);
1194
+ this.registry[id] = {
1195
+ displayName: entry.displayName,
1196
+ path: entry.path
3697
1197
  };
3698
- if (options?.handleDeletions && deleted.length > 0) {
3699
- result.filesDeleted = filesDeleted;
3700
- result.deleted = deleted;
3701
- }
3702
- if (errors > 0) result.errors = errors;
3703
- return result;
1198
+ await this.save();
3704
1199
  }
3705
1200
  /**
3706
- * Read content directly from cache
3707
- * For testing purposes - returns null if not cached
1201
+ * Get a component entry by ID
3708
1202
  */
3709
- async readFromCache(id, locale) {
3710
- return this.contentIndex.getCachedContent(id, locale);
1203
+ async get(id) {
1204
+ await this.initialize();
1205
+ return this.registry[id] || null;
3711
1206
  }
3712
- async getContentAsBuffer(id, locale) {
3713
- const manifest = this.contentIndex.getManifest(id);
3714
- if (!manifest || !manifest.locales[locale]) return null;
3715
- const localeVersion = manifest.locales[locale];
3716
- const filePath = this.getFilePath(manifest, localeVersion);
3717
- const buffer = await readFile(filePath);
3718
- const contentType = filePath.endsWith(".mdx") ? "text/mdx" : "application/json";
3719
- let etag;
3720
- if (contentType === "text/mdx") {
3721
- const contentStartMarker = new TextEncoder().encode("---\n\n");
3722
- let contentPos = -1;
3723
- for (let i = 0; i <= buffer.length - contentStartMarker.length; i++) {
3724
- let match = true;
3725
- for (let j = 0; j < contentStartMarker.length; j++) if (buffer[i + j] !== contentStartMarker[j]) {
3726
- match = false;
3727
- break;
3728
- }
3729
- if (match) {
3730
- contentPos = i + contentStartMarker.length;
3731
- break;
3732
- }
3733
- }
3734
- const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
3735
- etag = `${etags.metaEtag}.${etags.contentEtag}`;
3736
- } else {
3737
- const etagResult = VXJSON.calculateETags(buffer);
3738
- if (!etagResult.success) throw new Error(`Invalid VXJSON format in getContentAsBuffer: ${etagResult.error}`);
3739
- etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
3740
- }
3741
- return {
3742
- buffer,
3743
- etag,
3744
- contentType
3745
- };
1207
+ /**
1208
+ * Link a component to a path
1209
+ */
1210
+ async link(id, path) {
1211
+ await this.initialize();
1212
+ const entry = this.registry[id];
1213
+ if (!entry) throw new Error(`Component ${id} not found in registry`);
1214
+ entry.path = path;
1215
+ await this.save();
3746
1216
  }
3747
- async batchUpdate(operations) {
3748
- const validationResults = [];
3749
- for (const op of operations) {
3750
- const manifest = this.contentIndex.getManifest(op.id);
3751
- if (!manifest) return {
3752
- operations: operations.map((o) => ({
3753
- id: o.id,
3754
- locale: o.locale,
3755
- updated: false,
3756
- error: /* @__PURE__ */ new Error("Content not found")
3757
- })),
3758
- success: false,
3759
- updated: 0,
3760
- failed: operations.length
3761
- };
3762
- const localeVersion = manifest.locales[op.locale];
3763
- if (!localeVersion) return {
3764
- operations: operations.map((o) => ({
3765
- id: o.id,
3766
- locale: o.locale,
3767
- updated: false,
3768
- error: /* @__PURE__ */ new Error("Locale not found")
3769
- })),
3770
- success: false,
3771
- updated: 0,
3772
- failed: operations.length
3773
- };
3774
- if (localeVersion.etag !== op.etag) return {
3775
- operations: operations.map((o) => ({
3776
- id: o.id,
3777
- locale: o.locale,
3778
- updated: false,
3779
- error: /* @__PURE__ */ new Error("Stale write")
3780
- })),
3781
- success: false,
3782
- updated: 0,
3783
- failed: operations.length
3784
- };
3785
- const filePath = this.getFilePath(manifest, localeVersion);
3786
- const current = await this.readLocaleFile(filePath, op.locale);
3787
- if (!current) return {
3788
- operations: operations.map((o) => ({
3789
- id: o.id,
3790
- locale: o.locale,
3791
- updated: false,
3792
- error: /* @__PURE__ */ new Error("Failed to read content")
3793
- })),
3794
- success: false,
3795
- updated: 0,
3796
- failed: operations.length
3797
- };
3798
- if (op.data.meta) {
3799
- const validation = validateAndPrepareMetadata({
3800
- ...current.meta,
3801
- ...op.data.meta
3802
- });
3803
- if (!validation.valid) return {
3804
- operations: operations.map((o) => ({
3805
- id: o.id,
3806
- locale: o.locale,
3807
- updated: false,
3808
- error: new Error(validation.error)
3809
- })),
3810
- success: false,
3811
- updated: 0,
3812
- failed: operations.length
3813
- };
3814
- }
3815
- validationResults.push({
3816
- op,
3817
- manifest,
3818
- localeVersion,
3819
- current
3820
- });
3821
- }
3822
- const results = [];
3823
- let updated = 0;
3824
- for (const { op } of validationResults) {
3825
- const result = await this.updateLocalized(op);
3826
- if (result.success) {
3827
- updated++;
3828
- results.push({
3829
- id: op.id,
3830
- locale: op.locale,
3831
- updated: true,
3832
- etag: result.etag
3833
- });
3834
- } else results.push({
3835
- id: op.id,
3836
- locale: op.locale,
3837
- updated: false,
3838
- error: result.error
3839
- });
3840
- }
3841
- return {
3842
- operations: results,
3843
- success: updated === operations.length,
3844
- updated,
3845
- failed: operations.length - updated
3846
- };
1217
+ /**
1218
+ * Unlink a component (set path to null)
1219
+ */
1220
+ async unlink(id) {
1221
+ await this.initialize();
1222
+ const entry = this.registry[id];
1223
+ if (!entry) throw new Error(`Component ${id} not found in registry`);
1224
+ entry.path = null;
1225
+ await this.save();
1226
+ }
1227
+ /**
1228
+ * List all components
1229
+ */
1230
+ async list() {
1231
+ await this.initialize();
1232
+ return Object.entries(this.registry).map(([id, entry]) => ({
1233
+ id,
1234
+ ...entry
1235
+ }));
1236
+ }
1237
+ /**
1238
+ * Delete a component from registry
1239
+ */
1240
+ async delete(id) {
1241
+ await this.initialize();
1242
+ delete this.registry[id];
1243
+ await this.save();
3847
1244
  }
3848
1245
  };
3849
1246
 
@@ -3861,13 +1258,13 @@ async function createContentAPI(options) {
3861
1258
  /**
3862
1259
  * Creates file change handlers for content watching
3863
1260
  */
3864
- function createContentWatchHandlers(contentApi, options, ws) {
1261
+ function createContentWatchHandlers(contentApi, options, ws, onReindexed) {
3865
1262
  const handleFileChange = async (file, action) => {
3866
1263
  const isContentFile = file.endsWith(".mdx") || file.endsWith(".vxjson");
3867
1264
  const isDataFile = file.endsWith(".json") && file.includes("/data/");
3868
1265
  if (!isContentFile && !isDataFile) return;
3869
- const normalizedFile = normalize(resolve$1(file));
3870
- const normalizedRoot = normalize(resolve$1(options.contentRoot));
1266
+ const normalizedFile = normalize(resolve(file));
1267
+ const normalizedRoot = normalize(resolve(options.contentRoot));
3871
1268
  if (normalizedFile.startsWith(normalizedRoot)) {
3872
1269
  const relativePath = normalizedFile.replace(normalizedRoot + "/", "");
3873
1270
  console.log(`[Content] ${action}: ${relativePath}`);
@@ -3897,6 +1294,14 @@ function createContentWatchHandlers(contentApi, options, ws) {
3897
1294
  console.error("[Content Watcher] Reindex failed:", error);
3898
1295
  return;
3899
1296
  }
1297
+ try {
1298
+ await onReindexed?.({
1299
+ file: normalizedFile,
1300
+ action
1301
+ });
1302
+ } catch (error) {
1303
+ console.error("[Content Watcher] onReindexed callback failed:", error);
1304
+ }
3900
1305
  }
3901
1306
  };
3902
1307
  return {
@@ -4374,6 +1779,34 @@ var InMemoryContentAPI = class {
4374
1779
  }
4375
1780
  };
4376
1781
 
1782
+ //#endregion
1783
+ //#region src/mdx/compile.ts
1784
+ async function compileMDX(content) {
1785
+ try {
1786
+ const { data: metadata } = matter(content);
1787
+ const compiled = await compile(content, {
1788
+ outputFormat: "function-body",
1789
+ development: process.env.NODE_ENV === "development",
1790
+ remarkPlugins: [
1791
+ remarkFrontmatter,
1792
+ remarkMdxFrontmatter,
1793
+ remarkGfm
1794
+ ]
1795
+ });
1796
+ return {
1797
+ code: String(compiled.value),
1798
+ metadata
1799
+ };
1800
+ } catch (error) {
1801
+ if (error instanceof Error) {
1802
+ const enhancedError = /* @__PURE__ */ new Error(`MDX compilation failed: ${error.message}`);
1803
+ enhancedError.stack = error.stack;
1804
+ throw enhancedError;
1805
+ }
1806
+ throw error;
1807
+ }
1808
+ }
1809
+
4377
1810
  //#endregion
4378
1811
  //#region src/middleware.ts
4379
1812
  /**
@@ -4393,6 +1826,9 @@ function logAndCreateErrorResponse(error, code, message, details) {
4393
1826
  console.error(`[Content API] ${message}:`, error);
4394
1827
  return errorResponse(code, message, details);
4395
1828
  }
1829
+ function errorMessage(error, fallback) {
1830
+ return error instanceof Error ? error.message : fallback;
1831
+ }
4396
1832
  function createContentAPIRouter(api, options) {
4397
1833
  const app = new Hono();
4398
1834
  app.use("/*", cors());
@@ -5089,6 +2525,25 @@ function createContentAPIRouter(api, options) {
5089
2525
  return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PULL_FAILED, "Failed to pull from origin"), 500);
5090
2526
  }
5091
2527
  });
2528
+ app.post("/mdx/compile", async (c) => {
2529
+ try {
2530
+ let body;
2531
+ try {
2532
+ body = await c.req.json();
2533
+ } catch {
2534
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "Invalid JSON body"), 400);
2535
+ }
2536
+ const mdxContent = typeof body === "object" && body !== null ? body.mdxContent : null;
2537
+ if (!mdxContent || typeof mdxContent !== "string") return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "mdxContent string required", { field: "mdxContent" }), 400);
2538
+ const { code, metadata } = await compileMDX(mdxContent);
2539
+ return c.json({
2540
+ code,
2541
+ metadata
2542
+ });
2543
+ } catch (error) {
2544
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.MDX_COMPILE_FAILED, errorMessage(error, "Failed to compile MDX")), 422);
2545
+ }
2546
+ });
5092
2547
  return app;
5093
2548
  }
5094
2549
  /**
@@ -5159,5 +2614,5 @@ function conlocaContent(options) {
5159
2614
  }
5160
2615
 
5161
2616
  //#endregion
5162
- 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 };
2617
+ export { AssetManifest, AssetOperations, Blocks, ComponentRegistry, ErrorCodes, FileSystemContentAPI, InMemoryContentAPI, Site, UPDATE_SCOPE, analyzeUpdateScope, buildLocaleVersion, buildPathnameHistory, compileMDX, 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 };
5163
2618
  //# sourceMappingURL=node.mjs.map