@commentkit/comment-kit 0.0.0-stage → 0.6.1

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 (207) hide show
  1. package/CHANGELOG.md +276 -0
  2. package/LICENSE +18 -0
  3. package/README.md +766 -2
  4. package/dist/angular/ShadowRootContext-2BrAO1qU.js +7 -0
  5. package/dist/angular/chunk-Cyg4N8Ue.js +11 -0
  6. package/dist/angular/comment-kit-ui-wEJfMh4T.js +9483 -0
  7. package/dist/angular/dom-ON-u4y6t.js +97 -0
  8. package/dist/angular/error-boundary-CxhCm8iF.js +21 -0
  9. package/dist/angular/limits-AEqOBweE.js +71 -0
  10. package/dist/angular/mount-ui-CxChSb8B.js +55 -0
  11. package/dist/angular/pusher-Vs-W-c8I.js +2504 -0
  12. package/dist/angular/realtime-CfJZMEAi.js +558 -0
  13. package/dist/angular/shadow-root-C7wgghDv.js +86 -0
  14. package/dist/angular/styles-CvndAWRF.js +2 -0
  15. package/dist/angular.es.js +3656 -0
  16. package/dist/comment-kit.es.js +3361 -0
  17. package/dist/core/ShadowRootContext--ArKkwbH.js +7 -0
  18. package/dist/core/chunk-t7YoJN_i.js +11 -0
  19. package/dist/core/comment-kit-ui-DjWARy4X.js +9483 -0
  20. package/dist/core/dom-x9svfpMk.js +223 -0
  21. package/dist/core/error-boundary-CN_BGsYl.js +21 -0
  22. package/dist/core/mount-ui-DrFjMJJu.js +55 -0
  23. package/dist/core/pusher-CizoY5NA.js +2504 -0
  24. package/dist/core/realtime-DYf6E_sN.js +278 -0
  25. package/dist/core/shadow-root-09zwHxly.js +86 -0
  26. package/dist/core/styles-D19zARBi.js +2 -0
  27. package/dist/core/websocket-manager-DorGPjR4.js +351 -0
  28. package/dist/preact/ShadowRootContext-CJWLIRy4.js +7 -0
  29. package/dist/preact/chunk-CZ0PdaaN.js +11 -0
  30. package/dist/preact/comment-kit-ui-BKi15Z4Q.js +9483 -0
  31. package/dist/preact/dom-BAV8grk_.js +97 -0
  32. package/dist/preact/error-boundary-B4-Bfy3g.js +21 -0
  33. package/dist/preact/limits-C3ZEKcL_.js +71 -0
  34. package/dist/preact/mount-ui-b9JcJQYE.js +55 -0
  35. package/dist/preact/pusher-BP4kCufH.js +2504 -0
  36. package/dist/preact/realtime-BFgP4BlB.js +558 -0
  37. package/dist/preact/shadow-root-DAhpHo_W.js +86 -0
  38. package/dist/preact/styles-Dwd4AJR8.js +2 -0
  39. package/dist/preact.es.js +3465 -0
  40. package/dist/qwik/ShadowRootContext-CTbULRKq.js +7 -0
  41. package/dist/qwik/chunk-CKKKzG2Q.js +11 -0
  42. package/dist/qwik/comment-kit-ui-CRmJhZlX.js +9483 -0
  43. package/dist/qwik/dom-BjJ-QroQ.js +97 -0
  44. package/dist/qwik/error-boundary-C4hlYQwS.js +21 -0
  45. package/dist/qwik/limits-DK35yjGY.js +71 -0
  46. package/dist/qwik/mount-ui-CaRrLb9u.js +55 -0
  47. package/dist/qwik/pusher-B1KgC4iB.js +2504 -0
  48. package/dist/qwik/realtime-DUhkZAVc.js +558 -0
  49. package/dist/qwik/shadow-root-tLjXys-_.js +86 -0
  50. package/dist/qwik/styles-BB1B91hh.js +2 -0
  51. package/dist/qwik.es.js +3458 -0
  52. package/dist/react/chunk--MHYZ-zp.js +12 -0
  53. package/dist/react/limits-Dflmuf1P.js +168 -0
  54. package/dist/react/pusher-3dki8s2l.js +2505 -0
  55. package/dist/react/realtime-C7h-Agwo.js +558 -0
  56. package/dist/react.es.js +13010 -0
  57. package/dist/solid/ShadowRootContext-BS6MCclL.js +7 -0
  58. package/dist/solid/chunk-B2NCWFvW.js +11 -0
  59. package/dist/solid/comment-kit-ui-Dw_67h_e.js +9483 -0
  60. package/dist/solid/dom-Bpw1A0oz.js +97 -0
  61. package/dist/solid/error-boundary-9mimpbZA.js +21 -0
  62. package/dist/solid/limits-B_69IbLl.js +71 -0
  63. package/dist/solid/mount-ui-bPWYgjmm.js +55 -0
  64. package/dist/solid/pusher-_RVNpj1f.js +2504 -0
  65. package/dist/solid/realtime-DK86zDCJ.js +558 -0
  66. package/dist/solid/shadow-root-D5nErAFI.js +86 -0
  67. package/dist/solid/styles-CtYBghRP.js +2 -0
  68. package/dist/solid.es.js +3446 -0
  69. package/dist/svelte/ShadowRootContext-DhByMr-q.js +7 -0
  70. package/dist/svelte/chunk-Pi70BKld.js +11 -0
  71. package/dist/svelte/comment-kit-ui-DhCWlEd8.js +9483 -0
  72. package/dist/svelte/dom-mfioQqLy.js +97 -0
  73. package/dist/svelte/error-boundary-C3GWI_IX.js +21 -0
  74. package/dist/svelte/limits-CURF22v3.js +71 -0
  75. package/dist/svelte/mount-ui-DtXWMEYn.js +55 -0
  76. package/dist/svelte/pusher-DN1BiUDw.js +2504 -0
  77. package/dist/svelte/realtime-zYOctwRk.js +558 -0
  78. package/dist/svelte/shadow-root-Cz-v-rYe.js +86 -0
  79. package/dist/svelte/styles-DKCGeARl.js +2 -0
  80. package/dist/svelte.es.js +3478 -0
  81. package/dist/types/adapters/bridge.d.ts +125 -0
  82. package/dist/types/adapters/errors.d.ts +3 -0
  83. package/dist/types/angular/index.d.ts +135 -0
  84. package/dist/types/core/agent-context.d.ts +17 -0
  85. package/dist/types/core/api-client.d.ts +137 -0
  86. package/dist/types/core/auth.d.ts +18 -0
  87. package/dist/types/core/comment-kit-core.d.ts +215 -0
  88. package/dist/types/core/comments.d.ts +43 -0
  89. package/dist/types/core/dev-grab.d.ts +14 -0
  90. package/dist/types/core/keyboard.d.ts +12 -0
  91. package/dist/types/core/limits.d.ts +52 -0
  92. package/dist/types/core/offline-queue.d.ts +23 -0
  93. package/dist/types/core/realtime.d.ts +9 -0
  94. package/dist/types/core/screenshot.d.ts +12 -0
  95. package/dist/types/core/session.d.ts +9 -0
  96. package/dist/types/core/source-resolver.d.ts +19 -0
  97. package/dist/types/core/state.d.ts +24 -0
  98. package/dist/types/core/types.d.ts +610 -0
  99. package/dist/types/core/websocket-manager.d.ts +107 -0
  100. package/dist/types/index.d.ts +85 -0
  101. package/dist/types/preact/index.d.ts +25 -0
  102. package/dist/types/qwik/index.d.ts +70 -0
  103. package/dist/types/react/client.d.ts +31 -0
  104. package/dist/types/react/comment-kit-ui.d.ts +9 -0
  105. package/dist/types/react/components/comment-fab.d.ts +34 -0
  106. package/dist/types/react/components/dev-export-panel.d.ts +10 -0
  107. package/dist/types/react/components/element-selector.d.ts +11 -0
  108. package/dist/types/react/components/live-region.d.ts +16 -0
  109. package/dist/types/react/components/screenshot-capture.d.ts +17 -0
  110. package/dist/types/react/components/status-indicator.d.ts +43 -0
  111. package/dist/types/react/error-boundary.d.ts +25 -0
  112. package/dist/types/react/index.d.ts +4 -0
  113. package/dist/types/react/is-local-host.d.ts +2 -0
  114. package/dist/types/react/mount-ui.d.ts +19 -0
  115. package/dist/types/react/shadow-root.d.ts +23 -0
  116. package/dist/types/react/shims/use-sync-external-store-with-selector.d.ts +4 -0
  117. package/dist/types/react/shims/use-sync-external-store.d.ts +1 -0
  118. package/dist/types/react/ui/lib/ShadowRootContext.d.ts +10 -0
  119. package/dist/types/react/ui/lib/cn.d.ts +12 -0
  120. package/dist/types/react/ui/primitives/alert-dialog/alert-dialog.d.ts +23 -0
  121. package/dist/types/react/ui/primitives/alert-dialog/index.d.ts +1 -0
  122. package/dist/types/react/ui/primitives/avatar/avatar.d.ts +10 -0
  123. package/dist/types/react/ui/primitives/avatar/index.d.ts +1 -0
  124. package/dist/types/react/ui/primitives/badge/badge.d.ts +5 -0
  125. package/dist/types/react/ui/primitives/badge/index.d.ts +1 -0
  126. package/dist/types/react/ui/primitives/button/button.d.ts +6 -0
  127. package/dist/types/react/ui/primitives/button/index.d.ts +1 -0
  128. package/dist/types/react/ui/primitives/card/card.d.ts +11 -0
  129. package/dist/types/react/ui/primitives/card/index.d.ts +1 -0
  130. package/dist/types/react/ui/primitives/checkbox/checkbox.d.ts +3 -0
  131. package/dist/types/react/ui/primitives/checkbox/index.d.ts +1 -0
  132. package/dist/types/react/ui/primitives/dialog/dialog.d.ts +17 -0
  133. package/dist/types/react/ui/primitives/dialog/index.d.ts +1 -0
  134. package/dist/types/react/ui/primitives/dropdown-menu/dropdown-menu.d.ts +29 -0
  135. package/dist/types/react/ui/primitives/dropdown-menu/index.d.ts +1 -0
  136. package/dist/types/react/ui/primitives/empty/empty.d.ts +10 -0
  137. package/dist/types/react/ui/primitives/empty/index.d.ts +1 -0
  138. package/dist/types/react/ui/primitives/field/field.d.ts +22 -0
  139. package/dist/types/react/ui/primitives/field/index.d.ts +1 -0
  140. package/dist/types/react/ui/primitives/hover-card/hover-card.d.ts +6 -0
  141. package/dist/types/react/ui/primitives/hover-card/index.d.ts +1 -0
  142. package/dist/types/react/ui/primitives/input/index.d.ts +1 -0
  143. package/dist/types/react/ui/primitives/input/input.d.ts +3 -0
  144. package/dist/types/react/ui/primitives/input-group/index.d.ts +1 -0
  145. package/dist/types/react/ui/primitives/input-group/input-group.d.ts +16 -0
  146. package/dist/types/react/ui/primitives/kbd/index.d.ts +1 -0
  147. package/dist/types/react/ui/primitives/kbd/kbd.d.ts +4 -0
  148. package/dist/types/react/ui/primitives/label/index.d.ts +1 -0
  149. package/dist/types/react/ui/primitives/label/label.d.ts +3 -0
  150. package/dist/types/react/ui/primitives/native-select/index.d.ts +1 -0
  151. package/dist/types/react/ui/primitives/native-select/native-select.d.ts +7 -0
  152. package/dist/types/react/ui/primitives/popover/index.d.ts +1 -0
  153. package/dist/types/react/ui/primitives/popover/popover.d.ts +9 -0
  154. package/dist/types/react/ui/primitives/preview/component-preview.d.ts +8 -0
  155. package/dist/types/react/ui/primitives/progress/index.d.ts +1 -0
  156. package/dist/types/react/ui/primitives/progress/progress.d.ts +7 -0
  157. package/dist/types/react/ui/primitives/radio-group/index.d.ts +1 -0
  158. package/dist/types/react/ui/primitives/radio-group/radio-group.d.ts +6 -0
  159. package/dist/types/react/ui/primitives/scroll-area/index.d.ts +1 -0
  160. package/dist/types/react/ui/primitives/scroll-area/scroll-area.d.ts +6 -0
  161. package/dist/types/react/ui/primitives/select/index.d.ts +1 -0
  162. package/dist/types/react/ui/primitives/select/select.d.ts +15 -0
  163. package/dist/types/react/ui/primitives/separator/index.d.ts +1 -0
  164. package/dist/types/react/ui/primitives/separator/separator.d.ts +3 -0
  165. package/dist/types/react/ui/primitives/sheet/index.d.ts +1 -0
  166. package/dist/types/react/ui/primitives/sheet/sheet.d.ts +14 -0
  167. package/dist/types/react/ui/primitives/skeleton/index.d.ts +1 -0
  168. package/dist/types/react/ui/primitives/skeleton/skeleton.d.ts +3 -0
  169. package/dist/types/react/ui/primitives/slider/index.d.ts +1 -0
  170. package/dist/types/react/ui/primitives/slider/slider.d.ts +7 -0
  171. package/dist/types/react/ui/primitives/sonner/index.d.ts +1 -0
  172. package/dist/types/react/ui/primitives/sonner/sonner.d.ts +4 -0
  173. package/dist/types/react/ui/primitives/spinner/index.d.ts +1 -0
  174. package/dist/types/react/ui/primitives/spinner/spinner.d.ts +3 -0
  175. package/dist/types/react/ui/primitives/switch/index.d.ts +1 -0
  176. package/dist/types/react/ui/primitives/switch/switch.d.ts +5 -0
  177. package/dist/types/react/ui/primitives/tabs/index.d.ts +1 -0
  178. package/dist/types/react/ui/primitives/tabs/tabs.d.ts +8 -0
  179. package/dist/types/react/ui/primitives/textarea/index.d.ts +1 -0
  180. package/dist/types/react/ui/primitives/textarea/textarea.d.ts +3 -0
  181. package/dist/types/react/ui/primitives/toggle/index.d.ts +1 -0
  182. package/dist/types/react/ui/primitives/toggle/toggle.d.ts +7 -0
  183. package/dist/types/react/ui/primitives/toggle-group/index.d.ts +1 -0
  184. package/dist/types/react/ui/primitives/toggle-group/toggle-group.d.ts +14 -0
  185. package/dist/types/react/ui/primitives/tooltip/index.d.ts +1 -0
  186. package/dist/types/react/ui/primitives/tooltip/tooltip.d.ts +7 -0
  187. package/dist/types/solid/index.d.ts +37 -0
  188. package/dist/types/svelte/index.d.ts +55 -0
  189. package/dist/types/utils/dom.d.ts +59 -0
  190. package/dist/types/utils/event-emitter.d.ts +11 -0
  191. package/dist/types/utils/freeze-animations.d.ts +8 -0
  192. package/dist/types/utils/text.d.ts +9 -0
  193. package/dist/types/utils/validation.d.ts +10 -0
  194. package/dist/types/vue/index.d.ts +87 -0
  195. package/dist/vue/ShadowRootContext-BQTcHNil.js +7 -0
  196. package/dist/vue/chunk-DHrubWSL.js +11 -0
  197. package/dist/vue/comment-kit-ui-BX1wDZ2c.js +9483 -0
  198. package/dist/vue/dom-eo0P9Z6Z.js +97 -0
  199. package/dist/vue/error-boundary-DW6uGR8U.js +21 -0
  200. package/dist/vue/limits-B6csdQeI.js +71 -0
  201. package/dist/vue/mount-ui-DdTYzv6J.js +55 -0
  202. package/dist/vue/pusher-cmjNbW6a.js +2504 -0
  203. package/dist/vue/realtime-YJKvS2eB.js +558 -0
  204. package/dist/vue/shadow-root-SLTVf5yk.js +86 -0
  205. package/dist/vue/styles-BrHt1-ia.js +2 -0
  206. package/dist/vue.es.js +3495 -0
  207. package/package.json +205 -4
