@conloca/content-api 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.mjs","names":["process","MIME_MAP: Record<string, string>","stats: Stats","manifestEntry: ManifestEntryData","assets: AssetEntry[]","entries: Dirent[]","response: Response","fullPath: string","merged: ManifestEntryData","usages: AssetUsage[]","files: string[]","sourcePath: string","targetPath: string","result: FolderTreeNode[]","children","join","readFile","error: any","mkdir","dirname","writeFile","rename","unlink","generator: Generator<ContentManifest>","newManifest: ContentManifest","locales: string[]","oldPathname: string | undefined","addedPreviousPathnames: string[]","newManifest: ContentManifest","locale","sitesConfig: SitesConfig","api: ContentAPI","dataIndex: DataIndex","downstream: { update(data: Uint8Array): void }","textDecoder","partialContent","data","contentStartPos","etagResult","resolve","join","sitesConfig: SitesConfig","handle: FileHandle | undefined","site: string | undefined","collection: string","name: string | undefined","pathname: string | undefined","parsedData: ParsedMetadata","kind: 'block' | 'page' | 'data'","filename","dirname","content","localeVersion: LocaleVersion","manifest: ContentManifest","content: ContentData | undefined","data: VXJSONFile","vxjsonData: VXJSONFile","files: string[]","locale","locales: Record<string, LocaleVersion & ContentProp>","result: LocaleFileData","result","repairedData: VXJSONFile","contentCache: Record<string, ContentData>","meta: ContentMeta","fileData: VXJSONFile","etag: string","modified: string","newLocaleVersion: LocaleVersion","updatedFile: VXJSONFile","newEtag: string","updatedLocaleVersion: LocaleVersion","matchingLocale: LocaleVersion | undefined","filesToIndex: string[]","updated: LocalizedManifest[]","deleted: Array<{ id: string; locale: string; kind: 'page' | 'block' | 'data' }>","parsed","manifest: ContentManifest | null","currentManifest: ContentManifest | null","currentEtag: string","localizedManifest: LocalizedManifest","result: ReindexResult","validationResults: Array<{\n op: UpdateLocaleInput;\n manifest: ContentManifest;\n localeVersion: LocaleVersion;\n current?: LocaleFileData;\n }>","results: BatchOperationResult[]","resolve","contentEntry: ContentEntry","contentCache: Record<string, ContentData>","fileData: VXJSONFile","buffer: Uint8Array","etag: string","manifest: ContentManifest","newEtag: string","updatedManifest: ContentManifest","results: BatchResult","contentCache: Record<string, ContentData | null>","manifestLocale: LocaleVersion","calculatedEtag: string","contentType: 'application/json' | 'text/mdx'","c","filters: any","filters: GlobalFilters","collections","taken: ContentManifest | undefined","options: FindOptions","options","author: GitAuthor | undefined","chunks: Uint8Array[]","contentApi: FileSystemContentAPI"],"sources":["../src/asset-manifest.ts","../src/git-operations.ts","../src/asset-operations.ts","../src/cf-access.ts","../src/component-registry.ts","../src/content-filters.ts","../src/base-content-index.ts","../src/block-index.ts","../src/data-index.ts","../src/site-index.ts","../src/content-index.ts","../src/data.ts","../src/json-whitespace-view.ts","../src/url-safe-base64.ts","../src/etag-utils.ts","../src/vxjson.ts","../src/filesystem-content-api.ts","../src/content-watcher.ts","../src/in-memory-content-api.ts","../src/middleware.ts","../src/vite-plugin.ts"],"sourcesContent":["import { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport type { AssetManifestData, ManifestEntryData } from './asset-types';\n\n// Re-export types for backwards compatibility\nexport type {\n AssetEntry,\n AssetManifestData,\n AssetUsage,\n FolderListing,\n FolderTreeNode,\n ManifestEntryData,\n} from './asset-types';\n\nconst MANIFEST_FILENAME = '.asset-manifest.json';\n\nexport class AssetManifest {\n private manifestPath: string;\n\n constructor(assetsPath: string) {\n this.manifestPath = join(assetsPath, MANIFEST_FILENAME);\n }\n\n async read(): Promise<AssetManifestData> {\n try {\n const raw = await readFile(this.manifestPath, 'utf-8');\n return JSON.parse(raw) as AssetManifestData;\n } catch {\n return {};\n }\n }\n\n async write(data: AssetManifestData): Promise<void> {\n await writeFile(this.manifestPath, JSON.stringify(data, null, 2), 'utf-8');\n }\n\n async add(relativePath: string, data: ManifestEntryData): Promise<void> {\n const manifest = await this.read();\n manifest[relativePath] = data;\n await this.write(manifest);\n }\n\n async remove(relativePath: string): Promise<boolean> {\n const manifest = await this.read();\n if (!(relativePath in manifest)) return false;\n delete manifest[relativePath];\n await this.write(manifest);\n return true;\n }\n\n async get(relativePath: string): Promise<ManifestEntryData | undefined> {\n const manifest = await this.read();\n return manifest[relativePath];\n }\n\n /**\n * Backward compat helper: search manifest keys for entry ending with /filename or equal to filename\n * Useful during transition when only filename is known (not full relative path)\n */\n async getByFilename(filename: string): Promise<{ relativePath: string; data: ManifestEntryData } | undefined> {\n const manifest = await this.read();\n for (const [key, value] of Object.entries(manifest)) {\n if (key === filename || key.endsWith(`/${filename}`)) {\n return { relativePath: key, data: value };\n }\n }\n return undefined;\n }\n}\n","import { spawn } from 'node:child_process';\nimport { access, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\n\nexport interface GitStatus {\n isRepo: boolean;\n hasChanges: boolean;\n changedFiles: number;\n ahead: number;\n behind: number;\n branch: string;\n remoteConfigured?: boolean;\n}\n\nexport interface CommitResult {\n success: boolean;\n commit?: string;\n summary?: string;\n error?: string;\n}\n\nexport interface PushResult {\n success: boolean;\n error?: string;\n}\n\nexport interface PullResult {\n success: boolean;\n summary?: string;\n error?: string;\n}\n\nexport interface GitAuthor {\n name: string;\n email: string;\n}\n\nexport interface GitOperations {\n getStatus(): Promise<GitStatus>;\n commitAll(message: string, author?: GitAuthor): Promise<CommitResult>;\n pushOrigin(): Promise<PushResult>;\n pull(): Promise<PullResult>;\n}\n\nexport interface GitConfig {\n contentPath: string;\n branch?: string;\n}\n\ninterface GitCommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nfunction runGitCommand(cwd: string, args: string[]): Promise<GitCommandResult> {\n return new Promise((resolveCommand, reject) => {\n const process = spawn('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n\n process.stdout.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n process.stderr.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n process.on('error', reject);\n\n process.on('close', (exitCode) => {\n resolveCommand({\n exitCode: exitCode ?? 1,\n stdout: stdout.trim(),\n stderr: stderr.trim(),\n });\n });\n });\n}\n\n/**\n * Resolve the git repository root from a content path.\n * Uses `git rev-parse --show-toplevel` starting from the parent of the content directory.\n */\nasync function resolveRepoRoot(contentPath: string): Promise<string | null> {\n const contentRoot = resolve(contentPath);\n const startDir = dirname(contentRoot);\n const result = await runGitCommand(startDir, ['rev-parse', '--show-toplevel']);\n if (result.exitCode !== 0) {\n return null;\n }\n return result.stdout;\n}\n\n/**\n * Create git operations using local git CLI commands.\n * Requires git binary available on PATH and CONTENT_PATH inside a git repository.\n */\nexport function createGitOperations(config: GitConfig): GitOperations {\n const { contentPath, branch } = config;\n\n return {\n async getStatus(): Promise<GitStatus> {\n try {\n const repoRoot = await resolveRepoRoot(contentPath);\n if (!repoRoot) {\n return { isRepo: false, hasChanges: false, changedFiles: 0, ahead: 0, behind: 0, branch: 'unknown' };\n }\n\n // Get current branch\n const branchResult = await runGitCommand(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);\n const currentBranch = branchResult.exitCode === 0 ? branchResult.stdout : 'unknown';\n\n // Get changed files count\n const statusResult = await runGitCommand(repoRoot, ['status', '--porcelain']);\n const changedLines = statusResult.stdout ? statusResult.stdout.split('\\n').filter((l) => l.trim()) : [];\n const changedFiles = changedLines.length;\n const hasChanges = changedFiles > 0;\n\n // Check if remote origin is configured\n const remoteResult = await runGitCommand(repoRoot, ['remote', 'get-url', 'origin']);\n const remoteConfigured = remoteResult.exitCode === 0;\n\n // Get ahead/behind counts\n let ahead = 0;\n let behind = 0;\n if (remoteConfigured) {\n const trackingBranch = branch || currentBranch;\n const revListResult = await runGitCommand(repoRoot, [\n 'rev-list',\n '--left-right',\n '--count',\n `HEAD...origin/${trackingBranch}`,\n ]);\n if (revListResult.exitCode === 0 && revListResult.stdout) {\n const [a, b] = revListResult.stdout.split('\\t').map(Number);\n ahead = a || 0;\n behind = b || 0;\n }\n }\n\n return { isRepo: true, hasChanges, changedFiles, ahead, behind, branch: currentBranch, remoteConfigured };\n } catch {\n return { isRepo: false, hasChanges: false, changedFiles: 0, ahead: 0, behind: 0, branch: 'unknown' };\n }\n },\n\n async commitAll(message: string, author?: GitAuthor): Promise<CommitResult> {\n try {\n const repoRoot = await resolveRepoRoot(contentPath);\n if (!repoRoot) {\n return { success: false, error: 'Not a git repository' };\n }\n\n // Stage all changes\n const addResult = await runGitCommand(repoRoot, ['add', '-A']);\n if (addResult.exitCode !== 0) {\n return { success: false, error: addResult.stderr || 'Failed to stage changes' };\n }\n\n // Check if there's anything to commit after staging\n const diffResult = await runGitCommand(repoRoot, ['diff', '--cached', '--quiet']);\n if (diffResult.exitCode === 0) {\n return { success: false, error: 'No changes to commit' };\n }\n\n // Count staged files for summary\n const diffStatResult = await runGitCommand(repoRoot, ['diff', '--cached', '--numstat']);\n const fileCount = diffStatResult.stdout ? diffStatResult.stdout.split('\\n').filter((l) => l.trim()).length : 0;\n\n // Build commit command\n const commitArgs = ['commit', '-m', message];\n if (author) {\n commitArgs.push('--author', `${author.name} <${author.email}>`);\n }\n\n const commitResult = await runGitCommand(repoRoot, commitArgs);\n if (commitResult.exitCode !== 0) {\n return { success: false, error: commitResult.stderr || 'Commit failed' };\n }\n\n // Get the commit SHA\n const shaResult = await runGitCommand(repoRoot, ['rev-parse', 'HEAD']);\n const commitSha = shaResult.stdout || undefined;\n\n return {\n success: true,\n commit: commitSha,\n summary: `${fileCount} files committed`,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Commit failed',\n };\n }\n },\n\n async pushOrigin(): Promise<PushResult> {\n try {\n const repoRoot = await resolveRepoRoot(contentPath);\n if (!repoRoot) {\n return { success: false, error: 'Not a git repository' };\n }\n\n // Pre-check: verify remote is configured\n const remoteResult = await runGitCommand(repoRoot, ['remote', 'get-url', 'origin']);\n if (remoteResult.exitCode !== 0) {\n return {\n success: false,\n error: 'No git remote \"origin\" configured. Please configure a remote to enable push.',\n };\n }\n\n // Determine branch to push\n let targetBranch = branch;\n if (!targetBranch) {\n const branchResult = await runGitCommand(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);\n targetBranch = branchResult.stdout;\n }\n\n const pushResult = await runGitCommand(repoRoot, ['push', 'origin', targetBranch]);\n if (pushResult.exitCode !== 0) {\n const stderr = pushResult.stderr || '';\n if (stderr.includes('non-fast-forward') || stderr.includes('rejected')) {\n return {\n success: false,\n error: 'Push rejected: remote has changes. Pull first, then try pushing again.',\n };\n }\n if (stderr.includes('Could not resolve host')) {\n return {\n success: false,\n error: 'Cannot reach git remote. Check your network connection.',\n };\n }\n if (stderr.includes('Permission denied') || stderr.includes('Authentication failed')) {\n return {\n success: false,\n error: 'Git remote authentication failed. Check server SSH key or credential configuration.',\n };\n }\n return { success: false, error: stderr || 'Push failed' };\n }\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Push failed',\n };\n }\n },\n\n async pull(): Promise<PullResult> {\n try {\n const repoRoot = await resolveRepoRoot(contentPath);\n if (!repoRoot) {\n return { success: false, error: 'Not a git repository' };\n }\n\n // Determine branch for pull\n let targetBranch = branch;\n if (!targetBranch) {\n const branchResult = await runGitCommand(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);\n targetBranch = branchResult.stdout;\n }\n\n const pullResult = await runGitCommand(repoRoot, ['pull', '--autostash', '--rebase', 'origin', targetBranch]);\n\n if (pullResult.exitCode !== 0) {\n return {\n success: false,\n error: pullResult.stderr || pullResult.stdout || 'Pull failed',\n };\n }\n\n return {\n success: true,\n summary: pullResult.stdout || `Pulled latest changes from origin/${targetBranch}`,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Pull failed',\n };\n }\n },\n };\n}\n\nconst LFS_PATTERNS = [\n '*.jpg filter=lfs diff=lfs merge=lfs -text',\n '*.jpeg filter=lfs diff=lfs merge=lfs -text',\n '*.png filter=lfs diff=lfs merge=lfs -text',\n '*.gif filter=lfs diff=lfs merge=lfs -text',\n '*.svg filter=lfs diff=lfs merge=lfs -text',\n '*.webp filter=lfs diff=lfs merge=lfs -text',\n '*.avif filter=lfs diff=lfs merge=lfs -text',\n '*.ico filter=lfs diff=lfs merge=lfs -text',\n];\n\n/**\n * Ensure .gitattributes exists at contentRoot with LFS tracking patterns for web image extensions.\n * Creates the file if missing, or appends missing patterns if file exists.\n */\nexport async function setupGitLfsAttributes(contentRoot: string): Promise<void> {\n const gitattributesPath = join(contentRoot, '.gitattributes');\n let existing = '';\n\n try {\n await access(gitattributesPath);\n existing = await readFile(gitattributesPath, 'utf-8');\n } catch {\n // File doesn't exist — will create fresh\n }\n\n const missingPatterns = LFS_PATTERNS.filter((pattern) => !existing.includes(pattern));\n\n if (missingPatterns.length === 0) return;\n\n const newContent = existing\n ? `${existing.trimEnd()}\\n${missingPatterns.join('\\n')}\\n`\n : `${missingPatterns.join('\\n')}\\n`;\n\n await writeFile(gitattributesPath, newContent, 'utf-8');\n}\n","import { type Dirent, existsSync, type Stats } from 'node:fs';\nimport { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';\nimport { extname, join, parse, resolve } from 'node:path';\nimport { imageSize } from 'image-size';\nimport {\n type AssetEntry,\n AssetManifest,\n type AssetManifestData,\n type AssetUsage,\n type FolderListing,\n type FolderTreeNode,\n type ManifestEntryData,\n} from './asset-manifest';\nimport { setupGitLfsAttributes } from './git-operations';\n\nexport interface AssetConfig {\n assetsPath: string;\n maxFileSize?: number;\n acceptedFormats?: string[];\n /** Content root directory for usage tracking (scanning VXJSON files) */\n contentRoot?: string;\n}\n\nconst DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB\nconst DEFAULT_ACCEPTED_FORMATS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'svg', 'ico'];\n\nconst MIME_MAP: Record<string, string> = {\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n svg: 'image/svg+xml',\n ico: 'image/x-icon',\n};\n\n/** Recognized web image extensions for filesystem scanning */\nconst RECOGNIZED_IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'avif', 'ico']);\n\n/** System files to skip during filesystem scanning */\nconst SYSTEM_FILES = new Set(['.ds_store', 'thumbs.db', '.gitkeep', 'desktop.ini', '.asset-manifest.json']);\n\n/** Check if filename has a recognized web image extension */\nfunction isRecognizedImageExtension(filename: string): boolean {\n const ext = extname(filename).slice(1).toLowerCase();\n return RECOGNIZED_IMAGE_EXTENSIONS.has(ext);\n}\n\n/** Check if file is a system/hidden file that should be skipped */\nfunction isSystemFile(filename: string): boolean {\n return filename.startsWith('.') || SYSTEM_FILES.has(filename.toLowerCase());\n}\n\nexport class AssetOperations {\n private config: Required<Omit<AssetConfig, 'contentRoot'>> & Pick<AssetConfig, 'contentRoot'>;\n private manifest: AssetManifest;\n private dirEnsured = false;\n private lfsSetup = false;\n\n constructor(config: AssetConfig) {\n this.config = {\n assetsPath: config.assetsPath,\n maxFileSize: config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE,\n acceptedFormats: config.acceptedFormats ?? DEFAULT_ACCEPTED_FORMATS,\n contentRoot: config.contentRoot,\n };\n this.manifest = new AssetManifest(config.assetsPath);\n }\n\n private async ensureDir(subpath?: string): Promise<void> {\n const targetPath = subpath ? join(this.config.assetsPath, subpath) : this.config.assetsPath;\n if (!subpath && this.dirEnsured) return;\n await mkdir(targetPath, { recursive: true });\n if (!subpath) this.dirEnsured = true;\n }\n\n /**\n * Validate that a subpath is safe (no path traversal attacks)\n * Returns the resolved full path if valid, throws if invalid\n */\n private validateSubpath(subpath: string): string {\n // Normalize the path: remove leading/trailing slashes, resolve .. and .\n const normalizedSubpath = subpath.replace(/^\\/+|\\/+$/g, '') || '.';\n // Resolve both paths to absolute to ensure consistent comparison\n const assetsAbsolute = resolve(this.config.assetsPath);\n const fullPath = resolve(assetsAbsolute, normalizedSubpath);\n\n // Security check: ensure resolved path is within assetsPath\n if (!fullPath.startsWith(assetsAbsolute)) {\n throw new Error('Path traversal detected');\n }\n\n return fullPath;\n }\n\n /**\n * Resolve a unique filename by appending -1, -2, etc. if collision exists\n * @param originalName Original filename\n * @param folder Optional folder path (relative to assets root)\n */\n private resolveFilename(originalName: string, folder?: string): string {\n const { name, ext } = parse(originalName);\n // Sanitize: lowercase, replace spaces with dashes, remove non-alphanumeric except dash/dot\n const sanitized = name\n .toLowerCase()\n .replace(/\\s+/g, '-')\n .replace(/[^a-z0-9-]/g, '');\n const safeExt = ext.toLowerCase();\n\n // Determine base directory (assetsPath or assetsPath/folder)\n const baseDir =\n folder && folder !== '/'\n ? join(this.config.assetsPath, folder.replace(/^\\/+|\\/+$/g, ''))\n : this.config.assetsPath;\n\n let candidate = `${sanitized}${safeExt}`;\n let counter = 0;\n\n while (existsSync(join(baseDir, candidate))) {\n counter++;\n candidate = `${sanitized}-${counter}${safeExt}`;\n }\n\n return candidate;\n }\n\n private validateFormat(filename: string): boolean {\n const ext = extname(filename).slice(1).toLowerCase();\n return this.config.acceptedFormats.includes(ext);\n }\n\n private validateSize(size: number): boolean {\n return size <= this.config.maxFileSize;\n }\n\n /**\n * Get image dimensions from manifest cache or by reading file headers\n */\n private async getDimensions(\n filePath: string,\n manifestEntry?: ManifestEntryData,\n ): Promise<{ width?: number; height?: number; fromCache: boolean }> {\n // Check manifest cache first\n if (manifestEntry?.width && manifestEntry?.height) {\n return { width: manifestEntry.width, height: manifestEntry.height, fromCache: true };\n }\n\n // Read from file headers\n try {\n const buffer = await readFile(filePath);\n const result = imageSize(new Uint8Array(buffer));\n return { width: result.width, height: result.height, fromCache: false };\n } catch {\n // SVGs and some formats may fail - return undefined dimensions\n return { width: undefined, height: undefined, fromCache: false };\n }\n }\n\n /**\n * Build an AssetEntry from a directory entry, enriching with manifest metadata\n */\n private async buildAssetEntry(dirent: Dirent, folder: string, manifestData: AssetManifestData): Promise<AssetEntry> {\n // Compute relative path for manifest lookup\n const relativePath = folder === '/' ? dirent.name : `${folder.slice(1)}/${dirent.name}`;\n const manifestEntry = manifestData[relativePath];\n\n // Build full file path\n const fullPath = this.getAssetPath(dirent.name, folder);\n\n // Get file stats\n const stats: Stats = await stat(fullPath);\n\n // Get dimensions (from cache or file)\n const { width, height, fromCache } = await this.getDimensions(fullPath, manifestEntry);\n\n // Progressive caching: if dimensions were computed from file, cache them\n if (!fromCache && width && height) {\n this.manifest.add(relativePath, { ...manifestEntry, width, height }).catch(() => {});\n }\n\n // Derive mimeType from extension\n const ext = extname(dirent.name).slice(1).toLowerCase();\n const mimeType = MIME_MAP[ext] || `image/${ext}`;\n\n return {\n filename: dirent.name,\n originalName: manifestEntry?.originalName || dirent.name,\n mimeType,\n size: stats.size,\n width,\n height,\n alt: manifestEntry?.alt,\n uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),\n uploadedBy: manifestEntry?.uploadedBy,\n folder,\n tags: manifestEntry?.tags,\n };\n }\n\n async upload(\n file: File,\n metadata?: { alt?: string; uploadedBy?: string; width?: number; height?: number; folder?: string },\n ): Promise<{ success: true; asset: AssetEntry } | { success: false; error: string }> {\n if (!this.validateFormat(file.name)) {\n const allowed = this.config.acceptedFormats.join(', ');\n return { success: false, error: `Invalid format. Accepted: ${allowed}` };\n }\n\n if (!this.validateSize(file.size)) {\n const maxMB = Math.round(this.config.maxFileSize / (1024 * 1024));\n return { success: false, error: `File too large. Maximum: ${maxMB}MB` };\n }\n\n // Normalize folder path\n const folder = metadata?.folder && metadata.folder !== '/' ? '/' + metadata.folder.replace(/^\\/+|\\/+$/g, '') : '/';\n\n // Validate folder path (prevent path traversal)\n if (folder !== '/') {\n try {\n this.validateSubpath(folder);\n } catch {\n return { success: false, error: 'Invalid folder path' };\n }\n }\n\n await this.ensureDir();\n\n // Ensure target folder exists\n if (folder !== '/') {\n await this.ensureDir(folder.replace(/^\\//, ''));\n }\n\n if (!this.lfsSetup) {\n await setupGitLfsAttributes(this.config.assetsPath);\n this.lfsSetup = true;\n }\n\n const filename = this.resolveFilename(file.name, folder);\n\n // Determine file path (in folder if specified)\n const filePath =\n folder !== '/'\n ? join(this.config.assetsPath, folder.replace(/^\\//, ''), filename)\n : join(this.config.assetsPath, filename);\n\n const arrayBuffer = await file.arrayBuffer();\n await writeFile(filePath, new Uint8Array(arrayBuffer));\n\n // Compute relative path for manifest\n const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;\n\n // Create manifest entry\n const manifestEntry: ManifestEntryData = {\n alt: metadata?.alt,\n width: metadata?.width,\n height: metadata?.height,\n uploadedAt: new Date().toISOString(),\n uploadedBy: metadata?.uploadedBy,\n originalName: file.name,\n };\n\n await this.manifest.add(relativePath, manifestEntry);\n\n // Build full AssetEntry for return\n const ext = extname(filename).slice(1).toLowerCase();\n const entry: AssetEntry = {\n filename,\n originalName: file.name,\n mimeType: MIME_MAP[ext] || `image/${ext}`,\n size: file.size,\n width: metadata?.width,\n height: metadata?.height,\n alt: metadata?.alt,\n uploadedAt: manifestEntry.uploadedAt!,\n uploadedBy: metadata?.uploadedBy,\n folder,\n };\n\n return { success: true, asset: entry };\n }\n\n /**\n * List all assets recursively from filesystem\n */\n async list(): Promise<AssetEntry[]> {\n // Load manifest once for enrichment\n const manifestData = await this.manifest.read();\n const assets: AssetEntry[] = [];\n\n // Recursive scanning helper\n const scanFolder = async (folderPath: string, folder: string): Promise<void> => {\n let entries: Dirent[];\n try {\n entries = await readdir(folderPath, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n // Skip hidden files, system files, and symlinks\n if (isSystemFile(entry.name) || entry.isSymbolicLink()) {\n continue;\n }\n\n const entryPath = join(folderPath, entry.name);\n\n if (entry.isDirectory()) {\n // Recurse into subdirectories\n const subFolder = folder === '/' ? `/${entry.name}` : `${folder}/${entry.name}`;\n await scanFolder(entryPath, subFolder);\n } else if (entry.isFile() && isRecognizedImageExtension(entry.name)) {\n // Build asset entry from filesystem + manifest\n const assetEntry = await this.buildAssetEntry(entry, folder, manifestData);\n assets.push(assetEntry);\n }\n }\n };\n\n await scanFolder(this.config.assetsPath, '/');\n return assets;\n }\n\n /**\n * Get asset by filename and optional folder\n */\n async getAsset(filename: string, folder = '/'): Promise<AssetEntry | undefined> {\n // Compute relative path and full file path\n const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;\n const fullPath = this.getAssetPath(filename, folder);\n\n // Check if file exists on disk\n let stats: Stats;\n try {\n stats = await stat(fullPath);\n } catch {\n // File doesn't exist\n return undefined;\n }\n\n if (!stats.isFile()) {\n return undefined;\n }\n\n // Load manifest for enrichment\n const manifestData = await this.manifest.read();\n const manifestEntry = manifestData[relativePath];\n\n // Get dimensions\n const { width, height, fromCache } = await this.getDimensions(fullPath, manifestEntry);\n\n // Progressive caching\n if (!fromCache && width && height) {\n this.manifest.add(relativePath, { ...manifestEntry, width, height }).catch(() => {});\n }\n\n // Derive mimeType from extension\n const ext = extname(filename).slice(1).toLowerCase();\n const mimeType = MIME_MAP[ext] || `image/${ext}`;\n\n return {\n filename,\n originalName: manifestEntry?.originalName || filename,\n mimeType,\n size: stats.size,\n width,\n height,\n alt: manifestEntry?.alt,\n uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),\n uploadedBy: manifestEntry?.uploadedBy,\n folder,\n tags: manifestEntry?.tags,\n };\n }\n\n /**\n * Delete asset file and manifest entry\n */\n async delete(filename: string, folder = '/'): Promise<{ success: true } | { success: false; error: string }> {\n // Compute relative path for manifest\n const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;\n\n // Build full file path\n const filePath = this.getAssetPath(filename, folder);\n\n // Delete file from disk (ignore if already gone)\n try {\n await unlink(filePath);\n } catch {\n // File may already be gone, continue with manifest cleanup\n }\n\n // Remove manifest entry\n await this.manifest.remove(relativePath);\n return { success: true };\n }\n\n /**\n * Import an image from a URL (server-side fetch, no CORS issues)\n */\n async importFromUrl(\n url: string,\n metadata?: { alt?: string; uploadedBy?: string; folder?: string },\n ): Promise<{ success: true; asset: AssetEntry } | { success: false; error: string }> {\n let response: Response;\n try {\n response = await fetch(url);\n } catch {\n return { success: false, error: 'Failed to fetch URL' };\n }\n\n if (!response.ok) {\n return { success: false, error: `Fetch failed with status ${response.status}` };\n }\n\n const contentType = response.headers.get('content-type') || '';\n const urlPath = new URL(url).pathname;\n const urlFilename = urlPath.split('/').pop() || 'imported-image.jpg';\n\n // Build a File-like object from the response\n const arrayBuffer = await response.arrayBuffer();\n const file = new File([new Uint8Array(arrayBuffer)], urlFilename, { type: contentType });\n\n return this.upload(file, metadata);\n }\n\n /**\n * List assets and subfolders within a folder (filesystem-first)\n * @param subpath Folder path relative to assets root (default '/')\n */\n async listFolder(subpath = '/'): Promise<FolderListing> {\n // Normalize subpath\n const normalizedSubpath = subpath === '/' ? '/' : '/' + subpath.replace(/^\\/+|\\/+$/g, '');\n\n // Validate path (prevent path traversal)\n let fullPath: string;\n if (normalizedSubpath === '/') {\n fullPath = this.config.assetsPath;\n } else {\n fullPath = this.validateSubpath(normalizedSubpath);\n }\n\n // Read directory entries\n let entries: Dirent[];\n try {\n entries = await readdir(fullPath, { withFileTypes: true });\n } catch {\n // Directory doesn't exist yet - return empty\n return { assets: [], folders: [] };\n }\n\n // Get subfolders (exclude hidden, symlinks)\n const folders = entries\n .filter((e) => e.isDirectory() && !e.name.startsWith('.') && !e.isSymbolicLink())\n .map((e) => ({\n name: e.name,\n path: normalizedSubpath === '/' ? `/${e.name}` : `${normalizedSubpath}/${e.name}`,\n }));\n\n // Get image files (exclude hidden, system files, symlinks, non-images)\n const imageFiles = entries.filter(\n (e) => e.isFile() && !isSystemFile(e.name) && !e.isSymbolicLink() && isRecognizedImageExtension(e.name),\n );\n\n // Load manifest for enrichment\n const manifestData = await this.manifest.read();\n\n // Build asset entries from filesystem\n const assets = await Promise.all(\n imageFiles.map((dirent) => this.buildAssetEntry(dirent, normalizedSubpath, manifestData)),\n );\n\n return { assets, folders };\n }\n\n /**\n * Create a folder on disk\n * @param subpath Folder path relative to assets root\n */\n async createFolder(subpath: string): Promise<{ success: true } | { success: false; error: string }> {\n if (!subpath || subpath === '/') {\n return { success: false, error: 'Cannot create root folder' };\n }\n\n // Validate path (prevent path traversal)\n let fullPath: string;\n try {\n fullPath = this.validateSubpath(subpath);\n } catch {\n return { success: false, error: 'Invalid folder path' };\n }\n\n try {\n await mkdir(fullPath, { recursive: true });\n return { success: true };\n } catch (err) {\n return {\n success: false,\n error: `Failed to create folder: ${err instanceof Error ? err.message : 'Unknown error'}`,\n };\n }\n }\n\n /**\n * Update asset metadata (alt text, tags)\n * @param filename Asset filename\n * @param updates Metadata updates (alt, tags)\n * @param folder Optional folder path (default '/')\n */\n async updateMetadata(\n filename: string,\n updates: Partial<ManifestEntryData>,\n folder = '/',\n ): Promise<{ success: true; asset: AssetEntry } | { success: false; error: string }> {\n // Compute relative path\n const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;\n\n // Check if file exists on disk\n const fullPath = this.getAssetPath(filename, folder);\n try {\n await stat(fullPath);\n } catch {\n return { success: false, error: 'Asset not found' };\n }\n\n // Get existing manifest entry\n const manifestData = await this.manifest.read();\n const existing = manifestData[relativePath] || {};\n\n // Merge updates\n const merged: ManifestEntryData = { ...existing, ...updates };\n\n // Write back to manifest\n await this.manifest.add(relativePath, merged);\n\n // Return updated asset entry\n const asset = await this.getAsset(filename, folder);\n if (!asset) {\n return { success: false, error: 'Failed to retrieve updated asset' };\n }\n\n return { success: true, asset };\n }\n\n /**\n * Get usage information for an asset (which pages reference it)\n * @param filename Asset filename\n */\n async getUsage(filename: string): Promise<AssetUsage[]> {\n if (!this.config.contentRoot) {\n return [];\n }\n\n const usages: AssetUsage[] = [];\n\n // Search patterns for the asset\n const searchPatterns = [filename, `/assets/uploads/${filename}`, `assets/uploads/${filename}`];\n\n // Recursively walk the content directory to find all .vxjson files\n const walkDir = async (dir: string): Promise<string[]> => {\n const files: string[] = [];\n let entries: Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return files;\n }\n\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n files.push(...(await walkDir(fullPath)));\n } else if (entry.isFile() && entry.name.endsWith('.vxjson')) {\n files.push(fullPath);\n }\n }\n\n return files;\n };\n\n const vxjsonFiles = await walkDir(this.config.contentRoot);\n\n for (const filePath of vxjsonFiles) {\n try {\n const content = await readFile(filePath, 'utf-8');\n\n // Check if any search pattern is found in the file content\n const found = searchPatterns.some((pattern) => content.includes(pattern));\n\n if (found) {\n // Extract page name from file path (remove .vxjson extension)\n const relativePath = filePath.replace(this.config.contentRoot, '').replace(/^[/\\\\]/, '');\n const pageName = relativePath.replace(/\\.vxjson$/, '');\n\n // Try to identify which field contains the reference\n // Simple approach: look for the pattern in JSON structure\n let field = 'unknown';\n try {\n const json = JSON.parse(content);\n field = this.findFieldWithAsset(json, searchPatterns) || 'content';\n } catch {\n // If JSON parsing fails, just mark as content\n field = 'content';\n }\n\n usages.push({ page: pageName, field });\n }\n } catch {\n // Skip files that can't be read\n }\n }\n\n return usages;\n }\n\n /**\n * Get the file path for an asset\n * @param filename Asset filename\n * @param folder Optional folder path (defaults to asset's stored folder)\n */\n getAssetPath(filename: string, folder?: string): string {\n const subpath = folder && folder !== '/' ? folder.replace(/^\\/+|\\/+$/g, '') : '';\n return subpath ? join(this.config.assetsPath, subpath, filename) : join(this.config.assetsPath, filename);\n }\n\n /**\n * Read asset file contents for serving (filesystem-first)\n * @param filename Asset filename\n * @param folder Optional folder path (default '/')\n */\n async readAssetFile(\n filename: string,\n folder = '/',\n ): Promise<{ success: true; buffer: Buffer; mimeType: string } | { success: false; error: string }> {\n // Build path from folder + filename\n const filePath = this.getAssetPath(filename, folder);\n\n // Derive mimeType from extension (don't require manifest entry)\n const ext = extname(filename).slice(1).toLowerCase();\n const mimeType = MIME_MAP[ext] || `image/${ext}`;\n\n try {\n const buffer = await readFile(filePath);\n return { success: true, buffer, mimeType };\n } catch {\n return { success: false, error: 'Asset not found' };\n }\n }\n\n /**\n * Helper to find which field contains an asset reference\n */\n private findFieldWithAsset(obj: unknown, patterns: string[], path = ''): string | null {\n if (typeof obj === 'string') {\n if (patterns.some((p) => obj.includes(p))) {\n return path || 'root';\n }\n return null;\n }\n\n if (Array.isArray(obj)) {\n for (let i = 0; i < obj.length; i++) {\n const result = this.findFieldWithAsset(obj[i], patterns, path ? `${path}[${i}]` : `[${i}]`);\n if (result) return result;\n }\n return null;\n }\n\n if (obj && typeof obj === 'object') {\n for (const [key, value] of Object.entries(obj)) {\n const result = this.findFieldWithAsset(value, patterns, path ? `${path}.${key}` : key);\n if (result) return result;\n }\n }\n\n return null;\n }\n\n /**\n * Move assets from one folder to another\n * @param filenames List of filenames to move\n * @param sourceFolder Source folder path (relative to assets root)\n * @param targetFolder Target folder path (relative to assets root)\n */\n async moveAssets(\n filenames: string[],\n sourceFolder: string,\n targetFolder: string,\n ): Promise<{ success: true; moved: number } | { success: false; error: string }> {\n // Normalize folder paths\n const normalizedSource = sourceFolder === '/' ? '/' : '/' + sourceFolder.replace(/^\\/+|\\/+$/g, '');\n const normalizedTarget = targetFolder === '/' ? '/' : '/' + targetFolder.replace(/^\\/+|\\/+$/g, '');\n\n // Validate both folders exist (for non-root folders)\n let sourcePath: string;\n let targetPath: string;\n\n try {\n sourcePath = normalizedSource === '/' ? this.config.assetsPath : this.validateSubpath(normalizedSource);\n targetPath = normalizedTarget === '/' ? this.config.assetsPath : this.validateSubpath(normalizedTarget);\n } catch {\n return { success: false, error: 'Invalid folder path' };\n }\n\n // Verify source folder exists\n try {\n const sourceStat = await stat(sourcePath);\n if (!sourceStat.isDirectory()) {\n return { success: false, error: 'Source folder does not exist' };\n }\n } catch {\n return { success: false, error: 'Source folder does not exist' };\n }\n\n // Verify target folder exists\n try {\n const targetStat = await stat(targetPath);\n if (!targetStat.isDirectory()) {\n return { success: false, error: 'Target folder does not exist' };\n }\n } catch {\n return { success: false, error: 'Target folder does not exist' };\n }\n\n // Move each file\n let movedCount = 0;\n for (const filename of filenames) {\n const sourceFile = join(sourcePath, filename);\n const targetFile = join(targetPath, filename);\n\n // Compute manifest paths\n const oldRelativePath = normalizedSource === '/' ? filename : `${normalizedSource.slice(1)}/${filename}`;\n const newRelativePath = normalizedTarget === '/' ? filename : `${normalizedTarget.slice(1)}/${filename}`;\n\n try {\n // Move the file on disk\n await rename(sourceFile, targetFile);\n\n // Update manifest: remove old entry and add new one\n const manifestData = await this.manifest.read();\n const oldEntry = manifestData[oldRelativePath];\n\n if (oldEntry) {\n await this.manifest.remove(oldRelativePath);\n await this.manifest.add(newRelativePath, oldEntry);\n }\n\n movedCount++;\n } catch (err) {\n // Continue with other files even if one fails\n console.error(`[AssetOperations] Failed to move ${filename}:`, err);\n }\n }\n\n return { success: true, moved: movedCount };\n }\n\n /**\n * Get the complete folder tree with asset counts\n * @returns Array of folder tree nodes representing the folder hierarchy\n */\n async getFolderTree(): Promise<FolderTreeNode[]> {\n const buildTree = async (folderPath: string, folder: string): Promise<FolderTreeNode[]> => {\n let entries: Dirent[];\n try {\n entries = await readdir(folderPath, { withFileTypes: true });\n } catch {\n return [];\n }\n\n const result: FolderTreeNode[] = [];\n\n for (const entry of entries) {\n // Skip hidden files/folders and symlinks\n if (isSystemFile(entry.name) || entry.isSymbolicLink()) {\n continue;\n }\n\n if (entry.isDirectory()) {\n const entryPath = join(folderPath, entry.name);\n const subFolder = folder === '/' ? `/${entry.name}` : `${folder}/${entry.name}`;\n\n // Count image files in this folder (non-recursive count for this folder only)\n let assetCount = 0;\n try {\n const subEntries = await readdir(entryPath, { withFileTypes: true });\n assetCount = subEntries.filter(\n (e) => e.isFile() && !isSystemFile(e.name) && isRecognizedImageExtension(e.name),\n ).length;\n } catch {\n // If we can't read the folder, count is 0\n }\n\n // Recursively get children\n const children = await buildTree(entryPath, subFolder);\n\n result.push({\n name: entry.name,\n path: subFolder,\n assetCount,\n children,\n });\n }\n }\n\n return result;\n };\n\n // Count assets in root folder\n let rootAssetCount = 0;\n try {\n const rootEntries = await readdir(this.config.assetsPath, { withFileTypes: true });\n rootAssetCount = rootEntries.filter(\n (e) => e.isFile() && !isSystemFile(e.name) && isRecognizedImageExtension(e.name),\n ).length;\n } catch {\n // If we can't read root, count is 0\n }\n\n // Build tree starting from assets root\n const children = await buildTree(this.config.assetsPath, '/');\n\n // Return root as first element with its children\n return [\n {\n name: 'Root',\n path: '/',\n assetCount: rootAssetCount,\n children,\n },\n ];\n }\n}\n","/**\n * Cloudflare Access JWT validation utility\n *\n * Validates JWT tokens from CF Access for API authorization and git commit attribution.\n * When CF_ACCESS_TEAM_NAME and CF_ACCESS_AUD env vars are set, requests must have valid tokens.\n * When env vars are not set (local dev), validation is skipped.\n */\n\nimport { type JWTPayload, createRemoteJWKSet, jwtVerify } from 'jose'\n\nconst CF_ACCESS_TEAM_NAME = process.env.CF_ACCESS_TEAM_NAME\nconst CF_ACCESS_AUD = process.env.CF_ACCESS_AUD\n\n// JWKS with built-in caching (handles key rotation automatically)\nconst JWKS = CF_ACCESS_TEAM_NAME\n ? createRemoteJWKSet(new URL(`https://${CF_ACCESS_TEAM_NAME}.cloudflareaccess.com/cdn-cgi/access/certs`))\n : null\n\nexport interface CFAccessUser {\n email: string\n sub: string\n}\n\nexport interface CFAccessResult {\n valid: boolean\n required: boolean\n user?: CFAccessUser\n error?: string\n}\n\n/**\n * Extract CF Access JWT token from request.\n * Checks Cf-Access-Jwt-Assertion header first, falls back to CF_Authorization cookie.\n */\nexport function extractCFAccessToken(request: Request): string | null {\n // Header is primary (always present when behind CF Access)\n const headerToken = request.headers.get('Cf-Access-Jwt-Assertion')\n if (headerToken) return headerToken\n\n // Cookie is fallback (browser requests)\n const cookies = request.headers.get('Cookie') || ''\n const match = cookies.match(/CF_Authorization=([^;]+)/)\n return match ? match[1] : null\n}\n\n/**\n * Validate CF Access JWT from request.\n *\n * Returns { valid: true, required: false } when env vars not set (local dev mode).\n * Returns { valid: true, required: true, user } when token is valid.\n * Returns { valid: false, required: true, error } when token is invalid or missing.\n */\nexport async function validateCFAccessRequest(request: Request): Promise<CFAccessResult> {\n // If CF Access not configured, skip validation (local dev)\n if (!CF_ACCESS_TEAM_NAME || !CF_ACCESS_AUD || !JWKS) {\n return { valid: true, required: false }\n }\n\n const token = extractCFAccessToken(request)\n if (!token) {\n return { valid: false, required: true, error: 'No token provided' }\n }\n\n try {\n const { payload } = await jwtVerify(token, JWKS, {\n issuer: `https://${CF_ACCESS_TEAM_NAME}.cloudflareaccess.com`,\n audience: CF_ACCESS_AUD,\n })\n\n return {\n valid: true,\n required: true,\n user: {\n email: (payload as JWTPayload & { email?: string }).email || '',\n sub: payload.sub || '',\n },\n }\n } catch (error) {\n return {\n valid: false,\n required: true,\n error: error instanceof Error ? error.message : 'Validation failed',\n }\n }\n}\n","import { mkdir, readFile, rename, unlink, writeFile } from 'fs/promises';\nimport { dirname, join } from 'path';\nimport sortKeys from 'sort-keys';\nimport type {\n ComponentEntry,\n ComponentEntryWithId,\n ComponentRegistry as ComponentRegistryType,\n} from './component-registry.types';\n\n/**\n * Component Registry for managing linked and unlinked components\n *\n * Registry is stored at {canvasDir}/components/registry.json\n * Component IDs must follow the format: vx-{uuid}\n */\nexport class ComponentRegistry {\n private registryPath: string;\n private registry: ComponentRegistryType = {};\n private initialized = false;\n\n constructor(canvasDir: string) {\n this.registryPath = join(canvasDir, 'components', 'registry.json');\n }\n\n /**\n * Initialize the registry by loading from disk or creating new\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n try {\n const content = await readFile(this.registryPath, 'utf-8');\n this.registry = JSON.parse(content);\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n // File doesn't exist, create empty registry\n await this.save();\n } else {\n throw error;\n }\n }\n\n this.initialized = true;\n }\n\n /**\n * Validate component ID format (vx-{uuid})\n */\n private validateComponentId(id: string): void {\n const uuidRegex = /^vx-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n if (!uuidRegex.test(id)) {\n throw new Error('Invalid component ID format. Expected: vx-{uuid}');\n }\n }\n\n /**\n * Save registry to disk atomically\n */\n private async save(): Promise<void> {\n const tempPath = `${this.registryPath}.tmp.${Date.now()}.${Math.random().toString(36).substring(2, 9)}`;\n\n try {\n // Ensure directory exists\n await mkdir(dirname(this.registryPath), { recursive: true });\n\n // Sort keys for consistent output\n const sorted = sortKeys(this.registry, { deep: true });\n const content = JSON.stringify(sorted, null, 2);\n\n // Write to temp file\n await writeFile(tempPath, content);\n\n // Atomic rename\n await rename(tempPath, this.registryPath);\n } catch (error) {\n // Clean up temp file on error\n try {\n await unlink(tempPath);\n } catch {}\n throw error;\n }\n }\n\n /**\n * Register a new component or update existing\n */\n async register(id: string, entry: ComponentEntry): Promise<void> {\n await this.initialize();\n this.validateComponentId(id);\n\n this.registry[id] = {\n displayName: entry.displayName,\n path: entry.path,\n };\n\n await this.save();\n }\n\n /**\n * Get a component entry by ID\n */\n async get(id: string): Promise<ComponentEntry | null> {\n await this.initialize();\n return this.registry[id] || null;\n }\n\n /**\n * Link a component to a path\n */\n async link(id: string, path: string): Promise<void> {\n await this.initialize();\n\n const entry = this.registry[id];\n if (!entry) {\n throw new Error(`Component ${id} not found in registry`);\n }\n\n entry.path = path;\n await this.save();\n }\n\n /**\n * Unlink a component (set path to null)\n */\n async unlink(id: string): Promise<void> {\n await this.initialize();\n\n const entry = this.registry[id];\n if (!entry) {\n throw new Error(`Component ${id} not found in registry`);\n }\n\n entry.path = null;\n await this.save();\n }\n\n /**\n * List all components\n */\n async list(): Promise<ComponentEntryWithId[]> {\n await this.initialize();\n\n return Object.entries(this.registry).map(([id, entry]) => ({\n id,\n ...entry,\n }));\n }\n\n /**\n * Delete a component from registry\n */\n async delete(id: string): Promise<void> {\n await this.initialize();\n\n delete this.registry[id];\n await this.save();\n }\n}\n","import type { ContentIndex } from './content-index';\nimport { localesOf } from './content-utils';\nimport type { ContentManifest, GlobalFilters, SitesConfig } from './types';\n\n/**\n * Apply filters to a single content manifest\n * Pure function that checks if a manifest matches all provided filters\n */\nexport function applyContentFilters(manifest: ContentManifest, filters: GlobalFilters): boolean {\n // Site filter\n if (filters.site && manifest.site !== filters.site) return false;\n\n // Collection filter\n if (filters.collection && manifest.collection !== filters.collection) return false;\n\n // Type filter\n if (filters.type && manifest.type !== filters.type) return false;\n\n // Kind filter\n if (filters.kind && manifest.kind !== filters.kind) return false;\n\n // Locales filter - check if manifest has any of the requested locales\n if (filters.locales && filters.locales.length > 0) {\n const hasAnyLocale = filters.locales.some((locale) => manifest.locales[locale]);\n if (!hasAnyLocale) return false;\n }\n\n // Missing locales filter - content must NOT have any of these locales\n if (filters.missingLocales && filters.missingLocales.length > 0) {\n const hasAnyMissingLocale = filters.missingLocales.some((locale) => manifest.locales[locale]);\n if (hasAnyMissingLocale) return false;\n }\n\n // Published status filter - check all locales\n if (filters.published !== undefined) {\n let hasPublishedLocale = false;\n for (const localeVersion of localesOf(manifest)) {\n if (!localeVersion.unpublishAt) {\n hasPublishedLocale = true;\n break;\n }\n if (new Date(localeVersion.unpublishAt) > new Date()) {\n hasPublishedLocale = true;\n break;\n }\n }\n if (filters.published !== hasPublishedLocale) return false;\n }\n\n // All filters passed\n return true;\n}\n\n/**\n * Filter a collection of content manifests based on localization status\n * Returns manifests that match the specified localization criteria\n */\nexport function filterByLocalization(\n allManifests: ContentManifest[],\n filters: GlobalFilters,\n siteLocales: string[],\n): ContentManifest[] {\n const results: ContentManifest[] = [];\n\n if (!filters.localization) {\n // No localization filter - return all manifests that match other filters\n for (const manifest of allManifests) {\n if (applyContentFilters(manifest, filters)) {\n results.push(manifest);\n }\n }\n return results;\n }\n\n // Apply localization-specific filtering\n switch (filters.localization) {\n case 'one':\n // Find content with exactly one locale\n for (const manifest of allManifests) {\n const localeCount = Object.keys(manifest.locales).length;\n if (localeCount === 1 && applyContentFilters(manifest, filters)) {\n results.push(manifest);\n }\n }\n break;\n\n case 'complete':\n // Find content with all expected locales\n for (const manifest of allManifests) {\n const hasAllLocales = siteLocales.every((loc) => manifest.locales[loc]);\n if (hasAllLocales && applyContentFilters(manifest, filters)) {\n results.push(manifest);\n }\n }\n break;\n\n case 'partial':\n // Find content with some but not all translations\n for (const manifest of allManifests) {\n const localeCount = Object.keys(manifest.locales).length;\n const hasPartialLocales = localeCount > 0 && localeCount < siteLocales.length;\n if (hasPartialLocales && applyContentFilters(manifest, filters)) {\n results.push(manifest);\n }\n }\n break;\n }\n\n return results;\n}\n\n/**\n * Generator that yields manifests after applying all filters\n */\nexport function* filteredContentGenerator(\n contentIndex: ContentIndex,\n filters: GlobalFilters,\n): Generator<ContentManifest> {\n for (const manifest of getFilteredManifestsGenerator(contentIndex, filters)) {\n if (applyContentFilters(manifest, filters)) {\n yield manifest;\n }\n }\n}\n\n/**\n * Generator that yields manifests using the most efficient index path\n */\nexport function* getFilteredManifestsGenerator(\n contentIndex: ContentIndex,\n filters: GlobalFilters,\n): Generator<ContentManifest> {\n // Choose the most efficient index path based on available filters\n\n // Most specific: site + locale + collection\n if (filters.site && filters.locales?.length === 1 && filters.collection) {\n for (const manifest of contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0])) {\n if (manifest.collection === filters.collection) {\n yield manifest;\n }\n }\n return;\n }\n\n // Site + collection (use optimized method)\n if (filters.site && filters.collection) {\n yield* contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);\n return;\n }\n\n // Site + single locale (use optimized method)\n if (filters.site && filters.locales?.length === 1) {\n yield* contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0]);\n return;\n }\n\n // Just single locale\n if (filters.locales?.length === 1) {\n yield* contentIndex.getManifestsForLocale(filters.locales[0]);\n return;\n }\n\n // Just site\n if (filters.site) {\n yield* contentIndex.getManifestsForSite(filters.site);\n return;\n }\n\n // Just collection\n if (filters.collection) {\n yield* contentIndex.getManifestsForCollection(filters.collection);\n return;\n }\n\n // Kind filter\n if (filters.kind) {\n yield* contentIndex.getManifestsForKind(filters.kind);\n return;\n }\n\n // No specific filters - yield all manifests\n yield* contentIndex.listAllContent();\n}\n\n/**\n * Get filtered manifests using indexes where possible for performance\n * This function leverages ContentIndex's specialized indexes to avoid full scans\n */\nexport function getFilteredManifests(contentIndex: ContentIndex, filters: GlobalFilters): ContentManifest[] {\n return Array.from(getFilteredManifestsGenerator(contentIndex, filters));\n}\n\n/**\n * Generator that yields manifests after applying all filters\n * This is the main entry point for filtering content using indexes efficiently\n */\nexport function* filterContentWithIndexes(\n contentIndex: ContentIndex,\n filters: GlobalFilters | undefined,\n sitesConfig: SitesConfig,\n): Generator<ContentManifest> {\n if (!filters) {\n // No filters - return all content\n yield* contentIndex.listAllContent();\n return;\n }\n\n // Special optimization for kind + site + collection\n if (filters.kind === 'page' && filters.site && filters.collection) {\n // Check if the site even has this collection\n const siteCollections = contentIndex.getCollectionsForSite(filters.site);\n if (!siteCollections.has(filters.collection)) {\n return; // Early exit - no pages in this collection for this site\n }\n } else if (filters.kind === 'block' && filters.collection) {\n // Check if blocks have this collection\n const blockCollections = contentIndex.getBlockCollections();\n if (!blockCollections.has(filters.collection)) {\n return; // Early exit - no blocks in this collection\n }\n }\n\n // Use the most efficient generator based on filters\n let generator: Generator<ContentManifest>;\n\n // Optimal filter ordering for most specific queries first\n if (filters.kind === 'page' && filters.site && filters.collection) {\n // Most specific for pages: site + collection\n generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);\n } else if (filters.kind === 'block' && filters.collection) {\n // Most specific for blocks: kind + collection\n generator = contentIndex.getManifestsForCollection(filters.collection);\n } else if (filters.kind) {\n generator = contentIndex.getManifestsForKind(filters.kind);\n } else if (filters.site && filters.collection) {\n generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);\n } else if (filters.site && filters.locales?.length === 1) {\n // Single locale optimization\n generator = contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0]);\n } else if (filters.site) {\n generator = contentIndex.getManifestsForSite(filters.site);\n } else if (filters.collection) {\n generator = contentIndex.getManifestsForCollection(filters.collection);\n } else if (filters.locales?.length === 1) {\n // Single locale optimization\n generator = contentIndex.getManifestsForLocale(filters.locales[0]);\n } else {\n generator = contentIndex.listAllContent();\n }\n\n // Apply additional filters\n for (const manifest of generator) {\n if (!applyContentFilters(manifest, filters)) continue;\n\n // Localization filter\n if (filters.localization) {\n // Early exit optimization: if complete + missingLocales, no results possible\n if (filters.localization === 'complete' && filters.missingLocales?.length) {\n continue; // Complete means has all locales, can't be missing any\n }\n\n const siteLocales =\n filters.site && manifest.kind === 'page'\n ? sitesConfig.sites[filters.site]?.locales || sitesConfig.globalLocales\n : sitesConfig.globalLocales;\n\n const localeCount = Object.keys(manifest.locales).length;\n const hasLocales = siteLocales.filter((l) => manifest.locales[l]).length;\n const totalLocales = siteLocales.length;\n\n if (filters.localization === 'complete' && hasLocales !== totalLocales) continue;\n if (filters.localization === 'partial' && (localeCount <= 1 || hasLocales === totalLocales)) continue;\n if (filters.localization === 'one' && localeCount !== 1) continue;\n }\n\n yield manifest;\n }\n}\n","import { localesOf } from './content-utils';\nimport type { ContentData, ContentIdentity, ContentManifest, LocaleVersion } from './types';\n\n/**\n * Base class for content indexes (blocks, data)\n * Maintains collection->name->locale lookups with V8-optimized structures\n */\nexport class BaseContentIndex {\n // Primary index: id -> ContentManifest\n protected index: Map<string, ContentManifest> = new Map();\n\n // Content cache: id -> locale -> content (for small files)\n protected contentCache: Map<string, Record<string, ContentData | null>> = new Map();\n\n // Name index: collection -> name -> ContentManifest\n protected nameIndex: Map<string, Map<string, ContentManifest>> = new Map();\n\n // Collections used\n readonly collections: Set<string> = new Set();\n\n /**\n * Add or update content in the index\n * Merges manifest locales and updates content cache if provided\n */\n addContent(identity: ContentIdentity, localeVersion: LocaleVersion, content?: ContentData | null): void {\n // Get existing manifest\n const existing = this.index.get(identity.id);\n const locale = localeVersion.locale;\n\n if (existing) {\n // Update single locale\n const existingLocale = existing.locales[locale];\n if (!existingLocale || existingLocale.etag !== localeVersion.etag) {\n existing.locales[locale] = localeVersion;\n }\n } else {\n // New content - create ContentManifest with single locale\n const newManifest: ContentManifest = {\n id: identity.id,\n type: identity.type,\n kind: identity.kind,\n site: identity.site,\n collection: identity.collection,\n locales: {\n [locale]: localeVersion,\n },\n };\n\n this.index.set(identity.id, newManifest);\n this.collections.add(identity.collection);\n }\n\n // Update content cache if provided\n if (content !== undefined) {\n const existingCache = this.contentCache.get(identity.id);\n if (existingCache) {\n // Update single locale content\n existingCache[locale] = content;\n } else {\n this.contentCache.set(identity.id, { [locale]: content });\n }\n }\n\n // Update name index\n const manifestToIndex = existing || this.index.get(identity.id)!;\n if (localeVersion.name) {\n if (!this.nameIndex.has(identity.collection)) {\n this.nameIndex.set(identity.collection, new Map());\n }\n this.nameIndex.get(identity.collection)!.set(localeVersion.name, manifestToIndex);\n }\n }\n\n /**\n * Remove a specific locale from an entry\n */\n removeLocale(id: string, locale: string): void {\n const manifest = this.index.get(id);\n if (!manifest || !manifest.locales[locale]) return;\n\n // Remove locale from manifest\n manifest.locales[locale] = undefined;\n\n // Remove from content cache\n const contentCache = this.contentCache.get(id);\n if (contentCache) {\n delete contentCache[locale];\n }\n\n // If no defined locales left, remove the entire entry\n const remainingLocales = Object.values(manifest.locales).filter((v) => v !== undefined);\n if (remainingLocales.length === 0) {\n this.removeEntry(id);\n }\n }\n\n /**\n * Remove an entry from the index\n */\n removeEntry(id: string): void {\n const manifest = this.index.get(id);\n if (!manifest) return;\n\n // Remove from name index\n for (const localeVersion of localesOf(manifest)) {\n if (localeVersion.name) {\n const collectionMap = this.nameIndex.get(manifest.collection);\n if (collectionMap) {\n collectionMap.delete(localeVersion.name);\n }\n break; // All locales have same name\n }\n }\n\n // Remove from primary index\n this.index.delete(id);\n\n // Remove from content cache\n this.contentCache.delete(id);\n }\n\n /**\n * Get cached content for a specific locale\n */\n getCachedContent(id: string, locale: string): ContentData | null {\n const localeContent = this.contentCache.get(id);\n return localeContent?.[locale] || null;\n }\n\n /**\n * Get content manifest\n */\n getManifest(id: string): ContentManifest | null {\n return this.index.get(id) || null;\n }\n\n /**\n * Find entry by name\n */\n getByName(collection: string, name: string, locale?: string): ContentManifest | null {\n const collectionMap = this.nameIndex.get(collection);\n if (!collectionMap) return null;\n\n const manifest = collectionMap.get(name);\n if (!manifest) return null;\n\n // If specific locale requested, check it exists\n if (locale && !manifest.locales[locale]) {\n return null;\n }\n\n return manifest;\n }\n\n /**\n * Generator for all manifests\n */\n *getAllManifests(): Generator<ContentManifest> {\n for (const manifest of this.index.values()) {\n yield manifest;\n }\n }\n\n /**\n * Generator for manifests by locale\n */\n *getManifestsByLocale(locale: string): Generator<ContentManifest> {\n for (const manifest of this.index.values()) {\n if (manifest.locales[locale]) {\n yield manifest;\n }\n }\n }\n\n /**\n * Generator for manifests by collection\n */\n *getManifestsByCollection(collection: string): Generator<ContentManifest> {\n for (const manifest of this.index.values()) {\n if (manifest.collection === collection) {\n yield manifest;\n }\n }\n }\n\n /**\n * Get the count of indexed content entries (unique IDs)\n */\n get entryCount(): number {\n return this.index.size;\n }\n\n /**\n * Clear all indexes\n */\n clear(): void {\n this.index.clear();\n this.contentCache.clear();\n this.nameIndex.clear();\n this.collections.clear();\n }\n}\n","import { BaseContentIndex } from './base-content-index';\n\n/**\n * V8-optimized index for blocks\n * Maintains collection->name->locale lookups\n */\nexport class BlockIndex extends BaseContentIndex {\n constructor(locales: string[]) {\n super();\n // locales parameter kept for future use\n }\n}\n","import { BaseContentIndex } from './base-content-index';\n\n/**\n * V8-optimized index for data collections\n * Maintains collection->name->locale lookups\n */\nexport class DataIndex extends BaseContentIndex {}\n","import { isContentPublished, localesOf, mapLocales } from './content-utils';\nimport type { ContentData, ContentIdentity, ContentManifest, LocaleVersion } from './types';\n\n/**\n * V8-optimized index for a single site\n * Maintains pathname lookups and collections for one site only\n */\nexport class SiteIndex {\n // Primary index: id -> ContentManifest\n private index: Map<string, ContentManifest> = new Map();\n\n // Content cache: id -> locale -> content (for small files)\n private contentCache: Map<string, Record<string, ContentData | null>> = new Map();\n\n // Pathname index: locale -> (pathname -> ContentManifest)\n // Locale level uses V8-optimized record, pathname level uses Map for dynamic keys\n private pathnameIndex: Record<string, Map<string, ContentManifest>>;\n\n // Previous pathname index for redirects: locale -> (oldPathname -> ContentManifest)\n // Same structure - record for locales, Map for pathnames\n private previousPathnameIndex: Record<string, Map<string, ContentManifest>>;\n\n // Collections used by this site\n readonly collections: Set<string> = new Set();\n\n constructor(\n siteName: string,\n private locales: string[],\n ) {\n // Initialize pathname indexes - V8-optimized record for locales, Maps for pathnames\n this.pathnameIndex = mapLocales(locales, () => new Map());\n this.previousPathnameIndex = mapLocales(locales, () => new Map());\n }\n\n /**\n * Add or update content in the index\n * Merges manifest locales and updates content cache if provided\n */\n addContent(identity: ContentIdentity, localeVersion: LocaleVersion, content?: ContentData | null): void {\n // Get existing manifest\n const existing = this.index.get(identity.id);\n const locale = localeVersion.locale;\n\n if (existing) {\n const existingLocale = existing.locales[locale];\n\n // Track what we need to rollback\n // First check what pathname currently maps to this manifest in our index\n // This handles in-place updates where the manifest object has already been modified\n let oldPathname: string | undefined;\n\n // Find all pathnames that currently point to this manifest\n for (const [pathname, indexedManifest] of this.pathnameIndex[locale].entries()) {\n if (indexedManifest === existing && pathname !== localeVersion.pathname) {\n oldPathname = pathname;\n break;\n }\n }\n\n // If we didn't find it in the index, fall back to what's stored in the existing locale\n if (!oldPathname && existingLocale?.pathname && existingLocale.pathname !== localeVersion.pathname) {\n oldPathname = existingLocale.pathname;\n }\n\n const hadExistingLocale = !!existingLocale;\n let deletedOldPathname = false;\n let addedNewPathname = false;\n const addedPreviousPathnames: string[] = [];\n\n // Update locale manifest if changed\n // We need to always check for pathname changes, even if other fields haven't changed\n // This handles in-place updates where the manifest is modified before calling addContent\n const needsUpdate =\n !existingLocale ||\n existingLocale.etag !== localeVersion.etag ||\n existingLocale.modified !== localeVersion.modified ||\n (oldPathname && oldPathname !== localeVersion.pathname);\n\n if (needsUpdate) {\n try {\n // Update the manifest locale\n existing.locales[locale] = localeVersion;\n\n // Update pathname indexes after manifest is updated\n if (localeVersion.pathname) {\n // If pathname changed, remove the old one\n if (oldPathname && oldPathname !== localeVersion.pathname) {\n this.pathnameIndex[locale].delete(oldPathname);\n deletedOldPathname = true;\n\n // Track the old pathname for redirects only if content is published\n if (isContentPublished(localeVersion)) {\n this.previousPathnameIndex[locale].set(oldPathname, existing);\n addedPreviousPathnames.push(oldPathname);\n }\n }\n\n // Add/update the new pathname\n this.pathnameIndex[locale].set(localeVersion.pathname, existing);\n addedNewPathname = true;\n }\n\n // Update previous pathname indexes from the manifest\n if (localeVersion.previousPathnames) {\n for (const prevPath of Object.keys(localeVersion.previousPathnames)) {\n // Only add if not already there\n if (!this.previousPathnameIndex[locale].has(prevPath)) {\n this.previousPathnameIndex[locale].set(prevPath, existing);\n addedPreviousPathnames.push(prevPath);\n }\n }\n }\n } catch (error) {\n // Rollback only what we changed\n if (hadExistingLocale) {\n existing.locales[locale] = existingLocale;\n } else {\n existing.locales[locale] = undefined;\n }\n\n // Rollback pathname index changes\n if (deletedOldPathname && oldPathname) {\n this.pathnameIndex[locale].set(oldPathname, existing);\n }\n if (addedNewPathname && localeVersion.pathname) {\n this.pathnameIndex[locale].delete(localeVersion.pathname);\n }\n\n // Rollback previous pathname additions\n for (const prevPath of addedPreviousPathnames) {\n this.previousPathnameIndex[locale].delete(prevPath);\n }\n\n throw error;\n }\n }\n } else {\n // New content - create ContentManifest with single locale\n const newManifest: ContentManifest = {\n id: identity.id,\n type: identity.type,\n kind: identity.kind,\n site: identity.site,\n collection: identity.collection,\n locales: {\n [locale]: localeVersion,\n },\n };\n\n this.index.set(identity.id, newManifest);\n this.collections.add(identity.collection);\n\n // Add pathname indexes\n if (localeVersion.pathname) {\n this.pathnameIndex[locale].set(localeVersion.pathname, newManifest);\n }\n if (localeVersion.previousPathnames) {\n for (const prevPath of Object.keys(localeVersion.previousPathnames)) {\n this.previousPathnameIndex[locale].set(prevPath, newManifest);\n }\n }\n }\n\n // Update content cache if provided\n if (content !== undefined) {\n const existingCache = this.contentCache.get(identity.id);\n if (existingCache) {\n // Update single locale content\n existingCache[locale] = content;\n } else {\n this.contentCache.set(identity.id, { [locale]: content });\n }\n }\n }\n\n /**\n * Remove a specific locale from an entry\n */\n removeLocale(id: string, locale: string): void {\n const manifest = this.index.get(id);\n if (!manifest || !manifest.locales[locale]) return;\n\n const localeVersion = manifest.locales[locale];\n\n // Remove from pathname indexes\n if (localeVersion.pathname) {\n this.pathnameIndex[locale].delete(localeVersion.pathname);\n }\n if (localeVersion.previousPathnames) {\n for (const prevPath of Object.keys(localeVersion.previousPathnames)) {\n this.previousPathnameIndex[locale].delete(prevPath);\n }\n }\n\n // Remove locale from manifest\n manifest.locales[locale] = undefined;\n\n // Remove from content cache\n const contentCache = this.contentCache.get(id);\n if (contentCache) {\n delete contentCache[locale];\n }\n\n // If no locales left, remove the entire entry\n if (Object.keys(manifest.locales).length === 0) {\n this.removeEntry(id);\n }\n }\n\n /**\n * Remove an entry from the index\n */\n removeEntry(id: string): void {\n const manifest = this.index.get(id);\n if (!manifest) return;\n\n // Remove from pathname indexes\n for (const localeVersion of localesOf(manifest)) {\n const { locale } = localeVersion;\n if (localeVersion.pathname) {\n this.pathnameIndex[locale].delete(localeVersion.pathname);\n }\n if (localeVersion.previousPathnames) {\n for (const prevPath of Object.keys(localeVersion.previousPathnames)) {\n this.previousPathnameIndex[locale].delete(prevPath);\n }\n }\n }\n\n // Remove from primary index\n this.index.delete(id);\n\n // Remove from content cache\n this.contentCache.delete(id);\n }\n\n /**\n * Get cached content for a specific locale\n */\n getCachedContent(id: string, locale: string): ContentData | null {\n const localeContent = this.contentCache.get(id);\n return localeContent?.[locale] || null;\n }\n\n /**\n * Get content manifest\n */\n getManifest(id: string): ContentManifest | null {\n return this.index.get(id) || null;\n }\n\n /**\n * Find content by pathname\n */\n getByPathname(pathname: string, locale?: string): ContentManifest | null {\n if (locale) {\n return this.pathnameIndex[locale]?.get(pathname) || null;\n }\n\n // Check all locales\n for (const locale of this.locales) {\n const manifest = this.pathnameIndex[locale].get(pathname);\n if (manifest) {\n return manifest;\n }\n }\n\n return null;\n }\n\n /**\n * Find content by previous pathname (for redirects)\n */\n getByPreviousPathname(pathname: string, locale?: string): ContentManifest | null {\n if (locale) {\n return this.previousPathnameIndex[locale]?.get(pathname) || null;\n }\n\n // Check all locales\n for (const locale of this.locales) {\n const manifest = this.previousPathnameIndex[locale].get(pathname);\n if (manifest) {\n return manifest;\n }\n }\n\n return null;\n }\n\n /**\n * Generator for all manifests\n */\n *getAllManifests(): Generator<ContentManifest> {\n for (const manifest of this.index.values()) {\n yield manifest;\n }\n }\n\n /**\n * Generator for manifests by locale\n */\n *getManifestsByLocale(locale: string): Generator<ContentManifest> {\n for (const manifest of this.index.values()) {\n if (manifest.locales[locale]) {\n yield manifest;\n }\n }\n }\n\n /**\n * Get the count of indexed content entries (unique IDs)\n */\n get entryCount(): number {\n return this.index.size;\n }\n\n /**\n * Clear all indexes\n */\n clear(): void {\n this.index.clear();\n this.contentCache.clear();\n // Clear all Maps in the pathname indexes\n for (const locale of this.locales) {\n this.pathnameIndex[locale].clear();\n this.previousPathnameIndex[locale].clear();\n }\n this.collections.clear();\n }\n}\n","import { BlockIndex } from './block-index';\nimport { localesOf, mapSiteNames } from './content-utils';\nimport { DataIndex } from './data-index';\nimport { SiteIndex } from './site-index';\nimport type { ContentData, ContentIdentity, ContentManifest, LocaleVersion, SitesConfig } from './types';\n\n/**\n * ContentIndex coordinates between per-site indexes and the block index\n * This provides efficient filtering by routing to the appropriate specialized index\n */\n// Use global registry to survive module reloads in development\nconst globalCache = (globalThis as any).__CONLOCA_CONTENT_INDEX_CACHE__ || {};\nif (!(globalThis as any).__CONLOCA_CONTENT_INDEX_CACHE__) {\n (globalThis as any).__CONLOCA_CONTENT_INDEX_CACHE__ = globalCache;\n}\n\nexport class ContentIndex {\n // Use global cache instead of static cache\n private static get cache() {\n return globalCache;\n }\n\n // Per-site indexes using V8-optimized object\n private siteIndexes: Record<string, SiteIndex | undefined>;\n\n // Single block index\n private blockIndex: BlockIndex;\n\n // Single data index\n private dataIndex: DataIndex;\n\n private constructor(private sitesConfig: SitesConfig) {\n // Initialize block index\n this.blockIndex = new BlockIndex(sitesConfig.globalLocales);\n\n // Initialize data index\n this.dataIndex = new DataIndex();\n\n // Initialize V8-optimized site indexes\n this.siteIndexes = mapSiteNames(sitesConfig, (siteName) => {\n const siteConfig = sitesConfig.sites[siteName];\n return new SiteIndex(siteName, siteConfig.locales);\n });\n }\n\n /**\n * Get cached index or create a new one\n */\n static async getCachedOrCreate(contentRoot: string, sitesConfig: SitesConfig): Promise<ContentIndex> {\n if (!ContentIndex.cache[contentRoot]) {\n ContentIndex.cache[contentRoot] = new ContentIndex(sitesConfig);\n }\n return ContentIndex.cache[contentRoot];\n }\n\n /**\n * Clear all cached indexes\n */\n static clearCache(): void {\n Object.keys(globalCache).forEach((key) => delete globalCache[key]);\n }\n\n /**\n * Create a new index without caching - for testing\n */\n static createUncached(sitesConfig: SitesConfig): ContentIndex {\n return new ContentIndex(sitesConfig);\n }\n\n /**\n * Add or update content in the appropriate index\n * Updates a single locale's manifest and content cache if provided\n */\n addContent(identity: ContentIdentity, localeVersion: LocaleVersion, content?: ContentData | null): void {\n // Validate that blocks and data don't have a site\n if ((identity.kind === 'block' || identity.kind === 'data') && identity.site) {\n throw new Error(`${identity.kind} cannot have a site property`);\n }\n // Validate that pages must have a site\n if (identity.kind === 'page' && !identity.site) {\n throw new Error('Pages must have a site property');\n }\n\n if (identity.kind === 'block') {\n this.blockIndex.addContent(identity, localeVersion, content);\n } else if (identity.kind === 'data') {\n this.dataIndex.addContent(identity, localeVersion, content);\n } else {\n const siteIndex = this.siteIndexes[identity.site!];\n if (siteIndex) {\n siteIndex.addContent(identity, localeVersion, content);\n }\n }\n }\n\n /**\n * Remove a specific locale from content\n */\n removeLocale(id: string, locale: string): void {\n const manifest = this.getManifest(id);\n if (!manifest) return;\n\n // Remove from the appropriate index\n if (manifest.kind === 'block') {\n this.blockIndex.removeLocale(id, locale);\n } else if (manifest.kind === 'data') {\n this.dataIndex.removeLocale(id, locale);\n } else {\n const siteIndex = this.siteIndexes[manifest.site!];\n if (siteIndex) {\n siteIndex.removeLocale(id, locale);\n }\n }\n }\n\n /**\n * Get cached content\n */\n getCachedContent(id: string, locale: string): ContentData | null {\n const manifest = this.getManifest(id);\n if (!manifest) return null;\n\n if (manifest.kind === 'block') {\n return this.blockIndex.getCachedContent(id, locale);\n }\n if (manifest.kind === 'data') {\n return this.dataIndex.getCachedContent(id, locale);\n }\n const siteIndex = this.siteIndexes[manifest.site!];\n return siteIndex ? siteIndex.getCachedContent(id, locale) : null;\n }\n\n /**\n * Remove an entry from all indexes\n */\n removeEntry(id: string): void {\n // Try blocks first\n this.blockIndex.removeEntry(id);\n\n // Try data\n this.dataIndex.removeEntry(id);\n\n // Then try each site\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n siteIndex.removeEntry(id);\n }\n }\n }\n\n /**\n * Get content manifest for a content ID\n */\n getManifest(id: string): ContentManifest | null {\n // Check blocks first\n let manifest = this.blockIndex.getManifest(id);\n if (manifest) return manifest;\n\n // Check data\n manifest = this.dataIndex.getManifest(id);\n if (manifest) return manifest;\n\n // Then check each site\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n manifest = siteIndex.getManifest(id);\n if (manifest) return manifest;\n }\n }\n\n return null;\n }\n\n /**\n * Get a specific locale manifest\n */\n getLocaleVersion(id: string, locale: string): LocaleVersion | null {\n const manifest = this.getManifest(id);\n if (!manifest) return null;\n return manifest.locales[locale] || null;\n }\n\n /**\n * Get site index\n */\n getSiteIndex(site: string): SiteIndex | null {\n return this.siteIndexes[site] || null;\n }\n\n /**\n * Get block index\n */\n getBlockIndex(): BlockIndex {\n return this.blockIndex;\n }\n\n /**\n * Find content by pathname (delegates to site indexes)\n */\n getByPathname(site: string, pathname: string, locale?: string): ContentManifest | null {\n const siteIndex = this.siteIndexes[site];\n return siteIndex ? siteIndex.getByPathname(pathname, locale) : null;\n }\n\n /**\n * Find content by previous pathname (for redirects)\n */\n getByPreviousPathname(site: string, pathname: string, locale?: string): ContentManifest | null {\n const siteIndex = this.siteIndexes[site];\n return siteIndex ? siteIndex.getByPreviousPathname(pathname, locale) : null;\n }\n\n /**\n * Find block by name\n */\n getBlockByName(collection: string, name: string, locale?: string): ContentManifest | null {\n return this.blockIndex.getByName(collection, name, locale);\n }\n\n /**\n * Get data index\n */\n getDataIndex(): DataIndex {\n return this.dataIndex;\n }\n\n /**\n * Find data entry by name\n */\n getDataByName(collection: string, name: string, locale?: string): ContentManifest | null {\n return this.dataIndex.getByName(collection, name, locale);\n }\n\n /**\n * Get all collections for data\n */\n getDataCollections(): Set<string> {\n return this.dataIndex.collections;\n }\n\n /**\n * List all content (for iteration)\n */\n *listAllContent(): Generator<ContentManifest> {\n // Yield all blocks\n yield* this.blockIndex.getAllManifests();\n\n // Yield all data entries\n yield* this.dataIndex.getAllManifests();\n\n // Yield all site entries\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n yield* siteIndex.getAllManifests();\n }\n }\n }\n\n /**\n * Generator for all sites\n */\n *allSites(): Generator<string> {\n for (const site in this.siteIndexes) {\n if (this.siteIndexes[site]) {\n yield site;\n }\n }\n }\n\n /**\n * Get all collections for a site\n */\n getCollectionsForSite(site: string): Set<string> {\n const siteIndex = this.siteIndexes[site];\n return siteIndex ? siteIndex.collections : new Set();\n }\n\n /**\n * Get all collections for blocks\n */\n getBlockCollections(): Set<string> {\n return this.blockIndex.collections;\n }\n\n /**\n * Get default locale for a site\n */\n getDefaultLocale(site: string): string {\n // This method should only be called for pages, but handle gracefully\n if (!site) {\n return this.sitesConfig.globalLocales[0];\n }\n const siteConfig = this.sitesConfig.sites[site];\n return siteConfig?.defaultLocale || this.sitesConfig.globalLocales[0];\n }\n\n /**\n * Find content missing a specific locale\n */\n *findUntranslatedContent(\n targetLocale: string,\n options?: {\n excludeSites?: string[];\n includeUnpublished?: boolean;\n },\n ): Generator<ContentManifest> {\n // Always check blocks as they don't belong to any site\n for (const manifest of this.blockIndex.getAllManifests()) {\n if (!manifest.locales[targetLocale]) {\n // Check if we should include unpublished content\n if (!options?.includeUnpublished) {\n // Need to check if any locale is published\n let hasPublishedLocale = false;\n for (const locale of localesOf(manifest)) {\n if (!locale.unpublishAt || new Date(locale.unpublishAt) > new Date()) {\n hasPublishedLocale = true;\n break;\n }\n }\n if (!hasPublishedLocale) continue;\n }\n yield manifest;\n }\n }\n\n // Check each site\n for (const siteName in this.siteIndexes) {\n const siteIndex = this.siteIndexes[siteName];\n if (!siteIndex || options?.excludeSites?.includes(siteName)) continue;\n\n for (const manifest of siteIndex.getAllManifests()) {\n if (!manifest.locales[targetLocale]) {\n // Check if we should include unpublished content\n if (!options?.includeUnpublished) {\n let hasPublishedLocale = false;\n for (const locale of localesOf(manifest)) {\n if (!locale.unpublishAt || new Date(locale.unpublishAt) > new Date()) {\n hasPublishedLocale = true;\n break;\n }\n }\n if (!hasPublishedLocale) continue;\n }\n yield manifest;\n }\n }\n }\n }\n\n /**\n * Generators for efficient filtering\n */\n\n *getManifestsForKind(kind: 'block' | 'page' | 'data'): Generator<ContentManifest> {\n if (kind === 'block') {\n yield* this.blockIndex.getAllManifests();\n } else if (kind === 'data') {\n yield* this.dataIndex.getAllManifests();\n } else {\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n yield* siteIndex.getAllManifests();\n }\n }\n }\n }\n\n *getManifestsForSite(site: string): Generator<ContentManifest> {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n yield* siteIndex.getAllManifests();\n }\n }\n\n *getManifestsForSiteLocale(site: string, locale: string): Generator<ContentManifest> {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n yield* siteIndex.getManifestsByLocale(locale);\n }\n }\n\n *getManifestsForSiteCollection(site: string, collection: string): Generator<ContentManifest> {\n // For regular sites, we need to filter by collection\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n for (const manifest of siteIndex.getAllManifests()) {\n if (manifest.collection === collection) {\n yield manifest;\n }\n }\n }\n }\n\n *getManifestsForLocale(locale: string): Generator<ContentManifest> {\n // Yield from blocks\n yield* this.blockIndex.getManifestsByLocale(locale);\n\n // Yield from data\n yield* this.dataIndex.getManifestsByLocale(locale);\n\n // Yield from all sites\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n yield* siteIndex.getManifestsByLocale(locale);\n }\n }\n }\n\n *getManifestsForCollection(collection: string): Generator<ContentManifest> {\n // Check blocks first\n yield* this.blockIndex.getManifestsByCollection(collection);\n\n // Check data\n yield* this.dataIndex.getManifestsByCollection(collection);\n\n // Then check all sites\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n for (const manifest of siteIndex.getAllManifests()) {\n if (manifest.collection === collection) {\n yield manifest;\n }\n }\n }\n }\n }\n\n /**\n * Get the count of indexed content entries\n */\n get entryCount(): number {\n let count = this.blockIndex.entryCount;\n count += this.dataIndex.entryCount;\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n count += siteIndex.entryCount;\n }\n }\n return count;\n }\n\n /**\n * Clear all indexes\n */\n clear(): void {\n this.blockIndex.clear();\n this.dataIndex.clear();\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n siteIndex.clear();\n }\n }\n }\n}\n","import type { ContentAPI } from './content-api.interface';\nimport type { DataIndex } from './data-index';\nimport type { ContentManifest, CreateResult } from './types';\n\nexport interface DataFilters {\n collection?: string;\n locales?: string[];\n}\n\nexport interface CreateDataInput {\n collection: string;\n name: string;\n meta?: { title?: string; description?: string; [key: string]: unknown };\n locales: {\n [locale: string]: {\n publishAt?: string | null | false;\n unpublishAt?: string | null | false;\n meta?: { title?: string; description?: string; [key: string]: unknown };\n content: {\n data: Record<string, unknown>;\n };\n };\n };\n}\n\nexport class Data {\n constructor(\n private api: ContentAPI,\n private dataIndex: DataIndex,\n ) {}\n\n // Content discovery\n *listContent(filters?: DataFilters): Generator<ContentManifest> {\n // Choose the most efficient method based on filters\n if (filters?.collection) {\n if (filters.locales && filters.locales.length > 0) {\n // Filter by locales after getting collection entries\n for (const manifest of this.dataIndex.getManifestsByCollection(filters.collection)) {\n if (filters.locales.some((locale) => manifest.locales[locale])) {\n yield manifest;\n }\n }\n } else {\n yield* this.dataIndex.getManifestsByCollection(filters.collection);\n }\n } else if (filters?.locales && filters.locales.length > 0) {\n // For multiple locales, we need to check each\n for (const manifest of this.dataIndex.getAllManifests()) {\n if (filters.locales.some((locale) => manifest.locales[locale])) {\n yield manifest;\n }\n }\n } else {\n yield* this.dataIndex.getAllManifests();\n }\n }\n\n // Get all data collections\n get collections(): Set<string> {\n return this.dataIndex.collections;\n }\n\n // Data operations (returns null if not found)\n getByName(collection: string, name: string, locale?: string): ContentManifest | null {\n return this.dataIndex.getByName(collection, name, locale);\n }\n\n // Check if data name is available\n isNameAvailable(collection: string, name: string, excludeId?: string): boolean {\n const existing = this.getByName(collection, name);\n return !existing || existing.id === excludeId;\n }\n\n // Get the ID of content that conflicts with a data name\n getNameConflict(collection: string, name: string, excludeId?: string): string | null {\n const existing = this.getByName(collection, name);\n if (existing && existing.id !== excludeId) {\n return existing.id;\n }\n return null;\n }\n\n // Check if data name is valid\n isDataNameValid(dataName: string): boolean {\n // Data names must not be empty\n if (!dataName || dataName.trim() === '') {\n return false;\n }\n\n // Data names must not contain dots (would interfere with locale suffixes)\n if (dataName.includes('.')) {\n return false;\n }\n\n // Data names must not contain path separators\n if (dataName.includes('/') || dataName.includes('\\\\')) {\n return false;\n }\n\n // Data names should only contain alphanumeric, hyphens, underscores\n return /^[a-zA-Z0-9_-]+$/.test(dataName);\n }\n\n // Create data entry with name validation\n async create(input: CreateDataInput): Promise<CreateResult> {\n // Validate data name\n if (!this.isDataNameValid(input.name)) {\n return {\n success: false,\n reason: 'invalid_name',\n error: new Error(`Invalid data name: ${input.name}`),\n };\n }\n\n // Check if name is already taken in any locale\n const existing = this.getByName(input.collection, input.name);\n if (existing) {\n return {\n success: false,\n reason: 'name_taken',\n error: new Error(`Data name ${input.name} already exists in collection ${input.collection}`),\n };\n }\n\n // Create the content\n return this.api.createContent({\n kind: 'data',\n collection: input.collection,\n type: 'json',\n name: input.name,\n meta: input.meta,\n locales: input.locales,\n });\n }\n}\n","/**\n * Zero-allocation JSON whitespace-skipping stream transform\n * Skips whitespace outside of JSON strings, preserving whitespace inside strings\n * Optimized to process multiple bytes at once when possible\n */\nexport class JsonWhitespaceSkippingView {\n private inString = false;\n private escaped = false;\n private singleByte = new Uint8Array(1); // Reused allocation for single bytes\n\n constructor(private downstream: { update(data: Uint8Array): void }) {}\n\n /**\n * Process a single byte from JSON stream\n * @param byte - The byte to process\n */\n updateByte(byte: number): void {\n let shouldInclude = false;\n\n if (this.inString) {\n // Inside string: always include the byte\n shouldInclude = true;\n\n if (this.escaped) {\n this.escaped = false;\n } else if (byte === 0x5c) {\n // backslash\n this.escaped = true;\n } else if (byte === 0x22) {\n // quote\n this.inString = false;\n }\n } else {\n // Outside string: check for string start or skip whitespace\n if (byte === 0x22) {\n // 0x22 is the double quote character (\")\n // quote\n this.inString = true;\n shouldInclude = true;\n }\n // Check tab (0x09) first as it's the most common whitespace in our tab-indented VXJSON files\n // Then space (0x20), newline (0x0a), carriage return (0x0d)\n else if (byte !== 0x09 && byte !== 0x20 && byte !== 0x0a && byte !== 0x0d) {\n // Not whitespace, include it\n shouldInclude = true;\n }\n // Skip whitespace outside strings\n }\n\n if (shouldInclude) {\n this.singleByte[0] = byte;\n this.downstream.update(this.singleByte);\n }\n }\n\n /**\n * Process a buffer range with simple batching\n * Collects consecutive bytes that should be included\n * @param buffer - The buffer to process\n * @param start - Start position (inclusive)\n * @param end - End position (exclusive)\n */\n updateBuffer(buffer: Uint8Array, start = 0, end = buffer.length): void {\n let pos = start;\n let runStart = start;\n\n while (pos < end) {\n const byte = buffer[pos];\n let shouldInclude = false;\n\n if (this.inString) {\n // Inside string: always include\n shouldInclude = true;\n\n if (this.escaped) {\n this.escaped = false;\n } else if (byte === 0x5c) {\n // backslash\n this.escaped = true;\n } else if (byte === 0x22) {\n // quote - end of string\n this.inString = false;\n } else {\n // Regular character - use indexOf to skip to next quote\n pos++;\n let searchPos = pos;\n\n while (searchPos < end) {\n const quotePos = buffer.indexOf(0x22, searchPos);\n if (quotePos === -1 || quotePos >= end) {\n // No more quotes\n pos = end;\n break;\n }\n\n // Count consecutive backslashes before the quote\n let backslashCount = 0;\n let checkPos = quotePos - 1;\n while (checkPos >= 0 && buffer[checkPos] === 0x5c) {\n backslashCount++;\n checkPos--;\n }\n\n if (backslashCount % 2 === 0) {\n // Even backslashes (including 0) - quote is not escaped\n pos = quotePos + 1;\n this.inString = false;\n break;\n }\n // Odd backslashes - quote is escaped, continue searching\n searchPos = quotePos + 1;\n }\n continue; // Skip the pos++ at the bottom\n }\n } else {\n // Outside string\n if (byte === 0x22) {\n // quote - start of string\n this.inString = true;\n shouldInclude = true;\n // Check tab (0x09) first as it's the most common whitespace in our tab-indented VXJSON files\n // Then space (0x20), newline (0x0a), carriage return (0x0d)\n } else if (byte !== 0x09 && byte !== 0x20 && byte !== 0x0a && byte !== 0x0d) {\n // Not whitespace\n shouldInclude = true;\n }\n }\n\n if (shouldInclude) {\n // Continue the run\n pos++;\n } else {\n // End of run - send what we have\n if (pos > runStart) {\n this.downstream.update(buffer.subarray(runStart, pos));\n }\n pos++;\n runStart = pos;\n }\n }\n\n // Send any remaining bytes\n if (pos > runStart) {\n this.downstream.update(buffer.subarray(runStart, pos));\n }\n }\n\n /**\n * Reset the parser state\n */\n reset(): void {\n this.inString = false;\n this.escaped = false;\n }\n}\n","/**\n * Convert bytes to URL-safe base64\n * Replaces + with -, / with _, and removes = padding\n */\nexport function toUrlSafeBase64(bytes: Uint8Array): string {\n const b64 = Buffer.from(bytes).toString('base64');\n const buf = Buffer.from(b64, 'ascii');\n let write = 0;\n for (let read = 0; read < buf.length; read++) {\n const c = buf[read];\n if (c === 0x2b) {\n // '+'\n buf[write++] = 0x2d; // '-'\n } else if (c === 0x2f) {\n // '/'\n buf[write++] = 0x5f; // '_'\n } else if (c === 0x3d) {\n // '='\n // skip padding\n } else {\n buf[write++] = c;\n }\n }\n return buf.subarray(0, write).toString('ascii');\n}\n\n/**\n * Convert BigInt to URL-safe base64\n * @param value - The BigInt value to convert\n * @returns URL-safe base64 string representation\n */\nexport function bigintToUrlSafeBase64(value: bigint): string {\n // Convert BigInt to 8-byte buffer\n const hashBuffer = new Uint8Array(8);\n const dataView = new DataView(hashBuffer.buffer);\n dataView.setBigUint64(0, value, false); // big-endian\n return toUrlSafeBase64(hashBuffer);\n}\n","import { xxh3 } from '@node-rs/xxhash';\nimport { createHash } from 'crypto';\nimport { JsonWhitespaceSkippingView } from './json-whitespace-view';\nimport { bigintToUrlSafeBase64, toUrlSafeBase64 } from './url-safe-base64';\n\n/**\n * Dual ETag system for content API\n * - Meta ETag: Based on non-derived LocaleManifest fields (using xxHash)\n * - Content ETag: Based on ContentProp.content (using SHA256)\n * Both skip whitespace to allow pretty-printing without affecting hashes\n *\n * Format: \"metaEtag.contentEtag\" in query strings\n */\n\n/**\n * Calculate metadata ETag using xxHash from buffer view\n * @param buffer - The file buffer view\n * @param start - Start position (inclusive)\n * @param end - End position (exclusive), or -1 for entire buffer\n */\nexport function calculateMetaEtagFromBuffer(buffer: Uint8Array, start = 0, end = -1): string {\n const actualEnd = end === -1 ? buffer.length : end;\n const hasher = xxh3.Xxh3.withSeed(0n);\n const jsonView = new JsonWhitespaceSkippingView(hasher);\n\n jsonView.updateBuffer(buffer, start, actualEnd);\n\n const hashValue = hasher.digest();\n return bigintToUrlSafeBase64(hashValue);\n}\n\n/**\n * Calculate content ETag using SHA256 from buffer view\n * @param buffer - The file buffer view\n * @param start - Start position (inclusive)\n * @param end - End position (exclusive), or -1 for entire buffer\n */\nexport function calculateContentEtagFromBuffer(buffer: Uint8Array, start = 0, end = -1): string {\n const actualEnd = end === -1 ? buffer.length : end;\n const hasher = createHash('sha256');\n const jsonView = new JsonWhitespaceSkippingView(hasher);\n\n jsonView.updateBuffer(buffer, start, actualEnd);\n\n return toUrlSafeBase64(hasher.digest() as Uint8Array);\n}\n\nconst dashCode = '-'.charCodeAt(0); // 45\nconst newlineCode = '\\n'.charCodeAt(0); // 10\n\n/**\n * Find the content start position in MDX buffer (after second ---)\n * @param buffer - The MDX content buffer\n * @returns Position where content starts, or -1 if not found\n */\nexport function findMdxContentStartPosition(buffer: Uint8Array): number {\n let dashCount = 0;\n let i = 0;\n\n // Look for the second occurrence of \"---\\n\"\n while (i < buffer.length - 4) {\n if (\n buffer[i] === dashCode &&\n buffer[i + 1] === dashCode &&\n buffer[i + 2] === dashCode &&\n buffer[i + 3] === newlineCode\n ) {\n dashCount++;\n if (dashCount === 2) {\n // Found second ---, now look for the following newline to get content start\n i += 4; // Skip past \"---\\n\"\n if (i < buffer.length && buffer[i] === newlineCode) {\n return i + 1; // Return position after the empty line\n }\n return i; // Return position right after \"---\\n\"\n }\n i += 4; // Skip this \"---\\n\" and continue looking\n } else {\n // Use indexOf to skip ahead faster instead of incrementing by 1\n const nextDashPos = buffer.indexOf(dashCode, i + 1);\n if (nextDashPos === -1) {\n break; // No more dashes found\n }\n i = nextDashPos;\n }\n }\n\n return -1; // Not found\n}\n\n/**\n * Calculate both ETags from an MDX buffer\n *\n * MDX files use YAML frontmatter which has different characteristics than JSON:\n * - YAML does not require quotes around keys or string values\n * - YAML allows multiple formatting styles (flow vs block style)\n * - YAML field order is not significant for parsing\n *\n * Unlike VXJSON which requires \"content\" to be the last field and needs special\n * parsing to validate structure, YAML frontmatter can be hashed as-is because:\n * 1. The frontmatter boundaries are clearly delimited by ---\n * 2. Different YAML formatting of the same data SHOULD produce different hashes\n * (e.g., flow style [a,b] vs block style with dashes)\n * 3. There's no requirement to validate field ordering\n *\n * This means we can directly hash the YAML bytes without any whitespace\n * normalization or parsing, which is both simpler and more correct.\n *\n * @param buffer - The complete file buffer\n * @param contentStartPos - Position where content starts (after second ---), or -1 if no content\n */\nexport function calculateEtagsFromMdxBuffer(\n buffer: Uint8Array,\n contentStartPos: number,\n): {\n metaEtag: string;\n contentEtag: string;\n} {\n if (contentStartPos === -1) {\n // No content, only frontmatter - hash entire buffer as metadata\n const hasher = xxh3.Xxh3.withSeed(0n);\n hasher.update(buffer);\n const hashBigInt = hasher.digest();\n const metaEtag = bigintToUrlSafeBase64(hashBigInt);\n\n return {\n metaEtag,\n contentEtag: calculateContentEtagFromBuffer(new Uint8Array(0)), // empty content\n };\n }\n\n // For MDX, we hash the YAML frontmatter as-is (including the --- markers)\n // This is different from JSON where we need to parse and validate structure\n const metaHasher = xxh3.Xxh3.withSeed(0n);\n metaHasher.update(buffer.subarray(0, contentStartPos));\n const metaHashBigInt = metaHasher.digest();\n const metaEtag = bigintToUrlSafeBase64(metaHashBigInt);\n\n // Content is everything after the second ---\n const contentHasher = createHash('sha256');\n contentHasher.update(buffer.subarray(contentStartPos));\n const contentEtag = toUrlSafeBase64(contentHasher.digest() as Uint8Array);\n\n return {\n metaEtag,\n contentEtag,\n };\n}\n\n/**\n * Combined ETag structure\n */\nexport interface DualEtag {\n meta: string;\n content: string;\n}\n\n/**\n * Format dual ETags for query string: \"meta.content\"\n */\nexport function formatDualEtag(etags: DualEtag): string {\n return `${etags.meta}.${etags.content}`;\n}\n\n/**\n * Parse dual ETags from query string: \"meta.content\"\n */\nexport function parseDualEtag(etag: string): DualEtag | null {\n const parts = etag.split('.');\n if (parts.length !== 2) return null;\n\n return {\n meta: parts[0],\n content: parts[1],\n };\n}\n\n/**\n * Check if etag matches either meta or content\n */\nexport function matchesEtag(\n providedEtag: string,\n currentMeta: string,\n currentContent: string,\n): {\n matches: boolean;\n metaChanged: boolean;\n contentChanged: boolean;\n} {\n const parsed = parseDualEtag(providedEtag);\n if (!parsed) {\n return {\n matches: false,\n metaChanged: true,\n contentChanged: true,\n };\n }\n\n const metaChanged = parsed.meta !== currentMeta;\n const contentChanged = parsed.content !== currentContent;\n\n return {\n matches: !metaChanged && !contentChanged,\n metaChanged,\n contentChanged,\n };\n}\n","import { xxh3 } from '@node-rs/xxhash';\nimport { createHash } from 'crypto';\nimport sortKeys from 'sort-keys';\nimport { JsonWhitespaceSkippingView } from './json-whitespace-view';\nimport type { ContentData, ContentMeta, VXJSONFile } from './types';\nimport { bigintToUrlSafeBase64, toUrlSafeBase64 } from './url-safe-base64';\n\n// Reusable TextDecoder instance - safe to reuse as it's stateless\nconst textDecoder = new TextDecoder();\n\n// Pre-allocated content marker for efficiency\nconst CONTENT_MARKER = new TextEncoder().encode('\"content\":');\n\n/**\n * Calculate metadata ETag using xxHash from buffer view\n * @param buffer - The file buffer view\n * @param start - Start position (inclusive)\n * @param end - End position (exclusive), or -1 for entire buffer\n */\nfunction calculateMetaEtagFromBuffer(buffer: Uint8Array, start = 0, end = -1): string {\n const actualEnd = end === -1 ? buffer.length : end;\n const hasher = xxh3.Xxh3.withSeed(0n);\n const jsonView = new JsonWhitespaceSkippingView(hasher);\n\n jsonView.updateBuffer(buffer, start, actualEnd);\n\n const hashValue = hasher.digest();\n return bigintToUrlSafeBase64(hashValue);\n}\n\n/**\n * Calculate both ETags from a VXJSON buffer using views\n * Finds the \"content\" field position and validates it's the last field\n * @param buffer - The complete file buffer\n * @returns Result with ETags or validation error\n */\nfunction calculateEtagsFromVXJSONBuffer(\n buffer: Uint8Array,\n allowTruncated = false,\n):\n | { success: true; metaEtag: string; contentEtag?: string; contentStartPos: number }\n | { success: false; error: 'content_not_last' | 'invalid_json' } {\n let pos = 0;\n let depth = 0;\n let inString = false;\n let escaped = false;\n let contentStartPos = -1;\n let foundContentAtRoot = false;\n let expectingKey = false; // At root level, are we expecting a key?\n let expectingValue = false; // At root level, are we expecting a value?\n let keyStart = -1;\n\n // Skip whitespace and find opening brace\n while (\n pos < buffer.length &&\n (buffer[pos] === 0x20 || buffer[pos] === 0x09 || buffer[pos] === 0x0a || buffer[pos] === 0x0d)\n ) {\n pos++;\n }\n\n if (pos >= buffer.length || buffer[pos] !== 0x7b) {\n // {\n return { success: false, error: 'invalid_json' };\n }\n\n depth = 1;\n expectingKey = true; // After { we expect a key\n pos++;\n\n // Parse JSON structure\n while (pos < buffer.length && depth > 0) {\n const byte = buffer[pos];\n\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (byte === 0x5c) {\n // backslash\n escaped = true;\n } else if (byte === 0x22) {\n // quote\n inString = false;\n\n // If we were in a root key, check if it's \"content\"\n if (depth === 1 && expectingKey && keyStart >= 0) {\n const keyLength = pos - keyStart + 1; // +1 to include current quote\n\n // First check if we already found content and this is any key after it\n if (foundContentAtRoot) {\n // Check if this is another \"content\" key (duplicate)\n if (keyLength === 9) {\n let isContent = true;\n for (let i = 0; i < 7; i++) {\n if (buffer[keyStart + 1 + i] !== CONTENT_MARKER[i + 1]) {\n isContent = false;\n break;\n }\n }\n if (isContent) {\n // Duplicate content key\n return { success: false, error: 'invalid_json' };\n }\n }\n // Any other key after content is an error\n return { success: false, error: 'content_not_last' };\n }\n\n // Check if this key is \"content\" (7 chars + 2 quotes = 9 total)\n if (keyLength === 9) {\n let isContent = true;\n // Compare \"content\" part (skip opening quote)\n for (let i = 0; i < 7; i++) {\n if (buffer[keyStart + 1 + i] !== CONTENT_MARKER[i + 1]) {\n isContent = false;\n break;\n }\n }\n\n if (isContent) {\n // Found \"content\" at root level for the first time\n foundContentAtRoot = true;\n contentStartPos = keyStart; // Start of the quoted key\n }\n }\n\n expectingKey = false;\n expectingValue = true; // After a key, we expect : then value\n keyStart = -1;\n }\n }\n } else {\n // Not in string\n if (byte === 0x22) {\n // quote\n inString = true;\n\n // Check if this is a root-level key\n if (depth === 1 && expectingKey) {\n keyStart = pos;\n }\n } else if (byte === 0x7b || byte === 0x5b) {\n // { or [\n depth++;\n if (depth === 1 && expectingValue) {\n expectingValue = false; // We got our value\n }\n } else if (byte === 0x7d || byte === 0x5d) {\n // } or ]\n depth--;\n if (depth === 0) {\n break; // Done parsing\n }\n } else if (byte === 0x3a && depth === 1) {\n // : at root level\n if (!expectingValue) {\n return { success: false, error: 'invalid_json' };\n }\n // After : we're still expecting a value\n } else if (byte === 0x2c && depth === 1) {\n // , at root level\n expectingKey = true;\n expectingValue = false;\n } else if (depth === 1 && expectingValue && byte !== 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d) {\n // Non-whitespace at root level when expecting value\n // Could be number, true, false, null\n expectingValue = false; // We're consuming the value\n }\n }\n\n pos++;\n }\n\n // For truncated JSON (4KB parsing), we can still succeed if we found the content position\n const isTruncated = depth !== 0;\n\n // If JSON is truncated but we don't allow it, return invalid_json\n if (isTruncated && !allowTruncated) {\n return { success: false, error: 'invalid_json' };\n }\n\n if (contentStartPos === -1) {\n // No content field found - this is valid for both complete and truncated JSON\n return {\n success: true,\n metaEtag: calculateMetaEtagFromBuffer(buffer),\n contentStartPos: -1,\n };\n }\n\n // Found content field - proceed with ETag calculation\n if (isTruncated) {\n // For truncated JSON, we can still calculate metadata ETag up to content position\n return {\n success: true,\n metaEtag: calculateMetaEtagFromBuffer(buffer, 0, contentStartPos),\n contentStartPos,\n // Don't calculate contentEtag for truncated content\n };\n }\n\n // Find the end of metadata (before \"content\":)\n let metaEnd = contentStartPos - 1;\n while (metaEnd > 0) {\n const byte = buffer[metaEnd];\n if (byte === 0x2c || byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d) {\n metaEnd--;\n } else {\n break;\n }\n }\n\n // Hash metadata section: wrap in { } and exclude content field\n const metaHasher = xxh3.Xxh3.withSeed(0n);\n const metaView = new JsonWhitespaceSkippingView(metaHasher);\n const openBrace = new Uint8Array([0x7b]); // {\n const closeBrace = new Uint8Array([0x7d]); // }\n\n metaHasher.update(openBrace);\n metaView.updateBuffer(buffer, 1, metaEnd); // Skip opening brace, stop before content\n metaHasher.update(closeBrace);\n\n const metaHashValue = metaHasher.digest();\n const metaEtag = bigintToUrlSafeBase64(metaHashValue);\n\n // Hash content section: wrap as {\"content\": ... }\n const contentHasher = createHash('sha256');\n const contentView = new JsonWhitespaceSkippingView(contentHasher);\n\n contentHasher.update(openBrace); // {\n contentView.updateBuffer(buffer, contentStartPos, buffer.length - 1); // content field to end, exclude final }\n contentHasher.update(closeBrace); // }\n\n const contentEtag = toUrlSafeBase64(contentHasher.digest() as Uint8Array);\n\n return {\n success: true,\n metaEtag,\n contentEtag,\n contentStartPos,\n };\n}\n\n/**\n * VXJSON (Variant JSON) module for parsing and serializing VXJSON files\n *\n * VXJSON is a specialized JSON format that guarantees:\n * 1. The root is always an object (never an array or primitive)\n * 2. The \"content\" field always comes last in the object\n * 3. Field order is deterministic for consistent ETag calculation\n * 4. Metadata fits within 4085 bytes, ensuring \"content\" field is found within first 4KB\n * 5. First 4KB must either be complete JSON OR end exactly with '\"content\":'\n *\n * This format enables efficient 4KB parsing where only the first 4KB of a file\n * needs to be read to extract all metadata and locate the content position.\n * The constraint that 4KB reads must end with '\"content\":' ensures reliable parsing.\n *\n * This module centralizes all VXJSON-specific logic including:\n * - Parsing partial buffers (first 4KB for indexing)\n * - Finding content position for ETag calculation\n * - Serializing with proper field ordering and size validation\n * - Calculating ETags from buffers\n */\n\n/**\n * VXJSON static utilities for parsing and validating VXJSON files\n */\nexport class VXJSON {\n /**\n * Parse first 4KB of VXJSON content from buffer\n * Used during indexing to extract metadata without loading full content\n *\n * VXJSON format requirement: first 4KB must either be complete JSON OR end with '\"content\":'\n * This ensures reliable parsing and validation.\n */\n static parse4KB(\n buffer: Uint8Array,\n bytesRead: number,\n ): {\n id?: string;\n created?: string;\n modified?: string;\n publishAt?: string;\n unpublishAt?: string;\n previousPathnames?: Record<string, string>;\n pathname?: string;\n name?: string;\n meta: ContentMeta;\n content?: ContentData;\n contentStartPos?: number; // Position where \"content\": starts in buffer\n } {\n // Complete JSON (either small file or ends with })\n if (bytesRead < 4096 || buffer[bytesRead - 1] === 0x7d) {\n // 0x7D = '}'\n const partialContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const data = JSON.parse(partialContent);\n\n // Find content position for ETag calculation\n let contentStartPos = -1;\n if (data.content !== undefined) {\n const etagResult = calculateEtagsFromVXJSONBuffer(buffer.subarray(0, bytesRead));\n if (etagResult.success) {\n contentStartPos = etagResult.contentStartPos;\n }\n }\n\n return {\n id: data.id,\n created: data.created,\n modified: data.modified,\n publishAt: data.publishAt,\n unpublishAt: data.unpublishAt,\n previousPathnames: data.previousPathnames,\n pathname: data.pathname,\n name: data.name,\n meta: data.meta || {},\n content: data.content,\n contentStartPos,\n };\n }\n\n // Truncated 4KB read - use calculateETags to validate and find content position\n const etagResult = calculateEtagsFromVXJSONBuffer(buffer.subarray(0, bytesRead), true); // Allow truncated for 4KB parsing\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format: ${etagResult.error}. This violates the VXJSON specification.`);\n }\n\n const contentStartPos = etagResult.contentStartPos;\n\n // Find end of metadata by working backwards from content position\n let metadataEnd = contentStartPos;\n while (metadataEnd > 0) {\n const byte = buffer[metadataEnd - 1];\n if (byte === 0x2c) {\n // comma\n metadataEnd--;\n break;\n }\n if (byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d) {\n // whitespace\n metadataEnd--;\n } else {\n break;\n }\n }\n\n // Create metadata-only JSON by adding closing brace\n const metadataBuffer = new Uint8Array(metadataEnd + 1);\n metadataBuffer.set(buffer.subarray(0, metadataEnd));\n metadataBuffer[metadataEnd] = 0x7d; // }\n\n const partialContent = textDecoder.decode(metadataBuffer);\n\n const data = JSON.parse(partialContent);\n return {\n id: data.id,\n created: data.created,\n modified: data.modified,\n publishAt: data.publishAt,\n unpublishAt: data.unpublishAt,\n previousPathnames: data.previousPathnames,\n pathname: data.pathname,\n name: data.name,\n meta: data.meta || {},\n contentStartPos,\n };\n }\n\n /**\n * Find the position of the \"content\" field in a VXJSON buffer\n * Returns -1 if not found\n */\n static findContentPosition(buffer: Uint8Array): number {\n const etagResult = calculateEtagsFromVXJSONBuffer(buffer);\n if (etagResult.success) {\n return etagResult.contentStartPos;\n }\n return -1;\n }\n\n /**\n * Calculate ETags for a VXJSON buffer\n * Returns null if the buffer is not valid VXJSON\n */\n static calculateEtagsOnly(buffer: Uint8Array): { metaEtag: string; contentEtag?: string } | null {\n const result = calculateEtagsFromVXJSONBuffer(buffer);\n if (!result.success) {\n return null;\n }\n\n return {\n metaEtag: result.metaEtag,\n contentEtag: result.contentEtag,\n };\n }\n\n /**\n * Create a dual ETag string from a VXJSON buffer\n * Returns null if the buffer is not valid VXJSON\n */\n static createEtag(buffer: Uint8Array): string | null {\n const etags = VXJSON.calculateEtagsOnly(buffer);\n if (!etags) {\n return null;\n }\n\n return etags.contentEtag ? `${etags.metaEtag}.${etags.contentEtag}` : etags.metaEtag;\n }\n\n /**\n * Validate that a VXJSON buffer has the correct structure\n * (content field must be last)\n */\n static isValid(buffer: Uint8Array): boolean {\n const result = calculateEtagsFromVXJSONBuffer(buffer);\n return result.success;\n }\n\n /**\n * Parse a complete VXJSON file from string\n */\n static parse(content: string): VXJSONFile {\n return JSON.parse(content);\n }\n\n /**\n * Parse a complete VXJSON file from buffer\n */\n static parseBuffer(buffer: Uint8Array): VXJSONFile {\n const content = textDecoder.decode(buffer);\n return VXJSON.parse(content);\n }\n\n /**\n * Calculate both ETags from a VXJSON buffer using views\n * Finds the \"content\" field position and validates it's the last field\n * @param buffer - The complete file buffer\n * @returns Result with ETags or validation error\n */\n static calculateETags = calculateEtagsFromVXJSONBuffer;\n\n /**\n * Calculate a simple single etag from the entire buffer\n * Used for data files that don't follow the content-last convention\n */\n static calculateSimpleEtag(buffer: Uint8Array): string {\n return calculateMetaEtagFromBuffer(buffer);\n }\n\n /**\n * Serialize a VXJSONFile to VXJSON format string\n * Ensures content field is last and enforces 4KB constraint efficiently\n */\n static serialize(data: VXJSONFile): string {\n // Extract content to add it last\n const { content, ...metadataFields } = data;\n\n // Ensure content field exists (required for VXJSON format)\n if (content === undefined || content === null) {\n throw new Error('VXJSON format requires a \"content\" field');\n }\n\n // Sort all metadata fields alphabetically and serialize with tab indentation\n // Use a replacer function to filter out empty strings\n const sortedMetadata = sortKeys(metadataFields, { deep: true });\n const metadataJson = JSON.stringify(\n sortedMetadata,\n (_key, value) => {\n // Filter out empty strings at any level\n if (value === '') {\n return undefined;\n }\n return value;\n },\n '\\t',\n );\n\n // Serialize content wrapped in an object to get proper indentation\n const wrappedContent = JSON.stringify({ c: sortKeys(content, { deep: true }) }, null, '\\t');\n // Extract just the content part, removing the wrapper\n // This transforms: '{\\n \"c\": {\\n \"puckData\": ...\\n }\\n}'\n // Into: '{\\n \"puckData\": ...\\n }'\n const contentJson = wrappedContent.slice(wrappedContent.indexOf(': ') + 2, -2);\n\n // Remove the closing } and newline from metadata\n const metadataWithoutClosing = metadataJson.slice(0, -2); // Remove \\n}\n const contentFieldPrefix = ',\\n\\t\"content\": ';\n const contentKeyPosition = metadataWithoutClosing.length + 1 + '\\n\\t'.length; // Position of \"content\":\n\n // VXJSON constraint: \"content\": must appear within first 4KB\n const maxContentKeyPosition = 4096 - '\"content\":'.length; // 4086\n if (contentKeyPosition > maxContentKeyPosition) {\n throw new Error(\n 'VXJSON format violation: metadata too large. ' +\n `\"content\" field would start at position ${contentKeyPosition}, ` +\n `but must start within ${maxContentKeyPosition} bytes. ` +\n `Reduce metadata size by ${contentKeyPosition - maxContentKeyPosition} bytes.`,\n );\n }\n\n // Build final JSON string efficiently\n return `${metadataWithoutClosing}${contentFieldPrefix}${contentJson}\\n}`;\n }\n}\n","import { type FileHandle, mkdir, open, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';\nimport { xxh3 } from '@node-rs/xxhash';\nimport matter from 'gray-matter';\nimport { dirname, join, resolve } from 'path';\nimport sortKeys from 'sort-keys';\nimport { Blocks } from './blocks';\nimport type { ContentAPI } from './content-api.interface';\nimport { filterContentWithIndexes } from './content-filters';\nimport { ContentIndex } from './content-index';\nimport {\n analyzeUpdateScope,\n buildLocaleVersion,\n buildPathnameHistory,\n generateContentId,\n isContentPublished,\n shouldUpdateModifiedTimestamp,\n UPDATE_SCOPE,\n updatePublishDates,\n validateAndPrepareMetadata,\n validateCreateContent,\n} from './content-operations';\nimport { localesOf, mapSiteNames, resolvePublishDate, serializeMdxWithFrontmatter } from './content-utils';\nimport { Data } from './data';\nimport { calculateEtagsFromMdxBuffer, findMdxContentStartPosition, parseDualEtag } from './etag-utils';\nimport { Site } from './site';\nimport type {\n BatchOperationResult,\n BatchResult,\n ContentAPIOptions,\n ContentData,\n ContentEntry,\n ContentIdentity,\n ContentManifest,\n ContentMeta,\n ContentProp,\n CreateContentInput,\n CreateResult,\n DeleteLocaleInput,\n DeleteResult,\n FindOptions,\n GlobalFilters,\n LocaleFileData,\n LocalePathData,\n LocaleVersion,\n LocalizedEntry,\n LocalizedManifest,\n SitesConfig,\n UpdateLocaleInput,\n UpdateResult,\n VXJSONFile,\n} from './types';\n\ninterface ReindexResult {\n filesProcessed: number;\n filesSkipped: number;\n filesDeleted?: number;\n errors?: number;\n // Return manifests of updated locales (without content)\n updated: LocalizedManifest[];\n deleted?: Array<{ id: string; locale: string; kind: 'page' | 'block' | 'data' }>;\n}\n\nimport { VXJSON } from './vxjson';\n\n// Helper to ensure we have an Error object\nfunction ensureError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n return new Error(String(error));\n}\n\n// Reusable TextDecoder instance - safe to reuse as it's stateless\nconst textDecoder = new TextDecoder();\n\n// Parse 4KB MDX content - extracts frontmatter from buffer\nfunction parse4KBMDX(\n buffer: Uint8Array,\n bytesRead: number,\n): {\n id?: string;\n created?: string;\n modified?: string;\n publishAt?: string;\n unpublishAt?: string;\n meta: ContentMeta;\n contentStartPos?: number; // Position where content starts (after second ---)\n} {\n // Only convert to string what we need\n const partialContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const { data: frontmatter } = matter(partialContent);\n\n // Find where content starts (after second ---)\n const delimiter = new TextEncoder().encode('---');\n let delimiterCount = 0;\n let contentStartPos = -1;\n\n for (let i = 0; i <= bytesRead - delimiter.length; i++) {\n let match = true;\n for (let j = 0; j < delimiter.length; j++) {\n if (buffer[i + j] !== delimiter[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n delimiterCount++;\n if (delimiterCount === 2) {\n // Skip past --- and newline\n contentStartPos = i + delimiter.length;\n while (contentStartPos < bytesRead && (buffer[contentStartPos] === 0x0a || buffer[contentStartPos] === 0x0d)) {\n contentStartPos++;\n }\n break;\n }\n }\n }\n\n // Extract special fields and treat the rest as metadata\n const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;\n\n return {\n id,\n created,\n modified,\n publishAt,\n unpublishAt,\n meta: metaFields as ContentMeta, // All other fields are metadata\n contentStartPos,\n };\n}\n\n/**\n * FileSystem-based Content API Implementation\n *\n * Stores content as files on disk in a git-friendly format:\n * - Pages: /{site}/pages/{filename}.{locale}.vxjson\n * - Blocks: /blocks/{collection}/{filename}.{locale}.{mdx|vxjson}\n *\n * ## Indexing\n *\n * Content is indexed at startup for performance. The index is cached per\n * content root path and cleared when the process restarts.\n *\n * ## Read-Repair\n *\n * Since files can be modified externally (git, editors), this implementation:\n *\n * 1. Repairs invalid VXJSON files (ensures \"content\" field is last)\n * 2. Adds missing required fields (id, created, modified)\n * 3. Handles files added after initial indexing\n * 4. Updates the index when files are repaired or discovered\n *\n * ## Performance\n *\n * - Initial indexing reads only first 4KB of each file\n * - Full content is loaded on demand\n * - ETags are calculated using streaming for efficiency\n */\nexport class FileSystemContentAPI implements ContentAPI {\n private contentRoot: string;\n private absoluteContentRoot: string;\n private contentIndex: ContentIndex;\n readonly sitesConfig: SitesConfig;\n readonly blocks: Blocks;\n readonly data: Data;\n private readonly sites: Record<string, Site>;\n\n // Getter for testing purposes\n get normalizedContentRoot(): string {\n return this.contentRoot;\n }\n\n private constructor(\n contentRoot: string,\n canvasDir: string | undefined,\n sitesConfig: SitesConfig,\n contentIndex: ContentIndex,\n ) {\n // Normalize contentRoot: remove ./ prefix for relative paths, keep absolute paths as-is\n if (contentRoot.startsWith('./')) {\n this.contentRoot = contentRoot.slice(2);\n } else if (contentRoot.startsWith('/')) {\n // Absolute path, keep as-is\n this.contentRoot = contentRoot;\n } else {\n // Already normalized relative path\n this.contentRoot = contentRoot;\n }\n\n // Store absolute path for file operations\n this.absoluteContentRoot = resolve(this.contentRoot);\n\n // TODO: Use canvasDir for canvas/unlinked components\n this.sitesConfig = sitesConfig;\n this.contentIndex = contentIndex;\n\n // Initialize blocks\n this.blocks = new Blocks(this, this.contentIndex.getBlockIndex());\n\n // Initialize data\n this.data = new Data(this, this.contentIndex.getDataIndex());\n\n // Initialize all sites\n this.sites = mapSiteNames(sitesConfig, (siteName) => {\n const siteIndex = this.contentIndex.getSiteIndex(siteName);\n if (!siteIndex) {\n throw new Error(`Site index not found for ${siteName}`);\n }\n return new Site(siteName, this, siteIndex);\n });\n }\n\n static async create(options: ContentAPIOptions): Promise<FileSystemContentAPI> {\n const { canvasDir } = options;\n // Keep contentRoot as provided (will be normalized in constructor)\n const contentRoot = options.contentRoot;\n\n // For file operations, we need the absolute path\n const absoluteContentRoot = resolve(contentRoot);\n\n // Load sites config\n const sitesPath = join(absoluteContentRoot, 'sites.json');\n let sitesConfig: SitesConfig;\n try {\n const content = await readFile(sitesPath, 'utf-8');\n const parsed = JSON.parse(content);\n\n // Validate the structure\n if (!parsed.sites || typeof parsed.sites !== 'object') {\n console.warn(\n `Warning: sites.json has invalid structure at ${sitesPath}. Expected 'sites' property. Using default configuration.`,\n );\n sitesConfig = { sites: {}, globalLocales: ['en'] };\n } else if (!parsed.globalLocales || !Array.isArray(parsed.globalLocales)) {\n console.warn(\n `Warning: sites.json is missing 'globalLocales' array at ${sitesPath}. Using default global locales.`,\n );\n sitesConfig = {\n sites: parsed.sites,\n globalLocales: ['en'],\n };\n } else {\n sitesConfig = parsed;\n }\n } catch (error) {\n // Handle missing sites.json gracefully\n console.warn(`Warning: sites.json is missing at ${sitesPath}. Using empty configuration.`);\n sitesConfig = { sites: {}, globalLocales: ['en'] };\n }\n\n // Get cached content index or create new one\n // Use the normalized contentRoot for cache key\n const normalizedContentRoot = contentRoot.startsWith('./') ? contentRoot.slice(2) : contentRoot;\n const contentIndex = await ContentIndex.getCachedOrCreate(normalizedContentRoot, sitesConfig);\n\n // Create instance (not cached)\n const api = new FileSystemContentAPI(contentRoot, canvasDir, sitesConfig, contentIndex);\n\n // Index all content files (only if index is empty)\n if (contentIndex.entryCount === 0) {\n await api.indexAllContent();\n }\n\n return api;\n }\n\n /**\n * Clear all caches - useful for testing\n */\n static clearCaches(): void {\n ContentIndex.clearCache();\n // TODO: CanvasIndex.clearCache() when implemented\n }\n\n private async indexAllContent(): Promise<void> {\n // Clear existing indexes\n this.contentIndex.clear();\n\n // Scan content directory\n const files = await this.scanContentFiles();\n\n // Use optimized batch size based on benchmarks\n const OPTIMAL_BATCH_SIZE = 1000;\n\n console.log(`Indexing ${files.length} content files...`);\n\n // Pre-allocate reusable buffers for the entire indexing operation\n // Only allocate as many as we need (up to batch size)\n const bufferCount = Math.min(files.length, OPTIMAL_BATCH_SIZE);\n const buffers = Array.from({ length: bufferCount }, () => new Uint8Array(4096));\n\n for (let i = 0; i < files.length; i += OPTIMAL_BATCH_SIZE) {\n const batch = files.slice(i, i + OPTIMAL_BATCH_SIZE);\n\n // Process batch in parallel - winner of benchmarks\n await Promise.all(\n batch.map(async (filePath, index) => {\n try {\n const result = await this.parseFileHeaderWithRepair(filePath, buffers[index]);\n if (result) {\n const { manifest, localeVersion, content } = result;\n\n // Add to index with content if we have it\n this.contentIndex.addContent(manifest, localeVersion, content);\n }\n } catch (error) {\n console.error(`Failed to index ${filePath}:`, error);\n }\n }),\n );\n }\n }\n\n private async parseFileHeaderWithRepair(\n originalFilePath: string,\n buffer: Uint8Array,\n ): Promise<{\n manifest: ContentManifest;\n locale: string;\n localeVersion: LocaleVersion;\n bytesRead: number;\n content?: ContentData;\n } | null> {\n let handle: FileHandle | undefined;\n let bytesRead = 0;\n let filePath = originalFilePath; // Use a local variable that can be updated if file is renamed\n\n try {\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n } catch (error) {\n console.error(`Error reading ${filePath}:`, error);\n throw error;\n } finally {\n await handle?.close();\n }\n\n try {\n // Now parse the buffer content\n\n // Parse file to extract metadata\n let relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n let parts = relativePath.split('/');\n\n // Determine site/collection structure\n let site: string | undefined;\n let collection: string;\n let locale = 'en';\n let name: string | undefined;\n let pathname: string | undefined;\n // Type for parsed metadata from files\n interface ParsedMetadata {\n id?: string;\n created?: string;\n modified?: string;\n publishAt?: string;\n unpublishAt?: string;\n pathname?: string;\n name?: string;\n previousPathnames?: Record<string, string>;\n meta?: ContentMeta;\n type?: 'puck' | 'mdx' | 'json';\n contentStartPos?: number;\n data?: Record<string, unknown>; // For data collection entries\n }\n let parsedData: ParsedMetadata = {};\n let kind: 'block' | 'page' | 'data';\n\n if (parts[0] === 'blocks') {\n kind = 'block';\n\n // Check if block is directly in blocks/ directory (no collection subdirectory)\n if (parts.length === 2) {\n // Block is directly in blocks/ directory, needs to be moved to 'general' collection\n collection = 'general';\n const filename = parts[1];\n\n // Create the general directory if it doesn't exist\n const generalDir = join(this.absoluteContentRoot, 'blocks', 'general');\n try {\n await mkdir(generalDir, { recursive: true });\n } catch (error) {\n // Directory might already exist, that's fine\n }\n\n // Move the file to the general collection\n const newFilePath = join(generalDir, filename);\n\n try {\n await handle?.close(); // Close the current file handle before moving\n handle = undefined;\n\n // Check if target file already exists\n try {\n const targetHandle = await open(newFilePath, 'r');\n await targetHandle.close();\n console.warn(`Cannot move ${filename} to blocks/general/: target file already exists`);\n } catch (error) {\n // Target doesn't exist, safe to move\n await rename(filePath, newFilePath);\n console.log(`Repaired: Moved ${filename} to blocks/general/ collection`);\n\n // Update filePath to the new path for further processing\n filePath = newFilePath;\n\n // Update relativePath and parts for the new file path\n relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n parts = relativePath.split('/');\n\n // Re-open the file with the new path\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n }\n } catch (moveError) {\n console.error(`Failed to move ${filename} to general collection:`, moveError);\n // Continue processing with original file\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n }\n } else {\n // Block is in a collection subdirectory\n collection = parts[1];\n }\n\n const filename = parts[parts.length - 1];\n // Extract name and locale from filename: hero.en.mdx -> name: hero, locale: en\n // Also handle files without locale: hero.mdx -> name: hero, locale: default from sites.json\n const matchWithLocale = filename.match(/^(.+)\\.(\\w+)\\.(mdx|vxjson)$/);\n const matchWithoutLocale = filename.match(/^(.+)\\.(mdx|vxjson)$/);\n\n if (matchWithLocale) {\n name = matchWithLocale[1];\n locale = matchWithLocale[2];\n } else if (matchWithoutLocale) {\n name = matchWithoutLocale[1];\n // Use default locale from sites config instead of hardcoded 'en'\n locale = this.contentIndex.getDefaultLocale('');\n\n console.log(`Found file without locale suffix: ${filename}`);\n // Rename file to include locale suffix\n const extension = matchWithoutLocale[2];\n const newFilename = `${name}.${locale}.${extension}`;\n const newFilePath = join(dirname(filePath), newFilename);\n console.log(`Will rename to: ${newFilename} at ${newFilePath}`);\n\n // Check if target file already exists\n try {\n await handle?.close(); // Close the current file handle before renaming\n handle = undefined;\n\n // Try to open the target file to check if it exists\n const targetHandle = await open(newFilePath, 'r');\n await targetHandle.close();\n\n // Target file exists, skip renaming to avoid conflict\n console.warn(`Cannot rename ${filename} to ${newFilename}: target file already exists`);\n } catch (error) {\n // Target file doesn't exist, safe to rename\n console.log(`Target file doesn't exist, proceeding with rename`);\n try {\n await rename(filePath, newFilePath);\n console.log(`Successfully renamed ${filename} to ${newFilename}`);\n\n // Update filePath to the new path for further processing\n filePath = newFilePath;\n\n // Update relativePath and parts for the new file path\n relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n parts = relativePath.split('/');\n\n // Re-open the file with the new path\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n } catch (renameError) {\n console.error(`Failed to rename ${filename}:`, renameError);\n // Continue processing with original file\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n }\n }\n }\n\n // Parse content based on file type\n if (filePath.endsWith('.mdx')) {\n parsedData = parse4KBMDX(buffer, bytesRead);\n } else {\n parsedData = VXJSON.parse4KB(buffer, bytesRead);\n }\n } else if (parts[0] === 'data') {\n // Data collection entry: data/{collection}/{name}.{locale}.json\n kind = 'data';\n collection = parts[1];\n\n const filename = parts[parts.length - 1];\n // Extract name and locale from filename: testimonial.en.json -> name: testimonial, locale: en\n // Use strict locale pattern matching blocks: 2-letter code with optional region (en, en-US)\n const match = filename.match(/^(.+)\\.([a-z]{2}(?:-[A-Z]{2})?)\\.json$/);\n if (match) {\n name = match[1];\n locale = match[2];\n }\n\n // Parse JSON to get ID, metadata, and data\n const content = textDecoder.decode(buffer.subarray(0, bytesRead));\n try {\n const jsonData = JSON.parse(content);\n parsedData = {\n id: jsonData.id,\n type: 'json',\n created: jsonData.created,\n modified: jsonData.modified,\n publishAt: jsonData.publishAt,\n unpublishAt: jsonData.unpublishAt,\n meta: jsonData.meta || { title: name || 'Untitled' },\n data: jsonData.data,\n name,\n };\n } catch (error) {\n console.error(`Failed to parse JSON data file ${filePath}:`, error);\n return null;\n }\n } else {\n kind = 'page';\n site = parts[0];\n collection = parts[1];\n\n // Build pathname from file path: pages/products/widget.en.vxjson -> /products/widget\n const pathParts = parts.slice(2); // Remove site/collection\n const filename = pathParts[pathParts.length - 1];\n const match = filename.match(/^(.+)\\.(\\w+)\\.vxjson$/);\n if (match) {\n locale = match[2];\n // Replace filename with basename\n pathParts[pathParts.length - 1] = match[1];\n // index files map to parent: /index -> /, /foo/index -> /foo\n pathname =\n pathParts[pathParts.length - 1] === 'index'\n ? '/' + pathParts.slice(0, -1).join('/') || '/'\n : '/' + pathParts.join('/');\n }\n\n // Parse JSON to get ID and metadata\n parsedData = VXJSON.parse4KB(buffer, bytesRead);\n }\n\n // Check if the file is missing required fields\n const needsRepair = !parsedData.id || !parsedData.created || !parsedData.modified;\n\n // Extract or generate ID\n const id = parsedData.id || generateContentId();\n\n // Build LocaleManifest for this specific locale\n const localeVersion: LocaleVersion = {\n locale,\n etag: '', // Will be filled below\n created: parsedData.created || new Date().toISOString(),\n modified: parsedData.modified || new Date().toISOString(),\n ...(parsedData.publishAt && { publishAt: parsedData.publishAt }),\n ...(parsedData.unpublishAt && { unpublishAt: parsedData.unpublishAt }),\n ...(pathname && { pathname }),\n ...(parsedData.previousPathnames && { previousPathnames: parsedData.previousPathnames }),\n ...(name && { name }),\n meta: parsedData.meta || { title: name || 'Untitled' },\n };\n\n // Build ContentManifest (without content)\n const manifest: ContentManifest = {\n id,\n type: parsedData.type || (filePath.endsWith('.mdx') ? 'mdx' : filePath.endsWith('.json') ? 'json' : 'puck'),\n kind,\n site,\n collection,\n locales: {\n [locale]: localeVersion,\n },\n };\n\n // If we have full content, parse it and compute etags\n let content: ContentData | undefined;\n\n // Check if we need to repair the file first (missing required fields)\n if (needsRepair) {\n // Perform repair and get the repaired content\n const repairedData = await this.performReadRepair(filePath, manifest, locale);\n if (repairedData) {\n content = repairedData.content;\n localeVersion.etag = repairedData.etag;\n localeVersion.modified = repairedData.modified;\n return { manifest, locale, localeVersion, bytesRead, content };\n }\n // Repair failed, skip this file\n console.error(`Failed to repair ${filePath}, skipping`);\n return null;\n }\n\n if (\n bytesRead < 4096 ||\n (filePath.endsWith('.vxjson') && buffer[bytesRead - 1] === 0x7d) ||\n (filePath.endsWith('.json') && buffer[bytesRead - 1] === 0x7d)\n ) {\n // We have the full content\n if (filePath.endsWith('.mdx')) {\n const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const { content: mdx } = matter(fullContent);\n content = { mdx };\n } else if (filePath.endsWith('.json')) {\n // Data collection JSON file\n const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const jsonData = JSON.parse(fullContent);\n content = { data: jsonData.data };\n } else {\n const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const data = JSON.parse(fullContent);\n content = data.content || {};\n }\n\n // Calculate etags from the buffer (only use valid bytes)\n const validBuffer = buffer.subarray(0, bytesRead);\n\n if (filePath.endsWith('.mdx')) {\n const etags = calculateEtagsFromMdxBuffer(validBuffer, parsedData.contentStartPos || -1);\n localeVersion.etag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else if (filePath.endsWith('.json')) {\n // For data files, use simple etag (hash entire buffer)\n // Data files are typically small and don't need separate meta/content etags\n localeVersion.etag = VXJSON.calculateSimpleEtag(validBuffer);\n } else {\n const etagResult = VXJSON.calculateETags(validBuffer);\n\n if (!etagResult.success) {\n // Content field is not last or invalid JSON - repair immediately\n\n // Perform repair and get the repaired content\n const repairedData = await this.performReadRepair(filePath, manifest, locale);\n if (repairedData) {\n content = repairedData.content;\n localeVersion.etag = repairedData.etag;\n localeVersion.modified = repairedData.modified;\n return { manifest, locale, localeVersion, bytesRead, content };\n }\n // Repair failed, skip this file\n console.error(`Failed to repair ${filePath}, skipping`);\n return null;\n }\n localeVersion.etag = etagResult.contentEtag\n ? `${etagResult.metaEtag}.${etagResult.contentEtag}`\n : etagResult.metaEtag;\n }\n }\n\n // Return both for indexing\n return { manifest, locale, localeVersion, bytesRead, content };\n } catch (error) {\n console.error(`Error indexing ${originalFilePath}:`, error);\n return null;\n }\n }\n\n /**\n * Perform read-repair by writing back the file with missing fields\n * This ensures stable IDs and timestamps across restarts\n */\n private async performReadRepair(\n filePath: string,\n manifest: ContentManifest,\n locale: string,\n ): Promise<{\n content: ContentData;\n etag: string;\n modified: string;\n } | null> {\n try {\n const now = new Date().toISOString();\n let needsWrite = false;\n\n if (manifest.type === 'mdx') {\n // Read the full MDX file\n const content = await readFile(filePath, 'utf-8');\n const parsed = matter(content);\n\n // Check for missing fields\n if (!parsed.data.id) {\n parsed.data.id = manifest.id;\n needsWrite = true;\n }\n if (!parsed.data.created) {\n parsed.data.created = now;\n needsWrite = true;\n }\n if (!parsed.data.modified) {\n parsed.data.modified = now;\n needsWrite = true;\n }\n\n if (needsWrite) {\n // Write back with updated frontmatter\n const updatedContent = matter.stringify(parsed.content, parsed.data);\n await writeFile(filePath, updatedContent);\n console.log(`Repaired MDX file: ${filePath} (added missing fields)`);\n\n // Calculate ETags for the repaired MDX file\n const repairedBuffer = Buffer.from(updatedContent, 'utf-8') as Uint8Array;\n const contentStartPos = updatedContent.indexOf('\\n---\\n') + 5; // Position after frontmatter\n const etags = calculateEtagsFromMdxBuffer(repairedBuffer, contentStartPos);\n const etag = `${etags.metaEtag}.${etags.contentEtag}`;\n\n // Return the repaired data\n return {\n content: { mdx: parsed.content },\n etag,\n modified: parsed.data.modified || now,\n };\n }\n } else {\n // Read the full JSON file\n const content = await readFile(filePath, 'utf-8');\n const data: VXJSONFile = JSON.parse(content);\n\n // Check for missing fields\n if (!data.id) {\n data.id = manifest.id;\n needsWrite = true;\n }\n if (!data.created) {\n data.created = now;\n needsWrite = true;\n }\n if (!data.modified) {\n data.modified = now;\n needsWrite = true;\n }\n\n // Always rewrite VXJSON files during repair to ensure correct field order\n needsWrite = true;\n\n if (needsWrite) {\n // Write back with VXJSON format\n const vxjsonData: VXJSONFile = {\n id: data.id,\n type: data.type,\n created: data.created,\n modified: data.modified,\n publishAt: data.publishAt,\n unpublishAt: data.unpublishAt,\n previousPathnames: data.previousPathnames,\n meta: data.meta || {},\n content: data.content || {},\n };\n const repairedJson = VXJSON.serialize(vxjsonData);\n await writeFile(filePath, repairedJson);\n console.log(`Repaired VXJSON file: ${filePath} (fixed field order or added missing fields)`);\n // Return the repaired data\n\n // Calculate ETags from the repaired JSON\n const repairedBuffer = Buffer.from(repairedJson, 'utf-8') as Uint8Array;\n const etagResult = VXJSON.calculateETags(repairedBuffer);\n\n if (!etagResult.success) {\n console.error(`Failed to calculate ETags after repair: ${filePath}`);\n return null;\n }\n\n const etag = etagResult.contentEtag\n ? `${etagResult.metaEtag}.${etagResult.contentEtag}`\n : etagResult.metaEtag;\n\n // Return the complete repaired data\n return {\n content: vxjsonData.content,\n etag,\n modified: vxjsonData.modified,\n };\n }\n }\n\n // For MDX or no repair needed, return null\n return null;\n } catch (error) {\n console.error(`Failed to perform read-repair on ${filePath}:`, error);\n return null;\n }\n }\n\n private async scanContentFiles(): Promise<string[]> {\n const files: string[] = [];\n const contentRoot = this.absoluteContentRoot;\n\n async function scan(dir: string, inDataDir = false) {\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n // Check if we're entering the data/ directory\n const isDataDir = dir === contentRoot && entry.name === 'data';\n await scan(fullPath, inDataDir || isDataDir);\n } else if (entry.isFile()) {\n // Include .vxjson and .mdx files everywhere\n // Include .json files only in the data/ directory\n if (entry.name.endsWith('.vxjson') || entry.name.endsWith('.mdx')) {\n files.push(fullPath);\n } else if (inDataDir && entry.name.endsWith('.json')) {\n files.push(fullPath);\n }\n }\n }\n } catch (error) {\n // Directory doesn't exist yet\n }\n }\n\n await scan(this.absoluteContentRoot);\n return files;\n }\n\n private getFilePath(manifest: ContentIdentity, { locale, name, pathname }: LocalePathData): string {\n if (manifest.kind === 'block') {\n const ext = manifest.type === 'mdx' ? 'mdx' : 'vxjson';\n return join(this.absoluteContentRoot, 'blocks', manifest.collection, `${name}.${locale}.${ext}`);\n }\n if (manifest.kind === 'data') {\n return join(this.absoluteContentRoot, 'data', manifest.collection, `${name}.${locale}.json`);\n }\n if (manifest.kind === 'page' && pathname && manifest.site) {\n // For pages, derive path from pathname\n const basePath = pathname.replace(/^\\//, '').replace(/\\/$/, '') || 'index';\n return join(this.absoluteContentRoot, manifest.site, manifest.collection, `${basePath}.${locale}.vxjson`);\n }\n throw new Error(`Invalid manifest: ${JSON.stringify(manifest, null, 2)}`);\n }\n\n /**\n * Parse a file path back into its components for checking against the path index\n * Returns null if the path doesn't match expected patterns\n */\n parseFilePath(filePath: string): {\n kind: 'page' | 'block' | 'data';\n site?: string;\n collection: string;\n pathname?: string;\n name?: string;\n locale: string;\n } | null {\n // Remove contentRoot prefix\n const relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n const parts = relativePath.split('/');\n\n // Match locale.ext pattern at the end\n const filename = parts[parts.length - 1];\n\n // Handle data files: data/{collection}/{name}.{locale}.json\n if (parts[0] === 'data' && parts.length === 3) {\n const dataMatch = filename.match(/^(.+)\\.([a-z]{2}(?:-[A-Z]{2})?)\\.json$/);\n if (!dataMatch) return null;\n const [, name, locale] = dataMatch;\n return {\n kind: 'data',\n collection: parts[1],\n name,\n locale,\n };\n }\n\n // Match locale.ext pattern for non-data files (vxjson, mdx)\n const match = filename.match(/^(.+)\\.([a-z]{2}(?:-[A-Z]{2})?)\\.(?:vxjson|mdx)$/);\n if (!match) return null;\n\n const [, nameOrPath, locale] = match;\n\n if (parts[0] === 'blocks' && parts.length === 3) {\n // blocks/collection/name.locale.ext\n return {\n kind: 'block',\n collection: parts[1],\n name: nameOrPath,\n locale,\n };\n }\n if (parts.length >= 3 && parts[0] !== 'blocks') {\n // site/collection/pathname.locale.vxjson\n const site = parts[0];\n const collection = parts[1];\n // Reconstruct pathname from remaining parts\n const pathParts = parts.slice(2, -1); // All dirs between collection and filename\n pathParts.push(nameOrPath); // Add the filename part (without locale.ext)\n const pathname = '/' + pathParts.join('/');\n\n return {\n kind: 'page',\n site,\n collection,\n pathname,\n locale,\n };\n }\n\n return null;\n }\n\n async getContent(id: string): Promise<ContentEntry | null> {\n // Get manifest for this ID\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return null;\n }\n\n // Read all locale files in parallel\n const readPromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {\n const filePath = this.getFilePath(manifest, localeVersion);\n const content = await this.readLocaleFile(filePath, localeVersion.locale);\n return { localeVersion, content };\n });\n\n const results = await Promise.all(readPromises);\n\n // Build locales with content\n const locales: Record<string, LocaleVersion & ContentProp> = {};\n for (const { localeVersion, content } of results) {\n if (content) {\n locales[localeVersion.locale] = {\n ...localeVersion,\n etag: content.etag, // Use fresh etag from file, not stale manifest etag\n content: content.content,\n };\n }\n }\n\n return {\n id: manifest.id,\n site: manifest.site,\n collection: manifest.collection,\n type: manifest.type,\n kind: manifest.kind,\n locales,\n };\n }\n\n async getLocalized(id: string, locale: string): Promise<LocalizedEntry | null> {\n // Get manifest for this ID\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n // File might have been added after indexing - try reindexing\n await this.reindex();\n\n // Try again with updated index\n const updatedManifest = this.contentIndex.getManifest(id);\n if (!updatedManifest || !updatedManifest.locales[locale]) {\n return null;\n }\n\n return this.getLocalized(id, locale);\n }\n\n // Check if this locale exists\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return null;\n }\n\n // Read the locale-specific file\n const filePath = this.getFilePath(manifest, localeVersion);\n const localeData = await this.readLocaleFile(filePath, locale);\n if (!localeData) {\n return null;\n }\n\n // Build LocalizedEntry\n return {\n id: manifest.id,\n site: manifest.site,\n collection: manifest.collection,\n type: manifest.type,\n kind: manifest.kind,\n localized: {\n ...localeVersion,\n etag: localeData.etag, // Use fresh etag from file, not stale manifest etag\n content: localeData.content,\n },\n };\n }\n\n private async readLocaleFile(filePath: string, locale: string): Promise<LocaleFileData | null> {\n try {\n const buffer = (await readFile(filePath)) as Uint8Array;\n const content = textDecoder.decode(buffer);\n\n if (filePath.endsWith('.mdx')) {\n const { data: frontmatter } = matter(content);\n\n // Calculate etags from the file buffer\n const contentPos = findMdxContentStartPosition(buffer);\n\n const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);\n const etag = `${etags.metaEtag}.${etags.contentEtag}`;\n\n // Extract special fields from frontmatter, everything else is metadata\n const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;\n\n const result: LocaleFileData = {\n locale,\n etag,\n created: created,\n modified: modified,\n meta: metaFields as ContentMeta, // All non-special fields are metadata\n content: { mdx: content }, // Return the ENTIRE file content including frontmatter\n };\n\n // Only add publish dates if they exist\n if (frontmatter.publishAt !== undefined) {\n result.publishAt = frontmatter.publishAt;\n }\n if (frontmatter.unpublishAt !== undefined) {\n result.unpublishAt = frontmatter.unpublishAt;\n }\n\n return result;\n }\n\n // Parse JSON data first to determine type\n const data = JSON.parse(content);\n\n // Handle JSON data files (type: 'json') separately - they use simple etag\n if (data.type === 'json') {\n const etag = VXJSON.calculateSimpleEtag(buffer);\n\n const result: LocaleFileData = {\n locale,\n etag,\n created: data.created,\n modified: data.modified,\n meta: data.meta || {},\n content: { data: data.data || {} },\n };\n\n // Only add optional fields if they exist\n if (data.publishAt !== undefined) {\n result.publishAt = data.publishAt;\n }\n if (data.unpublishAt !== undefined) {\n result.unpublishAt = data.unpublishAt;\n }\n\n return result;\n }\n\n // For VXJSON (puck pages), calculate ETags with meta/content split\n const etagResult = VXJSON.calculateETags(buffer);\n\n if (!etagResult.success) {\n // File needs repair - parse it and rewrite in correct format\n const repairedData: VXJSONFile = {\n id: data.id,\n type: data.type,\n created: data.created,\n modified: data.modified,\n publishAt: data.publishAt,\n unpublishAt: data.unpublishAt,\n previousPathnames: data.previousPathnames,\n meta: data.meta || {},\n content: data.content || {},\n };\n\n // Rewrite file with correct format\n const repairedJson = VXJSON.serialize(repairedData);\n await writeFile(filePath, repairedJson);\n\n // Recalculate ETags from repaired buffer\n const repairedBuffer = Buffer.from(repairedJson, 'utf-8') as Uint8Array;\n const repairedEtagResult = VXJSON.calculateETags(repairedBuffer);\n\n if (!repairedEtagResult.success) {\n throw new Error(`Failed to repair VXJSON file: ${filePath}`);\n }\n\n const etag = repairedEtagResult.contentEtag\n ? `${repairedEtagResult.metaEtag}.${repairedEtagResult.contentEtag}`\n : repairedEtagResult.metaEtag;\n\n console.log(`Repaired VXJSON file: ${filePath}`);\n\n const result: LocaleFileData = {\n locale,\n etag,\n created: data.created,\n modified: data.modified,\n meta: data.meta || {},\n content: data.content || {},\n };\n\n // Only add optional fields if they exist\n if (data.publishAt !== undefined) {\n result.publishAt = data.publishAt;\n }\n if (data.unpublishAt !== undefined) {\n result.unpublishAt = data.unpublishAt;\n }\n if (data.previousPathnames !== undefined) {\n result.previousPathnames = data.previousPathnames;\n }\n\n return result;\n }\n\n const etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n\n const result: LocaleFileData = {\n locale,\n etag,\n created: data.created,\n modified: data.modified,\n meta: data.meta || {},\n content: data.content || {},\n };\n\n // Only add optional fields if they exist\n if (data.publishAt !== undefined) {\n result.publishAt = data.publishAt;\n }\n if (data.unpublishAt !== undefined) {\n result.unpublishAt = data.unpublishAt;\n }\n if (data.previousPathnames !== undefined) {\n result.previousPathnames = data.previousPathnames;\n }\n\n return result;\n } catch (error) {\n return null;\n }\n }\n\n async createContent(data: CreateContentInput): Promise<CreateResult> {\n // Use shared validation\n const validation = validateCreateContent(data, this.sites, this.blocks, this.data);\n if (!validation.valid) {\n return {\n success: false,\n reason: validation.reason,\n error: validation.error ? new Error(validation.error) : undefined,\n existingId: validation.existingId,\n };\n }\n\n const id = generateContentId();\n const now = data.created || new Date().toISOString();\n\n try {\n // Build the manifest with all locales\n const manifest: ContentManifest = {\n id,\n type: data.type,\n kind: data.kind,\n site: data.site,\n collection: data.collection,\n locales: {},\n };\n\n const contentCache: Record<string, ContentData> = {};\n\n // Create files for each locale\n for (const [locale, localeData] of Object.entries(data.locales)) {\n const content = localeData.content;\n\n // Build metadata with required title\n const title = localeData.meta?.title || data.meta?.title;\n if (!title) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error('Title is required in metadata'),\n };\n }\n\n // Build complete metadata\n const meta: ContentMeta = {\n title,\n ...data.meta,\n ...localeData.meta,\n };\n\n const fileData: VXJSONFile = {\n id,\n type: data.type,\n created: now,\n modified: now,\n publishAt:\n localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,\n unpublishAt:\n localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,\n meta,\n content,\n };\n\n // Use the proper getFilePath method\n const filePath = this.getFilePath(manifest, { locale, name: data.name, pathname: localeData.pathname });\n\n // Ensure directory exists\n await mkdir(dirname(filePath), { recursive: true });\n\n // Write file and calculate etag from the serialized content\n let etag: string;\n\n if (data.type === 'mdx') {\n // Write MDX with frontmatter - flatten metadata fields\n const frontmatterData = {\n id,\n created: now,\n modified: now,\n ...(localeData.publishAt && { publishAt: localeData.publishAt }),\n ...(localeData.unpublishAt && { unpublishAt: localeData.unpublishAt }),\n ...meta, // Spread metadata fields directly, not nested\n };\n\n const mdxContent = serializeMdxWithFrontmatter(frontmatterData, content.mdx || '');\n await writeFile(filePath, mdxContent);\n\n // For MDX, calculate etags from the serialized content\n const mdxBuffer = new TextEncoder().encode(mdxContent);\n // For MDX, all frontmatter is metadata, content starts after ---\n const contentStartMarker = new TextEncoder().encode('---\\n\\n');\n let contentPos = -1;\n for (let i = 0; i <= mdxBuffer.length - contentStartMarker.length; i++) {\n let match = true;\n for (let j = 0; j < contentStartMarker.length; j++) {\n if (mdxBuffer[i + j] !== contentStartMarker[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n contentPos = i + contentStartMarker.length;\n break;\n }\n }\n const etags = calculateEtagsFromMdxBuffer(mdxBuffer, contentPos);\n etag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else if (data.type === 'json') {\n // Data files use \"data\" field instead of \"content\"\n const dataFileContent = {\n id,\n type: 'json',\n created: now,\n modified: now,\n ...(localeData.publishAt &&\n typeof localeData.publishAt === 'string' && { publishAt: localeData.publishAt }),\n ...(localeData.unpublishAt &&\n typeof localeData.unpublishAt === 'string' && { unpublishAt: localeData.unpublishAt }),\n meta,\n data: content.data || {},\n };\n\n const jsonContent = JSON.stringify(sortKeys(dataFileContent, { deep: true }), null, '\\t');\n await writeFile(filePath, jsonContent);\n\n // For data files, use simple etag (hash entire buffer)\n const jsonBuffer = new TextEncoder().encode(jsonContent);\n etag = VXJSON.calculateSimpleEtag(jsonBuffer);\n } else {\n // VXJSON for pages (puck)\n const jsonContent = VXJSON.serialize(fileData);\n const jsonBuffer = new TextEncoder().encode(jsonContent);\n\n // Calculate etags from the buffer\n const etagResult = VXJSON.calculateETags(jsonBuffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format when creating content: ${etagResult.error}`);\n }\n\n etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n\n // Write the file\n await writeFile(filePath, jsonContent);\n }\n\n // Build locale manifest using shared function\n const localeVersion = buildLocaleVersion({\n locale,\n etag,\n created: now,\n modified: now,\n meta,\n kind: data.kind,\n pathname: data.kind === 'page' ? localeData.pathname : undefined,\n name: data.kind === 'block' || data.kind === 'data' ? data.name : undefined,\n publishAt:\n localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,\n unpublishAt:\n localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,\n });\n\n // Add locale to manifest\n manifest.locales[locale] = localeVersion;\n contentCache[locale] = content;\n }\n\n // Add each locale to the index\n for (const localeVersion of localesOf(manifest)) {\n const { locale } = localeVersion;\n this.contentIndex.addContent(manifest, localeVersion, contentCache[locale]);\n }\n\n return { success: true, id };\n } catch (error) {\n return {\n success: false,\n reason: 'write_error',\n error: ensureError(error),\n };\n }\n }\n\n async updateLocalized(input: UpdateLocaleInput): Promise<UpdateResult> {\n const { id, locale, data, etag } = input;\n\n // Get the manifest\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Get the specific locale manifest\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Get file path and read current content FIRST to get fresh etag\n const filePath = this.getFilePath(manifest, localeVersion);\n const current = await this.readLocaleFile(filePath, locale);\n if (!current) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Use fresh etag from file, not stale manifest etag\n const currentEtag = current.etag;\n\n // Check etag - data files use simple etags, others use dual etags\n if (manifest.kind === 'data') {\n // Data files use simple etag (single hash, no dot separator)\n // Just compare the full etag directly\n if (etag !== currentEtag) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag,\n };\n }\n } else {\n // Non-data files use dual etags (meta.content format)\n const etagParts = parseDualEtag(etag);\n const currentParts = parseDualEtag(currentEtag);\n\n if (!etagParts || !currentParts) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag,\n };\n }\n\n // Check which parts are being updated\n const updateScope = analyzeUpdateScope(data);\n const updatingMeta = (updateScope & UPDATE_SCOPE.META) !== 0;\n const updatingContent = (updateScope & UPDATE_SCOPE.CONTENT) !== 0;\n\n // Validate etags for parts being updated\n if (updatingMeta && etagParts.meta !== currentParts.meta) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag,\n };\n }\n\n if (updatingContent && etagParts.content !== currentParts.content) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag,\n };\n }\n }\n\n // Update modified timestamp for any change (metadata or content)\n let modified: string;\n if (shouldUpdateModifiedTimestamp(data)) {\n // Use provided modified timestamp or current time\n modified = data.modified || new Date().toISOString();\n } else if (data.modified) {\n // If modified timestamp is explicitly provided, always use it\n modified = data.modified;\n } else {\n // No changes and no explicit timestamp, keep current\n modified = current.modified;\n }\n\n const {\n sortedMeta: newMeta,\n valid: metaValid,\n error: metaError,\n } = validateAndPrepareMetadata({ ...current.meta, ...(data.meta ? data.meta : {}) });\n\n // Validate new metadata\n if (!newMeta || !metaValid) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error(metaError),\n };\n }\n\n // Merge updates\n const newContent = data.content ? { ...current.content, ...data.content } : current.content;\n\n // Validate pathname change if updating pathname for pages\n if (data.pathname && manifest.kind === 'page' && manifest.site) {\n const site = this.sites[manifest.site];\n if (site) {\n // Check if new pathname is already taken by another content\n const existingId = site.getPathnameConflict(data.pathname, locale, id);\n if (existingId) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error(`Pathname ${data.pathname} is already taken by content ${existingId}`),\n };\n }\n }\n }\n\n // Validate name change if updating name for blocks or data\n if (data.name && (manifest.kind === 'block' || manifest.kind === 'data')) {\n // Check if new name is already taken by another entry in the same collection\n const index = manifest.kind === 'block' ? this.contentIndex.getBlockIndex() : this.contentIndex.getDataIndex();\n const existing = index.getByName(manifest.collection, data.name);\n\n if (existing && existing.id !== id) {\n // Get title from the existing entry for a better error message\n const existingLocale = Object.values(existing.locales).find((lv) => lv !== undefined);\n const existingTitle = existingLocale?.meta?.title;\n const kindLabel = manifest.kind === 'block' ? 'Block' : 'Data';\n\n return {\n success: false,\n reason: 'write_error',\n error: new Error(\n `${kindLabel} name \"${data.name}\" is already in use${existingTitle ? ` by \"${existingTitle}\"` : ''}`,\n ),\n };\n }\n }\n\n // Handle pathname changes - track history only for published content\n const pathnameHistory = buildPathnameHistory(\n localeVersion.pathname,\n data.pathname,\n isContentPublished({\n publishAt: resolvePublishDate(data.publishAt, current.publishAt),\n unpublishAt: resolvePublishDate(data.unpublishAt, current.unpublishAt),\n }),\n new Date().toISOString(),\n );\n\n try {\n // Determine the target file path (may be different if pathname or name changed)\n let targetFilePath = filePath;\n if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname && manifest.site) {\n // For pages, calculate new file path based on new pathname\n const newLocaleVersion: LocaleVersion = {\n ...localeVersion,\n pathname: data.pathname,\n };\n targetFilePath = this.getFilePath(manifest, newLocaleVersion);\n\n // Ensure target directory exists\n await mkdir(dirname(targetFilePath), { recursive: true });\n } else if (data.name && localeVersion.name && data.name !== localeVersion.name && manifest.kind === 'block') {\n // For blocks, calculate new file path based on new name\n const newLocaleVersion: LocaleVersion = {\n ...localeVersion,\n name: data.name,\n };\n targetFilePath = this.getFilePath(manifest, newLocaleVersion);\n\n // Ensure target directory exists\n await mkdir(dirname(targetFilePath), { recursive: true });\n }\n\n // Write updated content\n if (targetFilePath.endsWith('.mdx')) {\n // Build frontmatter with special fields and metadata\n const publishAt = resolvePublishDate(data.publishAt, current.publishAt);\n const unpublishAt = resolvePublishDate(data.unpublishAt, current.unpublishAt);\n const frontmatterData = {\n id: manifest.id,\n created: current.created,\n modified,\n ...(publishAt && { publishAt }),\n ...(unpublishAt && { unpublishAt }),\n ...newMeta, // Spread metadata fields directly\n };\n\n // Extract just the content part from MDX (remove frontmatter if present)\n let mdxContentPart = newContent.mdx || '';\n if (mdxContentPart.startsWith('---')) {\n // Remove frontmatter if it exists\n const { content: contentOnly } = matter(mdxContentPart);\n mdxContentPart = contentOnly;\n }\n\n const mdxContent = serializeMdxWithFrontmatter(frontmatterData, mdxContentPart);\n\n // Use atomic write for MDX files too\n const hrtime = process.hrtime.bigint();\n const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;\n\n try {\n await writeFile(tempFile, mdxContent);\n await rename(tempFile, targetFilePath);\n } catch (error) {\n // Clean up temp file if rename fails\n try {\n await unlink(tempFile);\n } catch {\n // Ignore cleanup errors\n }\n throw error;\n }\n } else if (targetFilePath.endsWith('.json')) {\n // Data files use \"data\" field instead of \"content\"\n const fileContent = JSON.parse(await readFile(filePath, 'utf-8'));\n\n // Build updated data file structure\n const updatedFile = {\n id: fileContent.id,\n type: 'json' as const,\n created: fileContent.created,\n modified,\n ...(fileContent.publishAt && { publishAt: fileContent.publishAt }),\n ...(fileContent.unpublishAt && { unpublishAt: fileContent.unpublishAt }),\n meta: newMeta,\n data: sortKeys(newContent.data || {}, { deep: true }),\n };\n\n // Handle publish date updates\n if ('publishAt' in data) {\n if (data.publishAt) {\n (updatedFile as Record<string, unknown>).publishAt = data.publishAt;\n } else {\n delete (updatedFile as Record<string, unknown>).publishAt;\n }\n }\n\n if ('unpublishAt' in data) {\n if (data.unpublishAt) {\n (updatedFile as Record<string, unknown>).unpublishAt = data.unpublishAt;\n } else {\n delete (updatedFile as Record<string, unknown>).unpublishAt;\n }\n }\n\n // Serialize data file\n const serializedContent = JSON.stringify(sortKeys(updatedFile, { deep: true }), null, '\\t');\n\n // Use atomic write\n const hrtime = process.hrtime.bigint();\n const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;\n\n try {\n await writeFile(tempFile, serializedContent);\n await rename(tempFile, targetFilePath);\n } catch (error) {\n try {\n await unlink(tempFile);\n } catch {\n // Ignore cleanup errors\n }\n throw error;\n }\n } else {\n // VXJSON for pages (puck)\n const fileContent = JSON.parse(await readFile(filePath, 'utf-8'));\n\n // Build updated VXJSONFile structure\n const updatedFile: VXJSONFile = {\n id: fileContent.id,\n type: fileContent.type,\n created: fileContent.created,\n modified,\n publishAt: fileContent.publishAt,\n unpublishAt: fileContent.unpublishAt,\n previousPathnames: fileContent.previousPathnames,\n meta: newMeta,\n content: sortKeys(newContent, { deep: true }),\n };\n\n // Handle pathname changes and track history\n if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname) {\n // Only add to history if content is published\n if (isContentPublished(current)) {\n if (!updatedFile.previousPathnames) {\n updatedFile.previousPathnames = {};\n }\n updatedFile.previousPathnames[localeVersion.pathname] = modified;\n }\n }\n\n // Handle publish date updates\n if ('publishAt' in data) {\n if (data.publishAt) {\n updatedFile.publishAt = data.publishAt;\n } else {\n delete updatedFile.publishAt;\n }\n }\n\n if ('unpublishAt' in data) {\n if (data.unpublishAt) {\n updatedFile.unpublishAt = data.unpublishAt;\n } else {\n delete updatedFile.unpublishAt;\n }\n }\n\n // Serialize using VXJSON format to ensure content is last\n const serializedContent = VXJSON.serialize(updatedFile);\n\n // Use atomic write with better temp file naming\n // Include process.pid and hrtime for better uniqueness and easier debugging\n const hrtime = process.hrtime.bigint();\n const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;\n\n try {\n await writeFile(tempFile, serializedContent);\n await rename(tempFile, targetFilePath);\n } catch (error) {\n // Clean up temp file if rename fails\n try {\n await unlink(tempFile);\n } catch {\n // Ignore cleanup errors\n }\n throw error;\n }\n }\n\n // Calculate new etag from the written file\n const writtenBuffer = (await readFile(targetFilePath)) as Uint8Array;\n let newEtag: string;\n\n if (targetFilePath.endsWith('.mdx')) {\n // Find content position in MDX\n const contentStartMarker = new TextEncoder().encode('---\\n\\n');\n let contentPos = -1;\n for (let i = 0; i <= writtenBuffer.length - contentStartMarker.length; i++) {\n let match = true;\n for (let j = 0; j < contentStartMarker.length; j++) {\n if (writtenBuffer[i + j] !== contentStartMarker[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n contentPos = i + contentStartMarker.length;\n break;\n }\n }\n const etags = calculateEtagsFromMdxBuffer(writtenBuffer, contentPos);\n newEtag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else if (targetFilePath.endsWith('.json')) {\n // For data files, use simple etag (hash entire buffer)\n newEtag = VXJSON.calculateSimpleEtag(writtenBuffer);\n } else {\n // For VXJSON, calculateEtagsFromVXJSONBuffer finds the content position internally\n const etagResult = VXJSON.calculateETags(writtenBuffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format when updating content: ${etagResult.error}`);\n }\n\n newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n }\n\n // Build updated locale manifest with current publish data\n const updatedLocaleVersion: LocaleVersion = {\n ...localeVersion,\n etag: newEtag,\n modified,\n meta: newMeta,\n ...(data.pathname && { pathname: data.pathname }),\n ...(data.name && { name: data.name }),\n };\n\n // Handle publish dates using shared function\n // First preserve current values if not updating\n if (current.publishAt && !('publishAt' in data)) {\n updatedLocaleVersion.publishAt = current.publishAt;\n }\n if (current.unpublishAt && !('unpublishAt' in data)) {\n updatedLocaleVersion.unpublishAt = current.unpublishAt;\n }\n\n // Then apply updates\n updatePublishDates(updatedLocaleVersion, data);\n\n // Update pathname history if changed\n if (Object.keys(pathnameHistory).length > 0) {\n updatedLocaleVersion.previousPathnames = {\n ...localeVersion.previousPathnames,\n ...pathnameHistory,\n };\n } else {\n // Preserve existing previousPathnames if no change, but only if it has content\n const existingPreviousPathnames = localeVersion.previousPathnames;\n if (existingPreviousPathnames && Object.keys(existingPreviousPathnames).length > 0) {\n updatedLocaleVersion.previousPathnames = existingPreviousPathnames;\n } else {\n // Remove empty previousPathnames object\n delete updatedLocaleVersion.previousPathnames;\n }\n }\n\n // Store the old locale manifest for rollback if needed\n const oldLocaleVersion = manifest.locales[locale];\n\n try {\n // Update the locale in the existing manifest directly (avoids allocation)\n manifest.locales[locale] = updatedLocaleVersion;\n\n // Update index with the updated locale\n this.contentIndex.addContent(manifest, updatedLocaleVersion, newContent);\n\n // If pathname changed, delete the old file\n if (targetFilePath !== filePath) {\n try {\n await unlink(filePath);\n } catch (error) {\n // Log but don't fail if old file deletion fails\n console.warn(`Failed to delete old file ${filePath}:`, error);\n }\n }\n } catch (error) {\n // Rollback on error to maintain consistency\n manifest.locales[locale] = oldLocaleVersion;\n\n // If we wrote to a new file, try to clean it up\n if (targetFilePath !== filePath) {\n try {\n await unlink(targetFilePath);\n } catch {\n // Ignore cleanup errors\n }\n }\n\n throw error;\n }\n\n return {\n success: true,\n etag: newEtag,\n modified: new Date(),\n };\n } catch (error) {\n return {\n success: false,\n reason: 'write_error',\n error: ensureError(error),\n };\n }\n }\n\n async deleteContent(id: string, etag: string): Promise<DeleteResult> {\n // Get manifest for this ID\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Content not found'),\n };\n }\n\n // For deleteContent, we require the etag to match ANY locale (indicating user has current data)\n // But this is still a design flaw - we should probably require all etags or a master etag\n let matchingLocale: LocaleVersion | undefined;\n for (const localeVersion of localesOf(manifest)) {\n if (localeVersion.etag === etag) {\n matchingLocale = localeVersion;\n break;\n }\n }\n if (!matchingLocale) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag: Array.from(localesOf(manifest))[0]?.etag || '',\n error: new Error('Invalid etag - must match at least one locale'),\n };\n }\n\n try {\n // Delete all locale files in parallel\n const deletePromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {\n const filePath = this.getFilePath(manifest, localeVersion);\n await unlink(filePath);\n });\n\n await Promise.all(deletePromises);\n\n // Remove from index\n this.contentIndex.removeEntry(id);\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: ensureError(error),\n };\n }\n }\n\n async deleteLocalized(input: DeleteLocaleInput): Promise<DeleteResult> {\n const { id, locale, etag } = input;\n\n // Get manifest for this ID\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Content not found'),\n };\n }\n\n // Check if this locale exists\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Locale not found'),\n };\n }\n\n // Verify etag matches this locale\n if (localeVersion.etag !== etag) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag: localeVersion.etag,\n error: new Error('Invalid etag for locale'),\n };\n }\n\n // Don't allow deleting the last locale\n if (Object.keys(manifest.locales).length === 1) {\n return {\n success: false,\n error: new Error('Cannot delete the last locale. Use deleteContent to delete all content.'),\n };\n }\n\n try {\n // Delete the locale file\n const filePath = this.getFilePath(manifest, localeVersion);\n await unlink(filePath);\n\n // Remove locale from manifest and index\n manifest.locales[locale] = undefined;\n this.contentIndex.removeLocale(manifest.id, locale);\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: ensureError(error),\n };\n }\n }\n\n getSite(siteName: string): Site | null {\n if (siteName === 'blocks') {\n throw new Error('Use `blocks` property instead of getSite(\"blocks\")');\n }\n\n const site = this.sites[siteName];\n return site || null;\n }\n\n *listAllContent(filters?: GlobalFilters): Generator<ContentManifest> {\n yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);\n }\n *findUntranslatedContent(targetLocale: string, options?: FindOptions): Generator<ContentManifest> {\n yield* this.contentIndex.findUntranslatedContent(targetLocale, options);\n }\n\n /**\n * Reindex files that were added or changed after initial creation\n *\n * This method:\n * 1. Either scans for all content files or processes specific paths\n * 2. Uses the path index to check if files are already indexed\n * 3. Indexes new files or force-reindexes specified files\n * 4. Optionally handles file deletions\n *\n * @param paths - Optional array of specific file paths to reindex. If not provided, scans all content files.\n * @param options - Options for reindexing behavior\n * @returns Statistics about the reindexing operation\n */\n async reindex(paths?: string[], options?: { handleDeletions?: boolean }): Promise<ReindexResult> {\n const filesToProcess = paths || (await this.scanContentFiles());\n let filesSkipped = 0;\n let filesProcessed = 0;\n let filesDeleted = 0;\n let errors = 0;\n const filesToIndex: string[] = [];\n const updated: LocalizedManifest[] = [];\n const deleted: Array<{ id: string; locale: string; kind: 'page' | 'block' | 'data' }> = [];\n\n // Check each file\n for (const filePath of filesToProcess) {\n // Check if file exists (for deletion handling)\n if (options?.handleDeletions && paths) {\n try {\n await readFile(filePath);\n } catch (error) {\n // File doesn't exist - remove from index\n const parsed = this.parseFilePath(filePath);\n if (parsed) {\n // Find the content ID to remove\n let manifest: ContentManifest | null = null;\n if (parsed.kind === 'block' && parsed.name) {\n manifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);\n } else if (parsed.kind === 'data' && parsed.name) {\n manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);\n } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {\n manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);\n }\n\n if (manifest) {\n // Track the deletion\n deleted.push({\n id: manifest.id,\n locale: parsed.locale,\n kind: parsed.kind,\n });\n\n // Remove the specific locale or entire entry if it's the last locale\n if (Object.keys(manifest.locales).length === 1) {\n this.contentIndex.removeEntry(manifest.id);\n } else {\n // Remove just this locale\n manifest.locales[parsed.locale] = undefined;\n this.contentIndex.removeLocale(manifest.id, parsed.locale);\n }\n filesDeleted++;\n }\n }\n continue;\n }\n }\n\n const parsed = this.parseFilePath(filePath);\n if (!parsed) {\n console.warn(`Skipping unrecognized file pattern: ${filePath}`);\n errors++;\n continue;\n }\n\n // Check if this path is already indexed\n let isIndexed = false;\n if (parsed.kind === 'block' && parsed.name) {\n // Check block index by name\n const manifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);\n isIndexed = !!manifest;\n } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {\n // Check site index by pathname\n const manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);\n isIndexed = !!manifest;\n } else if (parsed.kind === 'data' && parsed.name) {\n // Check data index by name\n const manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);\n isIndexed = !!manifest;\n }\n\n if (isIndexed) {\n if (!paths) {\n // Skip already indexed files when doing a full scan\n filesSkipped++;\n } else {\n // For specific paths, check if the file has changed\n const fileStats = await readFile(filePath);\n let currentManifest: ContentManifest | null = null;\n if (parsed.kind === 'block' && parsed.name) {\n currentManifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);\n } else if (parsed.kind === 'data' && parsed.name) {\n currentManifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);\n } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {\n currentManifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);\n }\n\n if (currentManifest) {\n // Calculate current file etag\n const buffer = fileStats as Uint8Array;\n let currentEtag: string;\n\n if (filePath.endsWith('.mdx')) {\n const contentPos = findMdxContentStartPosition(buffer);\n const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);\n currentEtag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else if (filePath.endsWith('.vxjson')) {\n const etagResult = VXJSON.calculateETags(buffer);\n if (!etagResult.success) {\n // File needs repair - add to filesToIndex for repair\n filesToIndex.push(filePath);\n continue;\n }\n currentEtag = etagResult.contentEtag\n ? `${etagResult.metaEtag}.${etagResult.contentEtag}`\n : etagResult.metaEtag;\n } else if (filePath.endsWith('.json')) {\n // For JSON data files, use content hash as etag\n currentEtag = xxh3.xxh64(buffer).toString(16);\n } else {\n // Unknown file type, skip\n filesSkipped++;\n continue;\n }\n\n // Only reindex if etag changed\n const existingEtag = currentManifest.locales[parsed.locale]?.etag;\n\n if (existingEtag === currentEtag) {\n const relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n console.log(`[Content] skip ${relativePath} (unchanged)`);\n filesSkipped++;\n } else {\n filesToIndex.push(filePath);\n }\n } else {\n // Not indexed yet\n filesToIndex.push(filePath);\n }\n }\n } else {\n // Not indexed yet\n filesToIndex.push(filePath);\n }\n }\n\n // Index the files\n const buffers = Array.from({ length: Math.min(filesToIndex.length, 100) }, () => new Uint8Array(4096));\n\n for (let i = 0; i < filesToIndex.length; i++) {\n const filePath = filesToIndex[i];\n const bufferIndex = i % buffers.length;\n\n try {\n const result = await this.parseFileHeaderWithRepair(filePath, buffers[bufferIndex]);\n if (result) {\n const { manifest, localeVersion, content } = result;\n\n // Add to index\n this.contentIndex.addContent(manifest, localeVersion, content);\n filesProcessed++;\n\n // Create LocalizedManifest for the updated list\n const localizedManifest: LocalizedManifest = {\n id: manifest.id,\n type: manifest.type,\n kind: manifest.kind,\n site: manifest.site,\n collection: manifest.collection,\n localized: localeVersion,\n };\n updated.push(localizedManifest);\n }\n } catch (error) {\n console.error(`Failed to reindex ${filePath}:`, error);\n errors++;\n }\n }\n\n const result: ReindexResult = {\n filesProcessed,\n filesSkipped,\n updated,\n };\n\n if (options?.handleDeletions && deleted.length > 0) {\n result.filesDeleted = filesDeleted;\n result.deleted = deleted;\n }\n\n if (errors > 0) {\n result.errors = errors;\n }\n\n return result;\n }\n\n /**\n * Read content directly from cache\n * For testing purposes - returns null if not cached\n */\n async readFromCache(id: string, locale: string): Promise<ContentData | null> {\n return this.contentIndex.getCachedContent(id, locale);\n }\n\n async getContentAsBuffer(\n id: string,\n locale: string,\n ): Promise<{\n buffer: Uint8Array;\n etag: string;\n contentType: 'application/json' | 'text/mdx';\n } | null> {\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest || !manifest.locales[locale]) {\n return null;\n }\n\n const localeVersion = manifest.locales[locale];\n const filePath = this.getFilePath(manifest, localeVersion);\n const buffer = (await readFile(filePath)) as Uint8Array;\n const contentType = filePath.endsWith('.mdx') ? 'text/mdx' : 'application/json';\n\n // Calculate ETag based on file type\n let etag: string;\n if (contentType === 'text/mdx') {\n // Find content start position for MDX\n const contentStartMarker = new TextEncoder().encode('---\\n\\n');\n let contentPos = -1;\n for (let i = 0; i <= buffer.length - contentStartMarker.length; i++) {\n let match = true;\n for (let j = 0; j < contentStartMarker.length; j++) {\n if (buffer[i + j] !== contentStartMarker[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n contentPos = i + contentStartMarker.length;\n break;\n }\n }\n const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);\n etag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else {\n // Calculate ETags for JSON\n const etagResult = VXJSON.calculateETags(buffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format in getContentAsBuffer: ${etagResult.error}`);\n }\n\n etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n }\n\n return { buffer, etag, contentType };\n }\n\n async batchUpdate(operations: UpdateLocaleInput[]): Promise<BatchResult> {\n // First, validate all operations can succeed\n const validationResults: Array<{\n op: UpdateLocaleInput;\n manifest: ContentManifest;\n localeVersion: LocaleVersion;\n current?: LocaleFileData;\n }> = [];\n\n for (const op of operations) {\n const manifest = this.contentIndex.getManifest(op.id);\n if (!manifest) {\n // Content not found\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error('Content not found'),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n\n const localeVersion = manifest.locales[op.locale];\n if (!localeVersion) {\n // Locale not found\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error('Locale not found'),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n\n // Check etag\n if (localeVersion.etag !== op.etag) {\n // Stale write detected\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error('Stale write'),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n\n // Read current content for validation\n const filePath = this.getFilePath(manifest, localeVersion);\n const current = await this.readLocaleFile(filePath, op.locale);\n if (!current) {\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error('Failed to read content'),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n\n // Validate metadata size if updating\n if (op.data.meta) {\n const newMeta = { ...current.meta, ...op.data.meta };\n const validation = validateAndPrepareMetadata(newMeta);\n if (!validation.valid) {\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error(validation.error!),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n }\n\n validationResults.push({ op, manifest, localeVersion, current });\n }\n\n // All validations passed, now perform updates\n const results: BatchOperationResult[] = [];\n let updated = 0;\n\n for (const { op } of validationResults) {\n const result = await this.updateLocalized(op);\n if (result.success) {\n updated++;\n results.push({ id: op.id, locale: op.locale, updated: true, etag: result.etag });\n } else {\n // This shouldn't happen if validation was correct\n results.push({ id: op.id, locale: op.locale, updated: false, error: result.error });\n }\n }\n\n return {\n operations: results,\n success: updated === operations.length,\n updated,\n failed: operations.length - updated,\n };\n }\n}\n","import { normalize, resolve } from 'path';\nimport { FileSystemContentAPI } from './filesystem-content-api';\n\nexport interface ContentWatcherOptions {\n contentRoot: string;\n canvasDir?: string;\n}\n\nexport interface WebSocketSender {\n send(payload: { type: string; event: string; data: any }): void;\n}\n\n/**\n * Creates a content API instance for the given options\n */\nexport async function createContentAPI(options: ContentWatcherOptions): Promise<FileSystemContentAPI> {\n return await FileSystemContentAPI.create({\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n });\n}\n\n/**\n * Creates file change handlers for content watching\n */\nexport function createContentWatchHandlers(\n contentApi: FileSystemContentAPI,\n options: ContentWatcherOptions,\n ws: WebSocketSender,\n) {\n const handleFileChange = async (file: string, action: 'update' | 'create' | 'delete') => {\n // Only process content files (.mdx, .vxjson, and .json in data/ directory)\n const isContentFile = file.endsWith('.mdx') || file.endsWith('.vxjson');\n const isDataFile = file.endsWith('.json') && file.includes('/data/');\n if (!isContentFile && !isDataFile) {\n return;\n }\n\n // Normalize paths for consistent comparison\n const normalizedFile = normalize(resolve(file));\n const normalizedRoot = normalize(resolve(options.contentRoot));\n\n if (normalizedFile.startsWith(normalizedRoot)) {\n const relativePath = normalizedFile.replace(normalizedRoot + '/', '');\n console.log(`[Content] ${action}: ${relativePath}`);\n\n try {\n // Reindex the file\n const reindexOptions = action === 'delete' ? { handleDeletions: true } : undefined;\n const result = await contentApi.reindex([normalizedFile], reindexOptions);\n\n // Send updates for each changed locale\n for (const manifest of result.updated) {\n const message = {\n type: 'custom',\n event: 'conloca:content-update',\n data: {\n action,\n manifest,\n },\n };\n ws.send(message);\n }\n\n // Send deletion updates\n if (action === 'delete' && result.deleted) {\n for (const deletion of result.deleted) {\n ws.send({\n type: 'custom',\n event: 'conloca:content-update',\n data: {\n action: 'delete',\n ...deletion,\n },\n });\n }\n }\n } catch (error) {\n console.error('[Content Watcher] Reindex failed:', error);\n return;\n }\n }\n };\n\n return {\n onChange: (file: string) => handleFileChange(file, 'update'),\n onAdd: (file: string) => handleFileChange(file, 'create'),\n onUnlink: (file: string) => handleFileChange(file, 'delete'),\n };\n}\n","import { Blocks } from './blocks';\nimport type { ContentAPI } from './content-api.interface';\nimport { filterContentWithIndexes } from './content-filters';\nimport { ContentIndex } from './content-index';\nimport {\n buildLocaleVersion,\n buildPathnameHistory,\n generateContentId,\n isContentPublished,\n shouldUpdateModifiedTimestamp,\n updatePublishDates,\n validateAndPrepareMetadata,\n validateCreateContent,\n} from './content-operations';\nimport { getCurrentISODate, localesOf, mapLocales, mapSiteNames, serializeMdxWithFrontmatter } from './content-utils';\nimport { Data } from './data';\nimport { calculateEtagsFromMdxBuffer, findMdxContentStartPosition } from './etag-utils';\nimport { Site } from './site';\nimport type {\n BatchResult,\n ContentData,\n ContentEntry,\n ContentManifest,\n ContentMeta,\n CreateContentInput,\n CreateResult,\n DeleteLocaleInput,\n DeleteResult,\n FindOptions,\n GlobalFilters,\n LocaleVersion,\n LocalizedEntry,\n SitesConfig,\n UpdateLocaleInput,\n UpdateResult,\n VXJSONFile,\n} from './types';\nimport { VXJSON } from './vxjson';\n\n/**\n * In-memory implementation of ContentAPI for testing\n * Provides a clean, mock-free way to test the API without filesystem dependencies\n */\nexport class InMemoryContentAPI implements ContentAPI {\n private contentIndex: ContentIndex;\n readonly sitesConfig: SitesConfig;\n readonly blocks: Blocks;\n readonly data: Data;\n private readonly sites: Record<string, Site>;\n\n constructor(sitesConfig?: SitesConfig) {\n this.sitesConfig = sitesConfig || {\n sites: {},\n globalLocales: ['en'],\n };\n\n // Initialize content index (not cached for in-memory)\n this.contentIndex = ContentIndex.createUncached(this.sitesConfig);\n\n // Initialize blocks\n this.blocks = new Blocks(this, this.contentIndex.getBlockIndex());\n\n // Initialize data\n this.data = new Data(this, this.contentIndex.getDataIndex());\n\n // Initialize all sites\n this.sites = mapSiteNames(this.sitesConfig, (siteName) => {\n const siteIndex = this.contentIndex.getSiteIndex(siteName);\n if (!siteIndex) {\n throw new Error(`Site index not found for ${siteName}`);\n }\n return new Site(siteName, this, siteIndex);\n });\n }\n\n // Core content operations\n async getContent(id: string): Promise<ContentEntry | null> {\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return null;\n }\n\n // Build ContentEntry from manifest and cached content\n const contentEntry: ContentEntry = {\n id: manifest.id,\n kind: manifest.kind,\n site: manifest.site,\n collection: manifest.collection,\n type: manifest.type,\n locales: {},\n };\n\n // Add locale data with content from cache\n for (const localeVersion of localesOf(manifest)) {\n const { locale } = localeVersion;\n const cachedContent = this.contentIndex.getCachedContent(id, locale);\n if (cachedContent) {\n // For MDX content, include frontmatter for variable access\n let contentToReturn = cachedContent;\n if (manifest.type === 'mdx' && cachedContent.mdx) {\n const frontmatterData = {\n id: manifest.id,\n created: localeVersion.created,\n modified: localeVersion.modified,\n ...(localeVersion.publishAt && { publishAt: localeVersion.publishAt }),\n ...(localeVersion.unpublishAt && { unpublishAt: localeVersion.unpublishAt }),\n ...localeVersion.meta, // Spread metadata fields directly\n };\n contentToReturn = {\n ...cachedContent,\n mdx: serializeMdxWithFrontmatter(frontmatterData, cachedContent.mdx),\n };\n }\n\n contentEntry.locales[locale] = {\n ...localeVersion,\n content: contentToReturn,\n };\n }\n }\n\n return contentEntry;\n }\n\n async getLocalized(id: string, locale: string): Promise<LocalizedEntry | null> {\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest || !manifest.locales[locale]) {\n return null;\n }\n\n const localeVersion = manifest.locales[locale];\n const cachedContent = this.contentIndex.getCachedContent(id, locale);\n\n if (!cachedContent) {\n return null;\n }\n\n // For MDX content, include frontmatter for variable access\n let contentToReturn = { ...cachedContent };\n if (manifest.type === 'mdx' && cachedContent.mdx) {\n const frontmatterData = {\n id: manifest.id,\n created: localeVersion.created,\n modified: localeVersion.modified,\n ...(localeVersion.publishAt && { publishAt: localeVersion.publishAt }),\n ...(localeVersion.unpublishAt && { unpublishAt: localeVersion.unpublishAt }),\n ...localeVersion.meta, // Spread metadata fields directly\n };\n contentToReturn = {\n ...cachedContent,\n mdx: serializeMdxWithFrontmatter(frontmatterData, cachedContent.mdx),\n };\n }\n\n // Return a deep copy to prevent modifications to the original data\n return {\n id,\n site: manifest.site,\n collection: manifest.collection,\n type: manifest.type,\n kind: manifest.kind,\n localized: {\n ...localeVersion,\n meta: { ...localeVersion.meta },\n content: contentToReturn,\n previousPathnames: localeVersion.previousPathnames ? { ...localeVersion.previousPathnames } : undefined,\n },\n };\n }\n\n async createContent(data: CreateContentInput): Promise<CreateResult> {\n // Use shared validation\n const validation = validateCreateContent(data, this.sites, this.blocks);\n if (!validation.valid) {\n return {\n success: false,\n reason: validation.reason,\n error: validation.error ? new Error(validation.error) : undefined,\n existingId: validation.existingId,\n };\n }\n\n // Generate ID\n const id = generateContentId();\n const now = getCurrentISODate();\n\n const contentCache: Record<string, ContentData> = {};\n\n const locales = mapLocales(\n data.site ? this.sitesConfig.sites[data.site].locales : this.sitesConfig.globalLocales,\n (locale) => {\n const localeData = data.locales[locale];\n if (!localeData) return undefined;\n\n const meta = { ...data.meta, ...localeData.meta } as ContentMeta;\n\n // Calculate dual ETag for this locale\n const fileData: VXJSONFile = {\n id,\n type: data.type,\n created: now,\n modified: now,\n publishAt:\n localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,\n unpublishAt:\n localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,\n meta,\n content: localeData.content,\n };\n\n // Serialize to buffer and calculate ETags based on content type\n let buffer: Uint8Array;\n let etag: string;\n\n if (data.type === 'mdx') {\n // For MDX content, serialize as frontmatter + content\n const frontmatterData = {\n id,\n created: now,\n modified: now,\n ...(localeData.publishAt && { publishAt: localeData.publishAt }),\n ...(localeData.unpublishAt && { unpublishAt: localeData.unpublishAt }),\n ...meta, // Spread metadata fields directly, not nested\n };\n\n const mdxContent = serializeMdxWithFrontmatter(frontmatterData, localeData.content.mdx || '');\n buffer = new TextEncoder().encode(mdxContent);\n\n // Find content start position using shared utility\n const contentPos = findMdxContentStartPosition(buffer);\n\n // Calculate ETags using MDX-specific logic\n const etagResult = calculateEtagsFromMdxBuffer(buffer, contentPos);\n etag = `${etagResult.metaEtag}.${etagResult.contentEtag}`;\n } else {\n // For Puck content, serialize as VXJSON\n const jsonStr = VXJSON.serialize(fileData);\n buffer = Buffer.from(jsonStr, 'utf-8') as Uint8Array;\n const etagResult = VXJSON.calculateETags(buffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format: ${etagResult.error}`);\n }\n\n etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n }\n\n // Build locale manifest using shared function\n const localeVersion = buildLocaleVersion({\n locale,\n etag,\n created: now,\n modified: now,\n meta,\n kind: data.kind,\n pathname: data.kind === 'page' ? localeData.pathname : undefined,\n name: data.kind === 'block' || data.kind === 'data' ? data.name : undefined,\n publishAt:\n localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,\n unpublishAt:\n localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,\n });\n\n contentCache[locale] = localeData.content;\n return localeVersion;\n },\n );\n\n // Build manifest and content cache\n const manifest: ContentManifest = {\n id,\n type: data.type,\n kind: data.kind,\n site: data.site,\n collection: data.collection,\n locales,\n };\n\n // Update index with each locale\n for (const localeVersion of localesOf(manifest)) {\n this.contentIndex.addContent(manifest, localeVersion, contentCache[localeVersion.locale]);\n }\n\n // Return the first locale's etag (typically there's only one during creation)\n const firstLocaleEtag = Object.values(manifest.locales)[0]?.etag || '';\n\n return {\n success: true,\n id,\n etag: firstLocaleEtag,\n created: new Date(now),\n };\n }\n\n async updateLocalized(input: UpdateLocaleInput): Promise<UpdateResult> {\n const { id, locale, data, etag } = input;\n\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Get the specific locale manifest\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Check etag matches\n if (localeVersion.etag !== etag) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag: localeVersion.etag,\n };\n }\n\n // Get current content from cache\n const currentContent = this.contentIndex.getCachedContent(id, locale);\n if (!currentContent) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Validate metadata if updating\n if (data.meta) {\n const newMeta = { ...localeVersion.meta, ...data.meta };\n const validation = validateAndPrepareMetadata(newMeta);\n if (!validation.valid) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error(validation.error!),\n };\n }\n }\n\n // Validate pathname change if updating pathname for pages\n if (data.pathname && manifest.kind === 'page' && manifest.site) {\n const site = this.sites[manifest.site];\n if (site) {\n // Check if new pathname is already taken by another content\n const existingId = site.getPathnameConflict(data.pathname, locale, id);\n if (existingId) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error(`Pathname ${data.pathname} is already taken by content ${existingId}`),\n };\n }\n }\n }\n\n // Update content\n const now = new Date();\n const nowStr = now.toISOString();\n\n // Build updated locale manifest\n const oldPathname = localeVersion.pathname;\n const updatedLocaleVersion = { ...localeVersion };\n\n // Update modified timestamp for any changes (content or metadata)\n if (shouldUpdateModifiedTimestamp(data)) {\n // Use provided modified timestamp or current time\n const newModified = data.modified || nowStr;\n updatedLocaleVersion.modified = newModified;\n } else if (data.modified) {\n // If modified timestamp is explicitly provided, always use it\n updatedLocaleVersion.modified = data.modified;\n }\n\n if (data.meta) {\n updatedLocaleVersion.meta = { ...localeVersion.meta, ...data.meta };\n }\n\n if (data.pathname !== undefined && manifest.kind === 'page') {\n // Build pathname history for published content\n const pathnameHistory = buildPathnameHistory(\n oldPathname,\n data.pathname,\n isContentPublished(localeVersion),\n nowStr,\n );\n\n // Merge with existing pathname history\n if (Object.keys(pathnameHistory).length > 0) {\n updatedLocaleVersion.previousPathnames = {\n ...localeVersion.previousPathnames,\n ...pathnameHistory,\n };\n }\n\n updatedLocaleVersion.pathname = data.pathname;\n }\n\n // Handle publish date updates using shared function\n updatePublishDates(updatedLocaleVersion, data);\n\n // Prepare updated content\n const updatedContent = data.content ? { ...currentContent, ...data.content } : currentContent;\n\n // Calculate new dual ETag by creating a buffer from the in-memory data\n // Structure it like the filesystem JSON files\n const fileData: VXJSONFile = {\n id: manifest.id,\n type: manifest.type,\n created: updatedLocaleVersion.created,\n modified: updatedLocaleVersion.modified,\n publishAt: updatedLocaleVersion.publishAt,\n unpublishAt: updatedLocaleVersion.unpublishAt,\n meta: updatedLocaleVersion.meta,\n previousPathnames: updatedLocaleVersion.previousPathnames,\n content: updatedContent,\n };\n\n // Serialize to buffer and calculate ETags based on content type\n let buffer: Uint8Array;\n let newEtag: string;\n\n if (manifest.type === 'mdx') {\n // For MDX content, serialize as frontmatter + content\n const frontmatterData = {\n id: manifest.id,\n created: updatedLocaleVersion.created,\n modified: updatedLocaleVersion.modified,\n ...(updatedLocaleVersion.publishAt && { publishAt: updatedLocaleVersion.publishAt }),\n ...(updatedLocaleVersion.unpublishAt && { unpublishAt: updatedLocaleVersion.unpublishAt }),\n ...updatedLocaleVersion.meta, // Spread metadata fields directly, not nested\n };\n\n const mdxContent = serializeMdxWithFrontmatter(frontmatterData, updatedContent.mdx || '');\n buffer = new TextEncoder().encode(mdxContent);\n\n // Find content start position using shared utility\n const contentPos = findMdxContentStartPosition(buffer);\n\n // Calculate ETags using MDX-specific logic\n const etagResult = calculateEtagsFromMdxBuffer(buffer, contentPos);\n newEtag = `${etagResult.metaEtag}.${etagResult.contentEtag}`;\n } else {\n // For Puck content, serialize as VXJSON\n const jsonStr = VXJSON.serialize(fileData);\n buffer = Buffer.from(jsonStr, 'utf-8') as Uint8Array;\n const etagResult = VXJSON.calculateETags(buffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format: ${etagResult.error}`);\n }\n\n newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n }\n\n updatedLocaleVersion.etag = newEtag;\n\n // Build updated manifest with only the changed locale\n const updatedManifest: ContentManifest = {\n ...manifest,\n locales: {\n ...manifest.locales,\n [locale]: updatedLocaleVersion,\n },\n };\n\n // Update content in the index (this will handle pathname index updates)\n this.contentIndex.addContent(updatedManifest, updatedLocaleVersion, updatedContent);\n\n return {\n success: true,\n etag: updatedLocaleVersion.etag,\n modified: now,\n };\n }\n\n async deleteContent(id: string, etag: string): Promise<DeleteResult> {\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Content not found'),\n };\n }\n\n // Verify etag\n let hasMatchingEtag = false;\n for (const localeVersion of localesOf(manifest)) {\n if (localeVersion.etag === etag) {\n hasMatchingEtag = true;\n break;\n }\n }\n\n if (!hasMatchingEtag && etag) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag: Array.from(localesOf(manifest))[0]?.etag || '',\n error: new Error('ETag mismatch'),\n };\n }\n\n // Remove from index (this also removes from content cache)\n this.contentIndex.removeEntry(id);\n\n return {\n success: true,\n };\n }\n\n // Site and blocks access\n getSite(siteName: string): Site | null {\n if (siteName === 'blocks') {\n throw new Error('Use `blocks` property instead of getSite(\"blocks\")');\n }\n\n const site = this.sites[siteName];\n return site || null;\n }\n\n // Global operations\n *listAllContent(filters?: GlobalFilters): Generator<ContentManifest> {\n yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);\n }\n\n *findUntranslatedContent(targetLocale: string, options?: FindOptions): Generator<ContentManifest> {\n // Use the index method which already handles all the filtering efficiently\n yield* this.contentIndex.findUntranslatedContent(targetLocale, options);\n }\n\n async deleteLocalized(input: DeleteLocaleInput): Promise<DeleteResult> {\n const { id, locale, etag } = input;\n\n // Get existing manifest\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Content not found'),\n };\n }\n\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Locale not found'),\n };\n }\n\n // Check etag\n if (localeVersion.etag !== etag) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag: localeVersion.etag,\n error: new Error('Stale write - etag mismatch'),\n };\n }\n\n // If only one locale left, remove entire content\n if (Object.keys(manifest.locales).length === 1) {\n this.contentIndex.removeEntry(id);\n } else {\n // Build updated manifest without the deleted locale\n const updatedManifest: ContentManifest = {\n ...manifest,\n locales: { ...manifest.locales },\n };\n updatedManifest.locales[locale] = undefined;\n\n // Remove locale from index\n this.contentIndex.removeLocale(manifest.id, locale);\n }\n\n return {\n success: true,\n };\n }\n\n async batchUpdate(operations: UpdateLocaleInput[]): Promise<BatchResult> {\n const results: BatchResult = {\n operations: [],\n success: true,\n failed: 0,\n updated: 0,\n };\n\n for (const op of operations) {\n const result = await this.updateLocalized(op);\n\n if (result.success) {\n results.updated++;\n results.operations.push({\n id: op.id,\n locale: op.locale,\n updated: true,\n etag: result.etag,\n });\n } else {\n results.failed++;\n results.success = false;\n results.operations.push({\n id: op.id,\n locale: op.locale,\n updated: false,\n error: result.error || new Error(result.reason || 'Update failed'),\n });\n }\n }\n\n return results;\n }\n\n // Test helper method to directly set content\n setContent(id: string, content: ContentEntry): void {\n // Build manifest from ContentEntry\n const manifest: ContentManifest = {\n id: content.id,\n type: content.type,\n kind: content.kind,\n site: content.site,\n collection: content.collection,\n locales: {},\n };\n\n const contentCache: Record<string, ContentData | null> = {};\n\n for (const [locale, localeData] of Object.entries(content.locales)) {\n const manifestLocale: LocaleVersion = {\n locale,\n etag: localeData.etag,\n created: localeData.created,\n modified: localeData.modified,\n meta: localeData.meta,\n };\n if (localeData.publishAt !== undefined) {\n manifestLocale.publishAt = localeData.publishAt;\n }\n if (localeData.unpublishAt !== undefined) {\n manifestLocale.unpublishAt = localeData.unpublishAt;\n }\n if (localeData.name) {\n manifestLocale.name = localeData.name;\n }\n if (localeData.pathname) {\n manifestLocale.pathname = localeData.pathname;\n }\n if (localeData.previousPathnames) {\n manifestLocale.previousPathnames = localeData.previousPathnames;\n }\n manifest.locales[locale] = manifestLocale;\n contentCache[locale] = localeData.content;\n }\n\n // Add to content index with each locale\n for (const localeVersion of localesOf(manifest)) {\n this.contentIndex.addContent(manifest, localeVersion, contentCache[localeVersion.locale]);\n }\n }\n\n // Test helper to clear all content\n clear(): void {\n this.contentIndex.clear();\n }\n\n async getContentAsBuffer(\n id: string,\n locale: string,\n ): Promise<{\n buffer: Uint8Array;\n etag: string;\n contentType: 'application/json' | 'text/mdx';\n } | null> {\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest || !manifest.locales[locale]) {\n return null;\n }\n\n const localeVersion = manifest.locales[locale];\n const cachedContent = this.contentIndex.getCachedContent(id, locale);\n if (!cachedContent) {\n return null;\n }\n\n // Serialize based on content type\n let buffer: Uint8Array;\n let calculatedEtag: string;\n let contentType: 'application/json' | 'text/mdx';\n\n if (manifest.type === 'mdx') {\n // For MDX content, serialize as frontmatter + content\n const frontmatterData = {\n id: manifest.id,\n created: localeVersion.created,\n modified: localeVersion.modified,\n ...(localeVersion.publishAt && { publishAt: localeVersion.publishAt }),\n ...(localeVersion.unpublishAt && { unpublishAt: localeVersion.unpublishAt }),\n ...localeVersion.meta, // Spread metadata fields directly, not nested\n };\n\n const mdxContent = serializeMdxWithFrontmatter(frontmatterData, cachedContent.mdx || '');\n buffer = new TextEncoder().encode(mdxContent);\n\n // Find content start position using shared utility\n const contentPos = findMdxContentStartPosition(buffer);\n\n // Calculate ETags using MDX-specific logic\n const etagResult = calculateEtagsFromMdxBuffer(buffer, contentPos);\n calculatedEtag = `${etagResult.metaEtag}.${etagResult.contentEtag}`;\n contentType = 'text/mdx';\n } else {\n // For Puck content, serialize as VXJSON\n const fileData: VXJSONFile = {\n id: manifest.id,\n type: manifest.type,\n created: localeVersion.created,\n modified: localeVersion.modified,\n publishAt: localeVersion.publishAt,\n unpublishAt: localeVersion.unpublishAt,\n meta: localeVersion.meta,\n previousPathnames: localeVersion.previousPathnames,\n content: cachedContent,\n };\n const jsonStr = VXJSON.serialize(fileData);\n buffer = Buffer.from(jsonStr, 'utf-8') as Uint8Array;\n\n // Calculate ETags to ensure they match what's stored\n const etagResult = VXJSON.calculateETags(buffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format: ${etagResult.error}`);\n }\n\n calculatedEtag = etagResult.contentEtag\n ? `${etagResult.metaEtag}.${etagResult.contentEtag}`\n : etagResult.metaEtag;\n contentType = 'application/json';\n }\n\n return {\n buffer,\n etag: calculatedEtag,\n contentType,\n };\n }\n}\n","import { Hono } from 'hono';\nimport { cors } from 'hono/cors';\nimport { type AssetConfig, AssetOperations } from './asset-operations';\nimport type { ContentAPI } from './content-api.interface';\nimport { localesOf } from './content-utils';\nimport { createGitOperations, type GitAuthor, type GitConfig } from './git-operations';\nimport type { APIError, ContentManifest, ErrorCode, FindOptions, GlobalFilters } from './types';\nimport { ErrorCodes } from './types';\n\n/**\n * Helper to create standardized error responses\n */\nfunction errorResponse(code: ErrorCode, message: string, details?: any): APIError {\n return {\n error: {\n code,\n message,\n ...(details && { details }),\n },\n };\n}\n\n/**\n * Helper to log and create error responses for unexpected errors\n */\nfunction logAndCreateErrorResponse(error: unknown, code: ErrorCode, message: string, details?: any): APIError {\n console.error(`[Content API] ${message}:`, error);\n return errorResponse(code, message, details);\n}\n\n/**\n * Create REST API router using Hono\n * Implements the ID-based API specification from implementation-plan.md\n */\nexport interface ContentAPIRouterOptions {\n assetsPath?: string;\n assetConfig?: Omit<AssetConfig, 'assetsPath'>;\n /** Content root directory for asset usage tracking */\n contentRoot?: string;\n}\n\nexport function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRouterOptions) {\n const app = new Hono();\n\n // Enable CORS for CMS access\n app.use('/*', cors());\n\n // GET /auth/user - Get current authenticated user\n app.get('/auth/user', async (c) => {\n const email = c.req.header('X-CF-User-Email');\n const sub = c.req.header('X-CF-User-Sub');\n\n if (!email) {\n return c.json({ authenticated: false });\n }\n\n return c.json({\n authenticated: true,\n user: { email, sub },\n });\n });\n\n // GET /content/collections - List all collections across all sites\n app.get('/content/collections', async (c) => {\n try {\n const allCollections = new Set<string>();\n\n // Get collections from blocks\n const blockCollections = api.blocks.collections;\n blockCollections.forEach((c) => allCollections.add(c));\n\n // Get collections from all sites\n for (const siteName of Object.keys(api.sitesConfig.sites)) {\n const site = api.getSite(siteName);\n if (site) {\n const siteCollections = site.collections;\n siteCollections.forEach((c) => allCollections.add(c));\n }\n }\n\n return c.json({\n collections: Array.from(allCollections).sort(),\n });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list collections'), 500);\n }\n });\n\n // GET /content - List all content with optional filters\n app.get('/content', async (c) => {\n const kind = c.req.query('kind'); // 'block' or 'page'\n const site = c.req.query('site');\n const collection = c.req.query('collection');\n const locales = c.req.query('locales'); // comma-separated\n const type = c.req.query('type'); // 'puck' or 'mdx'\n const published = c.req.query('published');\n const localization = c.req.query('localization'); // 'complete', 'partial', 'one'\n const missingLocales = c.req.query('missingLocales'); // comma-separated\n\n try {\n const filters: any = {};\n\n // Pass all filters to the API - let it handle the logic\n if (kind) filters.kind = kind;\n if (site) filters.site = site;\n if (collection) filters.collection = collection;\n if (locales) filters.locales = locales.split(',').map((l) => l.trim());\n if (type) filters.type = type;\n if (published !== undefined) filters.published = published === 'true';\n if (localization) filters.localization = localization;\n if (missingLocales) filters.missingLocales = missingLocales.split(',').map((l) => l.trim());\n\n const items = Array.from(api.listAllContent(filters));\n return c.json({ items, total: items.length });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list content'), 500);\n }\n });\n\n // GET /content/:id - Get all locales for content ID\n app.get('/content/:id', async (c) => {\n const id = c.req.param('id');\n\n try {\n const content = await api.getContent(id);\n\n if (!content) {\n return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);\n }\n\n return c.json(content);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch content'), 500);\n }\n });\n\n // GET /content/:id/:locale - Get specific locale only\n app.get('/content/:id/:locale', async (c) => {\n const id = c.req.param('id');\n const locale = c.req.param('locale');\n\n try {\n const content = await api.getLocalized(id, locale);\n\n if (!content) {\n return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);\n }\n\n // Set ETag header\n c.header('ETag', content.localized.etag);\n\n return c.json(content);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch localized content'), 500);\n }\n });\n\n // POST /content - Create new content\n app.post('/content', async (c) => {\n try {\n const data = await c.req.json();\n const result = await api.createContent(data);\n\n if (!result.success) {\n if (result.reason === 'already_exists') {\n return c.json(result, 409);\n }\n if (result.reason === 'pathname_taken') {\n return c.json(result, 409);\n }\n if (result.reason === 'metadata_too_large') {\n return c.json(result, 400);\n }\n return c.json(result, 500);\n }\n\n return c.json(result, 201);\n } catch (error) {\n console.error('[Content API] Failed to create content:', error);\n return c.json(\n {\n success: false,\n reason: 'write_error',\n error: error instanceof Error ? error.message : 'Unknown error',\n },\n 500,\n );\n }\n });\n\n // PUT /content/:id - Update content (full update)\n app.put('/content/:id', async (c) => {\n const id = c.req.param('id');\n const locale = c.req.query('locale');\n const etag = c.req.query('etag') || '';\n\n if (!locale) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'locale query parameter is required', { field: 'locale' }),\n 400,\n );\n }\n\n try {\n const data = await c.req.json();\n const result = await api.updateLocalized({ id, locale, data, etag });\n\n if (!result.success) {\n if (result.reason === 'stale_write') {\n return c.json(\n errorResponse(ErrorCodes.STALE_WRITE, 'Content has been modified since you last loaded it', {\n currentEtag: result.currentEtag,\n }),\n 412,\n );\n }\n if (result.reason === 'not_found') {\n return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);\n }\n return c.json(result, 500);\n }\n\n // Set ETag header\n c.header('ETag', result.etag);\n\n return c.json(result);\n } catch (error) {\n console.error('[Content API] Failed to update content:', error);\n return c.json(\n {\n success: false,\n reason: 'write_error',\n error: error instanceof Error ? error.message : 'Unknown error',\n },\n 500,\n );\n }\n });\n\n // PATCH /content/:id - Partial update\n app.patch('/content/:id', async (c) => {\n const id = c.req.param('id');\n const locale = c.req.query('locale');\n const etag = c.req.query('etag') || '';\n\n if (!locale) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'locale query parameter is required', { field: 'locale' }),\n 400,\n );\n }\n\n try {\n const data = await c.req.json();\n const result = await api.updateLocalized({ id, locale, data, etag });\n\n if (!result.success) {\n if (result.reason === 'stale_write') {\n return c.json(\n errorResponse(ErrorCodes.STALE_WRITE, 'Content has been modified since you last loaded it', {\n currentEtag: result.currentEtag,\n }),\n 412,\n );\n }\n if (result.reason === 'not_found') {\n return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);\n }\n return c.json(result, 500);\n }\n\n // Set ETag header\n c.header('ETag', result.etag);\n\n return c.json(result);\n } catch (error) {\n console.error('[Content API] Failed to patch content:', error);\n return c.json(\n {\n success: false,\n reason: 'write_error',\n error: error instanceof Error ? error.message : 'Unknown error',\n },\n 500,\n );\n }\n });\n\n // DELETE /content/:id - Delete content (entire entry or specific locale)\n app.delete('/content/:id', async (c) => {\n const id = c.req.param('id');\n const locale = c.req.query('locale');\n const ifMatch = c.req.header('If-Match') || '';\n\n try {\n let result;\n\n if (locale) {\n // Delete specific locale\n result = await api.deleteLocalized({ id, locale, etag: ifMatch });\n } else {\n // Delete entire content entry\n result = await api.deleteContent(id, ifMatch);\n }\n\n if (!result.success) {\n if (result.reason === 'not_found') {\n return c.json(\n {\n success: false,\n error: 'Content not found',\n },\n 404,\n );\n }\n if (result.reason === 'stale_write') {\n return c.json(\n {\n success: false,\n reason: result.reason,\n currentEtag: result.currentEtag,\n message: 'Content has been modified',\n },\n 412,\n );\n }\n return c.json(result, 500);\n }\n\n return c.json({ success: true });\n } catch (error) {\n console.error('[Content API] Failed to delete content:', error);\n return c.json(\n {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n },\n 500,\n );\n }\n });\n\n // ===== Data Routes =====\n // NOTE: These routes MUST come before /:site/* routes to avoid being captured by them\n\n // GET /data/collections - List all data collections (must be before /data/:name)\n app.get('/data/collections', async (c) => {\n try {\n const collections = api.data.collections;\n return c.json({\n collections: Array.from(collections).sort(),\n });\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list data collections'),\n 500,\n );\n }\n });\n\n // GET /data/name-available - Check if data name is available\n app.get('/data/name-available', async (c) => {\n const name = c.req.query('name');\n const collection = c.req.query('collection');\n const excludeId = c.req.query('excludeId');\n\n if (!name) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'name query parameter is required', { field: 'name' }),\n 400,\n );\n }\n\n if (!collection) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'collection query parameter is required', {\n field: 'collection',\n }),\n 400,\n );\n }\n\n try {\n const available = api.data.isNameAvailable(collection, name, excludeId);\n if (available) {\n return c.json({ available: true });\n }\n\n const existing = api.data.getByName(collection, name);\n return c.json({\n available: false,\n existingId: existing?.id,\n });\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check data name availability'),\n 500,\n );\n }\n });\n\n // GET /data - List data entries\n app.get('/data', async (c) => {\n const collection = c.req.query('collection');\n const locale = c.req.query('locale');\n\n try {\n const filters: GlobalFilters = { kind: 'data' };\n if (collection) filters.collection = collection;\n if (locale) filters.locales = [locale];\n\n const items = Array.from(api.listAllContent(filters));\n return c.json({ items, total: items.length });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list data entries'), 500);\n }\n });\n\n // GET /data/:name - Get data entry by name\n app.get('/data/:name', async (c) => {\n const name = c.req.param('name');\n const collection = c.req.query('collection');\n const locale = c.req.query('locale');\n\n if (!collection) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'collection query parameter is required', {\n field: 'collection',\n }),\n 400,\n );\n }\n\n try {\n const dataEntry = api.data.getByName(collection, name, locale);\n\n if (!dataEntry) {\n return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Data entry not found', { name, collection }), 404);\n }\n\n // If locale specified and provided, filter the response\n if (locale && dataEntry.locales[locale]) {\n return c.json({\n ...dataEntry,\n locales: { [locale]: dataEntry.locales[locale] },\n });\n }\n\n return c.json(dataEntry);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch data entry'), 500);\n }\n });\n\n // ===== Asset Routes =====\n // Must be registered BEFORE /:site routes to avoid route conflicts (/:site would match \"assets\")\n\n if (options?.assetsPath) {\n const assetOps = new AssetOperations({\n assetsPath: options.assetsPath,\n contentRoot: options.contentRoot,\n ...options.assetConfig,\n });\n\n // POST /assets/move — move assets between folders\n app.post('/assets/move', async (c) => {\n try {\n const { filenames, sourceFolder, targetFolder } = await c.req.json<{\n filenames: string[];\n sourceFolder: string;\n targetFolder: string;\n }>();\n\n if (!Array.isArray(filenames)) {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'filenames must be an array'), 400);\n }\n if (typeof sourceFolder !== 'string') {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'sourceFolder is required'), 400);\n }\n if (typeof targetFolder !== 'string') {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'targetFolder is required'), 400);\n }\n\n const result = await assetOps.moveAssets(filenames, sourceFolder, targetFolder);\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);\n }\n\n return c.json(result);\n } catch (error) {\n if (error instanceof Error && error.message === 'Path traversal detected') {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid folder path'), 400);\n }\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to move assets'), 500);\n }\n });\n\n // POST /assets/upload — multipart form data upload\n app.post('/assets/upload', async (c) => {\n try {\n const body = await c.req.parseBody();\n const file = body.file;\n if (!(file instanceof File)) {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'No file provided in \"file\" field'), 400);\n }\n\n const alt = typeof body.alt === 'string' ? body.alt : undefined;\n const uploadedBy = typeof body.uploadedBy === 'string' ? body.uploadedBy : undefined;\n const width = typeof body.width === 'string' ? Number.parseInt(body.width, 10) : undefined;\n const height = typeof body.height === 'string' ? Number.parseInt(body.height, 10) : undefined;\n const folder = typeof body.folder === 'string' ? body.folder : undefined;\n\n const result = await assetOps.upload(file, { alt, uploadedBy, width, height, folder });\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.ASSET_UPLOAD_FAILED, result.error), 400);\n }\n\n return c.json(result.asset, 201);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.ASSET_UPLOAD_FAILED, 'Upload failed'), 500);\n }\n });\n\n // POST /assets/import-url — import image from URL\n app.post('/assets/import-url', async (c) => {\n try {\n const { url, alt, uploadedBy, folder } = await c.req.json<{\n url: string;\n alt?: string;\n uploadedBy?: string;\n folder?: string;\n }>();\n\n if (!url) {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'url is required'), 400);\n }\n\n const result = await assetOps.importFromUrl(url, { alt, uploadedBy, folder });\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.ASSET_UPLOAD_FAILED, result.error), 400);\n }\n\n return c.json(result.asset, 201);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.ASSET_UPLOAD_FAILED, 'URL import failed'), 500);\n }\n });\n\n // GET /assets — list all assets\n app.get('/assets', async (c) => {\n try {\n const assets = await assetOps.list();\n return c.json({ assets });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list assets'), 500);\n }\n });\n\n // GET /assets/folders — list assets and subfolders within a folder\n app.get('/assets/folders', async (c) => {\n try {\n const path = c.req.query('path') || '/';\n const result = await assetOps.listFolder(path);\n return c.json(result);\n } catch (error) {\n if (error instanceof Error && error.message === 'Path traversal detected') {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid folder path'), 400);\n }\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list folder'), 500);\n }\n });\n\n // POST /assets/folders — create a folder\n app.post('/assets/folders', async (c) => {\n try {\n const { path } = await c.req.json<{ path: string }>();\n\n if (!path) {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'path is required'), 400);\n }\n\n const result = await assetOps.createFolder(path);\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);\n }\n\n return c.json({ success: true }, 201);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to create folder'), 500);\n }\n });\n\n // GET /assets/folder-tree — get complete folder hierarchy with asset counts\n app.get('/assets/folder-tree', async (c) => {\n try {\n const tree = await assetOps.getFolderTree();\n return c.json({ tree });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get folder tree'), 500);\n }\n });\n\n // GET /assets/:filename/usage — get asset usage information\n app.get('/assets/:filename/usage', async (c) => {\n try {\n const filename = c.req.param('filename');\n const usage = await assetOps.getUsage(filename);\n return c.json({ usage });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get asset usage'), 500);\n }\n });\n\n // GET /assets/serve/:path{.+} — serve actual asset file (supports subfolders)\n app.get('/assets/serve/:path{.+}', async (c) => {\n try {\n const relativePath = c.req.param('path');\n // Split into folder and filename: 'images/tasks.png' → folder='/images', filename='tasks.png'\n const lastSlash = relativePath.lastIndexOf('/');\n const folder = lastSlash > 0 ? `/${relativePath.slice(0, lastSlash)}` : '/';\n const filename = lastSlash > 0 ? relativePath.slice(lastSlash + 1) : relativePath;\n const result = await assetOps.readAssetFile(filename, folder);\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);\n }\n\n // Set caching headers (1 year for immutable hashed filenames)\n c.header('Content-Type', result.mimeType);\n c.header('Cache-Control', 'public, max-age=31536000, immutable');\n\n return c.body(result.buffer as unknown as ArrayBuffer);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to serve asset'), 500);\n }\n });\n\n // GET /assets/:filename — get single asset metadata\n app.get('/assets/:filename', async (c) => {\n try {\n const filename = c.req.param('filename');\n const asset = await assetOps.getAsset(filename);\n\n if (!asset) {\n return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, 'Asset not found'), 404);\n }\n\n return c.json(asset);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get asset'), 500);\n }\n });\n\n // PATCH /assets/:filename — update asset metadata\n app.patch('/assets/:filename', async (c) => {\n try {\n const filename = c.req.param('filename');\n const { alt, tags } = await c.req.json<{ alt?: string; tags?: string[] }>();\n\n const result = await assetOps.updateMetadata(filename, { alt, tags });\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);\n }\n\n return c.json(result.asset);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to update asset'), 500);\n }\n });\n\n // DELETE /assets/:filename — delete asset\n app.delete('/assets/:filename', async (c) => {\n try {\n const filename = c.req.param('filename');\n const result = await assetOps.delete(filename);\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);\n }\n\n return c.json({ success: true });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to delete asset'), 500);\n }\n });\n }\n\n // ===== Site Routes =====\n // These use /:site parameter which matches any path segment\n\n // GET /:site/collections - Get collections for a site\n app.get('/:site/collections', async (c) => {\n const site = c.req.param('site');\n\n try {\n if (site === 'blocks') {\n // Use the efficient collections getter for blocks\n const collections = Array.from(api.blocks.collections).sort();\n return c.json({ collections });\n }\n // Use the efficient collections getter for sites\n const siteObj = api.getSite(site);\n if (!siteObj) {\n return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);\n }\n const collections = Array.from(siteObj.collections).sort();\n return c.json({ collections });\n } catch (error) {\n return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);\n }\n });\n\n // GET /:site/pages - Get pages for a site (not valid for blocks)\n app.get('/:site/pages', async (c) => {\n const site = c.req.param('site');\n const locale = c.req.query('locale');\n\n try {\n if (site === 'blocks') {\n return c.json(\n errorResponse(\n ErrorCodes.INVALID_REQUEST,\n 'Blocks do not have pages. Use /content?kind=block to list blocks.',\n ),\n 400,\n );\n }\n\n const siteObj = api.getSite(site);\n if (!siteObj) {\n return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);\n }\n\n // Use listContent with locales filter\n const items = Array.from(siteObj.listContent(locale ? { locales: [locale] } : {}));\n const result = { items, total: items.length };\n return c.json(result);\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, `Failed to list pages for site '${site}'`, {\n site,\n }),\n 500,\n );\n }\n });\n\n // GET /:site/pathname-available - Check if pathname is available\n app.get('/:site/pathname-available', async (c) => {\n const site = c.req.param('site');\n const pathname = c.req.query('pathname');\n const locale = c.req.query('locale') || 'en';\n const excludeId = c.req.query('excludeId');\n\n if (!pathname) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'pathname query parameter is required', { field: 'pathname' }),\n 400,\n );\n }\n\n try {\n if (site === 'blocks') {\n return c.json(\n errorResponse(\n ErrorCodes.INVALID_REQUEST,\n 'Blocks do not have pathnames. This endpoint is only for page content.',\n ),\n 400,\n );\n }\n\n // Use the optimized pathname index via site.isPathnameAvailable\n const siteObj = api.getSite(site);\n if (!siteObj) {\n return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);\n }\n const available = siteObj.isPathnameAvailable(pathname, locale, excludeId);\n\n if (available) {\n return c.json({ available: true });\n }\n\n // Get the conflicting content ID if pathname is taken\n const existingId = siteObj.getPathnameConflict(pathname, locale, excludeId);\n\n return c.json({\n available: false,\n existingId,\n });\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check pathname availability'),\n 500,\n );\n }\n });\n\n // GET /blocks - Shorthand for all blocks\n app.get('/blocks', async (c) => {\n const collection = c.req.query('collection');\n const locale = c.req.query('locale');\n\n try {\n const filters: any = { kind: 'block' };\n if (collection) filters.collection = collection;\n if (locale) filters.locales = [locale];\n\n const items = Array.from(api.listAllContent(filters));\n return c.json({ items, total: items.length });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list blocks'), 500);\n }\n });\n\n // GET /blocks/name-available - Check if block name is available\n app.get('/blocks/name-available', async (c) => {\n const name = c.req.query('name');\n const collection = c.req.query('collection') || 'components';\n const locale = c.req.query('locale') || 'en';\n const excludeId = c.req.query('excludeId');\n\n if (!name) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'name query parameter is required', { field: 'name' }),\n 400,\n );\n }\n\n try {\n // Check block name availability through listing\n const existing = Array.from(\n api.listAllContent({\n kind: 'block',\n collection: collection,\n locales: [locale],\n }),\n );\n\n let taken: ContentManifest | undefined;\n for (const item of existing) {\n for (const localeVersion of localesOf(item)) {\n if (localeVersion.name === name) {\n taken = item;\n break;\n }\n }\n }\n\n // If no existing block, name is available\n if (!taken) {\n return c.json({ available: true });\n }\n\n // If existing block has same ID as excludeId, name is available\n // (useful when editing existing block)\n if (excludeId && taken.id === excludeId) {\n return c.json({ available: true });\n }\n\n // Otherwise, name is taken\n return c.json({\n available: false,\n existingId: taken.id,\n });\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check block name availability'),\n 500,\n );\n }\n });\n\n // GET /blocks/:name - Get block by name\n app.get('/blocks/:name', async (c) => {\n const name = c.req.param('name');\n const collection = c.req.query('collection') || 'components';\n const locale = c.req.query('locale');\n\n try {\n const block = api.blocks.getByName(collection, name, locale);\n\n if (!block) {\n return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Block not found', { name, collection }), 404);\n }\n\n // If locale specified and provided, filter the response\n if (locale && block.locales[locale]) {\n return c.json({\n ...block,\n locales: { [locale]: block.locales[locale] },\n });\n }\n\n return c.json(block);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch block'), 500);\n }\n });\n\n // POST /:site/move - Move page to new pathname\n app.post('/:site/move', async (c) => {\n const site = c.req.param('site');\n\n try {\n const { id, pathname, locale, etag } = await c.req.json();\n\n if (!id || !pathname || !locale || !etag) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'id, pathname, locale, and etag are required'),\n 400,\n );\n }\n\n const siteObj = api.getSite(site);\n if (!siteObj) {\n return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);\n }\n\n // First check if the pathname is available\n const existing = siteObj.getByPathname(pathname, locale);\n if (existing && existing.id !== id) {\n return c.json(\n {\n moved: false,\n reason: 'already_exists',\n ...errorResponse(ErrorCodes.PATHNAME_TAKEN, 'Pathname already taken', { existingId: existing.id }),\n },\n 409,\n );\n }\n\n // Get current content to track previous pathname\n const current = await api.getLocalized(id, locale);\n if (!current) {\n return c.json(\n { moved: false, ...errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }) },\n 404,\n );\n }\n\n const previousPathname = current.localized.pathname;\n\n // Update with new pathname using updateLocalized for etag validation\n const updateResult = await api.updateLocalized({\n id,\n locale,\n data: {\n pathname: pathname,\n meta: current.localized.meta,\n },\n etag: etag,\n });\n\n if (!updateResult.success) {\n if (updateResult.reason === 'stale_write') {\n return c.json(\n {\n moved: false,\n reason: 'stale_write',\n currentEtag: updateResult.currentEtag,\n message: 'Content has been modified',\n },\n 412,\n );\n }\n if (updateResult.reason === 'not_found') {\n return c.json(\n { moved: false, ...errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }) },\n 404,\n );\n }\n return c.json({ moved: false, ...errorResponse(ErrorCodes.WRITE_ERROR, 'Update failed') }, 500);\n }\n\n return c.json({\n moved: true,\n previousPathname: previousPathname,\n etag: updateResult.etag,\n });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to move page'), 500);\n }\n });\n\n // GET /untranslated/:locale - Find untranslated content\n app.get('/untranslated/:targetLocale', async (c) => {\n const targetLocale = c.req.param('targetLocale');\n const excludeSites = c.req\n .query('excludeSites')\n ?.split(',')\n .map((s) => s.trim())\n .filter((s) => s);\n const includeUnpublished = c.req.query('includeUnpublished') === 'true';\n\n try {\n const options: FindOptions = {\n ...(excludeSites?.length && { excludeSites }),\n ...(includeUnpublished && { includeUnpublished }),\n };\n\n const items = Array.from(api.findUntranslatedContent(targetLocale, options));\n return c.json({ items, total: items.length });\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to find untranslated content'),\n 500,\n );\n }\n });\n\n // GET /sites - Get sites configuration\n app.get('/sites', async (c) => {\n try {\n const config = api.sitesConfig;\n return c.json(config);\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch sites configuration'),\n 500,\n );\n }\n });\n\n // POST /content/batch - Batch update operations\n app.post('/content/batch', async (c) => {\n try {\n const { operations } = await c.req.json();\n const result = await api.batchUpdate(operations);\n\n if (!result.success) {\n return c.json(result, 207); // Multi-status\n }\n\n return c.json(result);\n } catch (error) {\n console.error('[Content API] Failed to batch update:', error);\n return c.json(\n {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n },\n 500,\n );\n }\n });\n\n // ===== Git Routes =====\n\n /**\n * Get git config from environment variables.\n * Required: CONTENT_PATH\n * Optional: GIT_BRANCH (defaults to current checked-out branch)\n */\n function getGitConfig(): GitConfig {\n const contentPath = process.env.CONTENT_PATH;\n if (!contentPath) {\n throw new Error('CONTENT_PATH environment variable is required for git operations');\n }\n return {\n contentPath,\n branch: process.env.GIT_BRANCH,\n };\n }\n\n // GET /git/status - Get git repository status\n app.get('/git/status', async (c) => {\n try {\n const config = getGitConfig();\n const gitOps = createGitOperations(config);\n const status = await gitOps.getStatus();\n\n if (!status.isRepo) {\n return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, 'Repository not accessible'), 400);\n }\n\n return c.json(status);\n } catch (error) {\n if (error instanceof Error && error.message.includes('CONTENT_PATH')) {\n return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);\n }\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_STATUS_FAILED, 'Failed to get git status'), 500);\n }\n });\n\n // POST /git/commit - Commit all changes\n app.post('/git/commit', async (c) => {\n try {\n const body = await c.req.json<{ message?: string }>().catch(() => ({}) as { message?: string });\n\n // Auto-generate message if not provided\n const date = new Date();\n const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n const defaultMessage = `CMS changes - ${monthNames[date.getMonth()]} ${date.getDate()}`;\n const message = body.message || defaultMessage;\n\n // Extract user email from CF Access header for commit attribution\n const userEmail = c.req.header('X-CF-User-Email');\n const author: GitAuthor | undefined = userEmail ? { name: userEmail.split('@')[0], email: userEmail } : undefined;\n\n const config = getGitConfig();\n const gitOps = createGitOperations(config);\n const result = await gitOps.commitAll(message, author);\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.GIT_COMMIT_FAILED, result.error || 'Commit failed'), 500);\n }\n\n return c.json(result);\n } catch (error) {\n if (error instanceof Error && error.message.includes('CONTENT_PATH')) {\n return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);\n }\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_COMMIT_FAILED, 'Failed to commit changes'), 500);\n }\n });\n\n // POST /git/push - Push to origin\n app.post('/git/push', async (c) => {\n try {\n const config = getGitConfig();\n const gitOps = createGitOperations(config);\n const result = await gitOps.pushOrigin();\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.GIT_PUSH_FAILED, result.error || 'Push failed'), 500);\n }\n\n return c.json(result);\n } catch (error) {\n if (error instanceof Error && error.message.includes('CONTENT_PATH')) {\n return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);\n }\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PUSH_FAILED, 'Failed to push to origin'), 500);\n }\n });\n\n // POST /git/pull - Pull from origin with autostash + rebase\n app.post('/git/pull', async (c) => {\n try {\n const config = getGitConfig();\n const gitOps = createGitOperations(config);\n const result = await gitOps.pull();\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.GIT_PULL_FAILED, result.error || 'Pull failed'), 500);\n }\n\n return c.json(result);\n } catch (error) {\n if (error instanceof Error && error.message.includes('CONTENT_PATH')) {\n return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);\n }\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PULL_FAILED, 'Failed to pull from origin'), 500);\n }\n });\n\n return app;\n}\n\n/**\n * Create middleware for backwards compatibility with existing code\n * This wraps the Hono app to work with Node.js IncomingMessage/ServerResponse\n */\nexport function createContentMiddleware(contentApi: ContentAPI) {\n const app = createContentAPIRouter(contentApi);\n\n // Convert Hono app to Node.js middleware\n return async (req: any, res: any, next: () => void) => {\n const url = new URL(req.url!, `http://${req.headers.host}`);\n\n // Only handle API routes (base path depends on context)\n const basePath = url.pathname.startsWith('/__cms/api') ? '/__cms/api' : '/__conloca/api';\n if (!url.pathname.startsWith(basePath)) {\n return next();\n }\n\n // Strip the base path to match Hono routes\n const path = url.pathname.replace(basePath, '');\n\n // Create a Request object for Hono\n const request = new Request(`http://localhost${path}${url.search}`, {\n method: req.method,\n headers: req.headers,\n body: ['GET', 'HEAD'].includes(req.method!) ? undefined : await readBody(req),\n });\n\n // Handle with Hono\n const response = await app.fetch(request);\n\n // Copy response headers\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n // Set status code\n res.statusCode = response.status;\n\n // Send response body\n const body = await response.text();\n res.end(body);\n };\n}\n\n// Helper to read request body\nfunction readBody(req: any): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Uint8Array[] = [];\n req.on('data', (chunk: Buffer) => chunks.push(new Uint8Array(chunk)));\n req.on('end', () => {\n const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.length;\n }\n resolve(Buffer.from(combined).toString());\n });\n req.on('error', reject);\n });\n}\n","import { getRequestListener } from '@hono/node-server';\nimport type { Plugin, ViteDevServer } from 'vite';\nimport { createContentAPI, createContentWatchHandlers } from './content-watcher';\nimport type { FileSystemContentAPI } from './filesystem-content-api';\nimport { createContentAPIRouter } from './middleware';\n\nexport interface ConlocaContentOptions {\n contentRoot: string;\n canvasDir?: string;\n basePath?: string;\n}\n\n/**\n * Vite plugin wrapper for content middleware\n * This follows the spec in 04-cms-api.md and 09-conloca-content-editing.md\n */\nexport function conlocaContent(options: ConlocaContentOptions): Plugin {\n let contentApi: FileSystemContentAPI;\n\n const basePath = options.basePath || '/__conloca/api/content';\n\n return {\n name: 'vite-plugin-conloca-content',\n\n async configureServer(server: ViteDevServer) {\n // Initialize content API\n contentApi = await createContentAPI(options);\n\n // Set up content file watcher\n server.watcher.add(options.contentRoot);\n\n // Create Hono app with routes\n const app = createContentAPIRouter(contentApi);\n\n // Add to Vite as middleware using @hono/node-server\n server.middlewares.use(basePath, getRequestListener(app.fetch));\n\n // Set up HMR for content changes using extracted handlers\n const handlers = createContentWatchHandlers(contentApi, options, server.ws);\n server.watcher.on('change', handlers.onChange);\n server.watcher.on('add', handlers.onAdd);\n server.watcher.on('unlink', handlers.onUnlink);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAeA,MAAM,oBAAoB;AAE1B,IAAa,gBAAb,MAA2B;CACzB,AAAQ;CAER,YAAY,YAAoB;AAC9B,OAAK,eAAe,KAAK,YAAY,kBAAkB;;CAGzD,MAAM,OAAmC;AACvC,MAAI;GACF,MAAM,MAAM,MAAM,SAAS,KAAK,cAAc,QAAQ;AACtD,UAAO,KAAK,MAAM,IAAI;UAChB;AACN,UAAO,EAAE;;;CAIb,MAAM,MAAM,MAAwC;AAClD,QAAM,UAAU,KAAK,cAAc,KAAK,UAAU,MAAM,MAAM,EAAE,EAAE,QAAQ;;CAG5E,MAAM,IAAI,cAAsB,MAAwC;EACtE,MAAM,WAAW,MAAM,KAAK,MAAM;AAClC,WAAS,gBAAgB;AACzB,QAAM,KAAK,MAAM,SAAS;;CAG5B,MAAM,OAAO,cAAwC;EACnD,MAAM,WAAW,MAAM,KAAK,MAAM;AAClC,MAAI,EAAE,gBAAgB,UAAW,QAAO;AACxC,SAAO,SAAS;AAChB,QAAM,KAAK,MAAM,SAAS;AAC1B,SAAO;;CAGT,MAAM,IAAI,cAA8D;AAEtE,UADiB,MAAM,KAAK,MAAM,EAClB;;;;;;CAOlB,MAAM,cAAc,UAA0F;EAC5G,MAAM,WAAW,MAAM,KAAK,MAAM;AAClC,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,SAAS,CACjD,KAAI,QAAQ,YAAY,IAAI,SAAS,IAAI,WAAW,CAClD,QAAO;GAAE,cAAc;GAAK,MAAM;GAAO;;;;;;ACTjD,SAAS,cAAc,KAAa,MAA2C;AAC7E,QAAO,IAAI,SAAS,gBAAgB,WAAW;EAC7C,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AQ,YAAY;GAGvC,MAAM,MAAM,uBAAuB,WAAW;AAG9C,UAAO,YAAY,IAAI,UAAU,mBAAmB,IAAI,MAAM,CAAC;GAG/D,MAAM,WAAW,2BAA2B,YAAY,SAAS,OAAO,GAAG;AAC3E,UAAO,QAAQ,GAAG,UAAU,SAAS,SAAS;AAC9C,UAAO,QAAQ,GAAG,OAAO,SAAS,MAAM;AACxC,UAAO,QAAQ,GAAG,UAAU,SAAS,SAAS;;EAEjD"}
1
+ {"version":3,"file":"node.mjs","names":["process","MIME_MAP: Record<string, string>","stats: Stats","manifestEntry: ManifestEntryData","assets: AssetEntry[]","entries: Dirent[]","response: Response","fullPath: string","merged: ManifestEntryData","usages: AssetUsage[]","files: string[]","sourcePath: string","targetPath: string","result: FolderTreeNode[]","children","join","readFile","error: any","mkdir","dirname","writeFile","rename","unlink","generator: Generator<ContentManifest>","newManifest: ContentManifest","locales: string[]","oldPathname: string | undefined","addedPreviousPathnames: string[]","newManifest: ContentManifest","locale","sitesConfig: SitesConfig","api: ContentAPI","dataIndex: DataIndex","downstream: { update(data: Uint8Array): void }","textDecoder","partialContent","data","contentStartPos","etagResult","resolve","join","sitesConfig: SitesConfig","handle: FileHandle | undefined","site: string | undefined","collection: string","name: string | undefined","pathname: string | undefined","parsedData: ParsedMetadata","kind: 'block' | 'page' | 'data'","filename","dirname","content","localeVersion: LocaleVersion","manifest: ContentManifest","content: ContentData | undefined","data: VXJSONFile","vxjsonData: VXJSONFile","files: string[]","locale","locales: Record<string, LocaleVersion & ContentProp>","result: LocaleFileData","result","repairedData: VXJSONFile","contentCache: Record<string, ContentData>","meta: ContentMeta","fileData: VXJSONFile","etag: string","modified: string","newLocaleVersion: LocaleVersion","updatedFile: VXJSONFile","newEtag: string","updatedLocaleVersion: LocaleVersion","matchingLocale: LocaleVersion | undefined","filesToIndex: string[]","updated: LocalizedManifest[]","deleted: Array<{ id: string; locale: string; kind: 'page' | 'block' | 'data' }>","parsed","manifest: ContentManifest | null","currentManifest: ContentManifest | null","currentEtag: string","localizedManifest: LocalizedManifest","result: ReindexResult","validationResults: Array<{\n op: UpdateLocaleInput;\n manifest: ContentManifest;\n localeVersion: LocaleVersion;\n current?: LocaleFileData;\n }>","results: BatchOperationResult[]","resolve","contentEntry: ContentEntry","contentCache: Record<string, ContentData>","fileData: VXJSONFile","buffer: Uint8Array","etag: string","manifest: ContentManifest","newEtag: string","updatedManifest: ContentManifest","results: BatchResult","contentCache: Record<string, ContentData | null>","manifestLocale: LocaleVersion","calculatedEtag: string","contentType: 'application/json' | 'text/mdx'","c","filters: any","filters: GlobalFilters","collections","taken: ContentManifest | undefined","options: FindOptions","options","author: GitAuthor | undefined","chunks: Uint8Array[]","contentApi: FileSystemContentAPI"],"sources":["../src/asset-manifest.ts","../src/git-operations.ts","../src/asset-operations.ts","../src/cf-access.ts","../src/component-registry.ts","../src/content-filters.ts","../src/base-content-index.ts","../src/block-index.ts","../src/data-index.ts","../src/site-index.ts","../src/content-index.ts","../src/data.ts","../src/json-whitespace-view.ts","../src/url-safe-base64.ts","../src/etag-utils.ts","../src/vxjson.ts","../src/filesystem-content-api.ts","../src/content-watcher.ts","../src/in-memory-content-api.ts","../src/middleware.ts","../src/vite-plugin.ts"],"sourcesContent":["import { readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nimport type { AssetManifestData, ManifestEntryData } from './asset-types';\n\n// Re-export types for backwards compatibility\nexport type {\n AssetEntry,\n AssetManifestData,\n AssetUsage,\n FolderListing,\n FolderTreeNode,\n ManifestEntryData,\n} from './asset-types';\n\nconst MANIFEST_FILENAME = '.asset-manifest.json';\n\nexport class AssetManifest {\n private manifestPath: string;\n\n constructor(assetsPath: string) {\n this.manifestPath = join(assetsPath, MANIFEST_FILENAME);\n }\n\n async read(): Promise<AssetManifestData> {\n try {\n const raw = await readFile(this.manifestPath, 'utf-8');\n return JSON.parse(raw) as AssetManifestData;\n } catch {\n return {};\n }\n }\n\n async write(data: AssetManifestData): Promise<void> {\n await writeFile(this.manifestPath, JSON.stringify(data, null, 2), 'utf-8');\n }\n\n async add(relativePath: string, data: ManifestEntryData): Promise<void> {\n const manifest = await this.read();\n manifest[relativePath] = data;\n await this.write(manifest);\n }\n\n async remove(relativePath: string): Promise<boolean> {\n const manifest = await this.read();\n if (!(relativePath in manifest)) return false;\n delete manifest[relativePath];\n await this.write(manifest);\n return true;\n }\n\n async get(relativePath: string): Promise<ManifestEntryData | undefined> {\n const manifest = await this.read();\n return manifest[relativePath];\n }\n\n /**\n * Backward compat helper: search manifest keys for entry ending with /filename or equal to filename\n * Useful during transition when only filename is known (not full relative path)\n */\n async getByFilename(filename: string): Promise<{ relativePath: string; data: ManifestEntryData } | undefined> {\n const manifest = await this.read();\n for (const [key, value] of Object.entries(manifest)) {\n if (key === filename || key.endsWith(`/${filename}`)) {\n return { relativePath: key, data: value };\n }\n }\n return undefined;\n }\n}\n","import { spawn } from 'node:child_process';\nimport { access, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\n\nexport interface GitStatus {\n isRepo: boolean;\n hasChanges: boolean;\n changedFiles: number;\n ahead: number;\n behind: number;\n branch: string;\n remoteConfigured?: boolean;\n}\n\nexport interface CommitResult {\n success: boolean;\n commit?: string;\n summary?: string;\n error?: string;\n}\n\nexport interface PushResult {\n success: boolean;\n error?: string;\n}\n\nexport interface PullResult {\n success: boolean;\n summary?: string;\n error?: string;\n}\n\nexport interface GitAuthor {\n name: string;\n email: string;\n}\n\nexport interface GitOperations {\n getStatus(): Promise<GitStatus>;\n commitAll(message: string, author?: GitAuthor): Promise<CommitResult>;\n pushOrigin(): Promise<PushResult>;\n pull(): Promise<PullResult>;\n}\n\nexport interface GitConfig {\n contentPath: string;\n branch?: string;\n}\n\ninterface GitCommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nfunction runGitCommand(cwd: string, args: string[]): Promise<GitCommandResult> {\n return new Promise((resolveCommand, reject) => {\n const process = spawn('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n\n process.stdout.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n process.stderr.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n process.on('error', reject);\n\n process.on('close', (exitCode) => {\n resolveCommand({\n exitCode: exitCode ?? 1,\n stdout: stdout.trim(),\n stderr: stderr.trim(),\n });\n });\n });\n}\n\n/**\n * Resolve the git repository root from a content path.\n * Uses `git rev-parse --show-toplevel` starting from the parent of the content directory.\n */\nasync function resolveRepoRoot(contentPath: string): Promise<string | null> {\n const contentRoot = resolve(contentPath);\n const startDir = dirname(contentRoot);\n const result = await runGitCommand(startDir, ['rev-parse', '--show-toplevel']);\n if (result.exitCode !== 0) {\n return null;\n }\n return result.stdout;\n}\n\n/**\n * Create git operations using local git CLI commands.\n * Requires git binary available on PATH and CONTENT_PATH inside a git repository.\n */\nexport function createGitOperations(config: GitConfig): GitOperations {\n const { contentPath, branch } = config;\n\n return {\n async getStatus(): Promise<GitStatus> {\n try {\n const repoRoot = await resolveRepoRoot(contentPath);\n if (!repoRoot) {\n return { isRepo: false, hasChanges: false, changedFiles: 0, ahead: 0, behind: 0, branch: 'unknown' };\n }\n\n // Get current branch\n const branchResult = await runGitCommand(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);\n const currentBranch = branchResult.exitCode === 0 ? branchResult.stdout : 'unknown';\n\n // Get changed files count\n const statusResult = await runGitCommand(repoRoot, ['status', '--porcelain']);\n const changedLines = statusResult.stdout ? statusResult.stdout.split('\\n').filter((l) => l.trim()) : [];\n const changedFiles = changedLines.length;\n const hasChanges = changedFiles > 0;\n\n // Check if remote origin is configured\n const remoteResult = await runGitCommand(repoRoot, ['remote', 'get-url', 'origin']);\n const remoteConfigured = remoteResult.exitCode === 0;\n\n // Get ahead/behind counts\n let ahead = 0;\n let behind = 0;\n if (remoteConfigured) {\n const trackingBranch = branch || currentBranch;\n const revListResult = await runGitCommand(repoRoot, [\n 'rev-list',\n '--left-right',\n '--count',\n `HEAD...origin/${trackingBranch}`,\n ]);\n if (revListResult.exitCode === 0 && revListResult.stdout) {\n const [a, b] = revListResult.stdout.split('\\t').map(Number);\n ahead = a || 0;\n behind = b || 0;\n }\n }\n\n return { isRepo: true, hasChanges, changedFiles, ahead, behind, branch: currentBranch, remoteConfigured };\n } catch {\n return { isRepo: false, hasChanges: false, changedFiles: 0, ahead: 0, behind: 0, branch: 'unknown' };\n }\n },\n\n async commitAll(message: string, author?: GitAuthor): Promise<CommitResult> {\n try {\n const repoRoot = await resolveRepoRoot(contentPath);\n if (!repoRoot) {\n return { success: false, error: 'Not a git repository' };\n }\n\n // Stage all changes\n const addResult = await runGitCommand(repoRoot, ['add', '-A']);\n if (addResult.exitCode !== 0) {\n return { success: false, error: addResult.stderr || 'Failed to stage changes' };\n }\n\n // Check if there's anything to commit after staging\n const diffResult = await runGitCommand(repoRoot, ['diff', '--cached', '--quiet']);\n if (diffResult.exitCode === 0) {\n return { success: false, error: 'No changes to commit' };\n }\n\n // Count staged files for summary\n const diffStatResult = await runGitCommand(repoRoot, ['diff', '--cached', '--numstat']);\n const fileCount = diffStatResult.stdout ? diffStatResult.stdout.split('\\n').filter((l) => l.trim()).length : 0;\n\n // Build commit command\n const commitArgs = ['commit', '-m', message];\n if (author) {\n commitArgs.push('--author', `${author.name} <${author.email}>`);\n }\n\n const commitResult = await runGitCommand(repoRoot, commitArgs);\n if (commitResult.exitCode !== 0) {\n return { success: false, error: commitResult.stderr || 'Commit failed' };\n }\n\n // Get the commit SHA\n const shaResult = await runGitCommand(repoRoot, ['rev-parse', 'HEAD']);\n const commitSha = shaResult.stdout || undefined;\n\n return {\n success: true,\n commit: commitSha,\n summary: `${fileCount} files committed`,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Commit failed',\n };\n }\n },\n\n async pushOrigin(): Promise<PushResult> {\n try {\n const repoRoot = await resolveRepoRoot(contentPath);\n if (!repoRoot) {\n return { success: false, error: 'Not a git repository' };\n }\n\n // Pre-check: verify remote is configured\n const remoteResult = await runGitCommand(repoRoot, ['remote', 'get-url', 'origin']);\n if (remoteResult.exitCode !== 0) {\n return {\n success: false,\n error: 'No git remote \"origin\" configured. Please configure a remote to enable push.',\n };\n }\n\n // Determine branch to push\n let targetBranch = branch;\n if (!targetBranch) {\n const branchResult = await runGitCommand(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);\n targetBranch = branchResult.stdout;\n }\n\n const pushResult = await runGitCommand(repoRoot, ['push', 'origin', targetBranch]);\n if (pushResult.exitCode !== 0) {\n const stderr = pushResult.stderr || '';\n if (stderr.includes('non-fast-forward') || stderr.includes('rejected')) {\n return {\n success: false,\n error: 'Push rejected: remote has changes. Pull first, then try pushing again.',\n };\n }\n if (stderr.includes('Could not resolve host')) {\n return {\n success: false,\n error: 'Cannot reach git remote. Check your network connection.',\n };\n }\n if (stderr.includes('Permission denied') || stderr.includes('Authentication failed')) {\n return {\n success: false,\n error: 'Git remote authentication failed. Check server SSH key or credential configuration.',\n };\n }\n return { success: false, error: stderr || 'Push failed' };\n }\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Push failed',\n };\n }\n },\n\n async pull(): Promise<PullResult> {\n try {\n const repoRoot = await resolveRepoRoot(contentPath);\n if (!repoRoot) {\n return { success: false, error: 'Not a git repository' };\n }\n\n // Determine branch for pull\n let targetBranch = branch;\n if (!targetBranch) {\n const branchResult = await runGitCommand(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);\n targetBranch = branchResult.stdout;\n }\n\n const pullResult = await runGitCommand(repoRoot, ['pull', '--autostash', '--rebase', 'origin', targetBranch]);\n\n if (pullResult.exitCode !== 0) {\n return {\n success: false,\n error: pullResult.stderr || pullResult.stdout || 'Pull failed',\n };\n }\n\n return {\n success: true,\n summary: pullResult.stdout || `Pulled latest changes from origin/${targetBranch}`,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Pull failed',\n };\n }\n },\n };\n}\n\nconst LFS_PATTERNS = [\n '*.jpg filter=lfs diff=lfs merge=lfs -text',\n '*.jpeg filter=lfs diff=lfs merge=lfs -text',\n '*.png filter=lfs diff=lfs merge=lfs -text',\n '*.gif filter=lfs diff=lfs merge=lfs -text',\n '*.svg filter=lfs diff=lfs merge=lfs -text',\n '*.webp filter=lfs diff=lfs merge=lfs -text',\n '*.avif filter=lfs diff=lfs merge=lfs -text',\n '*.ico filter=lfs diff=lfs merge=lfs -text',\n];\n\n/**\n * Ensure .gitattributes exists at contentRoot with LFS tracking patterns for web image extensions.\n * Creates the file if missing, or appends missing patterns if file exists.\n */\nexport async function setupGitLfsAttributes(contentRoot: string): Promise<void> {\n const gitattributesPath = join(contentRoot, '.gitattributes');\n let existing = '';\n\n try {\n await access(gitattributesPath);\n existing = await readFile(gitattributesPath, 'utf-8');\n } catch {\n // File doesn't exist — will create fresh\n }\n\n const missingPatterns = LFS_PATTERNS.filter((pattern) => !existing.includes(pattern));\n\n if (missingPatterns.length === 0) return;\n\n const newContent = existing\n ? `${existing.trimEnd()}\\n${missingPatterns.join('\\n')}\\n`\n : `${missingPatterns.join('\\n')}\\n`;\n\n await writeFile(gitattributesPath, newContent, 'utf-8');\n}\n","import { type Dirent, existsSync, type Stats } from 'node:fs';\nimport { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';\nimport { extname, join, parse, resolve } from 'node:path';\nimport { imageSize } from 'image-size';\nimport {\n type AssetEntry,\n AssetManifest,\n type AssetManifestData,\n type AssetUsage,\n type FolderListing,\n type FolderTreeNode,\n type ManifestEntryData,\n} from './asset-manifest';\nimport { setupGitLfsAttributes } from './git-operations';\n\nexport interface AssetConfig {\n assetsPath: string;\n maxFileSize?: number;\n acceptedFormats?: string[];\n /** Content root directory for usage tracking (scanning VXJSON files) */\n contentRoot?: string;\n}\n\nconst DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB\nconst DEFAULT_ACCEPTED_FORMATS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'svg', 'ico'];\n\nconst MIME_MAP: Record<string, string> = {\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n svg: 'image/svg+xml',\n ico: 'image/x-icon',\n};\n\n/** Recognized web image extensions for filesystem scanning */\nconst RECOGNIZED_IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'avif', 'ico']);\n\n/** System files to skip during filesystem scanning */\nconst SYSTEM_FILES = new Set(['.ds_store', 'thumbs.db', '.gitkeep', 'desktop.ini', '.asset-manifest.json']);\n\n/** Check if filename has a recognized web image extension */\nfunction isRecognizedImageExtension(filename: string): boolean {\n const ext = extname(filename).slice(1).toLowerCase();\n return RECOGNIZED_IMAGE_EXTENSIONS.has(ext);\n}\n\n/** Check if file is a system/hidden file that should be skipped */\nfunction isSystemFile(filename: string): boolean {\n return filename.startsWith('.') || SYSTEM_FILES.has(filename.toLowerCase());\n}\n\nexport class AssetOperations {\n private config: Required<Omit<AssetConfig, 'contentRoot'>> & Pick<AssetConfig, 'contentRoot'>;\n private manifest: AssetManifest;\n private dirEnsured = false;\n private lfsSetup = false;\n\n constructor(config: AssetConfig) {\n this.config = {\n assetsPath: config.assetsPath,\n maxFileSize: config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE,\n acceptedFormats: config.acceptedFormats ?? DEFAULT_ACCEPTED_FORMATS,\n contentRoot: config.contentRoot,\n };\n this.manifest = new AssetManifest(config.assetsPath);\n }\n\n private async ensureDir(subpath?: string): Promise<void> {\n const targetPath = subpath ? join(this.config.assetsPath, subpath) : this.config.assetsPath;\n if (!subpath && this.dirEnsured) return;\n await mkdir(targetPath, { recursive: true });\n if (!subpath) this.dirEnsured = true;\n }\n\n /**\n * Validate that a subpath is safe (no path traversal attacks)\n * Returns the resolved full path if valid, throws if invalid\n */\n private validateSubpath(subpath: string): string {\n // Normalize the path: remove leading/trailing slashes, resolve .. and .\n const normalizedSubpath = subpath.replace(/^\\/+|\\/+$/g, '') || '.';\n // Resolve both paths to absolute to ensure consistent comparison\n const assetsAbsolute = resolve(this.config.assetsPath);\n const fullPath = resolve(assetsAbsolute, normalizedSubpath);\n\n // Security check: ensure resolved path is within assetsPath\n if (!fullPath.startsWith(assetsAbsolute)) {\n throw new Error('Path traversal detected');\n }\n\n return fullPath;\n }\n\n /**\n * Resolve a unique filename by appending -1, -2, etc. if collision exists\n * @param originalName Original filename\n * @param folder Optional folder path (relative to assets root)\n */\n private resolveFilename(originalName: string, folder?: string): string {\n const { name, ext } = parse(originalName);\n // Sanitize: lowercase, replace spaces with dashes, remove non-alphanumeric except dash/dot\n const sanitized = name\n .toLowerCase()\n .replace(/\\s+/g, '-')\n .replace(/[^a-z0-9-]/g, '');\n const safeExt = ext.toLowerCase();\n\n // Determine base directory (assetsPath or assetsPath/folder)\n const baseDir =\n folder && folder !== '/'\n ? join(this.config.assetsPath, folder.replace(/^\\/+|\\/+$/g, ''))\n : this.config.assetsPath;\n\n let candidate = `${sanitized}${safeExt}`;\n let counter = 0;\n\n while (existsSync(join(baseDir, candidate))) {\n counter++;\n candidate = `${sanitized}-${counter}${safeExt}`;\n }\n\n return candidate;\n }\n\n private validateFormat(filename: string): boolean {\n const ext = extname(filename).slice(1).toLowerCase();\n return this.config.acceptedFormats.includes(ext);\n }\n\n private validateSize(size: number): boolean {\n return size <= this.config.maxFileSize;\n }\n\n /**\n * Get image dimensions from manifest cache or by reading file headers\n */\n private async getDimensions(\n filePath: string,\n manifestEntry?: ManifestEntryData,\n ): Promise<{ width?: number; height?: number; fromCache: boolean }> {\n // Check manifest cache first\n if (manifestEntry?.width && manifestEntry?.height) {\n return { width: manifestEntry.width, height: manifestEntry.height, fromCache: true };\n }\n\n // Read from file headers\n try {\n const buffer = await readFile(filePath);\n const result = imageSize(new Uint8Array(buffer));\n return { width: result.width, height: result.height, fromCache: false };\n } catch {\n // SVGs and some formats may fail - return undefined dimensions\n return { width: undefined, height: undefined, fromCache: false };\n }\n }\n\n /**\n * Build an AssetEntry from a directory entry, enriching with manifest metadata\n */\n private async buildAssetEntry(dirent: Dirent, folder: string, manifestData: AssetManifestData): Promise<AssetEntry> {\n // Compute relative path for manifest lookup\n const relativePath = folder === '/' ? dirent.name : `${folder.slice(1)}/${dirent.name}`;\n const manifestEntry = manifestData[relativePath];\n\n // Build full file path\n const fullPath = this.getAssetPath(dirent.name, folder);\n\n // Get file stats\n const stats: Stats = await stat(fullPath);\n\n // Get dimensions (from cache or file)\n const { width, height, fromCache } = await this.getDimensions(fullPath, manifestEntry);\n\n // Progressive caching: if dimensions were computed from file, cache them\n if (!fromCache && width && height) {\n this.manifest.add(relativePath, { ...manifestEntry, width, height }).catch(() => {});\n }\n\n // Derive mimeType from extension\n const ext = extname(dirent.name).slice(1).toLowerCase();\n const mimeType = MIME_MAP[ext] || `image/${ext}`;\n\n return {\n filename: dirent.name,\n originalName: manifestEntry?.originalName || dirent.name,\n mimeType,\n size: stats.size,\n width,\n height,\n alt: manifestEntry?.alt,\n uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),\n uploadedBy: manifestEntry?.uploadedBy,\n folder,\n tags: manifestEntry?.tags,\n };\n }\n\n async upload(\n file: File,\n metadata?: { alt?: string; uploadedBy?: string; width?: number; height?: number; folder?: string },\n ): Promise<{ success: true; asset: AssetEntry } | { success: false; error: string }> {\n if (!this.validateFormat(file.name)) {\n const allowed = this.config.acceptedFormats.join(', ');\n return { success: false, error: `Invalid format. Accepted: ${allowed}` };\n }\n\n if (!this.validateSize(file.size)) {\n const maxMB = Math.round(this.config.maxFileSize / (1024 * 1024));\n return { success: false, error: `File too large. Maximum: ${maxMB}MB` };\n }\n\n // Normalize folder path\n const folder = metadata?.folder && metadata.folder !== '/' ? '/' + metadata.folder.replace(/^\\/+|\\/+$/g, '') : '/';\n\n // Validate folder path (prevent path traversal)\n if (folder !== '/') {\n try {\n this.validateSubpath(folder);\n } catch {\n return { success: false, error: 'Invalid folder path' };\n }\n }\n\n await this.ensureDir();\n\n // Ensure target folder exists\n if (folder !== '/') {\n await this.ensureDir(folder.replace(/^\\//, ''));\n }\n\n if (!this.lfsSetup) {\n await setupGitLfsAttributes(this.config.assetsPath);\n this.lfsSetup = true;\n }\n\n const filename = this.resolveFilename(file.name, folder);\n\n // Determine file path (in folder if specified)\n const filePath =\n folder !== '/'\n ? join(this.config.assetsPath, folder.replace(/^\\//, ''), filename)\n : join(this.config.assetsPath, filename);\n\n const arrayBuffer = await file.arrayBuffer();\n await writeFile(filePath, new Uint8Array(arrayBuffer));\n\n // Compute relative path for manifest\n const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;\n\n // Create manifest entry\n const manifestEntry: ManifestEntryData = {\n alt: metadata?.alt,\n width: metadata?.width,\n height: metadata?.height,\n uploadedAt: new Date().toISOString(),\n uploadedBy: metadata?.uploadedBy,\n originalName: file.name,\n };\n\n await this.manifest.add(relativePath, manifestEntry);\n\n // Build full AssetEntry for return\n const ext = extname(filename).slice(1).toLowerCase();\n const entry: AssetEntry = {\n filename,\n originalName: file.name,\n mimeType: MIME_MAP[ext] || `image/${ext}`,\n size: file.size,\n width: metadata?.width,\n height: metadata?.height,\n alt: metadata?.alt,\n uploadedAt: manifestEntry.uploadedAt!,\n uploadedBy: metadata?.uploadedBy,\n folder,\n };\n\n return { success: true, asset: entry };\n }\n\n /**\n * List all assets recursively from filesystem\n */\n async list(): Promise<AssetEntry[]> {\n // Load manifest once for enrichment\n const manifestData = await this.manifest.read();\n const assets: AssetEntry[] = [];\n\n // Recursive scanning helper\n const scanFolder = async (folderPath: string, folder: string): Promise<void> => {\n let entries: Dirent[];\n try {\n entries = await readdir(folderPath, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n // Skip hidden files, system files, and symlinks\n if (isSystemFile(entry.name) || entry.isSymbolicLink()) {\n continue;\n }\n\n const entryPath = join(folderPath, entry.name);\n\n if (entry.isDirectory()) {\n // Recurse into subdirectories\n const subFolder = folder === '/' ? `/${entry.name}` : `${folder}/${entry.name}`;\n await scanFolder(entryPath, subFolder);\n } else if (entry.isFile() && isRecognizedImageExtension(entry.name)) {\n // Build asset entry from filesystem + manifest\n const assetEntry = await this.buildAssetEntry(entry, folder, manifestData);\n assets.push(assetEntry);\n }\n }\n };\n\n await scanFolder(this.config.assetsPath, '/');\n return assets;\n }\n\n /**\n * Get asset by filename and optional folder\n */\n async getAsset(filename: string, folder = '/'): Promise<AssetEntry | undefined> {\n // Compute relative path and full file path\n const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;\n const fullPath = this.getAssetPath(filename, folder);\n\n // Check if file exists on disk\n let stats: Stats;\n try {\n stats = await stat(fullPath);\n } catch {\n // File doesn't exist\n return undefined;\n }\n\n if (!stats.isFile()) {\n return undefined;\n }\n\n // Load manifest for enrichment\n const manifestData = await this.manifest.read();\n const manifestEntry = manifestData[relativePath];\n\n // Get dimensions\n const { width, height, fromCache } = await this.getDimensions(fullPath, manifestEntry);\n\n // Progressive caching\n if (!fromCache && width && height) {\n this.manifest.add(relativePath, { ...manifestEntry, width, height }).catch(() => {});\n }\n\n // Derive mimeType from extension\n const ext = extname(filename).slice(1).toLowerCase();\n const mimeType = MIME_MAP[ext] || `image/${ext}`;\n\n return {\n filename,\n originalName: manifestEntry?.originalName || filename,\n mimeType,\n size: stats.size,\n width,\n height,\n alt: manifestEntry?.alt,\n uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),\n uploadedBy: manifestEntry?.uploadedBy,\n folder,\n tags: manifestEntry?.tags,\n };\n }\n\n /**\n * Delete asset file and manifest entry\n */\n async delete(filename: string, folder = '/'): Promise<{ success: true } | { success: false; error: string }> {\n // Compute relative path for manifest\n const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;\n\n // Build full file path\n const filePath = this.getAssetPath(filename, folder);\n\n // Delete file from disk (ignore if already gone)\n try {\n await unlink(filePath);\n } catch {\n // File may already be gone, continue with manifest cleanup\n }\n\n // Remove manifest entry\n await this.manifest.remove(relativePath);\n return { success: true };\n }\n\n /**\n * Import an image from a URL (server-side fetch, no CORS issues)\n */\n async importFromUrl(\n url: string,\n metadata?: { alt?: string; uploadedBy?: string; folder?: string },\n ): Promise<{ success: true; asset: AssetEntry } | { success: false; error: string }> {\n let response: Response;\n try {\n response = await fetch(url);\n } catch {\n return { success: false, error: 'Failed to fetch URL' };\n }\n\n if (!response.ok) {\n return { success: false, error: `Fetch failed with status ${response.status}` };\n }\n\n const contentType = response.headers.get('content-type') || '';\n const urlPath = new URL(url).pathname;\n const urlFilename = urlPath.split('/').pop() || 'imported-image.jpg';\n\n // Build a File-like object from the response\n const arrayBuffer = await response.arrayBuffer();\n const file = new File([new Uint8Array(arrayBuffer)], urlFilename, { type: contentType });\n\n return this.upload(file, metadata);\n }\n\n /**\n * List assets and subfolders within a folder (filesystem-first)\n * @param subpath Folder path relative to assets root (default '/')\n */\n async listFolder(subpath = '/'): Promise<FolderListing> {\n // Normalize subpath\n const normalizedSubpath = subpath === '/' ? '/' : '/' + subpath.replace(/^\\/+|\\/+$/g, '');\n\n // Validate path (prevent path traversal)\n let fullPath: string;\n if (normalizedSubpath === '/') {\n fullPath = this.config.assetsPath;\n } else {\n fullPath = this.validateSubpath(normalizedSubpath);\n }\n\n // Read directory entries\n let entries: Dirent[];\n try {\n entries = await readdir(fullPath, { withFileTypes: true });\n } catch {\n // Directory doesn't exist yet - return empty\n return { assets: [], folders: [] };\n }\n\n // Get subfolders (exclude hidden, symlinks)\n const folders = entries\n .filter((e) => e.isDirectory() && !e.name.startsWith('.') && !e.isSymbolicLink())\n .map((e) => ({\n name: e.name,\n path: normalizedSubpath === '/' ? `/${e.name}` : `${normalizedSubpath}/${e.name}`,\n }));\n\n // Get image files (exclude hidden, system files, symlinks, non-images)\n const imageFiles = entries.filter(\n (e) => e.isFile() && !isSystemFile(e.name) && !e.isSymbolicLink() && isRecognizedImageExtension(e.name),\n );\n\n // Load manifest for enrichment\n const manifestData = await this.manifest.read();\n\n // Build asset entries from filesystem\n const assets = await Promise.all(\n imageFiles.map((dirent) => this.buildAssetEntry(dirent, normalizedSubpath, manifestData)),\n );\n\n return { assets, folders };\n }\n\n /**\n * Create a folder on disk\n * @param subpath Folder path relative to assets root\n */\n async createFolder(subpath: string): Promise<{ success: true } | { success: false; error: string }> {\n if (!subpath || subpath === '/') {\n return { success: false, error: 'Cannot create root folder' };\n }\n\n // Validate path (prevent path traversal)\n let fullPath: string;\n try {\n fullPath = this.validateSubpath(subpath);\n } catch {\n return { success: false, error: 'Invalid folder path' };\n }\n\n try {\n await mkdir(fullPath, { recursive: true });\n return { success: true };\n } catch (err) {\n return {\n success: false,\n error: `Failed to create folder: ${err instanceof Error ? err.message : 'Unknown error'}`,\n };\n }\n }\n\n /**\n * Update asset metadata (alt text, tags)\n * @param filename Asset filename\n * @param updates Metadata updates (alt, tags)\n * @param folder Optional folder path (default '/')\n */\n async updateMetadata(\n filename: string,\n updates: Partial<ManifestEntryData>,\n folder = '/',\n ): Promise<{ success: true; asset: AssetEntry } | { success: false; error: string }> {\n // Compute relative path\n const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;\n\n // Check if file exists on disk\n const fullPath = this.getAssetPath(filename, folder);\n try {\n await stat(fullPath);\n } catch {\n return { success: false, error: 'Asset not found' };\n }\n\n // Get existing manifest entry\n const manifestData = await this.manifest.read();\n const existing = manifestData[relativePath] || {};\n\n // Merge updates\n const merged: ManifestEntryData = { ...existing, ...updates };\n\n // Write back to manifest\n await this.manifest.add(relativePath, merged);\n\n // Return updated asset entry\n const asset = await this.getAsset(filename, folder);\n if (!asset) {\n return { success: false, error: 'Failed to retrieve updated asset' };\n }\n\n return { success: true, asset };\n }\n\n /**\n * Get usage information for an asset (which pages reference it)\n * @param filename Asset filename\n */\n async getUsage(filename: string): Promise<AssetUsage[]> {\n if (!this.config.contentRoot) {\n return [];\n }\n\n const usages: AssetUsage[] = [];\n\n // Search patterns for the asset\n const searchPatterns = [filename, `/assets/uploads/${filename}`, `assets/uploads/${filename}`];\n\n // Recursively walk the content directory to find all .vxjson files\n const walkDir = async (dir: string): Promise<string[]> => {\n const files: string[] = [];\n let entries: Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return files;\n }\n\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n files.push(...(await walkDir(fullPath)));\n } else if (entry.isFile() && entry.name.endsWith('.vxjson')) {\n files.push(fullPath);\n }\n }\n\n return files;\n };\n\n const vxjsonFiles = await walkDir(this.config.contentRoot);\n\n for (const filePath of vxjsonFiles) {\n try {\n const content = await readFile(filePath, 'utf-8');\n\n // Check if any search pattern is found in the file content\n const found = searchPatterns.some((pattern) => content.includes(pattern));\n\n if (found) {\n // Extract page name from file path (remove .vxjson extension)\n const relativePath = filePath.replace(this.config.contentRoot, '').replace(/^[/\\\\]/, '');\n const pageName = relativePath.replace(/\\.vxjson$/, '');\n\n // Try to identify which field contains the reference\n // Simple approach: look for the pattern in JSON structure\n let field = 'unknown';\n try {\n const json = JSON.parse(content);\n field = this.findFieldWithAsset(json, searchPatterns) || 'content';\n } catch {\n // If JSON parsing fails, just mark as content\n field = 'content';\n }\n\n usages.push({ page: pageName, field });\n }\n } catch {\n // Skip files that can't be read\n }\n }\n\n return usages;\n }\n\n /**\n * Get the file path for an asset\n * @param filename Asset filename\n * @param folder Optional folder path (defaults to asset's stored folder)\n */\n getAssetPath(filename: string, folder?: string): string {\n const subpath = folder && folder !== '/' ? folder.replace(/^\\/+|\\/+$/g, '') : '';\n return subpath ? join(this.config.assetsPath, subpath, filename) : join(this.config.assetsPath, filename);\n }\n\n /**\n * Read asset file contents for serving (filesystem-first)\n * @param filename Asset filename\n * @param folder Optional folder path (default '/')\n */\n async readAssetFile(\n filename: string,\n folder = '/',\n ): Promise<{ success: true; buffer: Buffer; mimeType: string } | { success: false; error: string }> {\n // Build path from folder + filename\n const filePath = this.getAssetPath(filename, folder);\n\n // Derive mimeType from extension (don't require manifest entry)\n const ext = extname(filename).slice(1).toLowerCase();\n const mimeType = MIME_MAP[ext] || `image/${ext}`;\n\n try {\n const buffer = await readFile(filePath);\n return { success: true, buffer, mimeType };\n } catch {\n return { success: false, error: 'Asset not found' };\n }\n }\n\n /**\n * Helper to find which field contains an asset reference\n */\n private findFieldWithAsset(obj: unknown, patterns: string[], path = ''): string | null {\n if (typeof obj === 'string') {\n if (patterns.some((p) => obj.includes(p))) {\n return path || 'root';\n }\n return null;\n }\n\n if (Array.isArray(obj)) {\n for (let i = 0; i < obj.length; i++) {\n const result = this.findFieldWithAsset(obj[i], patterns, path ? `${path}[${i}]` : `[${i}]`);\n if (result) return result;\n }\n return null;\n }\n\n if (obj && typeof obj === 'object') {\n for (const [key, value] of Object.entries(obj)) {\n const result = this.findFieldWithAsset(value, patterns, path ? `${path}.${key}` : key);\n if (result) return result;\n }\n }\n\n return null;\n }\n\n /**\n * Move assets from one folder to another\n * @param filenames List of filenames to move\n * @param sourceFolder Source folder path (relative to assets root)\n * @param targetFolder Target folder path (relative to assets root)\n */\n async moveAssets(\n filenames: string[],\n sourceFolder: string,\n targetFolder: string,\n ): Promise<{ success: true; moved: number } | { success: false; error: string }> {\n // Normalize folder paths\n const normalizedSource = sourceFolder === '/' ? '/' : '/' + sourceFolder.replace(/^\\/+|\\/+$/g, '');\n const normalizedTarget = targetFolder === '/' ? '/' : '/' + targetFolder.replace(/^\\/+|\\/+$/g, '');\n\n // Validate both folders exist (for non-root folders)\n let sourcePath: string;\n let targetPath: string;\n\n try {\n sourcePath = normalizedSource === '/' ? this.config.assetsPath : this.validateSubpath(normalizedSource);\n targetPath = normalizedTarget === '/' ? this.config.assetsPath : this.validateSubpath(normalizedTarget);\n } catch {\n return { success: false, error: 'Invalid folder path' };\n }\n\n // Verify source folder exists\n try {\n const sourceStat = await stat(sourcePath);\n if (!sourceStat.isDirectory()) {\n return { success: false, error: 'Source folder does not exist' };\n }\n } catch {\n return { success: false, error: 'Source folder does not exist' };\n }\n\n // Verify target folder exists\n try {\n const targetStat = await stat(targetPath);\n if (!targetStat.isDirectory()) {\n return { success: false, error: 'Target folder does not exist' };\n }\n } catch {\n return { success: false, error: 'Target folder does not exist' };\n }\n\n // Move each file\n let movedCount = 0;\n for (const filename of filenames) {\n const sourceFile = join(sourcePath, filename);\n const targetFile = join(targetPath, filename);\n\n // Compute manifest paths\n const oldRelativePath = normalizedSource === '/' ? filename : `${normalizedSource.slice(1)}/${filename}`;\n const newRelativePath = normalizedTarget === '/' ? filename : `${normalizedTarget.slice(1)}/${filename}`;\n\n try {\n // Move the file on disk\n await rename(sourceFile, targetFile);\n\n // Update manifest: remove old entry and add new one\n const manifestData = await this.manifest.read();\n const oldEntry = manifestData[oldRelativePath];\n\n if (oldEntry) {\n await this.manifest.remove(oldRelativePath);\n await this.manifest.add(newRelativePath, oldEntry);\n }\n\n movedCount++;\n } catch (err) {\n // Continue with other files even if one fails\n console.error(`[AssetOperations] Failed to move ${filename}:`, err);\n }\n }\n\n return { success: true, moved: movedCount };\n }\n\n /**\n * Get the complete folder tree with asset counts\n * @returns Array of folder tree nodes representing the folder hierarchy\n */\n async getFolderTree(): Promise<FolderTreeNode[]> {\n const buildTree = async (folderPath: string, folder: string): Promise<FolderTreeNode[]> => {\n let entries: Dirent[];\n try {\n entries = await readdir(folderPath, { withFileTypes: true });\n } catch {\n return [];\n }\n\n const result: FolderTreeNode[] = [];\n\n for (const entry of entries) {\n // Skip hidden files/folders and symlinks\n if (isSystemFile(entry.name) || entry.isSymbolicLink()) {\n continue;\n }\n\n if (entry.isDirectory()) {\n const entryPath = join(folderPath, entry.name);\n const subFolder = folder === '/' ? `/${entry.name}` : `${folder}/${entry.name}`;\n\n // Count image files in this folder (non-recursive count for this folder only)\n let assetCount = 0;\n try {\n const subEntries = await readdir(entryPath, { withFileTypes: true });\n assetCount = subEntries.filter(\n (e) => e.isFile() && !isSystemFile(e.name) && isRecognizedImageExtension(e.name),\n ).length;\n } catch {\n // If we can't read the folder, count is 0\n }\n\n // Recursively get children\n const children = await buildTree(entryPath, subFolder);\n\n result.push({\n name: entry.name,\n path: subFolder,\n assetCount,\n children,\n });\n }\n }\n\n return result;\n };\n\n // Count assets in root folder\n let rootAssetCount = 0;\n try {\n const rootEntries = await readdir(this.config.assetsPath, { withFileTypes: true });\n rootAssetCount = rootEntries.filter(\n (e) => e.isFile() && !isSystemFile(e.name) && isRecognizedImageExtension(e.name),\n ).length;\n } catch {\n // If we can't read root, count is 0\n }\n\n // Build tree starting from assets root\n const children = await buildTree(this.config.assetsPath, '/');\n\n // Return root as first element with its children\n return [\n {\n name: 'Root',\n path: '/',\n assetCount: rootAssetCount,\n children,\n },\n ];\n }\n}\n","/**\n * Cloudflare Access JWT validation utility\n *\n * Validates JWT tokens from CF Access for API authorization and git commit attribution.\n * When CF_ACCESS_TEAM_NAME and CF_ACCESS_AUD env vars are set, requests must have valid tokens.\n * When env vars are not set (local dev), validation is skipped.\n */\n\nimport { type JWTPayload, createRemoteJWKSet, jwtVerify } from 'jose'\n\nconst CF_ACCESS_TEAM_NAME = process.env.CF_ACCESS_TEAM_NAME\nconst CF_ACCESS_AUD = process.env.CF_ACCESS_AUD\n\n// JWKS with built-in caching (handles key rotation automatically)\nconst JWKS = CF_ACCESS_TEAM_NAME\n ? createRemoteJWKSet(new URL(`https://${CF_ACCESS_TEAM_NAME}.cloudflareaccess.com/cdn-cgi/access/certs`))\n : null\n\nexport interface CFAccessUser {\n email: string\n sub: string\n}\n\nexport interface CFAccessResult {\n valid: boolean\n required: boolean\n user?: CFAccessUser\n error?: string\n}\n\n/**\n * Extract CF Access JWT token from request.\n * Checks Cf-Access-Jwt-Assertion header first, falls back to CF_Authorization cookie.\n */\nexport function extractCFAccessToken(request: Request): string | null {\n // Header is primary (always present when behind CF Access)\n const headerToken = request.headers.get('Cf-Access-Jwt-Assertion')\n if (headerToken) return headerToken\n\n // Cookie is fallback (browser requests)\n const cookies = request.headers.get('Cookie') || ''\n const match = cookies.match(/CF_Authorization=([^;]+)/)\n return match ? match[1] : null\n}\n\n/**\n * Validate CF Access JWT from request.\n *\n * Returns { valid: true, required: false } when env vars not set (local dev mode).\n * Returns { valid: true, required: true, user } when token is valid.\n * Returns { valid: false, required: true, error } when token is invalid or missing.\n */\nexport async function validateCFAccessRequest(request: Request): Promise<CFAccessResult> {\n // If CF Access not configured, skip validation (local dev)\n if (!CF_ACCESS_TEAM_NAME || !CF_ACCESS_AUD || !JWKS) {\n return { valid: true, required: false }\n }\n\n const token = extractCFAccessToken(request)\n if (!token) {\n return { valid: false, required: true, error: 'No token provided' }\n }\n\n try {\n const { payload } = await jwtVerify(token, JWKS, {\n issuer: `https://${CF_ACCESS_TEAM_NAME}.cloudflareaccess.com`,\n audience: CF_ACCESS_AUD,\n })\n\n return {\n valid: true,\n required: true,\n user: {\n email: (payload as JWTPayload & { email?: string }).email || '',\n sub: payload.sub || '',\n },\n }\n } catch (error) {\n return {\n valid: false,\n required: true,\n error: error instanceof Error ? error.message : 'Validation failed',\n }\n }\n}\n","import { mkdir, readFile, rename, unlink, writeFile } from 'fs/promises';\nimport { dirname, join } from 'path';\nimport sortKeys from 'sort-keys';\nimport type {\n ComponentEntry,\n ComponentEntryWithId,\n ComponentRegistry as ComponentRegistryType,\n} from './component-registry.types';\n\n/**\n * Component Registry for managing linked and unlinked components\n *\n * Registry is stored at {canvasDir}/components/registry.json\n * Component IDs must follow the format: vx-{uuid}\n */\nexport class ComponentRegistry {\n private registryPath: string;\n private registry: ComponentRegistryType = {};\n private initialized = false;\n\n constructor(canvasDir: string) {\n this.registryPath = join(canvasDir, 'components', 'registry.json');\n }\n\n /**\n * Initialize the registry by loading from disk or creating new\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n try {\n const content = await readFile(this.registryPath, 'utf-8');\n this.registry = JSON.parse(content);\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n // File doesn't exist, create empty registry\n await this.save();\n } else {\n throw error;\n }\n }\n\n this.initialized = true;\n }\n\n /**\n * Validate component ID format (vx-{uuid})\n */\n private validateComponentId(id: string): void {\n const uuidRegex = /^vx-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n if (!uuidRegex.test(id)) {\n throw new Error('Invalid component ID format. Expected: vx-{uuid}');\n }\n }\n\n /**\n * Save registry to disk atomically\n */\n private async save(): Promise<void> {\n const tempPath = `${this.registryPath}.tmp.${Date.now()}.${Math.random().toString(36).substring(2, 9)}`;\n\n try {\n // Ensure directory exists\n await mkdir(dirname(this.registryPath), { recursive: true });\n\n // Sort keys for consistent output\n const sorted = sortKeys(this.registry, { deep: true });\n const content = JSON.stringify(sorted, null, 2);\n\n // Write to temp file\n await writeFile(tempPath, content);\n\n // Atomic rename\n await rename(tempPath, this.registryPath);\n } catch (error) {\n // Clean up temp file on error\n try {\n await unlink(tempPath);\n } catch {}\n throw error;\n }\n }\n\n /**\n * Register a new component or update existing\n */\n async register(id: string, entry: ComponentEntry): Promise<void> {\n await this.initialize();\n this.validateComponentId(id);\n\n this.registry[id] = {\n displayName: entry.displayName,\n path: entry.path,\n };\n\n await this.save();\n }\n\n /**\n * Get a component entry by ID\n */\n async get(id: string): Promise<ComponentEntry | null> {\n await this.initialize();\n return this.registry[id] || null;\n }\n\n /**\n * Link a component to a path\n */\n async link(id: string, path: string): Promise<void> {\n await this.initialize();\n\n const entry = this.registry[id];\n if (!entry) {\n throw new Error(`Component ${id} not found in registry`);\n }\n\n entry.path = path;\n await this.save();\n }\n\n /**\n * Unlink a component (set path to null)\n */\n async unlink(id: string): Promise<void> {\n await this.initialize();\n\n const entry = this.registry[id];\n if (!entry) {\n throw new Error(`Component ${id} not found in registry`);\n }\n\n entry.path = null;\n await this.save();\n }\n\n /**\n * List all components\n */\n async list(): Promise<ComponentEntryWithId[]> {\n await this.initialize();\n\n return Object.entries(this.registry).map(([id, entry]) => ({\n id,\n ...entry,\n }));\n }\n\n /**\n * Delete a component from registry\n */\n async delete(id: string): Promise<void> {\n await this.initialize();\n\n delete this.registry[id];\n await this.save();\n }\n}\n","import type { ContentIndex } from './content-index';\nimport { localesOf } from './content-utils';\nimport type { ContentManifest, GlobalFilters, SitesConfig } from './types';\n\n/**\n * Apply filters to a single content manifest\n * Pure function that checks if a manifest matches all provided filters\n */\nexport function applyContentFilters(manifest: ContentManifest, filters: GlobalFilters): boolean {\n // Site filter\n if (filters.site && manifest.site !== filters.site) return false;\n\n // Collection filter\n if (filters.collection && manifest.collection !== filters.collection) return false;\n\n // Type filter\n if (filters.type && manifest.type !== filters.type) return false;\n\n // Kind filter\n if (filters.kind && manifest.kind !== filters.kind) return false;\n\n // Locales filter - check if manifest has any of the requested locales\n if (filters.locales && filters.locales.length > 0) {\n const hasAnyLocale = filters.locales.some((locale) => manifest.locales[locale]);\n if (!hasAnyLocale) return false;\n }\n\n // Missing locales filter - content must NOT have any of these locales\n if (filters.missingLocales && filters.missingLocales.length > 0) {\n const hasAnyMissingLocale = filters.missingLocales.some((locale) => manifest.locales[locale]);\n if (hasAnyMissingLocale) return false;\n }\n\n // Published status filter - check all locales\n if (filters.published !== undefined) {\n let hasPublishedLocale = false;\n for (const localeVersion of localesOf(manifest)) {\n if (!localeVersion.unpublishAt) {\n hasPublishedLocale = true;\n break;\n }\n if (new Date(localeVersion.unpublishAt) > new Date()) {\n hasPublishedLocale = true;\n break;\n }\n }\n if (filters.published !== hasPublishedLocale) return false;\n }\n\n // All filters passed\n return true;\n}\n\n/**\n * Filter a collection of content manifests based on localization status\n * Returns manifests that match the specified localization criteria\n */\nexport function filterByLocalization(\n allManifests: ContentManifest[],\n filters: GlobalFilters,\n siteLocales: string[],\n): ContentManifest[] {\n const results: ContentManifest[] = [];\n\n if (!filters.localization) {\n // No localization filter - return all manifests that match other filters\n for (const manifest of allManifests) {\n if (applyContentFilters(manifest, filters)) {\n results.push(manifest);\n }\n }\n return results;\n }\n\n // Apply localization-specific filtering\n switch (filters.localization) {\n case 'one':\n // Find content with exactly one locale\n for (const manifest of allManifests) {\n const localeCount = Object.keys(manifest.locales).length;\n if (localeCount === 1 && applyContentFilters(manifest, filters)) {\n results.push(manifest);\n }\n }\n break;\n\n case 'complete':\n // Find content with all expected locales\n for (const manifest of allManifests) {\n const hasAllLocales = siteLocales.every((loc) => manifest.locales[loc]);\n if (hasAllLocales && applyContentFilters(manifest, filters)) {\n results.push(manifest);\n }\n }\n break;\n\n case 'partial':\n // Find content with some but not all translations\n for (const manifest of allManifests) {\n const localeCount = Object.keys(manifest.locales).length;\n const hasPartialLocales = localeCount > 0 && localeCount < siteLocales.length;\n if (hasPartialLocales && applyContentFilters(manifest, filters)) {\n results.push(manifest);\n }\n }\n break;\n }\n\n return results;\n}\n\n/**\n * Generator that yields manifests after applying all filters\n */\nexport function* filteredContentGenerator(\n contentIndex: ContentIndex,\n filters: GlobalFilters,\n): Generator<ContentManifest> {\n for (const manifest of getFilteredManifestsGenerator(contentIndex, filters)) {\n if (applyContentFilters(manifest, filters)) {\n yield manifest;\n }\n }\n}\n\n/**\n * Generator that yields manifests using the most efficient index path\n */\nexport function* getFilteredManifestsGenerator(\n contentIndex: ContentIndex,\n filters: GlobalFilters,\n): Generator<ContentManifest> {\n // Choose the most efficient index path based on available filters\n\n // Most specific: site + locale + collection\n if (filters.site && filters.locales?.length === 1 && filters.collection) {\n for (const manifest of contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0])) {\n if (manifest.collection === filters.collection) {\n yield manifest;\n }\n }\n return;\n }\n\n // Site + collection (use optimized method)\n if (filters.site && filters.collection) {\n yield* contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);\n return;\n }\n\n // Site + single locale (use optimized method)\n if (filters.site && filters.locales?.length === 1) {\n yield* contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0]);\n return;\n }\n\n // Just single locale\n if (filters.locales?.length === 1) {\n yield* contentIndex.getManifestsForLocale(filters.locales[0]);\n return;\n }\n\n // Just site\n if (filters.site) {\n yield* contentIndex.getManifestsForSite(filters.site);\n return;\n }\n\n // Just collection\n if (filters.collection) {\n yield* contentIndex.getManifestsForCollection(filters.collection);\n return;\n }\n\n // Kind filter\n if (filters.kind) {\n yield* contentIndex.getManifestsForKind(filters.kind);\n return;\n }\n\n // No specific filters - yield all manifests\n yield* contentIndex.listAllContent();\n}\n\n/**\n * Get filtered manifests using indexes where possible for performance\n * This function leverages ContentIndex's specialized indexes to avoid full scans\n */\nexport function getFilteredManifests(contentIndex: ContentIndex, filters: GlobalFilters): ContentManifest[] {\n return Array.from(getFilteredManifestsGenerator(contentIndex, filters));\n}\n\n/**\n * Generator that yields manifests after applying all filters\n * This is the main entry point for filtering content using indexes efficiently\n */\nexport function* filterContentWithIndexes(\n contentIndex: ContentIndex,\n filters: GlobalFilters | undefined,\n sitesConfig: SitesConfig,\n): Generator<ContentManifest> {\n if (!filters) {\n // No filters - return all content\n yield* contentIndex.listAllContent();\n return;\n }\n\n // Special optimization for kind + site + collection\n if (filters.kind === 'page' && filters.site && filters.collection) {\n // Check if the site even has this collection\n const siteCollections = contentIndex.getCollectionsForSite(filters.site);\n if (!siteCollections.has(filters.collection)) {\n return; // Early exit - no pages in this collection for this site\n }\n } else if (filters.kind === 'block' && filters.collection) {\n // Check if blocks have this collection\n const blockCollections = contentIndex.getBlockCollections();\n if (!blockCollections.has(filters.collection)) {\n return; // Early exit - no blocks in this collection\n }\n }\n\n // Use the most efficient generator based on filters\n let generator: Generator<ContentManifest>;\n\n // Optimal filter ordering for most specific queries first\n if (filters.kind === 'page' && filters.site && filters.collection) {\n // Most specific for pages: site + collection\n generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);\n } else if (filters.kind === 'block' && filters.collection) {\n // Most specific for blocks: kind + collection\n generator = contentIndex.getManifestsForCollection(filters.collection);\n } else if (filters.kind) {\n generator = contentIndex.getManifestsForKind(filters.kind);\n } else if (filters.site && filters.collection) {\n generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);\n } else if (filters.site && filters.locales?.length === 1) {\n // Single locale optimization\n generator = contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0]);\n } else if (filters.site) {\n generator = contentIndex.getManifestsForSite(filters.site);\n } else if (filters.collection) {\n generator = contentIndex.getManifestsForCollection(filters.collection);\n } else if (filters.locales?.length === 1) {\n // Single locale optimization\n generator = contentIndex.getManifestsForLocale(filters.locales[0]);\n } else {\n generator = contentIndex.listAllContent();\n }\n\n // Apply additional filters\n for (const manifest of generator) {\n if (!applyContentFilters(manifest, filters)) continue;\n\n // Localization filter\n if (filters.localization) {\n // Early exit optimization: if complete + missingLocales, no results possible\n if (filters.localization === 'complete' && filters.missingLocales?.length) {\n continue; // Complete means has all locales, can't be missing any\n }\n\n const siteLocales =\n filters.site && manifest.kind === 'page'\n ? sitesConfig.sites[filters.site]?.locales || sitesConfig.globalLocales\n : sitesConfig.globalLocales;\n\n const localeCount = Object.keys(manifest.locales).length;\n const hasLocales = siteLocales.filter((l) => manifest.locales[l]).length;\n const totalLocales = siteLocales.length;\n\n if (filters.localization === 'complete' && hasLocales !== totalLocales) continue;\n if (filters.localization === 'partial' && (localeCount <= 1 || hasLocales === totalLocales)) continue;\n if (filters.localization === 'one' && localeCount !== 1) continue;\n }\n\n yield manifest;\n }\n}\n","import { localesOf } from './content-utils';\nimport type { ContentData, ContentIdentity, ContentManifest, LocaleVersion } from './types';\n\n/**\n * Base class for content indexes (blocks, data)\n * Maintains collection->name->locale lookups with V8-optimized structures\n */\nexport class BaseContentIndex {\n // Primary index: id -> ContentManifest\n protected index: Map<string, ContentManifest> = new Map();\n\n // Content cache: id -> locale -> content (for small files)\n protected contentCache: Map<string, Record<string, ContentData | null>> = new Map();\n\n // Name index: collection -> name -> ContentManifest\n protected nameIndex: Map<string, Map<string, ContentManifest>> = new Map();\n\n // Collections used\n readonly collections: Set<string> = new Set();\n\n /**\n * Add or update content in the index\n * Merges manifest locales and updates content cache if provided\n */\n addContent(identity: ContentIdentity, localeVersion: LocaleVersion, content?: ContentData | null): void {\n // Get existing manifest\n const existing = this.index.get(identity.id);\n const locale = localeVersion.locale;\n\n if (existing) {\n // Update single locale\n const existingLocale = existing.locales[locale];\n if (!existingLocale || existingLocale.etag !== localeVersion.etag) {\n existing.locales[locale] = localeVersion;\n }\n } else {\n // New content - create ContentManifest with single locale\n const newManifest: ContentManifest = {\n id: identity.id,\n type: identity.type,\n kind: identity.kind,\n site: identity.site,\n collection: identity.collection,\n locales: {\n [locale]: localeVersion,\n },\n };\n\n this.index.set(identity.id, newManifest);\n this.collections.add(identity.collection);\n }\n\n // Update content cache if provided\n if (content !== undefined) {\n const existingCache = this.contentCache.get(identity.id);\n if (existingCache) {\n // Update single locale content\n existingCache[locale] = content;\n } else {\n this.contentCache.set(identity.id, { [locale]: content });\n }\n }\n\n // Update name index\n const manifestToIndex = existing || this.index.get(identity.id)!;\n if (localeVersion.name) {\n if (!this.nameIndex.has(identity.collection)) {\n this.nameIndex.set(identity.collection, new Map());\n }\n this.nameIndex.get(identity.collection)!.set(localeVersion.name, manifestToIndex);\n }\n }\n\n /**\n * Remove a specific locale from an entry\n */\n removeLocale(id: string, locale: string): void {\n const manifest = this.index.get(id);\n if (!manifest || !manifest.locales[locale]) return;\n\n // Remove locale from manifest\n manifest.locales[locale] = undefined;\n\n // Remove from content cache\n const contentCache = this.contentCache.get(id);\n if (contentCache) {\n delete contentCache[locale];\n }\n\n // If no defined locales left, remove the entire entry\n const remainingLocales = Object.values(manifest.locales).filter((v) => v !== undefined);\n if (remainingLocales.length === 0) {\n this.removeEntry(id);\n }\n }\n\n /**\n * Remove an entry from the index\n */\n removeEntry(id: string): void {\n const manifest = this.index.get(id);\n if (!manifest) return;\n\n // Remove from name index\n for (const localeVersion of localesOf(manifest)) {\n if (localeVersion.name) {\n const collectionMap = this.nameIndex.get(manifest.collection);\n if (collectionMap) {\n collectionMap.delete(localeVersion.name);\n }\n break; // All locales have same name\n }\n }\n\n // Remove from primary index\n this.index.delete(id);\n\n // Remove from content cache\n this.contentCache.delete(id);\n }\n\n /**\n * Get cached content for a specific locale\n */\n getCachedContent(id: string, locale: string): ContentData | null {\n const localeContent = this.contentCache.get(id);\n return localeContent?.[locale] || null;\n }\n\n /**\n * Get content manifest\n */\n getManifest(id: string): ContentManifest | null {\n return this.index.get(id) || null;\n }\n\n /**\n * Find entry by name\n */\n getByName(collection: string, name: string, locale?: string): ContentManifest | null {\n const collectionMap = this.nameIndex.get(collection);\n if (!collectionMap) return null;\n\n const manifest = collectionMap.get(name);\n if (!manifest) return null;\n\n // If specific locale requested, check it exists\n if (locale && !manifest.locales[locale]) {\n return null;\n }\n\n return manifest;\n }\n\n /**\n * Generator for all manifests\n */\n *getAllManifests(): Generator<ContentManifest> {\n for (const manifest of this.index.values()) {\n yield manifest;\n }\n }\n\n /**\n * Generator for manifests by locale\n */\n *getManifestsByLocale(locale: string): Generator<ContentManifest> {\n for (const manifest of this.index.values()) {\n if (manifest.locales[locale]) {\n yield manifest;\n }\n }\n }\n\n /**\n * Generator for manifests by collection\n */\n *getManifestsByCollection(collection: string): Generator<ContentManifest> {\n for (const manifest of this.index.values()) {\n if (manifest.collection === collection) {\n yield manifest;\n }\n }\n }\n\n /**\n * Get the count of indexed content entries (unique IDs)\n */\n get entryCount(): number {\n return this.index.size;\n }\n\n /**\n * Clear all indexes\n */\n clear(): void {\n this.index.clear();\n this.contentCache.clear();\n this.nameIndex.clear();\n this.collections.clear();\n }\n}\n","import { BaseContentIndex } from './base-content-index';\n\n/**\n * V8-optimized index for blocks\n * Maintains collection->name->locale lookups\n */\nexport class BlockIndex extends BaseContentIndex {\n constructor(locales: string[]) {\n super();\n // locales parameter kept for future use\n }\n}\n","import { BaseContentIndex } from './base-content-index';\n\n/**\n * V8-optimized index for data collections\n * Maintains collection->name->locale lookups\n */\nexport class DataIndex extends BaseContentIndex {}\n","import { isContentPublished, localesOf, mapLocales } from './content-utils';\nimport type { ContentData, ContentIdentity, ContentManifest, LocaleVersion } from './types';\n\n/**\n * V8-optimized index for a single site\n * Maintains pathname lookups and collections for one site only\n */\nexport class SiteIndex {\n // Primary index: id -> ContentManifest\n private index: Map<string, ContentManifest> = new Map();\n\n // Content cache: id -> locale -> content (for small files)\n private contentCache: Map<string, Record<string, ContentData | null>> = new Map();\n\n // Pathname index: locale -> (pathname -> ContentManifest)\n // Locale level uses V8-optimized record, pathname level uses Map for dynamic keys\n private pathnameIndex: Record<string, Map<string, ContentManifest>>;\n\n // Previous pathname index for redirects: locale -> (oldPathname -> ContentManifest)\n // Same structure - record for locales, Map for pathnames\n private previousPathnameIndex: Record<string, Map<string, ContentManifest>>;\n\n // Collections used by this site\n readonly collections: Set<string> = new Set();\n\n constructor(\n siteName: string,\n private locales: string[],\n ) {\n // Initialize pathname indexes - V8-optimized record for locales, Maps for pathnames\n this.pathnameIndex = mapLocales(locales, () => new Map());\n this.previousPathnameIndex = mapLocales(locales, () => new Map());\n }\n\n /**\n * Add or update content in the index\n * Merges manifest locales and updates content cache if provided\n */\n addContent(identity: ContentIdentity, localeVersion: LocaleVersion, content?: ContentData | null): void {\n // Get existing manifest\n const existing = this.index.get(identity.id);\n const locale = localeVersion.locale;\n\n if (existing) {\n const existingLocale = existing.locales[locale];\n\n // Track what we need to rollback\n // First check what pathname currently maps to this manifest in our index\n // This handles in-place updates where the manifest object has already been modified\n let oldPathname: string | undefined;\n\n // Find all pathnames that currently point to this manifest\n for (const [pathname, indexedManifest] of this.pathnameIndex[locale].entries()) {\n if (indexedManifest === existing && pathname !== localeVersion.pathname) {\n oldPathname = pathname;\n break;\n }\n }\n\n // If we didn't find it in the index, fall back to what's stored in the existing locale\n if (!oldPathname && existingLocale?.pathname && existingLocale.pathname !== localeVersion.pathname) {\n oldPathname = existingLocale.pathname;\n }\n\n const hadExistingLocale = !!existingLocale;\n let deletedOldPathname = false;\n let addedNewPathname = false;\n const addedPreviousPathnames: string[] = [];\n\n // Update locale manifest if changed\n // We need to always check for pathname changes, even if other fields haven't changed\n // This handles in-place updates where the manifest is modified before calling addContent\n const needsUpdate =\n !existingLocale ||\n existingLocale.etag !== localeVersion.etag ||\n existingLocale.modified !== localeVersion.modified ||\n (oldPathname && oldPathname !== localeVersion.pathname);\n\n if (needsUpdate) {\n try {\n // Update the manifest locale\n existing.locales[locale] = localeVersion;\n\n // Update pathname indexes after manifest is updated\n if (localeVersion.pathname) {\n // If pathname changed, remove the old one\n if (oldPathname && oldPathname !== localeVersion.pathname) {\n this.pathnameIndex[locale].delete(oldPathname);\n deletedOldPathname = true;\n\n // Track the old pathname for redirects only if content is published\n if (isContentPublished(localeVersion)) {\n this.previousPathnameIndex[locale].set(oldPathname, existing);\n addedPreviousPathnames.push(oldPathname);\n }\n }\n\n // Add/update the new pathname\n this.pathnameIndex[locale].set(localeVersion.pathname, existing);\n addedNewPathname = true;\n }\n\n // Update previous pathname indexes from the manifest\n if (localeVersion.previousPathnames) {\n for (const prevPath of Object.keys(localeVersion.previousPathnames)) {\n // Only add if not already there\n if (!this.previousPathnameIndex[locale].has(prevPath)) {\n this.previousPathnameIndex[locale].set(prevPath, existing);\n addedPreviousPathnames.push(prevPath);\n }\n }\n }\n } catch (error) {\n // Rollback only what we changed\n if (hadExistingLocale) {\n existing.locales[locale] = existingLocale;\n } else {\n existing.locales[locale] = undefined;\n }\n\n // Rollback pathname index changes\n if (deletedOldPathname && oldPathname) {\n this.pathnameIndex[locale].set(oldPathname, existing);\n }\n if (addedNewPathname && localeVersion.pathname) {\n this.pathnameIndex[locale].delete(localeVersion.pathname);\n }\n\n // Rollback previous pathname additions\n for (const prevPath of addedPreviousPathnames) {\n this.previousPathnameIndex[locale].delete(prevPath);\n }\n\n throw error;\n }\n }\n } else {\n // New content - create ContentManifest with single locale\n const newManifest: ContentManifest = {\n id: identity.id,\n type: identity.type,\n kind: identity.kind,\n site: identity.site,\n collection: identity.collection,\n locales: {\n [locale]: localeVersion,\n },\n };\n\n this.index.set(identity.id, newManifest);\n this.collections.add(identity.collection);\n\n // Add pathname indexes\n if (localeVersion.pathname) {\n this.pathnameIndex[locale].set(localeVersion.pathname, newManifest);\n }\n if (localeVersion.previousPathnames) {\n for (const prevPath of Object.keys(localeVersion.previousPathnames)) {\n this.previousPathnameIndex[locale].set(prevPath, newManifest);\n }\n }\n }\n\n // Update content cache if provided\n if (content !== undefined) {\n const existingCache = this.contentCache.get(identity.id);\n if (existingCache) {\n // Update single locale content\n existingCache[locale] = content;\n } else {\n this.contentCache.set(identity.id, { [locale]: content });\n }\n }\n }\n\n /**\n * Remove a specific locale from an entry\n */\n removeLocale(id: string, locale: string): void {\n const manifest = this.index.get(id);\n if (!manifest || !manifest.locales[locale]) return;\n\n const localeVersion = manifest.locales[locale];\n\n // Remove from pathname indexes\n if (localeVersion.pathname) {\n this.pathnameIndex[locale].delete(localeVersion.pathname);\n }\n if (localeVersion.previousPathnames) {\n for (const prevPath of Object.keys(localeVersion.previousPathnames)) {\n this.previousPathnameIndex[locale].delete(prevPath);\n }\n }\n\n // Remove locale from manifest\n manifest.locales[locale] = undefined;\n\n // Remove from content cache\n const contentCache = this.contentCache.get(id);\n if (contentCache) {\n delete contentCache[locale];\n }\n\n // If no locales left, remove the entire entry\n if (Object.keys(manifest.locales).length === 0) {\n this.removeEntry(id);\n }\n }\n\n /**\n * Remove an entry from the index\n */\n removeEntry(id: string): void {\n const manifest = this.index.get(id);\n if (!manifest) return;\n\n // Remove from pathname indexes\n for (const localeVersion of localesOf(manifest)) {\n const { locale } = localeVersion;\n if (localeVersion.pathname) {\n this.pathnameIndex[locale].delete(localeVersion.pathname);\n }\n if (localeVersion.previousPathnames) {\n for (const prevPath of Object.keys(localeVersion.previousPathnames)) {\n this.previousPathnameIndex[locale].delete(prevPath);\n }\n }\n }\n\n // Remove from primary index\n this.index.delete(id);\n\n // Remove from content cache\n this.contentCache.delete(id);\n }\n\n /**\n * Get cached content for a specific locale\n */\n getCachedContent(id: string, locale: string): ContentData | null {\n const localeContent = this.contentCache.get(id);\n return localeContent?.[locale] || null;\n }\n\n /**\n * Get content manifest\n */\n getManifest(id: string): ContentManifest | null {\n return this.index.get(id) || null;\n }\n\n /**\n * Find content by pathname\n */\n getByPathname(pathname: string, locale?: string): ContentManifest | null {\n if (locale) {\n return this.pathnameIndex[locale]?.get(pathname) || null;\n }\n\n // Check all locales\n for (const locale of this.locales) {\n const manifest = this.pathnameIndex[locale].get(pathname);\n if (manifest) {\n return manifest;\n }\n }\n\n return null;\n }\n\n /**\n * Find content by previous pathname (for redirects)\n */\n getByPreviousPathname(pathname: string, locale?: string): ContentManifest | null {\n if (locale) {\n return this.previousPathnameIndex[locale]?.get(pathname) || null;\n }\n\n // Check all locales\n for (const locale of this.locales) {\n const manifest = this.previousPathnameIndex[locale].get(pathname);\n if (manifest) {\n return manifest;\n }\n }\n\n return null;\n }\n\n /**\n * Generator for all manifests\n */\n *getAllManifests(): Generator<ContentManifest> {\n for (const manifest of this.index.values()) {\n yield manifest;\n }\n }\n\n /**\n * Generator for manifests by locale\n */\n *getManifestsByLocale(locale: string): Generator<ContentManifest> {\n for (const manifest of this.index.values()) {\n if (manifest.locales[locale]) {\n yield manifest;\n }\n }\n }\n\n /**\n * Get the count of indexed content entries (unique IDs)\n */\n get entryCount(): number {\n return this.index.size;\n }\n\n /**\n * Clear all indexes\n */\n clear(): void {\n this.index.clear();\n this.contentCache.clear();\n // Clear all Maps in the pathname indexes\n for (const locale of this.locales) {\n this.pathnameIndex[locale].clear();\n this.previousPathnameIndex[locale].clear();\n }\n this.collections.clear();\n }\n}\n","import { BlockIndex } from './block-index';\nimport { localesOf, mapSiteNames } from './content-utils';\nimport { DataIndex } from './data-index';\nimport { SiteIndex } from './site-index';\nimport type { ContentData, ContentIdentity, ContentManifest, LocaleVersion, SitesConfig } from './types';\n\n/**\n * ContentIndex coordinates between per-site indexes and the block index\n * This provides efficient filtering by routing to the appropriate specialized index\n */\n// Use global registry to survive module reloads in development\nconst globalCache = (globalThis as any).__CONLOCA_CONTENT_INDEX_CACHE__ || {};\nif (!(globalThis as any).__CONLOCA_CONTENT_INDEX_CACHE__) {\n (globalThis as any).__CONLOCA_CONTENT_INDEX_CACHE__ = globalCache;\n}\n\nexport class ContentIndex {\n // Use global cache instead of static cache\n private static get cache() {\n return globalCache;\n }\n\n // Per-site indexes using V8-optimized object\n private siteIndexes: Record<string, SiteIndex | undefined>;\n\n // Single block index\n private blockIndex: BlockIndex;\n\n // Single data index\n private dataIndex: DataIndex;\n\n private constructor(private sitesConfig: SitesConfig) {\n // Initialize block index\n this.blockIndex = new BlockIndex(sitesConfig.globalLocales);\n\n // Initialize data index\n this.dataIndex = new DataIndex();\n\n // Initialize V8-optimized site indexes\n this.siteIndexes = mapSiteNames(sitesConfig, (siteName) => {\n const siteConfig = sitesConfig.sites[siteName];\n return new SiteIndex(siteName, siteConfig.locales);\n });\n }\n\n /**\n * Get cached index or create a new one\n */\n static async getCachedOrCreate(contentRoot: string, sitesConfig: SitesConfig): Promise<ContentIndex> {\n if (!ContentIndex.cache[contentRoot]) {\n ContentIndex.cache[contentRoot] = new ContentIndex(sitesConfig);\n }\n return ContentIndex.cache[contentRoot];\n }\n\n /**\n * Clear all cached indexes\n */\n static clearCache(): void {\n Object.keys(globalCache).forEach((key) => delete globalCache[key]);\n }\n\n /**\n * Create a new index without caching - for testing\n */\n static createUncached(sitesConfig: SitesConfig): ContentIndex {\n return new ContentIndex(sitesConfig);\n }\n\n /**\n * Add or update content in the appropriate index\n * Updates a single locale's manifest and content cache if provided\n */\n addContent(identity: ContentIdentity, localeVersion: LocaleVersion, content?: ContentData | null): void {\n // Validate that blocks and data don't have a site\n if ((identity.kind === 'block' || identity.kind === 'data') && identity.site) {\n throw new Error(`${identity.kind} cannot have a site property`);\n }\n // Validate that pages must have a site\n if (identity.kind === 'page' && !identity.site) {\n throw new Error('Pages must have a site property');\n }\n\n if (identity.kind === 'block') {\n this.blockIndex.addContent(identity, localeVersion, content);\n } else if (identity.kind === 'data') {\n this.dataIndex.addContent(identity, localeVersion, content);\n } else {\n const siteIndex = this.siteIndexes[identity.site!];\n if (siteIndex) {\n siteIndex.addContent(identity, localeVersion, content);\n }\n }\n }\n\n /**\n * Remove a specific locale from content\n */\n removeLocale(id: string, locale: string): void {\n const manifest = this.getManifest(id);\n if (!manifest) return;\n\n // Remove from the appropriate index\n if (manifest.kind === 'block') {\n this.blockIndex.removeLocale(id, locale);\n } else if (manifest.kind === 'data') {\n this.dataIndex.removeLocale(id, locale);\n } else {\n const siteIndex = this.siteIndexes[manifest.site!];\n if (siteIndex) {\n siteIndex.removeLocale(id, locale);\n }\n }\n }\n\n /**\n * Get cached content\n */\n getCachedContent(id: string, locale: string): ContentData | null {\n const manifest = this.getManifest(id);\n if (!manifest) return null;\n\n if (manifest.kind === 'block') {\n return this.blockIndex.getCachedContent(id, locale);\n }\n if (manifest.kind === 'data') {\n return this.dataIndex.getCachedContent(id, locale);\n }\n const siteIndex = this.siteIndexes[manifest.site!];\n return siteIndex ? siteIndex.getCachedContent(id, locale) : null;\n }\n\n /**\n * Remove an entry from all indexes\n */\n removeEntry(id: string): void {\n // Try blocks first\n this.blockIndex.removeEntry(id);\n\n // Try data\n this.dataIndex.removeEntry(id);\n\n // Then try each site\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n siteIndex.removeEntry(id);\n }\n }\n }\n\n /**\n * Get content manifest for a content ID\n */\n getManifest(id: string): ContentManifest | null {\n // Check blocks first\n let manifest = this.blockIndex.getManifest(id);\n if (manifest) return manifest;\n\n // Check data\n manifest = this.dataIndex.getManifest(id);\n if (manifest) return manifest;\n\n // Then check each site\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n manifest = siteIndex.getManifest(id);\n if (manifest) return manifest;\n }\n }\n\n return null;\n }\n\n /**\n * Get a specific locale manifest\n */\n getLocaleVersion(id: string, locale: string): LocaleVersion | null {\n const manifest = this.getManifest(id);\n if (!manifest) return null;\n return manifest.locales[locale] || null;\n }\n\n /**\n * Get site index\n */\n getSiteIndex(site: string): SiteIndex | null {\n return this.siteIndexes[site] || null;\n }\n\n /**\n * Get block index\n */\n getBlockIndex(): BlockIndex {\n return this.blockIndex;\n }\n\n /**\n * Find content by pathname (delegates to site indexes)\n */\n getByPathname(site: string, pathname: string, locale?: string): ContentManifest | null {\n const siteIndex = this.siteIndexes[site];\n return siteIndex ? siteIndex.getByPathname(pathname, locale) : null;\n }\n\n /**\n * Find content by previous pathname (for redirects)\n */\n getByPreviousPathname(site: string, pathname: string, locale?: string): ContentManifest | null {\n const siteIndex = this.siteIndexes[site];\n return siteIndex ? siteIndex.getByPreviousPathname(pathname, locale) : null;\n }\n\n /**\n * Find block by name\n */\n getBlockByName(collection: string, name: string, locale?: string): ContentManifest | null {\n return this.blockIndex.getByName(collection, name, locale);\n }\n\n /**\n * Get data index\n */\n getDataIndex(): DataIndex {\n return this.dataIndex;\n }\n\n /**\n * Find data entry by name\n */\n getDataByName(collection: string, name: string, locale?: string): ContentManifest | null {\n return this.dataIndex.getByName(collection, name, locale);\n }\n\n /**\n * Get all collections for data\n */\n getDataCollections(): Set<string> {\n return this.dataIndex.collections;\n }\n\n /**\n * List all content (for iteration)\n */\n *listAllContent(): Generator<ContentManifest> {\n // Yield all blocks\n yield* this.blockIndex.getAllManifests();\n\n // Yield all data entries\n yield* this.dataIndex.getAllManifests();\n\n // Yield all site entries\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n yield* siteIndex.getAllManifests();\n }\n }\n }\n\n /**\n * Generator for all sites\n */\n *allSites(): Generator<string> {\n for (const site in this.siteIndexes) {\n if (this.siteIndexes[site]) {\n yield site;\n }\n }\n }\n\n /**\n * Get all collections for a site\n */\n getCollectionsForSite(site: string): Set<string> {\n const siteIndex = this.siteIndexes[site];\n return siteIndex ? siteIndex.collections : new Set();\n }\n\n /**\n * Get all collections for blocks\n */\n getBlockCollections(): Set<string> {\n return this.blockIndex.collections;\n }\n\n /**\n * Get default locale for a site\n */\n getDefaultLocale(site: string): string {\n // This method should only be called for pages, but handle gracefully\n if (!site) {\n return this.sitesConfig.globalLocales[0];\n }\n const siteConfig = this.sitesConfig.sites[site];\n return siteConfig?.defaultLocale || this.sitesConfig.globalLocales[0];\n }\n\n /**\n * Find content missing a specific locale\n */\n *findUntranslatedContent(\n targetLocale: string,\n options?: {\n excludeSites?: string[];\n includeUnpublished?: boolean;\n },\n ): Generator<ContentManifest> {\n // Always check blocks as they don't belong to any site\n for (const manifest of this.blockIndex.getAllManifests()) {\n if (!manifest.locales[targetLocale]) {\n // Check if we should include unpublished content\n if (!options?.includeUnpublished) {\n // Need to check if any locale is published\n let hasPublishedLocale = false;\n for (const locale of localesOf(manifest)) {\n if (!locale.unpublishAt || new Date(locale.unpublishAt) > new Date()) {\n hasPublishedLocale = true;\n break;\n }\n }\n if (!hasPublishedLocale) continue;\n }\n yield manifest;\n }\n }\n\n // Check each site\n for (const siteName in this.siteIndexes) {\n const siteIndex = this.siteIndexes[siteName];\n if (!siteIndex || options?.excludeSites?.includes(siteName)) continue;\n\n for (const manifest of siteIndex.getAllManifests()) {\n if (!manifest.locales[targetLocale]) {\n // Check if we should include unpublished content\n if (!options?.includeUnpublished) {\n let hasPublishedLocale = false;\n for (const locale of localesOf(manifest)) {\n if (!locale.unpublishAt || new Date(locale.unpublishAt) > new Date()) {\n hasPublishedLocale = true;\n break;\n }\n }\n if (!hasPublishedLocale) continue;\n }\n yield manifest;\n }\n }\n }\n }\n\n /**\n * Generators for efficient filtering\n */\n\n *getManifestsForKind(kind: 'block' | 'page' | 'data'): Generator<ContentManifest> {\n if (kind === 'block') {\n yield* this.blockIndex.getAllManifests();\n } else if (kind === 'data') {\n yield* this.dataIndex.getAllManifests();\n } else {\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n yield* siteIndex.getAllManifests();\n }\n }\n }\n }\n\n *getManifestsForSite(site: string): Generator<ContentManifest> {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n yield* siteIndex.getAllManifests();\n }\n }\n\n *getManifestsForSiteLocale(site: string, locale: string): Generator<ContentManifest> {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n yield* siteIndex.getManifestsByLocale(locale);\n }\n }\n\n *getManifestsForSiteCollection(site: string, collection: string): Generator<ContentManifest> {\n // For regular sites, we need to filter by collection\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n for (const manifest of siteIndex.getAllManifests()) {\n if (manifest.collection === collection) {\n yield manifest;\n }\n }\n }\n }\n\n *getManifestsForLocale(locale: string): Generator<ContentManifest> {\n // Yield from blocks\n yield* this.blockIndex.getManifestsByLocale(locale);\n\n // Yield from data\n yield* this.dataIndex.getManifestsByLocale(locale);\n\n // Yield from all sites\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n yield* siteIndex.getManifestsByLocale(locale);\n }\n }\n }\n\n *getManifestsForCollection(collection: string): Generator<ContentManifest> {\n // Check blocks first\n yield* this.blockIndex.getManifestsByCollection(collection);\n\n // Check data\n yield* this.dataIndex.getManifestsByCollection(collection);\n\n // Then check all sites\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n for (const manifest of siteIndex.getAllManifests()) {\n if (manifest.collection === collection) {\n yield manifest;\n }\n }\n }\n }\n }\n\n /**\n * Get the count of indexed content entries\n */\n get entryCount(): number {\n let count = this.blockIndex.entryCount;\n count += this.dataIndex.entryCount;\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n count += siteIndex.entryCount;\n }\n }\n return count;\n }\n\n /**\n * Clear all indexes\n */\n clear(): void {\n this.blockIndex.clear();\n this.dataIndex.clear();\n for (const site in this.siteIndexes) {\n const siteIndex = this.siteIndexes[site];\n if (siteIndex) {\n siteIndex.clear();\n }\n }\n }\n}\n","import type { ContentAPI } from './content-api.interface';\nimport type { DataIndex } from './data-index';\nimport type { ContentManifest, CreateResult } from './types';\n\nexport interface DataFilters {\n collection?: string;\n locales?: string[];\n}\n\nexport interface CreateDataInput {\n collection: string;\n name: string;\n meta?: { title?: string; description?: string; [key: string]: unknown };\n locales: {\n [locale: string]: {\n publishAt?: string | null | false;\n unpublishAt?: string | null | false;\n meta?: { title?: string; description?: string; [key: string]: unknown };\n content: {\n data: Record<string, unknown>;\n };\n };\n };\n}\n\nexport class Data {\n constructor(\n private api: ContentAPI,\n private dataIndex: DataIndex,\n ) {}\n\n // Content discovery\n *listContent(filters?: DataFilters): Generator<ContentManifest> {\n // Choose the most efficient method based on filters\n if (filters?.collection) {\n if (filters.locales && filters.locales.length > 0) {\n // Filter by locales after getting collection entries\n for (const manifest of this.dataIndex.getManifestsByCollection(filters.collection)) {\n if (filters.locales.some((locale) => manifest.locales[locale])) {\n yield manifest;\n }\n }\n } else {\n yield* this.dataIndex.getManifestsByCollection(filters.collection);\n }\n } else if (filters?.locales && filters.locales.length > 0) {\n // For multiple locales, we need to check each\n for (const manifest of this.dataIndex.getAllManifests()) {\n if (filters.locales.some((locale) => manifest.locales[locale])) {\n yield manifest;\n }\n }\n } else {\n yield* this.dataIndex.getAllManifests();\n }\n }\n\n // Get all data collections\n get collections(): Set<string> {\n return this.dataIndex.collections;\n }\n\n // Data operations (returns null if not found)\n getByName(collection: string, name: string, locale?: string): ContentManifest | null {\n return this.dataIndex.getByName(collection, name, locale);\n }\n\n // Check if data name is available\n isNameAvailable(collection: string, name: string, excludeId?: string): boolean {\n const existing = this.getByName(collection, name);\n return !existing || existing.id === excludeId;\n }\n\n // Get the ID of content that conflicts with a data name\n getNameConflict(collection: string, name: string, excludeId?: string): string | null {\n const existing = this.getByName(collection, name);\n if (existing && existing.id !== excludeId) {\n return existing.id;\n }\n return null;\n }\n\n // Check if data name is valid\n isDataNameValid(dataName: string): boolean {\n // Data names must not be empty\n if (!dataName || dataName.trim() === '') {\n return false;\n }\n\n // Data names must not contain dots (would interfere with locale suffixes)\n if (dataName.includes('.')) {\n return false;\n }\n\n // Data names must not contain path separators\n if (dataName.includes('/') || dataName.includes('\\\\')) {\n return false;\n }\n\n // Data names should only contain alphanumeric, hyphens, underscores\n return /^[a-zA-Z0-9_-]+$/.test(dataName);\n }\n\n // Create data entry with name validation\n async create(input: CreateDataInput): Promise<CreateResult> {\n // Validate data name\n if (!this.isDataNameValid(input.name)) {\n return {\n success: false,\n reason: 'invalid_name',\n error: new Error(`Invalid data name: ${input.name}`),\n };\n }\n\n // Check if name is already taken in any locale\n const existing = this.getByName(input.collection, input.name);\n if (existing) {\n return {\n success: false,\n reason: 'name_taken',\n error: new Error(`Data name ${input.name} already exists in collection ${input.collection}`),\n };\n }\n\n // Create the content\n return this.api.createContent({\n kind: 'data',\n collection: input.collection,\n type: 'json',\n name: input.name,\n meta: input.meta,\n locales: input.locales,\n });\n }\n}\n","/**\n * Zero-allocation JSON whitespace-skipping stream transform\n * Skips whitespace outside of JSON strings, preserving whitespace inside strings\n * Optimized to process multiple bytes at once when possible\n */\nexport class JsonWhitespaceSkippingView {\n private inString = false;\n private escaped = false;\n private singleByte = new Uint8Array(1); // Reused allocation for single bytes\n\n constructor(private downstream: { update(data: Uint8Array): void }) {}\n\n /**\n * Process a single byte from JSON stream\n * @param byte - The byte to process\n */\n updateByte(byte: number): void {\n let shouldInclude = false;\n\n if (this.inString) {\n // Inside string: always include the byte\n shouldInclude = true;\n\n if (this.escaped) {\n this.escaped = false;\n } else if (byte === 0x5c) {\n // backslash\n this.escaped = true;\n } else if (byte === 0x22) {\n // quote\n this.inString = false;\n }\n } else {\n // Outside string: check for string start or skip whitespace\n if (byte === 0x22) {\n // 0x22 is the double quote character (\")\n // quote\n this.inString = true;\n shouldInclude = true;\n }\n // Check tab (0x09) first as it's the most common whitespace in our tab-indented VXJSON files\n // Then space (0x20), newline (0x0a), carriage return (0x0d)\n else if (byte !== 0x09 && byte !== 0x20 && byte !== 0x0a && byte !== 0x0d) {\n // Not whitespace, include it\n shouldInclude = true;\n }\n // Skip whitespace outside strings\n }\n\n if (shouldInclude) {\n this.singleByte[0] = byte;\n this.downstream.update(this.singleByte);\n }\n }\n\n /**\n * Process a buffer range with simple batching\n * Collects consecutive bytes that should be included\n * @param buffer - The buffer to process\n * @param start - Start position (inclusive)\n * @param end - End position (exclusive)\n */\n updateBuffer(buffer: Uint8Array, start = 0, end = buffer.length): void {\n let pos = start;\n let runStart = start;\n\n while (pos < end) {\n const byte = buffer[pos];\n let shouldInclude = false;\n\n if (this.inString) {\n // Inside string: always include\n shouldInclude = true;\n\n if (this.escaped) {\n this.escaped = false;\n } else if (byte === 0x5c) {\n // backslash\n this.escaped = true;\n } else if (byte === 0x22) {\n // quote - end of string\n this.inString = false;\n } else {\n // Regular character - use indexOf to skip to next quote\n pos++;\n let searchPos = pos;\n\n while (searchPos < end) {\n const quotePos = buffer.indexOf(0x22, searchPos);\n if (quotePos === -1 || quotePos >= end) {\n // No more quotes\n pos = end;\n break;\n }\n\n // Count consecutive backslashes before the quote\n let backslashCount = 0;\n let checkPos = quotePos - 1;\n while (checkPos >= 0 && buffer[checkPos] === 0x5c) {\n backslashCount++;\n checkPos--;\n }\n\n if (backslashCount % 2 === 0) {\n // Even backslashes (including 0) - quote is not escaped\n pos = quotePos + 1;\n this.inString = false;\n break;\n }\n // Odd backslashes - quote is escaped, continue searching\n searchPos = quotePos + 1;\n }\n continue; // Skip the pos++ at the bottom\n }\n } else {\n // Outside string\n if (byte === 0x22) {\n // quote - start of string\n this.inString = true;\n shouldInclude = true;\n // Check tab (0x09) first as it's the most common whitespace in our tab-indented VXJSON files\n // Then space (0x20), newline (0x0a), carriage return (0x0d)\n } else if (byte !== 0x09 && byte !== 0x20 && byte !== 0x0a && byte !== 0x0d) {\n // Not whitespace\n shouldInclude = true;\n }\n }\n\n if (shouldInclude) {\n // Continue the run\n pos++;\n } else {\n // End of run - send what we have\n if (pos > runStart) {\n this.downstream.update(buffer.subarray(runStart, pos));\n }\n pos++;\n runStart = pos;\n }\n }\n\n // Send any remaining bytes\n if (pos > runStart) {\n this.downstream.update(buffer.subarray(runStart, pos));\n }\n }\n\n /**\n * Reset the parser state\n */\n reset(): void {\n this.inString = false;\n this.escaped = false;\n }\n}\n","/**\n * Convert bytes to URL-safe base64\n * Replaces + with -, / with _, and removes = padding\n */\nexport function toUrlSafeBase64(bytes: Uint8Array): string {\n const b64 = Buffer.from(bytes).toString('base64');\n const buf = Buffer.from(b64, 'ascii');\n let write = 0;\n for (let read = 0; read < buf.length; read++) {\n const c = buf[read];\n if (c === 0x2b) {\n // '+'\n buf[write++] = 0x2d; // '-'\n } else if (c === 0x2f) {\n // '/'\n buf[write++] = 0x5f; // '_'\n } else if (c === 0x3d) {\n // '='\n // skip padding\n } else {\n buf[write++] = c;\n }\n }\n return buf.subarray(0, write).toString('ascii');\n}\n\n/**\n * Convert BigInt to URL-safe base64\n * @param value - The BigInt value to convert\n * @returns URL-safe base64 string representation\n */\nexport function bigintToUrlSafeBase64(value: bigint): string {\n // Convert BigInt to 8-byte buffer\n const hashBuffer = new Uint8Array(8);\n const dataView = new DataView(hashBuffer.buffer);\n dataView.setBigUint64(0, value, false); // big-endian\n return toUrlSafeBase64(hashBuffer);\n}\n","import { xxh3 } from '@node-rs/xxhash';\nimport { createHash } from 'crypto';\nimport { JsonWhitespaceSkippingView } from './json-whitespace-view';\nimport { bigintToUrlSafeBase64, toUrlSafeBase64 } from './url-safe-base64';\n\n/**\n * Dual ETag system for content API\n * - Meta ETag: Based on non-derived LocaleManifest fields (using xxHash)\n * - Content ETag: Based on ContentProp.content (using SHA256)\n * Both skip whitespace to allow pretty-printing without affecting hashes\n *\n * Format: \"metaEtag.contentEtag\" in query strings\n */\n\n/**\n * Calculate metadata ETag using xxHash from buffer view\n * @param buffer - The file buffer view\n * @param start - Start position (inclusive)\n * @param end - End position (exclusive), or -1 for entire buffer\n */\nexport function calculateMetaEtagFromBuffer(buffer: Uint8Array, start = 0, end = -1): string {\n const actualEnd = end === -1 ? buffer.length : end;\n const hasher = xxh3.Xxh3.withSeed(0n);\n const jsonView = new JsonWhitespaceSkippingView(hasher);\n\n jsonView.updateBuffer(buffer, start, actualEnd);\n\n const hashValue = hasher.digest();\n return bigintToUrlSafeBase64(hashValue);\n}\n\n/**\n * Calculate content ETag using SHA256 from buffer view\n * @param buffer - The file buffer view\n * @param start - Start position (inclusive)\n * @param end - End position (exclusive), or -1 for entire buffer\n */\nexport function calculateContentEtagFromBuffer(buffer: Uint8Array, start = 0, end = -1): string {\n const actualEnd = end === -1 ? buffer.length : end;\n const hasher = createHash('sha256');\n const jsonView = new JsonWhitespaceSkippingView(hasher);\n\n jsonView.updateBuffer(buffer, start, actualEnd);\n\n return toUrlSafeBase64(hasher.digest() as Uint8Array);\n}\n\nconst dashCode = '-'.charCodeAt(0); // 45\nconst newlineCode = '\\n'.charCodeAt(0); // 10\n\n/**\n * Find the content start position in MDX buffer (after second ---)\n * @param buffer - The MDX content buffer\n * @returns Position where content starts, or -1 if not found\n */\nexport function findMdxContentStartPosition(buffer: Uint8Array): number {\n let dashCount = 0;\n let i = 0;\n\n // Look for the second occurrence of \"---\\n\"\n while (i < buffer.length - 4) {\n if (\n buffer[i] === dashCode &&\n buffer[i + 1] === dashCode &&\n buffer[i + 2] === dashCode &&\n buffer[i + 3] === newlineCode\n ) {\n dashCount++;\n if (dashCount === 2) {\n // Found second ---, now look for the following newline to get content start\n i += 4; // Skip past \"---\\n\"\n if (i < buffer.length && buffer[i] === newlineCode) {\n return i + 1; // Return position after the empty line\n }\n return i; // Return position right after \"---\\n\"\n }\n i += 4; // Skip this \"---\\n\" and continue looking\n } else {\n // Use indexOf to skip ahead faster instead of incrementing by 1\n const nextDashPos = buffer.indexOf(dashCode, i + 1);\n if (nextDashPos === -1) {\n break; // No more dashes found\n }\n i = nextDashPos;\n }\n }\n\n return -1; // Not found\n}\n\n/**\n * Calculate both ETags from an MDX buffer\n *\n * MDX files use YAML frontmatter which has different characteristics than JSON:\n * - YAML does not require quotes around keys or string values\n * - YAML allows multiple formatting styles (flow vs block style)\n * - YAML field order is not significant for parsing\n *\n * Unlike VXJSON which requires \"content\" to be the last field and needs special\n * parsing to validate structure, YAML frontmatter can be hashed as-is because:\n * 1. The frontmatter boundaries are clearly delimited by ---\n * 2. Different YAML formatting of the same data SHOULD produce different hashes\n * (e.g., flow style [a,b] vs block style with dashes)\n * 3. There's no requirement to validate field ordering\n *\n * This means we can directly hash the YAML bytes without any whitespace\n * normalization or parsing, which is both simpler and more correct.\n *\n * @param buffer - The complete file buffer\n * @param contentStartPos - Position where content starts (after second ---), or -1 if no content\n */\nexport function calculateEtagsFromMdxBuffer(\n buffer: Uint8Array,\n contentStartPos: number,\n): {\n metaEtag: string;\n contentEtag: string;\n} {\n if (contentStartPos === -1) {\n // No content, only frontmatter - hash entire buffer as metadata\n const hasher = xxh3.Xxh3.withSeed(0n);\n hasher.update(buffer);\n const hashBigInt = hasher.digest();\n const metaEtag = bigintToUrlSafeBase64(hashBigInt);\n\n return {\n metaEtag,\n contentEtag: calculateContentEtagFromBuffer(new Uint8Array(0)), // empty content\n };\n }\n\n // For MDX, we hash the YAML frontmatter as-is (including the --- markers)\n // This is different from JSON where we need to parse and validate structure\n const metaHasher = xxh3.Xxh3.withSeed(0n);\n metaHasher.update(buffer.subarray(0, contentStartPos));\n const metaHashBigInt = metaHasher.digest();\n const metaEtag = bigintToUrlSafeBase64(metaHashBigInt);\n\n // Content is everything after the second ---\n const contentHasher = createHash('sha256');\n contentHasher.update(buffer.subarray(contentStartPos));\n const contentEtag = toUrlSafeBase64(contentHasher.digest() as Uint8Array);\n\n return {\n metaEtag,\n contentEtag,\n };\n}\n\n/**\n * Combined ETag structure\n */\nexport interface DualEtag {\n meta: string;\n content: string;\n}\n\n/**\n * Format dual ETags for query string: \"meta.content\"\n */\nexport function formatDualEtag(etags: DualEtag): string {\n return `${etags.meta}.${etags.content}`;\n}\n\n/**\n * Parse dual ETags from query string: \"meta.content\"\n */\nexport function parseDualEtag(etag: string): DualEtag | null {\n const parts = etag.split('.');\n if (parts.length !== 2) return null;\n\n return {\n meta: parts[0],\n content: parts[1],\n };\n}\n\n/**\n * Check if etag matches either meta or content\n */\nexport function matchesEtag(\n providedEtag: string,\n currentMeta: string,\n currentContent: string,\n): {\n matches: boolean;\n metaChanged: boolean;\n contentChanged: boolean;\n} {\n const parsed = parseDualEtag(providedEtag);\n if (!parsed) {\n return {\n matches: false,\n metaChanged: true,\n contentChanged: true,\n };\n }\n\n const metaChanged = parsed.meta !== currentMeta;\n const contentChanged = parsed.content !== currentContent;\n\n return {\n matches: !metaChanged && !contentChanged,\n metaChanged,\n contentChanged,\n };\n}\n","import { xxh3 } from '@node-rs/xxhash';\nimport { createHash } from 'crypto';\nimport sortKeys from 'sort-keys';\nimport { JsonWhitespaceSkippingView } from './json-whitespace-view';\nimport type { ContentData, ContentMeta, VXJSONFile } from './types';\nimport { bigintToUrlSafeBase64, toUrlSafeBase64 } from './url-safe-base64';\n\n// Reusable TextDecoder instance - safe to reuse as it's stateless\nconst textDecoder = new TextDecoder();\n\n// Pre-allocated content marker for efficiency\nconst CONTENT_MARKER = new TextEncoder().encode('\"content\":');\n\n/**\n * Calculate metadata ETag using xxHash from buffer view\n * @param buffer - The file buffer view\n * @param start - Start position (inclusive)\n * @param end - End position (exclusive), or -1 for entire buffer\n */\nfunction calculateMetaEtagFromBuffer(buffer: Uint8Array, start = 0, end = -1): string {\n const actualEnd = end === -1 ? buffer.length : end;\n const hasher = xxh3.Xxh3.withSeed(0n);\n const jsonView = new JsonWhitespaceSkippingView(hasher);\n\n jsonView.updateBuffer(buffer, start, actualEnd);\n\n const hashValue = hasher.digest();\n return bigintToUrlSafeBase64(hashValue);\n}\n\n/**\n * Calculate both ETags from a VXJSON buffer using views\n * Finds the \"content\" field position and validates it's the last field\n * @param buffer - The complete file buffer\n * @returns Result with ETags or validation error\n */\nfunction calculateEtagsFromVXJSONBuffer(\n buffer: Uint8Array,\n allowTruncated = false,\n):\n | { success: true; metaEtag: string; contentEtag?: string; contentStartPos: number }\n | { success: false; error: 'content_not_last' | 'invalid_json' } {\n let pos = 0;\n let depth = 0;\n let inString = false;\n let escaped = false;\n let contentStartPos = -1;\n let foundContentAtRoot = false;\n let expectingKey = false; // At root level, are we expecting a key?\n let expectingValue = false; // At root level, are we expecting a value?\n let keyStart = -1;\n\n // Skip whitespace and find opening brace\n while (\n pos < buffer.length &&\n (buffer[pos] === 0x20 || buffer[pos] === 0x09 || buffer[pos] === 0x0a || buffer[pos] === 0x0d)\n ) {\n pos++;\n }\n\n if (pos >= buffer.length || buffer[pos] !== 0x7b) {\n // {\n return { success: false, error: 'invalid_json' };\n }\n\n depth = 1;\n expectingKey = true; // After { we expect a key\n pos++;\n\n // Parse JSON structure\n while (pos < buffer.length && depth > 0) {\n const byte = buffer[pos];\n\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (byte === 0x5c) {\n // backslash\n escaped = true;\n } else if (byte === 0x22) {\n // quote\n inString = false;\n\n // If we were in a root key, check if it's \"content\"\n if (depth === 1 && expectingKey && keyStart >= 0) {\n const keyLength = pos - keyStart + 1; // +1 to include current quote\n\n // First check if we already found content and this is any key after it\n if (foundContentAtRoot) {\n // Check if this is another \"content\" key (duplicate)\n if (keyLength === 9) {\n let isContent = true;\n for (let i = 0; i < 7; i++) {\n if (buffer[keyStart + 1 + i] !== CONTENT_MARKER[i + 1]) {\n isContent = false;\n break;\n }\n }\n if (isContent) {\n // Duplicate content key\n return { success: false, error: 'invalid_json' };\n }\n }\n // Any other key after content is an error\n return { success: false, error: 'content_not_last' };\n }\n\n // Check if this key is \"content\" (7 chars + 2 quotes = 9 total)\n if (keyLength === 9) {\n let isContent = true;\n // Compare \"content\" part (skip opening quote)\n for (let i = 0; i < 7; i++) {\n if (buffer[keyStart + 1 + i] !== CONTENT_MARKER[i + 1]) {\n isContent = false;\n break;\n }\n }\n\n if (isContent) {\n // Found \"content\" at root level for the first time\n foundContentAtRoot = true;\n contentStartPos = keyStart; // Start of the quoted key\n }\n }\n\n expectingKey = false;\n expectingValue = true; // After a key, we expect : then value\n keyStart = -1;\n }\n }\n } else {\n // Not in string\n if (byte === 0x22) {\n // quote\n inString = true;\n\n // Check if this is a root-level key\n if (depth === 1 && expectingKey) {\n keyStart = pos;\n }\n } else if (byte === 0x7b || byte === 0x5b) {\n // { or [\n depth++;\n if (depth === 1 && expectingValue) {\n expectingValue = false; // We got our value\n }\n } else if (byte === 0x7d || byte === 0x5d) {\n // } or ]\n depth--;\n if (depth === 0) {\n break; // Done parsing\n }\n } else if (byte === 0x3a && depth === 1) {\n // : at root level\n if (!expectingValue) {\n return { success: false, error: 'invalid_json' };\n }\n // After : we're still expecting a value\n } else if (byte === 0x2c && depth === 1) {\n // , at root level\n expectingKey = true;\n expectingValue = false;\n } else if (depth === 1 && expectingValue && byte !== 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d) {\n // Non-whitespace at root level when expecting value\n // Could be number, true, false, null\n expectingValue = false; // We're consuming the value\n }\n }\n\n pos++;\n }\n\n // For truncated JSON (4KB parsing), we can still succeed if we found the content position\n const isTruncated = depth !== 0;\n\n // If JSON is truncated but we don't allow it, return invalid_json\n if (isTruncated && !allowTruncated) {\n return { success: false, error: 'invalid_json' };\n }\n\n if (contentStartPos === -1) {\n // No content field found - this is valid for both complete and truncated JSON\n return {\n success: true,\n metaEtag: calculateMetaEtagFromBuffer(buffer),\n contentStartPos: -1,\n };\n }\n\n // Found content field - proceed with ETag calculation\n if (isTruncated) {\n // For truncated JSON, we can still calculate metadata ETag up to content position\n return {\n success: true,\n metaEtag: calculateMetaEtagFromBuffer(buffer, 0, contentStartPos),\n contentStartPos,\n // Don't calculate contentEtag for truncated content\n };\n }\n\n // Find the end of metadata (before \"content\":)\n let metaEnd = contentStartPos - 1;\n while (metaEnd > 0) {\n const byte = buffer[metaEnd];\n if (byte === 0x2c || byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d) {\n metaEnd--;\n } else {\n break;\n }\n }\n\n // Hash metadata section: wrap in { } and exclude content field\n const metaHasher = xxh3.Xxh3.withSeed(0n);\n const metaView = new JsonWhitespaceSkippingView(metaHasher);\n const openBrace = new Uint8Array([0x7b]); // {\n const closeBrace = new Uint8Array([0x7d]); // }\n\n metaHasher.update(openBrace);\n metaView.updateBuffer(buffer, 1, metaEnd); // Skip opening brace, stop before content\n metaHasher.update(closeBrace);\n\n const metaHashValue = metaHasher.digest();\n const metaEtag = bigintToUrlSafeBase64(metaHashValue);\n\n // Hash content section: wrap as {\"content\": ... }\n const contentHasher = createHash('sha256');\n const contentView = new JsonWhitespaceSkippingView(contentHasher);\n\n contentHasher.update(openBrace); // {\n contentView.updateBuffer(buffer, contentStartPos, buffer.length - 1); // content field to end, exclude final }\n contentHasher.update(closeBrace); // }\n\n const contentEtag = toUrlSafeBase64(contentHasher.digest() as Uint8Array);\n\n return {\n success: true,\n metaEtag,\n contentEtag,\n contentStartPos,\n };\n}\n\n/**\n * VXJSON (Variant JSON) module for parsing and serializing VXJSON files\n *\n * VXJSON is a specialized JSON format that guarantees:\n * 1. The root is always an object (never an array or primitive)\n * 2. The \"content\" field always comes last in the object\n * 3. Field order is deterministic for consistent ETag calculation\n * 4. Metadata fits within 4085 bytes, ensuring \"content\" field is found within first 4KB\n * 5. First 4KB must either be complete JSON OR end exactly with '\"content\":'\n *\n * This format enables efficient 4KB parsing where only the first 4KB of a file\n * needs to be read to extract all metadata and locate the content position.\n * The constraint that 4KB reads must end with '\"content\":' ensures reliable parsing.\n *\n * This module centralizes all VXJSON-specific logic including:\n * - Parsing partial buffers (first 4KB for indexing)\n * - Finding content position for ETag calculation\n * - Serializing with proper field ordering and size validation\n * - Calculating ETags from buffers\n */\n\n/**\n * VXJSON static utilities for parsing and validating VXJSON files\n */\nexport class VXJSON {\n /**\n * Parse first 4KB of VXJSON content from buffer\n * Used during indexing to extract metadata without loading full content\n *\n * VXJSON format requirement: first 4KB must either be complete JSON OR end with '\"content\":'\n * This ensures reliable parsing and validation.\n */\n static parse4KB(\n buffer: Uint8Array,\n bytesRead: number,\n ): {\n id?: string;\n created?: string;\n modified?: string;\n publishAt?: string;\n unpublishAt?: string;\n previousPathnames?: Record<string, string>;\n pathname?: string;\n name?: string;\n meta: ContentMeta;\n content?: ContentData;\n contentStartPos?: number; // Position where \"content\": starts in buffer\n } {\n // Complete JSON (either small file or ends with })\n if (bytesRead < 4096 || buffer[bytesRead - 1] === 0x7d) {\n // 0x7D = '}'\n const partialContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const data = JSON.parse(partialContent);\n\n // Find content position for ETag calculation\n let contentStartPos = -1;\n if (data.content !== undefined) {\n const etagResult = calculateEtagsFromVXJSONBuffer(buffer.subarray(0, bytesRead));\n if (etagResult.success) {\n contentStartPos = etagResult.contentStartPos;\n }\n }\n\n return {\n id: data.id,\n created: data.created,\n modified: data.modified,\n publishAt: data.publishAt,\n unpublishAt: data.unpublishAt,\n previousPathnames: data.previousPathnames,\n pathname: data.pathname,\n name: data.name,\n meta: data.meta || {},\n content: data.content,\n contentStartPos,\n };\n }\n\n // Truncated 4KB read - use calculateETags to validate and find content position\n const etagResult = calculateEtagsFromVXJSONBuffer(buffer.subarray(0, bytesRead), true); // Allow truncated for 4KB parsing\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format: ${etagResult.error}. This violates the VXJSON specification.`);\n }\n\n const contentStartPos = etagResult.contentStartPos;\n\n // Find end of metadata by working backwards from content position\n let metadataEnd = contentStartPos;\n while (metadataEnd > 0) {\n const byte = buffer[metadataEnd - 1];\n if (byte === 0x2c) {\n // comma\n metadataEnd--;\n break;\n }\n if (byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d) {\n // whitespace\n metadataEnd--;\n } else {\n break;\n }\n }\n\n // Create metadata-only JSON by adding closing brace\n const metadataBuffer = new Uint8Array(metadataEnd + 1);\n metadataBuffer.set(buffer.subarray(0, metadataEnd));\n metadataBuffer[metadataEnd] = 0x7d; // }\n\n const partialContent = textDecoder.decode(metadataBuffer);\n\n const data = JSON.parse(partialContent);\n return {\n id: data.id,\n created: data.created,\n modified: data.modified,\n publishAt: data.publishAt,\n unpublishAt: data.unpublishAt,\n previousPathnames: data.previousPathnames,\n pathname: data.pathname,\n name: data.name,\n meta: data.meta || {},\n contentStartPos,\n };\n }\n\n /**\n * Find the position of the \"content\" field in a VXJSON buffer\n * Returns -1 if not found\n */\n static findContentPosition(buffer: Uint8Array): number {\n const etagResult = calculateEtagsFromVXJSONBuffer(buffer);\n if (etagResult.success) {\n return etagResult.contentStartPos;\n }\n return -1;\n }\n\n /**\n * Calculate ETags for a VXJSON buffer\n * Returns null if the buffer is not valid VXJSON\n */\n static calculateEtagsOnly(buffer: Uint8Array): { metaEtag: string; contentEtag?: string } | null {\n const result = calculateEtagsFromVXJSONBuffer(buffer);\n if (!result.success) {\n return null;\n }\n\n return {\n metaEtag: result.metaEtag,\n contentEtag: result.contentEtag,\n };\n }\n\n /**\n * Create a dual ETag string from a VXJSON buffer\n * Returns null if the buffer is not valid VXJSON\n */\n static createEtag(buffer: Uint8Array): string | null {\n const etags = VXJSON.calculateEtagsOnly(buffer);\n if (!etags) {\n return null;\n }\n\n return etags.contentEtag ? `${etags.metaEtag}.${etags.contentEtag}` : etags.metaEtag;\n }\n\n /**\n * Validate that a VXJSON buffer has the correct structure\n * (content field must be last)\n */\n static isValid(buffer: Uint8Array): boolean {\n const result = calculateEtagsFromVXJSONBuffer(buffer);\n return result.success;\n }\n\n /**\n * Parse a complete VXJSON file from string\n */\n static parse(content: string): VXJSONFile {\n return JSON.parse(content);\n }\n\n /**\n * Parse a complete VXJSON file from buffer\n */\n static parseBuffer(buffer: Uint8Array): VXJSONFile {\n const content = textDecoder.decode(buffer);\n return VXJSON.parse(content);\n }\n\n /**\n * Calculate both ETags from a VXJSON buffer using views\n * Finds the \"content\" field position and validates it's the last field\n * @param buffer - The complete file buffer\n * @returns Result with ETags or validation error\n */\n static calculateETags = calculateEtagsFromVXJSONBuffer;\n\n /**\n * Calculate a simple single etag from the entire buffer\n * Used for data files that don't follow the content-last convention\n */\n static calculateSimpleEtag(buffer: Uint8Array): string {\n return calculateMetaEtagFromBuffer(buffer);\n }\n\n /**\n * Serialize a VXJSONFile to VXJSON format string\n * Ensures content field is last and enforces 4KB constraint efficiently\n */\n static serialize(data: VXJSONFile): string {\n // Extract content to add it last\n const { content, ...metadataFields } = data;\n\n // Ensure content field exists (required for VXJSON format)\n if (content === undefined || content === null) {\n throw new Error('VXJSON format requires a \"content\" field');\n }\n\n // Sort all metadata fields alphabetically and serialize with tab indentation\n // Use a replacer function to filter out empty strings\n const sortedMetadata = sortKeys(metadataFields, { deep: true });\n const metadataJson = JSON.stringify(\n sortedMetadata,\n (_key, value) => {\n // Filter out empty strings at any level\n if (value === '') {\n return undefined;\n }\n return value;\n },\n '\\t',\n );\n\n // Serialize content wrapped in an object to get proper indentation\n const wrappedContent = JSON.stringify({ c: sortKeys(content, { deep: true }) }, null, '\\t');\n // Extract just the content part, removing the wrapper\n // This transforms: '{\\n \"c\": {\\n \"puckData\": ...\\n }\\n}'\n // Into: '{\\n \"puckData\": ...\\n }'\n const contentJson = wrappedContent.slice(wrappedContent.indexOf(': ') + 2, -2);\n\n // Remove the closing } and newline from metadata\n const metadataWithoutClosing = metadataJson.slice(0, -2); // Remove \\n}\n const contentFieldPrefix = ',\\n\\t\"content\": ';\n const contentKeyPosition = metadataWithoutClosing.length + 1 + '\\n\\t'.length; // Position of \"content\":\n\n // VXJSON constraint: \"content\": must appear within first 4KB\n const maxContentKeyPosition = 4096 - '\"content\":'.length; // 4086\n if (contentKeyPosition > maxContentKeyPosition) {\n throw new Error(\n 'VXJSON format violation: metadata too large. ' +\n `\"content\" field would start at position ${contentKeyPosition}, ` +\n `but must start within ${maxContentKeyPosition} bytes. ` +\n `Reduce metadata size by ${contentKeyPosition - maxContentKeyPosition} bytes.`,\n );\n }\n\n // Build final JSON string efficiently\n return `${metadataWithoutClosing}${contentFieldPrefix}${contentJson}\\n}`;\n }\n}\n","import { type FileHandle, mkdir, open, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';\nimport { xxh3 } from '@node-rs/xxhash';\nimport matter from 'gray-matter';\nimport { dirname, join, resolve } from 'path';\nimport sortKeys from 'sort-keys';\nimport { Blocks } from './blocks';\nimport type { ContentAPI } from './content-api.interface';\nimport { filterContentWithIndexes } from './content-filters';\nimport { ContentIndex } from './content-index';\nimport {\n analyzeUpdateScope,\n buildLocaleVersion,\n buildPathnameHistory,\n generateContentId,\n isContentPublished,\n shouldUpdateModifiedTimestamp,\n UPDATE_SCOPE,\n updatePublishDates,\n validateAndPrepareMetadata,\n validateCreateContent,\n} from './content-operations';\nimport { localesOf, mapSiteNames, resolvePublishDate, serializeMdxWithFrontmatter } from './content-utils';\nimport { Data } from './data';\nimport { calculateEtagsFromMdxBuffer, findMdxContentStartPosition, parseDualEtag } from './etag-utils';\nimport { Site } from './site';\nimport type {\n BatchOperationResult,\n BatchResult,\n ContentAPIOptions,\n ContentData,\n ContentEntry,\n ContentIdentity,\n ContentManifest,\n ContentMeta,\n ContentProp,\n CreateContentInput,\n CreateResult,\n DeleteLocaleInput,\n DeleteResult,\n FindOptions,\n GlobalFilters,\n LocaleFileData,\n LocalePathData,\n LocaleVersion,\n LocalizedEntry,\n LocalizedManifest,\n SitesConfig,\n UpdateLocaleInput,\n UpdateResult,\n VXJSONFile,\n} from './types';\n\ninterface ReindexResult {\n filesProcessed: number;\n filesSkipped: number;\n filesDeleted?: number;\n errors?: number;\n // Return manifests of updated locales (without content)\n updated: LocalizedManifest[];\n deleted?: Array<{ id: string; locale: string; kind: 'page' | 'block' | 'data' }>;\n}\n\nimport { VXJSON } from './vxjson';\n\n// Helper to ensure we have an Error object\nfunction ensureError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n return new Error(String(error));\n}\n\n// Reusable TextDecoder instance - safe to reuse as it's stateless\nconst textDecoder = new TextDecoder();\n\n// Parse 4KB MDX content - extracts frontmatter from buffer\nfunction parse4KBMDX(\n buffer: Uint8Array,\n bytesRead: number,\n): {\n id?: string;\n created?: string;\n modified?: string;\n publishAt?: string;\n unpublishAt?: string;\n meta: ContentMeta;\n contentStartPos?: number; // Position where content starts (after second ---)\n} {\n // Only convert to string what we need\n const partialContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const { data: frontmatter } = matter(partialContent);\n\n // Find where content starts (after second ---)\n const delimiter = new TextEncoder().encode('---');\n let delimiterCount = 0;\n let contentStartPos = -1;\n\n for (let i = 0; i <= bytesRead - delimiter.length; i++) {\n let match = true;\n for (let j = 0; j < delimiter.length; j++) {\n if (buffer[i + j] !== delimiter[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n delimiterCount++;\n if (delimiterCount === 2) {\n // Skip past --- and newline\n contentStartPos = i + delimiter.length;\n while (contentStartPos < bytesRead && (buffer[contentStartPos] === 0x0a || buffer[contentStartPos] === 0x0d)) {\n contentStartPos++;\n }\n break;\n }\n }\n }\n\n // Extract special fields and treat the rest as metadata\n const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;\n\n return {\n id,\n created,\n modified,\n publishAt,\n unpublishAt,\n meta: metaFields as ContentMeta, // All other fields are metadata\n contentStartPos,\n };\n}\n\n/**\n * FileSystem-based Content API Implementation\n *\n * Stores content as files on disk in a git-friendly format:\n * - Pages: /{site}/pages/{filename}.{locale}.vxjson\n * - Blocks: /blocks/{collection}/{filename}.{locale}.{mdx|vxjson}\n *\n * ## Indexing\n *\n * Content is indexed at startup for performance. The index is cached per\n * content root path and cleared when the process restarts.\n *\n * ## Read-Repair\n *\n * Since files can be modified externally (git, editors), this implementation:\n *\n * 1. Repairs invalid VXJSON files (ensures \"content\" field is last)\n * 2. Adds missing required fields (id, created, modified)\n * 3. Handles files added after initial indexing\n * 4. Updates the index when files are repaired or discovered\n *\n * ## Performance\n *\n * - Initial indexing reads only first 4KB of each file\n * - Full content is loaded on demand\n * - ETags are calculated using streaming for efficiency\n */\nexport class FileSystemContentAPI implements ContentAPI {\n private contentRoot: string;\n private absoluteContentRoot: string;\n private contentIndex: ContentIndex;\n readonly sitesConfig: SitesConfig;\n readonly blocks: Blocks;\n readonly data: Data;\n private readonly sites: Record<string, Site>;\n\n // Getter for testing purposes\n get normalizedContentRoot(): string {\n return this.contentRoot;\n }\n\n private constructor(\n contentRoot: string,\n canvasDir: string | undefined,\n sitesConfig: SitesConfig,\n contentIndex: ContentIndex,\n ) {\n // Normalize contentRoot: remove ./ prefix for relative paths, keep absolute paths as-is\n if (contentRoot.startsWith('./')) {\n this.contentRoot = contentRoot.slice(2);\n } else if (contentRoot.startsWith('/')) {\n // Absolute path, keep as-is\n this.contentRoot = contentRoot;\n } else {\n // Already normalized relative path\n this.contentRoot = contentRoot;\n }\n\n // Store absolute path for file operations\n this.absoluteContentRoot = resolve(this.contentRoot);\n\n // TODO: Use canvasDir for canvas/unlinked components\n this.sitesConfig = sitesConfig;\n this.contentIndex = contentIndex;\n\n // Initialize blocks\n this.blocks = new Blocks(this, this.contentIndex.getBlockIndex());\n\n // Initialize data\n this.data = new Data(this, this.contentIndex.getDataIndex());\n\n // Initialize all sites\n this.sites = mapSiteNames(sitesConfig, (siteName) => {\n const siteIndex = this.contentIndex.getSiteIndex(siteName);\n if (!siteIndex) {\n throw new Error(`Site index not found for ${siteName}`);\n }\n return new Site(siteName, this, siteIndex);\n });\n }\n\n static async create(options: ContentAPIOptions): Promise<FileSystemContentAPI> {\n const { canvasDir } = options;\n // Keep contentRoot as provided (will be normalized in constructor)\n const contentRoot = options.contentRoot;\n\n // For file operations, we need the absolute path\n const absoluteContentRoot = resolve(contentRoot);\n\n // Load sites config\n const sitesPath = join(absoluteContentRoot, 'sites.json');\n let sitesConfig: SitesConfig;\n try {\n const content = await readFile(sitesPath, 'utf-8');\n const parsed = JSON.parse(content);\n\n // Validate the structure\n if (!parsed.sites || typeof parsed.sites !== 'object') {\n console.warn(\n `Warning: sites.json has invalid structure at ${sitesPath}. Expected 'sites' property. Using default configuration.`,\n );\n sitesConfig = { sites: {}, globalLocales: ['en'] };\n } else if (!parsed.globalLocales || !Array.isArray(parsed.globalLocales)) {\n console.warn(\n `Warning: sites.json is missing 'globalLocales' array at ${sitesPath}. Using default global locales.`,\n );\n sitesConfig = {\n sites: parsed.sites,\n globalLocales: ['en'],\n };\n } else {\n sitesConfig = parsed;\n }\n } catch (error) {\n // Handle missing sites.json gracefully\n console.warn(`Warning: sites.json is missing at ${sitesPath}. Using empty configuration.`);\n sitesConfig = { sites: {}, globalLocales: ['en'] };\n }\n\n // Get cached content index or create new one\n // Use the normalized contentRoot for cache key\n const normalizedContentRoot = contentRoot.startsWith('./') ? contentRoot.slice(2) : contentRoot;\n const contentIndex = await ContentIndex.getCachedOrCreate(normalizedContentRoot, sitesConfig);\n\n // Create instance (not cached)\n const api = new FileSystemContentAPI(contentRoot, canvasDir, sitesConfig, contentIndex);\n\n // Index all content files (only if index is empty)\n if (contentIndex.entryCount === 0) {\n await api.indexAllContent();\n }\n\n return api;\n }\n\n /**\n * Clear all caches - useful for testing\n */\n static clearCaches(): void {\n ContentIndex.clearCache();\n // TODO: CanvasIndex.clearCache() when implemented\n }\n\n private async indexAllContent(): Promise<void> {\n // Clear existing indexes\n this.contentIndex.clear();\n\n // Scan content directory\n const files = await this.scanContentFiles();\n\n // Use optimized batch size based on benchmarks\n const OPTIMAL_BATCH_SIZE = 1000;\n\n console.log(`Indexing ${files.length} content files...`);\n\n // Pre-allocate reusable buffers for the entire indexing operation\n // Only allocate as many as we need (up to batch size)\n const bufferCount = Math.min(files.length, OPTIMAL_BATCH_SIZE);\n const buffers = Array.from({ length: bufferCount }, () => new Uint8Array(4096));\n\n for (let i = 0; i < files.length; i += OPTIMAL_BATCH_SIZE) {\n const batch = files.slice(i, i + OPTIMAL_BATCH_SIZE);\n\n // Process batch in parallel - winner of benchmarks\n await Promise.all(\n batch.map(async (filePath, index) => {\n try {\n const result = await this.parseFileHeaderWithRepair(filePath, buffers[index]);\n if (result) {\n const { manifest, localeVersion, content } = result;\n\n // Add to index with content if we have it\n this.contentIndex.addContent(manifest, localeVersion, content);\n }\n } catch (error) {\n console.error(`Failed to index ${filePath}:`, error);\n }\n }),\n );\n }\n }\n\n private async parseFileHeaderWithRepair(\n originalFilePath: string,\n buffer: Uint8Array,\n ): Promise<{\n manifest: ContentManifest;\n locale: string;\n localeVersion: LocaleVersion;\n bytesRead: number;\n content?: ContentData;\n } | null> {\n let handle: FileHandle | undefined;\n let bytesRead = 0;\n let filePath = originalFilePath; // Use a local variable that can be updated if file is renamed\n\n try {\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n } catch (error) {\n console.error(`Error reading ${filePath}:`, error);\n throw error;\n } finally {\n await handle?.close();\n }\n\n try {\n // Now parse the buffer content\n\n // Parse file to extract metadata\n let relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n let parts = relativePath.split('/');\n\n // Determine site/collection structure\n let site: string | undefined;\n let collection: string;\n let locale = 'en';\n let name: string | undefined;\n let pathname: string | undefined;\n // Type for parsed metadata from files\n interface ParsedMetadata {\n id?: string;\n created?: string;\n modified?: string;\n publishAt?: string;\n unpublishAt?: string;\n pathname?: string;\n name?: string;\n previousPathnames?: Record<string, string>;\n meta?: ContentMeta;\n type?: 'puck' | 'mdx' | 'json';\n contentStartPos?: number;\n data?: Record<string, unknown>; // For data collection entries\n }\n let parsedData: ParsedMetadata = {};\n let kind: 'block' | 'page' | 'data';\n\n if (parts[0] === 'blocks') {\n kind = 'block';\n\n // Check if block is directly in blocks/ directory (no collection subdirectory)\n if (parts.length === 2) {\n // Block is directly in blocks/ directory, needs to be moved to 'general' collection\n collection = 'general';\n const filename = parts[1];\n\n // Create the general directory if it doesn't exist\n const generalDir = join(this.absoluteContentRoot, 'blocks', 'general');\n try {\n await mkdir(generalDir, { recursive: true });\n } catch (error) {\n // Directory might already exist, that's fine\n }\n\n // Move the file to the general collection\n const newFilePath = join(generalDir, filename);\n\n try {\n await handle?.close(); // Close the current file handle before moving\n handle = undefined;\n\n // Check if target file already exists\n try {\n const targetHandle = await open(newFilePath, 'r');\n await targetHandle.close();\n console.warn(`Cannot move ${filename} to blocks/general/: target file already exists`);\n } catch (error) {\n // Target doesn't exist, safe to move\n await rename(filePath, newFilePath);\n console.log(`Repaired: Moved ${filename} to blocks/general/ collection`);\n\n // Update filePath to the new path for further processing\n filePath = newFilePath;\n\n // Update relativePath and parts for the new file path\n relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n parts = relativePath.split('/');\n\n // Re-open the file with the new path\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n }\n } catch (moveError) {\n console.error(`Failed to move ${filename} to general collection:`, moveError);\n // Continue processing with original file\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n }\n } else {\n // Block is in a collection subdirectory\n collection = parts[1];\n }\n\n const filename = parts[parts.length - 1];\n // Extract name and locale from filename: hero.en.mdx -> name: hero, locale: en\n // Also handle files without locale: hero.mdx -> name: hero, locale: default from sites.json\n const matchWithLocale = filename.match(/^(.+)\\.(\\w+)\\.(mdx|vxjson)$/);\n const matchWithoutLocale = filename.match(/^(.+)\\.(mdx|vxjson)$/);\n\n if (matchWithLocale) {\n name = matchWithLocale[1];\n locale = matchWithLocale[2];\n } else if (matchWithoutLocale) {\n name = matchWithoutLocale[1];\n // Use default locale from sites config instead of hardcoded 'en'\n locale = this.contentIndex.getDefaultLocale('');\n\n console.log(`Found file without locale suffix: ${filename}`);\n // Rename file to include locale suffix\n const extension = matchWithoutLocale[2];\n const newFilename = `${name}.${locale}.${extension}`;\n const newFilePath = join(dirname(filePath), newFilename);\n console.log(`Will rename to: ${newFilename} at ${newFilePath}`);\n\n // Check if target file already exists\n try {\n await handle?.close(); // Close the current file handle before renaming\n handle = undefined;\n\n // Try to open the target file to check if it exists\n const targetHandle = await open(newFilePath, 'r');\n await targetHandle.close();\n\n // Target file exists, skip renaming to avoid conflict\n console.warn(`Cannot rename ${filename} to ${newFilename}: target file already exists`);\n } catch (error) {\n // Target file doesn't exist, safe to rename\n console.log(`Target file doesn't exist, proceeding with rename`);\n try {\n await rename(filePath, newFilePath);\n console.log(`Successfully renamed ${filename} to ${newFilename}`);\n\n // Update filePath to the new path for further processing\n filePath = newFilePath;\n\n // Update relativePath and parts for the new file path\n relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n parts = relativePath.split('/');\n\n // Re-open the file with the new path\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n } catch (renameError) {\n console.error(`Failed to rename ${filename}:`, renameError);\n // Continue processing with original file\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n }\n }\n }\n\n // Parse content based on file type\n if (filePath.endsWith('.mdx')) {\n parsedData = parse4KBMDX(buffer, bytesRead);\n } else {\n parsedData = VXJSON.parse4KB(buffer, bytesRead);\n }\n } else if (parts[0] === 'data') {\n // Data collection entry: data/{collection}/{name}.{locale}.json\n kind = 'data';\n collection = parts[1];\n\n const filename = parts[parts.length - 1];\n // Extract name and locale from filename: testimonial.en.json -> name: testimonial, locale: en\n // Use strict locale pattern matching blocks: 2-letter code with optional region (en, en-US)\n const match = filename.match(/^(.+)\\.([a-z]{2}(?:-[A-Z]{2})?)\\.json$/);\n if (match) {\n name = match[1];\n locale = match[2];\n }\n\n // Parse JSON to get ID, metadata, and data\n const content = textDecoder.decode(buffer.subarray(0, bytesRead));\n try {\n const jsonData = JSON.parse(content);\n parsedData = {\n id: jsonData.id,\n type: 'json',\n created: jsonData.created,\n modified: jsonData.modified,\n publishAt: jsonData.publishAt,\n unpublishAt: jsonData.unpublishAt,\n meta: jsonData.meta || { title: name || 'Untitled' },\n data: jsonData.data,\n name,\n };\n } catch (error) {\n console.error(`Failed to parse JSON data file ${filePath}:`, error);\n return null;\n }\n } else {\n kind = 'page';\n site = parts[0];\n collection = parts[1];\n\n // Build pathname from file path: pages/products/widget.en.vxjson -> /products/widget\n const pathParts = parts.slice(2); // Remove site/collection\n const filename = pathParts[pathParts.length - 1];\n const match = filename.match(/^(.+)\\.(\\w+)\\.vxjson$/);\n if (match) {\n locale = match[2];\n // Replace filename with basename\n pathParts[pathParts.length - 1] = match[1];\n // index files map to parent: /index -> /, /foo/index -> /foo\n pathname =\n pathParts[pathParts.length - 1] === 'index'\n ? '/' + pathParts.slice(0, -1).join('/') || '/'\n : '/' + pathParts.join('/');\n }\n\n // Parse JSON to get ID and metadata\n parsedData = VXJSON.parse4KB(buffer, bytesRead);\n }\n\n // Check if the file is missing required fields\n const needsRepair = !parsedData.id || !parsedData.created || !parsedData.modified;\n\n // Extract or generate ID\n const id = parsedData.id || generateContentId();\n\n // Build LocaleManifest for this specific locale\n const localeVersion: LocaleVersion = {\n locale,\n etag: '', // Will be filled below\n created: parsedData.created || new Date().toISOString(),\n modified: parsedData.modified || new Date().toISOString(),\n ...(parsedData.publishAt && { publishAt: parsedData.publishAt }),\n ...(parsedData.unpublishAt && { unpublishAt: parsedData.unpublishAt }),\n ...(pathname && { pathname }),\n ...(parsedData.previousPathnames && { previousPathnames: parsedData.previousPathnames }),\n ...(name && { name }),\n meta: parsedData.meta || { title: name || 'Untitled' },\n };\n\n // Build ContentManifest (without content)\n const manifest: ContentManifest = {\n id,\n type: parsedData.type || (filePath.endsWith('.mdx') ? 'mdx' : filePath.endsWith('.json') ? 'json' : 'puck'),\n kind,\n site,\n collection,\n locales: {\n [locale]: localeVersion,\n },\n };\n\n // If we have full content, parse it and compute etags\n let content: ContentData | undefined;\n\n // Check if we need to repair the file first (missing required fields)\n if (needsRepair) {\n // Perform repair and get the repaired content\n const repairedData = await this.performReadRepair(filePath, manifest, locale);\n if (repairedData) {\n content = repairedData.content;\n localeVersion.etag = repairedData.etag;\n localeVersion.modified = repairedData.modified;\n return { manifest, locale, localeVersion, bytesRead, content };\n }\n // Repair failed, skip this file\n console.error(`Failed to repair ${filePath}, skipping`);\n return null;\n }\n\n if (\n bytesRead < 4096 ||\n (filePath.endsWith('.vxjson') && buffer[bytesRead - 1] === 0x7d) ||\n (filePath.endsWith('.json') && buffer[bytesRead - 1] === 0x7d)\n ) {\n // We have the full content\n if (filePath.endsWith('.mdx')) {\n const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const { content: mdx } = matter(fullContent);\n content = { mdx };\n } else if (filePath.endsWith('.json')) {\n // Data collection JSON file\n const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const jsonData = JSON.parse(fullContent);\n content = { data: jsonData.data };\n } else {\n const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const data = JSON.parse(fullContent);\n content = data.content || {};\n }\n\n // Calculate etags from the buffer (only use valid bytes)\n const validBuffer = buffer.subarray(0, bytesRead);\n\n if (filePath.endsWith('.mdx')) {\n const etags = calculateEtagsFromMdxBuffer(validBuffer, parsedData.contentStartPos || -1);\n localeVersion.etag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else if (filePath.endsWith('.json')) {\n // For data files, use simple etag (hash entire buffer)\n // Data files are typically small and don't need separate meta/content etags\n localeVersion.etag = VXJSON.calculateSimpleEtag(validBuffer);\n } else {\n const etagResult = VXJSON.calculateETags(validBuffer);\n\n if (!etagResult.success) {\n // Content field is not last or invalid JSON - repair immediately\n\n // Perform repair and get the repaired content\n const repairedData = await this.performReadRepair(filePath, manifest, locale);\n if (repairedData) {\n content = repairedData.content;\n localeVersion.etag = repairedData.etag;\n localeVersion.modified = repairedData.modified;\n return { manifest, locale, localeVersion, bytesRead, content };\n }\n // Repair failed, skip this file\n console.error(`Failed to repair ${filePath}, skipping`);\n return null;\n }\n localeVersion.etag = etagResult.contentEtag\n ? `${etagResult.metaEtag}.${etagResult.contentEtag}`\n : etagResult.metaEtag;\n }\n }\n\n // Return both for indexing\n return { manifest, locale, localeVersion, bytesRead, content };\n } catch (error) {\n console.error(`Error indexing ${originalFilePath}:`, error);\n return null;\n }\n }\n\n /**\n * Perform read-repair by writing back the file with missing fields\n * This ensures stable IDs and timestamps across restarts\n */\n private async performReadRepair(\n filePath: string,\n manifest: ContentManifest,\n locale: string,\n ): Promise<{\n content: ContentData;\n etag: string;\n modified: string;\n } | null> {\n try {\n const now = new Date().toISOString();\n let needsWrite = false;\n\n if (manifest.type === 'mdx') {\n // Read the full MDX file\n const content = await readFile(filePath, 'utf-8');\n const parsed = matter(content);\n\n // Check for missing fields\n if (!parsed.data.id) {\n parsed.data.id = manifest.id;\n needsWrite = true;\n }\n if (!parsed.data.created) {\n parsed.data.created = now;\n needsWrite = true;\n }\n if (!parsed.data.modified) {\n parsed.data.modified = now;\n needsWrite = true;\n }\n\n if (needsWrite) {\n // Write back with updated frontmatter\n const updatedContent = matter.stringify(parsed.content, parsed.data);\n await writeFile(filePath, updatedContent);\n console.log(`Repaired MDX file: ${filePath} (added missing fields)`);\n\n // Calculate ETags for the repaired MDX file\n const repairedBuffer = Buffer.from(updatedContent, 'utf-8') as Uint8Array;\n const contentStartPos = updatedContent.indexOf('\\n---\\n') + 5; // Position after frontmatter\n const etags = calculateEtagsFromMdxBuffer(repairedBuffer, contentStartPos);\n const etag = `${etags.metaEtag}.${etags.contentEtag}`;\n\n // Return the repaired data\n return {\n content: { mdx: parsed.content },\n etag,\n modified: parsed.data.modified || now,\n };\n }\n } else {\n // Read the full JSON file\n const content = await readFile(filePath, 'utf-8');\n const data: VXJSONFile = JSON.parse(content);\n\n // Check for missing fields\n if (!data.id) {\n data.id = manifest.id;\n needsWrite = true;\n }\n if (!data.created) {\n data.created = now;\n needsWrite = true;\n }\n if (!data.modified) {\n data.modified = now;\n needsWrite = true;\n }\n\n // Always rewrite VXJSON files during repair to ensure correct field order\n needsWrite = true;\n\n if (needsWrite) {\n // Write back with VXJSON format\n const vxjsonData: VXJSONFile = {\n id: data.id,\n type: data.type,\n created: data.created,\n modified: data.modified,\n publishAt: data.publishAt,\n unpublishAt: data.unpublishAt,\n previousPathnames: data.previousPathnames,\n meta: data.meta || {},\n content: data.content || {},\n };\n const repairedJson = VXJSON.serialize(vxjsonData);\n await writeFile(filePath, repairedJson);\n console.log(`Repaired VXJSON file: ${filePath} (fixed field order or added missing fields)`);\n // Return the repaired data\n\n // Calculate ETags from the repaired JSON\n const repairedBuffer = Buffer.from(repairedJson, 'utf-8') as Uint8Array;\n const etagResult = VXJSON.calculateETags(repairedBuffer);\n\n if (!etagResult.success) {\n console.error(`Failed to calculate ETags after repair: ${filePath}`);\n return null;\n }\n\n const etag = etagResult.contentEtag\n ? `${etagResult.metaEtag}.${etagResult.contentEtag}`\n : etagResult.metaEtag;\n\n // Return the complete repaired data\n return {\n content: vxjsonData.content,\n etag,\n modified: vxjsonData.modified,\n };\n }\n }\n\n // For MDX or no repair needed, return null\n return null;\n } catch (error) {\n console.error(`Failed to perform read-repair on ${filePath}:`, error);\n return null;\n }\n }\n\n private async scanContentFiles(): Promise<string[]> {\n const files: string[] = [];\n const contentRoot = this.absoluteContentRoot;\n\n async function scan(dir: string, inDataDir = false) {\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n // Check if we're entering the data/ directory\n const isDataDir = dir === contentRoot && entry.name === 'data';\n await scan(fullPath, inDataDir || isDataDir);\n } else if (entry.isFile()) {\n // Include .vxjson and .mdx files everywhere\n // Include .json files only in the data/ directory\n if (entry.name.endsWith('.vxjson') || entry.name.endsWith('.mdx')) {\n files.push(fullPath);\n } else if (inDataDir && entry.name.endsWith('.json')) {\n files.push(fullPath);\n }\n }\n }\n } catch (error) {\n // Directory doesn't exist yet\n }\n }\n\n await scan(this.absoluteContentRoot);\n return files;\n }\n\n private getFilePath(manifest: ContentIdentity, { locale, name, pathname }: LocalePathData): string {\n if (manifest.kind === 'block') {\n const ext = manifest.type === 'mdx' ? 'mdx' : 'vxjson';\n return join(this.absoluteContentRoot, 'blocks', manifest.collection, `${name}.${locale}.${ext}`);\n }\n if (manifest.kind === 'data') {\n return join(this.absoluteContentRoot, 'data', manifest.collection, `${name}.${locale}.json`);\n }\n if (manifest.kind === 'page' && pathname && manifest.site) {\n // For pages, derive path from pathname\n const basePath = pathname.replace(/^\\//, '').replace(/\\/$/, '') || 'index';\n return join(this.absoluteContentRoot, manifest.site, manifest.collection, `${basePath}.${locale}.vxjson`);\n }\n throw new Error(`Invalid manifest: ${JSON.stringify(manifest, null, 2)}`);\n }\n\n /**\n * Parse a file path back into its components for checking against the path index\n * Returns null if the path doesn't match expected patterns\n */\n parseFilePath(filePath: string): {\n kind: 'page' | 'block' | 'data';\n site?: string;\n collection: string;\n pathname?: string;\n name?: string;\n locale: string;\n } | null {\n // Remove contentRoot prefix\n const relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n const parts = relativePath.split('/');\n\n // Match locale.ext pattern at the end\n const filename = parts[parts.length - 1];\n\n // Handle data files: data/{collection}/{name}.{locale}.json\n if (parts[0] === 'data' && parts.length === 3) {\n const dataMatch = filename.match(/^(.+)\\.([a-z]{2}(?:-[A-Z]{2})?)\\.json$/);\n if (!dataMatch) return null;\n const [, name, locale] = dataMatch;\n return {\n kind: 'data',\n collection: parts[1],\n name,\n locale,\n };\n }\n\n // Match locale.ext pattern for non-data files (vxjson, mdx)\n const match = filename.match(/^(.+)\\.([a-z]{2}(?:-[A-Z]{2})?)\\.(?:vxjson|mdx)$/);\n if (!match) return null;\n\n const [, nameOrPath, locale] = match;\n\n if (parts[0] === 'blocks' && parts.length === 3) {\n // blocks/collection/name.locale.ext\n return {\n kind: 'block',\n collection: parts[1],\n name: nameOrPath,\n locale,\n };\n }\n if (parts.length >= 3 && parts[0] !== 'blocks') {\n // site/collection/pathname.locale.vxjson\n const site = parts[0];\n const collection = parts[1];\n // Reconstruct pathname from remaining parts\n const pathParts = parts.slice(2, -1); // All dirs between collection and filename\n pathParts.push(nameOrPath); // Add the filename part (without locale.ext)\n const pathname = '/' + pathParts.join('/');\n\n return {\n kind: 'page',\n site,\n collection,\n pathname,\n locale,\n };\n }\n\n return null;\n }\n\n async getContent(id: string): Promise<ContentEntry | null> {\n // Get manifest for this ID\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return null;\n }\n\n // Read all locale files in parallel\n const readPromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {\n const filePath = this.getFilePath(manifest, localeVersion);\n const content = await this.readLocaleFile(filePath, localeVersion.locale);\n return { localeVersion, content };\n });\n\n const results = await Promise.all(readPromises);\n\n // Build locales with content\n const locales: Record<string, LocaleVersion & ContentProp> = {};\n for (const { localeVersion, content } of results) {\n if (content) {\n locales[localeVersion.locale] = {\n ...localeVersion,\n etag: content.etag, // Use fresh etag from file, not stale manifest etag\n content: content.content,\n };\n }\n }\n\n return {\n id: manifest.id,\n site: manifest.site,\n collection: manifest.collection,\n type: manifest.type,\n kind: manifest.kind,\n locales,\n };\n }\n\n async getLocalized(id: string, locale: string): Promise<LocalizedEntry | null> {\n // Get manifest for this ID\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n // File might have been added after indexing - try reindexing\n await this.reindex();\n\n // Try again with updated index\n const updatedManifest = this.contentIndex.getManifest(id);\n if (!updatedManifest || !updatedManifest.locales[locale]) {\n return null;\n }\n\n return this.getLocalized(id, locale);\n }\n\n // Check if this locale exists\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return null;\n }\n\n // Read the locale-specific file\n const filePath = this.getFilePath(manifest, localeVersion);\n const localeData = await this.readLocaleFile(filePath, locale);\n if (!localeData) {\n return null;\n }\n\n // Build LocalizedEntry\n return {\n id: manifest.id,\n site: manifest.site,\n collection: manifest.collection,\n type: manifest.type,\n kind: manifest.kind,\n localized: {\n ...localeVersion,\n etag: localeData.etag, // Use fresh etag from file, not stale manifest etag\n content: localeData.content,\n },\n };\n }\n\n private async readLocaleFile(filePath: string, locale: string): Promise<LocaleFileData | null> {\n try {\n const buffer = (await readFile(filePath)) as Uint8Array;\n const content = textDecoder.decode(buffer);\n\n if (filePath.endsWith('.mdx')) {\n const { data: frontmatter } = matter(content);\n\n // Calculate etags from the file buffer\n const contentPos = findMdxContentStartPosition(buffer);\n\n const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);\n const etag = `${etags.metaEtag}.${etags.contentEtag}`;\n\n // Extract special fields from frontmatter, everything else is metadata\n const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;\n\n const result: LocaleFileData = {\n locale,\n etag,\n created: created,\n modified: modified,\n meta: metaFields as ContentMeta, // All non-special fields are metadata\n content: { mdx: content }, // Return the ENTIRE file content including frontmatter\n };\n\n // Only add publish dates if they exist\n if (frontmatter.publishAt !== undefined) {\n result.publishAt = frontmatter.publishAt;\n }\n if (frontmatter.unpublishAt !== undefined) {\n result.unpublishAt = frontmatter.unpublishAt;\n }\n\n return result;\n }\n\n // Parse JSON data first to determine type\n const data = JSON.parse(content);\n\n // Handle JSON data files (type: 'json') separately - they use simple etag\n if (data.type === 'json') {\n const etag = VXJSON.calculateSimpleEtag(buffer);\n\n const result: LocaleFileData = {\n locale,\n etag,\n created: data.created,\n modified: data.modified,\n meta: data.meta || {},\n content: { data: data.data || {} },\n };\n\n // Only add optional fields if they exist\n if (data.publishAt !== undefined) {\n result.publishAt = data.publishAt;\n }\n if (data.unpublishAt !== undefined) {\n result.unpublishAt = data.unpublishAt;\n }\n\n return result;\n }\n\n // For VXJSON (puck pages), calculate ETags with meta/content split\n const etagResult = VXJSON.calculateETags(buffer);\n\n if (!etagResult.success) {\n // File needs repair - parse it and rewrite in correct format\n const repairedData: VXJSONFile = {\n id: data.id,\n type: data.type,\n created: data.created,\n modified: data.modified,\n publishAt: data.publishAt,\n unpublishAt: data.unpublishAt,\n previousPathnames: data.previousPathnames,\n meta: data.meta || {},\n content: data.content || {},\n };\n\n // Rewrite file with correct format\n const repairedJson = VXJSON.serialize(repairedData);\n await writeFile(filePath, repairedJson);\n\n // Recalculate ETags from repaired buffer\n const repairedBuffer = Buffer.from(repairedJson, 'utf-8') as Uint8Array;\n const repairedEtagResult = VXJSON.calculateETags(repairedBuffer);\n\n if (!repairedEtagResult.success) {\n throw new Error(`Failed to repair VXJSON file: ${filePath}`);\n }\n\n const etag = repairedEtagResult.contentEtag\n ? `${repairedEtagResult.metaEtag}.${repairedEtagResult.contentEtag}`\n : repairedEtagResult.metaEtag;\n\n console.log(`Repaired VXJSON file: ${filePath}`);\n\n const result: LocaleFileData = {\n locale,\n etag,\n created: data.created,\n modified: data.modified,\n meta: data.meta || {},\n content: data.content || {},\n };\n\n // Only add optional fields if they exist\n if (data.publishAt !== undefined) {\n result.publishAt = data.publishAt;\n }\n if (data.unpublishAt !== undefined) {\n result.unpublishAt = data.unpublishAt;\n }\n if (data.previousPathnames !== undefined) {\n result.previousPathnames = data.previousPathnames;\n }\n\n return result;\n }\n\n const etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n\n const result: LocaleFileData = {\n locale,\n etag,\n created: data.created,\n modified: data.modified,\n meta: data.meta || {},\n content: data.content || {},\n };\n\n // Only add optional fields if they exist\n if (data.publishAt !== undefined) {\n result.publishAt = data.publishAt;\n }\n if (data.unpublishAt !== undefined) {\n result.unpublishAt = data.unpublishAt;\n }\n if (data.previousPathnames !== undefined) {\n result.previousPathnames = data.previousPathnames;\n }\n\n return result;\n } catch (error) {\n return null;\n }\n }\n\n async createContent(data: CreateContentInput): Promise<CreateResult> {\n // Use shared validation\n const validation = validateCreateContent(data, this.sites, this.blocks, this.data);\n if (!validation.valid) {\n return {\n success: false,\n reason: validation.reason,\n error: validation.error ? new Error(validation.error) : undefined,\n existingId: validation.existingId,\n };\n }\n\n const id = generateContentId();\n const now = data.created || new Date().toISOString();\n\n try {\n // Build the manifest with all locales\n const manifest: ContentManifest = {\n id,\n type: data.type,\n kind: data.kind,\n site: data.site,\n collection: data.collection,\n locales: {},\n };\n\n const contentCache: Record<string, ContentData> = {};\n\n // Create files for each locale\n for (const [locale, localeData] of Object.entries(data.locales)) {\n const content = localeData.content;\n\n // Build metadata with required title\n const title = localeData.meta?.title || data.meta?.title;\n if (!title) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error('Title is required in metadata'),\n };\n }\n\n // Build complete metadata\n const meta: ContentMeta = {\n title,\n ...data.meta,\n ...localeData.meta,\n };\n\n const fileData: VXJSONFile = {\n id,\n type: data.type,\n created: now,\n modified: now,\n publishAt:\n localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,\n unpublishAt:\n localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,\n meta,\n content,\n };\n\n // Use the proper getFilePath method\n const filePath = this.getFilePath(manifest, { locale, name: data.name, pathname: localeData.pathname });\n\n // Ensure directory exists\n await mkdir(dirname(filePath), { recursive: true });\n\n // Write file and calculate etag from the serialized content\n let etag: string;\n\n if (data.type === 'mdx') {\n // Write MDX with frontmatter - flatten metadata fields\n const frontmatterData = {\n id,\n created: now,\n modified: now,\n ...(localeData.publishAt && { publishAt: localeData.publishAt }),\n ...(localeData.unpublishAt && { unpublishAt: localeData.unpublishAt }),\n ...meta, // Spread metadata fields directly, not nested\n };\n\n const mdxContent = serializeMdxWithFrontmatter(frontmatterData, content.mdx || '');\n await writeFile(filePath, mdxContent);\n\n // For MDX, calculate etags from the serialized content\n const mdxBuffer = new TextEncoder().encode(mdxContent);\n // For MDX, all frontmatter is metadata, content starts after ---\n const contentStartMarker = new TextEncoder().encode('---\\n\\n');\n let contentPos = -1;\n for (let i = 0; i <= mdxBuffer.length - contentStartMarker.length; i++) {\n let match = true;\n for (let j = 0; j < contentStartMarker.length; j++) {\n if (mdxBuffer[i + j] !== contentStartMarker[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n contentPos = i + contentStartMarker.length;\n break;\n }\n }\n const etags = calculateEtagsFromMdxBuffer(mdxBuffer, contentPos);\n etag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else if (data.type === 'json') {\n // Data files use \"data\" field instead of \"content\"\n const dataFileContent = {\n id,\n type: 'json',\n created: now,\n modified: now,\n ...(localeData.publishAt &&\n typeof localeData.publishAt === 'string' && { publishAt: localeData.publishAt }),\n ...(localeData.unpublishAt &&\n typeof localeData.unpublishAt === 'string' && { unpublishAt: localeData.unpublishAt }),\n meta,\n data: content.data || {},\n };\n\n const jsonContent = JSON.stringify(sortKeys(dataFileContent, { deep: true }), null, '\\t');\n await writeFile(filePath, jsonContent);\n\n // For data files, use simple etag (hash entire buffer)\n const jsonBuffer = new TextEncoder().encode(jsonContent);\n etag = VXJSON.calculateSimpleEtag(jsonBuffer);\n } else {\n // VXJSON for pages (puck)\n const jsonContent = VXJSON.serialize(fileData);\n const jsonBuffer = new TextEncoder().encode(jsonContent);\n\n // Calculate etags from the buffer\n const etagResult = VXJSON.calculateETags(jsonBuffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format when creating content: ${etagResult.error}`);\n }\n\n etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n\n // Write the file\n await writeFile(filePath, jsonContent);\n }\n\n // Build locale manifest using shared function\n const localeVersion = buildLocaleVersion({\n locale,\n etag,\n created: now,\n modified: now,\n meta,\n kind: data.kind,\n pathname: data.kind === 'page' ? localeData.pathname : undefined,\n name: data.kind === 'block' || data.kind === 'data' ? data.name : undefined,\n publishAt:\n localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,\n unpublishAt:\n localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,\n });\n\n // Add locale to manifest\n manifest.locales[locale] = localeVersion;\n contentCache[locale] = content;\n }\n\n // Add each locale to the index\n for (const localeVersion of localesOf(manifest)) {\n const { locale } = localeVersion;\n this.contentIndex.addContent(manifest, localeVersion, contentCache[locale]);\n }\n\n return { success: true, id };\n } catch (error) {\n return {\n success: false,\n reason: 'write_error',\n error: ensureError(error),\n };\n }\n }\n\n async updateLocalized(input: UpdateLocaleInput): Promise<UpdateResult> {\n const { id, locale, data, etag } = input;\n\n // Get the manifest\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Get the specific locale manifest\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Get file path and read current content FIRST to get fresh etag\n const filePath = this.getFilePath(manifest, localeVersion);\n const current = await this.readLocaleFile(filePath, locale);\n if (!current) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Use fresh etag from file, not stale manifest etag\n const currentEtag = current.etag;\n\n // Check etag - data files use simple etags, others use dual etags\n if (manifest.kind === 'data') {\n // Data files use simple etag (single hash, no dot separator)\n // Just compare the full etag directly\n if (etag !== currentEtag) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag,\n };\n }\n } else {\n // Non-data files use dual etags (meta.content format)\n const etagParts = parseDualEtag(etag);\n const currentParts = parseDualEtag(currentEtag);\n\n if (!etagParts || !currentParts) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag,\n };\n }\n\n // Check which parts are being updated\n const updateScope = analyzeUpdateScope(data);\n const updatingMeta = (updateScope & UPDATE_SCOPE.META) !== 0;\n const updatingContent = (updateScope & UPDATE_SCOPE.CONTENT) !== 0;\n\n // Validate etags for parts being updated\n if (updatingMeta && etagParts.meta !== currentParts.meta) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag,\n };\n }\n\n if (updatingContent && etagParts.content !== currentParts.content) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag,\n };\n }\n }\n\n // Update modified timestamp for any change (metadata or content)\n let modified: string;\n if (shouldUpdateModifiedTimestamp(data)) {\n // Use provided modified timestamp or current time\n modified = data.modified || new Date().toISOString();\n } else if (data.modified) {\n // If modified timestamp is explicitly provided, always use it\n modified = data.modified;\n } else {\n // No changes and no explicit timestamp, keep current\n modified = current.modified;\n }\n\n const {\n sortedMeta: newMeta,\n valid: metaValid,\n error: metaError,\n } = validateAndPrepareMetadata({ ...current.meta, ...(data.meta ? data.meta : {}) });\n\n // Validate new metadata\n if (!newMeta || !metaValid) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error(metaError),\n };\n }\n\n // Merge updates\n const newContent = data.content ? { ...current.content, ...data.content } : current.content;\n\n // Validate pathname change if updating pathname for pages\n if (data.pathname && manifest.kind === 'page' && manifest.site) {\n const site = this.sites[manifest.site];\n if (site) {\n // Check if new pathname is already taken by another content\n const existingId = site.getPathnameConflict(data.pathname, locale, id);\n if (existingId) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error(`Pathname ${data.pathname} is already taken by content ${existingId}`),\n };\n }\n }\n }\n\n // Validate name change if updating name for blocks or data\n if (data.name && (manifest.kind === 'block' || manifest.kind === 'data')) {\n // Check if new name is already taken by another entry in the same collection\n const index = manifest.kind === 'block' ? this.contentIndex.getBlockIndex() : this.contentIndex.getDataIndex();\n const existing = index.getByName(manifest.collection, data.name);\n\n if (existing && existing.id !== id) {\n // Get title from the existing entry for a better error message\n const existingLocale = Object.values(existing.locales).find((lv) => lv !== undefined);\n const existingTitle = existingLocale?.meta?.title;\n const kindLabel = manifest.kind === 'block' ? 'Block' : 'Data';\n\n return {\n success: false,\n reason: 'write_error',\n error: new Error(\n `${kindLabel} name \"${data.name}\" is already in use${existingTitle ? ` by \"${existingTitle}\"` : ''}`,\n ),\n };\n }\n }\n\n // Handle pathname changes - track history only for published content\n const pathnameHistory = buildPathnameHistory(\n localeVersion.pathname,\n data.pathname,\n isContentPublished({\n publishAt: resolvePublishDate(data.publishAt, current.publishAt),\n unpublishAt: resolvePublishDate(data.unpublishAt, current.unpublishAt),\n }),\n new Date().toISOString(),\n );\n\n try {\n // Determine the target file path (may be different if pathname or name changed)\n let targetFilePath = filePath;\n if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname && manifest.site) {\n // For pages, calculate new file path based on new pathname\n const newLocaleVersion: LocaleVersion = {\n ...localeVersion,\n pathname: data.pathname,\n };\n targetFilePath = this.getFilePath(manifest, newLocaleVersion);\n\n // Ensure target directory exists\n await mkdir(dirname(targetFilePath), { recursive: true });\n } else if (data.name && localeVersion.name && data.name !== localeVersion.name && manifest.kind === 'block') {\n // For blocks, calculate new file path based on new name\n const newLocaleVersion: LocaleVersion = {\n ...localeVersion,\n name: data.name,\n };\n targetFilePath = this.getFilePath(manifest, newLocaleVersion);\n\n // Ensure target directory exists\n await mkdir(dirname(targetFilePath), { recursive: true });\n }\n\n // Write updated content\n if (targetFilePath.endsWith('.mdx')) {\n // Build frontmatter with special fields and metadata\n const publishAt = resolvePublishDate(data.publishAt, current.publishAt);\n const unpublishAt = resolvePublishDate(data.unpublishAt, current.unpublishAt);\n const frontmatterData = {\n id: manifest.id,\n created: current.created,\n modified,\n ...(publishAt && { publishAt }),\n ...(unpublishAt && { unpublishAt }),\n ...newMeta, // Spread metadata fields directly\n };\n\n // Extract just the content part from MDX (remove frontmatter if present)\n let mdxContentPart = newContent.mdx || '';\n if (mdxContentPart.startsWith('---')) {\n // Remove frontmatter if it exists\n const { content: contentOnly } = matter(mdxContentPart);\n mdxContentPart = contentOnly;\n }\n\n const mdxContent = serializeMdxWithFrontmatter(frontmatterData, mdxContentPart);\n\n // Use atomic write for MDX files too\n const hrtime = process.hrtime.bigint();\n const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;\n\n try {\n await writeFile(tempFile, mdxContent);\n await rename(tempFile, targetFilePath);\n } catch (error) {\n // Clean up temp file if rename fails\n try {\n await unlink(tempFile);\n } catch {\n // Ignore cleanup errors\n }\n throw error;\n }\n } else if (targetFilePath.endsWith('.json')) {\n // Data files use \"data\" field instead of \"content\"\n const fileContent = JSON.parse(await readFile(filePath, 'utf-8'));\n\n // Build updated data file structure\n const updatedFile = {\n id: fileContent.id,\n type: 'json' as const,\n created: fileContent.created,\n modified,\n ...(fileContent.publishAt && { publishAt: fileContent.publishAt }),\n ...(fileContent.unpublishAt && { unpublishAt: fileContent.unpublishAt }),\n meta: newMeta,\n data: sortKeys(newContent.data || {}, { deep: true }),\n };\n\n // Handle publish date updates\n if ('publishAt' in data) {\n if (data.publishAt) {\n (updatedFile as Record<string, unknown>).publishAt = data.publishAt;\n } else {\n delete (updatedFile as Record<string, unknown>).publishAt;\n }\n }\n\n if ('unpublishAt' in data) {\n if (data.unpublishAt) {\n (updatedFile as Record<string, unknown>).unpublishAt = data.unpublishAt;\n } else {\n delete (updatedFile as Record<string, unknown>).unpublishAt;\n }\n }\n\n // Serialize data file\n const serializedContent = JSON.stringify(sortKeys(updatedFile, { deep: true }), null, '\\t');\n\n // Use atomic write\n const hrtime = process.hrtime.bigint();\n const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;\n\n try {\n await writeFile(tempFile, serializedContent);\n await rename(tempFile, targetFilePath);\n } catch (error) {\n try {\n await unlink(tempFile);\n } catch {\n // Ignore cleanup errors\n }\n throw error;\n }\n } else {\n // VXJSON for pages (puck)\n const fileContent = JSON.parse(await readFile(filePath, 'utf-8'));\n\n // Build updated VXJSONFile structure\n const updatedFile: VXJSONFile = {\n id: fileContent.id,\n type: fileContent.type,\n created: fileContent.created,\n modified,\n publishAt: fileContent.publishAt,\n unpublishAt: fileContent.unpublishAt,\n previousPathnames: fileContent.previousPathnames,\n meta: newMeta,\n content: sortKeys(newContent, { deep: true }),\n };\n\n // Handle pathname changes and track history\n if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname) {\n // Only add to history if content is published\n if (isContentPublished(current)) {\n if (!updatedFile.previousPathnames) {\n updatedFile.previousPathnames = {};\n }\n updatedFile.previousPathnames[localeVersion.pathname] = modified;\n }\n }\n\n // Handle publish date updates\n if ('publishAt' in data) {\n if (data.publishAt) {\n updatedFile.publishAt = data.publishAt;\n } else {\n delete updatedFile.publishAt;\n }\n }\n\n if ('unpublishAt' in data) {\n if (data.unpublishAt) {\n updatedFile.unpublishAt = data.unpublishAt;\n } else {\n delete updatedFile.unpublishAt;\n }\n }\n\n // Serialize using VXJSON format to ensure content is last\n const serializedContent = VXJSON.serialize(updatedFile);\n\n // Use atomic write with better temp file naming\n // Include process.pid and hrtime for better uniqueness and easier debugging\n const hrtime = process.hrtime.bigint();\n const tempFile = `${targetFilePath}.tmp.${process.pid}.${hrtime}`;\n\n try {\n await writeFile(tempFile, serializedContent);\n await rename(tempFile, targetFilePath);\n } catch (error) {\n // Clean up temp file if rename fails\n try {\n await unlink(tempFile);\n } catch {\n // Ignore cleanup errors\n }\n throw error;\n }\n }\n\n // Calculate new etag from the written file\n const writtenBuffer = (await readFile(targetFilePath)) as Uint8Array;\n let newEtag: string;\n\n if (targetFilePath.endsWith('.mdx')) {\n // Find content position in MDX\n const contentStartMarker = new TextEncoder().encode('---\\n\\n');\n let contentPos = -1;\n for (let i = 0; i <= writtenBuffer.length - contentStartMarker.length; i++) {\n let match = true;\n for (let j = 0; j < contentStartMarker.length; j++) {\n if (writtenBuffer[i + j] !== contentStartMarker[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n contentPos = i + contentStartMarker.length;\n break;\n }\n }\n const etags = calculateEtagsFromMdxBuffer(writtenBuffer, contentPos);\n newEtag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else if (targetFilePath.endsWith('.json')) {\n // For data files, use simple etag (hash entire buffer)\n newEtag = VXJSON.calculateSimpleEtag(writtenBuffer);\n } else {\n // For VXJSON, calculateEtagsFromVXJSONBuffer finds the content position internally\n const etagResult = VXJSON.calculateETags(writtenBuffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format when updating content: ${etagResult.error}`);\n }\n\n newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n }\n\n // Build updated locale manifest with current publish data\n const updatedLocaleVersion: LocaleVersion = {\n ...localeVersion,\n etag: newEtag,\n modified,\n meta: newMeta,\n ...(data.pathname && { pathname: data.pathname }),\n ...(data.name && { name: data.name }),\n };\n\n // Handle publish dates using shared function\n // First preserve current values if not updating\n if (current.publishAt && !('publishAt' in data)) {\n updatedLocaleVersion.publishAt = current.publishAt;\n }\n if (current.unpublishAt && !('unpublishAt' in data)) {\n updatedLocaleVersion.unpublishAt = current.unpublishAt;\n }\n\n // Then apply updates\n updatePublishDates(updatedLocaleVersion, data);\n\n // Update pathname history if changed\n if (Object.keys(pathnameHistory).length > 0) {\n updatedLocaleVersion.previousPathnames = {\n ...localeVersion.previousPathnames,\n ...pathnameHistory,\n };\n } else {\n // Preserve existing previousPathnames if no change, but only if it has content\n const existingPreviousPathnames = localeVersion.previousPathnames;\n if (existingPreviousPathnames && Object.keys(existingPreviousPathnames).length > 0) {\n updatedLocaleVersion.previousPathnames = existingPreviousPathnames;\n } else {\n // Remove empty previousPathnames object\n delete updatedLocaleVersion.previousPathnames;\n }\n }\n\n // Store the old locale manifest for rollback if needed\n const oldLocaleVersion = manifest.locales[locale];\n\n try {\n // Update the locale in the existing manifest directly (avoids allocation)\n manifest.locales[locale] = updatedLocaleVersion;\n\n // Update index with the updated locale\n this.contentIndex.addContent(manifest, updatedLocaleVersion, newContent);\n\n // If pathname changed, delete the old file\n if (targetFilePath !== filePath) {\n try {\n await unlink(filePath);\n } catch (error) {\n // Log but don't fail if old file deletion fails\n console.warn(`Failed to delete old file ${filePath}:`, error);\n }\n }\n } catch (error) {\n // Rollback on error to maintain consistency\n manifest.locales[locale] = oldLocaleVersion;\n\n // If we wrote to a new file, try to clean it up\n if (targetFilePath !== filePath) {\n try {\n await unlink(targetFilePath);\n } catch {\n // Ignore cleanup errors\n }\n }\n\n throw error;\n }\n\n return {\n success: true,\n etag: newEtag,\n modified: new Date(),\n };\n } catch (error) {\n return {\n success: false,\n reason: 'write_error',\n error: ensureError(error),\n };\n }\n }\n\n async deleteContent(id: string, etag: string): Promise<DeleteResult> {\n // Get manifest for this ID\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Content not found'),\n };\n }\n\n // For deleteContent, we require the etag to match ANY locale (indicating user has current data)\n // But this is still a design flaw - we should probably require all etags or a master etag\n let matchingLocale: LocaleVersion | undefined;\n for (const localeVersion of localesOf(manifest)) {\n if (localeVersion.etag === etag) {\n matchingLocale = localeVersion;\n break;\n }\n }\n if (!matchingLocale) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag: Array.from(localesOf(manifest))[0]?.etag || '',\n error: new Error('Invalid etag - must match at least one locale'),\n };\n }\n\n try {\n // Delete all locale files in parallel\n const deletePromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {\n const filePath = this.getFilePath(manifest, localeVersion);\n await unlink(filePath);\n });\n\n await Promise.all(deletePromises);\n\n // Remove from index\n this.contentIndex.removeEntry(id);\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: ensureError(error),\n };\n }\n }\n\n async deleteLocalized(input: DeleteLocaleInput): Promise<DeleteResult> {\n const { id, locale, etag } = input;\n\n // Get manifest for this ID\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Content not found'),\n };\n }\n\n // Check if this locale exists\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Locale not found'),\n };\n }\n\n // Verify etag matches this locale\n if (localeVersion.etag !== etag) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag: localeVersion.etag,\n error: new Error('Invalid etag for locale'),\n };\n }\n\n // Don't allow deleting the last locale\n if (Object.keys(manifest.locales).length === 1) {\n return {\n success: false,\n error: new Error('Cannot delete the last locale. Use deleteContent to delete all content.'),\n };\n }\n\n try {\n // Delete the locale file\n const filePath = this.getFilePath(manifest, localeVersion);\n await unlink(filePath);\n\n // Remove locale from manifest and index\n manifest.locales[locale] = undefined;\n this.contentIndex.removeLocale(manifest.id, locale);\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: ensureError(error),\n };\n }\n }\n\n getSite(siteName: string): Site | null {\n if (siteName === 'blocks') {\n throw new Error('Use `blocks` property instead of getSite(\"blocks\")');\n }\n\n const site = this.sites[siteName];\n return site || null;\n }\n\n *listAllContent(filters?: GlobalFilters): Generator<ContentManifest> {\n yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);\n }\n *findUntranslatedContent(targetLocale: string, options?: FindOptions): Generator<ContentManifest> {\n yield* this.contentIndex.findUntranslatedContent(targetLocale, options);\n }\n\n /**\n * Reindex files that were added or changed after initial creation\n *\n * This method:\n * 1. Either scans for all content files or processes specific paths\n * 2. Uses the path index to check if files are already indexed\n * 3. Indexes new files or force-reindexes specified files\n * 4. Optionally handles file deletions\n *\n * @param paths - Optional array of specific file paths to reindex. If not provided, scans all content files.\n * @param options - Options for reindexing behavior\n * @returns Statistics about the reindexing operation\n */\n async reindex(paths?: string[], options?: { handleDeletions?: boolean }): Promise<ReindexResult> {\n const filesToProcess = paths || (await this.scanContentFiles());\n let filesSkipped = 0;\n let filesProcessed = 0;\n let filesDeleted = 0;\n let errors = 0;\n const filesToIndex: string[] = [];\n const updated: LocalizedManifest[] = [];\n const deleted: Array<{ id: string; locale: string; kind: 'page' | 'block' | 'data' }> = [];\n\n // Check each file\n for (const filePath of filesToProcess) {\n // Check if file exists (for deletion handling)\n if (options?.handleDeletions && paths) {\n try {\n await readFile(filePath);\n } catch (error) {\n // File doesn't exist - remove from index\n const parsed = this.parseFilePath(filePath);\n if (parsed) {\n // Find the content ID to remove\n let manifest: ContentManifest | null = null;\n if (parsed.kind === 'block' && parsed.name) {\n manifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);\n } else if (parsed.kind === 'data' && parsed.name) {\n manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);\n } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {\n manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);\n }\n\n if (manifest) {\n // Track the deletion\n deleted.push({\n id: manifest.id,\n locale: parsed.locale,\n kind: parsed.kind,\n });\n\n // Remove the specific locale or entire entry if it's the last locale\n if (Object.keys(manifest.locales).length === 1) {\n this.contentIndex.removeEntry(manifest.id);\n } else {\n // Remove just this locale\n manifest.locales[parsed.locale] = undefined;\n this.contentIndex.removeLocale(manifest.id, parsed.locale);\n }\n filesDeleted++;\n }\n }\n continue;\n }\n }\n\n const parsed = this.parseFilePath(filePath);\n if (!parsed) {\n console.warn(`Skipping unrecognized file pattern: ${filePath}`);\n errors++;\n continue;\n }\n\n // Check if this path is already indexed\n let isIndexed = false;\n if (parsed.kind === 'block' && parsed.name) {\n // Check block index by name\n const manifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);\n isIndexed = !!manifest;\n } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {\n // Check site index by pathname\n const manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);\n isIndexed = !!manifest;\n } else if (parsed.kind === 'data' && parsed.name) {\n // Check data index by name\n const manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);\n isIndexed = !!manifest;\n }\n\n if (isIndexed) {\n if (!paths) {\n // Skip already indexed files when doing a full scan\n filesSkipped++;\n } else {\n // For specific paths, check if the file has changed\n const fileStats = await readFile(filePath);\n let currentManifest: ContentManifest | null = null;\n if (parsed.kind === 'block' && parsed.name) {\n currentManifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);\n } else if (parsed.kind === 'data' && parsed.name) {\n currentManifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);\n } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {\n currentManifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);\n }\n\n if (currentManifest) {\n // Calculate current file etag\n const buffer = fileStats as Uint8Array;\n let currentEtag: string;\n\n if (filePath.endsWith('.mdx')) {\n const contentPos = findMdxContentStartPosition(buffer);\n const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);\n currentEtag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else if (filePath.endsWith('.vxjson')) {\n const etagResult = VXJSON.calculateETags(buffer);\n if (!etagResult.success) {\n // File needs repair - add to filesToIndex for repair\n filesToIndex.push(filePath);\n continue;\n }\n currentEtag = etagResult.contentEtag\n ? `${etagResult.metaEtag}.${etagResult.contentEtag}`\n : etagResult.metaEtag;\n } else if (filePath.endsWith('.json')) {\n // For JSON data files, use content hash as etag\n currentEtag = xxh3.xxh64(buffer).toString(16);\n } else {\n // Unknown file type, skip\n filesSkipped++;\n continue;\n }\n\n // Only reindex if etag changed\n const existingEtag = currentManifest.locales[parsed.locale]?.etag;\n\n if (existingEtag === currentEtag) {\n const relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n console.log(`[Content] skip ${relativePath} (unchanged)`);\n filesSkipped++;\n } else {\n filesToIndex.push(filePath);\n }\n } else {\n // Not indexed yet\n filesToIndex.push(filePath);\n }\n }\n } else {\n // Not indexed yet\n filesToIndex.push(filePath);\n }\n }\n\n // Index the files\n const buffers = Array.from({ length: Math.min(filesToIndex.length, 100) }, () => new Uint8Array(4096));\n\n for (let i = 0; i < filesToIndex.length; i++) {\n const filePath = filesToIndex[i];\n const bufferIndex = i % buffers.length;\n\n try {\n const result = await this.parseFileHeaderWithRepair(filePath, buffers[bufferIndex]);\n if (result) {\n const { manifest, localeVersion, content } = result;\n\n // Add to index\n this.contentIndex.addContent(manifest, localeVersion, content);\n filesProcessed++;\n\n // Create LocalizedManifest for the updated list\n const localizedManifest: LocalizedManifest = {\n id: manifest.id,\n type: manifest.type,\n kind: manifest.kind,\n site: manifest.site,\n collection: manifest.collection,\n localized: localeVersion,\n };\n updated.push(localizedManifest);\n }\n } catch (error) {\n console.error(`Failed to reindex ${filePath}:`, error);\n errors++;\n }\n }\n\n const result: ReindexResult = {\n filesProcessed,\n filesSkipped,\n updated,\n };\n\n if (options?.handleDeletions && deleted.length > 0) {\n result.filesDeleted = filesDeleted;\n result.deleted = deleted;\n }\n\n if (errors > 0) {\n result.errors = errors;\n }\n\n return result;\n }\n\n /**\n * Read content directly from cache\n * For testing purposes - returns null if not cached\n */\n async readFromCache(id: string, locale: string): Promise<ContentData | null> {\n return this.contentIndex.getCachedContent(id, locale);\n }\n\n async getContentAsBuffer(\n id: string,\n locale: string,\n ): Promise<{\n buffer: Uint8Array;\n etag: string;\n contentType: 'application/json' | 'text/mdx';\n } | null> {\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest || !manifest.locales[locale]) {\n return null;\n }\n\n const localeVersion = manifest.locales[locale];\n const filePath = this.getFilePath(manifest, localeVersion);\n const buffer = (await readFile(filePath)) as Uint8Array;\n const contentType = filePath.endsWith('.mdx') ? 'text/mdx' : 'application/json';\n\n // Calculate ETag based on file type\n let etag: string;\n if (contentType === 'text/mdx') {\n // Find content start position for MDX\n const contentStartMarker = new TextEncoder().encode('---\\n\\n');\n let contentPos = -1;\n for (let i = 0; i <= buffer.length - contentStartMarker.length; i++) {\n let match = true;\n for (let j = 0; j < contentStartMarker.length; j++) {\n if (buffer[i + j] !== contentStartMarker[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n contentPos = i + contentStartMarker.length;\n break;\n }\n }\n const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);\n etag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else {\n // Calculate ETags for JSON\n const etagResult = VXJSON.calculateETags(buffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format in getContentAsBuffer: ${etagResult.error}`);\n }\n\n etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n }\n\n return { buffer, etag, contentType };\n }\n\n async batchUpdate(operations: UpdateLocaleInput[]): Promise<BatchResult> {\n // First, validate all operations can succeed\n const validationResults: Array<{\n op: UpdateLocaleInput;\n manifest: ContentManifest;\n localeVersion: LocaleVersion;\n current?: LocaleFileData;\n }> = [];\n\n for (const op of operations) {\n const manifest = this.contentIndex.getManifest(op.id);\n if (!manifest) {\n // Content not found\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error('Content not found'),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n\n const localeVersion = manifest.locales[op.locale];\n if (!localeVersion) {\n // Locale not found\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error('Locale not found'),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n\n // Check etag\n if (localeVersion.etag !== op.etag) {\n // Stale write detected\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error('Stale write'),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n\n // Read current content for validation\n const filePath = this.getFilePath(manifest, localeVersion);\n const current = await this.readLocaleFile(filePath, op.locale);\n if (!current) {\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error('Failed to read content'),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n\n // Validate metadata size if updating\n if (op.data.meta) {\n const newMeta = { ...current.meta, ...op.data.meta };\n const validation = validateAndPrepareMetadata(newMeta);\n if (!validation.valid) {\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error(validation.error!),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n }\n\n validationResults.push({ op, manifest, localeVersion, current });\n }\n\n // All validations passed, now perform updates\n const results: BatchOperationResult[] = [];\n let updated = 0;\n\n for (const { op } of validationResults) {\n const result = await this.updateLocalized(op);\n if (result.success) {\n updated++;\n results.push({ id: op.id, locale: op.locale, updated: true, etag: result.etag });\n } else {\n // This shouldn't happen if validation was correct\n results.push({ id: op.id, locale: op.locale, updated: false, error: result.error });\n }\n }\n\n return {\n operations: results,\n success: updated === operations.length,\n updated,\n failed: operations.length - updated,\n };\n }\n}\n","import { normalize, resolve } from 'path';\nimport { FileSystemContentAPI } from './filesystem-content-api';\n\nexport interface ContentWatcherOptions {\n contentRoot: string;\n canvasDir?: string;\n}\n\nexport interface WebSocketSender {\n send(payload: { type: string; event: string; data: any }): void;\n}\n\n/**\n * Creates a content API instance for the given options\n */\nexport async function createContentAPI(options: ContentWatcherOptions): Promise<FileSystemContentAPI> {\n return await FileSystemContentAPI.create({\n contentRoot: options.contentRoot,\n canvasDir: options.canvasDir || './canvas',\n });\n}\n\n/**\n * Creates file change handlers for content watching\n */\nexport function createContentWatchHandlers(\n contentApi: FileSystemContentAPI,\n options: ContentWatcherOptions,\n ws: WebSocketSender,\n) {\n const handleFileChange = async (file: string, action: 'update' | 'create' | 'delete') => {\n // Only process content files (.mdx, .vxjson, and .json in data/ directory)\n const isContentFile = file.endsWith('.mdx') || file.endsWith('.vxjson');\n const isDataFile = file.endsWith('.json') && file.includes('/data/');\n if (!isContentFile && !isDataFile) {\n return;\n }\n\n // Normalize paths for consistent comparison\n const normalizedFile = normalize(resolve(file));\n const normalizedRoot = normalize(resolve(options.contentRoot));\n\n if (normalizedFile.startsWith(normalizedRoot)) {\n const relativePath = normalizedFile.replace(normalizedRoot + '/', '');\n console.log(`[Content] ${action}: ${relativePath}`);\n\n try {\n // Reindex the file\n const reindexOptions = action === 'delete' ? { handleDeletions: true } : undefined;\n const result = await contentApi.reindex([normalizedFile], reindexOptions);\n\n // Send updates for each changed locale\n for (const manifest of result.updated) {\n const message = {\n type: 'custom',\n event: 'conloca:content-update',\n data: {\n action,\n manifest,\n },\n };\n ws.send(message);\n }\n\n // Send deletion updates\n if (action === 'delete' && result.deleted) {\n for (const deletion of result.deleted) {\n ws.send({\n type: 'custom',\n event: 'conloca:content-update',\n data: {\n action: 'delete',\n ...deletion,\n },\n });\n }\n }\n } catch (error) {\n console.error('[Content Watcher] Reindex failed:', error);\n return;\n }\n }\n };\n\n return {\n onChange: (file: string) => handleFileChange(file, 'update'),\n onAdd: (file: string) => handleFileChange(file, 'create'),\n onUnlink: (file: string) => handleFileChange(file, 'delete'),\n };\n}\n","import { Blocks } from './blocks';\nimport type { ContentAPI } from './content-api.interface';\nimport { filterContentWithIndexes } from './content-filters';\nimport { ContentIndex } from './content-index';\nimport {\n buildLocaleVersion,\n buildPathnameHistory,\n generateContentId,\n isContentPublished,\n shouldUpdateModifiedTimestamp,\n updatePublishDates,\n validateAndPrepareMetadata,\n validateCreateContent,\n} from './content-operations';\nimport { getCurrentISODate, localesOf, mapLocales, mapSiteNames, serializeMdxWithFrontmatter } from './content-utils';\nimport { Data } from './data';\nimport { calculateEtagsFromMdxBuffer, findMdxContentStartPosition } from './etag-utils';\nimport { Site } from './site';\nimport type {\n BatchResult,\n ContentData,\n ContentEntry,\n ContentManifest,\n ContentMeta,\n CreateContentInput,\n CreateResult,\n DeleteLocaleInput,\n DeleteResult,\n FindOptions,\n GlobalFilters,\n LocaleVersion,\n LocalizedEntry,\n SitesConfig,\n UpdateLocaleInput,\n UpdateResult,\n VXJSONFile,\n} from './types';\nimport { VXJSON } from './vxjson';\n\n/**\n * In-memory implementation of ContentAPI for testing\n * Provides a clean, mock-free way to test the API without filesystem dependencies\n */\nexport class InMemoryContentAPI implements ContentAPI {\n private contentIndex: ContentIndex;\n readonly sitesConfig: SitesConfig;\n readonly blocks: Blocks;\n readonly data: Data;\n private readonly sites: Record<string, Site>;\n\n constructor(sitesConfig?: SitesConfig) {\n this.sitesConfig = sitesConfig || {\n sites: {},\n globalLocales: ['en'],\n };\n\n // Initialize content index (not cached for in-memory)\n this.contentIndex = ContentIndex.createUncached(this.sitesConfig);\n\n // Initialize blocks\n this.blocks = new Blocks(this, this.contentIndex.getBlockIndex());\n\n // Initialize data\n this.data = new Data(this, this.contentIndex.getDataIndex());\n\n // Initialize all sites\n this.sites = mapSiteNames(this.sitesConfig, (siteName) => {\n const siteIndex = this.contentIndex.getSiteIndex(siteName);\n if (!siteIndex) {\n throw new Error(`Site index not found for ${siteName}`);\n }\n return new Site(siteName, this, siteIndex);\n });\n }\n\n // Core content operations\n async getContent(id: string): Promise<ContentEntry | null> {\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return null;\n }\n\n // Build ContentEntry from manifest and cached content\n const contentEntry: ContentEntry = {\n id: manifest.id,\n kind: manifest.kind,\n site: manifest.site,\n collection: manifest.collection,\n type: manifest.type,\n locales: {},\n };\n\n // Add locale data with content from cache\n for (const localeVersion of localesOf(manifest)) {\n const { locale } = localeVersion;\n const cachedContent = this.contentIndex.getCachedContent(id, locale);\n if (cachedContent) {\n // For MDX content, include frontmatter for variable access\n let contentToReturn = cachedContent;\n if (manifest.type === 'mdx' && cachedContent.mdx) {\n const frontmatterData = {\n id: manifest.id,\n created: localeVersion.created,\n modified: localeVersion.modified,\n ...(localeVersion.publishAt && { publishAt: localeVersion.publishAt }),\n ...(localeVersion.unpublishAt && { unpublishAt: localeVersion.unpublishAt }),\n ...localeVersion.meta, // Spread metadata fields directly\n };\n contentToReturn = {\n ...cachedContent,\n mdx: serializeMdxWithFrontmatter(frontmatterData, cachedContent.mdx),\n };\n }\n\n contentEntry.locales[locale] = {\n ...localeVersion,\n content: contentToReturn,\n };\n }\n }\n\n return contentEntry;\n }\n\n async getLocalized(id: string, locale: string): Promise<LocalizedEntry | null> {\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest || !manifest.locales[locale]) {\n return null;\n }\n\n const localeVersion = manifest.locales[locale];\n const cachedContent = this.contentIndex.getCachedContent(id, locale);\n\n if (!cachedContent) {\n return null;\n }\n\n // For MDX content, include frontmatter for variable access\n let contentToReturn = { ...cachedContent };\n if (manifest.type === 'mdx' && cachedContent.mdx) {\n const frontmatterData = {\n id: manifest.id,\n created: localeVersion.created,\n modified: localeVersion.modified,\n ...(localeVersion.publishAt && { publishAt: localeVersion.publishAt }),\n ...(localeVersion.unpublishAt && { unpublishAt: localeVersion.unpublishAt }),\n ...localeVersion.meta, // Spread metadata fields directly\n };\n contentToReturn = {\n ...cachedContent,\n mdx: serializeMdxWithFrontmatter(frontmatterData, cachedContent.mdx),\n };\n }\n\n // Return a deep copy to prevent modifications to the original data\n return {\n id,\n site: manifest.site,\n collection: manifest.collection,\n type: manifest.type,\n kind: manifest.kind,\n localized: {\n ...localeVersion,\n meta: { ...localeVersion.meta },\n content: contentToReturn,\n previousPathnames: localeVersion.previousPathnames ? { ...localeVersion.previousPathnames } : undefined,\n },\n };\n }\n\n async createContent(data: CreateContentInput): Promise<CreateResult> {\n // Use shared validation\n const validation = validateCreateContent(data, this.sites, this.blocks);\n if (!validation.valid) {\n return {\n success: false,\n reason: validation.reason,\n error: validation.error ? new Error(validation.error) : undefined,\n existingId: validation.existingId,\n };\n }\n\n // Generate ID\n const id = generateContentId();\n const now = getCurrentISODate();\n\n const contentCache: Record<string, ContentData> = {};\n\n const locales = mapLocales(\n data.site ? this.sitesConfig.sites[data.site].locales : this.sitesConfig.globalLocales,\n (locale) => {\n const localeData = data.locales[locale];\n if (!localeData) return undefined;\n\n const meta = { ...data.meta, ...localeData.meta } as ContentMeta;\n\n // Calculate dual ETag for this locale\n const fileData: VXJSONFile = {\n id,\n type: data.type,\n created: now,\n modified: now,\n publishAt:\n localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,\n unpublishAt:\n localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,\n meta,\n content: localeData.content,\n };\n\n // Serialize to buffer and calculate ETags based on content type\n let buffer: Uint8Array;\n let etag: string;\n\n if (data.type === 'mdx') {\n // For MDX content, serialize as frontmatter + content\n const frontmatterData = {\n id,\n created: now,\n modified: now,\n ...(localeData.publishAt && { publishAt: localeData.publishAt }),\n ...(localeData.unpublishAt && { unpublishAt: localeData.unpublishAt }),\n ...meta, // Spread metadata fields directly, not nested\n };\n\n const mdxContent = serializeMdxWithFrontmatter(frontmatterData, localeData.content.mdx || '');\n buffer = new TextEncoder().encode(mdxContent);\n\n // Find content start position using shared utility\n const contentPos = findMdxContentStartPosition(buffer);\n\n // Calculate ETags using MDX-specific logic\n const etagResult = calculateEtagsFromMdxBuffer(buffer, contentPos);\n etag = `${etagResult.metaEtag}.${etagResult.contentEtag}`;\n } else {\n // For Puck content, serialize as VXJSON\n const jsonStr = VXJSON.serialize(fileData);\n buffer = Buffer.from(jsonStr, 'utf-8') as Uint8Array;\n const etagResult = VXJSON.calculateETags(buffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format: ${etagResult.error}`);\n }\n\n etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n }\n\n // Build locale manifest using shared function\n const localeVersion = buildLocaleVersion({\n locale,\n etag,\n created: now,\n modified: now,\n meta,\n kind: data.kind,\n pathname: data.kind === 'page' ? localeData.pathname : undefined,\n name: data.kind === 'block' || data.kind === 'data' ? data.name : undefined,\n publishAt:\n localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,\n unpublishAt:\n localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,\n });\n\n contentCache[locale] = localeData.content;\n return localeVersion;\n },\n );\n\n // Build manifest and content cache\n const manifest: ContentManifest = {\n id,\n type: data.type,\n kind: data.kind,\n site: data.site,\n collection: data.collection,\n locales,\n };\n\n // Update index with each locale\n for (const localeVersion of localesOf(manifest)) {\n this.contentIndex.addContent(manifest, localeVersion, contentCache[localeVersion.locale]);\n }\n\n // Return the first locale's etag (typically there's only one during creation)\n const firstLocaleEtag = Object.values(manifest.locales)[0]?.etag || '';\n\n return {\n success: true,\n id,\n etag: firstLocaleEtag,\n created: new Date(now),\n };\n }\n\n async updateLocalized(input: UpdateLocaleInput): Promise<UpdateResult> {\n const { id, locale, data, etag } = input;\n\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Get the specific locale manifest\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Check etag matches\n if (localeVersion.etag !== etag) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag: localeVersion.etag,\n };\n }\n\n // Get current content from cache\n const currentContent = this.contentIndex.getCachedContent(id, locale);\n if (!currentContent) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Validate metadata if updating\n if (data.meta) {\n const newMeta = { ...localeVersion.meta, ...data.meta };\n const validation = validateAndPrepareMetadata(newMeta);\n if (!validation.valid) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error(validation.error!),\n };\n }\n }\n\n // Validate pathname change if updating pathname for pages\n if (data.pathname && manifest.kind === 'page' && manifest.site) {\n const site = this.sites[manifest.site];\n if (site) {\n // Check if new pathname is already taken by another content\n const existingId = site.getPathnameConflict(data.pathname, locale, id);\n if (existingId) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error(`Pathname ${data.pathname} is already taken by content ${existingId}`),\n };\n }\n }\n }\n\n // Update content\n const now = new Date();\n const nowStr = now.toISOString();\n\n // Build updated locale manifest\n const oldPathname = localeVersion.pathname;\n const updatedLocaleVersion = { ...localeVersion };\n\n // Update modified timestamp for any changes (content or metadata)\n if (shouldUpdateModifiedTimestamp(data)) {\n // Use provided modified timestamp or current time\n const newModified = data.modified || nowStr;\n updatedLocaleVersion.modified = newModified;\n } else if (data.modified) {\n // If modified timestamp is explicitly provided, always use it\n updatedLocaleVersion.modified = data.modified;\n }\n\n if (data.meta) {\n updatedLocaleVersion.meta = { ...localeVersion.meta, ...data.meta };\n }\n\n if (data.pathname !== undefined && manifest.kind === 'page') {\n // Build pathname history for published content\n const pathnameHistory = buildPathnameHistory(\n oldPathname,\n data.pathname,\n isContentPublished(localeVersion),\n nowStr,\n );\n\n // Merge with existing pathname history\n if (Object.keys(pathnameHistory).length > 0) {\n updatedLocaleVersion.previousPathnames = {\n ...localeVersion.previousPathnames,\n ...pathnameHistory,\n };\n }\n\n updatedLocaleVersion.pathname = data.pathname;\n }\n\n // Handle publish date updates using shared function\n updatePublishDates(updatedLocaleVersion, data);\n\n // Prepare updated content\n const updatedContent = data.content ? { ...currentContent, ...data.content } : currentContent;\n\n // Calculate new dual ETag by creating a buffer from the in-memory data\n // Structure it like the filesystem JSON files\n const fileData: VXJSONFile = {\n id: manifest.id,\n type: manifest.type,\n created: updatedLocaleVersion.created,\n modified: updatedLocaleVersion.modified,\n publishAt: updatedLocaleVersion.publishAt,\n unpublishAt: updatedLocaleVersion.unpublishAt,\n meta: updatedLocaleVersion.meta,\n previousPathnames: updatedLocaleVersion.previousPathnames,\n content: updatedContent,\n };\n\n // Serialize to buffer and calculate ETags based on content type\n let buffer: Uint8Array;\n let newEtag: string;\n\n if (manifest.type === 'mdx') {\n // For MDX content, serialize as frontmatter + content\n const frontmatterData = {\n id: manifest.id,\n created: updatedLocaleVersion.created,\n modified: updatedLocaleVersion.modified,\n ...(updatedLocaleVersion.publishAt && { publishAt: updatedLocaleVersion.publishAt }),\n ...(updatedLocaleVersion.unpublishAt && { unpublishAt: updatedLocaleVersion.unpublishAt }),\n ...updatedLocaleVersion.meta, // Spread metadata fields directly, not nested\n };\n\n const mdxContent = serializeMdxWithFrontmatter(frontmatterData, updatedContent.mdx || '');\n buffer = new TextEncoder().encode(mdxContent);\n\n // Find content start position using shared utility\n const contentPos = findMdxContentStartPosition(buffer);\n\n // Calculate ETags using MDX-specific logic\n const etagResult = calculateEtagsFromMdxBuffer(buffer, contentPos);\n newEtag = `${etagResult.metaEtag}.${etagResult.contentEtag}`;\n } else {\n // For Puck content, serialize as VXJSON\n const jsonStr = VXJSON.serialize(fileData);\n buffer = Buffer.from(jsonStr, 'utf-8') as Uint8Array;\n const etagResult = VXJSON.calculateETags(buffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format: ${etagResult.error}`);\n }\n\n newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n }\n\n updatedLocaleVersion.etag = newEtag;\n\n // Build updated manifest with only the changed locale\n const updatedManifest: ContentManifest = {\n ...manifest,\n locales: {\n ...manifest.locales,\n [locale]: updatedLocaleVersion,\n },\n };\n\n // Update content in the index (this will handle pathname index updates)\n this.contentIndex.addContent(updatedManifest, updatedLocaleVersion, updatedContent);\n\n return {\n success: true,\n etag: updatedLocaleVersion.etag,\n modified: now,\n };\n }\n\n async deleteContent(id: string, etag: string): Promise<DeleteResult> {\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Content not found'),\n };\n }\n\n // Verify etag\n let hasMatchingEtag = false;\n for (const localeVersion of localesOf(manifest)) {\n if (localeVersion.etag === etag) {\n hasMatchingEtag = true;\n break;\n }\n }\n\n if (!hasMatchingEtag && etag) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag: Array.from(localesOf(manifest))[0]?.etag || '',\n error: new Error('ETag mismatch'),\n };\n }\n\n // Remove from index (this also removes from content cache)\n this.contentIndex.removeEntry(id);\n\n return {\n success: true,\n };\n }\n\n // Site and blocks access\n getSite(siteName: string): Site | null {\n if (siteName === 'blocks') {\n throw new Error('Use `blocks` property instead of getSite(\"blocks\")');\n }\n\n const site = this.sites[siteName];\n return site || null;\n }\n\n // Global operations\n *listAllContent(filters?: GlobalFilters): Generator<ContentManifest> {\n yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);\n }\n\n *findUntranslatedContent(targetLocale: string, options?: FindOptions): Generator<ContentManifest> {\n // Use the index method which already handles all the filtering efficiently\n yield* this.contentIndex.findUntranslatedContent(targetLocale, options);\n }\n\n async deleteLocalized(input: DeleteLocaleInput): Promise<DeleteResult> {\n const { id, locale, etag } = input;\n\n // Get existing manifest\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Content not found'),\n };\n }\n\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Locale not found'),\n };\n }\n\n // Check etag\n if (localeVersion.etag !== etag) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag: localeVersion.etag,\n error: new Error('Stale write - etag mismatch'),\n };\n }\n\n // If only one locale left, remove entire content\n if (Object.keys(manifest.locales).length === 1) {\n this.contentIndex.removeEntry(id);\n } else {\n // Build updated manifest without the deleted locale\n const updatedManifest: ContentManifest = {\n ...manifest,\n locales: { ...manifest.locales },\n };\n updatedManifest.locales[locale] = undefined;\n\n // Remove locale from index\n this.contentIndex.removeLocale(manifest.id, locale);\n }\n\n return {\n success: true,\n };\n }\n\n async batchUpdate(operations: UpdateLocaleInput[]): Promise<BatchResult> {\n const results: BatchResult = {\n operations: [],\n success: true,\n failed: 0,\n updated: 0,\n };\n\n for (const op of operations) {\n const result = await this.updateLocalized(op);\n\n if (result.success) {\n results.updated++;\n results.operations.push({\n id: op.id,\n locale: op.locale,\n updated: true,\n etag: result.etag,\n });\n } else {\n results.failed++;\n results.success = false;\n results.operations.push({\n id: op.id,\n locale: op.locale,\n updated: false,\n error: result.error || new Error(result.reason || 'Update failed'),\n });\n }\n }\n\n return results;\n }\n\n // Test helper method to directly set content\n setContent(id: string, content: ContentEntry): void {\n // Build manifest from ContentEntry\n const manifest: ContentManifest = {\n id: content.id,\n type: content.type,\n kind: content.kind,\n site: content.site,\n collection: content.collection,\n locales: {},\n };\n\n const contentCache: Record<string, ContentData | null> = {};\n\n for (const [locale, localeData] of Object.entries(content.locales)) {\n const manifestLocale: LocaleVersion = {\n locale,\n etag: localeData.etag,\n created: localeData.created,\n modified: localeData.modified,\n meta: localeData.meta,\n };\n if (localeData.publishAt !== undefined) {\n manifestLocale.publishAt = localeData.publishAt;\n }\n if (localeData.unpublishAt !== undefined) {\n manifestLocale.unpublishAt = localeData.unpublishAt;\n }\n if (localeData.name) {\n manifestLocale.name = localeData.name;\n }\n if (localeData.pathname) {\n manifestLocale.pathname = localeData.pathname;\n }\n if (localeData.previousPathnames) {\n manifestLocale.previousPathnames = localeData.previousPathnames;\n }\n manifest.locales[locale] = manifestLocale;\n contentCache[locale] = localeData.content;\n }\n\n // Add to content index with each locale\n for (const localeVersion of localesOf(manifest)) {\n this.contentIndex.addContent(manifest, localeVersion, contentCache[localeVersion.locale]);\n }\n }\n\n // Test helper to clear all content\n clear(): void {\n this.contentIndex.clear();\n }\n\n async getContentAsBuffer(\n id: string,\n locale: string,\n ): Promise<{\n buffer: Uint8Array;\n etag: string;\n contentType: 'application/json' | 'text/mdx';\n } | null> {\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest || !manifest.locales[locale]) {\n return null;\n }\n\n const localeVersion = manifest.locales[locale];\n const cachedContent = this.contentIndex.getCachedContent(id, locale);\n if (!cachedContent) {\n return null;\n }\n\n // Serialize based on content type\n let buffer: Uint8Array;\n let calculatedEtag: string;\n let contentType: 'application/json' | 'text/mdx';\n\n if (manifest.type === 'mdx') {\n // For MDX content, serialize as frontmatter + content\n const frontmatterData = {\n id: manifest.id,\n created: localeVersion.created,\n modified: localeVersion.modified,\n ...(localeVersion.publishAt && { publishAt: localeVersion.publishAt }),\n ...(localeVersion.unpublishAt && { unpublishAt: localeVersion.unpublishAt }),\n ...localeVersion.meta, // Spread metadata fields directly, not nested\n };\n\n const mdxContent = serializeMdxWithFrontmatter(frontmatterData, cachedContent.mdx || '');\n buffer = new TextEncoder().encode(mdxContent);\n\n // Find content start position using shared utility\n const contentPos = findMdxContentStartPosition(buffer);\n\n // Calculate ETags using MDX-specific logic\n const etagResult = calculateEtagsFromMdxBuffer(buffer, contentPos);\n calculatedEtag = `${etagResult.metaEtag}.${etagResult.contentEtag}`;\n contentType = 'text/mdx';\n } else {\n // For Puck content, serialize as VXJSON\n const fileData: VXJSONFile = {\n id: manifest.id,\n type: manifest.type,\n created: localeVersion.created,\n modified: localeVersion.modified,\n publishAt: localeVersion.publishAt,\n unpublishAt: localeVersion.unpublishAt,\n meta: localeVersion.meta,\n previousPathnames: localeVersion.previousPathnames,\n content: cachedContent,\n };\n const jsonStr = VXJSON.serialize(fileData);\n buffer = Buffer.from(jsonStr, 'utf-8') as Uint8Array;\n\n // Calculate ETags to ensure they match what's stored\n const etagResult = VXJSON.calculateETags(buffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format: ${etagResult.error}`);\n }\n\n calculatedEtag = etagResult.contentEtag\n ? `${etagResult.metaEtag}.${etagResult.contentEtag}`\n : etagResult.metaEtag;\n contentType = 'application/json';\n }\n\n return {\n buffer,\n etag: calculatedEtag,\n contentType,\n };\n }\n}\n","import { Hono } from 'hono';\nimport { cors } from 'hono/cors';\nimport { type AssetConfig, AssetOperations } from './asset-operations';\nimport type { ContentAPI } from './content-api.interface';\nimport { localesOf } from './content-utils';\nimport { createGitOperations, type GitAuthor, type GitConfig } from './git-operations';\nimport type { APIError, ContentManifest, ErrorCode, FindOptions, GlobalFilters } from './types';\nimport { ErrorCodes } from './types';\n\n/**\n * Helper to create standardized error responses\n */\nfunction errorResponse(code: ErrorCode, message: string, details?: any): APIError {\n return {\n error: {\n code,\n message,\n ...(details && { details }),\n },\n };\n}\n\n/**\n * Helper to log and create error responses for unexpected errors\n */\nfunction logAndCreateErrorResponse(error: unknown, code: ErrorCode, message: string, details?: any): APIError {\n console.error(`[Content API] ${message}:`, error);\n return errorResponse(code, message, details);\n}\n\n/**\n * Create REST API router using Hono\n * Implements the ID-based API specification from implementation-plan.md\n */\nexport interface ContentAPIRouterOptions {\n assetsPath?: string;\n assetConfig?: Omit<AssetConfig, 'assetsPath'>;\n /** Content root directory for asset usage tracking */\n contentRoot?: string;\n}\n\nexport function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRouterOptions) {\n const app = new Hono();\n\n // Enable CORS for CMS access\n app.use('/*', cors());\n\n // GET /auth/user - Get current authenticated user\n app.get('/auth/user', async (c) => {\n const email = c.req.header('X-CF-User-Email');\n const sub = c.req.header('X-CF-User-Sub');\n\n if (!email) {\n return c.json({ authenticated: false });\n }\n\n return c.json({\n authenticated: true,\n user: { email, sub },\n });\n });\n\n // GET /content/collections - List all collections across all sites\n app.get('/content/collections', async (c) => {\n try {\n const allCollections = new Set<string>();\n\n // Get collections from blocks\n const blockCollections = api.blocks.collections;\n blockCollections.forEach((c) => allCollections.add(c));\n\n // Get collections from all sites\n for (const siteName of Object.keys(api.sitesConfig.sites)) {\n const site = api.getSite(siteName);\n if (site) {\n const siteCollections = site.collections;\n siteCollections.forEach((c) => allCollections.add(c));\n }\n }\n\n return c.json({\n collections: Array.from(allCollections).sort(),\n });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list collections'), 500);\n }\n });\n\n // GET /content - List all content with optional filters\n app.get('/content', async (c) => {\n const kind = c.req.query('kind'); // 'block' or 'page'\n const site = c.req.query('site');\n const collection = c.req.query('collection');\n const locales = c.req.query('locales'); // comma-separated\n const type = c.req.query('type'); // 'puck' or 'mdx'\n const published = c.req.query('published');\n const localization = c.req.query('localization'); // 'complete', 'partial', 'one'\n const missingLocales = c.req.query('missingLocales'); // comma-separated\n\n try {\n const filters: any = {};\n\n // Pass all filters to the API - let it handle the logic\n if (kind) filters.kind = kind;\n if (site) filters.site = site;\n if (collection) filters.collection = collection;\n if (locales) filters.locales = locales.split(',').map((l) => l.trim());\n if (type) filters.type = type;\n if (published !== undefined) filters.published = published === 'true';\n if (localization) filters.localization = localization;\n if (missingLocales) filters.missingLocales = missingLocales.split(',').map((l) => l.trim());\n\n const items = Array.from(api.listAllContent(filters));\n return c.json({ items, total: items.length });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list content'), 500);\n }\n });\n\n // GET /content/:id - Get all locales for content ID\n app.get('/content/:id', async (c) => {\n const id = c.req.param('id');\n\n try {\n const content = await api.getContent(id);\n\n if (!content) {\n return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);\n }\n\n return c.json(content);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch content'), 500);\n }\n });\n\n // GET /content/:id/:locale - Get specific locale only\n app.get('/content/:id/:locale', async (c) => {\n const id = c.req.param('id');\n const locale = c.req.param('locale');\n\n try {\n const content = await api.getLocalized(id, locale);\n\n if (!content) {\n return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);\n }\n\n // Set ETag header\n c.header('ETag', content.localized.etag);\n\n return c.json(content);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch localized content'), 500);\n }\n });\n\n // POST /content - Create new content\n app.post('/content', async (c) => {\n try {\n const data = await c.req.json();\n const result = await api.createContent(data);\n\n if (!result.success) {\n if (result.reason === 'already_exists') {\n return c.json(result, 409);\n }\n if (result.reason === 'pathname_taken') {\n return c.json(result, 409);\n }\n if (result.reason === 'metadata_too_large') {\n return c.json(result, 400);\n }\n return c.json(result, 500);\n }\n\n return c.json(result, 201);\n } catch (error) {\n console.error('[Content API] Failed to create content:', error);\n return c.json(\n {\n success: false,\n reason: 'write_error',\n error: error instanceof Error ? error.message : 'Unknown error',\n },\n 500,\n );\n }\n });\n\n // PUT /content/:id - Update content (full update)\n app.put('/content/:id', async (c) => {\n const id = c.req.param('id');\n const locale = c.req.query('locale');\n const etag = c.req.query('etag') || '';\n\n if (!locale) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'locale query parameter is required', { field: 'locale' }),\n 400,\n );\n }\n\n try {\n const data = await c.req.json();\n const result = await api.updateLocalized({ id, locale, data, etag });\n\n if (!result.success) {\n if (result.reason === 'stale_write') {\n return c.json(\n errorResponse(ErrorCodes.STALE_WRITE, 'Content has been modified since you last loaded it', {\n currentEtag: result.currentEtag,\n }),\n 412,\n );\n }\n if (result.reason === 'not_found') {\n return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);\n }\n return c.json(result, 500);\n }\n\n // Set ETag header\n c.header('ETag', result.etag);\n\n return c.json(result);\n } catch (error) {\n console.error('[Content API] Failed to update content:', error);\n return c.json(\n {\n success: false,\n reason: 'write_error',\n error: error instanceof Error ? error.message : 'Unknown error',\n },\n 500,\n );\n }\n });\n\n // PATCH /content/:id - Partial update\n app.patch('/content/:id', async (c) => {\n const id = c.req.param('id');\n const locale = c.req.query('locale');\n const etag = c.req.query('etag') || '';\n\n if (!locale) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'locale query parameter is required', { field: 'locale' }),\n 400,\n );\n }\n\n try {\n const data = await c.req.json();\n const result = await api.updateLocalized({ id, locale, data, etag });\n\n if (!result.success) {\n if (result.reason === 'stale_write') {\n return c.json(\n errorResponse(ErrorCodes.STALE_WRITE, 'Content has been modified since you last loaded it', {\n currentEtag: result.currentEtag,\n }),\n 412,\n );\n }\n if (result.reason === 'not_found') {\n return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);\n }\n return c.json(result, 500);\n }\n\n // Set ETag header\n c.header('ETag', result.etag);\n\n return c.json(result);\n } catch (error) {\n console.error('[Content API] Failed to patch content:', error);\n return c.json(\n {\n success: false,\n reason: 'write_error',\n error: error instanceof Error ? error.message : 'Unknown error',\n },\n 500,\n );\n }\n });\n\n // DELETE /content/:id - Delete content (entire entry or specific locale)\n app.delete('/content/:id', async (c) => {\n const id = c.req.param('id');\n const locale = c.req.query('locale');\n const ifMatch = c.req.header('If-Match') || '';\n\n try {\n let result;\n\n if (locale) {\n // Delete specific locale\n result = await api.deleteLocalized({ id, locale, etag: ifMatch });\n } else {\n // Delete entire content entry\n result = await api.deleteContent(id, ifMatch);\n }\n\n if (!result.success) {\n if (result.reason === 'not_found') {\n return c.json(\n {\n success: false,\n error: 'Content not found',\n },\n 404,\n );\n }\n if (result.reason === 'stale_write') {\n return c.json(\n {\n success: false,\n reason: result.reason,\n currentEtag: result.currentEtag,\n message: 'Content has been modified',\n },\n 412,\n );\n }\n return c.json(result, 500);\n }\n\n return c.json({ success: true });\n } catch (error) {\n console.error('[Content API] Failed to delete content:', error);\n return c.json(\n {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n },\n 500,\n );\n }\n });\n\n // ===== Data Routes =====\n // NOTE: These routes MUST come before /:site/* routes to avoid being captured by them\n\n // GET /data/collections - List all data collections (must be before /data/:name)\n app.get('/data/collections', async (c) => {\n try {\n const collections = api.data.collections;\n return c.json({\n collections: Array.from(collections).sort(),\n });\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list data collections'),\n 500,\n );\n }\n });\n\n // GET /data/name-available - Check if data name is available\n app.get('/data/name-available', async (c) => {\n const name = c.req.query('name');\n const collection = c.req.query('collection');\n const excludeId = c.req.query('excludeId');\n\n if (!name) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'name query parameter is required', { field: 'name' }),\n 400,\n );\n }\n\n if (!collection) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'collection query parameter is required', {\n field: 'collection',\n }),\n 400,\n );\n }\n\n try {\n const available = api.data.isNameAvailable(collection, name, excludeId);\n if (available) {\n return c.json({ available: true });\n }\n\n const existing = api.data.getByName(collection, name);\n return c.json({\n available: false,\n existingId: existing?.id,\n });\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check data name availability'),\n 500,\n );\n }\n });\n\n // GET /data - List data entries\n app.get('/data', async (c) => {\n const collection = c.req.query('collection');\n const locale = c.req.query('locale');\n\n try {\n const filters: GlobalFilters = { kind: 'data' };\n if (collection) filters.collection = collection;\n if (locale) filters.locales = [locale];\n\n const items = Array.from(api.listAllContent(filters));\n return c.json({ items, total: items.length });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list data entries'), 500);\n }\n });\n\n // GET /data/:name - Get data entry by name\n app.get('/data/:name', async (c) => {\n const name = c.req.param('name');\n const collection = c.req.query('collection');\n const locale = c.req.query('locale');\n\n if (!collection) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'collection query parameter is required', {\n field: 'collection',\n }),\n 400,\n );\n }\n\n try {\n const dataEntry = api.data.getByName(collection, name, locale);\n\n if (!dataEntry) {\n return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Data entry not found', { name, collection }), 404);\n }\n\n // If locale specified and provided, filter the response\n if (locale && dataEntry.locales[locale]) {\n return c.json({\n ...dataEntry,\n locales: { [locale]: dataEntry.locales[locale] },\n });\n }\n\n return c.json(dataEntry);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch data entry'), 500);\n }\n });\n\n // ===== Asset Routes =====\n // Must be registered BEFORE /:site routes to avoid route conflicts (/:site would match \"assets\")\n\n if (options?.assetsPath) {\n const assetOps = new AssetOperations({\n assetsPath: options.assetsPath,\n contentRoot: options.contentRoot,\n ...options.assetConfig,\n });\n\n // POST /assets/move — move assets between folders\n app.post('/assets/move', async (c) => {\n try {\n const { filenames, sourceFolder, targetFolder } = await c.req.json<{\n filenames: string[];\n sourceFolder: string;\n targetFolder: string;\n }>();\n\n if (!Array.isArray(filenames)) {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'filenames must be an array'), 400);\n }\n if (typeof sourceFolder !== 'string') {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'sourceFolder is required'), 400);\n }\n if (typeof targetFolder !== 'string') {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'targetFolder is required'), 400);\n }\n\n const result = await assetOps.moveAssets(filenames, sourceFolder, targetFolder);\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);\n }\n\n return c.json(result);\n } catch (error) {\n if (error instanceof Error && error.message === 'Path traversal detected') {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid folder path'), 400);\n }\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to move assets'), 500);\n }\n });\n\n // POST /assets/upload — multipart form data upload\n app.post('/assets/upload', async (c) => {\n try {\n const body = await c.req.parseBody();\n const file = body.file;\n if (!(file instanceof File)) {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'No file provided in \"file\" field'), 400);\n }\n\n const alt = typeof body.alt === 'string' ? body.alt : undefined;\n const uploadedBy = typeof body.uploadedBy === 'string' ? body.uploadedBy : undefined;\n const width = typeof body.width === 'string' ? Number.parseInt(body.width, 10) : undefined;\n const height = typeof body.height === 'string' ? Number.parseInt(body.height, 10) : undefined;\n const folder = typeof body.folder === 'string' ? body.folder : undefined;\n\n const result = await assetOps.upload(file, { alt, uploadedBy, width, height, folder });\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.ASSET_UPLOAD_FAILED, result.error), 400);\n }\n\n return c.json(result.asset, 201);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.ASSET_UPLOAD_FAILED, 'Upload failed'), 500);\n }\n });\n\n // POST /assets/import-url — import image from URL\n app.post('/assets/import-url', async (c) => {\n try {\n const { url, alt, uploadedBy, folder } = await c.req.json<{\n url: string;\n alt?: string;\n uploadedBy?: string;\n folder?: string;\n }>();\n\n if (!url) {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'url is required'), 400);\n }\n\n const result = await assetOps.importFromUrl(url, { alt, uploadedBy, folder });\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.ASSET_UPLOAD_FAILED, result.error), 400);\n }\n\n return c.json(result.asset, 201);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.ASSET_UPLOAD_FAILED, 'URL import failed'), 500);\n }\n });\n\n // GET /assets — list all assets\n app.get('/assets', async (c) => {\n try {\n const assets = await assetOps.list();\n return c.json({ assets });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list assets'), 500);\n }\n });\n\n // GET /assets/folders — list assets and subfolders within a folder\n app.get('/assets/folders', async (c) => {\n try {\n const path = c.req.query('path') || '/';\n const result = await assetOps.listFolder(path);\n return c.json(result);\n } catch (error) {\n if (error instanceof Error && error.message === 'Path traversal detected') {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid folder path'), 400);\n }\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list folder'), 500);\n }\n });\n\n // POST /assets/folders — create a folder\n app.post('/assets/folders', async (c) => {\n try {\n const { path } = await c.req.json<{ path: string }>();\n\n if (!path) {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'path is required'), 400);\n }\n\n const result = await assetOps.createFolder(path);\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);\n }\n\n return c.json({ success: true }, 201);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to create folder'), 500);\n }\n });\n\n // GET /assets/folder-tree — get complete folder hierarchy with asset counts\n app.get('/assets/folder-tree', async (c) => {\n try {\n const tree = await assetOps.getFolderTree();\n return c.json({ tree });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get folder tree'), 500);\n }\n });\n\n // GET /assets/:filename/usage — get asset usage information\n app.get('/assets/:filename/usage', async (c) => {\n try {\n const filename = c.req.param('filename');\n const usage = await assetOps.getUsage(filename);\n return c.json({ usage });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get asset usage'), 500);\n }\n });\n\n // GET /assets/serve/:path{.+} — serve actual asset file (supports subfolders)\n app.get('/assets/serve/:path{.+}', async (c) => {\n try {\n const relativePath = c.req.param('path');\n // Split into folder and filename: 'images/tasks.png' → folder='/images', filename='tasks.png'\n const lastSlash = relativePath.lastIndexOf('/');\n const folder = lastSlash > 0 ? `/${relativePath.slice(0, lastSlash)}` : '/';\n const filename = lastSlash > 0 ? relativePath.slice(lastSlash + 1) : relativePath;\n const result = await assetOps.readAssetFile(filename, folder);\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);\n }\n\n // Set caching headers (1 year for immutable hashed filenames)\n c.header('Content-Type', result.mimeType);\n c.header('Cache-Control', 'public, max-age=31536000, immutable');\n\n return c.body(result.buffer as unknown as ArrayBuffer);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to serve asset'), 500);\n }\n });\n\n // GET /assets/:filename — get single asset metadata\n app.get('/assets/:filename', async (c) => {\n try {\n const filename = c.req.param('filename');\n const asset = await assetOps.getAsset(filename);\n\n if (!asset) {\n return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, 'Asset not found'), 404);\n }\n\n return c.json(asset);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get asset'), 500);\n }\n });\n\n // PATCH /assets/:filename — update asset metadata\n app.patch('/assets/:filename', async (c) => {\n try {\n const filename = c.req.param('filename');\n const { alt, tags } = await c.req.json<{ alt?: string; tags?: string[] }>();\n\n const result = await assetOps.updateMetadata(filename, { alt, tags });\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);\n }\n\n return c.json(result.asset);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to update asset'), 500);\n }\n });\n\n // DELETE /assets/:filename — delete asset\n app.delete('/assets/:filename', async (c) => {\n try {\n const filename = c.req.param('filename');\n const result = await assetOps.delete(filename);\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);\n }\n\n return c.json({ success: true });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to delete asset'), 500);\n }\n });\n }\n\n // ===== Site Routes =====\n // These use /:site parameter which matches any path segment\n\n // GET /:site/collections - Get collections for a site\n app.get('/:site/collections', async (c) => {\n const site = c.req.param('site');\n\n try {\n if (site === 'blocks') {\n // Use the efficient collections getter for blocks\n const collections = Array.from(api.blocks.collections).sort();\n return c.json({ collections });\n }\n // Use the efficient collections getter for sites\n const siteObj = api.getSite(site);\n if (!siteObj) {\n return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);\n }\n const collections = Array.from(siteObj.collections).sort();\n return c.json({ collections });\n } catch (error) {\n return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);\n }\n });\n\n // GET /:site/pages - Get pages for a site (not valid for blocks)\n app.get('/:site/pages', async (c) => {\n const site = c.req.param('site');\n const locale = c.req.query('locale');\n\n try {\n if (site === 'blocks') {\n return c.json(\n errorResponse(\n ErrorCodes.INVALID_REQUEST,\n 'Blocks do not have pages. Use /content?kind=block to list blocks.',\n ),\n 400,\n );\n }\n\n const siteObj = api.getSite(site);\n if (!siteObj) {\n return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);\n }\n\n // Use listContent with locales filter\n const items = Array.from(siteObj.listContent(locale ? { locales: [locale] } : {}));\n const result = { items, total: items.length };\n return c.json(result);\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, `Failed to list pages for site '${site}'`, {\n site,\n }),\n 500,\n );\n }\n });\n\n // GET /:site/pathname-available - Check if pathname is available\n app.get('/:site/pathname-available', async (c) => {\n const site = c.req.param('site');\n const pathname = c.req.query('pathname');\n const locale = c.req.query('locale') || 'en';\n const excludeId = c.req.query('excludeId');\n\n if (!pathname) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'pathname query parameter is required', { field: 'pathname' }),\n 400,\n );\n }\n\n try {\n if (site === 'blocks') {\n return c.json(\n errorResponse(\n ErrorCodes.INVALID_REQUEST,\n 'Blocks do not have pathnames. This endpoint is only for page content.',\n ),\n 400,\n );\n }\n\n // Use the optimized pathname index via site.isPathnameAvailable\n const siteObj = api.getSite(site);\n if (!siteObj) {\n return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);\n }\n const available = siteObj.isPathnameAvailable(pathname, locale, excludeId);\n\n if (available) {\n return c.json({ available: true });\n }\n\n // Get the conflicting content ID if pathname is taken\n const existingId = siteObj.getPathnameConflict(pathname, locale, excludeId);\n\n return c.json({\n available: false,\n existingId,\n });\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check pathname availability'),\n 500,\n );\n }\n });\n\n // GET /blocks - Shorthand for all blocks\n app.get('/blocks', async (c) => {\n const collection = c.req.query('collection');\n const locale = c.req.query('locale');\n\n try {\n const filters: any = { kind: 'block' };\n if (collection) filters.collection = collection;\n if (locale) filters.locales = [locale];\n\n const items = Array.from(api.listAllContent(filters));\n return c.json({ items, total: items.length });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list blocks'), 500);\n }\n });\n\n // GET /blocks/name-available - Check if block name is available\n app.get('/blocks/name-available', async (c) => {\n const name = c.req.query('name');\n const collection = c.req.query('collection') || 'components';\n const locale = c.req.query('locale') || 'en';\n const excludeId = c.req.query('excludeId');\n\n if (!name) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'name query parameter is required', { field: 'name' }),\n 400,\n );\n }\n\n try {\n // Check block name availability through listing\n const existing = Array.from(\n api.listAllContent({\n kind: 'block',\n collection: collection,\n locales: [locale],\n }),\n );\n\n let taken: ContentManifest | undefined;\n for (const item of existing) {\n for (const localeVersion of localesOf(item)) {\n if (localeVersion.name === name) {\n taken = item;\n break;\n }\n }\n }\n\n // If no existing block, name is available\n if (!taken) {\n return c.json({ available: true });\n }\n\n // If existing block has same ID as excludeId, name is available\n // (useful when editing existing block)\n if (excludeId && taken.id === excludeId) {\n return c.json({ available: true });\n }\n\n // Otherwise, name is taken\n return c.json({\n available: false,\n existingId: taken.id,\n });\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check block name availability'),\n 500,\n );\n }\n });\n\n // GET /blocks/:name - Get block by name\n app.get('/blocks/:name', async (c) => {\n const name = c.req.param('name');\n const collection = c.req.query('collection') || 'components';\n const locale = c.req.query('locale');\n\n try {\n const block = api.blocks.getByName(collection, name, locale);\n\n if (!block) {\n return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Block not found', { name, collection }), 404);\n }\n\n // If locale specified and provided, filter the response\n if (locale && block.locales[locale]) {\n return c.json({\n ...block,\n locales: { [locale]: block.locales[locale] },\n });\n }\n\n return c.json(block);\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch block'), 500);\n }\n });\n\n // POST /:site/move - Move page to new pathname\n app.post('/:site/move', async (c) => {\n const site = c.req.param('site');\n\n try {\n const { id, pathname, locale, etag } = await c.req.json();\n\n if (!id || !pathname || !locale || !etag) {\n return c.json(\n errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'id, pathname, locale, and etag are required'),\n 400,\n );\n }\n\n const siteObj = api.getSite(site);\n if (!siteObj) {\n return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);\n }\n\n // First check if the pathname is available\n const existing = siteObj.getByPathname(pathname, locale);\n if (existing && existing.id !== id) {\n return c.json(\n {\n moved: false,\n reason: 'already_exists',\n ...errorResponse(ErrorCodes.PATHNAME_TAKEN, 'Pathname already taken', { existingId: existing.id }),\n },\n 409,\n );\n }\n\n // Get current content to track previous pathname\n const current = await api.getLocalized(id, locale);\n if (!current) {\n return c.json(\n { moved: false, ...errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }) },\n 404,\n );\n }\n\n const previousPathname = current.localized.pathname;\n\n // Update with new pathname using updateLocalized for etag validation\n const updateResult = await api.updateLocalized({\n id,\n locale,\n data: {\n pathname: pathname,\n meta: current.localized.meta,\n },\n etag: etag,\n });\n\n if (!updateResult.success) {\n if (updateResult.reason === 'stale_write') {\n return c.json(\n {\n moved: false,\n reason: 'stale_write',\n currentEtag: updateResult.currentEtag,\n message: 'Content has been modified',\n },\n 412,\n );\n }\n if (updateResult.reason === 'not_found') {\n return c.json(\n { moved: false, ...errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }) },\n 404,\n );\n }\n return c.json({ moved: false, ...errorResponse(ErrorCodes.WRITE_ERROR, 'Update failed') }, 500);\n }\n\n return c.json({\n moved: true,\n previousPathname: previousPathname,\n etag: updateResult.etag,\n });\n } catch (error) {\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to move page'), 500);\n }\n });\n\n // GET /untranslated/:locale - Find untranslated content\n app.get('/untranslated/:targetLocale', async (c) => {\n const targetLocale = c.req.param('targetLocale');\n const excludeSites = c.req\n .query('excludeSites')\n ?.split(',')\n .map((s) => s.trim())\n .filter((s) => s);\n const includeUnpublished = c.req.query('includeUnpublished') === 'true';\n\n try {\n const options: FindOptions = {\n ...(excludeSites?.length && { excludeSites }),\n ...(includeUnpublished && { includeUnpublished }),\n };\n\n const items = Array.from(api.findUntranslatedContent(targetLocale, options));\n return c.json({ items, total: items.length });\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to find untranslated content'),\n 500,\n );\n }\n });\n\n // GET /sites - Get sites configuration\n app.get('/sites', async (c) => {\n try {\n const config = api.sitesConfig;\n return c.json(config);\n } catch (error) {\n return c.json(\n logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch sites configuration'),\n 500,\n );\n }\n });\n\n // POST /content/batch - Batch update operations\n app.post('/content/batch', async (c) => {\n try {\n const { operations } = await c.req.json();\n const result = await api.batchUpdate(operations);\n\n if (!result.success) {\n return c.json(result, 207); // Multi-status\n }\n\n return c.json(result);\n } catch (error) {\n console.error('[Content API] Failed to batch update:', error);\n return c.json(\n {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n },\n 500,\n );\n }\n });\n\n // ===== Git Routes =====\n\n /**\n * Get git config from router options or environment variables.\n * contentRoot from router options takes priority over CONTENT_PATH env var.\n * Optional: GIT_BRANCH (defaults to current checked-out branch)\n */\n function getGitConfig(): GitConfig {\n const contentPath = options?.contentRoot || process.env.CONTENT_PATH;\n if (!contentPath) {\n throw new Error('contentRoot option or CONTENT_PATH environment variable is required for git operations');\n }\n return {\n contentPath,\n branch: process.env.GIT_BRANCH,\n };\n }\n\n // GET /git/status - Get git repository status\n app.get('/git/status', async (c) => {\n try {\n const config = getGitConfig();\n const gitOps = createGitOperations(config);\n const status = await gitOps.getStatus();\n\n if (!status.isRepo) {\n return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, 'Repository not accessible'), 400);\n }\n\n return c.json(status);\n } catch (error) {\n if (error instanceof Error && (error.message.includes('contentRoot') || error.message.includes('CONTENT_PATH'))) {\n return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);\n }\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_STATUS_FAILED, 'Failed to get git status'), 500);\n }\n });\n\n // POST /git/commit - Commit all changes\n app.post('/git/commit', async (c) => {\n try {\n const body = await c.req.json<{ message?: string }>().catch(() => ({}) as { message?: string });\n\n // Auto-generate message if not provided\n const date = new Date();\n const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n const defaultMessage = `CMS changes - ${monthNames[date.getMonth()]} ${date.getDate()}`;\n const message = body.message || defaultMessage;\n\n // Extract user email from CF Access header for commit attribution\n const userEmail = c.req.header('X-CF-User-Email');\n const author: GitAuthor | undefined = userEmail ? { name: userEmail.split('@')[0], email: userEmail } : undefined;\n\n const config = getGitConfig();\n const gitOps = createGitOperations(config);\n const result = await gitOps.commitAll(message, author);\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.GIT_COMMIT_FAILED, result.error || 'Commit failed'), 500);\n }\n\n return c.json(result);\n } catch (error) {\n if (error instanceof Error && (error.message.includes('contentRoot') || error.message.includes('CONTENT_PATH'))) {\n return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);\n }\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_COMMIT_FAILED, 'Failed to commit changes'), 500);\n }\n });\n\n // POST /git/push - Push to origin\n app.post('/git/push', async (c) => {\n try {\n const config = getGitConfig();\n const gitOps = createGitOperations(config);\n const result = await gitOps.pushOrigin();\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.GIT_PUSH_FAILED, result.error || 'Push failed'), 500);\n }\n\n return c.json(result);\n } catch (error) {\n if (error instanceof Error && (error.message.includes('contentRoot') || error.message.includes('CONTENT_PATH'))) {\n return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);\n }\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PUSH_FAILED, 'Failed to push to origin'), 500);\n }\n });\n\n // POST /git/pull - Pull from origin with autostash + rebase\n app.post('/git/pull', async (c) => {\n try {\n const config = getGitConfig();\n const gitOps = createGitOperations(config);\n const result = await gitOps.pull();\n\n if (!result.success) {\n return c.json(errorResponse(ErrorCodes.GIT_PULL_FAILED, result.error || 'Pull failed'), 500);\n }\n\n return c.json(result);\n } catch (error) {\n if (error instanceof Error && (error.message.includes('contentRoot') || error.message.includes('CONTENT_PATH'))) {\n return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);\n }\n return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PULL_FAILED, 'Failed to pull from origin'), 500);\n }\n });\n\n return app;\n}\n\n/**\n * Create middleware for backwards compatibility with existing code\n * This wraps the Hono app to work with Node.js IncomingMessage/ServerResponse\n */\nexport function createContentMiddleware(contentApi: ContentAPI) {\n const app = createContentAPIRouter(contentApi);\n\n // Convert Hono app to Node.js middleware\n return async (req: any, res: any, next: () => void) => {\n const url = new URL(req.url!, `http://${req.headers.host}`);\n\n // Only handle API routes (base path depends on context)\n const basePath = url.pathname.startsWith('/__cms/api') ? '/__cms/api' : '/__conloca/api';\n if (!url.pathname.startsWith(basePath)) {\n return next();\n }\n\n // Strip the base path to match Hono routes\n const path = url.pathname.replace(basePath, '');\n\n // Create a Request object for Hono\n const request = new Request(`http://localhost${path}${url.search}`, {\n method: req.method,\n headers: req.headers,\n body: ['GET', 'HEAD'].includes(req.method!) ? undefined : await readBody(req),\n });\n\n // Handle with Hono\n const response = await app.fetch(request);\n\n // Copy response headers\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n // Set status code\n res.statusCode = response.status;\n\n // Send response body\n const body = await response.text();\n res.end(body);\n };\n}\n\n// Helper to read request body\nfunction readBody(req: any): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Uint8Array[] = [];\n req.on('data', (chunk: Buffer) => chunks.push(new Uint8Array(chunk)));\n req.on('end', () => {\n const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.length;\n }\n resolve(Buffer.from(combined).toString());\n });\n req.on('error', reject);\n });\n}\n","import { getRequestListener } from '@hono/node-server';\nimport type { Plugin, ViteDevServer } from 'vite';\nimport { createContentAPI, createContentWatchHandlers } from './content-watcher';\nimport type { FileSystemContentAPI } from './filesystem-content-api';\nimport { createContentAPIRouter } from './middleware';\n\nexport interface ConlocaContentOptions {\n contentRoot: string;\n canvasDir?: string;\n basePath?: string;\n}\n\n/**\n * Vite plugin wrapper for content middleware\n * This follows the spec in 04-cms-api.md and 09-conloca-content-editing.md\n */\nexport function conlocaContent(options: ConlocaContentOptions): Plugin {\n let contentApi: FileSystemContentAPI;\n\n const basePath = options.basePath || '/__conloca/api/content';\n\n return {\n name: 'vite-plugin-conloca-content',\n\n async configureServer(server: ViteDevServer) {\n // Initialize content API\n contentApi = await createContentAPI(options);\n\n // Set up content file watcher\n server.watcher.add(options.contentRoot);\n\n // Create Hono app with routes\n const app = createContentAPIRouter(contentApi);\n\n // Add to Vite as middleware using @hono/node-server\n server.middlewares.use(basePath, getRequestListener(app.fetch));\n\n // Set up HMR for content changes using extracted handlers\n const handlers = createContentWatchHandlers(contentApi, options, server.ws);\n server.watcher.on('change', handlers.onChange);\n server.watcher.on('add', handlers.onAdd);\n server.watcher.on('unlink', handlers.onUnlink);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAeA,MAAM,oBAAoB;AAE1B,IAAa,gBAAb,MAA2B;CACzB,AAAQ;CAER,YAAY,YAAoB;AAC9B,OAAK,eAAe,KAAK,YAAY,kBAAkB;;CAGzD,MAAM,OAAmC;AACvC,MAAI;GACF,MAAM,MAAM,MAAM,SAAS,KAAK,cAAc,QAAQ;AACtD,UAAO,KAAK,MAAM,IAAI;UAChB;AACN,UAAO,EAAE;;;CAIb,MAAM,MAAM,MAAwC;AAClD,QAAM,UAAU,KAAK,cAAc,KAAK,UAAU,MAAM,MAAM,EAAE,EAAE,QAAQ;;CAG5E,MAAM,IAAI,cAAsB,MAAwC;EACtE,MAAM,WAAW,MAAM,KAAK,MAAM;AAClC,WAAS,gBAAgB;AACzB,QAAM,KAAK,MAAM,SAAS;;CAG5B,MAAM,OAAO,cAAwC;EACnD,MAAM,WAAW,MAAM,KAAK,MAAM;AAClC,MAAI,EAAE,gBAAgB,UAAW,QAAO;AACxC,SAAO,SAAS;AAChB,QAAM,KAAK,MAAM,SAAS;AAC1B,SAAO;;CAGT,MAAM,IAAI,cAA8D;AAEtE,UADiB,MAAM,KAAK,MAAM,EAClB;;;;;;CAOlB,MAAM,cAAc,UAA0F;EA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