@aparte/core 0.27.3 → 0.28.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.
Files changed (55) hide show
  1. package/dist/client/stream-adapter.d.ts.map +1 -1
  2. package/dist/components/bubble/aparte-chat-bubble.d.ts +2 -0
  3. package/dist/components/bubble/aparte-chat-bubble.d.ts.map +1 -1
  4. package/dist/components/bubble/bubble-sync.d.ts.map +1 -1
  5. package/dist/config/aparte-config.d.ts +86 -7
  6. package/dist/config/aparte-config.d.ts.map +1 -1
  7. package/dist/config/index.d.ts +1 -1
  8. package/dist/config/index.d.ts.map +1 -1
  9. package/dist/config/locale.d.ts +14 -0
  10. package/dist/config/locale.d.ts.map +1 -1
  11. package/dist/config/sanitize.d.ts +7 -2
  12. package/dist/config/sanitize.d.ts.map +1 -1
  13. package/dist/custom-elements.json +17465 -16815
  14. package/dist/{defer-hydration-BG8ANn8q.js → defer-hydration-BMip3DKA.js} +1253 -103
  15. package/dist/defer-hydration-BMip3DKA.js.map +1 -0
  16. package/dist/elicitation/approval-panel.d.ts +1 -1
  17. package/dist/elicitation/approval-panel.d.ts.map +1 -1
  18. package/dist/elicitation/types.d.ts +3 -2
  19. package/dist/elicitation/types.d.ts.map +1 -1
  20. package/dist/index.css +1 -1
  21. package/dist/index.d.ts +5 -3
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +38 -14
  24. package/dist/index.js.map +1 -1
  25. package/dist/index.node.d.ts +4 -3
  26. package/dist/index.node.d.ts.map +1 -1
  27. package/dist/index.node.js +14 -12
  28. package/dist/index.node.js.map +1 -1
  29. package/dist/parsers/aparte-stream-parser.d.ts.map +1 -1
  30. package/dist/renderers/citations.d.ts +23 -0
  31. package/dist/renderers/citations.d.ts.map +1 -0
  32. package/dist/renderers/code-languages.d.ts +30 -0
  33. package/dist/renderers/code-languages.d.ts.map +1 -0
  34. package/dist/renderers/highlight-stream.d.ts.map +1 -1
  35. package/dist/renderers/index.d.ts +3 -0
  36. package/dist/renderers/index.d.ts.map +1 -1
  37. package/dist/renderers/markdown-stream.d.ts +12 -1
  38. package/dist/renderers/markdown-stream.d.ts.map +1 -1
  39. package/dist/renderers/segments/code.d.ts.map +1 -1
  40. package/dist/renderers/segments/text.d.ts.map +1 -1
  41. package/dist/renderers/segments/thinking.d.ts.map +1 -1
  42. package/dist/transport/backend-handler.d.ts.map +1 -1
  43. package/dist/transport/backend-transport.d.ts.map +1 -1
  44. package/dist/transport/types.d.ts +15 -2
  45. package/dist/transport/types.d.ts.map +1 -1
  46. package/dist/types/chat.d.ts +10 -1
  47. package/dist/types/chat.d.ts.map +1 -1
  48. package/dist/types/index.d.ts +1 -1
  49. package/dist/types/index.d.ts.map +1 -1
  50. package/dist/types/model-provider.d.ts +3 -1
  51. package/dist/types/model-provider.d.ts.map +1 -1
  52. package/dist/types/segments.d.ts +36 -0
  53. package/dist/types/segments.d.ts.map +1 -1
  54. package/package.json +2 -2
  55. package/dist/defer-hydration-BG8ANn8q.js.map +0 -1
