@conloca/content-api 0.1.16 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. package/dist/asset-constraints.d.ts +16 -0
  2. package/dist/asset-constraints.d.ts.map +1 -0
  3. package/dist/asset-constraints.js +29 -0
  4. package/dist/asset-constraints.js.map +1 -0
  5. package/dist/asset-metadata-store.d.ts +60 -0
  6. package/dist/asset-metadata-store.d.ts.map +1 -0
  7. package/dist/asset-metadata-store.js +335 -0
  8. package/dist/asset-metadata-store.js.map +1 -0
  9. package/dist/asset-operations.d.ts +21 -28
  10. package/dist/asset-operations.d.ts.map +1 -1
  11. package/dist/asset-operations.js +268 -305
  12. package/dist/asset-operations.js.map +1 -0
  13. package/dist/asset-types.d.ts +23 -7
  14. package/dist/asset-types.d.ts.map +1 -1
  15. package/dist/asset-types.js +8 -2
  16. package/dist/asset-types.js.map +1 -0
  17. package/dist/asset-usage.d.ts +11 -0
  18. package/dist/asset-usage.d.ts.map +1 -0
  19. package/dist/asset-usage.js +50 -0
  20. package/dist/asset-usage.js.map +1 -0
  21. package/dist/base-content-index.d.ts +8 -2
  22. package/dist/base-content-index.d.ts.map +1 -1
  23. package/dist/base-content-index.js +24 -3
  24. package/dist/base-content-index.js.map +1 -0
  25. package/dist/cf-access.js +1 -0
  26. package/dist/cf-access.js.map +1 -0
  27. package/dist/component-registry.d.ts +1 -1
  28. package/dist/component-registry.d.ts.map +1 -1
  29. package/dist/component-registry.js +2 -1
  30. package/dist/component-registry.js.map +1 -0
  31. package/dist/component-registry.types.js +1 -0
  32. package/dist/component-registry.types.js.map +1 -0
  33. package/dist/component-vocabulary.d.ts +33 -0
  34. package/dist/component-vocabulary.d.ts.map +1 -0
  35. package/dist/component-vocabulary.js +105 -0
  36. package/dist/component-vocabulary.js.map +1 -0
  37. package/dist/content-api.interface.d.ts +5 -5
  38. package/dist/content-api.interface.d.ts.map +1 -1
  39. package/dist/content-api.interface.js +1 -0
  40. package/dist/content-api.interface.js.map +1 -0
  41. package/dist/content-filters.d.ts +2 -2
  42. package/dist/content-filters.d.ts.map +1 -1
  43. package/dist/content-filters.js +9 -8
  44. package/dist/content-filters.js.map +1 -0
  45. package/dist/content-index.d.ts +74 -16
  46. package/dist/content-index.d.ts.map +1 -1
  47. package/dist/content-index.js +183 -55
  48. package/dist/content-index.js.map +1 -0
  49. package/dist/content-operations.d.ts +71 -7
  50. package/dist/content-operations.d.ts.map +1 -1
  51. package/dist/content-operations.js +166 -82
  52. package/dist/content-operations.js.map +1 -0
  53. package/dist/content-path.d.ts +64 -0
  54. package/dist/content-path.d.ts.map +1 -0
  55. package/dist/content-path.js +95 -0
  56. package/dist/content-path.js.map +1 -0
  57. package/dist/content-reader.d.ts +2 -2
  58. package/dist/content-reader.d.ts.map +1 -1
  59. package/dist/content-reader.js +2 -1
  60. package/dist/content-reader.js.map +1 -0
  61. package/dist/content-utils.d.ts +53 -10
  62. package/dist/content-utils.d.ts.map +1 -1
  63. package/dist/content-utils.js +103 -34
  64. package/dist/content-utils.js.map +1 -0
  65. package/dist/content-watcher.d.ts +3 -3
  66. package/dist/content-watcher.d.ts.map +1 -1
  67. package/dist/content-watcher.js +13 -10
  68. package/dist/content-watcher.js.map +1 -0
  69. package/dist/data-index.d.ts +1 -1
  70. package/dist/data-index.d.ts.map +1 -1
  71. package/dist/data-index.js +2 -1
  72. package/dist/data-index.js.map +1 -0
  73. package/dist/data.d.ts +5 -13
  74. package/dist/data.d.ts.map +1 -1
  75. package/dist/data.js +7 -6
  76. package/dist/data.js.map +1 -0
  77. package/dist/editor-data-bindings.d.ts +10 -0
  78. package/dist/editor-data-bindings.d.ts.map +1 -0
  79. package/dist/editor-data-bindings.js +67 -0
  80. package/dist/editor-data-bindings.js.map +1 -0
  81. package/dist/etag-utils.d.ts.map +1 -1
  82. package/dist/etag-utils.js +5 -4
  83. package/dist/etag-utils.js.map +1 -0
  84. package/dist/filesystem-content-api.d.ts +45 -18
  85. package/dist/filesystem-content-api.d.ts.map +1 -1
  86. package/dist/filesystem-content-api.js +455 -286
  87. package/dist/filesystem-content-api.js.map +1 -0
  88. package/dist/filesystem-reader-backend.d.ts +46 -0
  89. package/dist/filesystem-reader-backend.d.ts.map +1 -0
  90. package/dist/filesystem-reader-backend.js +119 -0
  91. package/dist/filesystem-reader-backend.js.map +1 -0
  92. package/dist/fragment-index.d.ts +8 -0
  93. package/dist/fragment-index.d.ts.map +1 -0
  94. package/dist/fragment-index.js +8 -0
  95. package/dist/fragment-index.js.map +1 -0
  96. package/dist/fragments.d.ts +16 -0
  97. package/dist/fragments.d.ts.map +1 -0
  98. package/dist/fragments.js +104 -0
  99. package/dist/fragments.js.map +1 -0
  100. package/dist/git-operations.d.ts.map +1 -1
  101. package/dist/git-operations.js +5 -1
  102. package/dist/git-operations.js.map +1 -0
  103. package/dist/header-parser.d.ts +4 -4
  104. package/dist/header-parser.d.ts.map +1 -1
  105. package/dist/header-parser.js +8 -61
  106. package/dist/header-parser.js.map +1 -0
  107. package/dist/in-memory-content-api.d.ts +7 -7
  108. package/dist/in-memory-content-api.d.ts.map +1 -1
  109. package/dist/in-memory-content-api.js +74 -56
  110. package/dist/in-memory-content-api.js.map +1 -0
  111. package/dist/index.d.ts +19 -12
  112. package/dist/index.d.ts.map +1 -1
  113. package/dist/index.js +21 -9
  114. package/dist/index.js.map +1 -0
  115. package/dist/indexing.d.ts +4 -4
  116. package/dist/indexing.d.ts.map +1 -1
  117. package/dist/indexing.js +6 -5
  118. package/dist/indexing.js.map +1 -0
  119. package/dist/json-whitespace-view.js +1 -0
  120. package/dist/json-whitespace-view.js.map +1 -0
  121. package/dist/middleware.d.ts +8 -6
  122. package/dist/middleware.d.ts.map +1 -1
  123. package/dist/middleware.js +178 -142
  124. package/dist/middleware.js.map +1 -0
  125. package/dist/node.d.ts +24 -17
  126. package/dist/node.d.ts.map +1 -1
  127. package/dist/node.js +17 -14
  128. package/dist/node.js.map +1 -0
  129. package/dist/page-references.d.ts +21 -0
  130. package/dist/page-references.d.ts.map +1 -0
  131. package/dist/page-references.js +50 -0
  132. package/dist/page-references.js.map +1 -0
  133. package/dist/read-date.d.ts +3 -0
  134. package/dist/read-date.d.ts.map +1 -0
  135. package/dist/read-date.js +9 -0
  136. package/dist/read-date.js.map +1 -0
  137. package/dist/reader-backend.d.ts +54 -0
  138. package/dist/reader-backend.d.ts.map +1 -0
  139. package/dist/reader-backend.js +2 -0
  140. package/dist/reader-backend.js.map +1 -0
  141. package/dist/reader.d.ts +8 -8
  142. package/dist/reader.d.ts.map +1 -1
  143. package/dist/reader.js +8 -7
  144. package/dist/reader.js.map +1 -0
  145. package/dist/schemas/index.d.ts +6 -6
  146. package/dist/schemas/index.d.ts.map +1 -1
  147. package/dist/schemas/index.js +9 -8
  148. package/dist/schemas/index.js.map +1 -0
  149. package/dist/site-index.d.ts +3 -3
  150. package/dist/site-index.d.ts.map +1 -1
  151. package/dist/site-index.js +9 -5
  152. package/dist/site-index.js.map +1 -0
  153. package/dist/site.d.ts +5 -3
  154. package/dist/site.d.ts.map +1 -1
  155. package/dist/site.js +14 -2
  156. package/dist/site.js.map +1 -0
  157. package/dist/types.d.ts +203 -15
  158. package/dist/types.d.ts.map +1 -1
  159. package/dist/types.js +9 -0
  160. package/dist/types.js.map +1 -0
  161. package/dist/url-safe-base64.js +1 -0
  162. package/dist/url-safe-base64.js.map +1 -0
  163. package/dist/url-validation.d.ts +14 -0
  164. package/dist/url-validation.d.ts.map +1 -1
  165. package/dist/url-validation.js +56 -14
  166. package/dist/url-validation.js.map +1 -0
  167. package/dist/utils/atomic-write.js +1 -0
  168. package/dist/utils/atomic-write.js.map +1 -0
  169. package/dist/utils.d.ts +1 -1
  170. package/dist/utils.js +2 -1
  171. package/dist/utils.js.map +1 -0
  172. package/dist/vite-plugin.d.ts +2 -2
  173. package/dist/vite-plugin.js +5 -4
  174. package/dist/vite-plugin.js.map +1 -0
  175. package/dist/vxjson-serialize.d.ts +5 -6
  176. package/dist/vxjson-serialize.d.ts.map +1 -1
  177. package/dist/vxjson-serialize.js +13 -10
  178. package/dist/vxjson-serialize.js.map +1 -0
  179. package/dist/vxjson.d.ts +4 -3
  180. package/dist/vxjson.d.ts.map +1 -1
  181. package/dist/vxjson.js +10 -20
  182. package/dist/vxjson.js.map +1 -0
  183. package/dist/xxhash.d.ts.map +1 -1
  184. package/dist/xxhash.js +6 -2
  185. package/dist/xxhash.js.map +1 -0
  186. package/package.json +92 -56
  187. package/src/asset-constraints.ts +33 -0
  188. package/src/asset-metadata-store.ts +401 -0
  189. package/src/asset-operations.ts +814 -0
  190. package/src/asset-types.ts +74 -0
  191. package/src/asset-usage.ts +48 -0
  192. package/src/base-content-index.ts +227 -0
  193. package/src/cf-access.ts +85 -0
  194. package/src/component-registry.ts +145 -0
  195. package/src/component-registry.types.ts +12 -0
  196. package/src/component-vocabulary.ts +87 -0
  197. package/src/content-api.interface.ts +94 -0
  198. package/src/content-filters.ts +278 -0
  199. package/src/content-index.ts +642 -0
  200. package/src/content-operations.ts +497 -0
  201. package/src/content-path.ts +121 -0
  202. package/src/content-reader.ts +18 -0
  203. package/src/content-utils.ts +474 -0
  204. package/src/content-watcher.ts +122 -0
  205. package/src/data-index.ts +7 -0
  206. package/src/data.ts +134 -0
  207. package/src/editor-data-bindings.ts +66 -0
  208. package/src/etag-utils.ts +204 -0
  209. package/src/filesystem-content-api.ts +2740 -0
  210. package/src/filesystem-reader-backend.ts +135 -0
  211. package/src/fragment-index.ts +7 -0
  212. package/src/fragments.ts +113 -0
  213. package/src/git-operations.ts +340 -0
  214. package/src/header-parser.ts +272 -0
  215. package/src/in-memory-content-api.ts +760 -0
  216. package/src/index.ts +45 -0
  217. package/src/indexing.ts +8 -0
  218. package/src/json-whitespace-view.ts +155 -0
  219. package/src/middleware.ts +1322 -0
  220. package/src/node.ts +40 -0
  221. package/src/page-references.ts +76 -0
  222. package/src/read-date.ts +7 -0
  223. package/src/reader-backend.ts +54 -0
  224. package/src/reader.ts +15 -0
  225. package/src/schemas/index.ts +113 -0
  226. package/src/site-index.ts +330 -0
  227. package/src/site.ts +198 -0
  228. package/src/types.ts +759 -0
  229. package/src/url-safe-base64.ts +38 -0
  230. package/src/url-validation.ts +121 -0
  231. package/src/utils/atomic-write.ts +20 -0
  232. package/src/utils.ts +84 -0
  233. package/src/vite-plugin.ts +45 -0
  234. package/src/vxjson-serialize.ts +66 -0
  235. package/src/vxjson.ts +442 -0
  236. package/src/xxhash.ts +43 -0
  237. package/dist/asset-manifest.d.ts +0 -23
  238. package/dist/asset-manifest.d.ts.map +0 -1
  239. package/dist/asset-manifest.js +0 -73
  240. package/dist/block-index.d.ts +0 -9
  241. package/dist/block-index.d.ts.map +0 -1
  242. package/dist/block-index.js +0 -11
  243. package/dist/blocks.d.ts +0 -16
  244. package/dist/blocks.d.ts.map +0 -1
  245. package/dist/blocks.js +0 -103
  246. package/dist/component-registry.types-C0ctF9nh.d.mts +0 -71
  247. package/dist/component-registry.types-C0ctF9nh.d.mts.map +0 -1
  248. package/dist/content-index-D092_vk1.mjs +0 -629
  249. package/dist/content-index-D092_vk1.mjs.map +0 -1
  250. package/dist/content-index-D6IVMmAB.d.mts +0 -127
  251. package/dist/content-index-D6IVMmAB.d.mts.map +0 -1
  252. package/dist/content-operations-DIbsxG5A.d.mts +0 -354
  253. package/dist/content-operations-DIbsxG5A.d.mts.map +0 -1
  254. package/dist/content-utils-fWNHTrPy.mjs +0 -280
  255. package/dist/content-utils-fWNHTrPy.mjs.map +0 -1
  256. package/dist/data-DquNIEnQ.mjs +0 -62
  257. package/dist/data-DquNIEnQ.mjs.map +0 -1
  258. package/dist/filesystem-content-api-B1KIQJfk.mjs +0 -2
  259. package/dist/filesystem-content-api-C0HIhqZi.mjs +0 -1620
  260. package/dist/filesystem-content-api-C0HIhqZi.mjs.map +0 -1
  261. package/dist/filesystem-content-api-DCdNi-co.d.mts +0 -134
  262. package/dist/filesystem-content-api-DCdNi-co.d.mts.map +0 -1
  263. package/dist/index-DxVTFK66.d.mts +0 -105
  264. package/dist/index-DxVTFK66.d.mts.map +0 -1
  265. package/dist/index.d.mts +0 -80
  266. package/dist/index.d.mts.map +0 -1
  267. package/dist/index.mjs +0 -78
  268. package/dist/index.mjs.map +0 -1
  269. package/dist/indexing.d.mts +0 -152
  270. package/dist/indexing.d.mts.map +0 -1
  271. package/dist/indexing.mjs +0 -255
  272. package/dist/indexing.mjs.map +0 -1
  273. package/dist/node.d.mts +0 -373
  274. package/dist/node.d.mts.map +0 -1
  275. package/dist/node.mjs +0 -2572
  276. package/dist/node.mjs.map +0 -1
  277. package/dist/reader.d.mts +0 -15
  278. package/dist/reader.d.mts.map +0 -1
  279. package/dist/reader.mjs +0 -22
  280. package/dist/reader.mjs.map +0 -1
  281. package/dist/schemas/index.d.mts +0 -2
  282. package/dist/schemas/index.mjs +0 -2
  283. package/dist/schemas-CFRD0FIQ.mjs +0 -84
  284. package/dist/schemas-CFRD0FIQ.mjs.map +0 -1
  285. package/dist/site-8oaj1Q60.mjs +0 -366
  286. package/dist/site-8oaj1Q60.mjs.map +0 -1
  287. package/dist/site-index-B_254bCc.d.mts +0 -136
  288. package/dist/site-index-B_254bCc.d.mts.map +0 -1
  289. package/dist/types-DOdldbfD.mjs +0 -34
  290. package/dist/types-DOdldbfD.mjs.map +0 -1
  291. package/dist/types-DjfhS272.d.mts +0 -456
  292. package/dist/types-DjfhS272.d.mts.map +0 -1
  293. package/dist/vxjson-qHrgLGip.mjs +0 -555
  294. package/dist/vxjson-qHrgLGip.mjs.map +0 -1
  295. package/dist/vxjson-serialize-geF6qvpn.mjs +0 -34
  296. package/dist/vxjson-serialize-geF6qvpn.mjs.map +0 -1
  297. package/dist/vxjson-serialize.d.mts +0 -17
  298. package/dist/vxjson-serialize.d.mts.map +0 -1
  299. package/dist/vxjson-serialize.mjs +0 -2
