@nuasite/cms-sidecar 0.70.5 → 0.71.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -52,6 +52,12 @@ version. `commitChangeset(fs)` is a reference implementation; it is atomic only
52
52
  else writes between its awaits, so a host with concurrent writers runs the same check
53
53
  (`versionOf`, `versionMatches`) and the writes inside its own critical section.
54
54
 
55
+ Every entry read (`GET …/entries/:slug`) carries `sourceHash`, the digest of the bytes it
56
+ parsed. An entry mutation returns the digest of the bytes it wrote, or for a rename of the
57
+ bytes it moved, taken from those bytes rather than by reading the file again. `PATCH`,
58
+ `DELETE` and `POST …/rename` take that value back as an optional `baseHash` and answer `409`
59
+ when the file changed since.
60
+
55
61
  ## Collections the scan cannot vouch for
56
62
 
57
63
  `GET /cms/v1/collections` lists the collections the scan could read. The scan is a walk
@@ -26101,11 +26101,68 @@ async function versionOf(fs3, path7) {
26101
26101
  return { kind: "present" };
26102
26102
  }
26103
26103
  }
26104
+ function changesetDigest(changeset, path7) {
26105
+ const target = normalize(path7);
26106
+ const changed = changeset.changes.findLast((change) => change.path === target);
26107
+ if (changed !== undefined)
26108
+ return changed.kind === "write" ? digestBytes(changed.content) : undefined;
26109
+ const read = changeset.reads.get(target);
26110
+ return read?.kind === "content" ? read.digest : undefined;
26111
+ }
26112
+ function recordVersions(base) {
26113
+ const versions = new Map;
26114
+ const encoder = new TextEncoder;
26115
+ return {
26116
+ readFile: (path7) => base.readFile(path7),
26117
+ async readBytes(path7) {
26118
+ const content = await base.readBytes(path7);
26119
+ const key = normalize(path7);
26120
+ if (!versions.has(key))
26121
+ versions.set(key, digestBytes(content));
26122
+ return content;
26123
+ },
26124
+ async writeFile(path7, content) {
26125
+ await base.writeFile(path7, content);
26126
+ versions.set(normalize(path7), digestBytes(encoder.encode(content)));
26127
+ },
26128
+ async writeBytes(path7, content) {
26129
+ await base.writeBytes(path7, content);
26130
+ versions.set(normalize(path7), digestBytes(content));
26131
+ },
26132
+ async remove(path7) {
26133
+ await base.remove(path7);
26134
+ versions.delete(normalize(path7));
26135
+ },
26136
+ async rename(rawFrom, rawTo) {
26137
+ await base.rename(rawFrom, rawTo);
26138
+ const from = normalize(rawFrom);
26139
+ const to = normalize(rawTo);
26140
+ for (const path7 of [...versions.keys()]) {
26141
+ if (path7 === to || isBelow(path7, to))
26142
+ versions.delete(path7);
26143
+ }
26144
+ for (const [path7, digest] of [...versions]) {
26145
+ if (path7 !== from && !isBelow(path7, from))
26146
+ continue;
26147
+ versions.delete(path7);
26148
+ versions.set(to + path7.slice(from.length), digest);
26149
+ }
26150
+ },
26151
+ exists: (path7) => base.exists(path7),
26152
+ list: (dir) => base.list(dir),
26153
+ glob: (pattern, options) => base.glob(pattern, options),
26154
+ stat: (path7) => base.stat(path7),
26155
+ digest(path7) {
26156
+ return versions.get(normalize(path7));
26157
+ }
26158
+ };
26159
+ }
26104
26160
 
26105
26161
  // ../cms-core/src/handlers/entry-ops.ts
26106
26162
  var import_yaml3 = __toESM(require_dist(), 1);
26107
26163
  import path7 from "path";
26108
26164
  var MARKDOWN_EXTENSIONS = ["md", "mdx"];
