@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.
@@ -87,6 +87,15 @@ function blocksToMarkdown(doc, options) {
87
87
  renderNodes(doc.content || [], "", void 0, 0, opts, out);
88
88
  return out.join("\n") + "\n";
89
89
  }
90
+ function resolvedLabel(label) {
91
+ return label.replace(/\s+/g, " ").replace(/-{2,}/g, "-").replace(/>/g, "").trim();
92
+ }
93
+ function pushResolved(shown, ind, out) {
94
+ const label = resolvedLabel(shown.label);
95
+ out.push(ind + `<!-- resolved${label ? `: ${label}` : ""} -->`);
96
+ for (const line of shown.lines) out.push(line ? ind + line : "");
97
+ out.push(ind + "<!-- /resolved -->");
98
+ }
90
99
  var LIST_TYPES = /* @__PURE__ */ new Set(["Unordered", "Ordered", "Blockquote"]);
91
100
  function markerFor(childrenType, index) {
92
101
  if (childrenType === "Unordered") return "- ";
@@ -108,6 +117,7 @@ function renderNodes(nodes, ind, childrenType, headingDepth, opts, out) {
108
117
  }
109
118
  }
110
119
  function renderNode(node, ind, marker, headingDepth, opts, out) {
120
+ var _a;
111
121
  const block = node.block;
112
122
  const children = node.children || [];
113
123
  const type = block.type;
@@ -118,7 +128,11 @@ function renderNode(node, ind, marker, headingDepth, opts, out) {
118
128
  if (type === "Table") {
119
129
  const extra2 = extraAttributes(type, attributes, false);
120
130
  const contentInd2 = ind + " ".repeat(marker.length);
121
- const table = tableToMarkdown(node, contentInd2, (t, a) => renderInline(t, a, { atLineStart: false }));
131
+ const table = tableToMarkdown(
132
+ node,
133
+ contentInd2,
134
+ (t, a) => renderInline(t, a, { atLineStart: false, leadingSpace: true, mentionLabel: opts.mentionLabel })
135
+ );
122
136
  out.push(ind + marker + blockComment(block.id, table ? void 0 : "Table", extra2));
123
137
  if (table) out.push(...table.split("\n"));
124
138
  return false;
@@ -139,14 +153,20 @@ function renderNode(node, ind, marker, headingDepth, opts, out) {
139
153
  } else if (!text) {
140
154
  out.push(ind + marker + comment);
141
155
  } else {
142
- out.push(ind + marker + renderInline(text, block.annotations, { atLineStart: true }) + " " + comment);
156
+ out.push(
157
+ ind + marker + renderInline(text, block.annotations, { atLineStart: true, mentionLabel: opts.mentionLabel }) + " " + comment
158
+ );
143
159
  }
144
160
  break;
145
161
  }
146
162
  case "Heading": {
147
163
  const level = Math.min(headingDepth + 1, 6);
148
164
  out.push(
149
- ind + marker + "#".repeat(level) + " " + renderInline(text, block.annotations, { atLineStart: false }) + " " + comment
165
+ ind + marker + "#".repeat(level) + " " + renderInline(text, block.annotations, {
166
+ atLineStart: false,
167
+ leadingSpace: true,
168
+ mentionLabel: opts.mentionLabel
169
+ }) + " " + comment
150
170
  );
151
171
  if (level < 6) {
152
172
  wroteHeading = !marker;
@@ -175,16 +195,21 @@ function renderNode(node, ind, marker, headingDepth, opts, out) {
175
195
  break;
176
196
  }
177
197
  case "Image": {
178
- const alt = renderInline(text, block.annotations, { atLineStart: false });
198
+ const alt = renderInline(text, block.annotations, { atLineStart: false, mentionLabel: opts.mentionLabel });
179
199
  out.push(ind + marker + `![${alt}](${renderUrl(formatMediaUrl(link, opts.ipfsGateway))}) ` + comment);
180
200
  break;
181
201
  }
182
202
  default: {
183
203
  const url = renderUrl(formatMediaUrl(link, opts.ipfsGateway));
184
204
  let visible = "";
185
- if (text && link) visible = `[${renderInline(text, block.annotations, { atLineStart: false })}](${url})`;
205
+ if (text && link)
206
+ visible = `[${renderInline(text, block.annotations, {
207
+ atLineStart: false,
208
+ mentionLabel: opts.mentionLabel
209
+ })}](${url})`;
186
210
  else if (link) visible = `<${formatMediaUrl(link, opts.ipfsGateway)}>`;
187
- else if (text) visible = renderInline(text, block.annotations, { atLineStart: true });
211
+ else if (text)
212
+ visible = renderInline(text, block.annotations, { atLineStart: true, mentionLabel: opts.mentionLabel });
188
213
  out.push(ind + marker + (visible ? visible + " " : "") + comment);
189
214
  if (!visible && children.length && LIST_TYPES.has(childrenType || "") && !marker) {
190
215
  shorthand = true;
@@ -192,6 +217,8 @@ function renderNode(node, ind, marker, headingDepth, opts, out) {
192
217
  }
193
218
  }
194
219
  }
220
+ const shown = (_a = opts.resolved) == null ? void 0 : _a.call(opts, block.id);
221
+ if (shown) pushResolved(shown, contentInd, out);
195
222
  if (children.length) {
196
223
  if (!shorthand && type !== "Heading" && !LIST_TYPES.has(childrenType || "")) out.push("");
197
224
  renderNodes(children, childInd, childrenType, childHeadingDepth, opts, out);
@@ -276,29 +303,8 @@ function tableToMarkdown(node, ind, renderCell) {
276
303
  }));
277
304
  return assembleTableMarkdown(columns, { rowId: headerRow == null ? void 0 : headerRow.id, cellTexts: renderRowCells(headerRow) }, bodyRows, ind);
278
305
  }
279
- async function tableToResolvedMarkdown(node, depth, renderCell) {
280
- var _a;
281
- const { columns, rows } = normalizeTableNode(node);
282
- if (columns.length === 0) return "";
283
- const renderRowCells = (row) => Promise.all(
284
- columns.map(async (col) => {
285
- const cell = row == null ? void 0 : row.cells.get(col.id);
286
- return cell ? escapeCellText(await renderCell(cell.text, cell.annotations)) : "";
287
- })
288
- );
289
- const headerRow = ((_a = rows[0]) == null ? void 0 : _a.isHeader) ? rows[0] : void 0;
290
- const bodyRows = await Promise.all(
291
- (headerRow ? rows.slice(1) : rows).map(async (row) => ({
292
- rowId: row.id,
293
- cellTexts: await renderRowCells(row)
294
- }))
295
- );
296
- return resolvedIndent(depth) + resolvedIdComment(node.block.id) + "\n" + assembleTableMarkdown(
297
- columns,
298
- { rowId: headerRow == null ? void 0 : headerRow.id, cellTexts: await renderRowCells(headerRow) },
299
- bodyRows,
300
- resolvedIndent(depth)
301
- );
306
+ function keepLeadingSpace(out, options) {
307
+ return options.leadingSpace && /^\s/.test(out) ? "\\" + out : out;
302
308
  }
303
309
  var SPAN_STYLE = {
304
310
  TextColor: "color",
@@ -352,7 +358,8 @@ function spanPriority(s) {
352
358
  }
353
359
  function renderInline(text, annotations, options) {
354
360
  const spans = spansFromAnnotations(text, annotations);
355
- if (spans.length === 0) return escapeTrailingWhitespace(escapeInline(text, options.atLineStart));
361
+ if (spans.length === 0)
362
+ return keepLeadingSpace(escapeTrailingWhitespace(escapeInline(text, options.atLineStart)), options);
356
363
  const boundaries = /* @__PURE__ */ new Set([0, text.length]);
357
364
  for (const s of spans) {
358
365
  boundaries.add(s.start);
@@ -390,7 +397,7 @@ function renderInline(text, annotations, options) {
390
397
  }
391
398
  for (const s of opening) {
392
399
  const chunk2 = text.slice(pos, next);
393
- const [open, close] = markersFor(s, chunk2, text);
400
+ const [open, close] = markersFor(s, chunk2, text, options);
394
401
  out += open;
395
402
  stack.push({ span: s, close });
396
403
  }
@@ -404,10 +411,10 @@ function renderInline(text, annotations, options) {
404
411
  }
405
412
  }
406
413
  while (stack.length) out += stack.pop().close;
407
- return escapeTrailingWhitespace(out);
414
+ return keepLeadingSpace(escapeTrailingWhitespace(out), options);
408
415
  }
409
- function markersFor(s, chunk, fullText) {
410
- var _a;
416
+ function markersFor(s, chunk, fullText, options) {
417
+ var _a, _b;
411
418
  switch (s.type) {
412
419
  case "Bold":
413
420
  return ["**", "**"];
@@ -421,8 +428,14 @@ function markersFor(s, chunk, fullText) {
421
428
  return ["<mark>", "</mark>"];
422
429
  case "Link":
423
430
  return ["[", `](${renderUrl(s.link || "")})`];
424
- case "Embed":
425
- return [`<${s.link || ""}>`, ""];
431
+ case "Embed": {
432
+ const link = s.link || "";
433
+ if (options.mentionLabel && link.startsWith("hm://") && !/[\s()<>]/.test(link)) {
434
+ const name = options.mentionLabel(link, (_a = s.attributes) == null ? void 0 : _a.mentionKind).replace(/^@/, "");
435
+ return [`[@${escapeInline(name, false)}](${link})`, ""];
436
+ }
437
+ return [`<${link}>`, ""];
438
+ }
426
439
  case "Code": {
427
440
  let fenceLen = 1;
428
441
  for (const m of Array.from(fullText.slice(s.start, s.end).matchAll(/`+/g)))
@@ -434,7 +447,7 @@ function markersFor(s, chunk, fullText) {
434
447
  default: {
435
448
  const prop = SPAN_STYLE[s.type];
436
449
  if (prop) {
437
- const value = String(((_a = s.attributes) == null ? void 0 : _a.value) ?? "");
450
+ const value = String(((_b = s.attributes) == null ? void 0 : _b.value) ?? "");
438
451
  return [`<span style="${prop}:${encodeHtmlAttr(value)}">`, "</span>"];
439
452
  }
440
453
  return ["", ""];
@@ -465,159 +478,122 @@ function parseDraftFilename(filename) {
465
478
  }
466
479
  return { id: base, ext };
467
480
  }
468
- async function documentToResolvedMarkdown(doc, options) {
469
- const ctx = {
481
+ var MAX_RESOLVE_REQUESTS = 8;
482
+ function requestLimiter(max) {
483
+ let active = 0;
484
+ const waiting = [];
485
+ return async (task) => {
486
+ var _a;
487
+ if (active >= max) await new Promise((resolve) => waiting.push(resolve));
488
+ active++;
489
+ try {
490
+ return await task();
491
+ } finally {
492
+ active--;
493
+ (_a = waiting.shift()) == null ? void 0 : _a();
494
+ }
495
+ };
496
+ }
497
+ function resolveContext(options) {
498
+ return {
470
499
  client: options.client,
471
500
  maxDepth: options.maxDepth ?? 2,
472
501
  currentDepth: 0,
473
- cache: /* @__PURE__ */ new Map()
502
+ ipfsGateway: options.ipfsGateway ?? true,
503
+ cache: /* @__PURE__ */ new Map(),
504
+ limit: requestLimiter(MAX_RESOLVE_REQUESTS)
474
505
  };
475
- return documentToResolvedMarkdownWithContext(doc, ctx);
506
+ }
507
+ async function documentToResolvedMarkdown(doc, options) {
508
+ const out = [emitFrontmatter(doc.metadata || {}).replace(/\n$/, "")];
509
+ out.push(...await resolvedLines(doc.content || [], resolveContext(options), soleQueryHome(doc)));
510
+ return out.join("\n") + "\n";
476
511
  }
477
512
  async function commentToResolvedMarkdown(comment, options) {
478
513
  return contentToResolvedMarkdown(comment.content || [], options);
479
514
  }
480
515
  async function contentToResolvedMarkdown(content, options) {
481
- const ctx = {
482
- client: options.client,
483
- maxDepth: options.maxDepth ?? 2,
484
- currentDepth: 0,
485
- cache: /* @__PURE__ */ new Map()
486
- };
487
- return blockNodesToResolvedMarkdown(content, ctx);
516
+ return (await resolvedLines(content, resolveContext(options))).join("\n");
488
517
  }
489
- async function documentToResolvedMarkdownWithContext(doc, ctx) {
490
- const lines = [emitFrontmatter(doc.metadata || {})];
491
- const body = await blockNodesToResolvedMarkdown(resolvedDocumentContent(doc), ctx);
492
- if (body) lines.push(body);
493
- return lines.join("\n");
494
- }
495
- function resolvedDocumentContent(doc) {
518
+ function soleQueryHome(doc) {
496
519
  var _a, _b;
497
520
  const content = doc.content || [];
498
521
  const root = content[0];
499
- if (!doc.account || content.length !== 1 || (root == null ? void 0 : root.block.type) !== "Query") return content;
522
+ if (!doc.account || content.length !== 1 || (root == null ? void 0 : root.block.type) !== "Query") return void 0;
500
523
  const query = (_a = root.block.attributes) == null ? void 0 : _a.query;
501
524
  const include = (_b = query == null ? void 0 : query.includes) == null ? void 0 : _b[0];
502
- if ((query == null ? void 0 : query.includes.length) !== 1 || !include || include.space || include.path) return content;
503
- return [
504
- {
505
- ...root,
506
- block: {
507
- ...root.block,
508
- attributes: {
509
- ...root.block.attributes,
510
- query: { ...query, includes: [{ ...include, space: doc.account, path: doc.path }] }
511
- }
525
+ if ((query == null ? void 0 : query.includes.length) !== 1 || !include || include.space || include.path) return void 0;
526
+ return { space: doc.account, path: doc.path };
527
+ }
528
+ async function resolvedLines(nodes, ctx, home) {
529
+ const names = /* @__PURE__ */ new Map();
530
+ const shown = /* @__PURE__ */ new Map();
531
+ const tasks = [];
532
+ const show = (id, lines) => tasks.push(
533
+ lines.then((result) => {
534
+ if (result) shown.set(id, result);
535
+ })
536
+ );
537
+ const visit = (list) => {
538
+ var _a;
539
+ for (const node of list) {
540
+ const block = node.block;
541
+ for (const ann of block.annotations || []) {
542
+ if (ann.type !== "Embed" || !ann.link) continue;
543
+ const link = ann.link;
544
+ const kind = (_a = ann.attributes) == null ? void 0 : _a.mentionKind;
545
+ const key = `${kind} ${link}`;
546
+ if (names.has(key)) continue;
547
+ names.set(key, fallbackLabel(link));
548
+ tasks.push(
549
+ resolveReference(link, ctx, kind).then(
550
+ (resolved) => {
551
+ names.set(key, resolved.label);
552
+ },
553
+ () => {
554
+ }
555
+ )
556
+ );
512
557
  }
558
+ if (block.type === "Embed") show(block.id, embedLines(block, ctx));
559
+ else if (block.type === "Query") show(block.id, queryLines(block, ctx, home));
560
+ visit(node.children || []);
513
561
  }
514
- ];
515
- }
516
- async function blockNodesToResolvedMarkdown(nodes, ctx) {
517
- const lines = [];
518
- for (const node of nodes) {
519
- const blockMd = await resolvedBlockNodeToMarkdown(node, 0, ctx);
520
- if (blockMd) lines.push(blockMd);
521
- }
522
- return lines.join("\n\n");
562
+ };
563
+ visit(nodes);
564
+ await Promise.all(tasks);
565
+ const out = [];
566
+ renderNodes(
567
+ nodes,
568
+ "",
569
+ void 0,
570
+ 0,
571
+ {
572
+ ipfsGateway: ctx.ipfsGateway,
573
+ mentionLabel: (link, kind) => names.get(`${kind} ${link}`) ?? fallbackLabel(link),
574
+ resolved: (id) => shown.get(id)
575
+ },
576
+ out
577
+ );
578
+ return out;
523
579
  }
524
- async function resolvedBlockNodeToMarkdown(node, depth, ctx) {
580
+ async function embedLines(block, ctx) {
525
581
  var _a;
526
- const block = node.block;
527
- const children = node.children || [];
528
- if (block.type === "Table") {
529
- return tableToResolvedMarkdown(node, depth, (text, annotations) => applyResolvedAnnotations(text, annotations, ctx));
530
- }
531
- const childrenType = (_a = block.attributes) == null ? void 0 : _a.childrenType;
532
- const isListContainer = block.type === "Paragraph" && !block.text && (childrenType === "Ordered" || childrenType === "Unordered" || childrenType === "Blockquote");
533
- let result = isListContainer ? resolvedIdComment(block.id) : await resolvedBlockToMarkdown(block, depth, ctx);
534
- for (const child of children) {
535
- const childMd = await resolvedBlockNodeToMarkdown(child, depth + 1, ctx);
536
- if (!childMd) continue;
537
- if (childrenType === "Ordered") result += "\n" + resolvedIndent(depth + 1) + "1. " + childMd.trim();
538
- else if (childrenType === "Unordered") result += "\n" + resolvedIndent(depth + 1) + "- " + childMd.trim();
539
- else if (childrenType === "Blockquote") result += "\n" + resolvedIndent(depth + 1) + "> " + childMd.trim();
540
- else result += "\n\n" + childMd;
541
- }
542
- return result;
543
- }
544
- async function resolvedBlockToMarkdown(block, depth, ctx) {
545
- var _a, _b;
546
- const ind = resolvedIndent(depth);
547
- const b = block;
548
- const text = b.text || "";
549
- const link = b.link || "";
550
- const annotations = b.annotations;
551
- const id = b.id;
552
- switch (block.type) {
553
- case "Paragraph":
554
- return appendResolvedIdToFirstLine(ind + await applyResolvedAnnotations(text, annotations, ctx), id);
555
- case "Heading": {
556
- const hashes = "#".repeat(Math.min(depth + 1, 6));
557
- return appendResolvedIdToFirstLine(`${hashes} ${await applyResolvedAnnotations(text, annotations, ctx)}`, id);
558
- }
559
- case "Code": {
560
- const lang = ((_a = b.attributes) == null ? void 0 : _a.language) || "";
561
- return ind + "```" + lang + " " + resolvedIdComment(id) + "\n" + ind + text + "\n" + ind + "```";
562
- }
563
- case "Math":
564
- return ind + "$$ " + resolvedIdComment(id) + "\n" + ind + text + "\n" + ind + "$$";
565
- case "Image":
566
- return ind + `![${text || "image"}](${formatResolvedMediaUrl(link)}) ${resolvedIdComment(id)}`;
567
- case "Video":
568
- return ind + `[Video](${formatResolvedMediaUrl(link)}) ${resolvedIdComment(id)}`;
569
- case "File": {
570
- const fileName = ((_b = b.attributes) == null ? void 0 : _b.name) || "file";
571
- return ind + `[${fileName}](${formatResolvedMediaUrl(link)}) ${resolvedIdComment(id)}`;
572
- }
573
- case "Embed":
574
- return appendResolvedIdToFirstLine(await resolveBlockEmbed(block, depth, ctx), id);
575
- case "WebEmbed":
576
- return ind + `[Web Embed](${link}) ${resolvedIdComment(id)}`;
577
- case "Button":
578
- return ind + `[${text || "Button"}](${link}) ${resolvedIdComment(id)}`;
579
- case "Query":
580
- return appendResolvedIdToFirstLine(await resolveQuery(block, depth, ctx), id);
581
- case "Nostr":
582
- return ind + `[Nostr: ${link}](${link}) ${resolvedIdComment(id)}`;
583
- default:
584
- return text ? appendResolvedIdToFirstLine(ind + text, id) : "";
585
- }
586
- }
587
- async function resolveBlockEmbed(block, depth, ctx) {
588
- var _a, _b;
589
- const ind = resolvedIndent(depth);
590
582
  const link = block.link || "";
591
- if (ctx.currentDepth >= ctx.maxDepth) return ind + `> [Embed: ${link}](${link})`;
592
583
  const id = unpackHmId(link);
593
- if (!id) return ind + `> [Embed: ${link}](${link})`;
584
+ if (!id || ctx.currentDepth >= ctx.maxDepth) return void 0;
594
585
  try {
595
586
  const resolved = await resolveEmbeddedResource(link, ctx);
596
- if (!((_a = resolved.content) == null ? void 0 : _a.length)) return ind + `> [Embed: ${resolved.label}](${link})`;
597
- const content = selectEmbeddedContent(resolved.content, id);
598
- if (!content.length) return ind + `> [Embed: ${resolved.label}](${link})`;
599
- const lines = [];
600
- const metadata = [`embed: ${link}`, `title: ${resolved.label}`];
601
- const view = (_b = block.attributes) == null ? void 0 : _b.view;
602
- if (typeof view === "string" && view) metadata.push(`view: ${view}`);
603
- if (id.version) metadata.push(`version: ${id.version}`);
604
- if (id.blockRef) metadata.push(`block: ${id.blockRef}${formatBlockRange(id)}`);
605
- lines.push(ind + `<!-- ${metadata.join("; ")} -->`);
606
- const nestedCtx = { ...ctx, currentDepth: ctx.currentDepth + 1 };
607
- for (const node of content) {
608
- const blockMd = await resolvedBlockNodeToMarkdown(node, depth, nestedCtx);
609
- if (!blockMd) continue;
610
- lines.push(blockMd);
611
- }
612
- lines.push(ind + `<!-- /embed: ${link} -->`);
613
- return lines.join("\n");
587
+ const content = ((_a = resolved.content) == null ? void 0 : _a.length) ? selectEmbeddedContent(resolved.content, id) : [];
588
+ const nested = { ...ctx, currentDepth: ctx.currentDepth + 1 };
589
+ return { label: resolved.label, lines: content.length ? await resolvedLines(content, nested, resolved.home) : [] };
614
590
  } catch {
615
- return ind + `> [Embed: ${link}](${link})`;
591
+ return { label: "not available", lines: [] };
616
592
  }
617
593
  }
618
- async function resolveQuery(block, depth, ctx) {
619
- var _a, _b;
620
- const ind = resolvedIndent(depth);
594
+ async function queryLines(block, ctx, home) {
595
+ var _a, _b, _c;
596
+ const note = (text) => ({ label: text, lines: [] });
621
597
  try {
622
598
  const attrs = block.attributes;
623
599
  const queryConfig = attrs == null ? void 0 : attrs.query;
@@ -626,8 +602,9 @@ async function resolveQuery(block, depth, ctx) {
626
602
  let filters;
627
603
  let limit;
628
604
  if (queryConfig == null ? void 0 : queryConfig.includes) {
629
- if (!((_a = queryConfig.includes[0]) == null ? void 0 : _a.space)) return ind + "<!-- Query: no space specified -->";
630
- includes = queryConfig.includes.map((inc) => ({
605
+ const sourced = home && queryConfig.includes.length === 1 && !((_a = queryConfig.includes[0]) == null ? void 0 : _a.space) ? [{ ...queryConfig.includes[0], space: home.space, path: home.path }] : queryConfig.includes;
606
+ if (!((_b = sourced[0]) == null ? void 0 : _b.space)) return note("query with no space");
607
+ includes = sourced.map((inc) => ({
631
608
  space: inc.space,
632
609
  path: inc.path,
633
610
  mode: inc.mode || "Children"
@@ -637,7 +614,7 @@ async function resolveQuery(block, depth, ctx) {
637
614
  limit = queryConfig.limit;
638
615
  } else {
639
616
  const space = (attrs == null ? void 0 : attrs.space) || "";
640
- if (!space) return ind + "<!-- Query: no space specified -->";
617
+ if (!space) return note("query with no space");
641
618
  limit = typeof (attrs == null ? void 0 : attrs.limit) === "number" ? attrs.limit : void 0;
642
619
  includes = [
643
620
  {
@@ -647,20 +624,25 @@ async function resolveQuery(block, depth, ctx) {
647
624
  }
648
625
  ];
649
626
  }
650
- const results = await ctx.client.request("Query", {
651
- includes,
652
- sort: (sort == null ? void 0 : sort.length) ? sort : [{ term: "updated", reverse: true }],
653
- filters,
654
- limit: limit || 10
655
- });
656
- if (!((_b = results == null ? void 0 : results.results) == null ? void 0 : _b.length)) return ind + "<!-- Query: no results -->";
657
- return results.results.map((doc) => {
658
- var _a2, _b2;
659
- const name = ((_a2 = doc.metadata) == null ? void 0 : _a2.name) || ((_b2 = doc.id.path) == null ? void 0 : _b2.join("/")) || doc.id.uid;
660
- return ind + `- [${name}](${doc.id.id})`;
661
- }).join("\n");
627
+ const results = await ctx.limit(
628
+ () => ctx.client.request("Query", {
629
+ includes,
630
+ sort: (sort == null ? void 0 : sort.length) ? sort : [{ term: "updated", reverse: true }],
631
+ filters,
632
+ limit: limit || 10
633
+ })
634
+ );
635
+ if (!((_c = results == null ? void 0 : results.results) == null ? void 0 : _c.length)) return note("query results: none");
636
+ return {
637
+ label: "query results",
638
+ lines: results.results.map((doc) => {
639
+ var _a2, _b2;
640
+ const name = ((_a2 = doc.metadata) == null ? void 0 : _a2.name) || ((_b2 = doc.id.path) == null ? void 0 : _b2.join("/")) || doc.id.uid;
641
+ return `- [${escapeInline(name, false)}](${doc.id.id})`;
642
+ })
643
+ };
662
644
  } catch (error) {
663
- return ind + `<!-- Query error: ${error instanceof Error ? error.message : String(error)} -->`;
645
+ return note(`query failed: ${error instanceof Error ? error.message : String(error)}`);
664
646
  }
665
647
  }
666
648
  function selectEmbeddedContent(content, id) {
@@ -676,156 +658,81 @@ function selectEmbeddedContent(content, id) {
676
658
  function sliceBlockText(node, start, end) {
677
659
  const block = node.block;
678
660
  if (typeof block.text !== "string") return { ...node, children: [] };
679
- return { ...node, block: { ...block, text: block.text.slice(start, end) }, children: [] };
680
- }
681
- async function applyResolvedAnnotations(text, annotations, ctx) {
682
- if (!(annotations == null ? void 0 : annotations.length)) return text;
683
- const markers = [];
684
- for (const ann of annotations) {
685
- const starts = ann.starts || [];
686
- const ends = ann.ends || [];
687
- for (let i = 0; i < starts.length; i++) {
688
- markers.push({ pos: starts[i], type: "open", annotation: ann });
689
- if (ends[i] !== void 0) markers.push({ pos: ends[i], type: "close", annotation: ann });
661
+ return { ...node, block: { ...block, text: block.text.slice(start, end), annotations: [] }, children: [] };
662
+ }
663
+ async function resolveMarkdownReferenceId(link, ctx) {
664
+ return resolveId(link, {
665
+ domainResolver: async (domain) => {
666
+ const info = await ctx.limit(() => ctx.client.request("GetDomain", { domain }));
667
+ return info.registeredAccountUid ? { registeredAccountUid: info.registeredAccountUid, isGateway: info.isGateway } : null;
690
668
  }
691
- }
692
- markers.sort((a, b) => a.pos !== b.pos ? a.pos - b.pos : a.type === "open" ? -1 : 1);
693
- let result = "";
694
- let lastPos = 0;
695
- for (const marker of markers) {
696
- result += text.slice(lastPos, marker.pos);
697
- lastPos = marker.pos;
698
- result += await getResolvedAnnotationMarker(marker.annotation, marker.type, ctx);
699
- }
700
- result += text.slice(lastPos);
701
- return result.replace(/\uFFFC/g, "");
669
+ });
702
670
  }
703
- async function getResolvedAnnotationMarker(ann, type, ctx) {
704
- switch (ann.type) {
705
- case "Bold":
706
- return "**";
707
- case "Italic":
708
- return "_";
709
- case "Strike":
710
- return "~~";
711
- case "Code":
712
- return "`";
713
- case "Underline":
714
- return type === "open" ? "<u>" : "</u>";
715
- case "Link":
716
- return type === "open" ? "[" : `](${ann.link || ""})`;
717
- case "Embed":
718
- return resolveInlineEmbed(ann, type, ctx);
719
- default:
720
- return "";
671
+ function resolveOnce(ctx, key, load) {
672
+ let pending = ctx.cache.get(key);
673
+ if (!pending) {
674
+ pending = load();
675
+ ctx.cache.set(key, pending);
721
676
  }
677
+ return pending;
722
678
  }
723
- async function resolveInlineEmbed(ann, type, ctx) {
679
+ async function commentAuthorName(author, ctx) {
724
680
  var _a;
725
- const link = "link" in ann ? ann.link || "" : "";
726
- if (type === "close") return `](${link})`;
727
- if (!link) return "[\u2197 embed";
728
681
  try {
729
- const resolved = await resolveReference(link, ctx, ann.type === "Embed" ? (_a = ann.attributes) == null ? void 0 : _a.mentionKind : void 0);
730
- const prefix = resolved.type === "account" && !resolved.label.startsWith("@") ? "@" : "";
731
- return `[${prefix}${resolved.label}`;
682
+ const account = await ctx.limit(() => ctx.client.request("Account", author));
683
+ if (account.type === "account" && ((_a = account.metadata) == null ? void 0 : _a.name)) return account.metadata.name;
732
684
  } catch {
733
- return `[\u2197 ${fallbackLabel(link)}`;
734
685
  }
686
+ return fallbackUid(author);
735
687
  }
736
- async function resolveMarkdownReferenceId(link, ctx) {
737
- return resolveId(link, {
738
- domainResolver: async (domain) => {
739
- const info = await ctx.client.request("GetDomain", { domain });
740
- return info.registeredAccountUid ? { registeredAccountUid: info.registeredAccountUid, isGateway: info.isGateway } : null;
741
- }
742
- });
743
- }
744
- async function resolveEmbeddedResource(link, ctx) {
745
- var _a, _b;
746
- const cacheKey = `embed:${link}`;
747
- const cached = ctx.cache.get(cacheKey);
748
- if (cached) return cached;
749
- const id = await resolveMarkdownReferenceId(link, ctx);
750
- const resource = await ctx.client.request("Resource", id);
751
- let resolved;
688
+ async function referenceFromResource(link, id, ctx) {
689
+ var _a;
690
+ const resource = await ctx.limit(() => ctx.client.request("Resource", id));
752
691
  if (resource.type === "document") {
753
- resolved = {
692
+ return {
754
693
  label: ((_a = resource.document.metadata) == null ? void 0 : _a.name) || fallbackDocLabel(id),
755
694
  type: "document",
756
- content: resolvedDocumentContent(resource.document),
695
+ content: resource.document.content || [],
696
+ home: soleQueryHome(resource.document),
757
697
  version: id.version || resource.document.version,
758
698
  latestVersion: resource.document.version
759
699
  };
760
- } else if (resource.type === "comment") {
761
- let authorName = fallbackUid(resource.comment.author);
762
- try {
763
- const account = await ctx.client.request("Account", resource.comment.author);
764
- if (account.type === "account" && ((_b = account.metadata) == null ? void 0 : _b.name)) authorName = account.metadata.name;
765
- } catch {
766
- }
767
- resolved = {
768
- label: `Comment by ${authorName}`,
700
+ }
701
+ if (resource.type === "comment") {
702
+ return {
703
+ label: `Comment by ${await commentAuthorName(resource.comment.author, ctx)}`,
769
704
  type: "comment",
770
705
  content: resource.comment.content || [],
771
706
  version: id.version || resource.comment.version,
772
707
  latestVersion: resource.comment.version,
773
708
  author: resource.comment.author
774
709
  };
775
- } else {
776
- resolved = { label: fallbackLabel(link), type: "unknown" };
777
710
  }
778
- ctx.cache.set(cacheKey, resolved);
779
- return resolved;
780
- }
781
- async function resolveReference(link, ctx, mentionKind) {
782
- var _a, _b, _c, _d, _e;
783
- const cacheKey = `${mentionKind || "legacy"}:${link}`;
784
- const cached = ctx.cache.get(cacheKey);
785
- if (cached) return cached;
786
- const id = await resolveMarkdownReferenceId(link, ctx);
787
- let resolved;
788
- const profileAccountUid = ((_a = id.path) == null ? void 0 : _a[0]) === ":profile" ? id.path[1] || id.uid : !((_b = id.path) == null ? void 0 : _b.length) ? id.uid : null;
789
- if (profileAccountUid && mentionKind !== "document") {
790
- try {
791
- const account = await ctx.client.request("Account", profileAccountUid);
792
- if (account.type === "account") {
793
- resolved = { label: ((_c = account.metadata) == null ? void 0 : _c.name) || fallbackUid(profileAccountUid), type: "account" };
794
- ctx.cache.set(cacheKey, resolved);
795
- return resolved;
711
+ return { label: fallbackLabel(link), type: "unknown" };
712
+ }
713
+ function resolveEmbeddedResource(link, ctx) {
714
+ return resolveOnce(
715
+ ctx,
716
+ `embed:${link}`,
717
+ async () => referenceFromResource(link, await resolveMarkdownReferenceId(link, ctx), ctx)
718
+ );
719
+ }
720
+ function resolveReference(link, ctx, mentionKind) {
721
+ return resolveOnce(ctx, `${mentionKind || "legacy"}:${link}`, async () => {
722
+ var _a, _b, _c;
723
+ const id = await resolveMarkdownReferenceId(link, ctx);
724
+ const profileAccountUid = ((_a = id.path) == null ? void 0 : _a[0]) === ":profile" ? id.path[1] || id.uid : !((_b = id.path) == null ? void 0 : _b.length) ? id.uid : null;
725
+ if (profileAccountUid && mentionKind !== "document") {
726
+ try {
727
+ const account = await ctx.limit(() => ctx.client.request("Account", profileAccountUid));
728
+ if (account.type === "account") {
729
+ return { label: ((_c = account.metadata) == null ? void 0 : _c.name) || fallbackUid(profileAccountUid), type: "account" };
730
+ }
731
+ } catch {
796
732
  }
797
- } catch {
798
733
  }
799
- }
800
- const resource = await ctx.client.request("Resource", id);
801
- if (resource.type === "document") {
802
- resolved = {
803
- label: ((_d = resource.document.metadata) == null ? void 0 : _d.name) || fallbackDocLabel(id),
804
- type: "document",
805
- content: resource.document.content || [],
806
- version: id.version || resource.document.version,
807
- latestVersion: resource.document.version
808
- };
809
- } else if (resource.type === "comment") {
810
- let authorName = fallbackUid(resource.comment.author);
811
- try {
812
- const account = await ctx.client.request("Account", resource.comment.author);
813
- if (account.type === "account" && ((_e = account.metadata) == null ? void 0 : _e.name)) authorName = account.metadata.name;
814
- } catch {
815
- }
816
- resolved = {
817
- label: `Comment by ${authorName}`,
818
- type: "comment",
819
- content: resource.comment.content || [],
820
- version: id.version || resource.comment.version,
821
- latestVersion: resource.comment.version,
822
- author: resource.comment.author
823
- };
824
- } else {
825
- resolved = { label: fallbackLabel(link), type: "unknown" };
826
- }
827
- ctx.cache.set(cacheKey, resolved);
828
- return resolved;
734
+ return referenceFromResource(link, id, ctx);
735
+ });
829
736
  }
830
737
  function findBlockById(content, blockId) {
831
738
  for (const node of content) {
@@ -835,25 +742,6 @@ function findBlockById(content, blockId) {
835
742
  }
836
743
  return null;
837
744
  }
838
- function resolvedIdComment(id) {
839
- return `<!-- id:${id} -->`;
840
- }
841
- function appendResolvedIdToFirstLine(md, id) {
842
- const newline = md.indexOf("\n");
843
- if (newline === -1) return md ? `${md} ${resolvedIdComment(id)}` : resolvedIdComment(id);
844
- return `${md.slice(0, newline)} ${resolvedIdComment(id)}${md.slice(newline)}`;
845
- }
846
- function formatResolvedMediaUrl(url) {
847
- if (url.startsWith("ipfs://")) return `https://ipfs.io/ipfs/${url.slice(7)}`;
848
- return url;
849
- }
850
- function formatBlockRange(id) {
851
- const range = id.blockRange;
852
- if (!range) return "";
853
- if ("expanded" in range && range.expanded) return "+";
854
- if ("start" in range) return `[${range.start}:${range.end}]`;
855
- return "";
856
- }
857
745
  function fallbackDocLabel(id) {
858
746
  var _a;
859
747
  return ((_a = id.path) == null ? void 0 : _a.length) ? id.path.join("/") : fallbackUid(id.uid);
@@ -866,9 +754,6 @@ function fallbackLabel(link) {
866
754
  function fallbackUid(uid) {
867
755
  return uid.length > 12 ? `${uid.slice(0, 12)}...` : uid;
868
756
  }
869
- function resolvedIndent(depth) {
870
- return " ".repeat(depth);
871
- }
872
757
 
873
758
  export {
874
759
  emitFrontmatter,