@conloca/content-api 0.2.0 → 0.2.2

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 (74) hide show
  1. package/dist/asset-metadata-store.d.ts.map +1 -1
  2. package/dist/asset-operations.d.ts +20 -34
  3. package/dist/asset-operations.d.ts.map +1 -1
  4. package/dist/asset-operations.js +219 -166
  5. package/dist/asset-operations.js.map +1 -1
  6. package/dist/asset-usage.d.ts +5 -4
  7. package/dist/asset-usage.d.ts.map +1 -1
  8. package/dist/asset-usage.js +6 -5
  9. package/dist/asset-usage.js.map +1 -1
  10. package/dist/cf-access.d.ts +4 -2
  11. package/dist/cf-access.d.ts.map +1 -1
  12. package/dist/cf-access.js +29 -13
  13. package/dist/cf-access.js.map +1 -1
  14. package/dist/component-registry.d.ts +0 -3
  15. package/dist/component-registry.d.ts.map +1 -1
  16. package/dist/content-file-id.d.ts +9 -0
  17. package/dist/content-file-id.d.ts.map +1 -0
  18. package/dist/content-file-id.js +33 -0
  19. package/dist/content-file-id.js.map +1 -0
  20. package/dist/content-operations.js +2 -2
  21. package/dist/content-operations.js.map +1 -1
  22. package/dist/content-path.d.ts +5 -0
  23. package/dist/content-path.d.ts.map +1 -1
  24. package/dist/content-path.js +7 -0
  25. package/dist/content-path.js.map +1 -1
  26. package/dist/filesystem-content-api.d.ts +0 -15
  27. package/dist/filesystem-content-api.d.ts.map +1 -1
  28. package/dist/filesystem-content-api.js +60 -17
  29. package/dist/filesystem-content-api.js.map +1 -1
  30. package/dist/git-operations.d.ts.map +1 -1
  31. package/dist/git-operations.js +162 -34
  32. package/dist/git-operations.js.map +1 -1
  33. package/dist/index.d.ts +1 -1
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +0 -1
  36. package/dist/index.js.map +1 -1
  37. package/dist/middleware.d.ts +2 -0
  38. package/dist/middleware.d.ts.map +1 -1
  39. package/dist/middleware.js +21 -31
  40. package/dist/middleware.js.map +1 -1
  41. package/dist/schemas/index.d.ts +9 -97
  42. package/dist/schemas/index.d.ts.map +1 -1
  43. package/dist/schemas/index.js +8 -83
  44. package/dist/schemas/index.js.map +1 -1
  45. package/dist/schemas/normalize.d.ts +101 -0
  46. package/dist/schemas/normalize.d.ts.map +1 -0
  47. package/dist/schemas/normalize.js +168 -0
  48. package/dist/schemas/normalize.js.map +1 -0
  49. package/dist/schemas/types.d.ts +135 -0
  50. package/dist/schemas/types.d.ts.map +1 -0
  51. package/dist/schemas/types.js +17 -0
  52. package/dist/schemas/types.js.map +1 -0
  53. package/dist/schemas/validators.d.ts +46 -0
  54. package/dist/schemas/validators.d.ts.map +1 -0
  55. package/dist/schemas/validators.js +938 -0
  56. package/dist/schemas/validators.js.map +1 -0
  57. package/dist/types.d.ts +7 -0
  58. package/dist/types.d.ts.map +1 -1
  59. package/package.json +12 -5
  60. package/src/asset-operations.ts +260 -187
  61. package/src/asset-usage.ts +6 -5
  62. package/src/cf-access.ts +30 -14
  63. package/src/content-file-id.ts +31 -0
  64. package/src/content-operations.ts +2 -2
  65. package/src/content-path.ts +8 -0
  66. package/src/filesystem-content-api.ts +72 -17
  67. package/src/git-operations.ts +188 -41
  68. package/src/index.ts +17 -1
  69. package/src/middleware.ts +23 -37
  70. package/src/schemas/index.ts +34 -108
  71. package/src/schemas/normalize.ts +194 -0
  72. package/src/schemas/types.ts +154 -0
  73. package/src/schemas/validators.ts +176 -0
  74. package/src/types.ts +7 -0
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The entry id a complete content file declares, for callers that hold a
3
+ * repository path rather than a content-layout one (a file a commit removed)
4
+ * and must name the entry the index knew it by.
5
+ *
6
+ * Its own subpath, apart from `./indexing`: that chunk evaluates WASM-backed
7
+ * hashing at import time, which a runtime that forbids compiling WASM from
8
+ * bytes refuses. This module imports only the frontmatter parser.
9
+ */
10
+ import matter from 'gray-matter';
11
+
12
+ const textDecoder = new TextDecoder();
13
+
14
+ /**
15
+ * The id `parseContentHeader` would index the file under, read the same way:
16
+ * YAML frontmatter through gray-matter (fresh options, so no memo cache) for
17
+ * `.mdx`, the top-level `id` of the JSON document for `.json` and `.vxjson`
18
+ * (canonicalizing a complete VXJSON file keeps that field as it is). Null for
19
+ * a non-content file, an unparseable one, or one that declares no id.
20
+ */
21
+ export function contentFileId(path: string, bytes: Uint8Array): string | null {
22
+ const text = textDecoder.decode(bytes);
23
+ let id: unknown;
24
+ try {
25
+ if (path.endsWith('.mdx')) id = matter(text, {}).data.id;
26
+ else if (path.endsWith('.json') || path.endsWith('.vxjson')) id = (JSON.parse(text) as { id?: unknown } | null)?.id;
27
+ } catch {
28
+ return null;
29
+ }
30
+ return typeof id === 'string' && id !== '' ? id : null;
31
+ }
@@ -1,5 +1,5 @@
1
1
  import sortKeys from 'sort-keys';