package/dist/vue.es.js ADDED
@@ -0,0 +1,3495 @@
1
+ import { c as e, d as t, i as n, l as r, n as i, o as a, r as o, s, t as c, u as l } from "./vue/limits-B6csdQeI.js";
2
+ import { i as u, n as d, r as f, t as p } from "./vue/dom-eo0P9Z6Z.js";
3
+ import { computed as m, h, onMounted as g, onUnmounted as _, shallowRef as v, watch as y } from "vue";
4
+ var b = 100, x = () => {};
5
+ function S(e) {
6
+ return typeof e == "function";
7
+ }
8
+ var ee = class {
9
+ constructor() {
10
+ this.listeners = /* @__PURE__ */ new Map(), this.onceWrappers = /* @__PURE__ */ new Map();
11
+ }
12
+ on(e, t) {
13
+ if (!S(t)) return console.warn(`[CommentKit] Ignoring non-function listener for '${String(e)}'`), x;
14
+ let n = this.listeners.get(e);
15
+ return n || (n = /* @__PURE__ */ new Set(), this.listeners.set(e, n)), !n.has(t) && n.size >= b && console.warn(`[CommentKit] Max listeners (${b}) reached for '${String(e)}' - possible memory leak`), n.add(t), () => this.off(e, t);
16
+ }
17
+ off(e, t) {
18
+ if (!S(t)) return;
19
+ let n = this.listeners.get(e);
20
+ if (n) {
21
+ n.delete(t);
22
+ let r = this.onceWrappers.get(e), i = r?.get(t);
23
+ r && i && (n.delete(i), r.delete(t), r.size === 0 && this.onceWrappers.delete(e)), n.size === 0 && this.listeners.delete(e);
24
+ }
25
+ }
26
+ emit(e, t) {
27
+ let n = this.listeners.get(e);
28
+ if (n) for (let r of Array.from(n)) try {
29
+ r(t);
30
+ } catch (t) {
31
+ console.error(`[CommentKit] Error in '${e}' listener:`, t);
32
+ }
33
+ }
34
+ once(e, t) {
35
+ if (!S(t)) return console.warn(`[CommentKit] Ignoring non-function listener for '${String(e)}'`), x;
36
+ let n = (n) => {
37
+ this.off(e, t), t(n);
38
+ }, r = this.onceWrappers.get(e);
39
+ return r || (r = /* @__PURE__ */ new Map(), this.onceWrappers.set(e, r)), r.set(t, n), this.on(e, n);
40
+ }
41
+ removeAllListeners(e) {
42
+ e ? (this.listeners.delete(e), this.onceWrappers.delete(e)) : (this.listeners.clear(), this.onceWrappers.clear());
43
+ }
44
+ listenerCount(e) {
45
+ return this.listeners.get(e)?.size ?? 0;
46
+ }
47
+ }, te = "https://api.commentkit.com/api", ne = 3e4, re = 10 * 1024 * 1024, ie = 10, ae = 1e4, C = 5e3, w = 254, T = 6, oe = 4096, E = [
48
+ ".png",
49
+ ".jpg",
50
+ ".jpeg",
51
+ ".gif",
52
+ ".webp"
53
+ ], D = [
54
+ "image/png",
55
+ "image/jpeg",
56
+ "image/gif",
57
+ "image/webp"
58
+ ], se = /@\[([^\]]+)\]\(([^)]+)\)/g, ce = {
59
+ invalid_api_key: "Authentication failed. Please check your API key.",
60
+ missing_api_key: "Authentication failed. Please check your API key.",
61
+ origin_not_allowed: "This domain is not allowed to use this project's API key.",
62
+ invalid_email: "A valid email address is required.",
63
+ invalid_otp: "A valid OTP code is required.",
64
+ invalid_token: "A valid invite token is required.",
65
+ network_error: "Unable to connect to servers. Please check your connection.",
66
+ timeout: "Request timed out. Please try again.",
67
+ rate_limit: "Too many requests. Please wait before trying again.",
68
+ unauthorized: "You are not authorized to perform this action.",
69
+ not_found: "The requested resource was not found.",
70
+ validation_error: "Invalid input. Please check your data.",
71
+ invalid_response: "Invalid server response.",
72
+ auth_failed: "Sign-in failed. Please check your email and try again.",
73
+ otp_cooldown: "A code was sent recently — please wait a minute before requesting another.",
74
+ otp_not_found: "No verification code found. Request a new one.",
75
+ otp_expired: "That verification code has expired. Request a new one.",
76
+ otp_max_attempts: "Too many incorrect attempts. Request a new code.",
77
+ otp_invalid: "Incorrect verification code. Please try again.",
78
+ invalid_invite: "This invite link is invalid or has expired.",
79
+ email_mismatch: "This invite was issued for a different email address.",
80
+ quota_exceeded: "This project has reached its plan limit."
81
+ };
82
+ function O(e, t) {
83
+ let n = {};
84
+ return e.content !== void 0 && (n.content = e.content), e.status !== void 0 && (n.status = e.status), e.priority !== void 0 && (n.priority = e.priority), e.description !== void 0 && (n.description = e.description), e.assignees !== void 0 && (n.assignees = e.assignees.map((e) => e.id)), e.checklist !== void 0 && (n.checklist = e.checklist.map((e) => ({
85
+ ...e,
86
+ id: /^\d+$/.test(e.id) ? Number(e.id) : null
87
+ }))), e.textSelection !== void 0 && (n.text_selection = e.textSelection), e.drawingData !== void 0 && (n.drawing_data = e.drawingData), e.attachmentIds !== void 0 && (n.attachment_ids = e.attachmentIds.map((e) => typeof e == "number" ? e : Number(e)).filter((e) => Number.isInteger(e) && e > 0).slice(0, 20)), t && t.length > 0 && (n.mentions = t), n;
88
+ }
89
+ function le(e) {
90
+ return e === "localhost" || e === "127.0.0.1" || e === "[::1]" || e.endsWith(".localhost");
91
+ }
92
+ function ue(e) {
93
+ let t = (e || te).trim().replace(/\/+$/, "");
94
+ try {
95
+ let e = new URL(t);
96
+ if (e.protocol !== "https:" && e.protocol !== "http:") throw Error("unsupported protocol");
97
+ if (e.protocol === "http:" && !le(e.hostname)) throw Error("insecure protocol");
98
+ } catch {
99
+ throw new M("invalid_base_url", "Invalid API base URL", 400);
100
+ }
101
+ return t;
102
+ }
103
+ function k(e) {
104
+ let t = String(e).trim();
105
+ if (!t || o(t)) throw new M("invalid_id", "Invalid identifier", 400);
106
+ return encodeURIComponent(t);
107
+ }
108
+ function A(e) {
109
+ if (typeof e != "string" || o(e)) throw new M("invalid_email", "A valid email address is required", 400);
110
+ let n = e.trim();
111
+ if (!t(n, w)) throw new M("invalid_email", "A valid email address is required", 400);
112
+ return n;
113
+ }
114
+ function de(e) {
115
+ if (o(e)) throw new M("invalid_otp", "A valid OTP code is required", 400);
116
+ let t = e.trim();
117
+ if (t.length !== T || /\s/.test(t)) throw new M("invalid_otp", "A valid OTP code is required", 400);
118
+ return t;
119
+ }
120
+ function fe(e) {
121
+ if (o(e)) throw new M("invalid_token", "A valid invite token is required", 400);
122
+ let t = e.trim();
123
+ if (t.length !== 64 || !/^[\w-]+$/.test(t)) throw new M("invalid_token", "A valid invite token is required", 400);
124
+ return t;
125
+ }
126
+ function j(e, t, n = ae) {
127
+ let r = e.trim();
128
+ if (!r) throw new M("invalid_content", `${t} cannot be empty`, 400);
129
+ if (r.length > n) throw new M("content_too_long", `${t} exceeds maximum length of ${n} characters`, 400);
130
+ return r;
131
+ }
132
+ function pe(e) {
133
+ if (!s(e)) return;
134
+ let t = {};
135
+ for (let [n, r] of Object.entries(e).slice(0, 20)) /^[\w.-]{1,64}$/.test(n) && (n === "__proto__" || n === "constructor" || n === "prototype" || (typeof r == "string" ? t[n] = r.slice(0, 200) : typeof r == "number" || typeof r == "boolean" || r === null ? t[n] = r : Array.isArray(r) && (t[n] = r.filter((e) => typeof e == "string" || typeof e == "number" || typeof e == "boolean" || e === null).slice(0, 10).map((e) => typeof e == "string" ? e.slice(0, 200) : e))));
136
+ return Object.keys(t).length > 0 ? t : void 0;
137
+ }
138
+ var me = class {
139
+ constructor(e) {
140
+ this.projectId = null, this.userEmail = null, this.authToken = null, this.environment = null, this.onAuthExpired = null, this.baseUrl = ue(e.baseUrl), this.apiKey = e.apiKey, this.projectId = e.projectId || null, this.environment = e.environment || null;
141
+ }
142
+ setProject(e) {
143
+ this.projectId = String(e).trim();
144
+ }
145
+ setUserEmail(e) {
146
+ this.userEmail = e ? A(e) : null;
147
+ }
148
+ setAuthToken(e) {
149
+ if (e && (o(e) || e.length > oe)) throw new M("invalid_token", "A valid auth token is required", 400);
150
+ let t = e?.trim() || null;
151
+ this.authToken = t;
152
+ }
153
+ setEnvironment(e) {
154
+ this.environment = e;
155
+ }
156
+ setOnAuthExpired(e) {
157
+ this.onAuthExpired = e;
158
+ }
159
+ buildHeaders(e) {
160
+ if (typeof this.apiKey != "string" || o(this.apiKey)) throw new M("invalid_api_key", "Authentication failed. Please check your API key.", 401);
161
+ return {
162
+ "X-API-Key": this.apiKey,
163
+ ...this.userEmail ? { "X-User-Email": this.userEmail } : {},
164
+ ...this.authToken ? { Authorization: `Bearer ${this.authToken}` } : {},
165
+ ...e
166
+ };
167
+ }
168
+ async executeRequest(e, t, n, r) {
169
+ let i = new AbortController(), a = setTimeout(() => i.abort(), ne);
170
+ try {
171
+ let a = await fetch(e, {
172
+ ...t,
173
+ signal: i.signal
174
+ }), o = await this.parseResponseBody(a);
175
+ if (!a.ok) {
176
+ a.status === 401 && this.authToken && (this.authToken = null, this.onAuthExpired?.());
177
+ let e = s(o) ? o : {}, t = typeof e.error == "string" ? e.error : n;
178
+ throw new M(t, ce[t] ?? r, a.status, pe(e.details));
179
+ }
180
+ return o;
181
+ } catch (e) {
182
+ if (e instanceof M) throw e;
183
+ if (e instanceof DOMException && e.name === "AbortError") throw new M("timeout", "Request timed out. Please try again.", 408);
184
+ if (e instanceof TypeError) throw new M("network_error", "Unable to connect to servers. Please check your connection.", 0);
185
+ let t = new M("unknown_error", "An unexpected error occurred", 500);
186
+ throw t.cause = e, t;
187
+ } finally {
188
+ clearTimeout(a);
189
+ }
190
+ }
191
+ async parseResponseBody(e) {
192
+ if (e.status === 204 || e.status === 205) return {};
193
+ let t = e.headers?.get?.("content-type") ?? "";
194
+ if (typeof e.text == "function") {
195
+ let n = await e.text();
196
+ if (!n) return {};
197
+ if (t && !t.toLowerCase().includes("application/json")) {
198
+ if (e.ok) throw new M("invalid_response", "Invalid server response", 502);
199
+ return {};
200
+ }
201
+ try {
202
+ return JSON.parse(n);
203
+ } catch {
204
+ if (e.ok) throw new M("invalid_response", "Invalid server response", 502);
205
+ return {};
206
+ }
207
+ }
208
+ if (typeof e.json == "function") try {
209
+ return await e.json();
210
+ } catch {
211
+ if (e.ok) throw new M("invalid_response", "Invalid server response", 502);
212
+ }
213
+ return {};
214
+ }
215
+ async request(e, t = {}) {
216
+ let n = `${this.baseUrl}${e}`, r = this.buildHeaders({
217
+ "Content-Type": "application/json",
218
+ ...t.headers
219
+ });
220
+ return this.executeRequest(n, {
221
+ ...t,
222
+ headers: r
223
+ }, "request_failed", "An error occurred");
224
+ }
225
+ async requestFormData(e, t) {
226
+ let n = `${this.baseUrl}${e}`, r = this.buildHeaders();
227
+ return this.executeRequest(n, {
228
+ method: "POST",
229
+ headers: r,
230
+ body: t
231
+ }, "upload_failed", "Upload failed");
232
+ }
233
+ requireProjectId() {
234
+ if (!this.projectId) throw new M("missing_project_id", "Project ID is required", 400);
235
+ return this.projectId;
236
+ }
237
+ async validateApiKey() {
238
+ return this.request("/auth/validate-key", {
239
+ method: "POST",
240
+ body: JSON.stringify({})
241
+ });
242
+ }
243
+ async requestOtp(e) {
244
+ let t = A(e);
245
+ return this.request("/auth/otp/request", {
246
+ method: "POST",
247
+ body: JSON.stringify({ email: t })
248
+ });
249
+ }
250
+ async verifyOtp(e, t) {
251
+ let n = A(e), r = de(t);
252
+ return this.request("/auth/otp/verify", {
253
+ method: "POST",
254
+ body: JSON.stringify({
255
+ email: n,
256
+ otp: r
257
+ })
258
+ });
259
+ }
260
+ async validateInvite(e, t) {
261
+ let n = fe(e), r = A(t);
262
+ return this.request("/auth/validate-invite", {
263
+ method: "POST",
264
+ body: JSON.stringify({
265
+ token: n,
266
+ email: r
267
+ })
268
+ });
269
+ }
270
+ async getComments(e, t = "all", n = 1, r = 50, i) {
271
+ let a = this.requireProjectId(), o = new URLSearchParams();
272
+ e && o.append("page_path", e), t !== "all" && o.append("status", t), i && o.append("environment", i);
273
+ let s = Number.isFinite(n) ? Math.max(1, Math.floor(n)) : 1, c = Number.isFinite(r) ? Math.min(100, Math.max(1, Math.floor(r))) : 50;
274
+ o.append("page", String(s)), o.append("limit", String(c));
275
+ let l = o.toString(), u = `/projects/${k(a)}/comments${l ? `?${l}` : ""}`, d = await this.request(u), f = d.comments ?? [];
276
+ return {
277
+ comments: f,
278
+ pagination: d.pagination ?? {
279
+ total: f.length,
280
+ hasMore: f.length >= c,
281
+ page: s,
282
+ limit: c
283
+ }
284
+ };
285
+ }
286
+ idempotencyHeaders(e) {
287
+ return typeof e == "string" && e.length > 0 && e.length <= 256 && !o(e) ? { "Idempotency-Key": e } : {};
288
+ }
289
+ async createComment(e, t, n, r, i = "medium", a, o, s, c) {
290
+ let l = j(t, "Comment content"), u = this.requireProjectId(), d = s?.mentions ?? he(l);
291
+ return (await this.request(`/projects/${k(u)}/comments`, {
292
+ method: "POST",
293
+ headers: this.idempotencyHeaders(c),
294
+ body: JSON.stringify({
295
+ type: e,
296
+ position: n,
297
+ page_url: r.url,
298
+ page_path: r.path,
299
+ page_title: r.title,
300
+ environment: this.environment || void 0,
301
+ ...O({
302
+ content: l,
303
+ priority: i,
304
+ description: s?.description,
305
+ assignees: s?.assignees,
306
+ checklist: s?.checklist,
307
+ textSelection: a,
308
+ drawingData: o,
309
+ attachmentIds: s?.attachmentIds
310
+ }, d)
311
+ })
312
+ })).comment;
313
+ }
314
+ async updateComment(e, t) {
315
+ let n = this.requireProjectId(), r = t.content === void 0 ? void 0 : j(t.content, "Comment content"), i = r ? he(r) : void 0, a = O({
316
+ ...t,
317
+ ...r === void 0 ? {} : { content: r }
318
+ }, i);
319
+ return (await this.request(`/projects/${k(n)}/comments/${k(e)}`, {
320
+ method: "PUT",
321
+ body: JSON.stringify(a)
322
+ })).comment;
323
+ }
324
+ async deleteComment(e) {
325
+ let t = this.requireProjectId();
326
+ await this.request(`/projects/${k(t)}/comments/${k(e)}`, { method: "DELETE" });
327
+ }
328
+ async addReply(e, t, n) {
329
+ let r = this.requireProjectId(), i = j(t, "Reply content", C), a = he(i);
330
+ return (await this.request(`/projects/${k(r)}/comments/${k(e)}/replies`, {
331
+ method: "POST",
332
+ headers: this.idempotencyHeaders(n),
333
+ body: JSON.stringify({
334
+ content: i,
335
+ ...a.length > 0 ? { mentions: a } : {}
336
+ })
337
+ })).reply;
338
+ }
339
+ async updateReply(e, t, n) {
340
+ let r = this.requireProjectId(), i = j(n, "Reply content", C);
341
+ return (await this.request(`/projects/${k(r)}/comments/${k(e)}/replies/${k(t)}`, {
342
+ method: "PUT",
343
+ body: JSON.stringify({ content: i })
344
+ })).reply;
345
+ }
346
+ async deleteReply(e, t) {
347
+ let n = this.requireProjectId();
348
+ await this.request(`/projects/${k(n)}/comments/${k(e)}/replies/${k(t)}`, { method: "DELETE" });
349
+ }
350
+ async resolveComment(e) {
351
+ let t = this.requireProjectId();
352
+ return (await this.request(`/projects/${k(t)}/comments/${k(e)}/resolve`, { method: "POST" })).comment;
353
+ }
354
+ async unresolveComment(e) {
355
+ let t = this.requireProjectId();
356
+ return (await this.request(`/projects/${k(t)}/comments/${k(e)}/unresolve`, { method: "POST" })).comment;
357
+ }
358
+ async markComplete(e) {
359
+ let t = this.requireProjectId();
360
+ return (await this.request(`/projects/${k(t)}/comments/${k(e)}/complete`, { method: "POST" })).comment;
361
+ }
362
+ async addReaction(e, t) {
363
+ let n = this.requireProjectId();
364
+ await this.request(`/projects/${k(n)}/comments/${k(e)}/reactions`, {
365
+ method: "POST",
366
+ body: JSON.stringify({ emoji: t })
367
+ });
368
+ }
369
+ async removeReaction(e, t) {
370
+ let n = this.requireProjectId();
371
+ await this.request(`/projects/${k(n)}/comments/${k(e)}/reactions`, {
372
+ method: "DELETE",
373
+ body: JSON.stringify({ emoji: t })
374
+ });
375
+ }
376
+ async updatePosition(e, t) {
377
+ let n = this.requireProjectId();
378
+ return (await this.request(`/projects/${k(n)}/comments/${k(e)}/position`, {
379
+ method: "PUT",
380
+ body: JSON.stringify({ position: t })
381
+ })).comment;
382
+ }
383
+ async createHighlight(e, t, n, r = "medium", i) {
384
+ return this.createComment("highlight", e, {
385
+ x: 0,
386
+ y: 0
387
+ }, n, r, t, void 0, void 0, i);
388
+ }
389
+ async createDrawing(e, t, n, r, i) {
390
+ return this.createComment("drawing", e, n, r, "medium", void 0, t, void 0, i);
391
+ }
392
+ validateFile(e, t = !1) {
393
+ if (e.size > re) throw new M("file_too_large", `File size (${Math.round(e.size / 1024 / 1024)}MB) exceeds maximum of ${re / 1024 / 1024}MB`, 400);
394
+ if (o(e.name) || e.name.includes("/") || e.name.includes("\\")) throw new M("invalid_filename", "Filename contains invalid characters", 400);
395
+ if (t) {
396
+ /* v8 ignore next -- pop() always returns a value since file has a name */
397
+ let t = "." + (e.name.split(".").pop()?.toLowerCase() ?? "");
398
+ if ((e.name.match(/\./g) || []).length > 1) throw new M("invalid_filename", "Filenames with multiple extensions are not allowed", 400);
399
+ if (!D.includes(e.type) || !E.includes(t)) throw new M("invalid_file_type", `Only image files are allowed (${E.join(", ")})`, 400);
400
+ }
401
+ if (i(e.name)) throw new M("invalid_file_type", "This file type is not allowed", 400);
402
+ }
403
+ async uploadFile(e, t, n) {
404
+ this.validateFile(e, t === "screenshot" || t === "drawing");
405
+ let r = this.requireProjectId(), i = new FormData();
406
+ i.append("file", e), i.append("type", t === "attachment" ? "file" : t), n?.commentId && i.append("comment_id", n.commentId), n?.replyId && i.append("reply_id", n.replyId);
407
+ let a = await this.requestFormData(`/projects/${k(r)}/files`, i);
408
+ return {
409
+ id: String(a.attachment.id),
410
+ type: a.attachment.type,
411
+ url: a.attachment.url,
412
+ thumbnail: a.attachment.thumbnail,
413
+ filename: a.attachment.filename,
414
+ size: a.attachment.size
415
+ };
416
+ }
417
+ async uploadScreenshot(e, t) {
418
+ this.validateFile(e, !0);
419
+ let n = j(t.content, "Screenshot comment"), r = this.requireProjectId(), i = new FormData();
420
+ return i.append("file", e), i.append("content", n), i.append("position_x", String(t.position.x)), i.append("position_y", String(t.position.y)), i.append("page_url", t.page.url), i.append("page_path", t.page.path), i.append("page_title", t.page.title), (await this.requestFormData(`/projects/${k(r)}/screenshots`, i)).comment;
421
+ }
422
+ async uploadFiles(e, t) {
423
+ if (e.length > ie) throw new M("too_many_files", `Cannot upload more than ${ie} files at once`, 400);
424
+ let n = await Promise.allSettled(e.map((e) => {
425
+ /* v8 ignore next -- pop() always returns a value since file has a name */
426
+ let n = "." + (e.name.split(".").pop()?.toLowerCase() ?? ""), r = D.includes(e.type) && E.includes(n);
427
+ return this.uploadFile(e, r ? "screenshot" : "attachment", t);
428
+ })), r = n.filter((e) => e.status === "fulfilled").map((e) => e.value.id), i = n.find((e) => e.status === "rejected");
429
+ if (i) {
430
+ let e = i.reason;
431
+ throw e instanceof M ? new M(e.error, e.message, e.code, {
432
+ ...e.details,
433
+ uploadedIds: r
434
+ }) : new M("upload_failed", "Upload failed", 0, { uploadedIds: r });
435
+ }
436
+ return r;
437
+ }
438
+ async getProjectMembers() {
439
+ let e = this.requireProjectId();
440
+ return (await this.request(`/projects/${k(e)}/members`)).members ?? [];
441
+ }
442
+ };
443
+ function he(e) {
444
+ let t = [], n;
445
+ for (se.lastIndex = 0; (n = se.exec(e)) !== null;) {
446
+ let e = n[1]?.trim(), r = n[2]?.trim();
447
+ !e || !r || !/^[\w-]+$/.test(r) || t.push({
448
+ name: e,
449
+ userId: r,
450
+ index: n.index
451
+ });
452
+ }
453
+ return t;
454
+ }
455
+ var M = class extends Error {
456
+ constructor(e, t, n, r) {
457
+ super(t), this.name = "ApiClientError", this.error = e, this.code = n, this.details = r;
458
+ }
459
+ isAuthError() {
460
+ return this.code === 401 || this.error === "invalid_api_key";
461
+ }
462
+ isNetworkError() {
463
+ return this.code === 0 || this.error === "network_error";
464
+ }
465
+ isRateLimitError() {
466
+ return this.code === 429;
467
+ }
468
+ isPremiumFeatureError() {
469
+ return this.code === 402;
470
+ }
471
+ };
472
+ function ge(e, t) {
473
+ return (e ?? "").replace(/\s+/g, " ").trim().slice(0, t);
474
+ }
475
+ function N(e, t) {
476
+ return (e ?? "").replace(/\s+/g, " ").replace(/`/g, "'").trim().slice(0, t);
477
+ }
478
+ var _e = null, ve = 0, ye = 3;
479
+ function be() {
480
+ return _e || (_e = (async () => {
481
+ try {
482
+ let e = await import("element-source");
483
+ return typeof e?.resolveElementInfo == "function" ? e : null;
484
+ } catch {
485
+ return ve += 1, ve < ye && (_e = null), null;
486
+ }
487
+ })(), _e);
488
+ }
489
+ async function xe(e) {
490
+ let t = await be();
491
+ if (!t) return null;
492
+ try {
493
+ return await t.resolveElementInfo(e);
494
+ } catch {
495
+ return null;
496
+ }
497
+ }
498
+ var Se = 200, Ce = 500, we = 500, Te = 2e3, Ee = "application/x-commentkit-agent-context", De = "Use this CommentKit context to understand unresolved UI feedback. Each comment includes page, selector/XPath, viewport position, resolved DOM metadata when available, and thread replies.";
499
+ function Oe(e) {
500
+ return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
501
+ }
502
+ function ke(e) {
503
+ return e === void 0 ? Se : !Number.isFinite(e) || e <= 0 ? 0 : Math.min(Ce, Math.floor(e));
504
+ }
505
+ function Ae(e) {
506
+ return {
507
+ id: e.id,
508
+ name: e.name,
509
+ email: e.email
510
+ };
511
+ }
512
+ function je(e, t) {
513
+ return e.page.path === t.path || e.page.url === t.url;
514
+ }
515
+ function Me(e, t, n, r) {
516
+ return !(!n.includeResolved && e.status !== "open" || n.currentPageOnly && !je(e, t) || r && !r.has(e.id));
517
+ }
518
+ function Ne(e) {
519
+ let t = e.getBoundingClientRect();
520
+ return {
521
+ top: t.top,
522
+ left: t.left,
523
+ width: t.width,
524
+ height: t.height
525
+ };
526
+ }
527
+ function Pe(e, t) {
528
+ let n = p(e.element ?? "", e.xpath), r = {
529
+ ...e.element ? { selector: e.element } : {},
530
+ ...e.xpath ? { xpath: e.xpath } : {}
531
+ };
532
+ if (!n) return {
533
+ ...r,
534
+ found: !1
535
+ };
536
+ let i = ge(n.textContent, we), a = t ? ge(n.outerHTML, Te) : "", o = n.getAttribute("class"), s = n.getAttribute("role"), c = n.getAttribute("aria-label");
537
+ return {
538
+ ...r,
539
+ found: !0,
540
+ tagName: n.tagName.toLowerCase(),
541
+ ...n.id ? { id: n.id } : {},
542
+ ...o ? { className: o } : {},
543
+ ...s ? { role: s } : {},
544
+ ...c ? { ariaLabel: c } : {},
545
+ ...i ? { text: i } : {},
546
+ rect: Ne(n),
547
+ ...a ? { htmlPreview: a } : {}
548
+ };
549
+ }
550
+ function Fe(e) {
551
+ return {
552
+ id: e.id,
553
+ content: e.content,
554
+ author: Ae(e.author),
555
+ createdAt: e.createdAt
556
+ };
557
+ }
558
+ function Ie(e) {
559
+ return e.attachments?.find((e) => e.url && e.type === "screenshot")?.url;
560
+ }
561
+ function Le(e, t) {
562
+ let n = Ie(e);
563
+ return {
564
+ id: e.id,
565
+ type: e.type,
566
+ status: e.status,
567
+ priority: e.priority,
568
+ content: e.content,
569
+ author: Ae(e.author),
570
+ createdAt: e.createdAt,
571
+ updatedAt: e.updatedAt,
572
+ page: e.page,
573
+ position: e.position,
574
+ element: Pe(e.position, t.includeHtml === !0),
575
+ ...n ? { screenshotUrl: n } : {},
576
+ replies: e.replies.map(Fe)
577
+ };
578
+ }
579
+ function Re(e) {
580
+ return {
581
+ filePath: e.filePath,
582
+ lineNumber: e.lineNumber,
583
+ columnNumber: e.columnNumber,
584
+ componentName: e.componentName
585
+ };
586
+ }
587
+ function ze(e, t = {}) {
588
+ let n = u(), r = {
589
+ url: n.url,
590
+ path: n.path,
591
+ title: n.title
592
+ }, i = t.commentIds?.length ? new Set(t.commentIds) : null, a = ke(t.maxComments), o = e.comments.filter((e) => Me(e, r, t, i)).slice(0, a).map((e) => Le(e, t));
593
+ return {
594
+ version: 1,
595
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
596
+ instructions: N(t.instructions, 2e3) || De,
597
+ page: r,
598
+ comments: o,
599
+ sourceResolved: !1
600
+ };
601
+ }
602
+ async function Be(e) {
603
+ let t = !1, n = await Promise.all(e.comments.map(async (e) => {
604
+ if (!e.element.found) return e;
605
+ let n = p(e.element.selector ?? "", e.element.xpath);
606
+ if (!n) return e;
607
+ let r = await xe(n);
608
+ if (!r || !r.source) return e;
609
+ t = !0;
610
+ let i = Re(r.source), a = r.stack.map(Re), o = r.componentName ?? void 0;
611
+ return {
612
+ ...e,
613
+ element: {
614
+ ...e.element,
615
+ source: i,
616
+ stack: a,
617
+ ...o ? { componentName: o } : {}
618
+ }
619
+ };
620
+ }));
621
+ return {
622
+ ...e,
623
+ comments: n,
624
+ sourceResolved: t
625
+ };
626
+ }
627
+ function Ve(e) {
628
+ let t = `${e.filePath}${e.lineNumber === null ? "" : `:${e.lineNumber}`}${e.columnNumber === null ? "" : `:${e.columnNumber}`}`;
629
+ return e.componentName ? `${e.componentName} (${t})` : t;
630
+ }
631
+ function He(e) {
632
+ return [
633
+ "# CommentKit Agent Context",
634
+ "",
635
+ e.instructions,
636
+ "",
637
+ `Current page: ${N(e.page.title, 300) || "Untitled"} (${e.page.url || e.page.path || "unknown"})`,
638
+ `Comments: ${e.comments.length}${e.sourceResolved ? " (source-resolved)" : ""}`,
639
+ "",
640
+ ...e.comments.map((e, t) => {
641
+ let n = e.element.found ? `${e.element.tagName}${e.element.id ? `#${e.element.id}` : ""}` : "not found", r = [
642
+ `## ${t + 1}. ${N(e.content, 300)}`,
643
+ `- Status: ${e.status}`,
644
+ `- Priority: ${e.priority}`,
645
+ `- Author: ${e.author.name} <${e.author.email}>`,
646
+ `- Page: ${e.page.url}`,
647
+ `- Element: ${n}`
648
+ ];
649
+ return e.element.source && r.push(`- Source: ${Ve(e.element.source)}`), e.element.stack && e.element.stack.length > 0 && r.push("- Stack:", ...e.element.stack.map((e) => ` - ${Ve(e)}`)), e.element.source || r.push(`- Selector: ${e.element.selector ?? "none"}`, `- XPath: ${e.element.xpath ?? "none"}`), e.screenshotUrl && r.push(`- Screenshot: ${e.screenshotUrl}`), r.push(e.replies.length > 0 ? `- Replies: ${e.replies.length}` : "- Replies: 0", ""), r.join("\n");
650
+ }),
651
+ "```json",
652
+ JSON.stringify(e, null, 2),
653
+ "```"
654
+ ].join("\n");
655
+ }
656
+ function Ue(e) {
657
+ return {
658
+ version: e?.version ?? 1,
659
+ generatedAt: e?.generatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
660
+ commentCount: e?.comments.length ?? 0,
661
+ context: e
662
+ };
663
+ }
664
+ function We(e, t) {
665
+ if (typeof document > "u" || !document.body || typeof document.execCommand != "function") return !1;
666
+ let n = JSON.stringify(t), r = (t) => {
667
+ t.preventDefault(), t.clipboardData?.setData("text/plain", e), t.clipboardData?.setData("text/html", `<meta charset="utf-8"><pre><code>${Oe(e)}</code></pre>`), t.clipboardData?.setData(Ee, n);
668
+ }, i = document.createElement("textarea");
669
+ i.value = e, i.setAttribute("readonly", ""), i.setAttribute("aria-hidden", "true"), i.style.position = "fixed", i.style.left = "-9999px", document.addEventListener("copy", r), document.body.appendChild(i), i.select();
670
+ try {
671
+ return document.execCommand("copy");
672
+ } finally {
673
+ document.removeEventListener("copy", r), i.remove();
674
+ }
675
+ }
676
+ async function Ge(e, t) {
677
+ if (typeof navigator > "u" || typeof navigator.clipboard?.write != "function" || typeof ClipboardItem > "u") return !1;
678
+ try {
679
+ let n = new Blob([`<meta charset="utf-8"><pre><code>${Oe(e)}</code></pre>`], { type: "text/html" }), r = new Blob([e], { type: "text/plain" }), i = t.type && t.type.startsWith("image/") ? t.type : "image/png";
680
+ return await navigator.clipboard.write([new ClipboardItem({
681
+ "text/plain": r,
682
+ "text/html": n,
683
+ [i]: t
684
+ })]), !0;
685
+ } catch {
686
+ return !1;
687
+ }
688
+ }
689
+ async function Ke(e, t) {
690
+ return t && await Ge(e, t) ? !0 : (await qe(e), !1);
691
+ }
692
+ async function qe(e, t = null) {
693
+ if (!We(e, Ue(t))) {
694
+ if (typeof navigator < "u" && typeof navigator.clipboard?.writeText == "function") {
695
+ await navigator.clipboard.writeText(e);
696
+ return;
697
+ }
698
+ throw Error("Clipboard is unavailable");
699
+ }
700
+ }
701
+ var Je = "commentkit:session:", Ye = 4096;
702
+ function Xe() {
703
+ try {
704
+ return typeof sessionStorage > "u" ? null : sessionStorage;
705
+ } catch {
706
+ return null;
707
+ }
708
+ }
709
+ function P(e) {
710
+ return `${Je}${e}`;
711
+ }
712
+ function Ze(e) {
713
+ return s(e) && l(e.id, c.ID) && l(e.name, c.NAME) && typeof e.email == "string" && t(e.email, c.EMAIL);
714
+ }
715
+ function Qe(e) {
716
+ return s(e) && l(e.token, Ye) && typeof e.email == "string" && t(e.email, c.EMAIL) && Ze(e.user);
717
+ }
718
+ function $e(e, t) {
719
+ if (!e) return;
720
+ let n = Xe();
721
+ if (n) try {
722
+ n.setItem(P(e), JSON.stringify(t));
723
+ } catch {}
724
+ }
725
+ function et(e) {
726
+ if (!e) return null;
727
+ let t = Xe();
728
+ if (!t) return null;
729
+ try {
730
+ let n = t.getItem(P(e));
731
+ if (!n) return null;
732
+ let r = JSON.parse(n);
733
+ return Qe(r) ? {
734
+ token: r.token.trim(),
735
+ email: r.email.trim(),
736
+ user: {
737
+ id: r.user.id.trim(),
738
+ name: r.user.name.trim(),
739
+ email: r.user.email.trim(),
740
+ ...r.user.avatar ? { avatar: r.user.avatar } : {}
741
+ }
742
+ } : (t.removeItem(P(e)), null);
743
+ } catch {
744
+ return null;
745
+ }
746
+ }
747
+ function tt(e) {
748
+ if (!e) return;
749
+ let t = Xe();
750
+ if (t) try {
751
+ t.removeItem(P(e));
752
+ } catch {}
753
+ }
754
+ function nt(e, t) {
755
+ for (let n of e.getState().pendingMutations) e.emit("offline:failed", {
756
+ id: n.id,
757
+ error: {
758
+ error: "auth_cleared",
759
+ message: t,
760
+ code: 401
761
+ }
762
+ });
763
+ }
764
+ var rt = c.EMAIL, it = c.NAME, at = c.ID, ot = 4096, st = 6;
765
+ function ct(e) {
766
+ if (typeof e != "string") return null;
767
+ let n = e.trim();
768
+ return t(n, rt) ? n : null;
769
+ }
770
+ function lt(e) {
771
+ return o(e) ? !1 : e.trim().length === st;
772
+ }
773
+ function ut(e) {
774
+ return s(e) && l(e.id, at) && l(e.name, it) && typeof e.email == "string" && ct(e.email) !== null;
775
+ }
776
+ function dt(e) {
777
+ return s(e) && l(e.id, at);
778
+ }
779
+ function F(e, t, n) {
780
+ return {
781
+ error: e,
782
+ message: t,
783
+ code: n
784
+ };
785
+ }
786
+ async function ft(e, t) {
787
+ let n = ct(t);
788
+ if (!n) {
789
+ e.setState({
790
+ isLoading: !1,
791
+ otpStep: "idle",
792
+ otpEmail: null
793
+ }), e.handleError(F("invalid_email", "A valid email address is required", 400));
794
+ return;
795
+ }
796
+ try {
797
+ e.setState({
798
+ isLoading: !0,
799
+ error: null,
800
+ otpStep: "requesting",
801
+ otpEmail: n
802
+ });
803
+ let t = await e.apiClient.requestOtp(n);
804
+ t.success ? (e.setState({
805
+ otpStep: "verifying",
806
+ isLoading: !1
807
+ }), e.emit("auth:otp-requested", {
808
+ email: n,
809
+ expiresIn: t.expiresIn
810
+ })) : (e.setState({
811
+ isLoading: !1,
812
+ otpStep: "idle",
813
+ otpEmail: null
814
+ }), e.handleError(F("otp_failed", "Failed to send OTP. Please try again.", 500)));
815
+ } catch (t) {
816
+ e.setState({
817
+ isLoading: !1,
818
+ otpStep: "idle",
819
+ otpEmail: null
820
+ }), e.handleError(t);
821
+ }
822
+ }
823
+ async function pt(e, t, n) {
824
+ let { onAuthenticated: r, onWrongOtp: i, onSuccess: a } = typeof n == "function" ? { onAuthenticated: n } : n, o = e.getState().otpEmail;
825
+ if (!o) {
826
+ e.handleError(F("no_email", "No OTP request in progress", 400));
827
+ return;
828
+ }
829
+ if (!lt(t)) {
830
+ e.setState({ isLoading: !1 }), e.handleError(F("invalid_otp", "Invalid or expired OTP code", 401));
831
+ return;
832
+ }
833
+ try {
834
+ e.setState({
835
+ isLoading: !0,
836
+ error: null
837
+ });
838
+ let n = await e.apiClient.verifyOtp(o, t);
839
+ n.verified && l(n.token, ot) && ut(n.user) && dt(n.project) ? (e.apiClient.setAuthToken(n.token), e.apiClient.setUserEmail(n.user.email), $e(e.config.projectId, {
840
+ token: n.token,
841
+ email: n.user.email,
842
+ user: n.user
843
+ }), e.setState({
844
+ currentUser: n.user,
845
+ project: n.project,
846
+ isAuthenticated: !0,
847
+ isLoginModalVisible: !1,
848
+ isLoading: !1,
849
+ otpStep: "idle",
850
+ otpEmail: null
851
+ }), a?.(), e.emit("auth:otp-verified", n.user), e.emit("auth:login", n.user), await r()) : (e.setState({ isLoading: !1 }), i?.(), e.handleError(F("invalid_otp", "Invalid or expired OTP code", 401)));
852
+ } catch (t) {
853
+ e.setState({ isLoading: !1 }), e.handleError(t);
854
+ }
855
+ }
856
+ function mt(e) {
857
+ e.setState({
858
+ otpStep: "idle",
859
+ otpEmail: null,
860
+ error: null,
861
+ isLoading: !1
862
+ });
863
+ }
864
+ async function ht(e) {
865
+ let t = e.getState().otpEmail;
866
+ t && await ft(e, t);
867
+ }
868
+ function gt(e, t) {
869
+ nt(e, "Pending offline changes were discarded on logout"), tt(e.config.projectId), e.apiClient.setUserEmail(null), e.apiClient.setAuthToken(null), t(), e.setState({
870
+ isAuthenticated: !1,
871
+ currentUser: null,
872
+ comments: [],
873
+ activeTool: null,
874
+ selectedComment: null,
875
+ activeComment: null,
876
+ activeDrawing: null,
877
+ activeScreenshot: null,
878
+ onlineUsers: [],
879
+ isOverlayVisible: !1,
880
+ isCommentModeActive: !1,
881
+ isDrawingModeActive: !1,
882
+ isHighlightModeActive: !1,
883
+ isScreenshotModeActive: !1,
884
+ isSidebarVisible: !1,
885
+ otpStep: "idle",
886
+ otpEmail: null,
887
+ pagination: null,
888
+ pendingMutations: [],
889
+ activities: [],
890
+ seenThreadIds: /* @__PURE__ */ new Set(),
891
+ panelView: "list",
892
+ connectionStatus: "disconnected",
893
+ error: null,
894
+ isLoading: !1
895
+ }), e.emit("auth:logout", void 0);
896
+ }
897
+ function _t(e) {
898
+ nt(e, "Pending offline changes were discarded because the session expired"), tt(e.config.projectId), e.apiClient.setUserEmail(null), e.apiClient.setAuthToken(null), e.setState({
899
+ isAuthenticated: !1,
900
+ currentUser: null,
901
+ comments: [],
902
+ selectedComment: null,
903
+ activeComment: null,
904
+ activeDrawing: null,
905
+ activeScreenshot: null,
906
+ onlineUsers: [],
907
+ pendingMutations: [],
908
+ activities: [],
909
+ seenThreadIds: /* @__PURE__ */ new Set(),
910
+ panelView: "list",
911
+ connectionStatus: "disconnected",
912
+ isLoginModalVisible: !0,
913
+ error: "Your session has expired. Please sign in again.",
914
+ isLoading: !1
915
+ }), e.emit("error", {
916
+ error: "auth_expired",
917
+ message: "Session expired",
918
+ code: 401
919
+ });
920
+ }
921
+ function vt(e) {
922
+ e.setState({ isLoginModalVisible: !e.getState().isLoginModalVisible });
923
+ }
924
+ async function yt(e, t, n) {
925
+ let r = e.config.inviteToken;
926
+ if (!r) {
927
+ e.handleError(F("no_invite", "No invite token found", 400));
928
+ return;
929
+ }
930
+ let i = ct(t);
931
+ if (!i) {
932
+ e.setState({ isLoading: !1 }), e.handleError(F("invalid_email", "A valid email address is required", 400));
933
+ return;
934
+ }
935
+ try {
936
+ e.setState({
937
+ isLoading: !0,
938
+ error: null
939
+ }), (await e.apiClient.validateInvite(r, i)).success ? await n(i) : (e.setState({ isLoading: !1 }), e.handleError(F("invite_invalid", "Invite validation failed", 400)));
940
+ } catch (t) {
941
+ e.setState({ isLoading: !1 }), e.handleError(t);
942
+ }
943
+ }
944
+ var I = c.ID, bt = c.CONTENT, xt = c.REPLY_CONTENT, St = c.SELECTOR, Ct = c.TEXT_SELECTION, wt = c.DESCRIPTION, Tt = c.ASSIGNEES, Et = c.CHECKLIST_ITEMS, Dt = c.CHECKLIST_LABEL, Ot = c.DRAWING_PATHS, kt = c.DRAWING_PATH_DATA, At = c.DRAWING_TEXT, jt = c.REACTION_COUNT, Mt = c.EMOJI, Nt = new Set([
945
+ "pin",
946
+ "highlight",
947
+ "drawing"
948
+ ]), Pt = new Set([
949
+ "low",
950
+ "medium",
951
+ "high",
952
+ "urgent"
953
+ ]), Ft = new Set([
954
+ "open",
955
+ "resolved",
956
+ "complete"
957
+ ]), It = new Set([
958
+ "path",
959
+ "line",
960
+ "rectangle",
961
+ "circle",
962
+ "text"
963
+ ]);
964
+ function L(e, t, n) {
965
+ e.handleError(new M(t, n, 400));
966
+ }
967
+ function R(e) {
968
+ return l(e, I);
969
+ }
970
+ function z(e, t = bt) {
971
+ if (typeof e != "string") return null;
972
+ let r = e.trim();
973
+ return !r || r.length > t || n(r) ? null : r;
974
+ }
975
+ function B(e, t) {
976
+ if (e === void 0) return;
977
+ if (typeof e != "string") return null;
978
+ let r = e.trim();
979
+ return r.length > t || n(r) ? null : r;
980
+ }
981
+ function V(e) {
982
+ if (e === void 0) return;
983
+ if (typeof e != "string") return null;
984
+ let t = e.trim();
985
+ return !t || t.length > St || n(t) ? null : t;
986
+ }
987
+ function Lt(e) {
988
+ if (!s(e) || !a(e.x) || !a(e.y)) return null;
989
+ let t = V(e.element), n = V(e.xpath);
990
+ return t === null || n === null ? null : {
991
+ x: e.x,
992
+ y: e.y,
993
+ ...t === void 0 ? {} : { element: t },
994
+ ...n === void 0 ? {} : { xpath: n }
995
+ };
996
+ }
997
+ function Rt(e) {
998
+ if (!s(e)) return null;
999
+ let t = B(e.avatar, St), r = B(e.organizationId, I);
1000
+ return !R(e.id) || typeof e.name != "string" || !e.name.trim() || e.name.length > c.NAME || n(e.name) || typeof e.email != "string" || !e.email.trim() || e.email.length > c.EMAIL || /\s/.test(e.email.trim()) || n(e.email) || t === null || r === null ? null : {
1001
+ id: e.id.trim(),
1002
+ name: e.name.trim(),
1003
+ email: e.email.trim(),
1004
+ ...t === void 0 ? {} : { avatar: t },
1005
+ ...r === void 0 ? {} : { organizationId: r }
1006
+ };
1007
+ }
1008
+ function zt(e) {
1009
+ if (e === void 0) return;
1010
+ if (!Array.isArray(e) || e.length > Tt) return null;
1011
+ let t = [];
1012
+ for (let n of e) {
1013
+ let e = Rt(n);
1014
+ if (!e) return null;
1015
+ t.push(e);
1016
+ }
1017
+ return t;
1018
+ }
1019
+ function Bt(e) {
1020
+ if (e === void 0) return;
1021
+ if (!Array.isArray(e) || e.length > Et) return null;
1022
+ let t = [];
1023
+ for (let n of e) {
1024
+ if (!s(n)) return null;
1025
+ let e = z(n.label);
1026
+ if (!R(n.id) || !e || typeof n.done != "boolean" || n.sortOrder !== void 0 && (typeof n.sortOrder != "number" || !Number.isFinite(n.sortOrder)) || e.length > Dt) return null;
1027
+ t.push({
1028
+ id: n.id.trim(),
1029
+ label: e,
1030
+ done: n.done,
1031
+ ...n.sortOrder === void 0 ? {} : { sortOrder: n.sortOrder }
1032
+ });
1033
+ }
1034
+ return t;
1035
+ }
1036
+ function Vt(e) {
1037
+ if (e === void 0) return;
1038
+ if (!s(e) || typeof e.text != "string") return null;
1039
+ let t = e.text.trim(), r = V(e.element), i = V(e.xpath);
1040
+ return !t || t.length > Ct || n(t) || typeof e.startOffset != "number" || typeof e.endOffset != "number" || !Number.isInteger(e.startOffset) || !Number.isInteger(e.endOffset) || e.startOffset < 0 || e.endOffset < e.startOffset || r === null || i === null || r === void 0 || i === void 0 ? null : {
1041
+ text: t,
1042
+ startOffset: e.startOffset,
1043
+ endOffset: e.endOffset,
1044
+ element: r,
1045
+ xpath: i
1046
+ };
1047
+ }
1048
+ function Ht(e) {
1049
+ return typeof e == "string" && e.length > 0 && e.length <= c.COLOR && !n(e);
1050
+ }
1051
+ function H(e) {
1052
+ return e === void 0 || typeof e == "number" && Number.isFinite(e);
1053
+ }
1054
+ function Ut(e) {
1055
+ if (e === void 0) return;
1056
+ if (!s(e) || e.type !== "svg" || !Array.isArray(e.paths) || e.paths.length > Ot || !s(e.viewport) || typeof e.viewport.width != "number" || typeof e.viewport.height != "number" || !Number.isFinite(e.viewport.width) || !Number.isFinite(e.viewport.height) || e.viewport.width <= 0 || e.viewport.height <= 0) return null;
1057
+ let t = [];
1058
+ for (let r of e.paths) {
1059
+ if (!s(r) || !It.has(String(r.type))) return null;
1060
+ let e = B(r.text, At);
1061
+ if (!Ht(r.stroke) || !Ht(r.fill) || typeof r.strokeWidth != "number" || !Number.isFinite(r.strokeWidth) || r.strokeWidth < 0 || r.d !== void 0 && (typeof r.d != "string" || r.d.length > kt || n(r.d)) || !H(r.x) || !H(r.y) || !H(r.width) || !H(r.height) || e === null) return null;
1062
+ t.push({
1063
+ type: r.type,
1064
+ stroke: r.stroke,
1065
+ strokeWidth: r.strokeWidth,
1066
+ fill: r.fill,
1067
+ ...r.d === void 0 ? {} : { d: r.d },
1068
+ ...r.x === void 0 ? {} : { x: r.x },
1069
+ ...r.y === void 0 ? {} : { y: r.y },
1070
+ ...r.width === void 0 ? {} : { width: r.width },
1071
+ ...r.height === void 0 ? {} : { height: r.height },
1072
+ ...e === void 0 ? {} : { text: e }
1073
+ });
1074
+ }
1075
+ return {
1076
+ type: "svg",
1077
+ paths: t,
1078
+ viewport: {
1079
+ width: e.viewport.width,
1080
+ height: e.viewport.height
1081
+ }
1082
+ };
1083
+ }
1084
+ function Wt(e) {
1085
+ if (e === void 0) return;
1086
+ if (!s(e)) return null;
1087
+ let t = B(e.description, wt), n = zt(e.assignees), r = Bt(e.checklist);
1088
+ if (t === null || n === null || r === null) return null;
1089
+ let i = Array.isArray(e.files) ? e.files.filter((e) => typeof File < "u" && e instanceof File) : void 0, a = Array.isArray(e.attachmentIds) ? e.attachmentIds.map((e) => String(e).trim()).filter((e) => e.length > 0 && e.length <= I).slice(0, 20) : void 0;
1090
+ return {
1091
+ ...t === void 0 ? {} : { description: t },
1092
+ ...n === void 0 ? {} : { assignees: n },
1093
+ ...r === void 0 ? {} : { checklist: r },
1094
+ ...i && i.length > 0 ? { files: i } : {},
1095
+ ...a && a.length > 0 ? { attachmentIds: a } : {}
1096
+ };
1097
+ }
1098
+ function Gt(e) {
1099
+ if (!s(e)) return null;
1100
+ let t = {};
1101
+ if ("content" in e) {
1102
+ let n = z(e.content);
1103
+ if (!n) return null;
1104
+ t.content = n;
1105
+ }
1106
+ if ("status" in e) {
1107
+ if (!Ft.has(e.status)) return null;
1108
+ t.status = e.status;
1109
+ }
1110
+ if ("priority" in e) {
1111
+ if (!Pt.has(e.priority)) return null;
1112
+ t.priority = e.priority;
1113
+ }
1114
+ if ("description" in e) {
1115
+ let n = B(e.description, wt);
1116
+ if (n === null) return null;
1117
+ t.description = n;
1118
+ }
1119
+ if ("assignees" in e) {
1120
+ let n = zt(e.assignees);
1121
+ if (n === null) return null;
1122
+ t.assignees = n;
1123
+ }
1124
+ if ("checklist" in e) {
1125
+ let n = Bt(e.checklist);
1126
+ if (n === null) return null;
1127
+ t.checklist = n;
1128
+ }
1129
+ if ("textSelection" in e) {
1130
+ let n = Vt(e.textSelection);
1131
+ if (n === null) return null;
1132
+ t.textSelection = n;
1133
+ }
1134
+ if ("drawingData" in e) {
1135
+ let n = Ut(e.drawingData);
1136
+ if (n === null) return null;
1137
+ t.drawingData = n;
1138
+ }
1139
+ if ("attachmentIds" in e) {
1140
+ let n = e.attachmentIds;
1141
+ if (!Array.isArray(n)) return null;
1142
+ t.attachmentIds = n.map((e) => String(e).trim()).filter((e) => e.length > 0 && e.length <= I).slice(0, 20);
1143
+ }
1144
+ return Object.keys(t).length > 0 ? t : void 0;
1145
+ }
1146
+ function U(e) {
1147
+ return `${e}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1148
+ }
1149
+ function W(e, t) {
1150
+ return e.getState().comments.some((e) => e.id === t);
1151
+ }
1152
+ function G(e, t, n) {
1153
+ let r = e.getState().comments.filter((e) => e.id !== n.id), i = r.some((e) => e.id === t);
1154
+ e.setState({ comments: i ? r.map((e) => e.id === t ? n : e) : [...r, n] });
1155
+ }
1156
+ function Kt(e, t, n, r) {
1157
+ e.setState({ comments: e.getState().comments.map((e) => {
1158
+ if (e.id !== t) return e;
1159
+ let i = e.replies.filter((e) => e.id !== r.id), a = i.some((e) => e.id === n);
1160
+ return {
1161
+ ...e,
1162
+ replies: a ? i.map((e) => e.id === n ? r : e) : [...i, r]
1163
+ };
1164
+ }) });
1165
+ }
1166
+ function qt(e, t, n) {
1167
+ return e.getState().comments.some((e) => e.id === t && e.replies.some((e) => e.id === n));
1168
+ }
1169
+ async function K(e) {
1170
+ try {
1171
+ let t = u(), n = await e.apiClient.getComments(t.path);
1172
+ e.setState({
1173
+ comments: n.comments,
1174
+ pagination: n.pagination
1175
+ });
1176
+ } catch (t) {
1177
+ e.handleError(t);
1178
+ }
1179
+ }
1180
+ async function Jt(e, t) {
1181
+ let n = e.getState().pagination;
1182
+ if (!(!n || !n.hasMore) && !t.current) {
1183
+ t.current = !0;
1184
+ try {
1185
+ e.setState({ isLoading: !0 });
1186
+ let t = u(), r = await e.apiClient.getComments(t.path, "all", n.page + 1, n.limit), i = new Set(e.getState().comments.map((e) => e.id)), a = r.comments.filter((e) => !i.has(e.id));
1187
+ e.setState({
1188
+ comments: [...e.getState().comments, ...a],
1189
+ pagination: r.pagination,
1190
+ isLoading: !1
1191
+ });
1192
+ } catch (t) {
1193
+ e.setState({ isLoading: !1 }), e.handleError(t);
1194
+ } finally {
1195
+ t.current = !1;
1196
+ }
1197
+ }
1198
+ }
1199
+ async function Yt(e, t, n, r, i, a, o = "medium", s, c, l) {
1200
+ let d = e.getState().currentUser;
1201
+ if (!d) return;
1202
+ let f = z(i), p = Lt(a), m = Vt(s), h = Ut(c), g = Wt(l);
1203
+ if (!Nt.has(r) || !f || !p || !Pt.has(o) || m === null || h === null || g === null) {
1204
+ L(e, "invalid_comment", "Comment data is invalid");
1205
+ return;
1206
+ }
1207
+ let _ = `create:${r}:${f.slice(0, 50)}:${p.x}:${p.y}`;
1208
+ if (n.has(_)) return;
1209
+ n.add(_);
1210
+ let v = u(), y = g?.files ?? [], b = y.map((e, t) => ({
1211
+ id: U(`pending-att-${t}`),
1212
+ type: e.type.startsWith("image/") ? "screenshot" : "file",
1213
+ url: "",
1214
+ filename: e.name,
1215
+ size: e.size
1216
+ })), x = U("temp"), S = {
1217
+ id: x,
1218
+ type: r,
1219
+ content: f,
1220
+ position: p,
1221
+ status: "open",
1222
+ priority: o,
1223
+ author: d,
1224
+ userId: d.id,
1225
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1226
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1227
+ page: {
1228
+ url: v.url,
1229
+ path: v.path,
1230
+ title: v.title
1231
+ },
1232
+ description: g?.description,
1233
+ assignees: g?.assignees,
1234
+ checklist: g?.checklist,
1235
+ replies: [],
1236
+ attachments: b,
1237
+ textSelection: m,
1238
+ drawingData: h
1239
+ };
1240
+ e.setState({
1241
+ comments: [...e.getState().comments, S],
1242
+ activeComment: null,
1243
+ activeTool: null,
1244
+ isCommentModeActive: !1,
1245
+ isDrawingModeActive: !1,
1246
+ isHighlightModeActive: !1
1247
+ });
1248
+ try {
1249
+ let { files: n, ...i } = g ?? {}, a = await e.apiClient.createComment(r, f, p, v, o, m, h, i, x), s = a;
1250
+ if (y.length > 0) try {
1251
+ let t = (await Promise.all(y.map(async (t) => {
1252
+ let n = "." + (t.name.split(".").pop()?.toLowerCase() ?? ""), r = t.type.startsWith("image/") && [
1253
+ ".jpg",
1254
+ ".jpeg",
1255
+ ".png",
1256
+ ".gif",
1257
+ ".webp"
1258
+ ].includes(n);
1259
+ return e.apiClient.uploadFile(t, r ? "screenshot" : "attachment", { commentId: a.id });
1260
+ }))).map((e) => ({
1261
+ id: e.id,
1262
+ type: e.type === "screenshot" || e.type === "drawing" ? e.type : "file",
1263
+ url: e.url,
1264
+ thumbnail: e.thumbnail,
1265
+ filename: e.filename,
1266
+ size: e.size
1267
+ }));
1268
+ s = {
1269
+ ...a,
1270
+ attachments: t
1271
+ };
1272
+ } catch (t) {
1273
+ e.handleError(t), s = {
1274
+ ...a,
1275
+ attachments: a.attachments ?? []
1276
+ };
1277
+ }
1278
+ G(e, x, s), e.emit("comment:created", s), t.addActivity({
1279
+ type: "comment_created",
1280
+ threadId: s.id,
1281
+ message: "created a new comment"
1282
+ });
1283
+ } catch (n) {
1284
+ t.shouldQueueMutation(n) && t.queueMutation("createComment", [
1285
+ r,
1286
+ f,
1287
+ p,
1288
+ o,
1289
+ m,
1290
+ h,
1291
+ g ? {
1292
+ description: g.description,
1293
+ assignees: g.assignees,
1294
+ checklist: g.checklist,
1295
+ attachmentIds: g.attachmentIds
1296
+ } : void 0,
1297
+ {
1298
+ url: v.url,
1299
+ path: v.path,
1300
+ title: v.title
1301
+ }
1302
+ ], x) || (e.setState({ comments: e.getState().comments.filter((e) => e.id !== x) }), e.handleError(n));
1303
+ } finally {
1304
+ n.delete(_);
1305
+ }
1306
+ }
1307
+ async function Xt(e, t, n, r) {
1308
+ if (!R(n)) return;
1309
+ let i = Gt(r);
1310
+ if (i === null) {
1311
+ L(e, "invalid_comment_update", "Comment update data is invalid");
1312
+ return;
1313
+ }
1314
+ if (i === void 0) return;
1315
+ let a = e.getState().comments, o = a.find((e) => e.id === n);
1316
+ if (o) {
1317
+ e.setState({ comments: a.map((e) => e.id === n ? {
1318
+ ...e,
1319
+ ...i
1320
+ } : e) });
1321
+ try {
1322
+ let t = await e.apiClient.updateComment(n, i);
1323
+ e.setState({ comments: e.getState().comments.map((e) => e.id === n ? t : e) }), e.emit("comment:updated", t);
1324
+ } catch (r) {
1325
+ t.shouldQueueMutation(r) && t.queueMutation("updateComment", [n, i]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n ? o : e) }), e.handleError(r));
1326
+ }
1327
+ }
1328
+ }
1329
+ async function Zt(e, t, n) {
1330
+ if (!R(n)) return;
1331
+ let r = e.getState().comments, i = r.find((e) => e.id === n);
1332
+ if (!i) return;
1333
+ let a = e.getState().selectedComment;
1334
+ e.setState({
1335
+ comments: r.filter((e) => e.id !== n),
1336
+ selectedComment: a?.id === n ? null : a
1337
+ });
1338
+ try {
1339
+ await e.apiClient.deleteComment(n), e.emit("comment:deleted", { id: n });
1340
+ } catch (r) {
1341
+ if (!(t.shouldQueueMutation(r) && t.queueMutation("deleteComment", [n]))) {
1342
+ let t = e.getState().comments;
1343
+ e.setState({
1344
+ comments: t.some((e) => e.id === n) ? t : [...t, i],
1345
+ selectedComment: a
1346
+ }), e.handleError(r);
1347
+ }
1348
+ }
1349
+ }
1350
+ async function Qt(e, t, n, r) {
1351
+ let i = e.getState().currentUser;
1352
+ if (!i || !R(n) || !W(e, n)) return;
1353
+ let a = z(r, xt);
1354
+ if (!a) {
1355
+ L(e, "invalid_reply", "Reply content is invalid");
1356
+ return;
1357
+ }
1358
+ let o = U("temp_reply"), s = {
1359
+ id: o,
1360
+ content: a,
1361
+ author: i,
1362
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1363
+ };
1364
+ e.setState({ comments: e.getState().comments.map((e) => e.id === n ? {
1365
+ ...e,
1366
+ replies: [...e.replies, s]
1367
+ } : e) });
1368
+ try {
1369
+ Kt(e, n, o, await e.apiClient.addReply(n, a, o));
1370
+ let t = e.getState().comments.find((e) => e.id === n);
1371
+ t && e.emit("comment:updated", t);
1372
+ } catch (r) {
1373
+ t.shouldQueueMutation(r) && t.queueMutation("addReply", [n, a], o) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n ? {
1374
+ ...e,
1375
+ replies: e.replies.filter((e) => e.id !== o)
1376
+ } : e) }), e.handleError(r));
1377
+ }
1378
+ }
1379
+ async function $t(e, t, n, r) {
1380
+ if (!R(t) || !R(n) || !qt(e, t, n)) return;
1381
+ let i = z(r, xt);
1382
+ if (!i) {
1383
+ L(e, "invalid_reply", "Reply content is invalid");
1384
+ return;
1385
+ }
1386
+ let a = e.getState().comments, o = a.find((e) => e.id === t)?.replies.find((e) => e.id === n);
1387
+ e.setState({ comments: a.map((e) => e.id === t ? {
1388
+ ...e,
1389
+ replies: e.replies.map((e) => e.id === n ? {
1390
+ ...e,
1391
+ content: i,
1392
+ isEdited: !0
1393
+ } : e)
1394
+ } : e) });
1395
+ try {
1396
+ let r = await e.apiClient.updateReply(t, n, i);
1397
+ e.setState({ comments: e.getState().comments.map((e) => e.id === t ? {
1398
+ ...e,
1399
+ replies: e.replies.map((e) => e.id === n ? r : e)
1400
+ } : e) });
1401
+ let a = e.getState().comments.find((e) => e.id === t);
1402
+ a && e.emit("comment:updated", a);
1403
+ } catch (r) {
1404
+ e.setState({ comments: e.getState().comments.map((e) => e.id === t && o ? {
1405
+ ...e,
1406
+ replies: e.replies.map((e) => e.id === n ? o : e)
1407
+ } : e) }), e.handleError(r);
1408
+ }
1409
+ }
1410
+ async function en(e, t, n) {
1411
+ if (!R(t) || !R(n) || !qt(e, t, n)) return;
1412
+ let r = e.getState().comments, i = r.find((e) => e.id === t)?.replies.find((e) => e.id === n);
1413
+ e.setState({ comments: r.map((e) => e.id === t ? {
1414
+ ...e,
1415
+ replies: e.replies.filter((e) => e.id !== n)
1416
+ } : e) });
1417
+ try {
1418
+ await e.apiClient.deleteReply(t, n);
1419
+ let r = e.getState().comments.find((e) => e.id === t);
1420
+ r && e.emit("comment:updated", r);
1421
+ } catch (r) {
1422
+ e.setState({ comments: e.getState().comments.map((e) => e.id === t && i && !e.replies.some((e) => e.id === n) ? {
1423
+ ...e,
1424
+ replies: [...e.replies, i]
1425
+ } : e) }), e.handleError(r);
1426
+ }
1427
+ }
1428
+ async function tn(e, t, n) {
1429
+ if (!R(n) || !W(e, n)) return;
1430
+ let r = e.getState().comments, i = r.find((e) => e.id === n);
1431
+ e.setState({ comments: r.map((e) => e.id === n ? {
1432
+ ...e,
1433
+ status: "resolved"
1434
+ } : e) });
1435
+ try {
1436
+ let r = await e.apiClient.resolveComment(n);
1437
+ e.setState({ comments: e.getState().comments.map((e) => e.id === n ? r : e) }), e.emit("comment:resolved", r), e.emit("comment:updated", r), t.addActivity({
1438
+ type: "comment_resolved",
1439
+ threadId: n,
1440
+ message: "resolved a comment"
1441
+ });
1442
+ } catch (r) {
1443
+ t.shouldQueueMutation(r) && t.queueMutation("resolveComment", [n]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n && i ? i : e) }), e.handleError(r));
1444
+ }
1445
+ }
1446
+ async function nn(e, t, n) {
1447
+ if (!R(n) || !W(e, n)) return;
1448
+ let r = e.getState().comments, i = r.find((e) => e.id === n);
1449
+ e.setState({ comments: r.map((e) => e.id === n ? {
1450
+ ...e,
1451
+ status: "open"
1452
+ } : e) });
1453
+ try {
1454
+ let t = await e.apiClient.unresolveComment(n);
1455
+ e.setState({ comments: e.getState().comments.map((e) => e.id === n ? t : e) }), e.emit("comment:updated", t);
1456
+ } catch (r) {
1457
+ t.shouldQueueMutation(r) && t.queueMutation("unresolveComment", [n]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n && i ? i : e) }), e.handleError(r));
1458
+ }
1459
+ }
1460
+ async function rn(e, t, n) {
1461
+ if (!R(n) || !W(e, n)) return;
1462
+ let r = e.getState().comments, i = r.find((e) => e.id === n);
1463
+ e.setState({ comments: r.map((e) => e.id === n ? {
1464
+ ...e,
1465
+ status: "complete"
1466
+ } : e) });
1467
+ try {
1468
+ let r = await e.apiClient.markComplete(n);
1469
+ e.setState({ comments: e.getState().comments.map((e) => e.id === n ? r : e) }), e.emit("comment:completed", r), t.addActivity({
1470
+ type: "comment_completed",
1471
+ threadId: n,
1472
+ message: "marked a comment as complete"
1473
+ });
1474
+ } catch (r) {
1475
+ t.shouldQueueMutation(r) && t.queueMutation("completeComment", [n]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n && i ? i : e) }), e.handleError(r));
1476
+ }
1477
+ }
1478
+ async function an(e, t, r, i) {
1479
+ if (!R(r) || typeof i != "string") return;
1480
+ let a = i.trim();
1481
+ if (!a || a.length > Mt || n(a)) return;
1482
+ let o = e.getState().comments.find((e) => e.id === r);
1483
+ if (!o) return;
1484
+ let s = (o.reactions ?? []).filter((e) => typeof e.emoji == "string" && e.emoji.length > 0 && e.emoji.length <= Mt && !n(e.emoji) && typeof e.count == "number" && Number.isInteger(e.count) && e.count >= 0 && e.count <= jt), c = s.find((e) => e.emoji === a)?.reacted, l = [...s];
1485
+ if (c) {
1486
+ let e = l.findIndex((e) => e.emoji === a), t = l[e];
1487
+ t.count <= 1 ? l.splice(e, 1) : l[e] = {
1488
+ ...t,
1489
+ count: t.count - 1,
1490
+ reacted: !1
1491
+ };
1492
+ } else {
1493
+ let e = l.findIndex((e) => e.emoji === a), t = e === -1 ? void 0 : l[e];
1494
+ t ? l[e] = {
1495
+ ...t,
1496
+ count: Math.min(t.count + 1, jt),
1497
+ reacted: !0
1498
+ } : l.push({
1499
+ emoji: a,
1500
+ count: 1,
1501
+ reacted: !0
1502
+ });
1503
+ }
1504
+ let u = e.getState().comments;
1505
+ e.setState({ comments: u.map((e) => e.id === r ? {
1506
+ ...e,
1507
+ reactions: l
1508
+ } : e) });
1509
+ try {
1510
+ c ? await e.apiClient.removeReaction(r, a) : await e.apiClient.addReaction(r, a);
1511
+ let t = e.getState().comments.find((e) => e.id === r);
1512
+ t && e.emit("comment:reaction", {
1513
+ commentId: r,
1514
+ emoji: a,
1515
+ comment: t
1516
+ });
1517
+ } catch (n) {
1518
+ t.shouldQueueMutation(n) && t.queueMutation("reactToComment", [
1519
+ r,
1520
+ a,
1521
+ c ? "remove" : "add"
1522
+ ]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === r ? {
1523
+ ...e,
1524
+ reactions: s
1525
+ } : e) }), e.handleError(n));
1526
+ }
1527
+ }
1528
+ async function on(e, t, n, r, i) {
1529
+ if (!R(n) || !W(e, n)) return;
1530
+ let a = Lt({
1531
+ x: r,
1532
+ y: i
1533
+ });
1534
+ if (!a) {
1535
+ L(e, "invalid_position", "Comment position is invalid");
1536
+ return;
1537
+ }
1538
+ let o = e.getState().comments, s = o.find((e) => e.id === n);
1539
+ e.setState({ comments: o.map((e) => e.id === n ? {
1540
+ ...e,
1541
+ position: a
1542
+ } : e) });
1543
+ try {
1544
+ let t = await e.apiClient.updatePosition(n, a);
1545
+ e.setState({ comments: e.getState().comments.map((e) => e.id === n ? t : e) }), e.emit("comment:position", {
1546
+ commentId: n,
1547
+ position: a
1548
+ });
1549
+ } catch (r) {
1550
+ t.shouldQueueMutation(r) && t.queueMutation("updatePosition", [n, a]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n && s ? {
1551
+ ...e,
1552
+ position: s.position
1553
+ } : e) }), e.handleError(r));
1554
+ }
1555
+ }
1556
+ function sn(e, t) {
1557
+ e.setState({ selectedComment: t });
1558
+ }
1559
+ async function cn(e, t, n, r, i) {
1560
+ let a = e.getState().currentUser;
1561
+ if (!a) return;
1562
+ let o = z(i), s = Vt(r);
1563
+ if (!o || s == null) {
1564
+ L(e, "invalid_highlight", "Highlight data is invalid");
1565
+ return;
1566
+ }
1567
+ let c = `highlight:${s.xpath}:${s.startOffset}:${o.slice(0, 50)}`;
1568
+ if (n.has(c)) return;
1569
+ n.add(c);
1570
+ let l = u(), d = U("temp"), f = {
1571
+ id: d,
1572
+ type: "highlight",
1573
+ content: o,
1574
+ position: {
1575
+ x: 0,
1576
+ y: 0
1577
+ },
1578
+ status: "open",
1579
+ priority: "medium",
1580
+ author: a,
1581
+ userId: a.id,
1582
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1583
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1584
+ page: {
1585
+ url: l.url,
1586
+ path: l.path,
1587
+ title: l.title
1588
+ },
1589
+ replies: [],
1590
+ attachments: [],
1591
+ textSelection: s
1592
+ };
1593
+ e.setState({ comments: [...e.getState().comments, f] });
1594
+ try {
1595
+ let t = await e.apiClient.createHighlight(o, s, l, "medium", d);
1596
+ G(e, d, t), e.emit("comment:created", t);
1597
+ } catch (n) {
1598
+ t.shouldQueueMutation(n) && t.queueMutation("createHighlight", [
1599
+ o,
1600
+ s,
1601
+ {
1602
+ url: l.url,
1603
+ path: l.path,
1604
+ title: l.title
1605
+ }
1606
+ ], d) || (e.setState({ comments: e.getState().comments.filter((e) => e.id !== d) }), e.handleError(n));
1607
+ } finally {
1608
+ n.delete(c);
1609
+ }
1610
+ }
1611
+ async function ln(e, t, n, r, i, a) {
1612
+ let o = e.getState().currentUser;
1613
+ if (!o) return;
1614
+ let s = z(a), c = Lt(i), l = Ut(r);
1615
+ if (!s || !c || l == null) {
1616
+ L(e, "invalid_drawing", "Drawing comment data is invalid");
1617
+ return;
1618
+ }
1619
+ let d = `drawing:${c.x}:${c.y}:${s.slice(0, 50)}`;
1620
+ if (n.has(d)) return;
1621
+ n.add(d);
1622
+ let f = u(), p = U("temp"), m = {
1623
+ id: p,
1624
+ type: "drawing",
1625
+ content: s,
1626
+ position: c,
1627
+ status: "open",
1628
+ priority: "medium",
1629
+ author: o,
1630
+ userId: o.id,
1631
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1632
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1633
+ page: {
1634
+ url: f.url,
1635
+ path: f.path,
1636
+ title: f.title
1637
+ },
1638
+ replies: [],
1639
+ attachments: [],
1640
+ drawingData: l
1641
+ };
1642
+ e.setState({ comments: [...e.getState().comments, m] });
1643
+ try {
1644
+ let t = await e.apiClient.createDrawing(s, l, c, f, p);
1645
+ G(e, p, t), e.emit("comment:created", t);
1646
+ } catch (n) {
1647
+ t.shouldQueueMutation(n) && t.queueMutation("createDrawing", [
1648
+ s,
1649
+ l,
1650
+ c,
1651
+ {
1652
+ url: f.url,
1653
+ path: f.path,
1654
+ title: f.title
1655
+ }
1656
+ ], p) || (e.setState({ comments: e.getState().comments.filter((e) => e.id !== p) }), e.handleError(n));
1657
+ } finally {
1658
+ n.delete(d);
1659
+ }
1660
+ }
1661
+ var un = 1e4, dn = 2048, fn = 10 * 1024 * 1024, pn = 20 * 1024 * 1024, q = 16384, mn = 32e6, hn = 10, gn = 10 * 1024 * 1024, _n = 25 * 1024 * 1024, vn = new Set([
1662
+ "jpg",
1663
+ "jpeg",
1664
+ "png",
1665
+ "gif",
1666
+ "webp",
1667
+ "pdf",
1668
+ "doc",
1669
+ "docx",
1670
+ "txt",
1671
+ "csv"
1672
+ ]), yn = 15e3, bn = 1e4, xn = {
1673
+ "image/gif": "gif",
1674
+ "image/jpeg": "jpg",
1675
+ "image/png": "png",
1676
+ "image/webp": "webp"
1677
+ };
1678
+ function J(e, t) {
1679
+ let n = Error(t);
1680
+ return n.error = e, n.code = 400, n;
1681
+ }
1682
+ function Sn(e) {
1683
+ if (typeof e != "string") throw J("invalid_position", "Invalid position");
1684
+ let t = e.trim();
1685
+ if (!t || t.length > dn || o(t)) throw J("invalid_position", "Invalid position");
1686
+ return t;
1687
+ }
1688
+ function Cn(e) {
1689
+ if (!s(e) || !a(e.x) || !a(e.y)) throw J("invalid_position", "Invalid position");
1690
+ return {
1691
+ x: e.x,
1692
+ y: e.y,
1693
+ ...e.element === void 0 ? {} : { element: Sn(e.element) },
1694
+ ...e.xpath === void 0 ? {} : { xpath: Sn(e.xpath) }
1695
+ };
1696
+ }
1697
+ function wn(e) {
1698
+ if (typeof e != "string") throw J("invalid_content", "Screenshot comment is required");
1699
+ let t = e.trim();
1700
+ if (!t || t.length > un || o(t)) throw J("invalid_content", "Screenshot comment is required");
1701
+ return t;
1702
+ }
1703
+ function Tn(e) {
1704
+ return typeof Blob < "u" && e instanceof Blob;
1705
+ }
1706
+ function En(e) {
1707
+ return typeof File < "u" && e instanceof File;
1708
+ }
1709
+ function Dn(e) {
1710
+ return typeof HTMLElement < "u" && e instanceof HTMLElement;
1711
+ }
1712
+ function On(e) {
1713
+ if (e !== void 0) {
1714
+ if (!Dn(e)) throw J("invalid_element", "Invalid screenshot target");
1715
+ return e;
1716
+ }
1717
+ if (typeof document > "u" || !document.body) throw J("invalid_element", "A browser document is required to capture screenshots");
1718
+ return document.body;
1719
+ }
1720
+ function kn(e) {
1721
+ let t = /^data:(image\/(?:png|jpeg|gif|webp));base64,/i.exec(e)?.[1];
1722
+ return t ? t.toLowerCase() : null;
1723
+ }
1724
+ function An(e) {
1725
+ if (!s(e)) throw J("invalid_screenshot", "Invalid screenshot result");
1726
+ let t = typeof e.dataUrl == "string" ? e.dataUrl.trim() : "", n = e.blob, r = e.dimensions;
1727
+ if (!kn(t) || t.length > pn || !Tn(n) || n.size <= 0 || n.size > fn || n.type && !Object.prototype.hasOwnProperty.call(xn, n.type)) throw J("invalid_screenshot", "Invalid screenshot result");
1728
+ if (!s(r)) throw J("invalid_screenshot", "Invalid screenshot dimensions");
1729
+ let { width: i, height: a } = r;
1730
+ if (typeof i != "number" || typeof a != "number" || !Number.isFinite(i) || !Number.isFinite(a) || i <= 0 || a <= 0 || i > q || a > q) throw J("invalid_screenshot", "Invalid screenshot dimensions");
1731
+ return {
1732
+ dataUrl: t,
1733
+ blob: n,
1734
+ dimensions: {
1735
+ width: i,
1736
+ height: a
1737
+ }
1738
+ };
1739
+ }
1740
+ function jn(e) {
1741
+ let t = kn(e.dataUrl);
1742
+ return e.blob.type || t;
1743
+ }
1744
+ function Mn(e) {
1745
+ return `screenshot.${xn[jn(e)]}`;
1746
+ }
1747
+ function Nn(e, t, n) {
1748
+ let r = null;
1749
+ return new Promise((i, a) => {
1750
+ r = setTimeout(() => {
1751
+ r = null, a(Error(n));
1752
+ }, t), e.then((e) => {
1753
+ r && clearTimeout(r), r = null, i(e);
1754
+ }, (e) => {
1755
+ r && clearTimeout(r), r = null, a(e);
1756
+ });
1757
+ });
1758
+ }
1759
+ function Pn(e) {
1760
+ return new Promise((t, n) => {
1761
+ let r = !1, i = setTimeout(() => {
1762
+ r = !0, n(/* @__PURE__ */ Error("toBlob timed out"));
1763
+ }, bn);
1764
+ e.toBlob((e) => {
1765
+ r || (r = !0, clearTimeout(i), e ? t(e) : n(/* @__PURE__ */ Error("toBlob returned null")));
1766
+ }, "image/png");
1767
+ });
1768
+ }
1769
+ function Fn(e) {
1770
+ let t = e.lastIndexOf(".");
1771
+ return t >= 0 ? e.slice(t + 1).toLowerCase() : "";
1772
+ }
1773
+ function In(e) {
1774
+ if (!Array.isArray(e)) throw J("invalid_files", "Files must be an array");
1775
+ if (e.length > hn) throw J("too_many_files", `Cannot upload more than ${hn} files at once`);
1776
+ let t = 0;
1777
+ for (let n of e) {
1778
+ if (!En(n)) throw J("invalid_files", "Invalid file upload");
1779
+ if (n.size > gn) throw J("file_too_large", `File "${n.name}" exceeds the ${gn / 1024 / 1024}MB limit`);
1780
+ if (t += n.size, t > _n) throw J("upload_too_large", `Total upload size exceeds the ${_n / 1024 / 1024}MB limit`);
1781
+ if (o(n.name) || n.name.includes("/") || n.name.includes("\\")) throw J("invalid_filename", "Filename contains invalid characters");
1782
+ if (i(n.name)) throw J("invalid_file_type", `File type ".${Fn(n.name)}" is not allowed`);
1783
+ if (!vn.has(Fn(n.name))) throw J("invalid_file_type", `File type ".${Fn(n.name)}" is not supported. Allowed: ${[...vn].map((e) => `.${e}`).join(", ")}`);
1784
+ }
1785
+ return e;
1786
+ }
1787
+ function Ln(e) {
1788
+ try {
1789
+ return e.matches?.("input[type=\"password\"],[data-commentkit-redact],[data-html2canvas-ignore],[autocomplete*=\"cc-\"],[autocomplete=\"current-password\"],[autocomplete=\"new-password\"]") ?? !1;
1790
+ } catch {
1791
+ return !1;
1792
+ }
1793
+ }
1794
+ async function Rn(e, t, n, r = {}) {
1795
+ try {
1796
+ let e = On(n);
1797
+ if (t) return An(await t(e));
1798
+ let r;
1799
+ try {
1800
+ r = (await import("html2canvas")).default;
1801
+ } catch {
1802
+ /* v8 ignore next 3 -- dynamic import() can't be intercepted by vi.mock */
1803
+ throw Error("Screenshot requires either a custom screenshotProvider in config or html2canvas installed. Install html2canvas: npm install html2canvas — or provide config.screenshotProvider.");
1804
+ }
1805
+ let i = await Nn(r(e, {
1806
+ useCORS: !0,
1807
+ allowTaint: !1,
1808
+ scale: 2,
1809
+ logging: !1,
1810
+ ignoreElements: Ln
1811
+ }), yn, "html2canvas timed out after 15s");
1812
+ if (i.width > q || i.height > q || i.width * i.height > mn) throw J("screenshot_too_large", "Captured area is too large to screenshot");
1813
+ return An({
1814
+ dataUrl: i.toDataURL("image/png"),
1815
+ blob: await Pn(i),
1816
+ dimensions: {
1817
+ width: i.width,
1818
+ height: i.height
1819
+ }
1820
+ });
1821
+ } catch (t) {
1822
+ return r.reportErrors !== !1 && (console.error("[CommentKit] Screenshot failed:", t), e.handleError({
1823
+ error: "screenshot_failed",
1824
+ message: "Failed to capture screenshot",
1825
+ code: 500
1826
+ })), null;
1827
+ }
1828
+ }
1829
+ async function zn(e, t, n, r) {
1830
+ try {
1831
+ let i = An(t), a = wn(n), o = Cn(r);
1832
+ e.setState({ isLoading: !0 });
1833
+ let s = new File([i.blob], Mn(i), { type: jn(i) }), c = u(), l = await e.apiClient.uploadScreenshot(s, {
1834
+ content: a,
1835
+ position: o,
1836
+ page: c
1837
+ });
1838
+ return e.setState({
1839
+ comments: [...e.getState().comments, l],
1840
+ isLoading: !1,
1841
+ activeScreenshot: null
1842
+ }), e.emit("comment:created", l), l;
1843
+ } catch (t) {
1844
+ return e.setState({ isLoading: !1 }), e.handleError(t), null;
1845
+ }
1846
+ }
1847
+ async function Bn(e, t, n) {
1848
+ try {
1849
+ let r = In(t);
1850
+ return r.length === 0 ? [] : await e.apiClient.uploadFiles(r, n);
1851
+ } catch (t) {
1852
+ return e.handleError(t), [];
1853
+ }
1854
+ }
1855
+ var Vn = 4e3, Hn = 500, Un = 2e3, Wn = 1e3, Gn = 5, Kn = 25, qn = 3 * 1024 * 1024;
1856
+ function Jn(e) {
1857
+ let t = N(e?.comment, Un);
1858
+ return t.length > 0 ? t : null;
1859
+ }
1860
+ function Yn(e) {
1861
+ return (e?.attachments ?? []).slice(0, Gn).flatMap((e) => {
1862
+ let t = N(e.name, Wn), n = N(e.path, Wn);
1863
+ return !t || !n ? [] : [{
1864
+ name: t,
1865
+ path: n,
1866
+ ...e.pathSource ? { pathSource: e.pathSource } : {},
1867
+ ...e.type ? { type: N(e.type, Wn) } : {},
1868
+ ...typeof e.size == "number" ? { size: e.size } : {},
1869
+ ...typeof e.lastModified == "number" ? { lastModified: e.lastModified } : {}
1870
+ }];
1871
+ });
1872
+ }
1873
+ function Xn(e) {
1874
+ return typeof HTMLElement < "u" && e instanceof HTMLElement;
1875
+ }
1876
+ function Zn(e, t, n, r) {
1877
+ let i = e.getBoundingClientRect(), a = d(e), o = f(e), s = e.getAttribute("class"), c = e.getAttribute("role"), l = e.getAttribute("aria-label"), u = N(e.textContent, Hn), p = N(e.outerHTML, Vn);
1878
+ return {
1879
+ found: !0,
1880
+ tagName: e.tagName.toLowerCase(),
1881
+ ...e.id ? { id: e.id } : {},
1882
+ ...s ? { className: s } : {},
1883
+ ...c ? { role: c } : {},
1884
+ ...l ? { ariaLabel: l } : {},
1885
+ ...u ? { text: u } : {},
1886
+ rect: {
1887
+ top: i.top,
1888
+ left: i.left,
1889
+ width: i.width,
1890
+ height: i.height
1891
+ },
1892
+ ...p ? { htmlPreview: p } : {},
1893
+ ...a ? { selector: a } : {},
1894
+ ...o ? { xpath: o } : {},
1895
+ ...t ? {
1896
+ source: Qn(t),
1897
+ stack: n.map(Qn)
1898
+ } : {},
1899
+ ...r ? { componentName: r } : {}
1900
+ };
1901
+ }
1902
+ function Qn(e) {
1903
+ return {
1904
+ filePath: e.filePath,
1905
+ lineNumber: e.lineNumber,
1906
+ columnNumber: e.columnNumber,
1907
+ componentName: e.componentName
1908
+ };
1909
+ }
1910
+ function $n(e) {
1911
+ let t = `${e.filePath}${e.lineNumber === null ? "" : `:${e.lineNumber}`}${e.columnNumber === null ? "" : `:${e.columnNumber}`}`;
1912
+ return e.componentName ? `${e.componentName} (${t})` : t;
1913
+ }
1914
+ function er(e, t, n, r, i, a) {
1915
+ let o = ["# CommentKit Element Grab", ""], s = t.tagName ?? "element", c = t.id ? `#${t.id}` : "";
1916
+ if (o.push(`**Tag:** \`${s}${c}\``), i && o.push(`**Comment:** ${i}`), a.length > 0) {
1917
+ o.push("", "**Attachments:**");
1918
+ for (let e of a) {
1919
+ let t = [
1920
+ e.type ? `type: \`${e.type}\`` : null,
1921
+ typeof e.size == "number" ? `size: ${e.size} bytes` : null,
1922
+ e.pathSource ? `path source: ${e.pathSource}` : null
1923
+ ].filter(Boolean).join(", ");
1924
+ o.push(`- \`${e.name}\` - path: \`${e.path}\`${t ? ` (${t})` : ""}`);
1925
+ }
1926
+ }
1927
+ if (t.componentName && o.push(`**Component:** \`${t.componentName}\``), t.source && o.push(`**Source:** ${$n(t.source)}`), t.stack && t.stack.length > 1) {
1928
+ o.push("", "**Stack:**");
1929
+ for (let e of t.stack) o.push(`- ${$n(e)}`);
1930
+ }
1931
+ return t.source || (t.selector && o.push(`**Selector:** \`${t.selector}\``), t.xpath && o.push(`**XPath:** \`${t.xpath}\``)), o.push(`**Page:** ${e.title || "Untitled"} — ${e.url || e.path}`), o.push(""), o.push("**HTML:**", "```html", n, "```", ""), r && o.push("**Screenshot:** attached to clipboard as an image (paste below this text).", ""), o.join("\n");
1932
+ }
1933
+ function tr(e) {
1934
+ let t = e.element;
1935
+ return {
1936
+ tagName: t.tagName,
1937
+ id: t.id,
1938
+ className: t.className,
1939
+ textContent: t.text,
1940
+ componentName: t.componentName,
1941
+ filePath: t.source?.filePath,
1942
+ lineNumber: t.source?.lineNumber ?? void 0,
1943
+ columnNumber: t.source?.columnNumber ?? void 0,
1944
+ comment: e.comment ?? void 0,
1945
+ attachments: e.attachments,
1946
+ selector: t.selector,
1947
+ xpath: t.xpath
1948
+ };
1949
+ }
1950
+ function nr(e) {
1951
+ if (typeof window > "u" || typeof window.dispatchEvent != "function") return;
1952
+ let t = e[0];
1953
+ t && window.dispatchEvent(new CustomEvent("commentkit:element-selected", { detail: {
1954
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1955
+ page: t.page,
1956
+ elements: e.map(tr)
1957
+ } }));
1958
+ }
1959
+ async function rr(e, t, n, r) {
1960
+ if (!e || typeof Element > "u" || !(e instanceof Element) || typeof e.getBoundingClientRect != "function") return null;
1961
+ let i = (Xn(e), e), a = await xe(e), o = a?.source ?? null, s = a?.stack ?? [], c = a?.componentName ?? null, l = await Rn(t, n, i, { reportErrors: !1 }), d = l?.dataUrl ?? null, f = l?.blob ?? null, p = Zn(e, o, s, c), m = p.htmlPreview ?? N(e.outerHTML, Vn), h = u(), g = Jn(r), _ = Yn(r), v = er({
1962
+ url: h.url,
1963
+ path: h.path,
1964
+ title: h.title
1965
+ }, p, m, d, g, _);
1966
+ try {
1967
+ f ? await Ke(v, f) : await qe(v);
1968
+ } catch {}
1969
+ let y = {
1970
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1971
+ page: {
1972
+ url: h.url,
1973
+ path: h.path,
1974
+ title: h.title
1975
+ },
1976
+ element: p,
1977
+ comment: g,
1978
+ attachments: _,
1979
+ html: m,
1980
+ screenshotDataUrl: d,
1981
+ markdown: v
1982
+ };
1983
+ return nr([y]), y;
1984
+ }
1985
+ function ir(e, t, n, r) {
1986
+ let i = [
1987
+ "# CommentKit Element Grab",
1988
+ "",
1989
+ `**Elements:** ${t.length}`,
1990
+ `**Page:** ${e.title || "Untitled"} — ${e.url || e.path}`
1991
+ ];
1992
+ if (n && i.push(`**Comment:** ${n}`), r.length > 0) {
1993
+ i.push("", "**Attachments:**");
1994
+ for (let e of r) i.push(`- \`${e.name}\` - path: \`${e.path}\`${e.pathSource ? ` (path source: ${e.pathSource})` : ""}`);
1995
+ }
1996
+ return i.push(""), t.forEach((e, t) => {
1997
+ let { element: n } = e, r = n.tagName ?? "element", a = n.id ? `#${n.id}` : "";
1998
+ i.push(`## [${t + 1}] \`${r}${a}\``), n.componentName && i.push(`- Component: \`${n.componentName}\``), n.source && i.push(`- Source: ${$n(n.source)}`), n.stack && n.stack.length > 1 && i.push(`- Stack: ${n.stack.map((e) => e.componentName ?? e.filePath).join(" → ")}`), n.source || (n.selector && i.push(`- Selector: \`${n.selector}\``), n.xpath && i.push(`- XPath: \`${n.xpath}\``)), i.push("", "```html", e.html, "```", ""), e.screenshotDataUrl && i.push(`![screenshot](${e.screenshotDataUrl})`, "");
1999
+ }), i.join("\n");
2000
+ }
2001
+ async function ar(e, t, n, r) {
2002
+ let i = e.filter((e) => !!e && typeof Element < "u" && e instanceof Element && typeof e.getBoundingClientRect == "function");
2003
+ if (i.length === 0) return null;
2004
+ let a = i.slice(0, Kn);
2005
+ i.length > Kn && typeof console < "u" && console.warn(`[CommentKit] grabElements was called with ${i.length} elements — capped to ${Kn} for clipboard size. Pass fewer elements to avoid truncation.`);
2006
+ let o = [], s = 0, c = 0, l = Jn(r), d = Yn(r);
2007
+ for (let e of a) {
2008
+ let r = (Xn(e), e), i = await xe(e), a = i?.source ?? null, f = i?.stack ?? [], p = i?.componentName ?? null, m = null;
2009
+ if (s < qn) {
2010
+ let e = (await Rn(t, n, r, { reportErrors: !1 }))?.dataUrl ?? null;
2011
+ e && s + e.length <= qn ? (m = e, s += e.length) : e && c++;
2012
+ } else c++;
2013
+ let h = Zn(e, a, f, p), g = h.htmlPreview ?? N(e.outerHTML, Vn), _ = u(), v = er({
2014
+ url: _.url,
2015
+ path: _.path,
2016
+ title: _.title
2017
+ }, h, g, m, l, d);
2018
+ o.push({
2019
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2020
+ page: {
2021
+ url: _.url,
2022
+ path: _.path,
2023
+ title: _.title
2024
+ },
2025
+ element: h,
2026
+ comment: l,
2027
+ attachments: d,
2028
+ html: g,
2029
+ screenshotDataUrl: m,
2030
+ markdown: v
2031
+ });
2032
+ }
2033
+ c > 0 && typeof console < "u" && console.warn(`[CommentKit] grabElements dropped ${c} screenshot${c === 1 ? "" : "s"} to stay under the ${Math.round(qn / 1024 / 1024)}MB clipboard budget.`);
2034
+ let f = u(), p = ir({
2035
+ url: f.url,
2036
+ path: f.path,
2037
+ title: f.title
2038
+ }, o, l, d);
2039
+ try {
2040
+ await qe(p);
2041
+ } catch {}
2042
+ let m = {
2043
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2044
+ page: {
2045
+ url: f.url,
2046
+ path: f.path,
2047
+ title: f.title
2048
+ },
2049
+ results: o,
2050
+ attachments: d,
2051
+ markdown: p
2052
+ };
2053
+ return nr(o), m;
2054
+ }
2055
+ var or = {
2056
+ c: "comment",
2057
+ e: "select",
2058
+ d: "draw",
2059
+ h: "highlight",
2060
+ s: "screenshot"
2061
+ };
2062
+ function sr(e) {
2063
+ return typeof e.composedPath == "function" ? e.composedPath() : e.target ? [e.target] : [];
2064
+ }
2065
+ function cr(e) {
2066
+ return typeof Element < "u" && e instanceof Element;
2067
+ }
2068
+ function lr(e) {
2069
+ if (!cr(e)) return !1;
2070
+ let t = e.tagName.toLowerCase();
2071
+ return t === "input" || t === "textarea" || t === "select" || e.isContentEditable || e.getAttribute("role") === "textbox";
2072
+ }
2073
+ function ur(e) {
2074
+ let t = e.activeElement;
2075
+ for (; t?.shadowRoot?.activeElement;) t = t.shadowRoot.activeElement;
2076
+ return t;
2077
+ }
2078
+ function dr(e) {
2079
+ return sr(e).some(lr) ? !0 : typeof document > "u" ? !1 : lr(ur(document));
2080
+ }
2081
+ function fr(e) {
2082
+ return sr(e).some((e) => cr(e) && (e.hasAttribute("data-commentkit") || e.hasAttribute("data-commentkit-ui") || e.hasAttribute("data-commentkit-host")));
2083
+ }
2084
+ function pr(e) {
2085
+ return (e.ctrlKey || e.metaKey) && e.shiftKey && (e.key === "K" || e.key === "k" || e.code === "KeyK");
2086
+ }
2087
+ function mr(e) {
2088
+ let t = e.key.toLowerCase(), n = e.code.startsWith("Key") ? e.code.slice(3).toLowerCase() : "";
2089
+ return or[t] ?? or[n] ?? null;
2090
+ }
2091
+ function Y(e) {
2092
+ e.preventDefault(), e.stopPropagation();
2093
+ }
2094
+ function hr(e, t) {
2095
+ if (e.isLoginModalVisible) t.toggleLoginModal();
2096
+ else if (e.isShortcutsOverlayVisible) t.toggleShortcutsOverlay();
2097
+ else if (e.activeComment) t.setState({ activeComment: null });
2098
+ else if (e.selectedComment) t.selectComment(null);
2099
+ else if (e.activeTool) t.setTool(null);
2100
+ else if (e.isSidebarVisible) t.toggleSidebar();
2101
+ else if (e.isOverlayVisible) t.toggleOverlay();
2102
+ else return !1;
2103
+ return !0;
2104
+ }
2105
+ function gr(e, t) {
2106
+ e.isAuthenticated ? t.toggleOverlay() : t.toggleLoginModal();
2107
+ }
2108
+ function _r(e, t, n) {
2109
+ if (e.defaultPrevented || e.repeat || e.isComposing) return;
2110
+ let r = dr(e), i = fr(e);
2111
+ if (pr(e)) {
2112
+ if (r) return;
2113
+ Y(e), gr(t, n);
2114
+ return;
2115
+ }
2116
+ if (e.key === "Escape") {
2117
+ if (r && !i) return;
2118
+ hr(t, n) && Y(e);
2119
+ return;
2120
+ }
2121
+ if (t.isAuthenticated && (t.isOverlayVisible || t.activeTool !== null) && !r && !e.ctrlKey && !e.metaKey && !e.altKey) {
2122
+ if (e.key === "?") {
2123
+ Y(e), n.toggleShortcutsOverlay();
2124
+ return;
2125
+ }
2126
+ let r = mr(e);
2127
+ r && (Y(e), n.setTool(t.activeTool === r ? null : r));
2128
+ }
2129
+ }
2130
+ function vr(e) {
2131
+ return Object.freeze(e);
2132
+ }
2133
+ var yr = Object.freeze({
2134
+ auth: vr([
2135
+ "isAuthenticated",
2136
+ "currentUser",
2137
+ "project",
2138
+ "isLoginModalVisible",
2139
+ "otpStep",
2140
+ "otpEmail"
2141
+ ]),
2142
+ ui: vr([
2143
+ "isOverlayVisible",
2144
+ "isSidebarVisible",
2145
+ "isShortcutsOverlayVisible",
2146
+ "activeTool",
2147
+ "isCommentModeActive",
2148
+ "isDrawingModeActive",
2149
+ "isHighlightModeActive",
2150
+ "isScreenshotModeActive",
2151
+ "selectedComment",
2152
+ "activeComment",
2153
+ "activeDrawing",
2154
+ "activeScreenshot",
2155
+ "panelView",
2156
+ "activities",
2157
+ "isLoading",
2158
+ "error"
2159
+ ]),
2160
+ comments: vr([
2161
+ "comments",
2162
+ "pagination",
2163
+ "seenThreadIds"
2164
+ ]),
2165
+ realtime: vr([
2166
+ "onlineUsers",
2167
+ "connectionStatus",
2168
+ "pendingMutations",
2169
+ "isOnline"
2170
+ ])
2171
+ });
2172
+ function br() {
2173
+ return typeof navigator < "u" && typeof navigator.onLine == "boolean" ? navigator.onLine : !0;
2174
+ }
2175
+ var xr = 2e3;
2176
+ function Sr() {
2177
+ return {
2178
+ isAuthenticated: !1,
2179
+ isOverlayVisible: !0,
2180
+ isCommentModeActive: !1,
2181
+ isDrawingModeActive: !1,
2182
+ isHighlightModeActive: !1,
2183
+ isScreenshotModeActive: !1,
2184
+ isSidebarVisible: !1,
2185
+ isLoginModalVisible: !1,
2186
+ isShortcutsOverlayVisible: !1,
2187
+ currentUser: null,
2188
+ project: null,
2189
+ comments: [],
2190
+ activeTool: null,
2191
+ selectedComment: null,
2192
+ activeComment: null,
2193
+ activeDrawing: null,
2194
+ activeScreenshot: null,
2195
+ onlineUsers: [],
2196
+ connectionStatus: "disconnected",
2197
+ activities: [],
2198
+ seenThreadIds: /* @__PURE__ */ new Set(),
2199
+ panelView: "list",
2200
+ isLoading: !1,
2201
+ error: null,
2202
+ otpStep: "idle",
2203
+ otpEmail: null,
2204
+ pagination: null,
2205
+ pendingMutations: [],
2206
+ isOnline: br()
2207
+ };
2208
+ }
2209
+ var Cr = c.PENDING_MUTATIONS, wr = c.RETRY_DELAY, X = c.ID, Tr = c.CONTENT, Er = c.REPLY_CONTENT, Dr = c.SELECTOR, Or = c.EMOJI, kr = new Set([
2210
+ "createComment",
2211
+ "createHighlight",
2212
+ "createDrawing",
2213
+ "updateComment",
2214
+ "deleteComment",
2215
+ "resolveComment",
2216
+ "unresolveComment",
2217
+ "completeComment",
2218
+ "addReply",
2219
+ "reactToComment",
2220
+ "updatePosition"
2221
+ ]), Ar = new Set([
2222
+ "pin",
2223
+ "highlight",
2224
+ "drawing"
2225
+ ]), jr = new Set([
2226
+ "low",
2227
+ "medium",
2228
+ "high",
2229
+ "urgent"
2230
+ ]), Mr = new Set(["add", "remove"]);
2231
+ function Nr(e) {
2232
+ return s(e) && a(e.x) && a(e.y) && r(e.element, Dr) && r(e.xpath, Dr);
2233
+ }
2234
+ function Pr(e) {
2235
+ return typeof e == "string" && e.length <= c.PAGE && !o(e);
2236
+ }
2237
+ function Fr(e) {
2238
+ return e === void 0 ? !0 : s(e) && Pr(e.url) && Pr(e.path) && Pr(e.title);
2239
+ }
2240
+ function Ir(e) {
2241
+ return typeof e == "string" && kr.has(e);
2242
+ }
2243
+ function Lr(e) {
2244
+ return Number.isInteger(e) && Number(e) >= 0;
2245
+ }
2246
+ function Rr(e) {
2247
+ return Lr(e) ? Math.min(e, 5) : 0;
2248
+ }
2249
+ function zr(e) {
2250
+ return e.isNetworkError() || e.code === 408 || e.isRateLimitError();
2251
+ }
2252
+ function Br(e) {
2253
+ return e instanceof M ? zr(e) : !0;
2254
+ }
2255
+ function Vr(e) {
2256
+ return e instanceof M ? {
2257
+ error: e.error,
2258
+ message: e.message,
2259
+ code: e.code,
2260
+ ...e.details ? { details: e.details } : {}
2261
+ } : {
2262
+ error: "retry_failed",
2263
+ message: "Operation failed after maximum retries",
2264
+ code: 0
2265
+ };
2266
+ }
2267
+ function Hr(e = Date.now()) {
2268
+ return `mutation_${e}_${typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : Math.random().toString(36).slice(2, 12)}`;
2269
+ }
2270
+ function Ur(e) {
2271
+ return Array.isArray(e) ? e.map((e) => Ur(e)) : s(e) ? Object.fromEntries(Object.entries(e).map(([e, t]) => [e, Ur(t)])) : e;
2272
+ }
2273
+ function Wr(e) {
2274
+ try {
2275
+ if (typeof structuredClone == "function") return structuredClone(e);
2276
+ } catch {}
2277
+ return Ur(e);
2278
+ }
2279
+ function Gr(t, n) {
2280
+ switch (t) {
2281
+ case "createComment": {
2282
+ let [t, r, i, a, o, c, l, u] = n;
2283
+ return n.length >= 3 && n.length <= 8 && Ar.has(String(t)) && e(r, Tr) && Nr(i) && (a === void 0 || jr.has(String(a))) && (o === void 0 || s(o)) && (c === void 0 || s(c)) && (l === void 0 || s(l)) && Fr(u);
2284
+ }
2285
+ case "createHighlight": {
2286
+ let [t, r, i] = n;
2287
+ return n.length >= 2 && n.length <= 3 && e(t, Tr) && s(r) && Fr(i);
2288
+ }
2289
+ case "createDrawing": {
2290
+ let [t, r, i, a] = n;
2291
+ return n.length >= 3 && n.length <= 4 && e(t, Tr) && s(r) && Nr(i) && Fr(a);
2292
+ }
2293
+ case "updateComment": return n.length === 2 && l(n[0], X) && s(n[1]);
2294
+ case "deleteComment":
2295
+ case "resolveComment":
2296
+ case "unresolveComment":
2297
+ case "completeComment": return n.length === 1 && l(n[0], X);
2298
+ case "addReply": return n.length === 2 && l(n[0], X) && e(n[1], Er);
2299
+ case "reactToComment": return n.length >= 2 && n.length <= 3 && l(n[0], X) && l(n[1], Or) && (n[2] === void 0 || Mr.has(String(n[2])));
2300
+ case "updatePosition": return n.length === 2 && l(n[0], X) && Nr(n[1]);
2301
+ }
2302
+ }
2303
+ function Kr(e) {
2304
+ return s(e) ? l(e.id, X) ? Ir(e.type) ? Array.isArray(e.args) ? Number.isFinite(e.timestamp) ? Lr(e.retries) ? r(e.tempId, X) ? Gr(e.type, e.args) ? null : "Queued mutation args are invalid" : "Queued mutation has an invalid temp id" : "Queued mutation has an invalid retry count" : "Queued mutation has an invalid timestamp" : "Queued mutation args must be an array" : "Queued mutation has an unsupported type" : "Queued mutation has an invalid id" : "Queued mutation must be an object";
2305
+ }
2306
+ function qr(e) {
2307
+ let t = Kr(e);
2308
+ if (t) throw new M("invalid_mutation", t, 400);
2309
+ }
2310
+ var Jr = "commentkit:offline-queue:";
2311
+ function Yr() {
2312
+ try {
2313
+ return typeof localStorage > "u" ? null : localStorage;
2314
+ } catch {
2315
+ return null;
2316
+ }
2317
+ }
2318
+ function Xr(e) {
2319
+ return `${Jr}${e}`;
2320
+ }
2321
+ function Zr(e, t) {
2322
+ if (!e) return;
2323
+ let n = Yr();
2324
+ if (n) try {
2325
+ t.length === 0 ? n.removeItem(Xr(e)) : n.setItem(Xr(e), JSON.stringify(t));
2326
+ } catch {}
2327
+ }
2328
+ function Qr(e) {
2329
+ if (!e) return [];
2330
+ let t = Yr();
2331
+ if (!t) return [];
2332
+ try {
2333
+ let n = t.getItem(Xr(e));
2334
+ if (!n) return [];
2335
+ let r = JSON.parse(n);
2336
+ if (!Array.isArray(r)) return [];
2337
+ let i = [];
2338
+ for (let e of r) {
2339
+ if (i.length >= Cr) break;
2340
+ Kr(e) === null && i.push(e);
2341
+ }
2342
+ return i;
2343
+ } catch {
2344
+ return [];
2345
+ }
2346
+ }
2347
+ function Z(e) {
2348
+ Promise.resolve().then(e);
2349
+ }
2350
+ function $r(e, t) {
2351
+ return e.type === t.type ? (t.type === "updatePosition" || t.type === "updateComment") && e.args[0] === t.args[0] : !1;
2352
+ }
2353
+ function ei(e, t) {
2354
+ return t.type === "updateComment" && s(e.args[1]) ? {
2355
+ ...t,
2356
+ args: [t.args[0], {
2357
+ ...e.args[1],
2358
+ ...t.args[1]
2359
+ }]
2360
+ } : t;
2361
+ }
2362
+ function ti(e, t) {
2363
+ let n = e.findIndex((e) => $r(e, t));
2364
+ if (n !== -1) {
2365
+ let r = [...e];
2366
+ return r[n] = ei(r[n], t), r;
2367
+ }
2368
+ return e.length >= Cr ? null : [...e, t];
2369
+ }
2370
+ function ni(e, t, n) {
2371
+ e.emit("offline:failed", {
2372
+ id: t,
2373
+ error: n
2374
+ });
2375
+ }
2376
+ function ri(e, t) {
2377
+ return e.isOnline ? t instanceof M ? zr(t) : !1 : !0;
2378
+ }
2379
+ function ii(e, t, n, i, a) {
2380
+ let o = Hr();
2381
+ if (!Ir(n) || !Array.isArray(i) || !Gr(n, i) || !r(a, X)) return ni(e, o, {
2382
+ error: "invalid_mutation",
2383
+ message: "Queued mutation args are invalid",
2384
+ code: 400
2385
+ }), !1;
2386
+ let s = {
2387
+ id: o,
2388
+ type: n,
2389
+ args: Wr(i),
2390
+ timestamp: Date.now(),
2391
+ retries: 0,
2392
+ ...a === void 0 ? {} : { tempId: a }
2393
+ }, c = ti(e.getState().pendingMutations, s);
2394
+ return c ? (e.setState({ pendingMutations: c }), e.emit("offline:queued", s), e.getState().isOnline && Z(t), !0) : (ni(e, o, {
2395
+ error: "queue_full",
2396
+ message: "Offline mutation queue is full",
2397
+ code: 0
2398
+ }), !1);
2399
+ }
2400
+ function ai(e, t, n) {
2401
+ if (t.current || e.getState().pendingMutations.length === 0) return;
2402
+ let r = e.getState().pendingMutations[0];
2403
+ if (!r) return;
2404
+ let i = Rr(r.retries), a = Math.min(wr, xr * 2 ** i);
2405
+ t.current = setTimeout(() => {
2406
+ t.current = null, n();
2407
+ }, a);
2408
+ }
2409
+ async function oi(e, t, n, r) {
2410
+ let i = e.getState();
2411
+ if (!i.isOnline || i.pendingMutations.length === 0 || !i.isAuthenticated || t.current) return;
2412
+ t.current = !0;
2413
+ let a = e.getState().pendingMutations[0];
2414
+ if (!a) {
2415
+ t.current = !1;
2416
+ return;
2417
+ }
2418
+ let o = Kr(a);
2419
+ if (o) {
2420
+ let r = e.getState().pendingMutations.filter((e) => e !== a);
2421
+ e.setState({ pendingMutations: r }), ni(e, l(a.id, X) ? a.id : "invalid", {
2422
+ error: "invalid_mutation",
2423
+ message: o,
2424
+ code: 400
2425
+ }), r.length > 0 && Z(n), t.current = !1;
2426
+ return;
2427
+ }
2428
+ e.emit("offline:retrying", {
2429
+ id: a.id,
2430
+ attempt: a.retries + 1
2431
+ });
2432
+ let s = r ?? ((t) => ci(e, t));
2433
+ try {
2434
+ await s(a);
2435
+ let r = e.getState().pendingMutations.filter((e) => e.id !== a.id);
2436
+ e.setState({ pendingMutations: r }), e.emit("offline:completed", { id: a.id }), r.length > 0 ? Z(n) : t.reconcileAfterDrain && (t.reconcileAfterDrain = !1, K(e));
2437
+ } catch (r) {
2438
+ let i = {
2439
+ ...a,
2440
+ retries: Rr(a.retries) + 1
2441
+ };
2442
+ if (Br(r) && i.retries < 5) {
2443
+ let t = e.getState().pendingMutations.map((e) => e.id === a.id ? i : e);
2444
+ e.setState({ pendingMutations: t }), Z(n);
2445
+ } else {
2446
+ let i = e.getState().pendingMutations.filter((e) => e.id !== a.id);
2447
+ e.setState({ pendingMutations: i }), ni(e, a.id, Vr(r)), i.length > 0 ? (t.reconcileAfterDrain = !0, Z(n)) : (t.reconcileAfterDrain = !1, K(e));
2448
+ }
2449
+ } finally {
2450
+ t.current = !1;
2451
+ }
2452
+ }
2453
+ function si(e, t, n) {
2454
+ let r = !1, i = e.getState().pendingMutations.map((e) => e.type !== "createComment" && e.args[0] === t ? (r = !0, {
2455
+ ...e,
2456
+ args: [n, ...e.args.slice(1)]
2457
+ }) : e);
2458
+ r && e.setState({ pendingMutations: i });
2459
+ }
2460
+ async function ci(e, t) {
2461
+ switch (qr(t), t.type) {
2462
+ case "createComment": {
2463
+ let [n, r, i, a, o, s, c, l] = t.args, d = await e.apiClient.createComment(n, r, i, l ?? u(), a, o, s, c, t.tempId);
2464
+ d && t.tempId && (G(e, t.tempId, d), si(e, t.tempId, d.id));
2465
+ break;
2466
+ }
2467
+ case "createHighlight": {
2468
+ let [n, r, i] = t.args, a = await e.apiClient.createHighlight(n, r, i ?? u(), "medium", t.tempId);
2469
+ a && t.tempId && (G(e, t.tempId, a), si(e, t.tempId, a.id));
2470
+ break;
2471
+ }
2472
+ case "createDrawing": {
2473
+ let [n, r, i, a] = t.args, o = await e.apiClient.createDrawing(n, r, i, a ?? u(), t.tempId);
2474
+ o && t.tempId && (G(e, t.tempId, o), si(e, t.tempId, o.id));
2475
+ break;
2476
+ }
2477
+ case "updateComment": {
2478
+ let [n, r] = t.args;
2479
+ await e.apiClient.updateComment(n, r);
2480
+ break;
2481
+ }
2482
+ case "deleteComment": {
2483
+ let [n] = t.args;
2484
+ await e.apiClient.deleteComment(n);
2485
+ break;
2486
+ }
2487
+ case "resolveComment": {
2488
+ let [n] = t.args;
2489
+ await e.apiClient.resolveComment(n);
2490
+ break;
2491
+ }
2492
+ case "unresolveComment": {
2493
+ let [n] = t.args;
2494
+ await e.apiClient.unresolveComment(n);
2495
+ break;
2496
+ }
2497
+ case "completeComment": {
2498
+ let [n] = t.args;
2499
+ await e.apiClient.markComplete(n);
2500
+ break;
2501
+ }
2502
+ case "addReply": {
2503
+ let [n, r] = t.args, i = await e.apiClient.addReply(n, r, t.tempId);
2504
+ i && t.tempId && Kt(e, n, t.tempId, i);
2505
+ break;
2506
+ }
2507
+ case "reactToComment": {
2508
+ let [n, r, i] = t.args, a;
2509
+ a = i === "add" || i === "remove" ? i === "remove" : e.getState().comments.find((e) => e.id === n)?.reactions?.find((e) => e.emoji === r)?.reacted === !0, a ? await e.apiClient.removeReaction(n, r) : await e.apiClient.addReaction(n, r);
2510
+ break;
2511
+ }
2512
+ case "updatePosition": {
2513
+ let [n, r] = t.args;
2514
+ await e.apiClient.updatePosition(n, r);
2515
+ break;
2516
+ }
2517
+ }
2518
+ }
2519
+ var Q = null;
2520
+ async function li() {
2521
+ return Q || (Q = await import("./vue/realtime-YJKvS2eB.js"), Q);
2522
+ }
2523
+ var ui = typeof window < "u", di = new Set([
2524
+ "list",
2525
+ "detail",
2526
+ "settings",
2527
+ "activity",
2528
+ "dev-export"
2529
+ ]), fi = new Set([
2530
+ "comment",
2531
+ "draw",
2532
+ "highlight",
2533
+ "screenshot",
2534
+ "select",
2535
+ null
2536
+ ]), pi = 256, mi = "0.6.1";
2537
+ function hi(e) {
2538
+ let t = e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);
2539
+ return t ? [
2540
+ Number(t[1]),
2541
+ Number(t[2] ?? 0),
2542
+ Number(t[3] ?? 0)
2543
+ ] : null;
2544
+ }
2545
+ function gi(e) {
2546
+ return /^v?\d+(?:\.\d+)?(?:\.\d+)?-/.test(e.trim());
2547
+ }
2548
+ function _i(e, t) {
2549
+ if (gi(e)) return !1;
2550
+ let n = hi(e), r = hi(t);
2551
+ if (!n || !r) return !1;
2552
+ for (let e = 0; e < 3; e++) {
2553
+ let t = n[e] ?? 0, i = r[e] ?? 0;
2554
+ if (t > i) return !0;
2555
+ if (t < i) return !1;
2556
+ }
2557
+ return !1;
2558
+ }
2559
+ var vi = class extends ee {
2560
+ get isProcessingQueue() {
2561
+ return this.queueGuard.current;
2562
+ }
2563
+ set isProcessingQueue(e) {
2564
+ this.queueGuard.current = e;
2565
+ }
2566
+ get isLoadingMore() {
2567
+ return this.loadMoreGuard.current;
2568
+ }
2569
+ set isLoadingMore(e) {
2570
+ this.loadMoreGuard.current = e;
2571
+ }
2572
+ get retryTimer() {
2573
+ return this.retryTimerRef.current;
2574
+ }
2575
+ set retryTimer(e) {
2576
+ this.retryTimerRef.current = e;
2577
+ }
2578
+ constructor(e) {
2579
+ super(), this.wsManager = null, this.wsUnsubscribers = [], this.keyboardHandler = null, this.holdActivationHandler = null, this.holdBlurHandler = null, this.toggleHandler = null, this.mouseMoveHandler = null, this.hashChangeHandler = null, this.onlineHandler = null, this.offlineHandler = null, this.initialized = !1, this.destroyed = !1, this.screenshotProvider = null, this.bootRetryTimer = null, this.bootAttempts = 0, this.pendingStateUpdates = null, this.flushScheduled = !1, this.isFlushing = !1, this.queueGuard = { current: !1 }, this.activeMutations = /* @__PURE__ */ new Set(), this.sliceSubscribers = /* @__PURE__ */ new Map(), this.retryTimerRef = { current: null }, this.otpFailedAttempts = 0, this.otpCooldownUntil = 0, this.overlayBeforeTool = null, this.loadMoreGuard = { current: !1 }, this.offlinePersistUnsub = null, this.escapeBlockers = /* @__PURE__ */ new Set(), this.config = { ...e }, ui && !this.config.environment && (this.config.environment = this.detectEnvironment()), this.apiClient = new me(this.config), this.apiClient.setOnAuthExpired(() => this.handleAuthExpired()), this.state = Sr(), this.screenshotProvider = e.screenshotProvider || null, this.ctx = {
2580
+ getState: () => this.getInternalState(),
2581
+ setState: (e) => this.setState(e),
2582
+ apiClient: this.apiClient,
2583
+ emit: (e, t) => {
2584
+ this.destroyed || this.emit(e, t);
2585
+ },
2586
+ handleError: (e) => this.handleError(e),
2587
+ config: this.config
2588
+ }, this.kbdCallbacks = {
2589
+ toggleLoginModal: () => this.toggleLoginModal(),
2590
+ toggleOverlay: () => this.toggleOverlay(),
2591
+ toggleSidebar: () => this.toggleSidebar(),
2592
+ toggleShortcutsOverlay: () => this.toggleShortcutsOverlay(),
2593
+ setTool: (e) => this.setTool(e),
2594
+ selectComment: (e) => this.selectComment(e),
2595
+ setState: (e) => this.setState(e)
2596
+ }, this.commentCb = {
2597
+ shouldQueueMutation: (e) => this.shouldQueueMutation(e),
2598
+ queueMutation: (e, t, n) => this.queueMutation(e, t, n),
2599
+ addActivity: (e) => this.addActivity(e)
2600
+ }, this.realtimeRefs = {
2601
+ wsManager: this.wsManager,
2602
+ wsUnsubscribers: this.wsUnsubscribers,
2603
+ mouseMoveHandler: this.mouseMoveHandler
2604
+ }, e.enabled !== !1 && ui && Promise.resolve().then(() => this.boot()).catch((e) => this.handleError(e));
2605
+ /* v8 ignore stop */
2606
+ }
2607
+ detectEnvironment() {
2608
+ let e = window.location.hostname;
2609
+ return e === "localhost" || e === "127.0.0.1" || e === "[::1]" || e.endsWith(".localhost") ? "development" : e.endsWith(".vercel.app") || e.endsWith(".netlify.app") || e.endsWith(".pages.dev") || e.includes("-preview.") || e.endsWith("-preview") || /-preview-\d/.test(e) ? "preview" : e.startsWith("staging.") || e.startsWith("stage.") || e.includes(".staging.") || e.endsWith(".staging") ? "staging" : "production";
2610
+ }
2611
+ async boot() {
2612
+ if (this.destroyed) return;
2613
+ this.keyboardHandler = this.handleKeyboardShortcuts.bind(this), window.addEventListener("keydown", this.keyboardHandler, !0);
2614
+ let e = this.config.ui?.activation;
2615
+ e?.mode === "hold" && e.key && (this.holdActivationHandler = (e) => {
2616
+ if (this.destroyed || !this.matchesHoldKey(e)) return;
2617
+ let t = this.getInternalState().activeTool;
2618
+ e.type === "keydown" && !t ? this.setTool("select") : e.type === "keyup" && t === "select" && this.setTool(null);
2619
+ }, window.addEventListener("keydown", this.holdActivationHandler), window.addEventListener("keyup", this.holdActivationHandler), this.holdBlurHandler = () => {
2620
+ this.destroyed || this.getInternalState().activeTool === "select" && this.setTool(null);
2621
+ }, window.addEventListener("blur", this.holdBlurHandler)), this.toggleHandler = () => this.handleToggleRequest(), window.addEventListener("commentkit:toggle-overlay", this.toggleHandler), this.hashChangeHandler = () => this.handleDeepLink(), window.addEventListener("hashchange", this.hashChangeHandler), this.handleDeepLink(), this.onlineHandler = () => {
2622
+ this.destroyed || (this.setState({ isOnline: !0 }), this.processOfflineQueue());
2623
+ }, this.offlineHandler = () => {
2624
+ this.destroyed || this.setState({ isOnline: !1 });
2625
+ }, window.addEventListener("online", this.onlineHandler), window.addEventListener("offline", this.offlineHandler), this.autoDetectInviteToken(), this.config.apiKey && await this.initialize();
2626
+ }
2627
+ autoDetectInviteToken() {
2628
+ try {
2629
+ let e = new URLSearchParams(window.location.search), t = e.get("ck_invite");
2630
+ if (!t) return;
2631
+ /^[\w-]{64}$/.test(t) && (this.config.inviteToken = t), e.delete("ck_invite");
2632
+ let n = e.toString(), r = window.location.pathname + (n ? `?${n}` : "") + window.location.hash;
2633
+ window.history.replaceState(window.history.state, "", r);
2634
+ } catch {}
2635
+ }
2636
+ async initialize() {
2637
+ if (!(this.initialized || this.destroyed)) {
2638
+ this.initialized = !0, this.bootAttempts += 1;
2639
+ try {
2640
+ this.setState({
2641
+ isLoading: !0,
2642
+ error: null
2643
+ });
2644
+ let e = await this.apiClient.validateApiKey();
2645
+ if (this.destroyed) return;
2646
+ if (!e.valid) {
2647
+ this.handleError({
2648
+ error: "invalid_api_key",
2649
+ message: "Invalid API key",
2650
+ code: 401
2651
+ });
2652
+ return;
2653
+ }
2654
+ e.project?.id && (this.config.projectId = String(e.project.id), this.hydrateOfflineQueue());
2655
+ let t = e.project?.slug ?? e.project?.id;
2656
+ if (t && this.apiClient.setProject(String(t)), e.project?.features && (this.config.features = e.project.features), e.project?.reverb && e.project.features?.realtime) {
2657
+ let t = e.project.reverb;
2658
+ this.config.reverb = {
2659
+ key: t.key,
2660
+ host: t.host,
2661
+ port: t.port ?? 443,
2662
+ scheme: t.scheme ?? "wss"
2663
+ };
2664
+ }
2665
+ let n = e.project?.sdkLatestVersion;
2666
+ n && _i(n, "0.6.1") && (console.warn(`[CommentKit] You are using v${mi}. Update to v${n}: npm update comment-kit`), this.emit("sdk:outdated", {
2667
+ current: mi,
2668
+ latest: n
2669
+ })), this.setState({
2670
+ project: e.project,
2671
+ isLoading: !1
2672
+ }), await this.restorePersistedSession();
2673
+ } catch (e) {
2674
+ if (this.initialized = !1, this.handleError(e), this.bootAttempts < 3 && !this.destroyed) {
2675
+ let e = 2e3 * 2 ** (this.bootAttempts - 1);
2676
+ this.bootRetryTimer = setTimeout(() => {
2677
+ this.bootRetryTimer = null, this.initialize();
2678
+ }, e);
2679
+ }
2680
+ }
2681
+ }
2682
+ }
2683
+ setState(e) {
2684
+ this.destroyed || (this.pendingStateUpdates ? Object.assign(this.pendingStateUpdates, e) : this.pendingStateUpdates = { ...e }, this.flushScheduled || (this.flushScheduled = !0, Promise.resolve().then(() => this.flushState())));
2685
+ }
2686
+ getInternalState() {
2687
+ return this.pendingStateUpdates ? {
2688
+ ...this.state,
2689
+ ...this.pendingStateUpdates
2690
+ } : this.state;
2691
+ }
2692
+ cloneStateSnapshot(e) {
2693
+ return {
2694
+ ...e,
2695
+ currentUser: e.currentUser ? structuredClone(e.currentUser) : null,
2696
+ project: e.project ? structuredClone(e.project) : null,
2697
+ comments: structuredClone(e.comments),
2698
+ selectedComment: e.selectedComment ? structuredClone(e.selectedComment) : null,
2699
+ activeComment: e.activeComment ? structuredClone(e.activeComment) : null,
2700
+ activeDrawing: e.activeDrawing ? structuredClone(e.activeDrawing) : null,
2701
+ activeScreenshot: e.activeScreenshot ? {
2702
+ ...e.activeScreenshot,
2703
+ dimensions: { ...e.activeScreenshot.dimensions }
2704
+ } : null,
2705
+ onlineUsers: structuredClone(e.onlineUsers),
2706
+ pendingMutations: structuredClone(e.pendingMutations),
2707
+ activities: structuredClone(e.activities),
2708
+ seenThreadIds: new Set(e.seenThreadIds),
2709
+ pagination: e.pagination ? { ...e.pagination } : null
2710
+ };
2711
+ }
2712
+ flushState() {
2713
+ if (this.destroyed) {
2714
+ this.pendingStateUpdates = null, this.flushScheduled = !1;
2715
+ return;
2716
+ }
2717
+ if (this.isFlushing) return;
2718
+ this.flushScheduled = !1;
2719
+ let e = this.pendingStateUpdates;
2720
+ if (!e) return;
2721
+ this.pendingStateUpdates = null;
2722
+ let t = this.state;
2723
+ this.state = {
2724
+ ...t,
2725
+ ...e
2726
+ }, this.isFlushing = !0;
2727
+ try {
2728
+ this.notifySubscribers(e, t);
2729
+ } finally {
2730
+ this.isFlushing = !1;
2731
+ }
2732
+ this.pendingStateUpdates && !this.flushScheduled && (this.flushScheduled = !0, Promise.resolve().then(() => this.flushState()));
2733
+ }
2734
+ notifySubscribers(e, t) {
2735
+ e.activeTool !== void 0 && e.activeTool !== t.activeTool && this.emit("tool:changed", e.activeTool), e.isOverlayVisible !== void 0 && e.isOverlayVisible !== t.isOverlayVisible && this.emit("overlay:toggled", e.isOverlayVisible), e.isSidebarVisible !== void 0 && e.isSidebarVisible !== t.isSidebarVisible && this.emit("sidebar:toggled", e.isSidebarVisible), e.isLoginModalVisible !== void 0 && e.isLoginModalVisible !== t.isLoginModalVisible && this.emit("loginmodal:toggled", e.isLoginModalVisible), e.isShortcutsOverlayVisible !== void 0 && e.isShortcutsOverlayVisible !== t.isShortcutsOverlayVisible && this.emit("shortcuts:toggled", e.isShortcutsOverlayVisible), e.connectionStatus !== void 0 && e.connectionStatus !== t.connectionStatus && this.emit("connection:changed", e.connectionStatus);
2736
+ let n = Object.keys(e);
2737
+ for (let [e, t] of this.sliceSubscribers) {
2738
+ let r = yr[e];
2739
+ if (n.some((e) => r.includes(e))) for (let n of t) try {
2740
+ n(this.state);
2741
+ } catch (t) {
2742
+ console.error(`[CommentKit] Error in ${e} slice subscriber:`, t);
2743
+ }
2744
+ }
2745
+ this.emit("state:changed", this.state);
2746
+ }
2747
+ flushStateSync() {
2748
+ this.pendingStateUpdates && !this.isFlushing && this.flushState();
2749
+ }
2750
+ getState() {
2751
+ return this.flushStateSync(), this.cloneStateSnapshot(this.state);
2752
+ }
2753
+ getFeatures() {
2754
+ return {
2755
+ comments: this.config.features?.comments ?? !0,
2756
+ drawing: this.config.features?.drawing ?? !0,
2757
+ highlighting: this.config.features?.highlighting ?? !0,
2758
+ screenshots: this.config.features?.screenshots ?? !0,
2759
+ realtime: this.config.features?.realtime ?? !0
2760
+ };
2761
+ }
2762
+ getConfig() {
2763
+ return {
2764
+ apiKey: this.config.apiKey,
2765
+ ...this.config.baseUrl !== void 0 && { baseUrl: this.config.baseUrl },
2766
+ ...this.config.enabled !== void 0 && { enabled: this.config.enabled },
2767
+ screenshotProvider: this.config.screenshotProvider,
2768
+ ui: this.config.ui ? { ...this.config.ui } : void 0
2769
+ };
2770
+ }
2771
+ async validateInvite(e) {
2772
+ if (!this.destroyed) return yt(this.ctx, e, (e) => this.login(e));
2773
+ }
2774
+ onSlice(e, t) {
2775
+ if (!yr[e] || typeof t != "function" || this.destroyed) return () => {};
2776
+ let n = this.sliceSubscribers.get(e);
2777
+ return n || (n = /* @__PURE__ */ new Set(), this.sliceSubscribers.set(e, n)), n.add(t), () => n.delete(t);
2778
+ }
2779
+ select(e, t) {
2780
+ if (typeof e != "function" || typeof t != "function" || this.destroyed) return () => {};
2781
+ let n;
2782
+ try {
2783
+ n = e(this.getInternalState());
2784
+ } catch (e) {
2785
+ return this.handleError(e), () => {};
2786
+ }
2787
+ return this.on("state:changed", (r) => {
2788
+ try {
2789
+ let i = e(r);
2790
+ i !== n && (n = i, t(i));
2791
+ } catch (e) {
2792
+ this.handleError(e);
2793
+ }
2794
+ });
2795
+ }
2796
+ handleError(e) {
2797
+ if (this.destroyed) return;
2798
+ let t = e && typeof e == "object" ? e : null, n = typeof t?.message == "string" && t.message ? t.message : String(e ?? "Unknown error"), r = {
2799
+ error: typeof t?.error == "string" && t.error ? t.error : "unknown",
2800
+ message: n,
2801
+ code: typeof t?.code == "number" && Number.isFinite(t.code) ? t.code : 0,
2802
+ ...t?.details && typeof t.details == "object" ? { details: t.details } : {}
2803
+ };
2804
+ console.error("[CommentKit]", r.message), this.setState({
2805
+ error: r.message,
2806
+ isLoading: !1
2807
+ }), this.emit("error", r);
2808
+ }
2809
+ async restorePersistedSession() {
2810
+ if (this.destroyed) return;
2811
+ let e = et(this.config.projectId);
2812
+ if (e) try {
2813
+ this.apiClient.setAuthToken(e.token), this.apiClient.setUserEmail(e.email), this.setState({
2814
+ currentUser: e.user,
2815
+ isAuthenticated: !0,
2816
+ isLoginModalVisible: !1,
2817
+ otpStep: "idle",
2818
+ otpEmail: null,
2819
+ error: null
2820
+ }), this.emit("auth:login", e.user), await this.afterAuthenticated();
2821
+ } catch {
2822
+ this.handleAuthExpired();
2823
+ }
2824
+ }
2825
+ async afterAuthenticated() {
2826
+ this.destroyed || (this.getFeatures().realtime && this.initializeWebSocket(), await this.loadComments(), this.handleDeepLink(), this.getInternalState().pendingMutations.length > 0 && this.scheduleRetry());
2827
+ }
2828
+ async login(e) {
2829
+ if (!this.destroyed) return ft(this.ctx, e);
2830
+ }
2831
+ async verifyOtp(e) {
2832
+ if (this.destroyed) return;
2833
+ let t = Date.now();
2834
+ if (t < this.otpCooldownUntil) {
2835
+ let e = Math.ceil((this.otpCooldownUntil - t) / 1e3);
2836
+ this.handleError({
2837
+ error: "otp_throttled",
2838
+ message: `Too many attempts. Please wait ${e}s and try again.`,
2839
+ code: 429
2840
+ });
2841
+ return;
2842
+ }
2843
+ return pt(this.ctx, e, {
2844
+ onAuthenticated: async () => {
2845
+ await this.afterAuthenticated();
2846
+ },
2847
+ onSuccess: () => {
2848
+ this.otpFailedAttempts = 0, this.otpCooldownUntil = 0;
2849
+ },
2850
+ onWrongOtp: () => {
2851
+ if (this.otpFailedAttempts += 1, this.otpFailedAttempts >= 3) {
2852
+ let e = Math.min(3e4, 2e3 * 2 ** (this.otpFailedAttempts - 3));
2853
+ this.otpCooldownUntil = Date.now() + e;
2854
+ }
2855
+ }
2856
+ });
2857
+ }
2858
+ cancelOtp() {
2859
+ this.destroyed || mt(this.ctx);
2860
+ }
2861
+ async resendOtp() {
2862
+ if (!this.destroyed) return ht(this.ctx);
2863
+ }
2864
+ logout() {
2865
+ this.destroyed || (this.overlayBeforeTool = null, gt(this.ctx, () => {
2866
+ this.disconnectRealtime(!0);
2867
+ }));
2868
+ }
2869
+ handleAuthExpired() {
2870
+ this.overlayBeforeTool = null, this.disconnectRealtime(!0), _t(this.ctx);
2871
+ }
2872
+ toggleLoginModal() {
2873
+ this.destroyed || vt(this.ctx);
2874
+ }
2875
+ toggleOverlay() {
2876
+ if (this.destroyed) return;
2877
+ let e = !this.getInternalState().isOverlayVisible;
2878
+ this.overlayBeforeTool = null, this.setState({
2879
+ isOverlayVisible: e,
2880
+ ...!e && {
2881
+ selectedComment: null,
2882
+ activeComment: null
2883
+ }
2884
+ });
2885
+ }
2886
+ toggleSidebar() {
2887
+ this.destroyed || this.setState({ isSidebarVisible: !this.getInternalState().isSidebarVisible });
2888
+ }
2889
+ setTool(e) {
2890
+ if (this.destroyed || !fi.has(e)) return;
2891
+ let t = this.getInternalState();
2892
+ if (!t.isAuthenticated && e !== "select" && e !== null) {
2893
+ this.toggleLoginModal();
2894
+ return;
2895
+ }
2896
+ let n;
2897
+ e === null ? (n = this.overlayBeforeTool ?? t.isOverlayVisible, this.overlayBeforeTool = null) : (this.overlayBeforeTool === null && (this.overlayBeforeTool = t.isOverlayVisible), n = !1), this.setState({
2898
+ activeTool: e,
2899
+ isCommentModeActive: e === "comment",
2900
+ isDrawingModeActive: e === "draw",
2901
+ isHighlightModeActive: e === "highlight",
2902
+ isScreenshotModeActive: e === "screenshot",
2903
+ isOverlayVisible: n,
2904
+ selectedComment: null,
2905
+ activeComment: null,
2906
+ activeDrawing: null,
2907
+ activeScreenshot: null
2908
+ });
2909
+ }
2910
+ async loadComments() {
2911
+ return K(this.ctx);
2912
+ }
2913
+ async loadMoreComments() {
2914
+ this.destroyed || await Jt(this.ctx, this.loadMoreGuard);
2915
+ }
2916
+ async reloadComments() {
2917
+ if (!this.destroyed) return K(this.ctx);
2918
+ }
2919
+ async createComment(e, t, n, r = "medium", i, a, o) {
2920
+ if (!this.destroyed) return Yt(this.ctx, this.commentCb, this.activeMutations, e, t, n, r, i, a, o);
2921
+ }
2922
+ async updateComment(e, t) {
2923
+ if (!this.destroyed) return Xt(this.ctx, this.commentCb, e, t);
2924
+ }
2925
+ async deleteComment(e) {
2926
+ if (!this.destroyed) return Zt(this.ctx, this.commentCb, e);
2927
+ }
2928
+ async addReply(e, t) {
2929
+ if (!this.destroyed) return Qt(this.ctx, this.commentCb, e, t);
2930
+ }
2931
+ async updateReply(e, t, n) {
2932
+ if (!this.destroyed) return $t(this.ctx, e, t, n);
2933
+ }
2934
+ async deleteReply(e, t) {
2935
+ if (!this.destroyed) return en(this.ctx, e, t);
2936
+ }
2937
+ async resolveComment(e) {
2938
+ if (!this.destroyed) return tn(this.ctx, this.commentCb, e);
2939
+ }
2940
+ async unresolveComment(e) {
2941
+ if (!this.destroyed) return nn(this.ctx, this.commentCb, e);
2942
+ }
2943
+ selectComment(e) {
2944
+ this.destroyed || sn(this.ctx, e);
2945
+ }
2946
+ async completeComment(e) {
2947
+ if (!this.destroyed) return rn(this.ctx, this.commentCb, e);
2948
+ }
2949
+ async reactToComment(e, t) {
2950
+ if (!this.destroyed) return an(this.ctx, this.commentCb, e, t);
2951
+ }
2952
+ async updateCommentPosition(e, t, n) {
2953
+ if (!this.destroyed) return on(this.ctx, this.commentCb, e, t, n);
2954
+ }
2955
+ hydrateOfflineQueue() {
2956
+ let e = Qr(this.config.projectId);
2957
+ if (e.length > 0) {
2958
+ let t = this.getInternalState().pendingMutations, n = new Set(t.map((e) => e.id)), r = [...t, ...e.filter((e) => !n.has(e.id))];
2959
+ this.setState({ pendingMutations: r }), this.getInternalState().isOnline && this.scheduleRetry();
2960
+ }
2961
+ this.offlinePersistUnsub?.(), this.offlinePersistUnsub = this.select((e) => e.pendingMutations, (e) => Zr(this.config.projectId, e));
2962
+ }
2963
+ shouldQueueMutation(e) {
2964
+ return ri(this.getInternalState(), e);
2965
+ }
2966
+ queueMutation(e, t, n) {
2967
+ return ii(this.ctx, () => this.scheduleRetry(), e, t, n);
2968
+ }
2969
+ scheduleRetry() {
2970
+ ai(this.ctx, this.retryTimerRef, () => this.processOfflineQueue());
2971
+ }
2972
+ async processOfflineQueue() {
2973
+ await oi(this.ctx, this.queueGuard, () => this.scheduleRetry(), (e) => this.executeMutation(e));
2974
+ }
2975
+ async executeMutation(e) {
2976
+ return ci(this.ctx, e);
2977
+ }
2978
+ getPendingMutationCount() {
2979
+ return this.getInternalState().pendingMutations.length;
2980
+ }
2981
+ markThreadSeen(e) {
2982
+ if (this.destroyed || typeof e != "string" || !e.trim() || e.length > pi) return;
2983
+ let t = new Set(this.getInternalState().seenThreadIds);
2984
+ if (t.add(e), t.size > 1e3) {
2985
+ let e = Array.from(t);
2986
+ t.clear();
2987
+ for (let n of e.slice(-1e3)) t.add(n);
2988
+ }
2989
+ this.setState({ seenThreadIds: t });
2990
+ }
2991
+ isThreadNew(e) {
2992
+ return typeof e != "string" || !e.trim() ? !1 : !this.getInternalState().seenThreadIds.has(e);
2993
+ }
2994
+ setPanelView(e) {
2995
+ this.destroyed || !di.has(e) || this.setState({ panelView: e });
2996
+ }
2997
+ toggleShortcutsOverlay() {
2998
+ this.destroyed || this.setState({ isShortcutsOverlayVisible: !this.getInternalState().isShortcutsOverlayVisible });
2999
+ }
3000
+ addActivity(e) {
3001
+ if (this.destroyed) return;
3002
+ let t = this.getInternalState(), n = t.currentUser;
3003
+ if (!n) return;
3004
+ let r = {
3005
+ id: `activity-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
3006
+ user: {
3007
+ id: n.id,
3008
+ name: n.name,
3009
+ avatarUrl: n.avatar
3010
+ },
3011
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3012
+ read: !1,
3013
+ ...e
3014
+ }, i = [r, ...t.activities].slice(0, 500);
3015
+ this.setState({ activities: i }), this.emit("activity:new", r);
3016
+ }
3017
+ markAllActivitiesRead() {
3018
+ if (this.destroyed) return;
3019
+ let e = this.getInternalState();
3020
+ this.setState({ activities: e.activities.map((e) => ({
3021
+ ...e,
3022
+ read: !0
3023
+ })) });
3024
+ }
3025
+ getUnreadActivityCount() {
3026
+ return this.getInternalState().activities.filter((e) => !e.read).length;
3027
+ }
3028
+ handleDeepLink() {
3029
+ if (this.destroyed) return;
3030
+ let e = window.location.hash.match(/^#comment-(.+)$/);
3031
+ if (!e?.[1]) return;
3032
+ let t = e[1];
3033
+ this.emit("deeplink:navigate", { commentId: t });
3034
+ let n = this.getInternalState().comments.find((e) => e.id === t);
3035
+ n && (this.selectComment(n), this.setState({
3036
+ isSidebarVisible: !0,
3037
+ panelView: "detail"
3038
+ }));
3039
+ }
3040
+ async createHighlight(e, t) {
3041
+ if (!this.destroyed) return cn(this.ctx, this.commentCb, this.activeMutations, e, t);
3042
+ }
3043
+ async createDrawing(e, t, n) {
3044
+ if (!this.destroyed) return ln(this.ctx, this.commentCb, this.activeMutations, e, t, n);
3045
+ }
3046
+ setActiveDrawing(e) {
3047
+ this.destroyed || this.setState({ activeDrawing: e });
3048
+ }
3049
+ sendDrawingStroke(e) {
3050
+ this.destroyed || this.wsManager?.sendDrawingStroke(e);
3051
+ }
3052
+ async captureScreenshot(e) {
3053
+ return this.destroyed ? null : Rn(this.ctx, this.screenshotProvider, e);
3054
+ }
3055
+ async uploadScreenshot(e, t, n) {
3056
+ return this.destroyed ? null : zn(this.ctx, e, t, n);
3057
+ }
3058
+ setActiveScreenshot(e) {
3059
+ this.destroyed || this.setState({ activeScreenshot: e });
3060
+ }
3061
+ async uploadFiles(e, t) {
3062
+ return this.destroyed ? [] : Bn(this.ctx, e, t);
3063
+ }
3064
+ getAgentContext(e) {
3065
+ return ze(this.getInternalState(), e);
3066
+ }
3067
+ async getAgentContextAsync(e) {
3068
+ return Be(ze(this.getInternalState(), e));
3069
+ }
3070
+ formatAgentContext(e) {
3071
+ return He(this.getAgentContext(e));
3072
+ }
3073
+ async formatAgentContextAsync(e) {
3074
+ return He(await this.getAgentContextAsync(e));
3075
+ }
3076
+ async copyAgentContext(e) {
3077
+ if (this.destroyed) return "";
3078
+ let t = await this.getAgentContextAsync(e), n = He(t);
3079
+ return await qe(n, t), this.emit("agent:context-copied", {
3080
+ commentCount: t.comments.length,
3081
+ sourceResolved: t.sourceResolved
3082
+ }), n;
3083
+ }
3084
+ async grabElement(e, t) {
3085
+ if (this.destroyed) return null;
3086
+ let n = await rr(e, this.ctx, this.screenshotProvider, t);
3087
+ return n && this.emit("agent:element-grabbed", {
3088
+ source: n.element.source?.filePath ?? null,
3089
+ componentName: n.element.componentName ?? null
3090
+ }), n;
3091
+ }
3092
+ async grabElements(e, t) {
3093
+ if (this.destroyed) return null;
3094
+ let n = await ar(e, this.ctx, this.screenshotProvider, t);
3095
+ return n && this.emit("agent:elements-grabbed", { count: n.results.length }), n;
3096
+ }
3097
+ async getProjectMembers() {
3098
+ if (this.destroyed) return [];
3099
+ try {
3100
+ return await this.apiClient.getProjectMembers();
3101
+ } catch (e) {
3102
+ return this.handleError(e), [];
3103
+ }
3104
+ }
3105
+ handleToggleRequest() {
3106
+ this.destroyed || gr(this.getInternalState(), this.kbdCallbacks);
3107
+ }
3108
+ handleKeyboardShortcuts(e) {
3109
+ this.destroyed || e.key === "Escape" && this.escapeBlockers.size > 0 || _r(e, this.getInternalState(), this.kbdCallbacks);
3110
+ }
3111
+ matchesHoldKey(e) {
3112
+ let t = this.config.ui?.activation?.key;
3113
+ return t ? t === "Alt" ? e.key === "Alt" || e.code === "AltLeft" || e.code === "AltRight" : t === "Meta" ? e.key === "Meta" || e.code === "MetaLeft" || e.code === "MetaRight" : t === "Control" ? e.key === "Control" || e.code === "ControlLeft" || e.code === "ControlRight" : t === "Shift" ? e.key === "Shift" || e.code === "ShiftLeft" || e.code === "ShiftRight" : !1 : !1;
3114
+ }
3115
+ blockEscape() {
3116
+ let e = Symbol();
3117
+ return this.escapeBlockers.add(e), () => {
3118
+ this.escapeBlockers.delete(e);
3119
+ };
3120
+ }
3121
+ initializeWebSocket() {
3122
+ this.destroyed || li().then((e) => {
3123
+ this.destroyed || this.getInternalState().isAuthenticated && (this.syncRealtimeRefs(), e.initializeWebSocket(this.ctx, this.realtimeRefs), this.syncFromRealtimeRefs());
3124
+ }).catch((e) => {
3125
+ this.ctx.handleError(e);
3126
+ });
3127
+ }
3128
+ getOnlineUsers() {
3129
+ /* v8 ignore next -- onlineUsers is always initialized as array */
3130
+ return structuredClone(this.getInternalState().onlineUsers || []);
3131
+ }
3132
+ syncRealtimeRefs() {
3133
+ this.realtimeRefs.wsManager = this.wsManager, this.realtimeRefs.wsUnsubscribers = this.wsUnsubscribers, this.realtimeRefs.mouseMoveHandler = this.mouseMoveHandler;
3134
+ }
3135
+ syncFromRealtimeRefs() {
3136
+ this.wsManager = this.realtimeRefs.wsManager, this.wsUnsubscribers = this.realtimeRefs.wsUnsubscribers, this.mouseMoveHandler = this.realtimeRefs.mouseMoveHandler;
3137
+ }
3138
+ removeMouseMoveListener() {
3139
+ Q && (this.syncRealtimeRefs(), Q.removeMouseMoveListener(this.realtimeRefs), this.syncFromRealtimeRefs());
3140
+ }
3141
+ disconnectRealtime(e) {
3142
+ for (let e of this.wsUnsubscribers) try {
3143
+ e();
3144
+ } catch (e) {
3145
+ console.error("[CommentKit] Error during realtime cleanup:", e);
3146
+ }
3147
+ if (this.wsUnsubscribers = [], this.wsManager) {
3148
+ try {
3149
+ e && this.wsManager.sendCursorLeave();
3150
+ } catch {}
3151
+ this.wsManager.destroy(), this.wsManager = null;
3152
+ }
3153
+ this.removeMouseMoveListener(), this.syncRealtimeRefs();
3154
+ }
3155
+ destroy() {
3156
+ this.destroyed || (this.destroyed = !0, ui && (this.keyboardHandler && window.removeEventListener("keydown", this.keyboardHandler, !0), this.holdActivationHandler && (window.removeEventListener("keydown", this.holdActivationHandler), window.removeEventListener("keyup", this.holdActivationHandler)), this.holdBlurHandler && window.removeEventListener("blur", this.holdBlurHandler), this.toggleHandler && window.removeEventListener("commentkit:toggle-overlay", this.toggleHandler), this.hashChangeHandler && window.removeEventListener("hashchange", this.hashChangeHandler), this.onlineHandler && window.removeEventListener("online", this.onlineHandler), this.offlineHandler && window.removeEventListener("offline", this.offlineHandler)), this.pendingStateUpdates = null, this.flushScheduled = !1, this.activeMutations.clear(), this.offlinePersistUnsub?.(), this.offlinePersistUnsub = null, this.retryTimer &&= (clearTimeout(this.retryTimer), null), this.bootRetryTimer &&= (clearTimeout(this.bootRetryTimer), null), this.disconnectRealtime(!0), this.sliceSubscribers.clear(), this.removeAllListeners());
3157
+ }
3158
+ }, yi = /* @__PURE__ */ new WeakMap();
3159
+ function bi(e) {
3160
+ yi.get(e)?.();
3161
+ }
3162
+ function xi(e, t) {
3163
+ let n = (e) => {
3164
+ try {
3165
+ t?.(e);
3166
+ } catch {}
3167
+ }, r = [], i = () => {
3168
+ let t = e();
3169
+ if (!t || r.length === 0) return;
3170
+ let i = r.splice(0, r.length);
3171
+ for (let e of i) if (!e.cancelled) try {
3172
+ e.unsubscribe = e.attach(t);
3173
+ } catch (e) {
3174
+ n(e);
3175
+ }
3176
+ }, a = (t, n) => {
3177
+ let a = e();
3178
+ if (a) return i(), t(a);
3179
+ let o = {
3180
+ attach: t,
3181
+ unsubscribe: null,
3182
+ cancelled: !1,
3183
+ meta: n
3184
+ };
3185
+ return r.push(o), () => {
3186
+ o.cancelled = !0, o.unsubscribe?.(), o.unsubscribe = null;
3187
+ let e = r.indexOf(o);
3188
+ e !== -1 && r.splice(e, 1);
3189
+ };
3190
+ }, o = () => /* @__PURE__ */ Error("CommentKit is not initialized yet — wait for the adapter's mount lifecycle before calling mutations"), s = async (t) => {
3191
+ let r = e();
3192
+ if (!r) {
3193
+ let e = o();
3194
+ throw n(e), e;
3195
+ }
3196
+ try {
3197
+ return await t(r);
3198
+ } catch (e) {
3199
+ throw n(e), e;
3200
+ }
3201
+ }, c = async (t, r) => {
3202
+ let i = e();
3203
+ if (!i) return r;
3204
+ try {
3205
+ return await t(i);
3206
+ } catch (e) {
3207
+ throw n(e), e;
3208
+ }
3209
+ }, l = (t) => {
3210
+ let r = e();
3211
+ if (r) {
3212
+ i();
3213
+ try {
3214
+ t(r);
3215
+ } catch (e) {
3216
+ throw n(e), e;
3217
+ }
3218
+ }
3219
+ }, u = (t, r) => {
3220
+ let i = e();
3221
+ if (!i) return r;
3222
+ try {
3223
+ return t(i);
3224
+ } catch (e) {
3225
+ throw n(e), e;
3226
+ }
3227
+ }, d = {
3228
+ validateInvite: (e) => s((t) => t.validateInvite(e)),
3229
+ login: (e) => s((t) => t.login(e)),
3230
+ verifyOtp: (e) => s((t) => t.verifyOtp(e)),
3231
+ cancelOtp: () => l((e) => e.cancelOtp()),
3232
+ resendOtp: () => s((e) => e.resendOtp()),
3233
+ logout: () => l((e) => e.logout()),
3234
+ toggleLoginModal: () => l((e) => e.toggleLoginModal()),
3235
+ toggleOverlay: () => l((e) => e.toggleOverlay()),
3236
+ toggleSidebar: () => l((e) => e.toggleSidebar()),
3237
+ setTool: (e) => l((t) => t.setTool(e)),
3238
+ toggleShortcutsOverlay: () => l((e) => e.toggleShortcutsOverlay()),
3239
+ setPanelView: (e) => l((t) => t.setPanelView(e)),
3240
+ loadMoreComments: () => s((e) => e.loadMoreComments()),
3241
+ getProjectMembers: () => c((e) => e.getProjectMembers(), []),
3242
+ createComment: (e, t, n, r, i, a, o) => s((s) => s.createComment(e, t, n, r, i, a, o)),
3243
+ updateComment: (e, t) => s((n) => n.updateComment(e, t)),
3244
+ deleteComment: (e) => s((t) => t.deleteComment(e)),
3245
+ resolveComment: (e) => s((t) => t.resolveComment(e)),
3246
+ unresolveComment: (e) => s((t) => t.unresolveComment(e)),
3247
+ completeComment: (e) => s((t) => t.completeComment(e)),
3248
+ selectComment: (e) => l((t) => t.selectComment(e)),
3249
+ addReply: (e, t) => s((n) => n.addReply(e, t)),
3250
+ updateReply: (e, t, n) => s((r) => r.updateReply(e, t, n)),
3251
+ deleteReply: (e, t) => s((n) => n.deleteReply(e, t)),
3252
+ reactToComment: (e, t) => s((n) => n.reactToComment(e, t)),
3253
+ updateCommentPosition: (e, t, n) => s((r) => r.updateCommentPosition(e, t, n)),
3254
+ createHighlight: (e, t) => s((n) => n.createHighlight(e, t)),
3255
+ createDrawing: (e, t, n) => s((r) => r.createDrawing(e, t, n)),
3256
+ setActiveDrawing: (e) => l((t) => t.setActiveDrawing(e)),
3257
+ sendDrawingStroke: (e) => l((t) => t.sendDrawingStroke(e)),
3258
+ captureScreenshot: (e) => c((t) => t.captureScreenshot(e), null),
3259
+ uploadScreenshot: (e, t, n) => c((r) => r.uploadScreenshot(e, t, n), null),
3260
+ setActiveScreenshot: (e) => l((t) => t.setActiveScreenshot(e)),
3261
+ uploadFiles: (e, t) => c((n) => n.uploadFiles(e, t), []),
3262
+ markThreadSeen: (e) => l((t) => t.markThreadSeen(e)),
3263
+ isThreadNew: (e) => u((t) => t.isThreadNew(e), !0),
3264
+ markAllActivitiesRead: () => l((e) => e.markAllActivitiesRead()),
3265
+ getUnreadActivityCount: () => u((e) => e.getUnreadActivityCount(), 0),
3266
+ getPendingMutationCount: () => u((e) => e.getPendingMutationCount(), 0),
3267
+ getOnlineUsers: () => u((e) => e.getOnlineUsers(), []),
3268
+ getAgentContext: (e) => u((t) => t.getAgentContext(e), {
3269
+ version: 1,
3270
+ generatedAt: "",
3271
+ instructions: "",
3272
+ page: {
3273
+ url: "",
3274
+ path: "",
3275
+ title: ""
3276
+ },
3277
+ comments: [],
3278
+ sourceResolved: !1
3279
+ }),
3280
+ getAgentContextAsync: (e) => c((t) => t.getAgentContextAsync(e), {
3281
+ version: 1,
3282
+ generatedAt: "",
3283
+ instructions: "",
3284
+ page: {
3285
+ url: "",
3286
+ path: "",
3287
+ title: ""
3288
+ },
3289
+ comments: [],
3290
+ sourceResolved: !1
3291
+ }),
3292
+ formatAgentContext: (e) => u((t) => t.formatAgentContext(e), ""),
3293
+ formatAgentContextAsync: (e) => c((t) => t.formatAgentContextAsync(e), ""),
3294
+ copyAgentContext: (e) => c((t) => t.copyAgentContext(e), ""),
3295
+ grabElement: (e, t) => c((n) => n.grabElement(e, t), null),
3296
+ grabElements: (e, t) => c((n) => n.grabElements(e, t), null),
3297
+ onSlice: (e, t) => a((n) => n.onSlice(e, t)),
3298
+ select: (e, t) => a((n) => n.select(e, t)),
3299
+ on: (e, t) => a((n) => n.on(e, t), {
3300
+ event: e,
3301
+ listener: t
3302
+ }),
3303
+ off: (e, t) => {
3304
+ for (let n = r.length - 1; n >= 0; n--) {
3305
+ let i = r[n]?.meta;
3306
+ i && i.event === e && i.listener === t && r.splice(n, 1);
3307
+ }
3308
+ l((n) => n.off(e, t));
3309
+ }
3310
+ };
3311
+ return yi.set(d, i), d;
3312
+ }
3313
+ var $ = {
3314
+ isAuthenticated: (e) => e?.isAuthenticated ?? !1,
3315
+ isOverlayVisible: (e) => e?.isOverlayVisible ?? !1,
3316
+ isSidebarVisible: (e) => e?.isSidebarVisible ?? !1,
3317
+ currentUser: (e) => e?.currentUser ?? null,
3318
+ comments: (e) => e?.comments ?? [],
3319
+ activeTool: (e) => e?.activeTool ?? null,
3320
+ otpStep: (e) => e?.otpStep ?? "idle",
3321
+ otpEmail: (e) => e?.otpEmail ?? null,
3322
+ pendingMutationCount: (e) => e?.pendingMutations?.length ?? 0,
3323
+ isOnline: (e) => e?.isOnline ?? !0,
3324
+ selectedComment: (e) => e?.selectedComment ?? null,
3325
+ connectionStatus: (e) => e?.connectionStatus ?? "disconnected",
3326
+ panelView: (e) => e?.panelView ?? "list",
3327
+ isShortcutsOverlayVisible: (e) => e?.isShortcutsOverlayVisible ?? !1,
3328
+ activeDrawing: (e) => e?.activeDrawing ?? null,
3329
+ activeScreenshot: (e) => e?.activeScreenshot ?? null
3330
+ };
3331
+ function Si(e) {
3332
+ return typeof e == "object" && !!e && "error" in e && "message" in e && "code" in e;
3333
+ }
3334
+ function Ci(e) {
3335
+ return e instanceof Error ? e.message : String(e);
3336
+ }
3337
+ function wi(e) {
3338
+ return Si(e) ? e : {
3339
+ error: "init_failed",
3340
+ message: Ci(e),
3341
+ code: 500
3342
+ };
3343
+ }
3344
+ function Ti(e) {
3345
+ return {
3346
+ error: "mount_failed",
3347
+ message: "Failed to mount CommentKit UI",
3348
+ code: 500,
3349
+ details: { cause: e instanceof Error ? e.message : String(e) }
3350
+ };
3351
+ }
3352
+ function Ei(e) {
3353
+ let t = typeof e == "function" ? e : () => e, n = v(null), r = v(!1), i = v(!0), a = v(null), o = v(null), s = m(() => $.isAuthenticated(n.value)), c = m(() => $.isOverlayVisible(n.value)), l = m(() => $.isSidebarVisible(n.value)), u = m(() => $.currentUser(n.value)), d = m(() => $.comments(n.value)), f = m(() => $.activeTool(n.value)), p = m(() => $.otpStep(n.value)), h = m(() => $.otpEmail(n.value)), b = m(() => $.pendingMutationCount(n.value)), x = m(() => $.isOnline(n.value)), S = m(() => $.selectedComment(n.value)), ee = m(() => $.connectionStatus(n.value)), te = m(() => $.panelView(n.value)), ne = m(() => $.isShortcutsOverlayVisible(n.value)), re = m(() => $.activeDrawing(n.value)), ie = m(() => $.activeScreenshot(n.value)), ae = xi(() => o.value, (e) => {
3354
+ a.value = wi(e);
3355
+ }), C = [], w = null, T = !1, oe = !1, E = () => {
3356
+ if (!oe) {
3357
+ oe = !0;
3358
+ try {
3359
+ t().onReady?.();
3360
+ } catch {}
3361
+ }
3362
+ }, D = (e) => {
3363
+ a.value = e;
3364
+ try {
3365
+ t().onError?.(e);
3366
+ } catch {}
3367
+ }, se = async (e) => {
3368
+ try {
3369
+ let { mountCommentKitUI: t } = await import("./vue/mount-ui-DdTYzv6J.js");
3370
+ if (T || o.value !== e) return;
3371
+ let n = await t(e);
3372
+ if (T || o.value !== e) {
3373
+ n.unmount();
3374
+ return;
3375
+ }
3376
+ w = n;
3377
+ } catch (t) {
3378
+ !T && o.value === e && D(Ti(t));
3379
+ }
3380
+ }, ce = () => {
3381
+ for (; C.length > 0;) {
3382
+ let e = C.pop();
3383
+ try {
3384
+ e?.();
3385
+ } catch {}
3386
+ }
3387
+ try {
3388
+ w?.unmount();
3389
+ } catch {}
3390
+ w = null;
3391
+ let e = o.value;
3392
+ if (o.value = null, e) try {
3393
+ e.destroy();
3394
+ } catch {}
3395
+ r.value = !1, oe = !1;
3396
+ }, O = () => {
3397
+ if (T) return;
3398
+ let e = t(), s = null;
3399
+ try {
3400
+ i.value = !0, a.value = null, s = new vi(e), o.value = s, bi(ae), e.enabled !== !1 && se(s), C.push(s.on("state:changed", (e) => {
3401
+ T || o.value !== s || (n.value = e, e.isAuthenticated && E());
3402
+ }), s.on("error", (e) => {
3403
+ T || o.value !== s || D(e);
3404
+ }));
3405
+ let t = s.getState();
3406
+ if (T || o.value !== s) return;
3407
+ n.value = t, r.value = !0, i.value = !1, t.isAuthenticated && E();
3408
+ } catch (e) {
3409
+ if (s && o.value === s) {
3410
+ o.value = null;
3411
+ try {
3412
+ s.destroy();
3413
+ } catch {}
3414
+ }
3415
+ T || (i.value = !1, D(wi(e))), o.value = null;
3416
+ }
3417
+ };
3418
+ return _(() => {
3419
+ T = !0, ce();
3420
+ }), g(() => {
3421
+ O();
3422
+ }), y(() => {
3423
+ let e = t();
3424
+ return [
3425
+ e.apiKey,
3426
+ e.baseUrl,
3427
+ e.enabled,
3428
+ e.screenshotProvider !== void 0,
3429
+ JSON.stringify(e.ui ?? null)
3430
+ ];
3431
+ }, (e, t) => {
3432
+ T || !o.value || t && e.every((e, n) => e === t[n]) || (ce(), O());
3433
+ }), {
3434
+ state: n,
3435
+ isReady: r,
3436
+ isLoading: i,
3437
+ error: a,
3438
+ core: o,
3439
+ isAuthenticated: s,
3440
+ isOverlayVisible: c,
3441
+ isSidebarVisible: l,
3442
+ currentUser: u,
3443
+ comments: d,
3444
+ activeTool: f,
3445
+ otpStep: p,
3446
+ otpEmail: h,
3447
+ pendingMutationCount: b,
3448
+ isOnline: x,
3449
+ selectedComment: S,
3450
+ connectionStatus: ee,
3451
+ panelView: te,
3452
+ isShortcutsOverlayVisible: ne,
3453
+ activeDrawing: re,
3454
+ activeScreenshot: ie,
3455
+ ...ae
3456
+ };
3457
+ }
3458
+ var Di = {
3459
+ name: "CommentKit",
3460
+ props: {
3461
+ apiKey: {
3462
+ type: String,
3463
+ required: !0
3464
+ },
3465
+ baseUrl: {
3466
+ type: String,
3467
+ default: void 0
3468
+ },
3469
+ enabled: { default: void 0 },
3470
+ screenshotProvider: {
3471
+ type: Function,
3472
+ default: void 0
3473
+ },
3474
+ ui: {
3475
+ type: Object,
3476
+ default: void 0
3477
+ }
3478
+ },
3479
+ emits: ["ready", "error"],
3480
+ setup(e, { emit: t, slots: n }) {
3481
+ let { isLoading: r } = Ei(() => ({
3482
+ apiKey: e.apiKey,
3483
+ baseUrl: e.baseUrl,
3484
+ enabled: e.enabled,
3485
+ screenshotProvider: e.screenshotProvider,
3486
+ ui: e.ui,
3487
+ onReady: () => t("ready"),
3488
+ onError: (e) => t("error", e)
3489
+ }));
3490
+ return () => h("div", { class: "comment-kit-vue" }, [...n.default?.() ?? [], ...r.value && n.loading ? n.loading() ?? [] : []]);
3491
+ }
3492
+ }, Oi = { install(e) {
3493
+ e.component("CommentKit", Di), e.provide("commentKitUtils", { useCommentKit: Ei });
3494
+ } };
3495
+ export { Di as CommentKit, Di as default, Oi as CommentKitPlugin, Ei as useCommentKit };