@seed-hypermedia/client 0.0.81 → 0.0.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/auto-link.d.ts +3 -4
  2. package/dist/auto-link.mjs +3 -3
  3. package/dist/block-diff.mjs +1 -1
  4. package/dist/blocks-to-markdown.d.ts +16 -11
  5. package/dist/blocks-to-markdown.mjs +2 -2
  6. package/dist/capability.mjs +2 -2
  7. package/dist/{chunk-MZENVC36.mjs → chunk-2GOQZ3DV.mjs} +1 -1
  8. package/dist/{chunk-OZKQOI2X.mjs → chunk-3KLY2B27.mjs} +51 -4
  9. package/dist/{chunk-D2LTD2KZ.mjs → chunk-4VD46ULS.mjs} +1 -1
  10. package/dist/{chunk-C42YWLL2.mjs → chunk-CRMBYTZY.mjs} +1 -1
  11. package/dist/{chunk-2OMSCQ56.mjs → chunk-E4PGX55A.mjs} +1 -1
  12. package/dist/{chunk-YH52VFVR.mjs → chunk-E6YSFT63.mjs} +304 -185
  13. package/dist/{chunk-IREIRKVP.mjs → chunk-IOXGTLKJ.mjs} +1 -1
  14. package/dist/{chunk-MZUGCZJ6.mjs → chunk-KMQYEO46.mjs} +38 -11
  15. package/dist/{chunk-LCKCG574.mjs → chunk-NVWWEHIS.mjs} +1 -1
  16. package/dist/{chunk-RCVLNXG6.mjs → chunk-QBYF2PVS.mjs} +1 -1
  17. package/dist/{chunk-55OXHA27.mjs → chunk-SIYJHDMJ.mjs} +4 -2
  18. package/dist/{chunk-WGOIXGRU.mjs → chunk-TUSTJXWH.mjs} +3 -3
  19. package/dist/{chunk-BO2QSSIU.mjs → chunk-V2UNLCDS.mjs} +1 -1
  20. package/dist/{chunk-AIQJ6BI3.mjs → chunk-WJRXPYFE.mjs} +1 -1
  21. package/dist/chunk-XB6E7EVC.mjs +872 -0
  22. package/dist/client.mjs +2 -2
  23. package/dist/comment.mjs +2 -2
  24. package/dist/document-state.mjs +2 -2
  25. package/dist/editorblock-to-hmblock.mjs +2 -2
  26. package/dist/hm-resolver.mjs +2 -2
  27. package/dist/hm-types.d.ts +216 -114
  28. package/dist/hm-types.mjs +5 -1
  29. package/dist/hmblock-to-editorblock.mjs +2 -2
  30. package/dist/index.mjs +15 -15
  31. package/dist/markdown-to-blocks.d.ts +27 -32
  32. package/dist/markdown-to-blocks.mjs +3 -1
  33. package/dist/pdf-to-blocks.mjs +3 -3
  34. package/dist/resource-read.mjs +4 -4
  35. package/dist/tei-to-blocks.mjs +2 -2
  36. package/dist/unicode.mjs +1 -1
  37. package/package.json +1 -1
  38. package/dist/chunk-H7L4TI6X.mjs +0 -705
@@ -1,168 +1,211 @@
1
1
  import {
2
+ normalizeQuerySort,
2
3
  unpackHmId
3
- } from "./chunk-MZUGCZJ6.mjs";
4
+ } from "./chunk-KMQYEO46.mjs";
4
5
 
5
6
  // src/blocks-to-markdown.ts