2
- import { isContentLocale } from './content-path.js';
2
+ import { invalidLocaleMessage, isContentLocale } from './content-path.js';
3
3
  import { generateContentId, isContentPublished, normalizeAndValidatePathname } from './content-utils.js';
4
4
  import type { Fragments } from './fragments.js';
5
5
  import type { Site } from './site.js';
@@ -309,7 +309,7 @@ export function checkEntryPlace(collection: string | undefined, locales: string[
309
309
  return {
310
310
  valid: false,
311
311
  reason: 'invalid_locale',
312
- error: `Invalid locale: ${malformed}. A locale is a two-letter language code, optionally with a region, like en or en-US.`,
312
+ error: invalidLocaleMessage(malformed),
313
313
  field: 'locales',
314
314
  };
315
315
  }
@@ -37,6 +37,14 @@ export function isContentLocale(locale: string): boolean {
37
37
  return LOCALE.test(locale);
38
38
  }
39
39
 
40
+ /**
41
+ * Why `locale` cannot name content files, in the words every refusal of one uses: creating an
42
+ * entry in it, a sites.json that declares it, and `conloca doctor`.
43
+ */
44
+ export function invalidLocaleMessage(locale: string): string {
45
+ return `Invalid locale: ${locale}. A locale is a two-letter language code, optionally with a region, like en or en-US.`;
46
+ }
47
+
40
48
  /** `<base>.<locale>.<ext>` — the filename half of every content layout. */
41
49
  const LOCALE_FILENAME = new RegExp(`^(.+)\\.(${LOCALE_SUBTAG})\\.(mdx|vxjson|json)$`);
42
50
 
@@ -21,7 +21,13 @@ import {
21
21
  validateAndPrepareMetadata,
22
22
  validateCreateContent,
23
23
  } from './content-operations.js';
24
- import { type ContentPathLayout, parseContentPathLayout, parseLocaleFilename } from './content-path.js';
24
+ import {
25
+ type ContentPathLayout,
26
+ invalidLocaleMessage,
27
+ isContentLocale,
28
+ parseContentPathLayout,
29
+ parseLocaleFilename,
30
+ } from './content-path.js';
25
31
  import {
26
32
  applyMetaPatch,
27
33
  localesOf,
@@ -86,6 +92,13 @@ function ensureError(error: unknown): Error {
86
92
  // Reusable TextDecoder instance - safe to reuse as it's stateless
87
93
  const textDecoder = new TextDecoder();
88
94
 
95
+ /**
96
+ * Where the read repair moves a fragment saved straight into fragments/: the
97
+ * folder the editor saves new fragments to, which every conlocaFragments(...)
98
+ * call in a site's content config declares, so the moved fragment still builds.
99
+ */
100
+ const REPAIRED_FRAGMENT_COLLECTION = 'fragments';
101
+
89
102
  async function readFilePrefix(filePath: string, buffer: Uint8Array): Promise<number> {
90
103
  const handle = await open(filePath, 'r');
91
104
  try {
@@ -229,14 +242,52 @@ export async function readSitesConfig(contentRoot: string): Promise<SitesConfig>
229
242
  }
230
243
  if (!parsed.globalLocales || !Array.isArray(parsed.globalLocales)) {
231
244
  console.warn(`Warning: sites.json is missing 'globalLocales' array at ${sitesPath}. Using default global locales.`);
245
+ warnUnreadableLocales(sitesPath, parsed.sites, []);
232
246
  return {
233
247
  sites: parsed.sites,
234
248
  globalLocales: ['en'],
235
249
  };
236
250
  }
251
+ warnUnreadableLocales(sitesPath, parsed.sites, parsed.globalLocales);
237
252
  return parsed;
238
253
  }
239
254
 
255
+ /**
256
+ * Why a page file's name gives no locale the content grammar reads: either it
257
+ * names one the grammar refuses ('about.pt-br.vxjson') or it names none.
258
+ */
259
+ function unreadablePageLocaleMessage(filename: string): string {
260
+ const written = /^.+\.([^.]+)\.(?:mdx|vxjson)$/.exec(filename)?.[1];
261
+ return written === undefined
262
+ ? `Page file ${filename} has no locale in its name (<name>.<locale>.vxjson), so it is not indexed.`
263
+ : `Page file ${filename} is not indexed. ${invalidLocaleMessage(written)}`;
264
+ }
265
+
266
+ // One warning per sites.json and locale for the whole process: the file is
267
+ // read again by every content API created and every config reload.
268
+ const warnedLocales = new Set<string>();
269
+
270
+ /**
271
+ * Warn about each locale sites.json declares that content file names cannot
272
+ * carry: its pages can be neither created nor read, and nothing else says so
273
+ * until a save is refused.
274
+ */
275
+ function warnUnreadableLocales(sitesPath: string, sites: SitesConfig['sites'], globalLocales: unknown[]): void {
276
+ const declared = [...globalLocales];
277
+ for (const site of Object.values(sites)) {
278
+ if (Array.isArray(site?.locales)) declared.push(...site.locales);
279
+ declared.push(site?.defaultLocale);
280
+ }
281
+ for (const locale of declared) {
282
+ const key = `${sitesPath}\0${locale}`;
283
+ if (typeof locale !== 'string' || isContentLocale(locale) || warnedLocales.has(key)) continue;
284
+ warnedLocales.add(key);
285
+ console.warn(
286
+ `Warning: sites.json at ${sitesPath} declares a locale no content file can carry, so its pages can be neither created nor read. ${invalidLocaleMessage(locale)}`,
287
+ );
288
+ }
289
+ }
290
+
240
291
  export type { IndexProblem } from './content-index.js';
241
292
 
242
293
  function messageOf(error: unknown): string {
@@ -463,18 +514,18 @@ export class FileSystemContentAPI implements ContentAPI {
463
514
  // is the one every local dev server and Astro build hydrates through.
464
515
  const claimedBy = new Map<string, string>();
465
516
 
466
- // Reuse a small pool of 4KB buffers across the batch; matches the
467
- // existing reindex() loop. parseFileHeaderWithRepair owns the buffer
468
- // contract (reads up to 4096 bytes from offset 0).
469
- const buffers = Array.from({ length: Math.min(files.length, 100) }, () => new Uint8Array(4096));
517
+ // One 4KB buffer per file in a batch: the batch is read in parallel, so
518
+ // two files sharing a buffer overwrite each other's bytes mid-parse.
519
+ // parseFileHeaderWithRepair owns the buffer contract (reads up to 4096
520
+ // bytes from offset 0).
521
+ const buffers = Array.from({ length: Math.min(files.length, OPTIMAL_BATCH_SIZE) }, () => new Uint8Array(4096));
470
522
 
471
523
  for (let i = 0; i < files.length; i += OPTIMAL_BATCH_SIZE) {
472
524
  const batch = files.slice(i, i + OPTIMAL_BATCH_SIZE);
473
525
  await Promise.all(
474
526
  batch.map(async (filePath, batchIndex) => {
475
- const buffer = buffers[(i + batchIndex) % buffers.length];
476
527
  try {
477
- const result = await this.parseFileHeaderWithRepair(filePath, buffer);
528
+ const result = await this.parseFileHeaderWithRepair(filePath, buffers[batchIndex]);
478
529
  if (result) {
479
530
  // Same reason as the shared indexAll loop: a page under a site
480
531
  // sites.json does not declare would be filed nowhere and
@@ -634,29 +685,31 @@ export class FileSystemContentAPI implements ContentAPI {
634
685
  collection = '';
635
686
  const filename = parts[1];
636
687
 
637
- // Create the general directory if it doesn't exist
638
- const generalDir = join(this.absoluteContentRoot, 'fragments', 'general');
688
+ // Create the repair folder if it doesn't exist
689
+ const repairDir = join(this.absoluteContentRoot, 'fragments', REPAIRED_FRAGMENT_COLLECTION);
639
690
  try {
640
- await mkdir(generalDir, { recursive: true });
691
+ await mkdir(repairDir, { recursive: true });
641
692
  } catch {
642
693
  // Directory might already exist, that's fine
643
694
  }
644
695
 
645
- // Move the file to the general collection
646
- const newFilePath = join(generalDir, filename);
696
+ // Move the file to the repair folder
697
+ const newFilePath = join(repairDir, filename);
647
698
 
648
699
  try {
649
700
  // Check if target file already exists
650
701
  try {
651
702
  await access(newFilePath);
652
- console.warn(`Cannot move ${filename} to fragments/general/: target file already exists`);
703
+ console.warn(
704
+ `Cannot move ${filename} to fragments/${REPAIRED_FRAGMENT_COLLECTION}/: target file already exists`,
705
+ );
653
706
  } catch {
654
707
  // Target doesn't exist, safe to move
655
708
  await rename(filePath, newFilePath);
656
- console.log(`Repaired: Moved ${filename} to fragments/general/ collection`);
709
+ console.log(`Repaired: Moved ${filename} to fragments/${REPAIRED_FRAGMENT_COLLECTION}/ collection`);
657
710
 
658
711
  // The file now uses the repaired collection layout.
659
- collection = 'general';
712
+ collection = REPAIRED_FRAGMENT_COLLECTION;
660
713
  filePath = newFilePath;
661
714
 
662
715
  // Update relativePath and parts for the new file path
@@ -666,7 +719,7 @@ export class FileSystemContentAPI implements ContentAPI {
666
719
  bytesRead = await readFilePrefix(filePath, buffer);
667
720
  }
668
721
  } catch (moveError) {
669
- console.error(`Failed to move ${filename} to general collection:`, moveError);
722
+ console.error(`Failed to move ${filename} to fragments/${REPAIRED_FRAGMENT_COLLECTION}/:`, moveError);
670
723
  // Continue processing with original file
671
724
  bytesRead = await readFilePrefix(filePath, buffer);
672
725
  }
@@ -789,7 +842,9 @@ export class FileSystemContentAPI implements ContentAPI {
789
842
  // (the reindex path) has always refused these — now both halves agree.
790
843
  const localeSuffix = filename ? parseLocaleFilename(filename) : null;
791
844
  if (!localeSuffix || localeSuffix.extension === 'json') {
792
- console.warn(`Skipping page file without a locale suffix: ${filePath}`);
845
+ const message = unreadablePageLocaleMessage(filename ?? relativePath);
846
+ console.warn(`Skipping ${filePath}: ${message}`);
847
+ this.recordIndexProblem(filePath, 'unsupported-locale-path', message);
793
848
  return null;
794
849
  }
795
850
  locale = localeSuffix.locale;
@@ -1,6 +1,11 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { access, readFile, writeFile } from 'node:fs/promises';
2
+ import { access, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
3
4
  import { dirname, join, resolve } from 'node:path';
5
+ import { setTimeout as sleep } from 'node:timers/promises';
6
+
7
+ /** Tries at lining the shared index up after a commit; ~1.5s total covers a briefly held index.lock. */
8
+ const INDEX_SYNC_ATTEMPTS = 6;
4
9
 
5
10
  export interface GitStatus {
6
11
  isRepo: boolean;
@@ -53,9 +58,15 @@ interface GitCommandResult {
53
58
  stderr: string;
54
59
  }
55
60
 
56
- function runGitCommand(cwd: string, args: string[]): Promise<GitCommandResult> {
61
+ function runGitCommand(
62
+ cwd: string,
63
+ args: string[],
64
+ env?: NodeJS.ProcessEnv,
65
+ input?: string,
66
+ ): Promise<GitCommandResult> {
57
67
  return new Promise((resolveCommand, reject) => {
58
- const process = spawn('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
68
+ const process = spawn('git', args, { cwd, env, stdio: 'pipe' });
69
+ process.stdin.end(input);
59
70
  let stdout = '';
60
71
  let stderr = '';
61
72
 
@@ -79,6 +90,66 @@ function runGitCommand(cwd: string, args: string[]): Promise<GitCommandResult> {
79
90
  });
80
91
  }
81
92
 
93
+ /** One path a commit changed, from `git diff-tree -r -z` raw output. */
94
+ interface TreeChange {
95
+ path: string;
96
+ oldBlob: string;
97
+ newMode: string;
98
+ newBlob: string;
99
+ }
100
+
101
+ function parseRawDiff(raw: string): TreeChange[] {
102
+ const fields = raw.split('\0');
103
+ const changes: TreeChange[] = [];
104
+ for (let i = 0; i + 1 < fields.length; i += 2) {
105
+ // ":oldmode newmode oldblob newblob status" then the path
106
+ const [, newMode, oldBlob, newBlob] = fields[i].replace(/^:/, '').split(' ');
107
+ if (!newBlob) continue;
108
+ changes.push({ path: fields[i + 1], oldBlob, newMode, newBlob });
109
+ }
110
+ return changes;
111
+ }
112
+
113
+ /**
114
+ * Point the shared index at the committed blobs, so committed files do not show as staged
115
+ * reversals — but only for entries that still hold what the parent commit had. An entry
116
+ * someone staged differently in the meantime is theirs and is left alone, as is everything
117
+ * outside the commit. Retries while another Git process briefly holds index.lock, re-reading
118
+ * the index each time so a `git add` made during the wait is not overwritten.
119
+ */
120
+ async function syncSharedIndex(
121
+ repoRoot: string,
122
+ contentPath: string,
123
+ changes: TreeChange[],
124
+ ): Promise<{ ok: true } | { ok: false; error: string }> {
125
+ if (changes.length === 0) return { ok: true };
126
+ let error = 'git update-index failed';
127
+ for (let attempt = 0; attempt < INDEX_SYNC_ATTEMPTS; attempt += 1) {
128
+ // oxlint-disable-next-line no-await-in-loop -- each retry waits for the lock holder to finish.
129
+ if (attempt > 0) await sleep(attempt * 100);
130
+ // A commit only ever changes paths under contentPath, so one pathspec covers them all
131
+ // without passing each path on the command line.
132
+ // oxlint-disable-next-line no-await-in-loop -- each attempt must see the index as it is now.
133
+ const staged = await runGitCommand(repoRoot, ['ls-files', '-s', '-z', '--', contentPath]);
134
+ const stagedBlob = new Map<string, string>();
135
+ for (const entry of staged.stdout.split('\0')) {
136
+ const tab = entry.indexOf('\t');
137
+ if (tab < 0) continue;
138
+ const [, blob, stage] = entry.slice(0, tab).split(' ');
139
+ if (stage === '0') stagedBlob.set(entry.slice(tab + 1), blob);
140
+ }
141
+ const lines = changes
142
+ .filter((c) => (stagedBlob.get(c.path) ?? '0'.repeat(c.oldBlob.length)) === c.oldBlob)
143
+ .map((c) => (/^0+$/.test(c.newBlob) ? `0 ${c.newBlob}\t${c.path}\0` : `${c.newMode} ${c.newBlob}\t${c.path}\0`));
144
+ if (lines.length === 0) return { ok: true };
145
+ // oxlint-disable-next-line no-await-in-loop -- retries are sequential by design.
146
+ const result = await runGitCommand(repoRoot, ['update-index', '-z', '--index-info'], undefined, lines.join(''));
147
+ if (result.exitCode === 0) return { ok: true };
148
+ error = result.stderr || error;
149
+ }
150
+ return { ok: false, error };
151
+ }
152
+
82
153
  /**
83
154
  * Resolve the git repository root from a content path.
84
155
  * Uses `git rev-parse --show-toplevel` starting from the parent of the content directory.
@@ -93,6 +164,22 @@ async function resolveRepoRoot(contentPath: string): Promise<string | null> {
93
164
  return result.stdout;
94
165
  }
95
166
 
167
+ /**
168
+ * Commits and pulls both move HEAD; queueing them per repository keeps one request's commit
169
+ * from landing inside another's. Module-wide and keyed by repo root because the router builds
170
+ * a fresh GitOperations for every request.
171
+ */
172
+ const headQueues = new Map<string, Promise<unknown>>();
173
+ function serializedOnRepo<T>(repoRoot: string, operation: () => Promise<T>): Promise<T> {
174
+ const run = (headQueues.get(repoRoot) ?? Promise.resolve()).then(operation, operation);
175
+ const settled = run.catch(() => undefined);
176
+ headQueues.set(repoRoot, settled);
177
+ void settled.then(() => {
178
+ if (headQueues.get(repoRoot) === settled) headQueues.delete(repoRoot);
179
+ });
180
+ return run;
181
+ }
182
+
96
183
  /**
97
184
  * Create git operations using local git CLI commands.
98
185
  * Requires git binary available on PATH and CONTENT_PATH inside a git repository.
@@ -112,6 +199,100 @@ export function createGitOperations(config: GitConfig): GitOperations {
112
199
  return cachedRepoRoot;
113
200
  }
114
201
 
202
+ async function commitContent(repoRoot: string, message: string, author?: GitAuthor): Promise<GitCommitResult> {
203
+ // Build the commit in a private index seeded from HEAD. The shared index may hold work
204
+ // someone staged outside contentPath; it must neither ride along nor lose its staging.
205
+ // Writing the tree from the private index (not a pathspec commit, which re-reads the
206
+ // working tree) also pins the snapshot `git add` took against content writes meanwhile.
207
+ const indexDir = await mkdtemp(join(tmpdir(), 'conloca-git-index-'));
208
+ const privateIndex = { ...process.env, GIT_INDEX_FILE: join(indexDir, 'index') };
209
+ try {
210
+ const headResult = await runGitCommand(repoRoot, ['rev-parse', '--verify', '--quiet', 'HEAD']);
211
+ const parent = headResult.exitCode === 0 ? headResult.stdout : null;
212
+ const seed = await runGitCommand(
213
+ repoRoot,
214
+ parent ? ['read-tree', parent] : ['read-tree', '--empty'],
215
+ privateIndex,
216
+ );
217
+ if (seed.exitCode !== 0) {
218
+ return { success: false, error: seed.stderr || 'Failed to prepare commit' };
219
+ }
220
+
221
+ const addResult = await runGitCommand(repoRoot, ['add', '-A', '--', contentPath], privateIndex);
222
+ if (addResult.exitCode !== 0) {
223
+ return { success: false, error: addResult.stderr || 'Failed to stage changes' };
224
+ }
225
+
226
+ const treeResult = await runGitCommand(repoRoot, ['write-tree'], privateIndex);
227
+ if (treeResult.exitCode !== 0) {
228
+ return { success: false, error: treeResult.stderr || 'Failed to write tree' };
229
+ }
230
+ const tree = treeResult.stdout;
231
+ if (parent && (await runGitCommand(repoRoot, ['rev-parse', `${parent}^{tree}`])).stdout === tree) {
232
+ return { success: false, error: 'No changes to commit' };
233
+ }
234
+
235
+ // author.name/author.email set only the author; the committer stays the server's identity,
236
+ // as `git commit --author` left it.
237
+ const authorConfig = author ? ['-c', `author.name=${author.name}`, '-c', `author.email=${author.email}`] : [];
238
+ const commitResult = await runGitCommand(repoRoot, [
239
+ ...authorConfig,
240
+ 'commit-tree',
241
+ tree,
242
+ ...(parent ? ['-p', parent] : []),
243
+ '-m',
244
+ message,
245
+ ]);
246
+ if (commitResult.exitCode !== 0) {
247
+ return { success: false, error: commitResult.stderr || 'Commit failed' };
248
+ }
249
+ const commitSha = commitResult.stdout;
250
+
251
+ // Move HEAD only if it still points where the tree was built from. A commit another
252
+ // process made meanwhile would otherwise be silently reverted by this stale tree.
253
+ const expected = parent ?? '0'.repeat(commitSha.length);
254
+ const moveHead = await runGitCommand(repoRoot, [
255
+ 'update-ref',
256
+ '-m',
257
+ `commit: ${message}`,
258
+ 'HEAD',
259
+ commitSha,
260
+ expected,
261
+ ]);
262
+ if (moveHead.exitCode !== 0) {
263
+ return { success: false, error: 'The branch moved while committing; nothing was committed. Try again.' };
264
+ }
265
+
266
+ // Count and sync from the commit just made, never from HEAD, which others may move again.
267
+ const changesResult = await runGitCommand(repoRoot, [
268
+ 'diff-tree',
269
+ '-r',
270
+ '-z',
271
+ '--no-renames',
272
+ '--no-commit-id',
273
+ ...(parent ? [parent, commitSha] : ['--root', commitSha]),
274
+ ]);
275
+ const changes = parseRawDiff(changesResult.stdout);
276
+
277
+ const synced = await syncSharedIndex(repoRoot, contentPath, changes);
278
+ if (!synced.ok) {
279
+ return {
280
+ success: false,
281
+ commit: commitSha,
282
+ error: `Committed ${commitSha}, but the Git index could not be updated for the content folder (${synced.error}). Run \`git reset -- ${contentPath}\` before committing outside the CMS.`,
283
+ };
284
+ }
285
+
286
+ return {
287
+ success: true,
288
+ commit: commitSha,
289
+ summary: `${changes.length} files committed`,
290
+ };
291
+ } finally {
292
+ await rm(indexDir, { recursive: true, force: true });
293
+ }
294
+ }
295
+
115
296
  return {
116
297
  async getStatus(): Promise<GitStatus> {
117
298
  try {
@@ -164,43 +345,7 @@ export function createGitOperations(config: GitConfig): GitOperations {
164
345
  if (!repoRoot) {
165
346
  return { success: false, error: 'Not a git repository' };
166
347
  }
167
-
168
- // Stage all changes
169
- const addResult = await runGitCommand(repoRoot, ['add', '-A', '--', contentPath]);
170
- if (addResult.exitCode !== 0) {
171
- return { success: false, error: addResult.stderr || 'Failed to stage changes' };
172
- }
173
-
174
- // Check if there's anything to commit after staging
175
- const diffResult = await runGitCommand(repoRoot, ['diff', '--cached', '--quiet', '--', contentPath]);
176
- if (diffResult.exitCode === 0) {
177
- return { success: false, error: 'No changes to commit' };
178
- }
179
-
180
- // Count staged files for summary
181
- const diffStatResult = await runGitCommand(repoRoot, ['diff', '--cached', '--numstat', '--', contentPath]);
182
- const fileCount = diffStatResult.stdout ? diffStatResult.stdout.split('\n').filter((l) => l.trim()).length : 0;
183
-
184
- // Build commit command
185
- const commitArgs = ['commit', '-m', message];
186
- if (author) {
187
- commitArgs.push('--author', `${author.name} <${author.email}>`);
188
- }
189
-
190
- const commitResult = await runGitCommand(repoRoot, commitArgs);
191
- if (commitResult.exitCode !== 0) {
192
- return { success: false, error: commitResult.stderr || 'Commit failed' };
193
- }
194
-
195
- // Get the commit SHA
196
- const shaResult = await runGitCommand(repoRoot, ['rev-parse', 'HEAD']);
197
- const commitSha = shaResult.stdout || undefined;
198
-
199
- return {
200
- success: true,
201
- commit: commitSha,
202
- summary: `${fileCount} files committed`,
203
- };
348
+ return await serializedOnRepo(repoRoot, () => commitContent(repoRoot, message, author));
204
349
  } catch (error) {
205
350
  return {
206
351
  success: false,
@@ -279,7 +424,9 @@ export function createGitOperations(config: GitConfig): GitOperations {
279
424
  targetBranch = branchResult.stdout;
280
425
  }
281
426
 
282
- const pullResult = await runGitCommand(repoRoot, ['pull', '--autostash', '--rebase', 'origin', targetBranch]);
427
+ const pullResult = await serializedOnRepo(repoRoot, () =>
428
+ runGitCommand(repoRoot, ['pull', '--autostash', '--rebase', 'origin', targetBranch]),
429
+ );
283
430
 
284
431
  if (pullResult.exitCode !== 0) {
285
432
  return {
package/src/index.ts CHANGED
@@ -37,7 +37,23 @@ export type { GitCommitResult, GitPullResult, GitPushResult, GitStatus } from '.
37
37
  export { pageReferenceOf, pageTimestampsOf, selectPagesByPrefix } from './page-references.js';
38
38
  // Reader backend interface types (browser-safe; type-only re-export).
39
39
  export type { BackendReadResult, ContentReaderBackend } from './reader-backend.js';
40
- export * from './schemas/index.js';
40
+ // Content metadata shapes. Types only: the generated validators live on the
41
+ // `./schemas` subpath so this browser barrel stays free of the Typia
42
+ // transform's output (and of anything a consumer would tree-shake to avoid it).
43
+ export type {
44
+ DataEditable,
45
+ DataMeta,
46
+ FragmentEditable,
47
+ FragmentMeta,
48
+ LooseDataMeta,
49
+ LooseFragmentMeta,
50
+ LoosePageMeta,
51
+ MdxPageFrontmatter,
52
+ PageEditable,
53
+ PageMeta,
54
+ SchemaIssue,
55
+ SchemaParseResult,
56
+ } from './schemas/types.js';
41
57
  export { Site } from './site.js';
42
58
  export * from './types.js';
43
59
  // SSRF host predicate — pure string/number logic, so any host's import guards can share it.
package/src/middleware.ts CHANGED
@@ -2,11 +2,10 @@ import { type Context, Hono } from 'hono';
2
2
  import { type AssetConfig, AssetOperations } from './asset-operations.js';
3
3
  import { findAssetUsage } from './asset-usage.js';
4
4
  import type { ContentAPI } from './content-api.interface.js';
5
- import { localesOf, normalizeAndValidatePathname } from './content-utils.js';
5
+ import { normalizeAndValidatePathname } from './content-utils.js';
6
6
  import { createGitOperations, type GitAuthor, type GitConfig } from './git-operations.js';
7
7
  import type {
8
8
  APIError,
9
- ContentManifest,
10
9
  CreateResult,
11
10
  DeleteResult,
12
11
  ErrorCode,
@@ -101,6 +100,8 @@ function isCrossSiteWrite(c: Context): boolean {
101
100
  */
102
101
  export interface ContentAPIRouterOptions {
103
102
  assetsPath?: string;
103
+ /** Where the site serves `assetsPath`, which begins every image link the editor stores; `/assets` when unset */
104
+ assetRefBase?: string;
104
105
  assetConfig?: Omit<AssetConfig, 'assetsPath' | 'contentRoot'>;
105
106
  /** Content root directory: holds asset metadata records, is scanned for asset usage, and is where git runs */
106
107
  contentRoot?: string;
@@ -365,12 +366,16 @@ export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRout
365
366
  );
366
367
  }
367
368
  if (result.reason === 'stale_write') {
369
+ // The error envelope is what a client reads to tell an outdated etag from any other failure.
368
370
  return c.json(
369
371
  {
370
372
  success: false,
371
373
  reason: result.reason,
372
374
  currentEtag: result.currentEtag,
373
375
  message: 'Content has been modified',
376
+ ...errorResponse(ErrorCodes.STALE_WRITE, 'Content has been modified since you last loaded it', {
377
+ currentEtag: result.currentEtag,
378
+ }),
374
379
  },
375
380
  412,
376
381
  );
@@ -555,6 +560,11 @@ export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRout
555
560
 
556
561
  const result = await assetOps.moveAssets(filenames, sourceFolder, targetFolder);
557
562
 
563
+ // A partly finished move answers with the result itself, so the editor learns which
564
+ // assets stayed and can keep exactly those selected for a retry.
565
+ if (!result.success && result.moved) {
566
+ return c.json(result);
567
+ }
558
568
  if (!result.success) {
559
569
  return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);
560
570
  }
@@ -679,7 +689,7 @@ export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRout
679
689
  // GET /assets/usage/:path{.+} — content that links to the asset at this path from the assets root
680
690
  app.get('/assets/usage/:path{.+}', async (c) => {
681
691
  try {
682
- const usage = await findAssetUsage(api, c.req.param('path'));
692
+ const usage = await findAssetUsage(api, c.req.param('path'), options.assetRefBase);
683
693
  return c.json({ usage });
684
694
  } catch (error) {
685
695
  return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get asset usage'), 500);
@@ -921,11 +931,12 @@ export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRout
921
931
  }
922
932
  });
923
933
 
924
- // GET /fragments/name-available - Check if fragment name is available
934
+ // GET /fragments/name-available - Check if fragment name is available, the way a create checks it: in
935
+ // any letter case and in any language. `locale` is still accepted but narrows nothing, since a fragment
936
+ // has one name for all its languages.
925
937
  app.get('/fragments/name-available', async (c) => {
926
938
  const name = c.req.query('name');
927
939
  const collection = c.req.query('collection') || 'components';
928
- const locale = c.req.query('locale') || 'en';
929
940
  const excludeId = c.req.query('excludeId');
930
941
 
931
942
  if (!name) {
@@ -936,41 +947,12 @@ export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRout
936
947
  }
937
948
 
938
949
  try {
939
- // Check fragment name availability through listing
940
- const existing = Array.from(
941
- api.listAllContent({
942
- kind: 'fragment',
943
- collection: collection,
944
- locales: [locale],
945
- }),
946
- );
947
-
948
- let taken: ContentManifest | undefined;
949
- for (const item of existing) {
950
- for (const localeVersion of localesOf(item)) {
951
- if (localeVersion.name === name) {
952
- taken = item;
953
- break;
954
- }
955
- }
956
- }
957
-
958
- // If no existing fragment, name is available
959
- if (!taken) {
960
- return c.json({ available: true });
961
- }
962
-
963
- // If existing fragment has same ID as excludeId, name is available
964
- // (useful when editing existing fragment)
965
- if (excludeId && taken.id === excludeId) {
950
+ const existingId = api.fragments.getNameConflict(collection, name, excludeId);
951
+ if (existingId === null) {
966
952
  return c.json({ available: true });
967
953
  }
968
954
 
969
- // Otherwise, name is taken
970
- return c.json({
971
- available: false,
972
- existingId: taken.id,
973
- });
955
+ return c.json({ available: false, existingId });
974
956
  } catch (error) {
975
957
  return c.json(
976
958
  logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check fragment name availability'),
@@ -1062,12 +1044,16 @@ export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRout
1062
1044
 
1063
1045
  if (!updateResult.success) {
1064
1046
  if (updateResult.reason === 'stale_write') {
1047
+ // The error envelope is what a client reads to tell an outdated etag from any other failure.
1065
1048
  return c.json(
1066
1049
  {
1067
1050
  moved: false,
1068
1051
  reason: 'stale_write',
1069
1052
  currentEtag: updateResult.currentEtag,
1070
1053
  message: 'Content has been modified',
1054
+ ...errorResponse(ErrorCodes.STALE_WRITE, 'Content has been modified since you last loaded it', {
1055
+ currentEtag: updateResult.currentEtag,
1056
+ }),
1071
1057
  },
1072
1058
  412,
1073
1059
  );