@seed-hypermedia/client 0.0.132 → 0.0.134

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.
@@ -417,6 +417,23 @@ function createTypedNode(visible, comment) {
417
417
  }
418
418
  var COL_ID_RE = /<!--\s*col:([A-Za-z0-9_-]+)(?:\s+attrs:(\{.*?\}))?\s*-->/;
419
419
  var CELL_ID_RE = /<!--\s*id:([A-Za-z0-9_-]+)\s*-->/;
420
+ function matchUnescaped(text, re) {
421
+ const all = new RegExp(re.source, "g");
422
+ for (let match = all.exec(text); match; match = all.exec(text)) {
423
+ let slashes = 0;
424
+ while (text[match.index - 1 - slashes] === "\\") slashes++;
425
+ if (slashes % 2 === 0) return match;
426
+ }
427
+ return null;
428
+ }
429
+ function trimCell(raw) {
430
+ const start = raw.replace(/^\s+/, "");
431
+ const end = start.replace(/\s+$/, "");
432
+ if (end.length === start.length) return end;
433
+ let slashes = 0;
434
+ while (end[end.length - 1 - slashes] === "\\") slashes++;
435
+ return slashes % 2 === 1 ? end + start[end.length] : end;
436
+ }
420
437
  function splitTableRow(line) {
421
438
  const { text, id: afterPipeId } = stripBlockId(line.trim());
422
439
  let s = text.trim();
@@ -428,25 +445,25 @@ function splitTableRow(line) {
428
445
  cur += "|";
429
446
  i++;
430
447
  } else if (s[i] === "|") {
431
- rawCells.push(cur.trim());
448
+ rawCells.push(cur);
432
449
  cur = "";
433
450
  } else {
434
451
  cur += s[i];
435
452
  }
436
453
  }
437
- const last = cur.trim();
438
- if (last !== "" || rawCells.length === 0) rawCells.push(last);
454
+ if (cur.trim() !== "" || rawCells.length === 0) rawCells.push(cur);
439
455
  let rowId = afterPipeId;
440
456
  const cells = rawCells.map((raw) => {
441
457
  let cellText = raw;
442
- const idMatch = cellText.match(CELL_ID_RE);
458
+ const cut = (match) => cellText.slice(0, match.index) + cellText.slice(match.index + match[0].length);
459
+ const idMatch = matchUnescaped(cellText, CELL_ID_RE);
443
460
  if (idMatch) {
444
461
  rowId = idMatch[1];
445
- cellText = cellText.replace(idMatch[0], "");
462
+ cellText = cut(idMatch);
446
463
  }
447
464
  let colId;
448
465
  let colAttrs;
449
- const colMatch = cellText.match(COL_ID_RE);
466
+ const colMatch = matchUnescaped(cellText, COL_ID_RE);
450
467
  if (colMatch) {
451
468
  colId = colMatch[1];
452
469
  if (colMatch[2]) {
@@ -455,9 +472,9 @@ function splitTableRow(line) {
455
472
  } catch {
456
473
  }
457
474
  }
458
- cellText = cellText.replace(colMatch[0], "");
475
+ cellText = cut(colMatch);
459
476
  }
460
- return { text: cellText.trim(), colId, colAttrs };
477
+ return { text: trimCell(cellText), colId, colAttrs };
461
478
  });
462
479
  return { cells, id: rowId };
463
480
  }
@@ -675,10 +692,50 @@ function collapseResolvedEmbeds(markdown) {
675
692
  }
676
693
  return out.join("\n");
677
694
  }
