@nuasite/cms-sidecar 0.58.2 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -14888,17 +14888,17 @@ var require_visit = __commonJS((exports) => {
14888
14888
  visit.BREAK = BREAK;
14889
14889
  visit.SKIP = SKIP;
14890
14890
  visit.REMOVE = REMOVE;
14891
- function visit_(key, node, visitor, path) {
14892
- const ctrl = callVisitor(key, node, visitor, path);
14891
+ function visit_(key, node, visitor, path3) {
14892
+ const ctrl = callVisitor(key, node, visitor, path3);
14893
14893
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
14894
- replaceNode(key, path, ctrl);
14895
- return visit_(key, ctrl, visitor, path);
14894
+ replaceNode(key, path3, ctrl);
14895
+ return visit_(key, ctrl, visitor, path3);
14896
14896
  }
14897
14897
  if (typeof ctrl !== "symbol") {
14898
14898
  if (identity.isCollection(node)) {
14899
- path = Object.freeze(path.concat(node));
14899
+ path3 = Object.freeze(path3.concat(node));
14900
14900
  for (let i = 0;i < node.items.length; ++i) {
14901
- const ci = visit_(i, node.items[i], visitor, path);
14901
+ const ci = visit_(i, node.items[i], visitor, path3);
14902
14902
  if (typeof ci === "number")
14903
14903
  i = ci - 1;
14904
14904
  else if (ci === BREAK)
@@ -14909,13 +14909,13 @@ var require_visit = __commonJS((exports) => {
14909
14909
  }
14910
14910
  }
14911
14911
  } else if (identity.isPair(node)) {
14912
- path = Object.freeze(path.concat(node));
14913
- const ck = visit_("key", node.key, visitor, path);
14912
+ path3 = Object.freeze(path3.concat(node));
14913
+ const ck = visit_("key", node.key, visitor, path3);
14914
14914
  if (ck === BREAK)
14915
14915
  return BREAK;
14916
14916
  else if (ck === REMOVE)
14917
14917
  node.key = null;
14918
- const cv = visit_("value", node.value, visitor, path);
14918
+ const cv = visit_("value", node.value, visitor, path3);
14919
14919
  if (cv === BREAK)
14920
14920
  return BREAK;
14921
14921
  else if (cv === REMOVE)
@@ -14936,17 +14936,17 @@ var require_visit = __commonJS((exports) => {
14936
14936
  visitAsync.BREAK = BREAK;
14937
14937
  visitAsync.SKIP = SKIP;
14938
14938
  visitAsync.REMOVE = REMOVE;
14939
- async function visitAsync_(key, node, visitor, path) {
14940
- const ctrl = await callVisitor(key, node, visitor, path);
14939
+ async function visitAsync_(key, node, visitor, path3) {
14940
+ const ctrl = await callVisitor(key, node, visitor, path3);
14941
14941
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
14942
- replaceNode(key, path, ctrl);
14943
- return visitAsync_(key, ctrl, visitor, path);
14942
+ replaceNode(key, path3, ctrl);
14943
+ return visitAsync_(key, ctrl, visitor, path3);
14944
14944
  }
14945
14945
  if (typeof ctrl !== "symbol") {
14946
14946
  if (identity.isCollection(node)) {
14947
- path = Object.freeze(path.concat(node));
14947
+ path3 = Object.freeze(path3.concat(node));
14948
14948
  for (let i = 0;i < node.items.length; ++i) {
14949
- const ci = await visitAsync_(i, node.items[i], visitor, path);
14949
+ const ci = await visitAsync_(i, node.items[i], visitor, path3);
14950
14950
  if (typeof ci === "number")
14951
14951
  i = ci - 1;
14952
14952
  else if (ci === BREAK)
@@ -14957,13 +14957,13 @@ var require_visit = __commonJS((exports) => {
14957
14957
  }
14958
14958
  }
14959
14959
  } else if (identity.isPair(node)) {
14960
- path = Object.freeze(path.concat(node));
14961
- const ck = await visitAsync_("key", node.key, visitor, path);
14960
+ path3 = Object.freeze(path3.concat(node));
14961
+ const ck = await visitAsync_("key", node.key, visitor, path3);
14962
14962
  if (ck === BREAK)
14963
14963
  return BREAK;
14964
14964
  else if (ck === REMOVE)
14965
14965
  node.key = null;
14966
- const cv = await visitAsync_("value", node.value, visitor, path);
14966
+ const cv = await visitAsync_("value", node.value, visitor, path3);
14967
14967
  if (cv === BREAK)
14968
14968
  return BREAK;
14969
14969
  else if (cv === REMOVE)
@@ -14990,23 +14990,23 @@ var require_visit = __commonJS((exports) => {
14990
14990
  }
14991
14991
  return visitor;
14992
14992
  }
14993
- function callVisitor(key, node, visitor, path) {
14993
+ function callVisitor(key, node, visitor, path3) {
14994
14994
  if (typeof visitor === "function")
14995
- return visitor(key, node, path);
14995
+ return visitor(key, node, path3);
14996
14996
  if (identity.isMap(node))
14997
- return visitor.Map?.(key, node, path);
14997
+ return visitor.Map?.(key, node, path3);
14998
14998
  if (identity.isSeq(node))
14999
- return visitor.Seq?.(key, node, path);
14999
+ return visitor.Seq?.(key, node, path3);
15000
15000
  if (identity.isPair(node))
15001
- return visitor.Pair?.(key, node, path);
15001
+ return visitor.Pair?.(key, node, path3);
15002
15002
  if (identity.isScalar(node))
15003
- return visitor.Scalar?.(key, node, path);
15003
+ return visitor.Scalar?.(key, node, path3);
15004
15004
  if (identity.isAlias(node))
15005
- return visitor.Alias?.(key, node, path);
15005
+ return visitor.Alias?.(key, node, path3);
15006
15006
  return;
15007
15007
  }
15008
- function replaceNode(key, path, node) {
15009
- const parent = path[path.length - 1];
15008
+ function replaceNode(key, path3, node) {
15009
+ const parent = path3[path3.length - 1];
15010
15010
  if (identity.isCollection(parent)) {
15011
15011
  parent.items[key] = node;
15012
15012
  } else if (identity.isPair(parent)) {
@@ -15563,10 +15563,10 @@ var require_Collection = __commonJS((exports) => {
15563
15563
  var createNode = require_createNode();
15564
15564
  var identity = require_identity();
15565
15565
  var Node = require_Node();
15566
- function collectionFromPath(schema, path, value) {
15566
+ function collectionFromPath(schema, path3, value) {
15567
15567
  let v = value;
15568
- for (let i = path.length - 1;i >= 0; --i) {
15569
- const k = path[i];
15568
+ for (let i = path3.length - 1;i >= 0; --i) {
15569
+ const k = path3[i];
15570
15570
  if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
15571
15571
  const a = [];
15572
15572
  a[k] = v;
@@ -15585,7 +15585,7 @@ var require_Collection = __commonJS((exports) => {
15585
15585
  sourceObjects: new Map
15586
15586
  });
15587
15587
  }
15588
- var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done;
15588
+ var isEmptyPath = (path3) => path3 == null || typeof path3 === "object" && !!path3[Symbol.iterator]().next().done;
15589
15589
 
15590
15590
  class Collection extends Node.NodeBase {
15591
15591
  constructor(type, schema) {
@@ -15606,11 +15606,11 @@ var require_Collection = __commonJS((exports) => {
15606
15606
  copy.range = this.range.slice();
15607
15607
  return copy;
15608
15608
  }
15609
- addIn(path, value) {
15610
- if (isEmptyPath(path))
15609
+ addIn(path3, value) {
15610
+ if (isEmptyPath(path3))
15611
15611
  this.add(value);
15612
15612
  else {
15613
- const [key, ...rest] = path;
15613
+ const [key, ...rest] = path3;
15614
15614
  const node = this.get(key, true);
15615
15615
  if (identity.isCollection(node))
15616
15616
  node.addIn(rest, value);
@@ -15620,8 +15620,8 @@ var require_Collection = __commonJS((exports) => {
15620
15620
  throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
15621
15621
  }
15622
15622
  }
15623
- deleteIn(path) {
15624
- const [key, ...rest] = path;
15623
+ deleteIn(path3) {
15624
+ const [key, ...rest] = path3;
15625
15625
  if (rest.length === 0)
15626
15626
  return this.delete(key);
15627
15627
  const node = this.get(key, true);
@@ -15630,8 +15630,8 @@ var require_Collection = __commonJS((exports) => {
15630
15630
  else
15631
15631
  throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
15632
15632
  }
15633
- getIn(path, keepScalar) {
15634
- const [key, ...rest] = path;
15633
+ getIn(path3, keepScalar) {
15634
+ const [key, ...rest] = path3;
15635
15635
  const node = this.get(key, true);
15636
15636
  if (rest.length === 0)
15637
15637
  return !keepScalar && identity.isScalar(node) ? node.value : node;
@@ -15646,15 +15646,15 @@ var require_Collection = __commonJS((exports) => {
15646
15646
  return n == null || allowScalar && identity.isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag;
15647
15647
  });
15648
15648
  }
15649
- hasIn(path) {
15650
- const [key, ...rest] = path;
15649
+ hasIn(path3) {
15650
+ const [key, ...rest] = path3;
15651
15651
  if (rest.length === 0)
15652
15652
  return this.has(key);
15653
15653
  const node = this.get(key, true);
15654
15654
  return identity.isCollection(node) ? node.hasIn(rest) : false;
15655
15655
  }
15656
- setIn(path, value) {
15657
- const [key, ...rest] = path;
15656
+ setIn(path3, value) {
15657
+ const [key, ...rest] = path3;
15658
15658
  if (rest.length === 0) {
15659
15659
  this.set(key, value);
15660
15660
  } else {
@@ -18044,9 +18044,9 @@ var require_Document = __commonJS((exports) => {
18044
18044
  if (assertCollection(this.contents))
18045
18045
  this.contents.add(value);
18046
18046
  }
18047
- addIn(path, value) {
18047
+ addIn(path3, value) {
18048
18048
  if (assertCollection(this.contents))
18049
- this.contents.addIn(path, value);
18049
+ this.contents.addIn(path3, value);
18050
18050
  }
18051
18051
  createAlias(node, name) {
18052
18052
  if (!node.anchor) {
@@ -18095,30 +18095,30 @@ var require_Document = __commonJS((exports) => {
18095
18095
  delete(key) {
18096
18096
  return assertCollection(this.contents) ? this.contents.delete(key) : false;
18097
18097
  }
18098
- deleteIn(path) {
18099
- if (Collection.isEmptyPath(path)) {
18098
+ deleteIn(path3) {
18099
+ if (Collection.isEmptyPath(path3)) {
18100
18100
  if (this.contents == null)
18101
18101
  return false;
18102
18102
  this.contents = null;
18103
18103
  return true;
18104
18104
  }
18105
- return assertCollection(this.contents) ? this.contents.deleteIn(path) : false;
18105
+ return assertCollection(this.contents) ? this.contents.deleteIn(path3) : false;
18106
18106
  }
18107
18107
  get(key, keepScalar) {
18108
18108
  return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : undefined;
18109
18109
  }
18110
- getIn(path, keepScalar) {
18111
- if (Collection.isEmptyPath(path))
18110
+ getIn(path3, keepScalar) {
18111
+ if (Collection.isEmptyPath(path3))
18112
18112
  return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
18113
- return identity.isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : undefined;
18113
+ return identity.isCollection(this.contents) ? this.contents.getIn(path3, keepScalar) : undefined;
18114
18114
  }
18115
18115
  has(key) {
18116
18116
  return identity.isCollection(this.contents) ? this.contents.has(key) : false;
18117
18117
  }
18118
- hasIn(path) {
18119
- if (Collection.isEmptyPath(path))
18118
+ hasIn(path3) {
18119
+ if (Collection.isEmptyPath(path3))
18120
18120
  return this.contents !== undefined;
18121
- return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;
18121
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path3) : false;
18122
18122
  }
18123
18123
  set(key, value) {
18124
18124
  if (this.contents == null) {
@@ -18127,13 +18127,13 @@ var require_Document = __commonJS((exports) => {
18127
18127
  this.contents.set(key, value);
18128
18128
  }
18129
18129
  }
18130
- setIn(path, value) {
18131
- if (Collection.isEmptyPath(path)) {
18130
+ setIn(path3, value) {
18131
+ if (Collection.isEmptyPath(path3)) {
18132
18132
  this.contents = value;
18133
18133
  } else if (this.contents == null) {
18134
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);
18134
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path3), value);
18135
18135
  } else if (assertCollection(this.contents)) {
18136
- this.contents.setIn(path, value);
18136
+ this.contents.setIn(path3, value);
18137
18137
  }
18138
18138
  }
18139
18139
  setSchema(version, options = {}) {
@@ -20027,9 +20027,9 @@ var require_cst_visit = __commonJS((exports) => {
20027
20027
  visit.BREAK = BREAK;
20028
20028
  visit.SKIP = SKIP;
20029
20029
  visit.REMOVE = REMOVE;
20030
- visit.itemAtPath = (cst, path) => {
20030
+ visit.itemAtPath = (cst, path3) => {
20031
20031
  let item = cst;
20032
- for (const [field, index] of path) {
20032
+ for (const [field, index] of path3) {
20033
20033
  const tok = item?.[field];
20034
20034
  if (tok && "items" in tok) {
20035
20035
  item = tok.items[index];
@@ -20038,23 +20038,23 @@ var require_cst_visit = __commonJS((exports) => {
20038
20038
  }
20039
20039
  return item;
20040
20040
  };
20041
- visit.parentCollection = (cst, path) => {
20042
- const parent = visit.itemAtPath(cst, path.slice(0, -1));
20043
- const field = path[path.length - 1][0];
20041
+ visit.parentCollection = (cst, path3) => {
20042
+ const parent = visit.itemAtPath(cst, path3.slice(0, -1));
20043
+ const field = path3[path3.length - 1][0];
20044
20044
  const coll = parent?.[field];
20045
20045
  if (coll && "items" in coll)
20046
20046
  return coll;
20047
20047
  throw new Error("Parent collection not found");
20048
20048
  };
20049
- function _visit(path, item, visitor) {
20050
- let ctrl = visitor(item, path);
20049
+ function _visit(path3, item, visitor) {
20050
+ let ctrl = visitor(item, path3);
20051
20051
  if (typeof ctrl === "symbol")
20052
20052
  return ctrl;
20053
20053
  for (const field of ["key", "value"]) {
20054
20054
  const token = item[field];
20055
20055
  if (token && "items" in token) {
20056
20056
  for (let i = 0;i < token.items.length; ++i) {
20057
- const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);
20057
+ const ci = _visit(Object.freeze(path3.concat([[field, i]])), token.items[i], visitor);
20058
20058
  if (typeof ci === "number")
20059
20059
  i = ci - 1;
20060
20060
  else if (ci === BREAK)
@@ -20065,10 +20065,10 @@ var require_cst_visit = __commonJS((exports) => {
20065
20065
  }
20066
20066
  }
20067
20067
  if (typeof ctrl === "function" && field === "key")
20068
- ctrl = ctrl(item, path);
20068
+ ctrl = ctrl(item, path3);
20069
20069
  }
20070
20070
  }
20071
- return typeof ctrl === "function" ? ctrl(item, path) : ctrl;
20071
+ return typeof ctrl === "function" ? ctrl(item, path3) : ctrl;
20072
20072
  }
20073
20073
  exports.visit = visit;
20074
20074
  });
@@ -21337,14 +21337,14 @@ var require_parser = __commonJS((exports) => {
21337
21337
  case "scalar":
21338
21338
  case "single-quoted-scalar":
21339
21339
  case "double-quoted-scalar": {
21340
- const fs = this.flowScalar(this.type);
21340
+ const fs3 = this.flowScalar(this.type);
21341
21341
  if (atNextItem || it.value) {
21342
- map.items.push({ start, key: fs, sep: [] });
21342
+ map.items.push({ start, key: fs3, sep: [] });
21343
21343
  this.onKeyLine = true;
21344
21344
  } else if (it.sep) {
21345
- this.stack.push(fs);
21345
+ this.stack.push(fs3);
21346
21346
  } else {
21347
- Object.assign(it, { key: fs, sep: [] });
21347
+ Object.assign(it, { key: fs3, sep: [] });
21348
21348
  this.onKeyLine = true;
21349
21349
  }
21350
21350
  return;
@@ -21472,13 +21472,13 @@ var require_parser = __commonJS((exports) => {
21472
21472
  case "scalar":
21473
21473
  case "single-quoted-scalar":
21474
21474
  case "double-quoted-scalar": {
21475
- const fs = this.flowScalar(this.type);
21475
+ const fs3 = this.flowScalar(this.type);
21476
21476
  if (!it || it.value)
21477
- fc.items.push({ start: [], key: fs, sep: [] });
21477
+ fc.items.push({ start: [], key: fs3, sep: [] });
21478
21478
  else if (it.sep)
21479
- this.stack.push(fs);
21479
+ this.stack.push(fs3);
21480
21480
  else
21481
- Object.assign(it, { key: fs, sep: [] });
21481
+ Object.assign(it, { key: fs3, sep: [] });
21482
21482
  return;
21483
21483
  }
21484
21484
  case "flow-map-end":
@@ -21780,6 +21780,424 @@ var require_dist = __commonJS((exports) => {
21780
21780
  exports.visitAsync = visit.visitAsync;
21781
21781
  });
21782
21782
 
21783
+ // ../cms-core/src/fs/node-fs.ts
21784
+ import fs from "fs/promises";
21785
+ import path from "path";
21786
+
21787
+ // ../cms-core/src/fs/glob.ts
21788
+ class UnreadableDirectoryError extends Error {
21789
+ directory;
21790
+ code;
21791
+ constructor(directory, code, options) {
21792
+ super(`Cannot read directory "${directory}" (${code})`, options);
21793
+ this.name = "UnreadableDirectoryError";
21794
+ this.directory = directory;
21795
+ this.code = code;
21796
+ }
21797
+ }
21798
+ function globToRegExp(glob) {
21799
+ let re = "";
21800
+ for (let i = 0;i < glob.length; i++) {
21801
+ const c = glob[i];
21802
+ if (c === "*") {
21803
+ if (glob[i + 1] === "*") {
21804
+ re += ".*";
21805
+ i++;
21806
+ if (glob[i + 1] === "/")
21807
+ i++;
21808
+ } else {
21809
+ re += "[^/]*";
21810
+ }
21811
+ } else if (c === "?") {
21812
+ re += "[^/]";
21813
+ } else if (c === "{") {
21814
+ const end = glob.indexOf("}", i);
21815
+ if (end === -1) {
21816
+ re += "\\{";
21817
+ } else {
21818
+ const opts = glob.slice(i + 1, end).split(",").map((s) => s.replace(/[.+^${}()|[\]\\]/g, "\\$&"));
21819
+ re += `(?:${opts.join("|")})`;
21820
+ i = end;
21821
+ }
21822
+ } else if (".+^$()|[]\\".includes(c)) {
21823
+ re += `\\${c}`;
21824
+ } else {
21825
+ re += c;
21826
+ }
21827
+ }
21828
+ return new RegExp(`^${re}$`);
21829
+ }
21830
+ function globMayMatchUnder(glob, dir) {
21831
+ if (/\{[^}]*\//.test(glob))
21832
+ return true;
21833
+ const segments = glob.split("/").filter((segment) => segment !== "" && segment !== ".");
21834
+ const dirs = dir.split("/").filter((segment) => segment !== "" && segment !== ".");
21835
+ const reaches = (i, j) => {
21836
+ if (j === dirs.length)
21837
+ return i < segments.length;
21838
+ if (i >= segments.length)
21839
+ return false;
21840
+ if (segments[i].includes("**"))
21841
+ return true;
21842
+ return globToRegExp(segments[i]).test(dirs[j]) && reaches(i + 1, j + 1);
21843
+ };
21844
+ return reaches(0, 0);
21845
+ }
21846
+
21847
+ // ../cms-core/src/fs/node-fs.ts
21848
+ function resolveWithinRoot(root, filePath) {
21849
+ const resolvedRoot = path.resolve(root);
21850
+ const isAbsoluteFs = filePath.startsWith(resolvedRoot);
21851
+ const normalizedPath = !isAbsoluteFs && filePath.startsWith("/") ? filePath.slice(1) : filePath;
21852
+ const fullPath = path.isAbsolute(normalizedPath) ? path.resolve(normalizedPath) : path.resolve(resolvedRoot, normalizedPath);
21853
+ if (!fullPath.startsWith(resolvedRoot + path.sep) && fullPath !== resolvedRoot) {
21854
+ throw new Error(`Path traversal detected: ${filePath}`);
21855
+ }
21856
+ return fullPath;
21857
+ }
21858
+ function isNodeError(error) {
21859
+ return error instanceof Error && "code" in error;
21860
+ }
21861
+ var isWithin = (root, abs) => abs === root || abs.startsWith(root.endsWith(path.sep) ? root : root + path.sep);
21862
+ var relativeTo = (absRoot, abs) => path.relative(absRoot, abs).split(path.sep).join("/") || ".";
21863
+ async function walkFiles(walk, absDir, linked) {
21864
+ if (linked.size > 0 && walk.linkedDirectoriesLeft !== undefined && walk.linkedDirectoriesLeft-- <= 0) {
21865
+ throw new Error(`More than ${walk.maxLinkedDirectories} directories to list behind symbolic links`);
21866
+ }
21867
+ let dirEntries;
21868
+ try {
21869
+ dirEntries = await fs.readdir(absDir, { withFileTypes: true });
21870
+ } catch (error) {
21871
+ if (!isNodeError(error))
21872
+ throw error;
21873
+ if (error.code === "ENOENT" || error.code === "ENOTDIR")
21874
+ return [];
21875
+ throw new UnreadableDirectoryError(relativeTo(walk.absRoot, absDir), error.code ?? "unknown error", { cause: error });
21876
+ }
21877
+ const out = [];
21878
+ for (const entry of dirEntries) {
21879
+ const abs = path.join(absDir, entry.name);
21880
+ let isDirectory = entry.isDirectory();
21881
+ let isFile = entry.isFile();
21882
+ let within = linked;
21883
+ let real = null;
21884
+ if (walk.followSymlinks && entry.isSymbolicLink()) {
21885
+ const target = await fs.stat(abs).catch(() => null);
21886
+ real = target?.isDirectory() ? await fs.realpath(abs).catch(() => abs) : null;
21887
+ isFile = target?.isFile() ?? false;
21888
+ isDirectory = real !== null && !linked.has(real);
21889
+ if (real !== null)
21890
+ within = new Set([...linked, real]);
21891
+ }
21892
+ if (isDirectory) {
21893
+ if (walk.skip(relativeTo(walk.absRoot, abs)))
21894
+ continue;
21895
+ if (!walk.mayHold(relativeTo(walk.absRoot, abs)))
21896
+ continue;
21897
+ if (real !== null && !isWithin(walk.realRoot, real)) {
21898
+ throw new Error(`Symbolic link "${relativeTo(walk.absRoot, abs)}" leads out of the project root`);
21899
+ }
21900
+ out.push(...await walkFiles(walk, abs, within));
21901
+ } else if (isFile) {
21902
+ out.push(relativeTo(walk.absRoot, abs));
21903
+ }
21904
+ }
21905
+ return out;
21906
+ }
21907
+ function staticPrefixDir(pattern) {
21908
+ const segments = pattern.split("/");
21909
+ const staticSegments = [];
21910
+ for (const segment of segments) {
21911
+ if (/[*?{}[\]]/.test(segment))
21912
+ break;
21913
+ staticSegments.push(segment);
21914
+ }
21915
+ if (staticSegments.length === segments.length) {
21916
+ staticSegments.pop();
21917
+ }
21918
+ return staticSegments.join("/");
21919
+ }
21920
+ async function writeAtomically(fullPath, content) {
21921
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
21922
+ const tempPath = `${fullPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
21923
+ try {
21924
+ await fs.writeFile(tempPath, content);
21925
+ await fs.rename(tempPath, fullPath);
21926
+ } catch (error) {
21927
+ await fs.rm(tempPath, { force: true });
21928
+ throw error;
21929
+ }
21930
+ }
21931
+ function createNodeFs(root) {
21932
+ const resolvedRoot = path.resolve(root);
21933
+ const resolve = (p) => resolveWithinRoot(resolvedRoot, p);
21934
+ return {
21935
+ async readFile(filePath) {
21936
+ return fs.readFile(resolve(filePath), "utf-8");
21937
+ },
21938
+ async readBytes(filePath) {
21939
+ return fs.readFile(resolve(filePath));
21940
+ },
21941
+ async writeFile(filePath, content) {
21942
+ await writeAtomically(resolve(filePath), content);
21943
+ },
21944
+ async writeBytes(filePath, content) {
21945
+ await writeAtomically(resolve(filePath), content);
21946
+ },
21947
+ async rename(from, to) {
21948
+ const fullTo = resolve(to);
21949
+ await fs.mkdir(path.dirname(fullTo), { recursive: true });
21950
+ await fs.rename(resolve(from), fullTo);
21951
+ },
21952
+ async remove(filePath) {
21953
+ await fs.rm(resolve(filePath), { force: true });
21954
+ },
21955
+ async exists(filePath) {
21956
+ try {
21957
+ await fs.access(resolve(filePath));
21958
+ return true;
21959
+ } catch {
21960
+ return false;
21961
+ }
21962
+ },
21963
+ async list(dir) {
21964
+ try {
21965
+ const entries = await fs.readdir(resolve(dir), { withFileTypes: true });
21966
+ return entries.map((entry) => ({ name: entry.name, isDirectory: entry.isDirectory() }));
21967
+ } catch (error) {
21968
+ if (isNodeError(error) && error.code === "ENOENT")
21969
+ return [];
21970
+ throw error;
21971
+ }
21972
+ },
21973
+ async glob(pattern, options) {
21974
+ const baseRel = staticPrefixDir(pattern);
21975
+ const absBase = resolve(baseRel);
21976
+ const matcher = globToRegExp(pattern);
21977
+ const followSymlinks = options?.followSymlinks ?? false;
21978
+ const walk = {
21979
+ absRoot: resolvedRoot,
21980
+ mayHold: (dir) => globMayMatchUnder(pattern, dir),
21981
+ skip: options?.skipDirectory ?? (() => false),
21982
+ followSymlinks,
21983
+ realRoot: followSymlinks ? await fs.realpath(resolvedRoot).catch(() => resolvedRoot) : resolvedRoot,
21984
+ maxLinkedDirectories: options?.maxLinkedDirectories,
21985
+ linkedDirectoriesLeft: options?.maxLinkedDirectories
21986
+ };
21987
+ if (!walk.mayHold(relativeTo(resolvedRoot, absBase)))
21988
+ return [];
21989
+ const files = await walkFiles(walk, absBase, new Set);
21990
+ return files.filter((rel) => matcher.test(rel));
21991
+ },
21992
+ async stat(filePath) {
21993
+ const s = await fs.stat(resolve(filePath));
21994
+ return { mtimeMs: s.mtimeMs, size: s.size };
21995
+ }
21996
+ };
21997
+ }
21998
+ // ../cms-core/src/media/local.ts
21999
+ import { randomUUID } from "crypto";
22000
+ import fs2 from "fs/promises";
22001
+ import path2 from "path";
22002
+
22003
+ // ../cms-core/src/media/errors.ts
22004
+ var MEDIA_INVALID_ID = "Invalid media id";
22005
+ var MEDIA_INVALID_FOLDER = "Invalid folder name";
22006
+ var MEDIA_NOT_FOUND = "Media file not found";
22007
+ function mediaErrorStatus(error) {
22008
+ if (error === MEDIA_INVALID_ID || error === MEDIA_INVALID_FOLDER)
22009
+ return 400;
22010
+ if (error === MEDIA_NOT_FOUND)
22011
+ return 404;
22012
+ return 500;
22013
+ }
22014
+
22015
+ // ../cms-core/src/media/mime.ts
22016
+ function getFileExtension(filename) {
22017
+ const parts = filename.split(".");
22018
+ const ext = parts.length > 1 ? parts.pop()?.toLowerCase() ?? "" : "";
22019
+ return /^[a-z0-9]+$/.test(ext) ? ext : "";
22020
+ }
22021
+ var MIME_BY_EXT = {
22022
+ ".jpg": "image/jpeg",
22023
+ ".jpeg": "image/jpeg",
22024
+ ".png": "image/png",
22025
+ ".gif": "image/gif",
22026
+ ".webp": "image/webp",
22027
+ ".avif": "image/avif",
22028
+ ".svg": "image/svg+xml",
22029
+ ".ico": "image/x-icon",
22030
+ ".mp4": "video/mp4",
22031
+ ".webm": "video/webm",
22032
+ ".pdf": "application/pdf"
22033
+ };
22034
+ function mimeFromExt(ext) {
22035
+ return MIME_BY_EXT[ext] ?? "application/octet-stream";
22036
+ }
22037
+
22038
+ // ../cms-core/src/media/names.ts
22039
+ function hasDotSegment(value) {
22040
+ return value.split("/").some((s) => s === "." || s === "..");
22041
+ }
22042
+ function isUnsafeFolder(folder) {
22043
+ return folder.includes("\\") || folder.split("/").some((s) => {
22044
+ const decoded = s.replace(/%2e/gi, ".");
22045
+ return decoded === "." || decoded === "..";
22046
+ });
22047
+ }
22048
+
22049
+ // ../cms-core/src/media/local.ts
22050
+ function errorCode(error) {
22051
+ return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined;
22052
+ }
22053
+ function failure(action, error) {
22054
+ const code = errorCode(error);
22055
+ return code ? `Failed to ${action} (${code})` : `Failed to ${action}`;
22056
+ }
22057
+ async function hasSymlink(from, names) {
22058
+ let current = from;
22059
+ for (const name of names) {
22060
+ current += path2.sep + name;
22061
+ try {
22062
+ if ((await fs2.lstat(current)).isSymbolicLink())
22063
+ return true;
22064
+ } catch (error) {
22065
+ const code = errorCode(error);
22066
+ if (code === "ENOENT" || code === "ENOTDIR")
22067
+ return false;
22068
+ throw error;
22069
+ }
22070
+ }
22071
+ return false;
22072
+ }
22073
+ function createLocalStorageAdapter(options = {}) {
22074
+ const dir = path2.resolve(options.dir ?? "public/uploads");
22075
+ const base = dir.endsWith(path2.sep) ? dir.slice(0, -path2.sep.length) : dir;
22076
+ const urlPrefix = (options.urlPrefix ?? "/uploads").replace(/\/$/, "");
22077
+ async function resolveInside(relative, kind) {
22078
+ const segments = relative.split("/");
22079
+ if (relative.includes("\x00") || segments.some((s) => s === "" || s === "." || s === ".."))
22080
+ return null;
22081
+ if (path2.sep === "\\" && segments.some((s) => /[\\:]|[. ]$/.test(s)))
22082
+ return null;
22083
+ const resolved = path2.resolve(dir, ...segments);
22084
+ if (resolved !== [base, ...segments].join(path2.sep))
22085
+ return null;
22086
+ if (await hasSymlink(base, kind === "file" ? segments.slice(0, -1) : segments))
22087
+ return null;
22088
+ return resolved;
22089
+ }
22090
+ async function resolveFolder(input, use) {
22091
+ const folder = (input ?? "").split("/").filter(Boolean).join("/");
22092
+ if (!folder)
22093
+ return { folder, targetDir: dir };
22094
+ if (use === "write" && isUnsafeFolder(folder))
22095
+ return null;
22096
+ const targetDir = await resolveInside(folder, "folder");
22097
+ return targetDir ? { folder, targetDir } : null;
22098
+ }
22099
+ return {
22100
+ staticFiles: { urlPrefix, dir },
22101
+ async list(opts) {
22102
+ const limit = opts?.limit ?? 50;
22103
+ const offset = opts?.cursor ? parseInt(opts.cursor, 10) : 0;
22104
+ const nothing = { items: [], folders: [], hasMore: false };
22105
+ try {
22106
+ const target = await resolveFolder(opts?.folder, "read");
22107
+ if (!target)
22108
+ return nothing;
22109
+ const { folder, targetDir } = target;
22110
+ await fs2.mkdir(targetDir, { recursive: true });
22111
+ const entries = await fs2.readdir(targetDir, { withFileTypes: true });
22112
+ const folders = entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => ({
22113
+ name: e.name,
22114
+ path: folder ? `${folder}/${e.name}` : e.name
22115
+ })).sort((a, b) => a.name.localeCompare(b.name));
22116
+ const files = entries.filter((e) => e.isFile() && !e.name.startsWith("."));
22117
+ const withStats = await Promise.all(files.map(async (f) => {
22118
+ const filePath = path2.join(targetDir, f.name);
22119
+ const stat = await fs2.stat(filePath);
22120
+ return { name: f.name, stat };
22121
+ }));
22122
+ withStats.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
22123
+ const slice = withStats.slice(offset, offset + limit);
22124
+ const hasMore = offset + limit < withStats.length;
22125
+ const urlFolder = folder ? `/${folder}` : "";
22126
+ const items = slice.map((f) => {
22127
+ const ext = path2.extname(f.name).toLowerCase();
22128
+ const contentType = mimeFromExt(ext);
22129
+ return {
22130
+ id: folder ? `${folder}/${f.name}` : f.name,
22131
+ url: `${urlPrefix}${urlFolder}/${f.name}`,
22132
+ filename: f.name,
22133
+ contentType,
22134
+ uploadedAt: f.stat.mtime.toISOString(),
22135
+ folder: folder || undefined
22136
+ };
22137
+ });
22138
+ return {
22139
+ items,
22140
+ folders,
22141
+ hasMore,
22142
+ cursor: hasMore ? String(offset + limit) : undefined
22143
+ };
22144
+ } catch (error) {
22145
+ const code = errorCode(error);
22146
+ if (opts?.folder && (code === "ENOTDIR" || code === "EEXIST" || code === "ENAMETOOLONG"))
22147
+ return nothing;
22148
+ throw new Error(failure("list media", error));
22149
+ }
22150
+ },
22151
+ async upload(file, filename, contentType, uploadOpts) {
22152
+ try {
22153
+ const target = await resolveFolder(uploadOpts?.folder, "write");
22154
+ if (!target)
22155
+ return { success: false, error: MEDIA_INVALID_FOLDER };
22156
+ const { folder, targetDir } = target;
22157
+ await fs2.mkdir(targetDir, { recursive: true });
22158
+ const ext = getFileExtension(filename);
22159
+ const uuid = randomUUID();
22160
+ const newFilename = `${uuid}${ext ? `.${ext}` : ""}`;
22161
+ const filePath = path2.join(targetDir, newFilename);
22162
+ await fs2.writeFile(filePath, file);
22163
+ const urlFolder = folder ? `/${folder}` : "";
22164
+ const id = folder ? `${folder}/${newFilename}` : newFilename;
22165
+ return {
22166
+ success: true,
22167
+ url: `${urlPrefix}${urlFolder}/${newFilename}`,
22168
+ filename: newFilename,
22169
+ id
22170
+ };
22171
+ } catch (error) {
22172
+ return { success: false, error: failure("store media file", error) };
22173
+ }
22174
+ },
22175
+ async delete(id) {
22176
+ try {
22177
+ const filePath = await resolveInside(id, "file");
22178
+ if (!filePath)
22179
+ return { success: false, error: MEDIA_INVALID_ID };
22180
+ await fs2.unlink(filePath);
22181
+ return { success: true };
22182
+ } catch (error) {
22183
+ if (errorCode(error) === "ENOENT")
22184
+ return { success: false, error: MEDIA_NOT_FOUND };
22185
+ return { success: false, error: failure("delete media file", error) };
22186
+ }
22187
+ },
22188
+ async createFolder(folder) {
22189
+ try {
22190
+ const target = await resolveFolder(folder, "write");
22191
+ if (!target)
22192
+ return { success: false, error: MEDIA_INVALID_FOLDER };
22193
+ await fs2.mkdir(target.targetDir, { recursive: true });
22194
+ return { success: true };
22195
+ } catch (error) {
22196
+ return { success: false, error: failure("create folder", error) };
22197
+ }
22198
+ }
22199
+ };
22200
+ }
21783
22201
  // ../cms-core/src/asset-paths.ts
21784
22202
  function assetBaseDir(file) {
21785
22203
  const lastSlash = file.lastIndexOf("/");
@@ -22274,68 +22692,6 @@ function analyzeAstroSource(source) {
22274
22692
  }
22275
22693
  // ../cms-core/src/check-entries.ts
22276
22694
  var import_yaml = __toESM(require_dist(), 1);
22277
-
22278
- // ../cms-core/src/fs/glob.ts
22279
- class UnreadableDirectoryError extends Error {
22280
- directory;
22281
- code;
22282
- constructor(directory, code, options) {
22283
- super(`Cannot read directory "${directory}" (${code})`, options);
22284
- this.name = "UnreadableDirectoryError";
22285
- this.directory = directory;
22286
- this.code = code;
22287
- }
22288
- }
22289
- function globToRegExp(glob) {
22290
- let re = "";
22291
- for (let i = 0;i < glob.length; i++) {
22292
- const c = glob[i];
22293
- if (c === "*") {
22294
- if (glob[i + 1] === "*") {
22295
- re += ".*";
22296
- i++;
22297
- if (glob[i + 1] === "/")
22298
- i++;
22299
- } else {
22300
- re += "[^/]*";
22301
- }
22302
- } else if (c === "?") {
22303
- re += "[^/]";
22304
- } else if (c === "{") {
22305
- const end = glob.indexOf("}", i);
22306
- if (end === -1) {
22307
- re += "\\{";
22308
- } else {
22309
- const opts = glob.slice(i + 1, end).split(",").map((s) => s.replace(/[.+^${}()|[\]\\]/g, "\\$&"));
22310
- re += `(?:${opts.join("|")})`;
22311
- i = end;
22312
- }
22313
- } else if (".+^$()|[]\\".includes(c)) {
22314
- re += `\\${c}`;
22315
- } else {
22316
- re += c;
22317
- }
22318
- }
22319
- return new RegExp(`^${re}$`);
22320
- }
22321
- function globMayMatchUnder(glob, dir) {
22322
- if (/\{[^}]*\//.test(glob))
22323
- return true;
22324
- const segments = glob.split("/").filter((segment) => segment !== "" && segment !== ".");
22325
- const dirs = dir.split("/").filter((segment) => segment !== "" && segment !== ".");
22326
- const reaches = (i, j) => {
22327
- if (j === dirs.length)
22328
- return i < segments.length;
22329
- if (i >= segments.length)
22330
- return false;
22331
- if (segments[i].includes("**"))
22332
- return true;
22333
- return globToRegExp(segments[i]).test(dirs[j]) && reaches(i + 1, j + 1);
22334
- };
22335
- return reaches(0, 0);
22336
- }
22337
-
22338
- // ../cms-core/src/check-entries.ts
22339
22695
  var DATA_EXTENSIONS = new Set([".json", ".yaml", ".yml"]);
22340
22696
 
22341
22697
  // ../cms-types/src/field-values.ts
@@ -22501,8 +22857,8 @@ function computePathnameFromSpec(spec, data) {
22501
22857
  return;
22502
22858
  segments.push(seg.map && Object.hasOwn(seg.map, value) ? seg.map[value] : value);
22503
22859
  }
22504
- const path = ("/" + segments.join("/")).replace(/\/{2,}/g, "/").replace(/\/+$/, "");
22505
- return path === "" ? "/" : path;
22860
+ const path3 = ("/" + segments.join("/")).replace(/\/{2,}/g, "/").replace(/\/+$/, "");
22861
+ return path3 === "" ? "/" : path3;
22506
22862
  }
22507
22863
  function resolvePathnameFromSpec(def, data) {
22508
22864
  if (!def.pathname)
@@ -22714,36 +23070,36 @@ var UNREAD_CONTENT_CONFIG_PATHS = [
22714
23070
  "src/content/config.js",
22715
23071
  "src/content/config.mts"
22716
23072
  ];
22717
- async function classifyEmptyContentConfig(fs) {
23073
+ async function classifyEmptyContentConfig(fs3) {
22718
23074
  let found = false;
22719
23075
  for (const configPath of CONTENT_CONFIG_PATHS) {
22720
23076
  try {
22721
- await fs.stat(configPath);
23077
+ await fs3.stat(configPath);
22722
23078
  } catch {
22723
23079
  continue;
22724
23080
  }
22725
23081
  found = true;
22726
- if (parseSource(await fs.readFile(configPath)) === null) {
23082
+ if (parseSource(await fs3.readFile(configPath)) === null) {
22727
23083
  return "unparseable";
22728
23084
  }
22729
23085
  }
22730
23086
  return found ? "no-collections" : "missing";
22731
23087
  }
22732
- async function parseContentConfig(fs, cache) {
22733
- return (await readContentConfig(fs, cache)).parsed;
23088
+ async function parseContentConfig(fs3, cache) {
23089
+ return (await readContentConfig(fs3, cache)).parsed;
22734
23090
  }
22735
- async function readContentConfig(fs, cache) {
23091
+ async function readContentConfig(fs3, cache) {
22736
23092
  let unparsed;
22737
23093
  for (const configPath of CONTENT_CONFIG_PATHS) {
22738
23094
  let stat;
22739
23095
  try {
22740
- stat = await fs.stat(configPath);
23096
+ stat = await fs3.stat(configPath);
22741
23097
  } catch {
22742
23098
  continue;
22743
23099
  }
22744
23100
  let cached = cache.get(configPath);
22745
23101
  if (!cached || cached.mtimeMs !== stat.mtimeMs) {
22746
- const content = await fs.readFile(configPath);
23102
+ const content = await fs3.readFile(configPath);
22747
23103
  cached = { mtimeMs: stat.mtimeMs, ...readConfigSource(content) };
22748
23104
  cache.set(configPath, cached);
22749
23105
  }
@@ -23118,9 +23474,9 @@ function configOptionMentions(source, name) {
23118
23474
  if (!ast)
23119
23475
  return null;
23120
23476
  const mentions = [];
23121
- walkValues(ast.program, (path) => {
23122
- const { node, key } = path.at(-1);
23123
- const parent = path.at(-2)?.node;
23477
+ walkValues(ast.program, (path3) => {
23478
+ const { node, key } = path3.at(-1);
23479
+ const parent = path3.at(-2)?.node;
23124
23480
  const isKey = parent?.type === "ObjectProperty" && key === "key";
23125
23481
  const asString = node.type === "StringLiteral" ? node.value : node.type === "TemplateLiteral" && node.expressions.length === 0 ? node.quasis[0]?.value.cooked : undefined;
23126
23482
  const named = node.type === "Identifier" ? node.name === name : asString === name;
@@ -23148,8 +23504,8 @@ var TS_NODES_WITH_CODE = new Set([
23148
23504
  "TSParameterProperty"
23149
23505
  ]);
23150
23506
  var NODE_METADATA = new Set(["loc", "extra", "leadingComments", "trailingComments", "innerComments"]);
23151
- function walkValues(node, visit, path = [{ node, key: "" }]) {
23152
- visit(path);
23507
+ function walkValues(node, visit, path3 = [{ node, key: "" }]) {
23508
+ visit(path3);
23153
23509
  const children = Object.entries(node);
23154
23510
  for (const [key, child] of children) {
23155
23511
  if (NODE_METADATA.has(key))
@@ -23157,16 +23513,16 @@ function walkValues(node, visit, path = [{ node, key: "" }]) {
23157
23513
  for (const item of Array.isArray(child) ? child : [child]) {
23158
23514
  if (!isAstNode(item) || item.type.startsWith("TS") && !TS_NODES_WITH_CODE.has(item.type))
23159
23515
  continue;
23160
- path.push({ node: item, key });
23161
- walkValues(item, visit, path);
23162
- path.pop();
23516
+ path3.push({ node: item, key });
23517
+ walkValues(item, visit, path3);
23518
+ path3.pop();
23163
23519
  }
23164
23520
  }
23165
23521
  }
23166
- function isModuleLevelDeclarator(path, index) {
23167
- const holder = path[index - 2]?.node;
23522
+ function isModuleLevelDeclarator(path3, index) {
23523
+ const holder = path3[index - 2]?.node;
23168
23524
  if (holder?.type === "ExportNamedDeclaration")
23169
- return path[index - 3]?.node.type === "Program";
23525
+ return path3[index - 3]?.node.type === "Program";
23170
23526
  return holder?.type === "Program";
23171
23527
  }
23172
23528
  function isImmutableLiteral(node) {
@@ -23187,34 +23543,34 @@ function followedConstants(ast, bindings) {
23187
23543
  const member = object?.type === "ObjectExpression" ? literalMember(object, key) : undefined;
23188
23544
  return !!member && isImmutableLiteral(resolveExpression(member, new Map));
23189
23545
  };
23190
- const readIn = (path, index) => {
23546
+ const readIn = (path3, index) => {
23191
23547
  const calls = [];
23192
23548
  for (let at = index;; ) {
23193
- const parent = path[at - 1]?.node;
23194
- const { node, key } = path[at];
23549
+ const parent = path3[at - 1]?.node;
23550
+ const { node, key } = path3[at];
23195
23551
  if (!parent)
23196
23552
  return null;
23197
23553
  if (VALUE_WRAPPERS.has(parent.type) && key === "expression") {
23198
23554
  at--;
23199
- } else if (parent.type === "ObjectProperty" && key === "value" && path[at - 2]?.node.type === "ObjectExpression") {
23555
+ } else if (parent.type === "ObjectProperty" && key === "value" && path3[at - 2]?.node.type === "ObjectExpression") {
23200
23556
  at -= 2;
23201
23557
  } else if (parent.type === "CallExpression" && parent.arguments[0] === node && parent.callee.type === "Identifier" && READER_CALLS.includes(parent.callee.name)) {
23202
23558
  calls.push(parent.callee.name);
23203
23559
  at--;
23204
23560
  } else {
23205
- return parent.type === "VariableDeclarator" && key === "init" && parent.id.type === "Identifier" && isModuleLevelDeclarator(path, at - 1) ? { holder: parent.id.name, calls } : null;
23561
+ return parent.type === "VariableDeclarator" && key === "init" && parent.id.type === "Identifier" && isModuleLevelDeclarator(path3, at - 1) ? { holder: parent.id.name, calls } : null;
23206
23562
  }
23207
23563
  }
23208
23564
  };
23209
- const isValueRead = (path, index) => {
23565
+ const isValueRead = (path3, index) => {
23210
23566
  let at = index;
23211
- while (VALUE_WRAPPERS.has(path[at - 1]?.node.type ?? "") && path[at].key === "expression")
23567
+ while (VALUE_WRAPPERS.has(path3[at - 1]?.node.type ?? "") && path3[at].key === "expression")
23212
23568
  at--;
23213
- const parent = path[at - 1]?.node;
23214
- const { key } = path[at];
23569
+ const parent = path3[at - 1]?.node;
23570
+ const { key } = path3[at];
23215
23571
  switch (parent?.type) {
23216
23572
  case "ObjectProperty":
23217
- return key === "value" && path[at - 2]?.node.type === "ObjectExpression";
23573
+ return key === "value" && path3[at - 2]?.node.type === "ObjectExpression";
23218
23574
  case "CallExpression":
23219
23575
  case "OptionalCallExpression":
23220
23576
  case "NewExpression":
@@ -23230,9 +23586,9 @@ function followedConstants(ast, bindings) {
23230
23586
  return false;
23231
23587
  }
23232
23588
  };
23233
- walkValues(ast.program, (path) => {
23234
- const { node, key } = path.at(-1);
23235
- const parent = path.at(-2)?.node;
23589
+ walkValues(ast.program, (path3) => {
23590
+ const { node, key } = path3.at(-1);
23591
+ const parent = path3.at(-2)?.node;
23236
23592
  if (node.type !== "Identifier" || !parent)
23237
23593
  return;
23238
23594
  const { name } = node;
@@ -23245,14 +23601,14 @@ function followedConstants(ast, bindings) {
23245
23601
  anythingMayChange = true;
23246
23602
  if (READER_CALLS.includes(name) || name === "Object") {
23247
23603
  const imported = (parent.type === "ImportSpecifier" || parent.type === "ImportDefaultSpecifier" || parent.type === "ImportNamespaceSpecifier") && key === "local";
23248
- const grandparent = path.at(-3)?.node;
23604
+ const grandparent = path3.at(-3)?.node;
23249
23605
  const called = parent.type === "CallExpression" && key === "callee" || name === "Object" && parent.type === "MemberExpression" && key === "object" && !parent.computed && grandparent?.type === "CallExpression" && grandparent.callee === parent;
23250
23606
  if (!imported && !called)
23251
23607
  untrusted.add(name);
23252
23608
  }
23253
23609
  if (!bindings.has(name))
23254
23610
  return;
23255
- if (parent.type === "VariableDeclarator" && key === "id" && isModuleLevelDeclarator(path, path.length - 2))
23611
+ if (parent.type === "VariableDeclarator" && key === "id" && isModuleLevelDeclarator(path3, path3.length - 2))
23256
23612
  return;
23257
23613
  if (parent.type === "ExportDefaultDeclaration")
23258
23614
  return;
@@ -23262,9 +23618,9 @@ function followedConstants(ast, bindings) {
23262
23618
  note(handedTo, name, ["Object"]);
23263
23619
  return;
23264
23620
  }
23265
- if ((parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && key === "object" && !parent.computed && parent.property.type === "Identifier" && holdsPrimitiveAt(name, parent.property.name) && isValueRead(path, path.length - 2))
23621
+ if ((parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && key === "object" && !parent.computed && parent.property.type === "Identifier" && holdsPrimitiveAt(name, parent.property.name) && isValueRead(path3, path3.length - 2))
23266
23622
  return;
23267
- const read = readIn(path, path.length - 1);
23623
+ const read = readIn(path3, path3.length - 1);
23268
23624
  if (read === null) {
23269
23625
  dropped.add(name);
23270
23626
  return;
@@ -23784,11 +24140,11 @@ function checkDerivedFromDeclarations(collectionName, fields) {
23784
24140
  dropNestedDerivedFrom(collectionName, field.name, field.fields);
23785
24141
  }
23786
24142
  }
23787
- function dropNestedDerivedFrom(collectionName, path, fields) {
24143
+ function dropNestedDerivedFrom(collectionName, path3, fields) {
23788
24144
  if (!fields)
23789
24145
  return;
23790
24146
  for (const field of fields) {
23791
- const fieldPath = `${path}.${field.name}`;
24147
+ const fieldPath = `${path3}.${field.name}`;
23792
24148
  const layout = field.layout;
23793
24149
  if (layout?.derivedFrom !== undefined) {
23794
24150
  console.warn(`[cms] collection "${collectionName}": field "${fieldPath}" declares \`derivedFrom\` on a nested field, which is not supported` + ` \u2014 only top-level fields derive, so the declaration is ignored and the field stays editable`);
@@ -23800,7 +24156,7 @@ function dropNestedDerivedFrom(collectionName, path, fields) {
23800
24156
  }
23801
24157
  // ../cms-core/src/collection-scanner.ts
23802
24158
  var import_yaml2 = __toESM(require_dist(), 1);
23803
- import path from "path";
24159
+ import path3 from "path";
23804
24160
  var DATE_PATTERN = /^\d{4}-\d{2}-\d{2}/;
23805
24161
  var URL_PATTERN = /^(https?:\/\/|\/)/;
23806
24162
  var IMAGE_EXTENSIONS = /\.(jpg|jpeg|png|gif|webp|svg|avif)$/i;
@@ -24051,7 +24407,7 @@ function assembleCollectionDefinition(collectionName, contentDir, fieldMap, entr
24051
24407
  return {
24052
24408
  name: collectionName,
24053
24409
  label,
24054
- path: path.join(contentDir, collectionName),
24410
+ path: path3.join(contentDir, collectionName),
24055
24411
  entryCount,
24056
24412
  fields,
24057
24413
  fileExtension: "md",
@@ -24060,14 +24416,14 @@ function assembleCollectionDefinition(collectionName, contentDir, fieldMap, entr
24060
24416
  };
24061
24417
  }
24062
24418
  function getCollectionSourceBasePath(basePath, collectionName, contentDir) {
24063
- const defaultCollectionPath = path.join(contentDir, collectionName);
24419
+ const defaultCollectionPath = path3.join(contentDir, collectionName);
24064
24420
  const normalizedBasePath = normalizeBasePath(basePath);
24065
- if (normalizedBasePath === path.normalize(defaultCollectionPath)) {
24066
- return path.join(contentDir, collectionName);
24421
+ if (normalizedBasePath === path3.normalize(defaultCollectionPath)) {
24422
+ return path3.join(contentDir, collectionName);
24067
24423
  }
24068
24424
  return normalizedBasePath;
24069
24425
  }
24070
- async function buildCollectionDefinition(fs, basePath, sources, collectionName, contentDir) {
24426
+ async function buildCollectionDefinition(fs3, basePath, sources, collectionName, contentDir) {
24071
24427
  if (sources.length === 0)
24072
24428
  return null;
24073
24429
  const sourceBasePath = getCollectionSourceBasePath(basePath, collectionName, contentDir);
@@ -24077,7 +24433,7 @@ async function buildCollectionDefinition(fs, basePath, sources, collectionName,
24077
24433
  const allDirectives = {};
24078
24434
  const entryInfos = [];
24079
24435
  let hasDraft = false;
24080
- const fileContents = await Promise.all(sources.map((s) => fs.readFile(path.join(basePath, s.relPath)).catch(() => null)));
24436
+ const fileContents = await Promise.all(sources.map((s) => fs3.readFile(path3.join(basePath, s.relPath)).catch(() => null)));
24081
24437
  for (let i = 0;i < sources.length; i++) {
24082
24438
  const source = sources[i];
24083
24439
  const content = fileContents[i];
@@ -24092,7 +24448,7 @@ async function buildCollectionDefinition(fs, basePath, sources, collectionName,
24092
24448
  }
24093
24449
  const entryInfo = {
24094
24450
  slug: source.slug,
24095
- sourcePath: path.join(sourceBasePath, source.relPath)
24451
+ sourcePath: path3.join(sourceBasePath, source.relPath)
24096
24452
  };
24097
24453
  if (frontmatter) {
24098
24454
  const title = deriveEntryTitle(frontmatter);
@@ -24119,14 +24475,14 @@ async function buildCollectionDefinition(fs, basePath, sources, collectionName,
24119
24475
  assignFieldMetadata(def.fields, allDirectives);
24120
24476
  return def;
24121
24477
  }
24122
- async function buildDataCollectionDefinition(fs, basePath, sources, collectionName, contentDir) {
24478
+ async function buildDataCollectionDefinition(fs3, basePath, sources, collectionName, contentDir) {
24123
24479
  if (sources.length === 0)
24124
24480
  return null;
24125
24481
  const sourceBasePath = getCollectionSourceBasePath(basePath, collectionName, contentDir);
24126
24482
  const fieldMap = new Map;
24127
24483
  const entryInfos = [];
24128
24484
  const ext = sources.some((s) => s.relPath.endsWith(".json")) ? "json" : sources.some((s) => s.relPath.endsWith(".yaml")) ? "yaml" : "yml";
24129
- const fileContents = await Promise.all(sources.map((s) => fs.readFile(path.join(basePath, s.relPath)).catch(() => null)));
24485
+ const fileContents = await Promise.all(sources.map((s) => fs3.readFile(path3.join(basePath, s.relPath)).catch(() => null)));
24130
24486
  for (let i = 0;i < sources.length; i++) {
24131
24487
  const source = sources[i];
24132
24488
  const raw = fileContents[i];
@@ -24144,7 +24500,7 @@ async function buildDataCollectionDefinition(fs, basePath, sources, collectionNa
24144
24500
  entryInfos.push({
24145
24501
  slug: source.slug,
24146
24502
  title,
24147
- sourcePath: path.join(sourceBasePath, source.relPath),
24503
+ sourcePath: path3.join(sourceBasePath, source.relPath),
24148
24504
  data
24149
24505
  });
24150
24506
  collectFieldObservations(fieldMap, data, sources.length);
@@ -24155,8 +24511,8 @@ async function buildDataCollectionDefinition(fs, basePath, sources, collectionNa
24155
24511
  fileExtension: ext
24156
24512
  });
24157
24513
  }
24158
- async function scanCollection(fs, collectionPath, collectionName, contentDir) {
24159
- const dirEntries = await fs.list(collectionPath);
24514
+ async function scanCollection(fs3, collectionPath, collectionName, contentDir) {
24515
+ const dirEntries = await fs3.list(collectionPath);
24160
24516
  if (dirEntries.length === 0)
24161
24517
  return null;
24162
24518
  const sources = [];
@@ -24175,8 +24531,8 @@ async function scanCollection(fs, collectionPath, collectionName, contentDir) {
24175
24531
  if (takenSlugs.has(dir.name))
24176
24532
  return null;
24177
24533
  for (const ext of ["md", "mdx"]) {
24178
- const relPath = path.join(dir.name, `index.${ext}`);
24179
- if (await fs.exists(path.join(collectionPath, relPath))) {
24534
+ const relPath = path3.join(dir.name, `index.${ext}`);
24535
+ if (await fs3.exists(path3.join(collectionPath, relPath))) {
24180
24536
  return { slug: dir.name, relPath };
24181
24537
  }
24182
24538
  }
@@ -24188,22 +24544,22 @@ async function scanCollection(fs, collectionPath, collectionName, contentDir) {
24188
24544
  }
24189
24545
  if (sources.length === 0)
24190
24546
  return null;
24191
- return await buildCollectionDefinition(fs, collectionPath, sources, collectionName, contentDir);
24547
+ return await buildCollectionDefinition(fs3, collectionPath, sources, collectionName, contentDir);
24192
24548
  }
24193
- async function globLoaderFiles(fs, baseRel, pattern, options) {
24549
+ async function globLoaderFiles(fs3, baseRel, pattern, options) {
24194
24550
  const isPrivate = (relToBase) => relToBase.split("/").some((seg) => seg.startsWith("_") || seg.startsWith("."));
24195
- const matches = await fs.glob(path.join(baseRel, pattern), { ...options, skipDirectory: (dir) => isPrivate(path.relative(baseRel, dir)) });
24196
- return matches.map((rel) => path.relative(baseRel, rel)).filter((relToBase) => !isPrivate(relToBase));
24551
+ const matches = await fs3.glob(path3.join(baseRel, pattern), { ...options, skipDirectory: (dir) => isPrivate(path3.relative(baseRel, dir)) });
24552
+ return matches.map((rel) => path3.relative(baseRel, rel)).filter((relToBase) => !isPrivate(relToBase));
24197
24553
  }
24198
- async function scanGlobCollection(fs, collectionName, baseRel, pattern, contentDir) {
24199
- const rels = await globLoaderFiles(fs, baseRel, pattern);
24554
+ async function scanGlobCollection(fs3, collectionName, baseRel, pattern, contentDir) {
24555
+ const rels = await globLoaderFiles(fs3, baseRel, pattern);
24200
24556
  const mdSources = rels.filter((relToBase) => relToBase.endsWith(".md") || relToBase.endsWith(".mdx")).map((relToBase) => ({ slug: relToBase.replace(/\.(md|mdx)$/, ""), relPath: relToBase }));
24201
24557
  if (mdSources.length > 0) {
24202
- return await buildCollectionDefinition(fs, baseRel, mdSources, collectionName, contentDir);
24558
+ return await buildCollectionDefinition(fs3, baseRel, mdSources, collectionName, contentDir);
24203
24559
  }
24204
24560
  const dataSources = rels.filter((relToBase) => /\.(ya?ml|json)$/.test(relToBase)).map((relToBase) => ({ slug: relToBase.replace(/\.(ya?ml|json)$/, ""), relPath: relToBase }));
24205
24561
  if (dataSources.length > 0) {
24206
- return await buildDataCollectionDefinition(fs, baseRel, dataSources, collectionName, contentDir);
24562
+ return await buildDataCollectionDefinition(fs3, baseRel, dataSources, collectionName, contentDir);
24207
24563
  }
24208
24564
  return null;
24209
24565
  }
@@ -24528,8 +24884,8 @@ function detectDerivedHrefFields(collections) {
24528
24884
  }
24529
24885
  }
24530
24886
  }
24531
- async function scanDataCollection(fs, collectionPath, collectionName, contentDir) {
24532
- const dirEntries = await fs.list(collectionPath);
24887
+ async function scanDataCollection(fs3, collectionPath, collectionName, contentDir) {
24888
+ const dirEntries = await fs3.list(collectionPath);
24533
24889
  if (dirEntries.length === 0)
24534
24890
  return null;
24535
24891
  const sources = [];
@@ -24548,8 +24904,8 @@ async function scanDataCollection(fs, collectionPath, collectionName, contentDir
24548
24904
  if (takenSlugs.has(dir.name))
24549
24905
  return null;
24550
24906
  for (const indexExt of ["json", "yaml", "yml"]) {
24551
- const relPath = path.join(dir.name, `index.${indexExt}`);
24552
- if (await fs.exists(path.join(collectionPath, relPath))) {
24907
+ const relPath = path3.join(dir.name, `index.${indexExt}`);
24908
+ if (await fs3.exists(path3.join(collectionPath, relPath))) {
24553
24909
  return { slug: dir.name, relPath };
24554
24910
  }
24555
24911
  }
@@ -24559,10 +24915,10 @@ async function scanDataCollection(fs, collectionPath, collectionName, contentDir
24559
24915
  if (entry)
24560
24916
  sources.push(entry);
24561
24917
  }
24562
- return await buildDataCollectionDefinition(fs, collectionPath, sources, collectionName, contentDir);
24918
+ return await buildDataCollectionDefinition(fs3, collectionPath, sources, collectionName, contentDir);
24563
24919
  }
24564
24920
  function normalizeBasePath(basePath) {
24565
- return path.normalize(basePath.replace(/^\.[/\\]+/, "")).replace(/[/\\]+$/, "");
24921
+ return path3.normalize(basePath.replace(/^\.[/\\]+/, "")).replace(/[/\\]+$/, "");
24566
24922
  }
24567
24923
  var WHOLE_DIRECTORY_PATTERN = /^(?:\*\*[/\\])*\*(?:\.(?:\{([^{}/\\]*)\}|([A-Za-z0-9]+)))?$/;
24568
24924
  function patternCoversWholeCollection(pattern, definition) {
@@ -24573,7 +24929,7 @@ function patternCoversWholeCollection(pattern, definition) {
24573
24929
  if (braceGroup === undefined && singleExtension === undefined)
24574
24930
  return true;
24575
24931
  const patternExtensions = new Set((braceGroup !== undefined ? braceGroup.split(",") : [singleExtension]).map((ext) => ext.trim().replace(/^\./, "").toLowerCase()).filter(Boolean));
24576
- const scannedExtensions = new Set((definition.entries ?? []).map((entry) => path.extname(entry.sourcePath).slice(1).toLowerCase()).filter(Boolean));
24932
+ const scannedExtensions = new Set((definition.entries ?? []).map((entry) => path3.extname(entry.sourcePath).slice(1).toLowerCase()).filter(Boolean));
24577
24933
  if (scannedExtensions.size === 0)
24578
24934
  return false;
24579
24935
  for (const ext of scannedExtensions) {
@@ -24582,24 +24938,24 @@ function patternCoversWholeCollection(pattern, definition) {
24582
24938
  }
24583
24939
  return true;
24584
24940
  }
24585
- async function scanCollections(fs, contentDir = "src/content", parseCache = new Map, options = {}) {
24941
+ async function scanCollections(fs3, contentDir = "src/content", parseCache = new Map, options = {}) {
24586
24942
  const collections = {};
24587
24943
  const failedScans = new Map;
24588
- const entries = await fs.list(contentDir);
24944
+ const entries = await fs3.list(contentDir);
24589
24945
  const scanPromises = entries.filter((entry) => entry.isDirectory && !entry.name.startsWith("_") && !entry.name.startsWith(".")).map(async (entry) => {
24590
24946
  try {
24591
- const collectionPath = path.join(contentDir, entry.name);
24592
- const definition = await scanCollection(fs, collectionPath, entry.name, contentDir) ?? await scanDataCollection(fs, collectionPath, entry.name, contentDir);
24947
+ const collectionPath = path3.join(contentDir, entry.name);
24948
+ const definition = await scanCollection(fs3, collectionPath, entry.name, contentDir) ?? await scanDataCollection(fs3, collectionPath, entry.name, contentDir);
24593
24949
  if (definition) {
24594
24950
  collections[entry.name] = definition;
24595
24951
  }
24596
24952
  } catch (error) {
24597
24953
  console.warn(`[cms] Skipping collection "${entry.name}" \u2014 scan failed:`, error);
24598
- failedScans.set(entry.name, { name: entry.name, reason: "scan-failed", base: path.join(contentDir, entry.name) });
24954
+ failedScans.set(entry.name, { name: entry.name, reason: "scan-failed", base: path3.join(contentDir, entry.name) });
24599
24955
  }
24600
24956
  });
24601
24957
  await Promise.all(scanPromises);
24602
- const config = await readContentConfig(fs, parseCache);
24958
+ const config = await readContentConfig(fs3, parseCache);
24603
24959
  const { parsed } = config;
24604
24960
  const scannedNameByBasePath = new Map;
24605
24961
  for (const [name, definition] of Object.entries(collections)) {
@@ -24626,7 +24982,7 @@ async function scanCollections(fs, contentDir = "src/content", parseCache = new
24626
24982
  }
24627
24983
  let definition;
24628
24984
  try {
24629
- definition = await scanGlobCollection(fs, collectionName, parsedCollection.loaderBase, parsedCollection.loaderPattern, contentDir);
24985
+ definition = await scanGlobCollection(fs3, collectionName, parsedCollection.loaderBase, parsedCollection.loaderPattern, contentDir);
24630
24986
  } catch (error) {
24631
24987
  console.warn(`[cms] Skipping glob collection "${collectionName}" \u2014 scan failed:`, error);
24632
24988
  failedScans.set(collectionName, {
@@ -24655,7 +25011,7 @@ async function scanCollections(fs, contentDir = "src/content", parseCache = new
24655
25011
  if (options.report) {
24656
25012
  try {
24657
25013
  const contentDirectories = entries.filter((entry) => entry.isDirectory && !entry.name.startsWith("_") && !entry.name.startsWith(".")).map((entry) => entry.name);
24658
- scanReports.set(collections, await buildScanReport(fs, contentDir, collections, config, failedScans, contentDirectories));
25014
+ scanReports.set(collections, await buildScanReport(fs3, contentDir, collections, config, failedScans, contentDirectories));
24659
25015
  } catch (error) {
24660
25016
  console.warn("[cms] Collection scan report unavailable:", error);
24661
25017
  }
@@ -24676,7 +25032,7 @@ function readsAsRelativeDirectory(base) {
24676
25032
  return false;
24677
25033
  try {
24678
25034
  const asUrl = decodeURIComponent(new URL(base, "file:///project-root/").pathname).replace(/\/{2,}/g, "/").replace(/\/+$/, "");
24679
- const asPath = normalizeBasePath(base).split(path.sep).join("/");
25035
+ const asPath = normalizeBasePath(base).split(path3.sep).join("/");
24680
25036
  return asUrl === (asPath === "." ? "/project-root" : `/project-root/${asPath}`);
24681
25037
  } catch {
24682
25038
  return false;
@@ -24685,7 +25041,7 @@ function readsAsRelativeDirectory(base) {
24685
25041
  function declaredLocation(declaration, contentDir) {
24686
25042
  const location = {};
24687
25043
  if (declaration.noLoader)
24688
- location.base = path.join(contentDir, declaration.name);
25044
+ location.base = path3.join(contentDir, declaration.name);
24689
25045
  if (declaration.loaderBase !== undefined)
24690
25046
  location.base = normalizeBasePath(declaration.loaderBase);
24691
25047
  if (declaration.loaderPattern !== undefined)
@@ -24694,15 +25050,15 @@ function declaredLocation(declaration, contentDir) {
24694
25050
  location.file = normalizeBasePath(declaration.loaderFile);
24695
25051
  return location;
24696
25052
  }
24697
- async function contentDirectoryFiles(fs, directory, entryFile) {
24698
- const files = await globLoaderFiles(fs, directory, "**/*", { followSymlinks: true, maxLinkedDirectories: REPORT_LINKED_DIRECTORY_LIMIT });
24699
- return files.filter((file) => entryFile.test(file)).map((file) => path.join(directory, file));
25053
+ async function contentDirectoryFiles(fs3, directory, entryFile) {
25054
+ const files = await globLoaderFiles(fs3, directory, "**/*", { followSymlinks: true, maxLinkedDirectories: REPORT_LINKED_DIRECTORY_LIMIT });
25055
+ return files.filter((file) => entryFile.test(file)).map((file) => path3.join(directory, file));
24700
25056
  }
24701
- async function declaredEntryFiles(fs, contentDir, declaration) {
25057
+ async function declaredEntryFiles(fs3, contentDir, declaration) {
24702
25058
  if (declaration.noLoader) {
24703
25059
  if (!readsAsRelativeDirectory(declaration.name))
24704
25060
  return null;
24705
- return { exact: true, files: await contentDirectoryFiles(fs, path.join(contentDir, declaration.name), ENTRY_FILE) };
25061
+ return { exact: true, files: await contentDirectoryFiles(fs3, path3.join(contentDir, declaration.name), ENTRY_FILE) };
24706
25062
  }
24707
25063
  const declaredBase = declaration.loaderBase;
24708
25064
  if (declaredBase === undefined || !readsAsRelativeDirectory(declaredBase))
@@ -24712,14 +25068,14 @@ async function declaredEntryFiles(fs, contentDir, declaration) {
24712
25068
  const patterns = pattern !== undefined ? [pattern] : declaration.loaderPatterns;
24713
25069
  if (patterns === undefined)
24714
25070
  return null;
24715
- const exact = pattern !== undefined && !UNSUPPORTED_GLOB_SYNTAX.test(pattern) && !UNSUPPORTED_GLOB_SYNTAX.test(path.posix.normalize(pattern));
25071
+ const exact = pattern !== undefined && !UNSUPPORTED_GLOB_SYNTAX.test(pattern) && !UNSUPPORTED_GLOB_SYNTAX.test(path3.posix.normalize(pattern));
24716
25072
  if (!exact && (base === "." || patterns.some((one) => LEAVES_THE_BASE.test(one))))
24717
25073
  return null;
24718
- const matches = await fs.glob(path.join(base, exact ? pattern : "**/*"), {
25074
+ const matches = await fs3.glob(path3.join(base, exact ? pattern : "**/*"), {
24719
25075
  followSymlinks: true,
24720
25076
  maxLinkedDirectories: REPORT_LINKED_DIRECTORY_LIMIT
24721
25077
  });
24722
- const files = matches.filter((file) => ENTRY_FILE.test(file) && patterns.some((one) => mayTakeDotPath(one, path.relative(base, file))));
25078
+ const files = matches.filter((file) => ENTRY_FILE.test(file) && patterns.some((one) => mayTakeDotPath(one, path3.relative(base, file))));
24723
25079
  return { exact, files };
24724
25080
  }
24725
25081
  function mayTakeDotPath(pattern, file) {
@@ -24736,9 +25092,9 @@ function mayTakeDotPath(pattern, file) {
24736
25092
  return (!dotFile || takesDot(pattern.slice(cut + 1))) && (!dotDirectory || takesDot(pattern.slice(0, Math.max(cut, 0))));
24737
25093
  }
24738
25094
  var ASTRO_CONFIG_PATHS = ["astro.config.mjs", "astro.config.js", "astro.config.ts", "astro.config.mts"];
24739
- async function customSrcDir(fs) {
25095
+ async function customSrcDir(fs3) {
24740
25096
  for (const configPath of ASTRO_CONFIG_PATHS) {
24741
- const source = await fs.readFile(configPath).catch(() => null);
25097
+ const source = await fs3.readFile(configPath).catch(() => null);
24742
25098
  if (source === null)
24743
25099
  continue;
24744
25100
  const roots = configOptionMentions(source, "root");
@@ -24754,24 +25110,24 @@ async function customSrcDir(fs) {
24754
25110
  return null;
24755
25111
  if (srcDir === "src")
24756
25112
  return;
24757
- return path.isAbsolute(srcDir) || srcDir.startsWith("..") ? null : srcDir;
25113
+ return path3.isAbsolute(srcDir) || srcDir.startsWith("..") ? null : srcDir;
24758
25114
  }
24759
25115
  return;
24760
25116
  }
24761
- async function contentConfigStatus(fs, config) {
25117
+ async function contentConfigStatus(fs3, config) {
24762
25118
  const configPaths = [...CONTENT_CONFIG_PATHS, ...UNREAD_CONTENT_CONFIG_PATHS];
24763
- const srcDir = await customSrcDir(fs);
25119
+ const srcDir = await customSrcDir(fs3);
24764
25120
  if (srcDir === null)
24765
25121
  return "unreadable";
24766
25122
  if (srcDir !== undefined) {
24767
25123
  for (const configPath of configPaths) {
24768
- if (await fs.exists(path.join(srcDir, path.relative("src", configPath))))
25124
+ if (await fs3.exists(path3.join(srcDir, path3.relative("src", configPath))))
24769
25125
  return "unreadable";
24770
25126
  }
24771
25127
  }
24772
25128
  let configFiles = 0;
24773
25129
  for (const configPath of configPaths) {
24774
- if (await fs.exists(configPath))
25130
+ if (await fs3.exists(configPath))
24775
25131
  configFiles++;
24776
25132
  }
24777
25133
  if (configFiles === 0)
@@ -24780,16 +25136,16 @@ async function contentConfigStatus(fs, config) {
24780
25136
  return "partial";
24781
25137
  if (config.declared.length > 0)
24782
25138
  return "ok";
24783
- return await classifyEmptyContentConfig(fs) === "no-collections" ? "ok" : "unreadable";
25139
+ return await classifyEmptyContentConfig(fs3) === "no-collections" ? "ok" : "unreadable";
24784
25140
  }
24785
- async function buildScanReport(fs, contentDir, collections, config, failedScans, contentDirectories) {
24786
- const contentConfig = await contentConfigStatus(fs, config);
25141
+ async function buildScanReport(fs3, contentDir, collections, config, failedScans, contentDirectories) {
25142
+ const contentConfig = await contentConfigStatus(fs3, config);
24787
25143
  const unresolved = new Map;
24788
25144
  const declaredByName = new Map(config.declared.map((declaration) => [declaration.name, declaration]));
24789
25145
  const listed = new Set;
24790
25146
  for (const definition of Object.values(collections)) {
24791
25147
  for (const entry of definition.entries ?? [])
24792
- listed.add(path.normalize(entry.sourcePath));
25148
+ listed.add(path3.normalize(entry.sourcePath));
24793
25149
  if ((definition.entries?.length ?? 0) >= definition.entryCount)
24794
25150
  continue;
24795
25151
  const declaration = declaredByName.get(definition.name);
@@ -24812,14 +25168,14 @@ async function buildScanReport(fs, contentDir, collections, config, failedScans,
24812
25168
  }
24813
25169
  let loads;
24814
25170
  try {
24815
- loads = await declaredEntryFiles(fs, contentDir, declaration);
25171
+ loads = await declaredEntryFiles(fs3, contentDir, declaration);
24816
25172
  } catch {
24817
25173
  unresolved.set(name, { name, reason: "scan-failed", ...location });
24818
25174
  continue;
24819
25175
  }
24820
25176
  if (loads === null) {
24821
25177
  unresolved.set(name, { name, reason: "unsupported-loader", ...location });
24822
- } else if (!loads.files.every((file) => listed.has(path.normalize(file)))) {
25178
+ } else if (!loads.files.every((file) => listed.has(path3.normalize(file)))) {
24823
25179
  unresolved.set(name, { name, reason: loads.exact ? "unlisted-entries" : "unsupported-loader", ...location });
24824
25180
  }
24825
25181
  }
@@ -24828,11 +25184,11 @@ async function buildScanReport(fs, contentDir, collections, config, failedScans,
24828
25184
  for (const name of contentDirectories) {
24829
25185
  if (declaredByName.has(name) || unresolved.has(name) || failedScans.has(name))
24830
25186
  continue;
24831
- const directory = path.join(contentDir, name);
24832
- const files = await contentDirectoryFiles(fs, directory, MARKDOWN_FILE).catch(() => null);
25187
+ const directory = path3.join(contentDir, name);
25188
+ const files = await contentDirectoryFiles(fs3, directory, MARKDOWN_FILE).catch(() => null);
24833
25189
  if (files === null)
24834
25190
  unresolved.set(name, { name, reason: "scan-failed", base: directory });
24835
- else if (!files.every((file) => listed.has(path.normalize(file))))
25191
+ else if (!files.every((file) => listed.has(path3.normalize(file))))
24836
25192
  unresolved.set(name, { name, reason: "unlisted-entries", base: directory });
24837
25193
  }
24838
25194
  }
@@ -24868,28 +25224,28 @@ function warnOnPathnameCollisions(collections) {
24868
25224
  }
24869
25225
  // ../cms-core/src/component-registry.ts
24870
25226
  var import_parser3 = __toESM(require_lib(), 1);
24871
- import path2 from "path";
24872
- async function scanComponentDefinitions(fs, componentDirs = ["src/components"]) {
25227
+ import path4 from "path";
25228
+ async function scanComponentDefinitions(fs3, componentDirs = ["src/components"]) {
24873
25229
  const components = {};
24874
25230
  for (const dir of componentDirs) {
24875
- await scanDirectory(fs, dir, components);
25231
+ await scanDirectory(fs3, dir, components);
24876
25232
  }
24877
25233
  return components;
24878
25234
  }
24879
- async function scanDirectory(fs, relativePath, components) {
24880
- const entries = await fs.list(relativePath);
25235
+ async function scanDirectory(fs3, relativePath, components) {
25236
+ const entries = await fs3.list(relativePath);
24881
25237
  for (const entry of entries) {
24882
25238
  const relPath = `${relativePath}/${entry.name}`;
24883
25239
  if (entry.isDirectory) {
24884
- await scanDirectory(fs, relPath, components);
25240
+ await scanDirectory(fs3, relPath, components);
24885
25241
  } else if (entry.name.endsWith(".astro")) {
24886
- await parseComponent(fs, relPath, components);
25242
+ await parseComponent(fs3, relPath, components);
24887
25243
  }
24888
25244
  }
24889
25245
  }
24890
- async function parseComponent(fs, relativePath, components) {
24891
- const content = await fs.readFile(relativePath);
24892
- const componentName = path2.basename(relativePath, ".astro");
25246
+ async function parseComponent(fs3, relativePath, components) {
25247
+ const content = await fs3.readFile(relativePath);
25248
+ const componentName = path4.basename(relativePath, ".astro");
24893
25249
  const props = extractProps(content);
24894
25250
  const slots = extractSlots(content);
24895
25251
  const description = extractDescription(content);
@@ -25114,213 +25470,173 @@ function extractPreviewWidth(content) {
25114
25470
  }
25115
25471
  return;
25116
25472
  }
25117
- // ../cms-core/src/handlers/entry-ops.ts
25118
- var import_yaml3 = __toESM(require_dist(), 1);
25119
- import path4 from "path";
25120
-
25121
- // ../cms-core/src/media/local.ts
25122
- import { randomUUID } from "crypto";
25123
- import fs from "fs/promises";
25124
- import path3 from "path";
25125
-
25126
- // ../cms-core/src/media/errors.ts
25127
- var MEDIA_INVALID_ID = "Invalid media id";
25128
- var MEDIA_INVALID_FOLDER = "Invalid folder name";
25129
- var MEDIA_NOT_FOUND = "Media file not found";
25130
- function mediaErrorStatus(error) {
25131
- if (error === MEDIA_INVALID_ID || error === MEDIA_INVALID_FOLDER)
25132
- return 400;
25133
- if (error === MEDIA_NOT_FOUND)
25134
- return 404;
25135
- return 500;
25136
- }
25137
-
25138
- // ../cms-core/src/media/names.ts
25139
- function hasDotSegment(value) {
25140
- return value.split("/").some((s) => s === "." || s === "..");
25141
- }
25142
- function isUnsafeFolder(folder) {
25143
- return folder.includes("\\") || folder.split("/").some((s) => {
25144
- const decoded = s.replace(/%2e/gi, ".");
25145
- return decoded === "." || decoded === "..";
25146
- });
25147
- }
25148
-
25149
- // ../cms-core/src/media/local.ts
25150
- function errorCode(error) {
25151
- return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined;
25152
- }
25153
- function failure(action, error) {
25154
- const code = errorCode(error);
25155
- return code ? `Failed to ${action} (${code})` : `Failed to ${action}`;
25156
- }
25157
- async function hasSymlink(from, names) {
25158
- let current = from;
25159
- for (const name of names) {
25160
- current += path3.sep + name;
25161
- try {
25162
- if ((await fs.lstat(current)).isSymbolicLink())
25163
- return true;
25164
- } catch (error) {
25165
- const code = errorCode(error);
25166
- if (code === "ENOENT" || code === "ENOTDIR")
25167
- return false;
25168
- throw error;
25169
- }
25170
- }
25171
- return false;
25172
- }
25173
- function createLocalStorageAdapter(options = {}) {
25174
- const dir = path3.resolve(options.dir ?? "public/uploads");
25175
- const base = dir.endsWith(path3.sep) ? dir.slice(0, -path3.sep.length) : dir;
25176
- const urlPrefix = (options.urlPrefix ?? "/uploads").replace(/\/$/, "");
25177
- async function resolveInside(relative, kind) {
25178
- const segments = relative.split("/");
25179
- if (relative.includes("\x00") || segments.some((s) => s === "" || s === "." || s === ".."))
25180
- return null;
25181
- if (path3.sep === "\\" && segments.some((s) => /[\\:]|[. ]$/.test(s)))
25182
- return null;
25183
- const resolved = path3.resolve(dir, ...segments);
25184
- if (resolved !== [base, ...segments].join(path3.sep))
25185
- return null;
25186
- if (await hasSymlink(base, kind === "file" ? segments.slice(0, -1) : segments))
25187
- return null;
25188
- return resolved;
25189
- }
25190
- async function resolveFolder(input, use) {
25191
- const folder = (input ?? "").split("/").filter(Boolean).join("/");
25192
- if (!folder)
25193
- return { folder, targetDir: dir };
25194
- if (use === "write" && isUnsafeFolder(folder))
25195
- return null;
25196
- const targetDir = await resolveInside(folder, "folder");
25197
- return targetDir ? { folder, targetDir } : null;
25198
- }
25199
- return {
25200
- staticFiles: { urlPrefix, dir },
25201
- async list(opts) {
25202
- const limit = opts?.limit ?? 50;
25203
- const offset = opts?.cursor ? parseInt(opts.cursor, 10) : 0;
25204
- const nothing = { items: [], folders: [], hasMore: false };
25205
- try {
25206
- const target = await resolveFolder(opts?.folder, "read");
25207
- if (!target)
25208
- return nothing;
25209
- const { folder, targetDir } = target;
25210
- await fs.mkdir(targetDir, { recursive: true });
25211
- const entries = await fs.readdir(targetDir, { withFileTypes: true });
25212
- const folders = entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => ({
25213
- name: e.name,
25214
- path: folder ? `${folder}/${e.name}` : e.name
25215
- })).sort((a, b) => a.name.localeCompare(b.name));
25216
- const files = entries.filter((e) => e.isFile() && !e.name.startsWith("."));
25217
- const withStats = await Promise.all(files.map(async (f) => {
25218
- const filePath = path3.join(targetDir, f.name);
25219
- const stat = await fs.stat(filePath);
25220
- return { name: f.name, stat };
25221
- }));
25222
- withStats.sort((a, b) => b.stat.mtimeMs - a.stat.mtimeMs);
25223
- const slice = withStats.slice(offset, offset + limit);
25224
- const hasMore = offset + limit < withStats.length;
25225
- const urlFolder = folder ? `/${folder}` : "";
25226
- const items = slice.map((f) => {
25227
- const ext = path3.extname(f.name).toLowerCase();
25228
- const contentType = mimeFromExt(ext);
25229
- return {
25230
- id: folder ? `${folder}/${f.name}` : f.name,
25231
- url: `${urlPrefix}${urlFolder}/${f.name}`,
25232
- filename: f.name,
25233
- contentType,
25234
- uploadedAt: f.stat.mtime.toISOString(),
25235
- folder: folder || undefined
25236
- };
25237
- });
25238
- return {
25239
- items,
25240
- folders,
25241
- hasMore,
25242
- cursor: hasMore ? String(offset + limit) : undefined
25243
- };
25244
- } catch (error) {
25245
- const code = errorCode(error);
25246
- if (opts?.folder && (code === "ENOTDIR" || code === "EEXIST" || code === "ENAMETOOLONG"))
25247
- return nothing;
25248
- throw new Error(failure("list media", error));
25249
- }
25473
+ // ../cms-core/src/fs/staged.ts
25474
+ import { createHash } from "crypto";
25475
+ class CmsCommitConflictError extends Error {
25476
+ paths;
25477
+ constructor(paths) {
25478
+ super(`Changed since the edit read them: ${paths.join(", ")}`);
25479
+ this.paths = paths;
25480
+ this.name = "CmsCommitConflictError";
25481
+ }
25482
+ }
25483
+ function digestBytes(content) {
25484
+ return `sha256:${createHash("sha256").update(content).digest("hex")}`;
25485
+ }
25486
+ function normalize(path5) {
25487
+ const segments = [];
25488
+ for (const segment of path5.split("/")) {
25489
+ if (segment === "" || segment === ".")
25490
+ continue;
25491
+ if (segment === ".." && segments.length > 0 && segments.at(-1) !== "..")
25492
+ segments.pop();
25493
+ else
25494
+ segments.push(segment);
25495
+ }
25496
+ return segments.join("/");
25497
+ }
25498
+ function isBelow(path5, dir) {
25499
+ return dir === "" || path5.startsWith(`${dir}/`);
25500
+ }
25501
+ function missing(path5) {
25502
+ return Object.assign(new Error(`ENOENT: no such file, '${path5}'`), { code: "ENOENT" });
25503
+ }
25504
+ function createStagedFileSystem(base) {
25505
+ const reads = new Map;
25506
+ const staged = new Map;
25507
+ const encoder = new TextEncoder;
25508
+ const decoder = new TextDecoder;
25509
+ function observe(path5, version) {
25510
+ const recorded = reads.get(path5);
25511
+ if (recorded === undefined || recorded.kind === "present" && version.kind === "content")
25512
+ reads.set(path5, version);
25513
+ }
25514
+ async function observeBeforeChange(path5) {
25515
+ if (staged.has(path5))
25516
+ return;
25517
+ const recorded = reads.get(path5);
25518
+ if (recorded !== undefined && recorded.kind !== "present")
25519
+ return;
25520
+ observe(path5, await versionOf(base, path5));
25521
+ }
25522
+ async function readBytes(rawPath) {
25523
+ const path5 = normalize(rawPath);
25524
+ const change = staged.get(path5);
25525
+ if (change === null)
25526
+ throw missing(path5);
25527
+ if (change !== undefined)
25528
+ return change.content.slice();
25529
+ try {
25530
+ const content = await base.readBytes(path5);
25531
+ observe(path5, { kind: "content", digest: digestBytes(content) });
25532
+ return content;
25533
+ } catch (error) {
25534
+ if (!await base.exists(path5))
25535
+ observe(path5, { kind: "absent" });
25536
+ throw error;
25537
+ }
25538
+ }
25539
+ async function write(rawPath, content) {
25540
+ const path5 = normalize(rawPath);
25541
+ await observeBeforeChange(path5);
25542
+ staged.set(path5, { content: content.slice(), mtimeMs: Date.now() });
25543
+ }
25544
+ async function remove(rawPath) {
25545
+ const path5 = normalize(rawPath);
25546
+ await observeBeforeChange(path5);
25547
+ staged.set(path5, null);
25548
+ }
25549
+ function stagedBelow(dir) {
25550
+ return [...staged].filter(([path5, change]) => change !== null && isBelow(path5, dir)).map(([path5]) => path5);
25551
+ }
25552
+ return {
25553
+ async readFile(path5) {
25554
+ return decoder.decode(await readBytes(path5));
25250
25555
  },
25251
- async upload(file, filename, contentType, uploadOpts) {
25252
- try {
25253
- const target = await resolveFolder(uploadOpts?.folder, "write");
25254
- if (!target)
25255
- return { success: false, error: MEDIA_INVALID_FOLDER };
25256
- const { folder, targetDir } = target;
25257
- await fs.mkdir(targetDir, { recursive: true });
25258
- const ext = getFileExtension(filename);
25259
- const uuid = randomUUID();
25260
- const newFilename = `${uuid}${ext ? `.${ext}` : ""}`;
25261
- const filePath = path3.join(targetDir, newFilename);
25262
- await fs.writeFile(filePath, file);
25263
- const urlFolder = folder ? `/${folder}` : "";
25264
- const id = folder ? `${folder}/${newFilename}` : newFilename;
25265
- return {
25266
- success: true,
25267
- url: `${urlPrefix}${urlFolder}/${newFilename}`,
25268
- filename: newFilename,
25269
- id
25270
- };
25271
- } catch (error) {
25272
- return { success: false, error: failure("store media file", error) };
25273
- }
25556
+ readBytes,
25557
+ writeFile(path5, content) {
25558
+ return write(path5, encoder.encode(content));
25274
25559
  },
25275
- async delete(id) {
25276
- try {
25277
- const filePath = await resolveInside(id, "file");
25278
- if (!filePath)
25279
- return { success: false, error: MEDIA_INVALID_ID };
25280
- await fs.unlink(filePath);
25281
- return { success: true };
25282
- } catch (error) {
25283
- if (errorCode(error) === "ENOENT")
25284
- return { success: false, error: MEDIA_NOT_FOUND };
25285
- return { success: false, error: failure("delete media file", error) };
25286
- }
25560
+ writeBytes: write,
25561
+ async rename(from, to) {
25562
+ const content = await readBytes(from);
25563
+ await remove(from);
25564
+ await write(to, content);
25287
25565
  },
25288
- async createFolder(folder) {
25289
- try {
25290
- const target = await resolveFolder(folder, "write");
25291
- if (!target)
25292
- return { success: false, error: MEDIA_INVALID_FOLDER };
25293
- await fs.mkdir(target.targetDir, { recursive: true });
25294
- return { success: true };
25295
- } catch (error) {
25296
- return { success: false, error: failure("create folder", error) };
25566
+ remove,
25567
+ async exists(rawPath) {
25568
+ const path5 = normalize(rawPath);
25569
+ const change = staged.get(path5);
25570
+ if (change !== undefined)
25571
+ return change !== null;
25572
+ if (stagedBelow(path5).length > 0)
25573
+ return true;
25574
+ const exists = await base.exists(path5);
25575
+ observe(path5, exists ? { kind: "present" } : { kind: "absent" });
25576
+ return exists;
25577
+ },
25578
+ async list(rawDir) {
25579
+ const dir = normalize(rawDir);
25580
+ const entries = new Map((await base.list(dir)).map((entry) => [entry.name, entry.isDirectory]));
25581
+ for (const [path5, change] of staged) {
25582
+ if (!isBelow(path5, dir))
25583
+ continue;
25584
+ const rest = dir === "" ? path5 : path5.slice(dir.length + 1);
25585
+ const [name, ...deeper] = rest.split("/");
25586
+ if (name === undefined)
25587
+ continue;
25588
+ if (deeper.length > 0) {
25589
+ if (change !== null)
25590
+ entries.set(name, true);
25591
+ } else if (change === null) {
25592
+ entries.delete(name);
25593
+ } else {
25594
+ entries.set(name, false);
25595
+ }
25297
25596
  }
25597
+ return [...entries].map(([name, isDirectory]) => ({ name, isDirectory }));
25598
+ },
25599
+ async glob(pattern, options) {
25600
+ const matcher = globToRegExp(pattern);
25601
+ const files = new Set(await base.glob(pattern, options));
25602
+ for (const [path5, change] of staged) {
25603
+ if (change === null)
25604
+ files.delete(path5);
25605
+ else if (matcher.test(path5))
25606
+ files.add(path5);
25607
+ }
25608
+ return [...files];
25609
+ },
25610
+ async stat(rawPath) {
25611
+ const path5 = normalize(rawPath);
25612
+ const change = staged.get(path5);
25613
+ if (change === null)
25614
+ throw missing(path5);
25615
+ if (change !== undefined)
25616
+ return { mtimeMs: change.mtimeMs, size: change.content.byteLength };
25617
+ const stat = await base.stat(path5);
25618
+ observe(path5, { kind: "present" });
25619
+ return stat;
25620
+ },
25621
+ changeset() {
25622
+ const changes = [...staged].map(([path5, change]) => change === null ? { kind: "remove", path: path5 } : { kind: "write", path: path5, content: change.content });
25623
+ return { reads: new Map(reads), changes };
25298
25624
  }
25299
25625
  };
25300
25626
  }
25301
- function getFileExtension(filename) {
25302
- const parts = filename.split(".");
25303
- const ext = parts.length > 1 ? parts.pop()?.toLowerCase() ?? "" : "";
25304
- return /^[a-z0-9]+$/.test(ext) ? ext : "";
25305
- }
25306
- var MIME_BY_EXT = {
25307
- ".jpg": "image/jpeg",
25308
- ".jpeg": "image/jpeg",
25309
- ".png": "image/png",
25310
- ".gif": "image/gif",
25311
- ".webp": "image/webp",
25312
- ".avif": "image/avif",
25313
- ".svg": "image/svg+xml",
25314
- ".ico": "image/x-icon",
25315
- ".mp4": "video/mp4",
25316
- ".webm": "video/webm",
25317
- ".pdf": "application/pdf"
25318
- };
25319
- function mimeFromExt(ext) {
25320
- return MIME_BY_EXT[ext] ?? "application/octet-stream";
25627
+ async function versionOf(fs3, path5) {
25628
+ if (!await fs3.exists(path5))
25629
+ return { kind: "absent" };
25630
+ try {
25631
+ return { kind: "content", digest: digestBytes(await fs3.readBytes(path5)) };
25632
+ } catch {
25633
+ return { kind: "present" };
25634
+ }
25321
25635
  }
25322
25636
 
25323
25637
  // ../cms-core/src/handlers/entry-ops.ts
25638
+ var import_yaml3 = __toESM(require_dist(), 1);
25639
+ import path5 from "path";
25324
25640
  var MARKDOWN_EXTENSIONS = ["md", "mdx"];
25325
25641
  function fileExtension(filePath) {
25326
25642
  const idx = filePath.lastIndexOf(".");
@@ -25341,12 +25657,12 @@ async function resolveEntryPath(deps, collection, slug) {
25341
25657
  const base = await resolveCollectionDir(deps, collection);
25342
25658
  const flatExts = ["md", "mdx", "json", "yaml", "yml"];
25343
25659
  for (const ext of flatExts) {
25344
- const candidate = path4.posix.join(base, `${slug}.${ext}`);
25660
+ const candidate = path5.posix.join(base, `${slug}.${ext}`);
25345
25661
  if (await deps.fs.exists(candidate))
25346
25662
  return candidate;
25347
25663
  }
25348
25664
  for (const ext of MARKDOWN_EXTENSIONS) {
25349
- const candidate = path4.posix.join(base, slug, `index.${ext}`);
25665
+ const candidate = path5.posix.join(base, slug, `index.${ext}`);
25350
25666
  if (await deps.fs.exists(candidate))
25351
25667
  return candidate;
25352
25668
  }
@@ -25512,7 +25828,7 @@ async function inferLayoutFromExistingEntries(deps, collection) {
25512
25828
  if (flatSlugs.has(dir.name))
25513
25829
  return false;
25514
25830
  for (const ext of MARKDOWN_EXTENSIONS) {
25515
- if (await deps.fs.exists(path4.posix.join(collectionPath, dir.name, `index.${ext}`)))
25831
+ if (await deps.fs.exists(path5.posix.join(collectionPath, dir.name, `index.${ext}`)))
25516
25832
  return true;
25517
25833
  }
25518
25834
  return false;
@@ -25570,8 +25886,8 @@ async function missingRequiredFields(deps, collection, frontmatter) {
25570
25886
  return [];
25571
25887
  return blankRequiredFields(parsedCollection.fields, frontmatter);
25572
25888
  }
25573
- function missingRequiredMessage(missing) {
25574
- return missing.length === 1 ? `Field "${missing[0]}" is required` : `Required fields are empty: ${missing.join(", ")}`;
25889
+ function missingRequiredMessage(missing2) {
25890
+ return missing2.length === 1 ? `Field "${missing2[0]}" is required` : `Required fields are empty: ${missing2.join(", ")}`;
25575
25891
  }
25576
25892
  function errorMessage(error) {
25577
25893
  return error instanceof Error ? error.message : String(error);
@@ -25607,14 +25923,14 @@ async function createEntry(deps, input) {
25607
25923
  }
25608
25924
  const seeded = await applyEntrySlugField(deps, collection, frontmatter, normalizedSlug);
25609
25925
  const resolved = await applyDerivedFields(deps, collection, seeded);
25610
- const missing = await missingRequiredFields(deps, collection, resolved);
25611
- if (missing.length > 0) {
25612
- return { success: false, error: missingRequiredMessage(missing) };
25926
+ const missing2 = await missingRequiredFields(deps, collection, resolved);
25927
+ if (missing2.length > 0) {
25928
+ return { success: false, error: missingRequiredMessage(missing2) };
25613
25929
  }
25614
25930
  const isData = ext === "json" || ext === "yaml" || ext === "yml";
25615
25931
  const layout = isData ? "flat" : await detectCollectionMarkdownLayout(deps, collection);
25616
25932
  const collectionDir = await resolveCollectionDir(deps, collection);
25617
- const sourcePath = layout === "index" ? path4.posix.join(collectionDir, normalizedSlug, `index.${ext}`) : path4.posix.join(collectionDir, `${normalizedSlug}.${ext}`);
25933
+ const sourcePath = layout === "index" ? path5.posix.join(collectionDir, normalizedSlug, `index.${ext}`) : path5.posix.join(collectionDir, `${normalizedSlug}.${ext}`);
25618
25934
  let fileContent;
25619
25935
  if (isData) {
25620
25936
  fileContent = ext === "json" ? JSON.stringify({ ...resolved }, null, 2) + `
@@ -25644,9 +25960,9 @@ async function updateEntry(deps, input) {
25644
25960
  const existing = sourcePath.endsWith(".json") ? JSON.parse(raw) : import_yaml3.default.parse(raw);
25645
25961
  const merged = { ...existing ?? {}, ...patch };
25646
25962
  const resolved = await applyDerivedFields(deps, input.collection, merged, patch ?? {});
25647
- const missing = await missingRequiredFields(deps, input.collection, resolved);
25648
- if (missing.length > 0) {
25649
- return { success: false, error: missingRequiredMessage(missing) };
25963
+ const missing2 = await missingRequiredFields(deps, input.collection, resolved);
25964
+ if (missing2.length > 0) {
25965
+ return { success: false, error: missingRequiredMessage(missing2) };
25650
25966
  }
25651
25967
  const output = sourcePath.endsWith(".json") ? JSON.stringify(resolved, null, 2) + `
25652
25968
  ` : import_yaml3.default.stringify(resolved);
@@ -25659,9 +25975,9 @@ async function updateEntry(deps, input) {
25659
25975
  ...patch
25660
25976
  };
25661
25977
  const resolvedFrontmatter = await applyDerivedFields(deps, input.collection, mergedFrontmatter, patch ?? {});
25662
- const missing = await missingRequiredFields(deps, input.collection, resolvedFrontmatter);
25663
- if (missing.length > 0) {
25664
- return { success: false, error: missingRequiredMessage(missing) };
25978
+ const missing2 = await missingRequiredFields(deps, input.collection, resolvedFrontmatter);
25979
+ if (missing2.length > 0) {
25980
+ return { success: false, error: missingRequiredMessage(missing2) };
25665
25981
  }
25666
25982
  let finalContent = input.body ?? existing.content;
25667
25983
  if (sourcePath.endsWith(".mdx")) {
@@ -26050,24 +26366,53 @@ function replacePageTitle(content, newTitle) {
26050
26366
  return result;
26051
26367
  }
26052
26368
 
26369
+ // ../cms-core/src/redirects.ts
26370
+ var CMS_REDIRECTS_FILE = "src/_redirects";
26371
+ var HEADER = `# Merged by @nuasite. A host applies the first rule that matches, so each source of rules
26372
+ ` + `# is listed ahead of the ones it takes precedence over.
26373
+ `;
26374
+ var isTarget = (field) => field.startsWith("/") || /^https?:\/\/\S/.test(field);
26375
+ var isCondition = (field) => field.includes("=") && !isTarget(field);
26376
+ var pathOf = (source) => source.replace(/^https?:\/\/[^/]*/, "");
26377
+ function parseRedirectRule(line) {
26378
+ const fields = line.trim().split(/\s+/);
26379
+ const source = fields.shift();
26380
+ if (!source || !isTarget(source))
26381
+ return;
26382
+ const conditions = [];
26383
+ while (fields[0] !== undefined && isCondition(fields[0]))
26384
+ conditions.push(fields.shift());
26385
+ const destination = fields.shift();
26386
+ if (!destination || !isTarget(destination))
26387
+ return;
26388
+ const status = fields[0] !== undefined && /^\d{3}!?$/.test(fields[0]) ? fields.shift() : undefined;
26389
+ while (fields[0] !== undefined && isCondition(fields[0]))
26390
+ conditions.push(fields.shift());
26391
+ if (fields.length > 0)
26392
+ return;
26393
+ return {
26394
+ source,
26395
+ destination,
26396
+ status,
26397
+ conditions,
26398
+ key: [source, ...conditions.toSorted()].join(" "),
26399
+ pattern: /\*|:[A-Za-z_]/.test(pathOf(source)),
26400
+ text: line.trim().split(/\s+/).join(" ")
26401
+ };
26402
+ }
26403
+
26053
26404
  // ../cms-core/src/handlers/redirect-ops.ts
26054
26405
  var DEFAULT_STATUS_CODE = 307;
26055
- var REDIRECTS_FILE = "src/_redirects";
26406
+ var REDIRECTS_FILE = CMS_REDIRECTS_FILE;
26056
26407
  async function listRedirects(deps) {
26057
26408
  const lines = await readRedirectsFile(deps);
26058
26409
  return { rules: parseRedirectLines(lines) };
26059
26410
  }
26060
26411
  async function addRedirect(deps, request) {
26061
26412
  const { source, destination, statusCode = DEFAULT_STATUS_CODE } = request;
26062
- if (!source || !destination) {
26063
- return { success: false, error: "Source and destination are required" };
26064
- }
26065
- if (!source.startsWith("/")) {
26066
- return { success: false, error: "Source must start with /" };
26067
- }
26068
- if (!destination.startsWith("/") && !destination.startsWith("http")) {
26069
- return { success: false, error: "Destination must start with / or http" };
26070
- }
26413
+ const invalid = ruleError(source, destination, statusCode);
26414
+ if (invalid)
26415
+ return { success: false, error: invalid };
26071
26416
  const lines = await readRedirectsFile(deps);
26072
26417
  const existing = parseRedirectLines(lines);
26073
26418
  if (existing.some((r) => r.source === source)) {
@@ -26079,14 +26424,19 @@ async function addRedirect(deps, request) {
26079
26424
  }
26080
26425
  async function updateRedirect(deps, request) {
26081
26426
  const { lineIndex, source, destination, statusCode = DEFAULT_STATUS_CODE } = request;
26082
- if (!source || !destination) {
26083
- return { success: false, error: "Source and destination are required" };
26084
- }
26427
+ const invalid = ruleError(source, destination, statusCode);
26428
+ if (invalid)
26429
+ return { success: false, error: invalid };
26085
26430
  const lines = await readRedirectsFile(deps);
26086
26431
  const currentLine = lines[lineIndex]?.trim();
26087
26432
  if (!currentLine || currentLine.startsWith("#")) {
26088
26433
  return { success: false, error: "Line at index is no longer a redirect rule \u2014 please refresh and try again" };
26089
26434
  }
26435
+ const rules = parseRedirectLines(lines);
26436
+ const current = rules.find((r) => r.lineIndex === lineIndex);
26437
+ if (current?.source !== source && rules.some((r) => r.source === source && r.lineIndex !== lineIndex)) {
26438
+ return { success: false, error: `Redirect already exists for ${source}` };
26439
+ }
26090
26440
  lines[lineIndex] = formatRedirectLine(source, destination, statusCode);
26091
26441
  await writeRedirectsFile(deps, lines);
26092
26442
  return { success: true };
@@ -26105,6 +26455,19 @@ async function deleteRedirect(deps, request) {
26105
26455
  await writeRedirectsFile(deps, lines);
26106
26456
  return { success: true };
26107
26457
  }
26458
+ function ruleError(source, destination, statusCode) {
26459
+ if (!source || !destination)
26460
+ return "Source and destination are required";
26461
+ if (/\s/.test(source) || /\s/.test(destination))
26462
+ return "Source and destination must not contain spaces";
26463
+ if (!source.startsWith("/"))
26464
+ return "Source must start with /";
26465
+ if (![301, 302, 303, 307, 308].includes(statusCode))
26466
+ return "Status must be a redirect: 301, 302, 303, 307 or 308";
26467
+ if (!parseRedirectRule(formatRedirectLine(source, destination, statusCode)))
26468
+ return "Destination must start with / or http:// or https://";
26469
+ return;
26470
+ }
26108
26471
  function formatRedirectLine(source, destination, statusCode) {
26109
26472
  return statusCode === DEFAULT_STATUS_CODE ? `${source} ${destination}` : `${source} ${destination} ${statusCode}`;
26110
26473
  }
@@ -26134,246 +26497,101 @@ function parseRedirectLines(lines) {
26134
26497
  const line = lines[i].trim();
26135
26498
  if (!line || line.startsWith("#"))
26136
26499
  continue;
26137
- const parts = line.split(/\s+/);
26138
- if (parts.length < 2)
26139
- continue;
26140
- const source = parts[0];
26141
- if (!source.startsWith("/"))
26500
+ const rule = parseRedirectRule(line);
26501
+ if (!rule || !rule.source.startsWith("/"))
26142
26502
  continue;
26143
- const destination = parts[1];
26144
- const statusCode = parts[2] ? parseInt(parts[2], 10) : DEFAULT_STATUS_CODE;
26145
- rules.push({
26146
- source,
26147
- destination,
26148
- statusCode: Number.isNaN(statusCode) ? DEFAULT_STATUS_CODE : statusCode,
26149
- lineIndex: i
26150
- });
26503
+ const statusCode = rule.status ? parseInt(rule.status, 10) : DEFAULT_STATUS_CODE;
26504
+ rules.push({ source: rule.source, destination: rule.destination, statusCode, lineIndex: i });
26151
26505
  }
26152
26506
  return rules;
26153
26507
  }
26154
26508
 
26155
26509
  // ../cms-core/src/core.ts
26156
- function createCmsCore(fs2, opts = {}) {
26510
+ function createCmsCore(fs3, opts = {}) {
26157
26511
  const contentDir = opts.contentDir ?? "src/content";
26158
26512
  const componentDirs = opts.componentDirs ?? ["src/components"];
26513
+ const commit = opts.commit;
26159
26514
  const parseCache = new Map;
26160
- const entryDeps = {
26161
- fs: fs2,
26162
- contentDir,
26163
- parseCache,
26164
- componentDirs,
26165
- resolveComponentDefinitions: () => scanComponentDefinitions(fs2, componentDirs)
26166
- };
26515
+ function entryDeps(over) {
26516
+ return {
26517
+ fs: over,
26518
+ contentDir,
26519
+ parseCache,
26520
+ componentDirs,
26521
+ resolveComponentDefinitions: () => scanComponentDefinitions(over, componentDirs)
26522
+ };
26523
+ }
26524
+ const readDeps = entryDeps(fs3);
26525
+ async function mutate(operation) {
26526
+ if (commit === undefined)
26527
+ return operation(fs3);
26528
+ const staged = createStagedFileSystem(fs3);
26529
+ const result = await operation(staged);
26530
+ await commit(staged.changeset());
26531
+ return result;
26532
+ }
26167
26533
  return {
26168
26534
  scanCollections(options) {
26169
- return scanCollections(fs2, contentDir, parseCache, { report: options?.report ?? false });
26535
+ return scanCollections(fs3, contentDir, parseCache, { report: options?.report ?? false });
26170
26536
  },
26171
26537
  collectionScanReport,
26172
26538
  scanComponents() {
26173
- return scanComponentDefinitions(fs2, componentDirs);
26539
+ return scanComponentDefinitions(fs3, componentDirs);
26174
26540
  },
26175
26541
  getEntry(collection, slug) {
26176
- return getEntry(entryDeps, collection, slug);
26542
+ return getEntry(readDeps, collection, slug);
26177
26543
  },
26178
26544
  getEntryAsset(collection, slug, assetPath) {
26179
- return getEntryAsset(entryDeps, collection, slug, assetPath);
26545
+ return getEntryAsset(readDeps, collection, slug, assetPath);
26180
26546
  },
26181
26547
  getProjectAsset(assetPath) {
26182
- return getProjectAsset(entryDeps, assetPath);
26548
+ return getProjectAsset(readDeps, assetPath);
26183
26549
  },
26184
26550
  createEntry(input) {
26185
- return createEntry(entryDeps, input);
26551
+ return mutate((over) => createEntry(entryDeps(over), input));
26186
26552
  },
26187
26553
  updateEntry(input) {
26188
- return updateEntry(entryDeps, input);
26554
+ return mutate((over) => updateEntry(entryDeps(over), input));
26189
26555
  },
26190
26556
  deleteEntry(collection, slug) {
26191
- return deleteEntry(entryDeps, collection, slug);
26557
+ return mutate((over) => deleteEntry(entryDeps(over), collection, slug));
26192
26558
  },
26193
26559
  renameEntry(collection, from, to) {
26194
- return renameEntry(entryDeps, collection, from, to);
26560
+ return mutate((over) => renameEntry(entryDeps(over), collection, from, to));
26195
26561
  },
26196
26562
  addArrayItem(input) {
26197
- return addArrayItem(entryDeps, input);
26563
+ return mutate((over) => addArrayItem(entryDeps(over), input));
26198
26564
  },
26199
26565
  removeArrayItem(input) {
26200
- return removeArrayItem(entryDeps, input);
26566
+ return mutate((over) => removeArrayItem(entryDeps(over), input));
26201
26567
  },
26202
26568
  createPage(input) {
26203
- return createPage({ fs: fs2 }, input);
26569
+ return mutate((over) => createPage({ fs: over }, input));
26204
26570
  },
26205
26571
  duplicatePage(input) {
26206
- return duplicatePage({ fs: fs2 }, input);
26572
+ return mutate((over) => duplicatePage({ fs: over }, input));
26207
26573
  },
26208
26574
  deletePage(input) {
26209
- return deletePage({ fs: fs2 }, input);
26575
+ return mutate((over) => deletePage({ fs: over }, input));
26210
26576
  },
26211
26577
  getLayouts() {
26212
- return getLayouts({ fs: fs2 });
26578
+ return getLayouts({ fs: fs3 });
26213
26579
  },
26214
26580
  listRedirects() {
26215
- return listRedirects({ fs: fs2 });
26581
+ return listRedirects({ fs: fs3 });
26216
26582
  },
26217
26583
  addRedirect(input) {
26218
- return addRedirect({ fs: fs2 }, input);
26584
+ return mutate((over) => addRedirect({ fs: over }, input));
26219
26585
  },
26220
26586
  updateRedirect(input) {
26221
- return updateRedirect({ fs: fs2 }, input);
26587
+ return mutate((over) => updateRedirect({ fs: over }, input));
26222
26588
  },
26223
26589
  deleteRedirect(input) {
26224
- return deleteRedirect({ fs: fs2 }, input);
26590
+ return mutate((over) => deleteRedirect({ fs: over }, input));
26225
26591
  },
26226
26592
  media: opts.media
26227
26593
  };
26228
26594
  }
26229
- // ../cms-core/src/fs/node-fs.ts
26230
- import fs2 from "fs/promises";
26231
- import path5 from "path";
26232
- function resolveWithinRoot(root, filePath) {
26233
- const resolvedRoot = path5.resolve(root);
26234
- const isAbsoluteFs = filePath.startsWith(resolvedRoot);
26235
- const normalizedPath = !isAbsoluteFs && filePath.startsWith("/") ? filePath.slice(1) : filePath;
26236
- const fullPath = path5.isAbsolute(normalizedPath) ? path5.resolve(normalizedPath) : path5.resolve(resolvedRoot, normalizedPath);
26237
- if (!fullPath.startsWith(resolvedRoot + path5.sep) && fullPath !== resolvedRoot) {
26238
- throw new Error(`Path traversal detected: ${filePath}`);
26239
- }
26240
- return fullPath;
26241
- }
26242
- function isNodeError(error) {
26243
- return error instanceof Error && "code" in error;
26244
- }
26245
- var isWithin = (root, abs) => abs === root || abs.startsWith(root.endsWith(path5.sep) ? root : root + path5.sep);
26246
- var relativeTo = (absRoot, abs) => path5.relative(absRoot, abs).split(path5.sep).join("/") || ".";
26247
- async function walkFiles(walk, absDir, linked) {
26248
- if (linked.size > 0 && walk.linkedDirectoriesLeft !== undefined && walk.linkedDirectoriesLeft-- <= 0) {
26249
- throw new Error(`More than ${walk.maxLinkedDirectories} directories to list behind symbolic links`);
26250
- }
26251
- let dirEntries;
26252
- try {
26253
- dirEntries = await fs2.readdir(absDir, { withFileTypes: true });
26254
- } catch (error) {
26255
- if (!isNodeError(error))
26256
- throw error;
26257
- if (error.code === "ENOENT" || error.code === "ENOTDIR")
26258
- return [];
26259
- throw new UnreadableDirectoryError(relativeTo(walk.absRoot, absDir), error.code ?? "unknown error", { cause: error });
26260
- }
26261
- const out = [];
26262
- for (const entry of dirEntries) {
26263
- const abs = path5.join(absDir, entry.name);
26264
- let isDirectory = entry.isDirectory();
26265
- let isFile = entry.isFile();
26266
- let within = linked;
26267
- let real = null;
26268
- if (walk.followSymlinks && entry.isSymbolicLink()) {
26269
- const target = await fs2.stat(abs).catch(() => null);
26270
- real = target?.isDirectory() ? await fs2.realpath(abs).catch(() => abs) : null;
26271
- isFile = target?.isFile() ?? false;
26272
- isDirectory = real !== null && !linked.has(real);
26273
- if (real !== null)
26274
- within = new Set([...linked, real]);
26275
- }
26276
- if (isDirectory) {
26277
- if (walk.skip(relativeTo(walk.absRoot, abs)))
26278
- continue;
26279
- if (!walk.mayHold(relativeTo(walk.absRoot, abs)))
26280
- continue;
26281
- if (real !== null && !isWithin(walk.realRoot, real)) {
26282
- throw new Error(`Symbolic link "${relativeTo(walk.absRoot, abs)}" leads out of the project root`);
26283
- }
26284
- out.push(...await walkFiles(walk, abs, within));
26285
- } else if (isFile) {
26286
- out.push(relativeTo(walk.absRoot, abs));
26287
- }
26288
- }
26289
- return out;
26290
- }
26291
- function staticPrefixDir(pattern) {
26292
- const segments = pattern.split("/");
26293
- const staticSegments = [];
26294
- for (const segment of segments) {
26295
- if (/[*?{}[\]]/.test(segment))
26296
- break;
26297
- staticSegments.push(segment);
26298
- }
26299
- if (staticSegments.length === segments.length) {
26300
- staticSegments.pop();
26301
- }
26302
- return staticSegments.join("/");
26303
- }
26304
- function createNodeFs(root) {
26305
- const resolvedRoot = path5.resolve(root);
26306
- const resolve = (p) => resolveWithinRoot(resolvedRoot, p);
26307
- return {
26308
- async readFile(filePath) {
26309
- return fs2.readFile(resolve(filePath), "utf-8");
26310
- },
26311
- async readBytes(filePath) {
26312
- return fs2.readFile(resolve(filePath));
26313
- },
26314
- async writeFile(filePath, content) {
26315
- const fullPath = resolve(filePath);
26316
- await fs2.mkdir(path5.dirname(fullPath), { recursive: true });
26317
- const tempPath = `${fullPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
26318
- try {
26319
- await fs2.writeFile(tempPath, content, "utf-8");
26320
- await fs2.rename(tempPath, fullPath);
26321
- } catch (error) {
26322
- await fs2.rm(tempPath, { force: true });
26323
- throw error;
26324
- }
26325
- },
26326
- async rename(from, to) {
26327
- const fullTo = resolve(to);
26328
- await fs2.mkdir(path5.dirname(fullTo), { recursive: true });
26329
- await fs2.rename(resolve(from), fullTo);
26330
- },
26331
- async remove(filePath) {
26332
- await fs2.rm(resolve(filePath), { force: true });
26333
- },
26334
- async exists(filePath) {
26335
- try {
26336
- await fs2.access(resolve(filePath));
26337
- return true;
26338
- } catch {
26339
- return false;
26340
- }
26341
- },
26342
- async list(dir) {
26343
- try {
26344
- const entries = await fs2.readdir(resolve(dir), { withFileTypes: true });
26345
- return entries.map((entry) => ({ name: entry.name, isDirectory: entry.isDirectory() }));
26346
- } catch (error) {
26347
- if (isNodeError(error) && error.code === "ENOENT")
26348
- return [];
26349
- throw error;
26350
- }
26351
- },
26352
- async glob(pattern, options) {
26353
- const baseRel = staticPrefixDir(pattern);
26354
- const absBase = resolve(baseRel);
26355
- const matcher = globToRegExp(pattern);
26356
- const followSymlinks = options?.followSymlinks ?? false;
26357
- const walk = {
26358
- absRoot: resolvedRoot,
26359
- mayHold: (dir) => globMayMatchUnder(pattern, dir),
26360
- skip: options?.skipDirectory ?? (() => false),
26361
- followSymlinks,
26362
- realRoot: followSymlinks ? await fs2.realpath(resolvedRoot).catch(() => resolvedRoot) : resolvedRoot,
26363
- maxLinkedDirectories: options?.maxLinkedDirectories,
26364
- linkedDirectoriesLeft: options?.maxLinkedDirectories
26365
- };
26366
- if (!walk.mayHold(relativeTo(resolvedRoot, absBase)))
26367
- return [];
26368
- const files = await walkFiles(walk, absBase, new Set);
26369
- return files.filter((rel) => matcher.test(rel));
26370
- },
26371
- async stat(filePath) {
26372
- const s = await fs2.stat(resolve(filePath));
26373
- return { mtimeMs: s.mtimeMs, size: s.size };
26374
- }
26375
- };
26376
- }
26377
26595
  // ../cms-core/src/media/contember.ts
26378
26596
  function createContemberStorageAdapter(options) {
26379
26597
  const { apiBaseUrl, projectSlug, sessionToken } = options;
@@ -27065,9 +27283,9 @@ function mediaFromEnv(env = process.env) {
27065
27283
  }
27066
27284
 
27067
27285
  // src/concurrency.ts
27068
- import { createHash } from "crypto";
27286
+ import { createHash as createHash2 } from "crypto";
27069
27287
  function hashContent(content) {
27070
- return `sha256:${createHash("sha256").update(content, "utf-8").digest("hex")}`;
27288
+ return `sha256:${createHash2("sha256").update(content, "utf-8").digest("hex")}`;
27071
27289
  }
27072
27290
  async function hashSource(fs3, sourcePath) {
27073
27291
  if (!await fs3.exists(sourcePath))
@@ -27519,25 +27737,39 @@ function createServer(opts) {
27519
27737
  if (!existing)
27520
27738
  return error("not_found", `Entry not found: ${collection}/${slug}`);
27521
27739
  const sourcePath = existing.sourcePath;
27740
+ const existingFrontmatter = existing.frontmatter;
27741
+ async function conflictResponse(serverHash) {
27742
+ const current = await core.getEntry(collection, slug);
27743
+ const conflict = {
27744
+ code: "conflict",
27745
+ serverHash,
27746
+ serverFrontmatter: current?.frontmatter ?? existingFrontmatter
27747
+ };
27748
+ if (current && current.content !== "")
27749
+ conflict.serverBody = current.content;
27750
+ return json(conflict, STATUS_BY_CODE.conflict);
27751
+ }
27522
27752
  return mutex.runExclusive(sourcePath, async () => {
27523
27753
  const serverHash = await hashSource(fs3, sourcePath);
27524
27754
  if (body.baseHash !== undefined && serverHash !== null && body.baseHash !== serverHash) {
27525
- const current = await core.getEntry(collection, slug);
27526
- const conflict = {
27527
- code: "conflict",
27528
- serverHash,
27529
- serverFrontmatter: current?.frontmatter ?? existing.frontmatter
27530
- };
27531
- if (current && current.content !== "")
27532
- conflict.serverBody = current.content;
27533
- return json(conflict, STATUS_BY_CODE.conflict);
27534
- }
27535
- const result = await core.updateEntry({
27536
- collection,
27537
- slug,
27538
- frontmatter: body.frontmatter,
27539
- body: body.body
27540
- });
27755
+ return conflictResponse(serverHash);
27756
+ }
27757
+ let result;
27758
+ try {
27759
+ result = await core.updateEntry({
27760
+ collection,
27761
+ slug,
27762
+ frontmatter: body.frontmatter,
27763
+ body: body.body
27764
+ });
27765
+ } catch (cause) {
27766
+ if (!(cause instanceof CmsCommitConflictError))
27767
+ throw cause;
27768
+ const currentHash = await hashSource(fs3, sourcePath);
27769
+ if (currentHash === null)
27770
+ throw cause;
27771
+ return conflictResponse(currentHash);
27772
+ }
27541
27773
  if (!result.success)
27542
27774
  return mutationResponse(result);
27543
27775
  const newHash = await hashSource(fs3, result.sourcePath ?? sourcePath);
@@ -27568,6 +27800,10 @@ function createServer(opts) {
27568
27800
  const method = req.method;
27569
27801
  try {
27570
27802
  return await route(method, segments, req, url);
27803
+ } catch (cause) {
27804
+ if (cause instanceof CmsCommitConflictError)
27805
+ return error("conflict", cause.message);
27806
+ throw cause;
27571
27807
  } finally {
27572
27808
  if (method !== "GET") {
27573
27809
  collectionsScan.invalidate();