@@ -145,6 +145,13 @@ const APARTE_DEFAULT_LOCALE = {
145
145
  toolNoApprover: "No one could approve it",
146
146
  toolTurnLimit: "Turn limit reached",
147
147
  maxTurnsReached: "Stopped after {n} turns to avoid an endless loop.",
148
+ sourcesCount: "{n} sources",
149
+ sourcesOne: "1 source",
150
+ sourcesCard: "Sources",
151
+ sourcePrevious: "Previous source",
152
+ sourceNext: "Next source",
153
+ sourcePosition: "Source {i} of {n}",
154
+ opensInNewTab: "(opens in a new tab)",
148
155
  questionDeclined: "You declined to answer.",
149
156
  artifactNotCreated: "Not created",
150
157
  thoughtFor: "Thought for {duration}",
@@ -254,7 +261,25 @@ async function parseNonStreamText(provider, response, providerId) {
254
261
  if (typeof provider.parseText !== "function") {
255
262
  throw new Error(`Provider "${providerId}" cannot resolve a non-streaming response: parseText is not implemented.`);
256
263
  }
257
- return provider.parseText(json);
264
+ const text = provider.parseText(json);
265
+ let sources2;
266
+ try {
267
+ sources2 = provider.parseSources?.(json);
268
+ } catch {
269
+ sources2 = void 0;
270
+ }
271
+ return withSources(text, sources2);
272
+ }
273
+ function withSources(text, sources2) {
274
+ if (!sources2 || sources2.sources.length === 0) return text;
275
+ const events = [{ type: "text", delta: text }, { type: "sources", ...sources2 }, { type: "done" }];
276
+ return new ReadableStream({
277
+ pull(controller) {
278
+ const next = events.shift();
279
+ if (next) controller.enqueue(next);
280
+ else controller.close();
281
+ }
282
+ });
258
283
  }
259
284
  class AparteDirectTransport {
260
285
  byok;
@@ -516,6 +541,7 @@ class AparteStreamParser {
516
541
  this._state.mode = "code";
517
542
  this._state.codeLanguage = language;
518
543
  this._state.activeSegment = this._createCodeSegment(language, "");
544
+ this._state.activeSegment.isStreaming = true;
519
545
  return { segment: null, remaining: buffer.slice(firstNewline + 1) };
520
546
  }
521
547
  _parseCodeMode(buffer) {
@@ -855,7 +881,9 @@ class AparteBackendTransport {
855
881
  if (request.stream === false) {
856
882
  const json = await response.json();
857
883
  const text = json?.text;
858
- return typeof text === "string" ? text : typeof json === "string" ? json : JSON.stringify(json);
884
+ if (typeof text !== "string") return typeof json === "string" ? json : JSON.stringify(json);
885
+ const { sources: sources2, citations } = json;
886
+ return withSources(text, Array.isArray(sources2) ? { sources: sources2, ...Array.isArray(citations) ? { citations } : {} } : void 0);
859
887
  }
860
888
  if (!response.body) {
861
889
  throw new Error("Backend returned no response body for a streaming request.");
@@ -948,7 +976,13 @@ function createAparteChatHandler(options) {
948
976
  } catch {
949
977
  return jsonError$1(502, "The vendor answered with an error.");
950
978
  }
951
- return new Response(JSON.stringify({ text }), {
979
+ let cited;
980
+ try {
981
+ cited = typeof adapter.parseSources === "function" ? adapter.parseSources(json) : void 0;
982
+ } catch {
983
+ cited = void 0;
984
+ }
985
+ return new Response(JSON.stringify(cited ? { text, ...cited } : { text }), {
952
986
  headers: { "Content-Type": "application/json" }
953
987
  });
954
988
  }
@@ -1161,6 +1195,47 @@ function createStreamAdapter(opts) {
1161
1195
  };
1162
1196
  let thinkingContent = "";
1163
1197
  let thinkingCollapsed = false;
1198
+ let callText = "";
1199
+ let callTexts = /* @__PURE__ */ new Map();
1200
+ let callSources = [];
1201
+ let callCitations = [];
1202
+ let given = /* @__PURE__ */ new Set();
1203
+ const noteText = (segment) => {
1204
+ const content = segment.content;
1205
+ if (typeof content === "string") callTexts.set(segment.id, { text: segment.type === "text", content });
1206
+ };
1207
+ const placeSources = () => {
1208
+ if (callSources.length === 0) return;
1209
+ let cursor = 0;
1210
+ const spans = [...callTexts].map(([id, { text, content }]) => {
1211
+ const start = callText.indexOf(content, cursor);
1212
+ if (start >= 0) cursor = start + content.length;
1213
+ return { id, text, start, length: content.length, citations: [] };
1214
+ }).filter((s) => s.text);
1215
+ if (spans.length === 0) return;
1216
+ const placed = /* @__PURE__ */ new Set();
1217
+ for (const citation of callCitations) {
1218
+ const span = spans.find((s) => s.start >= 0 && citation.end > s.start && citation.end <= s.start + s.length);
1219
+ if (!span) continue;
1220
+ const end = citation.end - span.start;
1221
+ const start = citation.start === void 0 ? void 0 : Math.max(0, Math.min(end, citation.start - span.start));
1222
+ span.citations.push({ ...citation, end, ...start === void 0 ? {} : { start } });
1223
+ for (const id of citation.sources) placed.add(id);
1224
+ }
1225
+ const last = spans[spans.length - 1];
1226
+ const now = /* @__PURE__ */ new Set();
1227
+ for (const span of spans) {
1228
+ const named = new Set(span.citations.flatMap((c) => c.sources));
1229
+ const sources2 = callSources.filter((s) => named.has(s.id) || span === last && !placed.has(s.id));
1230
+ if (sources2.length === 0) {
1231
+ if (given.has(span.id)) target.updateSegment?.(span.id, { sources: void 0, citations: void 0 });
1232
+ continue;
1233
+ }
1234
+ now.add(span.id);
1235
+ target.updateSegment?.(span.id, { sources: sources2, citations: span.citations });
1236
+ }
1237
+ given = now;
1238
+ };
1164
1239
  const settleThinking = (fold) => {
1165
1240
  if (!thinkingId || thinkingCollapsed) return;
1166
1241
  const chatConfig = typeof Element !== "undefined" && target instanceof Element ? resolveConfig(target) : config;
@@ -1177,6 +1252,11 @@ function createStreamAdapter(opts) {
1177
1252
  settleThinking(false);
1178
1253
  parser = new AparteStreamParser({ blocks: config.getStreamBlocks() });
1179
1254
  streaming = /* @__PURE__ */ new Set();
1255
+ callText = "";
1256
+ callTexts = /* @__PURE__ */ new Map();
1257
+ callSources = given.size === 0 ? callSources.map((s) => ({ ...s, id: `${s.id}~` })) : [];
1258
+ callCitations = [];
1259
+ given = /* @__PURE__ */ new Set();
1180
1260
  thinkingId = null;
1181
1261
  thinkingContent = "";
1182
1262
  thinkingCollapsed = false;
@@ -1200,8 +1280,10 @@ function createStreamAdapter(opts) {
1200
1280
  }
1201
1281
  case "text-delta": {
1202
1282
  settleThinking(true);
1283
+ callText += e.delta;
1203
1284
  const result = parser.parse(e.delta);
1204
1285
  for (const segment of result.segments) {
1286
+ noteText(segment);
1205
1287
  if (!streaming.has(segment.id)) {
1206
1288
  target.addSegment?.(segment);
1207
1289
  streaming.add(segment.id);
@@ -1211,6 +1293,7 @@ function createStreamAdapter(opts) {
1211
1293
  }
1212
1294
  const active = parser.getState().activeSegment;
1213
1295
  if (active) {
1296
+ noteText(active);
1214
1297
  if (!streaming.has(active.id)) {
1215
1298
  target.addSegment?.(active);
1216
1299
  streaming.add(active.id);
@@ -1223,9 +1306,26 @@ function createStreamAdapter(opts) {
1223
1306
  case "text-flush": {
1224
1307
  const finals = parser.finalize();
1225
1308
  for (const s of finals) {
1309
+ noteText(s);
1226
1310
  if (!streaming.has(s.id)) target.addSegment?.(s);
1227
1311
  else if ("content" in s) target.updateSegment?.(s.id, segmentContentUpdate(s));
1228
1312
  }
1313
+ placeSources();
1314
+ break;
1315
+ }
1316
+ case "sources": {
1317
+ const byId = new Map(callSources.map((s) => [s.id, s]));
1318
+ for (const s of Array.isArray(e.sources) ? e.sources : []) byId.set(s.id, { ...byId.get(s.id), ...s });
1319
+ callSources = [...byId.values()];
1320
+ const seen2 = new Set(callCitations.map((c) => JSON.stringify([c.start, c.end, c.marker, c.sources])));
1321
+ for (const c of Array.isArray(e.citations) ? e.citations : []) {
1322
+ const key = JSON.stringify([c.start, c.end, c.marker, c.sources]);
1323
+ if (!seen2.has(key)) {
1324
+ seen2.add(key);
1325
+ callCitations.push(c);
1326
+ }
1327
+ }
1328
+ placeSources();
1229
1329
  break;
1230
1330
  }
1231
1331
  case "tool-start": {
@@ -1291,8 +1391,8 @@ function createStreamAdapter(opts) {
1291
1391
  const ticket = e.ticket;
1292
1392
  for (const p of e.pending) {
1293
1393
  const id = `tool-${p.toolCallId}`;
1294
- const deferred = { reason: p.reason, ...typeof ticket === "string" ? { ticket } : {} };
1295
- target.updateSegment?.(id, { deferred });
1394
+ const deferred2 = { reason: p.reason, ...typeof ticket === "string" ? { ticket } : {} };
1395
+ target.updateSegment?.(id, { deferred: deferred2 });
1296
1396
  }
1297
1397
  target.updateMessage?.(messageId, { status: "completed" });
1298
1398
  if (e.usage) {
@@ -2035,6 +2135,7 @@ class AparteConfig {
2035
2135
  _markdownProvider;
2036
2136
  _streamingMarkdownProvider;
2037
2137
  _highlightProvider;
2138
+ _codeLanguageRenderers = /* @__PURE__ */ new Map();
2038
2139
  // HTML sanitizer applied to markdown/highlight PROVIDER output (untrusted,
2039
2140
  // LLM-authored) before it is injected via innerHTML. Default = built-in
2040
2141
  // zero-dep allowlist sanitizer; `null` disables it (trusted content only).
@@ -2273,24 +2374,64 @@ class AparteConfig {
2273
2374
  hasHighlightProvider() {
2274
2375
  return !!this._highlightProvider;
2275
2376
  }
2377
+ /**
2378
+ * Draw a language — `math`, `mermaid` — wherever it appears in a reply, whichever
2379
+ * Markdown provider produced it. Messages already on screen are drawn again.
2380
+ *
2381
+ * @returns a disposer that removes the renderer, if it is still the one registered.
2382
+ * @example aparteGlobalConfig.registerCodeLanguageRenderer({ languages: ['math'], render: ({ source }) => katex.renderToString(source) });
2383
+ */
2384
+ registerCodeLanguageRenderer(renderer) {
2385
+ const languages = renderer.languages.map((l) => l.toLowerCase());
2386
+ for (const language of languages) this._codeLanguageRenderers.set(language, renderer);
2387
+ bumpRenderingVersion(this);
2388
+ this._notify();
2389
+ return () => {
2390
+ let removed = false;
2391
+ for (const language of languages) {
2392
+ if (this._codeLanguageRenderers.get(language) !== renderer) continue;
2393
+ this._codeLanguageRenderers.delete(language);
2394
+ removed = true;
2395
+ }
2396
+ if (!removed) return;
2397
+ bumpRenderingVersion(this);
2398
+ this._notify();
2399
+ };
2400
+ }
2401
+ /** The renderer registered for `language`, if any. */
2402
+ getCodeLanguageRenderer(language) {
2403
+ return this._codeLanguageRenderers.get(language.toLowerCase());
2404
+ }
2405
+ /** Whether a renderer is registered for `language`, or for any language when none is given. */
2406
+ hasCodeLanguageRenderer(language) {
2407
+ return language === void 0 ? this._codeLanguageRenderers.size > 0 : this._codeLanguageRenderers.has(language.toLowerCase());
2408
+ }
2276
2409
  /**
2277
2410
  * Replace or disable the HTML sanitizer applied to markdown/highlight
2278
2411
  * provider output before it is injected into the DOM. Defaults to a built-in
2279
2412
  * zero-dependency allowlist sanitizer.
2280
2413
  *
2281
- * @param sanitizer A sanitizer function (e.g. a DOMPurify wrapper) for
2282
- * hardened coverage, or `null` to DISABLE sanitization. Disabling exposes
2283
- * you to XSS from LLM-authored content — only do so for content you fully
2284
- * trust and have already sanitized upstream. `null` prints a console warning, once.
2285
- * @example aparteGlobalConfig.setHtmlSanitizer((html) => DOMPurify.sanitize(html));
2414
+ * The function you pass REPLACES the built-in one, chat rules included: no
2415
+ * `aparte-` classes, no layout styles, no form controls, external links in a new
2416
+ * tab. DOMPurify's defaults hold none of the four, so chain it in front of
2417
+ * `defaultSanitizer` rather than in its place (the example below).
2418
+ *
2419
+ * @param sanitizer A sanitizer function, or `null` to DISABLE sanitization.
2420
+ * Disabling exposes you to XSS from LLM-authored content — only do so for
2421
+ * content you fully trust and have already sanitized upstream. `null` prints
2422
+ * a console warning, once.
2423
+ * @example aparteGlobalConfig.setHtmlSanitizer((html) => defaultSanitizer(DOMPurify.sanitize(html)));
2286
2424
  */
2287
2425
  setHtmlSanitizer(sanitizer) {
2426
+ if (sanitizer === this._sanitizer) return;
2288
2427
  if (sanitizer === null) {
2289
2428
  console.warn(
2290
- "[aparte] HTML sanitization is now DISABLED (setHtmlSanitizer(null)). Model-authored HTML will be inserted verbatim. Pass a sanitizer (e.g. DOMPurify.sanitize) unless you sanitize upstream yourself."
2429
+ "[aparte] HTML sanitization is now DISABLED (setHtmlSanitizer(null)). Model-authored HTML will be inserted verbatim. Pass a sanitizer (defaultSanitizer, or DOMPurify chained before it) unless you sanitize upstream yourself."
2291
2430
  );
2292
2431
  }
2293
2432
  this._sanitizer = sanitizer;
2433
+ bumpRenderingVersion(this);
2434
+ this._notify();
2294
2435
  }
2295
2436
  /**
2296
2437
  * Run the active sanitizer over provider-produced HTML. Public so a
@@ -2933,8 +3074,12 @@ class AparteConfig {
2933
3074
  * Highlight code block
2934
3075
  * Fallback: Returns raw code wrapped in `<pre><code>`
2935
3076
  * Supports Promise if provider is async/streaming
3077
+ *
3078
+ * @param options.fallback `false` rejects when the highlight provider fails, instead of
3079
+ * answering the plain block: for a caller that keeps what it highlighted, so a
3080
+ * failure (a highlighter still loading its grammars) is tried again rather than kept.
2936
3081
  */
2937
- async highlightCode(code, lang) {
3082
+ async highlightCode(code, lang, options = {}) {
2938
3083
  if (this._highlightProvider) {
2939
3084
  try {
2940
3085
  const result = this._highlightProvider(code, lang);
@@ -2942,6 +3087,7 @@ class AparteConfig {
2942
3087
  return this.sanitizeHtml(html);
2943
3088
  } catch (error) {
2944
3089
  console.warn("[AparteConfig] Highlight provider failed, using fallback:", error);
3090
+ if (options.fallback === false) throw error;
2945
3091
  }
2946
3092
  }
2947
3093
  return this._defaultHighlightRenderer(code);
@@ -3379,15 +3525,15 @@ class AparteConfig {
3379
3525
  requestUserInput(request) {
3380
3526
  const queue = this._elicitationQueueKey(request);
3381
3527
  const previous = this._elicitationQueue.get(queue);
3382
- const settled = previous === void 0 ? this._present(request) : previous.then(
3528
+ const settled2 = previous === void 0 ? this._present(request) : previous.then(
3383
3529
  () => this._present(request),
3384
3530
  () => this._present(request)
3385
3531
  );
3386
- const mine = settled.then(NOOP, NOOP).then(() => {
3532
+ const mine = settled2.then(NOOP, NOOP).then(() => {
3387
3533
  if (this._elicitationQueue.get(queue) === mine) this._elicitationQueue.delete(queue);
3388
3534
  });
3389
3535
  this._elicitationQueue.set(queue, mine);
3390
- return settled;
3536
+ return settled2;
3391
3537
  }
3392
3538
  /**
3393
3539
  * Which queue a request waits in: its own chat's.
@@ -3427,7 +3573,7 @@ class AparteConfig {
3427
3573
  /**
3428
3574
  * Put the configuration back to its defaults: the providers and the selected model,
3429
3575
  * the tools with their renderers and summaries, the renderers and render hooks, the
3430
- * Markdown and highlight providers, the sanitizer, the system prompt, the locale, icons,
3576
+ * Markdown and highlight providers, the code-language renderers, the sanitizer, the system prompt, the locale, icons,
3431
3577
  * avatars, actions and host handlers, the conversation manager, the question presenters
3432
3578
  * and their queue. Three things stay: the transport, the key sources added with
3433
3579
  * {@link AparteConfig.registerKeyProvider | registerKeyProvider()} (an `AparteClient`'s
@@ -3437,6 +3583,7 @@ class AparteConfig {
3437
3583
  this._markdownProvider = void 0;
3438
3584
  this._streamingMarkdownProvider = void 0;
3439
3585
  this._highlightProvider = void 0;
3586
+ this._codeLanguageRenderers.clear();
3440
3587
  this._systemPromptTemplate = void 0;
3441
3588
  this._systemPromptVarsProvider = void 0;
3442
3589
  this._statusRenderer = void 0;
@@ -3508,15 +3655,957 @@ function subscribeConfigChange(el2, handler) {
3508
3655
  window.addEventListener(APARTE_CONFIG_CHANGE, listener);
3509
3656
  return () => window.removeEventListener(APARTE_CONFIG_CHANGE, listener);
3510
3657
  }
3511
- const settledFromParser = /* @__PURE__ */ new WeakMap();
3658
+ const DRAWING_CLASS = "aparte-code-drawing";
3659
+ const PENDING_CLASS = "aparte-code-pending";
3660
+ const OPEN_ATTR = "data-aparte-open";
3661
+ const DRAWN_ATTR = "data-aparte-drawn";
3662
+ const CACHE_BUDGET = 4 * 1024 * 1024;
3663
+ class DrawingCache {
3664
+ entries = /* @__PURE__ */ new Map();
3665
+ size = 0;
3666
+ get(key) {
3667
+ const hit = this.entries.get(key);
3668
+ if (hit) {
3669
+ this.entries.delete(key);
3670
+ this.entries.set(key, hit);
3671
+ }
3672
+ return hit;
3673
+ }
3674
+ set(key, html) {
3675
+ const old = this.entries.get(key);
3676
+ if (old) {
3677
+ this.size -= weight(key, old);
3678
+ this.entries.delete(key);
3679
+ }
3680
+ const entry = { html };
3681
+ this.entries.set(key, entry);
3682
+ this.size += weight(key, entry);
3683
+ for (const [k, v] of this.entries) {
3684
+ if (this.size <= CACHE_BUDGET || k === key) break;
3685
+ this.entries.delete(k);
3686
+ this.size -= weight(k, v);
3687
+ }
3688
+ return entry;
3689
+ }
3690
+ }
3691
+ const weight = (key, entry) => key.length + (entry.html?.length ?? 0);
3692
+ const hosts = /* @__PURE__ */ new WeakMap();
3693
+ const drawingOwner = /* @__PURE__ */ new WeakMap();
3694
+ const caches = /* @__PURE__ */ new WeakMap();
3695
+ const inflight = /* @__PURE__ */ new WeakMap();
3696
+ const builtNodes = /* @__PURE__ */ new WeakMap();
3697
+ const lastGood = /* @__PURE__ */ new WeakMap();
3698
+ const asked = /* @__PURE__ */ new WeakMap();
3699
+ const lastOptions = /* @__PURE__ */ new WeakMap();
3700
+ const warned = /* @__PURE__ */ new WeakSet();
3701
+ const seen = /* @__PURE__ */ new WeakSet();
3702
+ const waitingRoot = /* @__PURE__ */ new WeakMap();
3703
+ const observers$1 = /* @__PURE__ */ new WeakMap();
3704
+ const observed = /* @__PURE__ */ new WeakMap();
3705
+ function cacheOf(renderer) {
3706
+ let cache = caches.get(renderer);
3707
+ if (!cache) {
3708
+ cache = new DrawingCache();
3709
+ caches.set(renderer, cache);
3710
+ }
3711
+ return cache;
3712
+ }
3713
+ function inflightOf(renderer) {
3714
+ let map = inflight.get(renderer);
3715
+ if (!map) {
3716
+ map = /* @__PURE__ */ new Map();
3717
+ inflight.set(renderer, map);
3718
+ }
3719
+ return map;
3720
+ }
3721
+ function mapOf(store, root) {
3722
+ let map = store.get(root);
3723
+ if (!map) {
3724
+ map = /* @__PURE__ */ new Map();
3725
+ store.set(root, map);
3726
+ }
3727
+ return map;
3728
+ }
3729
+ function warnOnce(renderer, error) {
3730
+ if (warned.has(renderer)) return;
3731
+ warned.add(renderer);
3732
+ console.warn(`[aparte] The ${renderer.languages.join("/")} renderer failed; the source is shown instead.`, error);
3733
+ }
3734
+ function languageOf$1(code) {
3735
+ for (const name of Array.from(code.classList)) {
3736
+ if (name.startsWith("language-")) return name.slice("language-".length).toLowerCase() || null;
3737
+ }
3738
+ return null;
3739
+ }
3740
+ function isDisplay(code) {
3741
+ if (code.classList.contains("math-display")) return true;
3742
+ if (code.classList.contains("math-inline")) return false;
3743
+ return code.parentElement?.tagName === "PRE";
3744
+ }
3745
+ function isMarkedOpen(code) {
3746
+ return code.hasAttribute(OPEN_ATTR) || code.parentElement?.tagName === "PRE" && code.parentElement.hasAttribute(OPEN_ATTR);
3747
+ }
3748
+ function keyOf(renderer, ctx) {
3749
+ let extra = "";
3750
+ try {
3751
+ extra = renderer.cacheKey?.(ctx) ?? "";
3752
+ } catch (error) {
3753
+ warnOnce(renderer, error);
3754
+ }
3755
+ return `${ctx.language}${ctx.display ? "d" : "i"}${extra}${ctx.source}`;
3756
+ }
3757
+ function isThenable(value) {
3758
+ return typeof value?.then === "function";
3759
+ }
3760
+ function boxOf(code) {
3761
+ return code.closest("pre") ?? hosts.get(code)?.drawing ?? code;
3762
+ }
3763
+ function grownBoxOf(code) {
3764
+ return code.closest("pre") ?? code.parentElement ?? code;
3765
+ }
3766
+ const plainRuns = /* @__PURE__ */ new Set();
3767
+ const refreshRuns = /* @__PURE__ */ new Map();
3768
+ let flushing = false;
3769
+ function schedule(root, refresh) {
3770
+ if (refresh) refreshRuns.set(root, refresh);
3771
+ else plainRuns.add(root);
3772
+ if (flushing) return;
3773
+ flushing = true;
3774
+ queueMicrotask(() => {
3775
+ flushing = false;
3776
+ const plain = [...plainRuns];
3777
+ const refreshes = [...refreshRuns];
3778
+ plainRuns.clear();
3779
+ refreshRuns.clear();
3780
+ for (const root2 of plain) rerun(root2);
3781
+ for (const [root2, options] of refreshes) if (root2.isConnected) renderCodeLanguages(root2, options);
3782
+ });
3783
+ }
3784
+ const waiters = /* @__PURE__ */ new WeakMap();
3785
+ function whenSettled(promise, root, refresh) {
3786
+ let roots = waiters.get(promise);
3787
+ if (!roots) {
3788
+ const waiting2 = /* @__PURE__ */ new Map();
3789
+ waiters.set(promise, waiting2);
3790
+ roots = waiting2;
3791
+ void promise.then(
3792
+ () => {
3793
+ for (const [r, options] of waiting2) schedule(r, options);
3794
+ waiting2.clear();
3795
+ },
3796
+ () => waiting2.clear()
3797
+ );
3798
+ }
3799
+ if (!roots.has(root) || refresh === void 0) roots.set(root, refresh);
3800
+ }
3801
+ let compensating = null;
3802
+ function scrollerOf$1(el2) {
3803
+ for (let node = el2.parentElement; node; node = node.parentElement) {
3804
+ const overflow = getComputedStyle(node).overflowY;
3805
+ if (overflow === "auto" || overflow === "scroll") return node;
3806
+ }
3807
+ return null;
3808
+ }
3809
+ function rerun(root) {
3810
+ if (!root.isConnected) return;
3811
+ const scroller = scrollerOf$1(root);
3812
+ const view = scroller ? scroller.getBoundingClientRect().top + (parseFloat(getComputedStyle(scroller).scrollPaddingTop) || 0) : 0;
3813
+ compensating = { scroller, top: view };
3814
+ try {
3815
+ renderCodeLanguages(root, lastOptions.get(root) ?? {});
3816
+ } finally {
3817
+ compensating = null;
3818
+ }
3819
+ }
3820
+ function deferred(code, root) {
3821
+ const target = boxOf(code);
3822
+ if (seen.has(target) || typeof IntersectionObserver === "undefined") return false;
3823
+ const scroller = scrollerOf$1(target);
3824
+ let set = observers$1.get(IntersectionObserver);
3825
+ if (!set) {
3826
+ set = { byScroller: /* @__PURE__ */ new WeakMap() };
3827
+ observers$1.set(IntersectionObserver, set);
3828
+ }
3829
+ let observer = scroller ? set.byScroller.get(scroller) : set.page;
3830
+ if (!observer) {
3831
+ const made = new IntersectionObserver((entries) => {
3832
+ for (const entry of entries) {
3833
+ const box = entry.target;
3834
+ if (box.isConnected && !entry.isIntersecting) continue;
3835
+ made.unobserve(box);
3836
+ const left = (observed.get(made) ?? 1) - 1;
3837
+ observed.set(made, left);
3838
+ if (left <= 0) {
3839
+ made.disconnect();
3840
+ if (scroller) set.byScroller.delete(scroller);
3841
+ else if (set.page === made) set.page = void 0;
3842
+ }
3843
+ if (!box.isConnected) continue;
3844
+ seen.add(box);
3845
+ const waiting2 = waitingRoot.get(box);
3846
+ if (waiting2) schedule(waiting2);
3847
+ }
3848
+ }, { root: scroller, rootMargin: "100% 0px" });
3849
+ observer = made;
3850
+ if (scroller) set.byScroller.set(scroller, made);
3851
+ else set.page = made;
3852
+ }
3853
+ if (waitingRoot.get(target) !== root) {
3854
+ waitingRoot.set(target, root);
3855
+ observed.set(observer, (observed.get(observer) ?? 0) + 1);
3856
+ observer.observe(target);
3857
+ }
3858
+ return true;
3859
+ }
3860
+ function fill(root, code, entry, renderer, ctx, key, move = true) {
3861
+ if (entry.html === null) {
3862
+ showSource(code, ctx.open);
3863
+ return;
3864
+ }
3865
+ const box = compensating ? grownBoxOf(code) : null;
3866
+ const before = box ? box.getBoundingClientRect() : null;
3867
+ const state = hosts.get(code);
3868
+ let drawing = state?.drawing;
3869
+ if (!drawing) {
3870
+ drawing = document.createElement("span");
3871
+ drawing.className = DRAWING_CLASS;
3872
+ if (ctx.display) drawing.setAttribute("data-aparte-display", "");
3873
+ code.after(drawing);
3874
+ drawingOwner.set(drawing, code);
3875
+ if (code.parentElement?.tagName === "PRE") code.parentElement.setAttribute(DRAWN_ATTR, "");
3876
+ }
3877
+ if (state?.entry !== entry || drawing.childNodes.length === 0) {
3878
+ let built = move ? builtNodes.get(root) : void 0;
3879
+ if (move && !built) {
3880
+ built = /* @__PURE__ */ new WeakMap();
3881
+ builtNodes.set(root, built);
3882
+ }
3883
+ const last = built?.get(entry);
3884
+ const movable = last && last.owner !== code && !last.owner.isConnected && code.isConnected && !last.drawing.isConnected && last.drawing.childNodes.length > 0;
3885
+ if (movable) {
3886
+ drawing.replaceChildren(...last.drawing.childNodes);
3887
+ last.drawing.remove();
3888
+ showSource(last.owner, false);
3889
+ } else {
3890
+ drawing.innerHTML = entry.html;
3891
+ try {
3892
+ renderer.relabel?.(drawing, ctx);
3893
+ } catch (error) {
3894
+ warnOnce(renderer, error);
3895
+ }
3896
+ }
3897
+ if (built) {
3898
+ if (state && state.entry !== entry && built.get(state.entry)?.drawing === drawing) built.delete(state.entry);
3899
+ built.set(entry, { drawing, owner: code });
3900
+ }
3901
+ }
3902
+ code.hidden = true;
3903
+ code.style.setProperty("display", "none");
3904
+ code.classList.remove(PENDING_CLASS);
3905
+ hosts.set(code, { renderer, key, drawing, entry, ctx });
3906
+ if (box && before && compensating) {
3907
+ const delta = box.getBoundingClientRect().height - before.height;
3908
+ if (delta > 0 && before.bottom <= compensating.top) {
3909
+ if (compensating.scroller) compensating.scroller.scrollTop += delta;
3910
+ else window.scrollBy(0, delta);
3911
+ }
3912
+ }
3913
+ }
3914
+ function showSource(code, pending2) {
3915
+ const state = hosts.get(code);
3916
+ if (state) {
3917
+ state.drawing.remove();
3918
+ hosts.delete(code);
3919
+ }
3920
+ if (code.parentElement?.tagName === "PRE") code.parentElement.removeAttribute(DRAWN_ATTR);
3921
+ code.hidden = false;
3922
+ code.style.removeProperty("display");
3923
+ code.classList.toggle(PENDING_CLASS, pending2);
3924
+ }
3925
+ function drawClosed(root, code, renderer, ctx, pos, refresh) {
3926
+ const key = keyOf(renderer, ctx);
3927
+ let state = hosts.get(code);
3928
+ if (state && state.renderer === renderer && state.key === key && state.drawing.childNodes.length > 0) return;
3929
+ const cache = cacheOf(renderer);
3930
+ const hit = cache.get(key);
3931
+ if (hit) {
3932
+ fill(root, code, hit, renderer, ctx, key, !refresh);
3933
+ return;
3934
+ }
3935
+ if (!state && !refresh) {
3936
+ const provisional = lastGood.get(root)?.get(pos);
3937
+ if (provisional && ctx.source.startsWith(provisional.source)) fill(root, code, provisional, renderer, ctx, null);
3938
+ state = hosts.get(code);
3939
+ }
3940
+ if (renderer.lazy && !refresh && !state && deferred(code, root)) return;
3941
+ const pending2 = inflightOf(renderer);
3942
+ const running = pending2.get(key);
3943
+ if (running) {
3944
+ whenSettled(running, root, refresh);
3945
+ return;
3946
+ }
3947
+ let result;
3948
+ try {
3949
+ result = renderer.render(ctx);
3950
+ } catch (error) {
3951
+ warnOnce(renderer, error);
3952
+ result = null;
3953
+ }
3954
+ if (!isThenable(result)) {
3955
+ fill(root, code, cache.set(key, result ?? null), renderer, ctx, key, !refresh);
3956
+ return;
3957
+ }
3958
+ const settled2 = result.then((html) => {
3959
+ pending2.delete(key);
3960
+ cache.set(key, html ?? null);
3961
+ return html;
3962
+ }, (error) => {
3963
+ pending2.delete(key);
3964
+ warnOnce(renderer, error);
3965
+ throw error;
3966
+ });
3967
+ pending2.set(key, settled2);
3968
+ void settled2.then(() => schedule(root, refresh), () => {
3969
+ });
3970
+ }
3971
+ function drawOpen(root, code, renderer, ctx, pos) {
3972
+ const good = mapOf(lastGood, root);
3973
+ const previous = good.get(pos);
3974
+ if (previous && ctx.source.startsWith(previous.source)) {
3975
+ if (hosts.get(code)?.entry !== previous) fill(root, code, previous, renderer, ctx, null);
3976
+ } else {
3977
+ good.delete(pos);
3978
+ showSource(code, true);
3979
+ }
3980
+ const requests = mapOf(asked, root);
3981
+ if (requests.get(pos) === ctx.source) return;
3982
+ requests.set(pos, ctx.source);
3983
+ const forget = () => {
3984
+ if (requests.get(pos) === ctx.source) requests.delete(pos);
3985
+ };
3986
+ const keep = (html) => {
3987
+ if (html === null || html === void 0) return false;
3988
+ const current = good.get(pos);
3989
+ if (current && !ctx.source.startsWith(current.source)) return false;
3990
+ good.set(pos, { source: ctx.source, html });
3991
+ return true;
3992
+ };
3993
+ let result;
3994
+ try {
3995
+ result = renderer.render(ctx);
3996
+ } catch {
3997
+ result = null;
3998
+ }
3999
+ if (!isThenable(result)) {
4000
+ if (keep(result)) fill(root, code, good.get(pos), renderer, ctx, null);
4001
+ else if (result == null) forget();
4002
+ return;
4003
+ }
4004
+ result.then((html) => {
4005
+ if (keep(html)) schedule(root);
4006
+ else if (html == null) forget();
4007
+ }, forget);
4008
+ }
4009
+ function renderCodeLanguages(root, options = {}) {
4010
+ if (typeof document === "undefined") return;
4011
+ const { streaming = false, refresh = false, language } = options;
4012
+ if (!refresh) {
4013
+ lastOptions.set(root, { streaming });
4014
+ if (!streaming) asked.delete(root);
4015
+ if (!contextConfig(root).hasCodeLanguageRenderer()) {
4016
+ if (root.querySelector(`.${DRAWING_CLASS}`)) unrenderCodeLanguages(root);
4017
+ return;
4018
+ }
4019
+ }
4020
+ const placeholders = Array.from(root.querySelectorAll('code[class*="language-"]')).filter((code) => !code.closest(`.${DRAWING_CLASS}`));
4021
+ const ranks = /* @__PURE__ */ new Map();
4022
+ placeholders.forEach((code, index) => {
4023
+ const lang = languageOf$1(code);
4024
+ if (!lang || language && lang !== language) return;
4025
+ const cfg = refresh ? contextConfig(code) : contextConfig(root);
4026
+ const renderer = cfg.getCodeLanguageRenderer(lang);
4027
+ const state = hosts.get(code);
4028
+ if (refresh && (!state || state.key === null)) return;
4029
+ if (!renderer) {
4030
+ if (state) showSource(code, false);
4031
+ return;
4032
+ }
4033
+ const display = isDisplay(code);
4034
+ const rankKey = `${lang}|${display ? "d" : "i"}`;
4035
+ const rank = ranks.get(rankKey) ?? 0;
4036
+ ranks.set(rankKey, rank + 1);
4037
+ const pos = `${rankKey}|${rank}`;
4038
+ const source = code.textContent ?? "";
4039
+ if (!source.trim()) {
4040
+ if (state) showSource(code, false);
4041
+ return;
4042
+ }
4043
+ const open = streaming && (isMarkedOpen(code) || index === placeholders.length - 1);
4044
+ const ctx = { language: lang, source, display, open, host: code, config: cfg };
4045
+ if (open) drawOpen(root, code, renderer, ctx, pos);
4046
+ else drawClosed(root, code, renderer, ctx, pos, refresh ? options : void 0);
4047
+ });
4048
+ }
4049
+ function unrenderCodeLanguages(root) {
4050
+ for (const drawing of Array.from(root.querySelectorAll(`.${DRAWING_CLASS}`))) {
4051
+ const code = drawingOwner.get(drawing);
4052
+ if (code) showSource(code, false);
4053
+ else drawing.remove();
4054
+ }
4055
+ }
4056
+ function relabelCodeLanguages(root) {
4057
+ for (const drawing of Array.from(root.querySelectorAll(`.${DRAWING_CLASS}`))) {
4058
+ const code = drawingOwner.get(drawing);
4059
+ const state = code ? hosts.get(code) : void 0;
4060
+ if (!state) continue;
4061
+ try {
4062
+ state.renderer.relabel?.(drawing, state.ctx);
4063
+ } catch (error) {
4064
+ warnOnce(state.renderer, error);
4065
+ }
4066
+ }
4067
+ }
4068
+ function isDrawnLanguage(language, element) {
4069
+ return !!language && contextConfig(element).hasCodeLanguageRenderer(language);
4070
+ }
4071
+ const CHIP_CLASS = "aparte-citation";
4072
+ const MARKER_CLASS = "aparte-citation-marker";
4073
+ const WORD = /[\p{L}\p{N}]/u;
4074
+ const TAILS = [24, 12, 6];
4075
+ const INLINE = /* @__PURE__ */ new Set(["A", "ABBR", "B", "CITE", "CODE", "DEL", "EM", "I", "INS", "KBD", "MARK", "Q", "S", "SMALL", "SPAN", "STRONG", "SUB", "SUP", "U"]);
4076
+ const CLOSING = /[.,;:!?)\]}»"'’”…。、,.!?:;」』)】》،؛؟]/;
4077
+ const THIN = /[\u00a0\u202f]/;
4078
+ const chipSources = /* @__PURE__ */ new WeakMap();
4079
+ const chipRoots = /* @__PURE__ */ new WeakMap();
4080
+ const wired = /* @__PURE__ */ new WeakSet();
4081
+ const drawn = /* @__PURE__ */ new WeakMap();
4082
+ let focused = null;
4083
+ function webUrl(source) {
4084
+ const url = source.url?.trim();
4085
+ return url && /^https?:\/\//i.test(url) && isSafeUrl(url, "a") ? url : void 0;
4086
+ }
4087
+ function sourceDomain(source) {
4088
+ const url = webUrl(source);
4089
+ if (url) {
4090
+ try {
4091
+ return new URL(url).hostname.replace(/^www\./, "");
4092
+ } catch {
4093
+ }
4094
+ }
4095
+ return source.title ?? "";
4096
+ }
4097
+ function chipLabel(sources2) {
4098
+ const first = sourceDomain(sources2[0]) || "?";
4099
+ return sources2.length > 1 ? `${first} +${sources2.length - 1}` : first;
4100
+ }
4101
+ function sourcesCount(config, n) {
4102
+ const locale = config.getLocale();
4103
+ return n === 1 ? locale.sourcesOne ?? "1 source" : (locale.sourcesCount ?? "{n} sources").replace("{n}", () => String(n));
4104
+ }
4105
+ function decodeEntity(entity) {
4106
+ if (typeof document === "undefined") return "";
4107
+ const area = document.createElement("textarea");
4108
+ area.innerHTML = entity;
4109
+ return area.value;
4110
+ }
4111
+ function shown(markdown) {
4112
+ return markdown.replace(/^[ \t]*(?:>[ \t]*)*(?:\d{1,9}[.)]|[*+-])[ \t]+(?:\[[ xX]\][ \t]+)?/gm, "").replace(/<!--[\s\S]*?-->/g, "").replace(/!\[[^\]\n]*\]\([^)\n]*\)/g, "").replace(/<([a-z][a-z0-9+.-]*:[^>\s]+)>/gi, "$1").replace(/\]\([^)\n]*\)/g, "]").replace(/<\/?[A-Za-z][^>\n]*>/g, "").replace(/&(?:#\d+|#x[0-9a-f]+|[a-z][a-z0-9]*);/gi, decodeEntity);
4113
+ }
4114
+ function visible(markdown) {
4115
+ const source = markdown.replace(/^ {0,3}(?:`{3,}|~{3,})[^\n]*$/gm, "");
4116
+ let text = "";
4117
+ let at = 0;
4118
+ for (const m of source.matchAll(/(`+)([^`][\s\S]*?)\1/g)) {
4119
+ text += shown(source.slice(at, m.index)) + m[2];
4120
+ at = (m.index ?? 0) + m[0].length;
4121
+ }
4122
+ text += shown(source.slice(at));
4123
+ let out = "";
4124
+ for (const ch of text) if (WORD.test(ch)) out += ch;
4125
+ return out;
4126
+ }
4127
+ function renderedText(root) {
4128
+ let text = "";
4129
+ const ends = [];
4130
+ const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
4131
+ // A drawing (a formula, a diagram) shows its source differently; its placeholder, hidden
4132
+ // beside it, still holds the source as written.
4133
+ acceptNode: (n) => n.parentElement?.closest(`.aparte-code-drawing, .${CHIP_CLASS}`) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT
4134
+ });
4135
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
4136
+ const data = node.data;
4137
+ for (let i = 0; i < data.length; ) {
4138
+ const width = (data.codePointAt(i) ?? 0) > 65535 ? 2 : 1;
4139
+ const ch = data.slice(i, i + width);
4140
+ i += width;
4141
+ if (!WORD.test(ch)) continue;
4142
+ text += ch;
4143
+ for (let k = 0; k < width; k++) ends.push([node, i]);
4144
+ }
4145
+ }
4146
+ return { text, ends };
4147
+ }
4148
+ function occurrences(haystack, needle) {
4149
+ let n = 0;
4150
+ for (let i = haystack.indexOf(needle); i >= 0; i = haystack.indexOf(needle, i + 1)) n++;
4151
+ return n;
4152
+ }
4153
+ function locate(content, citation, rendered) {
4154
+ const prefix = visible(content.slice(0, Math.max(0, Math.min(content.length, citation.end))));
4155
+ if (!prefix) return null;
4156
+ for (const size of TAILS) {
4157
+ const tail = prefix.slice(-size);
4158
+ const n = occurrences(prefix, tail);
4159
+ let at = -1;
4160
+ for (let k = 0; k < n && (k === 0 || at >= 0); k++) at = rendered.text.indexOf(tail, at + 1);
4161
+ if (at >= 0) return rendered.ends[at + tail.length - 1] ?? null;
4162
+ if (tail.length === prefix.length) break;
4163
+ }
4164
+ return null;
4165
+ }
4166
+ function closingRun(data, from) {
4167
+ let i = from;
4168
+ while (i < data.length && (CLOSING.test(data[i]) || THIN.test(data[i]) && CLOSING.test(data[i + 1] ?? ""))) i++;
4169
+ return i - from;
4170
+ }
4171
+ function placeChip(root, chip, node, offset) {
4172
+ const pre = node.parentElement?.closest("pre");
4173
+ if (pre && root.contains(pre)) {
4174
+ pre.after(chip);
4175
+ return;
4176
+ }
4177
+ let outer = null;
4178
+ for (let el2 = node.parentElement; el2 && el2 !== root && INLINE.has(el2.tagName); el2 = el2.parentElement) outer = el2;
4179
+ if (!outer) {
4180
+ node.splitText(offset + closingRun(node.data, offset));
4181
+ node.after(chip);
4182
+ return;
4183
+ }
4184
+ let after = outer;
4185
+ while (after.nextSibling instanceof Element && after.nextSibling.classList.contains("aparte-code-drawing")) after = after.nextSibling;
4186
+ const next = after.nextSibling;
4187
+ if (next instanceof Text) {
4188
+ const k = closingRun(next.data, 0);
4189
+ if (k > 0) {
4190
+ next.splitText(k);
4191
+ after = next;
4192
+ }
4193
+ }
4194
+ after.parentNode.insertBefore(chip, after.nextSibling);
4195
+ }
4196
+ function replaceMarker(chip, node, offset, marker) {
4197
+ const hide = (el2) => {
4198
+ const hidden = document.createElement("span");
4199
+ hidden.className = MARKER_CLASS;
4200
+ hidden.hidden = true;
4201
+ el2.parentNode.insertBefore(hidden, el2);
4202
+ hidden.append(el2);
4203
+ hidden.after(chip);
4204
+ };
4205
+ const start = node.data.lastIndexOf(marker, offset);
4206
+ if (start >= 0 && start + marker.length >= offset) {
4207
+ const rest = node.splitText(start);
4208
+ rest.splitText(marker.length);
4209
+ hide(rest);
4210
+ return true;
4211
+ }
4212
+ const parent = node.parentElement;
4213
+ const letters = marker.replace(/^\[|\]$/g, "");
4214
+ if (parent && INLINE.has(parent.tagName) && parent.textContent?.trim() === letters) {
4215
+ hide(parent);
4216
+ return true;
4217
+ }
4218
+ return false;
4219
+ }
4220
+ function makeChip(sources2, config) {
4221
+ const chip = document.createElement("button");
4222
+ chip.type = "button";
4223
+ chip.className = "aparte-citation aparte-tag aparte-tag--sm";
4224
+ chip.setAttribute("aria-haspopup", "dialog");
4225
+ chip.setAttribute("aria-expanded", "false");
4226
+ chipSources.set(chip, sources2);
4227
+ labelChip(chip, config);
4228
+ return chip;
4229
+ }
4230
+ function labelChip(chip, config) {
4231
+ const sources2 = chipSources.get(chip) ?? [];
4232
+ const label = chipLabel(sources2);
4233
+ chip.dataset.label = label;
4234
+ chip.setAttribute("aria-label", `${label}, ${sourcesCount(config, sources2.length)}`);
4235
+ }
4236
+ function unrenderCitations(root) {
4237
+ const parents = /* @__PURE__ */ new Set();
4238
+ for (const chip of Array.from(root.querySelectorAll(`.${CHIP_CLASS}`))) {
4239
+ if (chip.parentNode) parents.add(chip.parentNode);
4240
+ chip.remove();
4241
+ }
4242
+ for (const marker of Array.from(root.querySelectorAll(`.${MARKER_CLASS}`))) {
4243
+ if (marker.parentNode) parents.add(marker.parentNode);
4244
+ marker.replaceWith(...Array.from(marker.childNodes));
4245
+ }
4246
+ for (const parent of parents) parent.normalize();
4247
+ drawn.delete(root);
4248
+ }
4249
+ function renderCitations(root, segment) {
4250
+ if (typeof document === "undefined") return;
4251
+ const citations = segment.citations ?? [];
4252
+ const sources2 = new Map((segment.sources ?? []).map((s) => [s.id, s]));
4253
+ const signature = JSON.stringify([segment.content, citations, [...sources2.values()].map((s) => [s.id, s.url, s.title, s.snippet])]);
4254
+ const before = Array.from(root.querySelectorAll(`.${CHIP_CLASS}`));
4255
+ const last = drawn.get(root);
4256
+ if (last && last.signature === signature && last.count === before.length) return;
4257
+ const active = document.activeElement;
4258
+ const focusedAt = focused?.root === root && (active === focused.chip || (!active || active === document.body) && !focused.chip.isConnected) ? focused.at : -1;
4259
+ const openAt = card?.root === root ? card.chip.isConnected ? before.indexOf(card.chip) : card.at : -1;
4260
+ unrenderCitations(root);
4261
+ if (citations.length === 0 || sources2.size === 0) {
4262
+ drawn.set(root, { signature, count: 0 });
4263
+ if (openAt >= 0) closeCard(false);
4264
+ return;
4265
+ }
4266
+ const config = contextConfig(root);
4267
+ if (!wired.has(root)) {
4268
+ wired.add(root);
4269
+ root.addEventListener("click", (event) => {
4270
+ const chip = event.target?.closest?.(`.${CHIP_CLASS}`);
4271
+ if (!chip || !root.contains(chip)) return;
4272
+ event.preventDefault();
4273
+ toggleCard(chip);
4274
+ });
4275
+ root.addEventListener("focusin", (event) => {
4276
+ const chip = event.target;
4277
+ if (chip.classList?.contains(CHIP_CLASS)) focused = { root, chip, at: Array.from(root.querySelectorAll(`.${CHIP_CLASS}`)).indexOf(chip) };
4278
+ });
4279
+ root.addEventListener("focusout", (event) => {
4280
+ if (focused?.root === root && event.relatedTarget) focused = null;
4281
+ });
4282
+ }
4283
+ const rendered = renderedText(root);
4284
+ const spots = /* @__PURE__ */ new Map();
4285
+ for (const citation of citations) {
4286
+ const cited = citation.sources.map((id) => sources2.get(id)).filter((s) => !!s);
4287
+ if (cited.length === 0) continue;
4288
+ const found = locate(segment.content, citation, rendered);
4289
+ if (!found) continue;
4290
+ const key = rendered.ends.indexOf(found);
4291
+ const marker = citation.marker && citation.start !== void 0 ? segment.content.slice(citation.start, citation.end) : null;
4292
+ const spot = spots.get(key) ?? { node: found[0], offset: found[1], marker, sources: [] };
4293
+ for (const s of cited) if (!spot.sources.includes(s)) spot.sources.push(s);
4294
+ spots.set(key, spot);
4295
+ }
4296
+ const ordered = [...spots.values()].sort((a, b) => {
4297
+ if (a.node === b.node) return b.offset - a.offset;
4298
+ return a.node.compareDocumentPosition(b.node) & Node.DOCUMENT_POSITION_FOLLOWING ? 1 : -1;
4299
+ });
4300
+ for (const spot of ordered) {
4301
+ const chip = makeChip(spot.sources, config);
4302
+ chipRoots.set(chip, root);
4303
+ if (spot.marker && replaceMarker(chip, spot.node, spot.offset, spot.marker)) continue;
4304
+ placeChip(root, chip, spot.node, spot.offset);
4305
+ }
4306
+ const after = Array.from(root.querySelectorAll(`.${CHIP_CLASS}`));
4307
+ drawn.set(root, { signature, count: after.length });
4308
+ if (focusedAt >= 0) {
4309
+ if (after[focusedAt]) after[focusedAt].focus({ preventScroll: true });
4310
+ else focused = null;
4311
+ }
4312
+ if (openAt >= 0 && card) {
4313
+ const chip = after[openAt];
4314
+ if (chip) {
4315
+ card.chip = chip;
4316
+ card.at = openAt;
4317
+ chip.setAttribute("aria-expanded", "true");
4318
+ chip.setAttribute("aria-controls", card.el.id);
4319
+ } else {
4320
+ closeCard(false);
4321
+ }
4322
+ }
4323
+ }
4324
+ function relabelCitations(root) {
4325
+ const config = contextConfig(root);
4326
+ for (const chip of Array.from(root.querySelectorAll(`.${CHIP_CLASS}`))) labelChip(chip, config);
4327
+ }
4328
+ let card = null;
4329
+ let cards = 0;
4330
+ function toggleCard(chip) {
4331
+ if (card?.chip === chip) closeCard(true);
4332
+ else openCard(chip);
4333
+ }
4334
+ function openCard(chip) {
4335
+ closeCard(false);
4336
+ const sources2 = chipSources.get(chip) ?? [];
4337
+ if (sources2.length === 0) return;
4338
+ const root = chipRoots.get(chip) ?? chip.parentElement;
4339
+ const at = Array.from(root.querySelectorAll(`.${CHIP_CLASS}`)).indexOf(chip);
4340
+ const config = contextConfig(chip);
4341
+ const el2 = document.createElement("div");
4342
+ el2.className = "aparte-citation-card aparte-popover";
4343
+ el2.id = `aparte-citation-card-${++cards}`;
4344
+ el2.setAttribute("role", "dialog");
4345
+ el2.setAttribute("aria-label", config.getLocale().sourcesCard ?? "Sources");
4346
+ const body = document.createElement("div");
4347
+ body.className = "aparte-citation-card__body";
4348
+ const status = document.createElement("p");
4349
+ status.className = "aparte-sr-only";
4350
+ status.setAttribute("role", "status");
4351
+ el2.append(body, status);
4352
+ const top = typeof el2.showPopover === "function";
4353
+ if (top) el2.popover = "manual";
4354
+ (chip.closest("aparte-chat-viewport")?.parentElement ?? chip.ownerDocument.body).append(el2);
4355
+ if (top) el2.showPopover();
4356
+ chip.setAttribute("aria-expanded", "true");
4357
+ chip.setAttribute("aria-controls", el2.id);
4358
+ const watch = typeof MutationObserver === "function" ? new MutationObserver(guardCard) : null;
4359
+ watch?.observe(chip.ownerDocument.body, { childList: true, subtree: true });
4360
+ card = { root, chip, at, el: el2, body, status, sources: sources2, index: 0, config, watch };
4361
+ drawCard();
4362
+ placeCard();
4363
+ document.addEventListener("keydown", onKey, true);
4364
+ document.addEventListener("pointerdown", onPointer, true);
4365
+ window.addEventListener("scroll", onScroll, true);
4366
+ window.addEventListener("resize", placeCard);
4367
+ el2.addEventListener("focusout", onFocusOut);
4368
+ el2.addEventListener("keydown", onCardKey);
4369
+ focusIn(el2);
4370
+ }
4371
+ function focusIn(el2) {
4372
+ (el2.querySelector("a") ?? el2.querySelector("button:not([disabled])"))?.focus();
4373
+ }
4374
+ function closeCard(returnFocus) {
4375
+ if (!card) return;
4376
+ const { chip, el: el2, watch } = card;
4377
+ card = null;
4378
+ watch?.disconnect();
4379
+ el2.remove();
4380
+ chip.setAttribute("aria-expanded", "false");
4381
+ chip.removeAttribute("aria-controls");
4382
+ document.removeEventListener("keydown", onKey, true);
4383
+ document.removeEventListener("pointerdown", onPointer, true);
4384
+ window.removeEventListener("scroll", onScroll, true);
4385
+ window.removeEventListener("resize", placeCard);
4386
+ if (returnFocus && chip.isConnected) chip.focus();
4387
+ }
4388
+ function guardCard() {
4389
+ if (card && !card.chip.isConnected) closeCard(false);
4390
+ }
4391
+ function onKey(event) {
4392
+ if (event.key !== "Escape" || !card) return;
4393
+ event.preventDefault();
4394
+ closeCard(true);
4395
+ }
4396
+ function onCardKey(event) {
4397
+ if (event.key !== "Tab" || !card) return;
4398
+ const controls = Array.from(card.el.querySelectorAll("a[href], button:not([disabled])"));
4399
+ const edge = event.shiftKey ? controls[0] : controls[controls.length - 1];
4400
+ if (document.activeElement !== edge) return;
4401
+ event.preventDefault();
4402
+ closeCard(true);
4403
+ }
4404
+ function onPointer(event) {
4405
+ if (!card) return;
4406
+ const target = event.target;
4407
+ if (target && (card.el.contains(target) || card.chip.contains(target))) return;
4408
+ closeCard(false);
4409
+ }
4410
+ function onFocusOut(event) {
4411
+ if (!card) return;
4412
+ const to = event.relatedTarget;
4413
+ if (to && (card.el.contains(to) || card.chip.contains(to))) return;
4414
+ if (to) closeCard(false);
4415
+ }
4416
+ function scrollerOf(el2) {
4417
+ for (let node = el2.parentElement; node; node = node.parentElement) {
4418
+ const overflow = getComputedStyle(node).overflowY;
4419
+ if (overflow === "auto" || overflow === "scroll") return node;
4420
+ }
4421
+ return null;
4422
+ }
4423
+ function onScroll() {
4424
+ if (!card) return;
4425
+ const scroller = scrollerOf(card.chip);
4426
+ if (scroller) {
4427
+ const view = scroller.getBoundingClientRect();
4428
+ const at = card.chip.getBoundingClientRect();
4429
+ if (at.bottom < view.top || at.top > view.bottom) {
4430
+ closeCard(false);
4431
+ return;
4432
+ }
4433
+ }
4434
+ placeCard();
4435
+ }
4436
+ function placeCard() {
4437
+ if (!card) return;
4438
+ const { chip, el: el2 } = card;
4439
+ if (!chip.isConnected) {
4440
+ closeCard(false);
4441
+ return;
4442
+ }
4443
+ const anchor = chip.getBoundingClientRect();
4444
+ el2.style.left = "0px";
4445
+ el2.style.top = "0px";
4446
+ const origin = el2.getBoundingClientRect();
4447
+ const gap = 6;
4448
+ const rtl = getComputedStyle(chip).direction === "rtl";
4449
+ const start = rtl ? anchor.right - el2.offsetWidth : anchor.left;
4450
+ const left = Math.max(8, Math.min(start, window.innerWidth - el2.offsetWidth - 8));
4451
+ let top = anchor.bottom + gap;
4452
+ if (top + el2.offsetHeight > window.innerHeight - 8 && anchor.top - el2.offsetHeight - gap > 8) top = anchor.top - el2.offsetHeight - gap;
4453
+ el2.style.left = `${left - origin.left}px`;
4454
+ el2.style.top = `${top - origin.top}px`;
4455
+ }
4456
+ function drawCard() {
4457
+ if (!card) return;
4458
+ const { el: el2, body, status, sources: sources2, index, config } = card;
4459
+ const locale = config.getLocale();
4460
+ const source = sources2[index];
4461
+ const focused2 = el2.contains(document.activeElement) ? document.activeElement.dataset.aparteCardPart : void 0;
4462
+ body.replaceChildren();
4463
+ if (sources2.length > 1) {
4464
+ const pager = document.createElement("div");
4465
+ pager.className = "aparte-citation-card__pager";
4466
+ const prev = pagerButton(locale.sourcePrevious ?? "Previous source", config.getIcon("prevBranch"), "prev", index === 0, () => turn(-1));
4467
+ const position = document.createElement("span");
4468
+ position.className = "aparte-citation-card__position";
4469
+ position.textContent = `${index + 1}/${sources2.length}`;
4470
+ position.setAttribute("aria-hidden", "true");
4471
+ const next = pagerButton(locale.sourceNext ?? "Next source", config.getIcon("nextBranch"), "next", index === sources2.length - 1, () => turn(1));
4472
+ pager.append(prev, position, next);
4473
+ body.append(pager);
4474
+ }
4475
+ const url = webUrl(source);
4476
+ const title = source.title || sourceDomain(source) || source.url || "";
4477
+ if (url) {
4478
+ const link = document.createElement("a");
4479
+ link.className = "aparte-citation-card__title";
4480
+ link.href = url;
4481
+ link.target = "_blank";
4482
+ link.rel = "noopener noreferrer";
4483
+ link.dataset.aparteCardPart = "link";
4484
+ link.textContent = title;
4485
+ const hint = document.createElement("span");
4486
+ hint.className = "aparte-sr-only";
4487
+ hint.textContent = ` ${locale.opensInNewTab ?? "(opens in a new tab)"}`;
4488
+ link.append(hint);
4489
+ body.append(link);
4490
+ } else {
4491
+ const plain = document.createElement("p");
4492
+ plain.className = "aparte-citation-card__title";
4493
+ plain.textContent = title;
4494
+ body.append(plain);
4495
+ }
4496
+ const domain = sourceDomain(source);
4497
+ if (domain && domain !== title) {
4498
+ const p = document.createElement("p");
4499
+ p.className = "aparte-citation-card__domain";
4500
+ p.textContent = domain;
4501
+ body.append(p);
4502
+ }
4503
+ if (source.snippet) {
4504
+ const p = document.createElement("p");
4505
+ p.className = "aparte-citation-card__snippet";
4506
+ p.textContent = source.snippet;
4507
+ body.append(p);
4508
+ }
4509
+ if (sources2.length > 1) {
4510
+ status.textContent = (locale.sourcePosition ?? "Source {i} of {n}").replace("{i}", () => String(index + 1)).replace("{n}", () => String(sources2.length));
4511
+ }
4512
+ if (focused2) {
4513
+ const back = el2.querySelector(`[data-aparte-card-part="${focused2}"]`);
4514
+ if (back && !back.disabled) back.focus();
4515
+ else (el2.querySelector(".aparte-citation-card__pager button:not([disabled])") ?? el2.querySelector("a"))?.focus();
4516
+ }
4517
+ }
4518
+ function pagerButton(label, icon, part, disabled, act) {
4519
+ const button = document.createElement("button");
4520
+ button.type = "button";
4521
+ button.className = "aparte-btn aparte-btn--icon aparte-btn--sm";
4522
+ button.setAttribute("aria-label", label);
4523
+ button.dataset.aparteCardPart = part;
4524
+ button.disabled = disabled;
4525
+ button.innerHTML = icon;
4526
+ button.addEventListener("click", act);
4527
+ return button;
4528
+ }
4529
+ function turn(step) {
4530
+ if (!card) return;
4531
+ card.index = Math.max(0, Math.min(card.sources.length - 1, card.index + step));
4532
+ drawCard();
4533
+ placeCard();
4534
+ }
4535
+ function renderSourceList(container, after, sources2, config) {
4536
+ let list = container.querySelector(":scope > .aparte-sources");
4537
+ const unique = [];
4538
+ const seen2 = /* @__PURE__ */ new Set();
4539
+ for (const s of sources2) {
4540
+ const key2 = s.url ?? `#${s.id}${s.title ?? ""}`;
4541
+ if (seen2.has(key2)) continue;
4542
+ seen2.add(key2);
4543
+ unique.push(s);
4544
+ }
4545
+ if (unique.length === 0) {
4546
+ list?.remove();
4547
+ return;
4548
+ }
4549
+ const hintText = config.getLocale().opensInNewTab ?? "(opens in a new tab)";
4550
+ const key = [hintText, ...unique.map((s) => `${s.url ?? s.id}${s.title ?? ""}`)].join("");
4551
+ if (!list) {
4552
+ list = document.createElement("details");
4553
+ list.className = "aparte-sources";
4554
+ after.after(list);
4555
+ } else if (list.dataset.aparteKey === key) {
4556
+ list.querySelector("summary").textContent = sourcesCount(config, unique.length);
4557
+ return;
4558
+ }
4559
+ list.dataset.aparteKey = key;
4560
+ const summary = document.createElement("summary");
4561
+ summary.className = "aparte-sources__summary";
4562
+ summary.textContent = sourcesCount(config, unique.length);
4563
+ const items = document.createElement("ol");
4564
+ items.className = "aparte-sources__list";
4565
+ for (const s of unique) {
4566
+ const item = document.createElement("li");
4567
+ item.className = "aparte-sources__item";
4568
+ const domain = sourceDomain(s);
4569
+ const title = s.title || domain || s.url || "";
4570
+ const url = webUrl(s);
4571
+ if (url) {
4572
+ const link = document.createElement("a");
4573
+ link.href = url;
4574
+ link.target = "_blank";
4575
+ link.rel = "noopener noreferrer";
4576
+ link.textContent = title;
4577
+ const hint = document.createElement("span");
4578
+ hint.className = "aparte-sr-only";
4579
+ hint.textContent = ` ${hintText}`;
4580
+ link.append(hint);
4581
+ item.append(link);
4582
+ } else {
4583
+ item.append(title);
4584
+ }
4585
+ if (domain && domain !== title) {
4586
+ const d = document.createElement("span");
4587
+ d.className = "aparte-sources__domain";
4588
+ d.textContent = domain;
4589
+ item.append(" ", d);
4590
+ }
4591
+ items.append(item);
4592
+ }
4593
+ list.replaceChildren(summary, items);
4594
+ }
4595
+ const settled = /* @__PURE__ */ new WeakMap();
3512
4596
  const ONE_SHOT_PROBE = "<i>a</i>";
3513
4597
  function hasOneShotMarkdownProvider() {
3514
4598
  return contextConfig().renderMarkdown(ONE_SHOT_PROBE) !== escapeHtml(ONE_SHOT_PROBE);
3515
4599
  }
3516
4600
  function writeStreamedMarkdown(host2, contentEl, content, streaming) {
4601
+ writeMarkdown(host2, contentEl, content, streaming);
4602
+ renderCodeLanguages(contentEl, { streaming });
4603
+ }
4604
+ function writeMarkdown(host2, contentEl, content, streaming) {
4605
+ const cfg = contextConfig();
3517
4606
  if (streaming) {
4607
+ settled.delete(contentEl);
3518
4608
  if (host2._aparteSmd === void 0) {
3519
- settledFromParser.delete(contentEl);
3520
4609
  const renderer = contextConfig().createStreamingMarkdownRenderer(contentEl);
3521
4610
  if (renderer) {
3522
4611
  contentEl.textContent = "";
@@ -3544,15 +4633,22 @@ function writeStreamedMarkdown(host2, contentEl, content, streaming) {
3544
4633
  smd.renderer.end();
3545
4634
  host2._aparteSmd = void 0;
3546
4635
  if (!hasOneShotMarkdownProvider()) {
3547
- contentEl.innerHTML = contextConfig().sanitizeHtml(contentEl.innerHTML);
3548
- settledFromParser.set(contentEl, content);
4636
+ unrenderCodeLanguages(contentEl);
4637
+ unrenderCitations(contentEl);
4638
+ contentEl.innerHTML = cfg.sanitizeHtml(contentEl.innerHTML);
4639
+ settled.set(contentEl, { content, config: cfg, version: renderingVersionOf(cfg), writer: "parser" });
3549
4640
  return;
3550
4641
  }
3551
- } else if (settledFromParser.get(contentEl) === content && !hasOneShotMarkdownProvider()) {
3552
- return;
4642
+ } else {
4643
+ const last = settled.get(contentEl);
4644
+ if (last?.content === content) {
4645
+ if (last.writer === "parser" && !hasOneShotMarkdownProvider()) return;
4646
+ if (last.writer === "markdown" && last.config === cfg && last.version === renderingVersionOf(cfg)) return;
4647
+ }
3553
4648
  }
3554
- settledFromParser.delete(contentEl);
3555
- contentEl.innerHTML = contextConfig().renderMarkdown(content);
4649
+ contentEl.innerHTML = cfg.renderMarkdown(content);
4650
+ if (streaming) settled.delete(contentEl);
4651
+ else settled.set(contentEl, { content, config: cfg, version: renderingVersionOf(cfg), writer: "markdown" });
3556
4652
  }
3557
4653
  function highlightMarkdownFences(contentEl) {
3558
4654
  if (!contextConfig().hasHighlightProvider()) return;
@@ -3561,14 +4657,20 @@ function highlightMarkdownFences(contentEl) {
3561
4657
  const pre = block.parentElement;
3562
4658
  if (!pre) continue;
3563
4659
  const lang = Array.from(block.classList).find((c) => c.startsWith("language-"))?.slice("language-".length) ?? "";
4660
+ if (isDrawnLanguage(lang, contentEl) || block.closest(".aparte-code-drawing")) continue;
3564
4661
  const source = block.textContent ?? "";
3565
4662
  block.setAttribute("data-aparte-highlighted", "");
3566
- void contextConfig().highlightCode(source, lang).then((html) => {
3567
- if (pre.isConnected || pre.parentElement) pre.outerHTML = html;
3568
- }).catch(() => {
3569
- });
4663
+ void contextConfig().highlightCode(source, lang, { fallback: false }).then((html) => {
4664
+ if (pre.isConnected || pre.parentElement) replaceHighlighted(pre, html);
4665
+ }).catch(() => block.removeAttribute("data-aparte-highlighted"));
3570
4666
  }
3571
4667
  }
4668
+ function replaceHighlighted(pre, html) {
4669
+ const template = document.createElement("template");
4670
+ template.innerHTML = html;
4671
+ for (const code of Array.from(template.content.querySelectorAll("code"))) code.setAttribute("data-aparte-highlighted", "");
4672
+ pre.replaceWith(template.content);
4673
+ }
3572
4674
  const textRenderer = {
3573
4675
  type: "text",
3574
4676
  render: (segment) => `<div class="aparte-segment aparte-segment-text" data-segment-id="${escapeHtml(segment.id)}"><div class="aparte-segment-content">${contextConfig().renderMarkdown(segment.content)}</div></div>`,
@@ -3580,7 +4682,10 @@ const textRenderer = {
3580
4682
  */
3581
4683
  setup: (el2, segment) => {
3582
4684
  const contentEl = el2.querySelector(".aparte-segment-content");
3583
- if (contentEl && segment.isStreaming !== true) highlightMarkdownFences(contentEl);
4685
+ if (!contentEl) return;
4686
+ renderCodeLanguages(contentEl, { streaming: segment.isStreaming === true });
4687
+ if (segment.isStreaming !== true) highlightMarkdownFences(contentEl);
4688
+ renderCitations(contentEl, segment);
3584
4689
  },
3585
4690
  update: (el2, segment) => {
3586
4691
  const contentEl = el2.querySelector(".aparte-segment-content");
@@ -3592,6 +4697,7 @@ const textRenderer = {
3592
4697
  segment.isStreaming !== false
3593
4698
  );
3594
4699
  if (segment.isStreaming === false) highlightMarkdownFences(contentEl);
4700
+ renderCitations(contentEl, segment);
3595
4701
  },
3596
4702
  getStyles: () => ``
3597
4703
  };
@@ -3662,6 +4768,11 @@ const thinkingRenderer = {
3662
4768
  * still wins, exactly as in `render`, because that string is the app's.
3663
4769
  */
3664
4770
  relabel: (el2, segment) => setLabel(el2, segment),
4771
+ /** A block restored from storage is drawn here: `update` only runs on one that changes. */
4772
+ setup: (el2, segment) => {
4773
+ const contentEl = el2.querySelector(".aparte-thinking-content");
4774
+ if (contentEl) renderCodeLanguages(contentEl, { streaming: arriving(segment) });
4775
+ },
3665
4776
  update: (el2, segment) => {
3666
4777
  setLabel(el2, segment);
3667
4778
  const contentEl = el2.querySelector(".aparte-thinking-content");
@@ -3755,6 +4866,7 @@ function highlightedLen(pane) {
3755
4866
  function streamHighlight(element, paneSelector, content, lang, segId) {
3756
4867
  const pane = element.querySelector(paneSelector);
3757
4868
  if (!pane) return;
4869
+ delete pane.dataset.aparteSettled;
3758
4870
  const tail = pane.querySelector("[data-aparte-tail]");
3759
4871
  const hlLen = highlightedLen(pane);
3760
4872
  if (tail && hlLen <= content.length) {
@@ -3773,6 +4885,7 @@ function streamHighlight(element, paneSelector, content, lang, segId) {
3773
4885
  void contextConfig(element).highlightCode(content.slice(0, cut), lang).then((html) => {
3774
4886
  const live2 = element.querySelector(paneSelector);
3775
4887
  if (!live2) return;
4888
+ if (live2.dataset.aparteSettled !== void 0) return;
3776
4889
  if (cut <= highlightedLen(live2)) return;
3777
4890
  live2.innerHTML = html;
3778
4891
  const codeEl = live2.querySelector("code") ?? live2;
@@ -3784,6 +4897,42 @@ function streamHighlight(element, paneSelector, content, lang, segId) {
3784
4897
  }).catch(() => {
3785
4898
  });
3786
4899
  }
4900
+ const sources = /* @__PURE__ */ new WeakMap();
4901
+ const generations = /* @__PURE__ */ new WeakMap();
4902
+ const highlighted = /* @__PURE__ */ new WeakMap();
4903
+ function highlightSettled(element, segment) {
4904
+ const wrapper = element.querySelector(".aparte-code-content-wrapper");
4905
+ if (!wrapper) return;
4906
+ const what = `${segment.language ?? ""}${segment.content}`;
4907
+ const config = contextConfig();
4908
+ const last = highlighted.get(element);
4909
+ if (last?.what === what && last.config === config) return;
4910
+ highlighted.set(element, { what, config });
4911
+ const turn2 = (generations.get(element) ?? 0) + 1;
4912
+ generations.set(element, turn2);
4913
+ wrapper.dataset.aparteSettled = "";
4914
+ void config.highlightCode(segment.content, segment.language || "", { fallback: false }).then((html) => {
4915
+ if (generations.get(element) !== turn2) return;
4916
+ wrapper.innerHTML = html;
4917
+ }).catch(() => {
4918
+ if (generations.get(element) === turn2) highlighted.delete(element);
4919
+ });
4920
+ }
4921
+ const languageOf = (segment) => (segment.language || "").trim().split(/\s+/)[0] ?? "";
4922
+ function drawSettledOrStreaming(element, segment) {
4923
+ const wrapper = element.querySelector(".aparte-code-content-wrapper");
4924
+ if (!wrapper) return;
4925
+ generations.set(element, (generations.get(element) ?? 0) + 1);
4926
+ wrapper.dataset.aparteSettled = "";
4927
+ const language = languageOf(segment);
4928
+ let code = Array.from(wrapper.querySelectorAll("pre > code")).find((c) => c.classList.contains(`language-${language}`));
4929
+ if (!code) {
4930
+ wrapper.innerHTML = `<pre><code class="language-${escapeHtml(language)}"></code></pre>`;
4931
+ code = wrapper.querySelector("pre > code");
4932
+ }
4933
+ if (code.textContent !== segment.content) code.textContent = segment.content;
4934
+ renderCodeLanguages(wrapper, { streaming: segment.isStreaming === true });
4935
+ }
3787
4936
  const codeRenderer = {
3788
4937
  type: "code",
3789
4938
  render: (segment) => {
@@ -3807,27 +4956,20 @@ const codeRenderer = {
3807
4956
  if (copyBtn) relabelCopyButton(copyBtn);
3808
4957
  },
3809
4958
  setup: (element, segment) => {
3810
- const wrapper = element.querySelector(".aparte-code-content-wrapper");
3811
- if (wrapper) {
3812
- void contextConfig().highlightCode(segment.content, segment.language || "").then((html) => {
3813
- wrapper.innerHTML = html;
3814
- }).catch(() => {
3815
- });
3816
- }
4959
+ sources.set(element, segment.content);
4960
+ if (isDrawnLanguage(languageOf(segment), element)) drawSettledOrStreaming(element, segment);
4961
+ else if (segment.isStreaming !== true) highlightSettled(element, segment);
3817
4962
  const copyBtn = element.querySelector(".aparte-code-copy");
3818
- if (copyBtn) wireCopyButton(copyBtn, () => element.querySelector(".aparte-code-content-wrapper")?.textContent ?? "");
4963
+ if (copyBtn) wireCopyButton(copyBtn, () => sources.get(element) ?? "");
3819
4964
  },
3820
4965
  update: (element, segment) => {
3821
- if (segment.isStreaming) {
4966
+ sources.set(element, segment.content);
4967
+ if (isDrawnLanguage(languageOf(segment), element)) {
4968
+ drawSettledOrStreaming(element, segment);
4969
+ } else if (segment.isStreaming === true) {
3822
4970
  streamHighlight(element, ".aparte-code-content-wrapper", segment.content, segment.language || "", segment.id);
3823
4971
  } else {
3824
- const wrapper = element.querySelector(".aparte-code-content-wrapper");
3825
- if (wrapper) {
3826
- void contextConfig().highlightCode(segment.content, segment.language || "").then((html) => {
3827
- wrapper.innerHTML = html;
3828
- }).catch(() => {
3829
- });
3830
- }
4972
+ highlightSettled(element, segment);
3831
4973
  }
3832
4974
  },
3833
4975
  getStyles: () => ``
@@ -4344,9 +5486,9 @@ const toolCallRenderer = {
4344
5486
  return;
4345
5487
  }
4346
5488
  const custom = hidden ? null : contextConfig().getToolRenderer(segment.toolCall?.name) ?? null;
4347
- const drawn = isPlaceholder(element) ? null : drawerOf(element, custom);
4348
- if (drawn && drawn === custom && drawn.update && !isPlaceholder(element)) {
4349
- drawn.update(element, segment);
5489
+ const drawn2 = isPlaceholder(element) ? null : drawerOf(element, custom);
5490
+ if (drawn2 && drawn2 === custom && drawn2.update && !isPlaceholder(element)) {
5491
+ drawn2.update(element, segment);
4350
5492
  return;
4351
5493
  }
4352
5494
  const rebuild = (out) => {
@@ -4360,7 +5502,7 @@ const toolCallRenderer = {
4360
5502
  toolCallRenderer.setup?.(rebuilt, segment);
4361
5503
  }
4362
5504
  };
4363
- if (custom || drawn || hidden || isPlaceholder(element)) {
5505
+ if (custom || drawn2 || hidden || isPlaceholder(element)) {
4364
5506
  rebuild(toolCallRenderer.render(segment));
4365
5507
  return;
4366
5508
  }
@@ -4628,11 +5770,13 @@ function populateBubbleFromMessage(bubble, message, siblingInfo) {
4628
5770
  if (message.segments && message.segments.length > 0) {
4629
5771
  const existing = bubble.getSegments?.() ?? [];
4630
5772
  if (existing.length === message.segments.length) {
4631
- const settled = isTerminalStatus(message.status);
5773
+ const settled2 = isTerminalStatus(message.status);
4632
5774
  for (const seg of message.segments) {
4633
5775
  if ("content" in seg) {
4634
5776
  const patch = { content: seg.content };
4635
- if (settled) patch.isStreaming = false;
5777
+ if (settled2) patch.isStreaming = false;
5778
+ const had = existing.find((s) => s.id === seg.id);
5779
+ if (seg.type === "text" && (seg.sources || seg.citations || had?.sources || had?.citations)) Object.assign(patch, { sources: seg.sources, citations: seg.citations });
4636
5780
  bubble.updateSegment?.(seg.id, patch);
4637
5781
  }
4638
5782
  }
@@ -4777,8 +5921,8 @@ class AparteConversationManager {
4777
5921
  const kept = held.get(m.id);
4778
5922
  return kept ? { ...m, messages: kept.messages, ...kept.tree ? { tree: kept.tree } : {} } : { ...m, messages: [] };
4779
5923
  }) : (await this._adapter.loadAll()).map((c) => ({ ...c, messages: c.messages ?? [] }));
4780
- const seen = /* @__PURE__ */ new Set();
4781
- const unique = rows.filter((c) => !seen.has(c.id) && (seen.add(c.id), true));
5924
+ const seen2 = /* @__PURE__ */ new Set();
5925
+ const unique = rows.filter((c) => !seen2.has(c.id) && (seen2.add(c.id), true));
4782
5926
  if (unique.length !== rows.length) {
4783
5927
  console.warn(`[AparteConversationManager] ${rows.length - unique.length} repeated id(s) in the list; the first row wins.`);
4784
5928
  }
@@ -7078,13 +8222,13 @@ function buildElicitationPanel(message, schema, onChange) {
7078
8222
  }
7079
8223
  function buildPanel(message, schema, onChange) {
7080
8224
  const panel = el$1("div", "aparte-elic-panel");
7081
- const asked = typeof message === "function" ? message() : message;
7082
- if (asked) panel.appendChild(el$1("p", "aparte-elic-message", asked));
8225
+ const asked2 = typeof message === "function" ? message() : message;
8226
+ if (asked2) panel.appendChild(el$1("p", "aparte-elic-message", asked2));
7083
8227
  let settleCb = null;
7084
- let settled = false;
8228
+ let settled2 = false;
7085
8229
  const settle = (content) => {
7086
- if (settled) return;
7087
- settled = true;
8230
+ if (settled2) return;
8231
+ settled2 = true;
7088
8232
  settleCb?.(content);
7089
8233
  };
7090
8234
  const onSettle = (cb) => {
@@ -7195,7 +8339,7 @@ function buildPanel(message, schema, onChange) {
7195
8339
  };
7196
8340
  }
7197
8341
  const answerOnClick = contextConfig().getElicitationOptions().answerOnClick;
7198
- const field = buildField(schema, onChange, asked, void 0, answerOnClick ? settle : void 0);
8342
+ const field = buildField(schema, onChange, asked2, void 0, answerOnClick ? settle : void 0);
7199
8343
  body.appendChild(field.el);
7200
8344
  return {
7201
8345
  el: panel,
@@ -7218,7 +8362,7 @@ function el(tag, className, text) {
7218
8362
  return node;
7219
8363
  }
7220
8364
  let askSeq = 0;
7221
- function buildApprovalPanel(message, options, onChange, details, freeText = true) {
8365
+ function buildApprovalPanel(message, options, onChange, details, allowOther = true) {
7222
8366
  const cfg = contextConfig();
7223
8367
  const panel = el("div", "aparte-elic-panel aparte-approval-panel");
7224
8368
  const body = el("div", "aparte-elic-body");
@@ -7267,7 +8411,7 @@ function buildApprovalPanel(message, options, onChange, details, freeText = true
7267
8411
  labelled.push({ button, option });
7268
8412
  }
7269
8413
  body.appendChild(row);
7270
- const instruction = freeText ? el("textarea", "aparte-approval-instruction") : null;
8414
+ const instruction = allowOther ? el("textarea", "aparte-approval-instruction") : null;
7271
8415
  if (instruction) {
7272
8416
  instruction.rows = 1;
7273
8417
  instruction.placeholder = cfg.t("approvalInstructionPlaceholder");
@@ -7694,8 +8838,8 @@ class AparteClient {
7694
8838
  const turnIds = () => {
7695
8839
  const path = targetElement.getMessages?.() ?? [];
7696
8840
  const at = path.findIndex((m) => m.id === messageId);
7697
- const asked = at > 0 ? path[at - 1] : void 0;
7698
- return asked?.role === "user" ? [asked.id, messageId] : [messageId];
8841
+ const asked2 = at > 0 ? path[at - 1] : void 0;
8842
+ return asked2?.role === "user" ? [asked2.id, messageId] : [messageId];
7699
8843
  };
7700
8844
  const requestMessages = () => opts?.resume ? this._resumeMessages(targetElement, messageId, baseRequest.messages) : baseRequest.messages;
7701
8845
  const requestEstimate = () => estimateRequestTokens({ messages: requestMessages(), tools: baseRequest.tools });
@@ -9206,7 +10350,7 @@ function deferHydrationOf(ctor) {
9206
10350
  const connected = proto.connectedCallback;
9207
10351
  const changed = proto.attributeChangedCallback;
9208
10352
  const disconnected = proto.disconnectedCallback;
9209
- const observed = ctor.observedAttributes ?? [];
10353
+ const observed2 = ctor.observedAttributes ?? [];
9210
10354
  proto.connectedCallback = function() {
9211
10355
  if (isHeld(this)) {
9212
10356
  pending.add(this);
@@ -9214,7 +10358,7 @@ function deferHydrationOf(ctor) {
9214
10358
  }
9215
10359
  if (pending.has(this)) {
9216
10360
  pending.delete(this);
9217
- for (const name of observed) {
10361
+ for (const name of observed2) {
9218
10362
  const value = this.getAttribute(name);
9219
10363
  if (value !== null) changed?.call(this, name, null, value);
9220
10364
  }
@@ -9283,43 +10427,49 @@ export {
9283
10427
  registerDefaultRenderers as a6,
9284
10428
  registerSegmentRenderer as a7,
9285
10429
  releaseDeferredHydration as a8,
9286
- requestUserInput as a9,
9287
- renumberSegments as aA,
9288
- openSegmentIds as aB,
9289
- isTerminalStatus as aC,
9290
- adoptMessageSegments as aD,
9291
- APARTE_DERIVED_SEGMENTS as aE,
9292
- rememberConversationStatus as aF,
9293
- tellConversationStatus as aG,
9294
- conversationStatusOf as aH,
9295
- usageTokens as aI,
9296
- rootOf as aJ,
9297
- resolveConfig as aa,
9298
- revokeAttachmentUrls as ab,
9299
- runWithConfig as ac,
9300
- segmentDuration as ad,
9301
- segmentTiming as ae,
9302
- subscribeConfigChange as af,
9303
- toToolCallView as ag,
9304
- toolRefusal as ah,
9305
- unregisterSegmentRenderer as ai,
9306
- uuid as aj,
9307
- eventOrigin as ak,
9308
- activeElementIn as al,
9309
- gateGlide as am,
9310
- chatBoundaryOf as an,
9311
- toolCallRenderer as ao,
9312
- toolRendererThatDrew as ap,
9313
- isMountedRenderer as aq,
9314
- renderingVersionOf as ar,
9315
- onRenderersChange as as,
9316
- mergeSegmentUpdate as at,
9317
- writeStreamedMarkdown as au,
9318
- CheckpointStateWatcher as av,
9319
- chatIdOf as aw,
9320
- stampSegmentActivity as ax,
9321
- stampSegmentOnInsert as ay,
9322
- stampSegmentOnUpdate as az,
10430
+ renderCitations as a9,
10431
+ replaceHighlighted as aA,
10432
+ CheckpointStateWatcher as aB,
10433
+ chatIdOf as aC,
10434
+ stampSegmentActivity as aD,
10435
+ stampSegmentOnInsert as aE,
10436
+ stampSegmentOnUpdate as aF,
10437
+ renumberSegments as aG,
10438
+ openSegmentIds as aH,
10439
+ isTerminalStatus as aI,
10440
+ adoptMessageSegments as aJ,
10441
+ APARTE_DERIVED_SEGMENTS as aK,
10442
+ rememberConversationStatus as aL,
10443
+ tellConversationStatus as aM,
10444
+ conversationStatusOf as aN,
10445
+ usageTokens as aO,
10446
+ rootOf as aP,
10447
+ renderCodeLanguages as aa,
10448
+ requestUserInput as ab,
10449
+ resolveConfig as ac,
10450
+ revokeAttachmentUrls as ad,
10451
+ runWithConfig as ae,
10452
+ segmentDuration as af,
10453
+ segmentTiming as ag,
10454
+ subscribeConfigChange as ah,
10455
+ toToolCallView as ai,
10456
+ toolRefusal as aj,
10457
+ unregisterSegmentRenderer as ak,
10458
+ uuid as al,
10459
+ eventOrigin as am,
10460
+ activeElementIn as an,
10461
+ gateGlide as ao,
10462
+ chatBoundaryOf as ap,
10463
+ relabelCodeLanguages as aq,
10464
+ relabelCitations as ar,
10465
+ toolCallRenderer as as,
10466
+ toolRendererThatDrew as at,
10467
+ isMountedRenderer as au,
10468
+ renderingVersionOf as av,
10469
+ onRenderersChange as aw,
10470
+ renderSourceList as ax,
10471
+ mergeSegmentUpdate as ay,
10472
+ writeStreamedMarkdown as az,
9323
10473
  APARTE_DEFAULT_BUBBLE_ACTIONS as b,
9324
10474
  APARTE_DEFAULT_HOST_HANDLERS as c,
9325
10475
  APARTE_DEFAULT_ICON_FALLBACKS as d,
@@ -9346,4 +10496,4 @@ export {
9346
10496
  collectRendererStyles as y,
9347
10497
  contentToText as z
9348
10498
  };
9349
- //# sourceMappingURL=defer-hydration-BG8ANn8q.js.map
10499
+ //# sourceMappingURL=defer-hydration-BMip3DKA.js.map