scribe-cms 0.0.17 → 0.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +10 -0
  2. package/dist/cli/index.cjs +4021 -555
  3. package/dist/cli/index.cjs.map +1 -1
  4. package/dist/cli/index.js +4019 -553
  5. package/dist/cli/index.js.map +1 -1
  6. package/dist/index.cjs +1514 -229
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.js +1499 -228
  9. package/dist/index.js.map +1 -1
  10. package/dist/runtime.cjs +447 -33
  11. package/dist/runtime.cjs.map +1 -1
  12. package/dist/runtime.js +446 -32
  13. package/dist/runtime.js.map +1 -1
  14. package/dist/src/config/resolve-config.d.ts.map +1 -1
  15. package/dist/src/core/builtin-fields.d.ts +10 -1
  16. package/dist/src/core/builtin-fields.d.ts.map +1 -1
  17. package/dist/src/core/field.d.ts +70 -0
  18. package/dist/src/core/field.d.ts.map +1 -1
  19. package/dist/src/core/introspect-schema.d.ts +31 -1
  20. package/dist/src/core/introspect-schema.d.ts.map +1 -1
  21. package/dist/src/core/managed-roots.d.ts +15 -0
  22. package/dist/src/core/managed-roots.d.ts.map +1 -0
  23. package/dist/src/core/types.d.ts +56 -4
  24. package/dist/src/core/types.d.ts.map +1 -1
  25. package/dist/src/create-project.d.ts +17 -1
  26. package/dist/src/create-project.d.ts.map +1 -1
  27. package/dist/src/create-scribe.d.ts.map +1 -1
  28. package/dist/src/delete/execute.d.ts +21 -0
  29. package/dist/src/delete/execute.d.ts.map +1 -0
  30. package/dist/src/delete/plan.d.ts +85 -0
  31. package/dist/src/delete/plan.d.ts.map +1 -0
  32. package/dist/src/delete/render-text.d.ts +7 -0
  33. package/dist/src/delete/render-text.d.ts.map +1 -0
  34. package/dist/src/hash/page-hash.d.ts +9 -0
  35. package/dist/src/hash/page-hash.d.ts.map +1 -1
  36. package/dist/src/index.d.ts +12 -3
  37. package/dist/src/index.d.ts.map +1 -1
  38. package/dist/src/inline/resolve-tokens.d.ts +39 -0
  39. package/dist/src/inline/resolve-tokens.d.ts.map +1 -0
  40. package/dist/src/inline/tokens.d.ts +95 -0
  41. package/dist/src/inline/tokens.d.ts.map +1 -0
  42. package/dist/src/loader/create-loader.d.ts +7 -1
  43. package/dist/src/loader/create-loader.d.ts.map +1 -1
  44. package/dist/src/loader/resolve-assets.d.ts +16 -0
  45. package/dist/src/loader/resolve-assets.d.ts.map +1 -0
  46. package/dist/src/runtime.d.ts +1 -1
  47. package/dist/src/runtime.d.ts.map +1 -1
  48. package/dist/src/storage/translations.d.ts +8 -0
  49. package/dist/src/storage/translations.d.ts.map +1 -1
  50. package/dist/src/translate/resolve-translate-config.d.ts.map +1 -1
  51. package/dist/src/translate/response-schema.d.ts +7 -1
  52. package/dist/src/translate/response-schema.d.ts.map +1 -1
  53. package/dist/src/translate/translate-core.d.ts +6 -0
  54. package/dist/src/translate/translate-core.d.ts.map +1 -1
  55. package/dist/src/translate/validate-translation.d.ts.map +1 -1
  56. package/dist/src/translate/worklist.d.ts +8 -1
  57. package/dist/src/translate/worklist.d.ts.map +1 -1
  58. package/dist/src/validate/validate-assets.d.ts +26 -2
  59. package/dist/src/validate/validate-assets.d.ts.map +1 -1
  60. package/dist/src/validate/validate-inline-tokens.d.ts +10 -0
  61. package/dist/src/validate/validate-inline-tokens.d.ts.map +1 -0
  62. package/dist/src/validate/validate-project.d.ts.map +1 -1
  63. package/dist/src/validate/validate-relations.d.ts +2 -1
  64. package/dist/src/validate/validate-relations.d.ts.map +1 -1
  65. package/dist/studio/asset-serve.d.ts +39 -0
  66. package/dist/studio/asset-serve.d.ts.map +1 -0
  67. package/dist/studio/asset-views.d.ts +4 -0
  68. package/dist/studio/asset-views.d.ts.map +1 -0
  69. package/dist/studio/content-views.d.ts +85 -0
  70. package/dist/studio/content-views.d.ts.map +1 -0
  71. package/dist/studio/introspect-fields.d.ts +111 -0
  72. package/dist/studio/introspect-fields.d.ts.map +1 -0
  73. package/dist/studio/mdx-preview.d.ts +3 -0
  74. package/dist/studio/mdx-preview.d.ts.map +1 -0
  75. package/dist/studio/preview-tokens.d.ts +16 -0
  76. package/dist/studio/preview-tokens.d.ts.map +1 -0
  77. package/dist/studio/search.d.ts +34 -0
  78. package/dist/studio/search.d.ts.map +1 -0
  79. package/dist/studio/server.cjs +4699 -304
  80. package/dist/studio/server.cjs.map +1 -1
  81. package/dist/studio/server.d.ts.map +1 -1
  82. package/dist/studio/server.js +4697 -302
  83. package/dist/studio/server.js.map +1 -1
  84. package/dist/studio/shared.d.ts +20 -0
  85. package/dist/studio/shared.d.ts.map +1 -0
  86. package/dist/studio/studio-cache.d.ts +93 -0
  87. package/dist/studio/studio-cache.d.ts.map +1 -0
  88. package/package.json +2 -2
package/dist/index.cjs CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  var zod = require('zod');
4
4
  var path3 = require('path');
5
- var fs2 = require('fs');
6
- var matter = require('gray-matter');
5
+ var fs14 = require('fs');
6
+ var matter4 = require('gray-matter');
7
7
  var Database = require('better-sqlite3');
8
8
  var remarkMdx = require('remark-mdx');
9
9
  var remarkParse = require('remark-parse');
@@ -15,8 +15,8 @@ var genai = require('@google/genai');
15
15
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
16
16
 
17
17
  var path3__default = /*#__PURE__*/_interopDefault(path3);
18
- var fs2__default = /*#__PURE__*/_interopDefault(fs2);
19
- var matter__default = /*#__PURE__*/_interopDefault(matter);
18
+ var fs14__default = /*#__PURE__*/_interopDefault(fs14);
19
+ var matter4__default = /*#__PURE__*/_interopDefault(matter4);
20
20
  var Database__default = /*#__PURE__*/_interopDefault(Database);
21
21
  var remarkMdx__default = /*#__PURE__*/_interopDefault(remarkMdx);
22
22
  var remarkParse__default = /*#__PURE__*/_interopDefault(remarkParse);