6
- var FM_STRING_KEYS = [
7
+ import { stringify as stringifyYaml } from "yaml";
8
+ var FM_KEY_ORDER = [
7
9
  "name",
8
10
  "summary",
9
- "displayAuthor",
10
- "displayPublishTime",
11
11
  "icon",
12
12
  "cover",
13
+ "displayAuthor",
14
+ "displayPublishTime",
15
+ "schema",
16
+ "childrenSchema",
17
+ "schemaDefinition",
13
18
  "siteUrl",
14
19
  "layout",
15
- "seedExperimentalLogo",
16
- "seedExperimentalHomeOrder",
20
+ "theme",
17
21
  "contentWidth",
18
22
  "childrenType",
23
+ "showOutline",
24
+ "showActivity",
25
+ "seedExperimentalLogo",
26
+ "seedExperimentalHomeOrder",
19
27
  "importCategories",
20
28
  "importTags"
21
29
  ];
22
- var FM_BOOLEAN_KEYS = ["showOutline", "showActivity"];
30
+ function frontmatterKeyRank(key) {
31
+ const idx = FM_KEY_ORDER.indexOf(key);
32
+ return idx === -1 ? FM_KEY_ORDER.length : idx;
33
+ }
23
34
  function emitFrontmatter(metadata) {
24
- const lines = [];
25
- for (const key of FM_STRING_KEYS) {
26
- const val = metadata[key];
27
- if (val !== void 0 && val !== "") {
28
- lines.push(`${key}: ${JSON.stringify(val)}`);
29
- }
30
- }
31
- for (const key of FM_BOOLEAN_KEYS) {
32
- const val = metadata[key];
33
- if (val !== void 0) {
34
- lines.push(`${key}: ${val}`);
35
- }
36
- }
37
- if (metadata.theme && typeof metadata.theme === "object") {
38
- const entries = [];
39
- if (metadata.theme.headerLayout !== void 0) {
40
- entries.push(` headerLayout: ${JSON.stringify(metadata.theme.headerLayout)}`);
35
+ const entries = Object.entries(metadata || {}).filter(([, v]) => v !== void 0);
36
+ if (entries.length === 0) return "---\n---\n";
37
+ const body = stringifyYaml(Object.fromEntries(entries), {
38
+ lineWidth: 0,
39
+ sortMapEntries: (a, b) => {
40
+ const ka = String(a.key);
41
+ const kb = String(b.key);
42
+ return frontmatterKeyRank(ka) - frontmatterKeyRank(kb) || ka.localeCompare(kb);
41
43
  }
42
- if (entries.length > 0) {
43
- lines.push("theme:");
44
- lines.push(...entries);
44
+ });
45
+ return "---\n" + body.replace(/\n$/, "") + "\n---\n";
46
+ }
47
+ function commentJson(value) {
48
+ return JSON.stringify(sortKeysDeep(value)).replace(/--/g, "-\\u002d");
49
+ }
50
+ function sortKeysDeep(value) {
51
+ if (Array.isArray(value)) return value.map(sortKeysDeep);
52
+ if (value && typeof value === "object") {
53
+ const out = {};
54
+ for (const k of Object.keys(value).sort()) {
55
+ const v = value[k];
56
+ if (v !== void 0) out[k] = sortKeysDeep(v);
45
57
  }
58
+ return out;
46
59
  }
47
- if (lines.length === 0) return "---\n---\n";
48
- return "---\n" + lines.join("\n") + "\n---\n";
60
+ return value;
61
+ }
62
+ function blockComment(id, type, attrs) {
63
+ let s = `<!-- id:${id}`;
64
+ if (type) s += ` type:${type}`;
65
+ if (attrs && Object.keys(attrs).length) s += ` attrs:${commentJson(attrs)}`;
66
+ return s + " -->";
49
67
  }
50
68
  function idComment(id) {
51
- return `<!-- id:${id} -->`;
69
+ return blockComment(id);
52
70
  }
53
- function appendIdToFirstLine(md, id) {
54
- const newline = md.indexOf("\n");
55
- if (newline === -1) {
56
- return md ? `${md} ${idComment(id)}` : idComment(id);
71
+ var NATIVE_TYPES = /* @__PURE__ */ new Set(["Paragraph", "Heading", "Code", "Math", "Image", "Table"]);
72
+ function isNativeAttribute(type, key, value, hasChildren) {
73
+ if (key === "childrenType") {
74
+ if (value === "Unordered" || value === "Ordered" || value === "Blockquote") return true;
75
+ if (value === "Group") return hasChildren;
76
+ return false;
57
77
  }
58
- return `${md.slice(0, newline)} ${idComment(id)}${md.slice(newline)}`;
78
+ if (type === "Code" && key === "language") return true;
79
+ return false;
59
80
  }
60
81
  function blocksToMarkdown(doc, options) {
61
82
  const opts = { ipfsGateway: true, ...options };
62
- const lines = [];
63
- lines.push(emitFrontmatter(doc.metadata || {}));
64
- for (const node of doc.content) {
65
- const blockMd = blockNodeToMarkdown(node, 0, opts);
66
- if (blockMd) {
67
- lines.push(blockMd);
83
+ const out = [emitFrontmatter(doc.metadata || {}).replace(/\n$/, "")];
84
+ renderNodes(doc.content || [], "", void 0, 0, opts, out);
85
+ return out.join("\n") + "\n";
86
+ }
87
+ var LIST_TYPES = /* @__PURE__ */ new Set(["Unordered", "Ordered", "Blockquote"]);
88
+ function markerFor(childrenType, index) {
89
+ if (childrenType === "Unordered") return "- ";
90
+ if (childrenType === "Ordered") return `${index + 1}. `;
91
+ if (childrenType === "Blockquote") return "> ";
92
+ return "";
93
+ }
94
+ function renderNodes(nodes, ind, childrenType, headingDepth, opts, out) {
95
+ const listy = LIST_TYPES.has(childrenType || "");
96
+ for (let i = 0; i < nodes.length; i++) {
97
+ const node = nodes[i];
98
+ if (i > 0 && !listy) out.push("");
99
+ const marker = markerFor(childrenType, i);
100
+ const wroteHeading = renderNode(node, ind, marker, headingDepth, opts, out);
101
+ const next = nodes[i + 1];
102
+ if (wroteHeading && next && next.block.type !== "Heading") {
103
+ out.push(ind + `<!-- end:${node.block.id} -->`);
68
104
  }
69
105
  }
70
- return lines.join("\n");
71
106
  }
72
- function blockNodeToMarkdown(node, depth, opts) {
73
- var _a;
107
+ function renderNode(node, ind, marker, headingDepth, opts, out) {
74
108
  const block = node.block;
75
109
  const children = node.children || [];
76
- if (block.type === "Table") {
77
- return tableToMarkdown(node, depth, (text, annotations) => applyAnnotations(text, annotations));
78
- }
79
- const childrenType = (_a = block.attributes) == null ? void 0 : _a.childrenType;
80
- const isListContainer = (block.type === "Paragraph" || block.type === "Slot") && !block.text && (childrenType === "Ordered" || childrenType === "Unordered" || childrenType === "Blockquote");
81
- let result;
82
- if (isListContainer) {
83
- result = idComment(block.id);
84
- } else {
85
- result = blockToMarkdown(block, depth, opts);
86
- }
87
- for (const child of children) {
88
- const childMd = blockNodeToMarkdown(child, depth + 1, opts);
89
- if (childMd) {
90
- if (childrenType === "Ordered") {
91
- result += "\n" + indent(depth + 1) + "1. " + childMd.trim();
92
- } else if (childrenType === "Unordered") {
93
- result += "\n" + indent(depth + 1) + "- " + childMd.trim();
94
- } else if (childrenType === "Blockquote") {
95
- result += "\n" + indent(depth + 1) + "> " + childMd.trim();
110
+ const type = block.type;
111
+ const text = block.text || "";
112
+ const link = block.link || "";
113
+ const attributes = block.attributes || {};
114
+ const childrenType = attributes.childrenType;
115
+ if (type === "Table") {
116
+ const extra2 = extraAttributes(type, attributes, false);
117
+ const contentInd2 = ind + " ".repeat(marker.length);
118
+ const table = tableToMarkdown(node, contentInd2, (t, a) => renderInline(t, a, { atLineStart: false }));
119
+ out.push(ind + marker + blockComment(block.id, table ? void 0 : "Table", extra2));
120
+ if (table) out.push(...table.split("\n"));
121
+ return false;
122
+ }
123
+ const extra = extraAttributes(type, attributes, children.length > 0);
124
+ const comment = blockComment(block.id, NATIVE_TYPES.has(type) ? void 0 : type, extra);
125
+ const contentInd = ind + " ".repeat(marker.length);
126
+ let wroteHeading = false;
127
+ let childInd = marker ? contentInd : ind + " ";
128
+ let childHeadingDepth = 0;
129
+ let shorthand = false;
130
+ switch (type) {
131
+ case "Paragraph": {
132
+ if (!text && children.length && LIST_TYPES.has(childrenType || "") && !marker) {
133
+ out.push(ind + comment);
134
+ shorthand = true;
135
+ childInd = ind;
136
+ } else if (!text) {
137
+ out.push(ind + marker + comment);
96
138
  } else {
97
- result += "\n\n" + childMd;
139
+ out.push(ind + marker + renderInline(text, block.annotations, { atLineStart: true }) + " " + comment);
98
140
  }
99
- }
100
- }
101
- return result;
102
- }
103
- function blockToMarkdown(block, depth, opts) {
104
- var _a, _b;
105
- const ind = indent(depth);
106
- const b = block;
107
- const text = b.text || "";
108
- const link = b.link || "";
109
- const annotations = b.annotations;
110
- const id = b.id;
111
- switch (block.type) {
112
- case "Paragraph": {
113
- const rendered = ind + applyAnnotations(text, annotations);
114
- return appendIdToFirstLine(rendered, id);
141
+ break;
115
142
  }
116
143
  case "Heading": {
117
- const level = Math.min(depth + 1, 6);
118
- const hashes = "#".repeat(level);
119
- const rendered = `${hashes} ${applyAnnotations(text, annotations)}`;
120
- return appendIdToFirstLine(rendered, id);
144
+ const level = Math.min(headingDepth + 1, 6);
145
+ out.push(
146
+ ind + marker + "#".repeat(level) + " " + renderInline(text, block.annotations, { atLineStart: false }) + " " + comment
147
+ );
148
+ if (level < 6) {
149
+ wroteHeading = !marker;
150
+ childInd = contentInd;
151
+ childHeadingDepth = headingDepth + 1;
152
+ } else {
153
+ childInd = contentInd + " ";
154
+ }
155
+ if (children.length) out.push("");
156
+ break;
121
157
  }
122
158
  case "Code": {
123
- const lang = ((_a = b.attributes) == null ? void 0 : _a.language) || "";
124
- return ind + "```" + lang + " " + idComment(id) + "\n" + ind + text + "\n" + ind + "```";
159
+ const lang = attributes.language || "";
160
+ let fenceLen = 3;
161
+ for (const m of Array.from(text.matchAll(/`+/g))) fenceLen = Math.max(fenceLen, m[0].length + 1);
162
+ const fence = "`".repeat(fenceLen);
163
+ out.push(ind + marker + fence + lang + " " + comment);
164
+ for (const line of text.split("\n")) out.push(line ? contentInd + line : "");
165
+ out.push(contentInd + fence);
166
+ break;
125
167
  }
126
168
  case "Math": {
127
- return ind + "$$ " + idComment(id) + "\n" + ind + text + "\n" + ind + "$$";
169
+ out.push(ind + marker + "$$ " + comment);
170
+ for (const line of text.split("\n")) out.push(line ? contentInd + line : "");
171
+ out.push(contentInd + "$$");
172
+ break;
128
173
  }
129
174
  case "Image": {
130
- const altText = text || "image";
131
- const imgUrl = formatMediaUrl(link, opts.ipfsGateway);
132
- return ind + `![${altText}](${imgUrl}) ${idComment(id)}`;
133
- }
134
- case "Video": {
135
- const videoUrl = formatMediaUrl(link, opts.ipfsGateway);
136
- return ind + `[Video](${videoUrl}) ${idComment(id)}`;
137
- }
138
- case "File": {
139
- const fileName = ((_b = b.attributes) == null ? void 0 : _b.name) || "file";
140
- const fileUrl = formatMediaUrl(link, opts.ipfsGateway);
141
- return ind + `[${fileName}](${fileUrl}) ${idComment(id)}`;
142
- }
143
- case "Embed": {
144
- return ind + `> [Embed: ${link}](${link}) ${idComment(id)}`;
145
- }
146
- case "WebEmbed": {
147
- return ind + `[Web Embed](${link}) ${idComment(id)}`;
148
- }
149
- case "Button": {
150
- const buttonText = text || "Button";
151
- return ind + `[${buttonText}](${link}) ${idComment(id)}`;
152
- }
153
- case "Query": {
154
- return ind + `<!-- Query block --> ${idComment(id)}`;
155
- }
156
- case "Nostr": {
157
- return ind + `[Nostr: ${link}](${link}) ${idComment(id)}`;
175
+ const alt = renderInline(text, block.annotations, { atLineStart: false });
176
+ out.push(ind + marker + `![${alt}](${renderUrl(formatMediaUrl(link, opts.ipfsGateway))}) ` + comment);
177
+ break;
158
178
  }
159
179
  default: {
160
- if (text) {
161
- return appendIdToFirstLine(ind + text, id);
180
+ const url = renderUrl(formatMediaUrl(link, opts.ipfsGateway));
181
+ let visible = "";
182
+ if (text && link) visible = `[${renderInline(text, block.annotations, { atLineStart: false })}](${url})`;
183
+ else if (link) visible = `<${formatMediaUrl(link, opts.ipfsGateway)}>`;
184
+ else if (text) visible = renderInline(text, block.annotations, { atLineStart: true });
185
+ out.push(ind + marker + (visible ? visible + " " : "") + comment);
186
+ if (!visible && children.length && LIST_TYPES.has(childrenType || "") && !marker) {
187
+ shorthand = true;
188
+ childInd = ind;
162
189
  }
163
- return "";
164
190
  }
165
191
  }
192
+ if (children.length) {
193
+ if (!shorthand && type !== "Heading" && !LIST_TYPES.has(childrenType || "")) out.push("");
194
+ renderNodes(children, childInd, childrenType, childHeadingDepth, opts, out);
195
+ }
196
+ return wroteHeading;
197
+ }
198
+ function extraAttributes(type, attributes, hasChildren) {
199
+ const extra = {};
200
+ for (const [key, value] of Object.entries(attributes)) {
201
+ if (value === void 0 || value === null) continue;
202
+ if (isNativeAttribute(type, key, value, hasChildren)) continue;
203
+ extra[key] = value;
204
+ }
205
+ return extra;
206
+ }
207
+ function renderUrl(url) {
208
+ return /[\s()<>]/.test(url) ? `<${url}>` : url;
166
209
  }
167
210
  function normalizeTableNode(node) {
168
211
  var _a, _b;
@@ -171,7 +214,8 @@ function normalizeTableNode(node) {
171
214
  for (const child of node.children || []) {
172
215
  const block = child.block;
173
216
  if ((block == null ? void 0 : block.type) === "TableColumn") {
174
- columns.push({ id: block.id });
217
+ const attributes = extraAttributes("TableColumn", block.attributes || {}, false);
218
+ columns.push(Object.keys(attributes).length ? { id: block.id, attributes } : { id: block.id });
175
219
  } else if ((block == null ? void 0 : block.type) === "TableRow") {
176
220
  const cells = /* @__PURE__ */ new Map();
177
221
  for (const cellNode of child.children || []) {
@@ -194,12 +238,12 @@ function normalizeTableNode(node) {
194
238
  function escapeCellText(s) {
195
239
  return s.replace(/\|/g, "\\|").replace(/\n/g, "<br>");
196
240
  }
197
- function assembleTableMarkdown(tableId, columns, header, bodyRows, ind) {
241
+ function assembleTableMarkdown(columns, header, bodyRows, ind) {
198
242
  const lines = [];
199
- lines.push(ind + idComment(tableId));
200
243
  const headerCells = columns.map((col, idx) => {
201
244
  const text = header.cellTexts[idx] || "";
202
- return (text ? text + " " : "") + `<!-- col:${col.id} -->`;
245
+ const attrs = col.attributes && Object.keys(col.attributes).length ? ` attrs:${commentJson(col.attributes)}` : "";
246
+ return (text ? text + " " : "") + `<!-- col:${col.id}${attrs} -->`;
203
247
  });
204
248
  if (header.rowId) {
205
249
  headerCells[headerCells.length - 1] += " " + idComment(header.rowId);
@@ -214,7 +258,7 @@ function assembleTableMarkdown(tableId, columns, header, bodyRows, ind) {
214
258
  }
215
259
  return lines.join("\n");
216
260
  }
217
- function tableToMarkdown(node, depth, renderCell) {
261
+ function tableToMarkdown(node, ind, renderCell) {
218
262
  var _a;
219
263
  const { columns, rows } = normalizeTableNode(node);
220
264
  if (columns.length === 0) return "";
@@ -227,13 +271,7 @@ function tableToMarkdown(node, depth, renderCell) {
227
271
  rowId: row.id,
228
272
  cellTexts: renderRowCells(row)
229
273
  }));
230
- return assembleTableMarkdown(
231
- node.block.id,
232
- columns,
233
- { rowId: headerRow == null ? void 0 : headerRow.id, cellTexts: renderRowCells(headerRow) },
234
- bodyRows,
235
- indent(depth)
236
- );
274
+ return assembleTableMarkdown(columns, { rowId: headerRow == null ? void 0 : headerRow.id, cellTexts: renderRowCells(headerRow) }, bodyRows, ind);
237
275
  }
238
276
  async function tableToResolvedMarkdown(node, depth, renderCell) {
239
277
  var _a;
@@ -252,68 +290,152 @@ async function tableToResolvedMarkdown(node, depth, renderCell) {
252
290
  cellTexts: await renderRowCells(row)
253
291
  }))
254
292
  );
255
- return assembleTableMarkdown(
256
- node.block.id,
293
+ return resolvedIndent(depth) + resolvedIdComment(node.block.id) + "\n" + assembleTableMarkdown(
257
294
  columns,
258
295
  { rowId: headerRow == null ? void 0 : headerRow.id, cellTexts: await renderRowCells(headerRow) },
259
296
  bodyRows,
260
- indent(depth)
297
+ resolvedIndent(depth)
261
298
  );
262
299
  }
263
- function applyAnnotations(text, annotations) {
264
- if (!annotations || annotations.length === 0) {
265
- return text;
266
- }
267
- const markers = [];
268
- for (const ann of annotations) {
269
- const starts = ann.starts || [];
270
- const ends = ann.ends || [];
300
+ var SPAN_STYLE = {
301
+ TextColor: "color",
302
+ BackgroundColor: "background-color",
303
+ TextSize: "font-size",
304
+ TextFamily: "font-family"
305
+ };
306
+ function encodeHtmlAttr(s) {
307
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
308
+ }
309
+ function escapeInline(s, atLineStart) {
310
+ let out = s.replace(/[\\`*_~\[\]<]/g, (c) => "\\" + c).replace(/\n/g, "<br>");
311
+ if (atLineStart) {
312
+ out = out.replace(/^(#|[-+>|$]|\d+[.)])/, (m) => m.length === 1 ? "\\" + m : m.slice(0, -1) + "\\" + m.slice(-1));
313
+ if (/^\s/.test(out)) out = "\\" + out;
314
+ }
315
+ return out;
316
+ }
317
+ function escapeTrailingWhitespace(s) {
318
+ return /\s$/.test(s) ? s.slice(0, -1) + "\\" + s.slice(-1) : s;
319
+ }
320
+ function spansFromAnnotations(text, annotations) {
321
+ const spans = [];
322
+ for (const ann of annotations || []) {
323
+ const a = ann;
324
+ const starts = a.starts || [];
325
+ const ends = a.ends || [];
326
+ const link = a.link || void 0;
327
+ const attributes = a.attributes && Object.keys(a.attributes).length ? a.attributes : void 0;
328
+ const key = a.type + " " + (link ?? "") + " " + (attributes ? commentJson(attributes) : "");
271
329
  for (let i = 0; i < starts.length; i++) {
272
- markers.push({ pos: starts[i], type: "open", annotation: ann });
273
- if (ends[i] !== void 0) {
274
- markers.push({ pos: ends[i], type: "close", annotation: ann });
275
- }
330
+ const start = Math.max(0, starts[i]);
331
+ const end = Math.min(text.length, ends[i] ?? -1);
332
+ if (end <= start) continue;
333
+ spans.push({ start, end, type: a.type, link, attributes, key });
276
334
  }
277
335
  }
278
- markers.sort((a, b) => {
279
- if (a.pos !== b.pos) return a.pos - b.pos;
280
- return a.type === "open" ? -1 : 1;
281
- });
282
- let result = "";
283
- let lastPos = 0;
284
- for (const marker of markers) {
285
- result += text.slice(lastPos, marker.pos);
286
- lastPos = marker.pos;
287
- result += getAnnotationMarker(marker.annotation, marker.type);
336
+ spans.sort((x, y) => x.key.localeCompare(y.key) || x.start - y.start || x.end - y.end);
337
+ const merged = [];
338
+ for (const s of spans) {
339
+ const last = merged[merged.length - 1];
340
+ if (last && last.key === s.key && s.start <= last.end) last.end = Math.max(last.end, s.end);
341
+ else merged.push({ ...s });
342
+ }
343
+ return merged;
344
+ }
345
+ function spanPriority(s) {
346
+ if (s.type === "Embed") return 2;
347
+ if (s.type === "Code") return 1;
348
+ return 0;
349
+ }
350
+ function renderInline(text, annotations, options) {
351
+ const spans = spansFromAnnotations(text, annotations);
352
+ if (spans.length === 0) return escapeTrailingWhitespace(escapeInline(text, options.atLineStart));
353
+ const boundaries = /* @__PURE__ */ new Set([0, text.length]);
354
+ for (const s of spans) {
355
+ boundaries.add(s.start);
356
+ boundaries.add(s.end);
357
+ }
358
+ const points = Array.from(boundaries).sort((a, b) => a - b);
359
+ const stack = [];
360
+ let out = "";
361
+ for (let p = 0; p < points.length - 1; p++) {
362
+ const pos = points[p];
363
+ const next = points[p + 1];
364
+ const active = spans.filter((s) => s.start <= pos && s.end >= next);
365
+ const survivors = [];
366
+ let firstInactive = stack.findIndex((o) => !active.includes(o.span));
367
+ if (firstInactive === -1) firstInactive = stack.length;
368
+ while (stack.length > firstInactive) {
369
+ const top2 = stack.pop();
370
+ out += top2.close;
371
+ if (active.includes(top2.span)) survivors.unshift(top2.span);
372
+ }
373
+ const opening = [...survivors, ...active.filter((s) => !stack.some((o) => o.span === s) && !survivors.includes(s))];
374
+ opening.sort(
375
+ (a, b) => spanPriority(a) - spanPriority(b) || b.end - a.end || a.start - b.start || a.type.localeCompare(b.type)
376
+ );
377
+ const inner = stack.filter((o) => spanPriority(o.span) > 0);
378
+ if (opening.length && inner.length) {
379
+ for (const o of inner.reverse()) {
380
+ out += o.close;
381
+ stack.splice(stack.indexOf(o), 1);
382
+ opening.push(o.span);
383
+ }
384
+ opening.sort(
385
+ (a, b) => spanPriority(a) - spanPriority(b) || b.end - a.end || a.start - b.start || a.type.localeCompare(b.type)
386
+ );
387
+ }
388
+ for (const s of opening) {
389
+ const chunk2 = text.slice(pos, next);
390
+ const [open, close] = markersFor(s, chunk2, text);
391
+ out += open;
392
+ stack.push({ span: s, close });
393
+ }
394
+ const top = stack[stack.length - 1];
395
+ const chunk = text.slice(pos, next);
396
+ if ((top == null ? void 0 : top.span.type) === "Embed") {
397
+ } else if ((top == null ? void 0 : top.span.type) === "Code") {
398
+ out += chunk.replace(/\n/g, "<br>");
399
+ } else {
400
+ out += escapeInline(chunk, options.atLineStart && out === "");
401
+ }
288
402
  }
289
- result += text.slice(lastPos);
290
- result = result.replace(/\uFFFC/g, "");
291
- return result;
403
+ while (stack.length) out += stack.pop().close;
404
+ return escapeTrailingWhitespace(out);
292
405
  }
293
- function getAnnotationMarker(ann, type) {
294
- switch (ann.type) {
406
+ function markersFor(s, chunk, fullText) {
407
+ var _a;
408
+ switch (s.type) {
295
409
  case "Bold":
296
- return "**";
410
+ return ["**", "**"];
297
411
  case "Italic":
298
- return "_";
412
+ return ["_", "_"];
299
413
  case "Strike":
300
- return "~~";
301
- case "Code":
302
- return "`";
414
+ return ["~~", "~~"];
303
415
  case "Underline":
304
- return type === "open" ? "<u>" : "</u>";
416
+ return ["<u>", "</u>"];
417
+ case "Range":
418
+ return ["<mark>", "</mark>"];
305
419
  case "Link":
306
- if (type === "open") {
307
- return "[";
308
- } else {
309
- return `](${ann.link || ""})`;
420
+ return ["[", `](${renderUrl(s.link || "")})`];
421
+ case "Embed":
422
+ return [`<${s.link || ""}>`, ""];
423
+ case "Code": {
424
+ let fenceLen = 1;
425
+ for (const m of Array.from(fullText.slice(s.start, s.end).matchAll(/`+/g)))
426
+ fenceLen = Math.max(fenceLen, m[0].length + 1);
427
+ const fence = "`".repeat(fenceLen);
428
+ const pad = /^[` ]|[` ]$/.test(chunk) ? " " : "";
429
+ return [fence + pad, pad + fence];
430
+ }
431
+ default: {
432
+ const prop = SPAN_STYLE[s.type];
433
+ if (prop) {
434
+ const value = String(((_a = s.attributes) == null ? void 0 : _a.value) ?? "");
435
+ return [`<span style="${prop}:${encodeHtmlAttr(value)}">`, "</span>"];
310
436
  }
311
- case "Embed": {
312
- const link = "link" in ann ? ann.link || "" : "";
313
- return type === "open" ? `<${link}` : ">";
437
+ return ["", ""];
314
438
  }
315
- default:
316
- return "";
317
439
  }
318
440
  }
319
441
  function formatMediaUrl(url, useGateway) {
@@ -323,9 +445,6 @@ function formatMediaUrl(url, useGateway) {
323
445
  }
324
446
  return url;
325
447
  }
326
- function indent(depth) {
327
- return " ".repeat(depth);
328
- }
329
448
  function slugify(title) {
330
449
  return title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
331
450
  }
@@ -471,7 +590,7 @@ async function resolveBlockEmbed(block, depth, ctx) {
471
590
  }
472
591
  }
473
592
  async function resolveQuery(block, depth, ctx) {
474
- var _a, _b;
593
+ var _a;
475
594
  const ind = resolvedIndent(depth);
476
595
  try {
477
596
  const attrs = block.attributes;
@@ -485,7 +604,7 @@ async function resolveQuery(block, depth, ctx) {
485
604
  path: inc.path,
486
605
  mode: inc.mode || "Children"
487
606
  }));
488
- sort = (_a = queryConfig.sort) == null ? void 0 : _a.map((s) => ({ term: s.term, reverse: s.reverse ?? false }));
607
+ sort = normalizeQuerySort(queryConfig.sort);
489
608
  limit = queryConfig.limit;
490
609
  } else {
491
610
  const space = (attrs == null ? void 0 : attrs.space) || "";
@@ -501,13 +620,13 @@ async function resolveQuery(block, depth, ctx) {
501
620
  }
502
621
  const results = await ctx.client.request("Query", {
503
622
  includes,
504
- sort: sort || [{ term: "UpdateTime", reverse: true }],
623
+ sort: (sort == null ? void 0 : sort.length) ? sort : [{ term: "updated", reverse: true }],
505
624
  limit: limit || 10
506
625
  });
507
- if (!((_b = results == null ? void 0 : results.results) == null ? void 0 : _b.length)) return ind + "<!-- Query: no results -->";
626
+ if (!((_a = results == null ? void 0 : results.results) == null ? void 0 : _a.length)) return ind + "<!-- Query: no results -->";
508
627
  return results.results.map((doc) => {
509
- var _a2, _b2;
510
- const name = ((_a2 = doc.metadata) == null ? void 0 : _a2.name) || ((_b2 = doc.id.path) == null ? void 0 : _b2.join("/")) || doc.id.uid;
628
+ var _a2, _b;
629
+ const name = ((_a2 = doc.metadata) == null ? void 0 : _a2.name) || ((_b = doc.id.path) == null ? void 0 : _b.join("/")) || doc.id.uid;
511
630
  return ind + `- [${name}](${doc.id.id})`;
512
631
  }).join("\n");
513
632
  } catch (error) {
@@ -9,7 +9,7 @@ import {
9
9
  import {
10
10
  hmIdPathToEntityQueryPath,
11
11
  packHmId
12
- } from "./chunk-MZUGCZJ6.mjs";
12
+ } from "./chunk-KMQYEO46.mjs";
13
13
 
14
14
  // src/comment.ts
15
15
  import { decode as cborDecode, encode as cborEncode } from "@ipld/dag-cbor";