695
+ var RESOLVED_OPEN = /^\s*<!--\s*resolved(?::[^>]*?)?\s*-->\s*$/;
696
+ var RESOLVED_CLOSE = /^\s*<!--\s*\/resolved\s*-->\s*$/;
697
+ var MarkdownResolvedRangeError = class extends Error {
698
+ constructor(message) {
699
+ super(message);
700
+ this.name = "MarkdownResolvedRangeError";
701
+ }
702
+ };
703
+ function stripResolvedRanges(markdown, options = {}) {
704
+ if (!/<!--\s*resolved/.test(markdown)) return markdown;
705
+ const out = [];
706
+ let depth = 0;
707
+ let fence = null;
708
+ for (const line of markdown.split("\n")) {
709
+ const trimmed = line.trim();
710
+ if (fence === null) {
711
+ if (RESOLVED_OPEN.test(line)) {
712
+ depth++;
713
+ continue;
714
+ }
715
+ if (depth > 0 && RESOLVED_CLOSE.test(line)) {
716
+ depth--;
717
+ continue;
718
+ }
719
+ const start = trimmed.replace(/^(?:(?:[-*+]|\d+[.)]|>) )+/, "");
720
+ const opening = /^(`{3,})/.exec(start);
721
+ if (opening) fence = opening[1].length;
722
+ else if (start.startsWith("$$")) fence = "$$";
723
+ } else if (fence === "$$" ? trimmed === "$$" : /^`{3,}$/.test(trimmed) && trimmed.length >= fence) {
724
+ fence = null;
725
+ }
726
+ if (depth === 0) out.push(line);
727
+ }
728
+ if (depth > 0 && options.strict !== false) {
729
+ throw new MarkdownResolvedRangeError(
730
+ "A `<!-- resolved -->` range is never closed with `<!-- /resolved -->`. Those ranges show what an embed or a query points at and are not part of the document: remove the range, or restore its closing line."
731
+ );
732
+ }
733
+ return out.join("\n");
734
+ }
678
735
  function parseMarkdown(markdown, options = {}) {
679
736
  var _a;
680
737
  const { content, metadata } = parseFrontmatter(markdown, options);
681
- const lines = collapseResolvedEmbeds(content).split("\n");
738
+ const lines = collapseResolvedEmbeds(stripResolvedRanges(content, { strict: options.strictResolvedRanges })).split("\n");
682
739
  const infos = lines.map(analyzeLine);
683
740
  const root = { list: [], childIndent: 0 };
684
741
  const stack = [root];
@@ -969,6 +1026,8 @@ export {
969
1026
  MarkdownFrontmatterError,
970
1027
  parseFrontmatter,
971
1028
  collapseResolvedEmbeds,
1029
+ MarkdownResolvedRangeError,
1030
+ stripResolvedRanges,
972
1031
  parseMarkdown,
973
1032
  markdownBlockNodesToHMBlockNodes,
974
1033
  flattenToOperations
@@ -0,0 +1,163 @@
1
+ // src/block-edits.ts
2
+ var BlockEditError = class extends Error {
3
+ constructor(index, message) {
4
+ super(`Edit ${index + 1}: ${message}`);
5
+ this.index = index;
6
+ this.name = "BlockEditError";
7
+ }
8
+ };
9
+ var POSITIONS = ["after", "before", "into"];
10
+ var LIST_TYPES = /* @__PURE__ */ new Set(["Unordered", "Ordered", "Blockquote"]);
11
+ var FORMS = "{replace: ID, content}, {after | before | into: ID, content}, {move: ID, after | before | into: ID} or {delete: ID}";
12
+ function locate(nodes, id, parent) {
13
+ for (let index = 0; index < nodes.length; index++) {
14
+ const node = nodes[index];
15
+ if (node.block.id === id) return { node, siblings: nodes, index, parent };
16
+ const found = locate(node.children, id, node);
17
+ if (found) return found;
18
+ }
19
+ return void 0;
20
+ }
21
+ function copyTree(nodes) {
22
+ return nodes.map((node) => ({ block: node.block, children: copyTree(node.children) }));
23
+ }
24
+ function isBareList(node) {
25
+ return node.block.type === "Paragraph" && !node.block.text && !node.block.link && node.children.length > 0 && LIST_TYPES.has(node.block.childrenType || "");
26
+ }
27
+ function fragmentUnder(parent, nodes) {
28
+ const only = nodes.length === 1 ? nodes[0] : void 0;
29
+ if (only && parent && isBareList(only) && parent.block.childrenType === only.block.childrenType) return only.children;
30
+ return nodes;
31
+ }
32
+ function idOf(index, value, what) {
33
+ if (typeof value !== "string" || !value)
34
+ throw new BlockEditError(index, `${what} must be a block id (the X of an \`<!-- id:X -->\` comment).`);
35
+ return value;
36
+ }
37
+ function contentOf(index, edit) {
38
+ if (typeof edit.content !== "string") throw new BlockEditError(index, "`content` must be a markdown string.");
39
+ return edit.content;
40
+ }
41
+ function applyBlockEdits(tree, edits, parse) {
42
+ if (!Array.isArray(edits) || edits.length === 0) throw new BlockEditError(0, `edits must be a list of ${FORMS}.`);
43
+ const root = copyTree(tree);
44
+ const written = [];
45
+ const find = (index, id) => {
46
+ const found = locate(root, id);
47
+ if (!found)
48
+ throw new BlockEditError(
49
+ index,
50
+ `the document has no block with id "${id}". Read the document for its current block ids; an earlier edit in this list may have deleted it.`
51
+ );
52
+ return found;
53
+ };
54
+ const slot = (index, position, id) => {
55
+ const target = find(index, id);
56
+ if (position === "into") {
57
+ return { siblings: target.node.children, at: target.node.children.length, parent: target.node, target };
58
+ }
59
+ return {
60
+ siblings: target.siblings,
61
+ at: position === "after" ? target.index + 1 : target.index,
62
+ parent: target.parent,
63
+ target
64
+ };
65
+ };
66
+ const adopt = (parent, nodes) => {
67
+ if (!parent || parent.children.length > 0) return fragmentUnder(parent, nodes);
68
+ const only = nodes.length === 1 ? nodes[0] : void 0;
69
+ const nests = only && isBareList(only) && parent.block.type === "Paragraph" && !!parent.block.text;
70
+ const childrenType = nests ? only.block.childrenType : parent.block.childrenType || "Group";
71
+ if (parent.block.childrenType !== childrenType) parent.block = { ...parent.block, childrenType };
72
+ return nests ? only.children : fragmentUnder(parent, nodes);
73
+ };
74
+ edits.forEach((raw, index) => {
75
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
76
+ throw new BlockEditError(index, `an edit is one of ${FORMS}.`);
77
+ const edit = raw;
78
+ const positions = POSITIONS.filter((key) => edit[key] !== void 0);
79
+ const verbs = ["replace", "move", "delete"].filter((key) => edit[key] !== void 0);
80
+ const known = /* @__PURE__ */ new Set(["replace", "move", "delete", "content", ...POSITIONS]);
81
+ const unknown = Object.keys(edit).filter((key) => !known.has(key));
82
+ if (unknown.length || verbs.length > 1 || positions.length > 1)
83
+ throw new BlockEditError(index, `an edit is one of ${FORMS}.`);
84
+ if (edit.delete !== void 0) {
85
+ if (positions.length || edit.content !== void 0)
86
+ throw new BlockEditError(index, "a delete takes only the id, or a list of ids, to delete.");
87
+ const ids = Array.isArray(edit.delete) ? edit.delete : [edit.delete];
88
+ for (const id of ids) {
89
+ const target = find(index, idOf(index, id, "`delete`"));
90
+ target.siblings.splice(target.index, 1);
91
+ }
92
+ return;
93
+ }
94
+ if (edit.move !== void 0) {
95
+ if (positions.length !== 1 || edit.content !== void 0)
96
+ throw new BlockEditError(index, "a move names where the block goes: one of after, before or into.");
97
+ const moved = find(index, idOf(index, edit.move, "`move`"));
98
+ const position2 = positions[0];
99
+ const anchor = idOf(index, edit[position2], `\`${position2}\``);
100
+ if (locate([moved.node], anchor))
101
+ throw new BlockEditError(
102
+ index,
103
+ `block "${moved.node.block.id}" cannot move ${position2} itself or its children.`
104
+ );
105
+ moved.siblings.splice(moved.index, 1);
106
+ const to2 = slot(index, position2, anchor);
107
+ if (to2.parent && !to2.parent.children.length && !to2.parent.block.childrenType)
108
+ to2.parent.block = { ...to2.parent.block, childrenType: "Group" };
109
+ to2.siblings.splice(to2.at, 0, moved.node);
110
+ return;
111
+ }
112
+ if (edit.replace !== void 0) {
113
+ if (positions.length)
114
+ throw new BlockEditError(index, "a replace takes the id and `content`. Add blocks with a separate edit.");
115
+ const target = find(index, idOf(index, edit.replace, "`replace`"));
116
+ const nodes2 = fragmentUnder(target.parent, parse(contentOf(index, edit)));
117
+ const first = nodes2[0];
118
+ if (!first) throw new BlockEditError(index, "the replacement is empty. To remove the block, use {delete: ID}.");
119
+ const kept = target.node.block.type === "Table" ? [] : target.node.children;
120
+ if (first.block.type === "Table" ? kept.length > 0 : first.children.length > 0 && kept.length > 0)
121
+ throw new BlockEditError(
122
+ index,
123
+ `block "${target.node.block.id}" has children, which a replace keeps, so the replacement cannot bring children of its own. Write only the block itself, and change its children by their ids or add to them with {into: "${target.node.block.id}", content}.`
124
+ );
125
+ const children = first.block.type === "Table" || !kept.length ? first.children : kept;
126
+ const childrenType = kept.length ? target.node.block.childrenType : first.block.childrenType;
127
+ const { childrenType: _written, ...own } = first.block;
128
+ const replacement = {
129
+ block: { ...own, id: target.node.block.id, ...childrenType ? { childrenType } : {} },
130
+ children
131
+ };
132
+ target.siblings.splice(target.index, 1, replacement, ...nodes2.slice(1));
133
+ written.push(replacement, ...nodes2.slice(1));
134
+ return;
135
+ }
136
+ if (positions.length !== 1) throw new BlockEditError(index, `an edit is one of ${FORMS}.`);
137
+ const position = positions[0];
138
+ const to = slot(index, position, idOf(index, edit[position], `\`${position}\``));
139
+ const nodes = adopt(to.parent, parse(contentOf(index, edit)));
140
+ if (!nodes.length) throw new BlockEditError(index, "`content` holds no blocks to add.");
141
+ to.siblings.splice(to.at, 0, ...nodes);
142
+ written.push(...nodes);
143
+ });
144
+ const seen = /* @__PURE__ */ new Set();
145
+ const check = (nodes) => {
146
+ for (const node of nodes) {
147
+ if (seen.has(node.block.id))
148
+ throw new BlockEditError(
149
+ edits.length - 1,
150
+ `block id "${node.block.id}" would be in the document twice. Leave id comments off new blocks; an id is only for the block that already has it.`
151
+ );
152
+ seen.add(node.block.id);
153
+ check(node.children);
154
+ }
155
+ };
156
+ check(root);
157
+ return { tree: root, written };
158
+ }
159
+
160
+ export {
161
+ BlockEditError,
162
+ applyBlockEdits
163
+ };
@@ -1,3 +1,10 @@
1
+ import {
2
+ parseMarkdown
3
+ } from "./chunk-4ELQ4LJL.mjs";
4
+ import {
5
+ blocksToMarkdown
6
+ } from "./chunk-QFIEZZYJ.mjs";
7
+
1
8
  // src/block-diff.ts
2
9
  function createBlocksMap(nodes, parentId = "") {
3
10
  const result = {};
@@ -370,6 +377,144 @@ function hmBlockNodeToBlockNode(node) {
370
377
  children: (node.children || []).map(hmBlockNodeToBlockNode)
371
378
  };
372
379
  }
380
+ var TABLE_PARTS = /* @__PURE__ */ new Set(["Table", "TableColumn", "TableRow"]);
381
+ function stableJson(value) {
382
+ if (Array.isArray(value)) return "[" + value.map(stableJson).join(",") + "]";
383
+ if (value && typeof value === "object") {
384
+ const map = value;
385
+ const keys = Object.keys(map).filter((key) => map[key] !== void 0).sort();
386
+ return "{" + keys.map((key) => JSON.stringify(key) + ":" + stableJson(map[key])).join(",") + "}";
387
+ }
388
+ return JSON.stringify(value) ?? "null";
389
+ }
390
+ function nativeIpfsLink(link) {
391
+ const gateway = "https://ipfs.io/ipfs/";
392
+ return link.startsWith(gateway) ? "ipfs://" + link.slice(gateway.length) : link;
393
+ }
394
+ function blockKey(block, own = false) {
395
+ const annotations = (block.annotations || []).map(canonicalAnnotation).filter(hasRange).map((annotation) => stableJson(annotation)).sort();
396
+ return stableJson([
397
+ block.type,
398
+ block.text || "",
399
+ nativeIpfsLink(block.link || ""),
400
+ annotations,
401
+ own ? "" : block.childrenType || "",
402
+ block.language || "",
403
+ block.attributes || {}
404
+ ]);
405
+ }
406
+ function eachBlock(nodes, visit) {
407
+ for (const node of nodes) {
408
+ visit(node.block);
409
+ eachBlock(node.children, visit);
410
+ }
411
+ }
412
+ function markdownUpdateTree(oldContent, written) {
413
+ const oldNodes = oldContent.map(toAPIBlockNode);
414
+ const tree = rebindTableIdentities(oldNodes, written);
415
+ const stored = /* @__PURE__ */ new Map();
416
+ eachBlock(oldContent.map(hmBlockNodeToBlockNode), (block) => {
417
+ if (block.id && !stored.has(block.id)) stored.set(block.id, block);
418
+ });
419
+ const readsAs = /* @__PURE__ */ new Map();
420
+ const readsAsOwn = /* @__PURE__ */ new Map();
421
+ for (const mentionLabel of [() => "", void 0]) {
422
+ try {
423
+ const markdown = blocksToMarkdown({ metadata: {}, content: oldContent }, {
424
+ ipfsGateway: false,
425
+ mentionLabel
426
+ });
427
+ eachBlock(rebindTableIdentities(oldNodes, parseMarkdown(markdown).tree), (block) => {
428
+ if (!stored.has(block.id)) return;
429
+ readsAs.set(block.id, (readsAs.get(block.id) || /* @__PURE__ */ new Set()).add(blockKey(block)));
430
+ readsAsOwn.set(block.id, (readsAsOwn.get(block.id) || /* @__PURE__ */ new Set()).add(blockKey(block, true)));
431
+ });
432
+ } catch {
433
+ }
434
+ }
435
+ const present = /* @__PURE__ */ new Set();
436
+ eachBlock(tree, (block) => present.add(block.id));
437
+ const matchable = (block) => !TABLE_PARTS.has(block.type) && !!(block.text || block.link);
438
+ const unclaimed = /* @__PURE__ */ new Map();
439
+ for (const [id, block] of Array.from(stored)) {
440
+ if (present.has(id) || !matchable(block)) continue;
441
+ for (const key of Array.from(readsAsOwn.get(id) || [])) {
442
+ const ids = unclaimed.get(key);
443
+ if (ids) ids.push(id);
444
+ else unclaimed.set(key, [id]);
445
+ }
446
+ }
447
+ const claim = (key) => {
448
+ const ids = unclaimed.get(key) || [];
449
+ while (ids.length) {
450
+ const id = ids.shift();
451
+ if (!present.has(id)) {
452
+ present.add(id);
453
+ return id;
454
+ }
455
+ }
456
+ return void 0;
457
+ };
458
+ const walk = (nodes) => nodes.map((node) => {
459
+ var _a;
460
+ const key = blockKey(node.block);
461
+ let id = node.block.id;
462
+ if (!stored.has(id) && matchable(node.block)) id = claim(blockKey(node.block, true)) ?? id;
463
+ const block = ((_a = readsAs.get(id)) == null ? void 0 : _a.has(key)) ? stored.get(id) : id === node.block.id ? node.block : { ...node.block, id };
464
+ return { block, children: walk(node.children) };
465
+ });
466
+ return walk(tree);
467
+ }
468
+ function longestOrdered(ids, rank) {
469
+ const tails = [];
470
+ for (const id of ids) {
471
+ const value = rank.get(id);
472
+ let low = 0;
473
+ let high = tails.length;
474
+ while (low < high) {
475
+ const mid = low + high >> 1;
476
+ if (tails[mid] < value) low = mid + 1;
477
+ else high = mid;
478
+ }
479
+ tails[low] = value;
480
+ }
481
+ return tails.length;
482
+ }
483
+ function describeContentChange(oldNodes, newTree, ops) {
484
+ const place = (nodes) => {
485
+ const placed = /* @__PURE__ */ new Map();
486
+ const walk = (list, parent) => list.forEach((node, index) => {
487
+ var _a;
488
+ if (!((_a = node.block) == null ? void 0 : _a.id) || placed.has(node.block.id)) return;
489
+ placed.set(node.block.id, { parent, index });
490
+ walk(node.children || [], node.block.id);
491
+ });
492
+ walk(nodes, "");
493
+ return placed;
494
+ };
495
+ const before = place(oldNodes);
496
+ const after = place(newTree);
497
+ let added = 0;
498
+ let moved = 0;
499
+ const kept = /* @__PURE__ */ new Map();
500
+ for (const [id, now] of Array.from(after)) {
501
+ const was = before.get(id);
502
+ if (!was) added++;
503
+ else if (was.parent !== now.parent) moved++;
504
+ else kept.set(now.parent, [...kept.get(now.parent) || [], id]);
505
+ }
506
+ for (const ids of Array.from(kept.values())) {
507
+ const rank = new Map(ids.map((id) => [id, before.get(id).index]));
508
+ moved += ids.length - longestOrdered(ids, rank);
509
+ }
510
+ let deleted = 0;
511
+ for (const id of Array.from(before.keys())) if (!after.has(id)) deleted++;
512
+ let rewritten = 0;
513
+ for (const op of ops) {
514
+ if (op.type === "ReplaceBlock" && before.has(String(op.block.id))) rewritten++;
515
+ }
516
+ return { blocks: before.size, added, rewritten, moved, deleted };
517
+ }
373
518
 
374
519
  export {
375
520
  createBlocksMap,
@@ -377,5 +522,7 @@ export {
377
522
  rebindTableIdentities,
378
523
  computeReplaceOps,
379
524
  toAPIBlockNode,
380
- hmBlockNodeToBlockNode
525
+ hmBlockNodeToBlockNode,
526
+ markdownUpdateTree,
527
+ describeContentChange
381
528
  };
@@ -2,7 +2,7 @@ import {
2
2
  HM_SCHEMAS,
3
3
  HM_SCHEMA_MANIFEST,
4
4
  HM_SCHEMA_PAGES
5
- } from "./chunk-T7SWLR32.mjs";
5
+ } from "./chunk-37QDFTT6.mjs";
6
6
 
7
7
  // src/schema-engine.ts
8
8
  var LIBRARY_AUTHORITY = "hyper.media";
@@ -158,7 +158,8 @@ function structFields(schema) {
158
158
  name,
159
159
  schema: (entry == null ? void 0 : entry.value) === void 0 ? {} : entry.value,
160
160
  required: (entry == null ? void 0 : entry.required) === true,
161
- description: typeof (entry == null ? void 0 : entry.description) === "string" ? entry.description : void 0
161
+ description: typeof (entry == null ? void 0 : entry.description) === "string" ? entry.description : void 0,
162
+ ...entry && typeof entry === "object" && entry.default !== void 0 ? { default: entry.default } : {}
162
163
  }));