26165
+ var UTF8 = new TextDecoder("utf-8", { ignoreBOM: true });
26109
26166
  function fileExtension(filePath) {
26110
26167
  const idx = filePath.lastIndexOf(".");
26111
26168
  return idx >= 0 ? filePath.slice(idx + 1).toLowerCase() : "";
@@ -26370,17 +26427,20 @@ async function getEntry(deps, collection, slug) {
26370
26427
  const sourcePath = await resolveEntryPath(deps, collection, slug);
26371
26428
  if (!sourcePath)
26372
26429
  return null;
26373
- const raw = await deps.fs.readFile(sourcePath);
26430
+ const bytes = await deps.fs.readBytes(sourcePath);
26431
+ const raw = UTF8.decode(bytes);
26432
+ const sourceHash = digestBytes(bytes);
26374
26433
  if (isDataFile(sourcePath)) {
26375
26434
  const data = sourcePath.endsWith(".json") ? JSON.parse(raw) : import_yaml3.default.parse(raw);
26376
26435
  return {
26377
26436
  content: "",
26378
26437
  frontmatter: data && typeof data === "object" ? data : {},
26379
- sourcePath
26438
+ sourcePath,
26439
+ sourceHash
26380
26440
  };
26381
26441
  }
26382
26442
  const { frontmatter, content } = parseFrontmatter2(raw);
26383
- return { content, frontmatter, sourcePath };
26443
+ return { content, frontmatter, sourcePath, sourceHash };
26384
26444
  }
26385
26445
  async function createEntry(deps, input) {
26386
26446
  const { collection, slug, body = "" } = input;
@@ -26486,6 +26546,11 @@ async function renameEntry(deps, collection, from, to) {
26486
26546
  if (!normalizedSlug) {
26487
26547
  return { success: false, error: "Invalid slug" };
26488
26548
  }
26549
+ try {
26550
+ await deps.fs.readBytes(sourcePath);
26551
+ } catch {
26552
+ return { success: false, error: `Entry not found: ${collection}/${from}` };
26553
+ }
26489
26554
  const { moveFrom, moveTo, previousSlug, newSourcePath } = renameTarget(sourcePath, from, normalizedSlug);
26490
26555
  if (moveFrom === moveTo) {
26491
26556
  return { success: true, sourcePath: newSourcePath };
@@ -27005,6 +27070,25 @@ function createCmsCore(fs3, opts = {}) {
27005
27070
  await commit(staged.changeset());
27006
27071
  return result;
27007
27072
  }
27073
+ async function mutateEntry(operation) {
27074
+ let digestOf;
27075
+ let result;
27076
+ if (commit === undefined) {
27077
+ const recording = recordVersions(fs3);
27078
+ result = await operation(recording);
27079
+ digestOf = (path8) => recording.digest(path8);
27080
+ } else {
27081
+ const staged = createStagedFileSystem(fs3);
27082
+ result = await operation(staged);
27083
+ const changeset = staged.changeset();
27084
+ await commit(changeset);
27085
+ digestOf = (path8) => changesetDigest(changeset, path8);
27086
+ }
27087
+ if (!result.success || result.sourcePath === undefined)
27088
+ return result;
27089
+ const sourceHash = digestOf(result.sourcePath);
27090
+ return sourceHash === undefined ? result : { ...result, sourceHash };
27091
+ }
27008
27092
  return {
27009
27093
  scanCollections(options) {
27010
27094
  return scanCollections(fs3, contentDir, parseCache, { report: options?.report ?? false, frontmatterCache });
@@ -27023,22 +27107,22 @@ function createCmsCore(fs3, opts = {}) {
27023
27107
  return getProjectAsset(readDeps, assetPath);
27024
27108
  },
27025
27109
  createEntry(input) {
27026
- return mutate((over) => createEntry(entryDeps(over), input));
27110
+ return mutateEntry((over) => createEntry(entryDeps(over), input));
27027
27111
  },
27028
27112
  updateEntry(input) {
27029
- return mutate((over) => updateEntry(entryDeps(over), input));
27113
+ return mutateEntry((over) => updateEntry(entryDeps(over), input));
27030
27114
  },
27031
27115
  deleteEntry(collection, slug) {
27032
- return mutate((over) => deleteEntry(entryDeps(over), collection, slug));
27116
+ return mutateEntry((over) => deleteEntry(entryDeps(over), collection, slug));
27033
27117
  },
27034
27118
  renameEntry(collection, from, to) {
27035
- return mutate((over) => renameEntry(entryDeps(over), collection, from, to));
27119
+ return mutateEntry((over) => renameEntry(entryDeps(over), collection, from, to));
27036
27120
  },
27037
27121
  addArrayItem(input) {
27038
- return mutate((over) => addArrayItem(entryDeps(over), input));
27122
+ return mutateEntry((over) => addArrayItem(entryDeps(over), input));
27039
27123
  },
27040
27124
  removeArrayItem(input) {
27041
- return mutate((over) => removeArrayItem(entryDeps(over), input));
27125
+ return mutateEntry((over) => removeArrayItem(entryDeps(over), input));
27042
27126
  },
27043
27127
  createPage(input) {
27044
27128
  return mutate((over) => createPage({ fs: over }, input));
@@ -27559,15 +27643,10 @@ function mediaFromEnv(env = process.env) {
27559
27643
  }
27560
27644
 
27561
27645
  // src/concurrency.ts
27562
- import { createHash as createHash2 } from "crypto";
27563
- function hashContent(content) {
27564
- return `sha256:${createHash2("sha256").update(content, "utf-8").digest("hex")}`;
27565
- }
27566
27646
  async function hashSource(fs3, sourcePath) {
27567
27647
  if (!await fs3.exists(sourcePath))
27568
27648
  return null;
27569
- const raw = await fs3.readFile(sourcePath);
27570
- return hashContent(raw);
27649
+ return digestBytes(await fs3.readBytes(sourcePath));
27571
27650
  }
27572
27651
 
27573
27652
  class SharedRun {
@@ -27692,6 +27771,23 @@ async function parseJson(req) {
27692
27771
  return { ok: false, response: error("validation", "Invalid JSON body") };
27693
27772
  }
27694
27773
  }
27774
+ async function parseOptionalJson(req) {
27775
+ const text = await req.text();
27776
+ if (text.trim() === "")
27777
+ return { ok: true, value: undefined };
27778
+ try {
27779
+ const value = JSON.parse(text);
27780
+ return { ok: true, value };
27781
+ } catch {
27782
+ return { ok: false, response: error("validation", "Invalid JSON body") };
27783
+ }
27784
+ }
27785
+ function isOptionalHash(value) {
27786
+ return value === undefined || typeof value === "string" && value !== "";
27787
+ }
27788
+ function isBodyObject(value) {
27789
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27790
+ }
27695
27791
  function parseEntriesQuery(url) {
27696
27792
  const fields = url.searchParams.get("fields") ?? undefined;
27697
27793
  const rawDraft = url.searchParams.get("draft");
@@ -28009,7 +28105,8 @@ function createServer(opts) {
28009
28105
  sourcePath: result.sourcePath,
28010
28106
  frontmatter,
28011
28107
  body: result.content,
28012
- bodyStartLine: 0
28108
+ bodyStartLine: 0,
28109
+ sourceHash: result.sourceHash
28013
28110
  };
28014
28111
  return json(entry);
28015
28112
  }
@@ -28036,23 +28133,9 @@ function createServer(opts) {
28036
28133
  if (!existing)
28037
28134
  return error("not_found", `Entry not found: ${collection}/${slug}`);
28038
28135
  const sourcePath = existing.sourcePath;
28039
- const existingFrontmatter = existing.frontmatter;
28040
- async function conflictResponse(serverHash) {
28041
- const current = await core.getEntry(collection, slug);
28042
- const conflict = {
28043
- code: "conflict",
28044
- serverHash,
28045
- serverFrontmatter: current?.frontmatter ?? existingFrontmatter
28046
- };
28047
- if (current && current.content !== "")
28048
- conflict.serverBody = current.content;
28049
- return json(conflict, STATUS_BY_CODE.conflict);
28050
- }
28051
28136
  return mutex.runExclusive(sourcePath, async () => {
28052
- const serverHash = await hashSource(fs3, sourcePath);
28053
- if (body.baseHash !== undefined && serverHash !== null && body.baseHash !== serverHash) {
28054
- return conflictResponse(serverHash);
28055
- }
28137
+ if (await isStale(sourcePath, body.baseHash))
28138
+ return conflictResponse(collection, slug);
28056
28139
  let result;
28057
28140
  try {
28058
28141
  result = await core.updateEntry({
@@ -28064,20 +28147,32 @@ function createServer(opts) {
28064
28147
  } catch (cause) {
28065
28148
  if (!(cause instanceof CmsCommitConflictError))
28066
28149
  throw cause;
28067
- const currentHash = await hashSource(fs3, sourcePath);
28068
- if (currentHash === null)
28150
+ if (await hashSource(fs3, sourcePath) === null)
28069
28151
  throw cause;
28070
- return conflictResponse(currentHash);
28071
- }
28072
- if (!result.success)
28073
- return mutationResponse(result);
28074
- const newHash = await hashSource(fs3, result.sourcePath ?? sourcePath);
28075
- const enriched = { ...result };
28076
- if (newHash !== null)
28077
- enriched.sourceHash = newHash;
28078
- return json(enriched);
28152
+ return conflictResponse(collection, slug);
28153
+ }
28154
+ return mutationResponse(result);
28079
28155
  });
28080
28156
  }
28157
+ async function isStale(sourcePath, baseHash) {
28158
+ if (baseHash === undefined)
28159
+ return false;
28160
+ const serverHash = await hashSource(fs3, sourcePath);
28161
+ return serverHash !== null && serverHash !== baseHash;
28162
+ }
28163
+ async function conflictResponse(collection, slug) {
28164
+ const current = await core.getEntry(collection, slug);
28165
+ if (current === null)
28166
+ return error("conflict", `Entry changed and was removed meanwhile: ${collection}/${slug}`);
28167
+ const conflict = {
28168
+ code: "conflict",
28169
+ serverHash: current.sourceHash,
28170
+ serverFrontmatter: current.frontmatter
28171
+ };
28172
+ if (current.content !== "")
28173
+ conflict.serverBody = current.content;
28174
+ return json(conflict, STATUS_BY_CODE.conflict);
28175
+ }
28081
28176
  async function fetchHandler(req) {
28082
28177
  const url = new URL(req.url);
28083
28178
  let pathname = url.pathname;
@@ -28173,7 +28268,7 @@ function createServer(opts) {
28173
28268
  if (method === "PATCH")
28174
28269
  return updateEntryRoute(collection, slug, req);
28175
28270
  if (method === "DELETE")
28176
- return deleteEntryRoute(collection, slug);
28271
+ return deleteEntryRoute(collection, slug, req);
28177
28272
  return error("unsupported", `Unsupported: ${method} /collections/${collection}/entries/${slug}`);
28178
28273
  }
28179
28274
  if (action === "rename" && method === "POST")
@@ -28224,13 +28319,7 @@ function createServer(opts) {
28224
28319
  body: body.body,
28225
28320
  fileExtension: body.fileExtension
28226
28321
  });
28227
- if (!result.success)
28228
- return mutationResponse(result);
28229
- const newHash = result.sourcePath ? await hashSource(fs3, result.sourcePath) : null;
28230
- const enriched = { ...result };
28231
- if (newHash !== null)
28232
- enriched.sourceHash = newHash;
28233
- return json(enriched);
28322
+ return mutationResponse(result);
28234
28323
  }
28235
28324
  async function updateEntryRoute(collection, slug, req) {
28236
28325
  const parsed = await parseJson(req);
@@ -28238,11 +28327,20 @@ function createServer(opts) {
28238
28327
  return parsed.response;
28239
28328
  return patchEntry(collection, slug, parsed.value);
28240
28329
  }
28241
- async function deleteEntryRoute(collection, slug) {
28330
+ async function deleteEntryRoute(collection, slug, req) {
28331
+ const parsed = await parseOptionalJson(req);
28332
+ if (!parsed.ok)
28333
+ return parsed.response;
28334
+ if (parsed.value !== undefined && !isBodyObject(parsed.value))
28335
+ return error("validation", "The body must be a JSON object");
28336
+ if (!isOptionalHash(parsed.value?.baseHash))
28337
+ return error("validation", '"baseHash" must be a non-empty string');
28242
28338
  const existing = await core.getEntry(collection, slug);
28243
28339
  if (!existing)
28244
28340
  return error("not_found", `Entry not found: ${collection}/${slug}`);
28245
28341
  return mutex.runExclusive(existing.sourcePath, async () => {
28342
+ if (await isStale(existing.sourcePath, parsed.value?.baseHash))
28343
+ return conflictResponse(collection, slug);
28246
28344
  const result = await core.deleteEntry(collection, slug);
28247
28345
  return mutationResponse(result);
28248
28346
  });
@@ -28254,18 +28352,15 @@ function createServer(opts) {
28254
28352
  if (typeof parsed.value.to !== "string" || parsed.value.to.trim() === "") {
28255
28353
  return error("validation", 'A non-empty "to" slug is required');
28256
28354
  }
28355
+ if (!isOptionalHash(parsed.value.baseHash))
28356
+ return error("validation", '"baseHash" must be a non-empty string');
28257
28357
  const existing = await core.getEntry(collection, slug);
28258
28358
  if (!existing)
28259
28359
  return error("not_found", `Entry not found: ${collection}/${slug}`);
28260
28360
  return mutex.runExclusive(existing.sourcePath, async () => {
28261
- const result = await core.renameEntry(collection, slug, parsed.value.to);
28262
- if (!result.success)
28263
- return mutationResponse(result);
28264
- const newHash = result.sourcePath ? await hashSource(fs3, result.sourcePath) : null;
28265
- const enriched = { ...result };
28266
- if (newHash !== null)
28267
- enriched.sourceHash = newHash;
28268
- return json(enriched);
28361
+ if (await isStale(existing.sourcePath, parsed.value.baseHash))
28362
+ return conflictResponse(collection, slug);
28363
+ return mutationResponse(await core.renameEntry(collection, slug, parsed.value.to));
28269
28364
  });
28270
28365
  }
28271
28366
  async function addArrayRoute(collection, slug, req) {
@@ -1,4 +1,4 @@
1
- import type { CmsFileSystem } from '@nuasite/cms-core';
1
+ import { type CmsFileSystem } from '@nuasite/cms-core';
2
2
  /**
3
3
  * Hashing, per-file serialization and shared reads for the sidecar layer.
4
4
  *
@@ -7,11 +7,15 @@ import type { CmsFileSystem } from '@nuasite/cms-core';
7
7
  * through the same `CmsFileSystem` port cms-core uses, so the hash reflects exactly
8
8
  * the bytes a subsequent `getEntry` would parse.
9
9
  */
10
- /** Stable content hash of a UTF-8 string: `sha256:<hex>`. */
10
+ /**
11
+ * Stable content hash of a UTF-8 string: `sha256:<hex>`. Equal to the `sourceHash` of a file only when
12
+ * the file is valid UTF-8 that decodes to `content`; the server hashes the bytes (`hashSource`).
13
+ */
11
14
  export declare function hashContent(content: string): string;
12
15
  /**
13
16
  * Hash the current on-disk source at `sourcePath`, or `null` when the file does
14
- * not exist. Reads via the port so the hash matches the bytes cms-core sees.
17
+ * not exist. Hashes the bytes, as cms-core does for a read and a write, so the
18
+ * values compare exactly.
15
19
  */
16
20
  export declare function hashSource(fs: CmsFileSystem, sourcePath: string): Promise<string | null>;
17
21
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"concurrency.d.ts","sourceRoot":"","sources":["../src/concurrency.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAGtD;;;;;;;GAOG;AAEH,6DAA6D;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AC,CAAC,CAAC;IAIjC,GAAG,IAAI,OAAO,CAAC,CAAC,CAAC;IAWjB,UAAU,IAAI,IAAI;CAGlB;AAED;;;;GAIG;AACH,qBAAa,UAAU;IACtB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAsC;IAEtD,YAAY,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;CAetE"}
@@ -1,3 +1,4 @@
1
+ import { digestBytes } from '@nuasite/cms-core';
1
2
  import { createHash } from 'node:crypto';
2
3
  /**
3
4
  * Hashing, per-file serialization and shared reads for the sidecar layer.
@@ -7,19 +8,22 @@ import { createHash } from 'node:crypto';
7
8
  * through the same `CmsFileSystem` port cms-core uses, so the hash reflects exactly
8
9
  * the bytes a subsequent `getEntry` would parse.
9
10
  */
10
- /** Stable content hash of a UTF-8 string: `sha256:<hex>`. */
11
+ /**
12
+ * Stable content hash of a UTF-8 string: `sha256:<hex>`. Equal to the `sourceHash` of a file only when
13
+ * the file is valid UTF-8 that decodes to `content`; the server hashes the bytes (`hashSource`).
14
+ */
11
15
  export function hashContent(content) {
12
16
  return `sha256:${createHash('sha256').update(content, 'utf-8').digest('hex')}`;
13
17
  }
14
18
  /**
15
19
  * Hash the current on-disk source at `sourcePath`, or `null` when the file does
16
- * not exist. Reads via the port so the hash matches the bytes cms-core sees.
20
+ * not exist. Hashes the bytes, as cms-core does for a read and a write, so the
21
+ * values compare exactly.
17
22
  */
18
23
  export async function hashSource(fs, sourcePath) {
19
24
  if (!(await fs.exists(sourcePath)))
20
25
  return null;
21
- const raw = await fs.readFile(sourcePath);
22
- return hashContent(raw);
26
+ return digestBytes(await fs.readBytes(sourcePath));
23
27
  }
24
28
  /**
25
29
  * One run of an expensive read at a time, shared by every caller that asks while it is in flight.
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":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AAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAA;CACtC;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,mBAAmB,GAAG,gBAAgB,CA+nBxE"}
package/dist/server.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CmsCommitConflictError, isUnsafeFolder, listFilteredMedia, listProjectImages, MEDIA_CURSOR_TYPE_MISMATCH, MEDIA_INVALID_FOLDER, MediaCursorError, mediaErrorStatus, parseMediaTypeFilter, parseProjectCmsConfig, readRouteMap, resolveByteRange, resolvePathnameFromSpec, scanRouteCollections, sitePathname, } from '@nuasite/cms-core';
2
2
  import { filterMediaItems } from '@nuasite/cms-types';
3
- import { hashContent, hashSource, KeyedMutex, SharedRun } from "./concurrency.js";
3
+ import { hashSource, KeyedMutex, SharedRun } from "./concurrency.js";
4
4
  import { STATUS_BY_CODE, } from "./types.js";
5
5
  /** Features the sidecar advertises so older/newer clients can degrade gracefully. */
6
6
  export const SIDECAR_FEATURES = [
@@ -92,6 +92,27 @@ async function parseJson(req) {
92
92
  return { ok: false, response: error('validation', 'Invalid JSON body') };
93
93
  }
94
94
  }
95
+ /** A body that may be absent: no body reads as `undefined`, anything else must be JSON. */
96
+ async function parseOptionalJson(req) {
97
+ const text = await req.text();
98
+ if (text.trim() === '')
99
+ return { ok: true, value: undefined };
100
+ try {
101
+ // See `parseJson`: the route validates every field it reads.
102
+ const value = JSON.parse(text);
103
+ return { ok: true, value };
104
+ }
105
+ catch {
106
+ return { ok: false, response: error('validation', 'Invalid JSON body') };
107
+ }
108
+ }
109
+ function isOptionalHash(value) {
110
+ return value === undefined || (typeof value === 'string' && value !== '');
111
+ }
112
+ /** A JSON object, the only shape a request body takes. */
113
+ function isBodyObject(value) {
114
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
115
+ }
95
116
  function parseEntriesQuery(url) {
96
117
  const fields = url.searchParams.get('fields') ?? undefined;
97
118
  const rawDraft = url.searchParams.get('draft');
@@ -527,6 +548,7 @@ export function createServer(opts) {
527
548
  frontmatter,
528
549
  body: result.content,
529
550
  bodyStartLine: 0,
551
+ sourceHash: result.sourceHash,
530
552
  };
531
553
  return json(entry);
532
554
  }
@@ -556,25 +578,10 @@ export function createServer(opts) {
556
578
  if (!existing)
557
579
  return error('not_found', `Entry not found: ${collection}/${slug}`);
558
580
  const sourcePath = existing.sourcePath;
559
- const existingFrontmatter = existing.frontmatter;
560
- /** The 409 with the entry as it is now, so the client can offer "use server" vs "use ours". */
561
- async function conflictResponse(serverHash) {
562
- const current = await core.getEntry(collection, slug);
563
- const conflict = {
564
- code: 'conflict',
565
- serverHash,
566
- serverFrontmatter: current?.frontmatter ?? existingFrontmatter,
567
- };
568
- if (current && current.content !== '')
569
- conflict.serverBody = current.content;
570
- return json(conflict, STATUS_BY_CODE.conflict);
571
- }
572
581
  return mutex.runExclusive(sourcePath, async () => {
573
582
  // Re-hash under the lock so a concurrent writer cannot slip in between.
574
- const serverHash = await hashSource(fs, sourcePath);
575
- if (body.baseHash !== undefined && serverHash !== null && body.baseHash !== serverHash) {
576
- return conflictResponse(serverHash);
577
- }
583
+ if (await isStale(sourcePath, body.baseHash))
584
+ return conflictResponse(collection, slug);
578
585
  let result;
579
586
  try {
580
587
  result = await core.updateEntry({
@@ -588,21 +595,40 @@ export function createServer(opts) {
588
595
  // The core's commit found the file changed by a writer outside this server's lock.
589
596
  if (!(cause instanceof CmsCommitConflictError))
590
597
  throw cause;
591
- const currentHash = await hashSource(fs, sourcePath);
592
598
  // Removed meanwhile: there is no server version to offer, only the plain conflict.
593
- if (currentHash === null)
599
+ if (await hashSource(fs, sourcePath) === null)
594
600
  throw cause;
595
- return conflictResponse(currentHash);
601
+ return conflictResponse(collection, slug);
596
602
  }
597
- if (!result.success)
598
- return mutationResponse(result);
599
- const newHash = await hashSource(fs, result.sourcePath ?? sourcePath);
600
- const enriched = { ...result };
601
- if (newHash !== null)
602
- enriched.sourceHash = newHash;
603
- return json(enriched);
603
+ // The result carries the hash of the bytes the core wrote; hashing the file again here
604
+ // could pick up a write that landed after it.
605
+ return mutationResponse(result);
604
606
  });
605
607
  }
608
+ /** Whether `baseHash` was given and no longer matches the file. Call under the file's lock. */
609
+ async function isStale(sourcePath, baseHash) {
610
+ if (baseHash === undefined)
611
+ return false;
612
+ const serverHash = await hashSource(fs, sourcePath);
613
+ return serverHash !== null && serverHash !== baseHash;
614
+ }
615
+ /**
616
+ * The 409 with the entry as it is now, so the client can offer "use server" vs "use ours". The
617
+ * hash and the version come from one read, so they always describe the same bytes.
618
+ */
619
+ async function conflictResponse(collection, slug) {
620
+ const current = await core.getEntry(collection, slug);
621
+ if (current === null)
622
+ return error('conflict', `Entry changed and was removed meanwhile: ${collection}/${slug}`);
623
+ const conflict = {
624
+ code: 'conflict',
625
+ serverHash: current.sourceHash,
626
+ serverFrontmatter: current.frontmatter,
627
+ };
628
+ if (current.content !== '')
629
+ conflict.serverBody = current.content;
630
+ return json(conflict, STATUS_BY_CODE.conflict);
631
+ }
606
632
  async function fetchHandler(req) {
607
633
  const url = new URL(req.url);
608
634
  let pathname = url.pathname;
@@ -709,7 +735,7 @@ export function createServer(opts) {
709
735
  if (method === 'PATCH')
710
736
  return updateEntryRoute(collection, slug, req);
711
737
  if (method === 'DELETE')
712
- return deleteEntryRoute(collection, slug);
738
+ return deleteEntryRoute(collection, slug, req);
713
739
  return error('unsupported', `Unsupported: ${method} /collections/${collection}/entries/${slug}`);
714
740
  }
715
741
  if (action === 'rename' && method === 'POST')
@@ -763,13 +789,8 @@ export function createServer(opts) {
763
789
  body: body.body,
764
790
  fileExtension: body.fileExtension,
765
791
  });
766
- if (!result.success)
767
- return mutationResponse(result);
768
- const newHash = result.sourcePath ? await hashSource(fs, result.sourcePath) : null;
769
- const enriched = { ...result };
770
- if (newHash !== null)
771
- enriched.sourceHash = newHash;
772
- return json(enriched);
792
+ // The result carries the hash of the bytes the core wrote.
793
+ return mutationResponse(result);
773
794
  }
774
795
  async function updateEntryRoute(collection, slug, req) {
775
796
  const parsed = await parseJson(req);
@@ -777,11 +798,21 @@ export function createServer(opts) {
777
798
  return parsed.response;
778
799
  return patchEntry(collection, slug, parsed.value);
779
800
  }
780
- async function deleteEntryRoute(collection, slug) {
801
+ async function deleteEntryRoute(collection, slug, req) {
802
+ // The body is optional: a client that sends no `baseHash` deletes unchecked, as before.
803
+ const parsed = await parseOptionalJson(req);
804
+ if (!parsed.ok)
805
+ return parsed.response;
806
+ if (parsed.value !== undefined && !isBodyObject(parsed.value))
807
+ return error('validation', 'The body must be a JSON object');
808
+ if (!isOptionalHash(parsed.value?.baseHash))
809
+ return error('validation', '"baseHash" must be a non-empty string');
781
810
  const existing = await core.getEntry(collection, slug);
782
811
  if (!existing)
783
812
  return error('not_found', `Entry not found: ${collection}/${slug}`);
784
813
  return mutex.runExclusive(existing.sourcePath, async () => {
814
+ if (await isStale(existing.sourcePath, parsed.value?.baseHash))
815
+ return conflictResponse(collection, slug);
785
816
  const result = await core.deleteEntry(collection, slug);
786
817
  return mutationResponse(result);
787
818
  });
@@ -793,18 +824,16 @@ export function createServer(opts) {
793
824
  if (typeof parsed.value.to !== 'string' || parsed.value.to.trim() === '') {
794
825
  return error('validation', 'A non-empty "to" slug is required');
795
826
  }
827
+ if (!isOptionalHash(parsed.value.baseHash))
828
+ return error('validation', '"baseHash" must be a non-empty string');
796
829
  const existing = await core.getEntry(collection, slug);
797
830
  if (!existing)
798
831
  return error('not_found', `Entry not found: ${collection}/${slug}`);
799
832
  return mutex.runExclusive(existing.sourcePath, async () => {
800
- const result = await core.renameEntry(collection, slug, parsed.value.to);
801
- if (!result.success)
802
- return mutationResponse(result);
803
- const newHash = result.sourcePath ? await hashSource(fs, result.sourcePath) : null;
804
- const enriched = { ...result };
805
- if (newHash !== null)
806
- enriched.sourceHash = newHash;
807
- return json(enriched);
833
+ if (await isStale(existing.sourcePath, parsed.value.baseHash))
834
+ return conflictResponse(collection, slug);
835
+ // The result carries the hash of the bytes the core wrote at the new path.
836
+ return mutationResponse(await core.renameEntry(collection, slug, parsed.value.to));
808
837
  });
809
838
  }
810
839
  async function addArrayRoute(collection, slug, req) {