@contentrain/mcp 3.8.2 → 3.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{apply-manager-B-VMXKiW.mjs → apply-manager-BenQNb_b.mjs} +4 -4
- package/dist/{apply-manager-B-VMXKiW.mjs.map → apply-manager-BenQNb_b.mjs.map} +1 -1
- package/dist/{context-fJCKH_qv.mjs → context-Cp8b8Nxm.mjs} +2 -2
- package/dist/{context-fJCKH_qv.mjs.map → context-Cp8b8Nxm.mjs.map} +1 -1
- package/dist/core/apply-manager.mjs +4 -4
- package/dist/core/content-manager.mjs +1 -1
- package/dist/core/context.mjs +2 -2
- package/dist/core/doctor.mjs +2 -2
- package/dist/core/model-manager.d.mts.map +1 -1
- package/dist/core/model-manager.mjs +1 -1
- package/dist/core/ops/index.mjs +5 -5
- package/dist/core/validator/index.mjs +2 -2
- package/dist/{doctor-Du4MVG5w.mjs → doctor-Qabcb-Z1.mjs} +2 -2
- package/dist/{doctor-Du4MVG5w.mjs.map → doctor-Qabcb-Z1.mjs.map} +1 -1
- package/dist/git/reconcile.mjs +6 -6
- package/dist/git/transaction.mjs +3 -3
- package/dist/index.mjs +11 -11
- package/dist/{local-BXTVAAr-.mjs → local-DaITA8Ye.mjs} +5 -5
- package/dist/{local-BXTVAAr-.mjs.map → local-DaITA8Ye.mjs.map} +1 -1
- package/dist/{model-manager-DPXulg7z.mjs → model-manager-BYF2z7qC.mjs} +18 -8
- package/dist/model-manager-BYF2z7qC.mjs.map +1 -0
- package/dist/{ops-DxhCCs_Z.mjs → ops-CQ_IIedh.mjs} +3 -3
- package/dist/{ops-DxhCCs_Z.mjs.map → ops-CQ_IIedh.mjs.map} +1 -1
- package/dist/providers/local/index.mjs +7 -7
- package/dist/{reconcile-CPDGFQ8H.mjs → reconcile-8pEO4mBC.mjs} +4 -4
- package/dist/{reconcile-CPDGFQ8H.mjs.map → reconcile-8pEO4mBC.mjs.map} +1 -1
- package/dist/{reconcile-BWbckvbv.mjs → reconcile-Do8OJDAo.mjs} +3 -3
- package/dist/{reconcile-BWbckvbv.mjs.map → reconcile-Do8OJDAo.mjs.map} +1 -1
- package/dist/server/http/index.mjs +11 -11
- package/dist/{server-UojGbAaw.mjs → server-DUkF15wn.mjs} +12 -12
- package/dist/server-DUkF15wn.mjs.map +1 -0
- package/dist/server.mjs +11 -11
- package/dist/{transaction-DfrvGIfk.mjs → transaction-CcjGiVYg.mjs} +2 -2
- package/dist/{transaction-DfrvGIfk.mjs.map → transaction-CcjGiVYg.mjs.map} +1 -1
- package/dist/{validator-C08p1OpM.mjs → validator-eUdQqQGc.mjs} +3 -3
- package/dist/validator-eUdQqQGc.mjs.map +1 -0
- package/package.json +2 -2
- package/dist/model-manager-DPXulg7z.mjs.map +0 -1
- package/dist/server-UojGbAaw.mjs.map +0 -1
- package/dist/validator-C08p1OpM.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model-manager-BYF2z7qC.mjs","names":["validateLocale","validateEntryId","validateSlug","tryReadJsonViaReader"],"sources":["../src/core/ops/paths.ts","../src/providers/local/reader.ts","../src/core/content-manager.ts","../src/core/model-manager.ts"],"sourcesContent":["import type { ModelDefinition } from '@contentrain/types'\n\n/**\n * Content-root-relative path helpers for plan-API consumers.\n *\n * These mirror the logic inside `core/content-manager.ts:resolveJsonFilePath`\n * but return forward-slash relative strings suitable for `FileChange.path`.\n * Providers are responsible for resolving these against their backing store\n * (worktree on disk for LocalProvider, git tree path for GitHubProvider, ...).\n *\n * Kept inline to `core/ops/` for now; when Faz 2 finishes migrating every op\n * the legacy absolute-path helpers in `core/content-manager.ts` and\n * `core/meta-manager.ts` will call into these (or be replaced entirely).\n */\n\n/**\n * Content-root-relative content directory for a model (forward-slash paths).\n * Mirrors `resolveContentDir` with an empty `projectRoot`, so reader-backed\n * callers and plan-API consumers share the same path resolution.\n */\nexport function contentDirPath(\n model: Pick<ModelDefinition, 'domain' | 'id' | 'content_path'>,\n): string {\n if (model.content_path) return model.content_path\n return `.contentrain/content/${model.domain}/${model.id}`\n}\n\nfunction contentDir(model: Pick<ModelDefinition, 'domain' | 'id' | 'content_path'>): string {\n return contentDirPath(model)\n}\n\nexport function contentFilePath(\n model: Pick<ModelDefinition, 'id' | 'kind' | 'domain' | 'i18n' | 'content_path' | 'locale_strategy'>,\n locale: string,\n): string {\n const dir = contentDir(model)\n if (!model.i18n) return `${dir}/data.json`\n const strategy = model.locale_strategy ?? 'file'\n switch (strategy) {\n case 'suffix': return `${dir}/${model.id}.${locale}.json`\n case 'directory': return `${dir}/${locale}/${model.id}.json`\n case 'none': return `${dir}/${model.id}.json`\n default: return `${dir}/${locale}.json`\n }\n}\n\nexport function documentFilePath(\n model: Pick<ModelDefinition, 'id' | 'domain' | 'i18n' | 'content_path' | 'locale_strategy'>,\n locale: string,\n slug: string,\n): string {\n const dir = contentDir(model)\n if (!model.i18n) return `${dir}/${slug}.md`\n const strategy = model.locale_strategy ?? 'file'\n switch (strategy) {\n case 'suffix': return `${dir}/${slug}.${locale}.md`\n case 'directory': return `${dir}/${locale}/${slug}.md`\n case 'none': return `${dir}/${slug}.md`\n default: return `${dir}/${slug}/${locale}.md`\n }\n}\n\n/**\n * Content-root-relative meta path.\n *\n * `i18n` is in the Pick and `defaultLocale` is required on purpose. A non-i18n\n * model keeps all its content in one `data.json`, so it has exactly one meta\n * record — pinned to the default locale. Passing the caller's locale straight\n * through used to fan meta out across locales for that single content file\n * (`meta/{id}/tr.json` *and* `meta/{id}/en.json` for one `data.json`), leaving\n * every reader to guess which file was authoritative.\n */\nexport function metaFilePath(\n model: Pick<ModelDefinition, 'id' | 'kind' | 'i18n'>,\n locale: string,\n defaultLocale: string,\n slug?: string,\n): string {\n const base = `.contentrain/meta/${model.id}`\n const effective = model.i18n ? locale : defaultLocale\n if (model.kind === 'document' && slug) {\n return `${base}/${slug}/${effective}.json`\n }\n return `${base}/${effective}.json`\n}\n","import { access, readdir, readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport type { RepoReader } from '../../core/contracts/index.js'\n\n/**\n * LocalReader — `RepoReader` backed by the local filesystem.\n *\n * Paths may be absolute or relative to `projectRoot` (`node:path/resolve`\n * handles both). The `ref` parameter is accepted for interface compatibility\n * but ignored because LocalReader always reads from the working tree.\n *\n * Phase 1: provided as plumbing; core ops still use direct `fs` calls.\n * Phase 2 routes ops through this reader (and through GitHubProvider's reader\n * in Phase 5) so the same op surface works on every backing store.\n */\nexport class LocalReader implements RepoReader {\n constructor(public readonly projectRoot: string) {}\n\n async readFile(path: string, _ref?: string): Promise<string> {\n return readFile(resolve(this.projectRoot, path), 'utf-8')\n }\n\n async listDirectory(path: string, _ref?: string): Promise<string[]> {\n try {\n return await readdir(resolve(this.projectRoot, path))\n } catch {\n return []\n }\n }\n\n async fileExists(path: string, _ref?: string): Promise<boolean> {\n try {\n await access(resolve(this.projectRoot, path))\n return true\n } catch {\n return false\n }\n }\n}\n","import type { ModelDefinition, ContentrainConfig, EntryMeta, LocaleStrategy, DocumentEntry, Vocabulary } from '@contentrain/types'\nimport { validateSlug, validateEntryId, validateLocale, generateEntryId, parseMarkdownFrontmatter, serializeMarkdownFrontmatter } from '@contentrain/types'\nimport { join } from 'node:path'\nimport { rm } from 'node:fs/promises'\nimport { contentrainDir, readDir, readJson, readText, writeJson, writeText } from '../util/fs.js'\nimport { readMeta, writeMeta, deleteMeta, mergeEntryMeta } from './meta-manager.js'\nimport { readModel } from './model-manager.js'\nimport type { RepoReader } from './contracts/index.js'\nimport { contentDirPath, contentFilePath, documentFilePath } from './ops/paths.js'\n\n// Re-export for backward compatibility (MCP internal consumers)\nexport { validateSlug, validateEntryId, validateLocale }\nexport { parseMarkdownFrontmatter as parseFrontmatter, serializeMarkdownFrontmatter as serializeFrontmatter } from '@contentrain/types'\n\n/** Keys named individually in a replacement advisory before it collapses to a count. */\nconst MAX_REPORTED_KEYS = 5\n\n// ─── Content paths ───\n//\n// These take the narrowest `Pick<ModelDefinition, …>` each one actually reads,\n// mirroring `ops/paths.ts`. Path resolution has nothing to do with a model's\n// title or schema, and demanding a whole `ModelDefinition` pushed callers that\n// only have a path-shaped fragment into `as ModelDefinition` casts — which then\n// hide a genuinely missing required property from the compiler.\n\nexport type ContentPathModel = Pick<ModelDefinition, 'id' | 'domain' | 'content_path'>\nexport type LocaleStrategyModel = Pick<ModelDefinition, 'locale_strategy'>\nexport type ContentFileModel = Pick<ModelDefinition, 'id' | 'i18n' | 'locale_strategy'>\n\nexport function resolveContentDir(projectRoot: string, model: ContentPathModel): string {\n if (model.content_path) {\n return join(projectRoot, model.content_path)\n }\n return join(contentrainDir(projectRoot), 'content', model.domain, model.id)\n}\n\nexport function resolveLocaleStrategy(model: LocaleStrategyModel): LocaleStrategy {\n return model.locale_strategy ?? 'file'\n}\n\n/** Build the file path for a JSON content file (singleton/collection/dictionary) */\nexport function resolveJsonFilePath(dir: string, model: ContentFileModel, locale: string): string {\n // When i18n is disabled, always use data.json (locale parameter is ignored)\n if (!model.i18n) return join(dir, 'data.json')\n\n switch (resolveLocaleStrategy(model)) {\n case 'suffix': return join(dir, `${model.id}.${locale}.json`)\n case 'directory': return join(dir, locale, `${model.id}.json`)\n case 'none': return join(dir, `${model.id}.json`)\n case 'file':\n default: return join(dir, `${locale}.json`)\n }\n}\n\n/** Build the file path for a markdown document */\nexport function resolveMdFilePath(dir: string, model: Pick<ModelDefinition, 'i18n' | 'locale_strategy'>, locale: string, slug: string): string {\n // When i18n is disabled, always use {slug}.md (locale parameter is ignored)\n if (!model.i18n) return join(dir, `${slug}.md`)\n\n switch (resolveLocaleStrategy(model)) {\n case 'suffix': return join(dir, `${slug}.${locale}.md`)\n case 'directory': return join(dir, locale, `${slug}.md`)\n case 'none': return join(dir, `${slug}.md`)\n case 'file':\n default: return join(dir, slug, `${locale}.md`)\n }\n}\n\n// ─── Types ───\n\nexport interface ContentEntry {\n id?: string\n slug?: string\n locale?: string\n data: Record<string, unknown>\n /**\n * Scheduled publish date, ISO 8601. Meta only — never written to the content\n * file — and it never changes `status`. A string sets it, `null` clears it,\n * an absent key leaves it untouched. See `EntrySchedule` in meta-manager.\n */\n publish_at?: string | null\n /** Scheduled expiry, ISO 8601, with the same set/clear/leave semantics. */\n expire_at?: string | null\n}\n\nexport interface WriteResult {\n action: 'created' | 'updated'\n id?: string\n slug?: string\n locale: string\n advisories?: string[]\n}\n\nexport interface DeleteOpts {\n id?: string\n slug?: string\n locale?: string\n keys?: string[]\n /** `config.locales.default` — places a non-i18n model's single meta record. */\n defaultLocale: string\n}\n\nexport interface ListOpts {\n locale?: string\n filter?: Record<string, unknown>\n resolve?: boolean\n limit?: number\n offset?: number\n}\n\n// ─── writeContent ───\n\nexport async function writeContent(\n projectRoot: string,\n model: ModelDefinition,\n entries: ContentEntry[],\n config: ContentrainConfig,\n vocabulary?: Vocabulary | null,\n): Promise<WriteResult[]> {\n const results: WriteResult[] = []\n const defaultLocale = config.locales.default\n\n for (const entry of entries) {\n const locale = entry.locale ?? defaultLocale\n\n // Validate locale\n const localeErr = validateLocale(locale, config)\n if (localeErr) throw new Error(localeErr)\n\n // Validate entry ID if provided\n if (entry.id) {\n const idErr = validateEntryId(entry.id)\n if (idErr) throw new Error(idErr)\n }\n\n // Validate slug if provided\n if (entry.slug) {\n const slugErr = validateSlug(entry.slug)\n if (slugErr) throw new Error(slugErr)\n }\n\n switch (model.kind) {\n case 'singleton': {\n const filePath = resolveJsonFilePath(resolveContentDir(projectRoot, model), model, locale)\n await writeJson(filePath, entry.data)\n const prevMeta = await readMeta(projectRoot, model, { locale, defaultLocale }) as EntryMeta | null\n await writeMeta(projectRoot, model, { locale, defaultLocale }, mergeEntryMeta(prevMeta ?? undefined, entry))\n results.push({ action: 'updated', locale })\n break\n }\n\n case 'collection': {\n const isNew = !entry.id\n const id = entry.id ?? generateEntryId()\n const filePath = resolveJsonFilePath(resolveContentDir(projectRoot, model), model, locale)\n const existing = await readJson<Record<string, Record<string, unknown>>>(filePath) ?? {}\n\n const action: 'created' | 'updated' = (isNew || !(id in existing)) ? 'created' : 'updated'\n existing[id] = entry.data\n\n // Sort by entry ID for canonical output\n const sorted: Record<string, Record<string, unknown>> = {}\n for (const key of Object.keys(existing).toSorted()) {\n sorted[key] = existing[key]!\n }\n\n await writeJson(filePath, sorted)\n const prevMetaMap = await readMeta(projectRoot, model, { locale, defaultLocale }) as Record<string, EntryMeta> | null\n await writeMeta(projectRoot, model, { locale, entryId: id, defaultLocale }, mergeEntryMeta(prevMetaMap?.[id], entry))\n results.push({ action, id, locale })\n break\n }\n\n case 'document': {\n const slug = entry.slug ?? entry.data['slug'] as string\n if (!slug) throw new Error('Document entries require a slug')\n const slugErr = validateSlug(slug)\n if (slugErr) throw new Error(slugErr)\n\n const incomingFm = { ...entry.data }\n const bodySent = 'body' in incomingFm\n const incomingBody = (incomingFm['body'] as string | undefined) ?? ''\n delete incomingFm['body']\n if (!incomingFm['slug']) incomingFm['slug'] = slug\n\n // Check if existing\n const docPath = resolveMdFilePath(resolveContentDir(projectRoot, model), model, locale, slug)\n const existingRaw = await readText(docPath)\n const action: 'created' | 'updated' = existingRaw ? 'updated' : 'created'\n\n // Merge with what is there, matching `planContentSave`. This path is\n // reached by scaffold and by normalize extract; extracting into a model\n // that already has documents would otherwise replace them wholesale.\n const existingDoc = existingRaw ? parseMarkdownFrontmatter(existingRaw) : null\n const fmData = { ...existingDoc?.frontmatter, ...incomingFm }\n const bodyContent = bodySent ? incomingBody : (existingDoc?.body ?? '')\n\n const mdContent = serializeMarkdownFrontmatter(fmData, bodyContent)\n await writeText(docPath, mdContent)\n const prevMeta = await readMeta(projectRoot, model, { locale, slug, defaultLocale }) as EntryMeta | null\n await writeMeta(projectRoot, model, { locale, slug, defaultLocale }, mergeEntryMeta(prevMeta ?? undefined, entry))\n results.push({ action, slug, locale })\n break\n }\n\n case 'dictionary': {\n const filePath = resolveJsonFilePath(resolveContentDir(projectRoot, model), model, locale)\n const existing = await readJson<Record<string, string>>(filePath) ?? {}\n // Duplicate value advisory: warn when a new key maps to a value that already exists\n const advisories: string[] = []\n\n // Replacing a value is reported, not refused — see the same block in\n // `planContentSave`. Correcting a translation is a content decision.\n const incoming = entry.data as Record<string, string>\n const replaced = Object.keys(incoming).filter(\n k => k in existing && existing[k] !== incoming[k],\n )\n if (replaced.length > 0) {\n const shown = replaced.slice(0, MAX_REPORTED_KEYS)\n const detail = shown.map(k => `\"${k}\": \"${existing[k]}\" → \"${incoming[k]}\"`).join(', ')\n const more = replaced.length > shown.length ? `, and ${replaced.length - shown.length} more` : ''\n advisories.push(\n `Dictionary \"${model.id}\" (${locale}): replaced ${replaced.length} existing value(s) — ${detail}${more}.`,\n )\n }\n const reverseMap = new Map<string, string>()\n for (const [k, v] of Object.entries(existing)) {\n reverseMap.set(v, k)\n }\n for (const [newKey, newValue] of Object.entries(entry.data as Record<string, string>)) {\n if (newKey in existing) continue\n const existingKey = reverseMap.get(newValue as string)\n if (existingKey && existingKey !== newKey) {\n advisories.push(\n `Value \"${newValue}\" already exists as key \"${existingKey}\". Consider reusing instead of creating \"${newKey}\".`,\n )\n }\n }\n\n // Vocabulary cross-reference: warn when a value matches a known vocabulary term\n if (vocabulary && Object.keys(vocabulary.terms).length > 0) {\n for (const [newKey, newValue] of Object.entries(entry.data as Record<string, string>)) {\n if (newKey in existing) continue\n for (const [, translations] of Object.entries(vocabulary.terms)) {\n if (Object.values(translations).includes(newValue as string)) {\n advisories.push(\n `Value \"${newValue}\" matches a vocabulary term. Use the canonical form for consistency.`,\n )\n break\n }\n }\n }\n }\n\n const merged = { ...existing, ...entry.data as Record<string, string> }\n await writeJson(filePath, merged)\n const prevMeta = await readMeta(projectRoot, model, { locale, defaultLocale }) as EntryMeta | null\n await writeMeta(projectRoot, model, { locale, defaultLocale }, mergeEntryMeta(prevMeta ?? undefined, entry))\n results.push({ action: 'updated', locale, ...(advisories.length > 0 ? { advisories } : {}) })\n break\n }\n }\n }\n\n return results\n}\n\n// ─── deleteContent ───\n\nexport async function deleteContent(\n projectRoot: string,\n model: ModelDefinition,\n opts: DeleteOpts,\n): Promise<string[]> {\n // A non-i18n model stores content locale-agnostically in data.json with a\n // single meta record at the default locale, so a locale-scoped delete is\n // meaningless and destructive (the locale maps onto data.json + the default\n // meta, deleting the shared content and the wrong meta). Reject it; mirrors\n // the same guard in the plan API (`planContentDelete`).\n if (!model.i18n && opts.locale) {\n throw new Error(\n `Model \"${model.id}\" has i18n disabled — its content is locale-agnostic (stored in data.json), `\n + 'so a locale-scoped delete is invalid. Omit \"locale\" to delete the entry, '\n + 'or run contentrain_validate fix:true to remove stray per-locale meta files.',\n )\n }\n\n const removed: string[] = []\n const cDir = resolveContentDir(projectRoot, model)\n\n switch (model.kind) {\n case 'collection': {\n if (!opts.id) throw new Error('Collection delete requires an entry ID')\n const locales = opts.locale\n ? [opts.locale]\n : (await readDir(cDir)).filter(f => f.endsWith('.json')).map(f => f.replace('.json', '').replace(`${model.id}.`, ''))\n\n for (const loc of locales) {\n const filePath = resolveJsonFilePath(cDir, model, loc)\n const data = await readJson<Record<string, unknown>>(filePath)\n if (data && opts.id in data) {\n delete data[opts.id]\n await writeJson(filePath, data)\n removed.push(`content/${model.domain}/${model.id}/${loc}.json#${opts.id}`)\n }\n }\n\n for (const loc of locales) {\n await deleteMeta(projectRoot, model, { locale: loc, entryId: opts.id, defaultLocale: opts.defaultLocale })\n }\n break\n }\n\n case 'document': {\n if (!opts.slug) throw new Error('Document delete requires a slug')\n const slugDelErr = validateSlug(opts.slug)\n if (slugDelErr) throw new Error(slugDelErr)\n\n const strategy = resolveLocaleStrategy(model)\n if (!model.i18n) {\n // No i18n: single {slug}.md file\n await rm(join(cDir, `${opts.slug}.md`), { force: true })\n } else if (strategy === 'file') {\n // slug is a directory — remove entire slug directory\n await rm(join(cDir, opts.slug), { recursive: true, force: true })\n } else if (opts.locale) {\n // Remove specific locale file\n const filePath = resolveMdFilePath(cDir, model, opts.locale, opts.slug)\n await rm(filePath, { force: true })\n } else {\n // Remove all locale files for this slug\n const files = await readDir(strategy === 'directory' ? cDir : cDir)\n for (const f of files) {\n if (strategy === 'suffix' && f.startsWith(`${opts.slug}.`) && f.endsWith('.md')) {\n await rm(join(cDir, f), { force: true })\n } else if (strategy === 'directory') {\n // f is a locale dir — remove slug.md from it\n await rm(join(cDir, f, `${opts.slug}.md`), { force: true })\n } else if (strategy === 'none') {\n if (f === `${opts.slug}.md`) await rm(join(cDir, f), { force: true })\n }\n }\n }\n removed.push(`${model.content_path ?? `content/${model.domain}/${model.id}`}/${opts.slug}`)\n\n await deleteMeta(projectRoot, model, { slug: opts.slug, locale: opts.locale, defaultLocale: opts.defaultLocale })\n break\n }\n\n case 'singleton': {\n if (model.i18n && !opts.locale) throw new Error('Singleton delete requires a locale when i18n is enabled')\n const locale = opts.locale ?? 'data'\n const filePath = resolveJsonFilePath(cDir, model, locale)\n await rm(filePath, { force: true })\n removed.push(model.i18n\n ? `content/${model.domain}/${model.id}/${locale}.json`\n : `content/${model.domain}/${model.id}/data.json`)\n await deleteMeta(projectRoot, model, { locale: model.i18n ? locale : undefined, defaultLocale: opts.defaultLocale })\n break\n }\n\n case 'dictionary': {\n if (model.i18n && !opts.locale) throw new Error('Dictionary delete requires a locale when i18n is enabled')\n const locale = opts.locale ?? 'data'\n const filePath = resolveJsonFilePath(cDir, model, locale)\n\n if (opts.keys?.length) {\n // Delete specific keys from dictionary\n const existing = await readJson<Record<string, string>>(filePath) ?? {}\n const notFound: string[] = []\n for (const key of opts.keys) {\n if (key in existing) {\n delete existing[key]\n } else {\n notFound.push(key)\n }\n }\n if (notFound.length > 0) {\n throw new Error(`Dictionary \"${model.id}\" (${locale}): keys not found — [${notFound.join(', ')}]`)\n }\n await writeJson(filePath, existing)\n removed.push(...opts.keys.map(k => `${model.id}/${locale}:${k}`))\n } else {\n // Delete entire locale file\n await rm(filePath, { force: true })\n removed.push(model.i18n\n ? `content/${model.domain}/${model.id}/${locale}.json`\n : `content/${model.domain}/${model.id}/data.json`)\n await deleteMeta(projectRoot, model, { locale: model.i18n ? locale : undefined, defaultLocale: opts.defaultLocale })\n }\n break\n }\n }\n\n return removed\n}\n\n// ─── listContent ───\n\n/**\n * List content entries for a model. Dual signature:\n *\n * - `listContent(projectRoot, model, opts, config)` — legacy local flow,\n * uses direct filesystem reads and supports `opts.resolve` for\n * cross-model relation hydration.\n * - `listContent(reader, model, opts, config)` — reader-backed flow for\n * remote providers. Basic list works across all four model kinds.\n * `opts.resolve: true` is rejected with an error on remote readers\n * because the cross-model walk requires local filesystem access.\n *\n * The reader-based function lives in {@link listContentViaReader}; the\n * projectRoot-based entry point continues to call the legacy body to\n * preserve bit-for-bit behaviour for every existing caller.\n */\nexport function listContent(\n projectRoot: string,\n model: ModelDefinition,\n opts: ListOpts,\n config: ContentrainConfig,\n): Promise<unknown>\nexport function listContent(\n reader: RepoReader,\n model: ModelDefinition,\n opts: ListOpts,\n config: ContentrainConfig,\n): Promise<unknown>\nexport async function listContent(\n input: string | RepoReader,\n model: ModelDefinition,\n opts: ListOpts,\n config: ContentrainConfig,\n): Promise<unknown> {\n if (typeof input !== 'string') {\n return listContentViaReader(input, model, opts, config)\n }\n return listContentLocal(input, model, opts, config)\n}\n\nasync function listContentLocal(\n projectRoot: string,\n model: ModelDefinition,\n opts: ListOpts,\n config: ContentrainConfig,\n): Promise<unknown> {\n const cDir = resolveContentDir(projectRoot, model)\n const locale = opts.locale ?? config.locales.default\n\n switch (model.kind) {\n case 'singleton': {\n const data = await readJson<Record<string, unknown>>(resolveJsonFilePath(cDir, model, locale))\n return { kind: 'singleton', data: data ?? {}, locale }\n }\n\n case 'collection': {\n const data = await readJson<Record<string, Record<string, unknown>>>(resolveJsonFilePath(cDir, model, locale)) ?? {}\n let entries: Array<Record<string, unknown>> = Object.entries(data).map(([id, fields]) => {\n const entry: Record<string, unknown> = { id }\n Object.assign(entry, fields)\n return entry\n })\n\n // Filter\n if (opts.filter) {\n entries = entries.filter(entry => {\n for (const [key, value] of Object.entries(opts.filter!)) {\n if (entry[key] !== value) return false\n }\n return true\n })\n }\n\n const total = entries.length\n\n // Pagination\n const offset = opts.offset ?? 0\n const limit = opts.limit ?? entries.length\n entries = entries.slice(offset, offset + limit)\n\n // Resolve relations\n if (opts.resolve && model.fields) {\n entries = await resolveRelations(projectRoot, model, entries, locale)\n }\n\n return { kind: 'collection', data: entries, total, locale, offset, limit }\n }\n\n case 'document': {\n const entries: DocumentEntry[] = []\n const strategy = resolveLocaleStrategy(model)\n\n if (!model.i18n) {\n // No i18n: flat {slug}.md files, no locale in path\n const files = await readDir(cDir)\n for (const f of files) {\n if (!f.endsWith('.md')) continue\n const slug = f.replace('.md', '')\n const raw = await readText(join(cDir, f))\n if (!raw) continue\n const { frontmatter, body } = parseMarkdownFrontmatter(raw)\n entries.push({ slug, frontmatter, body })\n }\n } else if (strategy === 'file') {\n // Each slug is a subdirectory containing locale.md files\n const slugDirs = await readDir(cDir)\n for (const slug of slugDirs) {\n const raw = await readText(join(cDir, slug, `${locale}.md`))\n if (!raw) continue\n const { frontmatter, body } = parseMarkdownFrontmatter(raw)\n entries.push({ slug, frontmatter, body })\n }\n } else if (strategy === 'suffix') {\n // Files like {slug}.{locale}.md in flat directory\n const files = await readDir(cDir)\n const suffix = `.${locale}.md`\n for (const f of files) {\n if (!f.endsWith(suffix)) continue\n const slug = f.slice(0, -suffix.length)\n const raw = await readText(join(cDir, f))\n if (!raw) continue\n const { frontmatter, body } = parseMarkdownFrontmatter(raw)\n entries.push({ slug, frontmatter, body })\n }\n } else if (strategy === 'directory') {\n // Files in {locale}/ directory as {slug}.md\n const localeDir = join(cDir, locale)\n const files = await readDir(localeDir)\n for (const f of files) {\n if (!f.endsWith('.md')) continue\n const slug = f.replace('.md', '')\n const raw = await readText(join(localeDir, f))\n if (!raw) continue\n const { frontmatter, body } = parseMarkdownFrontmatter(raw)\n entries.push({ slug, frontmatter, body })\n }\n } else {\n // none — {slug}.md, no locale in filename\n const files = await readDir(cDir)\n for (const f of files) {\n if (!f.endsWith('.md')) continue\n const slug = f.replace('.md', '')\n const raw = await readText(join(cDir, f))\n if (!raw) continue\n const { frontmatter, body } = parseMarkdownFrontmatter(raw)\n entries.push({ slug, frontmatter, body })\n }\n }\n\n const total = entries.length\n const offset = opts.offset ?? 0\n const limit = opts.limit ?? entries.length\n const paged = entries.slice(offset, offset + limit)\n\n return { kind: 'document', data: paged, total, locale, offset, limit }\n }\n\n case 'dictionary': {\n const data = await readJson<Record<string, string>>(resolveJsonFilePath(cDir, model, locale)) ?? {}\n return { kind: 'dictionary', data, total_keys: Object.keys(data).length, locale }\n }\n }\n}\n\nasync function tryReadJsonViaReader<T>(reader: RepoReader, path: string): Promise<T | null> {\n try {\n return JSON.parse(await reader.readFile(path)) as T\n } catch {\n return null\n }\n}\n\nasync function tryReadTextViaReader(reader: RepoReader, path: string): Promise<string | null> {\n try {\n return await reader.readFile(path)\n } catch {\n return null\n }\n}\n\nasync function listContentViaReader(\n reader: RepoReader,\n model: ModelDefinition,\n opts: ListOpts,\n config: ContentrainConfig,\n): Promise<unknown> {\n if (opts.resolve) {\n throw new Error(\n 'contentrain_content_list with resolve:true requires local filesystem access. '\n + 'Use a LocalProvider (stdio or HTTP+LocalProvider) or omit resolve:true.',\n )\n }\n\n const cDir = contentDirPath(model)\n const locale = opts.locale ?? config.locales.default\n\n switch (model.kind) {\n case 'singleton': {\n const data = await tryReadJsonViaReader<Record<string, unknown>>(reader, contentFilePath(model, locale))\n return { kind: 'singleton', data: data ?? {}, locale }\n }\n\n case 'collection': {\n const data = await tryReadJsonViaReader<Record<string, Record<string, unknown>>>(\n reader,\n contentFilePath(model, locale),\n ) ?? {}\n let entries: Array<Record<string, unknown>> = Object.entries(data).map(([id, fields]) => {\n const entry: Record<string, unknown> = { id }\n Object.assign(entry, fields)\n return entry\n })\n\n if (opts.filter) {\n entries = entries.filter(entry => {\n for (const [key, value] of Object.entries(opts.filter!)) {\n if (entry[key] !== value) return false\n }\n return true\n })\n }\n\n const total = entries.length\n const offset = opts.offset ?? 0\n const limit = opts.limit ?? entries.length\n entries = entries.slice(offset, offset + limit)\n\n return { kind: 'collection', data: entries, total, locale, offset, limit }\n }\n\n case 'document': {\n const entries: DocumentEntry[] = []\n const strategy = resolveLocaleStrategy(model)\n\n const collectEntry = async (relPath: string, slug: string): Promise<void> => {\n const raw = await tryReadTextViaReader(reader, relPath)\n if (!raw) return\n const { frontmatter, body } = parseMarkdownFrontmatter(raw)\n entries.push({ slug, frontmatter, body })\n }\n\n if (!model.i18n) {\n const files = await reader.listDirectory(cDir)\n for (const f of files) {\n if (!f.endsWith('.md')) continue\n await collectEntry(documentFilePath(model, locale, f.replace(/\\.md$/u, '')), f.replace(/\\.md$/u, ''))\n }\n } else if (strategy === 'file') {\n const slugDirs = await reader.listDirectory(cDir)\n for (const slug of slugDirs) {\n await collectEntry(documentFilePath(model, locale, slug), slug)\n }\n } else if (strategy === 'suffix') {\n const files = await reader.listDirectory(cDir)\n const suffix = `.${locale}.md`\n for (const f of files) {\n if (!f.endsWith(suffix)) continue\n const slug = f.slice(0, -suffix.length)\n await collectEntry(documentFilePath(model, locale, slug), slug)\n }\n } else if (strategy === 'directory') {\n const files = await reader.listDirectory(`${cDir}/${locale}`)\n for (const f of files) {\n if (!f.endsWith('.md')) continue\n const slug = f.replace(/\\.md$/u, '')\n await collectEntry(documentFilePath(model, locale, slug), slug)\n }\n } else {\n const files = await reader.listDirectory(cDir)\n for (const f of files) {\n if (!f.endsWith('.md')) continue\n const slug = f.replace(/\\.md$/u, '')\n await collectEntry(documentFilePath(model, locale, slug), slug)\n }\n }\n\n const total = entries.length\n const offset = opts.offset ?? 0\n const limit = opts.limit ?? entries.length\n const paged = entries.slice(offset, offset + limit)\n\n return { kind: 'document', data: paged, total, locale, offset, limit }\n }\n\n case 'dictionary': {\n const data = await tryReadJsonViaReader<Record<string, string>>(reader, contentFilePath(model, locale)) ?? {}\n return { kind: 'dictionary', data, total_keys: Object.keys(data).length, locale }\n }\n }\n}\n\n// ─── readContent (for external use / relation resolving) ───\n\nexport async function readContent(\n projectRoot: string,\n model: ModelDefinition,\n opts: { locale: string; entryId?: string; slug?: string },\n): Promise<unknown> {\n const cDir = resolveContentDir(projectRoot, model)\n\n switch (model.kind) {\n case 'singleton':\n return readJson<Record<string, unknown>>(resolveJsonFilePath(cDir, model, opts.locale))\n\n case 'collection': {\n if (!opts.entryId) return null\n const data = await readJson<Record<string, Record<string, unknown>>>(resolveJsonFilePath(cDir, model, opts.locale))\n return data?.[opts.entryId] ? { id: opts.entryId, ...data[opts.entryId] } : null\n }\n\n case 'document': {\n if (!opts.slug) return null\n const raw = await readText(resolveMdFilePath(cDir, model, opts.locale, opts.slug))\n if (!raw) return null\n const { frontmatter, body } = parseMarkdownFrontmatter(raw)\n return { slug: opts.slug, ...frontmatter, body }\n }\n\n case 'dictionary':\n return readJson<Record<string, string>>(resolveJsonFilePath(cDir, model, opts.locale))\n }\n}\n\n// ─── Relation resolving ───\n\nasync function resolveRelations(\n projectRoot: string,\n model: ModelDefinition,\n entries: Array<Record<string, unknown>>,\n locale: string,\n): Promise<Array<Record<string, unknown>>> {\n if (!model.fields) return entries\n\n const relationFields: Array<{ name: string; targetModels: string[]; multi: boolean }> = []\n for (const [name, field] of Object.entries(model.fields)) {\n if (field.type === 'relation' || field.type === 'relations') {\n const targets = Array.isArray(field.model) ? field.model : field.model ? [field.model] : []\n relationFields.push({ name, targetModels: targets, multi: field.type === 'relations' })\n }\n }\n\n if (relationFields.length === 0) return entries\n\n // Load target model contents into cache (with circular reference protection)\n const targetCache: Record<string, Record<string, Record<string, unknown>>> = {}\n const visited = new Set<string>([model.id])\n\n for (const rf of relationFields) {\n for (const targetModelId of rf.targetModels) {\n if (targetCache[targetModelId] || visited.has(targetModelId)) continue\n visited.add(targetModelId)\n\n const targetModel = await readModel(projectRoot, targetModelId)\n if (!targetModel) continue\n\n if (targetModel.kind === 'collection') {\n const targetData = await readJson<Record<string, Record<string, unknown>>>(\n resolveJsonFilePath(resolveContentDir(projectRoot, targetModel), targetModel, locale),\n ) ?? {}\n targetCache[targetModelId] = targetData\n } else if (targetModel.kind === 'document') {\n // Build slug-keyed cache by listing document entries for this locale\n const docCache: Record<string, Record<string, unknown>> = {}\n const cDir = resolveContentDir(projectRoot, targetModel)\n const strategy = resolveLocaleStrategy(targetModel)\n\n if (!targetModel.i18n) {\n const files = await readDir(cDir)\n for (const f of files) {\n if (!f.endsWith('.md')) continue\n const slug = f.replace('.md', '')\n const raw = await readText(join(cDir, f))\n if (!raw) continue\n const { frontmatter, body } = parseMarkdownFrontmatter(raw)\n docCache[slug] = { slug, ...frontmatter, body }\n }\n } else if (strategy === 'file') {\n const slugDirs = await readDir(cDir)\n for (const slug of slugDirs) {\n const raw = await readText(join(cDir, slug, `${locale}.md`))\n if (!raw) continue\n const { frontmatter, body } = parseMarkdownFrontmatter(raw)\n docCache[slug] = { slug, ...frontmatter, body }\n }\n } else if (strategy === 'suffix') {\n const files = await readDir(cDir)\n const suffix = `.${locale}.md`\n for (const f of files) {\n if (!f.endsWith(suffix)) continue\n const slug = f.slice(0, -suffix.length)\n const raw = await readText(join(cDir, f))\n if (!raw) continue\n const { frontmatter, body } = parseMarkdownFrontmatter(raw)\n docCache[slug] = { slug, ...frontmatter, body }\n }\n } else if (strategy === 'directory') {\n const localeDir = join(cDir, locale)\n const files = await readDir(localeDir)\n for (const f of files) {\n if (!f.endsWith('.md')) continue\n const slug = f.replace('.md', '')\n const raw = await readText(join(localeDir, f))\n if (!raw) continue\n const { frontmatter, body } = parseMarkdownFrontmatter(raw)\n docCache[slug] = { slug, ...frontmatter, body }\n }\n } else {\n // 'none' strategy\n const files = await readDir(cDir)\n for (const f of files) {\n if (!f.endsWith('.md')) continue\n const slug = f.replace('.md', '')\n const raw = await readText(join(cDir, f))\n if (!raw) continue\n const { frontmatter, body } = parseMarkdownFrontmatter(raw)\n docCache[slug] = { slug, ...frontmatter, body }\n }\n }\n\n targetCache[targetModelId] = docCache\n }\n }\n }\n\n return entries.map(entry => {\n const resolved = { ...entry }\n for (const rf of relationFields) {\n const value = resolved[rf.name]\n if (!value) continue\n\n if (rf.multi && Array.isArray(value)) {\n resolved[rf.name] = value.map(id => {\n for (const targetModelId of rf.targetModels) {\n const cached = targetCache[targetModelId]?.[id as string]\n if (cached) return { id, ...cached }\n }\n return id\n })\n } else if (typeof value === 'string') {\n for (const targetModelId of rf.targetModels) {\n const cached = targetCache[targetModelId]?.[value]\n if (cached) {\n resolved[rf.name] = { id: value, ...cached }\n break\n }\n }\n }\n }\n return resolved\n })\n}\n","import type { FieldDef, FieldType, ModelDefinition, ModelSummary } from '@contentrain/types'\nimport { DICTIONARY_TITLE_FIELD, isTitleFieldType, LOCALE_PATTERN, MODEL_FIELD_ORDER, TITLE_FIELD_TYPES, titleFieldTarget } from '@contentrain/types'\nimport { join } from 'node:path'\nimport { rm } from 'node:fs/promises'\nimport { z } from 'zod'\nimport { contentrainDir, ensureDir, readDir, readJson, writeJson } from '../util/fs.js'\nimport type { RepoReader } from './contracts/index.js'\nimport { LocalReader } from '../providers/local/reader.js'\nimport { resolveContentDir, resolveLocaleStrategy } from './content-manager.js'\nimport { contentDirPath } from './ops/paths.js'\n\nexport type { ModelSummary } from '@contentrain/types'\n// Re-exported so `packages/rules` and `packages/skills` — which devDep\n// @contentrain/mcp but not @contentrain/types — can assert docs parity\n// against the canonical key list without taking a new dependency.\nexport { MODEL_FIELD_ORDER } from '@contentrain/types'\n\nconst MODELS_DIR_PATH = '.contentrain/models'\n\nasync function tryReadJsonViaReader<T>(reader: RepoReader, path: string): Promise<T | null> {\n try {\n return JSON.parse(await reader.readFile(path)) as T\n } catch {\n return null\n }\n}\n\n/**\n * List every model defined under `.contentrain/models/*.json`.\n *\n * Accepts either a legacy `projectRoot` string (filesystem walk) or any\n * `RepoReader` — HTTP-hosted callers pass their `GitHubProvider` so the\n * same helper resolves model metadata over the Git Data API.\n */\nexport function listModels(projectRoot: string): Promise<ModelSummary[]>\nexport function listModels(reader: RepoReader): Promise<ModelSummary[]>\nexport async function listModels(input: string | RepoReader): Promise<ModelSummary[]> {\n let files: string[]\n let load: (file: string) => Promise<ModelDefinition | null>\n\n if (typeof input === 'string') {\n const modelsDir = join(contentrainDir(input), 'models')\n files = await readDir(modelsDir)\n load = file => readJson<ModelDefinition>(join(modelsDir, file))\n } else {\n files = await input.listDirectory(MODELS_DIR_PATH)\n load = file => tryReadJsonViaReader<ModelDefinition>(input, `${MODELS_DIR_PATH}/${file}`)\n }\n\n const jsonFiles = files.filter(f => f.endsWith('.json'))\n const models = await Promise.all(jsonFiles.map(load))\n\n return models\n .filter((m): m is ModelDefinition => m !== null && !!m.id)\n .map(model => ({\n id: model.id,\n kind: model.kind,\n domain: model.domain,\n i18n: model.i18n,\n fields: model.fields ? Object.keys(model.fields).length : 0,\n }))\n .toSorted((a, b) => a.id.localeCompare(b.id, 'en'))\n}\n\n/**\n * Read a single model definition. Same dual signature as {@link listModels}.\n */\nexport function readModel(projectRoot: string, modelId: string): Promise<ModelDefinition | null>\nexport function readModel(reader: RepoReader, modelId: string): Promise<ModelDefinition | null>\nexport async function readModel(input: string | RepoReader, modelId: string): Promise<ModelDefinition | null> {\n if (typeof input === 'string') {\n const filePath = join(contentrainDir(input), 'models', `${modelId}.json`)\n return readJson<ModelDefinition>(filePath)\n }\n return tryReadJsonViaReader<ModelDefinition>(input, `${MODELS_DIR_PATH}/${modelId}.json`)\n}\n\nasync function countDocumentFileStrategy(\n reader: RepoReader,\n contentDir: string,\n entries: string[],\n): Promise<{ total: number, locales: Record<string, number> }> {\n const locales: Record<string, number> = {}\n let total = 0\n\n const results = await Promise.all(\n entries.map(async (entry) => {\n const localeFiles = await reader.listDirectory(`${contentDir}/${entry}`)\n return localeFiles\n .map(lf => lf.replace(/\\.(json|md|mdx)$/, ''))\n .filter((locale, i) => locale !== localeFiles[i])\n }),\n )\n\n for (const entryLocales of results) {\n for (const locale of entryLocales) {\n locales[locale] = (locales[locale] ?? 0) + 1\n total++\n }\n }\n\n return { total, locales }\n}\n\nasync function countDocumentSuffixStrategy(\n _reader: RepoReader,\n _contentDir: string,\n files: string[],\n): Promise<{ total: number, locales: Record<string, number> }> {\n const locales: Record<string, number> = {}\n const slugsByLocale: Record<string, Set<string>> = {}\n\n for (const f of files) {\n if (!f.endsWith('.md')) continue\n // Pattern: {slug}.{locale}.md\n const match = f.match(/^(.+)\\.([a-z]{2}(?:-[A-Z]{2})?)\\.md$/)\n if (!match) continue\n const locale = match[2]!\n if (!slugsByLocale[locale]) slugsByLocale[locale] = new Set()\n slugsByLocale[locale].add(match[1]!)\n }\n\n let total = 0\n for (const [locale, slugs] of Object.entries(slugsByLocale)) {\n locales[locale] = slugs.size\n total += slugs.size\n }\n\n return { total, locales }\n}\n\nasync function countDocumentDirectoryStrategy(\n reader: RepoReader,\n contentDir: string,\n localeDirs: string[],\n): Promise<{ total: number, locales: Record<string, number> }> {\n const locales: Record<string, number> = {}\n let total = 0\n\n const results = await Promise.all(\n localeDirs.map(async (localeDir) => {\n const files = await reader.listDirectory(`${contentDir}/${localeDir}`)\n const mdFiles = files.filter(f => f.endsWith('.md'))\n return { locale: localeDir, count: mdFiles.length }\n }),\n )\n\n for (const { locale, count } of results) {\n locales[locale] = count\n total += count\n }\n\n return { total, locales }\n}\n\nasync function countDocumentNoneStrategy(\n reader: RepoReader,\n modelId: string,\n files: string[],\n i18n: boolean,\n): Promise<{ total: number, locales: Record<string, number> }> {\n const mdFiles = files.filter(f => f.endsWith('.md'))\n\n if (!i18n) {\n return { total: mdFiles.length, locales: { _: mdFiles.length } }\n }\n\n // With i18n + none strategy, content files have no locale info.\n // Use meta/{modelId}/{slug}/ directories to determine locale counts.\n const metaDir = `.contentrain/meta/${modelId}`\n const locales: Record<string, number> = {}\n let total = 0\n\n const slugs = mdFiles.map(f => f.replace('.md', ''))\n const results = await Promise.all(\n slugs.map(async (slug) => {\n const metaFiles = await reader.listDirectory(`${metaDir}/${slug}`)\n return metaFiles\n .filter(f => f.endsWith('.json'))\n .map(f => f.replace('.json', ''))\n }),\n )\n\n for (const slugLocales of results) {\n for (const locale of slugLocales) {\n locales[locale] = (locales[locale] ?? 0) + 1\n total++\n }\n }\n\n return { total, locales }\n}\n\nasync function countCollectionEntries(\n reader: RepoReader,\n contentDir: string,\n jsonFiles: string[],\n): Promise<{ total: number, locales: Record<string, number> }> {\n const locales: Record<string, number> = {}\n let total = 0\n\n const results = await Promise.all(\n jsonFiles.map(async (file) => {\n const locale = file.replace(/\\.json$/, '')\n const data = await tryReadJsonViaReader<Record<string, unknown>>(reader, `${contentDir}/${file}`)\n return { locale, count: data ? Object.keys(data).length : 0 }\n }),\n )\n\n for (const { locale, count } of results) {\n locales[locale] = count\n total += count\n }\n\n return { total, locales }\n}\n\n/**\n * Count content entries across locales for a model.\n *\n * Accepts either a legacy `projectRoot` string (wraps LocalReader internally)\n * or any `RepoReader` — so remote providers (GitHubProvider) feed the same\n * counting logic via the Git Data API.\n */\nexport function countEntries(\n projectRoot: string,\n model: ModelDefinition,\n): Promise<{ total: number, locales: Record<string, number> }>\nexport function countEntries(\n reader: RepoReader,\n model: ModelDefinition,\n): Promise<{ total: number, locales: Record<string, number> }>\nexport async function countEntries(\n input: string | RepoReader,\n model: ModelDefinition,\n): Promise<{ total: number, locales: Record<string, number> }> {\n const reader: RepoReader = typeof input === 'string' ? new LocalReader(input) : input\n const cDir = contentDirPath(model)\n const strategy = resolveLocaleStrategy(model)\n const files = await reader.listDirectory(cDir)\n\n if (model.kind === 'document') {\n if (!model.i18n) {\n // No i18n: flat {slug}.md files\n return countDocumentNoneStrategy(reader, model.id, files, false)\n }\n\n switch (strategy) {\n case 'file':\n return countDocumentFileStrategy(reader, cDir, files)\n case 'suffix':\n return countDocumentSuffixStrategy(reader, cDir, files)\n case 'directory':\n return countDocumentDirectoryStrategy(reader, cDir, files)\n case 'none':\n return countDocumentNoneStrategy(reader, model.id, files, true)\n }\n }\n\n if (model.kind === 'collection') {\n if (!model.i18n) {\n // Non-i18n: single data.json\n const jsonFiles = files.filter(f => f.endsWith('.json'))\n return countCollectionEntries(reader, cDir, jsonFiles)\n }\n switch (strategy) {\n case 'suffix': {\n // Files: {model}.{locale}.json\n const jsonFiles = files.filter(f => f.endsWith('.json'))\n const locales: Record<string, number> = {}\n for (const f of jsonFiles) {\n const match = f.match(/^.+\\.([a-z]{2}(?:-[A-Z]{2})?)\\.json$/)\n if (match) {\n const data = await tryReadJsonViaReader<Record<string, unknown>>(reader, `${cDir}/${f}`)\n locales[match[1]!] = data ? Object.keys(data).length : 0\n }\n }\n const total = Object.values(locales).reduce((a, b) => a + b, 0)\n return { total, locales }\n }\n case 'directory': {\n // Dirs: {locale}/... containing json files\n const locales: Record<string, number> = {}\n let total = 0\n for (const localeDir of files) {\n const subFiles = await reader.listDirectory(`${cDir}/${localeDir}`)\n const jsonFile = subFiles.find(f => f.endsWith('.json'))\n if (jsonFile) {\n const data = await tryReadJsonViaReader<Record<string, unknown>>(reader, `${cDir}/${localeDir}/${jsonFile}`)\n const count = data ? Object.keys(data).length : 0\n locales[localeDir] = count\n total += count\n }\n }\n return { total, locales }\n }\n case 'none': {\n // Single file: {model}.json — count entries inside\n const noneFile = files.find(f => f === `${model.id}.json`)\n if (!noneFile) return { total: 0, locales: {} }\n const data = await tryReadJsonViaReader<Record<string, unknown>>(reader, `${cDir}/${noneFile}`)\n const count = data ? Object.keys(data).length : 0\n return { total: count, locales: { _: count } }\n }\n default: {\n // 'file': {locale}.json\n const jsonFiles = files.filter(f => f.endsWith('.json'))\n return countCollectionEntries(reader, cDir, jsonFiles)\n }\n }\n }\n\n // singleton / dictionary — one entry per locale file\n if (!model.i18n) {\n // Non-i18n: single data.json\n const hasData = files.some(f => f === 'data.json')\n return { total: hasData ? 1 : 0, locales: {} }\n }\n\n switch (strategy) {\n case 'suffix': {\n // Files: {model}.{locale}.json\n const locales: Record<string, number> = {}\n for (const f of files) {\n const match = f.match(/^.+\\.([a-z]{2}(?:-[A-Z]{2})?)\\.json$/)\n if (match) locales[match[1]!] = 1\n }\n return { total: Object.keys(locales).length, locales }\n }\n case 'directory': {\n // Dirs: {locale}/...\n const locales: Record<string, number> = {}\n for (const localeDir of files) {\n const subFiles = await reader.listDirectory(`${cDir}/${localeDir}`)\n if (subFiles.some(f => f.endsWith('.json'))) {\n locales[localeDir] = 1\n }\n }\n return { total: Object.keys(locales).length, locales }\n }\n case 'none': {\n // Single file: {model}.json\n const hasFile = files.some(f => f === `${model.id}.json`)\n return { total: hasFile ? 1 : 0, locales: {} }\n }\n default: {\n // 'file': {locale}.json\n const jsonFiles = files.filter(f => f.endsWith('.json'))\n const locales: Record<string, number> = {}\n for (const file of jsonFiles) {\n locales[file.replace(/\\.json$/, '')] = 1\n }\n return { total: jsonFiles.length, locales }\n }\n }\n}\n\nexport async function writeModel(projectRoot: string, model: ModelDefinition): Promise<void> {\n const filePath = join(contentrainDir(projectRoot), 'models', `${model.id}.json`)\n await writeJson(filePath, model, MODEL_FIELD_ORDER)\n\n // Ensure content and meta directories exist (respects content_path)\n await ensureDir(resolveContentDir(projectRoot, model))\n await ensureDir(join(contentrainDir(projectRoot), 'meta', model.id))\n}\n\nexport async function deleteModel(projectRoot: string, modelId: string): Promise<string[]> {\n const model = await readModel(projectRoot, modelId)\n if (!model) return []\n\n const crDir = contentrainDir(projectRoot)\n const removed: string[] = []\n\n const modelPath = join(crDir, 'models', `${modelId}.json`)\n const contentPath = resolveContentDir(projectRoot, model)\n const metaPath = join(crDir, 'meta', modelId)\n\n await rm(modelPath, { force: true })\n removed.push(`models/${modelId}.json`)\n\n try {\n await rm(contentPath, { recursive: true, force: true })\n removed.push(model.content_path ?? `content/${model.domain}/${modelId}/`)\n } catch {\n // directory may not exist\n }\n\n try {\n await rm(metaPath, { recursive: true, force: true })\n removed.push(`meta/${modelId}/`)\n } catch {\n // directory may not exist\n }\n\n return removed\n}\n\nexport interface ModelReference {\n model: string\n field: string\n type: 'relation' | 'relations'\n}\n\n/**\n * Enumerate models that reference `modelId` through relation or relations\n * fields. Used by `model_delete` to block destructive deletes when other\n * models still depend on the target.\n *\n * Accepts either a legacy `projectRoot` string (LocalReader wraps internally)\n * or any `RepoReader` — remote providers get the same pre-check.\n */\nexport function checkReferences(projectRoot: string, modelId: string): Promise<ModelReference[]>\nexport function checkReferences(reader: RepoReader, modelId: string): Promise<ModelReference[]>\nexport async function checkReferences(\n input: string | RepoReader,\n modelId: string,\n): Promise<ModelReference[]> {\n const summaries = typeof input === 'string' ? await listModels(input) : await listModels(input)\n const others = summaries.filter(s => s.id !== modelId)\n\n const models = await Promise.all(\n others.map(s => typeof input === 'string' ? readModel(input, s.id) : readModel(input, s.id)),\n )\n\n const refs: ModelReference[] = []\n for (const model of models) {\n if (!model?.fields) continue\n\n for (const [fieldName, fieldDef] of Object.entries(model.fields)) {\n if (fieldDef.type !== 'relation' && fieldDef.type !== 'relations') continue\n const targets = Array.isArray(fieldDef.model) ? fieldDef.model : [fieldDef.model]\n if (targets.includes(modelId)) {\n refs.push({ model: model.id, field: fieldName, type: fieldDef.type })\n }\n }\n }\n\n return refs\n}\n\n// ─── Shared Field Type Catalog ───\n\nexport const FIELD_TYPE_ENUM = [\n 'string', 'text', 'email', 'url', 'slug', 'color', 'phone', 'code', 'icon',\n 'markdown', 'richtext',\n 'number', 'integer', 'decimal', 'percent', 'rating',\n 'boolean', 'date', 'datetime',\n 'image', 'video', 'file',\n 'relation', 'relations',\n 'select', 'array', 'object',\n] as const\n\n/**\n * Shared Zod schema for field definitions.\n * Used by both model_save and normalize extract for full parity.\n *\n * `.strict()` is load-bearing: the default `z.object` *strips* unknown keys, so a\n * typo'd constraint (`requird: true`) used to vanish without a word and the field\n * silently lost the rule its author thought they had declared.\n */\nexport const fieldDefZodSchema: z.ZodType<Record<string, unknown>> = z.record(z.string(), z.object({\n type: z.enum(FIELD_TYPE_ENUM).describe('Field type from the 27-type catalog'),\n required: z.boolean().optional(),\n unique: z.boolean().optional(),\n default: z.unknown().optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n pattern: z.string().optional(),\n options: z.array(z.string()).optional(),\n model: z.union([z.string(), z.array(z.string())]).optional(),\n items: z.union([z.string(), z.lazy(() => z.record(z.string(), z.unknown()))]).optional(),\n fields: z.lazy(() => z.record(z.string(), z.unknown())).optional(),\n accept: z.string().optional(),\n maxSize: z.number().optional(),\n description: z.string().optional(),\n label: z.union([z.string(), z.record(z.string(), z.string())]).optional()\n .describe('Editor label. A string is one label for all locales; an object keyed by locale carries a translation each.'),\n order: z.number().optional()\n .describe('Display position, ascending. Fields without one sort last, alphabetically. Fractional values allowed.'),\n}).strict().refine(\n (f) => {\n if ((f.type === 'relation' || f.type === 'relations') && !f.model) return false\n if (f.type === 'select' && (!f.options || f.options.length === 0)) return false\n return true\n },\n { message: 'relation/relations requires \"model\", select requires non-empty \"options\"' },\n))\n\n// ─── Model Validation (shared between model_save and normalize extract) ───\n\nconst VALID_FIELD_TYPES = new Set<string>(FIELD_TYPE_ENUM)\n\n/** Field types whose value is a path/URL to a media asset. */\nconst MEDIA_FIELD_TYPES = new Set<string>(['image', 'video', 'file'])\n/** Bounds `items`/`fields` nesting; far above any real schema. */\nconst MAX_SCHEMA_DEPTH = 10\n/** Field names are snake_case: a letter, then letters, digits and underscores. */\nconst FIELD_NAME_PATTERN = /^[a-z][a-z0-9_]*$/\n\nexport interface ModelDefinitionIssues {\n /** Block the write. */\n errors: string[]\n /** Surface to the caller; the write proceeds. */\n warnings: string[]\n}\n\nexport interface ModelDefinitionOptions {\n /**\n * Field paths already declared by the model being updated — `title`,\n * `seo.title`, `tags.items.label` — as {@link collectFieldPaths} spells them.\n *\n * A name in this set that is not snake_case is grandfathered. It was accepted\n * before the rule existed, and refusing it now would make the whole model\n * read-only through MCP: no edit could be saved, not even one that never\n * touches the field. A one-line `title_field` correction on a model with one\n * legacy `creativeWork` relation should not require renaming the field, its\n * content keys in every locale, and every consuming component first.\n *\n * Only *new* fields must be snake_case. The legacy name is reported as a\n * warning so the caller knows what was tolerated.\n */\n existingFieldPaths?: ReadonlySet<string>\n}\n\n/**\n * Every field path a schema declares, nested paths dotted the way\n * `validateModelDefinition` reports them: `seo.title` for an object's member,\n * `tags.items.label` for a member of an array's item object.\n */\nexport function collectFieldPaths(fields: Record<string, unknown> | undefined, prefix = ''): Set<string> {\n const out = new Set<string>()\n if (!fields) return out\n for (const [name, raw] of Object.entries(fields)) {\n const path = `${prefix}${name}`\n out.add(path)\n const def = raw as RawFieldDef | null\n if (typeof def !== 'object' || def === null) continue\n if (typeof def.fields === 'object' && def.fields !== null) {\n for (const nested of collectFieldPaths(def.fields as Record<string, unknown>, `${path}.`)) out.add(nested)\n }\n const items = def.items as RawFieldDef | string | undefined\n if (typeof items === 'object' && items !== null && typeof items.fields === 'object' && items.fields !== null) {\n for (const nested of collectFieldPaths(items.fields as Record<string, unknown>, `${path}.items.`)) out.add(nested)\n }\n }\n return out\n}\n\n/**\n * Declared field paths whose name predates the snake_case rule.\n *\n * The project validator reports these so an agent learns a model carries\n * legacy names *before* it edits the model, rather than discovering them\n * mid-operation. `model_save` tolerates them; see {@link ModelDefinitionOptions}.\n */\nexport function legacyFieldNames(fields: Record<string, unknown> | undefined): string[] {\n return [...collectFieldPaths(fields)].filter(path => !FIELD_NAME_PATTERN.test(path.slice(path.lastIndexOf('.') + 1)))\n}\n\n/**\n * A field's name is snake_case, or it is a legacy name the model already has.\n * Anything else is an error. See {@link ModelDefinitionOptions.existingFieldPaths}.\n */\nfunction checkFieldName(\n path: string,\n opts: ModelDefinitionOptions,\n errors: string[],\n warnings: string[],\n): void {\n const name = path.slice(path.lastIndexOf('.') + 1)\n if (FIELD_NAME_PATTERN.test(name)) return\n if (opts.existingFieldPaths?.has(path)) {\n warnings.push(\n `Field \"${path}\": legacy name is not snake_case — kept because the model already has it. `\n + 'New fields must be snake_case. Renaming it also means renaming its content keys in every locale.',\n )\n return\n }\n errors.push(`Field \"${path}\": invalid name — must be snake_case starting with letter`)\n}\n\ninterface RawFieldDef {\n type?: string\n required?: unknown\n unique?: unknown\n default?: unknown\n min?: unknown\n max?: unknown\n pattern?: unknown\n options?: unknown\n model?: unknown\n items?: unknown\n fields?: unknown\n accept?: unknown\n maxSize?: unknown\n label?: unknown\n order?: unknown\n}\n\n/**\n * Check one field definition, recursing into `fields` and `items`.\n *\n * The governing rule: **do not accept a constraint that will not be enforced.**\n * A constraint that silently does nothing is worse than no constraint, because\n * the author stops looking. So a property declared where it cannot apply is an\n * error, and a property we genuinely cannot enforce says so out loud.\n */\nfunction checkFieldDef(\n raw: unknown,\n path: string,\n modelKind: string,\n errors: string[],\n warnings: string[],\n depth: number,\n opts: ModelDefinitionOptions,\n): void {\n if (typeof raw !== 'object' || raw === null) {\n errors.push(`Field \"${path}\": must be an object`)\n return\n }\n if (depth > MAX_SCHEMA_DEPTH) {\n errors.push(`Field \"${path}\": exceeds the maximum nesting depth of ${MAX_SCHEMA_DEPTH}`)\n return\n }\n\n const def = raw as RawFieldDef\n const type = def.type\n\n if (!type || !VALID_FIELD_TYPES.has(type)) {\n errors.push(`Field \"${path}\": invalid type \"${type}\"`)\n return\n }\n\n // Presentation. Wrong here is not fatal to a write, but a locale-keyed label\n // whose keys are not locales is the same inversion the vocabulary hits, and\n // it silently resolves to nothing.\n if (def.label !== undefined) {\n if (typeof def.label === 'string') {\n if (def.label.trim() === '') errors.push(`Field \"${path}\": \"label\" is empty`)\n } else if (typeof def.label === 'object' && def.label !== null && !Array.isArray(def.label)) {\n const entries = Object.entries(def.label as Record<string, unknown>)\n if (entries.length === 0) errors.push(`Field \"${path}\": \"label\" has no translations`)\n for (const [locale, value] of entries) {\n if (!LOCALE_PATTERN.test(locale)) {\n errors.push(`Field \"${path}\": \"label\" key \"${locale}\" is not a locale code. A per-locale label nests as { \"en\": \"…\", \"tr\": \"…\" }.`)\n }\n if (typeof value !== 'string' || value.trim() === '') {\n errors.push(`Field \"${path}\": \"label\" for \"${locale}\" must be a non-empty string`)\n }\n }\n } else {\n errors.push(`Field \"${path}\": \"label\" must be a string, or an object keyed by locale`)\n }\n }\n if (def.order !== undefined && (typeof def.order !== 'number' || !Number.isFinite(def.order))) {\n errors.push(`Field \"${path}\": \"order\" must be a finite number`)\n }\n\n if ((type === 'relation' || type === 'relations') && !def.model) {\n errors.push(`Field \"${path}\": ${type} type requires \"model\" property`)\n }\n if (type === 'select' && (!Array.isArray(def.options) || def.options.length === 0)) {\n errors.push(`Field \"${path}\": select type requires non-empty \"options\" array`)\n }\n\n // An object with no shape is a field nothing can validate and no editor can\n // render — it shows as an empty frame. A warning, not an error: it is a\n // legitimate intermediate state while a schema is being designed.\n if (type === 'object' && (!def.fields || typeof def.fields !== 'object' || Object.keys(def.fields as Record<string, unknown>).length === 0)) {\n warnings.push(`Field \"${path}\": \"object\" with no \"fields\" — nothing validates it and no editor can render it. Declare its shape, or use a plain type.`)\n }\n // The reverse direction was never checked, so `options` on a string field was\n // accepted and then silently ignored at validation time.\n if (def.options !== undefined && type !== 'select') {\n errors.push(`Field \"${path}\": \"options\" only applies to select fields — it is ignored on \"${type}\"`)\n }\n if (def.items !== undefined && type !== 'array') {\n errors.push(`Field \"${path}\": \"items\" only applies to array fields — it is ignored on \"${type}\"`)\n }\n if (def.fields !== undefined && type !== 'object') {\n errors.push(`Field \"${path}\": \"fields\" only applies to object fields — it is ignored on \"${type}\"`)\n }\n if (def.accept !== undefined && !MEDIA_FIELD_TYPES.has(type)) {\n errors.push(`Field \"${path}\": \"accept\" only applies to image/video/file fields — it is ignored on \"${type}\"`)\n }\n if (def.maxSize !== undefined && !MEDIA_FIELD_TYPES.has(type)) {\n errors.push(`Field \"${path}\": \"maxSize\" only applies to image/video/file fields — it is ignored on \"${type}\"`)\n }\n\n // A singleton holds one record per locale, so there is nothing for a value to\n // be unique against.\n if (def.unique === true && modelKind === 'singleton') {\n errors.push(`Field \"${path}\": \"unique\" has no meaning on a singleton — the model holds a single record per locale`)\n }\n\n if (typeof def.min === 'number' && typeof def.max === 'number' && def.min > def.max) {\n errors.push(`Field \"${path}\": min (${def.min}) is greater than max (${def.max})`)\n }\n\n // Compile the regex here rather than let it fail once per entry at validation\n // time, where it degrades to a warning and silently disables the constraint.\n if (typeof def.pattern === 'string') {\n try {\n // eslint-disable-next-line no-new\n new RegExp(def.pattern)\n } catch {\n errors.push(`Field \"${path}\": \"pattern\" is not a valid regular expression — /${def.pattern}/`)\n }\n }\n\n if (def.default !== undefined) {\n checkDefaultCoherence(def, type, path, errors)\n }\n\n // `max` on a media field measures the length of the stored path string, not\n // the file — almost certainly not what the author meant.\n if (typeof def.max === 'number' && MEDIA_FIELD_TYPES.has(type)) {\n warnings.push(\n `Field \"${path}\": \"max\" on a ${type} field limits the length of the stored path string, not the file size. Use \"maxSize\" for bytes.`,\n )\n }\n\n // Said plainly rather than accepted in silence: MCP holds a path, never the\n // bytes, so it cannot check this. The provider owns the policy at ingest.\n if (def.maxSize !== undefined && MEDIA_FIELD_TYPES.has(type)) {\n warnings.push(\n `Field \"${path}\": \"maxSize\" is not enforced by MCP — it has no access to the file. Your media provider enforces it when the asset is ingested.`,\n )\n }\n\n if (def.fields !== undefined && typeof def.fields === 'object' && def.fields !== null) {\n for (const [nested, nestedDef] of Object.entries(def.fields as Record<string, unknown>)) {\n checkFieldName(`${path}.${nested}`, opts, errors, warnings)\n checkFieldDef(nestedDef, `${path}.${nested}`, modelKind, errors, warnings, depth + 1, opts)\n }\n }\n\n if (typeof def.items === 'string') {\n if (!VALID_FIELD_TYPES.has(def.items)) {\n errors.push(`Field \"${path}.items\": invalid type \"${def.items}\"`)\n }\n } else if (def.items !== undefined) {\n checkFieldDef(def.items, `${path}.items`, modelKind, errors, warnings, depth + 1, opts)\n }\n}\n\n/** A default that its own field would reject is a schema bug, not a content one. */\nfunction checkDefaultCoherence(def: RawFieldDef, type: string, path: string, errors: string[]): void {\n const value = def.default\n const isString = typeof value === 'string'\n const isNumber = typeof value === 'number'\n\n if (type === 'select' && Array.isArray(def.options) && isString && !def.options.includes(value)) {\n errors.push(`Field \"${path}\": default \"${value}\" is not one of its own options [${(def.options as string[]).join(', ')}]`)\n return\n }\n const wantsNumber = ['number', 'integer', 'decimal', 'percent', 'rating'].includes(type)\n const wantsBoolean = type === 'boolean'\n const wantsArray = type === 'array'\n\n if (wantsNumber && !isNumber) {\n errors.push(`Field \"${path}\": default must be a number for type \"${type}\"`)\n } else if (wantsBoolean && typeof value !== 'boolean') {\n errors.push(`Field \"${path}\": default must be a boolean for type \"${type}\"`)\n } else if (wantsArray && !Array.isArray(value)) {\n errors.push(`Field \"${path}\": default must be an array for type \"${type}\"`)\n }\n}\n\n// ─── title_field ───\n\n/** Field names that announce themselves as a title, most explicit first. */\nconst TITLE_NAME_HINTS = ['title', 'name', 'label', 'heading'] as const\n\n/**\n * Preference among displayable types, short scalars first. A title is a label,\n * not a body: given both `question: string` and `answer: text`, the string wins.\n * Without this, \"first required text field\" resolves alphabetically and a FAQ\n * model gets titled by its answers. The three at the end only ever break a tie\n * on the name-match rung — see {@link NOT_INFERRED_AS_TITLE}.\n */\nconst TITLE_TYPE_PRIORITY: readonly FieldType[] = [\n 'string', 'email', 'text', 'markdown', 'richtext', 'slug', 'url', 'code',\n]\n\n/**\n * Legal `title_field` types that inference never falls back to.\n *\n * An author may deliberately title a model by its slug, URL or code snippet, and\n * `title_field` accepts that. *Guessed*, the same choice is the failure this\n * contract exists to prevent: a settings singleton whose only displayable field\n * is `whatsapp_url` was backfilled with it, and every Studio row read as a\n * WhatsApp link. Studio's runtime resolver (`entry-title.ts`) skips the same\n * three types on its fallback rung, so the writer here and the reader there\n * agree on what a fallback title is — before, the CLI wrote exactly what Studio\n * is written to avoid.\n */\nconst NOT_INFERRED_AS_TITLE: ReadonlySet<FieldType> = new Set<FieldType>(['slug', 'url', 'code'])\n\nexport interface TitleFieldPick {\n field: string\n /** Which rule chose it — surfaced to the user so an inferred title can be overruled. */\n rule: 'dictionary' | 'name-match' | 'required-displayable' | 'displayable'\n}\n\ninterface TitleCandidate {\n field: string\n type: FieldType\n required: boolean\n}\n\n/** Fields that could carry a title at all. Everything else is out of the running. */\nfunction titleCandidates(fields?: Record<string, unknown>): TitleCandidate[] {\n if (!fields) return []\n const out: TitleCandidate[] = []\n for (const [field, raw] of Object.entries(fields)) {\n const def = raw as { type?: unknown; required?: unknown } | null\n const type = def?.type\n if (typeof type !== 'string' || !isTitleFieldType(type as FieldType)) continue\n out.push({ field, type: type as FieldType, required: def?.required === true })\n }\n return out\n}\n\nfunction byTypeThenName(a: TitleCandidate, b: TitleCandidate): number {\n const byType = TITLE_TYPE_PRIORITY.indexOf(a.type) - TITLE_TYPE_PRIORITY.indexOf(b.type)\n return byType !== 0 ? byType : a.field.localeCompare(b.field, 'en')\n}\n\n/**\n * Required first. A required field always renders; an optional one may be empty,\n * and an entry titled by an empty field has no title. `authors` with an optional\n * `title` (the job title) and a required `name` is titled by `name`.\n */\nfunction byRequired(a: TitleCandidate, b: TitleCandidate): number {\n return Number(b.required) - Number(a.required)\n}\n\n/**\n * Fields a model may legally declare as its `title_field`.\n *\n * The picker's list, and the hint when {@link inferTitleField} declines to\n * guess: \"no field reads as a title\" is more useful with the legal choices\n * spelled out next to it.\n */\nexport function titleFieldOptions(kind: string, fields?: Record<string, unknown>): string[] {\n if (kind === 'dictionary') return [DICTIONARY_TITLE_FIELD]\n const top = titleCandidates(fields).map(c => c.field)\n // One level into object fields: a page singleton built from sections has no\n // top-level text, and `hero.heading` is its legal title. Never inferred.\n const nested = Object.entries(fields ?? {}).flatMap(([name, raw]) => {\n const def = raw as { type?: unknown; fields?: Record<string, unknown> } | null\n return def?.type === 'object' ? titleCandidates(def.fields).map(c => `${name}.${c.field}`) : []\n })\n return [...top, ...nested]\n}\n\n/**\n * How strongly a field name reads as a title. Exact matches outrank snake_case\n * token matches, so `name` beats `brand_name`, and `filename` matches nothing —\n * it tokenizes to `[\"filename\"]`, not `[\"file\", \"name\"]`.\n */\nfunction titleNameRank(field: string): number {\n const exact = (TITLE_NAME_HINTS as readonly string[]).indexOf(field)\n if (exact !== -1) return exact\n\n const tokens = field.split('_')\n const token = TITLE_NAME_HINTS.findIndex(hint => tokens.includes(hint))\n return token === -1 ? Number.POSITIVE_INFINITY : TITLE_NAME_HINTS.length + token\n}\n\n/**\n * Pick the field a model should title its entries by.\n *\n * Migration aid only — it exists to backfill models authored before `title_field`\n * was required, and `contentrain validate --fix` is its one caller. New models\n * declare the field; nothing here runs on the write path.\n *\n * Every rung filters by `isTitleFieldType` first. That filter is the whole point:\n * an unfiltered name match hands the title to a field called `name` that happens\n * to be typed `icon`, which is the exact bug this contract replaces.\n *\n * The rungs, in order — the same chain Studio's `resolveTitleFieldId` walks, with\n * requiredness as the tiebreak on each:\n *\n * 1. a required name-like field (`title`, `name`, `label`, `heading`)\n * 2. an optional name-like field\n * 3. a required prose field (string, email, text, markdown, richtext)\n * 4. any prose field\n *\n * A slug, URL or code field is never reached by inference — see\n * {@link NOT_INFERRED_AS_TITLE} — except as a tiebreak among name-like fields,\n * where the name has already made the case.\n *\n * Returns `null` when nothing qualifies. That is a real answer, not a failure —\n * guessing `image`, `relation` or `whatsapp_url` here would re-create the bug,\n * so the validation error stands and a human picks.\n */\nexport function inferTitleField(kind: string, fields?: Record<string, unknown>): TitleFieldPick | null {\n // A dictionary has no fields to point at — its key is the title.\n if (kind === 'dictionary') return { field: DICTIONARY_TITLE_FIELD, rule: 'dictionary' }\n\n const candidates = titleCandidates(fields)\n if (candidates.length === 0) return null\n\n const named = candidates.filter(c => Number.isFinite(titleNameRank(c.field)))\n if (named.length > 0) {\n const best = named.toSorted((a, b) =>\n byRequired(a, b)\n || titleNameRank(a.field) - titleNameRank(b.field)\n || byTypeThenName(a, b),\n )[0]!\n return { field: best.field, rule: 'name-match' }\n }\n\n const prose = candidates.filter(c => !NOT_INFERRED_AS_TITLE.has(c.type))\n const required = prose.filter(c => c.required)\n if (required.length > 0) {\n return { field: required.toSorted(byTypeThenName)[0]!.field, rule: 'required-displayable' }\n }\n if (prose.length > 0) {\n return { field: prose.toSorted(byTypeThenName)[0]!.field, rule: 'displayable' }\n }\n\n // Only slug/url/code fields are left. Each is a legal title_field, but naming\n // one is the author's decision — the caller reports the options instead.\n return null\n}\n\n/**\n * The `title_field` rule table.\n *\n * Extracted so `validateModelDefinition` (write path) and the project validator\n * (read path) report the same wording from one place, rather than one of them\n * sniffing the other's strings.\n *\n * Chained so a model gets one title_field error, not a cascade of five.\n */\nexport function titleFieldIssues(\n input: { kind: string; title_field?: unknown; fields?: Record<string, unknown> },\n): ModelDefinitionIssues {\n const errors: string[] = []\n const warnings: string[] = []\n const titleField = input.title_field\n\n if (titleField === undefined || titleField === null || titleField === '') {\n errors.push('Missing \"title_field\". Every model must name the field shown as its title. Dictionary models use \"key\".')\n } else if (typeof titleField !== 'string') {\n errors.push(`Invalid \"title_field\": must be a string, got ${typeof titleField}.`)\n } else if (input.kind === 'dictionary') {\n if (titleField !== DICTIONARY_TITLE_FIELD) {\n errors.push(`Dictionary models must use title_field: \"${DICTIONARY_TITLE_FIELD}\". Dictionaries have no fields — the key is the title. Got \"${titleField}\".`)\n }\n } else if (!input.fields || Object.keys(input.fields).length === 0) {\n errors.push(`Invalid \"title_field\": \"${titleField}\" cannot resolve — the model declares no fields.`)\n } else {\n // A dotted path (`hero.heading`) reaches one level into an object field — a\n // page singleton built from sections is titled by a section's heading.\n const target = titleFieldTarget(input.fields as Record<string, FieldDef>, titleField)\n if (target.kind === 'too-deep') {\n errors.push(`Invalid \"title_field\": \"${titleField}\" reaches more than one level deep. A title is a field, or a field of an object field (\"hero.heading\").`)\n } else if (target.kind === 'not-object') {\n errors.push(`Invalid \"title_field\": \"${titleField}\" goes through \"${target.at}\", which has type \"${target.type}\" — a dotted title reaches into an object field only.`)\n } else if (target.kind === 'missing') {\n // A non-dictionary model may legitimately own a field named \"key\" — the\n // sentinel only collides where there are no fields at all.\n errors.push(\n `Invalid \"title_field\": field \"${titleField}\" is not defined in fields.`\n + (titleField === DICTIONARY_TITLE_FIELD ? ` \"${DICTIONARY_TITLE_FIELD}\" is reserved for dictionary models.` : ''),\n )\n } else {\n const { def, parent } = target\n const type: unknown = def.type\n if (typeof type === 'string' && !isTitleFieldType(type as FieldType)) {\n errors.push(`Invalid \"title_field\": field \"${titleField}\" has type \"${type}\" — a title must be one of: ${TITLE_FIELD_TYPES.join(', ')}.`)\n } else if (def.required !== true || (parent && parent.required !== true)) {\n warnings.push(`\"title_field\" points at optional field \"${titleField}\" — entries may render with an empty title. Consider required: true${parent ? ' on the object and its field' : ''}.`)\n }\n // A non-string `type` falls through: the per-field loop already reports it,\n // and repeating it here would double-count one mistake.\n }\n }\n\n return { errors, warnings }\n}\n\n/**\n * Validate a model definition before writing.\n * Used by both the model_save tool and normalize extract.\n */\nexport function validateModelDefinition(\n // `title_field` is `unknown`, not `string?`: a model read back off disk is an\n // unvalidated cast, so the runtime check has to see a value the type system\n // already believes is a string.\n input: { id: string; kind: string; title_field?: unknown; fields?: Record<string, unknown> },\n opts: ModelDefinitionOptions = {},\n): ModelDefinitionIssues {\n const errors: string[] = []\n const warnings: string[] = []\n\n // ID format: kebab-case\n if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(input.id)) {\n errors.push(`Invalid model ID \"${input.id}\": must be kebab-case`)\n }\n\n // Dictionary models cannot have fields\n if (input.kind === 'dictionary' && input.fields && Object.keys(input.fields).length > 0) {\n errors.push('Dictionary models cannot have fields. Dictionaries store flat key-value pairs.')\n }\n\n // Reported above the per-field loop: a broken title_field explains the model,\n // the field errors only explain one field.\n const titleIssues = titleFieldIssues(input)\n errors.push(...titleIssues.errors)\n warnings.push(...titleIssues.warnings)\n\n if (input.fields) {\n for (const [fieldName, fieldDef] of Object.entries(input.fields)) {\n checkFieldName(fieldName, opts, errors, warnings)\n checkFieldDef(fieldDef, fieldName, input.kind, errors, warnings, 0, opts)\n }\n }\n\n return { errors, warnings }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,eACd,OACQ;AACR,KAAI,MAAM,aAAc,QAAO,MAAM;AACrC,QAAO,wBAAwB,MAAM,OA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kB,CAClE,QAAO,KAAK,iCAAiC,WAAW,cAAc,KAAK,8BAA8B,kBAAkB,KAAK,KAAK,CAAC,GAAG;YAChI,IAAI,aAAa,QAAS,UAAU,OAAO,aAAa,KACjE,UAAS,KAAK,2CAA2C,WAAW,qEAAqE,SAAS,iCAAiC,GAAG,GAAG;;;AAO/L,QAAO;EAAE;EAAQ;EAAU;;;;;;AAO7B,SAAgB,wBAId,OACA,OAA+B,EAAE,EACV;CACvB,MAAM,SAAmB,EAAE;CAC3B,MAAM,WAAqB,EAAE;AAG7B,KAAI,CAAC,6BAA6B,KAAK,MAAM,GAAG,CAC9C,QAAO,KAAK,qBAAqB,MAAM,GAAG,uBAAuB;AAInE,KAAI,MAAM,SAAS,gBAAgB,MAAM,UAAU,OAAO,KAAK,MAAM,OAAO,CAAC,SAAS,EACpF,QAAO,KAAK,iFAAiF;CAK/F,MAAM,cAAc,iBAAiB,MAAM;AAC3C,QAAO,KAAK,GAAG,YAAY,OAAO;AAClC,UAAS,KAAK,GAAG,YAAY,SAAS;AAEtC,KAAI,MAAM,OACR,MAAK,MAAM,CAAC,WAAW,aAAa,OAAO,QAAQ,MAAM,OAAO,EAAE;AAChE,iBAAe,WAAW,MAAM,QAAQ,SAAS;AACjD,gBAAc,UAAU,WAAW,MAAM,MAAM,QAAQ,UAAU,GAAG,KAAK;;AAI7E,QAAO;EAAE;EAAQ;EAAU"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as serializeMarkdownFrontmatter$1, i as parseMarkdownFrontmatter$1, o as canonicalStringify$1 } from "./context-
|
|
2
|
-
import { M as documentFilePath, N as metaFilePath, j as contentFilePath } from "./model-manager-
|
|
1
|
+
import { a as serializeMarkdownFrontmatter$1, i as parseMarkdownFrontmatter$1, o as canonicalStringify$1 } from "./context-Cp8b8Nxm.mjs";
|
|
2
|
+
import { M as documentFilePath, N as metaFilePath, j as contentFilePath } from "./model-manager-BYF2z7qC.mjs";
|
|
3
3
|
import { r as mergeEntryMeta } from "./meta-manager-CSpKtjnP.mjs";
|
|
4
4
|
import { LOCALE_PATTERN, MODEL_FIELD_ORDER, SLUG_PATTERN, canonicalStringify, generateEntryId, rewriteEntryMedia, rewriteMarkdownMedia, validateEntryId, validateLocale, validateSlug } from "@contentrain/types";
|
|
5
5
|
//#region src/core/ops/content-delete.ts
|
|
@@ -618,4 +618,4 @@ async function planVocabularyDelete(reader, input) {
|
|
|
618
618
|
//#endregion
|
|
619
619
|
export { planModelDelete as a, planModelSave as i, planVocabularySave as n, planContentSave as o, bindRef as r, planContentDelete as s, planVocabularyDelete as t };
|
|
620
620
|
|
|
621
|
-
//# sourceMappingURL=ops-
|
|
621
|
+
//# sourceMappingURL=ops-CQ_IIedh.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ops-DxhCCs_Z.mjs","names":["canonicalStringify","parseMarkdownFrontmatter","serializeMarkdownFrontmatter","canonicalStringify","canonicalStringify"],"sources":["../src/core/ops/content-delete.ts","../src/core/ops/content-save.ts","../src/core/ops/model-delete.ts","../src/core/ops/model-save.ts","../src/core/bind-ref.ts","../src/core/ops/vocabulary-save.ts"],"sourcesContent":["import type { EntryMeta, ModelDefinition } from '@contentrain/types'\nimport { validateSlug } from '@contentrain/types'\nimport type { FileChange, RepoReader } from '../contracts/index.js'\nimport { canonicalStringify } from '../serialization/index.js'\nimport { contentFilePath, documentFilePath, metaFilePath } from './paths.js'\nimport type { OpPlan } from './types.js'\n\nexport interface ContentDeleteInput {\n model: ModelDefinition\n id?: string\n slug?: string\n locale?: string\n keys?: string[]\n /**\n * `config.locales.default` — where a non-i18n model's single meta record\n * lives. Required to resolve meta paths; see `metaFilePath`.\n */\n defaultLocale: string\n}\n\nexport type ContentDeletePlan = OpPlan<string[]>\n\nfunction contentDir(model: Pick<ModelDefinition, 'domain' | 'id' | 'content_path'>): string {\n return model.content_path ?? `.contentrain/content/${model.domain}/${model.id}`\n}\n\nasync function tryReadJson<T>(reader: RepoReader, path: string): Promise<T | null> {\n try {\n return JSON.parse(await reader.readFile(path)) as T\n } catch {\n return null\n }\n}\n\nasync function discoverCollectionLocales(\n reader: RepoReader,\n model: ModelDefinition,\n): Promise<string[]> {\n const dir = contentDir(model)\n const files = await reader.listDirectory(dir)\n const strategy = model.locale_strategy ?? 'file'\n if (strategy === 'directory') {\n return files\n }\n return files\n .filter(f => f.endsWith('.json'))\n .map(f => f.replace('.json', '').replace(`${model.id}.`, ''))\n}\n\n/**\n * Build the FileChange[] required to delete content. Pure — touches no disk.\n *\n * Semantics preserved from legacy `deleteContent`:\n * - Collection: remove the entry ID from each locale's content file and its\n * meta file. Meta file is deleted outright if the removal empties it.\n * - Singleton: delete the locale's content + meta file (locale-scoped when\n * i18n, non-i18n removes whatever meta lives under `.contentrain/meta/{id}/`).\n * - Dictionary: two modes — key-scoped removal updates the file in place,\n * or locale-scoped removes the content + meta pair.\n * - Document: strategy-aware delete (file/suffix/directory/none), plus\n * meta removal under `.contentrain/meta/{id}/{slug}/`.\n */\nexport async function planContentDelete(\n reader: RepoReader,\n input: ContentDeleteInput,\n): Promise<ContentDeletePlan> {\n const { model } = input\n\n // A non-i18n model stores content locale-agnostically in data.json and keeps\n // exactly one meta record, pinned to the default locale. A locale-scoped\n // delete is therefore meaningless — and actively destructive: the locale\n // silently maps onto data.json and the default-locale meta, so passing a\n // non-default locale deletes the shared content and the wrong meta while the\n // named locale's stray meta is never touched. Reject it; stray per-locale\n // meta is cleaned up by `contentrain_validate fix:true`.\n if (!model.i18n && input.locale) {\n throw new Error(\n `Model \"${model.id}\" has i18n disabled — its content is locale-agnostic (stored in data.json), `\n + 'so a locale-scoped delete is invalid. Omit \"locale\" to delete the entry, '\n + 'or run contentrain_validate fix:true to remove stray per-locale meta files.',\n )\n }\n\n const changes: FileChange[] = []\n const removed: string[] = []\n\n switch (model.kind) {\n case 'collection': {\n if (!input.id) throw new Error('Collection delete requires an entry ID')\n\n const locales = input.locale\n ? [input.locale]\n : await discoverCollectionLocales(reader, model)\n\n for (const loc of locales) {\n const cPath = contentFilePath(model, loc)\n const data = await tryReadJson<Record<string, unknown>>(reader, cPath)\n if (!data || !(input.id in data)) continue\n delete data[input.id]\n const sorted: Record<string, unknown> = {}\n for (const k of Object.keys(data).toSorted()) sorted[k] = data[k]\n changes.push({ path: cPath, content: canonicalStringify(sorted) })\n removed.push(`content/${model.domain}/${model.id}/${loc}.json#${input.id}`)\n }\n\n for (const loc of locales) {\n // For a non-i18n model `loc` is the pseudo-locale \"data\" (discovered from\n // data.json); metaFilePath maps it onto the default locale regardless.\n const mPath = metaFilePath(model, loc, input.defaultLocale)\n const meta = await tryReadJson<Record<string, EntryMeta>>(reader, mPath)\n if (!meta || !(input.id in meta)) continue\n delete meta[input.id]\n if (Object.keys(meta).length > 0) {\n changes.push({ path: mPath, content: canonicalStringify(meta) })\n } else {\n changes.push({ path: mPath, content: null })\n }\n }\n break\n }\n\n case 'singleton': {\n if (model.i18n && !input.locale) {\n throw new Error('Singleton delete requires a locale when i18n is enabled')\n }\n const locale = input.locale ?? 'data'\n const cPath = contentFilePath(model, locale)\n changes.push({ path: cPath, content: null })\n removed.push(model.i18n\n ? `content/${model.domain}/${model.id}/${locale}.json`\n : `content/${model.domain}/${model.id}/data.json`)\n\n if (model.i18n) {\n changes.push({ path: metaFilePath(model, locale, input.defaultLocale), content: null })\n } else {\n // Removing data.json leaves a non-i18n model with no content at all, so\n // every meta file under it goes — including strays left by older writes.\n await pushAllMetaForModel(reader, model.id, changes)\n }\n break\n }\n\n case 'dictionary': {\n if (model.i18n && !input.locale) {\n throw new Error('Dictionary delete requires a locale when i18n is enabled')\n }\n const locale = input.locale ?? 'data'\n const cPath = contentFilePath(model, locale)\n\n if (input.keys?.length) {\n const existing = (await tryReadJson<Record<string, string>>(reader, cPath)) ?? {}\n const notFound: string[] = []\n for (const key of input.keys) {\n if (key in existing) delete existing[key]\n else notFound.push(key)\n }\n if (notFound.length > 0) {\n throw new Error(`Dictionary \"${model.id}\" (${locale}): keys not found — [${notFound.join(', ')}]`)\n }\n changes.push({ path: cPath, content: canonicalStringify(existing) })\n removed.push(...input.keys.map(k => `${model.id}/${locale}:${k}`))\n } else {\n changes.push({ path: cPath, content: null })\n removed.push(model.i18n\n ? `content/${model.domain}/${model.id}/${locale}.json`\n : `content/${model.domain}/${model.id}/data.json`)\n if (model.i18n) {\n changes.push({ path: metaFilePath(model, locale, input.defaultLocale), content: null })\n } else {\n await pushAllMetaForModel(reader, model.id, changes)\n }\n }\n break\n }\n\n case 'document': {\n if (!input.slug) throw new Error('Document delete requires a slug')\n const slugErr = validateSlug(input.slug)\n if (slugErr) throw new Error(slugErr)\n\n const dir = contentDir(model)\n const strategy = model.locale_strategy ?? 'file'\n\n if (!model.i18n) {\n changes.push({ path: `${dir}/${input.slug}.md`, content: null })\n } else if (strategy === 'file') {\n const slugDir = `${dir}/${input.slug}`\n const files = await reader.listDirectory(slugDir)\n for (const f of files) changes.push({ path: `${slugDir}/${f}`, content: null })\n } else if (input.locale) {\n changes.push({ path: documentFilePath(model, input.locale, input.slug), content: null })\n } else if (strategy === 'suffix') {\n const files = await reader.listDirectory(dir)\n for (const f of files) {\n if (f.startsWith(`${input.slug}.`) && f.endsWith('.md')) {\n changes.push({ path: `${dir}/${f}`, content: null })\n }\n }\n } else if (strategy === 'directory') {\n const subdirs = await reader.listDirectory(dir)\n for (const d of subdirs) {\n const filePath = `${dir}/${d}/${input.slug}.md`\n if (await reader.fileExists(filePath)) {\n changes.push({ path: filePath, content: null })\n }\n }\n } else if (strategy === 'none') {\n const files = await reader.listDirectory(dir)\n if (files.includes(`${input.slug}.md`)) {\n changes.push({ path: `${dir}/${input.slug}.md`, content: null })\n }\n }\n\n removed.push(`${model.content_path ?? `content/${model.domain}/${model.id}`}/${input.slug}`)\n\n const metaSlugDir = `.contentrain/meta/${model.id}/${input.slug}`\n if (input.locale) {\n changes.push({ path: `${metaSlugDir}/${input.locale}.json`, content: null })\n } else {\n const metaFiles = await reader.listDirectory(metaSlugDir)\n for (const f of metaFiles) changes.push({ path: `${metaSlugDir}/${f}`, content: null })\n }\n break\n }\n }\n\n changes.sort((a, b) => a.path.localeCompare(b.path))\n return { changes, result: removed, advisories: [] }\n}\n\nasync function pushAllMetaForModel(reader: RepoReader, modelId: string, changes: FileChange[]): Promise<void> {\n const metaDir = `.contentrain/meta/${modelId}`\n const files = await reader.listDirectory(metaDir)\n for (const f of files) changes.push({ path: `${metaDir}/${f}`, content: null })\n}\n","import type { ContentrainConfig, EntryMeta, ModelDefinition, Vocabulary } from '@contentrain/types'\nimport { generateEntryId, rewriteEntryMedia, rewriteMarkdownMedia, validateEntryId, validateLocale, validateSlug } from '@contentrain/types'\nimport type { FileChange, RepoReader } from '../contracts/index.js'\nimport type { ContentEntry } from '../content-manager.js'\nimport { canonicalStringify, parseMarkdownFrontmatter, serializeMarkdownFrontmatter } from '../serialization/index.js'\nimport type { ContentSaveEntryResult, ContentSavePlan } from './types.js'\nimport { contentFilePath, documentFilePath, metaFilePath } from './paths.js'\nimport { mergeEntryMeta } from '../meta-manager.js'\n\n/** Keys named individually in a replacement advisory before it collapses to a count. */\nconst MAX_REPORTED_KEYS = 5\n\ninterface PlanInput {\n model: ModelDefinition\n entries: ContentEntry[]\n config: ContentrainConfig\n vocabulary?: Vocabulary | null\n /**\n * Per-project public media delivery base (`RepoProvider.mediaBaseUrl`). When\n * set (hosted/cloud mode), relative `media/...` references in media fields\n * and markdown bodies are normalized to absolute delivery URLs before the\n * value is committed. Undefined in local mode — paths are kept verbatim.\n */\n mediaBaseUrl?: string\n}\n\n/**\n * Build the FileChange[] required to save a batch of content entries. The\n * plan is deterministic, pure, and does not touch disk — it reads existing\n * state through `reader` and returns changes for a single atomic commit.\n *\n * Grouping: multiple entries targeting the same (model, locale) share a\n * single content file and a single meta file. Reads are cached in-memory\n * so repeated reads of the same path during a plan are one IO.\n */\nexport async function planContentSave(reader: RepoReader, input: PlanInput): Promise<ContentSavePlan> {\n const { model, entries, config, vocabulary, mediaBaseUrl } = input\n const result: ContentSaveEntryResult[] = []\n const advisories: string[] = []\n\n // Hosted/cloud mode: normalize relative `media/...` references to absolute\n // delivery URLs so the committed value renders anywhere with no SDK. A no-op\n // in local mode (no base) or for field-less models (e.g. dictionaries).\n const normalizeMedia = (data: Record<string, unknown>): Record<string, unknown> =>\n mediaBaseUrl && model.fields ? rewriteEntryMedia(data, model.fields, mediaBaseUrl) : data\n\n // In-memory accumulators keyed by content-root-relative path.\n const contentByPath = new Map<string, unknown>()\n const metaByPath = new Map<string, unknown>()\n const markdownChanges = new Map<string, string>()\n\n async function readJsonOrEmpty<T>(path: string): Promise<T> {\n try {\n return JSON.parse(await reader.readFile(path)) as T\n } catch {\n return {} as T\n }\n }\n\n /** Absent file and absent entry both mean \"no prior meta\" — hence undefined, not `{}`. */\n async function readJsonOrUndefined<T>(path: string): Promise<T | undefined> {\n try {\n return JSON.parse(await reader.readFile(path)) as T\n } catch {\n return undefined\n }\n }\n\n /** Prior meta for a whole-file (non-collection) meta path, honouring the accumulator. */\n async function priorMeta(mPath: string): Promise<EntryMeta | undefined> {\n return (metaByPath.get(mPath) as EntryMeta | undefined)\n ?? await readJsonOrUndefined<EntryMeta>(mPath)\n }\n\n const defaultLocale = config.locales.default\n\n for (const entry of entries) {\n const locale = entry.locale ?? defaultLocale\n\n const localeErr = validateLocale(locale, config)\n if (localeErr) throw new Error(localeErr)\n if (entry.id) {\n const err = validateEntryId(entry.id)\n if (err) throw new Error(err)\n }\n if (entry.slug) {\n const err = validateSlug(entry.slug)\n if (err) throw new Error(err)\n }\n\n switch (model.kind) {\n case 'singleton': {\n const cPath = contentFilePath(model, locale)\n const mPath = metaFilePath(model, locale, defaultLocale)\n contentByPath.set(cPath, normalizeMedia(entry.data))\n metaByPath.set(mPath, mergeEntryMeta(await priorMeta(mPath), entry))\n result.push({ action: 'updated', locale })\n break\n }\n\n case 'collection': {\n const isNew = !entry.id\n const id = entry.id ?? generateEntryId()\n const cPath = contentFilePath(model, locale)\n const mPath = metaFilePath(model, locale, defaultLocale)\n\n const existing = (contentByPath.get(cPath) as Record<string, unknown> | undefined)\n ?? await readJsonOrEmpty<Record<string, unknown>>(cPath)\n\n const action: 'created' | 'updated' = isNew || !(id in existing) ? 'created' : 'updated'\n existing[id] = normalizeMedia(entry.data)\n\n const sorted: Record<string, unknown> = {}\n for (const key of Object.keys(existing).toSorted()) {\n sorted[key] = existing[key]\n }\n contentByPath.set(cPath, sorted)\n\n const existingMeta = (metaByPath.get(mPath) as Record<string, EntryMeta> | undefined)\n ?? await readJsonOrEmpty<Record<string, EntryMeta>>(mPath)\n existingMeta[id] = mergeEntryMeta(existingMeta[id], entry)\n metaByPath.set(mPath, existingMeta)\n\n result.push({ action, id, locale })\n break\n }\n\n case 'dictionary': {\n const cPath = contentFilePath(model, locale)\n const mPath = metaFilePath(model, locale, defaultLocale)\n\n const existing = (contentByPath.get(cPath) as Record<string, string> | undefined)\n ?? await readJsonOrEmpty<Record<string, string>>(cPath)\n\n const newData = entry.data as Record<string, string>\n const entryAdvisories: string[] = []\n\n // Overwriting a key used to be refused outright, which made the most\n // ordinary dictionary operation — correcting a translation — impossible:\n // the workaround was delete, merge, save, merge. Four operations and two\n // branches to fix one string. The refusal also advised \"include all keys\n // in a single save call\", which cannot work, because the check compares\n // values per key rather than counting them.\n //\n // Choosing a translation is a content decision, and MCP does not make\n // those. It reports them — the same way the duplicate-value case two\n // blocks below already does — and the branch diff shows the rest.\n const replaced = Object.keys(newData).filter(\n k => k in existing && existing[k] !== newData[k],\n )\n if (replaced.length > 0) {\n const shown = replaced.slice(0, MAX_REPORTED_KEYS)\n const detail = shown.map(k => `\"${k}\": \"${existing[k]}\" → \"${newData[k]}\"`).join(', ')\n const more = replaced.length > shown.length ? `, and ${replaced.length - shown.length} more` : ''\n entryAdvisories.push(\n `Dictionary \"${model.id}\" (${locale}): replaced ${replaced.length} existing value(s) — ${detail}${more}.`,\n )\n }\n\n const reverseMap = new Map<string, string>()\n for (const [k, v] of Object.entries(existing)) reverseMap.set(v, k)\n for (const [newKey, newValue] of Object.entries(newData)) {\n if (newKey in existing) continue\n const existingKey = reverseMap.get(newValue)\n if (existingKey && existingKey !== newKey) {\n entryAdvisories.push(\n `Value \"${newValue}\" already exists as key \"${existingKey}\". Consider reusing instead of creating \"${newKey}\".`,\n )\n }\n }\n\n if (vocabulary && Object.keys(vocabulary.terms).length > 0) {\n outer:\n for (const [newKey, newValue] of Object.entries(newData)) {\n if (newKey in existing) continue\n for (const translations of Object.values(vocabulary.terms)) {\n if (Object.values(translations).includes(newValue)) {\n entryAdvisories.push(\n `Value \"${newValue}\" matches a vocabulary term. Use the canonical form for consistency.`,\n )\n continue outer\n }\n }\n }\n }\n\n advisories.push(...entryAdvisories)\n\n contentByPath.set(cPath, { ...existing, ...newData })\n metaByPath.set(mPath, mergeEntryMeta(await priorMeta(mPath), entry))\n\n result.push({\n action: 'updated',\n locale,\n ...(entryAdvisories.length > 0 ? { advisories: entryAdvisories } : {}),\n })\n break\n }\n\n case 'document': {\n const entryAdvisories: string[] = []\n const slug = entry.slug ?? (entry.data['slug'] as string | undefined)\n if (!slug) throw new Error('Document entries require a slug')\n const slugErr = validateSlug(slug)\n if (slugErr) throw new Error(slugErr)\n\n const incomingFm = { ...entry.data }\n const bodySent = 'body' in incomingFm\n const incomingBody = (incomingFm['body'] as string | undefined) ?? ''\n delete incomingFm['body']\n if (!incomingFm['slug']) incomingFm['slug'] = slug\n\n const dPath = documentFilePath(model, locale, slug)\n const mPath = metaFilePath(model, locale, defaultLocale, slug)\n\n // Accumulator before disk, as the collection branch does: two entries\n // touching one document in a single call must compose, not race.\n let existingRaw: string | null = markdownChanges.get(dPath) ?? null\n if (existingRaw === null) {\n try { existingRaw = await reader.readFile(dPath) }\n catch { /* not yet */ }\n }\n // Same rule the collection branch uses: anything already present —\n // on disk or produced earlier in this plan — makes this an update.\n const action: 'created' | 'updated' = existingRaw ? 'updated' : 'created'\n\n // Merge with what is on disk, the way collections and singletons above\n // already do. Documents were the only kind that replaced instead of\n // merging, so a save that touched one frontmatter field wrote a file\n // containing only that field — and an entirely empty body. Nothing\n // reported it: the response said `valid: true`, because validation runs\n // over the plan's own output, which was internally consistent and\n // wrong. Under auto-merge that reaches the default branch directly.\n const existing = existingRaw ? parseMarkdownFrontmatter(existingRaw) : null\n const fmData = { ...existing?.frontmatter, ...incomingFm }\n\n // Absent `body` means \"I am not editing the body\" — keep what is there.\n // A `body` that is present, even empty, is an instruction, and is\n // honoured; clearing real content that way is announced rather than\n // silent, because it is indistinguishable from a templating mistake.\n const bodyContent = bodySent ? incomingBody : (existing?.body ?? '')\n if (bodySent && !incomingBody.trim() && existing?.body.trim()) {\n const notice = `Document \"${slug}\" (${locale}): body cleared — an explicit empty \"body\" replaced ${existing.body.length} characters. Omit \"body\" to leave it untouched.`\n entryAdvisories.push(notice)\n advisories.push(notice)\n }\n\n // Frontmatter media fields go through the schema-guided rewrite; the\n // markdown body has its `media/...` image/link targets rewritten too.\n const normalizedBody = mediaBaseUrl ? rewriteMarkdownMedia(bodyContent, mediaBaseUrl) : bodyContent\n markdownChanges.set(dPath, serializeMarkdownFrontmatter(normalizeMedia(fmData), normalizedBody))\n metaByPath.set(mPath, mergeEntryMeta(await priorMeta(mPath), entry))\n\n result.push({\n action,\n slug,\n locale,\n ...(entryAdvisories.length > 0 ? { advisories: entryAdvisories } : {}),\n })\n break\n }\n }\n }\n\n const changes: FileChange[] = []\n for (const [path, data] of contentByPath) {\n changes.push({ path, content: canonicalStringify(data) })\n }\n for (const [path, meta] of metaByPath) {\n changes.push({ path, content: canonicalStringify(meta) })\n }\n for (const [path, content] of markdownChanges) {\n changes.push({ path, content })\n }\n changes.sort((a, b) => a.path.localeCompare(b.path))\n\n return { changes, result, advisories }\n}\n","import type { ModelDefinition } from '@contentrain/types'\nimport type { FileChange, RepoReader } from '../contracts/index.js'\nimport type { OpPlan } from './types.js'\n\nexport interface ModelDeleteInput {\n model: ModelDefinition\n}\n\nexport type ModelDeletePlan = OpPlan<string[]>\n\n/**\n * Build the FileChange[] required to delete a model and its associated\n * content/meta files.\n *\n * The schema is at most two directory levels deep (e.g. document meta at\n * `.contentrain/meta/{id}/{slug}/{locale}.json`). The helper below walks\n * that much, which is enough for every model kind + locale strategy and\n * keeps us free of a general-purpose recursive lister for now.\n *\n * `result` is the legacy three-entry summary:\n * - `models/{id}.json`\n * - `content/{domain}/{id}/` (only if any content files existed)\n * - `meta/{id}/` (only if any meta files existed)\n */\nexport async function planModelDelete(reader: RepoReader, input: ModelDeleteInput): Promise<ModelDeletePlan> {\n const { model } = input\n const changes: FileChange[] = []\n const removed: string[] = []\n\n changes.push({ path: `.contentrain/models/${model.id}.json`, content: null })\n removed.push(`models/${model.id}.json`)\n\n const contentDir = model.content_path ?? `.contentrain/content/${model.domain}/${model.id}`\n const contentFiles = await enumerateTwoLevels(reader, contentDir)\n for (const path of contentFiles) {\n changes.push({ path, content: null })\n }\n if (contentFiles.length > 0) {\n removed.push(model.content_path ?? `content/${model.domain}/${model.id}/`)\n }\n\n const metaDir = `.contentrain/meta/${model.id}`\n const metaFiles = await enumerateTwoLevels(reader, metaDir)\n for (const path of metaFiles) {\n changes.push({ path, content: null })\n }\n if (metaFiles.length > 0) {\n removed.push(`meta/${model.id}/`)\n }\n\n changes.sort((a, b) => a.path.localeCompare(b.path))\n return { changes, result: removed, advisories: [] }\n}\n\n/** List files up to two directory levels deep. Filters to `.json` and `.md`. */\nasync function enumerateTwoLevels(reader: RepoReader, dir: string): Promise<string[]> {\n const results: string[] = []\n const entries = await reader.listDirectory(dir)\n for (const entry of entries) {\n const path = `${dir}/${entry}`\n if (entry.endsWith('.json') || entry.endsWith('.md')) {\n results.push(path)\n continue\n }\n const subEntries = await reader.listDirectory(path)\n for (const sub of subEntries) {\n if (sub.endsWith('.json') || sub.endsWith('.md')) {\n results.push(`${path}/${sub}`)\n }\n }\n }\n return results\n}\n","import type { ModelDefinition } from '@contentrain/types'\nimport { MODEL_FIELD_ORDER } from '@contentrain/types'\nimport type { FileChange, RepoReader } from '../contracts/index.js'\nimport { canonicalStringify } from '../serialization/index.js'\nimport type { OpPlan } from './types.js'\n\nexport interface ModelSaveInput {\n model: ModelDefinition\n}\n\nexport interface ModelSaveResult {\n action: 'created' | 'updated'\n id: string\n}\n\nexport type ModelSavePlan = OpPlan<ModelSaveResult>\n\n/**\n * Build the FileChange[] required to create or update a model definition.\n *\n * The only disk change is the model JSON file itself. Content and meta\n * directories are created on-demand when their first write lands — git does\n * not track empty directories, and MCP's write helpers `mkdir -p` before\n * every file write, so there is no operational reason to emit an empty-dir\n * ensure step here.\n */\nexport async function planModelSave(reader: RepoReader, input: ModelSaveInput): Promise<ModelSavePlan> {\n const { model } = input\n const modelPath = `.contentrain/models/${model.id}.json`\n\n let action: 'created' | 'updated' = 'created'\n try {\n await reader.readFile(modelPath)\n action = 'updated'\n } catch { /* not yet exists */ }\n\n const changes: FileChange[] = [\n { path: modelPath, content: canonicalStringify(model, MODEL_FIELD_ORDER) },\n ]\n\n return {\n changes,\n result: { action, id: model.id },\n advisories: [],\n }\n}\n","import type { RepoReader } from './contracts/index.js'\n\n/**\n * Pin a `RepoReader` to one ref. The reconcile planner takes three of these\n * (merge-base / contentrain / base branch) and stays entirely ignorant of\n * refs — executors and tools decide what to bind, the planner just reads.\n *\n * For readers that honour the per-call `ref?` parameter (GitHub, GitLab)\n * this is the whole story; a reader that ignores it (LocalReader reads the\n * working tree) needs a ref-aware implementation instead — see\n * `git/ref-reader.ts`.\n */\nexport function bindRef(reader: RepoReader, ref: string): RepoReader {\n return {\n readFile: path => reader.readFile(path, ref),\n listDirectory: path => reader.listDirectory(path, ref),\n fileExists: path => reader.fileExists(path, ref),\n }\n}\n","import type { Vocabulary } from '@contentrain/types'\nimport { canonicalStringify, LOCALE_PATTERN, SLUG_PATTERN } from '@contentrain/types'\nimport type { FileChange, RepoReader } from '../contracts/index.js'\nimport type { OpPlan } from './types.js'\n\nconst VOCABULARY_PATH = '.contentrain/vocabulary.json'\n\n/** Terms named individually in an advisory before it collapses to a count. */\nconst MAX_REPORTED_TERMS = 5\n\nexport interface VocabularySaveInput {\n /**\n * Terms to add or update, keyed by term slug, each holding its translations\n * keyed by locale. Merged with what is already there — a term absent from\n * this map is untouched.\n */\n terms: Record<string, Record<string, string>>\n}\n\nexport interface VocabularyDeleteInput {\n /** Term slugs to remove. A slug that is not present is reported, not an error. */\n terms: string[]\n}\n\nexport interface VocabularySaveResult {\n added: string[]\n updated: string[]\n total: number\n}\n\nexport interface VocabularyDeleteResult {\n deleted: string[]\n missing: string[]\n total: number\n}\n\nexport type VocabularySavePlan = OpPlan<VocabularySaveResult>\nexport type VocabularyDeletePlan = OpPlan<VocabularyDeleteResult>\n\nasync function readVocabulary(reader: RepoReader): Promise<Vocabulary> {\n try {\n const parsed = JSON.parse(await reader.readFile(VOCABULARY_PATH)) as Partial<Vocabulary>\n return { version: parsed.version ?? 1, terms: parsed.terms ?? {} }\n } catch {\n return { version: 1, terms: {} }\n }\n}\n\n/**\n * Validate the shape callers get wrong.\n *\n * The nesting is `term -> locale -> translation`, and it reads identically the\n * other way round, so a caller that groups by locale at the top level produces\n * a structurally valid file that matches nothing. That is not a typo anyone\n * notices — the vocabulary simply stops having any effect. Checking that outer\n * keys are term slugs and inner keys are locale codes catches the inversion at\n * the point of writing.\n */\nfunction validateTerms(terms: Record<string, Record<string, string>>): string[] {\n const errors: string[] = []\n\n for (const [term, translations] of Object.entries(terms)) {\n if (!SLUG_PATTERN.test(term)) {\n errors.push(`Term \"${term}\": must be kebab-case. The outer key is the term, not a locale.`)\n }\n if (typeof translations !== 'object' || translations === null || Array.isArray(translations)) {\n errors.push(`Term \"${term}\": expected an object of locale → translation.`)\n continue\n }\n if (Object.keys(translations).length === 0) {\n errors.push(`Term \"${term}\": has no translations.`)\n }\n for (const [locale, value] of Object.entries(translations)) {\n if (!LOCALE_PATTERN.test(locale)) {\n errors.push(\n `Term \"${term}\": \"${locale}\" is not a locale code. Terms nest as { \"${term}\": { \"en\": \"…\" } } — one term, its translations inside.`,\n )\n }\n if (typeof value !== 'string') {\n errors.push(`Term \"${term}\" (${locale}): translation must be a string, got ${typeof value}.`)\n }\n }\n }\n\n return errors\n}\n\n/**\n * Build the FileChange[] to add or update vocabulary terms.\n *\n * Vocabulary had no write tool at all: the rules forbid editing `.contentrain/`\n * by hand, and there was no supported way to obey that. This closes it through\n * the same plan/apply path every other write uses, so it lands on a `cr/*`\n * branch and follows the project's workflow like anything else.\n */\nexport async function planVocabularySave(\n reader: RepoReader,\n input: VocabularySaveInput,\n): Promise<VocabularySavePlan> {\n const errors = validateTerms(input.terms)\n if (errors.length > 0) {\n throw new Error(`Vocabulary validation failed:\\n- ${errors.join('\\n- ')}`)\n }\n\n const existing = await readVocabulary(reader)\n const added: string[] = []\n const updated: string[] = []\n const advisories: string[] = []\n\n const merged: Record<string, Record<string, string>> = { ...existing.terms }\n for (const [term, translations] of Object.entries(input.terms)) {\n const prior = existing.terms[term]\n if (!prior) {\n added.push(term)\n merged[term] = { ...translations }\n continue\n }\n updated.push(term)\n // Merge per locale: adding a Turkish translation must not drop the English.\n merged[term] = { ...prior, ...translations }\n\n const changed = Object.entries(translations).filter(([l, v]) => l in prior && prior[l] !== v)\n if (changed.length > 0) {\n const shown = changed.slice(0, MAX_REPORTED_TERMS)\n const detail = shown.map(([l, v]) => `${l}: \"${prior[l]}\" → \"${v}\"`).join(', ')\n const more = changed.length > shown.length ? `, and ${changed.length - shown.length} more` : ''\n advisories.push(`Term \"${term}\": replaced ${changed.length} translation(s) — ${detail}${more}.`)\n }\n }\n\n // A canonical term whose value duplicates another term's is the whole thing\n // this file exists to prevent, so it is worth saying out loud.\n const byValue = new Map<string, string>()\n for (const [term, translations] of Object.entries(merged)) {\n for (const value of Object.values(translations)) {\n const owner = byValue.get(value)\n if (owner && owner !== term) {\n advisories.push(`Terms \"${owner}\" and \"${term}\" share the translation \"${value}\".`)\n } else {\n byValue.set(value, term)\n }\n }\n }\n\n const next: Vocabulary = { version: existing.version, terms: merged }\n const changes: FileChange[] = [\n { path: VOCABULARY_PATH, content: canonicalStringify(next) },\n ]\n\n return {\n changes,\n result: { added, updated, total: Object.keys(merged).length },\n advisories,\n }\n}\n\n/** Build the FileChange[] to remove vocabulary terms. */\nexport async function planVocabularyDelete(\n reader: RepoReader,\n input: VocabularyDeleteInput,\n): Promise<VocabularyDeletePlan> {\n const existing = await readVocabulary(reader)\n\n const deleted: string[] = []\n const missing: string[] = []\n const remaining = { ...existing.terms }\n\n for (const term of input.terms) {\n if (term in remaining) {\n delete remaining[term]\n deleted.push(term)\n } else {\n missing.push(term)\n }\n }\n\n const advisories = missing.length > 0\n ? [`Not in the vocabulary, so nothing to delete: ${missing.join(', ')}.`]\n : []\n\n // Nothing changed — emit no FileChange, so the caller can skip the commit\n // rather than create an empty branch.\n const changes: FileChange[] = deleted.length > 0\n ? [{ path: VOCABULARY_PATH, content: canonicalStringify({ version: existing.version, terms: remaining } satisfies Vocabulary) }]\n : []\n\n return {\n changes,\n result: { deleted, missing, total: Object.keys(remaining).length },\n advisories,\n }\n}\n"],"mappings":";;;;;AAsBA,SAAS,WAAW,OAAwE;AAC1F,QAAO,MAAM,gBAAgB,wBAAwB,MAAM,OAAO,GAAG,MAAM;;AAG7E,eAAe,YAAe,QAAoB,MAAiC;AACjF,KAAI;AACF,SAAO,KAAK,MAAM,MAAM,OAAO,SAAS,KAAK,CAAC;SACxC;AACN,SAAO;;;AAIX,eAAe,0BACb,QACA,OACmB;CACnB,MAAM,MAAM,WAAW,MAAM;CAC7B,MAAM,QAAQ,MAAM,OAAO,cAAc,IAAI;AAE7C,MADiB,MAAM,mBAAmB,YACzB,YACf,QAAO;AAET,QAAO,MACJ,QAAO,MAAK,EAAE,SAAS,QAAQ,CAAC,CAChC,KAAI,MAAK,EAAE,QAAQ,SAAS,GAAG,CAAC,QAAQ,GAAG,MAAM,GAAG,IAAI,GAAG,CAAC;;;;;;;;;;;;;;;AAgBjE,eAAsB,kBACpB,QACA,OAC4B;CAC5B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EACL,SAL4B,QAAQ,SAAS,IAC3C,CAAC;GAAE,MAAM;GAAiB,SAAS,mBAAmB;IAAE,SAAS,SAAS;IAAS,OAAO;IAAW,CAAsB;GAAE,CAAC,GAC9H,EAAE;EAIJ,QAAQ;GAAE;GAAS;GAAS,OAAO,OAAO,KAAK,UAAU,CAAC;GAAQ;EAClE;EACD"}
|
|
1
|
+
{"version":3,"file":"ops-CQ_IIedh.mjs","names":["canonicalStringify","parseMarkdownFrontmatter","serializeMarkdownFrontmatter","canonicalStringify","canonicalStringify"],"sources":["../src/core/ops/content-delete.ts","../src/core/ops/content-save.ts","../src/core/ops/model-delete.ts","../src/core/ops/model-save.ts","../src/core/bind-ref.ts","../src/core/ops/vocabulary-save.ts"],"sourcesContent":["import type { EntryMeta, ModelDefinition } from '@contentrain/types'\nimport { validateSlug } from '@contentrain/types'\nimport type { FileChange, RepoReader } from '../contracts/index.js'\nimport { canonicalStringify } from '../serialization/index.js'\nimport { contentFilePath, documentFilePath, metaFilePath } from './paths.js'\nimport type { OpPlan } from './types.js'\n\nexport interface ContentDeleteInput {\n model: ModelDefinition\n id?: string\n slug?: string\n locale?: string\n keys?: string[]\n /**\n * `config.locales.default` — where a non-i18n model's single meta record\n * lives. Required to resolve meta paths; see `metaFilePath`.\n */\n defaultLocale: string\n}\n\nexport type ContentDeletePlan = OpPlan<string[]>\n\nfunction contentDir(model: Pick<ModelDefinition, 'domain' | 'id' | 'content_path'>): string {\n return model.content_path ?? `.contentrain/content/${model.domain}/${model.id}`\n}\n\nasync function tryReadJson<T>(reader: RepoReader, path: string): Promise<T | null> {\n try {\n return JSON.parse(await reader.readFile(path)) as T\n } catch {\n return null\n }\n}\n\nasync function discoverCollectionLocales(\n reader: RepoReader,\n model: ModelDefinition,\n): Promise<string[]> {\n const dir = contentDir(model)\n const files = await reader.listDirectory(dir)\n const strategy = model.locale_strategy ?? 'file'\n if (strategy === 'directory') {\n return files\n }\n return files\n .filter(f => f.endsWith('.json'))\n .map(f => f.replace('.json', '').replace(`${model.id}.`, ''))\n}\n\n/**\n * Build the FileChange[] required to delete content. Pure — touches no disk.\n *\n * Semantics preserved from legacy `deleteContent`:\n * - Collection: remove the entry ID from each locale's content file and its\n * meta file. Meta file is deleted outright if the removal empties it.\n * - Singleton: delete the locale's content + meta file (locale-scoped when\n * i18n, non-i18n removes whatever meta lives under `.contentrain/meta/{id}/`).\n * - Dictionary: two modes — key-scoped removal updates the file in place,\n * or locale-scoped removes the content + meta pair.\n * - Document: strategy-aware delete (file/suffix/directory/none), plus\n * meta removal under `.contentrain/meta/{id}/{slug}/`.\n */\nexport async function planContentDelete(\n reader: RepoReader,\n input: ContentDeleteInput,\n): Promise<ContentDeletePlan> {\n const { model } = input\n\n // A non-i18n model stores content locale-agnostically in data.json and keeps\n // exactly one meta record, pinned to the default locale. A locale-scoped\n // delete is therefore meaningless — and actively destructive: the locale\n // silently maps onto data.json and the default-locale meta, so passing a\n // non-default locale deletes the shared content and the wrong meta while the\n // named locale's stray meta is never touched. Reject it; stray per-locale\n // meta is cleaned up by `contentrain_validate fix:true`.\n if (!model.i18n && input.locale) {\n throw new Error(\n `Model \"${model.id}\" has i18n disabled — its content is locale-agnostic (stored in data.json), `\n + 'so a locale-scoped delete is invalid. Omit \"locale\" to delete the entry, '\n + 'or run contentrain_validate fix:true to remove stray per-locale meta files.',\n )\n }\n\n const changes: FileChange[] = []\n const removed: string[] = []\n\n switch (model.kind) {\n case 'collection': {\n if (!input.id) throw new Error('Collection delete requires an entry ID')\n\n const locales = input.locale\n ? [input.locale]\n : await discoverCollectionLocales(reader, model)\n\n for (const loc of locales) {\n const cPath = contentFilePath(model, loc)\n const data = await tryReadJson<Record<string, unknown>>(reader, cPath)\n if (!data || !(input.id in data)) continue\n delete data[input.id]\n const sorted: Record<string, unknown> = {}\n for (const k of Object.keys(data).toSorted()) sorted[k] = data[k]\n changes.push({ path: cPath, content: canonicalStringify(sorted) })\n removed.push(`content/${model.domain}/${model.id}/${loc}.json#${input.id}`)\n }\n\n for (const loc of locales) {\n // For a non-i18n model `loc` is the pseudo-locale \"data\" (discovered from\n // data.json); metaFilePath maps it onto the default locale regardless.\n const mPath = metaFilePath(model, loc, input.defaultLocale)\n const meta = await tryReadJson<Record<string, EntryMeta>>(reader, mPath)\n if (!meta || !(input.id in meta)) continue\n delete meta[input.id]\n if (Object.keys(meta).length > 0) {\n changes.push({ path: mPath, content: canonicalStringify(meta) })\n } else {\n changes.push({ path: mPath, content: null })\n }\n }\n break\n }\n\n case 'singleton': {\n if (model.i18n && !input.locale) {\n throw new Error('Singleton delete requires a locale when i18n is enabled')\n }\n const locale = input.locale ?? 'data'\n const cPath = contentFilePath(model, locale)\n changes.push({ path: cPath, content: null })\n removed.push(model.i18n\n ? `content/${model.domain}/${model.id}/${locale}.json`\n : `content/${model.domain}/${model.id}/data.json`)\n\n if (model.i18n) {\n changes.push({ path: metaFilePath(model, locale, input.defaultLocale), content: null })\n } else {\n // Removing data.json leaves a non-i18n model with no content at all, so\n // every meta file under it goes — including strays left by older writes.\n await pushAllMetaForModel(reader, model.id, changes)\n }\n break\n }\n\n case 'dictionary': {\n if (model.i18n && !input.locale) {\n throw new Error('Dictionary delete requires a locale when i18n is enabled')\n }\n const locale = input.locale ?? 'data'\n const cPath = contentFilePath(model, locale)\n\n if (input.keys?.length) {\n const existing = (await tryReadJson<Record<string, string>>(reader, cPath)) ?? {}\n const notFound: string[] = []\n for (const key of input.keys) {\n if (key in existing) delete existing[key]\n else notFound.push(key)\n }\n if (notFound.length > 0) {\n throw new Error(`Dictionary \"${model.id}\" (${locale}): keys not found — [${notFound.join(', ')}]`)\n }\n changes.push({ path: cPath, content: canonicalStringify(existing) })\n removed.push(...input.keys.map(k => `${model.id}/${locale}:${k}`))\n } else {\n changes.push({ path: cPath, content: null })\n removed.push(model.i18n\n ? `content/${model.domain}/${model.id}/${locale}.json`\n : `content/${model.domain}/${model.id}/data.json`)\n if (model.i18n) {\n changes.push({ path: metaFilePath(model, locale, input.defaultLocale), content: null })\n } else {\n await pushAllMetaForModel(reader, model.id, changes)\n }\n }\n break\n }\n\n case 'document': {\n if (!input.slug) throw new Error('Document delete requires a slug')\n const slugErr = validateSlug(input.slug)\n if (slugErr) throw new Error(slugErr)\n\n const dir = contentDir(model)\n const strategy = model.locale_strategy ?? 'file'\n\n if (!model.i18n) {\n changes.push({ path: `${dir}/${input.slug}.md`, content: null })\n } else if (strategy === 'file') {\n const slugDir = `${dir}/${input.slug}`\n const files = await reader.listDirectory(slugDir)\n for (const f of files) changes.push({ path: `${slugDir}/${f}`, content: null })\n } else if (input.locale) {\n changes.push({ path: documentFilePath(model, input.locale, input.slug), content: null })\n } else if (strategy === 'suffix') {\n const files = await reader.listDirectory(dir)\n for (const f of files) {\n if (f.startsWith(`${input.slug}.`) && f.endsWith('.md')) {\n changes.push({ path: `${dir}/${f}`, content: null })\n }\n }\n } else if (strategy === 'directory') {\n const subdirs = await reader.listDirectory(dir)\n for (const d of subdirs) {\n const filePath = `${dir}/${d}/${input.slug}.md`\n if (await reader.fileExists(filePath)) {\n changes.push({ path: filePath, content: null })\n }\n }\n } else if (strategy === 'none') {\n const files = await reader.listDirectory(dir)\n if (files.includes(`${input.slug}.md`)) {\n changes.push({ path: `${dir}/${input.slug}.md`, content: null })\n }\n }\n\n removed.push(`${model.content_path ?? `content/${model.domain}/${model.id}`}/${input.slug}`)\n\n const metaSlugDir = `.contentrain/meta/${model.id}/${input.slug}`\n if (input.locale) {\n changes.push({ path: `${metaSlugDir}/${input.locale}.json`, content: null })\n } else {\n const metaFiles = await reader.listDirectory(metaSlugDir)\n for (const f of metaFiles) changes.push({ path: `${metaSlugDir}/${f}`, content: null })\n }\n break\n }\n }\n\n changes.sort((a, b) => a.path.localeCompare(b.path))\n return { changes, result: removed, advisories: [] }\n}\n\nasync function pushAllMetaForModel(reader: RepoReader, modelId: string, changes: FileChange[]): Promise<void> {\n const metaDir = `.contentrain/meta/${modelId}`\n const files = await reader.listDirectory(metaDir)\n for (const f of files) changes.push({ path: `${metaDir}/${f}`, content: null })\n}\n","import type { ContentrainConfig, EntryMeta, ModelDefinition, Vocabulary } from '@contentrain/types'\nimport { generateEntryId, rewriteEntryMedia, rewriteMarkdownMedia, validateEntryId, validateLocale, validateSlug } from '@contentrain/types'\nimport type { FileChange, RepoReader } from '../contracts/index.js'\nimport type { ContentEntry } from '../content-manager.js'\nimport { canonicalStringify, parseMarkdownFrontmatter, serializeMarkdownFrontmatter } from '../serialization/index.js'\nimport type { ContentSaveEntryResult, ContentSavePlan } from './types.js'\nimport { contentFilePath, documentFilePath, metaFilePath } from './paths.js'\nimport { mergeEntryMeta } from '../meta-manager.js'\n\n/** Keys named individually in a replacement advisory before it collapses to a count. */\nconst MAX_REPORTED_KEYS = 5\n\ninterface PlanInput {\n model: ModelDefinition\n entries: ContentEntry[]\n config: ContentrainConfig\n vocabulary?: Vocabulary | null\n /**\n * Per-project public media delivery base (`RepoProvider.mediaBaseUrl`). When\n * set (hosted/cloud mode), relative `media/...` references in media fields\n * and markdown bodies are normalized to absolute delivery URLs before the\n * value is committed. Undefined in local mode — paths are kept verbatim.\n */\n mediaBaseUrl?: string\n}\n\n/**\n * Build the FileChange[] required to save a batch of content entries. The\n * plan is deterministic, pure, and does not touch disk — it reads existing\n * state through `reader` and returns changes for a single atomic commit.\n *\n * Grouping: multiple entries targeting the same (model, locale) share a\n * single content file and a single meta file. Reads are cached in-memory\n * so repeated reads of the same path during a plan are one IO.\n */\nexport async function planContentSave(reader: RepoReader, input: PlanInput): Promise<ContentSavePlan> {\n const { model, entries, config, vocabulary, mediaBaseUrl } = input\n const result: ContentSaveEntryResult[] = []\n const advisories: string[] = []\n\n // Hosted/cloud mode: normalize relative `media/...` references to absolute\n // delivery URLs so the committed value renders anywhere with no SDK. A no-op\n // in local mode (no base) or for field-less models (e.g. dictionaries).\n const normalizeMedia = (data: Record<string, unknown>): Record<string, unknown> =>\n mediaBaseUrl && model.fields ? rewriteEntryMedia(data, model.fields, mediaBaseUrl) : data\n\n // In-memory accumulators keyed by content-root-relative path.\n const contentByPath = new Map<string, unknown>()\n const metaByPath = new Map<string, unknown>()\n const markdownChanges = new Map<string, string>()\n\n async function readJsonOrEmpty<T>(path: string): Promise<T> {\n try {\n return JSON.parse(await reader.readFile(path)) as T\n } catch {\n return {} as T\n }\n }\n\n /** Absent file and absent entry both mean \"no prior meta\" — hence undefined, not `{}`. */\n async function readJsonOrUndefined<T>(path: string): Promise<T | undefined> {\n try {\n return JSON.parse(await reader.readFile(path)) as T\n } catch {\n return undefined\n }\n }\n\n /** Prior meta for a whole-file (non-collection) meta path, honouring the accumulator. */\n async function priorMeta(mPath: string): Promise<EntryMeta | undefined> {\n return (metaByPath.get(mPath) as EntryMeta | undefined)\n ?? await readJsonOrUndefined<EntryMeta>(mPath)\n }\n\n const defaultLocale = config.locales.default\n\n for (const entry of entries) {\n const locale = entry.locale ?? defaultLocale\n\n const localeErr = validateLocale(locale, config)\n if (localeErr) throw new Error(localeErr)\n if (entry.id) {\n const err = validateEntryId(entry.id)\n if (err) throw new Error(err)\n }\n if (entry.slug) {\n const err = validateSlug(entry.slug)\n if (err) throw new Error(err)\n }\n\n switch (model.kind) {\n case 'singleton': {\n const cPath = contentFilePath(model, locale)\n const mPath = metaFilePath(model, locale, defaultLocale)\n contentByPath.set(cPath, normalizeMedia(entry.data))\n metaByPath.set(mPath, mergeEntryMeta(await priorMeta(mPath), entry))\n result.push({ action: 'updated', locale })\n break\n }\n\n case 'collection': {\n const isNew = !entry.id\n const id = entry.id ?? generateEntryId()\n const cPath = contentFilePath(model, locale)\n const mPath = metaFilePath(model, locale, defaultLocale)\n\n const existing = (contentByPath.get(cPath) as Record<string, unknown> | undefined)\n ?? await readJsonOrEmpty<Record<string, unknown>>(cPath)\n\n const action: 'created' | 'updated' = isNew || !(id in existing) ? 'created' : 'updated'\n existing[id] = normalizeMedia(entry.data)\n\n const sorted: Record<string, unknown> = {}\n for (const key of Object.keys(existing).toSorted()) {\n sorted[key] = existing[key]\n }\n contentByPath.set(cPath, sorted)\n\n const existingMeta = (metaByPath.get(mPath) as Record<string, EntryMeta> | undefined)\n ?? await readJsonOrEmpty<Record<string, EntryMeta>>(mPath)\n existingMeta[id] = mergeEntryMeta(existingMeta[id], entry)\n metaByPath.set(mPath, existingMeta)\n\n result.push({ action, id, locale })\n break\n }\n\n case 'dictionary': {\n const cPath = contentFilePath(model, locale)\n const mPath = metaFilePath(model, locale, defaultLocale)\n\n const existing = (contentByPath.get(cPath) as Record<string, string> | undefined)\n ?? await readJsonOrEmpty<Record<string, string>>(cPath)\n\n const newData = entry.data as Record<string, string>\n const entryAdvisories: string[] = []\n\n // Overwriting a key used to be refused outright, which made the most\n // ordinary dictionary operation — correcting a translation — impossible:\n // the workaround was delete, merge, save, merge. Four operations and two\n // branches to fix one string. The refusal also advised \"include all keys\n // in a single save call\", which cannot work, because the check compares\n // values per key rather than counting them.\n //\n // Choosing a translation is a content decision, and MCP does not make\n // those. It reports them — the same way the duplicate-value case two\n // blocks below already does — and the branch diff shows the rest.\n const replaced = Object.keys(newData).filter(\n k => k in existing && existing[k] !== newData[k],\n )\n if (replaced.length > 0) {\n const shown = replaced.slice(0, MAX_REPORTED_KEYS)\n const detail = shown.map(k => `\"${k}\": \"${existing[k]}\" → \"${newData[k]}\"`).join(', ')\n const more = replaced.length > shown.length ? `, and ${replaced.length - shown.length} more` : ''\n entryAdvisories.push(\n `Dictionary \"${model.id}\" (${locale}): replaced ${replaced.length} existing value(s) — ${detail}${more}.`,\n )\n }\n\n const reverseMap = new Map<string, string>()\n for (const [k, v] of Object.entries(existing)) reverseMap.set(v, k)\n for (const [newKey, newValue] of Object.entries(newData)) {\n if (newKey in existing) continue\n const existingKey = reverseMap.get(newValue)\n if (existingKey && existingKey !== newKey) {\n entryAdvisories.push(\n `Value \"${newValue}\" already exists as key \"${existingKey}\". Consider reusing instead of creating \"${newKey}\".`,\n )\n }\n }\n\n if (vocabulary && Object.keys(vocabulary.terms).length > 0) {\n outer:\n for (const [newKey, newValue] of Object.entries(newData)) {\n if (newKey in existing) continue\n for (const translations of Object.values(vocabulary.terms)) {\n if (Object.values(translations).includes(newValue)) {\n entryAdvisories.push(\n `Value \"${newValue}\" matches a vocabulary term. Use the canonical form for consistency.`,\n )\n continue outer\n }\n }\n }\n }\n\n advisories.push(...entryAdvisories)\n\n contentByPath.set(cPath, { ...existing, ...newData })\n metaByPath.set(mPath, mergeEntryMeta(await priorMeta(mPath), entry))\n\n result.push({\n action: 'updated',\n locale,\n ...(entryAdvisories.length > 0 ? { advisories: entryAdvisories } : {}),\n })\n break\n }\n\n case 'document': {\n const entryAdvisories: string[] = []\n const slug = entry.slug ?? (entry.data['slug'] as string | undefined)\n if (!slug) throw new Error('Document entries require a slug')\n const slugErr = validateSlug(slug)\n if (slugErr) throw new Error(slugErr)\n\n const incomingFm = { ...entry.data }\n const bodySent = 'body' in incomingFm\n const incomingBody = (incomingFm['body'] as string | undefined) ?? ''\n delete incomingFm['body']\n if (!incomingFm['slug']) incomingFm['slug'] = slug\n\n const dPath = documentFilePath(model, locale, slug)\n const mPath = metaFilePath(model, locale, defaultLocale, slug)\n\n // Accumulator before disk, as the collection branch does: two entries\n // touching one document in a single call must compose, not race.\n let existingRaw: string | null = markdownChanges.get(dPath) ?? null\n if (existingRaw === null) {\n try { existingRaw = await reader.readFile(dPath) }\n catch { /* not yet */ }\n }\n // Same rule the collection branch uses: anything already present —\n // on disk or produced earlier in this plan — makes this an update.\n const action: 'created' | 'updated' = existingRaw ? 'updated' : 'created'\n\n // Merge with what is on disk, the way collections and singletons above\n // already do. Documents were the only kind that replaced instead of\n // merging, so a save that touched one frontmatter field wrote a file\n // containing only that field — and an entirely empty body. Nothing\n // reported it: the response said `valid: true`, because validation runs\n // over the plan's own output, which was internally consistent and\n // wrong. Under auto-merge that reaches the default branch directly.\n const existing = existingRaw ? parseMarkdownFrontmatter(existingRaw) : null\n const fmData = { ...existing?.frontmatter, ...incomingFm }\n\n // Absent `body` means \"I am not editing the body\" — keep what is there.\n // A `body` that is present, even empty, is an instruction, and is\n // honoured; clearing real content that way is announced rather than\n // silent, because it is indistinguishable from a templating mistake.\n const bodyContent = bodySent ? incomingBody : (existing?.body ?? '')\n if (bodySent && !incomingBody.trim() && existing?.body.trim()) {\n const notice = `Document \"${slug}\" (${locale}): body cleared — an explicit empty \"body\" replaced ${existing.body.length} characters. Omit \"body\" to leave it untouched.`\n entryAdvisories.push(notice)\n advisories.push(notice)\n }\n\n // Frontmatter media fields go through the schema-guided rewrite; the\n // markdown body has its `media/...` image/link targets rewritten too.\n const normalizedBody = mediaBaseUrl ? rewriteMarkdownMedia(bodyContent, mediaBaseUrl) : bodyContent\n markdownChanges.set(dPath, serializeMarkdownFrontmatter(normalizeMedia(fmData), normalizedBody))\n metaByPath.set(mPath, mergeEntryMeta(await priorMeta(mPath), entry))\n\n result.push({\n action,\n slug,\n locale,\n ...(entryAdvisories.length > 0 ? { advisories: entryAdvisories } : {}),\n })\n break\n }\n }\n }\n\n const changes: FileChange[] = []\n for (const [path, data] of contentByPath) {\n changes.push({ path, content: canonicalStringify(data) })\n }\n for (const [path, meta] of metaByPath) {\n changes.push({ path, content: canonicalStringify(meta) })\n }\n for (const [path, content] of markdownChanges) {\n changes.push({ path, content })\n }\n changes.sort((a, b) => a.path.localeCompare(b.path))\n\n return { changes, result, advisories }\n}\n","import type { ModelDefinition } from '@contentrain/types'\nimport type { FileChange, RepoReader } from '../contracts/index.js'\nimport type { OpPlan } from './types.js'\n\nexport interface ModelDeleteInput {\n model: ModelDefinition\n}\n\nexport type ModelDeletePlan = OpPlan<string[]>\n\n/**\n * Build the FileChange[] required to delete a model and its associated\n * content/meta files.\n *\n * The schema is at most two directory levels deep (e.g. document meta at\n * `.contentrain/meta/{id}/{slug}/{locale}.json`). The helper below walks\n * that much, which is enough for every model kind + locale strategy and\n * keeps us free of a general-purpose recursive lister for now.\n *\n * `result` is the legacy three-entry summary:\n * - `models/{id}.json`\n * - `content/{domain}/{id}/` (only if any content files existed)\n * - `meta/{id}/` (only if any meta files existed)\n */\nexport async function planModelDelete(reader: RepoReader, input: ModelDeleteInput): Promise<ModelDeletePlan> {\n const { model } = input\n const changes: FileChange[] = []\n const removed: string[] = []\n\n changes.push({ path: `.contentrain/models/${model.id}.json`, content: null })\n removed.push(`models/${model.id}.json`)\n\n const contentDir = model.content_path ?? `.contentrain/content/${model.domain}/${model.id}`\n const contentFiles = await enumerateTwoLevels(reader, contentDir)\n for (const path of contentFiles) {\n changes.push({ path, content: null })\n }\n if (contentFiles.length > 0) {\n removed.push(model.content_path ?? `content/${model.domain}/${model.id}/`)\n }\n\n const metaDir = `.contentrain/meta/${model.id}`\n const metaFiles = await enumerateTwoLevels(reader, metaDir)\n for (const path of metaFiles) {\n changes.push({ path, content: null })\n }\n if (metaFiles.length > 0) {\n removed.push(`meta/${model.id}/`)\n }\n\n changes.sort((a, b) => a.path.localeCompare(b.path))\n return { changes, result: removed, advisories: [] }\n}\n\n/** List files up to two directory levels deep. Filters to `.json` and `.md`. */\nasync function enumerateTwoLevels(reader: RepoReader, dir: string): Promise<string[]> {\n const results: string[] = []\n const entries = await reader.listDirectory(dir)\n for (const entry of entries) {\n const path = `${dir}/${entry}`\n if (entry.endsWith('.json') || entry.endsWith('.md')) {\n results.push(path)\n continue\n }\n const subEntries = await reader.listDirectory(path)\n for (const sub of subEntries) {\n if (sub.endsWith('.json') || sub.endsWith('.md')) {\n results.push(`${path}/${sub}`)\n }\n }\n }\n return results\n}\n","import type { ModelDefinition } from '@contentrain/types'\nimport { MODEL_FIELD_ORDER } from '@contentrain/types'\nimport type { FileChange, RepoReader } from '../contracts/index.js'\nimport { canonicalStringify } from '../serialization/index.js'\nimport type { OpPlan } from './types.js'\n\nexport interface ModelSaveInput {\n model: ModelDefinition\n}\n\nexport interface ModelSaveResult {\n action: 'created' | 'updated'\n id: string\n}\n\nexport type ModelSavePlan = OpPlan<ModelSaveResult>\n\n/**\n * Build the FileChange[] required to create or update a model definition.\n *\n * The only disk change is the model JSON file itself. Content and meta\n * directories are created on-demand when their first write lands — git does\n * not track empty directories, and MCP's write helpers `mkdir -p` before\n * every file write, so there is no operational reason to emit an empty-dir\n * ensure step here.\n */\nexport async function planModelSave(reader: RepoReader, input: ModelSaveInput): Promise<ModelSavePlan> {\n const { model } = input\n const modelPath = `.contentrain/models/${model.id}.json`\n\n let action: 'created' | 'updated' = 'created'\n try {\n await reader.readFile(modelPath)\n action = 'updated'\n } catch { /* not yet exists */ }\n\n const changes: FileChange[] = [\n { path: modelPath, content: canonicalStringify(model, MODEL_FIELD_ORDER) },\n ]\n\n return {\n changes,\n result: { action, id: model.id },\n advisories: [],\n }\n}\n","import type { RepoReader } from './contracts/index.js'\n\n/**\n * Pin a `RepoReader` to one ref. The reconcile planner takes three of these\n * (merge-base / contentrain / base branch) and stays entirely ignorant of\n * refs — executors and tools decide what to bind, the planner just reads.\n *\n * For readers that honour the per-call `ref?` parameter (GitHub, GitLab)\n * this is the whole story; a reader that ignores it (LocalReader reads the\n * working tree) needs a ref-aware implementation instead — see\n * `git/ref-reader.ts`.\n */\nexport function bindRef(reader: RepoReader, ref: string): RepoReader {\n return {\n readFile: path => reader.readFile(path, ref),\n listDirectory: path => reader.listDirectory(path, ref),\n fileExists: path => reader.fileExists(path, ref),\n }\n}\n","import type { Vocabulary } from '@contentrain/types'\nimport { canonicalStringify, LOCALE_PATTERN, SLUG_PATTERN } from '@contentrain/types'\nimport type { FileChange, RepoReader } from '../contracts/index.js'\nimport type { OpPlan } from './types.js'\n\nconst VOCABULARY_PATH = '.contentrain/vocabulary.json'\n\n/** Terms named individually in an advisory before it collapses to a count. */\nconst MAX_REPORTED_TERMS = 5\n\nexport interface VocabularySaveInput {\n /**\n * Terms to add or update, keyed by term slug, each holding its translations\n * keyed by locale. Merged with what is already there — a term absent from\n * this map is untouched.\n */\n terms: Record<string, Record<string, string>>\n}\n\nexport interface VocabularyDeleteInput {\n /** Term slugs to remove. A slug that is not present is reported, not an error. */\n terms: string[]\n}\n\nexport interface VocabularySaveResult {\n added: string[]\n updated: string[]\n total: number\n}\n\nexport interface VocabularyDeleteResult {\n deleted: string[]\n missing: string[]\n total: number\n}\n\nexport type VocabularySavePlan = OpPlan<VocabularySaveResult>\nexport type VocabularyDeletePlan = OpPlan<VocabularyDeleteResult>\n\nasync function readVocabulary(reader: RepoReader): Promise<Vocabulary> {\n try {\n const parsed = JSON.parse(await reader.readFile(VOCABULARY_PATH)) as Partial<Vocabulary>\n return { version: parsed.version ?? 1, terms: parsed.terms ?? {} }\n } catch {\n return { version: 1, terms: {} }\n }\n}\n\n/**\n * Validate the shape callers get wrong.\n *\n * The nesting is `term -> locale -> translation`, and it reads identically the\n * other way round, so a caller that groups by locale at the top level produces\n * a structurally valid file that matches nothing. That is not a typo anyone\n * notices — the vocabulary simply stops having any effect. Checking that outer\n * keys are term slugs and inner keys are locale codes catches the inversion at\n * the point of writing.\n */\nfunction validateTerms(terms: Record<string, Record<string, string>>): string[] {\n const errors: string[] = []\n\n for (const [term, translations] of Object.entries(terms)) {\n if (!SLUG_PATTERN.test(term)) {\n errors.push(`Term \"${term}\": must be kebab-case. The outer key is the term, not a locale.`)\n }\n if (typeof translations !== 'object' || translations === null || Array.isArray(translations)) {\n errors.push(`Term \"${term}\": expected an object of locale → translation.`)\n continue\n }\n if (Object.keys(translations).length === 0) {\n errors.push(`Term \"${term}\": has no translations.`)\n }\n for (const [locale, value] of Object.entries(translations)) {\n if (!LOCALE_PATTERN.test(locale)) {\n errors.push(\n `Term \"${term}\": \"${locale}\" is not a locale code. Terms nest as { \"${term}\": { \"en\": \"…\" } } — one term, its translations inside.`,\n )\n }\n if (typeof value !== 'string') {\n errors.push(`Term \"${term}\" (${locale}): translation must be a string, got ${typeof value}.`)\n }\n }\n }\n\n return errors\n}\n\n/**\n * Build the FileChange[] to add or update vocabulary terms.\n *\n * Vocabulary had no write tool at all: the rules forbid editing `.contentrain/`\n * by hand, and there was no supported way to obey that. This closes it through\n * the same plan/apply path every other write uses, so it lands on a `cr/*`\n * branch and follows the project's workflow like anything else.\n */\nexport async function planVocabularySave(\n reader: RepoReader,\n input: VocabularySaveInput,\n): Promise<VocabularySavePlan> {\n const errors = validateTerms(input.terms)\n if (errors.length > 0) {\n throw new Error(`Vocabulary validation failed:\\n- ${errors.join('\\n- ')}`)\n }\n\n const existing = await readVocabulary(reader)\n const added: string[] = []\n const updated: string[] = []\n const advisories: string[] = []\n\n const merged: Record<string, Record<string, string>> = { ...existing.terms }\n for (const [term, translations] of Object.entries(input.terms)) {\n const prior = existing.terms[term]\n if (!prior) {\n added.push(term)\n merged[term] = { ...translations }\n continue\n }\n updated.push(term)\n // Merge per locale: adding a Turkish translation must not drop the English.\n merged[term] = { ...prior, ...translations }\n\n const changed = Object.entries(translations).filter(([l, v]) => l in prior && prior[l] !== v)\n if (changed.length > 0) {\n const shown = changed.slice(0, MAX_REPORTED_TERMS)\n const detail = shown.map(([l, v]) => `${l}: \"${prior[l]}\" → \"${v}\"`).join(', ')\n const more = changed.length > shown.length ? `, and ${changed.length - shown.length} more` : ''\n advisories.push(`Term \"${term}\": replaced ${changed.length} translation(s) — ${detail}${more}.`)\n }\n }\n\n // A canonical term whose value duplicates another term's is the whole thing\n // this file exists to prevent, so it is worth saying out loud.\n const byValue = new Map<string, string>()\n for (const [term, translations] of Object.entries(merged)) {\n for (const value of Object.values(translations)) {\n const owner = byValue.get(value)\n if (owner && owner !== term) {\n advisories.push(`Terms \"${owner}\" and \"${term}\" share the translation \"${value}\".`)\n } else {\n byValue.set(value, term)\n }\n }\n }\n\n const next: Vocabulary = { version: existing.version, terms: merged }\n const changes: FileChange[] = [\n { path: VOCABULARY_PATH, content: canonicalStringify(next) },\n ]\n\n return {\n changes,\n result: { added, updated, total: Object.keys(merged).length },\n advisories,\n }\n}\n\n/** Build the FileChange[] to remove vocabulary terms. */\nexport async function planVocabularyDelete(\n reader: RepoReader,\n input: VocabularyDeleteInput,\n): Promise<VocabularyDeletePlan> {\n const existing = await readVocabulary(reader)\n\n const deleted: string[] = []\n const missing: string[] = []\n const remaining = { ...existing.terms }\n\n for (const term of input.terms) {\n if (term in remaining) {\n delete remaining[term]\n deleted.push(term)\n } else {\n missing.push(term)\n }\n }\n\n const advisories = missing.length > 0\n ? [`Not in the vocabulary, so nothing to delete: ${missing.join(', ')}.`]\n : []\n\n // Nothing changed — emit no FileChange, so the caller can skip the commit\n // rather than create an empty branch.\n const changes: FileChange[] = deleted.length > 0\n ? [{ path: VOCABULARY_PATH, content: canonicalStringify({ version: existing.version, terms: remaining } satisfies Vocabulary) }]\n : []\n\n return {\n changes,\n result: { deleted, missing, total: Object.keys(remaining).length },\n advisories,\n }\n}\n"],"mappings":";;;;;AAsBA,SAAS,WAAW,OAAwE;AAC1F,QAAO,MAAM,gBAAgB,wBAAwB,MAAM,OAAO,GAAG,MAAM;;AAG7E,eAAe,YAAe,QAAoB,MAAiC;AACjF,KAAI;AACF,SAAO,KAAK,MAAM,MAAM,OAAO,SAAS,KAAK,CAAC;SACxC;AACN,SAAO;;;AAIX,eAAe,0BACb,QACA,OACmB;CACnB,MAAM,MAAM,WAAW,MAAM;CAC7B,MAAM,QAAQ,MAAM,OAAO,cAAc,IAAI;AAE7C,MADiB,MAAM,mBAAmB,YACzB,YACf,QAAO;AAET,QAAO,MACJ,QAAO,MAAK,EAAE,SAAS,QAAQ,CAAC,CAChC,KAAI,MAAK,EAAE,QAAQ,SAAS,GAAG,CAAC,QAAQ,GAAG,MAAM,GAAG,IAAI,GAAG,CAAC;;;;;;;;;;;;;;;AAgBjE,eAAsB,kBACpB,QACA,OAC4B;CAC5B,MAAM,EAAE,UAAU;AASlB,KAAI,CAAC,MAAM,QAAQ,MAAM,OACvB,OAAM,IAAI,MACR,UAAU,MAAM,GAAG,kOAGpB;CAGH,MAAM,UAAwB,EAAE;CAChC,MAAM,UAAoB,EAAE;AAE5B,SAAQ,MAAM,MAAd;EACE,KAAK,cAAc;AACjB,OAAI,CAAC,MAAM,GAAI,OAAM,IAAI,MAAM,yCAAy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
1
1
|
import "../../contracts-DfL0BfrD.mjs";
|
|
2
|
-
import "../../reconcile-
|
|
3
|
-
import "../../context-
|
|
4
|
-
import { k as LocalReader } from "../../model-manager-
|
|
5
|
-
import "../../ops-
|
|
2
|
+
import "../../reconcile-8pEO4mBC.mjs";
|
|
3
|
+
import "../../context-Cp8b8Nxm.mjs";
|
|
4
|
+
import { k as LocalReader } from "../../model-manager-BYF2z7qC.mjs";
|
|
5
|
+
import "../../ops-CQ_IIedh.mjs";
|
|
6
6
|
import "../../fs-BFTuXbbw.mjs";
|
|
7
7
|
import "../../meta-manager-CSpKtjnP.mjs";
|
|
8
8
|
import "../../config-BLwZtwlI.mjs";
|
|
9
|
-
import "../../validator-
|
|
9
|
+
import "../../validator-eUdQqQGc.mjs";
|
|
10
10
|
import "../../identity-CxAB9Qb8.mjs";
|
|
11
11
|
import "../../base-branch-Cw9DWvCC.mjs";
|
|
12
12
|
import "../../branch-lifecycle-CcsSyfSw.mjs";
|
|
13
13
|
import "../../id-jrHWdtqn.mjs";
|
|
14
|
-
import "../../transaction-
|
|
15
|
-
import { t as LocalProvider } from "../../local-
|
|
14
|
+
import "../../transaction-CcjGiVYg.mjs";
|
|
15
|
+
import { t as LocalProvider } from "../../local-DaITA8Ye.mjs";
|
|
16
16
|
export { LocalProvider, LocalReader };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { t as buildContextChange } from "./context-
|
|
2
|
-
import { A as contentDirPath, M as documentFilePath, j as contentFilePath } from "./model-manager-
|
|
1
|
+
import { t as buildContextChange } from "./context-Cp8b8Nxm.mjs";
|
|
2
|
+
import { A as contentDirPath, M as documentFilePath, j as contentFilePath } from "./model-manager-BYF2z7qC.mjs";
|
|
3
3
|
import { t as OverlayReader } from "./overlay-reader-Bx1YxGXq.mjs";
|
|
4
|
-
import { t as validateProject } from "./validator-
|
|
4
|
+
import { t as validateProject } from "./validator-eUdQqQGc.mjs";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
6
6
|
import { mkdir, rm, writeFile } from "node:fs/promises";
|
|
7
7
|
import { MODEL_FIELD_ORDER, canonicalStringify, conflictId, parseMarkdownFrontmatter, serializeMarkdownFrontmatter, sortKeys, stableHash } from "@contentrain/types";
|
|
@@ -1724,4 +1724,4 @@ function parseJson(raw) {
|
|
|
1724
1724
|
//#endregion
|
|
1725
1725
|
export { applyChangesToWorktree as n, planReconcile as t };
|
|
1726
1726
|
|
|
1727
|
-
//# sourceMappingURL=reconcile-
|
|
1727
|
+
//# sourceMappingURL=reconcile-8pEO4mBC.mjs.map
|