@commentkit/comment-kit 1.0.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +133 -1
  2. package/README.md +12 -5
  3. package/SECURITY.md +3 -1
  4. package/dist/npm/THIRD_PARTY_NOTICES.txt +22 -23
  5. package/dist/npm/chunks/AgentSend-DyWxNQ0p.js +64 -0
  6. package/dist/npm/chunks/Checklist-VYkSl6Q9.js +259 -0
  7. package/dist/npm/chunks/Composer-CnsGQirF.js +679 -0
  8. package/dist/npm/chunks/Guest-DkIvY5zt.js +170 -0
  9. package/dist/npm/chunks/MarkupEditor-DxTI9nJH.js +334 -0
  10. package/dist/npm/chunks/Panel-riaMYxt-.js +863 -0
  11. package/dist/npm/chunks/Settings-CB4zxQAL.js +206 -0
  12. package/dist/npm/chunks/{Shortcuts-BSOKdMHt.js → Shortcuts-D1cbajg_.js} +21 -17
  13. package/dist/npm/chunks/StyleEditor-BtTv3I8_.js +44 -0
  14. package/dist/npm/chunks/StylePanel-BI-n5Me1.js +199 -0
  15. package/dist/npm/chunks/TaskFields-HwrD0FrH.js +272 -0
  16. package/dist/npm/chunks/ThreadCard-CjaC8BTa.js +1026 -0
  17. package/dist/npm/chunks/Viewer-BnWshSXb.js +110 -0
  18. package/dist/npm/chunks/agent-Cr6NB6We.js +146 -0
  19. package/dist/npm/chunks/anchor-OCQnjp_6.js +294 -0
  20. package/dist/npm/chunks/{ar-O7EPv0mI.js → ar-BQ9K9Oqf.js} +189 -8
  21. package/dist/npm/chunks/card-bits-CxteYiZ9.js +126 -0
  22. package/dist/npm/chunks/client-CJ1tpI62.js +754 -0
  23. package/dist/npm/chunks/colors-0Ied7PE2.js +101 -0
  24. package/dist/npm/chunks/confetti-DKeKR7-6.js +41 -0
  25. package/dist/npm/chunks/{de-PGyZVNHX.js → de-CcPi8xdC.js} +160 -8
  26. package/dist/npm/chunks/drafts-CpQdHhcK.js +51 -0
  27. package/dist/npm/chunks/{es-Bq1idl8M.js → es-DXgkjDCG.js} +160 -8
  28. package/dist/npm/chunks/extension-BIGfr4Gh.js +50 -0
  29. package/dist/npm/chunks/{extension-B7SelsS0.js → extension-DkDSW4qw.js} +2 -2
  30. package/dist/npm/chunks/{fr-BVB9GGco.js → fr-IjJaUbWh.js} +160 -8
  31. package/dist/npm/chunks/{hi-DyBvrjzQ.js → hi-BhKQK2MU.js} +160 -8
  32. package/dist/npm/chunks/html2canvas-pro.esm-lgs6tb4C.js +8378 -0
  33. package/dist/npm/chunks/i18n-DAJGndZ2.js +904 -0
  34. package/dist/npm/chunks/{it-BlMMMwZh.js → it-DKiSCkiD.js} +160 -8
  35. package/dist/npm/chunks/{ja-lAioBCJv.js → ja-BI1WagDg.js} +160 -8
  36. package/dist/npm/chunks/{live-YFyP1GnP.js → live-B-mo27Qq.js} +1 -1
  37. package/dist/npm/chunks/lock-C82sC17d.js +30 -0
  38. package/dist/npm/chunks/{nl-DR8mLHnn.js → nl-CJw3VUQ5.js} +160 -8
  39. package/dist/npm/chunks/pick-CYPkLLFJ.js +120 -0
  40. package/dist/npm/chunks/{pt-BR-D7j6aDPx.js → pt-BR-CjBolC5g.js} +160 -8
  41. package/dist/npm/chunks/{pusher-BSsQoE1K.js → realtime-D22tI_AS.js} +58 -4
  42. package/dist/npm/chunks/source-CTQmAh0Y.js +146 -0
  43. package/dist/npm/chunks/src-CgBEoWl0.js +150 -0
  44. package/dist/npm/chunks/start-DW9_DKmf.js +1783 -0
  45. package/dist/npm/chunks/upload-BmrpZE5G.js +42 -0
  46. package/dist/npm/chunks/uploads-CipONvCy.js +541 -0
  47. package/dist/npm/chunks/{zh-CN-tzYg9NPH.js → zh-CN-BrZGx2S0.js} +160 -8
  48. package/dist/npm/element.js +4 -5
  49. package/dist/npm/headless.js +3 -3
  50. package/dist/npm/index.js +2 -2
  51. package/dist/npm/react.js +1 -1
  52. package/dist/npm/svelte.js +1 -1
  53. package/dist/npm/types/adapters/vue.d.ts +14 -0
  54. package/dist/npm/types/anchor/index.d.ts +22 -1
  55. package/dist/npm/types/core/api.d.ts +3 -0
  56. package/dist/npm/types/core/auth.d.ts +11 -0
  57. package/dist/npm/types/core/client.d.ts +128 -6
  58. package/dist/npm/types/core/types.d.ts +78 -4
  59. package/dist/npm/types/headless.d.ts +1 -1
  60. package/dist/npm/types/index.d.ts +6 -1
  61. package/dist/npm/vue.js +5 -1
  62. package/package.json +7 -5
  63. package/dist/npm/chunks/Guest-VNoofLxw.js +0 -157
  64. package/dist/npm/chunks/MarkupEditor-DTXrS3DD.js +0 -199
  65. package/dist/npm/chunks/Panel-B88JYH52.js +0 -438
  66. package/dist/npm/chunks/ThreadCard-izybwXIC.js +0 -817
  67. package/dist/npm/chunks/anchor-DT-Ynhh1.js +0 -270
  68. package/dist/npm/chunks/art-DK1JwPIo.js +0 -155
  69. package/dist/npm/chunks/client-Iegfv6ZC.js +0 -620
  70. package/dist/npm/chunks/colors-CX-IPjvb.js +0 -86
  71. package/dist/npm/chunks/extension-DSA8S8Qz.js +0 -26
  72. package/dist/npm/chunks/format-B5tJGtPC.js +0 -524
  73. package/dist/npm/chunks/html2canvas-DfGb8yka.js +0 -4024
  74. package/dist/npm/chunks/mount-Dx_8NhX3.js +0 -1484
  75. package/dist/npm/chunks/privacy-DLhezjyi.js +0 -30
  76. package/dist/npm/chunks/realtime-CBRW9BB3.js +0 -34
  77. package/dist/npm/chunks/src-C1Qp94nr.js +0 -549