163
164
  }
164
165
  function fieldSchema(schema, name) {
@@ -176,6 +177,7 @@ function fieldsToProperties(fields) {
176
177
  const e = { value: f.schema };
177
178
  if (f.required) e.required = true;
178
179
  if (f.description) e.description = f.description;
180
+ if (f.default !== void 0) e.default = f.default;
179
181
  out[f.name] = e;
180
182
  }
181
183
  return out;
@@ -310,6 +312,99 @@ function validate(schema0, data, path = "$", env0 = {}, reg = {}) {
310
312
  return errors;
311
313
  }
312
314
  var validateAdvisory = validate;
315
+ var cloneValue = (v) => v !== null && typeof v === "object" ? JSON.parse(JSON.stringify(v)) : v;
316
+ function seedValue(schema, registry = {}) {
317
+ return seedWithEnv(schema, {}, registry);
318
+ }
319
+ function seedWithEnv(schema0, env, reg) {
320
+ return seedAt(schema0, env, reg, 0);
321
+ }
322
+ var MAX_SEED_DEPTH = 24;
323
+ function seedAt(schema0, env, reg, depth) {
324
+ const { schema, env: e } = resolveSchema(schema0, env, reg);
325
+ if (isLiteralSchema(schema)) return schema.value;
326
+ if (schema.anyOf) return schema.anyOf.length ? seedAt(schema.anyOf[0], e, reg, depth + 1) : void 0;
327
+ const kind = schema.type ? kindOf(schema.type) : null;
328
+ switch (kind) {
329
+ case "map":
330
+ case "struct": {
331
+ const o = {};
332
+ for (const f of structFields(schema)) {
333
+ if (f.default !== void 0) o[f.name] = cloneValue(f.default);
334
+ else if (f.required && depth < MAX_SEED_DEPTH) o[f.name] = seedAt(f.schema, e, reg, depth + 1);
335
+ }
336
+ return o;
337
+ }
338
+ case "list":
339
+ return [];
340
+ case "string":
341
+ return "";
342
+ case "integer":
343
+ case "float":
344
+ return 0;
345
+ case "boolean":
346
+ return false;
347
+ case "null":
348
+ return null;
349
+ case "link":
350
+ return { "/": "" };
351
+ case "bytes":
352
+ return { "/": { bytes: "" } };
353
+ default:
354
+ return null;
355
+ }
356
+ }
357
+ function seedField(field, env = {}, reg = {}) {
358
+ return field.default !== void 0 ? cloneValue(field.default) : seedWithEnv(field.schema, env, reg);
359
+ }
360
+ function propertyDefaults(schema, registry = {}) {
361
+ if (!schema) return {};
362
+ const { schema: resolved } = resolveSchema(schema, {}, registry);
363
+ const out = {};
364
+ for (const f of structFields(resolved)) if (f.default !== void 0) out[f.name] = cloneValue(f.default);
365
+ return out;
366
+ }
367
+ function missingPropertyDefaults(schema, current, registry = {}) {
368
+ const defaults = propertyDefaults(schema, registry);
369
+ const held = current ?? {};
370
+ for (const key of Object.keys(defaults)) if (key in held && held[key] !== void 0) delete defaults[key];
371
+ return defaults;
372
+ }
373
+ function validateDefaults(schema, path = "$", env = {}, reg = {}) {
374
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return [];
375
+ let scope = env;
376
+ if (schema.params && typeof schema.params === "object") {
377
+ scope = { ...env };
378
+ for (const [p, def] of Object.entries(schema.params)) if (scope[p] === void 0) scope[p] = def;
379
+ }
380
+ const errors = [];
381
+ if (schema.properties && typeof schema.properties === "object") {
382
+ for (const [name, entry] of Object.entries(schema.properties)) {
383
+ if (!entry || typeof entry !== "object") continue;
384
+ const at = `${path}.properties.${name}`;
385
+ const value = entry.value === void 0 ? {} : entry.value;
386
+ if (entry.default !== void 0) errors.push(...validate(value, entry.default, `${at}.default`, scope, reg));
387
+ errors.push(...validateDefaults(value, `${at}.value`, scope, reg));
388
+ }
389
+ }
390
+ if (schema.items) errors.push(...validateDefaults(schema.items, `${path}.items`, scope, reg));
391
+ if (schema.values) errors.push(...validateDefaults(schema.values, `${path}.values`, scope, reg));
392
+ if (Array.isArray(schema.anyOf))
393
+ schema.anyOf.forEach(
394
+ (arm, i) => errors.push(...validateDefaults(arm, `${path}.anyOf[${i}]`, scope, reg))
395
+ );
396
+ if (schema.params && typeof schema.params === "object")
397
+ for (const [p, def] of Object.entries(schema.params))
398
+ errors.push(...validateDefaults(def, `${path}.params.${p}`, scope, reg));
399
+ return errors;
400
+ }
401
+ function schemaErrors(value, reg = {}) {
402
+ const meta = HM_SCHEMAS["schema"];
403
+ if (!meta) return [];
404
+ const errors = validate(meta, value, "$", {}, reg);
405
+ if (errors.length || !value || typeof value !== "object") return errors;
406
+ return validateDefaults(value, "$", {}, reg);
407
+ }
313
408
  function isHypermediaSchema(value, reg = {}) {
314
409
  const meta = HM_SCHEMAS["schema"];
315
410
  if (!meta || !value || typeof value !== "object") return false;
@@ -350,6 +445,10 @@ function collectRefs(schema, acc = /* @__PURE__ */ new Set()) {
350
445
  if (typeof schema.target === "string") acc.add(refToName(schema.target));
351
446
  for (const [k, v] of Object.entries(schema)) {
352
447
  if (k === "ref" || k === "type" || k === "target") continue;
448
+ if (k === "properties" && v && typeof v === "object" && !Array.isArray(v)) {
449
+ for (const entry of Object.values(v)) collectRefs(entry == null ? void 0 : entry.value, acc);
450
+ continue;
451
+ }
353
452
  if (v && typeof v === "object") collectRefs(v, acc);
354
453
  }
355
454
  return acc;
@@ -400,6 +499,13 @@ export {
400
499
  resolveSchema,
401
500
  validate,
402
501
  validateAdvisory,
502
+ seedValue,
503
+ seedWithEnv,
504
+ seedField,
505
+ propertyDefaults,
506
+ missingPropertyDefaults,
507
+ validateDefaults,
508
+ schemaErrors,
403
509
  isHypermediaSchema,
404
510
  schemaShape,
405
511
  collectRefs,
@@ -4,16 +4,18 @@ import {
4
4
  fieldsToProperties,
5
5
  isLiteralSchema,
6
6
  loadFrom,
7
+ missingPropertyDefaults,
7
8
  refToName,
8
9
  resolveSchema,
9
10
  schemaCid,
11
+ schemaErrors,
10
12
  schemaForCid,
11
13
  structFields,
12
14
  validate
13
- } from "./chunk-NEUDKUBC.mjs";
15
+ } from "./chunk-BRNXLHBP.mjs";
14
16
  import {
15
17
  HM_SCHEMAS
16
- } from "./chunk-T7SWLR32.mjs";
18
+ } from "./chunk-37QDFTT6.mjs";
17
19
  import {
18
20
  parseCidString
19
21
  } from "./chunk-VWSAFDOL.mjs";
@@ -92,7 +94,9 @@ function referencesOf(schema, out = []) {
92
94
  const node = schema;
93
95
  for (const [key, value] of Object.entries(node)) {
94
96
  if ((key === "ref" || key === "type") && typeof value === "string") out.push(value);
95
- else if (key === "description" || key === "target" || key === "format" || key === "value") {
97
+ else if (key === "properties" && value && typeof value === "object" && !Array.isArray(value)) {
98
+ for (const entry of Object.values(value)) referencesOf(entry == null ? void 0 : entry.value, out);
99
+ } else if (key === "description" || key === "target" || key === "format" || key === "value") {
96
100
  if (key === "value" && value && typeof value === "object") referencesOf(value, out);
97
101
  } else if (value && typeof value === "object") referencesOf(value, out);
98
102
  }
@@ -183,6 +187,16 @@ async function checkDocumentSchema(client, id, metadata, content) {
183
187
  }
184
188
  return { ...base, required, missing, violations };
185
189
  }
190
+ async function newDocumentDefaults(client, id, metadata) {
191
+ try {
192
+ const effective = await effectiveSchemaRef(client, id, metadata);
193
+ if (!effective.ref || effective.source === "none") return {};
194
+ const loaded = await loadSchemaRef(client, effective.ref);
195
+ return missingPropertyDefaults(metadataSchemaOf(loaded.schema, loaded.registry), metadata, loaded.registry);
196
+ } catch {
197
+ return {};
198
+ }
199
+ }
186
200
  var isPlainMap = (value) => !!value && typeof value === "object" && !Array.isArray(value) && !("/" in value);
187
201
  function blobSchemaRef(value) {
188
202
  if (!isPlainMap(value)) return null;
@@ -199,10 +213,9 @@ function withoutSchemaLink(value) {
199
213
  return rest;
200
214
  }
201
215
  async function checkSchemaDefinition(client, ref) {
202
- const meta = HM_SCHEMAS["schema"];
203
216
  try {
204
217
  const loaded = await loadSchemaRef(client, ref);
205
- return validate(meta, loaded.schema, "$", {}, loaded.registry);
218
+ return schemaErrors(loaded.schema, loaded.registry);
206
219
  } catch (error) {
207
220
  return [error.message];
208
221
  }
@@ -223,6 +236,7 @@ export {
223
236
  isFixedLiteral,
224
237
  loadSchemaRef,
225
238
  checkDocumentSchema,
239
+ newDocumentDefaults,
226
240
  isPlainMap,
227
241
  blobSchemaRef,
228
242
  withoutSchemaLink,
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  documentUpdateBlobs
3
- } from "./chunk-6QBB3P3Q.mjs";
3
+ } from "./chunk-KAZNQFXV.mjs";
4
4
  import {
5
5
  resolveDocumentState
6
6
  } from "./chunk-QS6PIRUE.mjs";