@@ -0,0 +1,2740 @@
1
+ import { access, mkdir, open, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import matter from 'gray-matter';
4
+ import sortKeys from 'sort-keys';
5
+ import type { ContentAPI } from './content-api.interface.js';
6
+ import { filterContentWithIndexes } from './content-filters.js';
7
+ import { ContentIndex, duplicateIdMessage, type IndexProblem, unknownSiteMessage } from './content-index.js';
8
+ import {
9
+ analyzeUpdateScope,
10
+ buildLocaleVersion,
11
+ buildPathnameHistory,
12
+ checkEntryName,
13
+ checkMdxPagesPathname,
14
+ checkPagePathname,
15
+ generateContentId,
16
+ isContentPublished,
17
+ type PathnameRefusal,
18
+ shouldUpdateModifiedTimestamp,
19
+ UPDATE_SCOPE,
20
+ updatePublishDates,
21
+ validateAndPrepareMetadata,
22
+ validateCreateContent,
23
+ } from './content-operations.js';
24
+ import {
25
+ type ContentPathLayout,
26
+ invalidLocaleMessage,
27
+ isContentLocale,
28
+ parseContentPathLayout,
29
+ parseLocaleFilename,
30
+ } from './content-path.js';
31
+ import {
32
+ applyMetaPatch,
33
+ localesOf,
34
+ mapSiteNames,
35
+ resolvePublishDate,
36
+ serializeMdxWithFrontmatter,
37
+ } from './content-utils.js';
38
+ import { Data } from './data.js';
39
+ import { calculateEtagsFromMdxBuffer, findMdxContentStartPosition, parseDualEtag } from './etag-utils.js';
40
+ import { Fragments } from './fragments.js';
41
+ import { Site } from './site.js';
42
+ import type {
43
+ BatchOperationResult,
44
+ BatchResult,
45
+ ContentAPIOptions,
46
+ ContentData,
47
+ ContentEntry,
48
+ ContentIdentity,
49
+ ContentManifest,
50
+ ContentMeta,
51
+ ContentProp,
52
+ ContentType,
53
+ CreateContentInput,
54
+ CreateResult,
55
+ DeleteLocaleInput,
56
+ DeleteResult,
57
+ FindOptions,
58
+ GlobalFilters,
59
+ LocaleFileData,
60
+ LocalePathData,
61
+ LocaleVersion,
62
+ LocalizedEntry,
63
+ LocalizedManifest,
64
+ SitesConfig,
65
+ UpdateLocaleInput,
66
+ UpdateResult,
67
+ VXJSONFile,
68
+ } from './types.js';
69
+ import { atomicWriteFile } from './utils/atomic-write.js';
70
+ import { xxh64 } from './xxhash.js';
71
+
72
+ interface ReindexResult {
73
+ filesProcessed: number;
74
+ filesSkipped: number;
75
+ filesDeleted?: number;
76
+ errors?: number;
77
+ // Return manifests of updated locales (without content)
78
+ updated: LocalizedManifest[];
79
+ deleted?: Array<{ id: string; locale: string; kind: 'page' | 'fragment' | 'data' }>;
80
+ }
81
+
82
+ import { VXJSON } from './vxjson.js';
83
+
84
+ // Helper to ensure we have an Error object
85
+ function ensureError(error: unknown): Error {
86
+ if (error instanceof Error) {
87
+ return error;
88
+ }
89
+ return new Error(String(error));
90
+ }
91
+
92
+ // Reusable TextDecoder instance - safe to reuse as it's stateless
93
+ const textDecoder = new TextDecoder();
94
+
95
+ /**
96
+ * Where the read repair moves a fragment saved straight into fragments/: the
97
+ * folder the editor saves new fragments to, which every conlocaFragments(...)
98
+ * call in a site's content config declares, so the moved fragment still builds.
99
+ */
100
+ const REPAIRED_FRAGMENT_COLLECTION = 'fragments';
101
+
102
+ async function readFilePrefix(filePath: string, buffer: Uint8Array): Promise<number> {
103
+ const handle = await open(filePath, 'r');
104
+ try {
105
+ return (await handle.read(buffer, 0, buffer.byteLength, 0)).bytesRead;
106
+ } finally {
107
+ await handle.close();
108
+ }
109
+ }
110
+
111
+ // Parse 4KB MDX content - extracts frontmatter from buffer
112
+ function parse4KBMDX(
113
+ buffer: Uint8Array,
114
+ bytesRead: number,
115
+ ): {
116
+ id?: string;
117
+ created?: string;
118
+ modified?: string;
119
+ publishAt?: string;
120
+ unpublishAt?: string;
121
+ meta: ContentMeta;
122
+ contentStartPos?: number; // Position where content starts (after second ---)
123
+ } {
124
+ // Only convert to string what we need
125
+ const partialContent = textDecoder.decode(buffer.subarray(0, bytesRead));
126
+ // Empty options opt out of gray-matter's module-level memo cache — a plain
127
+ // object keyed by the raw input, so inputs naming an Object.prototype member
128
+ // ('valueOf', 'toString', …) return the inherited member instead of a parse.
129
+ // Same at every matter() call below.
130
+ const { data: frontmatter } = matter(partialContent, {});
131
+
132
+ // Find where content starts (after second ---)
133
+ const delimiter = new TextEncoder().encode('---');
134
+ let delimiterCount = 0;
135
+ let contentStartPos = -1;
136
+
137
+ for (let i = 0; i <= bytesRead - delimiter.length; i++) {
138
+ let match = true;
139
+ for (let j = 0; j < delimiter.length; j++) {
140
+ if (buffer[i + j] !== delimiter[j]) {
141
+ match = false;
142
+ break;
143
+ }
144
+ }
145
+ if (match) {
146
+ delimiterCount++;
147
+ if (delimiterCount === 2) {
148
+ // Skip past --- and newline
149
+ contentStartPos = i + delimiter.length;
150
+ while (contentStartPos < bytesRead && (buffer[contentStartPos] === 0x0a || buffer[contentStartPos] === 0x0d)) {
151
+ contentStartPos++;
152
+ }
153
+ break;
154
+ }
155
+ }
156
+ }
157
+
158
+ // Extract special fields and treat the rest as metadata
159
+ const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
160
+
161
+ return {
162
+ id,
163
+ created,
164
+ modified,
165
+ publishAt,
166
+ unpublishAt,
167
+ meta: metaFields as ContentMeta, // All other fields are metadata
168
+ contentStartPos,
169
+ };
170
+ }
171
+
172
+ /**
173
+ * FileSystem-based Content API Implementation
174
+ *
175
+ * Stores content as files on disk in a git-friendly format:
176
+ * - Pages: /{site}/pages/{filename}.{locale}.vxjson
177
+ * - Fragments: /fragments/{collection}/{filename}.{locale}.{mdx|vxjson}
178
+ *
179
+ * ## Indexing
180
+ *
181
+ * Content is indexed at startup for performance. The index is cached per
182
+ * content root path and cleared when the process restarts.
183
+ *
184
+ * ## Read-Repair
185
+ *
186
+ * Since files can be modified externally (git, editors), this implementation:
187
+ *
188
+ * 1. Repairs invalid VXJSON files (ensures "content" field is last)
189
+ * 2. Adds missing required fields (id, created, modified)
190
+ * 3. Handles files added after initial indexing
191
+ * 4. Updates the index when files are repaired or discovered
192
+ *
193
+ * ## Performance
194
+ *
195
+ * - Initial indexing reads only first 4KB of each file
196
+ * - Full content is loaded on demand
197
+ * - ETags are calculated using streaming for efficiency
198
+ */
199
+ /**
200
+ * Read and validate `<contentRoot>/sites.json`. Returns a safe default
201
+ * (`{ sites: {}, globalLocales: ['en'] }`) when the file is missing or
202
+ * has invalid structure, with a warning logged in each case.
203
+ *
204
+ * Exported standalone so the Astro integration (and any other tooling
205
+ * that needs to inspect per-site config at startup time) can read the
206
+ * config without spinning up a full content-api instance.
207
+ */
208
+ export async function readSitesConfig(contentRoot: string): Promise<SitesConfig> {
209
+ const absoluteContentRoot = resolve(contentRoot);
210
+ const sitesPath = join(absoluteContentRoot, 'sites.json');
211
+ let content: string;
212
+ try {
213
+ content = await readFile(sitesPath, 'utf-8');
214
+ } catch {
215
+ // A genuinely absent sites.json is a normal starting state.
216
+ console.warn(`Warning: sites.json is missing at ${sitesPath}. Using empty configuration.`);
217
+ return { sites: {}, globalLocales: ['en'] };
218
+ }
219
+
220
+ // Tolerating a malformed sites.json is deliberate ("Handle invalid sites.json gracefully"). What
221
+ // was not deliberate is the diagnosis: this used to share the catch above
222
+ // and report the file as MISSING, naming a path where it plainly sits,
223
+ // while every page silently dropped out of every site. Say what is
224
+ // actually wrong; the tolerance itself is unchanged.
225
+ let parsed: SitesConfig;
226
+ try {
227
+ parsed = JSON.parse(content);
228
+ } catch (error) {
229
+ console.warn(
230
+ `Warning: sites.json at ${sitesPath} is not valid JSON (${messageOf(error)}). ` +
231
+ 'Using empty configuration — every site will be empty until this is fixed.',
232
+ );
233
+ return { sites: {}, globalLocales: ['en'] };
234
+ }
235
+ // Validate the structure. `null` is valid JSON, so `parsed` itself needs
236
+ // the null check before anything reads a property off it.
237
+ if (!parsed?.sites || typeof parsed.sites !== 'object') {
238
+ console.warn(
239
+ `Warning: sites.json has invalid structure at ${sitesPath}. Expected 'sites' property. Using default configuration.`,
240
+ );
241
+ return { sites: {}, globalLocales: ['en'] };
242
+ }
243
+ if (!parsed.globalLocales || !Array.isArray(parsed.globalLocales)) {
244
+ console.warn(`Warning: sites.json is missing 'globalLocales' array at ${sitesPath}. Using default global locales.`);
245
+ warnUnreadableLocales(sitesPath, parsed.sites, []);
246
+ return {
247
+ sites: parsed.sites,
248
+ globalLocales: ['en'],
249
+ };
250
+ }
251
+ warnUnreadableLocales(sitesPath, parsed.sites, parsed.globalLocales);
252
+ return parsed;
253
+ }
254
+
255
+ /**
256
+ * Why a page file's name gives no locale the content grammar reads: either it
257
+ * names one the grammar refuses ('about.pt-br.vxjson') or it names none.
258
+ */
259
+ function unreadablePageLocaleMessage(filename: string): string {
260
+ const written = /^.+\.([^.]+)\.(?:mdx|vxjson)$/.exec(filename)?.[1];
261
+ return written === undefined
262
+ ? `Page file ${filename} has no locale in its name (<name>.<locale>.vxjson), so it is not indexed.`
263
+ : `Page file ${filename} is not indexed. ${invalidLocaleMessage(written)}`;
264
+ }
265
+
266
+ // One warning per sites.json and locale for the whole process: the file is
267
+ // read again by every content API created and every config reload.
268
+ const warnedLocales = new Set<string>();
269
+
270
+ /**
271
+ * Warn about each locale sites.json declares that content file names cannot
272
+ * carry: its pages can be neither created nor read, and nothing else says so
273
+ * until a save is refused.
274
+ */
275
+ function warnUnreadableLocales(sitesPath: string, sites: SitesConfig['sites'], globalLocales: unknown[]): void {
276
+ const declared = [...globalLocales];
277
+ for (const site of Object.values(sites)) {
278
+ if (Array.isArray(site?.locales)) declared.push(...site.locales);
279
+ declared.push(site?.defaultLocale);
280
+ }
281
+ for (const locale of declared) {
282
+ const key = `${sitesPath}\0${locale}`;
283
+ if (typeof locale !== 'string' || isContentLocale(locale) || warnedLocales.has(key)) continue;
284
+ warnedLocales.add(key);
285
+ console.warn(
286
+ `Warning: sites.json at ${sitesPath} declares a locale no content file can carry, so its pages can be neither created nor read. ${invalidLocaleMessage(locale)}`,
287
+ );
288
+ }
289
+ }
290
+
291
+ export type { IndexProblem } from './content-index.js';
292
+
293
+ function messageOf(error: unknown): string {
294
+ return error instanceof Error ? error.message : String(error);
295
+ }
296
+
297
+ export class FileSystemContentAPI implements ContentAPI {
298
+ private contentRoot: string;
299
+ private absoluteContentRoot: string;
300
+ private contentIndex: ContentIndex;
301
+ readonly sitesConfig: SitesConfig;
302
+ readonly fragments: Fragments;
303
+ readonly data: Data;
304
+ private readonly sites: Record<string, Site>;
305
+
306
+ // mdx-page support: optional second filesystem root for kind:'page'+type:'mdx'.
307
+ // Canonical source is the resolved site's `mdxPages` in sites.json; the
308
+ // ContentAPIOptions.mdxPagesRoot option exists as a test/programmatic
309
+ // override. See ContentAPIOptions.mdxPagesRoot for the design rationale.
310
+ private absoluteMdxPagesRoot?: string;
311
+ private mdxPagesDefaultLocale = 'en';
312
+ private mdxPagesSite = 'default';
313
+ private mdxPagesCollection = 'pages';
314
+
315
+ // Resolved locale list used to decide whether a path segment that
316
+ // looks locale-shaped (e.g. `de`, `en-US`) is actually a configured
317
+ // locale. Source-of-truth resolution (option > sites.json) happens in
318
+ // the constructor; parsers read this set directly.
319
+ private readonly availableLocales: ReadonlySet<string>;
320
+
321
+ // Getter for testing purposes
322
+ get normalizedContentRoot(): string {
323
+ return this.contentRoot;
324
+ }
325
+
326
+ private constructor(
327
+ contentRoot: string,
328
+ sitesConfig: SitesConfig,
329
+ contentIndex: ContentIndex,
330
+ mdxPagesOptions?: {
331
+ root?: string;
332
+ defaultLocale?: string;
333
+ site?: string;
334
+ },
335
+ localeOptions?: {
336
+ availableLocales?: string[];
337
+ defaultLocale?: string;
338
+ },
339
+ ) {
340
+ // Normalize contentRoot: remove ./ prefix for relative paths, keep absolute paths as-is
341
+ if (contentRoot.startsWith('./')) {
342
+ this.contentRoot = contentRoot.slice(2);
343
+ } else if (contentRoot.startsWith('/')) {
344
+ // Absolute path, keep as-is
345
+ this.contentRoot = contentRoot;
346
+ } else {
347
+ // Already normalized relative path
348
+ this.contentRoot = contentRoot;
349
+ }
350
+
351
+ // Store absolute path for file operations
352
+ this.absoluteContentRoot = resolve(this.contentRoot);
353
+
354
+ this.sitesConfig = sitesConfig;
355
+ this.contentIndex = contentIndex;
356
+
357
+ // Resolve which site owns mdx-type pages. Resolution order:
358
+ // 1. Explicit `mdxPagesOptions.site` (test / programmatic override)
359
+ // 2. First site in sites.json that declares an `mdxPages` path
360
+ // 3. First configured site (any)
361
+ // 4. Literal 'default'
362
+ const siteNames = Object.keys(sitesConfig.sites);
363
+ const firstSiteName = siteNames[0];
364
+ const firstSiteWithMdxPages = siteNames.find((name) => sitesConfig.sites[name]?.mdxPages);
365
+ this.mdxPagesSite = mdxPagesOptions?.site ?? firstSiteWithMdxPages ?? firstSiteName ?? 'default';
366
+
367
+ // Resolve the mdx-pages path. Option wins over sites.json so tests and
368
+ // programmatic callers can supply a path without writing a sites.json
369
+ // file. When neither is set, .mdx files fall back to living alongside
370
+ // Puck pages under `{contentRoot}/{site}/pages/`.
371
+ const sitesJsonMdxPages = sitesConfig.sites[this.mdxPagesSite]?.mdxPages;
372
+ const resolvedMdxPages = mdxPagesOptions?.root ?? sitesJsonMdxPages;
373
+ if (resolvedMdxPages) {
374
+ const normalizedMdxPages = resolvedMdxPages.startsWith('./') ? resolvedMdxPages.slice(2) : resolvedMdxPages;
375
+ this.absoluteMdxPagesRoot = resolve(normalizedMdxPages);
376
+ }
377
+ // Default locale: top-level option > mdxPages option > resolved-site's
378
+ // defaultLocale > first global locale > 'en'. The top-level option wins
379
+ // because it represents an explicit framework-level declaration (e.g.
380
+ // forwarded from Astro's i18n block via localesFromAstroI18n).
381
+ const siteConfig = sitesConfig.sites[this.mdxPagesSite];
382
+ this.mdxPagesDefaultLocale =
383
+ localeOptions?.defaultLocale ??
384
+ mdxPagesOptions?.defaultLocale ??
385
+ siteConfig?.defaultLocale ??
386
+ sitesConfig.globalLocales[0] ??
387
+ 'en';
388
+
389
+ // Resolve the available-locales set. The top-level option is
390
+ // authoritative when present; otherwise we merge sites.json's global
391
+ // locales with the resolved-site's per-site locales. The default
392
+ // locale is always added so getFilePath round-trips work.
393
+ const merged = new Set<string>();
394
+ if (localeOptions?.availableLocales && localeOptions.availableLocales.length > 0) {
395
+ for (const loc of localeOptions.availableLocales) merged.add(loc);
396
+ } else {
397
+ for (const loc of sitesConfig.globalLocales) merged.add(loc);
398
+ if (siteConfig?.locales) {
399
+ for (const loc of siteConfig.locales) merged.add(loc);
400
+ }
401
+ }
402
+ merged.add(this.mdxPagesDefaultLocale);
403
+ this.availableLocales = merged;
404
+
405
+ // Initialize fragments
406
+ this.fragments = new Fragments(this, this.contentIndex.getFragmentIndex());
407
+
408
+ // Initialize data
409
+ this.data = new Data(this, this.contentIndex.getDataIndex());
410
+
411
+ // Initialize all sites
412
+ this.sites = mapSiteNames(sitesConfig, (siteName) => {
413
+ const siteIndex = this.contentIndex.getSiteIndex(siteName);
414
+ if (!siteIndex) {
415
+ throw new Error(`Site index not found for ${siteName}`);
416
+ }
417
+ return new Site(siteName, this, siteIndex);
418
+ });
419
+ }
420
+
421
+ static async create(options: ContentAPIOptions): Promise<FileSystemContentAPI> {
422
+ // Keep contentRoot as provided (will be normalized in constructor)
423
+ const contentRoot = options.contentRoot;
424
+
425
+ // Load sites config (canonical home for per-site fields including mdxPages).
426
+ let sitesConfig = await readSitesConfig(contentRoot);
427
+
428
+ // Apply the top-level locales option as the authoritative source.
429
+ // We expand sitesConfig so that the FragmentIndex (which keys on
430
+ // globalLocales) and the resolved SiteIndex (which keys on the
431
+ // site's locales array) both have slots for every option-declared
432
+ // locale. Without this, the parser would correctly identify a file's
433
+ // locale but `addContent` would crash on a missing index bucket.
434
+ // We preserve the resolved site's existing `mdxPages` and `domains`
435
+ // through the rewrite so the locale-override doesn't clobber the
436
+ // per-site content config.
437
+ if (options.availableLocales && options.availableLocales.length > 0) {
438
+ const optionDefaultLocale = options.defaultLocale ?? options.availableLocales[0];
439
+ const optionSite = options.mdxPagesSite ?? Object.keys(sitesConfig.sites)[0] ?? 'default';
440
+ const existingSite = sitesConfig.sites[optionSite];
441
+ sitesConfig = {
442
+ sites: {
443
+ ...sitesConfig.sites,
444
+ [optionSite]: {
445
+ locales: options.availableLocales,
446
+ defaultLocale: optionDefaultLocale,
447
+ ...(existingSite?.domains && { domains: existingSite.domains }),
448
+ ...(existingSite?.mdxPages && { mdxPages: existingSite.mdxPages }),
449
+ },
450
+ },
451
+ globalLocales: Array.from(new Set([...sitesConfig.globalLocales, ...options.availableLocales])),
452
+ };
453
+ }
454
+
455
+ // Get cached content index or create new one
456
+ // Use the normalized contentRoot for cache key
457
+ const normalizedContentRoot = contentRoot.startsWith('./') ? contentRoot.slice(2) : contentRoot;
458
+ const contentIndex = await ContentIndex.getCachedOrCreate(normalizedContentRoot, sitesConfig);
459
+
460
+ // Create instance (not cached)
461
+ const api = new FileSystemContentAPI(
462
+ contentRoot,
463
+ sitesConfig,
464
+ contentIndex,
465
+ {
466
+ root: options.mdxPagesRoot,
467
+ defaultLocale: options.mdxPagesDefaultLocale,
468
+ site: options.mdxPagesSite,
469
+ },
470
+ {
471
+ availableLocales: options.availableLocales,
472
+ defaultLocale: options.defaultLocale,
473
+ },
474
+ );
475
+
476
+ // Index all content files (only if index is empty).
477
+ //
478
+ // FileSystemContentAPI continues to hydrate via parseFileHeaderWithRepair
479
+ // (legacy path), which performs read-repair side effects on disk (renaming
480
+ // missing-locale files, rewriting non-canonical VXJSON, adding missing
481
+ // id/created/modified). ContentIndex.indexAll(backend) is the newer,
482
+ // backend-agnostic hydration path for content that is not on disk;
483
+ // FileSystemContentAPI's behavior must stay identical, so this call site
484
+ // keeps the legacy path until the repair side effects move behind a backend.
485
+ if (contentIndex.entryCount === 0) {
486
+ await api.indexAllContent();
487
+ }
488
+
489
+ return api;
490
+ }
491
+
492
+ /**
493
+ * Hydrate the content index for this FileSystemContentAPI by scanning the
494
+ * content root and running parseFileHeaderWithRepair on each file. This is
495
+ * the legacy hydration path that preserves the filesystem read-repair
496
+ * behavior (file renames, canonical-form rewrites, id/timestamp backfill).
497
+ *
498
+ * ContentIndex.indexAll(backend) is the backend-agnostic replacement for
499
+ * content that is not on disk; this private method exists so FileSystemContentAPI
500
+ * can keep its repair-on-read side effects until they are lifted onto a
501
+ * dedicated FileSystemReaderBackend field.
502
+ */
503
+ private async indexAllContent(): Promise<void> {
504
+ // Also drops the previous problems: they describe an index that no longer exists.
505
+ this.contentIndex.clear();
506
+
507
+ const files = await this.scanContentFiles();
508
+ const OPTIMAL_BATCH_SIZE = 1000;
509
+ console.debug(`Indexing ${files.length} content files...`);
510
+
511
+ // Which file claimed each id+locale — same guard ContentIndex.indexAll
512
+ // carries. Without it a duplicated file merges into the first one's
513
+ // locale slot and a page silently stops existing, and this legacy path
514
+ // is the one every local dev server and Astro build hydrates through.
515
+ const claimedBy = new Map<string, string>();
516
+
517
+ // One 4KB buffer per file in a batch: the batch is read in parallel, so
518
+ // two files sharing a buffer overwrite each other's bytes mid-parse.
519
+ // parseFileHeaderWithRepair owns the buffer contract (reads up to 4096
520
+ // bytes from offset 0).
521
+ const buffers = Array.from({ length: Math.min(files.length, OPTIMAL_BATCH_SIZE) }, () => new Uint8Array(4096));
522
+
523
+ for (let i = 0; i < files.length; i += OPTIMAL_BATCH_SIZE) {
524
+ const batch = files.slice(i, i + OPTIMAL_BATCH_SIZE);
525
+ await Promise.all(
526
+ batch.map(async (filePath, batchIndex) => {
527
+ try {
528
+ const result = await this.parseFileHeaderWithRepair(filePath, buffers[batchIndex]);
529
+ if (result) {
530
+ // Same reason as the shared indexAll loop: a page under a site
531
+ // sites.json does not declare would be filed nowhere and
532
+ // silently vanish from every lookup and build.
533
+ if (
534
+ result.manifest.kind === 'page' &&
535
+ result.manifest.site &&
536
+ !this.contentIndex.hasSite(result.manifest.site)
537
+ ) {
538
+ this.recordIndexProblem(filePath, 'unknown-site', unknownSiteMessage(result.manifest.site));
539
+ return;
540
+ }
541
+ const claim = `${result.manifest.id}::${result.localeVersion.locale}`;
542
+ const claimant = claimedBy.get(claim);
543
+ if (claimant !== undefined && claimant !== filePath) {
544
+ this.recordIndexProblem(
545
+ filePath,
546
+ 'duplicate-id',
547
+ duplicateIdMessage(result.manifest.id, result.localeVersion.locale, claimant),
548
+ );
549
+ return;
550
+ }
551
+ claimedBy.set(claim, filePath);
552
+ this.contentIndex.addContent(result.manifest, result.localeVersion, result.content);
553
+ }
554
+ } catch (error) {
555
+ console.error(`Failed to index ${filePath}: ${messageOf(error)}`);
556
+ this.recordIndexProblem(filePath, 'index-error', messageOf(error));
557
+ }
558
+ }),
559
+ );
560
+ }
561
+ }
562
+
563
+ /**
564
+ * Record a file the indexer could not read. Signature matches the `onError`
565
+ * callback of ContentIndex.indexAll so it can be handed over unchanged when
566
+ * this class migrates off the legacy repair-on-read hydration path. The
567
+ * problems live on the index itself, not on this instance: the index is
568
+ * cached per content root, and a later instance over the same root reuses it
569
+ * without re-indexing, so instance-local problems would vanish.
570
+ */
571
+ private recordIndexProblem(path: string, reason: string, message: string): void {
572
+ this.contentIndex.recordProblem(path, reason, message);
573
+ }
574
+
575
+ /**
576
+ * Files the indexer could not read. They are absent from listAllContent(),
577
+ * so any caller that treats that list as complete — `conloca doctor`, most
578
+ * of all — must consult this to avoid reporting success over broken content.
579
+ */
580
+ getIndexProblems(): readonly IndexProblem[] {
581
+ return this.contentIndex.getProblems();
582
+ }
583
+
584
+ /**
585
+ * Clear all caches - useful for testing
586
+ */
587
+ static clearCaches(): void {
588
+ ContentIndex.clearCache();
589
+ // TODO: CanvasIndex.clearCache() when implemented
590
+ }
591
+
592
+ private async parseFileHeaderWithRepair(
593
+ originalFilePath: string,
594
+ buffer: Uint8Array,
595
+ ): Promise<{
596
+ manifest: ContentManifest;
597
+ locale: string;
598
+ localeVersion: LocaleVersion;
599
+ bytesRead: number;
600
+ content?: ContentData;
601
+ } | null> {
602
+ let bytesRead = 0;
603
+ let filePath = originalFilePath; // Use a local variable that can be updated if file is renamed
604
+
605
+ try {
606
+ bytesRead = await readFilePrefix(filePath, buffer);
607
+ } catch (error) {
608
+ console.error(`Error reading ${filePath}:`, error);
609
+ throw error;
610
+ }
611
+
612
+ try {
613
+ // Now parse the buffer content
614
+
615
+ // Parse file to extract metadata
616
+ let relativePath = filePath.replace(`${this.absoluteContentRoot}/`, '');
617
+ let parts = relativePath.split('/');
618
+
619
+ // Determine site/collection structure
620
+ let site: string | undefined;
621
+ let collection: string;
622
+ let locale = 'en';
623
+ let name: string | undefined;
624
+ let pathname: string | undefined;
625
+ // Type for parsed metadata from files
626
+ interface ParsedMetadata {
627
+ id?: string;
628
+ created?: string;
629
+ modified?: string;
630
+ publishAt?: string;
631
+ unpublishAt?: string;
632
+ pathname?: string;
633
+ name?: string;
634
+ previousPathnames?: Record<string, string>;
635
+ meta?: ContentMeta;
636
+ type?: 'puck' | 'mdx' | 'json';
637
+ contentStartPos?: number;
638
+ data?: Record<string, unknown>; // For data collection entries
639
+ }
640
+ let parsedData: ParsedMetadata = {};
641
+ let kind: 'fragment' | 'page' | 'data';
642
+
643
+ // Files under the optional mdxPagesRoot are kind:'page' + type:'mdx',
644
+ // independent of the directory tree rooted at absoluteContentRoot. The
645
+ // leading prefix is stripped here; locale lives as a directory segment
646
+ // ({locale}/{slug}.mdx for non-default locales, {slug}.mdx at the root
647
+ // for the default locale).
648
+ if (this.absoluteMdxPagesRoot && filePath.startsWith(`${this.absoluteMdxPagesRoot}/`)) {
649
+ kind = 'page';
650
+ site = this.mdxPagesSite;
651
+ collection = this.mdxPagesCollection;
652
+ const mdxRelativePath = filePath.replace(`${this.absoluteMdxPagesRoot}/`, '');
653
+ const mdxParts = mdxRelativePath.split('/');
654
+ const mdxFilename = mdxParts[mdxParts.length - 1];
655
+
656
+ const noLocaleMatch = mdxFilename.match(/^(.+)\.mdx$/);
657
+ if (!noLocaleMatch) return null;
658
+ mdxParts[mdxParts.length - 1] = noLocaleMatch[1];
659
+
660
+ // A leading folder counts as a locale only when it's a configured
661
+ // locale. A two-letter folder like `qa/` or `id/` is therefore
662
+ // left in the slug, not silently classified as a language.
663
+ if (mdxParts.length > 1 && this.availableLocales.has(mdxParts[0])) {
664
+ locale = mdxParts[0];
665
+ const slugParts = mdxParts.slice(1);
666
+ pathname =
667
+ slugParts[slugParts.length - 1] === 'index'
668
+ ? `/${slugParts.slice(0, -1).join('/')}`
669
+ : `/${slugParts.join('/')}`;
670
+ } else {
671
+ locale = this.mdxPagesDefaultLocale;
672
+ pathname =
673
+ mdxParts[mdxParts.length - 1] === 'index'
674
+ ? `/${mdxParts.slice(0, -1).join('/')}`
675
+ : `/${mdxParts.join('/')}`;
676
+ }
677
+
678
+ parsedData = parse4KBMDX(buffer, bytesRead);
679
+ } else if (parts[0] === 'fragments') {
680
+ kind = 'fragment';
681
+
682
+ // Check if fragment is directly in fragments/ directory (no collection subdirectory)
683
+ if (parts.length === 2) {
684
+ // Keep the direct layout unless the repair move succeeds.
685
+ collection = '';
686
+ const filename = parts[1];
687
+
688
+ // Create the repair folder if it doesn't exist
689
+ const repairDir = join(this.absoluteContentRoot, 'fragments', REPAIRED_FRAGMENT_COLLECTION);
690
+ try {
691
+ await mkdir(repairDir, { recursive: true });
692
+ } catch {
693
+ // Directory might already exist, that's fine
694
+ }
695
+
696
+ // Move the file to the repair folder
697
+ const newFilePath = join(repairDir, filename);
698
+
699
+ try {
700
+ // Check if target file already exists
701
+ try {
702
+ await access(newFilePath);
703
+ console.warn(
704
+ `Cannot move ${filename} to fragments/${REPAIRED_FRAGMENT_COLLECTION}/: target file already exists`,
705
+ );
706
+ } catch {
707
+ // Target doesn't exist, safe to move
708
+ await rename(filePath, newFilePath);
709
+ console.log(`Repaired: Moved ${filename} to fragments/${REPAIRED_FRAGMENT_COLLECTION}/ collection`);
710
+
711
+ // The file now uses the repaired collection layout.
712
+ collection = REPAIRED_FRAGMENT_COLLECTION;
713
+ filePath = newFilePath;
714
+
715
+ // Update relativePath and parts for the new file path
716
+ relativePath = filePath.replace(`${this.absoluteContentRoot}/`, '');
717
+ parts = relativePath.split('/');
718
+
719
+ bytesRead = await readFilePrefix(filePath, buffer);
720
+ }
721
+ } catch (moveError) {
722
+ console.error(`Failed to move ${filename} to fragments/${REPAIRED_FRAGMENT_COLLECTION}/:`, moveError);
723
+ // Continue processing with original file
724
+ bytesRead = await readFilePrefix(filePath, buffer);
725
+ }
726
+ } else {
727
+ // Fragment is in a collection subdirectory
728
+ collection = parts[1];
729
+ }
730
+
731
+ const filename = parts[parts.length - 1];
732
+ // Extract name and locale from filename: hero.en.mdx -> name: hero, locale: en
733
+ // Also handle files without locale: hero.mdx -> name: hero, locale: default from sites.json.
734
+ // The locale grammar is the shared one (content-path.ts): a suffix that is not
735
+ // a locale ('hero.v2.mdx') takes the rename repair below instead of being
736
+ // indexed under a made-up locale.
737
+ const localeSuffix = parseLocaleFilename(filename);
738
+ const matchWithoutLocale = filename.match(/^(.+)\.(mdx|vxjson)$/);
739
+
740
+ if (localeSuffix && localeSuffix.extension !== 'json') {
741
+ name = localeSuffix.base;
742
+ locale = localeSuffix.locale;
743
+ } else if (matchWithoutLocale) {
744
+ name = matchWithoutLocale[1];
745
+ // Use default locale from sites config instead of hardcoded 'en'
746
+ locale = this.contentIndex.getDefaultLocale('');
747
+
748
+ console.log(`Found file without locale suffix: ${filename}`);
749
+ // Rename file to include locale suffix
750
+ const extension = matchWithoutLocale[2];
751
+ const newFilename = `${name}.${locale}.${extension}`;
752
+ const newFilePath = join(dirname(filePath), newFilename);
753
+ console.log(`Will rename to: ${newFilename} at ${newFilePath}`);
754
+
755
+ // Check if target file already exists
756
+ try {
757
+ await access(newFilePath);
758
+
759
+ // Target file exists, skip renaming to avoid conflict
760
+ console.warn(`Cannot rename ${filename} to ${newFilename}: target file already exists`);
761
+ } catch {
762
+ // Target file doesn't exist, safe to rename
763
+ console.log(`Target file doesn't exist, proceeding with rename`);
764
+ try {
765
+ await rename(filePath, newFilePath);
766
+ console.log(`Successfully renamed ${filename} to ${newFilename}`);
767
+
768
+ // Update filePath to the new path for further processing
769
+ filePath = newFilePath;
770
+
771
+ // Update relativePath and parts for the new file path
772
+ relativePath = filePath.replace(`${this.absoluteContentRoot}/`, '');
773
+ parts = relativePath.split('/');
774
+
775
+ bytesRead = await readFilePrefix(filePath, buffer);
776
+ } catch (renameError) {
777
+ console.error(`Failed to rename ${filename}:`, renameError);
778
+ // Continue processing with original file
779
+ bytesRead = await readFilePrefix(filePath, buffer);
780
+ }
781
+ }
782
+ }
783
+
784
+ // Parse content based on file type
785
+ if (filePath.endsWith('.mdx')) {
786
+ parsedData = parse4KBMDX(buffer, bytesRead);
787
+ } else {
788
+ parsedData = VXJSON.parse4KB(buffer, bytesRead);
789
+ }
790
+ } else if (parts[0] === 'data') {
791
+ // Data collection entry: data/{collection}/{name}.{locale}.json
792
+ kind = 'data';
793
+ collection = parts[1];
794
+
795
+ const filename = parts[parts.length - 1];
796
+ // Extract name and locale from filename: testimonial.en.json -> name: testimonial, locale: en.
797
+ // The locale grammar is the shared one (content-path.ts).
798
+ const localeSuffix = parseLocaleFilename(filename);
799
+ if (localeSuffix?.extension === 'json') {
800
+ name = localeSuffix.base;
801
+ locale = localeSuffix.locale;
802
+ }
803
+
804
+ // Parse JSON to get ID, metadata, and data
805
+ const content = textDecoder.decode(buffer.subarray(0, bytesRead));
806
+ try {
807
+ const jsonData = JSON.parse(content);
808
+ parsedData = {
809
+ id: jsonData.id,
810
+ type: 'json',
811
+ created: jsonData.created,
812
+ modified: jsonData.modified,
813
+ publishAt: jsonData.publishAt,
814
+ unpublishAt: jsonData.unpublishAt,
815
+ meta: jsonData.meta || { title: name || 'Untitled' },
816
+ data: jsonData.data,
817
+ name,
818
+ };
819
+ } catch (error) {
820
+ console.error(`Failed to parse JSON data file ${filePath}: ${messageOf(error)}`);
821
+ this.recordIndexProblem(filePath, 'malformed-json', messageOf(error));
822
+ return null;
823
+ }
824
+ } else {
825
+ kind = 'page';
826
+ site = parts[0];
827
+ collection = parts[1];
828
+
829
+ // Build pathname from file path. Accepts both .vxjson (Puck pages) and
830
+ // .mdx (mdx-type pages) so consumers without a separate `mdxPages`
831
+ // path can colocate .mdx docs alongside Puck pages under
832
+ // `{contentRoot}/{site}/{collection}/...`. When `mdxPages` IS set
833
+ // on a site in sites.json, .mdx files are served from that
834
+ // separate path (handled in the `absoluteMdxPagesRoot` branch
835
+ // above) and won't reach this branch.
836
+ const pathParts = parts.slice(2); // Remove site/collection
837
+ const filename = pathParts[pathParts.length - 1];
838
+ // One grammar with the header parser and every other reader (content-path.ts).
839
+ // A page file with no parseable locale suffix is NOT content: indexing it
840
+ // under the fallback locale filed it with no pathname at all, invisible to
841
+ // every pathname lookup while still occupying that locale slot. parseFilePath
842
+ // (the reindex path) has always refused these — now both halves agree.
843
+ const localeSuffix = filename ? parseLocaleFilename(filename) : null;
844
+ if (!localeSuffix || localeSuffix.extension === 'json') {
845
+ const message = unreadablePageLocaleMessage(filename ?? relativePath);
846
+ console.warn(`Skipping ${filePath}: ${message}`);
847
+ this.recordIndexProblem(filePath, 'unsupported-locale-path', message);
848
+ return null;
849
+ }
850
+ locale = localeSuffix.locale;
851
+ // Replace filename with basename
852
+ pathParts[pathParts.length - 1] = localeSuffix.base;
853
+ // index files map to parent: /index -> /, /foo/index -> /foo
854
+ pathname =
855
+ pathParts[pathParts.length - 1] === 'index'
856
+ ? `/${pathParts.slice(0, -1).join('/')}`
857
+ : `/${pathParts.join('/')}`;
858
+
859
+ // Parse format-appropriately. parse4KBMDX reads frontmatter from the
860
+ // MDX header; VXJSON.parse4KB reads the leading JSON metadata.
861
+ if (filePath.endsWith('.mdx')) {
862
+ parsedData = parse4KBMDX(buffer, bytesRead);
863
+ } else {
864
+ parsedData = VXJSON.parse4KB(buffer, bytesRead);
865
+ }
866
+ }
867
+
868
+ // Check if the file is missing required fields
869
+ const needsRepair = !parsedData.id || !parsedData.created || !parsedData.modified;
870
+
871
+ // Extract or generate ID
872
+ const id = parsedData.id || generateContentId();
873
+
874
+ // Build LocaleManifest for this specific locale
875
+ const localeVersion: LocaleVersion = {
876
+ locale,
877
+ etag: '', // Will be filled below
878
+ created: parsedData.created || new Date().toISOString(),
879
+ modified: parsedData.modified || new Date().toISOString(),
880
+ ...(parsedData.publishAt && { publishAt: parsedData.publishAt }),
881
+ ...(parsedData.unpublishAt && { unpublishAt: parsedData.unpublishAt }),
882
+ ...(pathname && { pathname }),
883
+ ...(parsedData.previousPathnames && { previousPathnames: parsedData.previousPathnames }),
884
+ ...(name && { name }),
885
+ meta: parsedData.meta || { title: name || 'Untitled' },
886
+ sourcePath: filePath,
887
+ };
888
+
889
+ // Build ContentManifest (without content)
890
+ const manifest: ContentManifest = {
891
+ id,
892
+ type: parsedData.type || (filePath.endsWith('.mdx') ? 'mdx' : filePath.endsWith('.json') ? 'json' : 'puck'),
893
+ kind,
894
+ site,
895
+ collection,
896
+ locales: {
897
+ [locale]: localeVersion,
898
+ },
899
+ };
900
+
901
+ // If we have full content, parse it and compute etags
902
+ let content: ContentData | undefined;
903
+
904
+ // Check if we need to repair the file first (missing required fields)
905
+ if (needsRepair) {
906
+ // Perform repair and get the repaired content
907
+ const repairedData = await this.performReadRepair(filePath, manifest);
908
+ if (repairedData) {
909
+ content = repairedData.content;
910
+ localeVersion.etag = repairedData.etag;
911
+ localeVersion.modified = repairedData.modified;
912
+ return { manifest, locale, localeVersion, bytesRead, content };
913
+ }
914
+ // Repair failed, skip this file
915
+ console.error(`Failed to repair ${filePath}, skipping`);
916
+ this.recordIndexProblem(filePath, 'repair-failed', 'Read-repair failed');
917
+ return null;
918
+ }
919
+
920
+ if (
921
+ bytesRead < 4096 ||
922
+ (filePath.endsWith('.vxjson') && buffer[bytesRead - 1] === 0x7d) ||
923
+ (filePath.endsWith('.json') && buffer[bytesRead - 1] === 0x7d)
924
+ ) {
925
+ // We have the full content
926
+ if (filePath.endsWith('.mdx')) {
927
+ const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
928
+ const { content: mdx } = matter(fullContent, {});
929
+ content = { mdx };
930
+ } else if (filePath.endsWith('.json')) {
931
+ // Data collection JSON file
932
+ const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
933
+ const jsonData = JSON.parse(fullContent);
934
+ content = { data: jsonData.data };
935
+ } else {
936
+ const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
937
+ const data = JSON.parse(fullContent);
938
+ content = data.content || {};
939
+ }
940
+
941
+ // Calculate etags from the buffer (only use valid bytes)
942
+ const validBuffer = buffer.subarray(0, bytesRead);
943
+
944
+ if (filePath.endsWith('.mdx')) {
945
+ const etags = calculateEtagsFromMdxBuffer(validBuffer, parsedData.contentStartPos || -1);
946
+ localeVersion.etag = `${etags.metaEtag}.${etags.contentEtag}`;
947
+ } else if (filePath.endsWith('.json')) {
948
+ // For data files, use simple etag (hash entire buffer)
949
+ // Data files are typically small and don't need separate meta/content etags
950
+ localeVersion.etag = VXJSON.calculateSimpleEtag(validBuffer);
951
+ } else {
952
+ const etagResult = VXJSON.calculateETags(validBuffer);
953
+
954
+ if (!etagResult.success) {
955
+ // Content field is not last or invalid JSON - repair immediately
956
+
957
+ // Perform repair and get the repaired content
958
+ const repairedData = await this.performReadRepair(filePath, manifest);
959
+ if (repairedData) {
960
+ content = repairedData.content;
961
+ localeVersion.etag = repairedData.etag;
962
+ localeVersion.modified = repairedData.modified;
963
+ return { manifest, locale, localeVersion, bytesRead, content };
964
+ }
965
+ // Repair failed, skip this file
966
+ console.error(`Failed to repair ${filePath}, skipping`);
967
+ this.recordIndexProblem(filePath, 'repair-failed', 'Read-repair failed');
968
+ return null;
969
+ }
970
+ localeVersion.etag = etagResult.contentEtag
971
+ ? `${etagResult.metaEtag}.${etagResult.contentEtag}`
972
+ : etagResult.metaEtag;
973
+ }
974
+ }
975
+
976
+ // Return both for indexing
977
+ return { manifest, locale, localeVersion, bytesRead, content };
978
+ } catch (error) {
979
+ console.error(`Error indexing ${originalFilePath}: ${messageOf(error)}`);
980
+ this.recordIndexProblem(originalFilePath, 'parse-failed', messageOf(error));
981
+ return null;
982
+ }
983
+ }
984
+
985
+ /**
986
+ * Perform read-repair by writing back the file with missing fields
987
+ * This ensures stable IDs and timestamps across restarts
988
+ */
989
+ private async performReadRepair(
990
+ filePath: string,
991
+ manifest: ContentManifest,
992
+ ): Promise<{
993
+ content: ContentData;
994
+ etag: string;
995
+ modified: string;
996
+ } | null> {
997
+ try {
998
+ const now = new Date().toISOString();
999
+ let needsWrite = false;
1000
+
1001
+ if (manifest.type === 'mdx') {
1002
+ // Read the full MDX file
1003
+ const content = await readFile(filePath, 'utf-8');
1004
+ const parsed = matter(content, {});
1005
+
1006
+ // Check for missing fields
1007
+ if (!parsed.data.id) {
1008
+ parsed.data.id = manifest.id;
1009
+ needsWrite = true;
1010
+ }
1011
+ if (!parsed.data.created) {
1012
+ parsed.data.created = now;
1013
+ needsWrite = true;
1014
+ }
1015
+ if (!parsed.data.modified) {
1016
+ parsed.data.modified = now;
1017
+ needsWrite = true;
1018
+ }
1019
+
1020
+ if (needsWrite) {
1021
+ // Write back with updated frontmatter. Pass the parsed file
1022
+ // object, not the body string: stringify re-parses string inputs
1023
+ // through gray-matter's memo cache, which is a plain object — a
1024
+ // body equal to an Object.prototype member name ('toString',
1025
+ // 'valueOf', …) reads the prototype function back and crashes.
1026
+ // Same cache-opt-out rule as the matter(..., {}) calls above.
1027
+ const updatedContent = matter.stringify(parsed, parsed.data);
1028
+ await writeFile(filePath, updatedContent);
1029
+ console.log(`Repaired MDX file: ${filePath} (added missing fields)`);
1030
+
1031
+ // Calculate ETags for the repaired MDX file
1032
+ const repairedBuffer = Buffer.from(updatedContent, 'utf-8') as Uint8Array;
1033
+ const contentStartPos = updatedContent.indexOf('\n---\n') + 5; // Position after frontmatter
1034
+ const etags = calculateEtagsFromMdxBuffer(repairedBuffer, contentStartPos);
1035
+ const etag = `${etags.metaEtag}.${etags.contentEtag}`;
1036
+
1037
+ // Return the repaired data. Strip leading newlines so the
1038
+ // body matches what the author wrote — see `readLocaleFile`.
1039
+ return {
1040
+ content: { mdx: parsed.content.replace(/^\n+/, '') },
1041
+ etag,
1042
+ modified: parsed.data.modified || now,
1043
+ };
1044
+ }
1045
+ } else {
1046
+ // Read the full JSON file
1047
+ const content = await readFile(filePath, 'utf-8');
1048
+ const data: VXJSONFile = JSON.parse(content);
1049
+
1050
+ // Check for missing fields
1051
+ if (!data.id) {
1052
+ data.id = manifest.id;
1053
+ needsWrite = true;
1054
+ }
1055
+ if (!data.created) {
1056
+ data.created = now;
1057
+ needsWrite = true;
1058
+ }
1059
+ if (!data.modified) {
1060
+ data.modified = now;
1061
+ needsWrite = true;
1062
+ }
1063
+
1064
+ // Always rewrite VXJSON files during repair to ensure correct field order
1065
+ needsWrite = true;
1066
+
1067
+ if (needsWrite) {
1068
+ // Write back with VXJSON format
1069
+ const vxjsonData: VXJSONFile = {
1070
+ id: data.id,
1071
+ type: data.type,
1072
+ created: data.created,
1073
+ modified: data.modified,
1074
+ publishAt: data.publishAt,
1075
+ unpublishAt: data.unpublishAt,
1076
+ previousPathnames: data.previousPathnames,
1077
+ meta: data.meta || {},
1078
+ content: data.content || {},
1079
+ };
1080
+ const repairedJson = VXJSON.serialize(vxjsonData);
1081
+ await writeFile(filePath, repairedJson);
1082
+ console.log(`Repaired VXJSON file: ${filePath} (fixed field order or added missing fields)`);
1083
+ // Return the repaired data
1084
+
1085
+ // Calculate ETags from the repaired JSON
1086
+ const repairedBuffer = Buffer.from(repairedJson, 'utf-8') as Uint8Array;
1087
+ const etagResult = VXJSON.calculateETags(repairedBuffer);
1088
+
1089
+ if (!etagResult.success) {
1090
+ console.error(`Failed to calculate ETags after repair: ${filePath}`);
1091
+ return null;
1092
+ }
1093
+
1094
+ const etag = etagResult.contentEtag
1095
+ ? `${etagResult.metaEtag}.${etagResult.contentEtag}`
1096
+ : etagResult.metaEtag;
1097
+
1098
+ // Return the complete repaired data
1099
+ return {
1100
+ content: vxjsonData.content,
1101
+ etag,
1102
+ modified: vxjsonData.modified,
1103
+ };
1104
+ }
1105
+ }
1106
+
1107
+ // For MDX or no repair needed, return null
1108
+ return null;
1109
+ } catch (error) {
1110
+ console.error(`Failed to perform read-repair on ${filePath}:`, error);
1111
+ return null;
1112
+ }
1113
+ }
1114
+
1115
+ private async scanContentFiles(): Promise<string[]> {
1116
+ const files: string[] = [];
1117
+ const contentRoot = this.absoluteContentRoot;
1118
+
1119
+ async function scan(dir: string, inDataDir = false) {
1120
+ try {
1121
+ const entries = await readdir(dir, { withFileTypes: true });
1122
+ for (const entry of entries) {
1123
+ const fullPath = join(dir, entry.name);
1124
+ if (entry.isDirectory()) {
1125
+ // Check if we're entering the data/ directory
1126
+ const isDataDir = dir === contentRoot && entry.name === 'data';
1127
+ await scan(fullPath, inDataDir || isDataDir);
1128
+ } else if (entry.isFile()) {
1129
+ // Include .vxjson and .mdx files everywhere
1130
+ // Include .json files only in the data/ directory
1131
+ if (entry.name.endsWith('.vxjson') || entry.name.endsWith('.mdx')) {
1132
+ files.push(fullPath);
1133
+ } else if (inDataDir && entry.name.endsWith('.json')) {
1134
+ files.push(fullPath);
1135
+ }
1136
+ }
1137
+ }
1138
+ } catch {
1139
+ // Directory doesn't exist yet
1140
+ }
1141
+ }
1142
+
1143
+ await scan(this.absoluteContentRoot);
1144
+
1145
+ // Also scan mdxPagesRoot for .mdx files when the second root is configured.
1146
+ // Supports projects that store mdx-type pages outside the main content
1147
+ // tree (the rendering pipeline that consumes them is the project's choice).
1148
+ //
1149
+ // Skip the second scan when mdxPagesRoot is the same as contentRoot OR
1150
+ // nested inside it — the first scan already walked those files, and a
1151
+ // second pass would push every `.mdx` onto `files` twice. The nested case
1152
+ // is the documented Starlight pattern (`contentRoot: './src/content'`,
1153
+ // `mdxPagesRoot: './src/content/docs'`), so the prefix check matters in
1154
+ // practice.
1155
+ if (
1156
+ this.absoluteMdxPagesRoot &&
1157
+ this.absoluteMdxPagesRoot !== this.absoluteContentRoot &&
1158
+ !this.absoluteMdxPagesRoot.startsWith(`${this.absoluteContentRoot}/`)
1159
+ ) {
1160
+ async function scanMdxPages(dir: string) {
1161
+ try {
1162
+ const entries = await readdir(dir, { withFileTypes: true });
1163
+ for (const entry of entries) {
1164
+ const fullPath = join(dir, entry.name);
1165
+ if (entry.isDirectory()) {
1166
+ await scanMdxPages(fullPath);
1167
+ } else if (entry.isFile() && entry.name.endsWith('.mdx')) {
1168
+ files.push(fullPath);
1169
+ }
1170
+ }
1171
+ } catch {
1172
+ // Directory doesn't exist yet
1173
+ }
1174
+ }
1175
+ await scanMdxPages(this.absoluteMdxPagesRoot);
1176
+ }
1177
+
1178
+ return files;
1179
+ }
1180
+
1181
+ /**
1182
+ * Why a page of `type` cannot have `pathname` in `locale` where `getFilePath` puts it: an mdx
1183
+ * page lives in the MDX pages folder when one is configured, where a default-language path may
1184
+ * not start with a language folder (see `checkMdxPagesPathname`).
1185
+ */
1186
+ private mdxPagesPathnameRefusal(type: ContentType, pathname: string, locale: string): PathnameRefusal | null {
1187
+ if (type !== 'mdx' || !this.absoluteMdxPagesRoot) return null;
1188
+ return checkMdxPagesPathname(pathname, locale, {
1189
+ defaultLocale: this.mdxPagesDefaultLocale,
1190
+ locales: this.availableLocales,
1191
+ });
1192
+ }
1193
+
1194
+ private getFilePath(manifest: ContentIdentity, { locale, name, pathname }: LocalePathData): string {
1195
+ if (manifest.kind === 'fragment') {
1196
+ const ext = manifest.type === 'mdx' ? 'mdx' : 'vxjson';
1197
+ return join(this.absoluteContentRoot, 'fragments', manifest.collection, `${name}.${locale}.${ext}`);
1198
+ }
1199
+ if (manifest.kind === 'data') {
1200
+ return join(this.absoluteContentRoot, 'data', manifest.collection, `${name}.${locale}.json`);
1201
+ }
1202
+ if (manifest.kind === 'page' && pathname) {
1203
+ // For pages, derive path from pathname
1204
+ const basePath = pathname.replace(/^\//, '').replace(/\/$/, '') || 'index';
1205
+
1206
+ // mdx-type pages live under absoluteMdxPagesRoot when configured.
1207
+ // The locale appears as a directory segment for non-default locales;
1208
+ // the default locale's files live at the root with no locale prefix.
1209
+ if (manifest.type === 'mdx' && this.absoluteMdxPagesRoot) {
1210
+ return locale === this.mdxPagesDefaultLocale
1211
+ ? join(this.absoluteMdxPagesRoot, `${basePath}.mdx`)
1212
+ : join(this.absoluteMdxPagesRoot, locale, `${basePath}.mdx`);
1213
+ }
1214
+
1215
+ // Pages live under contentRoot/{site}/{collection}. When type:'mdx'
1216
+ // and no `mdxPages` path is configured for the site, the .mdx files
1217
+ // sit here alongside the .vxjson Puck pages — the layout chosen
1218
+ // when sites.json doesn't declare a separate `mdxPages` path.
1219
+ if (manifest.site) {
1220
+ const ext = manifest.type === 'mdx' ? 'mdx' : 'vxjson';
1221
+ return join(this.absoluteContentRoot, manifest.site, manifest.collection, `${basePath}.${locale}.${ext}`);
1222
+ }
1223
+ }
1224
+ throw new Error(`Invalid manifest: ${JSON.stringify(manifest, null, 2)}`);
1225
+ }
1226
+
1227
+ /**
1228
+ * Parse a file path back into its components for checking against the path index
1229
+ * Returns null if the path doesn't match expected patterns
1230
+ */
1231
+ parseFilePath(filePath: string): ContentPathLayout | null {
1232
+ // Files under mdxPagesRoot are kind:'page' + type:'mdx' regardless of
1233
+ // their position relative to absoluteContentRoot. Mirror the parsing
1234
+ // performed in parseFileHeaderWithRepair so both code paths agree on
1235
+ // the derived (pathname, locale) tuple.
1236
+ if (this.absoluteMdxPagesRoot && filePath.startsWith(`${this.absoluteMdxPagesRoot}/`)) {
1237
+ const mdxRelativePath = filePath.replace(`${this.absoluteMdxPagesRoot}/`, '');
1238
+ const mdxParts = mdxRelativePath.split('/');
1239
+ const mdxFilename = mdxParts[mdxParts.length - 1];
1240
+ let locale: string;
1241
+ let pathname: string;
1242
+
1243
+ const noLocaleMatch = mdxFilename.match(/^(.+)\.mdx$/);
1244
+ if (!noLocaleMatch) return null;
1245
+ mdxParts[mdxParts.length - 1] = noLocaleMatch[1];
1246
+
1247
+ // Membership-based locale detection — mirrors parseFileHeaderWithRepair
1248
+ // so both paths classify the same file identically.
1249
+ if (mdxParts.length > 1 && this.availableLocales.has(mdxParts[0])) {
1250
+ locale = mdxParts[0];
1251
+ const slugParts = mdxParts.slice(1);
1252
+ pathname =
1253
+ slugParts[slugParts.length - 1] === 'index'
1254
+ ? `/${slugParts.slice(0, -1).join('/')}`
1255
+ : `/${slugParts.join('/')}`;
1256
+ } else {
1257
+ locale = this.mdxPagesDefaultLocale;
1258
+ pathname =
1259
+ mdxParts[mdxParts.length - 1] === 'index' ? `/${mdxParts.slice(0, -1).join('/')}` : `/${mdxParts.join('/')}`;
1260
+ }
1261
+
1262
+ return {
1263
+ kind: 'page',
1264
+ site: this.mdxPagesSite,
1265
+ collection: this.mdxPagesCollection,
1266
+ pathname,
1267
+ locale,
1268
+ };
1269
+ }
1270
+
1271
+ // Everything under the primary content root shares ONE grammar with the
1272
+ // header parser and every other reader (content-path.ts) — including the
1273
+ // `index` -> parent-pathname rule this method used to skip. Missing it made
1274
+ // reindex look up `/index`, never find the entry the indexer had filed under
1275
+ // `/`, and leave a deleted index page in the index forever.
1276
+ return parseContentPathLayout(filePath.replace(`${this.absoluteContentRoot}/`, ''));
1277
+ }
1278
+
1279
+ async getContent(id: string): Promise<ContentEntry | null> {
1280
+ // Get manifest for this ID
1281
+ const manifest = this.contentIndex.getManifest(id);
1282
+ if (!manifest) {
1283
+ return null;
1284
+ }
1285
+
1286
+ // Read all locale files in parallel
1287
+ const readPromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {
1288
+ const filePath = this.getFilePath(manifest, localeVersion);
1289
+ const content = await this.readLocaleFile(filePath, localeVersion.locale);
1290
+ return { localeVersion, content };
1291
+ });
1292
+
1293
+ const results = await Promise.all(readPromises);
1294
+
1295
+ // Build locales with content
1296
+ const locales: Record<string, LocaleVersion & ContentProp> = {};
1297
+ for (const { localeVersion, content } of results) {
1298
+ if (content) {
1299
+ locales[localeVersion.locale] = {
1300
+ ...localeVersion,
1301
+ etag: content.etag, // Use fresh etag from file, not stale manifest etag
1302
+ content: content.content,
1303
+ };
1304
+ }
1305
+ }
1306
+
1307
+ return {
1308
+ id: manifest.id,
1309
+ site: manifest.site,
1310
+ collection: manifest.collection,
1311
+ type: manifest.type,
1312
+ kind: manifest.kind,
1313
+ locales,
1314
+ };
1315
+ }
1316
+
1317
+ async getLocalized(id: string, locale: string): Promise<LocalizedEntry | null> {
1318
+ // Get manifest for this ID
1319
+ const manifest = this.contentIndex.getManifest(id);
1320
+ if (!manifest) {
1321
+ // File might have been added after indexing - try reindexing
1322
+ await this.reindex();
1323
+
1324
+ // Try again with updated index
1325
+ const updatedManifest = this.contentIndex.getManifest(id);
1326
+ if (!updatedManifest?.locales[locale]) {
1327
+ return null;
1328
+ }
1329
+
1330
+ return this.getLocalized(id, locale);
1331
+ }
1332
+
1333
+ // Check if this locale exists
1334
+ const localeVersion = manifest.locales[locale];
1335
+ if (!localeVersion) {
1336
+ return null;
1337
+ }
1338
+
1339
+ // Read the locale-specific file
1340
+ const filePath = this.getFilePath(manifest, localeVersion);
1341
+ const localeData = await this.readLocaleFile(filePath, locale);
1342
+ if (!localeData) {
1343
+ return null;
1344
+ }
1345
+
1346
+ // Build LocalizedEntry
1347
+ return {
1348
+ id: manifest.id,
1349
+ site: manifest.site,
1350
+ collection: manifest.collection,
1351
+ type: manifest.type,
1352
+ kind: manifest.kind,
1353
+ localized: {
1354
+ ...localeVersion,
1355
+ etag: localeData.etag, // Use fresh etag from file, not stale manifest etag
1356
+ content: localeData.content,
1357
+ },
1358
+ };
1359
+ }
1360
+
1361
+ private async readLocaleFile(filePath: string, locale: string): Promise<LocaleFileData | null> {
1362
+ try {
1363
+ const buffer = (await readFile(filePath)) as Uint8Array;
1364
+ const content = textDecoder.decode(buffer);
1365
+
1366
+ if (filePath.endsWith('.mdx')) {
1367
+ const { data: frontmatter, content: rawBody } = matter(content, {});
1368
+ // gray-matter leaves the blank line after the closing `---` on
1369
+ // the body. Strip leading newlines so the round-trip matches the
1370
+ // body the author wrote.
1371
+ const body = rawBody.replace(/^\n+/, '');
1372
+
1373
+ // Calculate etags from the file buffer
1374
+ const contentPos = findMdxContentStartPosition(buffer);
1375
+
1376
+ const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
1377
+ const etag = `${etags.metaEtag}.${etags.contentEtag}`;
1378
+
1379
+ // Extract special fields from frontmatter, everything else is metadata
1380
+ const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
1381
+
1382
+ // Body-only — frontmatter is server-owned and surfaced separately
1383
+ // via `meta` / `created` / `modified`. Returning the full file here
1384
+ // would let the editor round-trip the YAML block as body text, which
1385
+ // duplicates the frontmatter on disk when content is inserted above
1386
+ // it (proven on assets.mdx, 2026-05-11).
1387
+ const result: LocaleFileData = {
1388
+ locale,
1389
+ etag,
1390
+ created: created,
1391
+ modified: modified,
1392
+ meta: metaFields as ContentMeta,
1393
+ content: { mdx: body },
1394
+ };
1395
+
1396
+ // Only add publish dates if they exist
1397
+ if (frontmatter.publishAt !== undefined) {
1398
+ result.publishAt = frontmatter.publishAt;
1399
+ }
1400
+ if (frontmatter.unpublishAt !== undefined) {
1401
+ result.unpublishAt = frontmatter.unpublishAt;
1402
+ }
1403
+
1404
+ return result;
1405
+ }
1406
+
1407
+ // Parse JSON data first to determine type
1408
+ const data = JSON.parse(content);
1409
+
1410
+ // Handle JSON data files (type: 'json') separately - they use simple etag
1411
+ if (data.type === 'json') {
1412
+ const etag = VXJSON.calculateSimpleEtag(buffer);
1413
+
1414
+ const result: LocaleFileData = {
1415
+ locale,
1416
+ etag,
1417
+ created: data.created,
1418
+ modified: data.modified,
1419
+ meta: data.meta || {},
1420
+ content: { data: data.data || {} },
1421
+ };
1422
+
1423
+ // Only add optional fields if they exist
1424
+ if (data.publishAt !== undefined) {
1425
+ result.publishAt = data.publishAt;
1426
+ }
1427
+ if (data.unpublishAt !== undefined) {
1428
+ result.unpublishAt = data.unpublishAt;
1429
+ }
1430
+
1431
+ return result;
1432
+ }
1433
+
1434
+ // For VXJSON (puck pages), calculate ETags with meta/content split
1435
+ const etagResult = VXJSON.calculateETags(buffer);
1436
+
1437
+ if (!etagResult.success) {
1438
+ // File needs repair - parse it and rewrite in correct format
1439
+ const repairedData: VXJSONFile = {
1440
+ id: data.id,
1441
+ type: data.type,
1442
+ created: data.created,
1443
+ modified: data.modified,
1444
+ publishAt: data.publishAt,
1445
+ unpublishAt: data.unpublishAt,
1446
+ previousPathnames: data.previousPathnames,
1447
+ meta: data.meta || {},
1448
+ content: data.content || {},
1449
+ };
1450
+
1451
+ // Rewrite file with correct format
1452
+ const repairedJson = VXJSON.serialize(repairedData);
1453
+ await writeFile(filePath, repairedJson);
1454
+
1455
+ // Recalculate ETags from repaired buffer
1456
+ const repairedBuffer = Buffer.from(repairedJson, 'utf-8') as Uint8Array;
1457
+ const repairedEtagResult = VXJSON.calculateETags(repairedBuffer);
1458
+
1459
+ if (!repairedEtagResult.success) {
1460
+ throw new Error(`Failed to repair VXJSON file: ${filePath}`);
1461
+ }
1462
+
1463
+ const etag = repairedEtagResult.contentEtag
1464
+ ? `${repairedEtagResult.metaEtag}.${repairedEtagResult.contentEtag}`
1465
+ : repairedEtagResult.metaEtag;
1466
+
1467
+ console.log(`Repaired VXJSON file: ${filePath}`);
1468
+
1469
+ const result: LocaleFileData = {
1470
+ locale,
1471
+ etag,
1472
+ created: data.created,
1473
+ modified: data.modified,
1474
+ meta: data.meta || {},
1475
+ content: data.content || {},
1476
+ };
1477
+
1478
+ // Only add optional fields if they exist
1479
+ if (data.publishAt !== undefined) {
1480
+ result.publishAt = data.publishAt;
1481
+ }
1482
+ if (data.unpublishAt !== undefined) {
1483
+ result.unpublishAt = data.unpublishAt;
1484
+ }
1485
+ if (data.previousPathnames !== undefined) {
1486
+ result.previousPathnames = data.previousPathnames;
1487
+ }
1488
+
1489
+ return result;
1490
+ }
1491
+
1492
+ const etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1493
+
1494
+ const result: LocaleFileData = {
1495
+ locale,
1496
+ etag,
1497
+ created: data.created,
1498
+ modified: data.modified,
1499
+ meta: data.meta || {},
1500
+ content: data.content || {},
1501
+ };
1502
+
1503
+ // Only add optional fields if they exist
1504
+ if (data.publishAt !== undefined) {
1505
+ result.publishAt = data.publishAt;
1506
+ }
1507
+ if (data.unpublishAt !== undefined) {
1508
+ result.unpublishAt = data.unpublishAt;
1509
+ }
1510
+ if (data.previousPathnames !== undefined) {
1511
+ result.previousPathnames = data.previousPathnames;
1512
+ }
1513
+
1514
+ return result;
1515
+ } catch {
1516
+ return null;
1517
+ }
1518
+ }
1519
+
1520
+ async createContent(data: CreateContentInput): Promise<CreateResult> {
1521
+ // Use shared validation
1522
+ const validation = validateCreateContent(data, this.sites, this.fragments, this.data);
1523
+ if (!validation.valid) {
1524
+ return {
1525
+ success: false,
1526
+ reason: validation.reason,
1527
+ error: validation.error ? new Error(validation.error) : undefined,
1528
+ existingId: validation.existingId,
1529
+ field: validation.field,
1530
+ };
1531
+ }
1532
+
1533
+ if (data.kind === 'page') {
1534
+ for (const [locale, localeData] of Object.entries(data.locales)) {
1535
+ const refused = this.mdxPagesPathnameRefusal(data.type, localeData.pathname ?? '', locale);
1536
+ if (refused) {
1537
+ return { success: false, reason: refused.reason, error: new Error(refused.error), field: 'pathname' };
1538
+ }
1539
+ }
1540
+ }
1541
+
1542
+ const id = generateContentId();
1543
+ const now = data.created || new Date().toISOString();
1544
+
1545
+ try {
1546
+ // Build the manifest with all locales
1547
+ const manifest: ContentManifest = {
1548
+ id,
1549
+ type: data.type,
1550
+ kind: data.kind,
1551
+ site: data.site,
1552
+ collection: data.collection,
1553
+ locales: {},
1554
+ };
1555
+
1556
+ const contentCache: Record<string, ContentData> = {};
1557
+
1558
+ // Create files for each locale
1559
+ for (const [locale, localeData] of Object.entries(data.locales)) {
1560
+ const content = localeData.content;
1561
+
1562
+ // Build metadata with required title
1563
+ const title = localeData.meta?.title || data.meta?.title;
1564
+ if (!title) {
1565
+ return {
1566
+ success: false,
1567
+ reason: 'write_error',
1568
+ error: new Error('Title is required in metadata'),
1569
+ };
1570
+ }
1571
+
1572
+ // Build complete metadata
1573
+ const meta: ContentMeta = {
1574
+ title,
1575
+ ...data.meta,
1576
+ ...localeData.meta,
1577
+ };
1578
+
1579
+ const fileData: VXJSONFile = {
1580
+ id,
1581
+ type: data.type,
1582
+ created: now,
1583
+ modified: now,
1584
+ publishAt:
1585
+ localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,
1586
+ unpublishAt:
1587
+ localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,
1588
+ meta,
1589
+ content,
1590
+ };
1591
+
1592
+ // Use the proper getFilePath method
1593
+ const filePath = this.getFilePath(manifest, { locale, name: data.name, pathname: localeData.pathname });
1594
+
1595
+ // Ensure directory exists
1596
+ await mkdir(dirname(filePath), { recursive: true });
1597
+
1598
+ // Write file and calculate etag from the serialized content
1599
+ let etag: string;
1600
+
1601
+ if (data.type === 'mdx') {
1602
+ // Write MDX with frontmatter - flatten metadata fields
1603
+ const frontmatterData = {
1604
+ id,
1605
+ created: now,
1606
+ modified: now,
1607
+ ...(localeData.publishAt && { publishAt: localeData.publishAt }),
1608
+ ...(localeData.unpublishAt && { unpublishAt: localeData.unpublishAt }),
1609
+ ...meta, // Spread metadata fields directly, not nested
1610
+ };
1611
+
1612
+ const mdxContent = serializeMdxWithFrontmatter(frontmatterData, content.mdx || '');
1613
+ await writeFile(filePath, mdxContent);
1614
+
1615
+ // For MDX, calculate etags from the serialized content
1616
+ const mdxBuffer = new TextEncoder().encode(mdxContent);
1617
+ // For MDX, all frontmatter is metadata, content starts after ---
1618
+ const contentStartMarker = new TextEncoder().encode('---\n\n');
1619
+ let contentPos = -1;
1620
+ for (let i = 0; i <= mdxBuffer.length - contentStartMarker.length; i++) {
1621
+ let match = true;
1622
+ for (let j = 0; j < contentStartMarker.length; j++) {
1623
+ if (mdxBuffer[i + j] !== contentStartMarker[j]) {
1624
+ match = false;
1625
+ break;
1626
+ }
1627
+ }
1628
+ if (match) {
1629
+ contentPos = i + contentStartMarker.length;
1630
+ break;
1631
+ }
1632
+ }
1633
+ const etags = calculateEtagsFromMdxBuffer(mdxBuffer, contentPos);
1634
+ etag = `${etags.metaEtag}.${etags.contentEtag}`;
1635
+ } else if (data.type === 'json') {
1636
+ // Data files use "data" field instead of "content"
1637
+ const dataFileContent = {
1638
+ id,
1639
+ type: 'json',
1640
+ created: now,
1641
+ modified: now,
1642
+ ...(localeData.publishAt &&
1643
+ typeof localeData.publishAt === 'string' && { publishAt: localeData.publishAt }),
1644
+ ...(localeData.unpublishAt &&
1645
+ typeof localeData.unpublishAt === 'string' && { unpublishAt: localeData.unpublishAt }),
1646
+ meta,
1647
+ data: content.data || {},
1648
+ };
1649
+
1650
+ const jsonContent = JSON.stringify(sortKeys(dataFileContent, { deep: true }), null, '\t');
1651
+ await writeFile(filePath, jsonContent);
1652
+
1653
+ // For data files, use simple etag (hash entire buffer)
1654
+ const jsonBuffer = new TextEncoder().encode(jsonContent);
1655
+ etag = VXJSON.calculateSimpleEtag(jsonBuffer);
1656
+ } else {
1657
+ // VXJSON for pages (puck)
1658
+ const jsonContent = VXJSON.serialize(fileData);
1659
+ const jsonBuffer = new TextEncoder().encode(jsonContent);
1660
+
1661
+ // Calculate etags from the buffer
1662
+ const etagResult = VXJSON.calculateETags(jsonBuffer);
1663
+
1664
+ if (!etagResult.success) {
1665
+ throw new Error(`Invalid VXJSON format when creating content: ${etagResult.error}`);
1666
+ }
1667
+
1668
+ etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1669
+
1670
+ // Write the file
1671
+ await writeFile(filePath, jsonContent);
1672
+ }
1673
+
1674
+ // Build locale manifest using shared function
1675
+ const localeVersion = buildLocaleVersion({
1676
+ locale,
1677
+ etag,
1678
+ created: now,
1679
+ modified: now,
1680
+ meta,
1681
+ kind: data.kind,
1682
+ pathname: data.kind === 'page' ? localeData.pathname : undefined,
1683
+ name: data.kind === 'fragment' || data.kind === 'data' ? data.name : undefined,
1684
+ publishAt:
1685
+ localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,
1686
+ unpublishAt:
1687
+ localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,
1688
+ });
1689
+
1690
+ // Add locale to manifest
1691
+ manifest.locales[locale] = localeVersion;
1692
+ contentCache[locale] = content;
1693
+ }
1694
+
1695
+ // Add each locale to the index
1696
+ for (const localeVersion of localesOf(manifest)) {
1697
+ const { locale } = localeVersion;
1698
+ this.contentIndex.addContent(manifest, localeVersion, contentCache[locale]);
1699
+ }
1700
+
1701
+ return { success: true, id };
1702
+ } catch (error) {
1703
+ return {
1704
+ success: false,
1705
+ reason: 'write_error',
1706
+ error: ensureError(error),
1707
+ };
1708
+ }
1709
+ }
1710
+
1711
+ async updateLocalized(input: UpdateLocaleInput): Promise<UpdateResult> {
1712
+ const { id, locale, data, etag } = input;
1713
+
1714
+ // Get the manifest
1715
+ const manifest = this.contentIndex.getManifest(id);
1716
+ if (!manifest) {
1717
+ return {
1718
+ success: false,
1719
+ reason: 'not_found',
1720
+ };
1721
+ }
1722
+
1723
+ // Get the specific locale manifest
1724
+ const localeVersion = manifest.locales[locale];
1725
+ if (!localeVersion) {
1726
+ return {
1727
+ success: false,
1728
+ reason: 'not_found',
1729
+ };
1730
+ }
1731
+
1732
+ // Get file path and read current content FIRST to get fresh etag
1733
+ const filePath = this.getFilePath(manifest, localeVersion);
1734
+ const current = await this.readLocaleFile(filePath, locale);
1735
+ if (!current) {
1736
+ return {
1737
+ success: false,
1738
+ reason: 'not_found',
1739
+ };
1740
+ }
1741
+
1742
+ // Use fresh etag from file, not stale manifest etag
1743
+ const currentEtag = current.etag;
1744
+
1745
+ // Check etag - data files use simple etags, others use dual etags
1746
+ if (manifest.kind === 'data') {
1747
+ // Data files use simple etag (single hash, no dot separator)
1748
+ // Just compare the full etag directly
1749
+ if (etag !== currentEtag) {
1750
+ return {
1751
+ success: false,
1752
+ reason: 'stale_write',
1753
+ currentEtag,
1754
+ };
1755
+ }
1756
+ } else {
1757
+ // Non-data files use dual etags (meta.content format)
1758
+ const etagParts = parseDualEtag(etag);
1759
+ const currentParts = parseDualEtag(currentEtag);
1760
+
1761
+ if (!etagParts || !currentParts) {
1762
+ return {
1763
+ success: false,
1764
+ reason: 'stale_write',
1765
+ currentEtag,
1766
+ };
1767
+ }
1768
+
1769
+ // Check which parts are being updated
1770
+ const updateScope = analyzeUpdateScope(data);
1771
+ const updatingMeta = (updateScope & UPDATE_SCOPE.META) !== 0;
1772
+ const updatingContent = (updateScope & UPDATE_SCOPE.CONTENT) !== 0;
1773
+
1774
+ // Validate etags for parts being updated
1775
+ if (updatingMeta && etagParts.meta !== currentParts.meta) {
1776
+ return {
1777
+ success: false,
1778
+ reason: 'stale_write',
1779
+ currentEtag,
1780
+ };
1781
+ }
1782
+
1783
+ if (updatingContent && etagParts.content !== currentParts.content) {
1784
+ return {
1785
+ success: false,
1786
+ reason: 'stale_write',
1787
+ currentEtag,
1788
+ };
1789
+ }
1790
+ }
1791
+
1792
+ // Update modified timestamp for any change (metadata or content)
1793
+ let modified: string;
1794
+ if (shouldUpdateModifiedTimestamp(data)) {
1795
+ // Use provided modified timestamp or current time
1796
+ modified = data.modified || new Date().toISOString();
1797
+ } else if (data.modified) {
1798
+ // If modified timestamp is explicitly provided, always use it
1799
+ modified = data.modified;
1800
+ } else {
1801
+ // No changes and no explicit timestamp, keep current
1802
+ modified = current.modified;
1803
+ }
1804
+
1805
+ const {
1806
+ sortedMeta: newMeta,
1807
+ valid: metaValid,
1808
+ error: metaError,
1809
+ } = validateAndPrepareMetadata(applyMetaPatch(current.meta, data.meta ?? {}));
1810
+
1811
+ // Validate new metadata
1812
+ if (!newMeta || !metaValid) {
1813
+ return {
1814
+ success: false,
1815
+ reason: 'write_error',
1816
+ error: new Error(metaError),
1817
+ };
1818
+ }
1819
+
1820
+ // Merge updates
1821
+ const newContent = data.content ? { ...current.content, ...data.content } : current.content;
1822
+
1823
+ // A page's new path is tidied, and refused when it is malformed or another page has it, as a
1824
+ // create's is; the tidied form names the file and keys the page in the site index. An unchanged
1825
+ // path is left alone, so a page keeps a path from before the checks.
1826
+ let pathname = data.pathname;
1827
+ if (pathname !== undefined && pathname !== localeVersion.pathname && manifest.kind === 'page') {
1828
+ // Own-key only: the manifest's site name comes from the on-disk layout
1829
+ // and is never checked against the configured sites, so an inherited key
1830
+ // would reach the calls below.
1831
+ const site = manifest.site && Object.hasOwn(this.sites, manifest.site) ? this.sites[manifest.site] : undefined;
1832
+ const checked = checkPagePathname(site, pathname, locale, id);
1833
+ if (!checked.valid) {
1834
+ return { success: false, reason: checked.reason, error: new Error(checked.error) };
1835
+ }
1836
+ const refused = this.mdxPagesPathnameRefusal(manifest.type, checked.pathname, locale);
1837
+ if (refused) {
1838
+ return { success: false, reason: refused.reason, error: new Error(refused.error) };
1839
+ }
1840
+ pathname = checked.pathname;
1841
+ }
1842
+
1843
+ // A new fragment or data name passes the create's checks. An unchanged name is left alone, so
1844
+ // an entry keeps a name from before the checks.
1845
+ if (
1846
+ data.name !== undefined &&
1847
+ data.name !== localeVersion.name &&
1848
+ (manifest.kind === 'fragment' || manifest.kind === 'data')
1849
+ ) {
1850
+ const entries = manifest.kind === 'fragment' ? this.fragments : this.data;
1851
+ const refused = checkEntryName(
1852
+ manifest.kind,
1853
+ manifest.collection,
1854
+ data.name,
1855
+ (name) =>
1856
+ manifest.kind === 'fragment' ? this.fragments.isFragmentNameValid(name) : this.data.isDataNameValid(name),
1857
+ (name) => entries.getNameConflict(manifest.collection, name, id),
1858
+ );
1859
+ if (refused) {
1860
+ return { success: false, reason: refused.reason, error: new Error(refused.error) };
1861
+ }
1862
+ }
1863
+
1864
+ // Handle pathname changes - track history only for published content
1865
+ const pathnameHistory = buildPathnameHistory(
1866
+ localeVersion.pathname,
1867
+ pathname,
1868
+ isContentPublished({
1869
+ publishAt: resolvePublishDate(data.publishAt, current.publishAt),
1870
+ unpublishAt: resolvePublishDate(data.unpublishAt, current.unpublishAt),
1871
+ }),
1872
+ new Date().toISOString(),
1873
+ );
1874
+
1875
+ try {
1876
+ // Determine the target file path (may be different if pathname or name changed)
1877
+ let targetFilePath = filePath;
1878
+ if (pathname && localeVersion.pathname && pathname !== localeVersion.pathname && manifest.site) {
1879
+ // For pages, calculate new file path based on new pathname
1880
+ const newLocaleVersion: LocaleVersion = {
1881
+ ...localeVersion,
1882
+ pathname,
1883
+ };
1884
+ targetFilePath = this.getFilePath(manifest, newLocaleVersion);
1885
+
1886
+ // Ensure target directory exists
1887
+ await mkdir(dirname(targetFilePath), { recursive: true });
1888
+ } else if (
1889
+ data.name &&
1890
+ localeVersion.name &&
1891
+ data.name !== localeVersion.name &&
1892
+ (manifest.kind === 'fragment' || manifest.kind === 'data')
1893
+ ) {
1894
+ // A fragment's or data entry's name is part of its file path, so a rename moves the file
1895
+ const newLocaleVersion: LocaleVersion = {
1896
+ ...localeVersion,
1897
+ name: data.name,
1898
+ };
1899
+ targetFilePath = this.getFilePath(manifest, newLocaleVersion);
1900
+
1901
+ // Ensure target directory exists
1902
+ await mkdir(dirname(targetFilePath), { recursive: true });
1903
+ }
1904
+
1905
+ // Write updated content
1906
+ if (targetFilePath.endsWith('.mdx')) {
1907
+ // Build frontmatter with special fields and metadata
1908
+ const publishAt = resolvePublishDate(data.publishAt, current.publishAt);
1909
+ const unpublishAt = resolvePublishDate(data.unpublishAt, current.unpublishAt);
1910
+ const frontmatterData = {
1911
+ id: manifest.id,
1912
+ created: current.created,
1913
+ modified,
1914
+ ...(publishAt && { publishAt }),
1915
+ ...(unpublishAt && { unpublishAt }),
1916
+ ...newMeta, // Spread metadata fields directly
1917
+ };
1918
+
1919
+ // Extract just the content part from MDX (remove frontmatter if present)
1920
+ let mdxContentPart = newContent.mdx || '';
1921
+ if (mdxContentPart.startsWith('---')) {
1922
+ // Remove frontmatter if it exists
1923
+ const { content: contentOnly } = matter(mdxContentPart, {});
1924
+ mdxContentPart = contentOnly;
1925
+ }
1926
+
1927
+ // Defensive guard: warn when a frontmatter-shaped block appears
1928
+ // mid-body. The load path strips frontmatter before it reaches the
1929
+ // editor, so this should never occur — if it does, surface it for
1930
+ // investigation instead of silently writing a file with stacked
1931
+ // frontmatter blocks.
1932
+ if (/\n---\r?\n[\s\S]*?\r?\n---(\r?\n|$)/.test(mdxContentPart)) {
1933
+ console.warn(
1934
+ `[content-api] Embedded frontmatter-shaped block detected in body for ${targetFilePath}. ` +
1935
+ 'This indicates a load-path regression or client-side leak.',
1936
+ );
1937
+ }
1938
+
1939
+ const mdxContent = serializeMdxWithFrontmatter(frontmatterData, mdxContentPart);
1940
+
1941
+ // Atomic write for MDX files
1942
+ await atomicWriteFile(targetFilePath, mdxContent);
1943
+ } else if (targetFilePath.endsWith('.json')) {
1944
+ // Data files use "data" field instead of "content"
1945
+ const fileContent = JSON.parse(await readFile(filePath, 'utf-8'));
1946
+
1947
+ // Build updated data file structure
1948
+ const updatedFile = {
1949
+ id: fileContent.id,
1950
+ type: 'json' as const,
1951
+ created: fileContent.created,
1952
+ modified,
1953
+ ...(fileContent.publishAt && { publishAt: fileContent.publishAt }),
1954
+ ...(fileContent.unpublishAt && { unpublishAt: fileContent.unpublishAt }),
1955
+ meta: newMeta,
1956
+ data: sortKeys(newContent.data || {}, { deep: true }),
1957
+ };
1958
+
1959
+ // Handle publish date updates
1960
+ if ('publishAt' in data) {
1961
+ if (data.publishAt) {
1962
+ (updatedFile as Record<string, unknown>).publishAt = data.publishAt;
1963
+ } else {
1964
+ delete (updatedFile as Record<string, unknown>).publishAt;
1965
+ }
1966
+ }
1967
+
1968
+ if ('unpublishAt' in data) {
1969
+ if (data.unpublishAt) {
1970
+ (updatedFile as Record<string, unknown>).unpublishAt = data.unpublishAt;
1971
+ } else {
1972
+ delete (updatedFile as Record<string, unknown>).unpublishAt;
1973
+ }
1974
+ }
1975
+
1976
+ // Serialize data file
1977
+ const serializedContent = JSON.stringify(sortKeys(updatedFile, { deep: true }), null, '\t');
1978
+
1979
+ // Atomic write for JSON data files
1980
+ await atomicWriteFile(targetFilePath, serializedContent);
1981
+ } else {
1982
+ // VXJSON for pages (puck)
1983
+ const fileContent = JSON.parse(await readFile(filePath, 'utf-8'));
1984
+
1985
+ // Build updated VXJSONFile structure
1986
+ const updatedFile: VXJSONFile = {
1987
+ id: fileContent.id,
1988
+ type: fileContent.type,
1989
+ created: fileContent.created,
1990
+ modified,
1991
+ publishAt: fileContent.publishAt,
1992
+ unpublishAt: fileContent.unpublishAt,
1993
+ previousPathnames: fileContent.previousPathnames,
1994
+ meta: newMeta,
1995
+ content: sortKeys(newContent, { deep: true }),
1996
+ };
1997
+
1998
+ // Handle pathname changes and track history
1999
+ if (pathname && localeVersion.pathname && pathname !== localeVersion.pathname) {
2000
+ // Only add to history if content is published
2001
+ if (isContentPublished(current)) {
2002
+ if (!updatedFile.previousPathnames) {
2003
+ updatedFile.previousPathnames = {};
2004
+ }
2005
+ updatedFile.previousPathnames[localeVersion.pathname] = modified;
2006
+ }
2007
+ }
2008
+
2009
+ // Handle publish date updates
2010
+ if ('publishAt' in data) {
2011
+ if (data.publishAt) {
2012
+ updatedFile.publishAt = data.publishAt;
2013
+ } else {
2014
+ delete updatedFile.publishAt;
2015
+ }
2016
+ }
2017
+
2018
+ if ('unpublishAt' in data) {
2019
+ if (data.unpublishAt) {
2020
+ updatedFile.unpublishAt = data.unpublishAt;
2021
+ } else {
2022
+ delete updatedFile.unpublishAt;
2023
+ }
2024
+ }
2025
+
2026
+ // Serialize using VXJSON format to ensure content is last
2027
+ const serializedContent = VXJSON.serialize(updatedFile);
2028
+
2029
+ // Atomic write for VXJSON page files
2030
+ await atomicWriteFile(targetFilePath, serializedContent);
2031
+ }
2032
+
2033
+ // Calculate new etag from the written file
2034
+ const writtenBuffer = (await readFile(targetFilePath)) as Uint8Array;
2035
+ let newEtag: string;
2036
+
2037
+ if (targetFilePath.endsWith('.mdx')) {
2038
+ // Find content position in MDX
2039
+ const contentStartMarker = new TextEncoder().encode('---\n\n');
2040
+ let contentPos = -1;
2041
+ for (let i = 0; i <= writtenBuffer.length - contentStartMarker.length; i++) {
2042
+ let match = true;
2043
+ for (let j = 0; j < contentStartMarker.length; j++) {
2044
+ if (writtenBuffer[i + j] !== contentStartMarker[j]) {
2045
+ match = false;
2046
+ break;
2047
+ }
2048
+ }
2049
+ if (match) {
2050
+ contentPos = i + contentStartMarker.length;
2051
+ break;
2052
+ }
2053
+ }
2054
+ const etags = calculateEtagsFromMdxBuffer(writtenBuffer, contentPos);
2055
+ newEtag = `${etags.metaEtag}.${etags.contentEtag}`;
2056
+ } else if (targetFilePath.endsWith('.json')) {
2057
+ // For data files, use simple etag (hash entire buffer)
2058
+ newEtag = VXJSON.calculateSimpleEtag(writtenBuffer);
2059
+ } else {
2060
+ // For VXJSON, calculateEtagsFromVXJSONBuffer finds the content position internally
2061
+ const etagResult = VXJSON.calculateETags(writtenBuffer);
2062
+
2063
+ if (!etagResult.success) {
2064
+ throw new Error(`Invalid VXJSON format when updating content: ${etagResult.error}`);
2065
+ }
2066
+
2067
+ newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
2068
+ }
2069
+
2070
+ // Build updated locale manifest with current publish data
2071
+ const updatedLocaleVersion: LocaleVersion = {
2072
+ ...localeVersion,
2073
+ etag: newEtag,
2074
+ modified,
2075
+ meta: newMeta,
2076
+ ...(pathname && { pathname }),
2077
+ ...(data.name && { name: data.name }),
2078
+ };
2079
+
2080
+ // Handle publish dates using shared function
2081
+ // First preserve current values if not updating
2082
+ if (current.publishAt && !('publishAt' in data)) {
2083
+ updatedLocaleVersion.publishAt = current.publishAt;
2084
+ }
2085
+ if (current.unpublishAt && !('unpublishAt' in data)) {
2086
+ updatedLocaleVersion.unpublishAt = current.unpublishAt;
2087
+ }
2088
+
2089
+ // Then apply updates
2090
+ updatePublishDates(updatedLocaleVersion, data);
2091
+
2092
+ // Update pathname history if changed
2093
+ if (Object.keys(pathnameHistory).length > 0) {
2094
+ updatedLocaleVersion.previousPathnames = {
2095
+ ...localeVersion.previousPathnames,
2096
+ ...pathnameHistory,
2097
+ };
2098
+ } else {
2099
+ // Preserve existing previousPathnames if no change, but only if it has content
2100
+ const existingPreviousPathnames = localeVersion.previousPathnames;
2101
+ if (existingPreviousPathnames && Object.keys(existingPreviousPathnames).length > 0) {
2102
+ updatedLocaleVersion.previousPathnames = existingPreviousPathnames;
2103
+ } else {
2104
+ // Remove empty previousPathnames object
2105
+ delete updatedLocaleVersion.previousPathnames;
2106
+ }
2107
+ }
2108
+
2109
+ // Store the old locale manifest for rollback if needed
2110
+ const oldLocaleVersion = localeVersion;
2111
+
2112
+ try {
2113
+ // Replace the locale so its old path/name mappings are removed first.
2114
+ this.contentIndex.removeLocale(id, locale);
2115
+ this.contentIndex.addContent(manifest, updatedLocaleVersion, newContent);
2116
+
2117
+ // If pathname changed, delete the old file
2118
+ if (targetFilePath !== filePath) {
2119
+ try {
2120
+ // A name changed only in letter case is the same file on a case-insensitive disk: the
2121
+ // write went into it, so deleting the old path would delete the entry. Renaming it
2122
+ // gives the file its new name's case.
2123
+ if (await isSameFile(filePath, targetFilePath)) await rename(filePath, targetFilePath);
2124
+ else await unlink(filePath);
2125
+ } catch (error) {
2126
+ // Log but don't fail if old file deletion fails
2127
+ console.warn(`Failed to delete old file ${filePath}:`, error);
2128
+ }
2129
+ }
2130
+ } catch (error) {
2131
+ // Rollback on error to maintain the original locale and name mapping.
2132
+ this.contentIndex.removeLocale(id, locale);
2133
+ this.contentIndex.addContent(manifest, oldLocaleVersion, current.content);
2134
+
2135
+ // If we wrote to a new file, try to clean it up. A name changed only in letter case wrote
2136
+ // into the entry's own file on a case-insensitive disk, and that file is kept.
2137
+ if (targetFilePath !== filePath && !(await isSameFile(filePath, targetFilePath))) {
2138
+ try {
2139
+ await unlink(targetFilePath);
2140
+ } catch {
2141
+ // Ignore cleanup errors
2142
+ }
2143
+ }
2144
+
2145
+ throw error;
2146
+ }
2147
+
2148
+ return {
2149
+ success: true,
2150
+ etag: newEtag,
2151
+ modified: new Date(),
2152
+ };
2153
+ } catch (error) {
2154
+ return {
2155
+ success: false,
2156
+ reason: 'write_error',
2157
+ error: ensureError(error),
2158
+ };
2159
+ }
2160
+ }
2161
+
2162
+ async deleteContent(id: string, etag: string): Promise<DeleteResult> {
2163
+ // Get manifest for this ID
2164
+ const manifest = this.contentIndex.getManifest(id);
2165
+ if (!manifest) {
2166
+ return {
2167
+ success: false,
2168
+ reason: 'not_found',
2169
+ error: new Error('Content not found'),
2170
+ };
2171
+ }
2172
+
2173
+ // For deleteContent, we require the etag to match ANY locale (indicating user has current data)
2174
+ // But this is still a design flaw - we should probably require all etags or a master etag
2175
+ let matchingLocale: LocaleVersion | undefined;
2176
+ for (const localeVersion of localesOf(manifest)) {
2177
+ if (localeVersion.etag === etag) {
2178
+ matchingLocale = localeVersion;
2179
+ break;
2180
+ }
2181
+ }
2182
+ if (!matchingLocale) {
2183
+ return {
2184
+ success: false,
2185
+ reason: 'stale_write',
2186
+ currentEtag: Array.from(localesOf(manifest))[0]?.etag || '',
2187
+ error: new Error('Invalid etag - must match at least one locale'),
2188
+ };
2189
+ }
2190
+
2191
+ // Settled, not all: Promise.all let one rejection abandon the others
2192
+ // AFTER they had already unlinked, so the caller was told the delete
2193
+ // failed while the content was gone and the index still listed it. A file
2194
+ // already absent (git checkout, a manual rm) is the common cause, and for
2195
+ // a delete that is the desired end state, not an error.
2196
+ const localeVersions = Array.from(localesOf(manifest));
2197
+ const outcomes = await Promise.allSettled(
2198
+ localeVersions.map(async (localeVersion) => {
2199
+ await rm(this.getFilePath(manifest, localeVersion), { force: true });
2200
+ }),
2201
+ );
2202
+
2203
+ const failures = outcomes.filter((outcome) => outcome.status === 'rejected');
2204
+ if (failures.length === 0) {
2205
+ this.contentIndex.removeEntry(id);
2206
+ return { success: true };
2207
+ }
2208
+
2209
+ // Some files are gone and some are not. Drop exactly what was removed so
2210
+ // the index still describes what is on disk; the survivors stay indexed
2211
+ // rather than becoming unreachable orphans.
2212
+ for (const [position, outcome] of outcomes.entries()) {
2213
+ if (outcome.status === 'fulfilled') {
2214
+ this.contentIndex.removeLocale(id, localeVersions[position].locale);
2215
+ }
2216
+ }
2217
+
2218
+ return {
2219
+ success: false,
2220
+ error: ensureError(failures[0].reason),
2221
+ };
2222
+ }
2223
+
2224
+ async deleteLocalized(input: DeleteLocaleInput): Promise<DeleteResult> {
2225
+ const { id, locale, etag } = input;
2226
+
2227
+ // Get manifest for this ID
2228
+ const manifest = this.contentIndex.getManifest(id);
2229
+ if (!manifest) {
2230
+ return {
2231
+ success: false,
2232
+ reason: 'not_found',
2233
+ error: new Error('Content not found'),
2234
+ };
2235
+ }
2236
+
2237
+ // Check if this locale exists
2238
+ const localeVersion = manifest.locales[locale];
2239
+ if (!localeVersion) {
2240
+ return {
2241
+ success: false,
2242
+ reason: 'not_found',
2243
+ error: new Error('Locale not found'),
2244
+ };
2245
+ }
2246
+
2247
+ // Verify etag matches this locale
2248
+ if (localeVersion.etag !== etag) {
2249
+ return {
2250
+ success: false,
2251
+ reason: 'stale_write',
2252
+ currentEtag: localeVersion.etag,
2253
+ error: new Error('Invalid etag for locale'),
2254
+ };
2255
+ }
2256
+
2257
+ // Don't allow deleting the last locale. Count actual locales, not
2258
+ // manifest keys — removeLocale clears a locale by assigning undefined
2259
+ // and keeping the key, so after an earlier translation delete the key
2260
+ // count still includes the dead slot and the guard would wave the
2261
+ // genuinely last locale through.
2262
+ if (Array.from(localesOf(manifest)).length === 1) {
2263
+ return {
2264
+ success: false,
2265
+ error: new Error('Cannot delete the last locale. Use deleteContent to delete all content.'),
2266
+ };
2267
+ }
2268
+
2269
+ try {
2270
+ // Delete the locale file. A file already absent (git checkout, a
2271
+ // manual rm) is the desired end state of a delete, not an error —
2272
+ // same stance deleteContent takes. Failing on it left the deleted
2273
+ // translation routable and cached while reporting failure.
2274
+ await rm(this.getFilePath(manifest, localeVersion), { force: true });
2275
+
2276
+ // Remove locale from manifest and index. removeLocale clears the
2277
+ // manifest field itself, and returns early if it is already cleared —
2278
+ // clearing it here first skipped the pathname-index and content-cache
2279
+ // cleanup, leaving the deleted translation routable and cached.
2280
+ this.contentIndex.removeLocale(manifest.id, locale);
2281
+
2282
+ return { success: true };
2283
+ } catch (error) {
2284
+ return {
2285
+ success: false,
2286
+ error: ensureError(error),
2287
+ };
2288
+ }
2289
+ }
2290
+
2291
+ getSite(siteName: string): Site | null {
2292
+ if (siteName === 'fragments') {
2293
+ throw new Error('Use `fragments` property instead of getSite("fragments")');
2294
+ }
2295
+
2296
+ // Own-key only: the name is caller-supplied, and an inherited key like
2297
+ // `constructor` would resolve to a truthy non-Site.
2298
+ return Object.hasOwn(this.sites, siteName) ? this.sites[siteName] : null;
2299
+ }
2300
+
2301
+ *listAllContent(filters?: GlobalFilters): Generator<ContentManifest> {
2302
+ yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);
2303
+ }
2304
+ *findUntranslatedContent(targetLocale: string, options?: FindOptions): Generator<ContentManifest> {
2305
+ yield* this.contentIndex.findUntranslatedContent(targetLocale, options);
2306
+ }
2307
+
2308
+ /**
2309
+ * Reindex files that were added or changed after initial creation
2310
+ *
2311
+ * This method:
2312
+ * 1. Either scans for all content files or processes specific paths
2313
+ * 2. Uses the path index to check if files are already indexed
2314
+ * 3. Indexes new files or force-reindexes specified files
2315
+ * 4. Optionally handles file deletions
2316
+ *
2317
+ * @param paths - Optional array of specific file paths to reindex. If not provided, scans all content files.
2318
+ * @param options - Options for reindexing behavior
2319
+ * @returns Statistics about the reindexing operation
2320
+ */
2321
+ async reindex(paths?: string[], options?: { handleDeletions?: boolean }): Promise<ReindexResult> {
2322
+ const filesToProcess = paths || (await this.scanContentFiles());
2323
+ let filesSkipped = 0;
2324
+ let filesProcessed = 0;
2325
+ let filesDeleted = 0;
2326
+ let errors = 0;
2327
+ const filesToIndex: string[] = [];
2328
+ const updated: LocalizedManifest[] = [];
2329
+ const deleted: Array<{ id: string; locale: string; kind: 'page' | 'fragment' | 'data' }> = [];
2330
+
2331
+ // Check each file
2332
+ for (const filePath of filesToProcess) {
2333
+ // Check if file exists (for deletion handling)
2334
+ if (options?.handleDeletions && paths) {
2335
+ try {
2336
+ await readFile(filePath);
2337
+ } catch {
2338
+ // File doesn't exist - remove from index
2339
+ const parsed = this.parseFilePath(filePath);
2340
+ if (parsed) {
2341
+ // Find the content ID to remove
2342
+ let manifest: ContentManifest | null = null;
2343
+ if (parsed.kind === 'fragment' && parsed.name) {
2344
+ manifest = this.contentIndex.getFragmentByName(parsed.collection, parsed.name, parsed.locale);
2345
+ } else if (parsed.kind === 'data' && parsed.name) {
2346
+ manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
2347
+ } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {
2348
+ manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
2349
+ }
2350
+ // A name finds an entry when any of its locales has it. A save that renames one locale
2351
+ // writes its new file and then deletes the old one, whose name the other locales still
2352
+ // carry: only a locale whose own name is the deleted file's has lost its file.
2353
+ if (parsed.kind !== 'page' && manifest?.locales[parsed.locale]?.name !== parsed.name) {
2354
+ manifest = null;
2355
+ }
2356
+
2357
+ if (manifest) {
2358
+ // Track the deletion
2359
+ deleted.push({
2360
+ id: manifest.id,
2361
+ locale: parsed.locale,
2362
+ kind: parsed.kind,
2363
+ });
2364
+
2365
+ // Remove the specific locale or entire entry if it's the last locale
2366
+ if (Object.keys(manifest.locales).length === 1) {
2367
+ this.contentIndex.removeEntry(manifest.id);
2368
+ } else {
2369
+ // Remove just this locale. removeLocale clears the manifest field itself and returns early
2370
+ // if it is already cleared, so clearing it here first left the locale's name taken.
2371
+ this.contentIndex.removeLocale(manifest.id, parsed.locale);
2372
+ }
2373
+ filesDeleted++;
2374
+ }
2375
+ }
2376
+ continue;
2377
+ }
2378
+ }
2379
+
2380
+ const parsed = this.parseFilePath(filePath);
2381
+ if (!parsed) {
2382
+ console.warn(`Skipping unrecognized file pattern: ${filePath}`);
2383
+ errors++;
2384
+ continue;
2385
+ }
2386
+
2387
+ // Check if this path is already indexed
2388
+ let isIndexed = false;
2389
+ if (parsed.kind === 'fragment' && parsed.name) {
2390
+ // Check fragment index by name
2391
+ const manifest = this.contentIndex.getFragmentByName(parsed.collection, parsed.name, parsed.locale);
2392
+ isIndexed = !!manifest;
2393
+ } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {
2394
+ // Check site index by pathname
2395
+ const manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
2396
+ isIndexed = !!manifest;
2397
+ } else if (parsed.kind === 'data' && parsed.name) {
2398
+ // Check data index by name
2399
+ const manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
2400
+ isIndexed = !!manifest;
2401
+ }
2402
+
2403
+ if (isIndexed) {
2404
+ if (!paths) {
2405
+ // Skip already indexed files when doing a full scan
2406
+ filesSkipped++;
2407
+ } else {
2408
+ // For specific paths, check if the file has changed
2409
+ const fileStats = await readFile(filePath);
2410
+ let currentManifest: ContentManifest | null = null;
2411
+ if (parsed.kind === 'fragment' && parsed.name) {
2412
+ currentManifest = this.contentIndex.getFragmentByName(parsed.collection, parsed.name, parsed.locale);
2413
+ } else if (parsed.kind === 'data' && parsed.name) {
2414
+ currentManifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
2415
+ } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {
2416
+ currentManifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
2417
+ }
2418
+
2419
+ if (currentManifest) {
2420
+ // Calculate current file etag
2421
+ const buffer = fileStats as Uint8Array;
2422
+ let currentEtag: string;
2423
+
2424
+ if (filePath.endsWith('.mdx')) {
2425
+ const contentPos = findMdxContentStartPosition(buffer);
2426
+ const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
2427
+ currentEtag = `${etags.metaEtag}.${etags.contentEtag}`;
2428
+ } else if (filePath.endsWith('.vxjson')) {
2429
+ const etagResult = VXJSON.calculateETags(buffer);
2430
+ if (!etagResult.success) {
2431
+ // File needs repair - add to filesToIndex for repair
2432
+ filesToIndex.push(filePath);
2433
+ continue;
2434
+ }
2435
+ currentEtag = etagResult.contentEtag
2436
+ ? `${etagResult.metaEtag}.${etagResult.contentEtag}`
2437
+ : etagResult.metaEtag;
2438
+ } else if (filePath.endsWith('.json')) {
2439
+ // For JSON data files, use content hash as etag
2440
+ currentEtag = xxh64(buffer).toString(16);
2441
+ } else {
2442
+ // Unknown file type, skip
2443
+ filesSkipped++;
2444
+ continue;
2445
+ }
2446
+
2447
+ // Only reindex if etag changed
2448
+ const existingEtag = currentManifest.locales[parsed.locale]?.etag;
2449
+
2450
+ if (existingEtag === currentEtag) {
2451
+ const relativePath = filePath.replace(`${this.absoluteContentRoot}/`, '');
2452
+ console.log(`[Content] skip ${relativePath} (unchanged)`);
2453
+ filesSkipped++;
2454
+ } else {
2455
+ filesToIndex.push(filePath);
2456
+ }
2457
+ } else {
2458
+ // Not indexed yet
2459
+ filesToIndex.push(filePath);
2460
+ }
2461
+ }
2462
+ } else {
2463
+ // Not indexed yet
2464
+ filesToIndex.push(filePath);
2465
+ }
2466
+ }
2467
+
2468
+ // Index the files
2469
+ const buffers = Array.from({ length: Math.min(filesToIndex.length, 100) }, () => new Uint8Array(4096));
2470
+
2471
+ // Drop the previous verdicts for every file this pass re-examines, so
2472
+ // problems do not pile up across reindexes. A full scan re-examines every
2473
+ // file that is not already indexed — and a file with a problem is never
2474
+ // indexed — so it can start from an empty slate.
2475
+ if (paths) {
2476
+ this.contentIndex.dropProblems(new Set(filesToIndex));
2477
+ } else {
2478
+ this.contentIndex.clearProblems();
2479
+ }
2480
+
2481
+ for (let i = 0; i < filesToIndex.length; i++) {
2482
+ const filePath = filesToIndex[i];
2483
+ const bufferIndex = i % buffers.length;
2484
+
2485
+ try {
2486
+ const result = await this.parseFileHeaderWithRepair(filePath, buffers[bufferIndex]);
2487
+ if (result) {
2488
+ const { manifest, localeVersion, content } = result;
2489
+
2490
+ // A different file already claims this id+locale. Its file still
2491
+ // being on disk is what tells a stray copy (refuse, or it merges
2492
+ // over the original and a page silently stops existing) apart from
2493
+ // an out-of-band rename (the old path is gone — this file is the
2494
+ // entry's new home and must keep merging).
2495
+ const claimant = this.contentIndex.getManifest(manifest.id);
2496
+ const claimedLocale = claimant?.locales[localeVersion.locale];
2497
+ if (claimant && claimedLocale) {
2498
+ const claimantPath = this.getFilePath(claimant, claimedLocale);
2499
+ const claimantOnDisk = await access(claimantPath).then(
2500
+ () => true,
2501
+ () => false,
2502
+ );
2503
+ if (claimantPath !== filePath && claimantOnDisk) {
2504
+ this.recordIndexProblem(
2505
+ filePath,
2506
+ 'duplicate-id',
2507
+ duplicateIdMessage(manifest.id, localeVersion.locale, claimantPath),
2508
+ );
2509
+ filesSkipped++;
2510
+ continue;
2511
+ }
2512
+ }
2513
+
2514
+ // Add to index
2515
+ this.contentIndex.addContent(manifest, localeVersion, content);
2516
+ filesProcessed++;
2517
+
2518
+ // Create LocalizedManifest for the updated list
2519
+ const localizedManifest: LocalizedManifest = {
2520
+ id: manifest.id,
2521
+ type: manifest.type,
2522
+ kind: manifest.kind,
2523
+ site: manifest.site,
2524
+ collection: manifest.collection,
2525
+ localized: localeVersion,
2526
+ };
2527
+ updated.push(localizedManifest);
2528
+ }
2529
+ } catch (error) {
2530
+ console.error(`Failed to reindex ${filePath}: ${messageOf(error)}`);
2531
+ this.recordIndexProblem(filePath, 'index-error', messageOf(error));
2532
+ errors++;
2533
+ }
2534
+ }
2535
+
2536
+ const result: ReindexResult = {
2537
+ filesProcessed,
2538
+ filesSkipped,
2539
+ updated,
2540
+ };
2541
+
2542
+ if (options?.handleDeletions && deleted.length > 0) {
2543
+ result.filesDeleted = filesDeleted;
2544
+ result.deleted = deleted;
2545
+ }
2546
+
2547
+ if (errors > 0) {
2548
+ result.errors = errors;
2549
+ }
2550
+
2551
+ return result;
2552
+ }
2553
+
2554
+ /**
2555
+ * Read content directly from cache
2556
+ * For testing purposes - returns null if not cached
2557
+ */
2558
+ async readFromCache(id: string, locale: string): Promise<ContentData | null> {
2559
+ return this.contentIndex.getCachedContent(id, locale);
2560
+ }
2561
+
2562
+ async getContentAsBuffer(
2563
+ id: string,
2564
+ locale: string,
2565
+ ): Promise<{
2566
+ buffer: Uint8Array;
2567
+ etag: string;
2568
+ contentType: 'application/json' | 'text/mdx';
2569
+ } | null> {
2570
+ const manifest = this.contentIndex.getManifest(id);
2571
+ if (!manifest?.locales[locale]) {
2572
+ return null;
2573
+ }
2574
+
2575
+ const localeVersion = manifest.locales[locale];
2576
+ const filePath = this.getFilePath(manifest, localeVersion);
2577
+ const buffer = (await readFile(filePath)) as Uint8Array;
2578
+ const contentType = filePath.endsWith('.mdx') ? 'text/mdx' : 'application/json';
2579
+
2580
+ // Calculate ETag based on file type
2581
+ let etag: string;
2582
+ if (contentType === 'text/mdx') {
2583
+ // Find content start position for MDX
2584
+ const contentStartMarker = new TextEncoder().encode('---\n\n');
2585
+ let contentPos = -1;
2586
+ for (let i = 0; i <= buffer.length - contentStartMarker.length; i++) {
2587
+ let match = true;
2588
+ for (let j = 0; j < contentStartMarker.length; j++) {
2589
+ if (buffer[i + j] !== contentStartMarker[j]) {
2590
+ match = false;
2591
+ break;
2592
+ }
2593
+ }
2594
+ if (match) {
2595
+ contentPos = i + contentStartMarker.length;
2596
+ break;
2597
+ }
2598
+ }
2599
+ const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
2600
+ etag = `${etags.metaEtag}.${etags.contentEtag}`;
2601
+ } else {
2602
+ // Calculate ETags for JSON
2603
+ const etagResult = VXJSON.calculateETags(buffer);
2604
+
2605
+ if (!etagResult.success) {
2606
+ throw new Error(`Invalid VXJSON format in getContentAsBuffer: ${etagResult.error}`);
2607
+ }
2608
+
2609
+ etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
2610
+ }
2611
+
2612
+ return { buffer, etag, contentType };
2613
+ }
2614
+
2615
+ async batchUpdate(operations: UpdateLocaleInput[]): Promise<BatchResult> {
2616
+ // First, validate all operations can succeed
2617
+ const validationResults: Array<{
2618
+ op: UpdateLocaleInput;
2619
+ manifest: ContentManifest;
2620
+ localeVersion: LocaleVersion;
2621
+ current?: LocaleFileData;
2622
+ }> = [];
2623
+
2624
+ for (const op of operations) {
2625
+ const manifest = this.contentIndex.getManifest(op.id);
2626
+ if (!manifest) {
2627
+ // Content not found
2628
+ return {
2629
+ operations: operations.map((o) => ({
2630
+ id: o.id,
2631
+ locale: o.locale,
2632
+ updated: false,
2633
+ error: new Error('Content not found'),
2634
+ })),
2635
+ success: false,
2636
+ updated: 0,
2637
+ failed: operations.length,
2638
+ };
2639
+ }
2640
+
2641
+ const localeVersion = manifest.locales[op.locale];
2642
+ if (!localeVersion) {
2643
+ // Locale not found
2644
+ return {
2645
+ operations: operations.map((o) => ({
2646
+ id: o.id,
2647
+ locale: o.locale,
2648
+ updated: false,
2649
+ error: new Error('Locale not found'),
2650
+ })),
2651
+ success: false,
2652
+ updated: 0,
2653
+ failed: operations.length,
2654
+ };
2655
+ }
2656
+
2657
+ // Check etag
2658
+ if (localeVersion.etag !== op.etag) {
2659
+ // Stale write detected
2660
+ return {
2661
+ operations: operations.map((o) => ({
2662
+ id: o.id,
2663
+ locale: o.locale,
2664
+ updated: false,
2665
+ error: new Error('Stale write'),
2666
+ })),
2667
+ success: false,
2668
+ updated: 0,
2669
+ failed: operations.length,
2670
+ };
2671
+ }
2672
+
2673
+ // Read current content for validation
2674
+ const filePath = this.getFilePath(manifest, localeVersion);
2675
+ const current = await this.readLocaleFile(filePath, op.locale);
2676
+ if (!current) {
2677
+ return {
2678
+ operations: operations.map((o) => ({
2679
+ id: o.id,
2680
+ locale: o.locale,
2681
+ updated: false,
2682
+ error: new Error('Failed to read content'),
2683
+ })),
2684
+ success: false,
2685
+ updated: 0,
2686
+ failed: operations.length,
2687
+ };
2688
+ }
2689
+
2690
+ // Validate metadata size if updating
2691
+ if (op.data.meta) {
2692
+ const newMeta = applyMetaPatch(current.meta, op.data.meta);
2693
+ const validation = validateAndPrepareMetadata(newMeta);
2694
+ if (!validation.valid) {
2695
+ return {
2696
+ operations: operations.map((o) => ({
2697
+ id: o.id,
2698
+ locale: o.locale,
2699
+ updated: false,
2700
+ error: new Error(validation.error!),
2701
+ })),
2702
+ success: false,
2703
+ updated: 0,
2704
+ failed: operations.length,
2705
+ };
2706
+ }
2707
+ }
2708
+
2709
+ validationResults.push({ op, manifest, localeVersion, current });
2710
+ }
2711
+
2712
+ // All validations passed, now perform updates
2713
+ const results: BatchOperationResult[] = [];
2714
+ let updated = 0;
2715
+
2716
+ for (const { op } of validationResults) {
2717
+ const result = await this.updateLocalized(op);
2718
+ if (result.success) {
2719
+ updated++;
2720
+ results.push({ id: op.id, locale: op.locale, updated: true, etag: result.etag });
2721
+ } else {
2722
+ // This shouldn't happen if validation was correct
2723
+ results.push({ id: op.id, locale: op.locale, updated: false, error: result.error });
2724
+ }
2725
+ }
2726
+
2727
+ return {
2728
+ operations: results,
2729
+ success: updated === operations.length,
2730
+ updated,
2731
+ failed: operations.length - updated,
2732
+ };
2733
+ }
2734
+ }
2735
+
2736
+ /** Whether two paths name one file, as 'hero.en.mdx' and 'Hero.en.mdx' do on a case-insensitive disk. */
2737
+ async function isSameFile(a: string, b: string): Promise<boolean> {
2738
+ const [statA, statB] = await Promise.all([stat(a), stat(b)]).catch(() => [null, null]);
2739
+ return statA !== null && statB !== null && statA.dev === statB.dev && statA.ino === statB.ino;
2740
+ }