pipeup 0.9.1 → 1.0.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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Comments and feedback right on any HTML page: documents, slide decks and whole sites.
4
4
 
5
- > **Alpha (0.9.1).** The API and the stored comment format may change before 1.0; pin an exact version.
5
+ > **Alpha (1.0.0).** The API and the stored comment format may change before 1.0; pin an exact version.
6
6
  > Website and Try pages: https://pipeup-ai.github.io/pipeup/ · Source: https://github.com/pipeup-ai/pipeup
7
7
 
8
8
  Pipeup: signed comment operations, threads with one-level replies, anchors that survive page changes,
@@ -23,7 +23,7 @@ its address:
23
23
  ```html
24
24
  <html data-pipeup-doc="<id>:<key>">
25
25
  ...
26
- <script src="https://cdn.jsdelivr.net/npm/pipeup@0.9.1/dist/pipeup.min.js" integrity="sha384-…" crossorigin="anonymous" defer></script>
26
+ <script src="https://cdn.jsdelivr.net/npm/pipeup@1.0.0/dist/pipeup.min.js" integrity="sha384-…" crossorigin="anonymous" defer></script>
27
27
  ```
28
28
 
29
29
  On a host that writes its own `<html>` (claude.ai Artifacts, for example), put the same settings on the script
@@ -45,7 +45,7 @@ Install with `npm i pipeup`. From a bundler (no side effects; call `mount` yours
45
45
 
46
46
  ```js
47
47
  import { mount } from "pipeup";
48
- const pipeup = await mount({ name: "Sam" }); // options: root, name, store, slides, doc, layout, theme, select
48
+ const pipeup = await mount({ name: "Sam" }); // options: root, name, store, prefs, keep, closed, field, ui, slides, doc, layout, theme, select, control
49
49
  await pipeup.flush(); // write any unsaved changes now (this also happens when the page is hidden)
50
50
  pipeup.unmount(); // remove Pipeup from the page; the comments stay saved
51
51
  ```
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env node
2
+ // The program the browser starts when the Pipeup extension talks to this computer (native messaging): one message in,
3
+ // one answer out, each a 4-byte length (in the computer's byte order) then JSON. See browser.mjs.
4
+ import { receive, replies } from "./browser.mjs";
5
+
6
+ let buffer = Buffer.alloc(0);
7
+
8
+ function answer(message) {
9
+ const body = Buffer.from(JSON.stringify(message));
10
+ const head = Buffer.alloc(4);
11
+ head.writeUInt32LE(body.length, 0);
12
+ process.stdout.write(Buffer.concat([head, body]));
13
+ }
14
+
15
+ async function handle(m) {
16
+ try {
17
+ if (m?.type === "hello") return answer({ ok: true });
18
+ if (m?.type === "send") return answer({ ok: true, ...(await receive(m)) });
19
+ if (m?.type === "replies") return answer({ ok: true, replies: await replies(m.doc) });
20
+ answer({ ok: false, error: `unknown message ${JSON.stringify(m?.type)}` });
21
+ } catch (e) {
22
+ answer({ ok: false, error: String(e?.message ?? e) });
23
+ }
24
+ }
25
+
26
+ process.stdin.on("data", (chunk) => {
27
+ buffer = Buffer.concat([buffer, chunk]);
28
+ while (buffer.length >= 4) {
29
+ const size = buffer.readUInt32LE(0);
30
+ if (buffer.length < 4 + size) return;
31
+ const text = buffer.subarray(4, 4 + size).toString("utf8");
32
+ buffer = buffer.subarray(4 + size);
33
+ let message;
34
+ try {
35
+ message = JSON.parse(text);
36
+ } catch {
37
+ answer({ ok: false, error: "not JSON" });
38
+ continue;
39
+ }
40
+ void handle(message);
41
+ }
42
+ });
43
+ process.stdin.on("end", () => process.exit(0));
@@ -0,0 +1,144 @@
1
+ // pipeup browser: the browser extension's link to agents on this computer. The extension sends a page's comments here
2
+ // (through Chrome's native messaging, to browser-host.mjs), an agent reads them with `pipeup browser read` and answers
3
+ // with `pipeup browser reply`, and the extension puts the replies into their threads. Everything stays in
4
+ // ~/.pipeup/browser, one folder per page; nothing leaves this computer.
5
+ import { chmod, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
6
+ import { homedir, platform } from "node:os";
7
+ import { dirname, join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ /** The name the extension asks the browser for. */
11
+ export const HOST = "ai.pipeup.browser";
12
+ /** The extension's id in Firefox, which (unlike Chrome's) is the same on every computer. */
13
+ export const FIREFOX_ID = "extension@pipeup.ai";
14
+ /** Where pages sent from the browser are kept. */
15
+ export const inbox = () => process.env.PIPEUP_BROWSER_DIR || join(homedir(), ".pipeup", "browser");
16
+ /** A document id as a folder name: Pipeup's ids are letters, digits, "-", "_" and ":" (kept as "_"). */
17
+ const folderOf = (doc) =>
18
+ join(
19
+ inbox(),
20
+ String(doc)
21
+ .replace(/[^A-Za-z0-9_-]/g, "_")
22
+ .slice(0, 120),
23
+ );
24
+
25
+ /** Where each browser looks for native messaging hosts, per platform. */
26
+ const PLACES = {
27
+ darwin: {
28
+ chrome: "Library/Application Support/Google/Chrome/NativeMessagingHosts",
29
+ chromium: "Library/Application Support/Chromium/NativeMessagingHosts",
30
+ edge: "Library/Application Support/Microsoft Edge/NativeMessagingHosts",
31
+ brave: "Library/Application Support/BraveSoftware/Brave-Browser/NativeMessagingHosts",
32
+ firefox: "Library/Application Support/Mozilla/NativeMessagingHosts",
33
+ },
34
+ linux: {
35
+ chrome: ".config/google-chrome/NativeMessagingHosts",
36
+ chromium: ".config/chromium/NativeMessagingHosts",
37
+ edge: ".config/microsoft-edge/NativeMessagingHosts",
38
+ brave: ".config/BraveSoftware/Brave-Browser/NativeMessagingHosts",
39
+ firefox: ".mozilla/native-messaging-hosts",
40
+ },
41
+ };
42
+
43
+ /**
44
+ * Lets the extension reach this computer's agents: writes a small launcher (with this Node's own path, since a
45
+ * browser starts programs without the terminal's PATH) and the browser's host file, allowing only Pipeup's extension:
46
+ * `extensionId` in Chrome and its kin (each computer's copy has its own), Pipeup's fixed id in Firefox.
47
+ */
48
+ export async function install({ extensionId, browser = "chrome" }) {
49
+ const firefox = browser === "firefox";
50
+ if (!firefox && !/^[a-p]{32}$/.test(extensionId ?? ""))
51
+ throw new Error(
52
+ "give the extension's id: chrome://extensions shows it on Pipeup's card (32 letters a to p)",
53
+ );
54
+ const place = PLACES[platform()]?.[browser];
55
+ if (!place)
56
+ throw new Error(`setting up ${browser} on ${platform()} isn't supported yet (macOS and Linux are)`);
57
+ const host = fileURLToPath(new URL("./browser-host.mjs", import.meta.url));
58
+ const launcher = join(homedir(), ".pipeup", "browser-host.sh");
59
+ await mkdir(dirname(launcher), { recursive: true });
60
+ await writeFile(launcher, `#!/bin/sh\nexec "${process.execPath}" "${host}" "$@"\n`);
61
+ await chmod(launcher, 0o755);
62
+ const file = join(homedir(), place, `${HOST}.json`);
63
+ await mkdir(dirname(file), { recursive: true });
64
+ const manifest = {
65
+ name: HOST,
66
+ description: "Pipeup: comments from the browser for agents on this computer",
67
+ path: launcher,
68
+ type: "stdio",
69
+ ...(firefox
70
+ ? { allowed_extensions: [FIREFOX_ID] }
71
+ : { allowed_origins: [`chrome-extension://${extensionId}/`] }),
72
+ };
73
+ await writeFile(file, JSON.stringify(manifest, null, 2) + "\n");
74
+ return { file, launcher };
75
+ }
76
+
77
+ /** What the extension sent: the page, its comments as Markdown for an AI, and as a Pipeup comments file. */
78
+ export async function receive({ doc, url, title, markdown, file }) {
79
+ if (!doc || typeof markdown !== "string") throw new Error("nothing to keep: no page or comments");
80
+ const dir = folderOf(doc);
81
+ await mkdir(dir, { recursive: true });
82
+ await writeFile(
83
+ join(dir, "page.json"),
84
+ JSON.stringify({ doc, url, title, at: Date.now() }, null, 2) + "\n",
85
+ );
86
+ await writeFile(join(dir, "comments.md"), markdown);
87
+ if (typeof file === "string") await writeFile(join(dir, "comments.json"), file);
88
+ return { folder: dir };
89
+ }
90
+
91
+ /** The replies agents left for a page, oldest first. */
92
+ export async function replies(doc) {
93
+ try {
94
+ return JSON.parse(await readFile(join(folderOf(doc), "replies.json"), "utf8"));
95
+ } catch {
96
+ return [];
97
+ }
98
+ }
99
+
100
+ /** Every page sent from the browser, newest first. */
101
+ export async function pages() {
102
+ const names = await readdir(inbox()).catch(() => []);
103
+ const out = [];
104
+ for (const n of names) {
105
+ try {
106
+ out.push(JSON.parse(await readFile(join(inbox(), n, "page.json"), "utf8")));
107
+ } catch {
108
+ // Not a page's folder.
109
+ }
110
+ }
111
+ return out.sort((a, b) => b.at - a.at);
112
+ }
113
+
114
+ /** The page whose doc, address or title contains `which` (the newest when there are several), or null. */
115
+ export async function find(which) {
116
+ const all = await pages();
117
+ if (!which) return all[0] ?? null;
118
+ const w = String(which).toLowerCase();
119
+ return (
120
+ all.find((p) =>
121
+ [p.doc, p.url, p.title].some((v) =>
122
+ String(v ?? "")
123
+ .toLowerCase()
124
+ .includes(w),
125
+ ),
126
+ ) ?? null
127
+ );
128
+ }
129
+
130
+ /** A page's comments, as the extension last sent them. */
131
+ export async function readComments(doc) {
132
+ return readFile(join(folderOf(doc), "comments.md"), "utf8");
133
+ }
134
+
135
+ /** Adds an agent's reply to a thread; the extension puts it in the thread the next time it looks. */
136
+ export async function reply({ doc, thread, agent, text }) {
137
+ if (!thread || !text?.trim()) throw new Error("a reply needs --thread <id> and the words");
138
+ const list = await replies(doc);
139
+ const id = `${Date.now().toString(36)}-${list.length}`;
140
+ list.push({ id, thread, agent: agent || "Agent", text: text.trim(), at: Date.now() });
141
+ await mkdir(folderOf(doc), { recursive: true });
142
+ await writeFile(join(folderOf(doc), "replies.json"), JSON.stringify(list, null, 2) + "\n");
143
+ return id;
144
+ }
package/cli/pipeup.mjs CHANGED
@@ -9,6 +9,7 @@ import { check, table } from "./check.mjs";
9
9
  import { apply, htmlAttr, init, InitError, survey } from "./init.mjs";
10
10
  import { read, ReadError } from "./read.mjs";
11
11
  import { comments, watch } from "./link.mjs";
12
+ import * as browser from "./browser.mjs";
12
13
  import * as skills from "./skills.mjs";
13
14
 
14
15
  // The page library, loaded only by the commands that sign or read a page: `skills` and `comments` need nothing built.
@@ -66,10 +67,22 @@ pipeup reply --print (--doc <document id> | --page <file.html>) --thread <id> "<
66
67
  Prints the same signed reply as a replies block for the person to paste into the page (Paste my agent's replies),
67
68
  for an agent that can't write next to the page. Copy for my agent gives the document id. Nothing is written.
68
69
 
69
- Agents run these as \`npx --yes pipeup@0 …\`: any release from 0.6 answers agent, reply and comments the same way.`;
70
+ pipeup browser install --extension-id <id> [--browser chrome|edge|chromium|brave]
71
+ pipeup browser install --browser firefox
72
+ Lets the Pipeup browser extension send comments to agents on this computer (macOS and Linux). Run it once; in Chrome
73
+ and its kin the id is on Pipeup's card in chrome://extensions; Firefox needs none.
74
+
75
+ pipeup browser [read <page>]
76
+ Lists the pages whose comments were sent from the browser (Send to my agent), newest first; read prints one page's
77
+ comments as Markdown (<page> is part of its address, title or document id; the newest when left out).
78
+
79
+ pipeup browser reply <page> --thread <id> [--agent <name>] "<words>"
80
+ Answers a thread on a page sent from the browser; the extension puts the reply in the thread.
81
+
82
+ Agents run these as \`npx --yes pipeup@1 …\`: any 1.x release answers agent, reply and comments the same way.`;
70
83
 
71
84
  /** How agents are told to run this command line: never stopping to ask, and any release npm will give. */
72
- const RUN = "npx --yes pipeup@0";
85
+ const RUN = "npx --yes pipeup@1";
73
86
  /** A path as the person typed it, or relative to where they are. */
74
87
  const shown = (file) => relative(process.cwd(), resolve(file)) || file;
75
88
  const DOC = /<html\b[^>]*\sdata-pipeup-doc\s*=\s*["']([^"']+)["']/i;
@@ -466,6 +479,45 @@ else if (command === "skills") {
466
479
  const stop = () => link.close().then(() => process.exit(0));
467
480
  process.on("SIGINT", stop);
468
481
  process.on("SIGTERM", stop);
482
+ } else if (command === "browser") {
483
+ const [sub, which] = args._;
484
+ try {
485
+ if (sub === "install") {
486
+ const { file } = await browser.install({
487
+ extensionId: typeof args["extension-id"] === "string" ? args["extension-id"] : "",
488
+ browser: typeof args.browser === "string" ? args.browser : "chrome",
489
+ });
490
+ console.log(
491
+ `Done: the extension can now send comments here (${file}). Reload the extension to use it.`,
492
+ );
493
+ } else if (sub === "read") {
494
+ const page = await browser.find(which);
495
+ if (!page) fail("no page has been sent from the browser yet: press Send to my agent in Pipeup's menu");
496
+ console.log(await browser.readComments(page.doc));
497
+ } else if (sub === "reply") {
498
+ const page = await browser.find(which);
499
+ if (!page) fail("no page with that address, title or id has been sent from the browser");
500
+ const text = args._.slice(2).join(" ");
501
+ await browser.reply({
502
+ doc: page.doc,
503
+ thread: typeof args.thread === "string" ? args.thread : "",
504
+ agent: typeof args.agent === "string" ? args.agent : AI,
505
+ text,
506
+ });
507
+ console.log(
508
+ `Reply kept for "${page.title || page.url}"; it shows in the thread when the page is next open.`,
509
+ );
510
+ } else {
511
+ const all = await browser.pages();
512
+ if (!all.length) console.log("No pages sent from the browser yet.");
513
+ for (const p of all)
514
+ console.log(
515
+ `${new Date(p.at).toISOString().slice(0, 16).replace("T", " ")} ${p.title || ""} ${p.url}`,
516
+ );
517
+ }
518
+ } catch (e) {
519
+ fail(e.message);
520
+ }
469
521
  } else {
470
522
  console.log(USAGE);
471
523
  process.exit(command ? 1 : 0);
package/cli/read.mjs CHANGED
@@ -53,7 +53,7 @@ async function filesIn(dir, deep) {
53
53
 
54
54
  /**
55
55
  * The share add-on's headless reader, if it is installed: beside this package, or in the project the command runs in
56
- * (as with `npx --yes pipeup@0 read` in a folder where `@pipeup/share` is installed). It is never a dependency of `pipeup`.
56
+ * (as with `npx --yes pipeup@1 read` in a folder where `@pipeup/share` is installed). It is never a dependency of `pipeup`.
57
57
  */
58
58
  async function shareReader() {
59
59
  try {
package/dist/addons.json CHANGED
@@ -1,31 +1,31 @@
1
1
  {
2
2
  "share": {
3
- "integrity": "sha384-Iv18knaI4OXVXr5FnKqan6+Voq4wXHJQEVVqjw8X8yGjnnQmIJDq5Le8SGkaAT22",
3
+ "integrity": "sha384-w4RYzEq5wRn8eDBAX921njKaVpWBX7kR7X9E1G0qQVt14N7JN9xCGx+goBw9o6Kz",
4
4
  "says": "Sends the comments you choose to share, sealed so only people with this page can read them, to the sharing service the page names. That service sees when and how much is sent, and your network address."
5
5
  },
6
6
  "voice": {
7
- "integrity": "sha384-Y7tU5injzCcaZRunW+X89e83ZZP0GndlNqBX2n0x4psJYYEHK+1m/uCbmUyxGWAV",
7
+ "integrity": "sha384-gOs/8ApOEJZ9xo5pku1gxug3iQ5C2BUDM2eYArjjqU4pNNKfW86u4ly0l4v3J82r",
8
8
  "says": "Only when you press the microphone: your browser may download a speech pack once, and, only if it can't work on this device, your voice goes to the browser maker's speech service."
9
9
  },
10
10
  "live": {
11
- "integrity": "sha384-S6BH6HAroTc5spdAhf/sKucop6NwJrFgcr3A68t0kJDRPks0oM38FAMDtFYpIqGy",
11
+ "integrity": "sha384-utHEBGBribe/S/s/CKS1jYc7PA1JPyGIcJjOMaI4Ebk3qtuREwV5aGGZOFZTGNlO",
12
12
  "says": "When you go live, you connect directly to other people viewing this page. They see your network address; the meeting-point services see your network address and when you connect, never your comments."
13
13
  },
14
14
  "assist": {
15
- "integrity": "sha384-Tn760J2DRZcf/t4Wh4uCqOzPDj/UOj4e9j+2O0ipyNPCXSAYcyryEsul26/uMPMK",
15
+ "integrity": "sha384-uErGyE6xJUAMUFaiIBXVnb1w60kuQkNA60ewOxSMwo571U7OoxqY3F6m3EO7gmwh",
16
16
  "says": "Only after you turn it on: your browser may download a small AI model once. Comments and the page are read on this device and never sent anywhere; if the page's author named notes files, they are read from this site."
17
17
  },
18
18
  "agents": {
19
- "integrity": "sha384-XGyYk3WwvxcaMOk/vL/SRy1It8qQROWbKDFaBiB/zppZNkFskQ41lcFGjkZW2PkW",
19
+ "integrity": "sha384-qPyenmXi+daHEYBvdxD8daUnzVVidLWKzvK8v7pxkv4SdJC5XYf2c12m6KRuqYcC",
20
20
  "says": "Reads a replies file next to this page, and replies you paste from your agent. When the page is shown through pipeup watch, and only after you switch it on, it sends this page's comments to the program running on this computer. Nothing leaves this computer."
21
21
  },
22
22
  "emoji": {
23
- "integrity": "sha384-PabpVVan4/2cFL2D1kKYLRUVAsFtx/I8dCXsmDZHHb3AWgaFyZ8CEGST3n1+YBB4",
23
+ "integrity": "sha384-kxynJAvc6pIXLeGULqM1QlscllYFQe5pUR7guCwJFXHjSRANazDissD8eiJ0PQei",
24
24
  "says": "Nothing is sent anywhere: the emoji are part of this script."
25
25
  },
26
26
  "github": {
27
- "integrity": "sha384-juzqkImsqHDSsplZ/LXAJdXNaiOBVC2p1bbtlmmQiAEcewiDwmfyHEzTmXLZFS/Q",
28
- "says": "Only when you press Mention on GitHub: your browser opens GitHub's new-issue page with the person's @name and the comment's words filled in; nothing is sent until you submit it there.",
27
+ "integrity": "sha384-1ya3Hiu034B+ovYc4Fmr965dYJDeHdN9Pc3yA7qmHKLtK5ZU0j9vrRJmLI42sIdf",
28
+ "says": "Only when you press Mention on GitHub: your browser opens GitHub's new-issue page with the person's @name, your name, the comment's words and this page's title and address filled in, so GitHub receives them as the page opens; nothing is filed until you submit it there.",
29
29
  "asks": {
30
30
  "attr": "data-pipeup-github-repo",
31
31
  "flag": "github-repo",
@@ -34,11 +34,11 @@
34
34
  }
35
35
  },
36
36
  "updates": {
37
- "integrity": "sha384-Ywds4XdYUEguFHXGNbwsHUcTQetCnD8wh4N8VkqMgrG2s0ap6L7hnBBMeIjLiioX",
37
+ "integrity": "sha384-ZjxhI+0agw31MWfQqwTIyIOX/+NR+VEkdDpyzZW15Mu6w7XCh2pv/MpBJHiMGM/9",
38
38
  "says": "Checks the Pipeup project's published update list (GitHub Pages) once a day, only on this computer or where the page's author asked; that service can see your network address."
39
39
  },
40
40
  "inbox": {
41
- "integrity": "sha384-Z490DtLPVSgn0+BOMNSRocB2BVVtA8CAQtyeAAipcftU/+0+4b21zWYLvbPaOXQH",
41
+ "integrity": "sha384-ofJo54CchllZPT8dAHOmJ4GTmUNYNNUgscQqOUfTG9ag1MhLlwxkOkQUKlsxGuoe",
42
42
  "says": "Only after you switch on Mentions by inbox: when you mention someone, a short note (who, your words, the page's address) is left for them at the page's inbox service, sealed so only they can read it; and your own inbox is checked there. The service sees that a note arrived, its size and when, and your network address, never who it is from or what it says.",
43
43
  "asks": {
44
44
  "attr": "data-pipeup-inbox",
@@ -48,11 +48,11 @@
48
48
  }
49
49
  },
50
50
  "identity": {
51
- "integrity": "sha384-Ay3J1FiQokTyK73407sJALq0VMWUjn5iiF+miAA0/HfE4N16wPM59056fbabU+O0",
51
+ "integrity": "sha384-x/uWzQfOpExQ6nvR9e92j0ZvesjYqo/YKfOeF8u5reRSJmMRkbIHFgbitDRV2ka7",
52
52
  "says": "Nothing. Your recovery code stays on this device unless you copy it or save it as a file yourself."
53
53
  },
54
54
  "inline": {
55
- "integrity": "sha384-sXx+qQEDv7O5iqSjd7MFdQqK4pDO4PWJkoAOkmu6QmpFpALpp5c5/mHqA15rgRc2",
55
+ "integrity": "sha384-PDr1VOWqQ32NPlqk7mUfLO0uY77SRA4/KwFOzkU+n/ULMRfikon4fjd1cN2c0Dj2",
56
56
  "says": "Sends nothing: answers to asks are ordinary comments, kept and sent the way the page's other comments are."
57
57
  }
58
58
  }
@@ -1,7 +1,7 @@
1
1
  "use strict";(()=>{function x(e){let t=globalThis;(t.pipeupAddons||=[]).push(e),typeof addEventListener=="function"&&addEventListener("load",()=>{t.Pipeup||console.error(`pipeup: the "${e.id}" add-on needs Pipeup on the page too; load pipeup.min.js.`)},{once:!0})}var w=(e,t)=>t?t.getAttribute(e):globalThis.Pipeup?.setting?.(e)??globalThis.document?.documentElement.getAttribute(e)??null;var Ie=2n**256n-2n**32n-977n;var X=/^\/__pipeup\/[A-Za-z0-9_-]{16,}$/;function I(e){let t=document.documentElement,s=t.getAttribute("data-pipeup-link")??"",r=X.test(s),n=!1,i=0,p=()=>{};async function c(){let l=!1;try{l=(await fetch(`${s}/comments`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(await e.snapshot())})).ok}catch{}if(!l)throw new Error("pipeup: the link to your agent isn't reachable; your comments are safe here")}let a=()=>{window.clearTimeout(i),p(),p=()=>{},n=!1};return{enabled:r,agent:t.getAttribute("data-pipeup-link-agent")??"",file:t.getAttribute("data-pipeup-link-file")??"",on:()=>n,set:async l=>{if(r){if(!l){a(),e.refresh();return}await c(),n=!0,p=e.changes(()=>{window.clearTimeout(i),i=window.setTimeout(()=>{c().catch(o=>{a(),e.refresh(),globalThis.reportError?.(o)})},300)}),e.refresh()}},destroy:a}}var Q=/```[ \t]*pipeup-replies[^\n]*\n([\s\S]*?)(?:\n[ \t]*```|$)/g,ee=/^[ \t]*(agent|thread|reply|addressed|signed)[ \t]*:[ \t]?(.*)$/i,L="Agent";function M(e){let t=[];for(let[,s]of e.replace(/\r\n?/g,`
2
2
  `).matchAll(Q)){let r=L,n=null,i=null;for(let p of s.split(`
3
3
  `)){let c=ee.exec(p);if(c){let a=c[1].toLowerCase(),l=c[2].trim();a==="agent"?(r=l||L,i=null):a==="thread"?(n={agent:r,thread:l,reply:"",addressed:"",signed:""},t.push(n),i=null):n&&(n[a]=l,i=a)}else n&&i&&i!=="signed"&&p.trim()?n[i]=`${n[i]}
4
- ${p.trim()}`:n&&i==="signed"&&(n.signed+=p.trim())}}return t.filter(s=>s.thread&&s.reply)}var O=(e,t)=>e.replace(/\s+/g," ").trim()===t.replace(/\s+/g," ").trim();function te(e){try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=Uint8Array.from(atob(t+"=".repeat((4-t.length%4)%4)),r=>r.charCodeAt(0));return JSON.parse(new TextDecoder().decode(s))}catch{return null}}async function D(e,t){let s=new Set(t.threads.map(n=>n.id)),r=[];for(let n of e){if(!s.has(n.thread)){r.push({kind:"gone",entry:n});continue}if(!n.signed){r.push({kind:"unsigned",entry:n,why:"none"});continue}let i=te(n.signed),p=Array.isArray(i)?i:[],c=p.find(d=>d?.body?.kind==="reply"),a=p.find(d=>d?.body?.kind==="addressed"),l=c?.body.author??"";!!c&&p.length===(a?2:1)&&p.every(d=>d.body.doc===t.doc&&d.body.thread===n.thread&&d.body.author===l)&&O(c.body.text??"",n.reply)&&(a?O(a.body.text??"",n.addressed):!n.addressed)&&(await Promise.all(p.map(t.check))).every(Boolean)?t.listed.includes(l)?r.push({kind:"signed",entry:n,ops:p,author:l}):r.push({kind:"unsigned",entry:n,why:"unlisted"}):r.push({kind:"unsigned",entry:n,why:"changed"})}return r}var $=(e,t,s)=>`${e} ${e===1?t:s}`,C=e=>{let t=[...new Set(e)];return t.length<=1?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`};function R(e){let t=e.filter(a=>a.kind==="signed"),s=e.filter(a=>a.kind==="unsigned"),r=e.filter(a=>a.kind==="gone"),n=t.length+s.length,i=[];t.length&&i.push(`${$(t.length,"reply","replies")} signed by ${C(t.map(a=>a.entry.agent))}, whom this page lists`);let p=(a,l)=>a==="none"?`${l?"is":"are"} not signed`:a==="unlisted"?`${l?"is":"are"} signed with a key this page doesn't list`:l?"was changed after it was signed":"were changed after they were signed";for(let a of["none","changed","unlisted"]){let l=s.filter(f=>f.why===a);if(!l.length)continue;let o=C(l.map(f=>f.entry.agent)),d=l.length===1;i.push(`${$(l.length,"reply","replies")} from ${o} ${p(a,d)}, so ${d?"it":"they"} will show as pasted by you`)}let c=[...t,...s].filter(a=>a.entry.addressed).length;return c&&i.push(`${c} of them ${c===1?"says":"say"} the comment is addressed`),r.length&&i.push(`${$(r.length,"reply is","replies are")} for a comment that's no longer here, so ${r.length===1?"it":"they"} will be left out`),{lines:i,adds:n}}function ne(e){if(!e)return{cli:"npx --yes pipeup@0",fallback:null};let s=`npx --yes pipeup@${e.split(".")[0]??"0"}`;return e.includes("-")?{cli:`npx --yes pipeup@${e}`,fallback:s}:{cli:s,fallback:null}}function re(e,t=""){if(t)return{page:t,served:!1};try{let s=new URL(e),r=decodeURIComponent(s.pathname);return r.endsWith("/")&&(r+="index.html"),s.protocol==="file:"?{page:/^\/[A-Za-z]:\//.test(r)?r.slice(1):r,served:!1}:{page:r,served:!0}}catch{return{page:"<the page's HTML file>",served:!1}}}var oe=e=>{try{let t=new URL(e);return t.protocol==="file:"?decodeURIComponent(t.pathname).replace(/^\/([A-Za-z]:\/)/,"$1"):t.href}catch{return e}},T=e=>e.replace(/\s+/g," ").trim();function _(e){let{cli:t,fallback:s}=ne(e.version),r=`https://pipeup-ai.github.io/pipeup/${e.version?.includes("-")?"next/":""}`,{page:n,served:i}=re(e.url,e.file),p=i?`<the HTML file your site serves at ${n}>`:n,c=`\`${t} reply --print --doc ${e.doc} --thread <thread id> "what you changed and where" --addressed "short note"\``;return[`Please act on my review comments on ${T(e.title)} (${T(e.url)}). The page uses Pipeup.`,"The comments were left in my browser. They are not in the page's file, so don't look for them there. Everything you need is below.","",`## ${e.open} open comment${e.open===1?"":"s"}${e.edition?` on the ${e.edition} edition`:""}`,"",e.comments.trim(),...e.resolved||e.earlier?["",`(${[e.resolved?`${e.resolved} resolved comment${e.resolved===1?"":"s"}`:"",e.earlier?`${e.earlier} open comment${e.earlier===1?"":"s"} on earlier editions`:""].filter(Boolean).join(" and ")} left out.)`]:[],"","## How to answer","","- For each thread, make the change I approved, or say why you didn't. Answer a question with an answer. Ask me before changing anything I haven't approved.","- Reply in one block I can paste back into the page with Paste my agent's replies, and tell me what you changed and where. Don't say the page was updated unless you updated it.","","```pipeup-replies","agent: <your name>","thread: <thread id>","reply: what you changed and where","addressed: short note, only if you made the change","```","",e.listed?`- This page lists an agent's key. If it's yours, sign the block so it shows as yours, not as pasted by me: ${c} prints each reply signed with the key you keep (in ~/.pipeup/agent.json). Without your key, send the same block unsigned.`:`- If you keep a Pipeup key between sessions, sign the block with ${c}, and ask me whether to list you on the page (\`${t} agent\` prints the line to add). If you can't keep a key, don't ask to be listed: the plain block works.`,...e.file?[`- You're on this computer, with a live link running: \`${t} comments ${e.file}\` reads the comments and \`${t} reply --page ${p} --thread <thread id> "\u2026" --addressed "\u2026"\` answers in the page by itself.`]:e.replies?[`- If you can write next to the page on this computer, \`${t} reply --page ${p} --thread <thread id> "\u2026" --addressed "\u2026"\` writes ${T(oe(e.replies))}, and your replies appear by themselves. Pass the HTML file that runs Pipeup, not a file it shows.`]:[],...(e.file||e.replies)&&!e.listed?[`- The page doesn't list you yet. Ask me first; after my yes, run \`${t} agent --name <your name> --page ${p} --yes\`.`]:[],...s?[`- If npm refuses ${t.split(" ").at(-1)}, use ${s.split(" ").at(-1)}: it answers these commands the same way.`]:[],"- Only mark a thread addressed. Never resolve, reopen, edit or delete: I close threads. Never answer as me, and keep your key out of the page and its folder.","",`Guide: ${r}skills/pipeup-apply/SKILL.md`].join(`
4
+ ${p.trim()}`:n&&i==="signed"&&(n.signed+=p.trim())}}return t.filter(s=>s.thread&&s.reply)}var O=(e,t)=>e.replace(/\s+/g," ").trim()===t.replace(/\s+/g," ").trim();function te(e){try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=Uint8Array.from(atob(t+"=".repeat((4-t.length%4)%4)),r=>r.charCodeAt(0));return JSON.parse(new TextDecoder().decode(s))}catch{return null}}async function D(e,t){let s=new Set(t.threads.map(n=>n.id)),r=[];for(let n of e){if(!s.has(n.thread)){r.push({kind:"gone",entry:n});continue}if(!n.signed){r.push({kind:"unsigned",entry:n,why:"none"});continue}let i=te(n.signed),p=Array.isArray(i)?i:[],c=p.find(d=>d?.body?.kind==="reply"),a=p.find(d=>d?.body?.kind==="addressed"),l=c?.body.author??"";!!c&&p.length===(a?2:1)&&p.every(d=>d.body.doc===t.doc&&d.body.thread===n.thread&&d.body.author===l)&&O(c.body.text??"",n.reply)&&(a?O(a.body.text??"",n.addressed):!n.addressed)&&(await Promise.all(p.map(t.check))).every(Boolean)?t.listed.includes(l)?r.push({kind:"signed",entry:n,ops:p,author:l}):r.push({kind:"unsigned",entry:n,why:"unlisted"}):r.push({kind:"unsigned",entry:n,why:"changed"})}return r}var $=(e,t,s)=>`${e} ${e===1?t:s}`,C=e=>{let t=[...new Set(e)];return t.length<=1?t[0]??"":`${t.slice(0,-1).join(", ")} and ${t.at(-1)}`};function R(e){let t=e.filter(a=>a.kind==="signed"),s=e.filter(a=>a.kind==="unsigned"),r=e.filter(a=>a.kind==="gone"),n=t.length+s.length,i=[];t.length&&i.push(`${$(t.length,"reply","replies")} signed by ${C(t.map(a=>a.entry.agent))}, whom this page lists`);let p=(a,l)=>a==="none"?`${l?"is":"are"} not signed`:a==="unlisted"?`${l?"is":"are"} signed with a key this page doesn't list`:l?"was changed after it was signed":"were changed after they were signed";for(let a of["none","changed","unlisted"]){let l=s.filter(f=>f.why===a);if(!l.length)continue;let o=C(l.map(f=>f.entry.agent)),d=l.length===1;i.push(`${$(l.length,"reply","replies")} from ${o} ${p(a,d)}, so ${d?"it":"they"} will show as pasted by you`)}let c=[...t,...s].filter(a=>a.entry.addressed).length;return c&&i.push(`${c} of them ${c===1?"says":"say"} the comment is addressed`),r.length&&i.push(`${$(r.length,"reply is","replies are")} for a comment that's no longer here, so ${r.length===1?"it":"they"} will be left out`),{lines:i,adds:n}}function ne(e){if(!e)return{cli:"npx --yes pipeup@1",fallback:null};let s=`npx --yes pipeup@${e.split(".")[0]??"0"}`;return e.includes("-")?{cli:`npx --yes pipeup@${e}`,fallback:s}:{cli:s,fallback:null}}function re(e,t=""){if(t)return{page:t,served:!1};try{let s=new URL(e),r=decodeURIComponent(s.pathname);return r.endsWith("/")&&(r+="index.html"),s.protocol==="file:"?{page:/^\/[A-Za-z]:\//.test(r)?r.slice(1):r,served:!1}:{page:r,served:!0}}catch{return{page:"<the page's HTML file>",served:!1}}}var oe=e=>{try{let t=new URL(e);return t.protocol==="file:"?decodeURIComponent(t.pathname).replace(/^\/([A-Za-z]:\/)/,"$1"):t.href}catch{return e}},T=e=>e.replace(/\s+/g," ").trim();function _(e){let{cli:t,fallback:s}=ne(e.version),r=`https://pipeup-ai.github.io/pipeup/${e.version?.includes("-")?"next/":""}`,{page:n,served:i}=re(e.url,e.file),p=i?`<the HTML file your site serves at ${n}>`:n,c=`\`${t} reply --print --doc ${e.doc} --thread <thread id> "what you changed and where" --addressed "short note"\``;return[`Please act on my review comments on ${T(e.title)} (${T(e.url)}). The page uses Pipeup.`,"The comments were left in my browser. They are not in the page's file, so don't look for them there. Everything you need is below.","",`## ${e.open} open comment${e.open===1?"":"s"}${e.edition?` on the ${e.edition} edition`:""}`,"",e.comments.trim(),...e.resolved||e.earlier?["",`(${[e.resolved?`${e.resolved} resolved comment${e.resolved===1?"":"s"}`:"",e.earlier?`${e.earlier} open comment${e.earlier===1?"":"s"} on earlier editions`:""].filter(Boolean).join(" and ")} left out.)`]:[],"","## How to answer","","- For each thread, make the change I approved, or say why you didn't. Answer a question with an answer. Ask me before changing anything I haven't approved.","- Reply in one block I can paste back into the page with Paste my agent's replies, and tell me what you changed and where. Don't say the page was updated unless you updated it.","","```pipeup-replies","agent: <your name>","thread: <thread id>","reply: what you changed and where","addressed: short note, only if you made the change","```","",e.listed?`- This page lists an agent's key. If it's yours, sign the block so it shows as yours, not as pasted by me: ${c} prints each reply signed with the key you keep (in ~/.pipeup/agent.json). Without your key, send the same block unsigned.`:`- If you keep a Pipeup key between sessions, sign the block with ${c}, and ask me whether to list you on the page (\`${t} agent\` prints the line to add). If you can't keep a key, don't ask to be listed: the plain block works.`,...e.file?[`- You're on this computer, with a live link running: \`${t} comments ${e.file}\` reads the comments and \`${t} reply --page ${p} --thread <thread id> "\u2026" --addressed "\u2026"\` answers in the page by itself.`]:e.replies?[`- If you can write next to the page on this computer, \`${t} reply --page ${p} --thread <thread id> "\u2026" --addressed "\u2026"\` writes ${T(oe(e.replies))}, and your replies appear by themselves. Pass the HTML file that runs Pipeup, not a file it shows.`]:[],...(e.file||e.replies)&&!e.listed?[`- The page doesn't list you yet. Ask me first; after my yes, run \`${t} agent --name <your name> --page ${p} --yes\`.`]:[],...s?[`- If npm refuses ${t.split(" ").at(-1)}, use ${s.split(" ").at(-1)}: it answers these commands the same way.`]:[],"- Only mark a thread addressed. Never resolve, reopen, edit or delete: I close threads. Never answer as me, and keep your key out of the page and its folder.","",`Guide: ${r}skills/pipeup-apply/SKILL.md`].join(`
5
5
  `)}var H=()=>["Please send your replies again in one block I can paste into the page, like this:","","```pipeup-replies","agent: <your name>","thread: <thread id>","reply: what you changed and where","addressed: short note, only if you made the change","```"].join(`
6
6
  `);var se=/^[A-Za-z0-9_-]{43}$/,ie="pipeupReplies",ae=4e3,de=4e3,pe=/^AI assistant\s*·?\s*/;function k(e){let t=w("data-pipeup-agents",e)??"";return[...new Set(t.split(/[\s,]+/).filter(s=>se.test(s)))]}function E(e=location,t){let s=w("data-pipeup-replies",t);try{let r=e.href.split(/[?#]/)[0],n=new URL(s??(/\/$/.test(r)?`${r}index.replies.js`:r.replace(/\.[^./]*$/,"")+".replies.js"),e.href),i=n.protocol==="file:"?e.protocol==="file:":n.origin===e.origin;return i||console.warn("pipeup: the replies file must be on this site or this computer; ignoring it"),i?n.href:null}catch{return null}}function N(e){let t=k(),s=0,r="",n=null;async function i(){let d=globalThis[ie];if(!Array.isArray(d))return 0;let f=d.splice(0),h=[];for(let u of f){let y=u;if(!(y?.format!=="pipeup-replies"||y.doc!==e.document.id||!Array.isArray(y.ops)))for(let g of y.ops){let m=g?.body;m&&t.includes(m.author)&&(m.kind==="reply"||m.kind==="addressed"||m.kind==="react"||m.kind==="unreact")?(h.push(g),(m.name==="AI assistant"||m.name.startsWith("AI assistant "))&&(r=m.name.replace(pe,""))):s++}}return h.length?e.merge(h):0}function p(){let d=E();return d?(n?.remove(),new Promise((f,h)=>{let u=document.createElement("script");n=u,u.src=`${d}?${Date.now()}`;let y=m=>{window.clearTimeout(g),u.remove(),n===u&&(n=null),m?h(new Error(`pipeup: ${m}`)):f()},g=window.setTimeout(()=>y("the replies file didn't answer"),ae);u.addEventListener("load",()=>y()),u.addEventListener("error",()=>y("there is no replies file yet")),e.overlay().append(u)})):Promise.reject(new Error("pipeup: the replies file can't be read from here"))}async function c(){if(!t.length)return 0;let d=await i();return await p(),d+await i()}let a=!1,l=()=>{a||document.hidden||(a=!0,c().catch(()=>{}).finally(()=>a=!1))},o=0;return t.length?(l(),o=window.setInterval(l,de),document.addEventListener("visibilitychange",l)):i(),{enabled:t.length>0,ignored:()=>s,who:()=>r,check:c,tally:d=>{let f=d.filter(g=>!g.resolved),h=g=>g.root.replies.some(m=>t.includes(m.author)||m.name.startsWith("AI assistant \xB7 ")),u=new Set(d.map(g=>g.id));return{stray:new Set(e.document.ops().filter(g=>t.includes(g.body.author)&&!u.has(g.body.thread)).map(g=>g.body.thread)).size,open:f.length,answered:f.filter(h).length,addressed:f.filter(g=>g.addressed).length}},destroy:()=>{window.clearInterval(o),document.removeEventListener("visibilitychange",l),n?.remove()}}}var z=`.ag-t{margin:0 0 8px;font-size:15px;font-weight:600}
7
7
  .ag-f{display:block;width:100%;height:96px;margin:4px 0 8px;padding:8px;border:1px solid var(--ln);border-radius:8px;background:var(--so);color:var(--k);font:12px/1.5 ui-monospace,monospace;resize:vertical}
@@ -1 +1 @@
1
- function e(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function t(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r}function r(e){return(new TextEncoder).encode(e)}function n(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(n).join(",")+"]";let t=e;return"{"+Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>JSON.stringify(e)+":"+n(t[e])).join(",")+"}"}function i(e){return e.replace(/\s+/g," ").trim()}function a(e){let t=i(e),r=2166136261;for(let e=0;e<t.length;e++)r^=t.charCodeAt(e),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}var o=/^[A-Za-z0-9_-]{43}$/,s=new Map;async function d(){let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]);return{publicKey:e(new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey))),privateKey:t.privateKey}}async function l(t,r){let n=await crypto.subtle.sign({name:"Ed25519"},t.privateKey,r);return e(new Uint8Array(n))}var u=["Otter","Fox","Owl","Bear","Rabbit"],c=["Red","Orange","Yellow","Green","Teal","Blue","Purple","Pink","Brown","Grey"];function h(e){let t=2166136261;for(let r=0;r<e.length;r++)t=Math.imul(t^e.charCodeAt(r),16777619);return t=Math.imul(t^t>>>16,2246822507),t=Math.imul(t^t>>>13,3266489909),(t^t>>>16)>>>0}var p=e=>`${c[(e=>Math.floor(h(e)/u.length)%c.length)(e)]} ${u[(e=>h(e)%u.length)(e)]}`,f=e=>{let t=e.name.replace(/^AI assistant \xb7 /,"")||p(e.author);return e.alike?`${t} \xb7 ${function(e){let t=h(`id:${e}`),r="";for(let e=0;e<4;e++,t>>>=5)r+="0123456789ABCDEFGHJKMNPQRSTVWXYZ"[31&t];return r}(e.author)}`:t},m="AI assistant",g=e=>e===m||e.startsWith(`${m} `),y=e=>`${m} \xb7 ${e.replace(/\s+/g," ").trim()||"Agent"}`.slice(0,80).trim(),w=(e,t)=>e.name.startsWith(`${m} \xb7 `)&&!t.includes(e.author),b=1e4,x=2**40,v=2**47,k=1e4,A=/^[0-9a-f]{8}$/,E=/^[A-Za-z0-9_-]{43}$/,$=/^(?:[^\s@<>"]{1,64}@[^\s@<>"]{1,190}\.[^\s@<>"]{2,24}|gh:[A-Za-z0-9-]{1,39})$/,S=/^(?:[A-Za-z0-9_-]{43}|(?:host|gh):[A-Za-z0-9._@-]{1,64})$/,M=/^[A-Za-z0-9_-]{43}$/,C=new Set(["create","reply","edit","delete","resolve","reopen","addressed","react","unreact","seen","contact","uncontact"]),N=/^(?:\p{Regional_Indicator}{2}|[#*0-9]\uFE0F?\u20E3|\p{Extended_Pictographic}(?:\uFE0F|\p{Emoji_Modifier})?(?:\u200D\p{Extended_Pictographic}(?:\uFE0F|\p{Emoji_Modifier})?)*)$/u,O=e=>"string"==typeof e&&N.test(e)&&[...e].length<=16;async function q(e,t){if(e.author!==t.publicKey)throw new Error("pipeup: an op must be signed by its author");return{body:e,sig:await l(t,r(n(e)))}}var j=(e,t)=>"string"==typeof e&&e.length<=t,P=e=>!!e&&"object"==typeof e,T=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<=1;function I(e){if(!P(e))return!1;let{id:t,path:r,fingerprint:n,snapshot:i,quote:a,point:o,view:s}=e;if(!(j(r,2e3)&&j(i,500)&&"string"==typeof n&&A.test(n)&&(void 0===t||j(t,200)&&""!==t)&&(void 0===a||P(a)&&j(a.exact,k)&&""!==a.exact&&j(a.prefix,64)&&j(a.suffix,64))&&(void 0===o||P(o)&&T(o.x)&&T(o.y))))return!1;if(void 0!==s){if(!P(s)||Array.isArray(s))return!1;let e=Object.entries(s);if(e.length>16||!e.every(([e,t])=>e.length<=64&&j(t,200)))return!1}return!0}function F(e){if(!P(e))return!1;let{body:t,sig:r}=e;if("string"!=typeof r||!P(t)||JSON.stringify({body:t,sig:r}).length>262144)return!1;let n=t;if(1!==n.v||"string"!=typeof n.id||!E.test(n.id)||!C.has(n.kind)||!j(n.doc,64)||""===n.doc||"string"!=typeof n.thread||!E.test(n.thread)||"string"!=typeof n.author||!M.test(n.author)||"string"!=typeof n.name||n.name.length>80||n.name!==n.name.trim()||"number"!=typeof n.clock||!Number.isSafeInteger(n.clock)||n.clock<1||n.clock>x||"number"!=typeof n.at||!Number.isSafeInteger(n.at)||n.at<0||n.at>v||void 0!==n.text&&(!j(n.text,b)||n.text!==n.text.trim())||void 0!==n.target&&("string"!=typeof n.target||!E.test(n.target))||("create"===n.kind||"reply"===n.kind||"edit"===n.kind||"addressed"===n.kind)&&!n.text||("reply"===n.kind||"edit"===n.kind||"delete"===n.kind)&&!n.target)return!1;if(void 0!==n.mentions){if("create"!==n.kind&&"reply"!==n.kind&&"edit"!==n.kind||!Array.isArray(n.mentions)||n.mentions.length>20)return!1;let e=n.text?.length??0;for(let t of n.mentions){if(!P(t)||!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end))return!1;let{start:r,end:n,ref:i}=t;if(r<0||n<=r||n>e||"string"!=typeof i||!S.test(i))return!1}}return!(!("contact"!==n.kind||"string"==typeof n.text&&$.test(n.text))||"seen"===n.kind&&!n.target||!("react"!==n.kind&&"unreact"!==n.kind||n.target&&O(n.text))||!("create"!==n.kind||n.id===n.thread&&I(n.anchor)))}function L(i){return async function(r,n,i){if(!o.test(r))return!1;try{if(e(t(r))!==r)return!1;let a=s.get(r);if(!a){s.size>=512&&s.delete(s.keys().next().value),a=crypto.subtle.importKey("raw",t(r),{name:"Ed25519"},!0,["verify"]),s.set(r,a);let e=a;e.catch(()=>{s.get(r)===e&&s.delete(r)})}return await crypto.subtle.verify({name:"Ed25519"},await a,t(i),n)}catch{return!1}}(i.body.author,r(n(i.body)),i.sig)}async function R(e){return F(e)&&await L(e).catch(()=>!1)}function D(e,t){return e.body.clock!==t.body.clock?e.body.clock-t.body.clock:e.body.at!==t.body.at?e.body.at-t.body.at:e.body.author!==t.body.author?e.body.author<t.body.author?-1:1:e.body.id!==t.body.id?e.body.id<t.body.id?-1:1:0}function U(e,t,r,n,i,a){let o={id:e,author:t,name:r,text:n,at:i,edited:!1,deleted:!1,replies:[],reactions:[]};return a?.length&&(o.mentions=a),o}async function B(t){let i={...t,id:void 0,thread:"create"===t.kind?void 0:t.thread},a=await crypto.subtle.digest("SHA-256",r(n(i)));return e(new Uint8Array(a))}var _=class{constructor(e){this.doc=e}ops=new Map;clock=0;createAt=new Map;threadAt=new Map;get size(){return this.ops.size}all(){return[...this.ops.values()]}threads(){return function(e){let t=new Map,r=new Map,n=new Map;for(let{body:i}of[...e].sort(D)){if(i.name&&!g(i.name)&&n.set(i.author,i.name),"create"===i.kind){if(t.has(i.id)||!i.anchor||void 0===i.text)continue;let e=U(i.id,i.author,i.name,i.text,i.at,i.mentions);t.set(i.id,{id:i.id,anchor:i.anchor,root:e,resolved:!1}),r.set(i.id,{comment:e,thread:i.id});continue}let e=t.get(i.thread);if(!e)continue;if("resolve"===i.kind||"reopen"===i.kind){e.resolved="resolve"===i.kind,"reopen"===i.kind&&delete e.addressed;continue}if("addressed"===i.kind){void 0!==i.text&&(e.addressed={text:i.text,author:i.author,name:i.name,at:i.at});continue}let a=i.target?r.get(i.target):void 0;if(a&&a.thread===i.thread){if("reply"===i.kind){if(r.has(i.id)||void 0===i.text)continue;let t=U(i.id,i.author,i.name,i.text,i.at,i.mentions);e.root.replies.push(t),r.set(i.id,{comment:t,thread:i.thread});continue}if("seen"===i.kind){let e=a.comment.seenBy??=[];e.includes(i.author)||e.push(i.author);continue}if("react"===i.kind||"unreact"===i.kind){if(void 0===i.text||a.comment.deleted)continue;let e=a.comment.reactions,t=e.find(e=>e.emoji===i.text);if("react"===i.kind){let r={author:i.author,name:i.name};t?t.by.some(e=>e.author===i.author)||t.by.push(r):e.length<12&&e.push({emoji:i.text,by:[r]})}else t&&(t.by=t.by.filter(e=>e.author!==i.author),t.by.length||e.splice(e.indexOf(t),1));continue}i.author!==a.comment.author||a.comment.deleted||("edit"===i.kind&&void 0!==i.text&&(a.comment.text=i.text,a.comment.edited=!0,i.mentions?a.comment.mentions=i.mentions:delete a.comment.mentions),"delete"===i.kind&&(a.comment.text="",a.comment.deleted=!0,a.comment.reactions=[],delete a.comment.mentions))}}for(let{comment:e}of r.values()){e.name||(e.unnamed=!0,e.name=n.get(e.author)??"");for(let t of e.reactions)for(let e of t.by)e.name||=n.get(e.author)??""}let i=new Map,a=(e,t)=>{let r=f({author:e,name:t}).toLowerCase();(i.get(r)??i.set(r,new Set).get(r)).add(e)};for(let{comment:e}of r.values()){a(e.author,e.name);for(let t of e.reactions)for(let e of t.by)a(e.author,e.name)}let o=(e,t)=>!g(t)&&(i.get(f({author:e,name:t}).toLowerCase())?.size??0)>1;for(let{comment:e}of r.values()){o(e.author,e.name)&&(e.alike=!0);for(let t of e.reactions)for(let e of t.by)o(e.author,e.name)&&(e.alike=!0)}return[...t.values()]}(this.ops.values())}async add(e){let t=[];for(let r of e){if(!F(r)||r.body.doc!==this.doc||this.ops.has(r.body.id)||r.body.id!==await B(r.body)||!await L(r))continue;let e={body:r.body,sig:r.sig};this.ops.set(e.body.id,e),this.clock=Math.max(this.clock,e.body.clock),"create"===e.body.kind&&this.createAt.set(e.body.author,Math.max(this.createAt.get(e.body.author)??0,e.body.at)),this.threadAt.set(e.body.thread,Math.max(this.threadAt.get(e.body.thread)??0,e.body.at)),t.push(e)}return t}async append(e,t,r){let n={v:1,...r,id:"",thread:"create"===r.kind?"":r.thread,doc:this.doc,author:e.publicKey,name:t,clock:Math.min(this.clock+1,x),at:Math.min(Math.max(Date.now(),"create"===r.kind?(this.createAt.get(e.publicKey)??0)+1:(this.threadAt.get(r.thread)??0)+1),v)};n.id=await B(n);let i=this.ops.get(n.id);if(i)return i;"create"===n.kind&&(n.thread=n.id);let[a]=await this.add([await q(n,e)]);if(!a)throw new Error("pipeup: could not record this change");return a}},z=/^([A-Za-z0-9_-]{16}):([A-Za-z0-9_-]{43})$/;function H(){return`${function(t=16){return e(crypto.getRandomValues(new Uint8Array(t)))}(12)}:${e(crypto.getRandomValues(new Uint8Array(32)))}`}async function K(e){let r=z.exec(e.trim()),n=r?.[1],i=r?.[2];if(!n||!i)throw new Error('pipeup: data-pipeup-doc must look like "<id>:<key>", as made by newDocumentAttribute()');return{id:n,key:await crypto.subtle.importKey("raw",t(i),{name:"AES-GCM"},!1,["encrypt","decrypt"])}}async function G(t,n,i){let a=crypto.getRandomValues(new Uint8Array(12)),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,additionalData:r(i)},t,r(n));return{iv:e(a),data:e(new Uint8Array(o))}}var Z=e=>`pipeup-file:${e}`;async function J(e,n,i){if(e.length>5e6)throw new Error("pipeup: this feedback file is too large");let a,o,s;try{a=JSON.parse(e)}catch{throw new Error("pipeup: this is not an Pipeup feedback file")}if(!a||"object"!=typeof a||1!==a.pipeup||"string"!=typeof a.doc)throw new Error("pipeup: this is not an Pipeup feedback file");if(a.doc!==n)throw new Error("pipeup: this feedback is for a different document");if(!a.sealed)return Array.isArray(a.ops)?a.ops:[];if(!i)throw new Error("pipeup: this feedback is sealed, and this page has no document key");if("string"!=typeof a.iv||"string"!=typeof a.data)throw new Error("pipeup: this is not an Pipeup feedback file");try{o=await async function(e,n,i){try{let a=await crypto.subtle.decrypt({name:"AES-GCM",iv:t(n.iv),additionalData:r(i)},e,t(n.data));return(new TextDecoder).decode(a)}catch{throw new Error("pipeup: this feedback could not be opened with this document")}}(i,{iv:a.iv,data:a.data},Z(n))}catch{throw new Error("pipeup: this feedback could not be opened with this document's key")}try{s=JSON.parse(o)}catch{throw new Error("pipeup: this is not an Pipeup feedback file")}return Array.isArray(s)?s:[]}var V=/^[a-z][a-z0-9-]{1,23}\/[a-z][a-z0-9-]{0,31}$/,W=class extends Error{constructor(e,t,r=1){super("pipeup: shown here, but not saved yet"),this.id=e,this.cause=t,this.count=r,this.name="UnsavedChangeError"}},Q=class e{constructor(e,t){this.log=e,this.options=t,this.displayName=t.name.trim()?ee(t.name):""}listeners=new Set;cache=[];comments=new Map;displayName;e=Promise.resolve();unsaved=[];static async open(t){if("string"!=typeof t.doc||""===t.doc||t.doc.length>64)throw new Error("pipeup: the document id must be 1 to 64 characters");let r=new _(t.doc),n=await t.store.load(t.doc),i=n.length-(await r.add(n)).length;i&&console.warn(`pipeup: ${i} saved change${1===i?"":"s"} on this page couldn't be read; kept as saved`);let a=new e(r,t);return a.refresh(!1),a}get id(){return this.options.doc}get me(){return this.options.identity.publicKey}get name(){return this.displayName}set name(e){this.displayName=ee(e),this.refresh(!0,[],"")}threads(){return this.cache}ops(){return this.log.all()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}comment(e,t,r){return this.enqueue(()=>this.write({kind:"create",anchor:e,text:X(t),...r?.length?{mentions:r}:{}}))}reply(e,t,r){return this.enqueue(()=>this.write({kind:"reply",thread:this.find(e).thread,target:e,text:X(t),...r?.length?{mentions:r}:{}}))}edit(e,t,r){return this.enqueue(async()=>{let{thread:n}=this.mine(e);await this.write({kind:"edit",thread:n,target:e,text:X(t),...r?.length?{mentions:r}:{}})})}remove(e){return this.enqueue(async()=>{let{thread:t}=this.mine(e);await this.write({kind:"delete",thread:t,target:e})})}contact(e){let t=e.trim();return $.test(t)?this.enqueue(async()=>{await this.write({kind:"contact",thread:this.me,text:t})}):Promise.reject(new Error("pipeup: that isn't an email address or a GitHub name"))}uncontact(){return this.enqueue(async()=>{await this.write({kind:"uncontact",thread:this.me})})}contacts(){let e=new Map;for(let{body:t}of[...this.log.all()].sort(D))"contact"===t.kind&&t.text?e.set(t.author,t.text):"uncontact"===t.kind&&e.delete(t.author);return e}get portable(){return this.options.identity.privateKey.extractable}async seed(){let e=this.options.identity.privateKey;if(!e.extractable)return null;let{d:r}=await crypto.subtle.exportKey("jwk",e);return r?t(r):null}seen(e){return this.enqueue(async()=>{for(let t of e){let e=this.comments.get(t);e&&!e.comment.seenBy?.includes(this.me)&&await this.write({kind:"seen",thread:e.thread,target:t})}})}react(e,t){return this.enqueue(async()=>{await this.write({kind:"react",thread:this.find(e).thread,target:e,text:Y(t)})})}unreact(e,t){return this.enqueue(async()=>{await this.write({kind:"unreact",thread:this.find(e).thread,target:e,text:Y(t)})})}resolve(e){return this.enqueue(async()=>{await this.write({kind:"resolve",thread:this.thread(e)})})}reopen(e){return this.enqueue(async()=>{await this.write({kind:"reopen",thread:this.thread(e)})})}paste(e,t,r,n){return this.enqueue(async()=>{let i=this.thread(e),a=y(t),o=this.cache.find(e=>e.id===i).root.id;await this.write({kind:"reply",thread:i,target:o,text:X(r)},a),n?.trim()&&await this.write({kind:"addressed",thread:i,text:X(n)},a)})}sign(e,t){if(!V.test(e))throw new Error('pipeup: a signing purpose looks like "<add-on id>/<name>"');return l(this.options.identity,r(`pipeup:${e}\n${t}`))}flush(){return this.enqueue(()=>this.persist())}exportFile(){return async function(e,t,r){let n=r?{pipeup:1,doc:e,sealed:!0,...await G(r,JSON.stringify(t),Z(e))}:{pipeup:1,doc:e,sealed:!1,ops:t};return JSON.stringify(n,null,2)}(this.options.doc,this.log.all(),this.options.key)}async importFile(e){return this.merge(await J(e,this.options.doc,this.options.key),"file")}merge(e,t){return e.length>5e3?Promise.reject(new RangeError("pipeup: too many changes to merge at once")):this.enqueue(async()=>{let r=await this.log.add([...e]);this.unsaved.push(...r),r.length>0&&this.refresh(!0,r,t);try{await this.persist()}catch(e){throw r.length>0?new W(r[0].body.id,e,r.length):e}return r.length})}enqueue(e){let t=this.e.then(e);return this.e=t.catch(()=>{}),t}async write(e,t=this.displayName){let r=await this.log.append(this.options.identity,t,e);this.unsaved.push(r),this.refresh(!0,[r],"local");try{await this.persist()}catch(e){throw new W(r.body.id,e)}return r.body.id}async persist(){if(0===this.unsaved.length)return;let e=[...this.unsaved];await this.options.store.append(this.options.doc,e),this.unsaved=this.unsaved.filter(t=>!e.includes(t))}refresh(e,t=[],r=""){this.cache=this.log.threads(),this.comments.clear();let n=(e,t)=>{e.unnamed&&e.author===this.me&&this.displayName&&(e.name=this.displayName),this.comments.set(e.id,{comment:e,thread:t});for(let r of e.replies)n(r,t)};for(let e of this.cache)n(e.root,e.id);if(e)for(let e of this.listeners)try{e(this.cache,t,r)}catch(e){globalThis.reportError?.(e)}}find(e){let t=this.comments.get(e);if(!t)throw new Error("pipeup: there is no comment with that id");return t}mine(e){let t=this.find(e);if(t.comment.author!==this.me)throw new Error("pipeup: only the writer can change a comment");return t}thread(e){if(!this.cache.some(t=>t.id===e))throw new Error("pipeup: there is no thread with that id");return e}};function X(e){let t=e.trim();if(!t)throw new Error("pipeup: a comment needs some words");if(t.length>b)throw new Error(`pipeup: comments are limited to ${b} characters`);return t}function Y(e){if(!O(e))throw new Error("pipeup: a reaction is one emoji");return e}function ee(e){let t=e.replace(/\s+/g," ").trim();if(!t||t.length>80)throw new Error("pipeup: choose a name of 1 to 80 characters");if(g(t))throw new Error("pipeup: that name is kept for AI replies; choose another");return t}var te=class{docs=new Map;profile=null;async load(e){return[...this.docs.get(e)?.values()??[]]}async append(e,t){let r=this.docs.get(e);r||this.docs.set(e,r=new Map);for(let e of t)r.set(e.body.id,e)}async loadProfile(){return this.profile}async saveProfile(e){this.profile=e}async saveProfileIfAbsent(e){return this.profile||(this.profile=e),this.profile}},re="";async function ne(e,t=""){let r=await e.loadProfile();if(r)return"Reviewer"===r.name?{...r,name:""}:r;let n={identity:await d(),name:t};return e.saveProfileIfAbsent(n)}var ie=class e{constructor(e){this.db=e}static open(t="pipeup"){return new Promise((r,n)=>{let i=indexedDB.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.createObjectStore("ops",{keyPath:["doc","id"]}).createIndex("doc","doc"),e.createObjectStore("meta")},i.onsuccess=()=>{let t=i.result;t.onversionchange=()=>t.close(),r(new e(t))},i.onerror=()=>n(i.error??new Error("pipeup: could not open local storage"))})}close(){this.db.close()}async load(e){return(await this.request("ops","readonly",t=>t.index("doc").getAll(e))).map(e=>e.op)}async append(e,t){if(0===t.length)return;let r=this.db.transaction("ops","readwrite"),n=r.objectStore("ops"),i=ae(r);try{for(let r of t)n.put({doc:e,id:r.body.id,op:r})}catch(e){throw r.abort(),i.catch(()=>{}),e}await i}async loadProfile(){return await this.request("meta","readonly",e=>e.get("profile"))??null}async saveProfile(e){await this.request("meta","readwrite",t=>t.put(e,"profile"))}async saveProfileIfAbsent(e){let t=this.db.transaction("meta","readwrite"),r=t.objectStore("meta"),n=ae(t),i=e,a=r.get("profile");return a.onsuccess=()=>{a.result?i=a.result:r.put(e,"profile")},await n,i}request(e,t,r){return new Promise((n,i)=>{let a=r(this.db.transaction(e,t).objectStore(e));a.onsuccess=()=>n(a.result),a.onerror=()=>i(a.error??new Error("pipeup: local storage request failed"))})}};function ae(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error??new Error("pipeup: local storage write failed")),e.onabort=()=>r(e.error??new Error("pipeup: local storage write aborted"))})}function oe(e){let t=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_TEXT),r=[],n="";for(let e=t.nextNode();e;e=t.nextNode())r.push({node:e,start:n.length}),n+=e.data;return{text:n,nodes:r}}function se(e,t,r){let n=(e.ownerDocument??e).createRange();return n.setStart(e,0),n.setEnd(t,r),n.toString().length}function de(e,t,r){let n=le(e,t,!1),i=le(e,r,!0);if(!n||!i||r<t)return null;let a=n.node.ownerDocument.createRange();return a.setStart(n.node,n.offset),a.setEnd(i.node,i.offset),a}function le(e,t,r){let n=e.nodes.find(e=>t>=e.start&&t<e.start+e.node.data.length+Number(r));return n&&{node:n.node,offset:t-n.start}}function ue(e){return e.nodeType===Node.ELEMENT_NODE?e:e.parentElement}function ce(e,t){for(let r=ue(e)?.closest("[data-pipeup-id]")??null;r;){if(!t.contains(r))return null;let e=r.getAttribute("data-pipeup-id")??"";if(""!==e&&e.length<=200)return r;r=r.parentElement?.closest("[data-pipeup-id]")??null}return null}function he(e,t,r){return e.slice(t,r).replace(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/g,"")}function pe(e,t){let r=function(e,t){if(e===t)return"";let r=[];for(let n=t;n&&n!==e;n=n.parentElement){let e=1;for(let t=n.previousElementSibling;t;t=t.previousElementSibling)t.tagName===n.tagName&&e++;r.unshift(`${n.tagName.toLowerCase()}:nth-of-type(${e})`)}return":scope > "+r.join(" > ")}(e,t);if(r.length>2e3)throw new Error("pipeup: this element is nested too deeply to comment on \u2014 give a nearby container a data-pipeup-id");return r}function fe(e){if(!I(e))throw new Error("pipeup: could not describe this place on the page");return e}function me(e,t){let r=ue(e),n=r?.closest("p,li,h1,h2,h3,h4,h5,h6,td,th,blockquote,pre,figcaption,dt,dd,summary,caption")??null;return n&&t.contains(n)?n:r&&t.contains(r)?r:t}function ge(e,t,r){if(!t.contains(e.commonAncestorContainer))throw new Error("pipeup: the selection is outside the commentable area");let n=ce(e.commonAncestorContainer,t),o=n??t,{text:s}=oe(o),d=se(o,e.startContainer,e.startOffset),l=se(o,e.endContainer,e.endOffset),u=s.slice(d,l);if(""===u)throw new Error("pipeup: select some text to comment on");if(u.length>k)throw new Error("pipeup: selections are limited to 10000 characters");let c=he(s,Math.max(0,d-32),d),h=he(s,l,l+32);return fe({...n?{id:n.getAttribute("data-pipeup-id")??""}:{},path:"",quote:{exact:u,prefix:c,suffix:h},...r?{view:r}:{},fingerprint:a(me(e.startContainer,t).textContent??""),snapshot:he(i(c+u+h),0,200)})}function ye(e,t,r,n){let o=ce(e,t);return fe({...o?{id:o.getAttribute("data-pipeup-id")??""}:{},path:pe(o??t,e),...r?{point:{x:we(r.x),y:we(r.y)}}:{},...n?{view:n}:{},fingerprint:a(e.textContent??""),snapshot:he(i(e.textContent??""),0,200)})}function we(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function be(e,t,r){let n=Array.from({length:t.length+1},(e,t)=>t),i=[...n],a=[t.length];for(let o=1;o<=e.length;o++){i[0]=r?0:o;for(let r=1;r<=t.length;r++){let a=e.charCodeAt(o-1)===t.charCodeAt(r-1)?0:1;i[r]=Math.min(n[r]+1,i[r-1]+1,n[r-1]+a)}a.push(i[t.length]),[n,i]=[i,n]}return a}var xe=(e,t)=>be(e,t,!1).pop(),ve={state:"orphaned",element:null,range:null};function ke(e,t,r={}){let n=e.id?function(e,t){for(let r of e.querySelectorAll("[data-pipeup-id]"))if(r.getAttribute("data-pipeup-id")===t)return r;return null}(t,e.id):t;return e.quote?function(e,t,r,n,i){let o=r??n,s=oe(o),d=function(e,t){if(!t.exact)return-1;let r=-1,n=-1;for(let i=e.indexOf(t.exact);-1!==i;i=e.indexOf(t.exact,i+1)){let a=e.slice(Math.max(0,i-t.prefix.length),i),o=e.slice(i+t.exact.length,i+t.exact.length+t.suffix.length),s=Ee(a,t.prefix)+Ae(o,t.suffix);s>n&&(r=i,n=s)}return r}(s.text,t);if(d>=0){let i=de(s,d,d+t.exact.length);if(i){let t=me(i.startContainer,n);return{state:null!==r&&a(t.textContent??"")===e.fingerprint?"attached":"moved",element:t,range:i}}}if(i){let e=o===n?s:oe(n);if(e.text.length<=5e4&&t.exact.length>=12&&t.exact.length<=300){let r=function(e,t,r){let n=t.length;if(0===n)return null;let i=-1,a=1/0;if(be(e,t,!0).forEach((e,t)=>{t&&e<a&&(a=e,i=t)}),a>r)return null;let o=Math.max(0,i-n),s=1/0;for(let a=Math.max(0,i-n-r);a<=Math.min(i,i-n+r);a++){let r=xe(e.slice(a,i),t);r<s&&(s=r,o=a)}return{start:o,end:i,distance:s}}(e.text,t.exact,Math.floor(t.exact.length/4)),i=r?de(e,r.start,r.end):null;if(i)return{state:"moved",element:me(i.startContainer,n),range:i}}}return ve}(e,e.quote,n,t,!1!==r.fuzzy):function(e,t){if(!t)return ve;let r=t;if(e.path){if(!e.path.startsWith(":scope > "))return ve;try{r=t.querySelector(e.path)}catch{return ve}}return r?{state:a(r.textContent??"")===e.fingerprint?"attached":"moved",element:r,range:null}:ve}(e,n)}function Ae(e,t){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;return r}function Ee(e,t){let r=0;for(;r<e.length&&r<t.length&&e[e.length-1-r]===t[t.length-1-r];)r++;return r}var $e={A:"Link",BUTTON:"Button",P:"Paragraph",LI:"List item",UL:"List",OL:"List",IMG:"Image",TABLE:"Table",TD:"Cell",TH:"Cell",FIGURE:"Figure",SVG:"Graphic",CANVAS:"Graphic",LABEL:"Label",INPUT:"Field",SELECT:"Dropdown",TEXTAREA:"Field",SUMMARY:"Disclosure",BLOCKQUOTE:"Quote",SECTION:"Section",ARTICLE:"Article",H1:"Heading",H2:"Heading",H3:"Heading",H4:"Heading",H5:"Heading",H6:"Heading",switch:"Switch",tab:"Tab",checkbox:"Checkbox",radio:"Radio button",button:"Button",submit:"Button",link:"Link"};function Se(e){let t=e.getAttribute("role")??("INPUT"===e.tagName?e.type:""),r=e.getAttribute("data-pipeup-label")||Object.hasOwn($e,t)&&$e[t]||$e[e.tagName.toUpperCase()];if(r)return r;if(Ce(e))return"Block";let n=e.getBoundingClientRect(),i=n.width/n.height;return i>1.4||i<.7?"Bar":"Shape"}var Me=e=>e.innerText||e.textContent||"";function Ce(e){let t=e,r=t.labels?.[0];return Pe(i(e.getAttribute("aria-label")??e.getAttribute("alt")??(r&&Me(r))??("SELECT"===e.tagName?t.selectedOptions[0]?.text:null)??(t.placeholder||Me(e))),40)}function Ne(e){let t=e.getAttribute("data-pipeup-label");if(t)return t;let r=e.getAttribute("data-pipeup-ask");if(r)return`Ask "${r}"`;let n=Ce(e);return n?`${Se(e)} \xb7 ${n}`:Se(e)}function Oe(e,t,r){let n=e.id??null,a=e.quote?.exact??null,o=e.point?`${Math.round(100*e.point.x)}% across, ${Math.round(100*e.point.y)}% down the element`:null,s=t.element;if("orphaned"===t.state||!s)return{where:`No longer on the page (it read: "${e.snapshot}")`,element:null,id:n,quote:a,pin:o};let d=[],l=e.view?.slide;if(l){let e=s.closest("[data-pipeup-slide],.reveal .slides section")?.querySelector(je)?.textContent;d.push(`Slide ${l}`+(e?` "${Pe(i(e))}"`:""))}else{let t=function(e){return e?e.label||Object.entries(e).filter(([e,t])=>t&&"slide"!==e&&e!==qe).map(([,e])=>e).join(" \xb7 "):""}(e.view);t&&d.push(t);let n=function(e,t){let r=e=>!1!==e.checkVisibility?.(),n=r(e),a=e=>i(e.textContent??"");for(let i=e;i&&i!==t;i=i.parentElement)for(let e=i.previousElementSibling;e;e=e.previousElementSibling){let t=e.matches(je)?e:[...e.querySelectorAll(je)].pop();if(t&&a(e)===a(t)&&(!n||r(t)))return t}return null}(s,r);n&&d.push(`Section "${Pe(i(n.textContent??""))}"`)}let u=Ne(s);return d.push(u),{where:d.join(" \u203a "),element:u,id:n,within:!!n&&s.getAttribute("data-pipeup-id")!==n,quote:a,pin:o}}var qe="pipeup-edition",je="h1,h2,h3";function Pe(e,t=60){return e.length>t?e.slice(0,t-1)+"\u2026":e}function Te(e,t){let r=Math.max(0,Math.round((t-e)/1e3));if(r<60)return"just now";let n=Math.round(r/60);if(n<60)return`${n}m ago`;let i=Math.round(n/60);return i<48?`${i}h ago`:`${Math.round(i/24)}d ago`}function Ie(e,t,r,n){return"ai"===t?De(e,"## ",n,r):Ue(e)}function Fe(e,t,r){let n=r.all?e:e.filter(e=>!e.thread.resolved);if("text"===t)return n.map(Ue).join("\n");let i=e.filter(e=>e.thread.resolved).length,a=e.length-i,o=function(e){let t=[...new Set(e.flatMap(({thread:e})=>[e.root,...e.root.replies].map(e=>Re(f(e)))))],r=t.length>3?[...t.slice(0,2),t.length-2+" others"]:t;return r.length>1?`${r.slice(0,-1).join(", ")} and ${r.at(-1)}`:r[0]??""}(n),s=r.exportedAt.toUTCString(),d=[`# Comments on ${Re(r.title)}`,"",`${a||"No"} open comment${1===a?"":"s"}${r.all&&i?` and ${i} resolved`:""}${o?` from ${o}`:""}, copied ${s.slice(5,16).replace(/^0/,"")}, ${s.slice(17,22)} UTC.`+(r.all||!i?"":` ${i} resolved comment${1===i?" is":"s are"} left out.`),"",`Page: ${Re(r.url)}`,"",""].join("\n"),l=r.exportedAt.getTime();return d+n.map((e,t)=>De(e,`## ${t+1}. `,l)).join("\n")+(n.length?"\n---\n\nFor an AI assistant: work through the open comments in order and say what you changed, or why you didn't. Each one's last line gives the thread to answer and the element's data-pipeup-id in the page's HTML. Answer in the thread with Pipeup (its pipeup-apply skill says how) and mark it addressed; never resolve it, the author does.\n":"")}function Le(e){return e.reactions.map(e=>`${e.emoji} ${e.by.length} (${e.by.map(e=>Re(f(e))).join(", ")})`).join(" \xb7 ")}function Re(e){return e.replace(/\s+/g," ").trim()}function De(e,t,r,n){let{thread:i,location:a}=e,o=[t+Re(a.where),""];n&&o.push(`Page: ${Re(n)}`,""),a.quote&&o.push(`On the words "${Re(a.quote)}".`,""),a.pin&&o.push(`Pinned ${Re(a.pin)}.`,""),o.push(`**${Re(f(i.root))}** (${Te(i.root.at,r)}): ${Be(i.root," ")}`),i.root.reactions.length&&o.push(`Reactions: ${Le(i.root)}`);for(let e of i.root.replies)o.push(`- **${Re(f(e))}** (${Te(e.at,r)}): ${Be(e," ")}`),e.reactions.length&&o.push(` - Reactions: ${Le(e)}`);i.addressed&&!i.resolved&&o.push("",`**${Re(f(i.addressed))}** marked it addressed (${Te(i.addressed.at,r)}): ${Re(i.addressed.text)}`);let s=a.id?` \xb7 ${a.within?"in":"on"} \`data-pipeup-id="${Re(a.id.replace(/`/g,""))}"\``:"";return o.push("",`${i.resolved?"Resolved":i.addressed?"Open, addressed":"Open"} \xb7 thread \`${i.id}\`${s}`),o.join("\n")+"\n"}function Ue(e){let{thread:t,location:r}=e,n=[Re(r.where)+(r.quote?`, on the text "${Re(r.quote)}"`:""),`${Re(f(t.root))}: ${Be(t.root," ")}`];t.root.reactions.length&&n.push(` Reactions: ${Le(t.root)}`);for(let e of t.root.replies)n.push(` ${Re(f(e))}: ${Be(e," ")}`),e.reactions.length&&n.push(` Reactions: ${Le(e)}`);return n.join("\n")+"\n"}function Be(e,t){return e.deleted?"(deleted)":e.text.replace(/\r\n|\r|\n/g,"\n"+t)+(e.edited?" (edited)":"")}function _e(e,t){return{markdown:Fe(e,"ai",t),threads:e.filter(e=>t.all||!e.thread.resolved).map(({thread:e,location:t})=>{let r={id:e.id,state:e.resolved?"resolved":e.addressed?"addressed":"open",where:t.where,comments:[e.root,...e.root.replies].map(e=>({id:e.id,by:f(e),agent:g(e.name),at:new Date(e.at).toISOString(),text:e.deleted?"":e.text,...e.reactions.length?{reactions:e.reactions.map(e=>({emoji:e.emoji,by:e.by.map(f)}))}:{}}))};return t.id&&(r.element=t.id),t.quote&&(r.quote=t.quote),t.pin&&(r.pin=t.pin),e.addressed&&!e.resolved&&(r.addressed={note:e.addressed.text,by:f(e.addressed)}),r})}}var ze="0.9.1",He="2026-11-01";export{m as AI_NAME,u as ANIMALS,He as BUILT,c as COLOURS,re as DEFAULT_PROFILE_NAME,ie as IndexedDbStore,te as MemoryStore,Q as PipeupDocument,W as UnsavedChangeError,ze as VERSION,_e as agentComments,y as agentName,p as animalName,R as checkOp,B as computeOpId,Fe as copyAll,Ie as copyThread,d as createIdentity,ye as describeElement,ge as describeRange,Te as formatAgo,g as isAiName,w as isPasted,Ne as labelOf,ne as loadOrCreateProfile,Oe as locate,f as nameOf,H as newDocumentAttribute,K as parseDocumentAttribute,J as readFeedbackFile,ke as resolveAnchor,q as signOp};
1
+ function e(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function t(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function n(e){return(new TextEncoder).encode(e)}function r(e){if(null===e||"object"!=typeof e)return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(r).join(",")+"]";let t=e;return"{"+Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>JSON.stringify(e)+":"+r(t[e])).join(",")+"}"}function i(e){return e.replace(/\s+/g," ").trim()}function a(e){let t=i(e),n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")}var o=/^[A-Za-z0-9_-]{43}$/,s=new Map;async function l(){let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]);return{publicKey:e(new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey))),privateKey:t.privateKey}}async function d(t,n){let r=await crypto.subtle.sign({name:"Ed25519"},t.privateKey,n);return e(new Uint8Array(r))}var u=["Otter","Fox","Owl","Bear","Rabbit"],h=["Red","Orange","Yellow","Green","Teal","Blue","Purple","Pink","Brown","Grey"];function c(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return t=Math.imul(t^t>>>16,2246822507),t=Math.imul(t^t>>>13,3266489909),(t^t>>>16)>>>0}var p=e=>`${h[(e=>Math.floor(c(e)/u.length)%h.length)(e)]} ${u[(e=>c(e)%u.length)(e)]}`,f=e=>{let t=e.name.replace(/^AI assistant \xb7 /,"")||p(e.author);return e.alike?`${t} \xb7 ${function(e){let t=c(`id:${e}`),n="";for(let e=0;e<4;e++,t>>>=5)n+="0123456789ABCDEFGHJKMNPQRSTVWXYZ"[31&t];return n}(e.author)}`:t},m="AI assistant",g=e=>e===m||e.startsWith(`${m} `),y=e=>`${m} \xb7 ${e.replace(/\s+/g," ").trim()||"Agent"}`.slice(0,80).trim(),w=(e,t)=>e.name.startsWith(`${m} \xb7 `)&&!t.includes(e.author),b=1e4,v=2**40,x=2**47,k=1e4,A=200,$=new Set(["h","p","img","button","link","field","media","box"]),E=new Set(["confirmed","moved","gone"]),M=/^[0-9a-f]{8}$/,S=/^[A-Za-z0-9_-]{43}$/,C=/^(?:[^\s@<>"]{1,64}@[^\s@<>"]{1,190}\.[^\s@<>"]{2,24}|gh:[A-Za-z0-9-]{1,39})$/,N=/^(?:[A-Za-z0-9_-]{43}|(?:host|gh):[A-Za-z0-9._@-]{1,64})$/,O=/^[A-Za-z0-9_-]{43}$/,q=new Set(["create","reply","edit","delete","resolve","reopen","addressed","react","unreact","seen","contact","uncontact","place"]),j=/^(?:\p{Regional_Indicator}{2}|[#*0-9]\uFE0F?\u20E3|\p{Extended_Pictographic}(?:\uFE0F|\p{Emoji_Modifier})?(?:\u200D\p{Extended_Pictographic}(?:\uFE0F|\p{Emoji_Modifier})?)*)$/u,P=e=>"string"==typeof e&&j.test(e)&&[...e].length<=16;async function T(e,t){if(e.author!==t.publicKey)throw new Error("pipeup: an op must be signed by its author");return{body:e,sig:await d(t,n(r(e)))}}var I=(e,t)=>"string"==typeof e&&e.length<=t,L=e=>!!e&&"object"==typeof e,F=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<=1;function R(e){if(!L(e))return!1;let{id:t,path:n,fingerprint:r,snapshot:i,quote:a,point:o,view:s,kind:l,name:d,heads:u,y:h,lost:c}=e;if(!(I(n,2e3)&&I(i,500)&&"string"==typeof r&&M.test(r)&&(void 0===t||I(t,200)&&""!==t)&&(void 0===a||L(a)&&I(a.exact,k)&&""!==a.exact&&I(a.prefix,64)&&I(a.suffix,64))&&(void 0===o||L(o)&&F(o.x)&&F(o.y))))return!1;if(void 0!==s){if(!L(s)||Array.isArray(s))return!1;let e=Object.entries(s);if(e.length>16||!e.every(([e,t])=>e.length<=64&&I(t,200)))return!1}return!(void 0!==l&&!$.has(l)||void 0!==d&&!I(d,A)||void 0!==u&&(!Array.isArray(u)||u.length>3||!u.every(e=>I(e,120)))||void 0!==h&&!F(h)||void 0!==c&&!0!==c)}function D(e){if(!L(e))return!1;let{body:t,sig:n}=e;if("string"!=typeof n||!L(t)||JSON.stringify({body:t,sig:n}).length>262144)return!1;let r=t;if(1!==r.v||"string"!=typeof r.id||!S.test(r.id)||!q.has(r.kind)||!I(r.doc,64)||""===r.doc||"string"!=typeof r.thread||!S.test(r.thread)||"string"!=typeof r.author||!O.test(r.author)||"string"!=typeof r.name||r.name.length>80||r.name!==r.name.trim()||"number"!=typeof r.clock||!Number.isSafeInteger(r.clock)||r.clock<1||r.clock>v||"number"!=typeof r.at||!Number.isSafeInteger(r.at)||r.at<0||r.at>x||void 0!==r.text&&(!I(r.text,b)||r.text!==r.text.trim())||void 0!==r.target&&("string"!=typeof r.target||!S.test(r.target))||("create"===r.kind||"reply"===r.kind||"edit"===r.kind||"addressed"===r.kind)&&!r.text||("reply"===r.kind||"edit"===r.kind||"delete"===r.kind)&&!r.target)return!1;if(void 0!==r.mentions){if("create"!==r.kind&&"reply"!==r.kind&&"edit"!==r.kind||!Array.isArray(r.mentions)||r.mentions.length>20)return!1;let e=r.text?.length??0;for(let t of r.mentions){if(!L(t)||!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end))return!1;let{start:n,end:r,ref:i}=t;if(n<0||r<=n||r>e||"string"!=typeof i||!N.test(i))return!1}}return!!(("contact"!==r.kind||"string"==typeof r.text&&C.test(r.text))&&("seen"!==r.kind||r.target)&&("react"!==r.kind&&"unreact"!==r.kind||r.target&&P(r.text))&&("create"!==r.kind||r.id===r.thread&&R(r.anchor))&&("place"!==r.kind||R(r.anchor)&&E.has(r.text)))}function U(i){return async function(n,r,i){if(!o.test(n))return!1;try{if(e(t(n))!==n)return!1;let a=s.get(n);if(!a){s.size>=512&&s.delete(s.keys().next().value),a=crypto.subtle.importKey("raw",t(n),{name:"Ed25519"},!0,["verify"]),s.set(n,a);let e=a;e.catch(()=>{s.get(n)===e&&s.delete(n)})}return await crypto.subtle.verify({name:"Ed25519"},await a,t(i),r)}catch{return!1}}(i.body.author,n(r(i.body)),i.sig)}async function B(e){return D(e)&&await U(e).catch(()=>!1)}function _(e,t){return e.body.clock!==t.body.clock?e.body.clock-t.body.clock:e.body.at!==t.body.at?e.body.at-t.body.at:e.body.author!==t.body.author?e.body.author<t.body.author?-1:1:e.body.id!==t.body.id?e.body.id<t.body.id?-1:1:0}function z(e,t,n,r,i,a){let o={id:e,author:t,name:n,text:r,at:i,edited:!1,deleted:!1,replies:[],reactions:[]};return a?.length&&(o.mentions=a),o}async function H(t){let i={...t,id:void 0,thread:"create"===t.kind?void 0:t.thread},a=await crypto.subtle.digest("SHA-256",n(r(i)));return e(new Uint8Array(a))}var K=class{constructor(e){this.doc=e}ops=new Map;clock=0;createAt=new Map;threadAt=new Map;get size(){return this.ops.size}all(){return[...this.ops.values()]}threads(){return function(e){let t=new Map,n=new Map,r=new Map;for(let{body:i}of[...e].sort(_)){if(i.name&&!g(i.name)&&r.set(i.author,i.name),"create"===i.kind){if(t.has(i.id)||!i.anchor||void 0===i.text)continue;let e=z(i.id,i.author,i.name,i.text,i.at,i.mentions);t.set(i.id,{id:i.id,anchor:i.anchor,root:e,resolved:!1}),n.set(i.id,{comment:e,thread:i.id});continue}let e=t.get(i.thread);if(!e)continue;if("resolve"===i.kind||"reopen"===i.kind){e.resolved="resolve"===i.kind,"reopen"===i.kind&&delete e.addressed;continue}if("place"===i.kind){if(!i.anchor)continue;e.anchor=i.anchor,e.placed={how:i.text,author:i.author,name:i.name,at:i.at};continue}if("addressed"===i.kind){void 0!==i.text&&(e.addressed={text:i.text,author:i.author,name:i.name,at:i.at});continue}let a=i.target?n.get(i.target):void 0;if(a&&a.thread===i.thread){if("reply"===i.kind){if(n.has(i.id)||void 0===i.text)continue;let t=z(i.id,i.author,i.name,i.text,i.at,i.mentions);e.root.replies.push(t),n.set(i.id,{comment:t,thread:i.thread});continue}if("seen"===i.kind){let e=a.comment.seenBy??=[];e.includes(i.author)||e.push(i.author);continue}if("react"===i.kind||"unreact"===i.kind){if(void 0===i.text||a.comment.deleted)continue;let e=a.comment.reactions,t=e.find(e=>e.emoji===i.text);if("react"===i.kind){let n={author:i.author,name:i.name};t?t.by.some(e=>e.author===i.author)||t.by.push(n):e.length<12&&e.push({emoji:i.text,by:[n]})}else t&&(t.by=t.by.filter(e=>e.author!==i.author),t.by.length||e.splice(e.indexOf(t),1));continue}i.author!==a.comment.author||a.comment.deleted||("edit"===i.kind&&void 0!==i.text&&(a.comment.text=i.text,a.comment.edited=!0,i.mentions?a.comment.mentions=i.mentions:delete a.comment.mentions),"delete"===i.kind&&(a.comment.text="",a.comment.deleted=!0,a.comment.reactions=[],delete a.comment.mentions))}}for(let{comment:e}of n.values()){e.name||(e.unnamed=!0,e.name=r.get(e.author)??"");for(let t of e.reactions)for(let e of t.by)e.name||=r.get(e.author)??""}let i=new Map,a=(e,t)=>{let n=f({author:e,name:t}).toLowerCase();(i.get(n)??i.set(n,new Set).get(n)).add(e)};for(let{comment:e}of n.values()){a(e.author,e.name);for(let t of e.reactions)for(let e of t.by)a(e.author,e.name)}let o=(e,t)=>!g(t)&&(i.get(f({author:e,name:t}).toLowerCase())?.size??0)>1;for(let{comment:e}of n.values()){o(e.author,e.name)&&(e.alike=!0);for(let t of e.reactions)for(let e of t.by)o(e.author,e.name)&&(e.alike=!0)}return[...t.values()]}(this.ops.values())}async add(e){let t=[];for(let n of e){if(!D(n)||n.body.doc!==this.doc||this.ops.has(n.body.id)||n.body.id!==await H(n.body)||!await U(n))continue;let e={body:n.body,sig:n.sig};this.ops.set(e.body.id,e),this.clock=Math.max(this.clock,e.body.clock),"create"===e.body.kind&&this.createAt.set(e.body.author,Math.max(this.createAt.get(e.body.author)??0,e.body.at)),this.threadAt.set(e.body.thread,Math.max(this.threadAt.get(e.body.thread)??0,e.body.at)),t.push(e)}return t}async append(e,t,n){let r={v:1,...n,id:"",thread:"create"===n.kind?"":n.thread,doc:this.doc,author:e.publicKey,name:t,clock:Math.min(this.clock+1,v),at:Math.min(Math.max(Date.now(),"create"===n.kind?(this.createAt.get(e.publicKey)??0)+1:(this.threadAt.get(n.thread)??0)+1),x)};r.id=await H(r);let i=this.ops.get(r.id);if(i)return i;"create"===r.kind&&(r.thread=r.id);let[a]=await this.add([await T(r,e)]);if(!a)throw new Error("pipeup: could not record this change");return a}},G=/^([A-Za-z0-9_-]{16}):([A-Za-z0-9_-]{43})$/;function Z(){return`${function(t=16){return e(crypto.getRandomValues(new Uint8Array(t)))}(12)}:${e(crypto.getRandomValues(new Uint8Array(32)))}`}async function J(e){let n=G.exec(e.trim()),r=n?.[1],i=n?.[2];if(!r||!i)throw new Error('pipeup: data-pipeup-doc must look like "<id>:<key>", as made by newDocumentAttribute()');return{id:r,key:await crypto.subtle.importKey("raw",t(i),{name:"AES-GCM"},!1,["encrypt","decrypt"])}}async function V(t,r,i){let a=crypto.getRandomValues(new Uint8Array(12)),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,additionalData:n(i)},t,n(r));return{iv:e(a),data:e(new Uint8Array(o))}}var W=e=>`pipeup-file:${e}`;async function Q(e,r,i){if(e.length>5e6)throw new Error("pipeup: this feedback file is too large");let a,o,s;try{a=JSON.parse(e)}catch{throw new Error("pipeup: this is not an Pipeup feedback file")}if(!a||"object"!=typeof a||1!==a.pipeup||"string"!=typeof a.doc)throw new Error("pipeup: this is not an Pipeup feedback file");if(a.doc!==r)throw new Error("pipeup: this feedback is for a different document");if(!a.sealed)return Array.isArray(a.ops)?a.ops:[];if(!i)throw new Error("pipeup: this feedback is sealed, and this page has no document key");if("string"!=typeof a.iv||"string"!=typeof a.data)throw new Error("pipeup: this is not an Pipeup feedback file");try{o=await async function(e,r,i){try{let a=await crypto.subtle.decrypt({name:"AES-GCM",iv:t(r.iv),additionalData:n(i)},e,t(r.data));return(new TextDecoder).decode(a)}catch{throw new Error("pipeup: this feedback could not be opened with this document")}}(i,{iv:a.iv,data:a.data},W(r))}catch{throw new Error("pipeup: this feedback could not be opened with this document's key")}try{s=JSON.parse(o)}catch{throw new Error("pipeup: this is not an Pipeup feedback file")}return Array.isArray(s)?s:[]}var X=/^[a-z][a-z0-9-]{1,23}\/[a-z][a-z0-9-]{0,31}$/,Y=class extends Error{constructor(e,t,n=1){super("pipeup: shown here, but not saved yet"),this.id=e,this.cause=t,this.count=n,this.name="UnsavedChangeError"}},ee=class e{constructor(e,t){this.log=e,this.options=t,this.displayName=t.name.trim()?re(t.name):""}listeners=new Set;cache=[];comments=new Map;displayName;e=Promise.resolve();unsaved=[];static async open(t){if("string"!=typeof t.doc||""===t.doc||t.doc.length>64)throw new Error("pipeup: the document id must be 1 to 64 characters");let n=new K(t.doc),r=await t.store.load(t.doc),i=r.length-(await n.add(r)).length;i&&console.warn(`pipeup: ${i} saved change${1===i?"":"s"} on this page couldn't be read; kept as saved`);let a=new e(n,t);return a.refresh(!1),a}get id(){return this.options.doc}get me(){return this.options.identity.publicKey}get name(){return this.displayName}set name(e){this.displayName=re(e),this.refresh(!0,[],"")}threads(){return this.cache}ops(){return this.log.all()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}comment(e,t,n){return this.enqueue(()=>this.write({kind:"create",anchor:e,text:te(t),...n?.length?{mentions:n}:{}}))}place(e,t,n){return this.enqueue(async()=>{let{thread:r}=this.find(e),i="gone"===n?{...t,lost:!0}:t;await this.write({kind:"place",thread:r,anchor:i,text:n})})}reply(e,t,n){return this.enqueue(()=>this.write({kind:"reply",thread:this.find(e).thread,target:e,text:te(t),...n?.length?{mentions:n}:{}}))}edit(e,t,n){return this.enqueue(async()=>{let{thread:r}=this.mine(e);await this.write({kind:"edit",thread:r,target:e,text:te(t),...n?.length?{mentions:n}:{}})})}remove(e){return this.enqueue(async()=>{let{thread:t}=this.mine(e);await this.write({kind:"delete",thread:t,target:e})})}contact(e){let t=e.trim();return C.test(t)?this.enqueue(async()=>{await this.write({kind:"contact",thread:this.me,text:t})}):Promise.reject(new Error("pipeup: that isn't an email address or a GitHub name"))}uncontact(){return this.enqueue(async()=>{await this.write({kind:"uncontact",thread:this.me})})}contacts(){let e=new Map;for(let{body:t}of[...this.log.all()].sort(_))"contact"===t.kind&&t.text?e.set(t.author,t.text):"uncontact"===t.kind&&e.delete(t.author);return e}get portable(){return this.options.identity.privateKey.extractable}async seed(){let e=this.options.identity.privateKey;if(!e.extractable)return null;let{d:n}=await crypto.subtle.exportKey("jwk",e);return n?t(n):null}seen(e){return this.enqueue(async()=>{for(let t of e){let e=this.comments.get(t);e&&!e.comment.seenBy?.includes(this.me)&&await this.write({kind:"seen",thread:e.thread,target:t})}})}react(e,t){return this.enqueue(async()=>{await this.write({kind:"react",thread:this.find(e).thread,target:e,text:ne(t)})})}unreact(e,t){return this.enqueue(async()=>{await this.write({kind:"unreact",thread:this.find(e).thread,target:e,text:ne(t)})})}resolve(e){return this.enqueue(async()=>{await this.write({kind:"resolve",thread:this.thread(e)})})}reopen(e){return this.enqueue(async()=>{await this.write({kind:"reopen",thread:this.thread(e)})})}paste(e,t,n,r){return this.enqueue(async()=>{let i=this.thread(e),a=y(t),o=this.cache.find(e=>e.id===i).root.id;await this.write({kind:"reply",thread:i,target:o,text:te(n)},a),r?.trim()&&await this.write({kind:"addressed",thread:i,text:te(r)},a)})}sign(e,t){if(!X.test(e))throw new Error('pipeup: a signing purpose looks like "<add-on id>/<name>"');return d(this.options.identity,n(`pipeup:${e}\n${t}`))}flush(){return this.enqueue(()=>this.persist())}exportFile(){return async function(e,t,n){let r=n?{pipeup:1,doc:e,sealed:!0,...await V(n,JSON.stringify(t),W(e))}:{pipeup:1,doc:e,sealed:!1,ops:t};return JSON.stringify(r,null,2)}(this.options.doc,this.log.all(),this.options.key)}async importFile(e){return this.merge(await Q(e,this.options.doc,this.options.key),"file")}merge(e,t){return e.length>5e3?Promise.reject(new RangeError("pipeup: too many changes to merge at once")):this.enqueue(async()=>{let n=await this.log.add([...e]);this.unsaved.push(...n),n.length>0&&this.refresh(!0,n,t);try{await this.persist()}catch(e){throw n.length>0?new Y(n[0].body.id,e,n.length):e}return n.length})}enqueue(e){let t=this.e.then(e);return this.e=t.catch(()=>{}),t}async write(e,t=this.displayName){let n=await this.log.append(this.options.identity,t,e);this.unsaved.push(n),this.refresh(!0,[n],"local");try{await this.persist()}catch(e){throw new Y(n.body.id,e)}return n.body.id}async persist(){if(0===this.unsaved.length)return;let e=[...this.unsaved];await this.options.store.append(this.options.doc,e),this.unsaved=this.unsaved.filter(t=>!e.includes(t))}refresh(e,t=[],n=""){this.cache=this.log.threads(),this.comments.clear();let r=(e,t)=>{e.unnamed&&e.author===this.me&&this.displayName&&(e.name=this.displayName),this.comments.set(e.id,{comment:e,thread:t});for(let n of e.replies)r(n,t)};for(let e of this.cache)r(e.root,e.id);if(e)for(let e of this.listeners)try{e(this.cache,t,n)}catch(e){globalThis.reportError?.(e)}}find(e){let t=this.comments.get(e);if(!t)throw new Error("pipeup: there is no comment with that id");return t}mine(e){let t=this.find(e);if(t.comment.author!==this.me)throw new Error("pipeup: only the writer can change a comment");return t}thread(e){if(!this.cache.some(t=>t.id===e))throw new Error("pipeup: there is no thread with that id");return e}};function te(e){let t=e.trim();if(!t)throw new Error("pipeup: a comment needs some words");if(t.length>b)throw new Error(`pipeup: comments are limited to ${b} characters`);return t}function ne(e){if(!P(e))throw new Error("pipeup: a reaction is one emoji");return e}function re(e){let t=e.replace(/\s+/g," ").trim();if(!t||t.length>80)throw new Error("pipeup: choose a name of 1 to 80 characters");if(g(t))throw new Error("pipeup: that name is kept for AI replies; choose another");return t}var ie=class{docs=new Map;profile=null;async load(e){return[...this.docs.get(e)?.values()??[]]}async append(e,t){let n=this.docs.get(e);n||this.docs.set(e,n=new Map);for(let e of t)n.set(e.body.id,e)}async loadProfile(){return this.profile}async saveProfile(e){this.profile=e}async saveProfileIfAbsent(e){return this.profile||(this.profile=e),this.profile}},ae="";async function oe(e,t=""){let n=await e.loadProfile();if(n)return"Reviewer"===n.name?{...n,name:""}:n;let r={identity:await l(),name:t};return e.saveProfileIfAbsent(r)}var se=class e{constructor(e){this.db=e}static open(t="pipeup"){return new Promise((n,r)=>{let i=indexedDB.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.createObjectStore("ops",{keyPath:["doc","id"]}).createIndex("doc","doc"),e.createObjectStore("meta")},i.onsuccess=()=>{let t=i.result;t.onversionchange=()=>t.close(),n(new e(t))},i.onerror=()=>r(i.error??new Error("pipeup: could not open local storage"))})}close(){this.db.close()}async load(e){return(await this.request("ops","readonly",t=>t.index("doc").getAll(e))).map(e=>e.op)}async append(e,t){if(0===t.length)return;let n=this.db.transaction("ops","readwrite"),r=n.objectStore("ops"),i=le(n);try{for(let n of t)r.put({doc:e,id:n.body.id,op:n})}catch(e){throw n.abort(),i.catch(()=>{}),e}await i}async loadProfile(){return await this.request("meta","readonly",e=>e.get("profile"))??null}async saveProfile(e){await this.request("meta","readwrite",t=>t.put(e,"profile"))}async saveProfileIfAbsent(e){let t=this.db.transaction("meta","readwrite"),n=t.objectStore("meta"),r=le(t),i=e,a=n.get("profile");return a.onsuccess=()=>{a.result?i=a.result:n.put(e,"profile")},await r,i}request(e,t,n){return new Promise((r,i)=>{let a=n(this.db.transaction(e,t).objectStore(e));a.onsuccess=()=>r(a.result),a.onerror=()=>i(a.error??new Error("pipeup: local storage request failed"))})}};function le(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error??new Error("pipeup: local storage write failed")),e.onabort=()=>n(e.error??new Error("pipeup: local storage write aborted"))})}var de=[["h","h1,h2,h3,h4,h5,h6,[role=heading]"],["img","img,svg,picture,canvas,[role=img]"],["button","button,[role=button],input[type=button],input[type=submit],input[type=reset]"],["link","a[href],[role=link]"],["field","input,select,textarea,[contenteditable=true]"],["media","video,audio,iframe,object,embed"],["p","p,li,blockquote,pre,dd,dt,figcaption,td,th,caption,summary"]];function ue(e){for(let[t,n]of de)if(e.matches(n))return t;return"box"}var he=(e,t)=>i(e).slice(0,t);function ce(e){let t=e.getAttribute("aria-label")||e.getAttribute("alt")||e.getAttribute("title")||(e.labels?.[0]?.textContent??"");if(t.trim())return he(t,A);let n=e.getAttribute("src");if(n)return he(function(e){let t=e.split(/[?#]/)[0]??"";return t.slice(t.lastIndexOf("/")+1)}(n),A);let r=e.getAttribute("href");return r&&!r.startsWith("javascript:")?he(r.split("#")[0]??"",A):""}function pe(e,t){let n=[];for(let r of t.querySelectorAll("h1,h2,h3,h4,h5,h6")){if(r===e||r.contains(e)||!(r.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING))break;let t=Number(r.tagName[1]);for(;n.length&&n[n.length-1].t>=t;)n.pop();let i=he(r.textContent??"",120);i&&n.push({t,text:i})}return n.slice(-3).map(e=>e.text)}function fe(e,t){let n=t.getBoundingClientRect();if(!(n.height>0))return;let r=(e.getBoundingClientRect().top-n.top)/n.height;return Math.round(1e3*Math.min(1,Math.max(0,r)))/1e3}function me(e,t){let n=ce(e),r=pe(e,t),i=fe(e,t);return{kind:ue(e),...n?{name:n}:{},...r.length?{heads:r}:{},...void 0!==i?{y:i}:{}}}function ge(e){let t=` ${e.toLowerCase()} `,n=new Map;for(let e=0;e+3<=t.length;e++){let r=t.slice(e,e+3);n.set(r,(n.get(r)??0)+1)}return n}function ye(e,t){if(!e||!t)return e===t?1:0;let n=ge(e),r=ge(t),i=0,a=0;for(let e of n.values())a+=e;for(let e of r.values())a+=e;for(let[e,t]of n)i+=Math.min(t,r.get(e)??0);return a?2*i/a:0}var we=new Map([["h","a heading"],["p","a paragraph"],["img","a picture"],["button","a button"],["link","a link"],["field","a field"],["media","a video"],["box","a box"]]),be=e=>e.kind?`it was ${e.quote?"in ":""}${we.get(e.kind)}${e.heads?.length?` under ${e.heads.join(" \u203a ")}`:""}`:"";function ve(e){let t=(e.ownerDocument??e).createTreeWalker(e,NodeFilter.SHOW_TEXT),n=[],r="";for(let e=t.nextNode();e;e=t.nextNode())n.push({node:e,start:r.length}),r+=e.data;return{text:r,nodes:n}}function xe(e,t,n){let r=(e.ownerDocument??e).createRange();return r.setStart(e,0),r.setEnd(t,n),r.toString().length}function ke(e,t,n){let r=Ae(e,t,!1),i=Ae(e,n,!0);if(!r||!i||n<t)return null;let a=r.node.ownerDocument.createRange();return a.setStart(r.node,r.offset),a.setEnd(i.node,i.offset),a}function Ae(e,t,n){let r=e.nodes.find(e=>t>=e.start&&t<e.start+e.node.data.length+Number(n));return r&&{node:r.node,offset:t-r.start}}function $e(e){return e.nodeType===Node.ELEMENT_NODE?e:e.parentElement}function Ee(e,t){for(let n=$e(e)?.closest("[data-pipeup-id]")??null;n;){if(!t.contains(n))return null;let e=n.getAttribute("data-pipeup-id")??"";if(""!==e&&e.length<=200)return n;n=n.parentElement?.closest("[data-pipeup-id]")??null}return null}function Me(e,t,n){return e.slice(t,n).replace(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/g,"")}function Se(e,t){let n=function(e,t){if(e===t)return"";let n=[];for(let r=t;r&&r!==e;r=r.parentElement){let e=1;for(let t=r.previousElementSibling;t;t=t.previousElementSibling)t.tagName===r.tagName&&e++;n.unshift(`${r.tagName.toLowerCase()}:nth-of-type(${e})`)}return":scope > "+n.join(" > ")}(e,t);if(n.length>2e3)throw new Error("pipeup: this element is nested too deeply to comment on \u2014 give a nearby container a data-pipeup-id");return n}function Ce(e){if(!R(e))throw new Error("pipeup: could not describe this place on the page");return e}function Ne(e,t){let n=$e(e),r=n?.closest("p,li,h1,h2,h3,h4,h5,h6,td,th,blockquote,pre,figcaption,dt,dd,summary,caption")??null;return r&&t.contains(r)?r:n&&t.contains(n)?n:t}function Oe(e,t,n){if(!t.contains(e.commonAncestorContainer))throw new Error("pipeup: the selection is outside the commentable area");let r=Ee(e.commonAncestorContainer,t),o=r??t,{text:s}=ve(o),l=xe(o,e.startContainer,e.startOffset),d=xe(o,e.endContainer,e.endOffset),u=s.slice(l,d);if(""===u)throw new Error("pipeup: select some text to comment on");if(u.length>k)throw new Error("pipeup: selections are limited to 10000 characters");let h=Me(s,Math.max(0,l-32),l),c=Me(s,d,d+32),p=Ne(e.startContainer,t),f=pe(p,t);return Ce({...r?{id:r.getAttribute("data-pipeup-id")??""}:{},path:"",quote:{exact:u,prefix:h,suffix:c},...n?{view:n}:{},fingerprint:a(p.textContent??""),snapshot:Me(i(h+u+c),0,200),kind:ue(p),...f.length?{heads:f}:{}})}function qe(e,t,n,r){let o=Ee(e,t);return Ce({...o?{id:o.getAttribute("data-pipeup-id")??""}:{},path:Se(o??t,e),...n?{point:{x:je(n.x),y:je(n.y)}}:{},...r?{view:r}:{},fingerprint:a(e.textContent??""),snapshot:Me(i(e.textContent??""),0,200),...me(e,t)})}function je(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Pe(e,t,n){let r=Array.from({length:t.length+1},(e,t)=>t),i=[...r],a=[t.length];for(let o=1;o<=e.length;o++){i[0]=n?0:o;for(let n=1;n<=t.length;n++){let a=e.charCodeAt(o-1)===t.charCodeAt(n-1)?0:1;i[n]=Math.min(r[n]+1,i[n-1]+1,r[n-1]+a)}a.push(i[t.length]),[r,i]=[i,r]}return a}var Te=(e,t)=>Pe(e,t,!1).pop(),Ie={state:"orphaned",element:null,range:null};function Le(e,t,n={}){if(e.lost)return Ie;let r=e.id?function(e,t){for(let n of e.querySelectorAll("[data-pipeup-id]"))if(n.getAttribute("data-pipeup-id")===t)return n;return null}(t,e.id):t;return e.quote?function(e,t,n,r,i){let o=n??r,s=ve(o),l=function(e,t){if(!t.exact)return-1;let n=-1,r=-1;for(let i=e.indexOf(t.exact);-1!==i;i=e.indexOf(t.exact,i+1)){let a=e.slice(Math.max(0,i-t.prefix.length),i),o=e.slice(i+t.exact.length,i+t.exact.length+t.suffix.length),s=Ke(a,t.prefix)+He(o,t.suffix);s>r&&(n=i,r=s)}return n}(s.text,t);if(l>=0){let i=ke(s,l,l+t.exact.length);if(i){let t=Ne(i.startContainer,r);return{state:null!==n&&a(t.textContent??"")===e.fingerprint?"attached":"moved",element:t,range:i}}}if(i){let e=o===r?s:ve(r);if(e.text.length<=5e4&&t.exact.length>=12&&t.exact.length<=300){let n=function(e,t,n){let r=t.length;if(0===r)return null;let i=-1,a=1/0;if(Pe(e,t,!0).forEach((e,t)=>{t&&e<a&&(a=e,i=t)}),a>n)return null;let o=Math.max(0,i-r),s=1/0;for(let a=Math.max(0,i-r-n);a<=Math.min(i,i-r+n);a++){let n=Te(e.slice(a,i),t);n<s&&(s=n,o=a)}return{start:o,end:i,distance:s}}(e.text,t.exact,Math.floor(t.exact.length/4)),i=n?ke(e,n.start,n.end):null;if(i)return{state:"moved",element:Ne(i.startContainer,r),range:i}}}return Ie}(e,e.quote,r,t,!1!==n.fuzzy):function(e,t,n,r){if(!t)return Ie;let i=function(e,t){if(!e.path)return t;if(!e.path.startsWith(":scope > "))return null;try{return t.querySelector(e.path)}catch{return null}}(e,t);if(i&&a(i.textContent??"")===e.fingerprint)return{state:"attached",element:i,range:null};if(!e.path)return i?{state:"moved",element:i,range:null}:Ie;let o=e.kind??(i?ue(i):null);if(!o||!r)return Ie;let{best:s,sure:l}=function(e,t,n,r,i){let a=null,o=-1,s=-1;for(let l of function(e,t){let n=de.find(([e])=>e===t)?.[1]??"*",r=[];for(let i of e.querySelectorAll(n))if(ue(i)===t&&(r.push(i),r.length>=2e3))break;return r}(n,t)){let t=Ue(e,l,r,i);t>o?[a,o,s]=[l,t,o]:t>s&&(s=t)}return{best:a,sure:!!a&&o>=Fe&&o-s>=Re}}(e,o,t,n,i),d=l?s:s&&s===i?i:null;return d?d===i?{state:"moved",element:i,range:null}:{state:"moved",element:d,range:null,alike:!0}:Ie}(e,r,t,!1!==n.fuzzy)}var Fe=.6,Re=.15,De=.15;function Ue(e,t,n,r){let i=t.textContent??"",o=[[.45,a(i)===e.fingerprint?1:ye(Be(i),e.snapshot)**2]];void 0!==e.name&&o.push([.25,_e(ce(t),e.name)?1:0]),e.heads?.length&&o.push([.2,ze(e.heads,pe(t,n))]);let s=void 0===e.y?void 0:fe(t,n);void 0!==e.y&&void 0!==s?o.push([.1,Math.max(0,1-Math.abs(s-e.y)/De)]):void 0===e.y&&o.push([.1,t===r?1:0]);let l=0,d=0;for(let[e,t]of o)l+=e*t,d+=e;return d?l/d:0}var Be=e=>e.replace(/\s+/g," ").trim().slice(0,200),_e=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();function ze(e,t){return e.length===t.length&&e.every((e,n)=>_e(e,t[n]))?1:t.length&&_e(e[e.length-1],t[t.length-1])?.6:0}function He(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;return n}function Ke(e,t){let n=0;for(;n<e.length&&n<t.length&&e[e.length-1-n]===t[t.length-1-n];)n++;return n}var Ge={A:"Link",BUTTON:"Button",P:"Paragraph",LI:"List item",UL:"List",OL:"List",IMG:"Image",TABLE:"Table",TD:"Cell",TH:"Cell",FIGURE:"Figure",SVG:"Graphic",CANVAS:"Graphic",LABEL:"Label",INPUT:"Field",SELECT:"Dropdown",TEXTAREA:"Field",SUMMARY:"Disclosure",BLOCKQUOTE:"Quote",SECTION:"Section",ARTICLE:"Article",H1:"Heading",H2:"Heading",H3:"Heading",H4:"Heading",H5:"Heading",H6:"Heading",switch:"Switch",tab:"Tab",checkbox:"Checkbox",radio:"Radio button",button:"Button",submit:"Button",link:"Link"};function Ze(e){let t=e.getAttribute("role")??("INPUT"===e.tagName?e.type:""),n=e.getAttribute("data-pipeup-label")||Object.hasOwn(Ge,t)&&Ge[t]||Ge[e.tagName.toUpperCase()];if(n)return n;if(Ve(e))return"Block";let r=e.getBoundingClientRect(),i=r.width/r.height;return i>1.4||i<.7?"Bar":"Shape"}var Je=e=>e.innerText||e.textContent||"";function Ve(e){let t=e,n=t.labels?.[0];return et(i(e.getAttribute("aria-label")??e.getAttribute("alt")??(n&&Je(n))??("SELECT"===e.tagName?t.selectedOptions[0]?.text:null)??(t.placeholder||Je(e))),40)}function We(e){let t=e.getAttribute("data-pipeup-label");if(t)return t;let n=e.getAttribute("data-pipeup-ask");if(n)return`Ask "${n}"`;let r=Ve(e);return r?`${Ze(e)} \xb7 ${r}`:Ze(e)}function Qe(e,t,n){let r=e.id??null,a=e.quote?.exact??null,o=e.point?`${Math.round(100*e.point.x)}% across, ${Math.round(100*e.point.y)}% down the element`:null,s=t.element;if("orphaned"===t.state||!s)return{where:`No longer on the page (${[be(e),`it read: "${e.snapshot}"`].filter(Boolean).join(", ")})`,element:null,id:r,quote:a,pin:o};let l=[],d=e.view?.slide;if(d){let e=s.closest("[data-pipeup-slide],.reveal .slides section")?.querySelector(Ye)?.textContent;l.push(`Slide ${d}`+(e?` "${et(i(e))}"`:""))}else{let t=function(e){return e?e.label||Object.entries(e).filter(([e,t])=>t&&"slide"!==e&&e!==Xe).map(([,e])=>e).join(" \xb7 "):""}(e.view);t&&l.push(t);let r=function(e,t){let n=e=>!1!==e.checkVisibility?.(),r=n(e),a=e=>i(e.textContent??"");for(let i=e;i&&i!==t;i=i.parentElement)for(let e=i.previousElementSibling;e;e=e.previousElementSibling){let t=e.matches(Ye)?e:[...e.querySelectorAll(Ye)].pop();if(t&&a(e)===a(t)&&(!r||n(t)))return t}return null}(s,n);r&&l.push(`Section "${et(i(r.textContent??""))}"`)}let u=We(s);return l.push(u),t.alike&&l.push(`Moved, not yet confirmed (${[be(e),`it read: "${e.snapshot}"`].filter(Boolean).join(", ")})`),{where:l.join(" \u203a "),element:u,id:r,within:!!r&&s.getAttribute("data-pipeup-id")!==r,quote:a,pin:o}}var Xe="pipeup-edition",Ye="h1,h2,h3";function et(e,t=60){return e.length>t?e.slice(0,t-1)+"\u2026":e}function tt(e,t){let n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";let r=Math.round(n/60);if(r<60)return`${r}m ago`;let i=Math.round(r/60);return i<48?`${i}h ago`:`${Math.round(i/24)}d ago`}function nt(e,t,n,r){return"ai"===t?ot(e,"## ",r,n):st(e)}function rt(e,t,n){let r=n.all?e:e.filter(e=>!e.thread.resolved);if("text"===t)return r.map(st).join("\n");let i=e.filter(e=>e.thread.resolved).length,a=e.length-i,o=function(e){let t=[...new Set(e.flatMap(({thread:e})=>[e.root,...e.root.replies].map(e=>at(f(e)))))],n=t.length>3?[...t.slice(0,2),t.length-2+" others"]:t;return n.length>1?`${n.slice(0,-1).join(", ")} and ${n.at(-1)}`:n[0]??""}(r),s=n.exportedAt.toUTCString(),l=[`# Comments on ${at(n.title)}`,"",`${a||"No"} open comment${1===a?"":"s"}${n.all&&i?` and ${i} resolved`:""}${o?` from ${o}`:""}, copied ${s.slice(5,16).replace(/^0/,"")}, ${s.slice(17,22)} UTC.`+(n.all||!i?"":` ${i} resolved comment${1===i?" is":"s are"} left out.`),"",`Page: ${at(n.url)}`,"",""].join("\n"),d=n.exportedAt.getTime();return l+r.map((e,t)=>ot(e,`## ${t+1}. `,d)).join("\n")+(r.length?"\n---\n\nFor an AI assistant: work through the open comments in order and say what you changed, or why you didn't. Each one's last line gives the thread to answer and the element's data-pipeup-id in the page's HTML. Answer in the thread with Pipeup (its pipeup-apply skill says how) and mark it addressed; never resolve it, the author does.\n":"")}function it(e){return e.reactions.map(e=>`${e.emoji} ${e.by.length} (${e.by.map(e=>at(f(e))).join(", ")})`).join(" \xb7 ")}function at(e){return e.replace(/\s+/g," ").trim()}function ot(e,t,n,r){let{thread:i,location:a}=e,o=[t+at(a.where),""];r&&o.push(`Page: ${at(r)}`,""),a.quote&&o.push(`On the words "${at(a.quote)}".`,""),a.pin&&o.push(`Pinned ${at(a.pin)}.`,""),o.push(`**${at(f(i.root))}** (${tt(i.root.at,n)}): ${lt(i.root," ")}`),i.root.reactions.length&&o.push(`Reactions: ${it(i.root)}`);for(let e of i.root.replies)o.push(`- **${at(f(e))}** (${tt(e.at,n)}): ${lt(e," ")}`),e.reactions.length&&o.push(` - Reactions: ${it(e)}`);i.addressed&&!i.resolved&&o.push("",`**${at(f(i.addressed))}** marked it addressed (${tt(i.addressed.at,n)}): ${at(i.addressed.text)}`);let s=a.id?` \xb7 ${a.within?"in":"on"} \`data-pipeup-id="${at(a.id.replace(/`/g,""))}"\``:"";return o.push("",`${i.resolved?"Resolved":i.addressed?"Open, addressed":"Open"} \xb7 thread \`${i.id}\`${s}`),o.join("\n")+"\n"}function st(e){let{thread:t,location:n}=e,r=[at(n.where)+(n.quote?`, on the text "${at(n.quote)}"`:""),`${at(f(t.root))}: ${lt(t.root," ")}`];t.root.reactions.length&&r.push(` Reactions: ${it(t.root)}`);for(let e of t.root.replies)r.push(` ${at(f(e))}: ${lt(e," ")}`),e.reactions.length&&r.push(` Reactions: ${it(e)}`);return r.join("\n")+"\n"}function lt(e,t){return e.deleted?"(deleted)":e.text.replace(/\r\n|\r|\n/g,"\n"+t)+(e.edited?" (edited)":"")}function dt(e,t){return{markdown:rt(e,"ai",t),threads:e.filter(e=>t.all||!e.thread.resolved).map(({thread:e,location:t})=>{let n={id:e.id,state:e.resolved?"resolved":e.addressed?"addressed":"open",where:t.where,comments:[e.root,...e.root.replies].map(e=>({id:e.id,by:f(e),agent:g(e.name),at:new Date(e.at).toISOString(),text:e.deleted?"":e.text,...e.reactions.length?{reactions:e.reactions.map(e=>({emoji:e.emoji,by:e.by.map(f)}))}:{}}))};return t.id&&(n.element=t.id),t.quote&&(n.quote=t.quote),t.pin&&(n.pin=t.pin),e.addressed&&!e.resolved&&(n.addressed={note:e.addressed.text,by:f(e.addressed)}),n})}}var ut="1.0.0",ht="2026-11-10";export{m as AI_NAME,u as ANIMALS,ht as BUILT,h as COLOURS,ae as DEFAULT_PROFILE_NAME,se as IndexedDbStore,ie as MemoryStore,ee as PipeupDocument,Y as UnsavedChangeError,ut as VERSION,dt as agentComments,y as agentName,p as animalName,B as checkOp,H as computeOpId,rt as copyAll,nt as copyThread,l as createIdentity,qe as describeElement,Oe as describeRange,tt as formatAgo,g as isAiName,w as isPasted,We as labelOf,oe as loadOrCreateProfile,Qe as locate,f as nameOf,Z as newDocumentAttribute,J as parseDocumentAttribute,Q as readFeedbackFile,Le as resolveAnchor,T as signOp};