@@ -0,0 +1,754 @@
1
+ //#region src/core/types.ts
2
+ var e = class extends Error {
3
+ constructor(e, t, n, r) {
4
+ super(n), this.status = e, this.code = t, this.errors = r, this.name = "CommentKitError";
5
+ }
6
+ }, t = /* @__PURE__ */ new Set([
7
+ 408,
8
+ 425,
9
+ 429,
10
+ 500,
11
+ 502,
12
+ 503,
13
+ 504
14
+ ]), n = 4, r = class {
15
+ constructor(e, t, n) {
16
+ this.baseUrl = e, this.tokens = t, this.sdkVersion = n;
17
+ }
18
+ async request(r, c = {}) {
19
+ let l = c.method ?? "GET", u = c.idempotencyKey ?? (c.idempotent ? crypto.randomUUID() : null), d = !1, f = 0;
20
+ for (let p = 0;; p++) {
21
+ let m = {
22
+ Accept: "application/json",
23
+ "X-CommentKit-SDK": this.sdkVersion,
24
+ ...c.headers
25
+ };
26
+ if (c.body !== void 0 && (m["Content-Type"] = "application/json"), u && (m["Idempotency-Key"] = u), !c.anonymous) {
27
+ let e = await this.tokens.accessToken();
28
+ e && (m.Authorization = `Bearer ${e}`);
29
+ }
30
+ let h;
31
+ try {
32
+ h = await fetch(this.url(r, c.query), {
33
+ method: l,
34
+ headers: m,
35
+ body: c.body === void 0 ? void 0 : JSON.stringify(c.body),
36
+ credentials: "omit",
37
+ signal: c.signal
38
+ });
39
+ } catch (t) {
40
+ if (c.signal?.aborted) throw t;
41
+ if (p < 3 && (l === "GET" || u)) {
42
+ await o(a(p));
43
+ continue;
44
+ }
45
+ throw new e(0, "network_error", navigator.onLine === !1 ? "You appear to be offline. Your draft is saved; try again in a moment." : "Couldn't reach CommentKit. Check your connection and try again.");
46
+ }
47
+ if (h.status === 401 && !c.anonymous && !d && (d = !0, await this.tokens.recover())) continue;
48
+ if (t.has(h.status) && p < 3 && (l === "GET" || u) && !await i(h)) {
49
+ let e = Number(h.headers.get("Retry-After"));
50
+ await o(Number.isFinite(e) && e > 0 ? Math.min(e, 30) * 1e3 : a(p));
51
+ continue;
52
+ }
53
+ if (h.status === 409 && u && f < n && h.headers.has("Retry-After") && (await h.clone().json().catch(() => null))?.code === "idempotency_in_progress") {
54
+ f++;
55
+ let e = Number(h.headers.get("Retry-After"));
56
+ await o((Number.isFinite(e) && e > 0 ? Math.min(e, 5) * 1e3 : 1e3) + Math.random() * 250);
57
+ continue;
58
+ }
59
+ if ((h.ok || h.status === 304) && c.onETag?.(h.headers.get("ETag")), h.status === 204 || h.status === 304) return;
60
+ let g = await h.text(), _ = g ? s(g) : null;
61
+ if (!h.ok) {
62
+ let t = _ ?? {};
63
+ throw new e(h.status, t.code ?? `http_${h.status}`, t.detail ?? t.title ?? "Something went wrong. Please try again.", t.errors);
64
+ }
65
+ return _;
66
+ }
67
+ }
68
+ url(e, t) {
69
+ let n = new URL(`/api/v1${e}`, this.baseUrl);
70
+ for (let [e, r] of Object.entries(t ?? {})) r != null && r !== "" && n.searchParams.set(e, String(r));
71
+ return n.toString();
72
+ }
73
+ };
74
+ async function i(e) {
75
+ return e.status === 503 && (await e.clone().json().catch(() => null))?.code === "widget_disabled";
76
+ }
77
+ function a(e) {
78
+ return Math.min(8e3, 400 * 2 ** e) + Math.random() * 250;
79
+ }
80
+ function o(e) {
81
+ return new Promise((t) => setTimeout(t, e));
82
+ }
83
+ function s(e) {
84
+ try {
85
+ return JSON.parse(e);
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ //#endregion
91
+ //#region src/core/pkce.ts
92
+ function c(e) {
93
+ let t = "";
94
+ for (let n of e) t += String.fromCharCode(n);
95
+ return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
96
+ }
97
+ function l(e = 32) {
98
+ let t = new Uint8Array(e);
99
+ return crypto.getRandomValues(t), c(t);
100
+ }
101
+ async function u(e) {
102
+ let t = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(e));
103
+ return c(new Uint8Array(t));
104
+ }
105
+ //#endregion
106
+ //#region src/core/auth.ts
107
+ function d(e = navigator.userAgent) {
108
+ return /FBAN|FBAV|Instagram|Line\/|WhatsApp|Snapchat|LinkedInApp|Slack|Twitter|MicroMessenger|; wv\)|GSA\//i.test(e);
109
+ }
110
+ var f = "popup=yes,width=460,height=680,left=120,top=80", p = 500, m = 6e5, h = 1e4, g = class {
111
+ constructor(e, t, n = location.origin) {
112
+ this.endpoint = e, this.projectKey = t, this.origin = n, this.access = null, this.refreshing = null, this.listeners = /* @__PURE__ */ new Set(), this.remember = !0, this.authorize = null;
113
+ }
114
+ get storageKey() {
115
+ return `commentkit:v1:${this.projectKey}`;
116
+ }
117
+ hasSession() {
118
+ return this.access !== null || this.readRefresh() !== null;
119
+ }
120
+ onChange(e) {
121
+ return this.listeners.add(e), () => this.listeners.delete(e);
122
+ }
123
+ async accessToken() {
124
+ return this.access && this.access.expiresAt - 3e4 > Date.now() ? this.access.token : this.readRefresh() ? await this.refresh() ? this.access?.token ?? null : null : this.pending()?.token ?? null;
125
+ }
126
+ async recover() {
127
+ return this.access = null, this.refresh();
128
+ }
129
+ async signIn(e = {}) {
130
+ let t = l(48), n = l(24), r = await u(t), i = e.mode ?? "auto", a = i === "redirect" || i === "auto" && d(), o = this.authorizeUrl(r, n, e.share ?? null, a ? location.href : null);
131
+ if (a) return this.redirect(o, t, n);
132
+ let s = window.open(o.toString(), "commentkit-signin", f);
133
+ if (!s) return i === "auto" ? this.redirect(this.authorizeUrl(r, n, e.share ?? null, location.href), t, n) : "popup_blocked";
134
+ let c = await this.awaitCode(s, n);
135
+ return c ? await this.exchange(c, t) ? "signed_in" : "failed" : "cancelled";
136
+ }
137
+ async exchange(e, t) {
138
+ try {
139
+ return this.store(await this.post("/oauth/token", {
140
+ grant_type: "authorization_code",
141
+ client_id: this.projectKey,
142
+ code: e,
143
+ code_verifier: t
144
+ })), !0;
145
+ } catch {
146
+ return !1;
147
+ }
148
+ }
149
+ async completeRedirect() {
150
+ let e = new URL(location.href), t = e.searchParams.get("ck_code"), n = e.searchParams.get("ck_state");
151
+ if (!t || !n) return !1;
152
+ e.searchParams.delete("ck_code"), e.searchParams.delete("ck_state"), history.replaceState(history.state, "", e.toString());
153
+ let r = null;
154
+ try {
155
+ r = JSON.parse(sessionStorage.getItem(this.pkceKey) ?? "null"), sessionStorage.removeItem(this.pkceKey);
156
+ } catch {
157
+ return !1;
158
+ }
159
+ return !r?.verifier || r.state !== n ? !1 : this.exchange(t, r.verifier);
160
+ }
161
+ get pkceKey() {
162
+ return `commentkit:pkce:${this.projectKey}`;
163
+ }
164
+ authorizeUrl(e, t, n, r) {
165
+ let i = new URL(this.authorize ?? "/widget/connect", this.endpoint);
166
+ return i.search = new URLSearchParams({
167
+ key: this.projectKey,
168
+ origin: this.origin,
169
+ code_challenge: e,
170
+ code_challenge_method: "S256",
171
+ state: t,
172
+ ...n ? { share: n } : {},
173
+ ...r ? { return_to: r } : {}
174
+ }).toString(), i;
175
+ }
176
+ redirect(e, t, n) {
177
+ try {
178
+ sessionStorage.setItem(this.pkceKey, JSON.stringify({
179
+ verifier: t,
180
+ state: n
181
+ }));
182
+ } catch {
183
+ return "failed";
184
+ }
185
+ return location.assign(e.toString()), "redirecting";
186
+ }
187
+ async signOut() {
188
+ let e = this.readRefresh();
189
+ this.clear(), e && await this.post("/oauth/revoke", { refresh_token: e }).catch(() => void 0);
190
+ }
191
+ awaitCode(e, t) {
192
+ let n = [new URL(this.endpoint).origin, new URL(this.authorize ?? this.endpoint).origin];
193
+ return new Promise((r) => {
194
+ let i = !1, a = Date.now(), o = (e) => {
195
+ i || (i = !0, window.removeEventListener("message", s), clearInterval(l), r(e));
196
+ }, s = (e) => {
197
+ if (!n.includes(e.origin)) return;
198
+ let r = e.data;
199
+ r?.type === "commentkit:auth" && r.state === t && typeof r.code == "string" && o(r.code);
200
+ };
201
+ window.addEventListener("message", s);
202
+ let c = null, l = setInterval(() => {
203
+ if (Date.now() - a > m) return o(null);
204
+ e.closed && (c ?? (c = Date.now())), c !== null && Date.now() - c > 1e3 && o(null);
205
+ }, p);
206
+ });
207
+ }
208
+ refresh() {
209
+ return this.refreshing ?? (this.refreshing = _(`commentkit:refresh:${this.projectKey}`, async () => {
210
+ let e = this.readRefresh();
211
+ if (!e) return !1;
212
+ try {
213
+ let t = await this.post("/oauth/token", {
214
+ grant_type: "refresh_token",
215
+ client_id: this.projectKey,
216
+ refresh_token: e
217
+ });
218
+ return this.readRefresh() === e && (this.store(t), !0);
219
+ } catch (e) {
220
+ return [
221
+ 400,
222
+ 401,
223
+ 403
224
+ ].includes(e.status ?? 0) && this.clear(), !1;
225
+ }
226
+ }).finally(() => this.refreshing = null)), this.refreshing;
227
+ }
228
+ configure(e) {
229
+ let t = this.readRefresh();
230
+ this.remember = e?.remember !== !1, t && this.write(t);
231
+ try {
232
+ let t = new URL(e?.authorize_url ?? "");
233
+ this.authorize = /^https?:$/.test(t.protocol) ? t.origin + t.pathname : null;
234
+ } catch {
235
+ this.authorize = null;
236
+ }
237
+ }
238
+ pending() {
239
+ try {
240
+ let e = JSON.parse(sessionStorage.getItem(this.pendingKey) ?? "null");
241
+ return e && e.expiresAt > Date.now() ? e : null;
242
+ } catch {
243
+ return null;
244
+ }
245
+ }
246
+ setPending(e) {
247
+ try {
248
+ e ? sessionStorage.setItem(this.pendingKey, JSON.stringify(e)) : sessionStorage.removeItem(this.pendingKey);
249
+ } catch {}
250
+ }
251
+ get pendingKey() {
252
+ return `commentkit:pending:${this.projectKey}`;
253
+ }
254
+ adopt(e) {
255
+ this.setPending(null), this.store(e);
256
+ }
257
+ store(e) {
258
+ let t = this.hasSession();
259
+ this.access = {
260
+ token: e.access_token,
261
+ expiresAt: Date.now() + e.expires_in * 1e3
262
+ }, this.write(e.refresh_token), t || this.emit(!0);
263
+ }
264
+ write(e) {
265
+ this.stores().forEach((t, n) => {
266
+ try {
267
+ e && !n ? t.setItem(this.storageKey, JSON.stringify({ refresh_token: e })) : t.removeItem(this.storageKey);
268
+ } catch {}
269
+ });
270
+ }
271
+ stores() {
272
+ try {
273
+ return this.remember ? [localStorage, sessionStorage] : [sessionStorage, localStorage];
274
+ } catch {
275
+ return [];
276
+ }
277
+ }
278
+ clear() {
279
+ let e = this.hasSession();
280
+ this.access = null, this.write(null), e && this.emit(!1);
281
+ }
282
+ readRefresh() {
283
+ for (let e of this.stores()) try {
284
+ let t = JSON.parse(e.getItem(this.storageKey) ?? "null")?.refresh_token;
285
+ if (typeof t == "string") return t;
286
+ } catch {}
287
+ return null;
288
+ }
289
+ emit(e) {
290
+ for (let t of [...this.listeners]) t(e);
291
+ }
292
+ async post(e, t) {
293
+ let n = new AbortController(), r = setTimeout(() => n.abort(), h);
294
+ try {
295
+ let r = await fetch(new URL(`/api/v1${e}`, this.endpoint), {
296
+ method: "POST",
297
+ headers: {
298
+ "Content-Type": "application/json",
299
+ Accept: "application/json"
300
+ },
301
+ body: JSON.stringify(t),
302
+ credentials: "omit",
303
+ signal: n.signal
304
+ });
305
+ if (r.status === 204) return;
306
+ let i = await r.json().catch((e) => {
307
+ if (n.signal.aborted) throw e;
308
+ return null;
309
+ });
310
+ if (!r.ok) throw Object.assign(/* @__PURE__ */ Error("auth_failed"), {
311
+ status: r.status,
312
+ data: i
313
+ });
314
+ return i;
315
+ } finally {
316
+ clearTimeout(r);
317
+ }
318
+ }
319
+ };
320
+ function _(e, t) {
321
+ let n = typeof navigator > "u" ? void 0 : navigator.locks;
322
+ return n?.request ? n.request(e, t) : import("./lock-C82sC17d.js").then((n) => n.storageLock(e, t));
323
+ }
324
+ //#endregion
325
+ //#region src/core/contract.ts
326
+ var v = /^pk_(live|test)_[a-z0-9]{20,40}$/, y = /^[A-Za-z0-9._/\-]+$/, b = /^[0-9a-f]{7,64}$/, x = /^[\p{L}\p{N}_.\/\\@+~()[\]{}$%,=!&#-]+(?::\d+){0,2}$/u, S = /^[\p{L}\p{N}_.:\/-]+$/u, C = /* @__PURE__ */ new Set();
327
+ function w(e, t, n, r) {
328
+ return t == null || t === "" ? null : t.length <= r && n.test(t) ? t : (C.has(e) || (C.add(e), console.warn(`[CommentKit] Left out ${e} "${t.slice(0, 80)}": it has characters CommentKit does not accept. See https://commentkit.dev/docs/errors#validation_failed`)), null);
329
+ }
330
+ function T(e, t) {
331
+ return {
332
+ branch: w("branch", e?.trim(), y, 255),
333
+ commit: w("commit", t?.trim().toLowerCase(), b, 64)
334
+ };
335
+ }
336
+ function E(e) {
337
+ return {
338
+ ...e,
339
+ source: w("data-ck-src", e.source, x, 500),
340
+ ck_id: w("data-ck-id", e.ck_id, S, 200)
341
+ };
342
+ }
343
+ //#endregion
344
+ //#region src/core/store.ts
345
+ function D(e) {
346
+ let t = e, n = /* @__PURE__ */ new Set();
347
+ return {
348
+ get: () => t,
349
+ set(e) {
350
+ let r = typeof e == "function" ? e(t) : e, i = !1;
351
+ for (let e in r) if (!Object.is(t[e], r[e])) {
352
+ i = !0;
353
+ break;
354
+ }
355
+ if (i) {
356
+ t = {
357
+ ...t,
358
+ ...r
359
+ };
360
+ for (let e of [...n]) e(t);
361
+ }
362
+ },
363
+ subscribe(e) {
364
+ return n.add(e), () => n.delete(e);
365
+ }
366
+ };
367
+ }
368
+ //#endregion
369
+ //#region src/core/client.ts
370
+ var O = "1.5.0", k = "https://commentkit.dev", A = "edit_conflict", j = 20, M = (e) => e ? `${e.project.id}|${e.person.type}:${e.person.id}|${e.role}` : null, N = class {
371
+ constructor(e) {
372
+ this.options = e, this.listeners = /* @__PURE__ */ new Map(), this.realtime = null, this.live = null, this.attempts = 0, this.configTag = null, this.tags = /* @__PURE__ */ new Map(), this.previews = /* @__PURE__ */ new Map(), this.unreadKnown = !1, this.conversations = /* @__PURE__ */ new Map();
373
+ let t = (e.endpoint ?? k).replace(/\/+$/, "");
374
+ this.endpoint = t, this.auth = new g(t, e.project), this.api = new r(t, this.auth, O), this.state = D({
375
+ config: null,
376
+ session: null,
377
+ threads: [],
378
+ loadingThreads: !1,
379
+ allBranches: !1,
380
+ unread: 0,
381
+ online: typeof navigator > "u" || navigator.onLine,
382
+ error: null,
383
+ here: 0,
384
+ opening: null,
385
+ request: null,
386
+ live: "off",
387
+ theme: F(),
388
+ team: []
389
+ }), this.auth.onChange((e) => {
390
+ e || (this.unreadKnown = !1, this.state.set({
391
+ session: null,
392
+ threads: [],
393
+ unread: 0
394
+ }));
395
+ }), this.offSession = this.state.subscribe((e) => {
396
+ this.live && M(e.session) !== this.live.key && this.disconnectRealtime();
397
+ });
398
+ }
399
+ get assets() {
400
+ return `${this.endpoint}/cdn`;
401
+ }
402
+ reportCrash(e, t = "crash") {
403
+ import("./report-DoDVi1qT.js").then((n) => n.reportCrash(this.endpoint, this.options.project, O, e, t, this.reportNonce)).catch(() => void 0);
404
+ }
405
+ on(e, t) {
406
+ let n = this.listeners.get(e) ?? /* @__PURE__ */ new Set();
407
+ return n.add(t), this.listeners.set(e, n), () => n.delete(t);
408
+ }
409
+ emit(e, t) {
410
+ for (let n of this.listeners.get(e) ?? []) n(t);
411
+ }
412
+ async loadConfig() {
413
+ let e = this.state.get().config, t = { "X-CommentKit-Load": this.configTag === null ? "1" : "0" };
414
+ e && this.configTag && (t["If-None-Match"] = this.configTag);
415
+ let n = null, r = await this.api.request("/widget/config", {
416
+ anonymous: !0,
417
+ query: { key: this.options.project },
418
+ headers: t,
419
+ onETag: (e) => n = e
420
+ });
421
+ return this.configTag = n ?? "", !r || (r.reporting?.nonce && (this.reportNonce = r.reporting.nonce), delete r.reporting, this.auth.configure(r.auth), e && JSON.stringify(e) === JSON.stringify(r)) ? e : (this.state.set({ config: r }), r);
422
+ }
423
+ async loadSession() {
424
+ if (!this.auth.hasSession()) return this.state.set({ session: null }), null;
425
+ try {
426
+ let e = await this.api.request("/me");
427
+ return this.state.set({ session: e }), this.emit("session:change", { session: e }), e;
428
+ } catch (t) {
429
+ if (t instanceof e && [401, 403].includes(t.status)) return this.state.set({ session: null }), null;
430
+ throw t;
431
+ }
432
+ }
433
+ async signIn(e) {
434
+ let t = await this.auth.signIn({
435
+ share: e,
436
+ mode: this.options.auth
437
+ });
438
+ return t === "signed_in" && await this.loadSession(), t;
439
+ }
440
+ async signOut() {
441
+ await this.auth.signOut(), this.state.set({
442
+ session: null,
443
+ threads: []
444
+ }), this.emit("session:change", { session: null });
445
+ }
446
+ async loadPageThreads(e = L()) {
447
+ this.state.set({ loadingThreads: !0 });
448
+ try {
449
+ let t = await this.api.request("/threads", { query: {
450
+ page_url: e,
451
+ status: "active",
452
+ limit: 100,
453
+ branch: this.branchFilter()
454
+ } });
455
+ return this.state.set({
456
+ threads: t.data,
457
+ loadingThreads: !1
458
+ }), t.data;
459
+ } catch (e) {
460
+ throw this.state.set({ loadingThreads: !1 }), e;
461
+ }
462
+ }
463
+ branchFilter() {
464
+ return this.state.get().allBranches ? void 0 : this.options.branch ?? void 0;
465
+ }
466
+ setAllBranches(e) {
467
+ return this.state.set({ allBranches: e }), this.loadPageThreads();
468
+ }
469
+ listThreads(e = {}) {
470
+ return this.api.request("/threads", { query: {
471
+ limit: 30,
472
+ ...e
473
+ } });
474
+ }
475
+ getThread(e) {
476
+ return this.thread(`/threads/${encodeURIComponent(e)}`, {});
477
+ }
478
+ async thread(e, t) {
479
+ let n = null, { data: r } = await this.api.request(e, {
480
+ ...t,
481
+ onETag: (e) => n = e
482
+ });
483
+ return this.tag(r.id, n), r;
484
+ }
485
+ tag(e, t) {
486
+ t ? this.tags.set(e, t) : this.tags.delete(e);
487
+ }
488
+ async createThread(e) {
489
+ let t = T(this.options.branch, this.options.commit), n = await this.thread("/threads", {
490
+ method: "POST",
491
+ idempotent: !0,
492
+ idempotencyKey: e.idempotencyKey,
493
+ body: {
494
+ page: {
495
+ url: L(),
496
+ title: document.title.slice(0, 500) || null,
497
+ branch: t.branch,
498
+ commit_sha: t.commit,
499
+ deployment_url: this.options.deploymentUrl ?? null
500
+ },
501
+ anchor: E(e.anchor),
502
+ breakpoint: innerWidth,
503
+ body: e.body,
504
+ capture: e.capture ?? null,
505
+ attachment_ids: e.attachmentIds ?? [],
506
+ mention_ids: e.mentionIds ?? [],
507
+ ...e.task,
508
+ ...e.description ? { description: e.description } : {},
509
+ ...e.checklist?.length ? { checklist: e.checklist } : {},
510
+ ...e.styleChanges?.length ? { style_changes: e.styleChanges } : {}
511
+ }
512
+ });
513
+ return this.upsert(n), this.emit("thread:created", { thread: n }), n;
514
+ }
515
+ async updateThread(e, t) {
516
+ let n = t.description === void 0 ? void 0 : this.tags.get(e), r = t.anchor ? {
517
+ ...t,
518
+ anchor: E(t.anchor)
519
+ } : t, i = await this.edit(e, () => this.thread(`/threads/${encodeURIComponent(e)}`, {
520
+ method: "PATCH",
521
+ body: r,
522
+ headers: n ? { "If-Match": n } : void 0
523
+ }), () => this.refreshThread(e));
524
+ return this.upsert(i), this.emit("thread:updated", { thread: i }), i;
525
+ }
526
+ async deleteThread(e) {
527
+ await this.api.request(`/threads/${encodeURIComponent(e)}`, { method: "DELETE" }), this.state.set((t) => ({ threads: t.threads.filter((t) => t.id !== e) }));
528
+ }
529
+ async messages(e, t) {
530
+ let n = await this.api.request(`/threads/${encodeURIComponent(e)}/messages`, { query: {
531
+ cursor: t,
532
+ limit: 100
533
+ } });
534
+ for (let e of n.data) this.tag(e.id, e.etag);
535
+ return n;
536
+ }
537
+ async allMessages(e, t = {}) {
538
+ let n = t.refresh ? this.conversations.get(e) : void 0, r = n ? n.slice(0, -1) : [], i = n?.at(-1)?.cursor;
539
+ for (let t = 0; t < j; t++) {
540
+ let t = await this.messages(e, i);
541
+ if (r.push({
542
+ cursor: i,
543
+ data: t.data,
544
+ next: t.next_cursor ?? null
545
+ }), !t.next_cursor) break;
546
+ i = t.next_cursor;
547
+ }
548
+ this.conversations.delete(e), this.conversations.set(e, r);
549
+ for (let e of this.conversations.keys()) {
550
+ if (this.conversations.size <= 10) break;
551
+ this.conversations.delete(e);
552
+ }
553
+ return r.flatMap((e) => e.data);
554
+ }
555
+ forgetConversationOf(e) {
556
+ for (let [t, n] of this.conversations) n.some((t) => t.data.some((t) => t.id === e)) && this.conversations.delete(t);
557
+ }
558
+ async reply(e, t, n = {}) {
559
+ let { data: r } = await this.api.request(`/threads/${encodeURIComponent(e)}/messages`, {
560
+ method: "POST",
561
+ idempotent: !0,
562
+ idempotencyKey: n.idempotencyKey,
563
+ body: {
564
+ body: t,
565
+ reply_to_id: n.replyTo ?? null,
566
+ attachment_ids: n.attachmentIds ?? [],
567
+ mention_ids: n.mentionIds ?? []
568
+ }
569
+ });
570
+ return this.tag(r.id, r.etag), this.emit("message:created", { message: r }), this.refreshThread(e), r;
571
+ }
572
+ editMessage(e, t, n = {}) {
573
+ let r = this.tags.get(e);
574
+ return this.forgetConversationOf(e), this.edit(e, async () => {
575
+ let { data: i } = await this.api.request(`/messages/${encodeURIComponent(e)}`, {
576
+ method: "PATCH",
577
+ body: {
578
+ body: t,
579
+ ...n.mentionIds ? { mention_ids: n.mentionIds } : {}
580
+ },
581
+ headers: r ? { "If-Match": r } : void 0
582
+ });
583
+ return this.tag(e, i.etag), i;
584
+ });
585
+ }
586
+ async edit(t, n, r) {
587
+ try {
588
+ return await n();
589
+ } catch (n) {
590
+ throw n instanceof e && n.code === "edit_conflict" && (this.tags.delete(t), await r?.()), n;
591
+ }
592
+ }
593
+ deleteMessage(e) {
594
+ return this.forgetConversationOf(e), this.api.request(`/messages/${encodeURIComponent(e)}`, { method: "DELETE" });
595
+ }
596
+ react(e, t, n) {
597
+ return this.forgetConversationOf(e), this.api.request(`/messages/${encodeURIComponent(e)}/reactions`, {
598
+ method: n ? "PUT" : "DELETE",
599
+ body: { emoji: t }
600
+ });
601
+ }
602
+ watch(e, t) {
603
+ return this.api.request(`/threads/${encodeURIComponent(e)}/watch`, { method: t ? "PUT" : "DELETE" });
604
+ }
605
+ labels() {
606
+ return this.api.request("/labels").then((e) => e.data);
607
+ }
608
+ people() {
609
+ return this.api.request("/people").then((e) => e.data);
610
+ }
611
+ addChecklistItem(e, t) {
612
+ return this.api.request(`/threads/${encodeURIComponent(e)}/checklist`, {
613
+ method: "POST",
614
+ body: { body: t }
615
+ }).then((e) => e.data);
616
+ }
617
+ updateChecklistItem(e, t) {
618
+ return this.api.request(`/checklist/${encodeURIComponent(e)}`, {
619
+ method: "PATCH",
620
+ body: t
621
+ }).then((e) => e.data);
622
+ }
623
+ deleteChecklistItem(e) {
624
+ return this.api.request(`/checklist/${encodeURIComponent(e)}`, { method: "DELETE" });
625
+ }
626
+ branches() {
627
+ return this.api.request("/branches").then((e) => e.data, () => []);
628
+ }
629
+ usage() {
630
+ return this.api.request("/usage").then((e) => e.storage);
631
+ }
632
+ linkPreview(e) {
633
+ let t = this.previews.get(e);
634
+ return t || (t = this.api.request("/link-preview", { query: { url: e } }).then((e) => e?.data ?? null, () => null), this.previews.set(e, t)), t;
635
+ }
636
+ get inboxLoaded() {
637
+ return this.unreadKnown;
638
+ }
639
+ async inbox() {
640
+ return (await this.inboxPage()).data;
641
+ }
642
+ async inboxPage(e) {
643
+ let t = await this.api.request("/inbox", { query: { cursor: e } });
644
+ return this.unreadKnown = !0, this.state.set({ unread: t.unread }), {
645
+ unread: t.unread,
646
+ data: t.data,
647
+ next_cursor: t.next_cursor ?? null
648
+ };
649
+ }
650
+ async markRead(e) {
651
+ let t = await this.api.request("/inbox/read", {
652
+ method: "POST",
653
+ idempotent: !0,
654
+ body: {
655
+ ids: e.ids,
656
+ thread_id: e.threadId,
657
+ all: e.all
658
+ }
659
+ });
660
+ this.unreadKnown = !0, this.state.set({ unread: t.unread });
661
+ }
662
+ upload(e, t, n = "file", r = {}) {
663
+ return import("./upload-BmrpZE5G.js").then((i) => i.upload(this.api, e, t, n, r));
664
+ }
665
+ connectRealtime(e) {
666
+ let t = this.state.get().config, n = this.state.get().session, r = M(n);
667
+ if (!t?.features.realtime || !t.realtime || !n || !r) return Promise.resolve();
668
+ if (this.live?.key === r) return this.live.ready;
669
+ this.disconnectRealtime();
670
+ let i = ++this.attempts, a = () => this.live?.attempt === i, o = (async () => {
671
+ let { connect: r } = await import("./realtime-D22tI_AS.js").then((e) => e.t);
672
+ if (!a()) return;
673
+ let i = await r({
674
+ ...t.realtime,
675
+ projectId: n.project.id,
676
+ inbox: `${n.person.type === "guest" ? "guest" : "user"}.${n.person.id}`,
677
+ authorize: async (e, t) => this.api.request("/realtime/auth", {
678
+ method: "POST",
679
+ body: {
680
+ socket_id: e,
681
+ channel_name: t
682
+ }
683
+ }),
684
+ onFeedback: (t) => a() && e(t),
685
+ onInbox: (e) => {
686
+ a() && (this.unreadKnown = !0, this.state.set({ unread: e }));
687
+ },
688
+ onPresence: (e) => a() && this.state.set({ here: e }),
689
+ onState: (e) => a() && this.state.set({ live: e }),
690
+ ...n.role === "admin" || n.role === "member" ? { onTeam: (e) => a() && this.state.set({ team: e }) } : {}
691
+ });
692
+ a() ? this.realtime = i : i.disconnect();
693
+ })().catch((e) => {
694
+ throw a() && (this.live = null), e;
695
+ });
696
+ return this.live = {
697
+ key: r,
698
+ attempt: i,
699
+ ready: o
700
+ }, o;
701
+ }
702
+ disconnectRealtime() {
703
+ this.live = null, this.realtime?.disconnect(), this.realtime = null, this.state.set({
704
+ live: "off",
705
+ here: 0,
706
+ team: []
707
+ });
708
+ }
709
+ reconnectRealtime() {
710
+ this.realtime?.reconnect?.();
711
+ }
712
+ async refreshThread(t) {
713
+ try {
714
+ this.upsert(await this.getThread(t));
715
+ } catch (n) {
716
+ n instanceof e && n.status === 404 && this.state.set((e) => ({ threads: e.threads.filter((e) => e.id !== t) }));
717
+ }
718
+ }
719
+ upsert(e) {
720
+ this.state.set((t) => {
721
+ let n = e.page.url === L() && !["resolved", "closed"].includes(e.status), r = t.threads.filter((t) => t.id !== e.id);
722
+ return { threads: n ? [e, ...r] : r };
723
+ });
724
+ }
725
+ destroy() {
726
+ this.offSession(), this.disconnectRealtime(), this.listeners.clear();
727
+ }
728
+ }, P = "commentkit:theme";
729
+ function F() {
730
+ try {
731
+ let e = typeof localStorage > "u" ? null : localStorage.getItem(P);
732
+ return e === "auto" || e === "light" || e === "dark" ? e : null;
733
+ } catch {
734
+ return null;
735
+ }
736
+ }
737
+ function I(e) {
738
+ try {
739
+ e ? localStorage.setItem(P, e) : localStorage.removeItem(P);
740
+ } catch {}
741
+ }
742
+ function L() {
743
+ let e = new URL(location.href);
744
+ for (let t of [
745
+ "ck_thread",
746
+ "ck",
747
+ "ck_invite",
748
+ "ck_code",
749
+ "ck_state"
750
+ ]) e.searchParams.delete(t);
751
+ return e.hash && !e.hash.startsWith("#/") && !e.hash.startsWith("#!/") && (e.hash = ""), e.toString();
752
+ }
753
+ //#endregion
754
+ export { I as a, T as c, l as d, r as f, L as i, g as l, A as n, v as o, e as p, O as r, x as s, N as t, u };