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