@@ -26,6 +26,7 @@ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${_
26
26
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
27
27
  var FIELD_KIND = /* @__PURE__ */ Symbol.for("@genlook/scribe/fieldKind");
28
28
  var RELATION_META = /* @__PURE__ */ Symbol.for("@genlook/scribe/relationMeta");
29
+ var ASSET_META = /* @__PURE__ */ Symbol.for("@genlook/scribe/assetMeta");
29
30
  function getFieldKind(schema) {
30
31
  const tagged = schema;
31
32
  return tagged[FIELD_KIND] ?? "structural";
@@ -53,6 +54,29 @@ function getRelationTarget(schema) {
53
54
  }
54
55
  return null;
55
56
  }
57
+ function getAssetMeta(schema) {
58
+ let current = schema;
59
+ for (let i = 0; i < 8; i++) {
60
+ const tagged = current;
61
+ if (tagged[ASSET_META]) {
62
+ return tagged[ASSET_META];
63
+ }
64
+ if (typeof tagged.unwrap === "function") {
65
+ current = tagged.unwrap();
66
+ continue;
67
+ }
68
+ if (typeof tagged.removeDefault === "function") {
69
+ current = tagged.removeDefault();
70
+ continue;
71
+ }
72
+ if (tagged._def?.innerType) {
73
+ current = tagged._def.innerType;
74
+ continue;
75
+ }
76
+ break;
77
+ }
78
+ return null;
79
+ }
56
80
  function mark(schema, kind) {
57
81
  Object.defineProperty(schema, FIELD_KIND, {
58
82
  value: kind,
@@ -69,6 +93,14 @@ function markRelation(schema, meta) {
69
93
  });
70
94
  return mark(schema, "structural");
71
95
  }
96
+ function markAsset(schema, meta) {
97
+ Object.defineProperty(schema, ASSET_META, {
98
+ value: meta,
99
+ enumerable: false,
100
+ configurable: true
101
+ });
102
+ return mark(schema, "structural");
103
+ }
72
104
  var field = {
73
105
  translatable: (schema) => mark(schema, "translatable"),
74
106
  structural: (schema) => mark(schema, "structural"),
@@ -89,9 +121,24 @@ var field = {
89
121
  } else {
90
122
  inner = zod.z.string().min(1);
91
123
  }
92
- markRelation(inner, { typeId, multiple, optional });
124
+ const onTargetDelete = options?.onTargetDelete ?? "restrict";
125
+ markRelation(inner, { typeId, multiple, optional, onTargetDelete });
93
126
  const schema = optional ? inner.optional() : inner;
94
127
  return schema;
128
+ },
129
+ asset: (options) => {
130
+ const optional = options?.optional ?? false;
131
+ const inner = zod.z.string().min(1);
132
+ markAsset(inner, {
133
+ dir: options?.dir,
134
+ template: options?.template,
135
+ formats: options?.formats,
136
+ maxKB: options?.maxKB,
137
+ optional,
138
+ onDelete: options?.onDelete ?? "delete"
139
+ });
140
+ const schema = optional || options?.template !== void 0 ? inner.optional() : inner;
141
+ return schema;
95
142
  }
96
143
  };
97
144
  function unwrapSchema(schema) {
@@ -131,6 +178,208 @@ function peelOptionalWrappers(schema) {
131
178
  return current;
132
179
  }
133
180
 
181
+ // src/core/introspect-schema.ts
182
+ function getArrayElement(schema) {
183
+ if (schema instanceof Object && "element" in schema && schema._def?.type === "array") {
184
+ return schema.element;
185
+ }
186
+ return null;
187
+ }
188
+ function introspectSchema(schema, prefix = []) {
189
+ const relation = getRelationTarget(schema);
190
+ if (relation && prefix.length > 0) {
191
+ return [
192
+ {
193
+ path: prefix,
194
+ kind: "relation",
195
+ relationTarget: relation.typeId,
196
+ relationMultiple: relation.multiple,
197
+ relationOptional: relation.optional,
198
+ relationOnTargetDelete: relation.onTargetDelete
199
+ }
200
+ ];
201
+ }
202
+ const asset = getAssetMeta(schema);
203
+ if (asset && prefix.length > 0) {
204
+ return [
205
+ {
206
+ path: prefix,
207
+ kind: "asset",
208
+ assetDir: asset.dir,
209
+ assetTemplate: asset.template,
210
+ assetFormats: asset.formats,
211
+ assetMaxKB: asset.maxKB,
212
+ assetOptional: asset.optional,
213
+ assetOnDelete: asset.onDelete
214
+ }
215
+ ];
216
+ }
217
+ if (prefix.length > 0 && getFieldKind(schema) === "translatable") {
218
+ return [{ path: prefix, kind: "translatable" }];
219
+ }
220
+ const base = peelOptionalWrappers(schema);
221
+ if (base instanceof Object && "shape" in base) {
222
+ const shape = base.shape;
223
+ const fields = [];
224
+ for (const [key, child] of Object.entries(shape)) {
225
+ fields.push(...introspectSchema(child, [...prefix, key]));
226
+ }
227
+ return fields;
228
+ }
229
+ const element = getArrayElement(base);
230
+ if (element) {
231
+ const elementBase = peelOptionalWrappers(element);
232
+ if (elementBase instanceof Object && "shape" in elementBase) {
233
+ const shape = elementBase.shape;
234
+ const fields = [];
235
+ for (const [key, child] of Object.entries(shape)) {
236
+ fields.push(...introspectSchema(child, [...prefix, "*", key]));
237
+ }
238
+ return fields;
239
+ }
240
+ }
241
+ return [{ path: prefix, kind: getFieldKind(schema) }];
242
+ }
243
+ function buildPathTrie(paths) {
244
+ const root = { leaf: false, children: /* @__PURE__ */ new Map() };
245
+ for (const path15 of paths) {
246
+ let node = root;
247
+ for (const segment of path15) {
248
+ let child = node.children.get(segment);
249
+ if (!child) {
250
+ child = { leaf: false, children: /* @__PURE__ */ new Map() };
251
+ node.children.set(segment, child);
252
+ }
253
+ node = child;
254
+ }
255
+ node.leaf = true;
256
+ }
257
+ return root;
258
+ }
259
+ function extractNode(data, trie) {
260
+ if (trie.leaf) return data;
261
+ const star = trie.children.get("*");
262
+ if (star) {
263
+ if (!Array.isArray(data)) return void 0;
264
+ return data.map(
265
+ (item) => typeof item === "object" && item !== null ? extractNode(item, star) ?? {} : {}
266
+ );
267
+ }
268
+ if (typeof data !== "object" || data === null || Array.isArray(data)) return void 0;
269
+ const record = data;
270
+ const out = {};
271
+ let any = false;
272
+ for (const [key, child] of trie.children) {
273
+ const value = extractNode(record[key], child);
274
+ if (value !== void 0) {
275
+ out[key] = value;
276
+ any = true;
277
+ }
278
+ }
279
+ return any ? out : void 0;
280
+ }
281
+ function extractByPaths(data, paths) {
282
+ if (paths.length === 0) return {};
283
+ const extracted = extractNode(data, buildPathTrie(paths));
284
+ return extracted && typeof extracted === "object" && !Array.isArray(extracted) ? extracted : {};
285
+ }
286
+ function pickTranslatable(data, schema) {
287
+ const translatablePaths = introspectSchema(schema).filter((f) => f.kind === "translatable").map((f) => f.path);
288
+ return extractByPaths(data, translatablePaths);
289
+ }
290
+ function pruneOrphanNestedTranslations(localeData, enData, schema) {
291
+ const out = { ...localeData };
292
+ const structuralParentsWithNested = /* @__PURE__ */ new Set();
293
+ for (const meta of introspectSchema(schema)) {
294
+ if (meta.kind !== "translatable" || meta.path.length < 3 || meta.path[1] !== "*") continue;
295
+ structuralParentsWithNested.add(meta.path[0]);
296
+ }
297
+ for (const parent of structuralParentsWithNested) {
298
+ const enParent = enData[parent];
299
+ if (enParent === void 0 || enParent === null) {
300
+ delete out[parent];
301
+ }
302
+ }
303
+ return out;
304
+ }
305
+ function pickStructural(data, schema) {
306
+ const structuralPaths = introspectSchema(schema).filter((f) => f.kind === "structural" || f.kind === "relation" || f.kind === "asset").map((f) => f.path);
307
+ return extractByPaths(data, structuralPaths);
308
+ }
309
+ function mergeStructuralOntoLocale(localeData, enData, schema) {
310
+ const structural = pickStructural(enData, schema);
311
+ const translatable = pickTranslatable(localeData, schema);
312
+ return deepMerge(structural, translatable);
313
+ }
314
+ function deepMerge(base, overlay) {
315
+ const out = { ...base };
316
+ for (const [key, value] of Object.entries(overlay)) {
317
+ if (value && typeof value === "object" && !Array.isArray(value) && out[key] && typeof out[key] === "object" && !Array.isArray(out[key])) {
318
+ out[key] = deepMerge(out[key], value);
319
+ } else if (Array.isArray(value) && Array.isArray(out[key])) {
320
+ out[key] = mergeArrayOverlay(out[key], value);
321
+ } else if (value !== void 0) {
322
+ out[key] = value;
323
+ }
324
+ }
325
+ return out;
326
+ }
327
+ function mergeArrayOverlay(base, overlay) {
328
+ return base.map((item, index) => {
329
+ const overlayItem = overlay[index];
330
+ if (item && typeof item === "object" && !Array.isArray(item) && overlayItem && typeof overlayItem === "object" && !Array.isArray(overlayItem)) {
331
+ return deepMerge(item, overlayItem);
332
+ }
333
+ return overlayItem ?? item;
334
+ });
335
+ }
336
+ function listTranslatableFields(schema) {
337
+ return introspectSchema(schema).filter((f) => f.kind === "translatable");
338
+ }
339
+ function isTypeTranslatable(type) {
340
+ return listTranslatableFields(type.schema).length > 0 || type.body !== false;
341
+ }
342
+ function listRelationFields(schema) {
343
+ return introspectSchema(schema).filter((f) => f.kind === "relation");
344
+ }
345
+ function listAssetFields(schema) {
346
+ return introspectSchema(schema).filter((f) => f.kind === "asset");
347
+ }
348
+
349
+ // src/core/managed-roots.ts
350
+ function normalizeRoot(root) {
351
+ const trimmed = `/${root.replace(/^\/+|\/+$/g, "")}`;
352
+ return trimmed === "/" ? "" : trimmed;
353
+ }
354
+ function templateManagedRoot(template) {
355
+ const braceIndex = template.indexOf("{");
356
+ const staticPart = braceIndex >= 0 ? template.slice(0, braceIndex) : template;
357
+ const lastSlash = staticPart.lastIndexOf("/");
358
+ const prefix = lastSlash >= 0 ? staticPart.slice(0, lastSlash) : staticPart;
359
+ return normalizeRoot(prefix);
360
+ }
361
+ function getManagedRoots(config) {
362
+ if (!config.assets) return [];
363
+ const roots = /* @__PURE__ */ new Set();
364
+ for (const dir of config.assets.managedDirs ?? []) {
365
+ const normalized = normalizeRoot(dir);
366
+ if (normalized) roots.add(normalized);
367
+ }
368
+ for (const type of config.types) {
369
+ for (const f of listAssetFields(type.schema)) {
370
+ if (f.assetDir) {
371
+ const normalized = normalizeRoot(f.assetDir);
372
+ if (normalized) roots.add(normalized);
373
+ }
374
+ if (f.assetTemplate) {
375
+ const normalized = templateManagedRoot(f.assetTemplate);
376
+ if (normalized) roots.add(normalized);
377
+ }
378
+ }
379
+ }
380
+ return [...roots].sort();
381
+ }
382
+
134
383
  // src/core/types.ts
135
384
  function defineConfig(config) {
136
385
  return config;
@@ -144,14 +393,14 @@ var SLUG_PLACEHOLDER = "{slug}";
144
393
  function isRoutableType(type) {
145
394
  return typeof type.path === "string" && type.path.length > 0;
146
395
  }
147
- function assertValidPathTemplate(path13, typeId) {
148
- if (!path13.startsWith("/")) {
149
- throw new Error(`Content type "${typeId}": path must start with / (got "${path13}")`);
396
+ function assertValidPathTemplate(path15, typeId) {
397
+ if (!path15.startsWith("/")) {
398
+ throw new Error(`Content type "${typeId}": path must start with / (got "${path15}")`);
150
399
  }
151
- const count = (path13.match(/\{slug\}/g) ?? []).length;
400
+ const count = (path15.match(/\{slug\}/g) ?? []).length;
152
401
  if (count !== 1) {
153
402
  throw new Error(
154
- `Content type "${typeId}": path must contain exactly one {slug} (got "${path13}")`
403
+ `Content type "${typeId}": path must contain exactly one {slug} (got "${path15}")`
155
404
  );
156
405
  }
157
406
  }
@@ -261,7 +510,15 @@ function resolveConfig(input, baseDir) {
261
510
  const projectRoot = path3__default.default.resolve(baseDir ?? process.cwd(), raw.rootDir);
262
511
  const contentRoot = path3__default.default.resolve(projectRoot, raw.contentDir ?? "content");
263
512
  const storePath = path3__default.default.resolve(projectRoot, raw.store ?? ".scribe/store.sqlite");
264
- const assetsPath = raw.assetsDir ? path3__default.default.resolve(projectRoot, raw.assetsDir) : void 0;
513
+ let assetsPath;
514
+ let assets;
515
+ if (raw.assets !== void 0 || raw.assetsDir !== void 0) {
516
+ const dir = raw.assets?.dir ?? raw.assetsDir ?? "public";
517
+ const publicPath = raw.assets?.publicPath ?? "/";
518
+ const managedDirs = raw.assets?.managedDirs ?? [];
519
+ assetsPath = path3__default.default.resolve(projectRoot, dir);
520
+ assets = { assetsPath, publicPath, managedDirs };
521
+ }
265
522
  const seenIds = /* @__PURE__ */ new Set();
266
523
  const types = raw.types.map((type) => {
267
524
  if (seenIds.has(type.id)) {
@@ -276,13 +533,17 @@ function resolveConfig(input, baseDir) {
276
533
  contentDir: type.contentDir ?? type.id,
277
534
  label: type.label ?? type.id.charAt(0).toUpperCase() + type.id.slice(1),
278
535
  slugStrategy: type.slugStrategy ?? "fixed",
279
- indexFallback: type.indexFallback ?? (type.path ? "en" : "none")
536
+ indexFallback: type.indexFallback ?? (type.path ? "en" : "none"),
537
+ // `body` defaults to true (fully backwards compatible). A resolved type
538
+ // always carries an explicit boolean so consumers read one source of truth.
539
+ body: type.body ?? true
280
540
  };
281
541
  });
282
542
  const config = {
283
543
  rootDir: contentRoot,
284
544
  storePath,
285
545
  assetsPath,
546
+ assets,
286
547
  locales: [...raw.locales],
287
548
  defaultLocale,
288
549
  localeRouting,
@@ -316,134 +577,6 @@ function deriveLocaleFallbacks(locales, defaultLocale) {
316
577
  }
317
578
  return fallbacks;
318
579
  }
319
-
320
- // src/core/introspect-schema.ts
321
- function getArrayElement(schema) {
322
- if (schema instanceof Object && "element" in schema && schema._def?.type === "array") {
323
- return schema.element;
324
- }
325
- return null;
326
- }
327
- function introspectSchema(schema, prefix = []) {
328
- const relation = getRelationTarget(schema);
329
- if (relation && prefix.length > 0) {
330
- return [
331
- {
332
- path: prefix,
333
- kind: "relation",
334
- relationTarget: relation.typeId,
335
- relationMultiple: relation.multiple,
336
- relationOptional: relation.optional
337
- }
338
- ];
339
- }
340
- if (prefix.length > 0 && getFieldKind(schema) === "translatable") {
341
- return [{ path: prefix, kind: "translatable" }];
342
- }
343
- const base = peelOptionalWrappers(schema);
344
- if (base instanceof Object && "shape" in base) {
345
- const shape = base.shape;
346
- const fields = [];
347
- for (const [key, child] of Object.entries(shape)) {
348
- fields.push(...introspectSchema(child, [...prefix, key]));
349
- }
350
- return fields;
351
- }
352
- const element = getArrayElement(base);
353
- if (element) {
354
- const elementBase = peelOptionalWrappers(element);
355
- if (elementBase instanceof Object && "shape" in elementBase) {
356
- const shape = elementBase.shape;
357
- const fields = [];
358
- for (const [key, child] of Object.entries(shape)) {
359
- fields.push(...introspectSchema(child, [...prefix, "*", key]));
360
- }
361
- return fields;
362
- }
363
- }
364
- return [{ path: prefix, kind: getFieldKind(schema) }];
365
- }
366
- function buildPathTrie(paths) {
367
- const root = { leaf: false, children: /* @__PURE__ */ new Map() };
368
- for (const path13 of paths) {
369
- let node = root;
370
- for (const segment of path13) {
371
- let child = node.children.get(segment);
372
- if (!child) {
373
- child = { leaf: false, children: /* @__PURE__ */ new Map() };
374
- node.children.set(segment, child);
375
- }
376
- node = child;
377
- }
378
- node.leaf = true;
379
- }
380
- return root;
381
- }
382
- function extractNode(data, trie) {
383
- if (trie.leaf) return data;
384
- const star = trie.children.get("*");
385
- if (star) {
386
- if (!Array.isArray(data)) return void 0;
387
- return data.map(
388
- (item) => typeof item === "object" && item !== null ? extractNode(item, star) ?? {} : {}
389
- );
390
- }
391
- if (typeof data !== "object" || data === null || Array.isArray(data)) return void 0;
392
- const record = data;
393
- const out = {};
394
- let any = false;
395
- for (const [key, child] of trie.children) {
396
- const value = extractNode(record[key], child);
397
- if (value !== void 0) {
398
- out[key] = value;
399
- any = true;
400
- }
401
- }
402
- return any ? out : void 0;
403
- }
404
- function extractByPaths(data, paths) {
405
- if (paths.length === 0) return {};
406
- const extracted = extractNode(data, buildPathTrie(paths));
407
- return extracted && typeof extracted === "object" && !Array.isArray(extracted) ? extracted : {};
408
- }
409
- function pickTranslatable(data, schema) {
410
- const translatablePaths = introspectSchema(schema).filter((f) => f.kind === "translatable").map((f) => f.path);
411
- return extractByPaths(data, translatablePaths);
412
- }
413
- function pickStructural(data, schema) {
414
- const structuralPaths = introspectSchema(schema).filter((f) => f.kind === "structural" || f.kind === "relation").map((f) => f.path);
415
- return extractByPaths(data, structuralPaths);
416
- }
417
- function mergeStructuralOntoLocale(localeData, enData, schema) {
418
- const structural = pickStructural(enData, schema);
419
- const translatable = pickTranslatable(localeData, schema);
420
- return deepMerge(structural, translatable);
421
- }
422
- function deepMerge(base, overlay) {
423
- const out = { ...base };
424
- for (const [key, value] of Object.entries(overlay)) {
425
- if (value && typeof value === "object" && !Array.isArray(value) && out[key] && typeof out[key] === "object" && !Array.isArray(out[key])) {
426
- out[key] = deepMerge(out[key], value);
427
- } else if (Array.isArray(value) && Array.isArray(out[key])) {
428
- out[key] = mergeArrayOverlay(out[key], value);
429
- } else {
430
- out[key] = value;
431
- }
432
- }
433
- return out;
434
- }
435
- function mergeArrayOverlay(base, overlay) {
436
- return base.map((item, index) => {
437
- const overlayItem = overlay[index];
438
- if (item && typeof item === "object" && !Array.isArray(item) && overlayItem && typeof overlayItem === "object" && !Array.isArray(overlayItem)) {
439
- return deepMerge(item, overlayItem);
440
- }
441
- return overlayItem ?? item;
442
- });
443
- }
444
- function listRelationFields(schema) {
445
- return introspectSchema(schema).filter((f) => f.kind === "relation");
446
- }
447
580
  var SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
448
581
  var slugPatternSchema = zod.z.string().regex(SLUG_PATTERN, "slug must be lowercase-kebab-case");
449
582
  var isoDateSchema = zod.z.string().regex(/^\d{4}-\d{2}-\d{2}(T[\d:.Z+-]*)?$/, "Use ISO date YYYY-MM-DD or full ISO 8601");
@@ -534,12 +667,18 @@ function extractBuiltinEnFields(data, _pathTemplate, _enSlug, _defaultLocale) {
534
667
  delete rest[internalKey];
535
668
  }
536
669
  }
670
+ let vars;
671
+ if (rest.vars !== void 0) {
672
+ vars = rest.vars;
673
+ delete rest.vars;
674
+ }
537
675
  return {
538
676
  builtin: {
539
677
  publishedAt,
540
678
  updatedAt,
541
679
  noindex,
542
- canonicalPathOverride
680
+ canonicalPathOverride,
681
+ vars
543
682
  },
544
683
  rest,
545
684
  issues
@@ -578,6 +717,7 @@ function mergeBuiltinsIntoFrontmatter(frontmatter, doc, type, defaultLocale, loc
578
717
  if (doc.updatedAt !== void 0) out.updatedAt = doc.updatedAt;
579
718
  out.noindex = doc.noindex;
580
719
  out.canonicalPath = resolveCanonicalPathname(type, doc, defaultLocale, localeRouting);
720
+ if (doc.vars !== void 0) out.vars = doc.vars;
581
721
  return out;
582
722
  }
583
723
  function seoFieldsFromEn(enDoc) {
@@ -667,7 +807,7 @@ function resolveStorePath(config) {
667
807
  function openStore(config, mode = "readwrite") {
668
808
  const storePath = resolveStorePath(config);
669
809
  if (mode === "readwrite") {
670
- fs2__default.default.mkdirSync(path3__default.default.dirname(storePath), { recursive: true });
810
+ fs14__default.default.mkdirSync(path3__default.default.dirname(storePath), { recursive: true });
671
811
  }
672
812
  const db = new Database__default.default(storePath, { readonly: mode === "readonly" });
673
813
  if (mode === "readwrite") {
@@ -767,6 +907,26 @@ function listTranslationsForEnSlug(db, contentType, enSlug) {
767
907
  function bulkLoadTranslations(db) {
768
908
  return db.prepare(`SELECT * FROM translations ORDER BY content_type, en_slug, locale`).all();
769
909
  }
910
+ function countTranslationsForEnSlug(db, contentType, enSlug) {
911
+ const row = db.prepare(
912
+ `SELECT COUNT(*) as count FROM translations WHERE content_type = ? AND en_slug = ?`
913
+ ).get(contentType, enSlug);
914
+ return row.count;
915
+ }
916
+ function countEnSnapshotsForEnSlug(db, contentType, enSlug) {
917
+ const row = db.prepare(
918
+ `SELECT COUNT(*) as count FROM en_snapshots WHERE content_type = ? AND en_slug = ?`
919
+ ).get(contentType, enSlug);
920
+ return row.count;
921
+ }
922
+ function deleteTranslationsForEnSlug(db, contentType, enSlug) {
923
+ const info = db.prepare(`DELETE FROM translations WHERE content_type = ? AND en_slug = ?`).run(contentType, enSlug);
924
+ return info.changes;
925
+ }
926
+ function deleteEnSnapshotsForEnSlug(db, contentType, enSlug) {
927
+ const info = db.prepare(`DELETE FROM en_snapshots WHERE content_type = ? AND en_slug = ?`).run(contentType, enSlug);
928
+ return info.changes;
929
+ }
770
930
 
771
931
  // src/translate/normalize-mdx-body.ts
772
932
  function needsMdxEscapeNormalization(body) {
@@ -900,6 +1060,317 @@ function assertValidTranslatedMdxBody(body) {
900
1060
  return prepared;
901
1061
  }
902
1062
 
1063
+ // src/loader/resolve-assets.ts
1064
+ function joinPublicPath(publicPath, webPath) {
1065
+ if (publicPath === "" || publicPath === "/") return webPath;
1066
+ const suffix = webPath.startsWith("/") ? webPath : `/${webPath}`;
1067
+ return publicPath.replace(/\/+$/, "") + suffix;
1068
+ }
1069
+ function materializeTemplate(template, enSlug) {
1070
+ return template.split("{slug}").join(enSlug);
1071
+ }
1072
+ function setAssetAtPath(container, path15, transform) {
1073
+ const [head, ...rest] = path15;
1074
+ if (head === void 0) return;
1075
+ if (rest.length === 0) {
1076
+ const current = container[head];
1077
+ const next = transform(typeof current === "string" ? current : void 0);
1078
+ if (next !== void 0) container[head] = next;
1079
+ return;
1080
+ }
1081
+ if (rest[0] === "*") {
1082
+ const arr = container[head];
1083
+ if (!Array.isArray(arr)) return;
1084
+ for (const item of arr) {
1085
+ if (item && typeof item === "object" && !Array.isArray(item)) {
1086
+ setAssetAtPath(item, rest.slice(1), transform);
1087
+ }
1088
+ }
1089
+ return;
1090
+ }
1091
+ const child = container[head];
1092
+ if (child && typeof child === "object" && !Array.isArray(child)) {
1093
+ setAssetAtPath(child, rest, transform);
1094
+ }
1095
+ }
1096
+ function resolveDocumentAssets(doc, assetFields, assets) {
1097
+ const frontmatter = doc.frontmatter;
1098
+ for (const f of assetFields) {
1099
+ setAssetAtPath(frontmatter, f.path, (current) => {
1100
+ let value = current;
1101
+ if (value === void 0) {
1102
+ if (!f.assetTemplate) return void 0;
1103
+ value = materializeTemplate(f.assetTemplate, doc.enSlug);
1104
+ }
1105
+ return joinPublicPath(assets.publicPath, value);
1106
+ });
1107
+ }
1108
+ }
1109
+
1110
+ // src/inline/tokens.ts
1111
+ var TOKEN_OPEN = "${{";
1112
+ var ESCAPE_SEQUENCE = "$\\{{";
1113
+ var ESCAPE_RESULT = "${{";
1114
+ function placeholderMarker(n) {
1115
+ return `%%${n}%%`;
1116
+ }
1117
+ function findTokenEnd(body, start) {
1118
+ let i = start;
1119
+ let inString = false;
1120
+ while (i < body.length) {
1121
+ const ch = body[i];
1122
+ if (ch === "\n") return -1;
1123
+ if (inString) {
1124
+ if (ch === "\\") {
1125
+ i += 2;
1126
+ continue;
1127
+ }
1128
+ if (ch === '"') inString = false;
1129
+ i += 1;
1130
+ continue;
1131
+ }
1132
+ if (ch === '"') {
1133
+ inString = true;
1134
+ i += 1;
1135
+ continue;
1136
+ }
1137
+ if (ch === "}" && body[i + 1] === "}") return i;
1138
+ i += 1;
1139
+ }
1140
+ return -1;
1141
+ }
1142
+ function parseTokenInner(inner) {
1143
+ const colon = inner.indexOf(":");
1144
+ if (colon === -1) {
1145
+ return { ok: false, reason: `missing kind separator ":"` };
1146
+ }
1147
+ const kind = inner.slice(0, colon);
1148
+ const rest = inner.slice(colon + 1);
1149
+ switch (kind) {
1150
+ case "static": {
1151
+ let text;
1152
+ try {
1153
+ text = JSON.parse(rest);
1154
+ } catch {
1155
+ return { ok: false, reason: `static value is not a valid JSON string` };
1156
+ }
1157
+ if (typeof text !== "string") {
1158
+ return { ok: false, reason: `static value must be a JSON string` };
1159
+ }
1160
+ return { ok: true, token: { kind: "static", text } };
1161
+ }
1162
+ case "relation": {
1163
+ const parts = rest.split(":");
1164
+ if (parts.length !== 3) {
1165
+ return {
1166
+ ok: false,
1167
+ reason: `relation must be relation:<typeId>:<enSlug>:href or relation:<typeId>:<enSlug>:slug`
1168
+ };
1169
+ }
1170
+ const [targetTypeId, enSlug, mode] = parts;
1171
+ if (!targetTypeId || !enSlug) {
1172
+ return { ok: false, reason: `relation is missing a typeId or enSlug` };
1173
+ }
1174
+ if (mode !== "href" && mode !== "slug") {
1175
+ return { ok: false, reason: `relation mode must be "href" or "slug" (got "${mode}")` };
1176
+ }
1177
+ return {
1178
+ ok: true,
1179
+ token: {
1180
+ kind: "relation",
1181
+ targetTypeId,
1182
+ enSlug,
1183
+ mode
1184
+ }
1185
+ };
1186
+ }
1187
+ case "asset": {
1188
+ if (!rest.startsWith("/")) {
1189
+ return { ok: false, reason: `asset path must start with "/" (got "${rest}")` };
1190
+ }
1191
+ return { ok: true, token: { kind: "asset", webPath: rest } };
1192
+ }
1193
+ case "var": {
1194
+ if (!rest) return { ok: false, reason: `var is missing a key` };
1195
+ return { ok: true, token: { kind: "var", key: rest } };
1196
+ }
1197
+ default:
1198
+ return { ok: false, reason: `unknown token kind "${kind}"` };
1199
+ }
1200
+ }
1201
+ function extractInlineTokens(body) {
1202
+ const tokens = [];
1203
+ const malformed = [];
1204
+ let out = "";
1205
+ let i = 0;
1206
+ while (i < body.length) {
1207
+ const open = body.indexOf(TOKEN_OPEN, i);
1208
+ if (open === -1) {
1209
+ out += body.slice(i);
1210
+ break;
1211
+ }
1212
+ out += body.slice(i, open);
1213
+ const contentStart = open + TOKEN_OPEN.length;
1214
+ const end = findTokenEnd(body, contentStart);
1215
+ if (end === -1) {
1216
+ malformed.push({
1217
+ raw: body.slice(open),
1218
+ reason: `unterminated token (missing "}}")`,
1219
+ index: open
1220
+ });
1221
+ out += body.slice(open);
1222
+ break;
1223
+ }
1224
+ const raw = body.slice(open, end + 2);
1225
+ const inner = body.slice(contentStart, end);
1226
+ const parsed = parseTokenInner(inner);
1227
+ if (parsed.ok) {
1228
+ tokens.push({ ...parsed.token, raw });
1229
+ out += placeholderMarker(tokens.length);
1230
+ } else {
1231
+ malformed.push({ raw, reason: parsed.reason, index: open });
1232
+ out += raw;
1233
+ }
1234
+ i = end + 2;
1235
+ }
1236
+ return { placeholderBody: out, tokens, malformed };
1237
+ }
1238
+ function fillPlaceholders(body, resolvedValues) {
1239
+ return body.replace(/%%(\d+)%%/g, (match, n) => {
1240
+ const idx = Number(n) - 1;
1241
+ return idx >= 0 && idx < resolvedValues.length ? resolvedValues[idx] : match;
1242
+ });
1243
+ }
1244
+ function unescapeInlineTokens(body) {
1245
+ return body.split(ESCAPE_SEQUENCE).join(ESCAPE_RESULT);
1246
+ }
1247
+ function countMarkerOccurrences(body, n) {
1248
+ return body.split(placeholderMarker(n)).length - 1;
1249
+ }
1250
+ function replaceInlineSpans(body, opts) {
1251
+ let out = "";
1252
+ let i = 0;
1253
+ while (i < body.length) {
1254
+ if (body.startsWith(ESCAPE_SEQUENCE, i)) {
1255
+ out += opts.escape();
1256
+ i += ESCAPE_SEQUENCE.length;
1257
+ continue;
1258
+ }
1259
+ if (body.startsWith(TOKEN_OPEN, i)) {
1260
+ const end = findTokenEnd(body, i + TOKEN_OPEN.length);
1261
+ if (end !== -1) {
1262
+ const raw = body.slice(i, end + 2);
1263
+ const inner = body.slice(i + TOKEN_OPEN.length, end);
1264
+ out += opts.token(raw, inner);
1265
+ i = end + 2;
1266
+ continue;
1267
+ }
1268
+ }
1269
+ out += body[i];
1270
+ i += 1;
1271
+ }
1272
+ return out;
1273
+ }
1274
+ function maskInlineTokensForMdx(body) {
1275
+ return replaceInlineSpans(body, {
1276
+ token: () => "inline",
1277
+ escape: () => "$"
1278
+ });
1279
+ }
1280
+
1281
+ // src/inline/resolve-tokens.ts
1282
+ function slugKey(typeId, enSlug, locale) {
1283
+ return `${typeId}\0${enSlug}\0${locale}`;
1284
+ }
1285
+ function isStringRecord(value) {
1286
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1287
+ return Object.values(value).every((v) => typeof v === "string");
1288
+ }
1289
+ function createInlineResolver(config, options = {}) {
1290
+ const linkStyle = options.linkStyle ?? "app";
1291
+ const exportExtension = options.exportExtension ?? ".md";
1292
+ const urlBuilder = createUrlBuilder(config);
1293
+ const typeById = new Map(config.types.map((t) => [t.id, t]));
1294
+ const storePath = resolveStorePath(config);
1295
+ let slugCache = null;
1296
+ const localizedSlugIndex = () => {
1297
+ let mtime = 0;
1298
+ try {
1299
+ mtime = fs14__default.default.statSync(storePath).mtimeMs;
1300
+ } catch {
1301
+ mtime = 0;
1302
+ }
1303
+ if (slugCache && slugCache.mtime === mtime) return slugCache.index;
1304
+ const index = /* @__PURE__ */ new Map();
1305
+ try {
1306
+ const db = openStore(config, "readonly");
1307
+ try {
1308
+ for (const row of bulkLoadTranslations(db)) {
1309
+ index.set(slugKey(row.content_type, row.en_slug, row.locale), row.slug);
1310
+ }
1311
+ } finally {
1312
+ db.close();
1313
+ }
1314
+ } catch {
1315
+ }
1316
+ slugCache = { mtime, index };
1317
+ return index;
1318
+ };
1319
+ const localizedSlug2 = (typeId, enSlug, locale) => {
1320
+ if (locale === config.defaultLocale) return enSlug;
1321
+ const index = localizedSlugIndex();
1322
+ const direct = index.get(slugKey(typeId, enSlug, locale));
1323
+ if (direct) return direct;
1324
+ for (const fb of config.localeFallbacks?.[locale] ?? []) {
1325
+ const hit = index.get(slugKey(typeId, enSlug, fb));
1326
+ if (hit) return hit;
1327
+ }
1328
+ return enSlug;
1329
+ };
1330
+ return {
1331
+ resolve(token, enFrontmatter, locale) {
1332
+ switch (token.kind) {
1333
+ case "static":
1334
+ return token.text;
1335
+ case "var": {
1336
+ const vars = enFrontmatter.vars;
1337
+ if (isStringRecord(vars) && typeof vars[token.key] === "string") {
1338
+ return vars[token.key];
1339
+ }
1340
+ return "";
1341
+ }
1342
+ case "asset": {
1343
+ const assets = config.assets;
1344
+ return assets ? joinPublicPath(assets.publicPath, token.webPath) : token.webPath;
1345
+ }
1346
+ case "relation": {
1347
+ const type = typeById.get(token.targetTypeId);
1348
+ if (!type) return "";
1349
+ if (token.mode === "slug") return token.enSlug;
1350
+ if (!isRoutableType(type)) return "";
1351
+ const slug = localizedSlug2(token.targetTypeId, token.enSlug, locale);
1352
+ if (linkStyle === "export") {
1353
+ return urlBuilder.resolvePath(type.path, `${slug}${exportExtension}`, locale);
1354
+ }
1355
+ return type.path.replace("{slug}", slug);
1356
+ }
1357
+ }
1358
+ }
1359
+ };
1360
+ }
1361
+ function substituteEnInlineBody(rawBody, enFrontmatter, defaultLocale, resolver) {
1362
+ const { placeholderBody, tokens } = extractInlineTokens(rawBody);
1363
+ if (tokens.length === 0) return unescapeInlineTokens(placeholderBody);
1364
+ const values = tokens.map((t) => resolver.resolve(t, enFrontmatter, defaultLocale));
1365
+ return unescapeInlineTokens(fillPlaceholders(placeholderBody, values));
1366
+ }
1367
+ function fillTranslatedInlineBody(translatedBody, enRawBody, enFrontmatter, locale, resolver) {
1368
+ const { tokens } = extractInlineTokens(enRawBody);
1369
+ if (tokens.length === 0) return unescapeInlineTokens(translatedBody);
1370
+ const values = tokens.map((t) => resolver.resolve(t, enFrontmatter, locale));
1371
+ return unescapeInlineTokens(fillPlaceholders(translatedBody, values));
1372
+ }
1373
+
903
1374
  // src/loader/normalize-en.ts
904
1375
  function normalizeEnFrontmatter(data) {
905
1376
  const out = { ...data };
@@ -925,15 +1396,15 @@ function isPostFile(name) {
925
1396
  return isPublishableContentFile(name);
926
1397
  }
927
1398
  function listEnFiles(contentDir) {
928
- if (!fs2__default.default.existsSync(contentDir)) return [];
929
- return fs2__default.default.readdirSync(contentDir).filter(isPostFile).map((f) => path3__default.default.join(contentDir, f));
1399
+ if (!fs14__default.default.existsSync(contentDir)) return [];
1400
+ return fs14__default.default.readdirSync(contentDir).filter(isPostFile).map((f) => path3__default.default.join(contentDir, f));
930
1401
  }
931
1402
  function slugFromPath(filePath) {
932
1403
  return path3__default.default.basename(filePath).replace(/\.(md|mdx)$/, "");
933
1404
  }
934
1405
  function parseEnMdx(filePath, config, type) {
935
- const raw = fs2__default.default.readFileSync(filePath, "utf8");
936
- const parsed = matter__default.default(raw);
1406
+ const raw = fs14__default.default.readFileSync(filePath, "utf8");
1407
+ const parsed = matter4__default.default(raw);
937
1408
  const slug = slugFromPath(filePath);
938
1409
  const normalized = normalizeEnFrontmatter(parsed.data);
939
1410
  const { builtin, rest, issues: builtinIssues } = extractBuiltinEnFields(
@@ -971,6 +1442,7 @@ function parseEnMdx(filePath, config, type) {
971
1442
  updatedAt: builtin.updatedAt,
972
1443
  noindex: builtin.noindex,
973
1444
  canonicalPathOverride: builtin.canonicalPathOverride,
1445
+ vars: builtin.vars,
974
1446
  slug,
975
1447
  locale: config.defaultLocale
976
1448
  },
@@ -995,12 +1467,15 @@ function parseEnMdx(filePath, config, type) {
995
1467
  noindex: builtin.noindex,
996
1468
  canonicalPathOverride: builtin.canonicalPathOverride,
997
1469
  frontmatter,
998
- content: parsed.content,
1470
+ // Bodyless types (`body: false`) never carry a body: the loader skips the
1471
+ // MDX body entirely so runtimes, exports, and hashing all see an empty body.
1472
+ // A stray body is reported separately by `scribe validate`.
1473
+ content: type.body === false ? "" : parsed.content,
999
1474
  filePath
1000
1475
  };
1001
1476
  return { document: document2, issues };
1002
1477
  }
1003
- function buildDocumentFromTranslation(row, enDoc, type, config) {
1478
+ function buildDocumentFromTranslation(row, enDoc, type, config, inlineResolver) {
1004
1479
  const localeFm = JSON.parse(row.frontmatter_json);
1005
1480
  const merged = mergeStructuralOntoLocale(localeFm, enDoc.frontmatter, type.schema);
1006
1481
  const seo = seoFieldsFromEn(enDoc);
@@ -1011,6 +1486,14 @@ function buildDocumentFromTranslation(row, enDoc, type, config) {
1011
1486
  config.defaultLocale,
1012
1487
  config.localeRouting
1013
1488
  );
1489
+ const preparedBody = prepareTranslatedMdxBody(row.body).body;
1490
+ const content = inlineResolver ? fillTranslatedInlineBody(
1491
+ preparedBody,
1492
+ enDoc.content,
1493
+ enDoc.frontmatter,
1494
+ row.locale,
1495
+ inlineResolver
1496
+ ) : preparedBody;
1014
1497
  return {
1015
1498
  slug: row.slug,
1016
1499
  enSlug: row.en_slug,
@@ -1020,14 +1503,19 @@ function buildDocumentFromTranslation(row, enDoc, type, config) {
1020
1503
  noindex: seo.noindex,
1021
1504
  canonicalPathOverride: seo.canonicalPathOverride,
1022
1505
  frontmatter,
1023
- content: prepareTranslatedMdxBody(row.body).body
1506
+ content
1024
1507
  };
1025
1508
  }
1026
1509
  var DEV_REVALIDATE_MS = 1500;
1027
- function createContentLoader(config, type) {
1510
+ var contentVersion = 0;
1511
+ function bumpContentVersion() {
1512
+ contentVersion++;
1513
+ }
1514
+ function createContentLoader(config, type, options = {}) {
1028
1515
  let cached = null;
1029
1516
  let signature = "";
1030
1517
  let lastCheck = 0;
1518
+ let builtVersion = contentVersion;
1031
1519
  const contentDir = path3__default.default.join(
1032
1520
  /* turbopackIgnore: true */
1033
1521
  config.rootDir,
@@ -1035,18 +1523,34 @@ function createContentLoader(config, type) {
1035
1523
  );
1036
1524
  const storePath = resolveStorePath(config);
1037
1525
  const isProd = process.env.NODE_ENV === "production";
1526
+ const assets = config.assets;
1527
+ const assetFields = assets && options.resolveAssets ? listAssetFields(type.schema) : [];
1528
+ const resolveAssets = (doc) => {
1529
+ if (assetFields.length > 0 && assets) resolveDocumentAssets(doc, assetFields, assets);
1530
+ };
1531
+ const inlineResolver = options.inlineResolver;
1532
+ const resolveEnInline = (doc) => {
1533
+ if (inlineResolver) {
1534
+ doc.content = substituteEnInlineBody(
1535
+ doc.content,
1536
+ doc.frontmatter,
1537
+ config.defaultLocale,
1538
+ inlineResolver
1539
+ );
1540
+ }
1541
+ };
1038
1542
  function computeSignature() {
1039
1543
  const files = listEnFiles(contentDir);
1040
1544
  let newest = 0;
1041
1545
  for (const f of files) {
1042
1546
  try {
1043
- newest = Math.max(newest, fs2__default.default.statSync(f).mtimeMs);
1547
+ newest = Math.max(newest, fs14__default.default.statSync(f).mtimeMs);
1044
1548
  } catch {
1045
1549
  }
1046
1550
  }
1047
1551
  let store = 0;
1048
1552
  try {
1049
- store = fs2__default.default.statSync(storePath).mtimeMs;
1553
+ store = fs14__default.default.statSync(storePath).mtimeMs;
1050
1554
  } catch {
1051
1555
  }
1052
1556
  return `${files.length}:${newest}:${store}`;
@@ -1092,16 +1596,28 @@ function createContentLoader(config, type) {
1092
1596
  for (const row of rowsByLocale.get(locale) ?? []) {
1093
1597
  const enDoc = englishBySlug.get(row.en_slug);
1094
1598
  if (!enDoc) continue;
1095
- const doc = buildDocumentFromTranslation(row, enDoc, type, config);
1599
+ const doc = buildDocumentFromTranslation(row, enDoc, type, config, inlineResolver);
1600
+ resolveAssets(doc);
1096
1601
  bySlug.set(doc.slug, doc);
1097
1602
  byEnSlug.set(row.en_slug, doc);
1098
1603
  }
1099
1604
  out.set(locale, { bySlug, byEnSlug });
1100
1605
  }
1606
+ for (const doc of englishBySlug.values()) {
1607
+ resolveAssets(doc);
1608
+ resolveEnInline(doc);
1609
+ }
1101
1610
  return out;
1102
1611
  }
1103
1612
  return () => {
1104
1613
  if (cached) {
1614
+ if (contentVersion !== builtVersion) {
1615
+ cached = build();
1616
+ builtVersion = contentVersion;
1617
+ lastCheck = Date.now();
1618
+ signature = isProd ? "" : computeSignature();
1619
+ return cached;
1620
+ }
1105
1621
  if (isProd) return cached;
1106
1622
  const now = Date.now();
1107
1623
  if (now - lastCheck < DEV_REVALIDATE_MS) return cached;
@@ -1114,6 +1630,7 @@ function createContentLoader(config, type) {
1114
1630
  }
1115
1631
  lastCheck = Date.now();
1116
1632
  cached = build();
1633
+ builtVersion = contentVersion;
1117
1634
  signature = isProd ? "" : computeSignature();
1118
1635
  return cached;
1119
1636
  };
@@ -1126,7 +1643,7 @@ function readEnDocument(config, type, enSlug) {
1126
1643
  );
1127
1644
  for (const ext of [".mdx", ".md"]) {
1128
1645
  const filePath = path3__default.default.join(contentDir, `${enSlug}${ext}`);
1129
- if (!fs2__default.default.existsSync(filePath)) continue;
1646
+ if (!fs14__default.default.existsSync(filePath)) continue;
1130
1647
  const { document: document2 } = parseEnMdx(filePath, config, type);
1131
1648
  return document2;
1132
1649
  }
@@ -1135,7 +1652,9 @@ function readEnDocument(config, type, enSlug) {
1135
1652
  function getTranslatablePayload(doc, type) {
1136
1653
  return {
1137
1654
  frontmatter: pickTranslatable(doc.frontmatter, type.schema),
1138
- body: doc.content
1655
+ // Bodyless types never contribute a body to any translation payload, hash,
1656
+ // or snapshot — regardless of what a document's `content` happens to hold.
1657
+ body: type.body === false ? "" : doc.content
1139
1658
  };
1140
1659
  }
1141
1660
 
@@ -1223,8 +1742,11 @@ function comparatorFor(orderBy) {
1223
1742
  return (a, b) => a.slug.localeCompare(b.slug);
1224
1743
  }
1225
1744
  }
1226
- function buildRuntime(config, type, getRuntime) {
1227
- const load = createContentLoader(config, type);
1745
+ function buildRuntime(config, type, getRuntime, options = {}) {
1746
+ const load = createContentLoader(config, type, {
1747
+ resolveAssets: options.resolveAssets,
1748
+ inlineResolver: options.inlineResolver
1749
+ });
1228
1750
  const relationFields = new Map(
1229
1751
  listRelationFields(type.schema).filter((f) => f.path.length === 1).map((f) => [f.path[0], f])
1230
1752
  );
@@ -1241,12 +1763,12 @@ function buildRuntime(config, type, getRuntime) {
1241
1763
  id: type.id,
1242
1764
  config: type,
1243
1765
  load,
1244
- list(locale = config.defaultLocale, options = {}) {
1766
+ list(locale = config.defaultLocale, options2 = {}) {
1245
1767
  const idx = load().get(locale);
1246
1768
  if (!idx) return [];
1247
1769
  const docs = Array.from(idx.bySlug.values());
1248
- docs.sort(comparatorFor(options.orderBy ?? type.orderBy ?? "slug"));
1249
- return options.limit !== void 0 ? docs.slice(0, options.limit) : docs;
1770
+ docs.sort(comparatorFor(options2.orderBy ?? type.orderBy ?? "slug"));
1771
+ return options2.limit !== void 0 ? docs.slice(0, options2.limit) : docs;
1250
1772
  },
1251
1773
  get(slug, locale = config.defaultLocale) {
1252
1774
  return load().get(locale)?.bySlug.get(slug) ?? null;
@@ -1259,7 +1781,7 @@ function buildRuntime(config, type, getRuntime) {
1259
1781
  load(),
1260
1782
  type,
1261
1783
  config.localeRouting,
1262
- config.localeFallbacks[locale] ?? []
1784
+ config.localeFallbacks?.[locale] ?? []
1263
1785
  );
1264
1786
  if (result.document && type.path) {
1265
1787
  return {
@@ -1273,15 +1795,15 @@ function buildRuntime(config, type, getRuntime) {
1273
1795
  }
1274
1796
  return result;
1275
1797
  },
1276
- staticParams(options = {}) {
1798
+ staticParams(options2 = {}) {
1277
1799
  assertRoutable("staticParams");
1278
1800
  const all = load();
1279
1801
  const enIdx = all.get(config.defaultLocale);
1280
1802
  if (!enIdx) return [];
1281
1803
  const params = [];
1282
- for (const locale of options.locales ?? config.locales) {
1804
+ for (const locale of options2.locales ?? config.locales) {
1283
1805
  const localeIdx = all.get(locale);
1284
- const fallbacks = config.localeFallbacks[locale] ?? [];
1806
+ const fallbacks = config.localeFallbacks?.[locale] ?? [];
1285
1807
  for (const doc of enIdx.bySlug.values()) {
1286
1808
  let slug;
1287
1809
  if (locale === config.defaultLocale) {
@@ -1360,7 +1882,7 @@ function buildRuntime(config, type, getRuntime) {
1360
1882
  };
1361
1883
  return runtime;
1362
1884
  }
1363
- function createProject(config) {
1885
+ function createProject(config, options = {}) {
1364
1886
  const runtimes = /* @__PURE__ */ new Map();
1365
1887
  const getRuntime = (id) => {
1366
1888
  const runtime = runtimes.get(id);
@@ -1369,8 +1891,18 @@ function createProject(config) {
1369
1891
  }
1370
1892
  return runtime;
1371
1893
  };
1894
+ const inlineResolver = options.resolveInlineTokens ? createInlineResolver(config, {
1895
+ linkStyle: options.inlineLinkStyle,
1896
+ exportExtension: options.exportLinkExtension
1897
+ }) : void 0;
1372
1898
  for (const type of config.types) {
1373
- runtimes.set(type.id, buildRuntime(config, type, getRuntime));
1899
+ runtimes.set(
1900
+ type.id,
1901
+ buildRuntime(config, type, getRuntime, {
1902
+ resolveAssets: options.resolveAssets,
1903
+ inlineResolver
1904
+ })
1905
+ );
1374
1906
  }
1375
1907
  return {
1376
1908
  config,
@@ -1387,12 +1919,12 @@ function createProject(config) {
1387
1919
  }
1388
1920
  function enFileExists(config, type, enSlug) {
1389
1921
  const dir = path3__default.default.join(config.rootDir, type.contentDir);
1390
- return fs2__default.default.existsSync(path3__default.default.join(dir, `${enSlug}.mdx`)) || fs2__default.default.existsSync(path3__default.default.join(dir, `${enSlug}.md`));
1922
+ return fs14__default.default.existsSync(path3__default.default.join(dir, `${enSlug}.mdx`)) || fs14__default.default.existsSync(path3__default.default.join(dir, `${enSlug}.md`));
1391
1923
  }
1392
1924
  function listEnSlugs(rootDir, contentDir) {
1393
1925
  const dir = path3__default.default.join(rootDir, contentDir);
1394
- if (!fs2__default.default.existsSync(dir)) return [];
1395
- return fs2__default.default.readdirSync(dir).filter(isPublishableContentFile).map((f) => f.replace(/\.(md|mdx)$/, ""));
1926
+ if (!fs14__default.default.existsSync(dir)) return [];
1927
+ return fs14__default.default.readdirSync(dir).filter(isPublishableContentFile).map((f) => f.replace(/\.(md|mdx)$/, ""));
1396
1928
  }
1397
1929
 
1398
1930
  // src/i18n/translation-index.ts
@@ -1488,10 +2020,10 @@ function redirectsFilePath(config, type) {
1488
2020
  }
1489
2021
  function loadTypeRedirectsFile(config, type) {
1490
2022
  const filePath = redirectsFilePath(config, type);
1491
- if (!fs2__default.default.existsSync(filePath)) return null;
2023
+ if (!fs14__default.default.existsSync(filePath)) return null;
1492
2024
  let raw;
1493
2025
  try {
1494
- raw = JSON.parse(fs2__default.default.readFileSync(filePath, "utf8"));
2026
+ raw = JSON.parse(fs14__default.default.readFileSync(filePath, "utf8"));
1495
2027
  } catch (error) {
1496
2028
  throw new Error(
1497
2029
  `${type.id}: failed to parse ${TYPE_REDIRECTS_FILENAME}: ${error instanceof Error ? error.message : String(error)}`
@@ -1799,8 +2331,8 @@ function getRedirectSourceSlugs(project) {
1799
2331
  // src/sitemap/join-base-url.ts
1800
2332
  function joinBaseUrl(baseUrl, pathname) {
1801
2333
  const origin = baseUrl.replace(/\/$/, "");
1802
- const path13 = pathname.startsWith("/") ? pathname : `/${pathname}`;
1803
- return `${origin}${path13}`;
2334
+ const path15 = pathname.startsWith("/") ? pathname : `/${pathname}`;
2335
+ return `${origin}${path15}`;
1804
2336
  }
1805
2337
 
1806
2338
  // src/sitemap/generate-sitemap.ts
@@ -1885,7 +2417,11 @@ async function generateSitemap(project, options) {
1885
2417
  // src/create-scribe.ts
1886
2418
  function createScribe(input) {
1887
2419
  const config = resolveConfig(input);
1888
- const project = createProject(config);
2420
+ const project = createProject(config, {
2421
+ resolveAssets: true,
2422
+ resolveInlineTokens: true,
2423
+ inlineLinkStyle: "app"
2424
+ });
1889
2425
  const scribe = {
1890
2426
  config,
1891
2427
  project,
@@ -1894,6 +2430,17 @@ function createScribe(input) {
1894
2430
  listRoutableTypes: project.listRoutableTypes,
1895
2431
  sitemap(options) {
1896
2432
  return generateSitemap(project, options);
2433
+ },
2434
+ assets: {
2435
+ url(ref, opts) {
2436
+ if (opts && Object.keys(opts).length > 0) {
2437
+ throw new Error(
2438
+ `scribe.assets.url: options are reserved for a future pipeline; got ${Object.keys(opts).join(", ")}`
2439
+ );
2440
+ }
2441
+ const assetsConfig = config.assets;
2442
+ return assetsConfig ? joinPublicPath(assetsConfig.publicPath, ref) : ref;
2443
+ }
1897
2444
  }
1898
2445
  };
1899
2446
  for (const type of config.types) {
@@ -1920,7 +2467,7 @@ function findConfigPath(cwd) {
1920
2467
  )
1921
2468
  ];
1922
2469
  for (const candidate of candidates) {
1923
- if (fs2__default.default.existsSync(candidate) && fs2__default.default.statSync(candidate).isFile()) {
2470
+ if (fs14__default.default.existsSync(candidate) && fs14__default.default.statSync(candidate).isFile()) {
1924
2471
  return candidate;
1925
2472
  }
1926
2473
  }
@@ -1972,7 +2519,7 @@ function validateTypeRedirects(project) {
1972
2519
  const globalFrom = /* @__PURE__ */ new Map();
1973
2520
  for (const type of project.config.types) {
1974
2521
  const filePath = path3__default.default.join(project.config.rootDir, type.contentDir, TYPE_REDIRECTS_FILENAME);
1975
- if (!fs2__default.default.existsSync(filePath)) continue;
2522
+ if (!fs14__default.default.existsSync(filePath)) continue;
1976
2523
  let loaded;
1977
2524
  try {
1978
2525
  loaded = loadTypeRedirectsFile(project.config, type);
@@ -2125,8 +2672,8 @@ function buildEnSlugIndex(config) {
2125
2672
  }
2126
2673
  function listEnSlugsForType(rootDir, contentDir) {
2127
2674
  const dir = path3__default.default.join(rootDir, contentDir);
2128
- if (!fs2__default.default.existsSync(dir)) return [];
2129
- return fs2__default.default.readdirSync(dir).filter(isPublishableContentFile).map((f) => f.replace(/\.(md|mdx)$/, ""));
2675
+ if (!fs14__default.default.existsSync(dir)) return [];
2676
+ return fs14__default.default.readdirSync(dir).filter(isPublishableContentFile).map((f) => f.replace(/\.(md|mdx)$/, ""));
2130
2677
  }
2131
2678
  function validateRelations(project) {
2132
2679
  const { config } = project;
@@ -2234,13 +2781,14 @@ function collectImagePaths(frontmatter, body) {
2234
2781
  function assetFilePath(assetsPath, webPath) {
2235
2782
  return path3__default.default.join(assetsPath, webPath.replace(/^\//, ""));
2236
2783
  }
2237
- function validateDocumentAssets(config, input) {
2784
+ function validateDocumentAssets(config, input, skipPaths) {
2238
2785
  const assetsPath = config.assetsPath;
2239
2786
  if (!assetsPath) return [];
2240
2787
  const issues = [];
2241
2788
  for (const webPath of collectImagePaths(input.frontmatter, input.body)) {
2789
+ if (skipPaths?.has(webPath)) continue;
2242
2790
  const filePath = assetFilePath(assetsPath, webPath);
2243
- if (fs2__default.default.existsSync(filePath)) continue;
2791
+ if (fs14__default.default.existsSync(filePath)) continue;
2244
2792
  issues.push({
2245
2793
  level: "warning",
2246
2794
  contentType: input.contentType,
@@ -2252,6 +2800,115 @@ function validateDocumentAssets(config, input) {
2252
2800
  }
2253
2801
  return issues;
2254
2802
  }
2803
+ function collectAssetValues(container, path15, out, fieldPathSoFar = []) {
2804
+ const [head, ...rest] = path15;
2805
+ if (head === void 0) return;
2806
+ if (typeof container !== "object" || container === null || Array.isArray(container)) return;
2807
+ const record = container;
2808
+ if (rest.length === 0) {
2809
+ const value = record[head];
2810
+ out.push({
2811
+ fieldPath: [...fieldPathSoFar, head].join("."),
2812
+ value: typeof value === "string" ? value : void 0
2813
+ });
2814
+ return;
2815
+ }
2816
+ if (rest[0] === "*") {
2817
+ const arr = record[head];
2818
+ if (!Array.isArray(arr)) {
2819
+ out.push({ fieldPath: [...fieldPathSoFar, head, "*", ...rest.slice(1)].join("."), value: void 0 });
2820
+ return;
2821
+ }
2822
+ arr.forEach((item) => {
2823
+ collectAssetValues(item, rest.slice(1), out, [...fieldPathSoFar, head, "*"]);
2824
+ });
2825
+ return;
2826
+ }
2827
+ collectAssetValues(record[head], rest, out, [...fieldPathSoFar, head]);
2828
+ }
2829
+ function normalizeDir(dir) {
2830
+ return `/${dir.replace(/^\/+|\/+$/g, "")}`;
2831
+ }
2832
+ function validateDeclaredAssetFields(config, input) {
2833
+ const assetsPath = config.assetsPath;
2834
+ if (!assetsPath) return [];
2835
+ const issues = [];
2836
+ const attrib = (fieldPath, level, message) => issues.push({
2837
+ level,
2838
+ contentType: input.contentType,
2839
+ enSlug: input.enSlug,
2840
+ locale: input.locale,
2841
+ field: fieldPath,
2842
+ message
2843
+ });
2844
+ for (const f of listAssetFields(input.schema)) {
2845
+ const locations = [];
2846
+ collectAssetValues(input.frontmatter, f.path, locations);
2847
+ for (const { fieldPath, value } of locations) {
2848
+ let effective = value;
2849
+ if (effective === void 0 && f.assetTemplate) {
2850
+ effective = f.assetTemplate.split("{slug}").join(input.enSlug);
2851
+ }
2852
+ if (effective === void 0) {
2853
+ if (!f.assetOptional) {
2854
+ attrib(fieldPath, "error", `${input.contentType}/${input.enSlug}: ${fieldPath} is required but missing`);
2855
+ }
2856
+ continue;
2857
+ }
2858
+ if (f.assetDir) {
2859
+ const dir = normalizeDir(f.assetDir);
2860
+ if (!(effective === dir || effective.startsWith(`${dir}/`))) {
2861
+ attrib(
2862
+ fieldPath,
2863
+ "error",
2864
+ `${input.contentType}/${input.enSlug}: ${fieldPath} value ${effective} is outside declared dir ${dir}`
2865
+ );
2866
+ }
2867
+ }
2868
+ const filePath = assetFilePath(assetsPath, effective);
2869
+ if (!fs14__default.default.existsSync(filePath)) {
2870
+ attrib(fieldPath, "error", `${input.contentType}/${input.enSlug}: ${fieldPath} \u2192 ${effective} not found`);
2871
+ continue;
2872
+ }
2873
+ if (f.assetFormats && f.assetFormats.length > 0) {
2874
+ const ext = path3__default.default.extname(effective).slice(1).toLowerCase();
2875
+ if (!f.assetFormats.includes(ext)) {
2876
+ attrib(
2877
+ fieldPath,
2878
+ "warning",
2879
+ `${input.contentType}/${input.enSlug}: ${fieldPath} \u2192 ${effective} extension .${ext} not in formats [${f.assetFormats.join(", ")}]`
2880
+ );
2881
+ }
2882
+ }
2883
+ if (f.assetMaxKB !== void 0) {
2884
+ try {
2885
+ const sizeKB = fs14__default.default.statSync(filePath).size / 1024;
2886
+ if (sizeKB > f.assetMaxKB) {
2887
+ attrib(
2888
+ fieldPath,
2889
+ "warning",
2890
+ `${input.contentType}/${input.enSlug}: ${fieldPath} \u2192 ${effective} is ${Math.round(sizeKB)}KB, over the ${f.assetMaxKB}KB budget`
2891
+ );
2892
+ }
2893
+ } catch {
2894
+ }
2895
+ }
2896
+ }
2897
+ }
2898
+ return issues;
2899
+ }
2900
+ function collectDeclaredAssetPaths(frontmatter, enSlug, schema, fields) {
2901
+ const out = /* @__PURE__ */ new Set();
2902
+ for (const f of listAssetFields(schema)) {
2903
+ const locations = [];
2904
+ collectAssetValues(frontmatter, f.path, locations);
2905
+ for (const { value } of locations) {
2906
+ if (value !== void 0) out.add(value);
2907
+ else if (f.assetTemplate) out.add(f.assetTemplate.split("{slug}").join(enSlug));
2908
+ }
2909
+ }
2910
+ return out;
2911
+ }
2255
2912
 
2256
2913
  // src/core/localized-slug.ts
2257
2914
  function findLocaleSuffixInSlug(slug, localeCodes) {
@@ -2294,15 +2951,151 @@ function validateTranslationSlugSuffixes(config, db) {
2294
2951
  }
2295
2952
  return issues;
2296
2953
  }
2954
+ function listEnSlugs3(rootDir, contentDir) {
2955
+ const dir = path3__default.default.join(rootDir, contentDir);
2956
+ if (!fs14__default.default.existsSync(dir)) return [];
2957
+ return fs14__default.default.readdirSync(dir).filter(isPublishableContentFile).map((f) => f.replace(/\.(md|mdx)$/, ""));
2958
+ }
2959
+ function isStringRecord2(value) {
2960
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2961
+ return Object.values(value).every((v) => typeof v === "string");
2962
+ }
2963
+ function assetFileExists(config, webPath) {
2964
+ const assetsPath = config.assetsPath;
2965
+ if (!assetsPath) return true;
2966
+ return fs14__default.default.existsSync(path3__default.default.join(assetsPath, webPath.replace(/^\//, "")));
2967
+ }
2968
+ function validateInlineTokens(config) {
2969
+ const issues = [];
2970
+ const slugIndex = buildEnSlugIndex(config);
2971
+ const typeIds = new Set(config.types.map((t) => t.id));
2972
+ const typeById = new Map(config.types.map((t) => [t.id, t]));
2973
+ for (const type of config.types) {
2974
+ for (const enSlug of listEnSlugs3(config.rootDir, type.contentDir)) {
2975
+ const doc = readEnDocument(config, type, enSlug);
2976
+ if (!doc) continue;
2977
+ const { tokens, malformed } = extractInlineTokens(doc.content);
2978
+ for (const bad of malformed) {
2979
+ issues.push({
2980
+ level: "error",
2981
+ contentType: type.id,
2982
+ enSlug,
2983
+ field: "body",
2984
+ message: `Malformed inline token (${bad.reason}): ${bad.raw}`
2985
+ });
2986
+ }
2987
+ let varsReported = false;
2988
+ const vars = doc.frontmatter.vars;
2989
+ for (const token of tokens) {
2990
+ switch (token.kind) {
2991
+ case "static":
2992
+ break;
2993
+ case "relation": {
2994
+ if (!typeIds.has(token.targetTypeId)) {
2995
+ issues.push({
2996
+ level: "error",
2997
+ contentType: type.id,
2998
+ enSlug,
2999
+ field: "body",
3000
+ message: `Inline relation token targets unknown type "${token.targetTypeId}"`
3001
+ });
3002
+ break;
3003
+ }
3004
+ const targetSlugs = slugIndex.get(token.targetTypeId) ?? /* @__PURE__ */ new Set();
3005
+ if (!targetSlugs.has(token.enSlug)) {
3006
+ issues.push({
3007
+ level: "error",
3008
+ contentType: type.id,
3009
+ enSlug,
3010
+ field: "body",
3011
+ message: `Inline relation token references "${token.enSlug}", but no ${token.targetTypeId} doc has that slug`
3012
+ });
3013
+ break;
3014
+ }
3015
+ if (token.mode === "href") {
3016
+ const targetType = typeById.get(token.targetTypeId);
3017
+ if (!isRoutableType(targetType)) {
3018
+ issues.push({
3019
+ level: "error",
3020
+ contentType: type.id,
3021
+ enSlug,
3022
+ field: "body",
3023
+ message: `Inline relation token resolves a URL for "${token.targetTypeId}", which has no path template (not routable)`
3024
+ });
3025
+ }
3026
+ }
3027
+ break;
3028
+ }
3029
+ case "asset": {
3030
+ if (!assetFileExists(config, token.webPath)) {
3031
+ issues.push({
3032
+ level: "error",
3033
+ contentType: type.id,
3034
+ enSlug,
3035
+ field: "body",
3036
+ message: `Inline asset token references ${token.webPath}, which is missing on disk`
3037
+ });
3038
+ }
3039
+ break;
3040
+ }
3041
+ case "var": {
3042
+ if (vars !== void 0 && !isStringRecord2(vars)) {
3043
+ if (!varsReported) {
3044
+ varsReported = true;
3045
+ issues.push({
3046
+ level: "error",
3047
+ contentType: type.id,
3048
+ enSlug,
3049
+ field: "vars",
3050
+ message: `Frontmatter "vars" must be a string-to-string map`
3051
+ });
3052
+ }
3053
+ break;
3054
+ }
3055
+ if (!isStringRecord2(vars) || !(token.key in vars)) {
3056
+ issues.push({
3057
+ level: "error",
3058
+ contentType: type.id,
3059
+ enSlug,
3060
+ field: "body",
3061
+ message: `Inline var token references "${token.key}", absent from this document's vars map`
3062
+ });
3063
+ }
3064
+ break;
3065
+ }
3066
+ }
3067
+ }
3068
+ }
3069
+ }
3070
+ return issues;
3071
+ }
2297
3072
 
2298
3073
  // src/validate/validate-project.ts
2299
- function listEnSlugs3(rootDir, contentDir) {
3074
+ function listEnSlugs4(rootDir, contentDir) {
2300
3075
  const dir = path3__default.default.join(rootDir, contentDir);
2301
- if (!fs2__default.default.existsSync(dir)) return [];
2302
- return fs2__default.default.readdirSync(dir).filter(isPublishableContentFile).map((f) => f.replace(/\.(md|mdx)$/, ""));
3076
+ if (!fs14__default.default.existsSync(dir)) return [];
3077
+ return fs14__default.default.readdirSync(dir).filter(isPublishableContentFile).map((f) => f.replace(/\.(md|mdx)$/, ""));
3078
+ }
3079
+ function validateBodylessEntry(issues, config, type, enSlug) {
3080
+ const contentDir = path3__default.default.join(config.rootDir, type.contentDir);
3081
+ for (const ext of [".mdx", ".md"]) {
3082
+ const filePath = path3__default.default.join(contentDir, `${enSlug}${ext}`);
3083
+ if (!fs14__default.default.existsSync(filePath)) continue;
3084
+ const body = matter4__default.default(fs14__default.default.readFileSync(filePath, "utf8")).content;
3085
+ if (body.trim().length > 0) {
3086
+ issues.push({
3087
+ level: "error",
3088
+ contentType: type.id,
3089
+ enSlug,
3090
+ field: "body",
3091
+ message: `type "${type.id}" is frontmatter-only (body: false) but the entry has body content`
3092
+ });
3093
+ }
3094
+ return;
3095
+ }
2303
3096
  }
2304
3097
  function validateDocumentMdxBody(issues, input) {
2305
- const preparedBody = prepareTranslatedMdxBody(input.body).body;
3098
+ const preparedBody = prepareTranslatedMdxBody(maskInlineTokensForMdx(input.body)).body;
2306
3099
  const mdxValidation = validateMdxBody(preparedBody);
2307
3100
  if (!mdxValidation.ok) {
2308
3101
  issues.push({
@@ -2319,7 +3112,7 @@ function validateProject(config) {
2319
3112
  const issues = [];
2320
3113
  const project = createProject(config);
2321
3114
  const storePath = project.storePath;
2322
- if (!fs2__default.default.existsSync(storePath)) {
3115
+ if (!fs14__default.default.existsSync(storePath)) {
2323
3116
  issues.push({
2324
3117
  level: "error",
2325
3118
  message: `Missing store.sqlite at ${storePath}`
@@ -2328,7 +3121,7 @@ function validateProject(config) {
2328
3121
  }
2329
3122
  const db = openStore(config, "readonly");
2330
3123
  for (const type of config.types) {
2331
- const enSlugs = listEnSlugs3(config.rootDir, type.contentDir);
3124
+ const enSlugs = listEnSlugs4(config.rootDir, type.contentDir);
2332
3125
  const englishSlugs = new Set(enSlugs);
2333
3126
  if (!type.translate && isRoutableType(type)) {
2334
3127
  issues.push({
@@ -2365,20 +3158,41 @@ function validateProject(config) {
2365
3158
  message: issue.message
2366
3159
  });
2367
3160
  }
2368
- for (const issue of validateDocumentAssets(config, {
3161
+ for (const issue of validateDeclaredAssetFields(config, {
2369
3162
  contentType: type.id,
2370
3163
  enSlug,
2371
3164
  frontmatter: enDoc.frontmatter,
2372
- body: enDoc.content
3165
+ schema: type.schema
2373
3166
  })) {
2374
3167
  issues.push(issue);
2375
3168
  }
2376
- validateDocumentMdxBody(issues, {
2377
- contentType: type.id,
3169
+ const declaredAssetPaths = collectDeclaredAssetPaths(
3170
+ enDoc.frontmatter,
2378
3171
  enSlug,
2379
- locale: config.defaultLocale,
2380
- body: enDoc.content
2381
- });
3172
+ type.schema
3173
+ );
3174
+ for (const issue of validateDocumentAssets(
3175
+ config,
3176
+ {
3177
+ contentType: type.id,
3178
+ enSlug,
3179
+ frontmatter: enDoc.frontmatter,
3180
+ body: enDoc.content
3181
+ },
3182
+ declaredAssetPaths
3183
+ )) {
3184
+ issues.push(issue);
3185
+ }
3186
+ if (type.body === false) {
3187
+ validateBodylessEntry(issues, config, type, enSlug);
3188
+ } else {
3189
+ validateDocumentMdxBody(issues, {
3190
+ contentType: type.id,
3191
+ enSlug,
3192
+ locale: config.defaultLocale,
3193
+ body: enDoc.content
3194
+ });
3195
+ }
2382
3196
  for (const locale of config.locales) {
2383
3197
  if (locale === config.defaultLocale) continue;
2384
3198
  const row = getTranslation(db, type.id, enSlug, locale);
@@ -2395,21 +3209,27 @@ function validateProject(config) {
2395
3209
  });
2396
3210
  }
2397
3211
  const preparedBody = prepareTranslatedMdxBody(row.body).body;
2398
- for (const issue of validateDocumentAssets(config, {
2399
- contentType: type.id,
2400
- enSlug,
2401
- locale,
2402
- frontmatter: localeFm,
2403
- body: preparedBody
2404
- })) {
3212
+ for (const issue of validateDocumentAssets(
3213
+ config,
3214
+ {
3215
+ contentType: type.id,
3216
+ enSlug,
3217
+ locale,
3218
+ frontmatter: localeFm,
3219
+ body: preparedBody
3220
+ },
3221
+ declaredAssetPaths
3222
+ )) {
2405
3223
  issues.push(issue);
2406
3224
  }
2407
- validateDocumentMdxBody(issues, {
2408
- contentType: type.id,
2409
- enSlug,
2410
- locale,
2411
- body: row.body
2412
- });
3225
+ if (type.body !== false) {
3226
+ validateDocumentMdxBody(issues, {
3227
+ contentType: type.id,
3228
+ enSlug,
3229
+ locale,
3230
+ body: row.body
3231
+ });
3232
+ }
2413
3233
  }
2414
3234
  }
2415
3235
  try {
@@ -2435,6 +3255,9 @@ function validateProject(config) {
2435
3255
  message: issue.message
2436
3256
  });
2437
3257
  }
3258
+ for (const issue of validateInlineTokens(config)) {
3259
+ issues.push(issue);
3260
+ }
2438
3261
  const dbForSuffix = openStore(config, "readonly");
2439
3262
  try {
2440
3263
  for (const issue of validateTranslationSlugSuffixes(config, dbForSuffix)) {
@@ -2459,6 +3282,10 @@ function computePageEnHash(translatableFrontmatter, body) {
2459
3282
  const payload = JSON.stringify({ frontmatter: translatableFrontmatter, body });
2460
3283
  return sha256(payload);
2461
3284
  }
3285
+ function computeTranslationEnHash(translatableFrontmatter, body) {
3286
+ const { placeholderBody } = extractInlineTokens(body);
3287
+ return computePageEnHash(translatableFrontmatter, placeholderBody);
3288
+ }
2462
3289
 
2463
3290
  // src/translate/worklist.ts
2464
3291
  function parseContentTypeFilter(contentType) {
@@ -2466,10 +3293,10 @@ function parseContentTypeFilter(contentType) {
2466
3293
  const ids = contentType.split(",").map((id) => id.trim()).filter(Boolean);
2467
3294
  return ids.length > 0 ? new Set(ids) : void 0;
2468
3295
  }
2469
- function listEnSlugs4(rootDir, contentDir) {
3296
+ function listEnSlugs5(rootDir, contentDir) {
2470
3297
  const dir = path3__default.default.join(rootDir, contentDir);
2471
- if (!fs2__default.default.existsSync(dir)) return [];
2472
- return fs2__default.default.readdirSync(dir).filter(isPublishableContentFile).map((f) => f.replace(/\.(md|mdx)$/, ""));
3298
+ if (!fs14__default.default.existsSync(dir)) return [];
3299
+ return fs14__default.default.readdirSync(dir).filter(isPublishableContentFile).map((f) => f.replace(/\.(md|mdx)$/, ""));
2473
3300
  }
2474
3301
  function buildWorklist(config, options = {}) {
2475
3302
  const db = openStore(config, "readonly");
@@ -2478,12 +3305,16 @@ function buildWorklist(config, options = {}) {
2478
3305
  const contentTypes = parseContentTypeFilter(options.contentType);
2479
3306
  for (const type of config.types) {
2480
3307
  if (contentTypes && !contentTypes.has(type.id)) continue;
2481
- const enSlugs = options.enSlug ? [options.enSlug] : listEnSlugs4(config.rootDir, type.contentDir);
3308
+ if (!isTypeTranslatable(type)) {
3309
+ options.onSkipType?.(type);
3310
+ continue;
3311
+ }
3312
+ const enSlugs = options.enSlug ? [options.enSlug] : listEnSlugs5(config.rootDir, type.contentDir);
2482
3313
  for (const enSlug of enSlugs) {
2483
3314
  const enDoc = readEnDocument(config, type, enSlug);
2484
3315
  if (!enDoc) continue;
2485
3316
  const payload = getTranslatablePayload(enDoc, type);
2486
- const currentEnHash = computePageEnHash(payload.frontmatter, payload.body);
3317
+ const currentEnHash = computeTranslationEnHash(payload.frontmatter, payload.body);
2487
3318
  for (const locale of locales) {
2488
3319
  if (locale === config.defaultLocale) continue;
2489
3320
  const existing = getTranslation(db, type.id, enSlug, locale);
@@ -2945,9 +3776,22 @@ function buildTranslatableSubschema(schema) {
2945
3776
  if (Object.keys(out).length === 0) return null;
2946
3777
  return zod.z.object(out);
2947
3778
  }
2948
- function buildGeminiResponseSchema(schema, slugStrategy) {
3779
+ function buildTranslatableSubschemaForPayload(schema, translatableFrontmatter) {
3780
+ const full = buildTranslatableSubschema(schema);
3781
+ if (!full) return null;
3782
+ const filtered = {};
3783
+ for (const [key, childSchema] of Object.entries(full.shape)) {
3784
+ if (!(key in translatableFrontmatter)) continue;
3785
+ const value = translatableFrontmatter[key];
3786
+ if (value === void 0 || value === null) continue;
3787
+ filtered[key] = childSchema;
3788
+ }
3789
+ if (Object.keys(filtered).length === 0) return null;
3790
+ return zod.z.object(filtered);
3791
+ }
3792
+ function buildGeminiResponseSchema(schema, slugStrategy, translatableFrontmatter) {
2949
3793
  try {
2950
- const translatable = buildTranslatableSubschema(schema);
3794
+ const translatable = translatableFrontmatter !== void 0 ? buildTranslatableSubschemaForPayload(schema, translatableFrontmatter) : buildTranslatableSubschema(schema);
2951
3795
  const responseShape = {
2952
3796
  ...translatable ? { frontmatter: translatable } : {},
2953
3797
  body: zod.z.string()
@@ -2969,9 +3813,12 @@ function buildGeminiResponseSchema(schema, slugStrategy) {
2969
3813
 
2970
3814
  // src/translate/resolve-translate-config.ts
2971
3815
  var BUILTIN_TRANSLATE_RULES = [
3816
+ "Placeholders written as %%1%%, %%2%%, %%3%% (double percent signs around a number) are immutable. Reproduce each placeholder that appears in the source EXACTLY as-is, exactly once, and never translate, edit, renumber, or add spaces inside it. You may move a placeholder to a different position within its sentence when the target grammar requires it.",
2972
3817
  "Do not translate brand or product names unless the brand has a well-known localized name in the target market (rare). Keep the original spelling and capitalization.",
2973
3818
  "Return the MDX body with real line breaks; do not use JSON escape sequences like \\n or \\t in the body string.",
2974
- 'In JSX attributes (e.g. FaqItem question="..."), use single quotes when the value contains double-quote characters (e.g. Hebrew \u05D3\u05D5\u05D0"\u05DC), or escape them as \\".'
3819
+ 'In JSX attributes (e.g. FaqItem question="..."), use single quotes when the value contains double-quote characters (e.g. Hebrew \u05D3\u05D5\u05D0"\u05DC), or escape them as \\".',
3820
+ "Match the EN source format: when the EN body uses Markdown/MDX (headings, paragraphs, GFM tables, links), keep that structure in the translation. Do not convert markdown elements into raw HTML (<p>, <h2>, <table>, etc.).",
3821
+ "Otherwise match the format and components used in the EN source."
2975
3822
  ];
2976
3823
  function slugStrategyRules(slugStrategy) {
2977
3824
  if (slugStrategy === "localized") {
@@ -3015,12 +3862,13 @@ function sanitizeTranslatedFrontmatter(rawFrontmatter, schema) {
3015
3862
  return pickTranslatable(rawFrontmatter, schema);
3016
3863
  }
3017
3864
  function validateTranslatedFrontmatter(enDoc, localeFrontmatter, typeSchema) {
3018
- const frontmatter = sanitizeTranslatedFrontmatter(localeFrontmatter, typeSchema);
3019
- const merged = mergeStructuralOntoLocale(
3020
- frontmatter,
3021
- enDoc.frontmatter,
3865
+ const enFrontmatter = enDoc.frontmatter;
3866
+ const frontmatter = pruneOrphanNestedTranslations(
3867
+ sanitizeTranslatedFrontmatter(localeFrontmatter, typeSchema),
3868
+ enFrontmatter,
3022
3869
  typeSchema
3023
3870
  );
3871
+ const merged = mergeStructuralOntoLocale(frontmatter, enFrontmatter, typeSchema);
3024
3872
  const parsed = typeSchema.safeParse(merged);
3025
3873
  if (!parsed.success) {
3026
3874
  return { ok: false, error: formatZodIssues(parsed.error) };
@@ -3069,6 +3917,22 @@ function formatTranslateError(error) {
3069
3917
  }
3070
3918
  return message.length > 160 ? `${message.slice(0, 157)}\u2026` : message;
3071
3919
  }
3920
+ function verifyInlineMarkers(enRawBody, translatedBody) {
3921
+ const { tokens } = extractInlineTokens(enRawBody);
3922
+ if (tokens.length === 0) return;
3923
+ const missing = [];
3924
+ const duplicated = [];
3925
+ for (let i = 1; i <= tokens.length; i++) {
3926
+ const count = countMarkerOccurrences(translatedBody, i);
3927
+ if (count === 0) missing.push(placeholderMarker(i));
3928
+ else if (count > 1) duplicated.push(placeholderMarker(i));
3929
+ }
3930
+ if (missing.length === 0 && duplicated.length === 0) return;
3931
+ const parts = [];
3932
+ if (missing.length > 0) parts.push(`missing ${missing.join(", ")}`);
3933
+ if (duplicated.length > 0) parts.push(`duplicated ${duplicated.join(", ")}`);
3934
+ throw new Error(`Inline token markers mismatch: ${parts.join("; ")}`);
3935
+ }
3072
3936
  function resolveContextLabel(enDoc, enSlug) {
3073
3937
  const fm = enDoc.frontmatter;
3074
3938
  for (const key of ["title", "name", "h1"]) {
@@ -3090,7 +3954,8 @@ function prepareTranslation(config, item, options, startedAt) {
3090
3954
  const enDoc = readEnDocument(config, type, item.enSlug);
3091
3955
  if (!enDoc) throw new Error(`EN document not found: ${item.enSlug}`);
3092
3956
  const payload = getTranslatablePayload(enDoc, type);
3093
- const currentEnHash = computePageEnHash(payload.frontmatter, payload.body);
3957
+ const { placeholderBody } = extractInlineTokens(payload.body);
3958
+ const currentEnHash = computeTranslationEnHash(payload.frontmatter, payload.body);
3094
3959
  const db = openStore(config, "readonly");
3095
3960
  const existing = getTranslation(db, type.id, item.enSlug, item.locale);
3096
3961
  db.close();
@@ -3112,11 +3977,15 @@ function prepareTranslation(config, item, options, startedAt) {
3112
3977
  targetLocale: item.locale,
3113
3978
  contextLabel: resolveContextLabel(enDoc, item.enSlug),
3114
3979
  translatableFrontmatter: payload.frontmatter,
3115
- enBody: payload.body,
3980
+ enBody: placeholderBody,
3116
3981
  slugStrategy: type.slugStrategy,
3117
3982
  previousError: item.previousError
3118
3983
  });
3119
- const responseSchema = buildGeminiResponseSchema(type.schema, type.slugStrategy);
3984
+ const responseSchema = buildGeminiResponseSchema(
3985
+ type.schema,
3986
+ type.slugStrategy,
3987
+ payload.frontmatter
3988
+ );
3120
3989
  return {
3121
3990
  status: "ready",
3122
3991
  prepared: {
@@ -3144,9 +4013,8 @@ function finalizeTranslation(config, prepared, output, options) {
3144
4013
  if (!validated.ok) {
3145
4014
  throw new Error(`Translation validation failed: ${validated.error}`);
3146
4015
  }
3147
- const { body: translatedBody, adjusted: mdxAdjusted } = assertValidTranslatedMdxBody(
3148
- output.parsed.body
3149
- );
4016
+ const { body: translatedBody, adjusted: mdxAdjusted } = type.body === false ? { body: "", adjusted: false } : assertValidTranslatedMdxBody(output.parsed.body);
4017
+ verifyInlineMarkers(payload.body, translatedBody);
3150
4018
  const writeDb = openStore(config, "readwrite");
3151
4019
  const snapshotId = options.snapshotId ?? recordEnSnapshot(
3152
4020
  config,
@@ -3860,7 +4728,7 @@ async function resumeTranslationJobs(config, options = {}) {
3860
4728
  return results;
3861
4729
  }
3862
4730
  function serializeMdx(frontmatter, content) {
3863
- return matter__default.default.stringify(content, frontmatter);
4731
+ return matter4__default.default.stringify(content, frontmatter);
3864
4732
  }
3865
4733
 
3866
4734
  // src/export/build-static-raw-exports.ts
@@ -3927,8 +4795,8 @@ function buildStaticRawExports(project, options = {}) {
3927
4795
  return out;
3928
4796
  }
3929
4797
  function rmDirIfExists(dir) {
3930
- if (fs2__default.default.existsSync(dir)) {
3931
- fs2__default.default.rmSync(dir, { recursive: true, force: true });
4798
+ if (fs14__default.default.existsSync(dir)) {
4799
+ fs14__default.default.rmSync(dir, { recursive: true, force: true });
3932
4800
  }
3933
4801
  }
3934
4802
  function writeStaticRawExports(project, options = {}) {
@@ -3944,8 +4812,8 @@ function writeStaticRawExports(project, options = {}) {
3944
4812
  const counts = /* @__PURE__ */ new Map();
3945
4813
  for (const item of exports) {
3946
4814
  const filePath = path3__default.default.join(outDir, item.relativePath);
3947
- fs2__default.default.mkdirSync(path3__default.default.dirname(filePath), { recursive: true });
3948
- fs2__default.default.writeFileSync(filePath, item.source, "utf8");
4815
+ fs14__default.default.mkdirSync(path3__default.default.dirname(filePath), { recursive: true });
4816
+ fs14__default.default.writeFileSync(filePath, item.source, "utf8");
3949
4817
  const key = `${item.typeId}/${item.locale}`;
3950
4818
  counts.set(key, (counts.get(key) ?? 0) + 1);
3951
4819
  }
@@ -3955,7 +4823,411 @@ function writeStaticRawExports(project, options = {}) {
3955
4823
  return { exports, written: exports.length };
3956
4824
  }
3957
4825
 
4826
+ // src/delete/plan.ts
4827
+ function isPlanBlocked(plan) {
4828
+ return plan.blocked.length > 0;
4829
+ }
4830
+ function deletedDocs(plan) {
4831
+ return [
4832
+ ...plan.roots.map((r) => ({ typeId: r.typeId, enSlug: r.enSlug })),
4833
+ ...plan.cascades.map((c) => ({ typeId: c.typeId, enSlug: c.enSlug }))
4834
+ ];
4835
+ }
4836
+ function docKey(typeId, enSlug) {
4837
+ return `${typeId}\0${enSlug}`;
4838
+ }
4839
+ function relationSlugsAt(frontmatter, path15) {
4840
+ const out = [];
4841
+ const walk = (container, remaining) => {
4842
+ const [head, ...rest] = remaining;
4843
+ if (head === void 0) return;
4844
+ if (typeof container !== "object" || container === null || Array.isArray(container)) return;
4845
+ const record = container;
4846
+ if (rest.length === 0) {
4847
+ const value = record[head];
4848
+ if (Array.isArray(value)) {
4849
+ for (const slug of value) if (typeof slug === "string" && slug) out.push(slug);
4850
+ } else if (typeof value === "string" && value) {
4851
+ out.push(value);
4852
+ }
4853
+ return;
4854
+ }
4855
+ if (rest[0] === "*") {
4856
+ const arr = record[head];
4857
+ if (Array.isArray(arr)) for (const item of arr) walk(item, rest.slice(1));
4858
+ return;
4859
+ }
4860
+ walk(record[head], rest);
4861
+ };
4862
+ walk(frontmatter, path15);
4863
+ return out;
4864
+ }
4865
+ function assetValuesAt(frontmatter, field2, enSlug) {
4866
+ const out = [];
4867
+ const walk = (container, remaining) => {
4868
+ const [head, ...rest] = remaining;
4869
+ if (head === void 0) return;
4870
+ if (typeof container !== "object" || container === null || Array.isArray(container)) return;
4871
+ const record = container;
4872
+ if (rest.length === 0) {
4873
+ const value = record[head];
4874
+ if (typeof value === "string" && value) out.push(value);
4875
+ else if (value === void 0 && field2.assetTemplate) {
4876
+ out.push(field2.assetTemplate.split("{slug}").join(enSlug));
4877
+ }
4878
+ return;
4879
+ }
4880
+ if (rest[0] === "*") {
4881
+ const arr = record[head];
4882
+ if (Array.isArray(arr)) for (const item of arr) walk(item, rest.slice(1));
4883
+ return;
4884
+ }
4885
+ walk(record[head], rest);
4886
+ };
4887
+ walk(frontmatter, field2.path);
4888
+ return out;
4889
+ }
4890
+ function buildDeletionPlan(project, typeId, enSlug) {
4891
+ const rootType = (() => {
4892
+ try {
4893
+ return project.getType(typeId);
4894
+ } catch {
4895
+ return null;
4896
+ }
4897
+ })();
4898
+ if (!rootType) {
4899
+ throw new Error(`Unknown content type "${typeId}"`);
4900
+ }
4901
+ const rootDoc = rootType.get(enSlug);
4902
+ if (!rootDoc) {
4903
+ throw new Error(`No ${typeId} entry "${enSlug}"`);
4904
+ }
4905
+ const docByKey = /* @__PURE__ */ new Map();
4906
+ const relationFieldsByType = /* @__PURE__ */ new Map();
4907
+ const assetFieldsByType = /* @__PURE__ */ new Map();
4908
+ const referrers = /* @__PURE__ */ new Map();
4909
+ const assetRefs = /* @__PURE__ */ new Map();
4910
+ const bodyRelationRefs = [];
4911
+ for (const type of project.listTypes()) {
4912
+ const relFields = listRelationFields(type.config.schema);
4913
+ const assetFields = listAssetFields(type.config.schema);
4914
+ relationFieldsByType.set(type.id, relFields);
4915
+ assetFieldsByType.set(type.id, assetFields);
4916
+ for (const doc of type.list()) {
4917
+ const frontmatter = doc.frontmatter;
4918
+ docByKey.set(docKey(type.id, doc.enSlug), {
4919
+ typeId: type.id,
4920
+ enSlug: doc.enSlug,
4921
+ frontmatter
4922
+ });
4923
+ for (const field2 of relFields) {
4924
+ const target = field2.relationTarget;
4925
+ if (!target) continue;
4926
+ for (const slug of relationSlugsAt(frontmatter, field2.path)) {
4927
+ const list = referrers.get(docKey(target, slug)) ?? [];
4928
+ list.push({
4929
+ typeId: type.id,
4930
+ enSlug: doc.enSlug,
4931
+ fieldPath: field2.path.join("."),
4932
+ multiple: Boolean(field2.relationMultiple),
4933
+ optional: Boolean(field2.relationOptional),
4934
+ onTargetDelete: field2.relationOnTargetDelete ?? "restrict"
4935
+ });
4936
+ referrers.set(docKey(target, slug), list);
4937
+ }
4938
+ }
4939
+ for (const field2 of assetFields) {
4940
+ for (const webPath of assetValuesAt(frontmatter, field2, doc.enSlug)) {
4941
+ const set = assetRefs.get(webPath) ?? /* @__PURE__ */ new Set();
4942
+ set.add(docKey(type.id, doc.enSlug));
4943
+ assetRefs.set(webPath, set);
4944
+ }
4945
+ }
4946
+ for (const token of extractInlineTokens(doc.content).tokens) {
4947
+ if (token.kind === "relation") {
4948
+ bodyRelationRefs.push({
4949
+ typeId: type.id,
4950
+ enSlug: doc.enSlug,
4951
+ targetTypeId: token.targetTypeId,
4952
+ targetEnSlug: token.enSlug
4953
+ });
4954
+ }
4955
+ }
4956
+ }
4957
+ }
4958
+ const deleted = /* @__PURE__ */ new Map();
4959
+ deleted.set(docKey(typeId, enSlug), { typeId, enSlug });
4960
+ const queue = [{ typeId, enSlug }];
4961
+ while (queue.length > 0) {
4962
+ const current = queue.shift();
4963
+ for (const ref of referrers.get(docKey(current.typeId, current.enSlug)) ?? []) {
4964
+ if (ref.onTargetDelete !== "cascade") continue;
4965
+ const refKey = docKey(ref.typeId, ref.enSlug);
4966
+ if (deleted.has(refKey)) continue;
4967
+ deleted.set(refKey, {
4968
+ typeId: ref.typeId,
4969
+ enSlug: ref.enSlug,
4970
+ via: `${ref.fieldPath}=${current.enSlug}`
4971
+ });
4972
+ queue.push({ typeId: ref.typeId, enSlug: ref.enSlug });
4973
+ }
4974
+ }
4975
+ const detaches = [];
4976
+ const blocked = [];
4977
+ const seenDetach = /* @__PURE__ */ new Set();
4978
+ const seenBlock = /* @__PURE__ */ new Set();
4979
+ for (const del of deleted.values()) {
4980
+ for (const ref of referrers.get(docKey(del.typeId, del.enSlug)) ?? []) {
4981
+ if (deleted.has(docKey(ref.typeId, ref.enSlug))) continue;
4982
+ if (ref.onTargetDelete === "restrict") {
4983
+ const k = `${ref.typeId}\0${ref.enSlug}\0${ref.fieldPath}\0restrict`;
4984
+ if (!seenBlock.has(k)) {
4985
+ seenBlock.add(k);
4986
+ blocked.push({
4987
+ typeId: ref.typeId,
4988
+ enSlug: ref.enSlug,
4989
+ fieldPath: ref.fieldPath,
4990
+ reason: "restrict"
4991
+ });
4992
+ }
4993
+ } else if (ref.onTargetDelete === "detach") {
4994
+ const requiredSingle = !ref.multiple && !ref.optional;
4995
+ if (requiredSingle) {
4996
+ const k = `${ref.typeId}\0${ref.enSlug}\0${ref.fieldPath}\0required-single`;
4997
+ if (!seenBlock.has(k)) {
4998
+ seenBlock.add(k);
4999
+ blocked.push({
5000
+ typeId: ref.typeId,
5001
+ enSlug: ref.enSlug,
5002
+ fieldPath: ref.fieldPath,
5003
+ reason: "required-single"
5004
+ });
5005
+ }
5006
+ } else {
5007
+ const k = `${ref.typeId}\0${ref.enSlug}\0${ref.fieldPath}\0${del.enSlug}`;
5008
+ if (!seenDetach.has(k)) {
5009
+ seenDetach.add(k);
5010
+ detaches.push({
5011
+ typeId: ref.typeId,
5012
+ enSlug: ref.enSlug,
5013
+ fieldPath: ref.fieldPath,
5014
+ removedSlug: del.enSlug
5015
+ });
5016
+ }
5017
+ }
5018
+ }
5019
+ }
5020
+ }
5021
+ const assets = [];
5022
+ const seenAsset = /* @__PURE__ */ new Set();
5023
+ for (const del of deleted.values()) {
5024
+ const record = docByKey.get(docKey(del.typeId, del.enSlug));
5025
+ if (!record) continue;
5026
+ for (const field2 of assetFieldsByType.get(del.typeId) ?? []) {
5027
+ for (const webPath of assetValuesAt(record.frontmatter, field2, del.enSlug)) {
5028
+ const dedupeKey = `${del.typeId}\0${del.enSlug}\0${webPath}`;
5029
+ if (seenAsset.has(dedupeKey)) continue;
5030
+ seenAsset.add(dedupeKey);
5031
+ if (field2.assetOnDelete === "keep") {
5032
+ assets.push({
5033
+ path: webPath,
5034
+ ownerTypeId: del.typeId,
5035
+ ownerEnSlug: del.enSlug,
5036
+ action: "keep",
5037
+ reason: "config-keep"
5038
+ });
5039
+ continue;
5040
+ }
5041
+ const refs = assetRefs.get(webPath) ?? /* @__PURE__ */ new Set();
5042
+ let sharedOutside = false;
5043
+ for (const owner of refs) {
5044
+ if (!deleted.has(owner)) {
5045
+ sharedOutside = true;
5046
+ break;
5047
+ }
5048
+ }
5049
+ assets.push(
5050
+ sharedOutside ? {
5051
+ path: webPath,
5052
+ ownerTypeId: del.typeId,
5053
+ ownerEnSlug: del.enSlug,
5054
+ action: "keep",
5055
+ reason: "shared"
5056
+ } : {
5057
+ path: webPath,
5058
+ ownerTypeId: del.typeId,
5059
+ ownerEnSlug: del.enSlug,
5060
+ action: "delete"
5061
+ }
5062
+ );
5063
+ }
5064
+ }
5065
+ }
5066
+ const store = [];
5067
+ try {
5068
+ const db = openStore(project.config, "readonly");
5069
+ try {
5070
+ for (const del of deleted.values()) {
5071
+ store.push({
5072
+ typeId: del.typeId,
5073
+ enSlug: del.enSlug,
5074
+ translations: countTranslationsForEnSlug(db, del.typeId, del.enSlug),
5075
+ snapshots: countEnSnapshotsForEnSlug(db, del.typeId, del.enSlug)
5076
+ });
5077
+ }
5078
+ } finally {
5079
+ db.close();
5080
+ }
5081
+ } catch {
5082
+ for (const del of deleted.values()) {
5083
+ store.push({ typeId: del.typeId, enSlug: del.enSlug, translations: 0, snapshots: 0 });
5084
+ }
5085
+ }
5086
+ const rootTitle = (() => {
5087
+ const title = rootDoc.frontmatter.title;
5088
+ return typeof title === "string" && title.trim() ? title : void 0;
5089
+ })();
5090
+ const cascades = [];
5091
+ for (const del of deleted.values()) {
5092
+ if (del.typeId === typeId && del.enSlug === enSlug) continue;
5093
+ cascades.push({ typeId: del.typeId, enSlug: del.enSlug, via: del.via ?? "" });
5094
+ }
5095
+ const bodyRefWarnings = bodyRelationRefs.filter(
5096
+ (ref) => deleted.has(docKey(ref.targetTypeId, ref.targetEnSlug)) && !deleted.has(docKey(ref.typeId, ref.enSlug))
5097
+ );
5098
+ return {
5099
+ roots: [{ typeId, enSlug, title: rootTitle }],
5100
+ cascades,
5101
+ detaches,
5102
+ blocked,
5103
+ assets,
5104
+ store,
5105
+ bodyRefWarnings
5106
+ };
5107
+ }
5108
+ function enFilePath(rootDir, contentDir, enSlug) {
5109
+ for (const ext of [".mdx", ".md"]) {
5110
+ const candidate = path3__default.default.join(rootDir, contentDir, `${enSlug}${ext}`);
5111
+ if (fs14__default.default.existsSync(candidate)) return candidate;
5112
+ }
5113
+ return null;
5114
+ }
5115
+ function rewriteFrontmatter(raw, data) {
5116
+ const match = raw.match(/^()?---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(\r?\n|$)/);
5117
+ if (!match) {
5118
+ throw new Error("Cannot rewrite frontmatter: no leading YAML block found");
5119
+ }
5120
+ const bom = match[1] ?? "";
5121
+ const body = raw.slice(match[0].length);
5122
+ const serialized = matter4__default.default.stringify("", data);
5123
+ const blockMatch = serialized.match(/^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*\r?\n/);
5124
+ const block = blockMatch ? blockMatch[0] : serialized;
5125
+ return `${bom}${block}${body}`;
5126
+ }
5127
+ function removeSlugAtPath(container, remaining, removedSlug, multiple) {
5128
+ const [head, ...rest] = remaining;
5129
+ if (head === void 0) return;
5130
+ if (typeof container !== "object" || container === null || Array.isArray(container)) return;
5131
+ const record = container;
5132
+ if (rest.length === 0) {
5133
+ if (multiple) {
5134
+ const value = record[head];
5135
+ if (Array.isArray(value)) {
5136
+ record[head] = value.filter((slug) => slug !== removedSlug);
5137
+ }
5138
+ } else if (record[head] === removedSlug) {
5139
+ delete record[head];
5140
+ }
5141
+ return;
5142
+ }
5143
+ if (rest[0] === "*") {
5144
+ const arr = record[head];
5145
+ if (Array.isArray(arr)) {
5146
+ for (const item of arr) removeSlugAtPath(item, rest.slice(1), removedSlug, multiple);
5147
+ }
5148
+ return;
5149
+ }
5150
+ removeSlugAtPath(record[head], rest, removedSlug, multiple);
5151
+ }
5152
+ function executeDeletionPlan(project, plan) {
5153
+ if (isPlanBlocked(plan)) {
5154
+ throw new Error("Refusing to execute a blocked deletion plan");
5155
+ }
5156
+ const config = project.config;
5157
+ const result = {
5158
+ deletedFiles: [],
5159
+ deletedAssets: [],
5160
+ detachedFiles: [],
5161
+ translationsDeleted: 0,
5162
+ snapshotsDeleted: 0
5163
+ };
5164
+ const detachesByFile = /* @__PURE__ */ new Map();
5165
+ for (const detach of plan.detaches) {
5166
+ const key = `${detach.typeId} ${detach.enSlug}`;
5167
+ const list = detachesByFile.get(key) ?? [];
5168
+ list.push(detach);
5169
+ detachesByFile.set(key, list);
5170
+ }
5171
+ for (const [, detaches] of detachesByFile) {
5172
+ const { typeId, enSlug } = detaches[0];
5173
+ const type = project.getType(typeId);
5174
+ const file = enFilePath(config.rootDir, type.config.contentDir, enSlug);
5175
+ if (!file) continue;
5176
+ const fieldByPath = new Map(
5177
+ listRelationFields(type.config.schema).map((f) => [f.path.join("."), f])
5178
+ );
5179
+ const raw = fs14__default.default.readFileSync(file, "utf8");
5180
+ const data = structuredClone(matter4__default.default(raw).data);
5181
+ for (const detach of detaches) {
5182
+ const field2 = fieldByPath.get(detach.fieldPath);
5183
+ if (!field2) continue;
5184
+ removeSlugAtPath(
5185
+ data,
5186
+ detach.fieldPath.split("."),
5187
+ detach.removedSlug,
5188
+ Boolean(field2.relationMultiple)
5189
+ );
5190
+ }
5191
+ fs14__default.default.writeFileSync(file, rewriteFrontmatter(raw, data), "utf8");
5192
+ result.detachedFiles.push(file);
5193
+ }
5194
+ const assetsDir = config.assets?.assetsPath ?? config.assetsPath;
5195
+ for (const asset of plan.assets) {
5196
+ if (asset.action !== "delete") continue;
5197
+ if (!assetsDir) continue;
5198
+ const root = path3__default.default.resolve(assetsDir);
5199
+ const relative = asset.path.replace(/^\/+/, "");
5200
+ const abs = path3__default.default.resolve(root, relative);
5201
+ const rootWithSep = root.endsWith(path3__default.default.sep) ? root : root + path3__default.default.sep;
5202
+ if (abs !== root && !abs.startsWith(rootWithSep)) continue;
5203
+ if (fs14__default.default.existsSync(abs)) {
5204
+ fs14__default.default.rmSync(abs, { force: true });
5205
+ result.deletedAssets.push(abs);
5206
+ }
5207
+ }
5208
+ for (const doc of deletedDocs(plan)) {
5209
+ const type = project.getType(doc.typeId);
5210
+ const file = enFilePath(config.rootDir, type.config.contentDir, doc.enSlug);
5211
+ if (file && fs14__default.default.existsSync(file)) {
5212
+ fs14__default.default.rmSync(file, { force: true });
5213
+ result.deletedFiles.push(file);
5214
+ }
5215
+ }
5216
+ const db = openStore(config, "readwrite");
5217
+ try {
5218
+ for (const doc of deletedDocs(plan)) {
5219
+ result.translationsDeleted += deleteTranslationsForEnSlug(db, doc.typeId, doc.enSlug);
5220
+ result.snapshotsDeleted += deleteEnSnapshotsForEnSlug(db, doc.typeId, doc.enSlug);
5221
+ }
5222
+ } finally {
5223
+ db.close();
5224
+ }
5225
+ bumpContentVersion();
5226
+ return result;
5227
+ }
5228
+
3958
5229
  exports.buildAllContentRedirects = buildAllContentRedirects;
5230
+ exports.buildDeletionPlan = buildDeletionPlan;
3959
5231
  exports.buildStaticRawExports = buildStaticRawExports;
3960
5232
  exports.buildWorklist = buildWorklist;
3961
5233
  exports.createProject = createProject;
@@ -3963,23 +5235,36 @@ exports.createScribe = createScribe;
3963
5235
  exports.createUrlBuilder = createUrlBuilder;
3964
5236
  exports.defineConfig = defineConfig;
3965
5237
  exports.defineContentType = defineContentType;
5238
+ exports.executeDeletionPlan = executeDeletionPlan;
3966
5239
  exports.exportDirSegment = exportDirSegment;
5240
+ exports.extractInlineTokens = extractInlineTokens;
3967
5241
  exports.field = field;
5242
+ exports.fillPlaceholders = fillPlaceholders;
3968
5243
  exports.findConfigPath = findConfigPath;
3969
5244
  exports.generateSitemap = generateSitemap;
5245
+ exports.getAssetMeta = getAssetMeta;
3970
5246
  exports.getFieldKind = getFieldKind;
5247
+ exports.getManagedRoots = getManagedRoots;
3971
5248
  exports.getRedirectSourceSlugs = getRedirectSourceSlugs;
3972
5249
  exports.getRelationTarget = getRelationTarget;
3973
5250
  exports.getStaticExportRoots = getStaticExportRoots;
5251
+ exports.introspectSchema = introspectSchema;
3974
5252
  exports.isResolvedConfig = isResolvedConfig;
3975
5253
  exports.isRoutableType = isRoutableType;
5254
+ exports.isTypeTranslatable = isTypeTranslatable;
5255
+ exports.listAssetFields = listAssetFields;
5256
+ exports.listRelationFields = listRelationFields;
5257
+ exports.listTranslatableFields = listTranslatableFields;
3976
5258
  exports.loadConfigSync = loadConfigSync;
5259
+ exports.placeholderMarker = placeholderMarker;
3977
5260
  exports.resolveConfig = resolveConfig;
3978
5261
  exports.resolveLocalesFromPreset = resolveLocalesFromPreset;
3979
5262
  exports.resumeTranslationJobs = resumeTranslationJobs;
3980
5263
  exports.serializeMdx = serializeMdx;
5264
+ exports.templateManagedRoot = templateManagedRoot;
3981
5265
  exports.translatePage = translatePage;
3982
5266
  exports.translateWorklist = translateWorklist;
5267
+ exports.unescapeInlineTokens = unescapeInlineTokens;
3983
5268
  exports.unwrapSchema = unwrapSchema;
3984
5269
  exports.validateProject = validateProject;
3985
5270
  exports.writeStaticRawExports = writeStaticRawExports;