@artifactshare/cli 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { C as defaultPreviewNotificationRegistration, D as isPreviewAnchor, O as isPreviewAnnotation, S as createPreviewNotificationCoordinator, T as PREVIEW_MUTATION_HEADER, _ as resolveLiveSession, a as annotationsFilePath, b as updateSessionNotificationRegistration, c as isSessionId, d as previewsDir, f as probeSession, g as removeSessionFile, h as releaseStaleClaim, i as cursorNotificationRegistration, k as isPreviewDoneItemInput, l as previewIdentityPath, m as readSessionFile, n as CURSOR_ACP_NOTIFICATION_TIMEOUT_MS, o as claimSessionStart, p as processAlive, r as createCursorAcpAdapter, s as isConnectionRefused, u as previewRealpath, v as sessionIdForPath, w as samePreviewNotificationRegistration, x as writeSessionFile, y as tokenFingerprint } from "./cursor-notification-BBGHJ5v5.js";
2
+ import { C as defaultPreviewNotificationRegistration, D as isPreviewAnchor, O as isPreviewAnnotation, S as createPreviewNotificationCoordinator, T as PREVIEW_MUTATION_HEADER, _ as resolveLiveSession, a as annotationsFilePath, b as updateSessionNotificationRegistration, c as isSessionId, d as previewsDir, f as probeSession, g as removeSessionFile, h as releaseStaleClaim, i as cursorNotificationRegistration, k as isPreviewDoneItemInput, l as previewIdentityPath, m as readSessionFile, n as CURSOR_ACP_NOTIFICATION_TIMEOUT_MS, o as claimSessionStart, p as processAlive, r as createCursorAcpAdapter, s as isConnectionRefused, u as previewRealpath, v as sessionIdForPath, w as samePreviewNotificationRegistration, x as writeSessionFile, y as tokenFingerprint } from "./cursor-notification-Hz6fuACK.js";
3
3
  import { cli, define, lazy } from "gunshi";
4
4
  import { generate } from "gunshi/generator";
5
5
  import { chmodSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, watch, writeFileSync } from "node:fs";
@@ -351,7 +351,12 @@ const CommentAnchorSchema = z.union([z.object({
351
351
  }), z.object({
352
352
  kind: z.literal("text"),
353
353
  quoted_text: z.string(),
354
- state: z.enum(["attached", "orphaned"])
354
+ state: z.enum(["attached", "orphaned"]),
355
+ position_state: z.enum([
356
+ "attached",
357
+ "needs-check",
358
+ "unchecked"
359
+ ]).optional()
355
360
  })]);
