@snagset/server 0.1.67 → 0.1.68

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.
@@ -0,0 +1,37 @@
1
+ -- ───────────────────────────────────────
2
+ -- attachments.storage_key stops being UNIQUE: two pictures may be the same
3
+ -- file.
4
+ --
5
+ -- The key is the content's hash (storage/bucket.ts), so the same bytes
6
+ -- uploaded twice to one site have the same key, and the bucket holds them
7
+ -- once. UNIQUE on the column turned that into "one ROW per file": the second
8
+ -- upload inserted nothing and was answered with the first upload's id. That
9
+ -- row was already bound to the first comment, the thread create binds only
10
+ -- pending rows, and so the second comment had no picture, although its
11
+ -- upload had answered 201. A reviewer leaving two comments on a page that
12
+ -- did not change between them is exactly this, every time. The same
13
+ -- happened for good once a row was deleted or reaped: its key stayed taken,
14
+ -- and no later comment could carry those bytes.
15
+ --
16
+ -- From here a row is one picture, on one comment, and several rows may name
17
+ -- one file. What the constraint used to guarantee by accident, that deleting
18
+ -- a row's file cannot take another row's picture with it, is now the
19
+ -- reaper's to check: it takes a file out of the bucket only when no other
20
+ -- row that is still pending or bound names it (jobs/reaper.ts). The index is
21
+ -- that question, and it replaces the one the constraint owned.
22
+ --
23
+ -- AN OLDER SERVER STILL RUNNING BESIDE THIS SCHEMA writes its upload with
24
+ -- ON CONFLICT (storage_key), which needs the constraint and fails without
25
+ -- it. For the length of a deploy's overlap an upload that reaches the old
26
+ -- process is a 500; the widget sends the comment without its picture, as it
27
+ -- does for any failed upload. Nothing is corrupted by it.
28
+ --
29
+ -- DDL only: no rows are read or written by this file, so no maintenance
30
+ -- claim. Dropping the constraint is a catalogue change. The plain CREATE
31
+ -- INDEX inside the runner's transaction blocks writes to attachments while
32
+ -- it builds, which on the tables this has met is well under a second.
33
+ --
34
+ -- Under D71, 05 §3 loses the UNIQUE and gains the index in the same commit.
35
+ ALTER TABLE attachments DROP CONSTRAINT attachments_storage_key_key;
36
+
37
+ CREATE INDEX attachments_storage_key_idx ON attachments (storage_key);
@@ -1,3 +1,4 @@
1
+ import { fileHolding } from "../storage/shared.js";
1
2
  /**
2
3
  * The reaper, cut to the three jobs L1 needs.
3
4
  *
@@ -127,6 +128,23 @@ export const expireRows = {
127
128
  * the row being marked orphaned while the bytes stay — so the delete is
128
129
  * attempted first and the row is updated after.
129
130
  *
131
+ * A ROW THE UPLOAD ROUTE GAVE UP is taken at once, whatever its age. When the
132
+ * bucket refuses an upload's write, the route marks the row deleted_at and
133
+ * released_at, takes its bytes off the count and leaves it pending
134
+ * (routes/attachments.ts): the row may be the last to name a file a deleted
135
+ * comment left behind, and whether it is can only be asked here, under the
136
+ * key's lock. For such a row a refused delete is NOT swallowed. It stays as
137
+ * it is for the next tick, because the row exists for this delete and
138
+ * nothing would come back for the object after it; a key that is not there
139
+ * is not a refusal, so a row cannot get stuck on a file that never arrived.
140
+ * Its bytes are not taken off a second time.
141
+ *
142
+ * THE FILE MAY NOT BE THIS ROW'S ALONE. Keys are content hashes, so the same
143
+ * bytes uploaded again are another row naming the same object, and that row
144
+ * may be on a comment that was sent. The delete is attempted only when no
145
+ * other pending or bound row names the key (storage/shared.ts); the row is
146
+ * written off and its bytes uncounted either way, since each row is counted.
147
+ *
130
148
  * With no bucket configured the job does nothing and says so. That is the
131
149
  * annotation-mode deployment, where no blob was ever written and
132
150
  * there is nothing to reap.
@@ -139,11 +157,12 @@ export function reapPendingAttachments(bucket) {
139
157
  const imageCutoff = new Date(now.getTime() - 2 * 60 * 60_000);
140
158
  const fileCutoff = new Date(now.getTime() - 15 * 60_000);
141
159
  const rows = await sql `
142
- SELECT id, project_id, storage_key, bytes, kind
160
+ SELECT id, project_id, storage_key, bytes, kind, (deleted_at IS NOT NULL) AS given_up, released_at
143
161
  FROM attachments
144
162
  WHERE state = 'pending'
145
163
  AND ((kind = 'file' AND created_at < ${fileCutoff})
146
- OR (kind <> 'file' AND created_at < ${imageCutoff}))
164
+ OR (kind <> 'file' AND created_at < ${imageCutoff})
165
+ OR deleted_at IS NOT NULL)
147
166
  ORDER BY created_at
148
167
  LIMIT ${BATCH}
149
168
  `;
@@ -154,23 +173,39 @@ export function reapPendingAttachments(bucket) {
154
173
  }
155
174
  let reaped = 0;
156
175
  for (const row of rows) {
157
- try {
158
- await bucket.del(row.storage_key);
159
- }
160
- catch (e) {
161
- // Named, not silent: a bucket that refuses every delete is a bill
162
- // that grows, and the only place it shows up is here.
163
- log(`jobs: reap-pending-attachments: delete ${row.storage_key} failed: ${String(e)}`);
176
+ // The file goes only with the last row that names it: the same bytes
177
+ // may be on a comment that WAS sent (storage/shared.ts). And a row
178
+ // whose bytes are being uploaded again this instant waits a tick.
179
+ const holding = await fileHolding(sql, row);
180
+ if (holding === "busy")
181
+ continue;
182
+ if (holding === "last") {
183
+ try {
184
+ await bucket.del(row.storage_key);
185
+ }
186
+ catch (e) {
187
+ // Named, not silent: a bucket that refuses every delete is a bill
188
+ // that grows, and the only place it shows up is here.
189
+ log(`jobs: reap-pending-attachments: delete ${row.storage_key} failed: ${String(e)}`);
190
+ // A given-up row is here FOR this delete, and may be the last to
191
+ // name a file that is known to be there. It waits for a bucket
192
+ // that answers, as a deleted picture does in the job below.
193
+ if (row.given_up)
194
+ continue;
195
+ }
164
196
  }
165
197
  await sql `UPDATE attachments SET state = 'orphaned' WHERE id = ${row.id}`;
166
198
  // The counter. Decremented per row rather than in one statement at
167
199
  // the end so a mid-batch failure cannot leave the counter describing
168
- // rows that were already reaped.
169
- await sql `
170
- UPDATE projects
171
- SET storage_bytes_used = GREATEST(0, storage_bytes_used - ${Number(row.bytes)})
172
- WHERE id = ${row.project_id}
173
- `;
200
+ // rows that were already reaped. Not for a row whose bytes the upload
201
+ // route already gave back when it gave the row up (released_at).
202
+ if (!row.released_at) {
203
+ await sql `
204
+ UPDATE projects
205
+ SET storage_bytes_used = GREATEST(0, storage_bytes_used - ${Number(row.bytes)})
206
+ WHERE id = ${row.project_id}
207
+ `;
208
+ }
174
209
  reaped++;
175
210
  }
176
211
  return {
@@ -228,6 +263,12 @@ export const DELETED_SITE_GRACE_MS = 30 * 24 * 60 * 60_000;
228
263
  * get stuck on a blob that is already gone. A refused row is not retried
229
264
  * inside the same run (`more` is false unless the whole batch went).
230
265
  *
266
+ * A FILE SHARED WITH A LIVE PICTURE STAYS. Two comments with the same
267
+ * screenshot are two rows naming one object (keys are content hashes). The
268
+ * deleted one's row is marked `orphaned` here like any other, and the object
269
+ * is deleted only when no other pending or bound row names it
270
+ * (storage/shared.ts), so it leaves with whichever row is collected last.
271
+ *
231
272
  * With no bucket the job does nothing and says how many are waiting: a studio
232
273
  * that disconnected its bucket still has the rows, and reconnecting it lets
233
274
  * the next tick finish.
@@ -263,12 +304,21 @@ export function collectDeletedAttachments(bucket) {
263
304
  }
264
305
  let collected = 0;
265
306
  for (const row of rows) {
266
- try {
267
- await bucket.del(row.storage_key);
268
- }
269
- catch (e) {
270
- log(`jobs: collect-deleted-attachments: delete ${row.storage_key} failed: ${String(e)}`);
307
+ // The file goes only with the last row that names it. A row that is
308
+ // not the last is marked all the same: it is done with, and the one
309
+ // that IS the last finds no other holder when its turn comes. A row
310
+ // whose bytes are being uploaded again this instant waits a tick.
311
+ const holding = await fileHolding(sql, row);
312
+ if (holding === "busy")
271
313
  continue;
314
+ if (holding === "last") {
315
+ try {
316
+ await bucket.del(row.storage_key);
317
+ }
318
+ catch (e) {
319
+ log(`jobs: collect-deleted-attachments: delete ${row.storage_key} failed: ${String(e)}`);
320
+ continue;
321
+ }
272
322
  }
273
323
  // What goes with the state, by the table's CHECKs: only a bound row
274
324
  // has `bound_at`, and only a bound row names a thread or a comment.
@@ -303,7 +353,7 @@ export function collectDeletedAttachments(bucket) {
303
353
  return {
304
354
  did: collected,
305
355
  more: rows.length === BATCH && collected === rows.length,
306
- ...(collected < rows.length ? { note: `${rows.length - collected} could not be deleted from the bucket and will be tried again` } : {}),
356
+ ...(collected < rows.length ? { note: `${rows.length - collected} could not be taken out of the bucket yet and will be tried again` } : {}),
307
357
  };
308
358
  },
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AAE,CAAC,CAAC,CAAC,EAAE,CAAC;aAC5I,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AAED;qEACqE;AACrE,MAAM,UAAU,MAAM,CAAC,MAAqB;IAC1C,OAAO,CAAC,kBAAkB,EAAE,UAAU,EAAE,sBAAsB,CAAC,MAAM,CAAC,EAAE,yBAAyB,CAAC,MAAM,CAAC,CAAC,CAAC;AAC7G,CAAC"}
package/dist/plan.js CHANGED
@@ -47,7 +47,7 @@ export function limitsSource(sql, keys, resolver) {
47
47
  return value;
48
48
  };
49
49
  }
50
- /** The counts the numbers are measured against (an archived site, keeps its pictures but not its place under the site cap), under the org's claim. Storage is bucket bytes summed over the studio's sites (L4's per-project counters). */
50
+ /** The counts the numbers are measured against (an archived site, keeps its pictures but not its place under the site cap), under the org's claim. Storage is the bytes of the studio's pictures summed over its sites (L4's per-project counters); each picture is counted, and identical ones share a file in the bucket. */
51
51
  export async function usage(tx, orgId) {
52
52
  const [p] = await tx `SELECT (count(*) FILTER (WHERE archived_at IS NULL))::int AS n, COALESCE(sum(storage_bytes_used), 0)::float8 AS bytes FROM projects WHERE org_id = ${orgId}::uuid AND deleted_at IS NULL`;
53
53
  const [m] = await tx `SELECT count(*)::int AS n FROM memberships WHERE org_id = ${orgId}::uuid`;
package/dist/plan.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"plan.js","sourceRoot":"","sources":["../src/plan.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAoCrD,MAAM,CAAC,MAAM,SAAS,GAAe,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC;AAYlI,MAAM,GAAG,GAAG,QAAQ,CAAC;AACrB,MAAM,MAAM,GAAG,MAAM,CAAC;AACtB,MAAM,KAAK,GAAG,IAAI,GAAG,EAA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G,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF;AAED,MAAM,IAAI,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,kBAAkB,EAAE,WAAW,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,EAAW,CAAC;AAE1J;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAAC,CAAU,EAAE,CAAe;IAC1D,MAAM,OAAO,GACX,CAAC,CAAC,QAAQ,KAAK,UAAU,IAAI,CAAC,CAAC,QAAQ,KAAK,SAAS;QACnD,CAAC,CAAC,6BAA6B,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC,IAAI,4CAA4C;QAC3H,CAAC,CAAC,uCAAuC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,6BAA6B,CAAC;IAC3F,OAAO,CAAC,CAAC,IAAI,CACX,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,oBAAoB,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,EAAE,EAClJ,GAAG,CACJ,CAAC;AACJ,CAAC"}
@@ -4,6 +4,7 @@ import { HTTP_HEADER, ID_PREFIX } from "../vendor/types/names.js";
4
4
  import { getBucket, storageStatus } from "../storage/settings.js";
5
5
  import { storageKeyFor } from "../storage/bucket.js";
6
6
  import { inOrg, maintenance } from "../db/scope.js";
7
+ import { holdFileForUpload } from "../storage/shared.js";
7
8
  import { usage } from "../plan.js";
8
9
  function fail(c, status, code, message) {
9
10
  return c.json({ error: { code, message, requestId: c.get("requestId") } }, status);
@@ -70,55 +71,106 @@ export function attachmentRoutes(deps) {
70
71
  return fail(c, 413, "storage_quota_exceeded", "This studio has used the picture storage its plan includes. Existing comments are unaffected; a plan with more storage lifts it.");
71
72
  }
72
73
  }
73
- // The same digest the storage key is derived from — stored so integrity can
74
- // be checked without re-reading the object, and so a duplicate upload is
75
- // recognisable by content rather than by key alone.
74
+ // The same digest the storage key is derived from, stored so integrity can
75
+ // be checked without re-reading the object.
76
76
  const digest = createHash("sha256").update(body).digest();
77
77
  const key = storageKeyFor(project.id, body, ext);
78
78
  const width = Number(c.req.header(HTTP_HEADER.attachmentWidth)) || null;
79
79
  const height = Number(c.req.header(HTTP_HEADER.attachmentHeight)) || null;
80
- try {
81
- await bucket.put(key, body, contentType);
82
- }
83
- catch (e) {
84
- // The bucket is the operator's, so its failure is theirs to see —
85
- // and the reviewer's comment must survive it (the widget falls back
86
- // to sending the thread without a picture).
87
- console.error(`attachment upload failed [${c.get("requestId")}]`, e);
88
- return fail(c, 502, "storage_unavailable", "The picture could not be stored. Your comment can still be sent.");
89
- }
80
+ /*
81
+ * EVERY UPLOAD IS ITS OWN ROW, whatever its bytes.
82
+ *
83
+ * The key is the content's hash, so two reviewers screenshotting the
84
+ * identical viewport, or one reviewer leaving two comments on a page that
85
+ * did not change, send the same key, and the bucket holds one object.
86
+ * This used to hold one ROW as well: the column was UNIQUE, the insert
87
+ * was ON CONFLICT DO NOTHING, and the second upload was answered with the
88
+ * first one's id. That row was already bound to the first comment, the
89
+ * thread create binds only pending rows, and the second comment was left
90
+ * with no picture after a 201. Migration 0020 took the UNIQUE away. A row
91
+ * is one picture on one comment; the file is shared, and it is the
92
+ * reaper that asks whether anyone still holds it before it deletes one
93
+ * (storage/shared.ts).
94
+ *
95
+ * EACH ROW IS COUNTED. Two comments with the same screenshot take its
96
+ * bytes off the site's storage twice, although the bucket holds them
97
+ * once. The counter is then the plain sum of the pictures a site shows,
98
+ * and every path that gives bytes back (a deleted thread, a reaped
99
+ * upload) gives back its own row's and has no other row to ask about.
100
+ *
101
+ * THE ROW BEFORE THE OBJECT, and that order is the shared file's safety,
102
+ * not a preference: see the lock in storage/shared.ts. A row whose
103
+ * object never arrives is given up below and is the reaper's on its
104
+ * next tick, or, if this process dies in between, is a pending row like
105
+ * any other and the reaper's in two hours.
106
+ *
107
+ * 'pending', and the schema is what taught me that. 05 section 3.6's
108
+ * CHECKs say state='bound' requires bound_at AND exactly one of thread_id
109
+ * or comment_id, and at upload time the thread does not exist yet,
110
+ * because the widget uploads the picture and THEN creates the thread so
111
+ * the attachment ref can ride the same write. So a row is born pending
112
+ * and is bound by the thread create (05 section 6.6: v1's wire binds
113
+ * attachments relationally after the fact).
114
+ */
90
115
  const id = randomUUID();
91
- await sql.begin(async (tx) => {
92
- await tx `SELECT set_config('app.org_id', ${project.org_id}, true)`;
116
+ await inOrg(sql, project.org_id, async (tx) => {
117
+ await holdFileForUpload(tx, key);
93
118
  await tx `
94
119
  INSERT INTO attachments (id, org_id, project_id, kind, state, storage_key, storage_backend,
95
120
  content_type, bytes, width, height, sha256, uploaded_by)
96
- -- 'pending', and the schema is what taught me that. The CHECKs say
97
- -- state='bound' requires bound_at AND exactly one of thread_id or
98
- -- comment_id -- and at upload time the thread does not exist yet,
99
- -- because the widget uploads the picture and THEN creates the thread
100
- -- so the attachment ref can ride the same write. So a row is born
101
- -- pending and is bound by the thread create (v1's wire binds
102
- -- attachments relationally after the fact).
103
121
  VALUES (${id}, ${project.org_id}, ${project.id}, ${kind}::snag_attachment_kind, 'pending',
104
122
  ${key}, 's3', ${contentType}, ${body.length}, ${width}, ${height},
105
123
  ${digest}, ${session.sub})
106
- ON CONFLICT (storage_key) DO NOTHING
107
124
  `;
108
- // Two reviewers screenshotting the identical viewport produce the same
109
- // hash and therefore the same key — one object, and the byte count is
110
- // only charged once.
111
125
  await tx `
112
126
  UPDATE projects SET storage_bytes_used = storage_bytes_used + ${body.length}
113
127
  WHERE id = ${project.id}
114
- AND EXISTS (SELECT 1 FROM attachments WHERE id = ${id})
115
128
  `;
116
129
  });
117
- const [row] = await maintenance(sql, (tx) => tx `
118
- SELECT id FROM attachments WHERE storage_key = ${key}
119
- `);
130
+ try {
131
+ await bucket.put(key, body, contentType);
132
+ }
133
+ catch (e) {
134
+ // The bucket is the operator's, so its failure is theirs to see, and
135
+ // the reviewer's comment must survive it (the widget falls back to
136
+ // sending the thread without a picture).
137
+ console.error(`attachment upload failed [${c.get("requestId")}]`, e);
138
+ /*
139
+ * The row is given up, and its bytes come off the count now. It is
140
+ * NOT marked orphaned here, and that is the point. An orphaned row
141
+ * holds no file, and a row may stop holding one only when somebody has
142
+ * asked, under the key's lock, whether it was the last, and deleted the
143
+ * object if it was (storage/shared.ts). This row may be the last: the
144
+ * same bytes can be in the bucket from a comment since deleted, whose
145
+ * own row the reaper finished a moment ago BECAUSE this one named the
146
+ * file. Marking this one orphaned would leave that object with nobody
147
+ * to delete it, for good.
148
+ *
149
+ * So it is marked the way a deleted picture is, deleted_at and
150
+ * released_at, and left pending: it cannot be bound or served, it is
151
+ * not counted, it still holds, and reap-pending-attachments takes a
152
+ * given-up row on its next tick whatever its age, asks the question
153
+ * and deletes. No lock is taken here and nothing is asked of a bucket
154
+ * that has just said no.
155
+ *
156
+ * If this write fails too, the row is an ordinary pending one, counted
157
+ * until the same reaper reaches it in two hours.
158
+ */
159
+ await inOrg(sql, project.org_id, (tx) => tx `
160
+ WITH gone AS (
161
+ UPDATE attachments SET deleted_at = now(), released_at = now()
162
+ WHERE id = ${id} AND state = 'pending' AND deleted_at IS NULL
163
+ RETURNING project_id, bytes
164
+ )
165
+ UPDATE projects p
166
+ SET storage_bytes_used = GREATEST(0, p.storage_bytes_used - gone.bytes)
167
+ FROM gone
168
+ WHERE p.id = gone.project_id
169
+ `).catch((undo) => console.error(`attachment upload: could not give up ${id} [${c.get("requestId")}]`, undo));
170
+ return fail(c, 502, "storage_unavailable", "The picture could not be stored. Your comment can still be sent.");
171
+ }
120
172
  return c.json({
121
- id: ID_PREFIX.attachment + (row?.id ?? id),
173
+ id: ID_PREFIX.attachment + id,
122
174
  kind,
123
175
  contentType,
124
176
  byteSize: body.length,
@@ -139,8 +191,12 @@ export function attachmentRoutes(deps) {
139
191
  const id = wire.startsWith(ID_PREFIX.attachment) ? wire.slice(ID_PREFIX.attachment.length) : wire;
140
192
  const [row] = await maintenance(sql, (tx) => tx `
141
193
  SELECT storage_key, content_type, project_id FROM attachments
142
- WHERE id = ${id} AND deleted_at IS NULL
194
+ WHERE id = ${id} AND deleted_at IS NULL AND state <> 'orphaned'
143
195
  `);
196
+ // Not an orphaned row's either. That used to follow from the bucket: a
197
+ // reaped upload's object was gone, so the read below found nothing. Since
198
+ // a file can be shared (storage/shared.ts) the object may still be there
199
+ // for another comment, and a reaped row would go on serving it.
144
200
  if (!row)
145
201
  return fail(c, 404, "not_found", "No such attachment.");
146
202
  const bucket = await getBucket(sql, keys);
@@ -1 +1 @@
1
- {"version":3,"file":"attachments.js","sourceRoot":"","sources":["../../src/routes/attachments.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAgB,MAAM,MAAM,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAI9D,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,KAAK,EAAqB,MAAM,YAAY,CAAC;AAiCtD,SAAS,IAAI,CAAC,CAAM,EAAE,MAAc,EAAE,IAAY,EAAE,OAAe;IACjE,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,CAA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ACjD,CAAC,CAAC,CAAC;IAEH,OAAO,GAAG,CAAC;AACb,CAAC;AAED,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,GAAiB,EACjB,IAAa,EACb,MAA0C,OAAO,CAAC,GAAG;IAErD,MAAM,EAAE,GAAG,MAAM,aAAa,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;IAC/C,OAAO,EAAE,WAAW,EAAE,EAAE,CAAC,SAAS,EAAE,OAAO,EAAE,EAAE,CAAC,SAAS,EAAE,CAAC;AAC9D,CAAC"}
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Several pictures, one file.
3
+ *
4
+ * The storage key is the content's hash under the site's id
5
+ * (`storageKeyFor`), so the same bytes uploaded twice to one site are one
6
+ * object in the bucket. Each upload is still its own row: its own id, its
7
+ * own comment, its own delete. So a file can have several rows naming it,
8
+ * and the one thing that must never happen is the file leaving the bucket
9
+ * while a row that is still shown names it.
10
+ *
11
+ * Two rules keep that, and both live here so that the upload and the reaper
12
+ * cannot come to mean different things by them:
13
+ *
14
+ * · WHO HOLDS A FILE. A row that is `pending` or `bound`. An `orphaned`
15
+ * row is one the reaper has finished with; it names a key and holds
16
+ * nothing. A `bound` row with `deleted_at` set still holds, until the
17
+ * reaper reaches it: it is the reaper's own turn at that row that lets
18
+ * go, so of two deleted rows naming one file the second one collected
19
+ * is the one that deletes it. The same goes for a `pending` row the
20
+ * upload route gave up when the bucket refused its write. ONLY THE
21
+ * REAPER MAKES A ROW `orphaned`, and only after `fileHolding` below:
22
+ * a row marked orphaned anywhere else could be the last to name a file,
23
+ * and no job comes back for an orphaned row.
24
+ *
25
+ * · THE LOCK. "Nobody else holds it" and "delete it" are two steps with a
26
+ * network call between them, and an upload of the same bytes can land in
27
+ * the gap: the reaper finds no other holder, the upload writes the object
28
+ * and its row, the reaper deletes the object. The new comment then has a
29
+ * row and no picture, for good. An advisory lock on the key closes the
30
+ * gap. The reaper takes it exclusively before it looks and keeps it until
31
+ * its pass commits. The upload takes it shared, in the transaction that
32
+ * inserts its row, and writes the object only after that transaction has
33
+ * committed. So either the row is there when the reaper looks, and the
34
+ * file stays; or the reaper is done before the row exists, and the
35
+ * object is written after the delete, not before it.
36
+ *
37
+ * · WHO WAITS. The upload waits for the lock; the reaper only TRIES it,
38
+ * and leaves the row for its next tick when an upload has it. That is
39
+ * not politeness. The reaper's pass is one transaction that by then may
40
+ * hold the site's `projects` row (it takes bytes off the counter as it
41
+ * goes), and the upload, holding the key, is about to wait for that same
42
+ * row to add its own. A reaper that waited for the key there would be a
43
+ * deadlock, and Postgres would settle it by failing one of the two. A
44
+ * file whose bytes are being uploaded this instant is in no hurry to be
45
+ * deleted.
46
+ *
47
+ * Transaction-scoped, for the reason `migrate.ts` gives: a pooler in
48
+ * transaction mode hands out a backend per transaction, and a session lock
49
+ * taken on one and released on another is held by nobody. Shared between
50
+ * uploads, so two reviewers sending the same picture never wait on each
51
+ * other. An upload waits only on a reaper pass that is, at that moment,
52
+ * collecting a file with exactly its bytes, and for no longer than the rest
53
+ * of that pass.
54
+ *
55
+ * 0x6364424C is the ASCII for "cdBL", picked as `JOB_LOCK_NAMESPACE` picks
56
+ * "cdJB": the number means nothing, and every instance computes the same
57
+ * one. `hashtext` runs in Postgres on both sides, so the two agree by
58
+ * construction; a collision between two keys costs a wait and nothing else.
59
+ */
60
+ export const FILE_LOCK_NAMESPACE = 0x6364424c;
61
+ /** The upload's side: hold the key while this transaction inserts a row that names it. */
62
+ export async function holdFileForUpload(tx, storageKey) {
63
+ await tx `SELECT pg_advisory_xact_lock_shared(${FILE_LOCK_NAMESPACE}, hashtext(${storageKey}))`;
64
+ }
65
+ /**
66
+ * The reaper's side: may this row's file leave the bucket?
67
+ *
68
+ * "last" no other row that is pending or bound names the key: delete it.
69
+ * "shared" another row still holds it: leave the file, finish the row.
70
+ * "busy" an upload of these bytes is in flight: leave the row as it is
71
+ * and ask again on the next tick.
72
+ *
73
+ * Takes the key's lock first and keeps it to the end of the caller's
74
+ * transaction, which is what makes "last" still true when the delete that
75
+ * follows reaches the bucket. So it is for a caller already inside a
76
+ * transaction, as every job is (jobs/index.ts); on a bare connection the
77
+ * lock would be gone before the answer came back.
78
+ *
79
+ * Two statements on purpose. A statement's snapshot is taken when it starts,
80
+ * so one that locked and looked in the same breath could miss the row of an
81
+ * upload that committed in between.
82
+ */
83
+ export async function fileHolding(tx, row) {
84
+ const [lock] = await tx `
85
+ SELECT pg_try_advisory_xact_lock(${FILE_LOCK_NAMESPACE}, hashtext(${row.storage_key})) AS ok
86
+ `;
87
+ if (!lock?.ok)
88
+ return "busy";
89
+ const [other] = await tx `
90
+ SELECT id FROM attachments
91
+ WHERE storage_key = ${row.storage_key} AND id <> ${row.id} AND state <> 'orphaned'
92
+ LIMIT 1
93
+ `;
94
+ return other ? "shared" : "last";
95
+ }
96
+ //# sourceMappingURL=shared.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.js","sourceRoot":"","sources":["../../src/storage/shared.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0DG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,UAAU,CAAC;AAE9C,0FAA0F;AAC1F,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,EAA2B,EAAE,UAAkB;IACrF,MAAM,EAAE,CAAA,uCAAuC,mBAAmB,cAAc,UAAU,IAAI,CAAC;AACjG,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,EAA0C,EAC1C,GAAwC;IAExC,MAAM,CAAC,IAAI,CAAC,GAAG,MAAM,EAAE,CAAmB;uCACL,mBAAmB,cAAc,GAAG,CAAC,WAAW;GACpF,CAAC;IACF,IAAI,CAAC,IAAI,EAAE,EAAE;QAAE,OAAO,MAAM,CAAC;IAC7B,MAAM,CAAC,KAAK,CAAC,GAAG,MAAM,EAAE,CAAkB;;2BAEjB,GAAG,CAAC,WAAW,cAAc,GAAG,CAAC,EAAE;;GAE3D,CAAC;IACF,OAAO,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC;AACnC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snagset/server",
3
- "version": "0.1.67",
3
+ "version": "0.1.68",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "The Snagset server: API, dashboard and widget in one package. Node and Postgres, or Vercel.",
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "0.1.67",
3
- "cv": "0.1.67+74eb73"
2
+ "version": "0.1.68",
3
+ "cv": "0.1.68+e77816"
4
4
  }
@@ -2,4 +2,4 @@
2
2
  `).slice(0,10).join(`
3
3
  `):"";return(o?`${r}
4
4
  ${o}`:r).slice(0,1024)}return t.nodeType!==void 0?typeof t.tagName=="string"?`<${t.tagName.toLowerCase()}>`:"[Node]":Array.isArray(e)?`[Array(${e.length})]`:`[${Object.prototype.toString.call(e).slice(8,-1)}]`}catch{return"[unreadable]"}}function K(e,t,r){const o=[];let n=0,c=0,i=0,a=0,s=null,d=0;const m=(f,p,u)=>{if(!(d>=3))try{const w=Date.now();if(w-c>250&&(a&&(o.push([w,"system","info",`${a} records suppressed (flood guard)`]),a=0),c=w,i=0),++i>50){a++;return}const h=[w,f,p,u];if(s){s(h);return}for(o.push(h);o.length>100;)o.shift(),n++;d=0}catch{d++}};m("navigation","info",e.location.href),e.addEventListener("error",f=>{try{const p=f.target;if(p&&p!==e&&typeof p.tagName=="string"){m("error","error",`Failed to load <${p.tagName.toLowerCase()}> ${p.src??p.href??""}`);return}const u=f,w=`${u.message??"Script error"} (${u.filename??""}:${u.lineno??0}:${u.colno??0})`,h=u.error?`
5
- ${E(u.error)}`:"";m("error","error",`${w}${h}`)}catch{d++}},{capture:!0,signal:r}),e.addEventListener("unhandledrejection",f=>{try{m("error","error",`Unhandled rejection: ${E(f.reason)}`)}catch{d++}},{signal:r});const l=[];if(t.early){let f=!1;for(const p of["error","warn"])l.push(D(e.console,p,u=>function(...w){const h=u.apply(this,w);return f||(f=!0,m("console",p,w.map(E).join(" ").slice(0,4096)),f=!1),h}))}const b=()=>{for(const f of l)f();l.length=0,s=null,o.length=0};return r.addEventListener("abort",b,{once:!0}),{drain(f){const u={records:o.slice(),dropped:n};return o.length=0,n=0,s=f,u},destroy:b}}const S="0.1.67+74eb73",A=Y();function Y(){try{const e=location.hash.slice(1);if(!e.includes($("k")))return;const t=new URLSearchParams(e),r=t.get($("k"))??void 0;if(!r)return;t.delete($("k"));const o=t.toString(),n=location.pathname+location.search+(o?`#${o}`:"");return history.replaceState(history.state,"",n),r}catch{return}}const q=["site","host","disabled","env","mode","hotkey","allowAutomation","assetBase","theme","autoMount","storage"];function W(e){const t=e[g.config];return t&&typeof t=="object"?t:void 0}function V(e,t){const r={};for(const o of q){const n=t?.[o];(typeof n=="string"||typeof n=="number")&&(r[o]=String(n));const c=e?.getAttribute(y(o));c!=null&&(r[o]=c)}return r}function H(e,t){const r=new URL(e,t);return r.searchParams.set("cv",S),r.href}function J(e,t){const r=e.assetBase??window[g.assetBase];if(r)return new URL(r,location.href).href.replace(/\/?$/,"/");const o=t?.src;return o?new URL(".",o).href:new URL(".",location.href).href}function P(){const e=new Map,t=(r,o)=>void e.get(r)?.delete(o);return{on(r,o){let n=e.get(r);return n||e.set(r,n=new Set),n.add(o),()=>t(r,o)},off:t,emit(r,o){const n=e.get(r);if(n)for(const c of[...n])try{c(o)}catch(i){console.error(`[${v}] listener for "${r}" threw`,i)}document.dispatchEvent(new CustomEvent(`${O}${r}`,{detail:o,bubbles:!1,composed:!1}))}}}function X(e,t,r){let o=!1;const n=()=>{o||(o=!0,console.info(`[${v}] not activated: ${r}`))},c=P(),i={version:S,config:e,assetBase:t,state:"inert",pointerMode:"browse",activated:!1,init:()=>(n(),Promise.resolve(i)),activate:()=>(n(),Promise.resolve(null)),deactivate:()=>{},destroy:()=>{},setMode:n,setRoute:n,open:()=>(n(),Promise.resolve({ok:!1,reason:"inert"})),resync:()=>{},close:()=>{},on:c.on,off:c.off};return i}function C(e){const t=window.requestIdleCallback;typeof t=="function"?t(e,{timeout:2e3}):setTimeout(e,1)}function j(e){if(document.readyState==="complete"){C(e);return}window.addEventListener("load",()=>requestAnimationFrame(()=>requestAnimationFrame(()=>C(e))),{once:!0})}function z(e,t,r){t.hotkey!=="off"&&document.addEventListener("keydown",o=>{if(!(!o.altKey||o.ctrlKey||o.metaKey)&&o.code==="KeyC"){if(o.preventDefault(),e.state==="active"){e.setMode(e.pointerMode==="add"?"comments":"add");return}e.activate().catch(()=>{})}},{capture:!0,signal:r})}function Q(e,t,r,o){let n=null,c,i="dormant",a=null,s=0;const d=P(),m={version:S,config:e,assetBase:t,get state(){return i},get pointerMode(){return i==="active"&&a?a.getState():"browse"},activated:!1,init(l){return l&&Object.assign(e,l),n?n.then(()=>m,()=>m):Promise.resolve(m)},activate(l){if(i==="destroyed")return Promise.resolve(null);if(a&&i!=="active"&&(i="active",d.emit("activated",{mode:a.getState()})),!n){const b=H(T.runtime,t);n=import(b).then(f=>i==="destroyed"?null:(m.activated=!0,i="active",a=f.mount(void 0,{assetBase:t,config:e,emit:d.emit,...o?{early:o}:{},...A?{reviewToken:A}:{}}),c!==void 0&&a.setRoute(c),d.emit("ready",{version:S,state:i}),d.emit("activated",{mode:a.getState()}),a)).catch(f=>{throw n=null,console.error(`[${v}] runtime failed to load from ${b}`,f),d.emit("error",{code:"runtime-load-failed",message:b,cause:f}),f})}return l?.mode?n.then(b=>(a?.setState(l.mode),b)):n},deactivate(){i!=="active"||!a||(a.closePanel(),a.setState("browse"),i="dormant",d.emit("deactivated",{}))},destroy(){if(i!=="destroyed"){r.abort(),s&&cancelAnimationFrame(s),s=0;try{a?.destroy()}catch(l){console.error(`[${v}] destroy failed`,l)}a=null,n=null,i="destroyed",m.activated=!1,d.emit("destroyed",{})}},setMode(l){if(i!=="destroyed"){if(i==="active"&&a){a.setState(l);return}m.activate({mode:l}).catch(()=>{})}},setRoute(l){c=l,a?.setRoute(l)},async open(l){return i==="destroyed"?{ok:!1,reason:"inert"}:await m.activate()?a.open(l):{ok:!1,reason:"inert"}},resync(){i!=="active"||s||(s=requestAnimationFrame(()=>{s=0,a?.refresh()}))},close(){a?.closePanel()},on:d.on,off:d.off};return Object.assign(m,{signal:r.signal})}const Z=`${O}stub-init`;function ee(){if(typeof document>"u"||typeof window>"u")return;const e=performance.now(),t=document.currentScript,r=window,o=W(r),n=V(t,o),c=J(n,t);F(n,t?.src);let i="";try{i=document.cookie}catch{}const a=n.site?!!x(n.site):!1,s=I({config:n,search:location.search,cookie:i,webdriver:navigator.webdriver,globals:r,inReview:!!A||a,...o?{configGlobal:o}:{},origin:location.origin}),d=Symbol.for(R.instance),m=r[g.api];if(m?.[d]){(m.__duplicates??=[]).push({version:S,src:t?.src??""}),console.warn(`[${v}] a second copy of the script is on this page and was ignored; the first one is running. See window.${g.api}.__duplicates.`);return}const l=m===void 0?g.api:g.collisionFallback;if(l===g.collisionFallback&&console.warn(`[${v}] window.${g.api} is taken; installing at window.${g.collisionFallback}.`),s){const h=X(n,c,s.gate);h[d]=!0,r[l]=h,s.silent||console.info(`[${v}] not activated: ${s.gate} \u2014 ${s.fix}`);return}const b=new AbortController,f=o?.breadcrumbs,p=f===!1?void 0:K(window,{early:f?.early!==!1},b.signal),u=Q(n,c,b,p);u[d]=!0,r[l]=u,te(e),z(u,n,u.signal);const w=new URLSearchParams(location.search).has($("t"));(n.mode==="on"||w||A||a)&&n.autoMount!=="false"?j(()=>void u.activate().catch(()=>{})):n.site&&n.host&&n.mode!=="off"&&n.autoMount!=="false"&&fetch(`${n.host.replace(/\/+$/,"")}/api/v1/projects/${n.site}/config`).then(h=>h.ok?h.json():null).then(h=>{h?.writeMode==="open"&&h.writable!==!1&&j(()=>void u.activate().catch(()=>{}))}).catch(()=>{})}function te(e){try{performance.measure(Z,{start:e})}catch{}}ee()})();
5
+ ${E(u.error)}`:"";m("error","error",`${w}${h}`)}catch{d++}},{capture:!0,signal:r}),e.addEventListener("unhandledrejection",f=>{try{m("error","error",`Unhandled rejection: ${E(f.reason)}`)}catch{d++}},{signal:r});const l=[];if(t.early){let f=!1;for(const p of["error","warn"])l.push(D(e.console,p,u=>function(...w){const h=u.apply(this,w);return f||(f=!0,m("console",p,w.map(E).join(" ").slice(0,4096)),f=!1),h}))}const b=()=>{for(const f of l)f();l.length=0,s=null,o.length=0};return r.addEventListener("abort",b,{once:!0}),{drain(f){const u={records:o.slice(),dropped:n};return o.length=0,n=0,s=f,u},destroy:b}}const S="0.1.68+e77816",A=Y();function Y(){try{const e=location.hash.slice(1);if(!e.includes($("k")))return;const t=new URLSearchParams(e),r=t.get($("k"))??void 0;if(!r)return;t.delete($("k"));const o=t.toString(),n=location.pathname+location.search+(o?`#${o}`:"");return history.replaceState(history.state,"",n),r}catch{return}}const q=["site","host","disabled","env","mode","hotkey","allowAutomation","assetBase","theme","autoMount","storage"];function W(e){const t=e[g.config];return t&&typeof t=="object"?t:void 0}function V(e,t){const r={};for(const o of q){const n=t?.[o];(typeof n=="string"||typeof n=="number")&&(r[o]=String(n));const c=e?.getAttribute(y(o));c!=null&&(r[o]=c)}return r}function H(e,t){const r=new URL(e,t);return r.searchParams.set("cv",S),r.href}function J(e,t){const r=e.assetBase??window[g.assetBase];if(r)return new URL(r,location.href).href.replace(/\/?$/,"/");const o=t?.src;return o?new URL(".",o).href:new URL(".",location.href).href}function P(){const e=new Map,t=(r,o)=>void e.get(r)?.delete(o);return{on(r,o){let n=e.get(r);return n||e.set(r,n=new Set),n.add(o),()=>t(r,o)},off:t,emit(r,o){const n=e.get(r);if(n)for(const c of[...n])try{c(o)}catch(i){console.error(`[${v}] listener for "${r}" threw`,i)}document.dispatchEvent(new CustomEvent(`${O}${r}`,{detail:o,bubbles:!1,composed:!1}))}}}function X(e,t,r){let o=!1;const n=()=>{o||(o=!0,console.info(`[${v}] not activated: ${r}`))},c=P(),i={version:S,config:e,assetBase:t,state:"inert",pointerMode:"browse",activated:!1,init:()=>(n(),Promise.resolve(i)),activate:()=>(n(),Promise.resolve(null)),deactivate:()=>{},destroy:()=>{},setMode:n,setRoute:n,open:()=>(n(),Promise.resolve({ok:!1,reason:"inert"})),resync:()=>{},close:()=>{},on:c.on,off:c.off};return i}function C(e){const t=window.requestIdleCallback;typeof t=="function"?t(e,{timeout:2e3}):setTimeout(e,1)}function j(e){if(document.readyState==="complete"){C(e);return}window.addEventListener("load",()=>requestAnimationFrame(()=>requestAnimationFrame(()=>C(e))),{once:!0})}function z(e,t,r){t.hotkey!=="off"&&document.addEventListener("keydown",o=>{if(!(!o.altKey||o.ctrlKey||o.metaKey)&&o.code==="KeyC"){if(o.preventDefault(),e.state==="active"){e.setMode(e.pointerMode==="add"?"comments":"add");return}e.activate().catch(()=>{})}},{capture:!0,signal:r})}function Q(e,t,r,o){let n=null,c,i="dormant",a=null,s=0;const d=P(),m={version:S,config:e,assetBase:t,get state(){return i},get pointerMode(){return i==="active"&&a?a.getState():"browse"},activated:!1,init(l){return l&&Object.assign(e,l),n?n.then(()=>m,()=>m):Promise.resolve(m)},activate(l){if(i==="destroyed")return Promise.resolve(null);if(a&&i!=="active"&&(i="active",d.emit("activated",{mode:a.getState()})),!n){const b=H(T.runtime,t);n=import(b).then(f=>i==="destroyed"?null:(m.activated=!0,i="active",a=f.mount(void 0,{assetBase:t,config:e,emit:d.emit,...o?{early:o}:{},...A?{reviewToken:A}:{}}),c!==void 0&&a.setRoute(c),d.emit("ready",{version:S,state:i}),d.emit("activated",{mode:a.getState()}),a)).catch(f=>{throw n=null,console.error(`[${v}] runtime failed to load from ${b}`,f),d.emit("error",{code:"runtime-load-failed",message:b,cause:f}),f})}return l?.mode?n.then(b=>(a?.setState(l.mode),b)):n},deactivate(){i!=="active"||!a||(a.closePanel(),a.setState("browse"),i="dormant",d.emit("deactivated",{}))},destroy(){if(i!=="destroyed"){r.abort(),s&&cancelAnimationFrame(s),s=0;try{a?.destroy()}catch(l){console.error(`[${v}] destroy failed`,l)}a=null,n=null,i="destroyed",m.activated=!1,d.emit("destroyed",{})}},setMode(l){if(i!=="destroyed"){if(i==="active"&&a){a.setState(l);return}m.activate({mode:l}).catch(()=>{})}},setRoute(l){c=l,a?.setRoute(l)},async open(l){return i==="destroyed"?{ok:!1,reason:"inert"}:await m.activate()?a.open(l):{ok:!1,reason:"inert"}},resync(){i!=="active"||s||(s=requestAnimationFrame(()=>{s=0,a?.refresh()}))},close(){a?.closePanel()},on:d.on,off:d.off};return Object.assign(m,{signal:r.signal})}const Z=`${O}stub-init`;function ee(){if(typeof document>"u"||typeof window>"u")return;const e=performance.now(),t=document.currentScript,r=window,o=W(r),n=V(t,o),c=J(n,t);F(n,t?.src);let i="";try{i=document.cookie}catch{}const a=n.site?!!x(n.site):!1,s=I({config:n,search:location.search,cookie:i,webdriver:navigator.webdriver,globals:r,inReview:!!A||a,...o?{configGlobal:o}:{},origin:location.origin}),d=Symbol.for(R.instance),m=r[g.api];if(m?.[d]){(m.__duplicates??=[]).push({version:S,src:t?.src??""}),console.warn(`[${v}] a second copy of the script is on this page and was ignored; the first one is running. See window.${g.api}.__duplicates.`);return}const l=m===void 0?g.api:g.collisionFallback;if(l===g.collisionFallback&&console.warn(`[${v}] window.${g.api} is taken; installing at window.${g.collisionFallback}.`),s){const h=X(n,c,s.gate);h[d]=!0,r[l]=h,s.silent||console.info(`[${v}] not activated: ${s.gate} \u2014 ${s.fix}`);return}const b=new AbortController,f=o?.breadcrumbs,p=f===!1?void 0:K(window,{early:f?.early!==!1},b.signal),u=Q(n,c,b,p);u[d]=!0,r[l]=u,te(e),z(u,n,u.signal);const w=new URLSearchParams(location.search).has($("t"));(n.mode==="on"||w||A||a)&&n.autoMount!=="false"?j(()=>void u.activate().catch(()=>{})):n.site&&n.host&&n.mode!=="off"&&n.autoMount!=="false"&&fetch(`${n.host.replace(/\/+$/,"")}/api/v1/projects/${n.site}/config`).then(h=>h.ok?h.json():null).then(h=>{h?.writeMode==="open"&&h.writable!==!1&&j(()=>void u.activate().catch(()=>{}))}).catch(()=>{})}function te(e){try{performance.measure(Z,{start:e})}catch{}}ee()})();
@@ -1,2 +1,2 @@
1
1
  const Se="Snagset",Wo="snagset",Sn="snagset.v1",jo="Snagset",Wt="Snag",Fo="Snags",Uo={config:"SnagsetConfig"},Bo={root:"data-snag-root"},jt=e=>Bo[e],Zo={anchor:"data-snag-anchor",ignore:"data-snag-ignore",mask:"data-snag-mask",nomask:"data-snag-nomask",src:"data-snag-src",component:"data-snag-component"},Vo=e=>Zo[e],P={font:"--snag-font",accent:"--snag-accent",onAccent:"--snag-onAccent",bg:"--snag-bg",fg:"--snag-fg",muted:"--snag-muted",border:"--snag-border",radius:"--snag-radius",shadow:"--snag-shadow",z:"--snag-z",motion:"--snag-motion",surface:"--snag-surface",sunken:"--snag-sunken",hover:"--snag-hover",focus:"--snag-focus",disabled:"--snag-disabled",statusOpen:"--snag-status-open",statusProgress:"--snag-status-progress",statusReview:"--snag-status-review",statusResolved:"--snag-status-resolved",anchorOrphan:"--snag-anchor-orphan",tbH:"--snag-tb-h",dockW:"--snag-dock-w",kb:"--snag-kb",thumbX:"--snag-thumb-x",thumbW:"--snag-thumb-w"},Yo=e=>`var(${P[e]})`,Xo=e=>"snag_"+e,St={query:["snag_t","snag_off","snag_debug","snag_theme"],fragment:["snag_k"]},Ko="snag:disclosure:v1",Ft="snag:identity",An="data-snag-theme",se={session:e=>`snag:session:${e}`,silent:e=>`snag:silent:${e}`,identity:Ft,threads:(e,t)=>`snag:threads:${e}:${t}`,seen:(e,t)=>`snag:seen:${e}:${t}`,filter:(e,t)=>`snag:filter:${e}:${t}`,counts:e=>`snag:counts:${e}`,list:(e,t)=>`snag:list:${e}:${t}`,draft:(e,t)=>`snag:draft:${e}:${t}`,outbox:e=>`snag:outbox:${e}`,mode:"snag:mode",handoff:"snag:handoff",seenCoach:"snag:seen-coach",disclosure:Ko},Oe={panels:"snag.panels.js",crumbs:"snag.crumbs.js",capture:"snag.capture.js",screenshot:"snag.screenshot.js",anchorExt:"snag.anchor-ext.js",anchorFuzzy:"snag.anchor-fuzzy.js",dock:"snag.dock.js",text:"snag.text.js"},At={thread:"thr_",comment:"cmt_",attachment:"att_"},Ut={attachmentKind:"x-snagset-attachment-kind",attachmentWidth:"x-snagset-attachment-width",attachmentHeight:"x-snagset-attachment-height"},Jo={route:"snagset:route"},kn={original:"snagset.original",wrapped:"snagset.wrapped"},$n="position:absolute!important;top:0!important;left:0!important;width:0!important;height:0!important;margin:0!important;padding:0!important;border:0!important;pointer-events:none!important;z-index:2147483647;isolation:isolate;color-scheme:light dark;";function En(e){const t=e.ownerDocument.defaultView?.getComputedStyle(e);return t?t.transform!=="none"&&t.transform!==""||t.filter!=="none"&&t.filter!==""||t.perspective!=="none"&&t.perspective!==""||/transform|filter|perspective|contain/.test(t.willChange)||/paint|layout|strict|content/.test(t.contain)||t.containerType!==void 0&&t.containerType!=="normal"&&t.containerType!=="":!1}function Bt(e){const t=e.documentElement,n=e.body;return t&&En(t)?{parent:n??t,trapped:!0}:n&&En(n)?{parent:t??n,trapped:!1}:{parent:n??t,trapped:!1}}function Cn(e=document){const t=jt("root"),n=e.querySelector(`[${t}]`);if(n?.shadowRoot)return n.shadowRoot;const o=e.createElement("div");return o.setAttribute(t,""),o.style.cssText=$n,Bt(e).parent.appendChild(o),o.attachShadow({mode:"open"})}function qo(e,t,n=5){const o=e.ownerDocument??document,r=e.host,l=Bt(o).parent;if(typeof MutationObserver!="function"||!l)return()=>{};let u=0;const a=new MutationObserver(()=>{if(!r.isConnected){if(u++,u>n){a.disconnect(),t(u);return}Bt(o).parent.appendChild(r)}});return a.observe(l,{childList:!0}),()=>a.disconnect()}const Tn=[["pointerdown",!0],["mousedown",!0],["touchstart",!0],["pointerup",!0],["mouseup",!0],["touchend",!0],["click",!0],["dblclick",!0],["focusin",!0],["focusout",!0]];function Qo(e){const t=e.host,n=o=>o.stopPropagation();for(const[o,r]of Tn)t.addEventListener(o,n,{passive:r});return()=>{for(const[o]of Tn)t.removeEventListener(o,n)}}function Go(e,t,n=20){const o=e.host;if(typeof MutationObserver!="function")return()=>{};let r=0;const l=()=>{let a=!1;return o.getAttribute("aria-hidden")==="true"&&(o.removeAttribute("aria-hidden"),a=!0),o.hasAttribute("inert")&&(o.removeAttribute("inert"),a=!0),a},u=new MutationObserver(()=>{l()&&++r>n&&(u.disconnect(),t(r))});return l(),u.observe(o,{attributes:!0,attributeFilter:["aria-hidden","inert"]}),()=>u.disconnect()}const er={product:Se,set:jo,item:Wt,items:Fo};function Rn(e){return(t,n)=>(e[t]??"").replace(/\{(\w+)\}/g,(o,r)=>{const l=n?.[r]??er[r];return l===void 0?o:String(l)})}const tr=e=>new Intl.NumberFormat().format(e),_n={"where.anchored":"{label}","where.approximate":"position approximate \u2014 the page changed","where.orphaned":"moved \u2014 the element is gone","status.open":"Active","status.progress":"In progress","status.review":"In review","status.resolved":"Resolved","author.unknown":"Someone","label.image":"an image","label.link":"a link","label.button":"a button","label.tag":"the {tag}"},In=Rn(_n),Pn={open:{colour:"#4f6ef7"},progress:{colour:"#f59e0b"},review:{colour:"#8b5cf6"},resolved:{colour:"#10b981"}},Mn=e=>e==="open"||e==="review"?"#fff":"#16161a",On=e=>e in Pn?In(`status.${e}`):e,nr=e=>In(`where.${e.anchorState}`,{label:e.anchor.label});class Zt extends Error{code;constructor(t,n){super(n??t),this.name="AdapterError",this.code=t}}function zn(e){return{id:e.id,key:e.key,route:e.route,...e.scope?{scope:e.scope}:{},...e.attachments?.length?{attachments:e.attachments}:{},anchor:e.anchor,anchorState:e.anchorState,context:e.context,status:"open",comments:e.comment?[{id:e.comment.id,snagId:e.id,body:e.comment.body,author:e.comment.author,createdAt:e.createdAt}]:[],createdBy:e.createdBy,createdAt:e.createdAt,updatedAt:e.createdAt}}const k=Object.fromEntries(Object.keys(P).map(e=>[e,Yo(e)])),or=Object.entries(Pn).map(([e,t])=>` ${P[`status${e[0].toUpperCase()}${e.slice(1)}`]}:${t.colour};`).join(`
2
- `),rr=` :host{all:initial}[hidden]{display:none!important}:host{display:block;font:400 14px/1.45 ${k.font};color:${k.fg};${P.font}:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;${P.accent}:#2a51b8;${P.bg}:#fefdfc;${P.fg}:#181716;${P.muted}:#666564;${P.border}:#e4e3e0;${P.radius}:8px;${P.shadow}:0 6px 24px -4px rgb(0 0 0 / .18);${P.z}:2147483647;${P.motion}:160ms;${P.surface}:color-mix(in srgb,${k.fg} 6%,${k.bg});${P.sunken}:color-mix(in srgb,${k.fg} 3%,${k.bg});${P.hover}:color-mix(in srgb,${k.fg} 8%,${k.bg});${P.onAccent}:#fff;${P.focus}:color-mix(in srgb,${k.accent} 62%,${k.fg});${P.disabled}:color-mix(in srgb,${k.muted} 52%,${k.bg});${or} ${P.anchorOrphan}:#DC2626;}:host([${An}="dark"]){${P.accent}:#8aafff;${P.onAccent}:#1d1c1a;${P.bg}:#1d1c1a;${P.fg}:#f0eeec;${P.muted}:#9a9997;${P.border}:#2d2c2b;${P.shadow}:0 6px 24px -4px rgb(0 0 0 / .6);}@media (prefers-reduced-motion:reduce){:host{${P.motion}:0ms}}@media (forced-colors:active){:host{${P.bg}:Canvas;${P.fg}:CanvasText;${P.muted}:CanvasText;${P.border}:CanvasText;${P.accent}:Highlight;${P.onAccent}:HighlightText;${P.surface}:Canvas;${P.sunken}:Canvas;${P.hover}:Canvas;${P.focus}:Highlight;${P.disabled}:GrayText;${P.shadow}:none;${P.anchorOrphan}:CanvasText;}.snag-pin{border-color:CanvasText!important;color:CanvasText!important;forced-color-adjust:none}}`,qe={shield:1,pins:3,dock:5,notice:6,toolbar:7},Ln=new WeakMap;function at(e,t,n){let o=Ln.get(e);if(o||Ln.set(e,o=new Set),o.has(t))return;o.add(t);try{const u=new CSSStyleSheet;u.replaceSync(n),e.adoptedStyleSheets=[...e.adoptedStyleSheets,u];return}catch{}const l=(e.ownerDocument??document).createElement("style");l.setAttribute(`data-snag-${t}`,""),l.textContent=n,e.appendChild(l)}function sr(e){return e==="light"||e==="dark"?e:"auto"}function ar(e,t){const n=An;if(t!=="auto")return e.setAttribute(n,t),()=>e.removeAttribute(n);const o=e.ownerDocument?.defaultView?.matchMedia?.("(prefers-color-scheme: dark)");if(!o)return e.setAttribute(n,"light"),()=>e.removeAttribute(n);const r=()=>e.setAttribute(n,o.matches?"dark":"light");return r(),o.addEventListener("change",r),()=>{o.removeEventListener("change",r),e.removeAttribute(n)}}function Vt(e){return e.getBoundingClientRect()}function kt(e){if(e.closest('[inert],[aria-hidden="true"]'))return!1;const t=e.checkVisibility;if(typeof t=="function")return t.call(e,{contentVisibilityAuto:!0,opacityProperty:!1,visibilityProperty:!0});const n=Vt(e);if(!(n.width>0||n.height>0||e.getClientRects().length>0))return!1;const r=e.ownerDocument?.defaultView;return r?r.getComputedStyle(e).visibility!=="hidden":!0}const ir="button,a[href],[role=button],[role=link],[role=tab],[role=menuitem],label,input,select,textarea,summary",cr=3,Dn=8,lr=new Set(["img","picture","canvas","video","audio","iframe","embed","object","svg","math","input","select","textarea","button","progress","meter"]);function dr(e,t){return lr.has(e.tagName.toLowerCase())?!1:t.getComputedStyle(e).display==="inline"}function Nn(e){const t=e.ownerDocument?.defaultView;if(!t)return e;let n=e;for(let r=e;r;r=r.parentElement){const l=Vt(r);if(l.width>=Dn&&l.height>=Dn&&!dr(r,t)){n=r;break}n=r}let o=0;for(let r=n;r&&o<=cr;r=r.parentElement){if(r.matches(ir))return r;o++}return n}const ur=10,Yt=[["click",!1],["auxclick",!1],["dblclick",!1],["pointerdown",!1],["pointerup",!1],["mousedown",!1],["mouseup",!1],["contextmenu",!1],["dragstart",!1],["wheel",!1],["touchstart",!0],["touchmove",!0],["touchend",!0],["selectstart",!0],["keydown",!1],["keyup",!1]];function fr(e,t,n){let o=e;for(;o&&o!==o.ownerDocument.documentElement&&o!==o.ownerDocument.body;){const r=getComputedStyle(o),l=(r.overflowY==="auto"||r.overflowY==="scroll")&&o.scrollHeight>o.clientHeight&&(t>0&&o.scrollTop+o.clientHeight<o.scrollHeight-1||t<0&&o.scrollTop>0),u=(r.overflowX==="auto"||r.overflowX==="scroll")&&o.scrollWidth>o.clientWidth&&(n>0&&o.scrollLeft+o.clientWidth<o.scrollWidth-1||n<0&&o.scrollLeft>0);if(l||u)return o;o=o.parentElement}return null}function Hn(e,t){const n=t==="y"?e.deltaY:e.deltaX;return e.deltaMode===1?n*16:e.deltaMode===2?n*(t==="y"?innerHeight:innerWidth):n}const hr=["position:fixed","inset:0",`z-index:${qe.shield}`,"touch-action:pan-x pan-y pinch-zoom","background:transparent"].join(";");function pr(e,t={}){const n=t.doc??e.ownerDocument??document,o=n.defaultView??window;let r=t.coarsePointer??o.matchMedia?.("(pointer: coarse)").matches??!1;const l=i=>{const p=i.pointerType,y=p==="touch"?!0:p==="mouse"||p==="pen"?!1:r;y!==r&&(r=y,d())},u=n.createElement("div");u.className="snag-shield",u.style.cssText=hr;let a="browse";const d=()=>{u.style.pointerEvents=r?"none":"auto",u.style.cursor="crosshair"};d();const v=i=>{const p=i;return!p||typeof p.closest!="function"?!1:e.contains(p)?!0:!!p.closest(`[${jt("root")}]`)};function S(i,p,y){let m=y,C=0;for(;m.shadowRoot&&C++<ur;){const z=_(m.shadowRoot,i,p);if(!z||z===m)break;m=z}return m}function _(i,p,y){const m=i.elementsFromPoint;if(typeof m=="function"){for(const z of m.call(i,p,y))if(z.getRootNode()===i)return z;return null}const C=i.elementFromPoint(p,y);return C&&C.getRootNode()===i?C:null}function h(i,p){const y=[];for(const m of n.elementsFromPoint(i,p)){if(v(m))continue;if(m===n.documentElement||m===n.body){y.push(m);continue}const C=S(i,p,m);y.push(v(C)?m:C)}return y}let I=null;const H=(i,p)=>{const[y]=h(i,p);y&&t.onPick?.(Nn(y),{x:i,y:p})};let F=!1;const b=()=>{const i=n.getSelection?.();if(!i||i.isCollapsed||i.rangeCount===0||!i.toString().trim())return!1;const p=i.anchorNode;if(!p||e.contains(p))return!1;const y=p.nodeType===1?p:p.parentElement;return!v(y)},j=i=>{const p=i.composedPath()[0];if(p&&v(p)){F=!1;return}if(i.type==="selectstart"){t.onSelectStart?.();return}const y=i.type;if(y.endsWith("down")||y.endsWith("start")){F=!1;return}if(y.endsWith("up")||y.endsWith("end")){F=b();return}if(y==="click"||y==="auxclick"){if(!F)return;F=!1,i.preventDefault(),i.stopImmediatePropagation()}},ee=i=>{if(i.type==="pointerdown"&&l(i),a==="comments"){j(i);return}if(a!=="add")return;if(i.type==="keydown"||i.type==="keyup"){ue(i);return}const p=i.composedPath()[0];if(p&&p!==u&&v(p))return;const y=Yt.find(([m])=>m===i.type)?.[1]??!1;if(i.stopImmediatePropagation(),!y){if(r&&i.type==="pointerdown"){const m=i;I={x:m.clientX,y:m.clientY,t:performance.now()},g(m.clientX,m.clientY)}if(r&&i.type==="pointerup"&&I){const m=i,C=I;I=null,Math.hypot(m.clientX-C.x,m.clientY-C.y)<=8&&performance.now()-C.t<=700&&H(m.clientX,m.clientY);return}if(i.type==="click"||i.type==="auxclick"||i.type==="dblclick"){i.preventDefault();const m=i;H(m.clientX,m.clientY);return}if(i.type==="wheel"){const m=i,C=Hn(m,"y"),z=Hn(m,"x"),[te]=h(m.clientX,m.clientY),U=fr(te??null,C,z);U&&(U.scrollTop+=C,U.scrollLeft+=z,i.preventDefault());return}if(i.type==="dragstart"||i.type==="contextmenu"){i.preventDefault();return}(i.type==="pointerdown"||i.type==="mousedown")&&!r&&i.preventDefault()}},ne=new Set(["Tab","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"," ","Spacebar","PageUp","PageDown","Home","End"]),le=/^[a-z0-9/?]$/;function X(i){for(const p of i.composedPath()){const y=p;if(!(!y||y.nodeType!==1||typeof y.matches!="function")&&y.matches('input:not([type=button]):not([type=submit]):not([type=checkbox]):not([type=radio]),textarea,select,[contenteditable=""],[contenteditable=true],[role=textbox],[role=searchbox],[role=combobox]'))return!0}return!1}function ue(i){ne.has(i.key)||i.metaKey||i.ctrlKey||i.altKey||/^F\d{1,2}$/.test(i.key)||i.key!=="Escape"&&i.key.length===1&&le.test(i.key.toLowerCase())&&!X(i)&&(i.preventDefault(),i.stopImmediatePropagation())}for(const[i,p]of Yt)o.addEventListener(i,ee,{capture:!0,passive:p});let ae=0,K=null;function oe(){if(ae=0,a!=="add"||!K)return;const[i]=h(K.x,K.y);t.onHover?.(i?Nn(i):null)}function g(i,p){a==="add"&&(K={x:i,y:p},!ae&&(ae=o.requestAnimationFrame(oe)))}return u.addEventListener("pointermove",i=>g(i.clientX,i.clientY)),u.addEventListener("pointerleave",()=>{K=null,t.onHover?.(null)}),{shield:u,getMode:()=>a,setMode(i){a=i,F=!1,d(),i==="add"?e.appendChild(u):u.remove(),i!=="add"&&(K=null,t.onHover?.(null))},hitTest:h,destroy(){ae&&o.cancelAnimationFrame(ae);for(const[i]of Yt)o.removeEventListener(i,ee,{capture:!0});u.remove()}}}const mr=/[\u200B-\u200D\u2060\uFEFF]/gu,gr=/[\s\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+/gu,yr=[[/[\u2018\u2019\u201A\u201B]/gu,"'"],[/[\u201C\u201D\u201E\u201F]/gu,'"'],[/[\u2010-\u2015\u2212]/gu,"-"],[/\u2026/gu,"..."],[/\u2044/gu,"/"]];function br(e){let t=e.normalize("NFC").replace(mr,"");for(const[n,o]of yr)t=t.replace(n,o);return t.replace(gr," ").trim()}const vr={testid:1,domid:1,css:.9,aria:.75,"text-exact":.8,"text-fuzzy":.78,"path-rect":.35,none:0,manual:1},Wn={anchored:.75,approximate:.35};function wr(e,t){const n=vr[e];return t===1?n:n/(1+Math.log2(t))}function jn(e){return e>=Wn.anchored?"anchored":e>=Wn.approximate?"approximate":"orphaned"}const xr=[Vo("anchor"),"data-testid","data-test-id","data-test","data-cy","data-qa","data-pw","data-automation-id"],Fn=e=>typeof CSS<"u"&&CSS.escape?CSS.escape(e):e.replace(/["\\]/g,"\\$&"),Sr=[{strategy:"testid",applicable:e=>!!e.testid,find:(e,t)=>Xt(t,xr.map(n=>`[${n}="${Fn(e.testid)}"]`).join(","))},{strategy:"domid",applicable:e=>!!e.domid,find:(e,t)=>Xt(t,`#${Fn(e.domid)}`)},{strategy:"css",applicable:e=>!!e.css,find:(e,t)=>{try{return Xt(t,e.css)}catch{return[]}}}];function Xt(e,t){return[...e.querySelectorAll(t)].filter(Ar)}function Ar(e){return!e.closest(`[${jt("root")}]`)}function kr(e,t){const n=t.text?.exact;if(!n)return!0;const o=br(e.textContent??"");return o?o===n||o.includes(n)||n.includes(o):!0}function Un(e,t,n,o){kt(e)||o.push("hidden"),t.hostPath?.length&&o.push("shadow-boundary");const r=!kr(e,t);r&&o.push("text-drift");let l=o.includes("hidden")?Math.min(n,.7):n;return r&&(l=Math.min(l,.5)),l}const $r={element:null,strategy:"none",score:0,state:"orphaned",reasons:["not-found"],candidates:0};function Kt(e,t=document,n={}){const o=[];for(const r of Sr){if(!r.applicable(e))continue;const l=r.find(e,t);if(l.length===0)continue;const u=wr(r.strategy,l.length),a=l[0];l.length>1&&o.push("ambiguous");const d=Un(a,e,u,o),v={element:a,strategy:r.strategy,score:d,state:jn(d),reasons:o.length?o:["exact"],candidates:l.length};if(v.reasons.includes("text-drift")&&n.extended){const S=n.extended(e,t,{...n.viewportWidth===void 0?{}:{viewportWidth:n.viewportWidth},...n.passCaches?{caches:n.passCaches}:{}});if(S&&S.score>v.score)return S}return v}return n.extended?.(e,t,{...n.viewportWidth===void 0?{}:{viewportWidth:n.viewportWidth},...n.passCaches?{caches:n.passCaches}:{}})??$r}const Er={"toolbar.aria":"{product} review toolbar","toolbar.group":"What you see","toolbar.browse":"Browse","toolbar.comments":"Comment","toolbar.comments.unresolved":"Comment, {n} unresolved","toolbar.add":"Add a comment","toolbar.add.draft":"Add a comment \u2014 one is unfinished","toolbar.panel":"All comments","pin.aria":"Comment {key} on {target}. {status}, {replies} replies. Press Enter.","pin.aria.one":"Comment {key} on {target}. {status}, 1 reply. Press Enter.","pin.aria.none":"Comment {key} on {target}. {status}. Press Enter.","pin.aria.moved":"Comment {key} on {target}. {status}. {where}. Press Enter.","pin.target":"{role} \u201C{name}\u201D","cluster.aria":"{n} comments here: {list}","nav.announce":"Comment {n} on {label}, {i} of {total}","action.retry":"Retry","action.dismiss":"Dismiss","action.export":"Export","action.exportclear":"Export & clear","error.quota":"Storage is full \u2014 this {item} is on screen but not saved. Export to keep them.","error.nostorage":"Comments won't be saved in this browser. Export before you leave to keep them.","error.linkrevoked":"This review link was turned off. Ask whoever sent it for a new one.","error.sessionended":"This review session has ended. Open your review link again to carry on.","error.sendfailed":"That {item} couldn't be sent, so it wasn't kept. Check your connection and try again.","error.readonly":"This site is read-only for now. You can read what is here, but new comments are off.","error.origin":"{product} is not enabled for {origin}. Add that address to the site's allowed origins.","error.panels":"{product} loaded, but its comment UI didn't. You can still see the comments on the page.","error.panels.add":"Adding comments is unavailable until the comment UI loads.","error.capture":"{product} can't take new comments \u2014 the part that records the page didn't load. Everything already here still works.","paused.dialog":"Review paused \u2014 a dialog is open on this page. Close it to carry on commenting. Commenting inside a native dialog isn't supported yet.","paused.close":"Close","announce.created":"Comment {key} added.","permalink.unknown":"That comment isn't on this page any more"},Cr={..._n,...Er},Z=Rn(Cr);function Tr(e,t){const n=new Array(e.length),o=[],r=new Map,l=[];let u=0;for(let a=0;a<e.length;a++){u++;const d=e[a],v=Math.floor(d.x/t),S=Math.floor(d.y/t);let _=-1;e:for(let h=-1;h<=1;h++)for(let I=-1;I<=1;I++)for(const H of r.get(`${v+h},${S+I}`)??[]){const F=l[H],b=d.x-F.x,j=d.y-F.y;if(b*b+j*j<=t*t){_=H;break e}}if(_===-1){_=o.length,o.push([]),l.push(d);const h=`${v},${S}`,I=r.get(h);I?I.push(_):r.set(h,[_])}n[a]=_,o[_].push(a)}return{group:n,members:o,visits:u}}const Rr=`position:absolute;top:0;left:0;width:0;height:0;pointer-events:none;z-index:${qe.pins}`,_r=' .snag-pp{animation:snag-pp .5s ease-out 2}@keyframes snag-pp{50%{transform:scale(1.45)}}@media (prefers-reduced-motion: reduce){.snag-pp{animation:none}}.snag-pin{width:28px;height:28px;margin:-14px 0 0 -14px}.snag-pin::after{content:"";position:absolute;inset:-8px}@media (pointer:coarse){.snag-pin{width:34px;height:34px;margin:-17px 0 0 -17px}}',Ir=`position:fixed;inset:0;width:0;height:0;pointer-events:none;z-index:${qe.pins}`,it=["position:absolute",`color:${k.onAccent}`,`font:600 12px/1 ${k.font}`,"display:flex","align-items:center","justify-content:center","box-shadow:0 1px 4px rgb(0 0 0 / .35)","pointer-events:auto","cursor:pointer","box-sizing:border-box"].join(";"),$t="border-radius:50% 50% 50% 2px",Bn=e=>k[`status${e[0].toUpperCase()}${e.slice(1)}`]??k.muted;function Zn(e,t){const n=Mn(t.status),o=`background:${Bn(t.status)};color:${n}`,r="0 1px 4px rgb(0 0 0 / .35)";return e==="anchored"?`${it};${$t};${o};border:2px solid ${n};box-shadow:${r}`:e==="approximate"?`${it};${$t};${o};border:2px dashed ${n};box-shadow:${r}`:`${it};${$t};${o};border:2px solid ${n};box-shadow:inset 0 0 0 2px ${n},${r}`}function Pr(e,t){const n=[];let o="static",r=!1;for(let l=e;l&&l!==e.ownerDocument.documentElement;l=l.parentElement){const u=t.getComputedStyle(l),a=l!==e.ownerDocument.body&&/auto|scroll|hidden|overlay/.test(u.overflowY+u.overflowX);a&&!r&&n.push(l),u.position==="fixed"?(o="dynamic",r=!0):u.transform!=="none"||u.filter!=="none"||u.perspective!=="none"?(o="dynamic",r=!1):(u.position==="sticky"||u.willChange.includes("transform")||u.contain.includes("layout")||a&&(l.scrollHeight>l.clientHeight||l.scrollWidth>l.clientWidth))&&(o="dynamic")}return{tier:o,clips:n}}function Mr(e,t,n,o){const r=e.ownerDocument??document,l=r.defaultView??window;at(e,"pins",_r);const u=r.createElement("div");u.className="snag-pins",u.style.cssText=Rr,e.appendChild(u);const a=r.createElement("div");a.className="snag-pins-dyn",a.style.cssText=Ir,e.appendChild(a);let d=[],v=[];const S=new Map;let _=new Map,h=null;const I=new Map;let H=new Map;const F=l.matchMedia?.("(pointer: coarse)").matches??!1,b=F?32:24,j=F?34:28;let ee=[],ne=null,le=null,X={x:0,y:0};function ue(){const $=r.defaultView,w=u.getBoundingClientRect();X={x:w.left+($?.scrollX??0),y:w.top+($?.scrollY??0)}}let ae=[];const K=new Map,oe=1e4,g=5,i=new Map,p=new Set(["testid","domid"]);function y($){const w=i.get($.id),x=w?.ref.deref();if(!x||!x.isConnected)return null;if(p.has(w.strategy))return x;if($.anchor.css)try{if(!x.matches($.anchor.css))return null}catch{return null}return x}function m($,w){const x=[],L=Un(w,$.anchor,1,x);return{element:w,strategy:i.get($.id).strategy,score:L,state:jn(L),reasons:x.length?x:["exact"],candidates:1}}function C($,w="authoritative"){S.clear(),ae=[];const x=Date.now(),L=n?.newPass?.();return $.map(E=>{const D=y(E),T=n?.get();let R=D?m(E,D):Kt(E.anchor,r,{viewportWidth:r.defaultView?.innerWidth??0,...T?{extended:T}:{},...L?{passCaches:L}:{}});if(D&&R.reasons.includes("text-drift")){const M=Kt(E.anchor,r,{viewportWidth:r.defaultView?.innerWidth??0,...T?{extended:T}:{},...L?{passCaches:L}:{}});M.score>R.score&&(R=M)}if(n&&(!R.element||R.reasons.includes("text-drift"))&&n.want(E.anchor),!R.element&&n){const M=n.fuzzyHit?.(E.id);M?R=M:n.wantFuzzy?.(E.id,E.anchor)}const J=R.element&&E.anchor.text?.exact&&(R.reasons.includes("text-drift")||R.strategy==="path-rect"&&R.score<.5);if(n&&J){const M=n.fuzzyHit?.(E.id);M&&M.score>R.score?R=M:M||n.wantFuzzy?.(E.id,E.anchor)}R.element?i.set(E.id,{ref:new WeakRef(R.element),strategy:R.strategy}):i.delete(E.id),R.element&&S.set(E.id,R.element);let V=!1;if(R.state==="orphaned"){const M=K.get(E.id)??{firstSeenAt:x,tries:0,best:R};M.tries++,R.score>=M.best.score&&(M.best=R),K.set(E.id,M);const q=n?.unavailable?.()??!1,ve=q?2:g,we=x-M.firstSeenAt<oe;w==="optimistic"||we&&(w==="navigating"||M.tries<ve)?V=!0:(R=M.best,q&&!R.reasons.includes("budget-exceeded")&&(R={...R,reasons:[...R.reasons,"budget-exceeded"]}),K.delete(E.id))}else K.delete(E.id);V||ae.push({id:E.id,state:R.state,strategy:R.strategy,confidence:R.score});const N=R.element?Vt(R.element):void 0;if(N&&(N.width>0||N.height>0)){const M=r.defaultView;E.anchor.rect={x:N.left+(M?.scrollX??0),y:N.top+(M?.scrollY??0),w:N.width,h:N.height}}return{...E,anchorState:V?E.anchorState:R.state,anchorPending:V,anchorReasons:R.reasons}})}function z(){const $=r.documentElement;return{w:$.scrollWidth,h:$.scrollHeight}}function te($,w,x){return{x:Math.min(Math.max($,14),Math.max(x.w,28)-14),y:Math.min(Math.max(w,14),Math.max(x.h,28)-14)}}function U($,w){ue(),u.textContent="",a.textContent="",d=[],v=[],_=new Map,H=new Map,I.clear(),ee=[],le=null,$.forEach((x,L)=>{const E=x.anchor.rect;if(!E)return;const D=x.anchor.offset??{fx:.5,fy:.5},T=r.createElement("div");T.className="snag-pin",T.setAttribute("data-state",x.anchorPending?"pending":x.anchorState),T.setAttribute("data-key",x.key),T.style.cssText=x.anchorPending?`${Zn("approximate",x)};opacity:.55`:Zn(x.anchorState,x);const R=S.get(x.id),{tier:J,clips:V}=R?Pr(R,l):{tier:"static",clips:[]};if(J==="dynamic"&&R){const re=R.getBoundingClientRect(),et=W();T.style.left=`${re.left-et.left+re.width*D.fx}px`,T.style.top=`${re.top-et.top+re.height*D.fy}px`,I.set(T,{x:re.left+re.width*D.fx+l.scrollX-X.x,y:re.top+re.height*D.fy+l.scrollY-X.y});const ce={node:T,el:R,fx:D.fx,fy:D.fy,clips:V};d.push(ce),T.hidden=!kt(R),T.hidden||ie(ce,re,new Map(V.map(We=>[We,We.getBoundingClientRect()])))}else{const re=te(E.x+E.w*D.fx-X.x,E.y+E.h*D.fy-X.y,z());T.style.left=`${re.x}px`,T.style.top=`${re.y}px`,I.set(T,re),R&&(v.push({node:T,el:R,fx:D.fx,fy:D.fy,clips:[]}),T.hidden=!kt(R))}T.textContent=String(L+1);const N=nr(x),M=x.anchor.role?Z("pin.target",{role:x.anchor.role,name:x.anchor.accessibleName??x.anchor.label}):x.anchor.label,q=x.comments.length-1,ve=x.anchorState==="approximate"?`~ ${x.key}`:x.key;T.setAttribute("role","button"),T.setAttribute("tabindex","0");const we=x.anchorState==="anchored"?Z(q===0?"pin.aria.none":q===1?"pin.aria.one":"pin.aria",{key:ve,target:M,status:On(x.status),replies:q}):Z("pin.aria.moved",{key:ve,target:M,status:On(x.status),where:N});T.title=we,T.setAttribute("aria-label",we),t&&Ne(T,()=>t(x)),w?.has(x.id)&&(T.hidden=!0,T.setAttribute("data-fo","")),_.set(x.id,T),H.set(T,{snag:x,ordinal:L+1}),(J==="dynamic"?a:u).appendChild(T)}),$e(),h&&ye(h),de(),be="",He(r.visibilityState==="visible"&&_.size>0)}const W=()=>a.getBoundingClientRect();let G=!1;function ie($,w,x){for(const L of $.clips){const E=x.get(L);if(E&&(w.right<=E.left||w.left>=E.right||w.bottom<=E.top||w.top>=E.bottom)){$.node.hidden=!0;return}}$.node.hidden=!1}function Ge($){const w=new Map;for(const x of $)for(const L of x.clips)w.has(L)||w.set(L,L.getBoundingClientRect());return w}const De=["open","progress","review","resolved"];function Ne($,w){$.addEventListener("click",w),$.addEventListener("keydown",x=>{x.key!=="Enter"&&x.key!==" "||(x.preventDefault(),w())})}function dt($,w,x,L,E){const D=De.find(R=>$.some(J=>J.snag.status===R))??"open",T=r.createElement("div");T.className="snag-pin snag-cluster",T.style.cssText=`${it};border-radius:50%;background:${Bn(D)};color:${Mn(D)};border:2px solid ${k.onAccent}`,T.style.left=`${w}px`,T.style.top=`${x}px`,T.textContent=String($.length),T.setAttribute("data-count",String($.length)),T.setAttribute("data-state",D),T.setAttribute("role","button"),T.setAttribute("tabindex","0"),E&&T.setAttribute("aria-expanded","true"),T.setAttribute("aria-label",Z("cluster.aria",{n:$.length,list:$.map(R=>R.ordinal).join(", ")})),Ne(T,()=>{if(E)ne=null;else if($.length<=6)ne=L;else{o?.($.map(R=>R.snag.id));return}$e()}),u.appendChild(T),ee.push(T)}function _e($,w,x,L){dt($,w,x,L,!0),$.forEach((E,D)=>{const T=w,R=x+(D+1)*(j+12),J=E.x-T,V=E.y-R,N=Math.hypot(J,V);if(N>4){const q=r.createElement("div");q.className="snag-leader",q.setAttribute("aria-hidden","true"),q.style.cssText=`position:absolute;left:${T}px;top:${R}px;width:${N}px;height:0;border-top:1px solid ${k.onAccent};transform-origin:0 0;transform:rotate(${Math.atan2(V,J)}rad)`,u.appendChild(q),ee.push(q)}const M=E.dot.cloneNode(!0);M.style.visibility="",M.style.left=`${T}px`,M.style.top=`${R}px`,Ne(M,()=>t?.(E.snag)),u.appendChild(M),ee.push(M)})}function $e(){for(const E of ee)E.remove();ee=[];const $=[];for(const[E,D]of H){if(E.hidden){E.style.visibility="";continue}const T=I.get(E);T&&$.push({dot:E,snag:D.snag,ordinal:D.ordinal,x:T.x,y:T.y})}const{members:w,visits:x}=Tr($,b);u.setAttribute("data-cv",String(x)),u.setAttribute("data-cp",String($.length));let L=!1;for(const E of w){if(E.length<2){$[E[0]].dot.style.visibility="";continue}const D=E.map(V=>$[V]),T=D.map(V=>V.snag.id).sort().join("|");for(const V of D)V.dot.style.visibility="hidden";const R=D.reduce((V,N)=>V+N.x,0)/D.length,J=D.reduce((V,N)=>V+N.y,0)/D.length;ne===T&&D.length<=6?(L=!0,_e(D,R,J,T)):dt(D,R,J,T,!1)}ne&&!L&&(ne=null)}function Ve($){le?.remove(),le=null;const w=$.anchor.rect;if(!w)return;const x=$.anchor.offset??{fx:.5,fy:.5},L=r.createElement("div");L.className="snag-pin snag-ghost",L.style.cssText=`${it};${$t};background:transparent;border:2px dashed ${k.anchorOrphan};color:${k.anchorOrphan};box-shadow:none;pointer-events:none`;const E=te(w.x+w.w*x.fx-X.x,w.y+w.h*x.fy-X.y,z());L.style.left=`${E.x}px`,L.style.top=`${E.y}px`,L.setAttribute("aria-hidden","true"),u.appendChild(L),le=L}function de($=!1){const w=$?[...d,...v]:d;G||w.length===0||(G=!0,l.requestAnimationFrame(()=>{G=!1;const x=performance.now(),L=l.scrollX,E=l.scrollY,D=W(),T=w.map(N=>N.el.isConnected?N.el.getBoundingClientRect():null),R=w.map(N=>N.el.isConnected&&kt(N.el)),J=Ge(w),V=z();w.forEach((N,M)=>{const q=T[M];if(!q)return;if(N.node.hasAttribute("data-fo")){N.node.hidden=!0;return}if(!R[M]){N.node.hidden=!0;return}N.node.hidden=!1;const ve=q.left+q.width*N.fx,we=q.top+q.height*N.fy;if(N.node.parentElement===a)N.node.style.left=`${ve-D.left}px`,N.node.style.top=`${we-D.top}px`,ie(N,q,J),I.set(N.node,{x:ve+L-X.x,y:we+E-X.y});else{const re=te(ve+L-X.x,we+E-X.y,V);N.node.style.left=`${re.x}px`,N.node.style.top=`${re.y}px`,I.set(N.node,re)}}),$e(),u.setAttribute("data-ms",(performance.now()-x).toFixed(2))}))}const ut=()=>de();r.addEventListener("scroll",ut,{capture:!0,passive:!0});const Ye=typeof l.ResizeObserver=="function"?new l.ResizeObserver(()=>de(!0)):null;Ye?.observe(r.documentElement);let Ie=null,be="";function Mt(){let $="";for(const w of[...v,...d]){if(!w.el.isConnected)continue;const x=w.el.getBoundingClientRect();$+=`${Math.round(x.left)},${Math.round(x.top)},${Math.round(x.width)};`}!$||$===be||(be=$,de(!0))}function He($){if(Ie&&clearTimeout(Ie),Ie=null,!$)return;const w=()=>{Mt(),Ie=setTimeout(w,500)};Ie=setTimeout(w,500)}const he=()=>He(r.visibilityState==="visible"&&_.size>0);r.addEventListener("visibilitychange",he);function Ot($){const w=_.get($);w&&(w.classList.remove("snag-pp"),l.requestAnimationFrame(()=>w.classList.add("snag-pp")),l.setTimeout(()=>w.classList.remove("snag-pp"),1400))}function ye($){const w=h?_.get(h):void 0;w&&(w.style.transform="",w.style.zIndex=""),h=$;const x=$?_.get($):void 0;x&&(x.style.transform="scale(1.4)",x.style.zIndex="1")}return{el:u,render:U,showGhost:Ve,pulse:Ot,reanchor:C,settled:()=>ae,hasPending:()=>K.size>0,highlight:ye,destroy(){r.removeEventListener("scroll",ut,{capture:!0}),r.removeEventListener("visibilitychange",he),Ye?.disconnect(),He(!1),u.remove(),a.remove()}}}const Or=` .snag-notice{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(24px + var(${P.tbH},56px));z-index:${qe.notice};max-width:min(420px,calc(100vw - 24px));background:${k.bg};color:${k.fg};border:1px solid ${k.border};border-inline-start:3px solid ${k.anchorOrphan};border-radius:${k.radius};box-shadow:${k.shadow};padding:12px 14px;pointer-events:auto;font:400 13px/1.45 ${k.font};display:flex;flex-direction:column;gap:10px}@media (pointer:coarse){.snag-notice{bottom:calc(12px + var(${P.tbH},64px))}}.snag-notice p{margin:0}.snag-notice-actions{display:flex;gap:6px;justify-content:flex-end}.snag-notice button{appearance:none;font:inherit;cursor:pointer;border-radius:calc(${k.radius} - 2px);padding:6px 12px;min-height:30px;border:0;transition:background ${k.motion}}.snag-notice-retry{background:${k.accent};color:${k.onAccent};font-weight:600}.snag-notice-dismiss{background:transparent;color:${k.muted}}.snag-notice-dismiss:hover{background:${k.hover};color:inherit}.snag-notice button:focus-visible{outline:2px solid ${k.focus};outline-offset:2px}`;function zr(e,t){const n=e.ownerDocument??document,o=n.defaultView??window;at(e,"notice",Or);const r=n.createElement("div");r.className="snag-notice",r.setAttribute("role","alert"),r.hidden=!0;const l=n.createElement("p"),u=n.createElement("div");u.className="snag-notice-actions";const a=n.createElement("button");a.type="button",a.className="snag-notice-dismiss",a.textContent=Z("action.dismiss"),a.addEventListener("click",()=>_());const d=n.createElement("button");d.type="button",d.className="snag-notice-retry",u.append(a,d),r.append(l,u);let v;d.addEventListener("click",()=>{_(),v?.run()});let S=0;function _(){S&&o.cancelAnimationFrame(S),S=0,r.hidden=!0,r.remove()}return{show(h,I,H){v=I,d.hidden=!I,I&&(d.textContent=Z(I.label)),r.hidden=!1,l.textContent="",(t??e).appendChild(r);const F=Z(h,H);S&&o.cancelAnimationFrame(S),S=o.requestAnimationFrame(()=>{S=0,l.textContent=F})},hide:_,visible:()=>r.isConnected&&!r.hidden,destroy(){r.remove()}}}const Lr=` .snag-paused{border:0;padding:0;background:transparent;pointer-events:auto;max-width:min(420px,calc(100vw - 32px))}.snag-paused::backdrop{background:rgb(0 0 0 / .28)}.snag-paused-box{background:${k.bg};color:${k.fg};border:1px solid ${k.border};border-inline-start:3px solid ${k.accent};border-radius:${k.radius};box-shadow:${k.shadow};padding:14px 16px;font:400 13px/1.45 ${k.font};display:flex;flex-direction:column;gap:12px}.snag-paused p{margin:0}.snag-paused-actions{display:flex;justify-content:flex-end}.snag-paused button{appearance:none;font:inherit;cursor:pointer;border:0;font-weight:600;border-radius:calc(${k.radius} - 2px);padding:6px 14px;min-height:30px;background:${k.accent};color:${k.onAccent}}.snag-paused button:focus-visible{outline:2px solid ${k.focus};outline-offset:2px}`;function Dr(e,t){const n=e.ownerDocument??document;at(e,"paused",Lr);const o=n.createElement("dialog");o.className="snag-paused",o.setAttribute("aria-label",Z("paused.dialog"));const r=n.createElement("div");r.className="snag-paused-box",r.setAttribute("role","status");const l=n.createElement("p");l.textContent=Z("paused.dialog");const u=n.createElement("div");u.className="snag-paused-actions";const a=n.createElement("button");a.type="button",a.textContent=Z("paused.close"),a.addEventListener("click",()=>S()),u.append(a),r.append(l,u),o.append(r);let d=!1;function v(){if(!d){(t??e).appendChild(o);try{o.showModal(),d=!0}catch{o.setAttribute("open",""),d=!0}}}function S(){if(d){d=!1;try{o.close()}catch{o.removeAttribute("open")}o.remove()}}return o.addEventListener("close",()=>{d=!1,o.remove()}),{show:v,hide:S,destroy(){S(),o.remove()}}}const Nr=Symbol.for(kn.original),Vn=Symbol.for(kn.wrapped),ct=()=>{};function Hr(e,t,n){let o;try{o=e[t]}catch{return ct}if(typeof o!="function"||o[Vn])return ct;const r=o,l=n(r);let u=!1;const a=function(...d){return u?r.apply(this,d):l.apply(this,d)};try{const d=a;d[Vn]=!0,d[Nr]=r,Object.defineProperty(a,"name",{value:r.name,configurable:!0}),Object.defineProperty(a,"length",{value:r.length,configurable:!0})}catch{}try{e[t]=a}catch{return ct}return e[t]!==a?ct:()=>{let d;try{d=e[t]}catch{d=void 0}if(d===a)try{e[t]=r;return}catch{}u=!0}}function Wr(e,t){const n=[];let o=0;const r=()=>{o||(o=e.requestAnimationFrame(()=>{o=0,t.onResize()}))};e.addEventListener("resize",r),n.push(()=>{o&&e.cancelAnimationFrame(o),e.removeEventListener("resize",r)}),e.visualViewport?.addEventListener("resize",r),n.push(()=>e.visualViewport?.removeEventListener("resize",r));const l=()=>void e.setTimeout(t.onResize,250);e.addEventListener("orientationchange",l),n.push(()=>e.removeEventListener("orientationchange",l));let u=e.location.pathname;const a=()=>{const b=e.location.pathname;b!==u&&(u=b,t.onRoute())},d=e.navigation;if(d){const b=()=>void e.setTimeout(a,0);d.addEventListener("navigatesuccess",b),n.push(()=>d.removeEventListener("navigatesuccess",b))}else for(const b of["pushState","replaceState"])n.push(Hr(e.history,b,j=>function(...ee){const ne=j.apply(this,ee);return e.setTimeout(a,0),ne}));const v=e.document;let S=!0;try{v.documentElement.matches(":modal")}catch{S=!1}const _=()=>{const b=v.querySelectorAll("dialog[open]");if(!S)return b.length>0;for(const j of b)if(j.matches(":modal"))return!0;return!1};let h=!1;const I=()=>{const b=_();b!==h&&(h=b,t.onModal(b))};v.addEventListener("toggle",I,!0),n.push(()=>v.removeEventListener("toggle",I,!0));const H=new MutationObserver(I);H.observe(v.documentElement,{subtree:!0,attributes:!0,attributeFilter:["open"]}),n.push(()=>H.disconnect());const F=()=>void e.setTimeout(a,0);return e.addEventListener("popstate",F),n.push(()=>e.removeEventListener("popstate",F)),{destroy(){for(const b of n)b();n.length=0}}}function jr(e,t){try{e.sessionStorage.setItem(se.handoff,JSON.stringify({openThreadId:t}))}catch{}}function Fr(e){try{const t=e.sessionStorage.getItem(se.handoff);if(t===null)return null;e.sessionStorage.removeItem(se.handoff);const n=JSON.parse(t);return typeof n.openThreadId=="string"?n.openThreadId:null}catch{return null}}const Et=["open","progress","review","resolved"];function Yn(){return{statuses:[...Et],read:"all",pageOnly:!1,newOnly:!1,sort:"page"}}function Xn(e){return e.length>0&&!Et.every(t=>e.includes(t))}function Ur(e,t,n){if(Xn(t.statuses)&&Et.includes(e.status)&&!t.statuses.includes(e.status)||t.by&&e.createdBy.id!==t.by||t.assignee!==void 0&&(e.assignee?.id??null)!==t.assignee||t.page&&e.route!==t.page)return!1;if(t.read!=="all"&&n){const o=Kn(e,n);if(t.read==="unread"&&!o||t.read==="read"&&o)return!1}return!0}function Kn(e,t){const n=t.get(e.id)??0;return Date.parse(e.updatedAt)>n}function Br(e,t){try{const n=JSON.parse(sessionStorage.getItem(se.filter(e,t))??"0");if(n?.v!==1)return null;const o=Yn(),r=Et.filter(l=>Array.isArray(n.statuses)&&n.statuses.includes(l));r.length&&(o.statuses=r),(n.read==="unread"||n.read==="read")&&(o.read=n.read),(n.sort==="newest"||n.sort==="oldest")&&(o.sort=n.sort),n.pageOnly===!0&&(o.pageOnly=!0);for(const l of["by","page","q"])typeof n[l]=="string"&&n[l]&&(o[l]=n[l]);return(n.assignee===null||typeof n.assignee=="string"&&n.assignee)&&(o.assignee=n.assignee),o}catch{return null}}function Zr(e,t,n){try{const{newOnly:o,...r}=n;sessionStorage.setItem(se.filter(e,t),JSON.stringify({v:1,...r}))}catch{}}function Vr(e,t,n){const o=e.visualViewport;let r=0;const l=()=>{if(r=0,!o)return;const a=o.offsetLeft,d=o.offsetTop;t.style.translate=a||d?`${a}px ${d}px`:"",t.style.width=`${o.width}px`,t.style.height=`${o.height}px`,n?.(o.scale)},u=()=>{r||(r=e.requestAnimationFrame(l))};return o?.addEventListener("resize",u,{passive:!0}),o?.addEventListener("scroll",u,{passive:!0}),u(),()=>{r&&e.cancelAnimationFrame(r),o?.removeEventListener("resize",u),o?.removeEventListener("scroll",u)}}const Yr=/^eyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/,Xr=/^[a-f0-9]{32,}$/i,Kr=/^(?=[A-Za-z0-9_-]{24,}$)(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9_-]+$/,Jr="[redacted]";function Jn(e){return e.includes("/")?e.split("/").map(t=>Yr.test(t)||Xr.test(t)||Kr.test(t)?Jr:t).join("/"):e}const qr=/\/index\.(html?|php)$/i;function Qr(e){if(!e.startsWith("/"))return e;let t=e.replace(qr,"/");return t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t.toLowerCase()}function Gr(e){try{const t=e.querySelector(`meta[name="${Jo.route}"]`)?.getAttribute("content")?.trim();return!t||t.length>512||!t.startsWith("/")?null:t}catch{return null}}function es(e,t){const n=t??Gr(e);return Qr(n??Jn(e.location.pathname))}const ts=[/^utm_/,/^(gclid|gbraid|wbraid|fbclid|msclkid|ttclid|twclid|igshid|yclid|li_fat_id)$/,/^(mc_cid|mc_eid|_hsenc|_hsmi|vero_id|oly_enc_id|oly_anon_id)$/,/^_vercel_/,/^__vercel_/,/^_rsc$/],ns=[...St.query,...St.fragment];function os(e,t=[]){return ns.includes(e)||t.includes(e)?!0:ts.some(n=>n.test(e))}function rs(e,t={}){const n=t.significantQueryParams??[];if(n!=="*"&&n.length===0)return;let o;try{o=new URLSearchParams(e)}catch{return}const r={};for(const[l,u]of o)os(l,t.ignoredQueryParams??[])||n!=="*"&&!n.includes(l)||(r[l]=u);return Object.keys(r).length>0?r:void 0}function ss(e,t,n={}){const o=n.significantQueryParams??[];if(o==="*"){const r=e??{},l=t??{},u=new Set([...Object.keys(r),...Object.keys(l)]);for(const a of u)if(r[a]!==l[a])return!1;return!0}for(const r of o)if((e?.[r]??void 0)!==(t?.[r]??void 0))return!1;return!0}const as=120,is=1e3,cs=200,ls=1e4;function ds(e,t,n){const o=t.MutationObserver;if(typeof o!="function")return{destroy:()=>{}};let r=!1,l=null,u=!1,a=!1,d=0,v=_(),S=0;function _(){return t.performance?.now?.()??0}const h=new o(()=>{r=!0,d++,H()});function I(){const b=_();return b-v>=1e3&&(d>cs&&(S=b+ls),d=0,v=b),b<S?is:as}function H(){l||(l=setTimeout(F,I()))}function F(){if(l=null,!!r){if(u){a=!0;return}r=!1,u=!0;try{n()}finally{u=!1,a&&(a=!1,r=!0,H())}}}return h.observe(e.documentElement,{childList:!0,subtree:!0}),{destroy(){h.disconnect(),l&&clearTimeout(l),l=null}}}const qn="0.1.67+74eb73",us={capture:Oe.capture,"anchor-ext":Oe.anchorExt,"anchor-fuzzy":Oe.anchorFuzzy,crumbs:Oe.crumbs,screenshot:Oe.screenshot,dock:Oe.dock,text:Oe.text},Qn=new Map,Jt=new Map,Gn=new Map;function fs(e,t,n){const o=new URL(t,n.location.href).href,r=new URL(us[e],o);r.searchParams.set("cv",qn);const l=Gn.get(e)??0;return l>0&&r.searchParams.set("r",String(l)),Gn.set(e,l+1),r.href}async function ze(e,t,n=document){const o=Qn.get(e);if(o)return{ok:!0,mod:o};const r=Jt.get(e);if(r)return r;const l=(async()=>{for(let u=0;u<2;u++)try{const a=await import(fs(e,t,n));return Qn.set(e,a),{ok:!0,mod:a}}catch{}return{ok:!1,reason:"unavailable"}})();Jt.set(e,l);try{return await l}finally{Jt.delete(e)}}const hs="composer",qt=e=>se.draft(e,hs),ps=se.draft("\0","").split("\0")[0];function ms(e){try{return e.body.trim()?(localStorage.setItem(qt(e.route),JSON.stringify(e)),!0):(eo(e.route),!0)}catch{return!1}}function gs(e){try{const t=localStorage.getItem(qt(e));if(!t)return null;const n=JSON.parse(t);return!n||typeof n.body!="string"||!n.anchor||n.route!==e?null:n}catch{return null}}function eo(e){try{localStorage.removeItem(qt(e))}catch{}}function Qt(){try{for(let e=0;e<localStorage.length;e++){const t=localStorage.key(e);if(t&&t.startsWith(ps))return!0}return!1}catch{return!1}}const ys="http://www.w3.org/2000/svg";function Le(e,t,n,o=[]){const r=e.createElementNS(ys,t);for(const l in n)r.setAttribute(l,n[l]);for(const l of o)r.appendChild(l);return r}const Gt=(e,t="16",n="16",o="0 0 16 16")=>({width:t,height:n,viewBox:o,fill:"none","aria-hidden":"true"}),bs=e=>Le(e,"svg",Gt(),[Le(e,"path",{d:"M8 3v10M3 8h10",stroke:"currentColor","stroke-width":"1.75","stroke-linecap":"round"})]),vs=e=>Le(e,"svg",Gt(),[Le(e,"rect",{x:"2.25",y:"3.25",width:"11.5",height:"9.5",rx:"1.75",stroke:"currentColor","stroke-width":"1.5"}),Le(e,"path",{d:"M9.5 3.5v9",stroke:"currentColor","stroke-width":"1.5"})]),ws=e=>Le(e,"svg",{...Gt(e,"10","16","0 0 10 16"),fill:"currentColor"},[Le(e,"g",{fill:"currentColor"},[4,8,12].flatMap(t=>[3,7].map(n=>Le(e,"circle",{cx:String(n),cy:String(t),r:"1"}))))]),xs=` .snag-tb{position:fixed;z-index:${qe.toolbar};display:flex;align-items:center;gap:2px;padding:4px;border-radius:calc(${k.radius} + 4px);background:${k.bg};color:${k.fg};box-shadow:${k.shadow};font:500 13px/1 ${k.font};pointer-events:auto;user-select:none;border:1px solid ${k.border}}.snag-tb{transition:inset-inline-end ${k.motion}}.snag-tb--fine{inset-inline-end:calc(20px + env(safe-area-inset-right) + var(${P.dockW},0px));inset-block-end:calc(20px + env(safe-area-inset-bottom));transition:inset-inline-end ${k.motion}}.snag-tb--coarse{inset-inline:0;inset-block-end:0;border-radius:14px 14px 0 0;padding:6px 10px calc(6px + env(safe-area-inset-bottom));justify-content:center;gap:4px;flex-direction:column}.snag-grabber{width:36px;height:4px;border-radius:2px;background:${k.muted};margin:2px auto 6px}.snag-row{display:flex;align-items:center;gap:2px}.snag-grip{display:flex;align-items:center;padding:0 4px;color:${k.muted};cursor:grab;touch-action:none}.snag-grip:active{cursor:grabbing}.snag-seg{display:flex;background:${k.surface};border-radius:${k.radius};padding:2px;position:relative}.snag-seg::before{content:"";position:absolute;inset-block:2px;inset-inline-start:var(${P.thumbX},0);width:var(${P.thumbW},0);background:${k.accent};border-radius:calc(${k.radius} - 2px);pointer-events:none;transition:inset-inline-start ${k.motion},width ${k.motion}}.snag-seg>.snag-b[aria-pressed="true"]{background:transparent;color:${k.onAccent}}.snag-seg>.snag-b{z-index:1}.snag-b{appearance:none;border:0;background:transparent;color:inherit;font:inherit;padding:6px 11px;border-radius:calc(${k.radius} - 2px);cursor:pointer;display:flex;align-items:center;gap:6px;position:relative;min-height:32px;transition:background ${k.motion}}.snag-b:hover:not(:disabled){background:color-mix(in srgb,currentColor 12%,transparent)}.snag-b:disabled{opacity:.4;cursor:not-allowed}.snag-b[aria-pressed="true"]{background:${k.accent};color:${k.onAccent}}.snag-b:focus-visible{outline:2px solid ${k.focus};outline-offset:2px}.snag-icon{padding:6px 9px}@media (pointer:coarse){.snag-b{min-height:44px;min-width:44px;padding:6px 14px}.snag-icon{padding:6px 14px}}.snag-puck .snag-row>:not([aria-expanded]){display:none}.snag-puck{padding:4px;border-radius:50%}.snag-puck [aria-expanded]{min-width:44px;min-height:44px;border-radius:50%}`;function Ss(e,t){const n=e.ownerDocument??document,o=t.coarsePointer??n.defaultView?.matchMedia?.("(pointer: coarse)").matches??!1;at(e,"toolbar",xs);const r=n.createElement("div");r.className=`snag-tb ${o?"snag-tb--coarse":"snag-tb--fine"}`,r.setAttribute("role","toolbar"),r.setAttribute("aria-label",Z("toolbar.aria"));const l=n.createElement("div");l.className="snag-grabber",l.setAttribute("aria-hidden","true");const u=n.createElement("div");u.className="snag-row";const a=n.createElement("span");a.className="snag-grip",a.setAttribute("aria-hidden","true"),a.appendChild(ws(n));const d=n.createElement("div");d.className="snag-seg",d.setAttribute("role","group"),d.setAttribute("aria-label",Z("toolbar.group"));const v=(i,p,y)=>{const m=n.createElement("button");return m.type="button",m.className=`snag-b ${i}`,m.setAttribute("aria-label",p),typeof y=="string"?m.textContent=y:m.appendChild(y),m},S=v("",Z("toolbar.browse"),Z("toolbar.browse")),_=v("",Z("toolbar.comments"),Z("toolbar.comments")),h=v("snag-icon",Z("toolbar.add"),bs(n)),I=v("snag-icon",Z("toolbar.panel"),vs(n));I.setAttribute("aria-expanded","false"),d.append(S,_),o||u.appendChild(a),u.append(d,h,I),o&&r.appendChild(l),r.appendChild(u),(t.parent??e).appendChild(r);const H=()=>{e.host.style.setProperty(P.tbH,`${r.offsetHeight}px`)};H();let F=null;function b(i,p){const y=n.defaultView,m=r.offsetWidth,C=r.offsetHeight,z=to(i,8,Math.max(8,y.innerWidth-m-8)),te=to(p,8,Math.max(8,y.innerHeight-C-8));F={left:z,top:te},r.style.left=`${z}px`,r.style.top=`${te}px`,r.style.right="auto",r.style.bottom="auto"}const j=()=>{H(),F&&b(F.left,F.top)},ee=n.defaultView;if(ee?.addEventListener("resize",j),S.addEventListener("click",()=>t.onState("browse")),_.addEventListener("click",()=>t.onState("comments")),h.addEventListener("click",()=>t.onState(ne==="add"?"comments":"add")),I.addEventListener("click",()=>t.onPanel()),!o){let i=null;a.addEventListener("pointerdown",y=>{i={x:y.clientX,y:y.clientY,r:r.getBoundingClientRect()},a.setPointerCapture(y.pointerId),y.preventDefault()}),a.addEventListener("pointermove",y=>{i&&b(i.r.left+(y.clientX-i.x),i.r.top+(y.clientY-i.y))});const p=y=>{i=null,a.hasPointerCapture(y.pointerId)&&a.releasePointerCapture(y.pointerId)};a.addEventListener("pointerup",p),a.addEventListener("pointercancel",p)}let ne="browse";function le(i){ne=i,S.setAttribute("aria-pressed",String(i==="browse")),_.setAttribute("aria-pressed",String(i!=="browse")),h.setAttribute("aria-pressed",String(i==="add")),X()}function X(){const i=d.querySelector('.snag-b[aria-pressed="true"]'),p=d.getBoundingClientRect(),y=i?.getBoundingClientRect();if(!i||!y?.width){d.style.setProperty(P.thumbW,"0px");return}const m=n.defaultView?.getComputedStyle(d),C=m?.direction==="rtl",z=parseFloat((C?m?.paddingRight:m?.paddingLeft)??"0")||0,te=(C?p.right-y.right:y.left-p.left)-z;d.style.setProperty(P.thumbW,`${Math.round(y.width)}px`),d.style.setProperty(P.thumbX,`${Math.max(0,Math.round(te))}px`)}function ue(i){h.disabled=i,i?h.title=Z("error.panels.add"):h.removeAttribute("title")}function ae(i){h.setAttribute("aria-label",Z(i?"toolbar.add.draft":"toolbar.add"))}function K(i){_.setAttribute("aria-label",i!==null&&i>0?Z("toolbar.comments.unresolved",{n:tr(i)}):Z("toolbar.comments"))}le("browse"),K(0);function oe(i){r.classList.toggle("snag-puck",i),i||X()}function g(i){r.hidden=i,i||X(),H()}return{el:r,setState:le,setCount:K,setDegraded:ue,setDraft:ae,setPuck:oe,setConcealed:g,destroy(){ee?.removeEventListener("resize",j),e.host.style.removeProperty(P.tbH),r.remove()}}}const to=(e,t,n)=>e<t?t:e>n?n:e,no=24;function As(e,t){const n=e.innerHeight,o=t.querySelector(".snag-dk");if(!o)return{top:0,bottom:n};const r=o.getBoundingClientRect();return r.height>=n-1?{top:0,bottom:n}:{top:0,bottom:Math.max(0,r.top)}}function ks(e,t,n){const o=n.anchor.rect;if(!o)return;const r=n.anchor.offset??{fy:.5},l=o.y+o.h*r.fy,u=As(e,t),a=l-e.scrollY;if(a>=u.top+no&&a<=u.bottom-no)return;const d=e.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;e.scrollTo({top:Math.max(0,l-(u.top+u.bottom)/2),behavior:d?"auto":"smooth"})}function en(){const e=new Uint8Array(16);crypto.getRandomValues(e);const t=Date.now();e[0]=Math.floor(t/2**40)&255,e[1]=Math.floor(t/2**32)&255,e[2]=Math.floor(t/2**24)&255,e[3]=Math.floor(t/2**16)&255,e[4]=Math.floor(t/2**8)&255,e[5]=t&255,e[6]=e[6]&15|112,e[8]=e[8]&63|128;const n=Array.from(e,o=>o.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}const $s=()=>At.thread+en(),oo=()=>At.comment+en(),Es=()=>At.attachment+en(),Cs={attachments:"direct",realtime:"none",anchorReports:!1,identity:["guest"],export:["json","md"],serverSideSearch:!1,privateThreads:!1,assignees:!1};function Ts(){const e=se.threads("probe","probe");try{return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch(t){return ro(t)}}function Rs(e,t,n){const o=se.threads(e,t);function r(){let a=null;try{a=localStorage.getItem(o)}catch{return[]}if(!a)return[];try{const d=JSON.parse(a);return Array.isArray(d)?d.filter(Is):[]}catch{return[]}}function l(a){try{localStorage.setItem(o,JSON.stringify(a))}catch(d){if(!ro(d))return;throw new Zt("local_quota_exceeded")}}const u=a=>({...a,updatedAt:new Date().toISOString()});return{kind:"local",capabilities:Cs,async init(a){return{uid:a.uid,env:a.env,features:{screenshots:!0,uploads:!1}}},async listThreads(a={}){let d=r();return a.route!==void 0&&(d=d.filter(v=>v.route===a.route)),a.status?.length&&(d=d.filter(v=>a.status.includes(v.status))),{data:d,serverTime:new Date().toISOString()}},async getThread(a){return r().find(d=>d.id===a)??null},async createThread(a){const d=zn(a);return l([...r(),d]),d},async patchThread(a,d){const v=r(),S=v.findIndex(H=>H.id===a);if(S<0)return null;const{assignee:_,...h}=d,I=u({...v[S],..._s(h)});return v[S]=I,l(v),I},async deleteThread(a){const d=r(),v=d.find(_=>_.id===a),S=d.filter(_=>_.id!==a);S.length!==d.length&&l(S);for(const _ of v?.attachments??[])n?.del(_.id).catch(()=>{})},async uploadAttachment(a,d){if(!n)throw new Zt("attachments_unsupported");const v=Es();return await n.put(v,{blob:a,uid:e,env:t,kind:d.kind,...d.width!==void 0?{width:d.width}:{},...d.height!==void 0?{height:d.height}:{},createdAt:Date.now()}),{id:v,kind:d.kind,url:"",...d.width!==void 0?{width:d.width}:{},...d.height!==void 0?{height:d.height}:{},bytes:a.size,contentType:a.type}},async createComment(a,d){const v=r(),S=v.findIndex(h=>h.id===a);if(S<0)return null;const _={id:d.id,snagId:a,body:d.body,author:d.author,createdAt:new Date().toISOString()};return v[S]=u({...v[S],comments:[...v[S].comments,_]}),l(v),_},async patchComment(a,d){const v=r();for(let S=0;S<v.length;S++){const _=v[S].comments.find(I=>I.id===a);if(!_)continue;const h={..._,body:d};return v[S]=u({...v[S],comments:v[S].comments.map(I=>I.id===a?h:I)}),l(v),h}return null},async deleteComment(a){const d=r(),v=d.findIndex(S=>S.comments.some(_=>_.id===a));v<0||(d[v]=u({...d[v],comments:d[v].comments.filter(S=>S.id!==a)}),l(d))}}}function _s(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ro(e){return e instanceof Error?e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED"||e.code===22||e.code===1014:!1}function Is(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.id=="string"&&typeof t.key=="string"&&typeof t.route=="string"&&typeof t.anchor=="object"&&t.anchor!==null&&typeof t.anchor.label=="string"&&Array.isArray(t.comments)}function Ps(e,t,n=()=>Date.now()){const o=se.seen(e,t);let r=null;function l(){if(r)return r;try{const a=localStorage.getItem(o),d=a?JSON.parse(a):{};return r=typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{}}catch{return r={}}}function u(a){r=a;try{localStorage.setItem(o,JSON.stringify(a))}catch{}}return{map:()=>new Map(Object.entries(l())),mark(a){u({...l(),[a]:n()})},markAll(a){const d=n(),v={...l()};for(const S of a)v[S.id]=d;u(v)}}}function lt(){let e=null;try{e=localStorage.getItem(Ft)}catch{return{}}if(!e)return{};if(e[0]!=="{")return{name:e};try{const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function so(e){try{localStorage.setItem(Ft,JSON.stringify(e))}catch{}}function tn(){const e=lt();return{name:typeof e.name=="string"?e.name:"",...e.email?{email:e.email}:{}}}function ao(e){return lt().projects?.[e]?.holderId}function Ms(e){const t=lt().projects?.[e]?.holderSecret;return t&&/^[\w-]{43}$/.test(t)?t:void 0}function Os(e,t,n){const o=lt();so({...o,projects:{...o.projects,[e]:{holderId:t,holderSecret:n}}})}function zs(e,t){const n=lt(),o=n.projects?.[e];o&&so({...n,projects:{...n.projects,[e]:{...o,holderId:t}}})}const Ls=1e6,Ct=e=>e==="member"?localStorage:sessionStorage;function io(e,t){const n=JSON.parse(Ct(t).getItem(se.list(e,t))??"0");return n?.v===1&&n.m&&typeof n.m=="object"?n.m:{}}function co(e,t,n){try{const o=io(e,t)[n];return Array.isArray(o)?o:null}catch{return null}}function Ds(e,t,n,o){const r=se.list(e,t);try{let l={};try{l=io(e,t)}catch{}l[n]=o;const u=JSON.stringify({v:1,m:l});u.length>Ls?Ct(t).removeItem(r):Ct(t).setItem(r,u)}catch{}}function Tt(e,t){try{Ct(t).removeItem(se.list(e,t))}catch{}}const Ze=e=>se.session(e);function lo(e){if(!e)return null;const t=JSON.parse(e);return typeof t?.token=="string"&&typeof t?.refreshableUntil=="number"?t:null}function Qe(e){try{const t=lo(sessionStorage.getItem(Ze(e)));if(t)return t;const n=lo(localStorage.getItem(Ze(e)));return n?.member?n:null}catch{return null}}function nn(e,t){try{t.member?(localStorage.setItem(Ze(e),JSON.stringify(t)),sessionStorage.removeItem(Ze(e))):sessionStorage.setItem(Ze(e),JSON.stringify(t))}catch{}}function Ns(e){try{sessionStorage.removeItem(Ze(e)),localStorage.removeItem(Ze(e))}catch{}}const Hs=(e,t=Date.now())=>t>e.expiresAt-3e4,Rt=(e,t=Date.now())=>t>=e.refreshableUntil;class Ae extends Error{code;status;constructor(t,n,o){super(o),this.name="HttpAdapterError",this.status=t,this.code=n}}function Ws(e){const{offset:t,testId:n,domId:o,page:r,schemaVersion:l,...u}=e;return{...u,...n?{testid:n}:{},...o?{domid:o}:{},...t?{offset:{fx:t.x,fy:t.y}}:{}}}function js(e,t){const n=e.url??"",o=/^https?:/i.test(n)?n:n?`${t}${n.startsWith("/")?"":"/"}${n}`:`${t}/api/v1/attachments/${encodeURIComponent(e.id)}/blob`;return{...e,url:o}}function _t(e,t,n){return{id:e.id,route:e.anchor?.page?.route??"",key:e.key,status:e.status,anchor:Ws(e.anchor),anchorState:e.anchorState,context:e.context,comments:e.comments??[],createdBy:e.createdBy,assignee:e.assignee??null,...e.private?{private:!0}:{},createdAt:e.createdAt,updatedAt:e.updatedAt,...e.resolvedAt?{resolvedAt:e.resolvedAt}:{},...e.attachments?.length?{attachments:e.attachments.map(o=>js(o,n))}:{},...t?{scope:{environment:t}}:{}}}function Fs(e,t){const{offset:n,testid:o,domid:r,...l}=e;return{...l,schemaVersion:Sn,...o?{testId:o}:{},...r?{domId:r}:{},offset:n?{x:n.fx,y:n.fy}:{x:.5,y:.5},page:{route:t,pathname:location.pathname,origin:location.origin}}}function Us(e,t){const n=o=>/^[\d.]+$|:/.test(o)?o:o.split(".").slice(-2).join(".");return n(e)===n(t)}const uo=10*6e4;function Bs(e,t,n,o={}){const r=e.replace(/\/+$/,""),l=`${r}/api/v1/projects/${encodeURIComponent(t)}`;let u=o.reviewToken,a=Qe(t);const d=()=>a?.member?"member":"guest",v=()=>`${n??""}:${a?.round??""}`;let S="";const _=g=>{S==d()+v()&&Ds(t,d(),v(),g)},h=()=>{S="",Ns(t),Tt(t,"member"),Tt(t,"guest")};let I=[];const H=se.silent(t);let F=0,b=Promise.resolve(!1);function j(){if(u||Date.now()-F<uo)return b;try{if(!Us(location.hostname,new URL(r).hostname)||localStorage.getItem(H)||Date.now()-Number(sessionStorage.getItem(H))<uo)return b}catch{}return F=Date.now(),b=(async()=>{try{const g=await fetch(`${l}/sessions/member/silent`,{method:"POST",credentials:"include",...n?{body:JSON.stringify({environment:n})}:{}});if(g.status===201)return ne(await g.json()),F=0,!0}catch{}try{sessionStorage.setItem(H,String(Date.now()))}catch{}return!1})()}let ee=null;function ne(g){Tt(t,"member"),a={token:g.sessionToken,expiresAt:Date.parse(g.expiresAt),refreshableUntil:Date.parse(g.refreshableUntil),reviewerId:g.reviewer.id,permissions:g.permissions,member:g.reviewer.name,...g.moderator?{moderator:!0}:{}},nn(t,a),o.onSessionStarted?.()}const le=()=>a;async function X(g=!1){const i=a&&!Rt(a)?a.token:null,p=!!i&&!u&&!g,y=p?void 0:u?{kind:"link",token:u,name:tn().name||void 0}:{kind:"guest",name:tn().name||"Anonymous",holderId:ao(t),holderSecret:Ms(t)};let m;try{m=await fetch(`${l}/sessions`,{method:"POST",credentials:"omit",headers:{"content-type":"application/json",...i?{Authorization:`Bearer ${i}`}:{}},body:JSON.stringify({...n?{environment:n}:{},...y?{identity:y}:{},client:{widget:Wo,schema:Sn}})})}catch(U){throw new Ae(0,"network_error",U.message)}finally{u=void 0}if(!m.ok){const W=(await m.json().catch(()=>null))?.error?.code??"unauthorized",G=p&&!!a?.member;if(h(),a=null,G&&m.status===401&&await j())return le();throw W==="session_revoked"||W==="token_revoked"?o.onSessionEnded?.("revoked"):m.status===401&&o.onSessionEnded?.("expired"),new Ae(m.status,W,"This review session is not valid.")}const C=await m.json();C.holderSecret&&C.reviewer?Os(t,C.reviewer.id,C.holderSecret):C.reviewer&&zs(t,C.reviewer.id);const z=C.round?.number??(p||g?a?.round:void 0),te=y?y.name:a?.name;return a&&C.reviewer&&C.reviewer.id!==a.reviewerId&&h(),a={token:C.sessionToken,expiresAt:Date.parse(C.expiresAt),refreshableUntil:Date.parse(C.refreshableUntil),reviewerId:C.reviewer?.id??a?.reviewerId??"",permissions:C.permissions??a?.permissions??[],...z!==void 0?{round:z}:{},...p&&a?.member?{member:a.member}:{},...p&&a?.member&&a.moderator?{moderator:!0}:{},...te?{name:te}:{}},nn(t,a),o.onSessionStarted?.(),a}async function ue(){if(a){if(Rt(a)){h(),a=null,await j()||o.onSessionEnded?.("expired");return}await X().catch(()=>{})}}let ae=null;async function K(){if(await(ee??=a?.member?Promise.resolve():j()),a&&Rt(a)&&(h(),a=null,!await j()))return o.onSessionEnded?.("expired"),null;const g=tn().name||null,i=a!==null&&!a.member&&g!==null&&g!==(a.name??null);if(!a||Hs(a)||u||i)try{await(ae??=X(i).finally(()=>ae=null))}catch(p){if(!(p instanceof Ae)||p.status===0)throw p;return null}return a?.token??null}async function oe(g,i,p=!1){const y=await K();let m;try{m=await fetch(l+g,{...i,headers:{"content-type":"application/json",...y?{Authorization:`Bearer ${y}`}:{},...i?.headers??{}},credentials:"omit"})}catch(C){throw new Ae(0,"network_error",C.message)}if(!m.ok){const C=await m.json().catch(()=>null),z=C?.error?.code??"http_error";if(m.status===401&&!p&&z!=="session_revoked"){const te=!!a?.member;return h(),a=null,te&&await j(),oe(g,i,!0)}throw new Ae(m.status,z,C?.error?.message??`The server answered ${m.status}.`)}return await m.json()}return{kind:"http",capabilities:{attachments:"none",realtime:"none",anchorReports:!0,identity:["guest"],export:[],serverSideSearch:!1,privateThreads:!1,assignees:!0},async init(g){K().catch(()=>{});const i=await fetch(`${l}/config`).catch(y=>{throw new Ae(0,"network_error",y.message)});if(!i.ok)throw new Ae(i.status,"http_error",`The server answered ${i.status}.`);const p=await i.json();return this.capabilities.attachments=p.features.screenshots?"direct":"none",I=p.rounds??[],{uid:g.uid,env:g.env,features:p.features,...p.rounds?{rounds:p.rounds}:{},...p.writable===void 0?{}:{writable:p.writable},...p.reason===void 0?{}:{reason:p.reason}}},async reportAnchors(g){if(g.length!==0)for(let i=0;i<g.length;i+=50)try{await oe("/anchor-reports",{method:"POST",body:JSON.stringify({reports:g.slice(i,i+50)})})}catch{return}},revalidate:ue,member:()=>a?.member??null,adoptSession(g){try{localStorage.removeItem(H)}catch{}ne(g)},signOut(){h(),a=null;try{localStorage.setItem(H,"out")}catch{}},remember:_,cached(){if(u||a&&Rt(a))return null;const g=d();return co(t,g,v())??(a?.round===I.find(i=>!i.closed)?.number?co(t,g,`${n??""}:`):null)},getRound(){return a?.round??Qe(t)?.round??null},setRound(g){a&&(a={...a,round:g});const i=Qe(t);i&&nn(t,{...i,round:g})},async fetchForeignImage(g){try{const i=await K(),p=await fetch(`${l}/image?src=${encodeURIComponent(g)}`,{credentials:"omit",...i?{headers:{Authorization:`Bearer ${i}`}}:{}});if(!p.ok)return null;const y=await p.blob();return y.type.startsWith("image/")?y:null}catch{return null}},async uploadAttachment(g,i){const p=await K(),y=await fetch(`${l}/attachments`,{method:"POST",credentials:"omit",headers:{"content-type":g.type||"image/webp",[Ut.attachmentKind]:i.kind,...i.width?{[Ut.attachmentWidth]:String(i.width)}:{},...i.height?{[Ut.attachmentHeight]:String(i.height)}:{},...p?{Authorization:`Bearer ${p}`}:{}},body:g});if(!y.ok){const C=await y.json().catch(()=>null);throw new Ae(y.status,C?.error?.code??"upload_failed",C?.error?.message??"Upload failed.")}const m=await y.json();return{id:m.id,kind:i.kind,contentType:m.contentType,byteSize:m.byteSize,...i.width?{width:i.width}:{},...i.height?{height:i.height}:{},url:`${r}/api/v1/attachments/${m.id}/blob`}},async listThreads(g){const i=!a&&!u;i?K().catch(()=>{}):await K();const p=new URLSearchParams;n&&p.set("env",n),g?.route&&p.set("route",g.route),a?.round&&p.set("round",String(a.round));const y=`/threads?${p}`,m=()=>oe(y),C=d(),z=v(),te=await(i?fetch(l+y,{credentials:"omit"}).then(W=>W.ok?W.json():m(),m):m()).catch(W=>{throw W instanceof Ae&&(W.status===401||W.status===403)&&(Tt(t,C),S=""),W}),U=te.data.map(W=>_t(W,n,r));return S=C+z,_(U),{data:U,...te.nextCursor?{nextCursor:te.nextCursor}:{},deleted:[],serverTime:te.serverTime}},async getThread(g){return(await this.listThreads()).data.find(p=>p.id===g)??null},async getThreadByKey(g){const i=new URLSearchParams({key:g});n&&i.set("env",n);const y=(await oe(`/threads?${i}`)).data[0];return y?_t(y,n,r):null},async createThread(g){const i=a?.round,p=I.some(C=>C.number===i&&!C.closed)?i:void 0,y=C=>oe("/threads",{method:"POST",body:JSON.stringify({id:g.id,anchor:Fs(g.anchor,g.route),anchorState:g.anchorState,context:g.context,...n||C?{scope:{...n?{environment:n}:{},...C?{round:C}:{}}}:{},createdBy:{name:g.createdBy.name},...g.comment?{comment:{id:g.comment.id,body:g.comment.body}}:{},...g.attachments?.length?{attachments:g.attachments.map(z=>z.id)}:{}})}),m=await y(p).catch(C=>{if(p&&C instanceof Ae&&C.code.startsWith("round_"))return y();throw C});return _t(m,n,r)},async patchThread(g,i){const p="assignee"in i;if(!i.status&&!p)return null;const y=await oe(`/threads/${encodeURIComponent(g)}`,{method:"PATCH",body:JSON.stringify({...i.status?{status:i.status}:{},...p?{assignee:i.assignee??null}:{}})});return _t(y,n,r)},async listAssignees(g){return(await oe(`/assignees${g?`?q=${encodeURIComponent(g)}`:""}`)).data??[]},async deleteThread(g){await oe(`/threads/${encodeURIComponent(g)}`,{method:"DELETE"})},isMine(g){return g.id?g.id===(a??Qe(t))?.reviewerId||g.id===ao(t):!1},canModerate(){const g=a??Qe(t);return!!g?.member&&!!g.moderator},can(g){return(a??Qe(t))?.permissions.includes(g)??!1},async createComment(g,i){const p=await oe(`/threads/${encodeURIComponent(g)}/comments`,{method:"POST",body:JSON.stringify({id:i.id,body:i.body})});return{id:p.id,snagId:g,body:p.body,author:p.author,createdAt:p.createdAt}},async patchComment(g,i){return await oe(`/comments/${encodeURIComponent(g)}`,{method:"PATCH",body:JSON.stringify({body:i})}),null},async deleteComment(g){await oe(`/comments/${encodeURIComponent(g)}`,{method:"DELETE"})}}}async function Zs(e,t){if(e.url&&/^https?:/i.test(e.url))try{const n=await fetch(e.url,{credentials:"omit"});if(!n.ok)return null;const o=await n.blob();return o.type&&!o.type.startsWith("image/")?null:o}catch{return null}return t(e.id)}const Vs=64,Ys=4096,Xs=e=>se.counts(e),Ks=e=>e.filter(t=>t.status!=="resolved").length;function Js(e,t,n){const o=new Map;for(const a of t){const d=o.get(a.route)??{n:0,seen:""};a.status!=="resolved"&&d.n++,a.updatedAt>d.seen&&(d.seen=a.updatedAt),o.set(a.route,d)}o.has(n)||o.set(n,{n:0,seen:new Date().toISOString()});const l=[...o.entries()].sort((a,d)=>d[1].seen.localeCompare(a[1].seen)).slice(0,Vs);l.some(([a])=>a===n)||(l[l.length-1]=[n,o.get(n)]);let u={v:1,p:Ks(t),r:Object.fromEntries(l.map(([a,d])=>[a,d.n])),t:new Date().toISOString()};JSON.stringify(u).length>Ys&&(u={...u,r:{}});try{localStorage.setItem(Xs(e),JSON.stringify(u))}catch{return null}return u}function qs(e,t){return e?.r[t]??0}const Qs="pass(?:word|wd)?|pwd|secret|token|api[_-]?key|apikey|auth(?:orization)?|credential|session|sid|cookie|jwt|bearer|otp|mfa|totp|cvv|cvc|ssn|nino|iban|card(?:[_-]?number)?|account[_-]?number|private[_-]?key|signature|client[_-]?secret|refresh[_-]?token|access[_-]?token",Gs=new RegExp(`(["'\`]?)(?<![A-Za-z0-9])(?:${Qs})[\\w-]*\\b\\1?\\s*[:=]\\s*(?:(["'\`])((?:\\\\.|(?!\\2)[^\\\\])*)\\2|([^\\s,;&}\\])]{3,}))`,"gi"),ea=/^(?:Bearer|Basic|Digest|Negotiate|Token)$/i,ta=(e,t,n,o,r,l,u)=>{if(!n&&ea.test(r)&&u.slice(l+e.length).startsWith(" [redacted]")||(n?o:r).startsWith("[redacted"))return e;const a=n?`${n}${o}${n}`:r;return e.slice(0,e.length-a.length)+(n?`${n}[redacted]${n}`:"[redacted]")},fo=/data:[a-z0-9.+-]*\/?[a-z0-9.+-]*;base64,[A-Za-z0-9+/=]{16,}/gi,ho=/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{0,}/g,po=/\b(sk-[A-Za-z0-9]+-[A-Za-z0-9_-]{20,}|sk-ant-[A-Za-z0-9_-]{20,}|sk-[A-Za-z0-9]{20,}|(sk|pk|rk)_(live|test)_[A-Za-z0-9]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{16,}|xox[baprs]-[A-Za-z0-9-]{10,}|xapp-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16}|ASIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{35}|ya29\.[A-Za-z0-9_-]{20,}|SG\.[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{30,}|dop_v1_[a-f0-9]{40,}|shpat_[a-f0-9]{30,}|sbp_[a-f0-9]{30,}|hf_[A-Za-z0-9]{30,}|nvapi-[A-Za-z0-9_-]{20,})\b/g,na=/\b(Bearer|Basic|Digest|Negotiate|Token)\s+[A-Za-z0-9._~+/=-]{8,}/gi,mo=/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z]{2,24})+\b/g,on=/\b(?:\d[ -]?){12,18}\d\b/g,go=/\b(?=[A-Za-z0-9+/]*[a-z])(?=[A-Za-z0-9+/]*[A-Z])(?=[A-Za-z0-9+/]*\d)[A-Za-z0-9+/]{40,}={0,2}\b/g,yo=/\b[0-9a-f]{32,}\b/gi,bo=/\b(?=[A-Za-z0-9_-]*[a-z])(?=[A-Za-z0-9_-]*[A-Z])(?=[A-Za-z0-9_-]*\d)[A-Za-z0-9_-]{40,}\b/g,vo=/\b[a-z][a-z0-9]{1,15}(?:_[a-z0-9]{1,15}){0,2}_(?=[A-Za-z0-9_-]*[A-Z])(?=[A-Za-z0-9_-]*\d)[A-Za-z0-9_-]{24,}\b/g,wo=/\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:[^\s/@]+@/gi,oa=/^(?=[A-Za-z0-9_~.+/=-]*[a-z])(?=[A-Za-z0-9_~.+/=-]*[A-Z])(?=[A-Za-z0-9_~.+/=-]*\d)[A-Za-z0-9_~.+/=-]{24,}$/;function Re(e,t){e.lastIndex=0;const n=e.test(t);return e.lastIndex=0,n}function xo(e){const t=e.replace(/[ -]/g,"");if(t.length<13||t.length>19)return!1;let n=0,o=!1;for(let r=t.length-1;r>=0;r--){let l=t.charCodeAt(r)-48;o&&(l*=2,l>9&&(l-=9)),n+=l,o=!o}return n%10===0}function ra(e){on.lastIndex=0;for(const t of e.matchAll(on))if(xo(t[0]))return!0;return!1}function It(e){let t=e;return t=t.replace(fo,"data:[redacted]"),t=t.replace(na,"$1 [redacted]"),t=t.replace(Gs,ta),t=t.replace(ho,"[redacted:jwt]"),t=t.replace(po,"[redacted:key]"),t=t.replace(vo,"[redacted:key]"),t=t.replace(wo,"[redacted:url-cred]@"),t=t.replace(mo,"[redacted:email]"),t=t.replace(on,n=>xo(n)?"[redacted:card]":n),t=t.replace(bo,n=>`[redacted:b64:${n.length}]`),t=t.replace(go,n=>`[redacted:b64:${n.length}]`),t=t.replace(yo,n=>`[redacted:hex:${n.length}]`),t}const sa=St.query,aa=St.fragment;function ia(e,t=[]){let n;try{const o=globalThis.location?.href;n=new URL(e,o)}catch{return It(e)}n.username="",n.password="";for(const o of[...n.searchParams.keys()]){if(aa.includes(o)){n.searchParams.set(o,"[redacted]");continue}if(sa.includes(o))continue;if(!t.includes(o)){n.searchParams.set(o,"[redacted]");continue}const r=n.searchParams.get(o)??"";It(r)!==r&&n.searchParams.set(o,"[redacted]")}return n.hash&&n.hash.length>1&&(n.hash=t.includes("#")?n.hash:"#[redacted]"),It(n.toString().replace(/%5Bredacted%5D/gi,"[redacted]"))}function ca(e){return e.length>120?!0:Re(mo,e)||Re(ho,e)||Re(po,e)||Re(yo,e)||Re(go,e)||Re(fo,e)||Re(bo,e)||Re(vo,e)||Re(wo,e)||oa.test(e)||ra(e)}const Pt={id:"rev_local",name:Z("author.unknown"),kind:"guest"};function So(e,t){if(e)return{...Pt,name:e,...t?{email:t}:{}};try{const n=localStorage.getItem(se.identity);if(n)return{...Pt,name:n[0]==="{"?JSON.parse(n).name??Pt.name:n}}catch{}return Pt}function la(e){return`SN-${e.reduce((n,o)=>{const r=Number(o.key.split("-")[1]??0);return Number.isFinite(r)&&r>n?r:n},0)+1}`}let rn=null;const ke=e=>es(e,rn);function da(e,t){const n=Cn(),o=n.ownerDocument??document,r=o.defaultView??window,l=t?.config?.site??"local",u=t?.emit??(()=>{}),a=t?.assetBase??"./",d=t?.config?.env??"default";at(n,"tokens",rr);const v=ar(n.host,sr(t?.config?.theme)),S={},_=t?.config?.storage==="local"?void 0:t?.config?.host,h=_&&l!=="local"?Bs(_,l,t?.config?.env,{reviewToken:t?.reviewToken,onSessionEnded:s=>{w.show(s==="revoked"?"error.linkrevoked":"error.sessionended")},onSessionStarted:()=>w.hide()}):Rs(l,d,{put:(s,c)=>S.put(s,c),del:s=>S.del(s)}),I=Ps(l,d);let H=null;const F=s=>h.init({uid:l,env:d}).catch(c=>s>=3?Promise.reject(c):new Promise(f=>setTimeout(f,1500*(s+1))).then(()=>F(s+1)));F(0).then(s=>{H=s.rounds??null,G?.update(M()),s.writable===!1&&s.reason==="origin_not_allowed"&&w.show("error.origin",void 0,{origin:location.origin}),s.writable===!1&&(s.reason==="site_archived"||s.reason==="site_locked")&&w.show("error.readonly")}).catch(()=>{});let b=[],j=[],ee=!0,ne=0;const le=Ts();let X=null,ue=null,ae=!1,K=!1,oe=!1,g=null,i=!1;const p={get:()=>X,unavailable:()=>K||oe,newPass:()=>ue?.createPassCaches(),fuzzyHit:s=>g?.hit(s)??null,wantFuzzy:(s,c)=>{if(g){g.enqueue(s,c,()=>Q());return}i||!ue||!c.text?.exact||c.text.exact.length<8||(i=!0,ze("anchor-fuzzy",a,o).then(f=>{if(!f.ok||!ue){oe=!0,Q();return}g=f.mod.createFuzzyEngine(o,ue.fuzzyDeps),Ce()}))},want:s=>{ae||!(s.role&&s.accessibleName)&&!s.text?.exact&&!s.path?.length||(ae=!0,ze("anchor-ext",a,o).then(c=>{if(!c.ok){K=!0,Q();return}ue=c.mod,X=c.mod.resolveExtended,Ce()}))}};let y=null,m=Br(l,d)??Yn();const C=()=>Xn(m.statuses)||!!m.by||m.assignee!==void 0||!!m.page||m.read!=="all",z=Mr(n,s=>{if(U==="add"){if(W?.hasText()){W.pulse();return}W?.close(),W=null,pe("comments")}J(s.id)},p,s=>{y=s,G?G.update(M()):J()});let U=(()=>{try{return sessionStorage.getItem(se.mode)==="comments"?"comments":"browse"}catch{return"browse"}})(),W=null,G=null,ie=null,Ge=!1,De=null,Ne=!1,dt=null,_e=null,$e=null,Ve=!1;function de(){return $e?Promise.resolve($e):Ve?Promise.resolve(null):ze("capture",a,o).then(c=>c.ok?(S.put=c.mod.putBlob,S.del=c.mod.deleteBlob,$e=c.mod):(ut(new Error("chunk unavailable")),null))}function ut(s){Ve||(Ve=!0,U==="add"&&pe("comments"),ce.setDegraded(!0),w.show("error.capture",{label:"action.retry",run:()=>{Ve=!1,ce.setDegraded(!1),de()}}),console.warn(`[${Se}] the capture chunk failed to load`,s))}let Ye=0;function Ie(){const s=new URL(a,o.location.href).href,c=new URL(Oe.panels,s);return c.searchParams.set("cv",qn),Ye>0&&c.searchParams.set("r",String(Ye)),Ye++,import(c.href)}async function be(){if(Ne)return null;if(De)return De.catch(()=>null);De=Ie().catch(async()=>(await new Promise(s=>setTimeout(s,1e3)),Ie()));try{return dt=await De}catch(s){return De=null,Mt(s),null}}function Mt(s){Ne=!0,U==="add"&&pe("comments"),ce.setDegraded(!0),w.show("error.panels",{label:"action.retry",run:()=>{Ne=!1,ce.setDegraded(!1),J(ie)}}),console.warn(`[${Se}] the panels chunk failed to load`,s)}const He=o.defaultView?.matchMedia?.("(pointer: coarse)").matches??!1;let he=null;async function Ot(){if(he)return;const s=await de();!s||he||(he=s.createAddChrome(n,He,{pick:(c,f)=>void E(c,f),announce:nt}),he.setActive(U==="add"))}const ye=o.createElement("div");ye.style.cssText=`position:fixed;left:0;top:0;pointer-events:none;z-index:${qe.dock}`,n.appendChild(ye);const $=Vr(r,ye,s=>ce.setPuck(s>1.2)),w=zr(n,ye),x=Dr(n,ye),L=pr(n,{onPick:(s,c)=>void E(s,c),onHover:s=>s?he?.show(s):he?.clear(),onSelectStart:()=>{He||dn()}});async function E(s,c){if(W?.hasText()){W.pulse();return}W?.close();const[f,A]=await Promise.all([be(),de()]);if(!f||!A)return;const O=A.captureContext({page:A.derivePageRef(o.location,yt()),...vt()});wn(s);const B=A.deriveAnchorLabel(s);D(f,s,c,O,B,A)}function D(s,c,f,A,O,B,Y,Ue){let xe=c;bt=!1;const me=ke(o);Nt=!1;const wt=()=>{W=null,eo(me),ce.setDraft(Qt()),pe("comments")},st=()=>{rt?.abort(),Fe=rt=null,wt()},ge=H?.find(fe=>fe.number===h.getRound?.())?.closed?H.find(fe=>!fe.closed):void 0,Be={at:f,label:O,...Y?{initialBody:Y.body,initialName:Y.author,...Y.email?{initialEmail:Y.email}:{}}:{},onDraft:(fe,Me,xt)=>{const Ho=ms({route:me,body:fe,author:Me,...xt?{email:xt}:{},label:O,anchor:Ue??B.createElementAnchor(c,{point:f,viewportWidth:r.innerWidth,label:O,...B.describeElement(c)}),at:{x:f.x+r.scrollX,y:f.y+r.scrollY},savedAt:new Date().toISOString()});ce.setDraft(Qt()),!Ho&&!Nt&&(Nt=!0,pn())},onSend:(fe,Me,xt)=>{wt(),ge&&h.setRound(ge.number),mn(xe,f,A,fe,Me,xt,Ue).then(()=>ge&&Ce())},onRetarget:fe=>{const Me=fe==="up"?B.widen(xe):B.narrow(xe);Me&&(xe=Me,he?.show(Me),W?.setLabel(B.deriveAnchorLabel(Me)))},...We&&ot!==!1?{onShotOptIn:fe=>bt=fe}:{},onCancel:st,crumbsOn:vn!==!1,shotsOn:ot!==!1,..._&&l!=="local"?{serverHost:new URL(_).host}:{},..._&&h.adoptSession?{studio:{host:_,uid:l,env:t?.config?.env,member:h.member(),adopt:fe=>h.adoptSession(fe),signOut:()=>h.signOut()}}:{},...Ue?.text?.exact?{quote:Ue.text.exact}:{},...ge?{roundNote:ge.name}:{}};W=s.openComposer(n,Be,ye),ft()}async function T(){const s=ke(o),c=gs(s);if(ce.setDraft(Qt()),!c||W)return;const[f,A]=await Promise.all([be(),de()]);if(!f||!A)return;const O=Kt(c.anchor,o,{viewportWidth:r.innerWidth,...X?{extended:X}:{}});if(!O.element)return;const B=O.element.getBoundingClientRect();if(B.width===0&&B.height===0)return;const Y={x:c.at.x-r.scrollX,y:c.at.y-r.scrollY};pe("add"),D(f,O.element,Y,A.captureContext({page:A.derivePageRef(o.location,yt()),...vt()}),c.label,A,{body:c.body,author:c.author,...c.email?{email:c.email}:{}})}function R(){m.newOnly&&!b.some(s=>Kn(s,I.map()))&&(m={...m,newOnly:!1})}async function J(s=null){if(s&&s!==ie&&u("thread:open",{threadId:s}),s&&(I.mark(s),R()),ie=s,Ge=!0,U==="browse"&&pe("comments"),G){G.update(M());return}if(!await be())return;const f=await ze("dock",a,o);if(!f.ok){w.show("error.panels",{label:"action.retry",run:()=>void J(ie)});return}!Ge||G||(_e=f.mod,G=f.mod.openDock(n,M(),ye),ft())}function V(){I.markAll(b),m.newOnly&&(m={...m,newOnly:!1}),Ge=!1,G?.close(),G=null,ie=null,z.highlight(null),ft(),C()&&Q()}function N(s){const c=s?b.find(f=>f.id===s):void 0;if(c&&c.route!==ke(o)){jr(r,c.id),r.location.assign(c.route);return}s&&(I.mark(s),R()),ie=s,z.highlight(null),C()?Q():G?.update(M()),c&&_e?.scrollToSnag(r,n,c)}function M(){return{snags:b,loading:ee,route:ke(o),openId:ie,seenAt:I.map(),onOpen:N,onStatus:(s,c)=>void Co(s,c),onReply:(s,c,f)=>void Ro(s,c,f),onEdit:(s,c)=>void ve(s,c),onDeleteComment:s=>void we(s),onDeleteThread:s=>void re(s),...h.isMine?{isMine:s=>h.isMine(s)}:{},..._&&h.adoptSession?{studio:{host:_,uid:l,env:t?.config?.env,member:h.member(),adopt:s=>h.adoptSession(s),signOut:()=>h.signOut()}}:{},canDeleteOwnThread:h.can?h.can("thread:delete:own"):!0,canStatus:h.can?h.can("thread:resolve"):!0,canModerate:h.canModerate?.()??!1,...h.listAssignees&&h.can?.("thread:assign")?{assignees:()=>h.listAssignees(),onAssign:(s,c)=>void To(s,c)}:{},onClearAll:()=>void et(),onMarkAllRead:()=>{I.markAll(b),m={...m,newOnly:!1},Q()},onClose:V,...h.kind==="local"?{onExport:Dt}:{},onHover:s=>z.highlight(s),...H&&H.length>1&&h.setRound?{rounds:H,activeRound:h.getRound?.()??H.find(s=>!s.closed)?.number??H[0].number,onRound:s=>{h.setRound(s),ne++,ee=!0,b=h.cached?.()??[],Q(),Ce()}}:{},onAnnounce:nt,loadShot:s=>Zs(s,async c=>{const f=await de();return f?(await f.getBlob(c))?.blob??null:null}),filter:m,onFilter:s=>{const c=s.statuses.join()!==m.statuses.join()||s.by!==m.by||s.assignee!==m.assignee||s.page!==m.page||s.read!==m.read;m=s,Zr(l,d,s),c?Q():G?.update(M())},...y?{clusterFilter:y}:{},onClusterClear:()=>{y=null,G?.update(M())},onShowAnyway:s=>{z.showGhost(s),_e?.scrollToSnag(r,n,s)}}}async function q(s,c){const f=b;b=s,Q();try{await Ke(c)}catch{b=f,Q(),h.remember?.(b),w.show("error.sendfailed",void 0,{item:"change"})}}async function ve(s,c){await q(b.map(f=>({...f,comments:f.comments.map(A=>A.id===s?{...A,body:c}:A)})),()=>h.patchComment(s,c))}async function we(s){await q(b.map(c=>({...c,comments:c.comments.filter(f=>f.id!==s)})),()=>h.deleteComment(s))}async function re(s){const c=ie;ie===s&&(ie=null),await q(b.filter(f=>f.id!==s),()=>h.deleteThread(s)),b.some(f=>f.id===s)&&(ie=c)}async function et(){const s=b.map(c=>c.id);b=[],ie=null,Q(),await Promise.all(s.map(c=>Ke(()=>h.deleteThread(c))))}const ce=Ss(n,{onState:s=>pe(s),onPanel:()=>G?V():void J(),onNav:s=>cn(s),parent:ye}),We=r.matchMedia?.("(pointer: coarse)").matches??!1,ft=()=>{We&&ce.setConcealed(!!W||!!G)};let Pe=null,ht=[];function Ao(s){let c=!1;const f=()=>{c||(c=!0,r.removeEventListener("scrollend",f),s())};r.addEventListener("scrollend",f,{once:!0}),r.setTimeout(f,600)}const tt=o.createElement("div");tt.setAttribute("aria-live","polite"),tt.setAttribute("role","status");const sn="position:absolute;width:1px;height:1px;overflow:hidden";tt.style.cssText=sn;const zt=o.createElement("div");zt.setAttribute("aria-live","assertive"),zt.style.cssText=sn,n.append(tt,zt);let an=0;function nt(s){r.clearTimeout(an),an=r.setTimeout(()=>{tt.textContent=s},400)}function cn(s){const c=ht.length;if(c===0)return;Pe=Pe===null?s===1?0:c-1:(Pe+s+c)%c;const f=ht[Pe];ks(r,n,f);const A=Pe+1;Ao(()=>{z.pulse(f.id),nt(Z("nav.announce",{n:A,label:f.anchor.label,i:A,total:c}))})}function ln(){if(U!=="comments"||He){Ee?.disarm();return}dn().then(s=>{s&&U==="comments"&&s.arm()})}let Ee=null,Lt=null;async function dn(){if(Ee)return Ee;const s=await ze("text",a,o);return!s.ok||Ee||(Lt=s.mod,Ee=s.mod.createSelectionWatcher(n,{onQuote:(c,f)=>void ko(c,f)})),Ee}async function ko(s,c){const f=$e??await de();if(!f||!Lt)return;const A=Lt.createTextAnchor(s,f,{viewportWidth:r.innerWidth,ourRoot:n});if(A.kind==="refused-form-control"){E(A.el,c);return}if(A.kind!=="text")return;const O=await be();if(!O)return;const B=f.captureContext({page:f.derivePageRef(o.location,yt()),...vt()});try{s.removeAllRanges()}catch{}D(O,A.el,A.point,B,A.label,f,void 0,A.record)}function pe(s,c=!1){const f=U;U=s,s!=="add"&&W&&!c&&(W.close(),W=null),s==="add"&&G&&V(),s==="add"&&(be(),de());try{sessionStorage.setItem(se.mode,s==="add"?"comments":s)}catch{}L.setMode(s),s!==f&&nt(Z(`toolbar.${s}`)),ft(),s==="add"&&Ot(),ln(),he?.setActive(s==="add"),ce.setState(s),Q(),s!==f&&u("modechange",{mode:s,previous:f})}let Xe=0,un=0;const fn=[300,800,1600,3200];function $o(){if(Xe||!z.hasPending()){z.hasPending()||(un=0);return}const s=fn[Math.min(un++,fn.length-1)];Xe=r.setTimeout(()=>{Xe=0,Q()},s)}const Eo=3e3;let hn=0;function Q(s){const c=s??(Date.now()<hn?"navigating":"authoritative");j=z.reanchor(b.filter(Lo()),c),zo(),$o();const f=new Map(j.map(Y=>[Y.id,Y]));b=b.map(Y=>f.get(Y.id)??Y);const A=C()?new Set(j.filter(Y=>!Ur(Y,m,I.map())&&Y.id!==ie).map(Y=>Y.id)):void 0;ht=A?j.filter(Y=>!A.has(Y.id)):j,z.render(U==="browse"?[]:j,A);const O=ke(o),B=le?Js(o.location.origin,b,O):null;ce.setCount(B?qs(B,O):le?j.filter(Y=>Y.status!=="resolved").length:null),Pe!==null&&Pe>=ht.length&&(Pe=null),G?.update(M())}async function Ce(){const s=ne;let c;try{({data:c}=await h.listThreads())}catch(A){if(s===ne){ee=!1;const O=A.status;(O===401||O===403)&&(b=[]),Q()}throw A}if(s!==ne)return j;ee=!1,b=c,Q();const f=z.settled();for(const A of f)u("anchor:settled",{threadId:A.id,state:A.state,strategy:A.strategy,confidence:A.confidence});return h.capabilities.anchorReports&&h.reportAnchors&&f.length&&Ke(()=>h.reportAnchors(f.map(A=>({threadId:A.id,state:A.state,confidence:A.confidence,strategy:A.strategy})))),h.capabilities.anchorReports||await Promise.all(c.flatMap(A=>{const O=b.find(B=>B.id===A.id);return!O||O.anchorState===A.anchorState?[]:[Ke(()=>h.patchThread(O.id,{anchor:O.anchor,anchorState:O.anchorState}))]})),j}async function Co(s,c){u("thread:resolve",{threadId:s,status:c}),await q(b.map(f=>f.id===s?{...f,status:c}:f),()=>h.patchThread(s,{status:c}))}async function To(s,c){await q(b.map(f=>f.id===s?{...f,assignee:c}:f),()=>h.patchThread(s,{assignee:c&&c.id}))}async function Ro(s,c,f){const A={id:oo(),body:c,author:So(f)};b=b.map(O=>O.id===s?{...O,comments:[...O.comments,{...A,snagId:s,createdAt:new Date().toISOString()}]}:O),I.mark(s),Q(),u("comment:create",{threadId:s,comment:A}),await Ke(()=>h.createComment(s,A))}function pn(){w.show("error.quota",{label:"action.exportclear",run:()=>{Dt("json"),et()}}),console.warn(`[${Se}] ${Z("error.quota")}`)}async function Ke(s){try{const c=await s();return h.remember?.(b),c}catch(c){if(c instanceof Zt&&c.code==="local_quota_exceeded")return pn(),null;throw c}}function Dt(s){de().then(async c=>{if(!c)return;const f=await c.resolveAttachmentUris(b).catch(()=>new Map);c.download(n,c.buildExport(s,b,{origin:o.location.origin,exportedAt:new Date().toISOString()},f),r)})}async function mn(s,c,f,A,O,B,Y){const Ue=So(O,B),xe=$e??await de();if(!xe)throw new Error(`[${Se}] add() needs the capture chunk`);Fe||wn(s);const me=Fe?await Fe:null;Fe=rt=null,xe.applyShotOutcome(f,me,ot===!1,We&&!bt);const wt=me?.blob&&h.uploadAttachment?h.uploadAttachment(me.blob,{kind:"screenshot",...me.width!==void 0?{width:me.width}:{},...me.height!==void 0?{height:me.height}:{}}).catch(()=>null):Promise.resolve(null),st={id:$s(),key:la(b),route:ke(o),anchor:Y??xe.createElementAnchor(s,{point:c,viewportWidth:r.innerWidth,label:xe.deriveAnchorLabel(s),...xe.describeElement(s)}),anchorState:"anchored",scope:Mo(),context:f,createdBy:Ue,createdAt:new Date().toISOString(),...A?{comment:{id:oo(),body:A,author:Ue}}:{}},Te=zn(st);me?.blob&&(Te.screenshotBlob=me.blob),b=[...b,Te],I.mark(Te.id),nt(Z("announce.created",{key:Te.key})),u("thread:create",{thread:Te}),U==="browse"?pe("comments"):Q();try{const ge=await wt;ge&&(st.attachments=[ge],b=b.map(Be=>Be.id===Te.id?{...Be,attachments:[ge]}:Be),Q()),await Ke(()=>h.createThread(st))}catch(ge){throw b=b.filter(Be=>Be.id!==Te.id),Q(),w.show("error.sendfailed",void 0,{item:Wt.toLowerCase()}),console.warn(`[${Se}] ${Z("error.sendfailed",{item:Wt.toLowerCase()})}`,ge),ge}return Te}function gn(s){if((s.key==="n"||s.key==="p")&&U==="comments"&&!W){if(s.metaKey||s.ctrlKey||s.altKey)return;const c=s.composedPath()[0]??s.target;if(c&&(c.closest?.("input,textarea,select,[contenteditable]")||c.isContentEditable))return;s.preventDefault(),s.stopPropagation(),cn(s.key==="n"?1:-1);return}U==="add"&&s.key==="Escape"&&(W||(s.stopPropagation(),pe("comments")))}o.addEventListener("keydown",gn,!0);let yn=0;const bn=()=>{if(o.hidden||!h.revalidate)return;const s=Date.now();s-yn<3e4||(yn=s,h.revalidate())};o.addEventListener("visibilitychange",bn);const _o=Qo(n),Io=Go(n,s=>{console.warn(`[${Se}] the host page hid the widget from assistive technology ${s} times; leaving it alone.`)}),Po=qo(n,s=>{console.warn(`[${Se}] the host page removed the widget ${s} times; leaving it alone. Reload to comment again.`)});function Mo(){return{environment:d,...t?.config?.branch?{branch:t.config.branch}:{}}}let pt={route:ke(o),url:o.location.href},Nt=!1,mt=null;function Oo(s){if(s){if(U==="browse")return;mt=U,pe("browse",!0),x.show(),u("paused",{reason:"modal-dialog"})}else if(mt){const c=mt;mt=null,x.hide(),pe(c),u("resumed",{mode:c})}}be();function zo(){j.length>0&&ze("dock",a,o)}{const s=o.createElement("div");s.style.cssText="position:fixed;inset:0;pointer-events:none;visibility:hidden",n.appendChild(s);const c=s.getBoundingClientRect(),f=Math.abs(c.left)>1||Math.abs(c.top)>1||Math.abs(c.width-r.innerWidth)>1||Math.abs(c.height-r.innerHeight)>1;s.remove(),f&&(console.warn(`[${Se}] fixed-trapped: <html> has transform/filter/contain, so our fixed layer follows it, not the viewport. Remove it, or expect drift.`),u("error",{code:"fixed-trapped"}))}let Je=null;const gt=new Set,je=(()=>{const s=r[Uo.config];return s&&typeof s=="object"?s:void 0})(),vn=je?.breadcrumbs,Ht=(()=>{const s=je?.significantQueryParams,c=je?.ignoredQueryParams,f={};return s==="*"?f.significantQueryParams="*":Array.isArray(s)&&(f.significantQueryParams=s.map(String)),Array.isArray(c)&&(f.ignoredQueryParams=c.map(String)),f})(),yt=()=>({routeOverride:rn,query:Ht,doc:o}),ot=je?.screenshot===!1?!1:je?.screenshot&&typeof je.screenshot=="object"?je.screenshot:{};let bt=!1,Fe=null,rt=null;function wn(s){if(ot===!1||Fe||We&&!bt)return;rt=new AbortController;const c=rt.signal;Fe=ze("screenshot",a,o).then(f=>f.ok?f.mod.captureScreenshot({doc:o,target:s,signal:c,...ot,...h.fetchForeignImage?{fetchForeignImage:A=>h.fetchForeignImage(A)}:{}}):{situation:"engine-load-failed",blindSpots:[],maskedCount:0})}function Lo(){const s=ke(o),c=Jn(o.location.pathname),f=rs(o.location.search,Ht);return A=>(A.route===s||A.context?.page?.pathname===c)&&ss(A.context?.page?.query,f,Ht)}{const s=vn;s!==!1&&ze("crumbs",a,o).then(c=>{c.ok&&(Je=c.mod.installTierC({win:r,...t?.early?{early:t.early}:{},...s&&typeof s=="object"?{config:s}:{},subscribeNav:f=>(gt.add(f),()=>gt.delete(f))}))})}const vt=()=>Je?{breadcrumbs:{records:Je.drain(),status:Je.status()}}:{},Do=ds(o,r,()=>{U!=="browse"&&j.length>0&&Q()}),No=Wr(r,{onResize:()=>Q(),onRoute:()=>{const s={route:ke(o),url:o.location.href},c=s.route!==pt.route;if(c){u("navigate",{from:pt,to:s});for(const f of gt)f(pt.url,s.url)}if(pt=s,!c){Ce();return}hn=Date.now()+Eo,r.setTimeout(()=>{h.listThreads().then(({data:f})=>{b=f,Q("optimistic")})},100),r.setTimeout(()=>void Ce(),600)},onModal:Oo});ce.setState(U),L.setMode(U),ln(),le||w.show("error.nostorage",{label:"action.export",run:()=>Dt("md")});const xn=h.cached?.();return xn&&(b=xn,Q()),Ce().then(async s=>{const c=Fr(r);if(!c){const A=new URLSearchParams(o.location.search).get(Xo("t"));if(A){let O=s.find(B=>B.key===A);if(!O&&h.getThreadByKey){const B=await h.getThreadByKey(A).catch(()=>null);B&&(b=[...b.filter(Y=>Y.id!==B.id),B],Q(),O=b.find(Y=>Y.id===B.id))}O?(await J(O.id),_e?.scrollToSnag(r,n,O)):(w.show("permalink.unknown"),await J(null));return}await T();return}const f=s.find(A=>A.id===c);await J(f?c:null),f&&_e?.scrollToSnag(r,n,f)}),{root:n,assetBase:t?.assetBase??"",snags:()=>j,async add(s,c,f,A){const O=A?null:await de(),B=A??(O?O.captureContext({page:O.derivePageRef(o.location,yt()),...vt()}):void 0);if(!B)throw new Error(`[${Se}] add() needs the capture chunk, or an explicit context`);return mn(s,c,B,f)},refresh:Ce,setRoute(s){rn=s&&s.startsWith("/")?s:null,Ce()},setState:pe,getState:()=>U,openPanel:J,async open(s){const c=s.startsWith(At.thread)?b.find(f=>f.id===s):b.find(f=>f.key===s);return c?c.route!==ke(o)?{ok:!1,reason:"wrong-page",url:c.context?.url??c.route,route:c.route}:(await J(c.id),_e?.scrollToSnag(r,n,c),{ok:!0,anchorState:c.anchorState}):{ok:!1,reason:"not-found"}},closePanel:V,hitTest:(s,c)=>L.hitTest(s,c),destroy(){W?.close(),V(),he?.destroy(),w.destroy(),x.destroy(),$(),Po(),Io(),_o(),No.destroy(),Do.destroy(),Je?.destroy(),Je=null,gt.clear(),Ee?.destroy(),Ee=null,g?.destroy(),g=null,Xe&&r.clearTimeout(Xe),Xe=0,o.removeEventListener("keydown",gn,!0),o.removeEventListener("visibilitychange",bn),v(),L.destroy(),z.destroy(),ce.destroy(),n.host.remove()}}}export{$n as HOST_CSS,Cn as createHost,ca as isSensitiveValue,da as mount,It as redactText,ia as redactUrl};
2
+ `),rr=` :host{all:initial}[hidden]{display:none!important}:host{display:block;font:400 14px/1.45 ${k.font};color:${k.fg};${P.font}:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;${P.accent}:#2a51b8;${P.bg}:#fefdfc;${P.fg}:#181716;${P.muted}:#666564;${P.border}:#e4e3e0;${P.radius}:8px;${P.shadow}:0 6px 24px -4px rgb(0 0 0 / .18);${P.z}:2147483647;${P.motion}:160ms;${P.surface}:color-mix(in srgb,${k.fg} 6%,${k.bg});${P.sunken}:color-mix(in srgb,${k.fg} 3%,${k.bg});${P.hover}:color-mix(in srgb,${k.fg} 8%,${k.bg});${P.onAccent}:#fff;${P.focus}:color-mix(in srgb,${k.accent} 62%,${k.fg});${P.disabled}:color-mix(in srgb,${k.muted} 52%,${k.bg});${or} ${P.anchorOrphan}:#DC2626;}:host([${An}="dark"]){${P.accent}:#8aafff;${P.onAccent}:#1d1c1a;${P.bg}:#1d1c1a;${P.fg}:#f0eeec;${P.muted}:#9a9997;${P.border}:#2d2c2b;${P.shadow}:0 6px 24px -4px rgb(0 0 0 / .6);}@media (prefers-reduced-motion:reduce){:host{${P.motion}:0ms}}@media (forced-colors:active){:host{${P.bg}:Canvas;${P.fg}:CanvasText;${P.muted}:CanvasText;${P.border}:CanvasText;${P.accent}:Highlight;${P.onAccent}:HighlightText;${P.surface}:Canvas;${P.sunken}:Canvas;${P.hover}:Canvas;${P.focus}:Highlight;${P.disabled}:GrayText;${P.shadow}:none;${P.anchorOrphan}:CanvasText;}.snag-pin{border-color:CanvasText!important;color:CanvasText!important;forced-color-adjust:none}}`,qe={shield:1,pins:3,dock:5,notice:6,toolbar:7},Ln=new WeakMap;function at(e,t,n){let o=Ln.get(e);if(o||Ln.set(e,o=new Set),o.has(t))return;o.add(t);try{const u=new CSSStyleSheet;u.replaceSync(n),e.adoptedStyleSheets=[...e.adoptedStyleSheets,u];return}catch{}const l=(e.ownerDocument??document).createElement("style");l.setAttribute(`data-snag-${t}`,""),l.textContent=n,e.appendChild(l)}function sr(e){return e==="light"||e==="dark"?e:"auto"}function ar(e,t){const n=An;if(t!=="auto")return e.setAttribute(n,t),()=>e.removeAttribute(n);const o=e.ownerDocument?.defaultView?.matchMedia?.("(prefers-color-scheme: dark)");if(!o)return e.setAttribute(n,"light"),()=>e.removeAttribute(n);const r=()=>e.setAttribute(n,o.matches?"dark":"light");return r(),o.addEventListener("change",r),()=>{o.removeEventListener("change",r),e.removeAttribute(n)}}function Vt(e){return e.getBoundingClientRect()}function kt(e){if(e.closest('[inert],[aria-hidden="true"]'))return!1;const t=e.checkVisibility;if(typeof t=="function")return t.call(e,{contentVisibilityAuto:!0,opacityProperty:!1,visibilityProperty:!0});const n=Vt(e);if(!(n.width>0||n.height>0||e.getClientRects().length>0))return!1;const r=e.ownerDocument?.defaultView;return r?r.getComputedStyle(e).visibility!=="hidden":!0}const ir="button,a[href],[role=button],[role=link],[role=tab],[role=menuitem],label,input,select,textarea,summary",cr=3,Dn=8,lr=new Set(["img","picture","canvas","video","audio","iframe","embed","object","svg","math","input","select","textarea","button","progress","meter"]);function dr(e,t){return lr.has(e.tagName.toLowerCase())?!1:t.getComputedStyle(e).display==="inline"}function Nn(e){const t=e.ownerDocument?.defaultView;if(!t)return e;let n=e;for(let r=e;r;r=r.parentElement){const l=Vt(r);if(l.width>=Dn&&l.height>=Dn&&!dr(r,t)){n=r;break}n=r}let o=0;for(let r=n;r&&o<=cr;r=r.parentElement){if(r.matches(ir))return r;o++}return n}const ur=10,Yt=[["click",!1],["auxclick",!1],["dblclick",!1],["pointerdown",!1],["pointerup",!1],["mousedown",!1],["mouseup",!1],["contextmenu",!1],["dragstart",!1],["wheel",!1],["touchstart",!0],["touchmove",!0],["touchend",!0],["selectstart",!0],["keydown",!1],["keyup",!1]];function fr(e,t,n){let o=e;for(;o&&o!==o.ownerDocument.documentElement&&o!==o.ownerDocument.body;){const r=getComputedStyle(o),l=(r.overflowY==="auto"||r.overflowY==="scroll")&&o.scrollHeight>o.clientHeight&&(t>0&&o.scrollTop+o.clientHeight<o.scrollHeight-1||t<0&&o.scrollTop>0),u=(r.overflowX==="auto"||r.overflowX==="scroll")&&o.scrollWidth>o.clientWidth&&(n>0&&o.scrollLeft+o.clientWidth<o.scrollWidth-1||n<0&&o.scrollLeft>0);if(l||u)return o;o=o.parentElement}return null}function Hn(e,t){const n=t==="y"?e.deltaY:e.deltaX;return e.deltaMode===1?n*16:e.deltaMode===2?n*(t==="y"?innerHeight:innerWidth):n}const hr=["position:fixed","inset:0",`z-index:${qe.shield}`,"touch-action:pan-x pan-y pinch-zoom","background:transparent"].join(";");function pr(e,t={}){const n=t.doc??e.ownerDocument??document,o=n.defaultView??window;let r=t.coarsePointer??o.matchMedia?.("(pointer: coarse)").matches??!1;const l=i=>{const p=i.pointerType,y=p==="touch"?!0:p==="mouse"||p==="pen"?!1:r;y!==r&&(r=y,d())},u=n.createElement("div");u.className="snag-shield",u.style.cssText=hr;let a="browse";const d=()=>{u.style.pointerEvents=r?"none":"auto",u.style.cursor="crosshair"};d();const v=i=>{const p=i;return!p||typeof p.closest!="function"?!1:e.contains(p)?!0:!!p.closest(`[${jt("root")}]`)};function S(i,p,y){let m=y,C=0;for(;m.shadowRoot&&C++<ur;){const z=_(m.shadowRoot,i,p);if(!z||z===m)break;m=z}return m}function _(i,p,y){const m=i.elementsFromPoint;if(typeof m=="function"){for(const z of m.call(i,p,y))if(z.getRootNode()===i)return z;return null}const C=i.elementFromPoint(p,y);return C&&C.getRootNode()===i?C:null}function h(i,p){const y=[];for(const m of n.elementsFromPoint(i,p)){if(v(m))continue;if(m===n.documentElement||m===n.body){y.push(m);continue}const C=S(i,p,m);y.push(v(C)?m:C)}return y}let I=null;const H=(i,p)=>{const[y]=h(i,p);y&&t.onPick?.(Nn(y),{x:i,y:p})};let F=!1;const b=()=>{const i=n.getSelection?.();if(!i||i.isCollapsed||i.rangeCount===0||!i.toString().trim())return!1;const p=i.anchorNode;if(!p||e.contains(p))return!1;const y=p.nodeType===1?p:p.parentElement;return!v(y)},j=i=>{const p=i.composedPath()[0];if(p&&v(p)){F=!1;return}if(i.type==="selectstart"){t.onSelectStart?.();return}const y=i.type;if(y.endsWith("down")||y.endsWith("start")){F=!1;return}if(y.endsWith("up")||y.endsWith("end")){F=b();return}if(y==="click"||y==="auxclick"){if(!F)return;F=!1,i.preventDefault(),i.stopImmediatePropagation()}},ee=i=>{if(i.type==="pointerdown"&&l(i),a==="comments"){j(i);return}if(a!=="add")return;if(i.type==="keydown"||i.type==="keyup"){ue(i);return}const p=i.composedPath()[0];if(p&&p!==u&&v(p))return;const y=Yt.find(([m])=>m===i.type)?.[1]??!1;if(i.stopImmediatePropagation(),!y){if(r&&i.type==="pointerdown"){const m=i;I={x:m.clientX,y:m.clientY,t:performance.now()},g(m.clientX,m.clientY)}if(r&&i.type==="pointerup"&&I){const m=i,C=I;I=null,Math.hypot(m.clientX-C.x,m.clientY-C.y)<=8&&performance.now()-C.t<=700&&H(m.clientX,m.clientY);return}if(i.type==="click"||i.type==="auxclick"||i.type==="dblclick"){i.preventDefault();const m=i;H(m.clientX,m.clientY);return}if(i.type==="wheel"){const m=i,C=Hn(m,"y"),z=Hn(m,"x"),[te]=h(m.clientX,m.clientY),U=fr(te??null,C,z);U&&(U.scrollTop+=C,U.scrollLeft+=z,i.preventDefault());return}if(i.type==="dragstart"||i.type==="contextmenu"){i.preventDefault();return}(i.type==="pointerdown"||i.type==="mousedown")&&!r&&i.preventDefault()}},ne=new Set(["Tab","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"," ","Spacebar","PageUp","PageDown","Home","End"]),le=/^[a-z0-9/?]$/;function X(i){for(const p of i.composedPath()){const y=p;if(!(!y||y.nodeType!==1||typeof y.matches!="function")&&y.matches('input:not([type=button]):not([type=submit]):not([type=checkbox]):not([type=radio]),textarea,select,[contenteditable=""],[contenteditable=true],[role=textbox],[role=searchbox],[role=combobox]'))return!0}return!1}function ue(i){ne.has(i.key)||i.metaKey||i.ctrlKey||i.altKey||/^F\d{1,2}$/.test(i.key)||i.key!=="Escape"&&i.key.length===1&&le.test(i.key.toLowerCase())&&!X(i)&&(i.preventDefault(),i.stopImmediatePropagation())}for(const[i,p]of Yt)o.addEventListener(i,ee,{capture:!0,passive:p});let ae=0,K=null;function oe(){if(ae=0,a!=="add"||!K)return;const[i]=h(K.x,K.y);t.onHover?.(i?Nn(i):null)}function g(i,p){a==="add"&&(K={x:i,y:p},!ae&&(ae=o.requestAnimationFrame(oe)))}return u.addEventListener("pointermove",i=>g(i.clientX,i.clientY)),u.addEventListener("pointerleave",()=>{K=null,t.onHover?.(null)}),{shield:u,getMode:()=>a,setMode(i){a=i,F=!1,d(),i==="add"?e.appendChild(u):u.remove(),i!=="add"&&(K=null,t.onHover?.(null))},hitTest:h,destroy(){ae&&o.cancelAnimationFrame(ae);for(const[i]of Yt)o.removeEventListener(i,ee,{capture:!0});u.remove()}}}const mr=/[\u200B-\u200D\u2060\uFEFF]/gu,gr=/[\s\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]+/gu,yr=[[/[\u2018\u2019\u201A\u201B]/gu,"'"],[/[\u201C\u201D\u201E\u201F]/gu,'"'],[/[\u2010-\u2015\u2212]/gu,"-"],[/\u2026/gu,"..."],[/\u2044/gu,"/"]];function br(e){let t=e.normalize("NFC").replace(mr,"");for(const[n,o]of yr)t=t.replace(n,o);return t.replace(gr," ").trim()}const vr={testid:1,domid:1,css:.9,aria:.75,"text-exact":.8,"text-fuzzy":.78,"path-rect":.35,none:0,manual:1},Wn={anchored:.75,approximate:.35};function wr(e,t){const n=vr[e];return t===1?n:n/(1+Math.log2(t))}function jn(e){return e>=Wn.anchored?"anchored":e>=Wn.approximate?"approximate":"orphaned"}const xr=[Vo("anchor"),"data-testid","data-test-id","data-test","data-cy","data-qa","data-pw","data-automation-id"],Fn=e=>typeof CSS<"u"&&CSS.escape?CSS.escape(e):e.replace(/["\\]/g,"\\$&"),Sr=[{strategy:"testid",applicable:e=>!!e.testid,find:(e,t)=>Xt(t,xr.map(n=>`[${n}="${Fn(e.testid)}"]`).join(","))},{strategy:"domid",applicable:e=>!!e.domid,find:(e,t)=>Xt(t,`#${Fn(e.domid)}`)},{strategy:"css",applicable:e=>!!e.css,find:(e,t)=>{try{return Xt(t,e.css)}catch{return[]}}}];function Xt(e,t){return[...e.querySelectorAll(t)].filter(Ar)}function Ar(e){return!e.closest(`[${jt("root")}]`)}function kr(e,t){const n=t.text?.exact;if(!n)return!0;const o=br(e.textContent??"");return o?o===n||o.includes(n)||n.includes(o):!0}function Un(e,t,n,o){kt(e)||o.push("hidden"),t.hostPath?.length&&o.push("shadow-boundary");const r=!kr(e,t);r&&o.push("text-drift");let l=o.includes("hidden")?Math.min(n,.7):n;return r&&(l=Math.min(l,.5)),l}const $r={element:null,strategy:"none",score:0,state:"orphaned",reasons:["not-found"],candidates:0};function Kt(e,t=document,n={}){const o=[];for(const r of Sr){if(!r.applicable(e))continue;const l=r.find(e,t);if(l.length===0)continue;const u=wr(r.strategy,l.length),a=l[0];l.length>1&&o.push("ambiguous");const d=Un(a,e,u,o),v={element:a,strategy:r.strategy,score:d,state:jn(d),reasons:o.length?o:["exact"],candidates:l.length};if(v.reasons.includes("text-drift")&&n.extended){const S=n.extended(e,t,{...n.viewportWidth===void 0?{}:{viewportWidth:n.viewportWidth},...n.passCaches?{caches:n.passCaches}:{}});if(S&&S.score>v.score)return S}return v}return n.extended?.(e,t,{...n.viewportWidth===void 0?{}:{viewportWidth:n.viewportWidth},...n.passCaches?{caches:n.passCaches}:{}})??$r}const Er={"toolbar.aria":"{product} review toolbar","toolbar.group":"What you see","toolbar.browse":"Browse","toolbar.comments":"Comment","toolbar.comments.unresolved":"Comment, {n} unresolved","toolbar.add":"Add a comment","toolbar.add.draft":"Add a comment \u2014 one is unfinished","toolbar.panel":"All comments","pin.aria":"Comment {key} on {target}. {status}, {replies} replies. Press Enter.","pin.aria.one":"Comment {key} on {target}. {status}, 1 reply. Press Enter.","pin.aria.none":"Comment {key} on {target}. {status}. Press Enter.","pin.aria.moved":"Comment {key} on {target}. {status}. {where}. Press Enter.","pin.target":"{role} \u201C{name}\u201D","cluster.aria":"{n} comments here: {list}","nav.announce":"Comment {n} on {label}, {i} of {total}","action.retry":"Retry","action.dismiss":"Dismiss","action.export":"Export","action.exportclear":"Export & clear","error.quota":"Storage is full \u2014 this {item} is on screen but not saved. Export to keep them.","error.nostorage":"Comments won't be saved in this browser. Export before you leave to keep them.","error.linkrevoked":"This review link was turned off. Ask whoever sent it for a new one.","error.sessionended":"This review session has ended. Open your review link again to carry on.","error.sendfailed":"That {item} couldn't be sent, so it wasn't kept. Check your connection and try again.","error.readonly":"This site is read-only for now. You can read what is here, but new comments are off.","error.origin":"{product} is not enabled for {origin}. Add that address to the site's allowed origins.","error.panels":"{product} loaded, but its comment UI didn't. You can still see the comments on the page.","error.panels.add":"Adding comments is unavailable until the comment UI loads.","error.capture":"{product} can't take new comments \u2014 the part that records the page didn't load. Everything already here still works.","paused.dialog":"Review paused \u2014 a dialog is open on this page. Close it to carry on commenting. Commenting inside a native dialog isn't supported yet.","paused.close":"Close","announce.created":"Comment {key} added.","permalink.unknown":"That comment isn't on this page any more"},Cr={..._n,...Er},Z=Rn(Cr);function Tr(e,t){const n=new Array(e.length),o=[],r=new Map,l=[];let u=0;for(let a=0;a<e.length;a++){u++;const d=e[a],v=Math.floor(d.x/t),S=Math.floor(d.y/t);let _=-1;e:for(let h=-1;h<=1;h++)for(let I=-1;I<=1;I++)for(const H of r.get(`${v+h},${S+I}`)??[]){const F=l[H],b=d.x-F.x,j=d.y-F.y;if(b*b+j*j<=t*t){_=H;break e}}if(_===-1){_=o.length,o.push([]),l.push(d);const h=`${v},${S}`,I=r.get(h);I?I.push(_):r.set(h,[_])}n[a]=_,o[_].push(a)}return{group:n,members:o,visits:u}}const Rr=`position:absolute;top:0;left:0;width:0;height:0;pointer-events:none;z-index:${qe.pins}`,_r=' .snag-pp{animation:snag-pp .5s ease-out 2}@keyframes snag-pp{50%{transform:scale(1.45)}}@media (prefers-reduced-motion: reduce){.snag-pp{animation:none}}.snag-pin{width:28px;height:28px;margin:-14px 0 0 -14px}.snag-pin::after{content:"";position:absolute;inset:-8px}@media (pointer:coarse){.snag-pin{width:34px;height:34px;margin:-17px 0 0 -17px}}',Ir=`position:fixed;inset:0;width:0;height:0;pointer-events:none;z-index:${qe.pins}`,it=["position:absolute",`color:${k.onAccent}`,`font:600 12px/1 ${k.font}`,"display:flex","align-items:center","justify-content:center","box-shadow:0 1px 4px rgb(0 0 0 / .35)","pointer-events:auto","cursor:pointer","box-sizing:border-box"].join(";"),$t="border-radius:50% 50% 50% 2px",Bn=e=>k[`status${e[0].toUpperCase()}${e.slice(1)}`]??k.muted;function Zn(e,t){const n=Mn(t.status),o=`background:${Bn(t.status)};color:${n}`,r="0 1px 4px rgb(0 0 0 / .35)";return e==="anchored"?`${it};${$t};${o};border:2px solid ${n};box-shadow:${r}`:e==="approximate"?`${it};${$t};${o};border:2px dashed ${n};box-shadow:${r}`:`${it};${$t};${o};border:2px solid ${n};box-shadow:inset 0 0 0 2px ${n},${r}`}function Pr(e,t){const n=[];let o="static",r=!1;for(let l=e;l&&l!==e.ownerDocument.documentElement;l=l.parentElement){const u=t.getComputedStyle(l),a=l!==e.ownerDocument.body&&/auto|scroll|hidden|overlay/.test(u.overflowY+u.overflowX);a&&!r&&n.push(l),u.position==="fixed"?(o="dynamic",r=!0):u.transform!=="none"||u.filter!=="none"||u.perspective!=="none"?(o="dynamic",r=!1):(u.position==="sticky"||u.willChange.includes("transform")||u.contain.includes("layout")||a&&(l.scrollHeight>l.clientHeight||l.scrollWidth>l.clientWidth))&&(o="dynamic")}return{tier:o,clips:n}}function Mr(e,t,n,o){const r=e.ownerDocument??document,l=r.defaultView??window;at(e,"pins",_r);const u=r.createElement("div");u.className="snag-pins",u.style.cssText=Rr,e.appendChild(u);const a=r.createElement("div");a.className="snag-pins-dyn",a.style.cssText=Ir,e.appendChild(a);let d=[],v=[];const S=new Map;let _=new Map,h=null;const I=new Map;let H=new Map;const F=l.matchMedia?.("(pointer: coarse)").matches??!1,b=F?32:24,j=F?34:28;let ee=[],ne=null,le=null,X={x:0,y:0};function ue(){const $=r.defaultView,w=u.getBoundingClientRect();X={x:w.left+($?.scrollX??0),y:w.top+($?.scrollY??0)}}let ae=[];const K=new Map,oe=1e4,g=5,i=new Map,p=new Set(["testid","domid"]);function y($){const w=i.get($.id),x=w?.ref.deref();if(!x||!x.isConnected)return null;if(p.has(w.strategy))return x;if($.anchor.css)try{if(!x.matches($.anchor.css))return null}catch{return null}return x}function m($,w){const x=[],L=Un(w,$.anchor,1,x);return{element:w,strategy:i.get($.id).strategy,score:L,state:jn(L),reasons:x.length?x:["exact"],candidates:1}}function C($,w="authoritative"){S.clear(),ae=[];const x=Date.now(),L=n?.newPass?.();return $.map(E=>{const D=y(E),T=n?.get();let R=D?m(E,D):Kt(E.anchor,r,{viewportWidth:r.defaultView?.innerWidth??0,...T?{extended:T}:{},...L?{passCaches:L}:{}});if(D&&R.reasons.includes("text-drift")){const M=Kt(E.anchor,r,{viewportWidth:r.defaultView?.innerWidth??0,...T?{extended:T}:{},...L?{passCaches:L}:{}});M.score>R.score&&(R=M)}if(n&&(!R.element||R.reasons.includes("text-drift"))&&n.want(E.anchor),!R.element&&n){const M=n.fuzzyHit?.(E.id);M?R=M:n.wantFuzzy?.(E.id,E.anchor)}const J=R.element&&E.anchor.text?.exact&&(R.reasons.includes("text-drift")||R.strategy==="path-rect"&&R.score<.5);if(n&&J){const M=n.fuzzyHit?.(E.id);M&&M.score>R.score?R=M:M||n.wantFuzzy?.(E.id,E.anchor)}R.element?i.set(E.id,{ref:new WeakRef(R.element),strategy:R.strategy}):i.delete(E.id),R.element&&S.set(E.id,R.element);let V=!1;if(R.state==="orphaned"){const M=K.get(E.id)??{firstSeenAt:x,tries:0,best:R};M.tries++,R.score>=M.best.score&&(M.best=R),K.set(E.id,M);const q=n?.unavailable?.()??!1,ve=q?2:g,we=x-M.firstSeenAt<oe;w==="optimistic"||we&&(w==="navigating"||M.tries<ve)?V=!0:(R=M.best,q&&!R.reasons.includes("budget-exceeded")&&(R={...R,reasons:[...R.reasons,"budget-exceeded"]}),K.delete(E.id))}else K.delete(E.id);V||ae.push({id:E.id,state:R.state,strategy:R.strategy,confidence:R.score});const N=R.element?Vt(R.element):void 0;if(N&&(N.width>0||N.height>0)){const M=r.defaultView;E.anchor.rect={x:N.left+(M?.scrollX??0),y:N.top+(M?.scrollY??0),w:N.width,h:N.height}}return{...E,anchorState:V?E.anchorState:R.state,anchorPending:V,anchorReasons:R.reasons}})}function z(){const $=r.documentElement;return{w:$.scrollWidth,h:$.scrollHeight}}function te($,w,x){return{x:Math.min(Math.max($,14),Math.max(x.w,28)-14),y:Math.min(Math.max(w,14),Math.max(x.h,28)-14)}}function U($,w){ue(),u.textContent="",a.textContent="",d=[],v=[],_=new Map,H=new Map,I.clear(),ee=[],le=null,$.forEach((x,L)=>{const E=x.anchor.rect;if(!E)return;const D=x.anchor.offset??{fx:.5,fy:.5},T=r.createElement("div");T.className="snag-pin",T.setAttribute("data-state",x.anchorPending?"pending":x.anchorState),T.setAttribute("data-key",x.key),T.style.cssText=x.anchorPending?`${Zn("approximate",x)};opacity:.55`:Zn(x.anchorState,x);const R=S.get(x.id),{tier:J,clips:V}=R?Pr(R,l):{tier:"static",clips:[]};if(J==="dynamic"&&R){const re=R.getBoundingClientRect(),et=W();T.style.left=`${re.left-et.left+re.width*D.fx}px`,T.style.top=`${re.top-et.top+re.height*D.fy}px`,I.set(T,{x:re.left+re.width*D.fx+l.scrollX-X.x,y:re.top+re.height*D.fy+l.scrollY-X.y});const ce={node:T,el:R,fx:D.fx,fy:D.fy,clips:V};d.push(ce),T.hidden=!kt(R),T.hidden||ie(ce,re,new Map(V.map(We=>[We,We.getBoundingClientRect()])))}else{const re=te(E.x+E.w*D.fx-X.x,E.y+E.h*D.fy-X.y,z());T.style.left=`${re.x}px`,T.style.top=`${re.y}px`,I.set(T,re),R&&(v.push({node:T,el:R,fx:D.fx,fy:D.fy,clips:[]}),T.hidden=!kt(R))}T.textContent=String(L+1);const N=nr(x),M=x.anchor.role?Z("pin.target",{role:x.anchor.role,name:x.anchor.accessibleName??x.anchor.label}):x.anchor.label,q=x.comments.length-1,ve=x.anchorState==="approximate"?`~ ${x.key}`:x.key;T.setAttribute("role","button"),T.setAttribute("tabindex","0");const we=x.anchorState==="anchored"?Z(q===0?"pin.aria.none":q===1?"pin.aria.one":"pin.aria",{key:ve,target:M,status:On(x.status),replies:q}):Z("pin.aria.moved",{key:ve,target:M,status:On(x.status),where:N});T.title=we,T.setAttribute("aria-label",we),t&&Ne(T,()=>t(x)),w?.has(x.id)&&(T.hidden=!0,T.setAttribute("data-fo","")),_.set(x.id,T),H.set(T,{snag:x,ordinal:L+1}),(J==="dynamic"?a:u).appendChild(T)}),$e(),h&&ye(h),de(),be="",He(r.visibilityState==="visible"&&_.size>0)}const W=()=>a.getBoundingClientRect();let G=!1;function ie($,w,x){for(const L of $.clips){const E=x.get(L);if(E&&(w.right<=E.left||w.left>=E.right||w.bottom<=E.top||w.top>=E.bottom)){$.node.hidden=!0;return}}$.node.hidden=!1}function Ge($){const w=new Map;for(const x of $)for(const L of x.clips)w.has(L)||w.set(L,L.getBoundingClientRect());return w}const De=["open","progress","review","resolved"];function Ne($,w){$.addEventListener("click",w),$.addEventListener("keydown",x=>{x.key!=="Enter"&&x.key!==" "||(x.preventDefault(),w())})}function dt($,w,x,L,E){const D=De.find(R=>$.some(J=>J.snag.status===R))??"open",T=r.createElement("div");T.className="snag-pin snag-cluster",T.style.cssText=`${it};border-radius:50%;background:${Bn(D)};color:${Mn(D)};border:2px solid ${k.onAccent}`,T.style.left=`${w}px`,T.style.top=`${x}px`,T.textContent=String($.length),T.setAttribute("data-count",String($.length)),T.setAttribute("data-state",D),T.setAttribute("role","button"),T.setAttribute("tabindex","0"),E&&T.setAttribute("aria-expanded","true"),T.setAttribute("aria-label",Z("cluster.aria",{n:$.length,list:$.map(R=>R.ordinal).join(", ")})),Ne(T,()=>{if(E)ne=null;else if($.length<=6)ne=L;else{o?.($.map(R=>R.snag.id));return}$e()}),u.appendChild(T),ee.push(T)}function _e($,w,x,L){dt($,w,x,L,!0),$.forEach((E,D)=>{const T=w,R=x+(D+1)*(j+12),J=E.x-T,V=E.y-R,N=Math.hypot(J,V);if(N>4){const q=r.createElement("div");q.className="snag-leader",q.setAttribute("aria-hidden","true"),q.style.cssText=`position:absolute;left:${T}px;top:${R}px;width:${N}px;height:0;border-top:1px solid ${k.onAccent};transform-origin:0 0;transform:rotate(${Math.atan2(V,J)}rad)`,u.appendChild(q),ee.push(q)}const M=E.dot.cloneNode(!0);M.style.visibility="",M.style.left=`${T}px`,M.style.top=`${R}px`,Ne(M,()=>t?.(E.snag)),u.appendChild(M),ee.push(M)})}function $e(){for(const E of ee)E.remove();ee=[];const $=[];for(const[E,D]of H){if(E.hidden){E.style.visibility="";continue}const T=I.get(E);T&&$.push({dot:E,snag:D.snag,ordinal:D.ordinal,x:T.x,y:T.y})}const{members:w,visits:x}=Tr($,b);u.setAttribute("data-cv",String(x)),u.setAttribute("data-cp",String($.length));let L=!1;for(const E of w){if(E.length<2){$[E[0]].dot.style.visibility="";continue}const D=E.map(V=>$[V]),T=D.map(V=>V.snag.id).sort().join("|");for(const V of D)V.dot.style.visibility="hidden";const R=D.reduce((V,N)=>V+N.x,0)/D.length,J=D.reduce((V,N)=>V+N.y,0)/D.length;ne===T&&D.length<=6?(L=!0,_e(D,R,J,T)):dt(D,R,J,T,!1)}ne&&!L&&(ne=null)}function Ve($){le?.remove(),le=null;const w=$.anchor.rect;if(!w)return;const x=$.anchor.offset??{fx:.5,fy:.5},L=r.createElement("div");L.className="snag-pin snag-ghost",L.style.cssText=`${it};${$t};background:transparent;border:2px dashed ${k.anchorOrphan};color:${k.anchorOrphan};box-shadow:none;pointer-events:none`;const E=te(w.x+w.w*x.fx-X.x,w.y+w.h*x.fy-X.y,z());L.style.left=`${E.x}px`,L.style.top=`${E.y}px`,L.setAttribute("aria-hidden","true"),u.appendChild(L),le=L}function de($=!1){const w=$?[...d,...v]:d;G||w.length===0||(G=!0,l.requestAnimationFrame(()=>{G=!1;const x=performance.now(),L=l.scrollX,E=l.scrollY,D=W(),T=w.map(N=>N.el.isConnected?N.el.getBoundingClientRect():null),R=w.map(N=>N.el.isConnected&&kt(N.el)),J=Ge(w),V=z();w.forEach((N,M)=>{const q=T[M];if(!q)return;if(N.node.hasAttribute("data-fo")){N.node.hidden=!0;return}if(!R[M]){N.node.hidden=!0;return}N.node.hidden=!1;const ve=q.left+q.width*N.fx,we=q.top+q.height*N.fy;if(N.node.parentElement===a)N.node.style.left=`${ve-D.left}px`,N.node.style.top=`${we-D.top}px`,ie(N,q,J),I.set(N.node,{x:ve+L-X.x,y:we+E-X.y});else{const re=te(ve+L-X.x,we+E-X.y,V);N.node.style.left=`${re.x}px`,N.node.style.top=`${re.y}px`,I.set(N.node,re)}}),$e(),u.setAttribute("data-ms",(performance.now()-x).toFixed(2))}))}const ut=()=>de();r.addEventListener("scroll",ut,{capture:!0,passive:!0});const Ye=typeof l.ResizeObserver=="function"?new l.ResizeObserver(()=>de(!0)):null;Ye?.observe(r.documentElement);let Ie=null,be="";function Mt(){let $="";for(const w of[...v,...d]){if(!w.el.isConnected)continue;const x=w.el.getBoundingClientRect();$+=`${Math.round(x.left)},${Math.round(x.top)},${Math.round(x.width)};`}!$||$===be||(be=$,de(!0))}function He($){if(Ie&&clearTimeout(Ie),Ie=null,!$)return;const w=()=>{Mt(),Ie=setTimeout(w,500)};Ie=setTimeout(w,500)}const he=()=>He(r.visibilityState==="visible"&&_.size>0);r.addEventListener("visibilitychange",he);function Ot($){const w=_.get($);w&&(w.classList.remove("snag-pp"),l.requestAnimationFrame(()=>w.classList.add("snag-pp")),l.setTimeout(()=>w.classList.remove("snag-pp"),1400))}function ye($){const w=h?_.get(h):void 0;w&&(w.style.transform="",w.style.zIndex=""),h=$;const x=$?_.get($):void 0;x&&(x.style.transform="scale(1.4)",x.style.zIndex="1")}return{el:u,render:U,showGhost:Ve,pulse:Ot,reanchor:C,settled:()=>ae,hasPending:()=>K.size>0,highlight:ye,destroy(){r.removeEventListener("scroll",ut,{capture:!0}),r.removeEventListener("visibilitychange",he),Ye?.disconnect(),He(!1),u.remove(),a.remove()}}}const Or=` .snag-notice{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(24px + var(${P.tbH},56px));z-index:${qe.notice};max-width:min(420px,calc(100vw - 24px));background:${k.bg};color:${k.fg};border:1px solid ${k.border};border-inline-start:3px solid ${k.anchorOrphan};border-radius:${k.radius};box-shadow:${k.shadow};padding:12px 14px;pointer-events:auto;font:400 13px/1.45 ${k.font};display:flex;flex-direction:column;gap:10px}@media (pointer:coarse){.snag-notice{bottom:calc(12px + var(${P.tbH},64px))}}.snag-notice p{margin:0}.snag-notice-actions{display:flex;gap:6px;justify-content:flex-end}.snag-notice button{appearance:none;font:inherit;cursor:pointer;border-radius:calc(${k.radius} - 2px);padding:6px 12px;min-height:30px;border:0;transition:background ${k.motion}}.snag-notice-retry{background:${k.accent};color:${k.onAccent};font-weight:600}.snag-notice-dismiss{background:transparent;color:${k.muted}}.snag-notice-dismiss:hover{background:${k.hover};color:inherit}.snag-notice button:focus-visible{outline:2px solid ${k.focus};outline-offset:2px}`;function zr(e,t){const n=e.ownerDocument??document,o=n.defaultView??window;at(e,"notice",Or);const r=n.createElement("div");r.className="snag-notice",r.setAttribute("role","alert"),r.hidden=!0;const l=n.createElement("p"),u=n.createElement("div");u.className="snag-notice-actions";const a=n.createElement("button");a.type="button",a.className="snag-notice-dismiss",a.textContent=Z("action.dismiss"),a.addEventListener("click",()=>_());const d=n.createElement("button");d.type="button",d.className="snag-notice-retry",u.append(a,d),r.append(l,u);let v;d.addEventListener("click",()=>{_(),v?.run()});let S=0;function _(){S&&o.cancelAnimationFrame(S),S=0,r.hidden=!0,r.remove()}return{show(h,I,H){v=I,d.hidden=!I,I&&(d.textContent=Z(I.label)),r.hidden=!1,l.textContent="",(t??e).appendChild(r);const F=Z(h,H);S&&o.cancelAnimationFrame(S),S=o.requestAnimationFrame(()=>{S=0,l.textContent=F})},hide:_,visible:()=>r.isConnected&&!r.hidden,destroy(){r.remove()}}}const Lr=` .snag-paused{border:0;padding:0;background:transparent;pointer-events:auto;max-width:min(420px,calc(100vw - 32px))}.snag-paused::backdrop{background:rgb(0 0 0 / .28)}.snag-paused-box{background:${k.bg};color:${k.fg};border:1px solid ${k.border};border-inline-start:3px solid ${k.accent};border-radius:${k.radius};box-shadow:${k.shadow};padding:14px 16px;font:400 13px/1.45 ${k.font};display:flex;flex-direction:column;gap:12px}.snag-paused p{margin:0}.snag-paused-actions{display:flex;justify-content:flex-end}.snag-paused button{appearance:none;font:inherit;cursor:pointer;border:0;font-weight:600;border-radius:calc(${k.radius} - 2px);padding:6px 14px;min-height:30px;background:${k.accent};color:${k.onAccent}}.snag-paused button:focus-visible{outline:2px solid ${k.focus};outline-offset:2px}`;function Dr(e,t){const n=e.ownerDocument??document;at(e,"paused",Lr);const o=n.createElement("dialog");o.className="snag-paused",o.setAttribute("aria-label",Z("paused.dialog"));const r=n.createElement("div");r.className="snag-paused-box",r.setAttribute("role","status");const l=n.createElement("p");l.textContent=Z("paused.dialog");const u=n.createElement("div");u.className="snag-paused-actions";const a=n.createElement("button");a.type="button",a.textContent=Z("paused.close"),a.addEventListener("click",()=>S()),u.append(a),r.append(l,u),o.append(r);let d=!1;function v(){if(!d){(t??e).appendChild(o);try{o.showModal(),d=!0}catch{o.setAttribute("open",""),d=!0}}}function S(){if(d){d=!1;try{o.close()}catch{o.removeAttribute("open")}o.remove()}}return o.addEventListener("close",()=>{d=!1,o.remove()}),{show:v,hide:S,destroy(){S(),o.remove()}}}const Nr=Symbol.for(kn.original),Vn=Symbol.for(kn.wrapped),ct=()=>{};function Hr(e,t,n){let o;try{o=e[t]}catch{return ct}if(typeof o!="function"||o[Vn])return ct;const r=o,l=n(r);let u=!1;const a=function(...d){return u?r.apply(this,d):l.apply(this,d)};try{const d=a;d[Vn]=!0,d[Nr]=r,Object.defineProperty(a,"name",{value:r.name,configurable:!0}),Object.defineProperty(a,"length",{value:r.length,configurable:!0})}catch{}try{e[t]=a}catch{return ct}return e[t]!==a?ct:()=>{let d;try{d=e[t]}catch{d=void 0}if(d===a)try{e[t]=r;return}catch{}u=!0}}function Wr(e,t){const n=[];let o=0;const r=()=>{o||(o=e.requestAnimationFrame(()=>{o=0,t.onResize()}))};e.addEventListener("resize",r),n.push(()=>{o&&e.cancelAnimationFrame(o),e.removeEventListener("resize",r)}),e.visualViewport?.addEventListener("resize",r),n.push(()=>e.visualViewport?.removeEventListener("resize",r));const l=()=>void e.setTimeout(t.onResize,250);e.addEventListener("orientationchange",l),n.push(()=>e.removeEventListener("orientationchange",l));let u=e.location.pathname;const a=()=>{const b=e.location.pathname;b!==u&&(u=b,t.onRoute())},d=e.navigation;if(d){const b=()=>void e.setTimeout(a,0);d.addEventListener("navigatesuccess",b),n.push(()=>d.removeEventListener("navigatesuccess",b))}else for(const b of["pushState","replaceState"])n.push(Hr(e.history,b,j=>function(...ee){const ne=j.apply(this,ee);return e.setTimeout(a,0),ne}));const v=e.document;let S=!0;try{v.documentElement.matches(":modal")}catch{S=!1}const _=()=>{const b=v.querySelectorAll("dialog[open]");if(!S)return b.length>0;for(const j of b)if(j.matches(":modal"))return!0;return!1};let h=!1;const I=()=>{const b=_();b!==h&&(h=b,t.onModal(b))};v.addEventListener("toggle",I,!0),n.push(()=>v.removeEventListener("toggle",I,!0));const H=new MutationObserver(I);H.observe(v.documentElement,{subtree:!0,attributes:!0,attributeFilter:["open"]}),n.push(()=>H.disconnect());const F=()=>void e.setTimeout(a,0);return e.addEventListener("popstate",F),n.push(()=>e.removeEventListener("popstate",F)),{destroy(){for(const b of n)b();n.length=0}}}function jr(e,t){try{e.sessionStorage.setItem(se.handoff,JSON.stringify({openThreadId:t}))}catch{}}function Fr(e){try{const t=e.sessionStorage.getItem(se.handoff);if(t===null)return null;e.sessionStorage.removeItem(se.handoff);const n=JSON.parse(t);return typeof n.openThreadId=="string"?n.openThreadId:null}catch{return null}}const Et=["open","progress","review","resolved"];function Yn(){return{statuses:[...Et],read:"all",pageOnly:!1,newOnly:!1,sort:"page"}}function Xn(e){return e.length>0&&!Et.every(t=>e.includes(t))}function Ur(e,t,n){if(Xn(t.statuses)&&Et.includes(e.status)&&!t.statuses.includes(e.status)||t.by&&e.createdBy.id!==t.by||t.assignee!==void 0&&(e.assignee?.id??null)!==t.assignee||t.page&&e.route!==t.page)return!1;if(t.read!=="all"&&n){const o=Kn(e,n);if(t.read==="unread"&&!o||t.read==="read"&&o)return!1}return!0}function Kn(e,t){const n=t.get(e.id)??0;return Date.parse(e.updatedAt)>n}function Br(e,t){try{const n=JSON.parse(sessionStorage.getItem(se.filter(e,t))??"0");if(n?.v!==1)return null;const o=Yn(),r=Et.filter(l=>Array.isArray(n.statuses)&&n.statuses.includes(l));r.length&&(o.statuses=r),(n.read==="unread"||n.read==="read")&&(o.read=n.read),(n.sort==="newest"||n.sort==="oldest")&&(o.sort=n.sort),n.pageOnly===!0&&(o.pageOnly=!0);for(const l of["by","page","q"])typeof n[l]=="string"&&n[l]&&(o[l]=n[l]);return(n.assignee===null||typeof n.assignee=="string"&&n.assignee)&&(o.assignee=n.assignee),o}catch{return null}}function Zr(e,t,n){try{const{newOnly:o,...r}=n;sessionStorage.setItem(se.filter(e,t),JSON.stringify({v:1,...r}))}catch{}}function Vr(e,t,n){const o=e.visualViewport;let r=0;const l=()=>{if(r=0,!o)return;const a=o.offsetLeft,d=o.offsetTop;t.style.translate=a||d?`${a}px ${d}px`:"",t.style.width=`${o.width}px`,t.style.height=`${o.height}px`,n?.(o.scale)},u=()=>{r||(r=e.requestAnimationFrame(l))};return o?.addEventListener("resize",u,{passive:!0}),o?.addEventListener("scroll",u,{passive:!0}),u(),()=>{r&&e.cancelAnimationFrame(r),o?.removeEventListener("resize",u),o?.removeEventListener("scroll",u)}}const Yr=/^eyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/,Xr=/^[a-f0-9]{32,}$/i,Kr=/^(?=[A-Za-z0-9_-]{24,}$)(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9_-]+$/,Jr="[redacted]";function Jn(e){return e.includes("/")?e.split("/").map(t=>Yr.test(t)||Xr.test(t)||Kr.test(t)?Jr:t).join("/"):e}const qr=/\/index\.(html?|php)$/i;function Qr(e){if(!e.startsWith("/"))return e;let t=e.replace(qr,"/");return t.length>1&&t.endsWith("/")&&(t=t.slice(0,-1)),t.toLowerCase()}function Gr(e){try{const t=e.querySelector(`meta[name="${Jo.route}"]`)?.getAttribute("content")?.trim();return!t||t.length>512||!t.startsWith("/")?null:t}catch{return null}}function es(e,t){const n=t??Gr(e);return Qr(n??Jn(e.location.pathname))}const ts=[/^utm_/,/^(gclid|gbraid|wbraid|fbclid|msclkid|ttclid|twclid|igshid|yclid|li_fat_id)$/,/^(mc_cid|mc_eid|_hsenc|_hsmi|vero_id|oly_enc_id|oly_anon_id)$/,/^_vercel_/,/^__vercel_/,/^_rsc$/],ns=[...St.query,...St.fragment];function os(e,t=[]){return ns.includes(e)||t.includes(e)?!0:ts.some(n=>n.test(e))}function rs(e,t={}){const n=t.significantQueryParams??[];if(n!=="*"&&n.length===0)return;let o;try{o=new URLSearchParams(e)}catch{return}const r={};for(const[l,u]of o)os(l,t.ignoredQueryParams??[])||n!=="*"&&!n.includes(l)||(r[l]=u);return Object.keys(r).length>0?r:void 0}function ss(e,t,n={}){const o=n.significantQueryParams??[];if(o==="*"){const r=e??{},l=t??{},u=new Set([...Object.keys(r),...Object.keys(l)]);for(const a of u)if(r[a]!==l[a])return!1;return!0}for(const r of o)if((e?.[r]??void 0)!==(t?.[r]??void 0))return!1;return!0}const as=120,is=1e3,cs=200,ls=1e4;function ds(e,t,n){const o=t.MutationObserver;if(typeof o!="function")return{destroy:()=>{}};let r=!1,l=null,u=!1,a=!1,d=0,v=_(),S=0;function _(){return t.performance?.now?.()??0}const h=new o(()=>{r=!0,d++,H()});function I(){const b=_();return b-v>=1e3&&(d>cs&&(S=b+ls),d=0,v=b),b<S?is:as}function H(){l||(l=setTimeout(F,I()))}function F(){if(l=null,!!r){if(u){a=!0;return}r=!1,u=!0;try{n()}finally{u=!1,a&&(a=!1,r=!0,H())}}}return h.observe(e.documentElement,{childList:!0,subtree:!0}),{destroy(){h.disconnect(),l&&clearTimeout(l),l=null}}}const qn="0.1.68+e77816",us={capture:Oe.capture,"anchor-ext":Oe.anchorExt,"anchor-fuzzy":Oe.anchorFuzzy,crumbs:Oe.crumbs,screenshot:Oe.screenshot,dock:Oe.dock,text:Oe.text},Qn=new Map,Jt=new Map,Gn=new Map;function fs(e,t,n){const o=new URL(t,n.location.href).href,r=new URL(us[e],o);r.searchParams.set("cv",qn);const l=Gn.get(e)??0;return l>0&&r.searchParams.set("r",String(l)),Gn.set(e,l+1),r.href}async function ze(e,t,n=document){const o=Qn.get(e);if(o)return{ok:!0,mod:o};const r=Jt.get(e);if(r)return r;const l=(async()=>{for(let u=0;u<2;u++)try{const a=await import(fs(e,t,n));return Qn.set(e,a),{ok:!0,mod:a}}catch{}return{ok:!1,reason:"unavailable"}})();Jt.set(e,l);try{return await l}finally{Jt.delete(e)}}const hs="composer",qt=e=>se.draft(e,hs),ps=se.draft("\0","").split("\0")[0];function ms(e){try{return e.body.trim()?(localStorage.setItem(qt(e.route),JSON.stringify(e)),!0):(eo(e.route),!0)}catch{return!1}}function gs(e){try{const t=localStorage.getItem(qt(e));if(!t)return null;const n=JSON.parse(t);return!n||typeof n.body!="string"||!n.anchor||n.route!==e?null:n}catch{return null}}function eo(e){try{localStorage.removeItem(qt(e))}catch{}}function Qt(){try{for(let e=0;e<localStorage.length;e++){const t=localStorage.key(e);if(t&&t.startsWith(ps))return!0}return!1}catch{return!1}}const ys="http://www.w3.org/2000/svg";function Le(e,t,n,o=[]){const r=e.createElementNS(ys,t);for(const l in n)r.setAttribute(l,n[l]);for(const l of o)r.appendChild(l);return r}const Gt=(e,t="16",n="16",o="0 0 16 16")=>({width:t,height:n,viewBox:o,fill:"none","aria-hidden":"true"}),bs=e=>Le(e,"svg",Gt(),[Le(e,"path",{d:"M8 3v10M3 8h10",stroke:"currentColor","stroke-width":"1.75","stroke-linecap":"round"})]),vs=e=>Le(e,"svg",Gt(),[Le(e,"rect",{x:"2.25",y:"3.25",width:"11.5",height:"9.5",rx:"1.75",stroke:"currentColor","stroke-width":"1.5"}),Le(e,"path",{d:"M9.5 3.5v9",stroke:"currentColor","stroke-width":"1.5"})]),ws=e=>Le(e,"svg",{...Gt(e,"10","16","0 0 10 16"),fill:"currentColor"},[Le(e,"g",{fill:"currentColor"},[4,8,12].flatMap(t=>[3,7].map(n=>Le(e,"circle",{cx:String(n),cy:String(t),r:"1"}))))]),xs=` .snag-tb{position:fixed;z-index:${qe.toolbar};display:flex;align-items:center;gap:2px;padding:4px;border-radius:calc(${k.radius} + 4px);background:${k.bg};color:${k.fg};box-shadow:${k.shadow};font:500 13px/1 ${k.font};pointer-events:auto;user-select:none;border:1px solid ${k.border}}.snag-tb{transition:inset-inline-end ${k.motion}}.snag-tb--fine{inset-inline-end:calc(20px + env(safe-area-inset-right) + var(${P.dockW},0px));inset-block-end:calc(20px + env(safe-area-inset-bottom));transition:inset-inline-end ${k.motion}}.snag-tb--coarse{inset-inline:0;inset-block-end:0;border-radius:14px 14px 0 0;padding:6px 10px calc(6px + env(safe-area-inset-bottom));justify-content:center;gap:4px;flex-direction:column}.snag-grabber{width:36px;height:4px;border-radius:2px;background:${k.muted};margin:2px auto 6px}.snag-row{display:flex;align-items:center;gap:2px}.snag-grip{display:flex;align-items:center;padding:0 4px;color:${k.muted};cursor:grab;touch-action:none}.snag-grip:active{cursor:grabbing}.snag-seg{display:flex;background:${k.surface};border-radius:${k.radius};padding:2px;position:relative}.snag-seg::before{content:"";position:absolute;inset-block:2px;inset-inline-start:var(${P.thumbX},0);width:var(${P.thumbW},0);background:${k.accent};border-radius:calc(${k.radius} - 2px);pointer-events:none;transition:inset-inline-start ${k.motion},width ${k.motion}}.snag-seg>.snag-b[aria-pressed="true"]{background:transparent;color:${k.onAccent}}.snag-seg>.snag-b{z-index:1}.snag-b{appearance:none;border:0;background:transparent;color:inherit;font:inherit;padding:6px 11px;border-radius:calc(${k.radius} - 2px);cursor:pointer;display:flex;align-items:center;gap:6px;position:relative;min-height:32px;transition:background ${k.motion}}.snag-b:hover:not(:disabled){background:color-mix(in srgb,currentColor 12%,transparent)}.snag-b:disabled{opacity:.4;cursor:not-allowed}.snag-b[aria-pressed="true"]{background:${k.accent};color:${k.onAccent}}.snag-b:focus-visible{outline:2px solid ${k.focus};outline-offset:2px}.snag-icon{padding:6px 9px}@media (pointer:coarse){.snag-b{min-height:44px;min-width:44px;padding:6px 14px}.snag-icon{padding:6px 14px}}.snag-puck .snag-row>:not([aria-expanded]){display:none}.snag-puck{padding:4px;border-radius:50%}.snag-puck [aria-expanded]{min-width:44px;min-height:44px;border-radius:50%}`;function Ss(e,t){const n=e.ownerDocument??document,o=t.coarsePointer??n.defaultView?.matchMedia?.("(pointer: coarse)").matches??!1;at(e,"toolbar",xs);const r=n.createElement("div");r.className=`snag-tb ${o?"snag-tb--coarse":"snag-tb--fine"}`,r.setAttribute("role","toolbar"),r.setAttribute("aria-label",Z("toolbar.aria"));const l=n.createElement("div");l.className="snag-grabber",l.setAttribute("aria-hidden","true");const u=n.createElement("div");u.className="snag-row";const a=n.createElement("span");a.className="snag-grip",a.setAttribute("aria-hidden","true"),a.appendChild(ws(n));const d=n.createElement("div");d.className="snag-seg",d.setAttribute("role","group"),d.setAttribute("aria-label",Z("toolbar.group"));const v=(i,p,y)=>{const m=n.createElement("button");return m.type="button",m.className=`snag-b ${i}`,m.setAttribute("aria-label",p),typeof y=="string"?m.textContent=y:m.appendChild(y),m},S=v("",Z("toolbar.browse"),Z("toolbar.browse")),_=v("",Z("toolbar.comments"),Z("toolbar.comments")),h=v("snag-icon",Z("toolbar.add"),bs(n)),I=v("snag-icon",Z("toolbar.panel"),vs(n));I.setAttribute("aria-expanded","false"),d.append(S,_),o||u.appendChild(a),u.append(d,h,I),o&&r.appendChild(l),r.appendChild(u),(t.parent??e).appendChild(r);const H=()=>{e.host.style.setProperty(P.tbH,`${r.offsetHeight}px`)};H();let F=null;function b(i,p){const y=n.defaultView,m=r.offsetWidth,C=r.offsetHeight,z=to(i,8,Math.max(8,y.innerWidth-m-8)),te=to(p,8,Math.max(8,y.innerHeight-C-8));F={left:z,top:te},r.style.left=`${z}px`,r.style.top=`${te}px`,r.style.right="auto",r.style.bottom="auto"}const j=()=>{H(),F&&b(F.left,F.top)},ee=n.defaultView;if(ee?.addEventListener("resize",j),S.addEventListener("click",()=>t.onState("browse")),_.addEventListener("click",()=>t.onState("comments")),h.addEventListener("click",()=>t.onState(ne==="add"?"comments":"add")),I.addEventListener("click",()=>t.onPanel()),!o){let i=null;a.addEventListener("pointerdown",y=>{i={x:y.clientX,y:y.clientY,r:r.getBoundingClientRect()},a.setPointerCapture(y.pointerId),y.preventDefault()}),a.addEventListener("pointermove",y=>{i&&b(i.r.left+(y.clientX-i.x),i.r.top+(y.clientY-i.y))});const p=y=>{i=null,a.hasPointerCapture(y.pointerId)&&a.releasePointerCapture(y.pointerId)};a.addEventListener("pointerup",p),a.addEventListener("pointercancel",p)}let ne="browse";function le(i){ne=i,S.setAttribute("aria-pressed",String(i==="browse")),_.setAttribute("aria-pressed",String(i!=="browse")),h.setAttribute("aria-pressed",String(i==="add")),X()}function X(){const i=d.querySelector('.snag-b[aria-pressed="true"]'),p=d.getBoundingClientRect(),y=i?.getBoundingClientRect();if(!i||!y?.width){d.style.setProperty(P.thumbW,"0px");return}const m=n.defaultView?.getComputedStyle(d),C=m?.direction==="rtl",z=parseFloat((C?m?.paddingRight:m?.paddingLeft)??"0")||0,te=(C?p.right-y.right:y.left-p.left)-z;d.style.setProperty(P.thumbW,`${Math.round(y.width)}px`),d.style.setProperty(P.thumbX,`${Math.max(0,Math.round(te))}px`)}function ue(i){h.disabled=i,i?h.title=Z("error.panels.add"):h.removeAttribute("title")}function ae(i){h.setAttribute("aria-label",Z(i?"toolbar.add.draft":"toolbar.add"))}function K(i){_.setAttribute("aria-label",i!==null&&i>0?Z("toolbar.comments.unresolved",{n:tr(i)}):Z("toolbar.comments"))}le("browse"),K(0);function oe(i){r.classList.toggle("snag-puck",i),i||X()}function g(i){r.hidden=i,i||X(),H()}return{el:r,setState:le,setCount:K,setDegraded:ue,setDraft:ae,setPuck:oe,setConcealed:g,destroy(){ee?.removeEventListener("resize",j),e.host.style.removeProperty(P.tbH),r.remove()}}}const to=(e,t,n)=>e<t?t:e>n?n:e,no=24;function As(e,t){const n=e.innerHeight,o=t.querySelector(".snag-dk");if(!o)return{top:0,bottom:n};const r=o.getBoundingClientRect();return r.height>=n-1?{top:0,bottom:n}:{top:0,bottom:Math.max(0,r.top)}}function ks(e,t,n){const o=n.anchor.rect;if(!o)return;const r=n.anchor.offset??{fy:.5},l=o.y+o.h*r.fy,u=As(e,t),a=l-e.scrollY;if(a>=u.top+no&&a<=u.bottom-no)return;const d=e.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1;e.scrollTo({top:Math.max(0,l-(u.top+u.bottom)/2),behavior:d?"auto":"smooth"})}function en(){const e=new Uint8Array(16);crypto.getRandomValues(e);const t=Date.now();e[0]=Math.floor(t/2**40)&255,e[1]=Math.floor(t/2**32)&255,e[2]=Math.floor(t/2**24)&255,e[3]=Math.floor(t/2**16)&255,e[4]=Math.floor(t/2**8)&255,e[5]=t&255,e[6]=e[6]&15|112,e[8]=e[8]&63|128;const n=Array.from(e,o=>o.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}const $s=()=>At.thread+en(),oo=()=>At.comment+en(),Es=()=>At.attachment+en(),Cs={attachments:"direct",realtime:"none",anchorReports:!1,identity:["guest"],export:["json","md"],serverSideSearch:!1,privateThreads:!1,assignees:!1};function Ts(){const e=se.threads("probe","probe");try{return localStorage.setItem(e,"1"),localStorage.removeItem(e),!0}catch(t){return ro(t)}}function Rs(e,t,n){const o=se.threads(e,t);function r(){let a=null;try{a=localStorage.getItem(o)}catch{return[]}if(!a)return[];try{const d=JSON.parse(a);return Array.isArray(d)?d.filter(Is):[]}catch{return[]}}function l(a){try{localStorage.setItem(o,JSON.stringify(a))}catch(d){if(!ro(d))return;throw new Zt("local_quota_exceeded")}}const u=a=>({...a,updatedAt:new Date().toISOString()});return{kind:"local",capabilities:Cs,async init(a){return{uid:a.uid,env:a.env,features:{screenshots:!0,uploads:!1}}},async listThreads(a={}){let d=r();return a.route!==void 0&&(d=d.filter(v=>v.route===a.route)),a.status?.length&&(d=d.filter(v=>a.status.includes(v.status))),{data:d,serverTime:new Date().toISOString()}},async getThread(a){return r().find(d=>d.id===a)??null},async createThread(a){const d=zn(a);return l([...r(),d]),d},async patchThread(a,d){const v=r(),S=v.findIndex(H=>H.id===a);if(S<0)return null;const{assignee:_,...h}=d,I=u({...v[S],..._s(h)});return v[S]=I,l(v),I},async deleteThread(a){const d=r(),v=d.find(_=>_.id===a),S=d.filter(_=>_.id!==a);S.length!==d.length&&l(S);for(const _ of v?.attachments??[])n?.del(_.id).catch(()=>{})},async uploadAttachment(a,d){if(!n)throw new Zt("attachments_unsupported");const v=Es();return await n.put(v,{blob:a,uid:e,env:t,kind:d.kind,...d.width!==void 0?{width:d.width}:{},...d.height!==void 0?{height:d.height}:{},createdAt:Date.now()}),{id:v,kind:d.kind,url:"",...d.width!==void 0?{width:d.width}:{},...d.height!==void 0?{height:d.height}:{},bytes:a.size,contentType:a.type}},async createComment(a,d){const v=r(),S=v.findIndex(h=>h.id===a);if(S<0)return null;const _={id:d.id,snagId:a,body:d.body,author:d.author,createdAt:new Date().toISOString()};return v[S]=u({...v[S],comments:[...v[S].comments,_]}),l(v),_},async patchComment(a,d){const v=r();for(let S=0;S<v.length;S++){const _=v[S].comments.find(I=>I.id===a);if(!_)continue;const h={..._,body:d};return v[S]=u({...v[S],comments:v[S].comments.map(I=>I.id===a?h:I)}),l(v),h}return null},async deleteComment(a){const d=r(),v=d.findIndex(S=>S.comments.some(_=>_.id===a));v<0||(d[v]=u({...d[v],comments:d[v].comments.filter(S=>S.id!==a)}),l(d))}}}function _s(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ro(e){return e instanceof Error?e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED"||e.code===22||e.code===1014:!1}function Is(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.id=="string"&&typeof t.key=="string"&&typeof t.route=="string"&&typeof t.anchor=="object"&&t.anchor!==null&&typeof t.anchor.label=="string"&&Array.isArray(t.comments)}function Ps(e,t,n=()=>Date.now()){const o=se.seen(e,t);let r=null;function l(){if(r)return r;try{const a=localStorage.getItem(o),d=a?JSON.parse(a):{};return r=typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{}}catch{return r={}}}function u(a){r=a;try{localStorage.setItem(o,JSON.stringify(a))}catch{}}return{map:()=>new Map(Object.entries(l())),mark(a){u({...l(),[a]:n()})},markAll(a){const d=n(),v={...l()};for(const S of a)v[S.id]=d;u(v)}}}function lt(){let e=null;try{e=localStorage.getItem(Ft)}catch{return{}}if(!e)return{};if(e[0]!=="{")return{name:e};try{const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function so(e){try{localStorage.setItem(Ft,JSON.stringify(e))}catch{}}function tn(){const e=lt();return{name:typeof e.name=="string"?e.name:"",...e.email?{email:e.email}:{}}}function ao(e){return lt().projects?.[e]?.holderId}function Ms(e){const t=lt().projects?.[e]?.holderSecret;return t&&/^[\w-]{43}$/.test(t)?t:void 0}function Os(e,t,n){const o=lt();so({...o,projects:{...o.projects,[e]:{holderId:t,holderSecret:n}}})}function zs(e,t){const n=lt(),o=n.projects?.[e];o&&so({...n,projects:{...n.projects,[e]:{...o,holderId:t}}})}const Ls=1e6,Ct=e=>e==="member"?localStorage:sessionStorage;function io(e,t){const n=JSON.parse(Ct(t).getItem(se.list(e,t))??"0");return n?.v===1&&n.m&&typeof n.m=="object"?n.m:{}}function co(e,t,n){try{const o=io(e,t)[n];return Array.isArray(o)?o:null}catch{return null}}function Ds(e,t,n,o){const r=se.list(e,t);try{let l={};try{l=io(e,t)}catch{}l[n]=o;const u=JSON.stringify({v:1,m:l});u.length>Ls?Ct(t).removeItem(r):Ct(t).setItem(r,u)}catch{}}function Tt(e,t){try{Ct(t).removeItem(se.list(e,t))}catch{}}const Ze=e=>se.session(e);function lo(e){if(!e)return null;const t=JSON.parse(e);return typeof t?.token=="string"&&typeof t?.refreshableUntil=="number"?t:null}function Qe(e){try{const t=lo(sessionStorage.getItem(Ze(e)));if(t)return t;const n=lo(localStorage.getItem(Ze(e)));return n?.member?n:null}catch{return null}}function nn(e,t){try{t.member?(localStorage.setItem(Ze(e),JSON.stringify(t)),sessionStorage.removeItem(Ze(e))):sessionStorage.setItem(Ze(e),JSON.stringify(t))}catch{}}function Ns(e){try{sessionStorage.removeItem(Ze(e)),localStorage.removeItem(Ze(e))}catch{}}const Hs=(e,t=Date.now())=>t>e.expiresAt-3e4,Rt=(e,t=Date.now())=>t>=e.refreshableUntil;class Ae extends Error{code;status;constructor(t,n,o){super(o),this.name="HttpAdapterError",this.status=t,this.code=n}}function Ws(e){const{offset:t,testId:n,domId:o,page:r,schemaVersion:l,...u}=e;return{...u,...n?{testid:n}:{},...o?{domid:o}:{},...t?{offset:{fx:t.x,fy:t.y}}:{}}}function js(e,t){const n=e.url??"",o=/^https?:/i.test(n)?n:n?`${t}${n.startsWith("/")?"":"/"}${n}`:`${t}/api/v1/attachments/${encodeURIComponent(e.id)}/blob`;return{...e,url:o}}function _t(e,t,n){return{id:e.id,route:e.anchor?.page?.route??"",key:e.key,status:e.status,anchor:Ws(e.anchor),anchorState:e.anchorState,context:e.context,comments:e.comments??[],createdBy:e.createdBy,assignee:e.assignee??null,...e.private?{private:!0}:{},createdAt:e.createdAt,updatedAt:e.updatedAt,...e.resolvedAt?{resolvedAt:e.resolvedAt}:{},...e.attachments?.length?{attachments:e.attachments.map(o=>js(o,n))}:{},...t?{scope:{environment:t}}:{}}}function Fs(e,t){const{offset:n,testid:o,domid:r,...l}=e;return{...l,schemaVersion:Sn,...o?{testId:o}:{},...r?{domId:r}:{},offset:n?{x:n.fx,y:n.fy}:{x:.5,y:.5},page:{route:t,pathname:location.pathname,origin:location.origin}}}function Us(e,t){const n=o=>/^[\d.]+$|:/.test(o)?o:o.split(".").slice(-2).join(".");return n(e)===n(t)}const uo=10*6e4;function Bs(e,t,n,o={}){const r=e.replace(/\/+$/,""),l=`${r}/api/v1/projects/${encodeURIComponent(t)}`;let u=o.reviewToken,a=Qe(t);const d=()=>a?.member?"member":"guest",v=()=>`${n??""}:${a?.round??""}`;let S="";const _=g=>{S==d()+v()&&Ds(t,d(),v(),g)},h=()=>{S="",Ns(t),Tt(t,"member"),Tt(t,"guest")};let I=[];const H=se.silent(t);let F=0,b=Promise.resolve(!1);function j(){if(u||Date.now()-F<uo)return b;try{if(!Us(location.hostname,new URL(r).hostname)||localStorage.getItem(H)||Date.now()-Number(sessionStorage.getItem(H))<uo)return b}catch{}return F=Date.now(),b=(async()=>{try{const g=await fetch(`${l}/sessions/member/silent`,{method:"POST",credentials:"include",...n?{body:JSON.stringify({environment:n})}:{}});if(g.status===201)return ne(await g.json()),F=0,!0}catch{}try{sessionStorage.setItem(H,String(Date.now()))}catch{}return!1})()}let ee=null;function ne(g){Tt(t,"member"),a={token:g.sessionToken,expiresAt:Date.parse(g.expiresAt),refreshableUntil:Date.parse(g.refreshableUntil),reviewerId:g.reviewer.id,permissions:g.permissions,member:g.reviewer.name,...g.moderator?{moderator:!0}:{}},nn(t,a),o.onSessionStarted?.()}const le=()=>a;async function X(g=!1){const i=a&&!Rt(a)?a.token:null,p=!!i&&!u&&!g,y=p?void 0:u?{kind:"link",token:u,name:tn().name||void 0}:{kind:"guest",name:tn().name||"Anonymous",holderId:ao(t),holderSecret:Ms(t)};let m;try{m=await fetch(`${l}/sessions`,{method:"POST",credentials:"omit",headers:{"content-type":"application/json",...i?{Authorization:`Bearer ${i}`}:{}},body:JSON.stringify({...n?{environment:n}:{},...y?{identity:y}:{},client:{widget:Wo,schema:Sn}})})}catch(U){throw new Ae(0,"network_error",U.message)}finally{u=void 0}if(!m.ok){const W=(await m.json().catch(()=>null))?.error?.code??"unauthorized",G=p&&!!a?.member;if(h(),a=null,G&&m.status===401&&await j())return le();throw W==="session_revoked"||W==="token_revoked"?o.onSessionEnded?.("revoked"):m.status===401&&o.onSessionEnded?.("expired"),new Ae(m.status,W,"This review session is not valid.")}const C=await m.json();C.holderSecret&&C.reviewer?Os(t,C.reviewer.id,C.holderSecret):C.reviewer&&zs(t,C.reviewer.id);const z=C.round?.number??(p||g?a?.round:void 0),te=y?y.name:a?.name;return a&&C.reviewer&&C.reviewer.id!==a.reviewerId&&h(),a={token:C.sessionToken,expiresAt:Date.parse(C.expiresAt),refreshableUntil:Date.parse(C.refreshableUntil),reviewerId:C.reviewer?.id??a?.reviewerId??"",permissions:C.permissions??a?.permissions??[],...z!==void 0?{round:z}:{},...p&&a?.member?{member:a.member}:{},...p&&a?.member&&a.moderator?{moderator:!0}:{},...te?{name:te}:{}},nn(t,a),o.onSessionStarted?.(),a}async function ue(){if(a){if(Rt(a)){h(),a=null,await j()||o.onSessionEnded?.("expired");return}await X().catch(()=>{})}}let ae=null;async function K(){if(await(ee??=a?.member?Promise.resolve():j()),a&&Rt(a)&&(h(),a=null,!await j()))return o.onSessionEnded?.("expired"),null;const g=tn().name||null,i=a!==null&&!a.member&&g!==null&&g!==(a.name??null);if(!a||Hs(a)||u||i)try{await(ae??=X(i).finally(()=>ae=null))}catch(p){if(!(p instanceof Ae)||p.status===0)throw p;return null}return a?.token??null}async function oe(g,i,p=!1){const y=await K();let m;try{m=await fetch(l+g,{...i,headers:{"content-type":"application/json",...y?{Authorization:`Bearer ${y}`}:{},...i?.headers??{}},credentials:"omit"})}catch(C){throw new Ae(0,"network_error",C.message)}if(!m.ok){const C=await m.json().catch(()=>null),z=C?.error?.code??"http_error";if(m.status===401&&!p&&z!=="session_revoked"){const te=!!a?.member;return h(),a=null,te&&await j(),oe(g,i,!0)}throw new Ae(m.status,z,C?.error?.message??`The server answered ${m.status}.`)}return await m.json()}return{kind:"http",capabilities:{attachments:"none",realtime:"none",anchorReports:!0,identity:["guest"],export:[],serverSideSearch:!1,privateThreads:!1,assignees:!0},async init(g){K().catch(()=>{});const i=await fetch(`${l}/config`).catch(y=>{throw new Ae(0,"network_error",y.message)});if(!i.ok)throw new Ae(i.status,"http_error",`The server answered ${i.status}.`);const p=await i.json();return this.capabilities.attachments=p.features.screenshots?"direct":"none",I=p.rounds??[],{uid:g.uid,env:g.env,features:p.features,...p.rounds?{rounds:p.rounds}:{},...p.writable===void 0?{}:{writable:p.writable},...p.reason===void 0?{}:{reason:p.reason}}},async reportAnchors(g){if(g.length!==0)for(let i=0;i<g.length;i+=50)try{await oe("/anchor-reports",{method:"POST",body:JSON.stringify({reports:g.slice(i,i+50)})})}catch{return}},revalidate:ue,member:()=>a?.member??null,adoptSession(g){try{localStorage.removeItem(H)}catch{}ne(g)},signOut(){h(),a=null;try{localStorage.setItem(H,"out")}catch{}},remember:_,cached(){if(u||a&&Rt(a))return null;const g=d();return co(t,g,v())??(a?.round===I.find(i=>!i.closed)?.number?co(t,g,`${n??""}:`):null)},getRound(){return a?.round??Qe(t)?.round??null},setRound(g){a&&(a={...a,round:g});const i=Qe(t);i&&nn(t,{...i,round:g})},async fetchForeignImage(g){try{const i=await K(),p=await fetch(`${l}/image?src=${encodeURIComponent(g)}`,{credentials:"omit",...i?{headers:{Authorization:`Bearer ${i}`}}:{}});if(!p.ok)return null;const y=await p.blob();return y.type.startsWith("image/")?y:null}catch{return null}},async uploadAttachment(g,i){const p=await K(),y=await fetch(`${l}/attachments`,{method:"POST",credentials:"omit",headers:{"content-type":g.type||"image/webp",[Ut.attachmentKind]:i.kind,...i.width?{[Ut.attachmentWidth]:String(i.width)}:{},...i.height?{[Ut.attachmentHeight]:String(i.height)}:{},...p?{Authorization:`Bearer ${p}`}:{}},body:g});if(!y.ok){const C=await y.json().catch(()=>null);throw new Ae(y.status,C?.error?.code??"upload_failed",C?.error?.message??"Upload failed.")}const m=await y.json();return{id:m.id,kind:i.kind,contentType:m.contentType,byteSize:m.byteSize,...i.width?{width:i.width}:{},...i.height?{height:i.height}:{},url:`${r}/api/v1/attachments/${m.id}/blob`}},async listThreads(g){const i=!a&&!u;i?K().catch(()=>{}):await K();const p=new URLSearchParams;n&&p.set("env",n),g?.route&&p.set("route",g.route),a?.round&&p.set("round",String(a.round));const y=`/threads?${p}`,m=()=>oe(y),C=d(),z=v(),te=await(i?fetch(l+y,{credentials:"omit"}).then(W=>W.ok?W.json():m(),m):m()).catch(W=>{throw W instanceof Ae&&(W.status===401||W.status===403)&&(Tt(t,C),S=""),W}),U=te.data.map(W=>_t(W,n,r));return S=C+z,_(U),{data:U,...te.nextCursor?{nextCursor:te.nextCursor}:{},deleted:[],serverTime:te.serverTime}},async getThread(g){return(await this.listThreads()).data.find(p=>p.id===g)??null},async getThreadByKey(g){const i=new URLSearchParams({key:g});n&&i.set("env",n);const y=(await oe(`/threads?${i}`)).data[0];return y?_t(y,n,r):null},async createThread(g){const i=a?.round,p=I.some(C=>C.number===i&&!C.closed)?i:void 0,y=C=>oe("/threads",{method:"POST",body:JSON.stringify({id:g.id,anchor:Fs(g.anchor,g.route),anchorState:g.anchorState,context:g.context,...n||C?{scope:{...n?{environment:n}:{},...C?{round:C}:{}}}:{},createdBy:{name:g.createdBy.name},...g.comment?{comment:{id:g.comment.id,body:g.comment.body}}:{},...g.attachments?.length?{attachments:g.attachments.map(z=>z.id)}:{}})}),m=await y(p).catch(C=>{if(p&&C instanceof Ae&&C.code.startsWith("round_"))return y();throw C});return _t(m,n,r)},async patchThread(g,i){const p="assignee"in i;if(!i.status&&!p)return null;const y=await oe(`/threads/${encodeURIComponent(g)}`,{method:"PATCH",body:JSON.stringify({...i.status?{status:i.status}:{},...p?{assignee:i.assignee??null}:{}})});return _t(y,n,r)},async listAssignees(g){return(await oe(`/assignees${g?`?q=${encodeURIComponent(g)}`:""}`)).data??[]},async deleteThread(g){await oe(`/threads/${encodeURIComponent(g)}`,{method:"DELETE"})},isMine(g){return g.id?g.id===(a??Qe(t))?.reviewerId||g.id===ao(t):!1},canModerate(){const g=a??Qe(t);return!!g?.member&&!!g.moderator},can(g){return(a??Qe(t))?.permissions.includes(g)??!1},async createComment(g,i){const p=await oe(`/threads/${encodeURIComponent(g)}/comments`,{method:"POST",body:JSON.stringify({id:i.id,body:i.body})});return{id:p.id,snagId:g,body:p.body,author:p.author,createdAt:p.createdAt}},async patchComment(g,i){return await oe(`/comments/${encodeURIComponent(g)}`,{method:"PATCH",body:JSON.stringify({body:i})}),null},async deleteComment(g){await oe(`/comments/${encodeURIComponent(g)}`,{method:"DELETE"})}}}async function Zs(e,t){if(e.url&&/^https?:/i.test(e.url))try{const n=await fetch(e.url,{credentials:"omit"});if(!n.ok)return null;const o=await n.blob();return o.type&&!o.type.startsWith("image/")?null:o}catch{return null}return t(e.id)}const Vs=64,Ys=4096,Xs=e=>se.counts(e),Ks=e=>e.filter(t=>t.status!=="resolved").length;function Js(e,t,n){const o=new Map;for(const a of t){const d=o.get(a.route)??{n:0,seen:""};a.status!=="resolved"&&d.n++,a.updatedAt>d.seen&&(d.seen=a.updatedAt),o.set(a.route,d)}o.has(n)||o.set(n,{n:0,seen:new Date().toISOString()});const l=[...o.entries()].sort((a,d)=>d[1].seen.localeCompare(a[1].seen)).slice(0,Vs);l.some(([a])=>a===n)||(l[l.length-1]=[n,o.get(n)]);let u={v:1,p:Ks(t),r:Object.fromEntries(l.map(([a,d])=>[a,d.n])),t:new Date().toISOString()};JSON.stringify(u).length>Ys&&(u={...u,r:{}});try{localStorage.setItem(Xs(e),JSON.stringify(u))}catch{return null}return u}function qs(e,t){return e?.r[t]??0}const Qs="pass(?:word|wd)?|pwd|secret|token|api[_-]?key|apikey|auth(?:orization)?|credential|session|sid|cookie|jwt|bearer|otp|mfa|totp|cvv|cvc|ssn|nino|iban|card(?:[_-]?number)?|account[_-]?number|private[_-]?key|signature|client[_-]?secret|refresh[_-]?token|access[_-]?token",Gs=new RegExp(`(["'\`]?)(?<![A-Za-z0-9])(?:${Qs})[\\w-]*\\b\\1?\\s*[:=]\\s*(?:(["'\`])((?:\\\\.|(?!\\2)[^\\\\])*)\\2|([^\\s,;&}\\])]{3,}))`,"gi"),ea=/^(?:Bearer|Basic|Digest|Negotiate|Token)$/i,ta=(e,t,n,o,r,l,u)=>{if(!n&&ea.test(r)&&u.slice(l+e.length).startsWith(" [redacted]")||(n?o:r).startsWith("[redacted"))return e;const a=n?`${n}${o}${n}`:r;return e.slice(0,e.length-a.length)+(n?`${n}[redacted]${n}`:"[redacted]")},fo=/data:[a-z0-9.+-]*\/?[a-z0-9.+-]*;base64,[A-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\b/g,wo=/\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:[^\s/@]+@/gi,oa=/^(?=[A-Za-z0-9_~.+/=-]*[a-z])(?=[A-Za-z0-9_~.+/=-]*[A-Z])(?=[A-Za-z0-9_~.+/=-]*\d)[A-Za-z0-9_~.+/=-]{24,}$/;function Re(e,t){e.lastIndex=0;const n=e.test(t);return e.lastIndex=0,n}function xo(e){const t=e.replace(/[ -]/g,"");if(t.length<13||t.length>19)return!1;let n=0,o=!1;for(let r=t.length-1;r>=0;r--){let l=t.charCodeAt(r)-48;o&&(l*=2,l>9&&(l-=9)),n+=l,o=!o}return n%10===0}function ra(e){on.lastIndex=0;for(const t of e.matchAll(on))if(xo(t[0]))return!0;return!1}function It(e){let t=e;return t=t.replace(fo,"data:[redacted]"),t=t.replace(na,"$1 [redacted]"),t=t.replace(Gs,ta),t=t.replace(ho,"[redacted:jwt]"),t=t.replace(po,"[redacted:key]"),t=t.replace(vo,"[redacted:key]"),t=t.replace(wo,"[redacted:url-cred]@"),t=t.replace(mo,"[redacted:email]"),t=t.replace(on,n=>xo(n)?"[redacted:card]":n),t=t.replace(bo,n=>`[redacted:b64:${n.length}]`),t=t.replace(go,n=>`[redacted:b64:${n.length}]`),t=t.replace(yo,n=>`[redacted:hex:${n.length}]`),t}const sa=St.query,aa=St.fragment;function ia(e,t=[]){let n;try{const o=globalThis.location?.href;n=new URL(e,o)}catch{return It(e)}n.username="",n.password="";for(const o of[...n.searchParams.keys()]){if(aa.includes(o)){n.searchParams.set(o,"[redacted]");continue}if(sa.includes(o))continue;if(!t.includes(o)){n.searchParams.set(o,"[redacted]");continue}const r=n.searchParams.get(o)??"";It(r)!==r&&n.searchParams.set(o,"[redacted]")}return n.hash&&n.hash.length>1&&(n.hash=t.includes("#")?n.hash:"#[redacted]"),It(n.toString().replace(/%5Bredacted%5D/gi,"[redacted]"))}function ca(e){return e.length>120?!0:Re(mo,e)||Re(ho,e)||Re(po,e)||Re(yo,e)||Re(go,e)||Re(fo,e)||Re(bo,e)||Re(vo,e)||Re(wo,e)||oa.test(e)||ra(e)}const Pt={id:"rev_local",name:Z("author.unknown"),kind:"guest"};function So(e,t){if(e)return{...Pt,name:e,...t?{email:t}:{}};try{const n=localStorage.getItem(se.identity);if(n)return{...Pt,name:n[0]==="{"?JSON.parse(n).name??Pt.name:n}}catch{}return Pt}function la(e){return`SN-${e.reduce((n,o)=>{const r=Number(o.key.split("-")[1]??0);return Number.isFinite(r)&&r>n?r:n},0)+1}`}let rn=null;const ke=e=>es(e,rn);function da(e,t){const n=Cn(),o=n.ownerDocument??document,r=o.defaultView??window,l=t?.config?.site??"local",u=t?.emit??(()=>{}),a=t?.assetBase??"./",d=t?.config?.env??"default";at(n,"tokens",rr);const v=ar(n.host,sr(t?.config?.theme)),S={},_=t?.config?.storage==="local"?void 0:t?.config?.host,h=_&&l!=="local"?Bs(_,l,t?.config?.env,{reviewToken:t?.reviewToken,onSessionEnded:s=>{w.show(s==="revoked"?"error.linkrevoked":"error.sessionended")},onSessionStarted:()=>w.hide()}):Rs(l,d,{put:(s,c)=>S.put(s,c),del:s=>S.del(s)}),I=Ps(l,d);let H=null;const F=s=>h.init({uid:l,env:d}).catch(c=>s>=3?Promise.reject(c):new Promise(f=>setTimeout(f,1500*(s+1))).then(()=>F(s+1)));F(0).then(s=>{H=s.rounds??null,G?.update(M()),s.writable===!1&&s.reason==="origin_not_allowed"&&w.show("error.origin",void 0,{origin:location.origin}),s.writable===!1&&(s.reason==="site_archived"||s.reason==="site_locked")&&w.show("error.readonly")}).catch(()=>{});let b=[],j=[],ee=!0,ne=0;const le=Ts();let X=null,ue=null,ae=!1,K=!1,oe=!1,g=null,i=!1;const p={get:()=>X,unavailable:()=>K||oe,newPass:()=>ue?.createPassCaches(),fuzzyHit:s=>g?.hit(s)??null,wantFuzzy:(s,c)=>{if(g){g.enqueue(s,c,()=>Q());return}i||!ue||!c.text?.exact||c.text.exact.length<8||(i=!0,ze("anchor-fuzzy",a,o).then(f=>{if(!f.ok||!ue){oe=!0,Q();return}g=f.mod.createFuzzyEngine(o,ue.fuzzyDeps),Ce()}))},want:s=>{ae||!(s.role&&s.accessibleName)&&!s.text?.exact&&!s.path?.length||(ae=!0,ze("anchor-ext",a,o).then(c=>{if(!c.ok){K=!0,Q();return}ue=c.mod,X=c.mod.resolveExtended,Ce()}))}};let y=null,m=Br(l,d)??Yn();const C=()=>Xn(m.statuses)||!!m.by||m.assignee!==void 0||!!m.page||m.read!=="all",z=Mr(n,s=>{if(U==="add"){if(W?.hasText()){W.pulse();return}W?.close(),W=null,pe("comments")}J(s.id)},p,s=>{y=s,G?G.update(M()):J()});let U=(()=>{try{return sessionStorage.getItem(se.mode)==="comments"?"comments":"browse"}catch{return"browse"}})(),W=null,G=null,ie=null,Ge=!1,De=null,Ne=!1,dt=null,_e=null,$e=null,Ve=!1;function de(){return $e?Promise.resolve($e):Ve?Promise.resolve(null):ze("capture",a,o).then(c=>c.ok?(S.put=c.mod.putBlob,S.del=c.mod.deleteBlob,$e=c.mod):(ut(new Error("chunk unavailable")),null))}function ut(s){Ve||(Ve=!0,U==="add"&&pe("comments"),ce.setDegraded(!0),w.show("error.capture",{label:"action.retry",run:()=>{Ve=!1,ce.setDegraded(!1),de()}}),console.warn(`[${Se}] the capture chunk failed to load`,s))}let Ye=0;function Ie(){const s=new URL(a,o.location.href).href,c=new URL(Oe.panels,s);return c.searchParams.set("cv",qn),Ye>0&&c.searchParams.set("r",String(Ye)),Ye++,import(c.href)}async function be(){if(Ne)return null;if(De)return De.catch(()=>null);De=Ie().catch(async()=>(await new Promise(s=>setTimeout(s,1e3)),Ie()));try{return dt=await De}catch(s){return De=null,Mt(s),null}}function Mt(s){Ne=!0,U==="add"&&pe("comments"),ce.setDegraded(!0),w.show("error.panels",{label:"action.retry",run:()=>{Ne=!1,ce.setDegraded(!1),J(ie)}}),console.warn(`[${Se}] the panels chunk failed to load`,s)}const He=o.defaultView?.matchMedia?.("(pointer: coarse)").matches??!1;let he=null;async function Ot(){if(he)return;const s=await de();!s||he||(he=s.createAddChrome(n,He,{pick:(c,f)=>void E(c,f),announce:nt}),he.setActive(U==="add"))}const ye=o.createElement("div");ye.style.cssText=`position:fixed;left:0;top:0;pointer-events:none;z-index:${qe.dock}`,n.appendChild(ye);const $=Vr(r,ye,s=>ce.setPuck(s>1.2)),w=zr(n,ye),x=Dr(n,ye),L=pr(n,{onPick:(s,c)=>void E(s,c),onHover:s=>s?he?.show(s):he?.clear(),onSelectStart:()=>{He||dn()}});async function E(s,c){if(W?.hasText()){W.pulse();return}W?.close();const[f,A]=await Promise.all([be(),de()]);if(!f||!A)return;const O=A.captureContext({page:A.derivePageRef(o.location,yt()),...vt()});wn(s);const B=A.deriveAnchorLabel(s);D(f,s,c,O,B,A)}function D(s,c,f,A,O,B,Y,Ue){let xe=c;bt=!1;const me=ke(o);Nt=!1;const wt=()=>{W=null,eo(me),ce.setDraft(Qt()),pe("comments")},st=()=>{rt?.abort(),Fe=rt=null,wt()},ge=H?.find(fe=>fe.number===h.getRound?.())?.closed?H.find(fe=>!fe.closed):void 0,Be={at:f,label:O,...Y?{initialBody:Y.body,initialName:Y.author,...Y.email?{initialEmail:Y.email}:{}}:{},onDraft:(fe,Me,xt)=>{const Ho=ms({route:me,body:fe,author:Me,...xt?{email:xt}:{},label:O,anchor:Ue??B.createElementAnchor(c,{point:f,viewportWidth:r.innerWidth,label:O,...B.describeElement(c)}),at:{x:f.x+r.scrollX,y:f.y+r.scrollY},savedAt:new Date().toISOString()});ce.setDraft(Qt()),!Ho&&!Nt&&(Nt=!0,pn())},onSend:(fe,Me,xt)=>{wt(),ge&&h.setRound(ge.number),mn(xe,f,A,fe,Me,xt,Ue).then(()=>ge&&Ce())},onRetarget:fe=>{const Me=fe==="up"?B.widen(xe):B.narrow(xe);Me&&(xe=Me,he?.show(Me),W?.setLabel(B.deriveAnchorLabel(Me)))},...We&&ot!==!1?{onShotOptIn:fe=>bt=fe}:{},onCancel:st,crumbsOn:vn!==!1,shotsOn:ot!==!1,..._&&l!=="local"?{serverHost:new URL(_).host}:{},..._&&h.adoptSession?{studio:{host:_,uid:l,env:t?.config?.env,member:h.member(),adopt:fe=>h.adoptSession(fe),signOut:()=>h.signOut()}}:{},...Ue?.text?.exact?{quote:Ue.text.exact}:{},...ge?{roundNote:ge.name}:{}};W=s.openComposer(n,Be,ye),ft()}async function T(){const s=ke(o),c=gs(s);if(ce.setDraft(Qt()),!c||W)return;const[f,A]=await Promise.all([be(),de()]);if(!f||!A)return;const O=Kt(c.anchor,o,{viewportWidth:r.innerWidth,...X?{extended:X}:{}});if(!O.element)return;const B=O.element.getBoundingClientRect();if(B.width===0&&B.height===0)return;const Y={x:c.at.x-r.scrollX,y:c.at.y-r.scrollY};pe("add"),D(f,O.element,Y,A.captureContext({page:A.derivePageRef(o.location,yt()),...vt()}),c.label,A,{body:c.body,author:c.author,...c.email?{email:c.email}:{}})}function R(){m.newOnly&&!b.some(s=>Kn(s,I.map()))&&(m={...m,newOnly:!1})}async function J(s=null){if(s&&s!==ie&&u("thread:open",{threadId:s}),s&&(I.mark(s),R()),ie=s,Ge=!0,U==="browse"&&pe("comments"),G){G.update(M());return}if(!await be())return;const f=await ze("dock",a,o);if(!f.ok){w.show("error.panels",{label:"action.retry",run:()=>void J(ie)});return}!Ge||G||(_e=f.mod,G=f.mod.openDock(n,M(),ye),ft())}function V(){I.markAll(b),m.newOnly&&(m={...m,newOnly:!1}),Ge=!1,G?.close(),G=null,ie=null,z.highlight(null),ft(),C()&&Q()}function N(s){const c=s?b.find(f=>f.id===s):void 0;if(c&&c.route!==ke(o)){jr(r,c.id),r.location.assign(c.route);return}s&&(I.mark(s),R()),ie=s,z.highlight(null),C()?Q():G?.update(M()),c&&_e?.scrollToSnag(r,n,c)}function M(){return{snags:b,loading:ee,route:ke(o),openId:ie,seenAt:I.map(),onOpen:N,onStatus:(s,c)=>void Co(s,c),onReply:(s,c,f)=>void Ro(s,c,f),onEdit:(s,c)=>void ve(s,c),onDeleteComment:s=>void we(s),onDeleteThread:s=>void re(s),...h.isMine?{isMine:s=>h.isMine(s)}:{},..._&&h.adoptSession?{studio:{host:_,uid:l,env:t?.config?.env,member:h.member(),adopt:s=>h.adoptSession(s),signOut:()=>h.signOut()}}:{},canDeleteOwnThread:h.can?h.can("thread:delete:own"):!0,canStatus:h.can?h.can("thread:resolve"):!0,canModerate:h.canModerate?.()??!1,...h.listAssignees&&h.can?.("thread:assign")?{assignees:()=>h.listAssignees(),onAssign:(s,c)=>void To(s,c)}:{},onClearAll:()=>void et(),onMarkAllRead:()=>{I.markAll(b),m={...m,newOnly:!1},Q()},onClose:V,...h.kind==="local"?{onExport:Dt}:{},onHover:s=>z.highlight(s),...H&&H.length>1&&h.setRound?{rounds:H,activeRound:h.getRound?.()??H.find(s=>!s.closed)?.number??H[0].number,onRound:s=>{h.setRound(s),ne++,ee=!0,b=h.cached?.()??[],Q(),Ce()}}:{},onAnnounce:nt,loadShot:s=>Zs(s,async c=>{const f=await de();return f?(await f.getBlob(c))?.blob??null:null}),filter:m,onFilter:s=>{const c=s.statuses.join()!==m.statuses.join()||s.by!==m.by||s.assignee!==m.assignee||s.page!==m.page||s.read!==m.read;m=s,Zr(l,d,s),c?Q():G?.update(M())},...y?{clusterFilter:y}:{},onClusterClear:()=>{y=null,G?.update(M())},onShowAnyway:s=>{z.showGhost(s),_e?.scrollToSnag(r,n,s)}}}async function q(s,c){const f=b;b=s,Q();try{await Ke(c)}catch{b=f,Q(),h.remember?.(b),w.show("error.sendfailed",void 0,{item:"change"})}}async function ve(s,c){await q(b.map(f=>({...f,comments:f.comments.map(A=>A.id===s?{...A,body:c}:A)})),()=>h.patchComment(s,c))}async function we(s){await q(b.map(c=>({...c,comments:c.comments.filter(f=>f.id!==s)})),()=>h.deleteComment(s))}async function re(s){const c=ie;ie===s&&(ie=null),await q(b.filter(f=>f.id!==s),()=>h.deleteThread(s)),b.some(f=>f.id===s)&&(ie=c)}async function et(){const s=b.map(c=>c.id);b=[],ie=null,Q(),await Promise.all(s.map(c=>Ke(()=>h.deleteThread(c))))}const ce=Ss(n,{onState:s=>pe(s),onPanel:()=>G?V():void J(),onNav:s=>cn(s),parent:ye}),We=r.matchMedia?.("(pointer: coarse)").matches??!1,ft=()=>{We&&ce.setConcealed(!!W||!!G)};let Pe=null,ht=[];function Ao(s){let c=!1;const f=()=>{c||(c=!0,r.removeEventListener("scrollend",f),s())};r.addEventListener("scrollend",f,{once:!0}),r.setTimeout(f,600)}const tt=o.createElement("div");tt.setAttribute("aria-live","polite"),tt.setAttribute("role","status");const sn="position:absolute;width:1px;height:1px;overflow:hidden";tt.style.cssText=sn;const zt=o.createElement("div");zt.setAttribute("aria-live","assertive"),zt.style.cssText=sn,n.append(tt,zt);let an=0;function nt(s){r.clearTimeout(an),an=r.setTimeout(()=>{tt.textContent=s},400)}function cn(s){const c=ht.length;if(c===0)return;Pe=Pe===null?s===1?0:c-1:(Pe+s+c)%c;const f=ht[Pe];ks(r,n,f);const A=Pe+1;Ao(()=>{z.pulse(f.id),nt(Z("nav.announce",{n:A,label:f.anchor.label,i:A,total:c}))})}function ln(){if(U!=="comments"||He){Ee?.disarm();return}dn().then(s=>{s&&U==="comments"&&s.arm()})}let Ee=null,Lt=null;async function dn(){if(Ee)return Ee;const s=await ze("text",a,o);return!s.ok||Ee||(Lt=s.mod,Ee=s.mod.createSelectionWatcher(n,{onQuote:(c,f)=>void ko(c,f)})),Ee}async function ko(s,c){const f=$e??await de();if(!f||!Lt)return;const A=Lt.createTextAnchor(s,f,{viewportWidth:r.innerWidth,ourRoot:n});if(A.kind==="refused-form-control"){E(A.el,c);return}if(A.kind!=="text")return;const O=await be();if(!O)return;const B=f.captureContext({page:f.derivePageRef(o.location,yt()),...vt()});try{s.removeAllRanges()}catch{}D(O,A.el,A.point,B,A.label,f,void 0,A.record)}function pe(s,c=!1){const f=U;U=s,s!=="add"&&W&&!c&&(W.close(),W=null),s==="add"&&G&&V(),s==="add"&&(be(),de());try{sessionStorage.setItem(se.mode,s==="add"?"comments":s)}catch{}L.setMode(s),s!==f&&nt(Z(`toolbar.${s}`)),ft(),s==="add"&&Ot(),ln(),he?.setActive(s==="add"),ce.setState(s),Q(),s!==f&&u("modechange",{mode:s,previous:f})}let Xe=0,un=0;const fn=[300,800,1600,3200];function $o(){if(Xe||!z.hasPending()){z.hasPending()||(un=0);return}const s=fn[Math.min(un++,fn.length-1)];Xe=r.setTimeout(()=>{Xe=0,Q()},s)}const Eo=3e3;let hn=0;function Q(s){const c=s??(Date.now()<hn?"navigating":"authoritative");j=z.reanchor(b.filter(Lo()),c),zo(),$o();const f=new Map(j.map(Y=>[Y.id,Y]));b=b.map(Y=>f.get(Y.id)??Y);const A=C()?new Set(j.filter(Y=>!Ur(Y,m,I.map())&&Y.id!==ie).map(Y=>Y.id)):void 0;ht=A?j.filter(Y=>!A.has(Y.id)):j,z.render(U==="browse"?[]:j,A);const O=ke(o),B=le?Js(o.location.origin,b,O):null;ce.setCount(B?qs(B,O):le?j.filter(Y=>Y.status!=="resolved").length:null),Pe!==null&&Pe>=ht.length&&(Pe=null),G?.update(M())}async function Ce(){const s=ne;let c;try{({data:c}=await h.listThreads())}catch(A){if(s===ne){ee=!1;const O=A.status;(O===401||O===403)&&(b=[]),Q()}throw A}if(s!==ne)return j;ee=!1,b=c,Q();const f=z.settled();for(const A of f)u("anchor:settled",{threadId:A.id,state:A.state,strategy:A.strategy,confidence:A.confidence});return h.capabilities.anchorReports&&h.reportAnchors&&f.length&&Ke(()=>h.reportAnchors(f.map(A=>({threadId:A.id,state:A.state,confidence:A.confidence,strategy:A.strategy})))),h.capabilities.anchorReports||await Promise.all(c.flatMap(A=>{const O=b.find(B=>B.id===A.id);return!O||O.anchorState===A.anchorState?[]:[Ke(()=>h.patchThread(O.id,{anchor:O.anchor,anchorState:O.anchorState}))]})),j}async function Co(s,c){u("thread:resolve",{threadId:s,status:c}),await q(b.map(f=>f.id===s?{...f,status:c}:f),()=>h.patchThread(s,{status:c}))}async function To(s,c){await q(b.map(f=>f.id===s?{...f,assignee:c}:f),()=>h.patchThread(s,{assignee:c&&c.id}))}async function Ro(s,c,f){const A={id:oo(),body:c,author:So(f)};b=b.map(O=>O.id===s?{...O,comments:[...O.comments,{...A,snagId:s,createdAt:new Date().toISOString()}]}:O),I.mark(s),Q(),u("comment:create",{threadId:s,comment:A}),await Ke(()=>h.createComment(s,A))}function pn(){w.show("error.quota",{label:"action.exportclear",run:()=>{Dt("json"),et()}}),console.warn(`[${Se}] ${Z("error.quota")}`)}async function Ke(s){try{const c=await s();return h.remember?.(b),c}catch(c){if(c instanceof Zt&&c.code==="local_quota_exceeded")return pn(),null;throw c}}function Dt(s){de().then(async c=>{if(!c)return;const f=await c.resolveAttachmentUris(b).catch(()=>new Map);c.download(n,c.buildExport(s,b,{origin:o.location.origin,exportedAt:new Date().toISOString()},f),r)})}async function mn(s,c,f,A,O,B,Y){const Ue=So(O,B),xe=$e??await de();if(!xe)throw new Error(`[${Se}] add() needs the capture chunk`);Fe||wn(s);const me=Fe?await Fe:null;Fe=rt=null,xe.applyShotOutcome(f,me,ot===!1,We&&!bt);const wt=me?.blob&&h.uploadAttachment?h.uploadAttachment(me.blob,{kind:"screenshot",...me.width!==void 0?{width:me.width}:{},...me.height!==void 0?{height:me.height}:{}}).catch(()=>null):Promise.resolve(null),st={id:$s(),key:la(b),route:ke(o),anchor:Y??xe.createElementAnchor(s,{point:c,viewportWidth:r.innerWidth,label:xe.deriveAnchorLabel(s),...xe.describeElement(s)}),anchorState:"anchored",scope:Mo(),context:f,createdBy:Ue,createdAt:new Date().toISOString(),...A?{comment:{id:oo(),body:A,author:Ue}}:{}},Te=zn(st);me?.blob&&(Te.screenshotBlob=me.blob),b=[...b,Te],I.mark(Te.id),nt(Z("announce.created",{key:Te.key})),u("thread:create",{thread:Te}),U==="browse"?pe("comments"):Q();try{const ge=await wt;ge&&(st.attachments=[ge],b=b.map(Be=>Be.id===Te.id?{...Be,attachments:[ge]}:Be),Q()),await Ke(()=>h.createThread(st))}catch(ge){throw b=b.filter(Be=>Be.id!==Te.id),Q(),w.show("error.sendfailed",void 0,{item:Wt.toLowerCase()}),console.warn(`[${Se}] ${Z("error.sendfailed",{item:Wt.toLowerCase()})}`,ge),ge}return Te}function gn(s){if((s.key==="n"||s.key==="p")&&U==="comments"&&!W){if(s.metaKey||s.ctrlKey||s.altKey)return;const c=s.composedPath()[0]??s.target;if(c&&(c.closest?.("input,textarea,select,[contenteditable]")||c.isContentEditable))return;s.preventDefault(),s.stopPropagation(),cn(s.key==="n"?1:-1);return}U==="add"&&s.key==="Escape"&&(W||(s.stopPropagation(),pe("comments")))}o.addEventListener("keydown",gn,!0);let yn=0;const bn=()=>{if(o.hidden||!h.revalidate)return;const s=Date.now();s-yn<3e4||(yn=s,h.revalidate())};o.addEventListener("visibilitychange",bn);const _o=Qo(n),Io=Go(n,s=>{console.warn(`[${Se}] the host page hid the widget from assistive technology ${s} times; leaving it alone.`)}),Po=qo(n,s=>{console.warn(`[${Se}] the host page removed the widget ${s} times; leaving it alone. Reload to comment again.`)});function Mo(){return{environment:d,...t?.config?.branch?{branch:t.config.branch}:{}}}let pt={route:ke(o),url:o.location.href},Nt=!1,mt=null;function Oo(s){if(s){if(U==="browse")return;mt=U,pe("browse",!0),x.show(),u("paused",{reason:"modal-dialog"})}else if(mt){const c=mt;mt=null,x.hide(),pe(c),u("resumed",{mode:c})}}be();function zo(){j.length>0&&ze("dock",a,o)}{const s=o.createElement("div");s.style.cssText="position:fixed;inset:0;pointer-events:none;visibility:hidden",n.appendChild(s);const c=s.getBoundingClientRect(),f=Math.abs(c.left)>1||Math.abs(c.top)>1||Math.abs(c.width-r.innerWidth)>1||Math.abs(c.height-r.innerHeight)>1;s.remove(),f&&(console.warn(`[${Se}] fixed-trapped: <html> has transform/filter/contain, so our fixed layer follows it, not the viewport. Remove it, or expect drift.`),u("error",{code:"fixed-trapped"}))}let Je=null;const gt=new Set,je=(()=>{const s=r[Uo.config];return s&&typeof s=="object"?s:void 0})(),vn=je?.breadcrumbs,Ht=(()=>{const s=je?.significantQueryParams,c=je?.ignoredQueryParams,f={};return s==="*"?f.significantQueryParams="*":Array.isArray(s)&&(f.significantQueryParams=s.map(String)),Array.isArray(c)&&(f.ignoredQueryParams=c.map(String)),f})(),yt=()=>({routeOverride:rn,query:Ht,doc:o}),ot=je?.screenshot===!1?!1:je?.screenshot&&typeof je.screenshot=="object"?je.screenshot:{};let bt=!1,Fe=null,rt=null;function wn(s){if(ot===!1||Fe||We&&!bt)return;rt=new AbortController;const c=rt.signal;Fe=ze("screenshot",a,o).then(f=>f.ok?f.mod.captureScreenshot({doc:o,target:s,signal:c,...ot,...h.fetchForeignImage?{fetchForeignImage:A=>h.fetchForeignImage(A)}:{}}):{situation:"engine-load-failed",blindSpots:[],maskedCount:0})}function Lo(){const s=ke(o),c=Jn(o.location.pathname),f=rs(o.location.search,Ht);return A=>(A.route===s||A.context?.page?.pathname===c)&&ss(A.context?.page?.query,f,Ht)}{const s=vn;s!==!1&&ze("crumbs",a,o).then(c=>{c.ok&&(Je=c.mod.installTierC({win:r,...t?.early?{early:t.early}:{},...s&&typeof s=="object"?{config:s}:{},subscribeNav:f=>(gt.add(f),()=>gt.delete(f))}))})}const vt=()=>Je?{breadcrumbs:{records:Je.drain(),status:Je.status()}}:{},Do=ds(o,r,()=>{U!=="browse"&&j.length>0&&Q()}),No=Wr(r,{onResize:()=>Q(),onRoute:()=>{const s={route:ke(o),url:o.location.href},c=s.route!==pt.route;if(c){u("navigate",{from:pt,to:s});for(const f of gt)f(pt.url,s.url)}if(pt=s,!c){Ce();return}hn=Date.now()+Eo,r.setTimeout(()=>{h.listThreads().then(({data:f})=>{b=f,Q("optimistic")})},100),r.setTimeout(()=>void Ce(),600)},onModal:Oo});ce.setState(U),L.setMode(U),ln(),le||w.show("error.nostorage",{label:"action.export",run:()=>Dt("md")});const xn=h.cached?.();return xn&&(b=xn,Q()),Ce().then(async s=>{const c=Fr(r);if(!c){const A=new URLSearchParams(o.location.search).get(Xo("t"));if(A){let O=s.find(B=>B.key===A);if(!O&&h.getThreadByKey){const B=await h.getThreadByKey(A).catch(()=>null);B&&(b=[...b.filter(Y=>Y.id!==B.id),B],Q(),O=b.find(Y=>Y.id===B.id))}O?(await J(O.id),_e?.scrollToSnag(r,n,O)):(w.show("permalink.unknown"),await J(null));return}await T();return}const f=s.find(A=>A.id===c);await J(f?c:null),f&&_e?.scrollToSnag(r,n,f)}),{root:n,assetBase:t?.assetBase??"",snags:()=>j,async add(s,c,f,A){const O=A?null:await de(),B=A??(O?O.captureContext({page:O.derivePageRef(o.location,yt()),...vt()}):void 0);if(!B)throw new Error(`[${Se}] add() needs the capture chunk, or an explicit context`);return mn(s,c,B,f)},refresh:Ce,setRoute(s){rn=s&&s.startsWith("/")?s:null,Ce()},setState:pe,getState:()=>U,openPanel:J,async open(s){const c=s.startsWith(At.thread)?b.find(f=>f.id===s):b.find(f=>f.key===s);return c?c.route!==ke(o)?{ok:!1,reason:"wrong-page",url:c.context?.url??c.route,route:c.route}:(await J(c.id),_e?.scrollToSnag(r,n,c),{ok:!0,anchorState:c.anchorState}):{ok:!1,reason:"not-found"}},closePanel:V,hitTest:(s,c)=>L.hitTest(s,c),destroy(){W?.close(),V(),he?.destroy(),w.destroy(),x.destroy(),$(),Po(),Io(),_o(),No.destroy(),Do.destroy(),Je?.destroy(),Je=null,gt.clear(),Ee?.destroy(),Ee=null,g?.destroy(),g=null,Xe&&r.clearTimeout(Xe),Xe=0,o.removeEventListener("keydown",gn,!0),o.removeEventListener("visibilitychange",bn),v(),L.destroy(),z.destroy(),ce.destroy(),n.host.remove()}}}export{$n as HOST_CSS,Cn as createHost,ca as isSensitiveValue,da as mount,It as redactText,ia as redactUrl};