356
361
  const CommentMessageSchema = z.object({
357
362
  message_id: stringId,
@@ -376,8 +381,8 @@ const CommentPostRequestSchema = z.object({
376
381
  body: z.string().min(1).max(4e3),
377
382
  reply_to: z.string().min(1).max(128).optional(),
378
383
  quote: z.string().min(1).max(1e3).optional(),
379
- quote_before: z.string().min(1).max(200).optional(),
380
- quote_after: z.string().min(1).max(200).optional(),
384
+ quote_before: z.string().max(400).optional(),
385
+ quote_after: z.string().max(400).optional(),
381
386
  agent: z.string().refine((value) => value.trim().length <= 30, "agent must contain at most 30 characters after trimming").optional()
382
387
  }).superRefine((value, context) => {
383
388
  if (value.reply_to !== void 0 && value.quote !== void 0) context.addIssue({
@@ -490,6 +495,7 @@ const CliEditableVisibilitySchema = z.enum([
490
495
  const CliDestinationSchema = z.union([z.literal("home"), z.object({ project_id: stringId })]);
491
496
  const CliEditDestinationSchema = z.union([z.literal("home"), z.object({ project_id: z.string().trim().min(1) })]);
492
497
  z.object({
498
+ retain_versions: z.number().int().min(1).nullable().optional(),
493
499
  title: z.string().optional(),
494
500
  visibility: CliEditableVisibilitySchema.optional(),
495
501
  link_expires_at: z.string().nullable().optional(),
@@ -509,6 +515,8 @@ const CliArtifactDestinationSchema = z.union([z.object({
509
515
  project_id: stringId
510
516
  })]);
511
517
  const CliEditResponseSchema = z.object({
518
+ retain_versions: z.number().int().min(1).nullable().optional(),
519
+ deleted_versions: z.number().int().min(0).optional(),
512
520
  artifact: CliArtifactReferenceSchema,
513
521
  title: z.string(),
514
522
  destination: CliArtifactDestinationSchema,
@@ -667,6 +675,7 @@ const VALUE_FLAGS = /* @__PURE__ */ new Set([
667
675
  "quote-before",
668
676
  "remove-email",
669
677
  "reply-to",
678
+ "retain-versions",
670
679
  "revoke-email",
671
680
  "scope",
672
681
  "session",
@@ -4473,9 +4482,10 @@ function isAnnotationsFileV1(value) {
4473
4482
  }
4474
4483
  function createPreviewStore(annotationsPath) {
4475
4484
  let annotations = [];
4485
+ const skippedAnnotations = [];
4476
4486
  let batches = [];
4477
4487
  let quarantined = null;
4478
- let migrated = false;
4488
+ let needsSave = false;
4479
4489
  if (existsSync(annotationsPath)) {
4480
4490
  let parsed = null;
4481
4491
  try {
@@ -4483,6 +4493,47 @@ function createPreviewStore(annotationsPath) {
4483
4493
  } catch {
4484
4494
  parsed = null;
4485
4495
  }
4496
+ if (parsed && typeof parsed === "object" && "schema_version" in parsed && [1, 2].includes(Number(parsed.schema_version)) && "annotations" in parsed && Array.isArray(parsed.annotations)) {
4497
+ const record = parsed;
4498
+ const retainedAnnotations = parsed.annotations.filter((annotation, index) => {
4499
+ const storedBatches = "batches" in record ? record.batches : void 0;
4500
+ const validBatch = record.schema_version !== 2 || !isPreviewAnnotation(annotation) || !["requested", "in_progress"].includes(annotation.status) || Array.isArray(storedBatches) && storedBatches.some((batch) => isBatch(batch) && batch.id === annotation.batch_id && batch.members.some((member) => member.thread === annotation.thread && member.generation === annotation.generation && member.terminal_result === null));
4501
+ if (isPreviewAnnotation(annotation) && validBatch) return true;
4502
+ skippedAnnotations.push(annotation);
4503
+ needsSave = true;
4504
+ console.warn(`Skipping invalid stored annotation at index ${index}`);
4505
+ return false;
4506
+ });
4507
+ parsed.annotations = retainedAnnotations;
4508
+ if (record.schema_version === 2 && "batches" in record && Array.isArray(record.batches)) {
4509
+ const retained = new Map(retainedAnnotations.map((annotation) => [`${annotation.thread}:${annotation.generation}`, annotation]));
4510
+ for (const batch of record.batches) {
4511
+ if (!isBatch(batch)) continue;
4512
+ const members = batch.members.flatMap((member) => {
4513
+ if (member.terminal_result !== null) return [member];
4514
+ const annotation = retained.get(`${member.thread}:${member.generation}`);
4515
+ if (!annotation || annotation.batch_id !== batch.id || annotation.status === "draft") return [];
4516
+ if (annotation.status === "resolved" || annotation.status === "dismissed") return [{
4517
+ ...member,
4518
+ terminal_result: annotation.status
4519
+ }];
4520
+ return [member];
4521
+ });
4522
+ const changed = members.length !== batch.members.length || members.some((member, index) => member !== batch.members[index]);
4523
+ const completed = members.every((member) => member.terminal_result !== null);
4524
+ if (changed || completed && batch.state !== "completed") {
4525
+ batch.members = members;
4526
+ if (completed) {
4527
+ batch.state = "completed";
4528
+ batch.failure_code = null;
4529
+ batch.retryable = null;
4530
+ }
4531
+ batch.updated_at = nowIso();
4532
+ needsSave = true;
4533
+ }
4534
+ }
4535
+ }
4536
+ }
4486
4537
  if (isAnnotationsFile(parsed)) {
4487
4538
  annotations = parsed.annotations;
4488
4539
  batches = parsed.batches;
@@ -4530,17 +4581,18 @@ function createPreviewStore(annotationsPath) {
4530
4581
  for (const annotation of activeAnnotations) annotation.batch_id = active.id;
4531
4582
  batches = [...migratedBatches.filter((batch) => batch.state === "completed"), active];
4532
4583
  } else batches = migratedBatches;
4533
- migrated = true;
4584
+ needsSave = true;
4534
4585
  } else {
4535
4586
  const target = `${annotationsPath}.corrupt-${nowIso().replaceAll(":", "")}`;
4536
4587
  renameSync(annotationsPath, target);
4537
4588
  quarantined = target;
4589
+ needsSave = false;
4538
4590
  }
4539
4591
  }
4540
4592
  function save() {
4541
4593
  const payload = {
4542
4594
  schema_version: 2,
4543
- annotations,
4595
+ annotations: [...annotations, ...skippedAnnotations],
4544
4596
  batches
4545
4597
  };
4546
4598
  const dir = dirname(annotationsPath);
@@ -4553,7 +4605,7 @@ function createPreviewStore(annotationsPath) {
4553
4605
  renameSync(temp, annotationsPath);
4554
4606
  chmodSync(annotationsPath, 384);
4555
4607
  }
4556
- if (migrated) save();
4608
+ if (needsSave) save();
4557
4609
  function find(thread) {
4558
4610
  return annotations.find((annotation) => annotation.thread === thread);
4559
4611
  }
@@ -4848,7 +4900,8 @@ function createPreviewStore(annotationsPath) {
4848
4900
  if (annotation.anchor.kind !== "artifact") {
4849
4901
  annotation.anchor = {
4850
4902
  ...annotation.anchor,
4851
- state
4903
+ state,
4904
+ ...annotation.anchor.kind === "text" ? { position_state: state === "attached" ? "attached" : "needs-check" } : {}
4852
4905
  };
4853
4906
  touch(annotation);
4854
4907
  save();
@@ -5138,6 +5191,8 @@ const PREVIEW_MESSAGES = {
5138
5191
  "preview.orphanNoticeOne": "The page changed a lot; {n} annotation lost its target",
5139
5192
  "preview.orphanNoticeOther": "The page changed a lot; {n} annotations lost their targets",
5140
5193
  "preview.orphanDiscard": "Discard them",
5194
+ "preview.positionChecking": "Checking comment position…",
5195
+ "preview.positionNeedsCheck": "Quoted text not found in this version",
5141
5196
  "preview.orphanKeep": "Keep",
5142
5197
  "preview.you": "You",
5143
5198
  "preview.agentName": "Agent",
@@ -5224,6 +5279,8 @@ const PREVIEW_MESSAGES = {
5224
5279
  "preview.orphanNoticeOne": "ページが大きく変わったため {n} 件のコメントが対象を見失いました",
5225
5280
  "preview.orphanNoticeOther": "ページが大きく変わったため {n} 件のコメントが対象を見失いました",
5226
5281
  "preview.orphanDiscard": "まとめて破棄",
5282
+ "preview.positionChecking": "コメントの位置を確認しています…",
5283
+ "preview.positionNeedsCheck": "引用した文がこの版に見つかりません",
5227
5284
  "preview.orphanKeep": "残す",
5228
5285
  "preview.you": "あなた",
5229
5286
  "preview.agentName": "エージェント",
@@ -6098,1641 +6155,15 @@ function pickShareMessages(locale) {
6098
6155
  return picked;
6099
6156
  }
6100
6157
  //#endregion
6101
- //#region ../viewer-kit/src/csp-reporter.ts
6102
- const VIOLATION_REPORTER_MARKER = "securitypolicyviolation";
6158
+ //#region ../viewer-kit/src/reporter.generated.ts
6159
+ const VIOLATION_REPORTER_SCRIPT_BODY = "(function() {\n\n\"use strict\";\n const VIOLATION_REPORTER_MARKER = \"securitypolicyviolation\";\n const READY_MESSAGE_REPEAT_COUNT = 20;\n const READY_MESSAGE_REPEAT_INTERVAL_MS = 100;\n const READY_CHECK_MESSAGE_SOURCE = \"artifactshare-parent\";\n const READY_CHECK_MESSAGE_KIND = \"ready-check\";\n\n const ANCHOR_IGNORE_ATTRIBUTE = \"data-anchor-ignore\";\n const COMMENT_UI_ATTRIBUTE = \"data-comment-ui\";\n const EXCLUSION_CLASS_ATTRIBUTE = \"class\";\n const HIGHLIGHT_STYLE_ID = \"ash-comment-highlight-style\";\n const TEXT_ANCHOR_EXCLUDED_SELECTOR = \"script,style,noscript,template,textarea,select,[\" + ANCHOR_IGNORE_ATTRIBUTE + \"],[\" + COMMENT_UI_ATTRIBUTE + \"],.ash-comment-highlight-badge,.mermaid-diagram\";\n const IGNORED_MUTATION_SELECTOR = \"[\" + ANCHOR_IGNORE_ATTRIBUTE + \"],#\" + HIGHLIGHT_STYLE_ID;\n const COMMENT_UI_SELECTOR = \"[\" + COMMENT_UI_ATTRIBUTE + \"]\";\n function anchorIgnoreAttribute() {\n return ANCHOR_IGNORE_ATTRIBUTE;\n }\n function commentUiAttribute() {\n return COMMENT_UI_ATTRIBUTE;\n }\n function highlightStyleId() {\n return HIGHLIGHT_STYLE_ID;\n }\n function ignoredMutationSelector() {\n return IGNORED_MUTATION_SELECTOR;\n }\n function commentUiSelector() {\n return COMMENT_UI_SELECTOR;\n }\n function createTextAnchorEngine(root) {\n const document = root.ownerDocument;\n const units = [];\n let text = \"\";\n let previousBlock = null;\n const blockTags = new Set(\"p div li ul ol dl dt dd h1 h2 h3 h4 h5 h6 pre blockquote table thead tbody tfoot tr td th caption section article aside header footer nav main figure figcaption details summary hr br address form fieldset\".split(\" \"));\n const walker = document.createTreeWalker(root, 4 | 1);\n let node;\n while (node = walker.nextNode()) {\n const element = node.nodeType === 1 ? node : node.parentElement;\n if (!element || element.closest(TEXT_ANCHOR_EXCLUDED_SELECTOR)) continue;\n if (node.nodeType === 1) {\n if ((node.localName === \"br\" || node.localName === \"hr\") && text && !text.endsWith(\" \")) {\n text += \" \";\n units.push([]);\n }\n continue;\n }\n const parent = node.parentElement;\n let block = parent;\n while (block && block !== root && !blockTags.has(block.localName)) block = block.parentElement;\n if (text && previousBlock !== block && !text.endsWith(\" \")) {\n text += \" \";\n units.push([]);\n }\n previousBlock = block;\n const value = node.nodeValue || \"\";\n for (let offset = 0; offset < value.length; offset++) {\n const segment = {\n node,\n start: offset,\n end: offset + 1\n };\n if (/\\s/.test(value[offset])) {\n if (!text) continue;\n if (text.endsWith(\" \")) units[units.length - 1].push(segment);\n else {\n text += \" \";\n units.push([segment]);\n }\n } else {\n text += value[offset];\n units.push([segment]);\n }\n }\n }\n function textHash(value) {\n const bytes = new TextEncoder().encode(value);\n const words = new Uint32Array(Math.ceil((bytes.length + 9) / 64) * 16);\n for (let i = 0; i < bytes.length; i++) words[i >>> 2] = words[i >>> 2] | bytes[i] << 24 - i % 4 * 8;\n words[bytes.length >>> 2] = words[bytes.length >>> 2] | 128 << 24 - bytes.length % 4 * 8;\n words[words.length - 2] = Math.floor(bytes.length / 536870912);\n words[words.length - 1] = bytes.length * 8;\n const h = [\n 1779033703,\n 3144134277,\n 1013904242,\n 2773480762,\n 1359893119,\n 2600822924,\n 528734635,\n 1541459225\n ];\n const k = [\n 1116352408,\n 1899447441,\n 3049323471,\n 3921009573,\n 961987163,\n 1508970993,\n 2453635748,\n 2870763221,\n 3624381080,\n 310598401,\n 607225278,\n 1426881987,\n 1925078388,\n 2162078206,\n 2614888103,\n 3248222580,\n 3835390401,\n 4022224774,\n 264347078,\n 604807628,\n 770255983,\n 1249150122,\n 1555081692,\n 1996064986,\n 2554220882,\n 2821834349,\n 2952996808,\n 3210313671,\n 3336571891,\n 3584528711,\n 113926993,\n 338241895,\n 666307205,\n 773529912,\n 1294757372,\n 1396182291,\n 1695183700,\n 1986661051,\n 2177026350,\n 2456956037,\n 2730485921,\n 2820302411,\n 3259730800,\n 3345764771,\n 3516065817,\n 3600352804,\n 4094571909,\n 275423344,\n 430227734,\n 506948616,\n 659060556,\n 883997877,\n 958139571,\n 1322822218,\n 1537002063,\n 1747873779,\n 1955562222,\n 2024104815,\n 2227730452,\n 2361852424,\n 2428436474,\n 2756734187,\n 3204031479,\n 3329325298\n ];\n const rotate = (x, n) => x >>> n | x << 32 - n;\n const w = new Uint32Array(64);\n for (let offset = 0; offset < words.length; offset += 16) {\n for (let i = 0; i < 64; i++) {\n if (i < 16) w[i] = words[offset + i];\n else {\n const x = w[i - 15], y = w[i - 2];\n w[i] = w[i - 16] + (rotate(x, 7) ^ rotate(x, 18) ^ x >>> 3) + w[i - 7] + (rotate(y, 17) ^ rotate(y, 19) ^ y >>> 10);\n }\n }\n let [a, b, c, d, e, f, g, j] = h;\n for (let i = 0; i < 64; i++) {\n const t1 = j + (rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25)) + (e & f ^ ~e & g) + k[i] + w[i] | 0;\n const t2 = (rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22)) + (a & b ^ a & c ^ b & c) | 0;\n j = g;\n g = f;\n f = e;\n e = d + t1 | 0;\n d = c;\n c = b;\n b = a;\n a = t1 + t2 | 0;\n }\n const next = [\n a,\n b,\n c,\n d,\n e,\n f,\n g,\n j\n ];\n for (let i = 0; i < 8; i++) h[i] = h[i] + next[i] | 0;\n }\n return h.map((word) => (word >>> 0).toString(16).padStart(8, \"0\")).join(\"\");\n }\n const hash = textHash(text);\n function hits(haystack, needle) {\n const found = [];\n if (needle) for (let at = haystack.indexOf(needle); at >= 0; at = haystack.indexOf(needle, at + 1)) found.push(at);\n return found;\n }\n function normalizedQuote(selector) {\n return selector.selectorFormat === \"normalized-v1\" ? selector.quotedText : selector.quotedText.replace(/\\s+/g, \" \").trim();\n }\n function resolve(selector) {\n if (!selector || typeof selector.quotedText !== \"string\" || selector.prefixText != null && typeof selector.prefixText !== \"string\" || selector.suffixText != null && typeof selector.suffixText !== \"string\") return null;\n const modern = selector.selectorFormat === \"normalized-v1\";\n const legacy = !selector.selectorFormat;\n const normalize = (value) => modern ? value : legacy ? value.replace(/\\s+/g, \" \").trim() : value.replace(/\\s+/g, \" \");\n const quote = normalizedQuote(selector);\n const prefix = normalize(selector.prefixText || \"\");\n const suffix = normalize(selector.suffixText || \"\");\n if (!quote.trim()) return null;\n if (legacy || selector.selectorFormat === \"quote-v1\") {\n const positions = new Set();\n for (const before of prefix && !prefix.endsWith(\" \") ? [\"\", \" \"] : [\"\"]) for (const after of suffix && !suffix.startsWith(\" \") ? [\"\", \" \"] : [\"\"]) for (const at of hits(text, prefix + before + quote + after + suffix)) positions.add(at + prefix.length + before.length);\n if (positions.size !== 1) return null;\n const start = positions.values().next().value;\n return {\n textStart: start,\n textEnd: start + quote.length\n };\n }\n const matches = hits(text, prefix + quote + suffix);\n const hit = matches.length === 1 ? matches[0] + prefix.length : -1;\n const context = prefix + quote + suffix;\n const start = selector.textStart, end = selector.textEnd;\n if (modern && typeof start === \"number\" && Number.isInteger(start) && typeof end === \"number\" && Number.isInteger(end) && start >= prefix.length && end - start === quote.length && text.slice(start, end) === quote && text.slice(start - prefix.length, end + suffix.length) === context && (hit >= 0 || selector.textHash === hash)) return {\n textStart: start,\n textEnd: end\n };\n if (hit >= 0 && !selector.ambiguousAtCreation) return {\n textStart: hit,\n textEnd: hit + quote.length\n };\n return null;\n }\n function ranges(start, end) {\n const segments = [];\n for (const unit of units.slice(start, end)) for (const segment of unit) {\n const last = segments[segments.length - 1];\n if (last && last.node === segment.node && last.end === segment.start) last.end = segment.end;\n else segments.push({ ...segment });\n }\n return segments.map((segment) => {\n const range = document.createRange();\n range.setStart(segment.node, segment.start);\n range.setEnd(segment.node, segment.end);\n return range;\n });\n }\n const sourceIndexes = new WeakMap();\n const sourceSegments = [];\n units.forEach((segments, index) => {\n for (const segment of segments) {\n sourceSegments.push({\n segment,\n index\n });\n let offsets = sourceIndexes.get(segment.node);\n if (!offsets) sourceIndexes.set(segment.node, offsets = []);\n offsets[segment.start] = index;\n }\n });\n function paintedText(first, last) {\n const start = sourceIndexes.get(first.startContainer)?.[first.startOffset];\n const end = sourceIndexes.get(last.endContainer)?.[last.endOffset - 1];\n return start === undefined || end === undefined || start > end ? null : text.slice(start, end + 1).trim();\n }\n function mappedSlice(range) {\n if (!root.contains(range.startContainer) || !root.contains(range.endContainer) || range.collapsed) return null;\n function boundary(boundaryNode, offset, isEnd) {\n const direct = sourceIndexes.get(boundaryNode)?.[isEnd ? offset - 1 : offset];\n if (direct !== undefined) return direct + (isEnd ? 1 : 0);\n const point = document.createRange();\n point.setStart(boundaryNode, offset);\n point.collapse(true);\n let low = 0, high = sourceSegments.length;\n while (low < high) {\n const mid = low + high >>> 1;\n const entry = sourceSegments[mid];\n const comparison = point.comparePoint(entry.segment.node, isEnd ? entry.segment.start : entry.segment.end);\n if (isEnd ? comparison < 0 : comparison <= 0) low = mid + 1;\n else high = mid;\n }\n return isEnd ? low ? sourceSegments[low - 1].index + 1 : 0 : low < sourceSegments.length ? sourceSegments[low].index : text.length;\n }\n let start = boundary(range.startContainer, range.startOffset, false);\n let end = boundary(range.endContainer, range.endOffset, true);\n while (start >= 0 && start < end && /\\s/.test(text[start])) start++;\n while (end > start && /\\s/.test(text[end - 1])) end--;\n if (start < 0 || start >= end || end - start > 1e3) return null;\n return {\n textStart: start,\n textEnd: end,\n quotedText: text.slice(start, end)\n };\n }\n function describe(range) {\n const mapped = mappedSlice(range);\n if (!mapped) return null;\n const { textStart: start, textEnd: end, quotedText: quote } = mapped;\n let prefix = \"\", suffix = \"\", ambiguous = true;\n for (let size = 32;; size = Math.min(400, size + 32)) {\n prefix = text.slice(Math.max(0, start - size), start);\n suffix = text.slice(end, end + size);\n ambiguous = hits(text, prefix + quote + suffix).length !== 1;\n if (!ambiguous || size === 400) break;\n }\n return {\n quotedText: quote,\n prefixText: prefix,\n suffixText: suffix,\n textStart: start,\n textEnd: end,\n textHash: hash,\n selectorFormat: \"normalized-v1\",\n ambiguousAtCreation: ambiguous\n };\n }\n return {\n text,\n hash,\n describe,\n mappedSlice,\n resolve,\n ranges,\n paintedText,\n normalizedQuote\n };\n }\n\n function trusted(ctx, event) {\n try {\n return ctx.primordials.trustedGetter && ctx.primordials.trustedGetter.get ? ctx.primordials.trustedGet(event) === true : event.isTrusted === true;\n } catch (e) {\n return false;\n }\n }\n function shouldHandleLink(ctx, url) {\n if (url.origin !== ctx.win.location.origin) return true;\n if (url.pathname !== ctx.win.location.pathname) return true;\n if (url.search !== ctx.win.location.search && url.search !== \"\") return true;\n return false;\n }\n function openExternalLink(ctx, href) {\n ctx.win.open(href, \"_blank\", \"noopener,noreferrer\");\n }\n function isExternallyOpenable(ctx, url) {\n return url.protocol === \"http:\" || url.protocol === \"https:\";\n }\n function prepareLinkClick(ctx, event) {\n let defaultPrevented = readEventValue(ctx, ctx.primordials.defaultPreventedGet, event);\n let button = readEventValue(ctx, ctx.primordials.buttonGet, event);\n let metaKey = readEventValue(ctx, ctx.primordials.metaKeyGet, event);\n let ctrlKey = readEventValue(ctx, ctx.primordials.ctrlKeyGet, event);\n let shiftKey = readEventValue(ctx, ctx.primordials.shiftKeyGet, event);\n let altKey = readEventValue(ctx, ctx.primordials.altKeyGet, event);\n if (!trusted(ctx, event) || defaultPrevented !== false || button !== 0 || metaKey !== false || ctrlKey !== false || shiftKey !== false || altKey !== false) {\n return;\n }\n if (hitComment(ctx, event)) return;\n let target = readEventValue(ctx, ctx.primordials.targetGet, event);\n let element = target && target.nodeType === 1 ? target : target && target.parentElement;\n if (element && ctx.primordials.closest(element, \".ash-comment-highlight, .ash-comment-highlight-badge\")) {\n return;\n }\n let anchor = element ? ctx.primordials.closest(element, \"a[href]\") : null;\n if (!anchor || ctx.primordials.hasAttribute(anchor, \"download\")) return;\n let rawHref = ctx.primordials.getAttribute(anchor, \"href\");\n if (!rawHref || rawHref.charAt(0) === \"#\") return;\n let url;\n let href;\n let openExternally = false;\n try {\n url = new ctx.win.URL(rawHref, ctx.win.location.href);\n if (!shouldHandleLink(ctx, url)) return;\n href = url.href;\n openExternally = url.origin !== ctx.win.location.origin && isExternallyOpenable(ctx, url);\n } catch (e) {\n href = rawHref;\n }\n let pending = ctx.primordials.objectCreate(null);\n pending.artifactPrevented = false;\n pending.href = href;\n pending.openExternally = openExternally;\n try {\n ctx.primordials.defineProperty(event, \"preventDefault\", {\n configurable: true,\n value: function() {\n pending.artifactPrevented = true;\n ctx.primordials.preventDefault(event);\n }\n });\n ctx.primordials.defineProperty(event, \"defaultPrevented\", {\n configurable: true,\n get: function() {\n return pending.artifactPrevented;\n }\n });\n ctx.primordials.weakMapSet(ctx.pendingLinkClicks, event, pending);\n } catch (e) {\n ctx.primordials.preventDefault(event);\n return;\n }\n ctx.primordials.preventDefault(event);\n }\n function finishLinkClick(ctx, event) {\n let pending = ctx.primordials.weakMapGet(ctx.pendingLinkClicks, event);\n if (!pending) return;\n ctx.primordials.weakMapDelete(ctx.pendingLinkClicks, event);\n if (pending.artifactPrevented) return;\n if (pending.openExternally && ctx.externalLinkPolicyMode === \"direct\") {\n openExternalLink(ctx, pending.href);\n return;\n }\n send(ctx, {\n kind: \"link-clicked\",\n href: pending.href,\n token: ctx.documentToken\n });\n }\n\n function badgeStyleForHighlight(ctx, highlight, isDark) {\n let palette = highlightPalette(ctx, isDark, highlight.status === \"resolved\");\n let base = \"display:inline-flex;align-items:center;gap:4px;min-height:16px;padding:0 5px;border-radius:999px;font:700 10px system-ui,sans-serif;box-shadow:0 2px 8px rgba(27,39,35,.08);cursor:pointer;touch-action:none;position:absolute;z-index:2147483646;\";\n let borderColor;\n let textColor;\n let bgColor;\n if (highlight.target) {\n borderColor = palette.badgeTargetBorder;\n textColor = palette.badgeTargetText;\n bgColor = palette.badgeTargetBg;\n } else {\n borderColor = palette.badgeBorder;\n textColor = palette.badgeText;\n bgColor = palette.badgeBg;\n }\n return base + \"border:1px solid \" + borderColor + \";color:\" + textColor + \";background:\" + bgColor + \";\";\n }\n function positionSingleBadge(ctx, entry) {\n let badge = entry.badge;\n let rects = measureBadgeEntry(ctx, entry);\n let rect = rects.length ? rects[rects.length - 1] : null;\n if (!rect || rect.width === 0 || rect.height === 0) {\n badge.style.display = \"none\";\n return;\n }\n badge.style.display = \"inline-flex\";\n badge.style.left = \"0px\";\n badge.style.top = \"0px\";\n let base = badge.getBoundingClientRect();\n let scaleX = badge.offsetWidth ? base.width / badge.offsetWidth : 1;\n let scaleY = badge.offsetHeight ? base.height / badge.offsetHeight : 1;\n if (!scaleX || !isFinite(scaleX)) scaleX = 1;\n if (!scaleY || !isFinite(scaleY)) scaleY = 1;\n let badgeHeight = badge.offsetHeight || 16;\n let threadId = badge.dataset.threadId;\n let offset = ctx.badgeOffsets[threadId] || {\n x: 0,\n y: 0\n };\n badge.style.left = (rect.right - base.left) / scaleX - 6 + offset.x + \"px\";\n badge.style.top = (rect.top - base.top) / scaleY - badgeHeight + 3 + offset.y + \"px\";\n }\n function positionBadges(ctx) {\n let layouts = [];\n for (let i = 0; i < ctx.badges.length; i++) {\n let badge = ctx.badges[i].badge;\n let rects = measureBadgeEntry(ctx, ctx.badges[i]);\n let rect = rects.length ? rects[rects.length - 1] : null;\n badge.style.display = \"inline-flex\";\n badge.style.left = \"0px\";\n badge.style.top = \"0px\";\n let base = badge.getBoundingClientRect();\n let scaleX = badge.offsetWidth ? base.width / badge.offsetWidth : 1;\n let scaleY = badge.offsetHeight ? base.height / badge.offsetHeight : 1;\n if (!scaleX || !isFinite(scaleX)) scaleX = 1;\n if (!scaleY || !isFinite(scaleY)) scaleY = 1;\n layouts.push({\n badge,\n rect,\n base,\n badgeHeight: badge.offsetHeight || 16,\n scaleX,\n scaleY,\n threadId: badge.dataset.threadId\n });\n }\n for (let j = 0; j < layouts.length; j++) {\n let layout = layouts[j];\n if (!layout.rect || layout.rect.width === 0 || layout.rect.height === 0) {\n layout.badge.style.display = \"none\";\n continue;\n }\n let offset = ctx.badgeOffsets[layout.threadId] || {\n x: 0,\n y: 0\n };\n layout.badge.style.display = \"inline-flex\";\n layout.badge.style.left = (layout.rect.right - layout.base.left) / layout.scaleX - 6 + offset.x + \"px\";\n layout.badge.style.top = (layout.rect.top - layout.base.top) / layout.scaleY - layout.badgeHeight + 3 + offset.y + \"px\";\n }\n }\n function isBadgeAnchorVisible(ctx, element) {\n if (!element) return false;\n let visibility = ctx.win.getComputedStyle(element).visibility;\n if (visibility === \"hidden\" || visibility === \"collapse\") return false;\n let boxedElement = element;\n while (boxedElement && ctx.win.getComputedStyle(boxedElement).display === \"contents\") {\n boxedElement = boxedElement.parentElement;\n }\n return !!boxedElement && !!boxedElement.getClientRects().length && (!boxedElement.checkVisibility || boxedElement.checkVisibility());\n }\n function measureBadgeEntry(ctx, entry) {\n if (entry.measure) return entry.measure();\n return [];\n }\n function schedulePositionBadges(ctx) {\n if (ctx.badgePositionFrame) return;\n ctx.badgePositionFrame = ctx.win.requestAnimationFrame(function() {\n ctx.badgePositionFrame = 0;\n positionBadges(ctx);\n });\n }\n function takeBadge(ctx, highlight) {\n let badge = ctx.reusableBadges.get(highlight.threadId);\n if (badge) ctx.reusableBadges.delete(highlight.threadId);\n else {\n badge = ctx.doc.createElement(\"button\");\n bindBadgePointer(ctx, badge);\n }\n if (!badge.isConnected) ctx.doc.documentElement.appendChild(badge);\n return badge;\n }\n function hitComment(ctx, event) {\n if (!trusted(ctx, event) || event.type === \"click\" && (event.detail <= 0 || event.pointerType === \"\" || event.mozInputSource === 6)) return null;\n for (let index = 0; index < ctx.badges.length; index++) {\n let rects = measureBadgeEntry(ctx, ctx.badges[index]);\n if (Array.from(rects).some(function(rect) {\n return event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;\n })) return ctx.badges[index].badge;\n }\n return null;\n }\n function rectFromPointer(ctx, event, fallback) {\n if (event.detail !== 0 && typeof event.clientX === \"number\" && typeof event.clientY === \"number\") {\n return {\n top: event.clientY - 8,\n left: event.clientX,\n width: 1,\n height: 16\n };\n }\n return fallback;\n }\n function bindBadgePointer(ctx, badge) {\n let dragState = null;\n let badgeEntry = null;\n function finishDrag(event) {\n if (!dragState || event.pointerId !== dragState.pointerId) return;\n if (event.type === \"pointerup\" && dragState.dragged) ctx.badgeDragged = true;\n try {\n badge.releasePointerCapture(event.pointerId);\n } catch (e) {}\n dragState = null;\n }\n badge.addEventListener(\"pointerdown\", function(event) {\n ctx.badgeDragged = false;\n if (event.button !== 0) return;\n for (let i = 0; i < ctx.badges.length; i++) {\n if (ctx.badges[i].badge === badge) {\n badgeEntry = ctx.badges[i];\n break;\n }\n }\n let threadId = badge.dataset.threadId;\n let offset = ctx.badgeOffsets[threadId] || {\n x: 0,\n y: 0\n };\n dragState = {\n pointerId: event.pointerId,\n startX: event.clientX,\n startY: event.clientY,\n offsetX: offset.x,\n offsetY: offset.y,\n dragged: false\n };\n try {\n badge.setPointerCapture(event.pointerId);\n } catch (e) {}\n event.preventDefault();\n });\n badge.addEventListener(\"pointermove\", function(event) {\n if (!dragState || event.pointerId !== dragState.pointerId) return;\n let dx = event.clientX - dragState.startX;\n let dy = event.clientY - dragState.startY;\n if (!dragState.dragged && (Math.abs(dx) > 4 || Math.abs(dy) > 4)) {\n dragState.dragged = true;\n }\n if (!dragState.dragged) return;\n let threadId = badge.dataset.threadId;\n ctx.badgeOffsets[threadId] = {\n x: dragState.offsetX + dx,\n y: dragState.offsetY + dy\n };\n if (badgeEntry) positionSingleBadge(ctx, badgeEntry);\n });\n badge.addEventListener(\"pointerup\", finishDrag);\n badge.addEventListener(\"pointercancel\", finishDrag);\n badge.addEventListener(\"click\", function(event) {\n if (ctx.badgeDragged) {\n ctx.badgeDragged = false;\n event.preventDefault();\n event.stopPropagation();\n return;\n }\n let r = badge.getBoundingClientRect();\n selectThreadFromElement(ctx, badge, rectFromPointer(ctx, event, r));\n event.preventDefault();\n event.stopPropagation();\n });\n function updateSvgActive(active) {\n ctx.svgActiveThreads[badge.dataset.threadId] = active;\n setSvgHighlightState(ctx, badge.dataset.threadId, active);\n }\n badge.addEventListener(\"pointerenter\", function() {\n updateSvgActive(true);\n });\n badge.addEventListener(\"pointerleave\", function() {\n updateSvgActive(ctx.doc.activeElement === badge);\n });\n badge.addEventListener(\"focus\", function() {\n updateSvgActive(true);\n });\n badge.addEventListener(\"blur\", function() {\n updateSvgActive(badge.matches(\":hover\"));\n });\n }\n function selectThreadFromElement(ctx, element, rect) {\n send(ctx, {\n kind: \"comment-thread-selected\",\n threadId: element.dataset.threadId,\n rect: {\n top: rect.top,\n left: rect.left,\n width: rect.width,\n height: rect.height\n }\n });\n }\n function sendOutsidePointerDown(ctx, event) {\n if (!ctx.textAnchorsEnabled || hitComment(ctx, event)) return;\n let target = event.target;\n if (target && target.closest && target.closest(\".ash-comment-highlight, .ash-comment-highlight-badge, [data-code-copy]\")) {\n return;\n }\n send(ctx, { kind: \"comment-outside-pointer-down\" });\n }\n\n function setSvgHighlightState(ctx, threadId, active) {\n ctx.textPaints.forEach(function(paint) {\n if (paint.threadId === threadId) paint.active = active || paint.target;\n });\n refreshTextPaints(ctx);\n let overlays = ctx.doc.querySelectorAll(\".ash-comment-highlight-svg[data-thread-id=\\\"\" + ctx.win.CSS.escape(threadId) + \"\\\"]\");\n for (let i = 0; i < overlays.length; i++) {\n let overlay = overlays[i];\n let palette = overlay.dataset.palette;\n if (!palette) continue;\n let parts = palette.split(\"|\");\n let normalFill = parts[0];\n let outline = parts[1];\n let target = overlay.dataset.target === \"true\";\n let state = active || target ? \"active\" : \"normal\";\n let applied = ctx.svgOverlayStyles.get(overlay);\n if (overlay.dataset.state !== state) overlay.dataset.state = state;\n if (applied && applied.state === state && overlay.getAttribute(\"style\") === applied.style) continue;\n if (active || target) {\n overlay.style.fill = normalFill;\n overlay.style.stroke = outline;\n overlay.style.strokeWidth = \"2\";\n overlay.style.vectorEffect = \"non-scaling-stroke\";\n } else {\n overlay.style.fill = normalFill;\n overlay.style.stroke = \"none\";\n overlay.style.strokeWidth = \"0\";\n }\n ctx.svgOverlayStyles.set(overlay, {\n state,\n style: overlay.getAttribute(\"style\")\n });\n }\n }\n function svgTextRange(ctx, ranges) {\n return ranges.flatMap(function(range) {\n let node = range.startContainer;\n if (!node.parentElement.closest(\"svg text\")) return [];\n let text = node.parentElement.closest(\"text,tspan,textPath\");\n if (!text || !text.getNumberOfChars) return [];\n let walker = ctx.doc.createTreeWalker(text, ctx.win.NodeFilter.SHOW_TEXT);\n let raw = [], collapsed = [], candidate;\n let whitespace = false;\n while (candidate = walker.nextNode()) {\n let value = candidate.nodeValue || \"\";\n for (let offset = 0; offset < value.length; offset++) {\n let unit = {\n node: candidate,\n offset\n };\n raw.push([unit]);\n if (/[\\t\\n\\r ]/.test(value[offset])) {\n if (!collapsed.length) continue;\n if (whitespace) collapsed[collapsed.length - 1].push(unit);\n else collapsed.push([unit]);\n whitespace = true;\n } else {\n collapsed.push([unit]);\n whitespace = false;\n }\n }\n }\n if (whitespace) collapsed.pop();\n let count = text.getNumberOfChars();\n let characters = collapsed.length === count ? collapsed : raw.length === count ? raw : null;\n if (!characters) return [];\n let start = -1, end = -1;\n characters.forEach(function(units, index) {\n for (let i = 0; i < units.length; i++) {\n let unit = units[i];\n if (unit.node === node && unit.offset >= range.startOffset && unit.offset < range.endOffset) {\n if (start < 0) start = index;\n end = index + 1;\n break;\n }\n }\n });\n return start < 0 ? [] : [{\n text,\n start,\n end\n }];\n });\n }\n function wrapSvgRange(ctx, highlight, groups) {\n if (!groups.length) return false;\n let texts = groups.map(function(group) {\n return group.text;\n }).filter(function(text, index, all) {\n return all.indexOf(text) === index;\n });\n let first = texts[0];\n let svg = first && first.ownerSVGElement;\n while (svg && svg.ownerSVGElement) svg = svg.ownerSVGElement;\n if (!svg || !svg.parentNode) return false;\n ensureCommentStyles(ctx);\n let overlays = {};\n let badgeEntry = {\n badge: null,\n highlight,\n overlays,\n measure: measureSvgRange\n };\n function overlayKey(text, index) {\n return texts.indexOf(text) + \":\" + index;\n }\n function setAttributeIfChanged(shape, name, value) {\n value = String(value);\n if (shape.getAttribute(name) !== value) shape.setAttribute(name, String(value));\n }\n function updateOverlay(text, index, box, screenCtm) {\n let currentHighlight = badgeEntry.highlight;\n let key = overlayKey(text, index);\n let shape = overlays[key];\n if (!shape) {\n shape = ctx.doc.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\");\n shape.setAttribute(\"class\", \"ash-comment-highlight-svg\");\n shape.setAttribute(anchorIgnoreAttribute(), \"\");\n shape.setAttribute(\"pointer-events\", \"none\");\n shape.dataset.threadId = currentHighlight.threadId;\n shape.dataset.target = currentHighlight.target ? \"true\" : \"false\";\n let palette = highlightPalette(ctx, isDarkBackgroundForSvgText(ctx, text), currentHighlight.status === \"resolved\");\n shape.dataset.palette = palette.markBg + \"|\" + palette.outline;\n let textRoot = text.closest(\"text\");\n textRoot.parentNode.insertBefore(shape, textRoot);\n overlays[key] = shape;\n }\n let scaleX = screenCtm ? Math.hypot(screenCtm.a, screenCtm.b) : 1;\n let scaleY = screenCtm ? Math.hypot(screenCtm.c, screenCtm.d) : 1;\n let padX = scaleX ? 2 / scaleX : 2;\n let padY = scaleY ? 2 / scaleY : 2;\n setAttributeIfChanged(shape, \"x\", box.x - padX);\n setAttributeIfChanged(shape, \"y\", box.y - padY);\n setAttributeIfChanged(shape, \"width\", box.width + padX * 2);\n setAttributeIfChanged(shape, \"height\", box.height + padY * 2);\n let textCtm = text.getCTM ? text.getCTM() : null;\n let parentNode = shape.parentNode;\n let parentCtm = parentNode && parentNode.getCTM ? parentNode.getCTM() : null;\n if (textCtm && parentCtm && parentCtm.inverse) {\n let matrix = parentCtm.inverse().multiply(textCtm);\n setAttributeIfChanged(shape, \"transform\", \"matrix(\" + [\n matrix.a,\n matrix.b,\n matrix.c,\n matrix.d,\n matrix.e,\n matrix.f\n ].join(\" \") + \")\");\n } else if (shape.hasAttribute(\"transform\")) {\n shape.removeAttribute(\"transform\");\n }\n return shape;\n }\n function measureSvgRange() {\n let current = [];\n let lastElement = null;\n let usedOverlays = {};\n for (let i = 0; i < groups.length; i++) {\n let group = groups[i];\n let ctm = group.text.getScreenCTM ? group.text.getScreenCTM() : null;\n let runs = [];\n for (let index = group.start; index < group.end; index++) {\n try {\n let box = group.text.getExtentOfChar(index);\n if (!box || box.width < 0 || box.height <= 0) continue;\n let previous = runs.length ? runs[runs.length - 1] : null;\n let overlapsVertically = previous && box.y <= previous.y + previous.height && previous.y <= box.y + box.height;\n let sameLine = previous && overlapsVertically && box.x <= previous.x + previous.width + Math.max(4, box.height * .5);\n if (sameLine && previous) {\n let runRight = Math.max(previous.x + previous.width, box.x + box.width);\n let runBottom = Math.max(previous.y + previous.height, box.y + box.height);\n previous.x = Math.min(previous.x, box.x);\n previous.y = Math.min(previous.y, box.y);\n previous.width = runRight - previous.x;\n previous.height = runBottom - previous.y;\n } else {\n runs.push({\n x: box.x,\n y: box.y,\n width: box.width,\n height: box.height\n });\n }\n } catch (e) {}\n }\n for (let runIndex = 0; runIndex < runs.length; runIndex++) {\n try {\n let run = runs[runIndex];\n let overlayIndex = i + \"-\" + runIndex;\n let overlay = updateOverlay(group.text, overlayIndex, run, ctm);\n let display = isBadgeAnchorVisible(ctx, group.text) ? \"inline\" : \"none\";\n if (overlay.style.display !== display) overlay.style.display = display;\n usedOverlays[overlayKey(group.text, overlayIndex)] = true;\n let points = [\n [run.x, run.y],\n [run.x + run.width, run.y],\n [run.x, run.y + run.height],\n [run.x + run.width, run.y + run.height]\n ].map(function(point) {\n return ctm ? new ctx.win.DOMPoint(point[0], point[1]).matrixTransform(ctm) : {\n x: point[0],\n y: point[1]\n };\n });\n let left = Math.min.apply(null, points.map(function(point) {\n return point.x;\n }));\n let top = Math.min.apply(null, points.map(function(point) {\n return point.y;\n }));\n let right = Math.max.apply(null, points.map(function(point) {\n return point.x;\n }));\n let bottom = Math.max.apply(null, points.map(function(point) {\n return point.y;\n }));\n if (right > left && bottom > top) {\n current.push({\n left,\n right,\n top,\n width: right - left,\n height: bottom - top\n });\n lastElement = group.text;\n }\n } catch (e) {}\n }\n }\n Object.keys(overlays).forEach(function(key) {\n if (!usedOverlays[key]) {\n overlays[key].remove();\n delete overlays[key];\n }\n });\n setSvgHighlightState(ctx, highlight.threadId, ctx.svgActiveThreads[highlight.threadId] === true);\n if (current.length) return isBadgeAnchorVisible(ctx, lastElement) ? current : [];\n if (!isBadgeAnchorVisible(ctx, first)) return [];\n let fallback = first.getBoundingClientRect ? first.getBoundingClientRect() : null;\n if (!fallback || fallback.width === 0 || fallback.height === 0) {\n fallback = svg.getBoundingClientRect();\n }\n return fallback ? [fallback] : [];\n }\n let badge = takeBadge(ctx, highlight);\n badge.setAttribute(anchorIgnoreAttribute(), \"\");\n badge.type = \"button\";\n badge.className = \"ash-comment-highlight-badge\";\n badge.dataset.threadId = highlight.threadId;\n badge.dataset.count = String(highlight.count || 1);\n badge.setAttribute(\"aria-label\", commentLabel(ctx, highlight));\n badge.innerHTML = highlight.status === \"resolved\" ? \"<svg viewBox=\\\"0 0 24 24\\\" width=\\\"10\\\" height=\\\"10\\\" style=\\\"width:10px;height:10px;flex:none;border:0;padding:0;margin:0;background:none;box-shadow:none\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\" aria-hidden=\\\"true\\\"><path d=\\\"M20 6 9 17l-5-5\\\"/></svg>\" : \"<svg viewBox=\\\"0 0 24 24\\\" width=\\\"10\\\" height=\\\"10\\\" style=\\\"width:10px;height:10px;flex:none;border:0;padding:0;margin:0;background:none;box-shadow:none\\\" fill=\\\"none\\\" stroke=\\\"currentColor\\\" stroke-width=\\\"2\\\" stroke-linecap=\\\"round\\\" stroke-linejoin=\\\"round\\\" aria-hidden=\\\"true\\\"><path d=\\\"M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z\\\"/></svg>\";\n badge.style.cssText = badgeStyleForHighlight(ctx, highlight, isDarkBackgroundForSvgText(ctx, first));\n badgeEntry.badge = badge;\n ctx.badges.push(badgeEntry);\n measureSvgRange();\n return true;\n }\n\n function cssPath(ctx, element) {\n if (!element || element.nodeType !== 1) return null;\n let parts = [];\n while (element && element.nodeType === 1 && element !== ctx.doc.body) {\n let name = element.nodeName.toLowerCase();\n let index = 1;\n let sibling = element;\n while (sibling = sibling.previousElementSibling) {\n if (sibling.nodeName.toLowerCase() === name) index++;\n }\n parts[parts.length] = name + \":nth-of-type(\" + index + \")\";\n element = element.parentElement;\n }\n let path = \"body\";\n for (let i = parts.length - 1; i >= 0; i--) path += \" > \" + parts[i];\n return path;\n }\n function selectedElement(ctx, range) {\n let node = range.commonAncestorContainer;\n return (node.nodeType === 1 ? node : node.parentElement) || ctx.doc.body;\n }\n function anchorRoot(ctx) {\n return ctx.doc.querySelector(\"[data-comment-content]\") || ctx.doc.body;\n }\n function sendSelection(ctx) {\n if (!ctx.textAnchorsEnabled) return;\n let selection = ctx.win.getSelection();\n if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {\n send(ctx, { kind: \"text-selection-cleared\" });\n return;\n }\n let range = selection.getRangeAt(0);\n if (!ctx.primordials.rangeToString(range).trim()) {\n send(ctx, { kind: \"text-selection-cleared\" });\n return;\n }\n let engine = createTextAnchorEngine(anchorRoot(ctx));\n let selector = engine.describe(range);\n if (!selector) {\n send(ctx, { kind: \"text-selection-cleared\" });\n return;\n }\n let rect = range.getBoundingClientRect();\n send(ctx, {\n kind: \"text-selection\",\n token: ctx.documentToken,\n quotedText: selector.quotedText,\n prefixText: selector.prefixText,\n suffixText: selector.suffixText,\n textStart: selector.textStart,\n textEnd: selector.textEnd,\n selectorFormat: selector.selectorFormat,\n textHash: selector.textHash,\n ambiguousAtCreation: selector.ambiguousAtCreation,\n versionId: ctx.displayedVersionId,\n cssPath: cssPath(ctx, selectedElement(ctx, range)),\n rect: {\n top: rect.top,\n left: rect.left,\n width: rect.width,\n height: rect.height\n }\n });\n }\n\n function ensureAnnotateStyles(ctx) {\n if (ctx.doc.getElementById(\"as-preview-annotate-style\")) return;\n let style = ctx.doc.createElement(\"style\");\n style.setAttribute(anchorIgnoreAttribute(), \"\");\n style.id = \"as-preview-annotate-style\";\n style.textContent = \".as-preview-annotate-hover{outline:2px solid #6366f1 !important;outline-offset:2px;}\" + \".as-preview-pinged{outline:2px solid #6366f1 !important;outline-offset:2px;background-color:rgba(99,102,241,0.12) !important;transition:background-color 0.4s ease;}\" + \".as-preview-flash{background-color:rgba(34,197,94,0.35) !important;transition:background-color 1s ease;}\" + \".as-preview-flash-fade{background-color:transparent !important;}\";\n ctx.doc.head.appendChild(style);\n }\n function annotateTargetFrom(ctx, eventTarget) {\n const target = eventTarget;\n if (!target || target.nodeType !== 1) return null;\n if (target === ctx.doc.body || target === ctx.doc.documentElement) return null;\n if (ctx.primordials.closest(target, commentUiSelector())) return null;\n return target;\n }\n function clearAnnotateHover(ctx) {\n if (ctx.annotateHoverElement) {\n ctx.annotateHoverElement.classList.remove(\"as-preview-annotate-hover\");\n ctx.annotateHoverElement = null;\n }\n }\n function elementLabel(ctx, el) {\n let quote = function(text) {\n return \"\\\"\" + text + \"\\\"\";\n };\n let tag = el.nodeName.toLowerCase();\n let ariaLabel = el.getAttribute && el.getAttribute(\"aria-label\");\n if (ariaLabel) return tag + \" \" + quote(ariaLabel.trim());\n let text = (el.textContent || \"\").replace(/\\s+/g, \" \").trim();\n if (text) return tag + \" \" + quote(text.slice(0, 25));\n if (tag === \"img\") {\n let alt = el.getAttribute(\"alt\");\n if (alt) return \"img \" + quote(alt.trim());\n }\n let role = el.getAttribute && el.getAttribute(\"role\");\n if (role) return tag + \" [role=\" + role + \"]\";\n return tag;\n }\n function siblingText(ctx, el) {\n return el && el.textContent ? el.textContent.replace(/\\s+/g, \" \").trim().slice(0, 40) : \"\";\n }\n function annotateContextText(ctx, el) {\n let own = (el.textContent || \"\").replace(/\\s+/g, \" \").trim().slice(0, 100);\n let before = siblingText(ctx, el.previousElementSibling);\n let after = siblingText(ctx, el.nextElementSibling);\n let parts = [own];\n if (before) parts.push(\"[before: \" + before + \"]\");\n if (after) parts.push(\"[after: \" + after + \"]\");\n return parts.join(\" \").trim();\n }\n function verifyAnchors(ctx, anchors, engine) {\n ctx.anchorSnapshotGeneration++;\n ctx.pendingAnchors = anchors || [];\n if (!ctx.pendingAnchors.length) {\n ctx.checkingAnchors = [];\n scheduleChecking(ctx);\n return;\n }\n let checking = [];\n let verdicts = [];\n if (!engine) {\n for (let i = 0; i < ctx.pendingAnchors.length; i++) {\n if (ctx.pendingAnchors[i].kind === \"text\") {\n engine = createTextAnchorEngine(anchorRoot(ctx));\n break;\n }\n }\n }\n for (let i = 0; i < (anchors || []).length; i++) {\n let anchor = anchors[i] || {};\n let attached = false;\n if (anchor.kind === \"element\") {\n attached = findElement(ctx, anchor) !== null;\n } else if (anchor.kind === \"text\") {\n attached = engine.resolve(anchor) !== null;\n }\n if (attached) delete ctx.checkingDeadlines[anchor.thread];\n verdicts.push({\n thread: anchor.thread,\n attached,\n position_state: attached ? \"attached\" : missingState(ctx, anchor.thread, checking)\n });\n }\n send(ctx, {\n kind: \"anchor-verdicts\",\n verificationId: ctx.pendingVerificationId,\n generation: ++ctx.resolutionGeneration,\n verdicts\n });\n ctx.checkingAnchors = checking;\n scheduleChecking(ctx);\n }\n function findElement(ctx, anchor) {\n if (!anchor.ownText) {\n try {\n return ctx.doc.querySelector(anchor.selector);\n } catch (error) {\n return null;\n }\n }\n let peers = anchor.tagName ? anchorRoot(ctx).getElementsByTagName(anchor.tagName) : anchorRoot(ctx).getElementsByTagName(\"*\");\n let matches = [];\n for (let i = 0; i < peers.length; i++) {\n if (ownText(ctx, peers[i]) === anchor.ownText) matches.push(peers[i]);\n }\n if (matches.length === 0) return null;\n if (matches.length === 1) return matches[0];\n for (let j = 0; j < matches.length; j++) {\n if (annotateContextText(ctx, matches[j]) === anchor.contextText) return matches[j];\n }\n return null;\n }\n function ownText(ctx, el) {\n return (el.textContent || \"\").replace(/\\s+/g, \" \").trim();\n }\n function setAnnotateMode(ctx, enabled) {\n ctx.annotateModeEnabled = enabled === true;\n if (ctx.annotateModeEnabled) {\n ensureAnnotateStyles(ctx);\n } else {\n clearAnnotateHover(ctx);\n }\n }\n function pingElement(ctx, selector) {\n if (typeof selector !== \"string\" || !selector) return;\n let el = null;\n try {\n el = ctx.doc.querySelector(selector);\n } catch (error) {}\n if (!el) return;\n ensureAnnotateStyles(ctx);\n el.scrollIntoView({\n behavior: \"smooth\",\n block: \"center\"\n });\n el.classList.add(\"as-preview-pinged\");\n ctx.win.setTimeout(function() {\n el.classList.remove(\"as-preview-pinged\");\n }, 2500);\n }\n function flashElement(ctx, selector) {\n if (typeof selector !== \"string\" || !selector) return;\n let el = null;\n try {\n el = ctx.doc.querySelector(selector);\n } catch (error) {}\n if (!el) return;\n ensureAnnotateStyles(ctx);\n el.classList.add(\"as-preview-flash\");\n ctx.win.setTimeout(function() {\n el.classList.add(\"as-preview-flash-fade\");\n }, 100);\n ctx.win.setTimeout(function() {\n el.classList.remove(\"as-preview-flash\");\n el.classList.remove(\"as-preview-flash-fade\");\n }, 1100);\n }\n function onAnnotateHover(ctx, event) {\n if (!ctx.annotateModeEnabled) return;\n let target = annotateTargetFrom(ctx, ctx.primordials.targetGet ? ctx.primordials.targetGet(event) : event.target);\n if (target === ctx.annotateHoverElement) return;\n clearAnnotateHover(ctx);\n if (!target) return;\n ctx.annotateHoverElement = target;\n target.classList.add(\"as-preview-annotate-hover\");\n }\n function onAnnotateClick(ctx, event) {\n if (!ctx.annotateModeEnabled) return;\n let target = annotateTargetFrom(ctx, ctx.primordials.targetGet ? ctx.primordials.targetGet(event) : event.target);\n if (!target) return;\n event.preventDefault();\n event.stopPropagation();\n let selected = ctx.win.getSelection();\n if (selected && !selected.isCollapsed && selected.toString().trim()) return;\n let rect = target.getBoundingClientRect();\n send(ctx, {\n kind: \"element-annotate\",\n selector: cssPath(ctx, target),\n label: elementLabel(ctx, target),\n contextText: annotateContextText(ctx, target),\n ownText: ownText(ctx, target),\n tagName: target.tagName,\n rect: {\n top: rect.top,\n left: rect.left,\n width: rect.width,\n height: rect.height\n }\n });\n }\n\n function ensureCommentStyles(ctx) {\n if (ctx.doc.getElementById(highlightStyleId())) return;\n let style = ctx.doc.createElement(\"style\");\n style.setAttribute(anchorIgnoreAttribute(), \"\");\n style.id = highlightStyleId();\n style.textContent = \".ash-comment-highlight-badge::after{content:attr(data-count);}\";\n ctx.doc.head.appendChild(style);\n }\n function clearMarks(ctx, preserveBadges = false) {\n for (let i = 0; i < ctx.badges.length; i++) {\n if (preserveBadges) ctx.reusableBadges.set(ctx.badges[i].badge.dataset.threadId, ctx.badges[i].badge);\n else ctx.badges[i].badge.remove();\n }\n ctx.badges = [];\n ctx.paintedAnchors = [];\n if (typeof ctx.win.CSS !== \"undefined\" && ctx.win.CSS.highlights) {\n ctx.highlightNames.forEach(function(name) {\n ctx.win.CSS.highlights.delete(name);\n });\n }\n ctx.highlightNames = [];\n ctx.textPaints = [];\n let svgOverlays = ctx.doc.querySelectorAll(\".ash-comment-highlight-svg\");\n for (let s = 0; s < svgOverlays.length; s++) svgOverlays[s].remove();\n if (!preserveBadges) ctx.svgActiveThreads = {};\n ctx.appliedHighlightKey = \"\";\n let style = ctx.doc.getElementById(highlightStyleId());\n if (style) style.textContent = \".ash-comment-highlight-badge::after{content:attr(data-count);}\";\n }\n function paintIntact(ctx, highlightsById) {\n let style = ctx.doc.getElementById(highlightStyleId());\n if (ctx.paintedAnchors.length && (!style || !style.isConnected || style.textContent !== textPaintCss(ctx))) return false;\n if (typeof ctx.win.CSS !== \"undefined\" && ctx.win.CSS.highlights) {\n for (let i = 0; i < ctx.textPaints.length; i++) {\n let paint = ctx.textPaints[i];\n if (ctx.win.CSS.highlights.get(paint.name) !== paint.highlight || paint.highlight.size !== paint.ranges.length) return false;\n for (let j = 0; j < paint.ranges.length; j++) {\n if (!paint.highlight.has(paint.ranges[j])) return false;\n }\n }\n }\n for (let i = 0; i < ctx.badges.length; i++) {\n let entry = ctx.badges[i];\n if (!highlightsById.has(entry.highlight.threadId) || !entry.badge.isConnected) return false;\n if (entry.overlays) {\n let shapes = Object.values(entry.overlays);\n for (let j = 0; j < shapes.length; j++) {\n if (!shapes[j].isConnected) return false;\n }\n }\n }\n return ctx.paintedAnchors.every(function(entry) {\n let next = highlightsById.get(entry.highlight.threadId);\n if (!next || next.ranges.length !== entry.ranges.length) return false;\n for (let i = 0; i < entry.ranges.length; i++) {\n let range = entry.ranges[i];\n let current = next.ranges[i];\n if (range.startContainer !== current.startContainer || range.startOffset !== current.startOffset || range.endContainer !== current.endContainer || range.endOffset !== current.endOffset) return false;\n }\n if (entry.groups.length) {\n let groups = svgTextRange(ctx, entry.ranges);\n if (groups.length !== entry.groups.length) return false;\n for (let i = 0; i < groups.length; i++) {\n let group = groups[i];\n let previous = entry.groups[i];\n if (group.text !== previous.text || group.start !== previous.start || group.end !== previous.end) return false;\n }\n }\n return true;\n });\n }\n function setCommentLabels(ctx, labels) {\n if (!labels || typeof labels !== \"object\") return;\n if (typeof labels.openOne === \"string\") ctx.commentLabels.openOne = labels.openOne;\n if (typeof labels.openOther === \"string\") ctx.commentLabels.openOther = labels.openOther;\n if (typeof labels.resolvedOne === \"string\") ctx.commentLabels.resolvedOne = labels.resolvedOne;\n if (typeof labels.resolvedOther === \"string\") ctx.commentLabels.resolvedOther = labels.resolvedOther;\n }\n function commentLabel(ctx, highlight) {\n let count = highlight.count || 1;\n let template = highlight.status === \"resolved\" ? count === 1 ? ctx.commentLabels.resolvedOne : ctx.commentLabels.resolvedOther : count === 1 ? ctx.commentLabels.openOne : ctx.commentLabels.openOther;\n let label = template.replace(/\\{n\\}/g, String(count));\n return highlight.quotedText ? label + \": \" + highlight.quotedText : label;\n }\n function parseRgbColor(ctx, value) {\n if (!value || value === \"transparent\") return null;\n let match = value.match(/^rgba?\\(\\s*([\\d.]+)\\s*,\\s*([\\d.]+)\\s*,\\s*([\\d.]+)(?:\\s*,\\s*([\\d.]+))?\\s*\\)$/);\n if (!match) return null;\n return [\n parseFloat(match[1]),\n parseFloat(match[2]),\n parseFloat(match[3]),\n match[4] === undefined ? 1 : parseFloat(match[4])\n ];\n }\n function rgbToLuminance(ctx, r, g, b) {\n return .2126 * (r / 255) + .7152 * (g / 255) + .0722 * (b / 255);\n }\n function parseColorValue(ctx, value) {\n if (!value || value === \"transparent\") return { type: \"none\" };\n let rgb = parseRgbColor(ctx, value);\n if (rgb) {\n return {\n type: \"rgb\",\n r: rgb[0],\n g: rgb[1],\n b: rgb[2],\n a: rgb[3]\n };\n }\n let modernMatch = value.match(/^oklch\\(\\s*([\\d.]+)(%?)[^/)]*(?:\\/\\s*([\\d.]+)(%?))?/);\n if (modernMatch) {\n let lightness = parseFloat(modernMatch[1]);\n if (modernMatch[2] === \"%\") lightness = lightness / 100;\n let oklchAlpha = modernMatch[3] === undefined ? 1 : parseFloat(modernMatch[3]);\n if (modernMatch[4] === \"%\") oklchAlpha = oklchAlpha / 100;\n return {\n type: \"luminance\",\n value: lightness,\n a: oklchAlpha\n };\n }\n modernMatch = value.match(/^lab\\(\\s*([\\d.]+)(%?)[^/)]*(?:\\/\\s*([\\d.]+)(%?))?/);\n if (modernMatch) {\n let labLightness = parseFloat(modernMatch[1]);\n if (modernMatch[2] === \"%\") labLightness = labLightness / 100;\n else labLightness = labLightness / 100;\n let labAlpha = modernMatch[3] === undefined ? 1 : parseFloat(modernMatch[3]);\n if (modernMatch[4] === \"%\") labAlpha = labAlpha / 100;\n return {\n type: \"luminance\",\n value: labLightness,\n a: labAlpha\n };\n }\n modernMatch = value.match(/^color\\(\\s*(?:display-p3|srgb)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)[^/)]*(?:\\/\\s*([\\d.]+)(%?))?/);\n if (modernMatch) {\n let colorAlpha = modernMatch[4] === undefined ? 1 : parseFloat(modernMatch[4]);\n if (modernMatch[5] === \"%\") colorAlpha = colorAlpha / 100;\n return {\n type: \"luminance\",\n value: .2126 * parseFloat(modernMatch[1]) + .7152 * parseFloat(modernMatch[2]) + .0722 * parseFloat(modernMatch[3]),\n a: colorAlpha\n };\n }\n return { type: \"none\" };\n }\n function resolveBackgroundRgb(ctx, el) {\n while (el) {\n let parsed = parseColorValue(ctx, ctx.win.getComputedStyle(el).backgroundColor);\n if (parsed.type === \"none\") {\n el = el.parentElement;\n continue;\n }\n if (parsed.type === \"luminance\") {\n if (parsed.a === 0) {\n el = el.parentElement;\n continue;\n }\n let gray = parsed.value * 255;\n if (parsed.a < 1) {\n let ancestorRgb = resolveBackgroundRgb(ctx, el.parentElement);\n let lumAlpha = parsed.a;\n return [\n gray * lumAlpha + ancestorRgb[0] * (1 - lumAlpha),\n gray * lumAlpha + ancestorRgb[1] * (1 - lumAlpha),\n gray * lumAlpha + ancestorRgb[2] * (1 - lumAlpha)\n ];\n }\n return [\n gray,\n gray,\n gray\n ];\n }\n if (parsed.type === \"rgb\") {\n if (parsed.a === 0) {\n el = el.parentElement;\n continue;\n }\n if (parsed.a < 1) {\n let ancestorRgb = resolveBackgroundRgb(ctx, el.parentElement);\n let alpha = parsed.a;\n return [\n parsed.r * alpha + ancestorRgb[0] * (1 - alpha),\n parsed.g * alpha + ancestorRgb[1] * (1 - alpha),\n parsed.b * alpha + ancestorRgb[2] * (1 - alpha)\n ];\n }\n return [\n parsed.r,\n parsed.g,\n parsed.b\n ];\n }\n }\n return [\n 255,\n 255,\n 255\n ];\n }\n function resolvedLuminance(ctx, element) {\n function resolveFrom(el) {\n while (el) {\n let parsed = parseColorValue(ctx, ctx.win.getComputedStyle(el).backgroundColor);\n if (parsed.type === \"none\") {\n el = el.parentElement;\n continue;\n }\n if (parsed.type === \"luminance\") {\n if (parsed.a === 0) {\n el = el.parentElement;\n continue;\n }\n if (parsed.a < 1) {\n let ancestor = resolveFrom(el.parentElement);\n let ancestorLum = ancestor !== null ? ancestor : 1;\n return parsed.value * parsed.a + ancestorLum * (1 - parsed.a);\n }\n return parsed.value;\n }\n if (parsed.type === \"rgb\") {\n if (parsed.a === 0) {\n el = el.parentElement;\n continue;\n }\n if (parsed.a < 1) {\n let ancestorRgb = resolveBackgroundRgb(ctx, el.parentElement);\n let alpha = parsed.a;\n return rgbToLuminance(ctx, parsed.r * alpha + ancestorRgb[0] * (1 - alpha), parsed.g * alpha + ancestorRgb[1] * (1 - alpha), parsed.b * alpha + ancestorRgb[2] * (1 - alpha));\n }\n return rgbToLuminance(ctx, parsed.r, parsed.g, parsed.b);\n }\n }\n return null;\n }\n let result = resolveFrom(element);\n return result !== null ? result : 1;\n }\n function isDarkBackground(ctx, element) {\n return resolvedLuminance(ctx, element) < .5;\n }\n function isDarkBackgroundForSvgText(ctx, text) {\n if (!text) return isDarkBackground(ctx, ctx.doc.body);\n let fill = ctx.win.getComputedStyle(text).fill;\n let parsed = parseColorValue(ctx, fill);\n if (parsed.type === \"rgb\" && parsed.a > 0) return rgbToLuminance(ctx, parsed.r, parsed.g, parsed.b) >= .5;\n if (parsed.type === \"luminance\" && parsed.a > 0) return parsed.value >= .5;\n return isDarkBackground(ctx, text);\n }\n function textPaintCss(ctx) {\n return \".ash-comment-highlight-badge::after{content:attr(data-count);}\" + ctx.textPaints.map(function(paint) {\n return \"::highlight(\" + paint.name + \"){background-color:\" + paint.palette.markBg + \";text-decoration:underline;text-decoration-color:\" + (paint.active ? paint.palette.outline : paint.palette.markUnderline) + \";text-decoration-thickness:\" + (paint.active ? \"3px\" : \"2px\") + \";}\";\n }).join(\"\");\n }\n function refreshTextPaints(ctx) {\n let style = ctx.doc.getElementById(highlightStyleId());\n if (!style) return;\n let css = textPaintCss(ctx);\n if (style.textContent !== css) style.textContent = css;\n }\n function highlightPalette(ctx, isDark, resolved) {\n if (isDark) {\n if (resolved) {\n return {\n markBg: \"rgba(134,197,165,.14)\",\n markUnderline: \"rgba(134,197,165,.75)\",\n outline: \"#86c5a5\",\n badgeBorder: \"rgba(134,197,165,.75)\",\n badgeText: \"#86c5a5\",\n badgeBg: \"#1f2937\",\n badgeTargetBorder: \"#86c5a5\",\n badgeTargetText: \"#fff\",\n badgeTargetBg: \"#86c5a5\"\n };\n }\n return {\n markBg: \"rgba(96,165,250,.16)\",\n markUnderline: \"rgba(96,165,250,.85)\",\n outline: \"#60a5fa\",\n badgeBorder: \"rgba(96,165,250,.85)\",\n badgeText: \"#60a5fa\",\n badgeBg: \"#1f2937\",\n badgeTargetBorder: \"#60a5fa\",\n badgeTargetText: \"#fff\",\n badgeTargetBg: \"#60a5fa\"\n };\n }\n if (resolved) {\n return {\n markBg: \"rgba(68,131,97,.12)\",\n markUnderline: \"rgba(68,131,97,.58)\",\n outline: \"#448361\",\n badgeBorder: \"rgba(68,131,97,.36)\",\n badgeText: \"#448361\",\n badgeBg: \"#fff\",\n badgeTargetBorder: \"#448361\",\n badgeTargetText: \"#fff\",\n badgeTargetBg: \"#448361\"\n };\n }\n return {\n markBg: \"rgba(37,99,235,.16)\",\n markUnderline: \"rgba(37,99,235,.72)\",\n outline: \"#2383e2\",\n badgeBorder: \"rgba(35,131,226,.44)\",\n badgeText: \"#2383e2\",\n badgeBg: \"#fff\",\n badgeTargetBorder: \"#2383e2\",\n badgeTargetText: \"#fff\",\n badgeTargetBg: \"#2383e2\"\n };\n }\n function wrapRange(ctx, highlight, ranges, covered) {\n if (!ranges.length) return;\n let groups = !covered && ctx.doc.querySelector(\"svg text\") ? svgTextRange(ctx, ranges) : [];\n ctx.paintedAnchors.push({\n highlight,\n ranges,\n groups\n });\n if (covered) return;\n let svgWrapped = wrapSvgRange(ctx, highlight, groups);\n ensureCommentStyles(ctx);\n let name = \"ash-comment-\" + ctx.highlightNames.length;\n let palette = highlightPalette(ctx, isDarkBackground(ctx, ranges[0].startContainer.parentElement), highlight.status === \"resolved\");\n if (typeof ctx.win.CSS !== \"undefined\" && ctx.win.CSS.highlights && typeof ctx.win.Highlight !== \"undefined\") {\n let paint = new ctx.win.Highlight(...ranges);\n ctx.win.CSS.highlights.set(name, paint);\n ctx.highlightNames.push(name);\n ctx.textPaints.push({\n name,\n highlight: paint,\n ranges,\n threadId: highlight.threadId,\n palette,\n active: highlight.target,\n target: highlight.target\n });\n refreshTextPaints(ctx);\n }\n if (svgWrapped) return;\n let badge = takeBadge(ctx, highlight);\n badge.setAttribute(anchorIgnoreAttribute(), \"\");\n badge.type = \"button\";\n badge.className = \"ash-comment-highlight-badge\";\n badge.setAttribute(\"aria-label\", commentLabel(ctx, highlight));\n badge.dataset.threadId = highlight.threadId;\n badge.dataset.count = String(highlight.count || 1);\n badge.style.cssText = badgeStyleForHighlight(ctx, highlight, isDarkBackground(ctx, ranges[0].startContainer.parentElement));\n ctx.badges.push({\n badge,\n highlight,\n measure: function() {\n let rects = [];\n let lastElement = null;\n ranges.forEach(function(range) {\n let current = Array.from(range.getClientRects());\n if (current.length) {\n rects.push(...current);\n lastElement = range.startContainer.parentElement;\n }\n });\n return isBadgeAnchorVisible(ctx, lastElement) ? rects : [];\n }\n });\n }\n function missingState(ctx, id, checking) {\n if (!ctx.checkingDeadlines[id]) ctx.checkingDeadlines[id] = Date.now() + 3e3;\n let deadline = ctx.checkingDeadlines[id];\n if (Date.now() < deadline) {\n checking.push(deadline);\n return \"checking\";\n }\n return \"needs-check\";\n }\n function scheduleChecking(ctx, retryDelay = 0) {\n if (ctx.checkingTimer) ctx.win.clearTimeout(ctx.checkingTimer);\n let deadlines = ctx.checkingHighlights.concat(ctx.checkingAnchors);\n if (!deadlines.length) {\n ctx.checkingTimer = undefined;\n return;\n }\n ctx.checkingTimer = ctx.win.setTimeout(function() {\n ctx.checkingTimer = undefined;\n let completed = false;\n try {\n let engine = createTextAnchorEngine(anchorRoot(ctx));\n try {\n applyHighlights(ctx, ctx.pendingHighlights, engine);\n } finally {\n verifyAnchors(ctx, ctx.pendingAnchors, engine);\n }\n completed = true;\n } finally {\n scheduleChecking(ctx, completed ? 0 : Math.min(1e3, Math.max(1, retryDelay * 2)));\n }\n }, Math.max(1, retryDelay, Math.min.apply(null, deadlines) - Date.now()));\n }\n function applyHighlights(ctx, list, engine) {\n ctx.anchorSnapshotGeneration++;\n ctx.pendingHighlights = Array.isArray(list) ? list : [];\n if (!ctx.pendingHighlights.length) {\n ctx.checkingHighlights = [];\n ctx.lastResolutionSignature = \"\";\n scheduleChecking(ctx);\n clearMarks(ctx);\n return;\n }\n let checking = [];\n let forcePaint = !!engine;\n engine = engine || createTextAnchorEngine(anchorRoot(ctx));\n ctx.measuredText = engine.text;\n let results = [];\n let resolvedHighlights = ctx.pendingHighlights.map(function(highlight) {\n let resolved = engine.resolve(highlight);\n return {\n highlight: resolved ? {\n ...highlight,\n ...resolved\n } : highlight,\n resolved,\n ranges: resolved ? engine.ranges(resolved.textStart, resolved.textEnd) : []\n };\n });\n let highlightsById = new Map(resolvedHighlights.map(function(entry) {\n return [entry.highlight.threadId, entry];\n }));\n let paintKey = JSON.stringify(resolvedHighlights.map(function(entry) {\n let palettes = entry.ranges.map(function(range) {\n let element = range.startContainer.parentElement;\n let svgText = element.closest(\"svg text\") && element.closest(\"text,tspan,textPath\");\n return [isDarkBackground(ctx, element), svgText ? isDarkBackgroundForSvgText(ctx, svgText) : null];\n });\n return [\n entry.highlight.threadId,\n entry.highlight.status,\n entry.highlight.target,\n palettes,\n entry.resolved && entry.resolved.textStart,\n entry.resolved && entry.resolved.textEnd\n ];\n }).sort(function(left, right) {\n return left[0].localeCompare(right[0]);\n }));\n let repaint = forcePaint || ctx.appliedHighlightKey !== paintKey || !paintIntact(ctx, highlightsById);\n if (repaint) clearMarks(ctx, true);\n else {\n ctx.paintedAnchors.forEach(function(entry) {\n entry.highlight = highlightsById.get(entry.highlight.threadId).highlight;\n });\n ctx.badges.forEach(function(entry) {\n let highlight = highlightsById.get(entry.highlight.threadId).highlight;\n entry.highlight = highlight;\n if (entry.badge.dataset.threadId !== highlight.threadId) entry.badge.dataset.threadId = highlight.threadId;\n let count = String(highlight.count || 1), label = commentLabel(ctx, highlight);\n if (entry.badge.dataset.count !== count) entry.badge.dataset.count = count;\n if (entry.badge.getAttribute(\"aria-label\") !== label) entry.badge.setAttribute(\"aria-label\", label);\n });\n }\n resolvedHighlights.forEach(function(entry) {\n let highlight = entry.highlight, resolved = entry.resolved;\n let covered = false;\n if (resolved && highlight.status === \"resolved\") {\n for (let i = 0; i < resolvedHighlights.length; i++) {\n let other = resolvedHighlights[i];\n if (other.highlight.status !== \"resolved\" && other.resolved && resolved.textStart < other.resolved.textEnd && other.resolved.textStart < resolved.textEnd) {\n covered = true;\n break;\n }\n }\n }\n if (resolved) {\n delete ctx.checkingDeadlines[highlight.threadId];\n if (repaint) wrapRange(ctx, entry.highlight, entry.ranges, covered);\n }\n results.push({\n threadId: highlight.threadId,\n state: resolved ? \"attached\" : missingState(ctx, highlight.threadId, checking),\n textStart: resolved ? resolved.textStart : null,\n textEnd: resolved ? resolved.textEnd : null,\n textHash: resolved ? engine.hash : null\n });\n });\n ctx.reusableBadges.forEach(function(badge) {\n badge.remove();\n });\n ctx.reusableBadges.clear();\n ctx.appliedHighlightKey = paintKey;\n positionBadges(ctx);\n let signature = JSON.stringify([\n ctx.displayedVersionId,\n ctx.displayedPath,\n results.map(function(result) {\n return [\n result.threadId,\n result.state,\n result.textStart,\n result.textEnd\n ];\n })\n ]);\n if (signature !== ctx.lastResolutionSignature) for (let offset = 0; offset < results.length; offset += 100) {\n send(ctx, {\n kind: \"anchor-resolutions\",\n token: ctx.documentToken,\n versionId: ctx.displayedVersionId,\n targetPath: ctx.displayedPath,\n generation: ++ctx.resolutionGeneration,\n results: results.slice(offset, offset + 100)\n });\n }\n ctx.lastResolutionSignature = signature;\n ctx.checkingHighlights = checking;\n scheduleChecking(ctx);\n }\n function invalidateChangedPaint(ctx, engine) {\n ctx.paintedAnchors = ctx.paintedAnchors.filter(function(entry) {\n let first = entry.ranges[0];\n let last = entry.ranges[entry.ranges.length - 1];\n if (engine.paintedText(first, last) === engine.normalizedQuote(entry.highlight)) return true;\n ctx.appliedHighlightKey = \"\";\n let id = entry.highlight.threadId;\n ctx.textPaints = ctx.textPaints.filter(function(paint) {\n if (paint.threadId !== id) return true;\n if (typeof ctx.win.CSS !== \"undefined\" && ctx.win.CSS.highlights) ctx.win.CSS.highlights.delete(paint.name);\n return false;\n });\n ctx.badges = ctx.badges.filter(function(badgeEntry) {\n if (badgeEntry.badge.dataset.threadId !== id) return true;\n badgeEntry.badge.remove();\n return false;\n });\n ctx.doc.querySelectorAll(\".ash-comment-highlight-svg\").forEach(function(shape) {\n if (shape.dataset.threadId === id) shape.remove();\n });\n return false;\n });\n }\n function scrollToThread(ctx, id) {\n let painted = ctx.paintedAnchors.find(function(entry) {\n return entry.highlight.threadId === id;\n });\n if (painted && painted.ranges.length) {\n let start = painted.ranges[0].startContainer;\n let target = start.nodeType === 1 ? start : start.parentElement;\n if (target) {\n target.scrollIntoView({\n block: \"center\",\n inline: \"nearest\",\n behavior: \"instant\"\n });\n let range = painted.ranges[0];\n for (let ancestor = target; ancestor && ancestor !== ctx.doc.scrollingElement; ancestor = ancestor.parentElement) {\n let style = ctx.win.getComputedStyle(ancestor);\n let scrollX = /(auto|scroll|hidden|overlay)/.test(style.overflowX) && ancestor.scrollWidth > ancestor.clientWidth;\n let scrollY = /(auto|scroll|hidden|overlay)/.test(style.overflowY) && ancestor.scrollHeight > ancestor.clientHeight;\n if (!scrollX && !scrollY) continue;\n let rect = range.getClientRects()[0];\n if (!rect) return;\n let box = ancestor.getBoundingClientRect();\n let scaleX = ancestor.offsetWidth ? box.width / ancestor.offsetWidth : 1;\n let scaleY = ancestor.offsetHeight ? box.height / ancestor.offsetHeight : 1;\n if (!scaleX || !scaleY) continue;\n let left = box.left + ancestor.clientLeft * scaleX;\n let top = box.top + ancestor.clientTop * scaleY;\n let width = ancestor.clientWidth * scaleX;\n let height = ancestor.clientHeight * scaleY;\n let dx = rect.left < left || rect.width > width ? rect.left - left : Math.max(0, rect.right - left - width);\n ancestor.scrollBy({\n left: scrollX ? dx / scaleX : 0,\n top: scrollY ? (rect.top + rect.height / 2 - top - height / 2) / scaleY : 0,\n behavior: \"instant\"\n });\n }\n let visible = range.getClientRects()[0];\n if (visible) {\n let viewportWidth = ctx.doc.documentElement.clientWidth;\n ctx.win.scrollBy({\n left: visible.left < 0 || visible.width > viewportWidth ? visible.left : Math.max(0, visible.right - viewportWidth),\n top: visible.top + visible.height / 2 - ctx.doc.documentElement.clientHeight / 2,\n behavior: \"instant\"\n });\n }\n schedulePositionBadges(ctx);\n }\n return;\n }\n let element = ctx.doc.querySelector(\".ash-comment-highlight[data-thread-id=\\\"\" + ctx.win.CSS.escape(id) + \"\\\"], .ash-comment-highlight-badge[data-thread-id=\\\"\" + ctx.win.CSS.escape(id) + \"\\\"], .ash-comment-highlight-svg[data-thread-id=\\\"\" + ctx.win.CSS.escape(id) + \"\\\"]\");\n if (element) element.scrollIntoView({\n block: \"center\",\n behavior: \"smooth\"\n });\n }\n\n function requestMermaidRendering(ctx) {\n if (ctx.mermaidRequested) return;\n if (!ctx.doc.body || !ctx.doc.body.hasAttribute(\"data-artifact-markdown\")) return;\n let blocks = ctx.doc.querySelectorAll(\"pre code.language-mermaid\");\n let diagrams = [];\n for (let index = 0; index < blocks.length && diagrams.length < 16; index++) {\n let source = blocks[index].textContent || \"\";\n if (!source || source.length > 2e4) continue;\n let pre = blocks[index].closest(\"pre\");\n if (!pre) continue;\n let id = \"artifactshare-mermaid-\" + index;\n ctx.mermaidBlocks[id] = pre;\n diagrams[diagrams.length] = {\n id,\n source\n };\n }\n if (diagrams.length) {\n ctx.mermaidRequested = true;\n send(ctx, {\n kind: \"mermaid-render-request\",\n renderToken: ctx.readyChallenge,\n diagrams\n });\n }\n }\n function installMermaidResults(ctx, renderToken, results) {\n if (renderToken !== ctx.readyChallenge) return;\n if (!Array.isArray(results)) return;\n for (let index = 0; index < results.length; index++) {\n let result = results[index] || {};\n let pre = typeof result.id === \"string\" ? ctx.mermaidBlocks[result.id] : null;\n if (!pre || typeof result.svg !== \"string\" || !result.svg.startsWith(\"<svg\")) continue;\n let svgDocument = new ctx.win.DOMParser().parseFromString(result.svg, \"image/svg+xml\");\n let svg = svgDocument.documentElement;\n if (svg.localName !== \"svg\" || svg.namespaceURI !== \"http://www.w3.org/2000/svg\" || svgDocument.querySelector(\"parsererror\")) continue;\n let container = ctx.doc.createElement(\"div\");\n container.className = \"mermaid-diagram\";\n container.appendChild(ctx.doc.importNode(svg, true));\n pre.dataset.mermaidRendered = \"true\";\n pre.hidden = true;\n pre.before(container);\n delete ctx.mermaidBlocks[result.id];\n }\n schedulePositionBadges(ctx);\n }\n\n function send(ctx, message) {\n try {\n let payload = createMessagePayload(ctx.primordials, message);\n ctx.primordials.savedPostMessage(ctx.primordials.savedParent, payload, \"*\");\n } catch (e) {}\n }\n function ready(ctx) {\n if (ctx.readyChallenge && ctx.documentToken) {\n send(ctx, {\n kind: \"ready\",\n challenge: ctx.readyChallenge,\n token: ctx.documentToken\n });\n }\n }\n function onReadyCheck(ctx, event) {\n let message = event && event.data;\n if (!event || event.source !== ctx.primordials.savedParent || !message || message.source !== \"artifactshare-parent\" || message.kind !== \"ready-check\") return;\n if (typeof message.challenge !== \"string\" || !message.challenge) return;\n ctx.readyChallenge = message.challenge;\n requestMermaidRendering(ctx);\n ready(ctx);\n }\n function readEventValue(ctx, getter, event) {\n if (!getter) return null;\n try {\n return getter(event);\n } catch (e) {\n return null;\n }\n }\n function createMessagePayload(primitives, message) {\n const payload = primitives.objectCreate(null);\n payload.source = \"artifactshare\";\n const keys = primitives.objectKeys(message);\n for (let index = 0; index < keys.length; index++) {\n const key = keys[index];\n payload[key] = message[key];\n }\n return payload;\n }\n function installMessageListener(ctx) {\n ctx.primordials.savedAddEventListener(\"message\", function(event) {\n let data = event.data || {};\n if (event.source !== ctx.primordials.savedParent || data.source !== \"artifactshare-parent\") {\n return;\n }\n if (data.kind === \"ready-check\") {\n onReadyCheck(ctx, event);\n ctx.displayedVersionId = data.versionId || ctx.displayedVersionId;\n ctx.displayedPath = data.targetPath || ctx.displayedPath;\n ctx.textAnchorsEnabled = data.textAnchorsEnabled === true;\n setCommentLabels(ctx, data.commentLabels);\n } else if (data.kind === \"external-link-policy\" && (data.mode === \"parent\" || data.mode === \"direct\")) {\n ctx.externalLinkPolicyMode = data.mode;\n } else if (data.kind === \"comment-highlights\") {\n ctx.textAnchorsEnabled = data.textAnchorsEnabled === true;\n setCommentLabels(ctx, data.commentLabels);\n ctx.displayedVersionId = data.versionId || null;\n ctx.displayedPath = data.targetPath || null;\n applyHighlights(ctx, data.highlights);\n } else if (data.kind === \"scroll-to-comment\") {\n scrollToThread(ctx, data.threadId);\n } else if (data.kind === \"mermaid-rendered\") {\n installMermaidResults(ctx, data.renderToken, data.results);\n } else if (data.kind === \"annotate-mode\") {\n setAnnotateMode(ctx, data.enabled);\n } else if (data.kind === \"element-ping\") {\n pingElement(ctx, data.selector);\n } else if (data.kind === \"element-flash\") {\n flashElement(ctx, data.selector);\n } else if (data.kind === \"verify-anchors\") {\n if (Number.isSafeInteger(ctx.pendingVerificationId) && Number.isSafeInteger(data.verificationId) && data.verificationId < ctx.pendingVerificationId) return;\n ctx.pendingVerificationId = data.verificationId;\n verifyAnchors(ctx, data.anchors);\n }\n });\n }\n\n function installCspViolations(ctx) {\n ctx.doc.addEventListener(VIOLATION_REPORTER_MARKER, function(event) {\n send(ctx, {\n kind: \"csp-violation\",\n directive: event.violatedDirective || event.effectiveDirective,\n blockedURI: event.blockedURI || \"inline\",\n sourceFile: event.sourceFile || null,\n lineNumber: event.lineNumber || null\n });\n });\n }\n\n function updateMarkdownToc(ctx) {\n let links = ctx.doc.querySelectorAll(\".md-toc a[href^=\\\"#\\\"]\");\n if (!links.length) return;\n let activeId = null;\n for (let index = 0; index < links.length; index++) {\n let id = links[index].getAttribute(\"href\").slice(1);\n let heading = ctx.doc.getElementById(id);\n if (heading && heading.getBoundingClientRect().top <= 96) activeId = id;\n }\n if (!activeId) activeId = links[0].getAttribute(\"href\").slice(1);\n for (let linkIndex = 0; linkIndex < links.length; linkIndex++) {\n if (links[linkIndex].getAttribute(\"href\").slice(1) === activeId) {\n links[linkIndex].setAttribute(\"aria-current\", \"location\");\n } else {\n links[linkIndex].removeAttribute(\"aria-current\");\n }\n }\n }\n function installCodeCopy(ctx) {\n ctx.doc.addEventListener(\"click\", function(event) {\n let target = event.target;\n let button = target && target.closest && target.closest(\"[data-code-copy]\");\n if (!button) return;\n let block = button.closest(\".md-code-block\");\n let code = block && block.querySelector(\"pre code\");\n if (!code) return;\n event.preventDefault();\n event.stopPropagation();\n let copied = function() {\n button.textContent = \"Copied\";\n button.setAttribute(\"aria-label\", \"Code copied\");\n ctx.win.setTimeout(function() {\n button.textContent = \"Copy\";\n button.setAttribute(\"aria-label\", \"Copy code\");\n }, 1500);\n };\n let fallback = function() {\n let textarea = ctx.doc.createElement(\"textarea\");\n textarea.setAttribute(anchorIgnoreAttribute(), \"\");\n textarea.value = code.textContent || \"\";\n textarea.style.position = \"fixed\";\n textarea.style.opacity = \"0\";\n ctx.doc.body.appendChild(textarea);\n textarea.select();\n try {\n if (ctx.doc.execCommand(\"copy\")) copied();\n } catch (error) {}\n textarea.remove();\n };\n if (ctx.win.navigator.clipboard && ctx.win.navigator.clipboard.writeText) {\n ctx.win.navigator.clipboard.writeText(code.textContent || \"\").then(copied, fallback);\n } else {\n fallback();\n }\n });\n }\n\n function rebuildAfterMutations(ctx) {\n let hasText = ctx.pendingHighlights.length > 0;\n for (let i = 0; !hasText && i < ctx.pendingAnchors.length; i++) {\n if (ctx.pendingAnchors[i].kind === \"text\") hasText = true;\n }\n if (!hasText) {\n verifyAnchors(ctx, ctx.pendingAnchors);\n return;\n }\n let engine = createTextAnchorEngine(anchorRoot(ctx));\n if (engine.text === ctx.measuredText) {\n ctx.win.clearTimeout(ctx.resolveTimer);\n ctx.resolveStartedAt = 0;\n try {\n applyHighlights(ctx, ctx.pendingHighlights, engine);\n } finally {\n verifyAnchors(ctx, ctx.pendingAnchors, engine);\n }\n } else {\n invalidateChangedPaint(ctx, engine);\n ctx.win.clearTimeout(ctx.resolveTimer);\n if (!ctx.resolveStartedAt) ctx.resolveStartedAt = Date.now();\n let snapshotGeneration = ctx.anchorSnapshotGeneration;\n ctx.resolveTimer = ctx.win.setTimeout(function() {\n ctx.resolveStartedAt = 0;\n if (snapshotGeneration !== ctx.anchorSnapshotGeneration) engine = createTextAnchorEngine(anchorRoot(ctx));\n try {\n applyHighlights(ctx, ctx.pendingHighlights, engine);\n } finally {\n verifyAnchors(ctx, ctx.pendingAnchors, engine);\n }\n }, Math.min(300, Math.max(0, 1e3 - (Date.now() - ctx.resolveStartedAt))));\n }\n }\n function handleMutations(ctx, records) {\n let root = anchorRoot(ctx);\n let rootReplaced = root !== ctx.observedAnchorRoot;\n ctx.observedAnchorRoot = root;\n let exclusionChanged = false;\n for (let recordIndex = 0; recordIndex < records.length; recordIndex++) {\n const record = records[recordIndex];\n if (record.type === \"attributes\" && (record.attributeName === anchorIgnoreAttribute() || record.attributeName === commentUiAttribute() || record.attributeName === \"class\")) {\n exclusionChanged = true;\n break;\n }\n }\n if (rootReplaced || exclusionChanged) ctx.anchorSnapshotGeneration++;\n if (!root || !ctx.doc.body || !ctx.pendingHighlights.length && !ctx.pendingAnchors.length) return;\n let hasRelevant = false;\n let hasRelevantContent = false;\n for (let recordIndex = 0; recordIndex < records.length; recordIndex++) {\n const record = records[recordIndex];\n if (record.type !== \"attributes\" && !root.contains(record.target)) continue;\n let element = record.target.nodeType === 1 ? record.target : record.target.parentElement;\n if (element && ctx.primordials.closest(element, ignoredMutationSelector())) continue;\n if (record.type === \"childList\") {\n let hasContentNode = false;\n for (let group = 0; group < 2; group++) {\n const nodes = group === 0 ? record.addedNodes : record.removedNodes;\n for (let index = 0; index < nodes.length; index++) {\n const node = nodes[index];\n if (node.nodeType !== 1 || !ctx.primordials.hasAttribute(node, anchorIgnoreAttribute()) && node.id !== highlightStyleId()) hasContentNode = true;\n }\n }\n if (!hasContentNode) continue;\n }\n hasRelevant = true;\n if (record.type !== \"attributes\") hasRelevantContent = true;\n }\n if (!rootReplaced && !hasRelevant) return;\n schedulePositionBadges(ctx);\n if (rootReplaced || hasRelevantContent) {\n rebuildAfterMutations(ctx);\n }\n }\n function installAnchorObserver(ctx) {\n ctx.observedAnchorRoot = anchorRoot(ctx);\n const observer = new ctx.win.MutationObserver((records) => handleMutations(ctx, records));\n ctx.anchorObserver = observer;\n observer.observe(ctx.doc.documentElement, {\n subtree: true,\n childList: true,\n characterData: true,\n attributes: true\n });\n return observer;\n }\n\n function capturePrimordials(win) {\n const savedParent = win.parent;\n const savedPostMessage = win.Function.prototype.call.bind(savedParent.postMessage);\n const savedAddEventListener = win.addEventListener.bind(win);\n const trustedGetter = win.Object.getOwnPropertyDescriptor(win.Event.prototype, \"isTrusted\");\n const targetGetter = win.Object.getOwnPropertyDescriptor(win.Event.prototype, \"target\");\n const defaultPreventedGetter = win.Object.getOwnPropertyDescriptor(win.Event.prototype, \"defaultPrevented\");\n const persistedGetter = win.PageTransitionEvent ? win.Object.getOwnPropertyDescriptor(win.PageTransitionEvent.prototype, \"persisted\") : undefined;\n const buttonGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"button\");\n const metaKeyGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"metaKey\");\n const ctrlKeyGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"ctrlKey\");\n const shiftKeyGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"shiftKey\");\n const altKeyGetter = win.Object.getOwnPropertyDescriptor(win.MouseEvent.prototype, \"altKey\");\n const trustedGet = trustedGetter && trustedGetter.get ? win.Function.prototype.call.bind(trustedGetter.get) : null;\n const targetGet = targetGetter && targetGetter.get ? win.Function.prototype.call.bind(targetGetter.get) : null;\n const defaultPreventedGet = defaultPreventedGetter && defaultPreventedGetter.get ? win.Function.prototype.call.bind(defaultPreventedGetter.get) : null;\n const persistedGet = persistedGetter && persistedGetter.get ? win.Function.prototype.call.bind(persistedGetter.get) : null;\n const buttonGet = buttonGetter && buttonGetter.get ? win.Function.prototype.call.bind(buttonGetter.get) : null;\n const metaKeyGet = metaKeyGetter && metaKeyGetter.get ? win.Function.prototype.call.bind(metaKeyGetter.get) : null;\n const ctrlKeyGet = ctrlKeyGetter && ctrlKeyGetter.get ? win.Function.prototype.call.bind(ctrlKeyGetter.get) : null;\n const shiftKeyGet = shiftKeyGetter && shiftKeyGetter.get ? win.Function.prototype.call.bind(shiftKeyGetter.get) : null;\n const altKeyGet = altKeyGetter && altKeyGetter.get ? win.Function.prototype.call.bind(altKeyGetter.get) : null;\n const preventDefault = win.Function.prototype.call.bind(win.Event.prototype.preventDefault);\n const addEventListener = win.Function.prototype.call.bind(win.EventTarget.prototype.addEventListener);\n const rangeToString = win.Function.prototype.call.bind(win.Range.prototype.toString);\n const arrayMap = win.Function.prototype.call.bind(win.Array.prototype.map);\n const weakMapDelete = win.Function.prototype.call.bind(win.WeakMap.prototype.delete);\n const weakMapGet = win.Function.prototype.call.bind(win.WeakMap.prototype.get);\n const weakMapSet = win.Function.prototype.call.bind(win.WeakMap.prototype.set);\n const defineProperty = win.Object.defineProperty;\n const objectCreate = win.Object.create;\n const objectKeys = win.Object.keys;\n const closest = win.Function.prototype.call.bind(win.Element.prototype.closest);\n const getAttribute = win.Function.prototype.call.bind(win.Element.prototype.getAttribute);\n const hasAttribute = win.Function.prototype.call.bind(win.Element.prototype.hasAttribute);\n return {\n savedParent,\n savedPostMessage,\n savedAddEventListener,\n trustedGetter,\n targetGetter,\n defaultPreventedGetter,\n buttonGetter,\n metaKeyGetter,\n ctrlKeyGetter,\n shiftKeyGetter,\n altKeyGetter,\n trustedGet,\n targetGet,\n defaultPreventedGet,\n persistedGet,\n buttonGet,\n metaKeyGet,\n ctrlKeyGet,\n shiftKeyGet,\n altKeyGet,\n preventDefault,\n addEventListener,\n rangeToString,\n arrayMap,\n weakMapDelete,\n weakMapGet,\n weakMapSet,\n defineProperty,\n objectCreate,\n objectKeys,\n closest,\n getAttribute,\n hasAttribute\n };\n }\n\n function createReporterState(win, primordials = capturePrimordials(win)) {\n return {\n win,\n doc: win.document,\n primordials,\n documentToken: \"\",\n readyChallenge: \"\",\n externalLinkPolicyMode: \"parent\",\n pendingLinkClicks: new win.WeakMap(),\n highlightNames: [],\n textPaints: [],\n pendingHighlights: [],\n pendingAnchors: [],\n measuredText: null,\n anchorSnapshotGeneration: 0,\n paintedAnchors: [],\n resolveStartedAt: 0,\n resolveTimer: undefined,\n checkingTimer: undefined,\n checkingDeadlines: {},\n checkingHighlights: [],\n checkingAnchors: [],\n pendingVerificationId: null,\n resolutionGeneration: 0,\n lastResolutionSignature: \"\",\n displayedVersionId: null,\n displayedPath: null,\n badges: [],\n badgeOffsets: {},\n badgeDragged: false,\n appliedHighlightKey: \"\",\n textAnchorsEnabled: false,\n mermaidBlocks: primordials.objectCreate(null),\n mermaidRequested: false,\n commentLabels: {\n openOne: \"Open 1 unresolved comment on this text\",\n openOther: \"Open {n} unresolved comments on this text\",\n resolvedOne: \"Open 1 resolved comment on this text\",\n resolvedOther: \"Open {n} resolved comments on this text\"\n },\n reusableBadges: new win.Map(),\n svgActiveThreads: {},\n svgOverlayStyles: new win.WeakMap(),\n badgePositionFrame: 0,\n annotateModeEnabled: false,\n annotateHoverElement: null,\n readyCount: 0,\n observedAnchorRoot: win.document.body,\n anchorObserver: null,\n readyInterval: 0\n };\n }\n\n function installReporter(win) {\n if (win.parent === win) return;\n const primordials = capturePrimordials(win);\n const ctx = createReporterState(win, primordials);\n try {\n let random = new win.Uint8Array(32);\n ctx.win.crypto.getRandomValues(random);\n ctx.documentToken = ctx.primordials.arrayMap(random, function(byte) {\n return byte.toString(16).padStart(2, \"0\");\n }).join(\"\");\n } catch (e) {\n ctx.documentToken = \"\";\n }\n installAnchorObserver(ctx);\n ctx.primordials.addEventListener(ctx.win, \"pagehide\", function(event) {\n if (readEventValue(ctx, ctx.primordials.persistedGet, event) === true) return;\n ctx.anchorObserver.disconnect();\n ctx.win.clearTimeout(ctx.resolveTimer);\n ctx.win.clearTimeout(ctx.checkingTimer);\n ctx.win.cancelAnimationFrame(ctx.badgePositionFrame);\n clearMarks(ctx);\n });\n ctx.doc.addEventListener(\"click\", function(event) {\n let selection = ctx.win.getSelection();\n if (selection && !selection.isCollapsed) return;\n let badge = hitComment(ctx, event);\n if (!badge) return;\n selectThreadFromElement(ctx, badge, rectFromPointer(ctx, event, badge.getBoundingClientRect()));\n event.preventDefault();\n event.stopPropagation();\n });\n ctx.primordials.addEventListener(ctx.doc, \"mousemove\", (event) => onAnnotateHover(ctx, event), true);\n ctx.primordials.addEventListener(ctx.doc, \"mouseover\", (event) => onAnnotateHover(ctx, event), true);\n ctx.primordials.addEventListener(ctx.doc, \"click\", (event) => onAnnotateClick(ctx, event), true);\n installMessageListener(ctx);\n ctx.doc.addEventListener(\"mouseup\", function() {\n ctx.win.setTimeout(() => sendSelection(ctx), 0);\n });\n ctx.doc.addEventListener(\"keyup\", function() {\n ctx.win.setTimeout(() => sendSelection(ctx), 0);\n });\n installCodeCopy(ctx);\n ctx.primordials.addEventListener(ctx.win, \"click\", (event) => prepareLinkClick(ctx, event), true);\n ctx.primordials.addEventListener(ctx.win, \"click\", (event) => finishLinkClick(ctx, event));\n ctx.doc.addEventListener(\"pointerdown\", (event) => sendOutsidePointerDown(ctx, event));\n installCspViolations(ctx);\n ctx.win.addEventListener(\"resize\", () => schedulePositionBadges(ctx));\n ctx.win.addEventListener(\"scroll\", () => schedulePositionBadges(ctx), true);\n ctx.win.addEventListener(\"load\", function() {\n if (!ctx.pendingHighlights.length && !ctx.pendingAnchors.length) return;\n let engine = createTextAnchorEngine(anchorRoot(ctx));\n try {\n applyHighlights(ctx, ctx.pendingHighlights, engine);\n } finally {\n verifyAnchors(ctx, ctx.pendingAnchors, engine);\n }\n });\n ctx.win.addEventListener(\"load\", () => schedulePositionBadges(ctx));\n ctx.win.addEventListener(\"load\", () => updateMarkdownToc(ctx));\n ctx.win.addEventListener(\"scroll\", () => updateMarkdownToc(ctx), { passive: true });\n if (ctx.doc.fonts && ctx.doc.fonts.ready) {\n ctx.doc.fonts.ready.then(() => schedulePositionBadges(ctx));\n }\n ctx.readyInterval = ctx.win.setInterval(function() {\n ready(ctx);\n if (++ctx.readyCount >= 20) ctx.win.clearInterval(ctx.readyInterval);\n }, 100);\n ready(ctx);\n return ctx;\n }\n\n installReporter(window);\n\n})();";
6160
+ //#endregion
6161
+ //#region ../viewer-kit/src/reporter-constants.ts
6103
6162
  const READY_CHECK_MESSAGE_SOURCE = "artifactshare-parent";
6104
6163
  const READY_CHECK_MESSAGE_KIND = "ready-check";
6105
- const VIOLATION_REPORTER_TAG = `<script>${`(function () {
6106
- if (parent === window) return;
6107
-
6108
- var savedParent = parent;
6109
- var savedPostMessage = savedParent.postMessage.bind(savedParent);
6110
- var savedAddEventListener = window.addEventListener.bind(window);
6111
- var trustedGetter = Object.getOwnPropertyDescriptor(Event.prototype, 'isTrusted');
6112
- var targetGetter = Object.getOwnPropertyDescriptor(Event.prototype, 'target');
6113
- var defaultPreventedGetter = Object.getOwnPropertyDescriptor(Event.prototype, 'defaultPrevented');
6114
- var buttonGetter = Object.getOwnPropertyDescriptor(MouseEvent.prototype, 'button');
6115
- var metaKeyGetter = Object.getOwnPropertyDescriptor(MouseEvent.prototype, 'metaKey');
6116
- var ctrlKeyGetter = Object.getOwnPropertyDescriptor(MouseEvent.prototype, 'ctrlKey');
6117
- var shiftKeyGetter = Object.getOwnPropertyDescriptor(MouseEvent.prototype, 'shiftKey');
6118
- var altKeyGetter = Object.getOwnPropertyDescriptor(MouseEvent.prototype, 'altKey');
6119
- var trustedGet = trustedGetter && trustedGetter.get
6120
- ? Function.prototype.call.bind(trustedGetter.get)
6121
- : null;
6122
- var targetGet = targetGetter && targetGetter.get
6123
- ? Function.prototype.call.bind(targetGetter.get)
6124
- : null;
6125
- var defaultPreventedGet = defaultPreventedGetter && defaultPreventedGetter.get
6126
- ? Function.prototype.call.bind(defaultPreventedGetter.get)
6127
- : null;
6128
- var buttonGet = buttonGetter && buttonGetter.get
6129
- ? Function.prototype.call.bind(buttonGetter.get)
6130
- : null;
6131
- var metaKeyGet = metaKeyGetter && metaKeyGetter.get
6132
- ? Function.prototype.call.bind(metaKeyGetter.get)
6133
- : null;
6134
- var ctrlKeyGet = ctrlKeyGetter && ctrlKeyGetter.get
6135
- ? Function.prototype.call.bind(ctrlKeyGetter.get)
6136
- : null;
6137
- var shiftKeyGet = shiftKeyGetter && shiftKeyGetter.get
6138
- ? Function.prototype.call.bind(shiftKeyGetter.get)
6139
- : null;
6140
- var altKeyGet = altKeyGetter && altKeyGetter.get
6141
- ? Function.prototype.call.bind(altKeyGetter.get)
6142
- : null;
6143
- var preventDefault = Function.prototype.call.bind(Event.prototype.preventDefault);
6144
- var addEventListener = Function.prototype.call.bind(EventTarget.prototype.addEventListener);
6145
- var arrayMap = Function.prototype.call.bind(Array.prototype.map);
6146
- var weakMapDelete = Function.prototype.call.bind(WeakMap.prototype.delete);
6147
- var weakMapGet = Function.prototype.call.bind(WeakMap.prototype.get);
6148
- var weakMapSet = Function.prototype.call.bind(WeakMap.prototype.set);
6149
- var defineProperty = Object.defineProperty;
6150
- var objectCreate = Object.create;
6151
- var objectKeys = Object.keys;
6152
- var closest = Function.prototype.call.bind(Element.prototype.closest);
6153
- var getAttribute = Function.prototype.call.bind(Element.prototype.getAttribute);
6154
- var hasAttribute = Function.prototype.call.bind(Element.prototype.hasAttribute);
6155
- var documentToken = '';
6156
- var readyChallenge = '';
6157
- var externalLinkPolicyMode = 'parent';
6158
- var pendingLinkClicks = new WeakMap();
6159
- function trusted(event) {
6160
- try {
6161
- return trustedGetter && trustedGetter.get
6162
- ? trustedGet(event) === true
6163
- : event.isTrusted === true;
6164
- } catch (e) {
6165
- return false;
6166
- }
6167
- }
6168
-
6169
- function readEventValue(getter, event) {
6170
- if (!getter) return null;
6171
- try {
6172
- return getter(event);
6173
- } catch (e) {
6174
- return null;
6175
- }
6176
- }
6177
-
6178
- var marks = [];
6179
- var badges = [];
6180
- var badgeOffsets = {};
6181
- var badgeDragged = false;
6182
- var appliedHighlightKey = '';
6183
- var textAnchorsEnabled = false;
6184
- var mermaidBlocks = objectCreate(null);
6185
- var mermaidRequested = false;
6186
- var commentLabels = {
6187
- openOne: 'Open 1 unresolved comment on this text',
6188
- openOther: 'Open {n} unresolved comments on this text',
6189
- resolvedOne: 'Open 1 resolved comment on this text',
6190
- resolvedOther: 'Open {n} resolved comments on this text',
6191
- };
6192
-
6193
- function send(message) {
6194
- try {
6195
- function createMessagePayload(message) {
6196
- var payload = objectCreate(null);
6197
- payload.source = 'artifactshare';
6198
- var keys = objectKeys(message);
6199
- for (var index = 0; index < keys.length; index++) {
6200
- var key = keys[index];
6201
- payload[key] = message[key];
6202
- }
6203
- return payload;
6204
- }
6205
- var payload = createMessagePayload(message);
6206
- savedPostMessage(payload, '*');
6207
- } catch (e) {}
6208
- }
6209
-
6210
- function ready() {
6211
- if (readyChallenge && documentToken) {
6212
- send({ kind: 'ready', challenge: readyChallenge, token: documentToken });
6213
- }
6214
- }
6215
-
6216
- function requestMermaidRendering() {
6217
- if (mermaidRequested) return;
6218
- if (!document.body || !document.body.hasAttribute('data-artifact-markdown')) return;
6219
- var blocks = document.querySelectorAll('pre code.language-mermaid');
6220
- var diagrams = [];
6221
- for (
6222
- var index = 0;
6223
- index < blocks.length && diagrams.length < 16;
6224
- index++
6225
- ) {
6226
- var source = blocks[index].textContent || '';
6227
- if (!source || source.length > 20000) continue;
6228
- var pre = blocks[index].closest('pre');
6229
- if (!pre) continue;
6230
- var id = 'artifactshare-mermaid-' + index;
6231
- mermaidBlocks[id] = pre;
6232
- diagrams.push({ id: id, source: source });
6233
- }
6234
- if (diagrams.length) {
6235
- mermaidRequested = true;
6236
- send({
6237
- kind: 'mermaid-render-request',
6238
- renderToken: readyChallenge,
6239
- diagrams: diagrams,
6240
- });
6241
- }
6242
- }
6243
-
6244
- function installMermaidResults(renderToken, results) {
6245
- if (renderToken !== readyChallenge) return;
6246
- if (!Array.isArray(results)) return;
6247
- for (var index = 0; index < results.length; index++) {
6248
- var result = results[index] || {};
6249
- var pre = typeof result.id === 'string' ? mermaidBlocks[result.id] : null;
6250
- if (!pre || typeof result.svg !== 'string' || !result.svg.startsWith('<svg')) continue;
6251
- var svgDocument = new DOMParser().parseFromString(result.svg, 'image/svg+xml');
6252
- var svg = svgDocument.documentElement;
6253
- if (
6254
- svg.localName !== 'svg' ||
6255
- svg.namespaceURI !== 'http://www.w3.org/2000/svg' ||
6256
- svgDocument.querySelector('parsererror')
6257
- ) continue;
6258
- var container = document.createElement('div');
6259
- container.className = 'mermaid-diagram';
6260
- container.appendChild(document.importNode(svg, true));
6261
- pre.dataset.mermaidRendered = 'true';
6262
- pre.hidden = true;
6263
- pre.before(container);
6264
- delete mermaidBlocks[result.id];
6265
- }
6266
- schedulePositionBadges();
6267
- }
6268
-
6269
- function onReadyCheck(event) {
6270
- var message = event && event.data;
6271
- if (
6272
- !event ||
6273
- event.source !== savedParent ||
6274
- !message ||
6275
- message.source !== 'artifactshare-parent' ||
6276
- message.kind !== 'ready-check'
6277
- ) return;
6278
- if (typeof message.challenge !== 'string' || !message.challenge) return;
6279
- readyChallenge = message.challenge;
6280
- requestMermaidRendering();
6281
- ready();
6282
- }
6283
- try {
6284
- var random = new Uint8Array(32);
6285
- crypto.getRandomValues(random);
6286
- documentToken = arrayMap(random, function (byte) {
6287
- return byte.toString(16).padStart(2, '0');
6288
- }).join('');
6289
- } catch (e) {
6290
- documentToken = '';
6291
- }
6292
-
6293
- function shouldHandleLink(url) {
6294
- if (url.origin !== location.origin) return true;
6295
- if (url.pathname !== location.pathname) return true;
6296
- if (url.search !== location.search && url.search !== '') return true;
6297
- return false;
6298
- }
6299
-
6300
- function openExternalLink(href) {
6301
- window.open(href, '_blank', 'noopener,noreferrer');
6302
- }
6303
-
6304
- function isExternallyOpenable(url) {
6305
- return url.protocol === 'http:' || url.protocol === 'https:';
6306
- }
6307
-
6308
- function prepareLinkClick(event) {
6309
- var defaultPrevented = readEventValue(defaultPreventedGet, event);
6310
- var button = readEventValue(buttonGet, event);
6311
- var metaKey = readEventValue(metaKeyGet, event);
6312
- var ctrlKey = readEventValue(ctrlKeyGet, event);
6313
- var shiftKey = readEventValue(shiftKeyGet, event);
6314
- var altKey = readEventValue(altKeyGet, event);
6315
- if (
6316
- !trusted(event) ||
6317
- defaultPrevented !== false ||
6318
- button !== 0 ||
6319
- metaKey !== false ||
6320
- ctrlKey !== false ||
6321
- shiftKey !== false ||
6322
- altKey !== false
6323
- ) {
6324
- return;
6325
- }
6326
- var target = readEventValue(targetGet, event);
6327
- var element =
6328
- target && target.nodeType === 1 ? target : target && target.parentElement;
6329
- if (
6330
- element &&
6331
- closest(element, '.ash-comment-highlight, .ash-comment-highlight-badge')
6332
- ) {
6333
- return;
6334
- }
6335
- var anchor = element ? closest(element, 'a[href]') : null;
6336
- if (!anchor || hasAttribute(anchor, 'download')) return;
6337
- var rawHref = getAttribute(anchor, 'href');
6338
- if (!rawHref || rawHref.charAt(0) === '#') return;
6339
-
6340
- var url;
6341
- var href;
6342
- var openExternally = false;
6343
- try {
6344
- url = new URL(rawHref, location.href);
6345
- if (!shouldHandleLink(url)) return;
6346
- href = url.href;
6347
- openExternally =
6348
- url.origin !== location.origin && isExternallyOpenable(url);
6349
- } catch (e) {
6350
- href = rawHref;
6351
- }
6352
-
6353
- var pending = objectCreate(null);
6354
- pending.artifactPrevented = false;
6355
- pending.href = href;
6356
- pending.openExternally = openExternally;
6357
- try {
6358
- defineProperty(event, 'preventDefault', {
6359
- configurable: true,
6360
- value: function () {
6361
- pending.artifactPrevented = true;
6362
- preventDefault(event);
6363
- },
6364
- });
6365
- defineProperty(event, 'defaultPrevented', {
6366
- configurable: true,
6367
- get: function () {
6368
- return pending.artifactPrevented;
6369
- },
6370
- });
6371
- weakMapSet(pendingLinkClicks, event, pending);
6372
- } catch (e) {
6373
- // If the event cannot be wrapped, suppress navigation rather than bypass the gate.
6374
- preventDefault(event);
6375
- return;
6376
- }
6377
- preventDefault(event);
6378
- }
6379
-
6380
- function finishLinkClick(event) {
6381
- var pending = weakMapGet(pendingLinkClicks, event);
6382
- if (!pending) return;
6383
- weakMapDelete(pendingLinkClicks, event);
6384
- if (pending.artifactPrevented) return;
6385
- if (pending.openExternally && externalLinkPolicyMode === 'direct') {
6386
- openExternalLink(pending.href);
6387
- return;
6388
- }
6389
- send({ kind: 'link-clicked', href: pending.href, token: documentToken });
6390
- }
6391
-
6392
- function cssPath(element) {
6393
- if (!element || element.nodeType !== 1) return null;
6394
- var parts = [];
6395
- while (element && element.nodeType === 1 && element !== document.body) {
6396
- var name = element.nodeName.toLowerCase();
6397
- var index = 1;
6398
- var sibling = element;
6399
- while ((sibling = sibling.previousElementSibling)) {
6400
- if (sibling.nodeName.toLowerCase() === name) index++;
6401
- }
6402
- parts.unshift(name + ':nth-of-type(' + index + ')');
6403
- element = element.parentElement;
6404
- }
6405
- return parts.length ? 'body > ' + parts.join(' > ') : 'body';
6406
- }
6407
-
6408
- function selectedElement(range) {
6409
- var node = range.commonAncestorContainer;
6410
- return (node.nodeType === 1 ? node : node.parentElement) || document.body;
6411
- }
6412
-
6413
- function acceptsAnchorText(node) {
6414
- return !(
6415
- node.parentElement &&
6416
- (node.parentElement.closest('script,style,.ash-comment-highlight-badge') ||
6417
- (document.body.hasAttribute('data-artifact-markdown') &&
6418
- node.parentElement.closest('.mermaid-diagram')))
6419
- );
6420
- }
6421
-
6422
- function acceptsHighlightText(node) {
6423
- return !(
6424
- node.parentElement &&
6425
- (node.parentElement.closest(
6426
- 'script,style,.ash-comment-highlight,.ash-comment-highlight-badge,.ash-comment-highlight-svg',
6427
- ) ||
6428
- (document.body.hasAttribute('data-artifact-markdown') &&
6429
- node.parentElement.closest('.mermaid-diagram')))
6430
- );
6431
- }
6432
-
6433
- function anchorRoot() {
6434
- return document.querySelector('[data-comment-content]') || document.body;
6435
- }
6436
-
6437
- function textOffset(node, offset) {
6438
- var walker = document.createTreeWalker(anchorRoot(), NodeFilter.SHOW_TEXT, {
6439
- acceptNode: function (textNode) {
6440
- return acceptsAnchorText(textNode)
6441
- ? NodeFilter.FILTER_ACCEPT
6442
- : NodeFilter.FILTER_REJECT;
6443
- },
6444
- });
6445
- var position = 0;
6446
- var textNode;
6447
- while ((textNode = walker.nextNode())) {
6448
- if (textNode === node) return position + offset;
6449
- position += textNode.nodeValue.length;
6450
- }
6451
- return position;
6452
- }
6453
-
6454
- function anchorTextContent() {
6455
- var walker = document.createTreeWalker(anchorRoot(), NodeFilter.SHOW_TEXT, {
6456
- acceptNode: function (node) {
6457
- return acceptsAnchorText(node)
6458
- ? NodeFilter.FILTER_ACCEPT
6459
- : NodeFilter.FILTER_REJECT;
6460
- },
6461
- });
6462
- var text = '';
6463
- var node;
6464
- while ((node = walker.nextNode())) {
6465
- text += node.nodeValue;
6466
- }
6467
- return text;
6468
- }
6469
-
6470
- function ensureCommentStyles() {
6471
- if (document.getElementById('ash-comment-highlight-style')) return;
6472
- var style = document.createElement('style');
6473
- style.id = 'ash-comment-highlight-style';
6474
- style.textContent =
6475
- '.ash-comment-highlight-badge::after{content:attr(data-count);}';
6476
- document.head.appendChild(style);
6477
- }
6478
-
6479
- function sendSelection() {
6480
- if (!textAnchorsEnabled) return;
6481
- var selection = getSelection();
6482
- if (!selection || selection.rangeCount === 0) {
6483
- send({ kind: 'text-selection-cleared' });
6484
- return;
6485
- }
6486
- var selectionText = selection.toString();
6487
- var quotedText = selectionText.trim();
6488
- if (!quotedText) {
6489
- send({ kind: 'text-selection-cleared' });
6490
- return;
6491
- }
6492
- var range = selection.getRangeAt(0);
6493
- if (!anchorRoot().contains(range.commonAncestorContainer)) {
6494
- return;
6495
- }
6496
-
6497
- var rawStart = textOffset(range.startContainer, range.startOffset);
6498
- var leadingWhitespace = selectionText.length - selectionText.trimStart().length;
6499
- var start = rawStart + leadingWhitespace;
6500
- var end = start + quotedText.length;
6501
- var bodyText = anchorTextContent();
6502
- var rect = range.getBoundingClientRect();
6503
- send({
6504
- kind: 'text-selection',
6505
- quotedText: quotedText,
6506
- prefixText: bodyText.slice(Math.max(0, start - 120), start).trim(),
6507
- suffixText: bodyText.slice(end, Math.min(bodyText.length, end + 120)).trim(),
6508
- textStart: start,
6509
- textEnd: end,
6510
- cssPath: cssPath(selectedElement(range)),
6511
- rect: {
6512
- top: rect.top,
6513
- left: rect.left,
6514
- width: rect.width,
6515
- height: rect.height,
6516
- },
6517
- });
6518
- }
6519
-
6520
- function clearMarks() {
6521
- for (var i = 0; i < badges.length; i++) {
6522
- badges[i].badge.remove();
6523
- }
6524
- badges = [];
6525
- for (var i = 0; i < marks.length; i++) {
6526
- marks[i].replaceWith(document.createTextNode(marks[i].textContent || ''));
6527
- }
6528
- marks = [];
6529
- var svgOverlays = document.querySelectorAll('.ash-comment-highlight-svg');
6530
- for (var s = 0; s < svgOverlays.length; s++) svgOverlays[s].remove();
6531
- svgActiveThreads = {};
6532
- appliedHighlightKey = '';
6533
- document.body.normalize();
6534
- }
6535
-
6536
- function highlightKey(list) {
6537
- return list
6538
- .map(function (highlight) {
6539
- return [
6540
- highlight.threadId,
6541
- highlight.status,
6542
- highlight.textStart,
6543
- highlight.textEnd,
6544
- highlight.quotedText || '',
6545
- highlight.target ? '1' : '0',
6546
- ].join(':');
6547
- })
6548
- .join('|');
6549
- }
6550
-
6551
- function updateHighlightBadges(list) {
6552
- for (var i = 0; i < list.length; i++) {
6553
- var highlight = list[i];
6554
- var badgeElements = document.querySelectorAll(
6555
- '.ash-comment-highlight-badge[data-thread-id="' +
6556
- CSS.escape(highlight.threadId) +
6557
- '"]',
6558
- );
6559
- for (var j = 0; j < badgeElements.length; j++) {
6560
- badgeElements[j].dataset.count = String(highlight.count || 1);
6561
- badgeElements[j].setAttribute('aria-label', commentLabel(highlight));
6562
- }
6563
- }
6564
- }
6565
-
6566
- function setCommentLabels(labels) {
6567
- if (!labels || typeof labels !== 'object') return;
6568
- if (typeof labels.openOne === 'string') commentLabels.openOne = labels.openOne;
6569
- if (typeof labels.openOther === 'string') commentLabels.openOther = labels.openOther;
6570
- if (typeof labels.resolvedOne === 'string') commentLabels.resolvedOne = labels.resolvedOne;
6571
- if (typeof labels.resolvedOther === 'string') commentLabels.resolvedOther = labels.resolvedOther;
6572
- }
6573
-
6574
- function commentLabel(highlight) {
6575
- var count = highlight.count || 1;
6576
- var template =
6577
- highlight.status === 'resolved'
6578
- ? count === 1
6579
- ? commentLabels.resolvedOne
6580
- : commentLabels.resolvedOther
6581
- : count === 1
6582
- ? commentLabels.openOne
6583
- : commentLabels.openOther;
6584
- var label = template.replace(/\\{n\\}/g, String(count));
6585
- return highlight.quotedText ? label + ': ' + highlight.quotedText : label;
6586
- }
6587
-
6588
- function parseRgbColor(value) {
6589
- if (!value || value === 'transparent') return null;
6590
- var match = value.match(
6591
- /^rgba?\\(\\s*([\\d.]+)\\s*,\\s*([\\d.]+)\\s*,\\s*([\\d.]+)(?:\\s*,\\s*([\\d.]+))?\\s*\\)$/,
6592
- );
6593
- if (!match) return null;
6594
- return [
6595
- parseFloat(match[1]),
6596
- parseFloat(match[2]),
6597
- parseFloat(match[3]),
6598
- match[4] === undefined ? 1 : parseFloat(match[4]),
6599
- ];
6600
- }
6601
-
6602
- function rgbToLuminance(r, g, b) {
6603
- return (
6604
- 0.2126 * (r / 255) + 0.7152 * (g / 255) + 0.0722 * (b / 255)
6605
- );
6606
- }
6607
-
6608
- function parseColorValue(value) {
6609
- if (!value || value === 'transparent') return { type: 'none' };
6610
- var rgb = parseRgbColor(value);
6611
- if (rgb) {
6612
- return { type: 'rgb', r: rgb[0], g: rgb[1], b: rgb[2], a: rgb[3] };
6613
- }
6614
- var modernMatch = value.match(
6615
- /^oklch\\(\\s*([\\d.]+)(%?)[^/)]*(?:\\/\\s*([\\d.]+)(%?))?/,
6616
- );
6617
- if (modernMatch) {
6618
- var lightness = parseFloat(modernMatch[1]);
6619
- if (modernMatch[2] === '%') lightness = lightness / 100;
6620
- var oklchAlpha =
6621
- modernMatch[3] === undefined ? 1 : parseFloat(modernMatch[3]);
6622
- if (modernMatch[4] === '%') oklchAlpha = oklchAlpha / 100;
6623
- return { type: 'luminance', value: lightness, a: oklchAlpha };
6624
- }
6625
- modernMatch = value.match(
6626
- /^lab\\(\\s*([\\d.]+)(%?)[^/)]*(?:\\/\\s*([\\d.]+)(%?))?/,
6627
- );
6628
- if (modernMatch) {
6629
- var labLightness = parseFloat(modernMatch[1]);
6630
- if (modernMatch[2] === '%') labLightness = labLightness / 100;
6631
- else labLightness = labLightness / 100;
6632
- var labAlpha = modernMatch[3] === undefined ? 1 : parseFloat(modernMatch[3]);
6633
- if (modernMatch[4] === '%') labAlpha = labAlpha / 100;
6634
- return { type: 'luminance', value: labLightness, a: labAlpha };
6635
- }
6636
- modernMatch = value.match(
6637
- /^color\\(\\s*(?:display-p3|srgb)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)[^/)]*(?:\\/\\s*([\\d.]+)(%?))?/,
6638
- );
6639
- if (modernMatch) {
6640
- var colorAlpha =
6641
- modernMatch[4] === undefined ? 1 : parseFloat(modernMatch[4]);
6642
- if (modernMatch[5] === '%') colorAlpha = colorAlpha / 100;
6643
- return {
6644
- type: 'luminance',
6645
- value:
6646
- 0.2126 * parseFloat(modernMatch[1]) +
6647
- 0.7152 * parseFloat(modernMatch[2]) +
6648
- 0.0722 * parseFloat(modernMatch[3]),
6649
- a: colorAlpha,
6650
- };
6651
- }
6652
- return { type: 'none' };
6653
- }
6654
-
6655
- function resolveBackgroundRgb(el) {
6656
- while (el) {
6657
- var parsed = parseColorValue(getComputedStyle(el).backgroundColor);
6658
- if (parsed.type === 'none') {
6659
- el = el.parentElement;
6660
- continue;
6661
- }
6662
- if (parsed.type === 'luminance') {
6663
- if (parsed.a === 0) {
6664
- el = el.parentElement;
6665
- continue;
6666
- }
6667
- var gray = parsed.value * 255;
6668
- if (parsed.a < 1) {
6669
- var ancestorRgb = resolveBackgroundRgb(el.parentElement);
6670
- var lumAlpha = parsed.a;
6671
- return [
6672
- gray * lumAlpha + ancestorRgb[0] * (1 - lumAlpha),
6673
- gray * lumAlpha + ancestorRgb[1] * (1 - lumAlpha),
6674
- gray * lumAlpha + ancestorRgb[2] * (1 - lumAlpha),
6675
- ];
6676
- }
6677
- return [gray, gray, gray];
6678
- }
6679
- if (parsed.type === 'rgb') {
6680
- if (parsed.a === 0) {
6681
- el = el.parentElement;
6682
- continue;
6683
- }
6684
- if (parsed.a < 1) {
6685
- var ancestorRgb = resolveBackgroundRgb(el.parentElement);
6686
- var alpha = parsed.a;
6687
- return [
6688
- parsed.r * alpha + ancestorRgb[0] * (1 - alpha),
6689
- parsed.g * alpha + ancestorRgb[1] * (1 - alpha),
6690
- parsed.b * alpha + ancestorRgb[2] * (1 - alpha),
6691
- ];
6692
- }
6693
- return [parsed.r, parsed.g, parsed.b];
6694
- }
6695
- }
6696
- return [255, 255, 255];
6697
- }
6698
-
6699
- function resolvedLuminance(element) {
6700
- function resolveFrom(el) {
6701
- while (el) {
6702
- var parsed = parseColorValue(getComputedStyle(el).backgroundColor);
6703
- if (parsed.type === 'none') {
6704
- el = el.parentElement;
6705
- continue;
6706
- }
6707
- if (parsed.type === 'luminance') {
6708
- if (parsed.a === 0) {
6709
- el = el.parentElement;
6710
- continue;
6711
- }
6712
- if (parsed.a < 1) {
6713
- var ancestor = resolveFrom(el.parentElement);
6714
- var ancestorLum = ancestor !== null ? ancestor : 1;
6715
- return parsed.value * parsed.a + ancestorLum * (1 - parsed.a);
6716
- }
6717
- return parsed.value;
6718
- }
6719
- if (parsed.type === 'rgb') {
6720
- if (parsed.a === 0) {
6721
- el = el.parentElement;
6722
- continue;
6723
- }
6724
- if (parsed.a < 1) {
6725
- var ancestorRgb = resolveBackgroundRgb(el.parentElement);
6726
- var alpha = parsed.a;
6727
- return rgbToLuminance(
6728
- parsed.r * alpha + ancestorRgb[0] * (1 - alpha),
6729
- parsed.g * alpha + ancestorRgb[1] * (1 - alpha),
6730
- parsed.b * alpha + ancestorRgb[2] * (1 - alpha),
6731
- );
6732
- }
6733
- return rgbToLuminance(parsed.r, parsed.g, parsed.b);
6734
- }
6735
- }
6736
- return null;
6737
- }
6738
- var result = resolveFrom(element);
6739
- return result !== null ? result : 1;
6740
- }
6741
-
6742
- function isDarkBackground(element) {
6743
- return resolvedLuminance(element) < 0.5;
6744
- }
6745
-
6746
- function isDarkBackgroundForSvgText(text) {
6747
- if (!text) return isDarkBackground(document.body);
6748
- var fill = getComputedStyle(text).fill;
6749
- var parsed = parseColorValue(fill);
6750
- if (parsed.type === 'rgb' && parsed.a > 0) return rgbToLuminance(parsed.r, parsed.g, parsed.b) >= 0.5;
6751
- if (parsed.type === 'luminance' && parsed.a > 0) return parsed.value >= 0.5;
6752
- return isDarkBackground(text);
6753
- }
6754
-
6755
- var svgActiveThreads = {};
6756
- function setSvgHighlightState(threadId, active) {
6757
- var overlays = document.querySelectorAll('.ash-comment-highlight-svg[data-thread-id="' + CSS.escape(threadId) + '"]');
6758
- for (var i = 0; i < overlays.length; i++) {
6759
- var overlay = overlays[i];
6760
- var palette = overlay.dataset.palette;
6761
- if (!palette) continue;
6762
- var parts = palette.split('|');
6763
- var normalFill = parts[0];
6764
- var outline = parts[1];
6765
- var target = overlay.dataset.target === 'true';
6766
- overlay.dataset.state = active || target ? 'active' : 'normal';
6767
- if (active || target) {
6768
- overlay.style.fill = normalFill;
6769
- overlay.style.stroke = outline;
6770
- overlay.style.strokeWidth = '2';
6771
- overlay.style.vectorEffect = 'non-scaling-stroke';
6772
- } else {
6773
- overlay.style.fill = normalFill;
6774
- overlay.style.stroke = 'none';
6775
- overlay.style.strokeWidth = '0';
6776
- }
6777
- }
6778
- }
6779
-
6780
- function highlightPalette(isDark, resolved) {
6781
- if (isDark) {
6782
- if (resolved) {
6783
- return {
6784
- markBg: 'rgba(134,197,165,.14)',
6785
- markUnderline: 'rgba(134,197,165,.75)',
6786
- outline: '#86c5a5',
6787
- badgeBorder: 'rgba(134,197,165,.75)',
6788
- badgeText: '#86c5a5',
6789
- badgeBg: '#1f2937',
6790
- badgeTargetBorder: '#86c5a5',
6791
- badgeTargetText: '#fff',
6792
- badgeTargetBg: '#86c5a5',
6793
- };
6794
- }
6795
- return {
6796
- markBg: 'rgba(96,165,250,.16)',
6797
- markUnderline: 'rgba(96,165,250,.85)',
6798
- outline: '#60a5fa',
6799
- badgeBorder: 'rgba(96,165,250,.85)',
6800
- badgeText: '#60a5fa',
6801
- badgeBg: '#1f2937',
6802
- badgeTargetBorder: '#60a5fa',
6803
- badgeTargetText: '#fff',
6804
- badgeTargetBg: '#60a5fa',
6805
- };
6806
- }
6807
- if (resolved) {
6808
- return {
6809
- markBg: 'rgba(68,131,97,.12)',
6810
- markUnderline: 'rgba(68,131,97,.58)',
6811
- outline: '#448361',
6812
- badgeBorder: 'rgba(68,131,97,.36)',
6813
- badgeText: '#448361',
6814
- badgeBg: '#fff',
6815
- badgeTargetBorder: '#448361',
6816
- badgeTargetText: '#fff',
6817
- badgeTargetBg: '#448361',
6818
- };
6819
- }
6820
- return {
6821
- markBg: 'rgba(37,99,235,.16)',
6822
- markUnderline: 'rgba(37,99,235,.72)',
6823
- outline: '#2383e2',
6824
- badgeBorder: 'rgba(35,131,226,.44)',
6825
- badgeText: '#2383e2',
6826
- badgeBg: '#fff',
6827
- badgeTargetBorder: '#2383e2',
6828
- badgeTargetText: '#fff',
6829
- badgeTargetBg: '#2383e2',
6830
- };
6831
- }
6832
-
6833
- function markStyleForHighlight(highlight, isDark) {
6834
- var palette = highlightPalette(isDark, highlight.status === 'resolved');
6835
- var css =
6836
- 'background:' +
6837
- palette.markBg +
6838
- ';box-shadow:inset 0 -2px 0 ' +
6839
- palette.markUnderline +
6840
- ';color:inherit;border-radius:3px;scroll-margin:120px;cursor:pointer;touch-action:manipulation;';
6841
- if (highlight.target) {
6842
- css +=
6843
- 'outline:2px solid ' +
6844
- palette.outline +
6845
- ';outline-offset:2px;box-shadow:inset 0 -2px 0 ' +
6846
- palette.outline +
6847
- ';';
6848
- }
6849
- return css;
6850
- }
6851
-
6852
- function badgeStyleForHighlight(highlight, isDark) {
6853
- var palette = highlightPalette(isDark, highlight.status === 'resolved');
6854
- var base =
6855
- 'display:inline-flex;align-items:center;gap:4px;min-height:16px;padding:0 5px;border-radius:999px;font:700 10px system-ui,sans-serif;box-shadow:0 2px 8px rgba(27,39,35,.08);cursor:pointer;touch-action:none;position:absolute;z-index:2147483646;';
6856
- var borderColor;
6857
- var textColor;
6858
- var bgColor;
6859
- if (highlight.target) {
6860
- borderColor = palette.badgeTargetBorder;
6861
- textColor = palette.badgeTargetText;
6862
- bgColor = palette.badgeTargetBg;
6863
- } else {
6864
- borderColor = palette.badgeBorder;
6865
- textColor = palette.badgeText;
6866
- bgColor = palette.badgeBg;
6867
- }
6868
- return (
6869
- base +
6870
- 'border:1px solid ' +
6871
- borderColor +
6872
- ';color:' +
6873
- textColor +
6874
- ';background:' +
6875
- bgColor +
6876
- ';'
6877
- );
6878
- }
6879
-
6880
- function positionSingleBadge(entry) {
6881
- var badge = entry.badge;
6882
- var rects = measureBadgeEntry(entry);
6883
- var rect = rects.length ? rects[rects.length - 1] : null;
6884
- if (!rect || rect.width === 0 || rect.height === 0) {
6885
- badge.style.display = 'none';
6886
- return;
6887
- }
6888
- badge.style.display = 'inline-flex';
6889
- badge.style.left = '0px';
6890
- badge.style.top = '0px';
6891
- var base = badge.getBoundingClientRect();
6892
- var scaleX = badge.offsetWidth ? base.width / badge.offsetWidth : 1;
6893
- var scaleY = badge.offsetHeight ? base.height / badge.offsetHeight : 1;
6894
- if (!scaleX || !isFinite(scaleX)) scaleX = 1;
6895
- if (!scaleY || !isFinite(scaleY)) scaleY = 1;
6896
- var badgeHeight = badge.offsetHeight || 16;
6897
- var threadId = badge.dataset.threadId;
6898
- var offset = badgeOffsets[threadId] || { x: 0, y: 0 };
6899
- badge.style.left =
6900
- (rect.right - base.left) / scaleX - 6 + offset.x + 'px';
6901
- badge.style.top =
6902
- (rect.top - base.top) / scaleY - badgeHeight + 3 + offset.y + 'px';
6903
- }
6904
-
6905
- function positionBadges() {
6906
- var layouts = [];
6907
- for (var i = 0; i < badges.length; i++) {
6908
- var badge = badges[i].badge;
6909
- var rects = measureBadgeEntry(badges[i]);
6910
- var rect = rects.length ? rects[rects.length - 1] : null;
6911
- badge.style.display = 'inline-flex';
6912
- badge.style.left = '0px';
6913
- badge.style.top = '0px';
6914
- var base = badge.getBoundingClientRect();
6915
- var scaleX = badge.offsetWidth ? base.width / badge.offsetWidth : 1;
6916
- var scaleY = badge.offsetHeight ? base.height / badge.offsetHeight : 1;
6917
- if (!scaleX || !isFinite(scaleX)) scaleX = 1;
6918
- if (!scaleY || !isFinite(scaleY)) scaleY = 1;
6919
- layouts.push({
6920
- badge: badge,
6921
- rect: rect,
6922
- base: base,
6923
- badgeHeight: badge.offsetHeight || 16,
6924
- scaleX: scaleX,
6925
- scaleY: scaleY,
6926
- threadId: badge.dataset.threadId,
6927
- });
6928
- }
6929
- for (var j = 0; j < layouts.length; j++) {
6930
- var layout = layouts[j];
6931
- if (
6932
- !layout.rect ||
6933
- layout.rect.width === 0 ||
6934
- layout.rect.height === 0
6935
- ) {
6936
- layout.badge.style.display = 'none';
6937
- continue;
6938
- }
6939
- var offset = badgeOffsets[layout.threadId] || { x: 0, y: 0 };
6940
- layout.badge.style.display = 'inline-flex';
6941
- layout.badge.style.left =
6942
- (layout.rect.right - layout.base.left) / layout.scaleX -
6943
- 6 +
6944
- offset.x +
6945
- 'px';
6946
- layout.badge.style.top =
6947
- (layout.rect.top - layout.base.top) / layout.scaleY -
6948
- layout.badgeHeight +
6949
- 3 +
6950
- offset.y +
6951
- 'px';
6952
- }
6953
- }
6954
-
6955
- function measureBadgeEntry(entry) {
6956
- if (entry.measure) return entry.measure();
6957
- return entry.mark && entry.mark.getClientRects ? entry.mark.getClientRects() : [];
6958
- }
6959
-
6960
- var badgePositionFrame = 0;
6961
- function schedulePositionBadges() {
6962
- if (badgePositionFrame) return;
6963
- badgePositionFrame = requestAnimationFrame(function () {
6964
- badgePositionFrame = 0;
6965
- positionBadges();
6966
- });
6967
- }
6968
-
6969
- function svgTextRange(highlight) {
6970
- var walker = document.createTreeWalker(anchorRoot(), NodeFilter.SHOW_TEXT, {
6971
- acceptNode: function (node) {
6972
- return acceptsAnchorText(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
6973
- },
6974
- });
6975
- var position = 0;
6976
- var groups = [];
6977
- var node;
6978
- while ((node = walker.nextNode())) {
6979
- var parent = node.parentElement;
6980
- var text = parent && parent.closest ? parent.closest('text') : null;
6981
- var length = node.nodeValue.length;
6982
- if (text && position < highlight.textEnd && position + length > highlight.textStart) {
6983
- var localStart = Math.max(0, highlight.textStart - position);
6984
- var localEnd = Math.min(length, highlight.textEnd - position);
6985
- var localPosition = 0;
6986
- var localWalker = document.createTreeWalker(text, NodeFilter.SHOW_TEXT, {
6987
- acceptNode: function (candidate) {
6988
- return acceptsAnchorText(candidate) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
6989
- },
6990
- });
6991
- var candidate;
6992
- while ((candidate = localWalker.nextNode()) && candidate !== node) {
6993
- if (candidate.nodeValue.trim()) localPosition += candidate.nodeValue.length;
6994
- }
6995
- if (candidate === node) groups.push({ text: text, start: localPosition + localStart, end: localPosition + localEnd });
6996
- }
6997
- position += length;
6998
- if (position >= highlight.textEnd) break;
6999
- }
7000
- return groups;
7001
- }
7002
-
7003
- function wrapSvgRange(highlight) {
7004
- if (!document.querySelector('svg text')) return false;
7005
- var groups = svgTextRange(highlight);
7006
- if (!groups.length) return false;
7007
- var texts = groups.map(function (group) { return group.text; }).filter(function (text, index, all) { return all.indexOf(text) === index; });
7008
- var mappingValid = texts.every(function (text) {
7009
- if (!text.getNumberOfChars) return false;
7010
- var walker = document.createTreeWalker(text, NodeFilter.SHOW_TEXT);
7011
- var domLength = 0;
7012
- var node;
7013
- while ((node = walker.nextNode())) {
7014
- if (node.nodeValue.trim()) domLength += node.nodeValue.length;
7015
- }
7016
- return domLength === text.getNumberOfChars();
7017
- });
7018
- var first = texts[0];
7019
- var svg = first && first.ownerSVGElement;
7020
- while (svg && svg.ownerSVGElement) svg = svg.ownerSVGElement;
7021
- if (!svg || !svg.parentNode) return false;
7022
- ensureCommentStyles();
7023
- var overlays = {};
7024
-
7025
- function overlayKey(text, index) {
7026
- return texts.indexOf(text) + ':' + index;
7027
- }
7028
-
7029
- function updateOverlay(text, index, box, screenCtm) {
7030
- var key = overlayKey(text, index);
7031
- var shape = overlays[key];
7032
- if (!shape) {
7033
- shape = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
7034
- shape.setAttribute('class', 'ash-comment-highlight-svg');
7035
- shape.setAttribute('pointer-events', 'none');
7036
- shape.dataset.threadId = highlight.threadId;
7037
- shape.dataset.target = highlight.target ? 'true' : 'false';
7038
- var palette = highlightPalette(isDarkBackgroundForSvgText(text), highlight.status === 'resolved');
7039
- shape.dataset.palette = palette.markBg + '|' + palette.outline;
7040
- text.parentNode.insertBefore(shape, text);
7041
- overlays[key] = shape;
7042
- }
7043
- var scaleX = screenCtm ? Math.hypot(screenCtm.a, screenCtm.b) : 1;
7044
- var scaleY = screenCtm ? Math.hypot(screenCtm.c, screenCtm.d) : 1;
7045
- var padX = scaleX ? 2 / scaleX : 2;
7046
- var padY = scaleY ? 2 / scaleY : 2;
7047
- shape.setAttribute('x', box.x - padX);
7048
- shape.setAttribute('y', box.y - padY);
7049
- shape.setAttribute('width', box.width + padX * 2);
7050
- shape.setAttribute('height', box.height + padY * 2);
7051
- var textCtm = text.getCTM ? text.getCTM() : null;
7052
- var parentCtm = text.parentNode && text.parentNode.getCTM ? text.parentNode.getCTM() : null;
7053
- if (textCtm && parentCtm && parentCtm.inverse) {
7054
- var matrix = parentCtm.inverse().multiply(textCtm);
7055
- shape.setAttribute(
7056
- 'transform',
7057
- 'matrix(' + [matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f].join(' ') + ')',
7058
- );
7059
- } else {
7060
- shape.removeAttribute('transform');
7061
- }
7062
- return shape;
7063
- }
7064
-
7065
- function measureSvgRange() {
7066
- var current = [];
7067
- var usedOverlays = {};
7068
- for (var i = 0; mappingValid && i < groups.length; i++) {
7069
- var group = groups[i];
7070
- var ctm = group.text.getScreenCTM ? group.text.getScreenCTM() : null;
7071
- var runs = [];
7072
- for (var index = group.start; index < group.end; index++) {
7073
- try {
7074
- var box = group.text.getExtentOfChar(index);
7075
- if (!box || box.width < 0 || box.height <= 0) continue;
7076
- var previous = runs.length ? runs[runs.length - 1] : null;
7077
- var overlapsVertically =
7078
- previous &&
7079
- box.y <= previous.y + previous.height &&
7080
- previous.y <= box.y + box.height;
7081
- var sameLine =
7082
- previous &&
7083
- overlapsVertically &&
7084
- box.x <= previous.x + previous.width + Math.max(4, box.height * 0.5);
7085
- if (sameLine) {
7086
- var runRight = Math.max(previous.x + previous.width, box.x + box.width);
7087
- var runBottom = Math.max(previous.y + previous.height, box.y + box.height);
7088
- previous.x = Math.min(previous.x, box.x);
7089
- previous.y = Math.min(previous.y, box.y);
7090
- previous.width = runRight - previous.x;
7091
- previous.height = runBottom - previous.y;
7092
- } else {
7093
- runs.push({ x: box.x, y: box.y, width: box.width, height: box.height });
7094
- }
7095
- } catch (e) {}
7096
- }
7097
- for (var runIndex = 0; runIndex < runs.length; runIndex++) {
7098
- try {
7099
- var run = runs[runIndex];
7100
- var overlayIndex = i + '-' + runIndex;
7101
- var overlay = updateOverlay(group.text, overlayIndex, run, ctm);
7102
- usedOverlays[overlayKey(group.text, overlayIndex)] = true;
7103
- var points = [
7104
- [run.x, run.y],
7105
- [run.x + run.width, run.y],
7106
- [run.x, run.y + run.height],
7107
- [run.x + run.width, run.y + run.height],
7108
- ].map(function (point) {
7109
- return ctm
7110
- ? new DOMPoint(point[0], point[1]).matrixTransform(ctm)
7111
- : { x: point[0], y: point[1] };
7112
- });
7113
- var left = Math.min.apply(null, points.map(function (point) { return point.x; }));
7114
- var top = Math.min.apply(null, points.map(function (point) { return point.y; }));
7115
- var right = Math.max.apply(null, points.map(function (point) { return point.x; }));
7116
- var bottom = Math.max.apply(null, points.map(function (point) { return point.y; }));
7117
- if (right > left && bottom > top) {
7118
- current.push({ left: left, right: right, top: top, width: right - left, height: bottom - top });
7119
- }
7120
- } catch (e) {}
7121
- }
7122
- }
7123
- Object.keys(overlays).forEach(function (key) {
7124
- if (!usedOverlays[key]) {
7125
- overlays[key].remove();
7126
- delete overlays[key];
7127
- }
7128
- });
7129
- setSvgHighlightState(
7130
- highlight.threadId,
7131
- svgActiveThreads[highlight.threadId] === true,
7132
- );
7133
- if (current.length) return current;
7134
- var fallback = first.getBoundingClientRect ? first.getBoundingClientRect() : null;
7135
- if (!fallback || fallback.width === 0 || fallback.height === 0) {
7136
- fallback = svg.getBoundingClientRect ? svg.getBoundingClientRect() : null;
7137
- }
7138
- return fallback ? [fallback] : [];
7139
- }
7140
-
7141
- var badge = document.createElement('button');
7142
- badge.type = 'button';
7143
- badge.className = 'ash-comment-highlight-badge';
7144
- badge.dataset.threadId = highlight.threadId;
7145
- badge.dataset.count = String(highlight.count || 1);
7146
- badge.setAttribute('aria-label', commentLabel(highlight));
7147
- badge.innerHTML =
7148
- highlight.status === 'resolved'
7149
- ? '<svg viewBox="0 0 24 24" width="10" height="10" style="width:10px;height:10px;flex:none;border:0;padding:0;margin:0;background:none;box-shadow:none" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>'
7150
- : '<svg viewBox="0 0 24 24" width="10" height="10" style="width:10px;height:10px;flex:none;border:0;padding:0;margin:0;background:none;box-shadow:none" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z"/></svg>';
7151
- badge.style.cssText = badgeStyleForHighlight(highlight, isDarkBackgroundForSvgText(first));
7152
- bindBadgePointer(badge);
7153
- svg.parentNode.insertBefore(badge, svg.nextSibling);
7154
- badges.push({ badge: badge, measure: measureSvgRange });
7155
- measureSvgRange();
7156
- return true;
7157
- }
7158
-
7159
- function wrapRange(highlight) {
7160
- var start = highlight.textStart;
7161
- var end = highlight.textEnd;
7162
- if (typeof start !== 'number' || typeof end !== 'number' || end <= start) {
7163
- return;
7164
- }
7165
- var svgWrapped = wrapSvgRange(highlight);
7166
- var walker = document.createTreeWalker(anchorRoot(), NodeFilter.SHOW_TEXT, {
7167
- acceptNode: function (node) {
7168
- return acceptsAnchorText(node)
7169
- ? NodeFilter.FILTER_ACCEPT
7170
- : NodeFilter.FILTER_REJECT;
7171
- },
7172
- });
7173
- var position = 0;
7174
- var parts = [];
7175
- var node;
7176
- var badgeAdded = svgWrapped;
7177
- while ((node = walker.nextNode())) {
7178
- var length = node.nodeValue.length;
7179
- var next = position + length;
7180
- if (next <= start) {
7181
- position = next;
7182
- continue;
7183
- }
7184
- if (position >= end) break;
7185
- var localStart = Math.max(0, start - position);
7186
- var localEnd = Math.min(length, end - position);
7187
- var parent = node.parentElement;
7188
- var inSvgText = parent && parent.closest && parent.closest('svg text');
7189
- if (!inSvgText) {
7190
- parts.push({ node: node, start: localStart, end: localEnd });
7191
- }
7192
- position = next;
7193
- }
7194
- for (var i = parts.length - 1; i >= 0; i--) {
7195
- var part = parts[i];
7196
- var range = document.createRange();
7197
- range.setStart(part.node, part.start);
7198
- range.setEnd(part.node, part.end);
7199
- var mark = document.createElement('mark');
7200
- mark.className =
7201
- 'ash-comment-highlight' +
7202
- (highlight.target ? ' is-target' : '') +
7203
- (highlight.status === 'resolved' ? ' is-resolved' : '');
7204
- mark.dataset.threadId = highlight.threadId;
7205
- var isDark = isDarkBackground(part.node.parentElement);
7206
- mark.style.cssText = markStyleForHighlight(highlight, isDark);
7207
- try {
7208
- range.surroundContents(mark);
7209
- if (!badgeAdded) {
7210
- ensureCommentStyles();
7211
- var badge = document.createElement('button');
7212
- badge.type = 'button';
7213
- badge.className = 'ash-comment-highlight-badge';
7214
- badge.setAttribute('aria-label', commentLabel(highlight));
7215
- badge.dataset.threadId = highlight.threadId;
7216
- badge.dataset.count = String(highlight.count || 1);
7217
- badge.innerHTML =
7218
- highlight.status === 'resolved'
7219
- ? '<svg viewBox="0 0 24 24" width="10" height="10" style="width:10px;height:10px;flex:none;border:0;padding:0;margin:0;background:none;box-shadow:none" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>'
7220
- : '<svg viewBox="0 0 24 24" width="10" height="10" style="width:10px;height:10px;flex:none;border:0;padding:0;margin:0;background:none;box-shadow:none" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z"/></svg>';
7221
- badge.style.cssText = badgeStyleForHighlight(highlight, isDark);
7222
- bindBadgePointer(badge);
7223
- mark.insertAdjacentElement('afterend', badge);
7224
- badges.push({ badge: badge, mark: mark });
7225
- badgeAdded = true;
7226
- }
7227
- bindCommentPointer(mark);
7228
- marks.push(mark);
7229
- } catch (e) {}
7230
- }
7231
- }
7232
-
7233
- function applyHighlights(list) {
7234
- if (!Array.isArray(list)) {
7235
- clearMarks();
7236
- return;
7237
- }
7238
- var sorted = list
7239
- .slice()
7240
- .sort(function (a, b) {
7241
- return b.textStart - a.textStart;
7242
- });
7243
- var nextKey = highlightKey(sorted);
7244
- if (
7245
- nextKey === appliedHighlightKey &&
7246
- (marks.length > 0 || badges.length > 0 || sorted.length === 0)
7247
- ) {
7248
- updateHighlightBadges(sorted);
7249
- return;
7250
- }
7251
- clearMarks();
7252
- sorted.forEach(wrapRange);
7253
- positionBadges();
7254
- appliedHighlightKey =
7255
- marks.length > 0 || badges.length > 0 || sorted.length === 0 ? nextKey : '';
7256
- }
7257
-
7258
- function scrollToThread(id) {
7259
- var element = document.querySelector(
7260
- '.ash-comment-highlight[data-thread-id="' + CSS.escape(id) + '"], .ash-comment-highlight-badge[data-thread-id="' + CSS.escape(id) + '"], .ash-comment-highlight-svg[data-thread-id="' + CSS.escape(id) + '"]',
7261
- );
7262
- if (element) element.scrollIntoView({ block: 'center', behavior: 'smooth' });
7263
- }
7264
-
7265
- function rectFromPointer(event, fallback) {
7266
- if (
7267
- event.detail !== 0 &&
7268
- typeof event.clientX === 'number' &&
7269
- typeof event.clientY === 'number'
7270
- ) {
7271
- return {
7272
- top: event.clientY - 8,
7273
- left: event.clientX,
7274
- width: 1,
7275
- height: 16,
7276
- };
7277
- }
7278
- return fallback;
7279
- }
7280
-
7281
- function bindCommentPointer(element) {
7282
- element.addEventListener('click', function (event) {
7283
- var r = this.getBoundingClientRect();
7284
- selectThreadFromElement(this, rectFromPointer(event, r));
7285
- event.preventDefault();
7286
- event.stopPropagation();
7287
- });
7288
- }
7289
-
7290
- function bindBadgePointer(badge) {
7291
- var dragState = null;
7292
- var badgeEntry = null;
7293
-
7294
- function finishDrag(event) {
7295
- if (!dragState || event.pointerId !== dragState.pointerId) return;
7296
- if (event.type === 'pointerup' && dragState.dragged) badgeDragged = true;
7297
- try {
7298
- badge.releasePointerCapture(event.pointerId);
7299
- } catch (e) {}
7300
- dragState = null;
7301
- }
7302
-
7303
- badge.addEventListener('pointerdown', function (event) {
7304
- badgeDragged = false;
7305
- if (event.button !== 0) return;
7306
- for (var i = 0; i < badges.length; i++) {
7307
- if (badges[i].badge === badge) {
7308
- badgeEntry = badges[i];
7309
- break;
7310
- }
7311
- }
7312
- var threadId = badge.dataset.threadId;
7313
- var offset = badgeOffsets[threadId] || { x: 0, y: 0 };
7314
- dragState = {
7315
- pointerId: event.pointerId,
7316
- startX: event.clientX,
7317
- startY: event.clientY,
7318
- offsetX: offset.x,
7319
- offsetY: offset.y,
7320
- dragged: false,
7321
- };
7322
- try {
7323
- badge.setPointerCapture(event.pointerId);
7324
- } catch (e) {}
7325
- event.preventDefault();
7326
- });
7327
-
7328
- badge.addEventListener('pointermove', function (event) {
7329
- if (!dragState || event.pointerId !== dragState.pointerId) return;
7330
- var dx = event.clientX - dragState.startX;
7331
- var dy = event.clientY - dragState.startY;
7332
- if (!dragState.dragged && (Math.abs(dx) > 4 || Math.abs(dy) > 4)) {
7333
- dragState.dragged = true;
7334
- }
7335
- if (!dragState.dragged) return;
7336
- var threadId = badge.dataset.threadId;
7337
- badgeOffsets[threadId] = {
7338
- x: dragState.offsetX + dx,
7339
- y: dragState.offsetY + dy,
7340
- };
7341
- if (badgeEntry) positionSingleBadge(badgeEntry);
7342
- });
7343
-
7344
- badge.addEventListener('pointerup', finishDrag);
7345
- badge.addEventListener('pointercancel', finishDrag);
7346
-
7347
- badge.addEventListener('click', function (event) {
7348
- if (badgeDragged) {
7349
- badgeDragged = false;
7350
- event.preventDefault();
7351
- event.stopPropagation();
7352
- return;
7353
- }
7354
- var r = badge.getBoundingClientRect();
7355
- selectThreadFromElement(badge, rectFromPointer(event, r));
7356
- event.preventDefault();
7357
- event.stopPropagation();
7358
- });
7359
- function updateSvgActive(active) {
7360
- svgActiveThreads[badge.dataset.threadId] = active;
7361
- setSvgHighlightState(badge.dataset.threadId, active);
7362
- }
7363
- badge.addEventListener('pointerenter', function () { updateSvgActive(true); });
7364
- badge.addEventListener('pointerleave', function () { updateSvgActive(document.activeElement === badge); });
7365
- badge.addEventListener('focus', function () { updateSvgActive(true); });
7366
- badge.addEventListener('blur', function () { updateSvgActive(badge.matches(':hover')); });
7367
- }
7368
-
7369
- function selectThreadFromElement(element, rect) {
7370
- send({
7371
- kind: 'comment-thread-selected',
7372
- threadId: element.dataset.threadId,
7373
- rect: {
7374
- top: rect.top,
7375
- left: rect.left,
7376
- width: rect.width,
7377
- height: rect.height,
7378
- },
7379
- });
7380
- }
7381
-
7382
- function sendOutsidePointerDown(event) {
7383
- if (!textAnchorsEnabled) return;
7384
- var target = event.target;
7385
- if (
7386
- target &&
7387
- target.closest &&
7388
- target.closest(
7389
- '.ash-comment-highlight, .ash-comment-highlight-badge, [data-code-copy]',
7390
- )
7391
- ) {
7392
- return;
7393
- }
7394
- send({ kind: 'comment-outside-pointer-down' });
7395
- }
7396
-
7397
- function updateMarkdownToc() {
7398
- var links = document.querySelectorAll('.md-toc a[href^="#"]');
7399
- if (!links.length) return;
7400
- var activeId = null;
7401
- for (var index = 0; index < links.length; index++) {
7402
- var id = links[index].getAttribute('href').slice(1);
7403
- var heading = document.getElementById(id);
7404
- if (heading && heading.getBoundingClientRect().top <= 96) activeId = id;
7405
- }
7406
- if (!activeId) activeId = links[0].getAttribute('href').slice(1);
7407
- for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
7408
- if (links[linkIndex].getAttribute('href').slice(1) === activeId) {
7409
- links[linkIndex].setAttribute('aria-current', 'location');
7410
- } else {
7411
- links[linkIndex].removeAttribute('aria-current');
7412
- }
7413
- }
7414
- }
7415
-
7416
- var annotateModeEnabled = false;
7417
- var annotateHoverElement = null;
7418
-
7419
- function ensureAnnotateStyles() {
7420
- if (document.getElementById('as-preview-annotate-style')) return;
7421
- var style = document.createElement('style');
7422
- style.id = 'as-preview-annotate-style';
7423
- style.textContent =
7424
- '.as-preview-annotate-hover{outline:2px solid #6366f1 !important;outline-offset:2px;}' +
7425
- '.as-preview-pinged{outline:2px solid #6366f1 !important;outline-offset:2px;background-color:rgba(99,102,241,0.12) !important;transition:background-color 0.4s ease;}' +
7426
- '.as-preview-flash{background-color:rgba(34,197,94,0.35) !important;transition:background-color 1s ease;}' +
7427
- '.as-preview-flash-fade{background-color:transparent !important;}';
7428
- document.head.appendChild(style);
7429
- }
7430
-
7431
- function annotateTargetFrom(target) {
7432
- if (!target || target.nodeType !== 1) return null;
7433
- if (target === document.body || target === document.documentElement) return null;
7434
- if (target.closest && target.closest('[data-comment-ui]')) return null;
7435
- return target;
7436
- }
7437
-
7438
- function clearAnnotateHover() {
7439
- if (annotateHoverElement) {
7440
- annotateHoverElement.classList.remove('as-preview-annotate-hover');
7441
- annotateHoverElement = null;
7442
- }
7443
- }
7444
-
7445
- function elementLabel(el) {
7446
- var quote = function (text) {
7447
- return '\x22' + text + '\x22';
7448
- };
7449
- var tag = el.nodeName.toLowerCase();
7450
- var ariaLabel = el.getAttribute && el.getAttribute('aria-label');
7451
- if (ariaLabel) return tag + ' ' + quote(ariaLabel.trim());
7452
- var text = (el.textContent || '').replace(/\\s+/g, ' ').trim();
7453
- if (text) return tag + ' ' + quote(text.slice(0, 25));
7454
- if (tag === 'img') {
7455
- var alt = el.getAttribute('alt');
7456
- if (alt) return 'img ' + quote(alt.trim());
7457
- }
7458
- var role = el.getAttribute && el.getAttribute('role');
7459
- if (role) return tag + ' [role=' + role + ']';
7460
- return tag;
7461
- }
7462
-
7463
- function siblingText(el) {
7464
- return el && el.textContent
7465
- ? el.textContent.replace(/\\s+/g, ' ').trim().slice(0, 40)
7466
- : '';
7467
- }
7468
-
7469
- function annotateContextText(el) {
7470
- var own = (el.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 100);
7471
- var before = siblingText(el.previousElementSibling);
7472
- var after = siblingText(el.nextElementSibling);
7473
- var parts = [own];
7474
- if (before) parts.push('[before: ' + before + ']');
7475
- if (after) parts.push('[after: ' + after + ']');
7476
- return parts.join(' ').trim();
7477
- }
7478
-
7479
- /** Re-resolve saved anchors against the reloaded document.
7480
- *
7481
- * The captured selector is positional, so it answers the wrong question
7482
- * twice over: inserting anything above the target breaks a path that still
7483
- * has its element, and deleting the first of two identical items leaves the
7484
- * path quietly matching the survivor. What identifies the target is its own
7485
- * content, so that is what is searched for; the captured surroundings only
7486
- * decide between several equal candidates. */
7487
- function verifyAnchors(anchors) {
7488
- var verdicts = [];
7489
- var bodyText = null;
7490
- for (var i = 0; i < (anchors || []).length; i++) {
7491
- var anchor = anchors[i] || {};
7492
- var attached = false;
7493
- if (anchor.kind === 'element') {
7494
- attached = findElement(anchor) !== null;
7495
- } else if (anchor.kind === 'text') {
7496
- if (bodyText === null) bodyText = anchorTextContent();
7497
- attached = anchor.quotedText !== '' && findQuoted(bodyText, anchor) !== -1;
7498
- }
7499
- verdicts.push({ thread: anchor.thread, attached: attached });
7500
- }
7501
- send({ kind: 'anchor-verdicts', verdicts: verdicts });
7502
- }
7503
-
7504
- function findElement(anchor) {
7505
- if (!anchor.ownText) {
7506
- // Nothing to search for, so the selector is all there is.
7507
- try { return document.querySelector(anchor.selector); } catch (error) { return null; }
7508
- }
7509
- var peers = anchor.tagName
7510
- ? anchorRoot().getElementsByTagName(anchor.tagName)
7511
- : anchorRoot().getElementsByTagName('*');
7512
- var matches = [];
7513
- for (var i = 0; i < peers.length; i++) {
7514
- if (ownText(peers[i]) === anchor.ownText) matches.push(peers[i]);
7515
- }
7516
- if (matches.length === 0) return null;
7517
- if (matches.length === 1) return matches[0];
7518
- for (var j = 0; j < matches.length; j++) {
7519
- if (annotateContextText(matches[j]) === anchor.contextText) return matches[j];
7520
- }
7521
- // Several identical candidates and none in the captured surroundings:
7522
- // saying "attached" here would point the comment at content nobody wrote
7523
- // it about.
7524
- return null;
7525
- }
7526
-
7527
- /** One occurrence is the target. Several means the captured prefix and
7528
- * suffix have to say which. */
7529
- function findQuoted(bodyText, anchor) {
7530
- var first = bodyText.indexOf(anchor.quotedText);
7531
- if (first === -1) return -1;
7532
- if (bodyText.indexOf(anchor.quotedText, first + 1) === -1) return first;
7533
- var from = 0;
7534
- while (true) {
7535
- var at = bodyText.indexOf(anchor.quotedText, from);
7536
- if (at === -1) return -1;
7537
- var end = at + anchor.quotedText.length;
7538
- var prefix = bodyText.slice(Math.max(0, at - 120), at).trim();
7539
- var suffix = bodyText.slice(end, Math.min(bodyText.length, end + 120)).trim();
7540
- if (prefix === anchor.prefixText && suffix === anchor.suffixText) return at;
7541
- from = at + 1;
7542
- }
7543
- }
7544
-
7545
- function ownText(el) {
7546
- return (el.textContent || '').replace(/\\s+/g, ' ').trim();
7547
- }
7548
-
7549
- function setAnnotateMode(enabled) {
7550
- annotateModeEnabled = enabled === true;
7551
- if (annotateModeEnabled) {
7552
- ensureAnnotateStyles();
7553
- } else {
7554
- clearAnnotateHover();
7555
- }
7556
- }
7557
-
7558
- function pingElement(selector) {
7559
- if (typeof selector !== 'string' || !selector) return;
7560
- var el = null;
7561
- try {
7562
- el = document.querySelector(selector);
7563
- } catch (error) {}
7564
- if (!el) return;
7565
- ensureAnnotateStyles();
7566
- el.scrollIntoView({ behavior: 'smooth', block: 'center' });
7567
- el.classList.add('as-preview-pinged');
7568
- setTimeout(function () {
7569
- el.classList.remove('as-preview-pinged');
7570
- }, 2500);
7571
- }
7572
-
7573
- function flashElement(selector) {
7574
- if (typeof selector !== 'string' || !selector) return;
7575
- var el = null;
7576
- try {
7577
- el = document.querySelector(selector);
7578
- } catch (error) {}
7579
- if (!el) return;
7580
- ensureAnnotateStyles();
7581
- el.classList.add('as-preview-flash');
7582
- setTimeout(function () {
7583
- el.classList.add('as-preview-flash-fade');
7584
- }, 100);
7585
- setTimeout(function () {
7586
- el.classList.remove('as-preview-flash');
7587
- el.classList.remove('as-preview-flash-fade');
7588
- }, 1100);
7589
- }
7590
-
7591
- function onAnnotateHover(event) {
7592
- if (!annotateModeEnabled) return;
7593
- var target = annotateTargetFrom(targetGet ? targetGet(event) : event.target);
7594
- if (target === annotateHoverElement) return;
7595
- clearAnnotateHover();
7596
- if (!target) return;
7597
- annotateHoverElement = target;
7598
- target.classList.add('as-preview-annotate-hover');
7599
- }
7600
-
7601
- function onAnnotateClick(event) {
7602
- if (!annotateModeEnabled) return;
7603
- var target = annotateTargetFrom(targetGet ? targetGet(event) : event.target);
7604
- if (!target) return;
7605
- event.preventDefault();
7606
- event.stopPropagation();
7607
- // The click that ends a drag-selection belongs to that selection, not to
7608
- // an element pick. Both would otherwise open the popover and the anchor
7609
- // kind would depend on which task the browser ran first.
7610
- var selected = getSelection();
7611
- if (selected && !selected.isCollapsed && selected.toString().trim()) return;
7612
- var rect = target.getBoundingClientRect();
7613
- send({
7614
- kind: 'element-annotate',
7615
- selector: cssPath(target),
7616
- label: elementLabel(target),
7617
- contextText: annotateContextText(target),
7618
- ownText: ownText(target),
7619
- tagName: target.tagName,
7620
- rect: {
7621
- top: rect.top,
7622
- left: rect.left,
7623
- width: rect.width,
7624
- height: rect.height,
7625
- },
7626
- });
7627
- }
7628
-
7629
- addEventListener(document, 'mousemove', onAnnotateHover, true);
7630
- addEventListener(document, 'mouseover', onAnnotateHover, true);
7631
- addEventListener(document, 'click', onAnnotateClick, true);
7632
-
7633
- savedAddEventListener('message', function (event) {
7634
- var data = event.data || {};
7635
- if (event.source !== savedParent || data.source !== '${READY_CHECK_MESSAGE_SOURCE}') {
7636
- return;
7637
- }
7638
- if (data.kind === '${READY_CHECK_MESSAGE_KIND}') {
7639
- onReadyCheck(event);
7640
- textAnchorsEnabled = data.textAnchorsEnabled === true;
7641
- setCommentLabels(data.commentLabels);
7642
- } else if (
7643
- data.kind === 'external-link-policy' &&
7644
- (data.mode === 'parent' || data.mode === 'direct')
7645
- ) {
7646
- externalLinkPolicyMode = data.mode;
7647
- } else if (data.kind === 'comment-highlights') {
7648
- textAnchorsEnabled = data.textAnchorsEnabled === true;
7649
- setCommentLabels(data.commentLabels);
7650
- applyHighlights(data.highlights);
7651
- } else if (data.kind === 'scroll-to-comment') {
7652
- scrollToThread(data.threadId);
7653
- } else if (data.kind === 'mermaid-rendered') {
7654
- installMermaidResults(data.renderToken, data.results);
7655
- } else if (data.kind === 'annotate-mode') {
7656
- setAnnotateMode(data.enabled);
7657
- } else if (data.kind === 'element-ping') {
7658
- pingElement(data.selector);
7659
- } else if (data.kind === 'element-flash') {
7660
- flashElement(data.selector);
7661
- } else if (data.kind === 'verify-anchors') {
7662
- verifyAnchors(data.anchors);
7663
- }
7664
- });
7665
-
7666
- document.addEventListener('mouseup', function () {
7667
- setTimeout(sendSelection, 0);
7668
- });
7669
- document.addEventListener('keyup', function () {
7670
- setTimeout(sendSelection, 0);
7671
- });
7672
- document.addEventListener('click', function (event) {
7673
- var target = event.target;
7674
- var button = target && target.closest && target.closest('[data-code-copy]');
7675
- if (!button) return;
7676
- var block = button.closest('.md-code-block');
7677
- var code = block && block.querySelector('pre code');
7678
- if (!code) return;
7679
- event.preventDefault();
7680
- event.stopPropagation();
7681
-
7682
- var copied = function () {
7683
- button.textContent = 'Copied';
7684
- button.setAttribute('aria-label', 'Code copied');
7685
- setTimeout(function () {
7686
- button.textContent = 'Copy';
7687
- button.setAttribute('aria-label', 'Copy code');
7688
- }, 1500);
7689
- };
7690
- var fallback = function () {
7691
- var textarea = document.createElement('textarea');
7692
- textarea.value = code.textContent || '';
7693
- textarea.style.position = 'fixed';
7694
- textarea.style.opacity = '0';
7695
- document.body.appendChild(textarea);
7696
- textarea.select();
7697
- try {
7698
- if (document.execCommand('copy')) copied();
7699
- } catch (error) {}
7700
- textarea.remove();
7701
- };
7702
- if (navigator.clipboard && navigator.clipboard.writeText) {
7703
- navigator.clipboard.writeText(code.textContent || '').then(copied, fallback);
7704
- } else {
7705
- fallback();
7706
- }
7707
- });
7708
- addEventListener(window, 'click', prepareLinkClick, true);
7709
- addEventListener(window, 'click', finishLinkClick);
7710
- document.addEventListener('pointerdown', sendOutsidePointerDown);
7711
- document.addEventListener('${VIOLATION_REPORTER_MARKER}', function (event) {
7712
- send({
7713
- kind: 'csp-violation',
7714
- directive: event.violatedDirective || event.effectiveDirective,
7715
- blockedURI: event.blockedURI || 'inline',
7716
- sourceFile: event.sourceFile || null,
7717
- lineNumber: event.lineNumber || null,
7718
- });
7719
- });
7720
-
7721
- window.addEventListener('resize', schedulePositionBadges);
7722
- window.addEventListener('load', schedulePositionBadges);
7723
- window.addEventListener('load', updateMarkdownToc);
7724
- window.addEventListener('scroll', updateMarkdownToc, { passive: true });
7725
- if (document.fonts && document.fonts.ready) {
7726
- document.fonts.ready.then(schedulePositionBadges);
7727
- }
7728
-
7729
- var readyCount = 0;
7730
- var readyInterval = setInterval(function () {
7731
- ready();
7732
- if (++readyCount >= 20) clearInterval(readyInterval);
7733
- }, 100);
7734
- ready();
7735
- })();`}<\/script>`;
6164
+ //#endregion
6165
+ //#region ../viewer-kit/src/csp-reporter.ts
6166
+ const VIOLATION_REPORTER_TAG = `<script>${VIOLATION_REPORTER_SCRIPT_BODY}<\/script>`;
7736
6167
  //#endregion
7737
6168
  //#region ../viewer-kit/src/inject.ts
7738
6169
  function injectReadyReporter(html) {
@@ -10337,7 +8768,7 @@ function highlightCode(html) {
10337
8768
  const language = matchedLanguage ?? "text";
10338
8769
  const label = readAttribute(attributes, "data-code-title") ?? readAttribute(attributes, "data-filename") ?? language;
10339
8770
  const renderedCode = language === "mermaid" ? original : highlightTanStackCode(decodeHtml(encodedCode), language).html;
10340
- return `<figure class="md-code-block" data-lang="${escapeAttribute(language)}"><figcaption class="md-code-toolbar"><span class="md-code-label">${escapeHtml$2(label)}</span><button type="button" class="md-code-copy" data-code-copy aria-label="Copy code">Copy</button></figcaption>${renderedCode}</figure>`;
8771
+ return `<figure class="md-code-block" data-lang="${escapeAttribute(language)}"><figcaption class="md-code-toolbar" data-anchor-ignore><span class="md-code-label">${escapeHtml$2(label)}</span><button type="button" class="md-code-copy" data-code-copy data-anchor-ignore aria-label="Copy code">Copy</button></figcaption>${renderedCode}</figure>`;
10341
8772
  }).replace(/<figure class="tm-code-frame"[^>]*><figcaption>[\s\S]*?<\/figcaption>(<figure class="md-code-block"[\s\S]*?<\/figure>)<\/figure>/g, "$1");
10342
8773
  }
10343
8774
  function readAttribute(attributes, name) {
@@ -10889,7 +9320,7 @@ function renderPreviewShell(options) {
10889
9320
  cursor: pointer; color: var(--muted-foreground); font-size: 12px; padding: 3px 4px;
10890
9321
  min-width: 24px; min-height: 24px; flex: none; }
10891
9322
  .thread .draft-del:hover, .thread .reopen-btn:hover { color: var(--foreground); }
10892
- .thread.orphaned .anchor-label { text-decoration: line-through; }
9323
+
10893
9324
  .panel .empty { color: var(--muted-foreground); font-size: 12.5px; padding: 20px 4px; text-align: center; }
10894
9325
  .submit-bar { display: none; align-items: center; gap: 8px; }
10895
9326
  .submit-bar.show { display: flex; }
@@ -11032,7 +9463,7 @@ function renderPreviewShell(options) {
11032
9463
  // reconcile once the first frame is ready rather than waiting for a save.
11033
9464
  frame.addEventListener('load', function onFirstLoad() {
11034
9465
  frame.removeEventListener('load', onFirstLoad);
11035
- setTimeout(checkOrphans, 400);
9466
+ setTimeout(() => { lastVerifiedAnchors = null; checkOrphans(); }, 400);
11036
9467
  }); const body = document.body;
11037
9468
  const popover = document.getElementById('popover');
11038
9469
  const popTarget = document.getElementById('popTarget');
@@ -11057,6 +9488,10 @@ function renderPreviewShell(options) {
11057
9488
  let revision = null;
11058
9489
  let pendingReload = null;
11059
9490
  let orphanedThreads = new Set();
9491
+ let checkingThreads = new Set();
9492
+ let lastVerifiedAnchors = null;
9493
+ let verificationId = 0;
9494
+ let verificationGeneration = -1;
11060
9495
  let verifyPending = false;
11061
9496
  let batchWorkingCount = 0;
11062
9497
  function renderBatchStatus() {
@@ -11160,13 +9595,16 @@ function renderPreviewShell(options) {
11160
9595
  ownText: data.ownText, tagName: data.tagName,
11161
9596
  }, data.label, data.rect);
11162
9597
  } else if (data.kind === 'anchor-verdicts') {
9598
+ if (data.verificationId !== verificationId || !Number.isSafeInteger(data.generation) || data.generation <= verificationGeneration) return;
9599
+ verificationGeneration = data.generation;
11163
9600
  applyAnchorVerdicts(data.verdicts);
11164
9601
  } else if (data.kind === 'text-selection') {
11165
9602
  // The reporter keeps emitting selections so normal reading still works;
11166
9603
  // only annotation mode turns one into a comment.
11167
9604
  if (!annotateMode) return;
11168
9605
  openPopover({
11169
- kind: 'text', state: 'attached',
9606
+ kind: 'text', state: 'attached', position_state: 'attached',
9607
+ selectorFormat: data.selectorFormat, textHash: data.textHash, ambiguousAtCreation: data.ambiguousAtCreation,
11170
9608
  quotedText: data.quotedText, prefixText: data.prefixText,
11171
9609
  suffixText: data.suffixText, textStart: data.textStart,
11172
9610
  textEnd: data.textEnd, cssPath: data.cssPath,
@@ -11265,6 +9703,8 @@ function renderPreviewShell(options) {
11265
9703
  const label = document.createElement('span');
11266
9704
  label.className = 'anchor-label';
11267
9705
  label.textContent = anchorLabel(annotation.anchor);
9706
+ if (checkingThreads.has(annotation.thread)) label.textContent += ' · ' + t('preview.positionChecking');
9707
+ else if (orphanedThreads.has(annotation.thread)) label.textContent += ' · ' + t('preview.positionNeedsCheck');
11268
9708
  const state = document.createElement('span');
11269
9709
  state.className = 'state';
11270
9710
  state.textContent = stateLabel(annotation.status);
@@ -11302,7 +9742,7 @@ function renderPreviewShell(options) {
11302
9742
  });
11303
9743
  thread.addEventListener('click', () => {
11304
9744
  if (annotation.anchor && annotation.anchor.kind === 'element') {
11305
- postToFrame({ kind: 'element-ping', selector: annotation.anchor.selector });
9745
+ if (!orphanedThreads.has(annotation.thread) && !checkingThreads.has(annotation.thread)) postToFrame({ kind: 'element-ping', selector: annotation.anchor.selector });
11306
9746
  }
11307
9747
  });
11308
9748
  threadsEl.appendChild(thread);
@@ -11357,12 +9797,14 @@ function renderPreviewShell(options) {
11357
9797
 
11358
9798
  // --- reload + orphan handling ------------------------------------------
11359
9799
  function reloadFrame(nextRevision) {
9800
+ verificationId++;
9801
+ verificationGeneration = -1;
11360
9802
  let scrollY = 0;
11361
9803
  try { scrollY = frame.contentWindow.scrollY || 0; } catch (error) {}
11362
9804
  const restore = () => {
11363
9805
  try { frame.contentWindow.scrollTo(0, scrollY); } catch (error) {}
11364
9806
  startReadyBurst();
11365
- setTimeout(checkOrphans, 400);
9807
+ setTimeout(() => { lastVerifiedAnchors = null; checkOrphans(); }, 400);
11366
9808
  frame.removeEventListener('load', restore);
11367
9809
  };
11368
9810
  frame.addEventListener('load', restore);
@@ -11379,27 +9821,39 @@ function renderPreviewShell(options) {
11379
9821
  const anchor = annotation.anchor;
11380
9822
  return Boolean(anchor) && anchor.kind !== 'artifact';
11381
9823
  });
11382
- if (pending.length === 0) return;
9824
+ const key = JSON.stringify(pending.map(annotation => {
9825
+ const { state, position_state, ...selector } = annotation.anchor;
9826
+ return { thread: annotation.thread, ...selector };
9827
+ }));
9828
+ if (key === lastVerifiedAnchors) return;
9829
+ lastVerifiedAnchors = key;
9830
+ checkingThreads = new Set(pending.map(annotation => annotation.thread));
9831
+ renderPanel();
9832
+ verificationId++;
9833
+ verificationGeneration = -1;
11383
9834
  const request = {
9835
+ verificationId,
11384
9836
  kind: 'verify-anchors',
11385
9837
  anchors: pending.map((annotation) => Object.assign(
11386
9838
  { thread: annotation.thread }, annotation.anchor)),
11387
9839
  };
11388
9840
  verifyPending = true;
9841
+ postToFrame({ kind: 'comment-highlights', textAnchorsEnabled: true, highlights: pending.filter(a => a.anchor.kind === 'text').map(a => Object.assign({ threadId: a.thread, count: 1 }, a.anchor)) });
11389
9842
  postToFrame(request);
11390
9843
  // The frame arms its listener during the ready handshake, which this can
11391
9844
  // still race. One resend keeps a missed request from leaving every anchor
11392
9845
  // on a stale verdict.
11393
- setTimeout(() => { if (verifyPending) postToFrame(request); }, 1200);
9846
+ setTimeout(() => { if (verifyPending && request.verificationId === verificationId) postToFrame(request); }, 1200);
11394
9847
  }
11395
9848
 
11396
9849
  function applyAnchorVerdicts(verdicts) {
11397
9850
  verifyPending = false;
11398
9851
  const attached = new Map((verdicts || []).map((v) => [v.thread, v.attached === true]));
9852
+ checkingThreads = new Set((verdicts || []).filter(v => v.position_state === 'checking').map(v => v.thread));
11399
9853
  const newlyOrphaned = [];
11400
9854
  const states = [];
11401
9855
  annotations.forEach((annotation) => {
11402
- if (!attached.has(annotation.thread)) return;
9856
+ if (!attached.has(annotation.thread) || checkingThreads.has(annotation.thread)) return;
11403
9857
  const anchor = annotation.anchor;
11404
9858
  const found = attached.get(annotation.thread);
11405
9859
  if (!found && !orphanedThreads.has(annotation.thread)) {
@@ -11408,7 +9862,7 @@ function renderPreviewShell(options) {
11408
9862
  if (!found) orphanedThreads.add(annotation.thread);
11409
9863
  else orphanedThreads.delete(annotation.thread);
11410
9864
  const nextState = found ? 'attached' : 'orphaned';
11411
- if (anchor.state !== nextState) {
9865
+ if (anchor.state !== nextState || (anchor.kind === 'text' && anchor.position_state !== (found ? 'attached' : 'needs-check'))) {
11412
9866
  states.push({ thread: annotation.thread, state: nextState });
11413
9867
  }
11414
9868
  });
@@ -11465,6 +9919,7 @@ function renderPreviewShell(options) {
11465
9919
  }
11466
9920
  catch (error) { return; }
11467
9921
  renderPanel();
9922
+ checkOrphans();
11468
9923
  });
11469
9924
  events.addEventListener('reload', (event) => {
11470
9925
  let data = null;
@@ -11515,6 +9970,7 @@ function renderPreviewShell(options) {
11515
9970
  agent = (data && data.agent) || agent;
11516
9971
  revision = data ? data.revision : null;
11517
9972
  renderPanel();
9973
+ checkOrphans();
11518
9974
  if (data && data.quarantined) {
11519
9975
  // The saved annotations could not be read; say so, or the empty panel
11520
9976
  // reads as "my work was never saved".
@@ -13642,6 +12098,12 @@ async function runEdit(parsed, mode) {
13642
12098
  function buildEditPayload(parsed) {
13643
12099
  const body = {};
13644
12100
  let hasChange = false;
12101
+ if (parsed.options.retainVersions !== void 0) {
12102
+ const value = parsed.options.retainVersions;
12103
+ if (value !== "all" && (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value)))) return { error: validationError("--retain-versions must be a positive integer or all.", "Pass --retain-versions 1 or --retain-versions all.") };
12104
+ body.retain_versions = value === "all" ? null : Number(value);
12105
+ hasChange = true;
12106
+ }
13645
12107
  if (parsed.options.linkExpiresAt !== void 0 && parsed.options.noLinkExpiry === true) return { error: validationError("Choose only one link expiry option.", "Pass --link-expires-at <RFC3339 UTC> or --no-link-expiry, not both.") };
13646
12108
  if (parsed.options.title !== void 0) {
13647
12109
  body.title = parsed.options.title;
@@ -13682,7 +12144,7 @@ function buildEditPayload(parsed) {
13682
12144
  body.destination = { project_id: projectId };
13683
12145
  hasChange = true;
13684
12146
  }
13685
- if (!hasChange) return { error: validationError("At least one edit option is required.", "Pass --title, --visibility, --link-expires-at, --no-link-expiry, --grant-email, --revoke-email, --project-id, or --home.") };
12147
+ if (!hasChange) return { error: validationError("At least one edit option is required.", "Pass --title, --visibility, --link-expires-at, --no-link-expiry, --retain-versions, --grant-email, --revoke-email, --project-id, or --home.") };
13686
12148
  return { body };
13687
12149
  }
13688
12150
  function normalizedEmailOptions(value) {
@@ -15289,6 +13751,11 @@ const editDefinition = define({
15289
13751
  toKebab: true,
15290
13752
  description: "Set a finite link expiry as an RFC3339 UTC timestamp"
15291
13753
  },
13754
+ retainVersions: {
13755
+ type: "string",
13756
+ toKebab: true,
13757
+ description: "Keep the latest N versions; use all to clear retention (owner only)"
13758
+ },
15292
13759
  noLinkExpiry: {
15293
13760
  type: "boolean",
15294
13761
  toKebab: true,
@@ -15625,7 +14092,7 @@ const commentsPostDefinition = define({
15625
14092
  quote: {
15626
14093
  type: "string",
15627
14094
  toKebab: true,
15628
- description: "Anchor the comment to this exact text from the artifact (new threads only)"
14095
+ description: "Quote text for strict viewer resolution (new threads only)"
15629
14096
  },
15630
14097
  quoteBefore: {
15631
14098
  type: "string",
@@ -15647,14 +14114,15 @@ const commentsPostDefinition = define({
15647
14114
  npm exec --yes --package=@artifactshare/cli -- artifactshare comments post abc123def4 --body "Done" --reply-to <thread-id> --json
15648
14115
  npm exec --yes --package=@artifactshare/cli -- artifactshare comments post abc123def4 --body "Fix this" --quote "exact text" --json
15649
14116
 
15650
- Copy quote text from artifacts get so it matches the artifact exactly.
14117
+ The viewer resolves quoted comments using unique exact quote and context.
14118
+ Resolution is deferred until the version is viewed; anchor.position_state is
14119
+ attached, needs-check, or unchecked. Context supports 400 characters per side.
15651
14120
 
15652
14121
  Common failures:
15653
14122
  auth_required Set ARTIFACTSHARE_TOKEN before comments post
15654
14123
  target_not_found Retry with an artifact ID, share URL, or sandbox URL
15655
14124
  thread_not_found Run comments list and retry with a listed thread id
15656
14125
  thread_resolved Reopen the thread in the viewer, or start a new thread
15657
- quote_not_found Copy the exact text from artifacts get
15658
14126
  validation_failed Pass --body, and do not combine --quote with --reply-to`
15659
14127
  });
15660
14128
  const commentThreadActionArgs = {