@commentkit/comment-kit 1.6.0 → 2.0.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 (137) hide show
  1. package/CHANGELOG.md +298 -590
  2. package/README.md +421 -145
  3. package/SECURITY.md +47 -46
  4. package/dist/node/THIRD_PARTY_NOTICES.txt +56 -0
  5. package/dist/node/browser.js +17 -0
  6. package/dist/node/cli/api.js +226 -0
  7. package/dist/node/cli/bin.js +18 -0
  8. package/dist/node/cli/credentials.js +268 -0
  9. package/dist/node/cli/doctor.js +789 -0
  10. package/dist/node/cli/format.js +54 -0
  11. package/dist/node/cli/init.js +686 -0
  12. package/dist/node/cli/main.js +537 -0
  13. package/dist/node/cli/mcp.js +295 -0
  14. package/dist/node/cli/open.js +20 -0
  15. package/dist/node/plugins/astro-B5y1Gtbf.js +31 -0
  16. package/dist/node/plugins/astro.js +26 -0
  17. package/dist/node/plugins/git-BIXLbL3f.js +92 -0
  18. package/dist/node/plugins/jsx-Bg4BdSph.js +7958 -0
  19. package/dist/node/plugins/next.js +48 -0
  20. package/dist/node/plugins/options-THop1K92.js +71 -0
  21. package/dist/node/plugins/transform-CKiAuSbk.js +1155 -0
  22. package/dist/node/plugins/vite-BdAYUW10.js +74 -0
  23. package/dist/node/plugins/vite.js +1 -0
  24. package/dist/node/plugins/webpack-R2U2DLlY.js +35 -0
  25. package/dist/node/plugins/webpack-loader.cjs +21 -0
  26. package/dist/node/plugins/webpack-loader.js +18 -0
  27. package/dist/node/plugins/webpack.js +1 -0
  28. package/dist/node/shared/dashboard-places.js +33 -0
  29. package/dist/node/shared/endpoint.js +26 -0
  30. package/dist/node/shared/format.js +63 -0
  31. package/dist/node/types/astro.d.ts +11 -0
  32. package/dist/node/types/next.d.ts +34 -0
  33. package/dist/node/types/options.d.ts +59 -0
  34. package/dist/node/types/vite.d.ts +11 -0
  35. package/dist/node/types/webpack-loader.d.ts +22 -0
  36. package/dist/node/types/webpack.d.ts +27 -0
  37. package/dist/npm/THIRD_PARTY_NOTICES.txt +6 -6
  38. package/dist/npm/chunks/AgentSend-DOy3jhyF.js +68 -0
  39. package/dist/npm/chunks/Checklist-CW_SwMpS.js +282 -0
  40. package/dist/npm/chunks/Composer-Bveq5QrK.js +727 -0
  41. package/dist/npm/chunks/Guest-7hcN765o.js +270 -0
  42. package/dist/npm/chunks/MarkupEditor-6bJGpWGO.js +345 -0
  43. package/dist/npm/chunks/Panel-ChPUB68C.js +1211 -0
  44. package/dist/npm/chunks/Settings-CB5eEKnf.js +231 -0
  45. package/dist/npm/chunks/Shortcuts-eAyjJ89P.js +62 -0
  46. package/dist/npm/chunks/StyleEditor-CZTdAA5c.js +46 -0
  47. package/dist/npm/chunks/StylePanel-B4pHQUL9.js +199 -0
  48. package/dist/npm/chunks/TaskFields-C8BX0Sgg.js +289 -0
  49. package/dist/npm/chunks/ThreadCard-B1EsX3PR.js +1160 -0
  50. package/dist/npm/chunks/Viewer-DY6zb90M.js +114 -0
  51. package/dist/npm/chunks/{agent-BDMQtOzH.js → agent-MTQHr9ei.js} +9 -9
  52. package/dist/npm/chunks/{anchor-BsradQhn.js → anchor-BsQNVkHj.js} +108 -85
  53. package/dist/npm/chunks/{ar-8tPch6W4.js → ar-L5cQ-NPe.js} +71 -19
  54. package/dist/npm/chunks/card-bits-CTdrkYn8.js +53 -0
  55. package/dist/npm/chunks/{client-EFTWxHbJ.js → client-7eVxvg5j.js} +282 -290
  56. package/dist/npm/chunks/confetti-BIs5s14P.js +49 -0
  57. package/dist/npm/chunks/context-BuMl7A07.js +48 -0
  58. package/dist/npm/chunks/context-Cf6khm7A.js +20 -0
  59. package/dist/npm/chunks/{de-C63897uD.js → de-D0C-v6tP.js} +62 -18
  60. package/dist/npm/chunks/dialog-DvdIkCW0.js +3 -0
  61. package/dist/npm/chunks/dpop-0A76OPa9.js +96 -0
  62. package/dist/npm/chunks/drafts-B0ctr1g9.js +21 -0
  63. package/dist/npm/chunks/{es-CI2bSpvB.js → es-Bw4Dj9tN.js} +62 -18
  64. package/dist/npm/chunks/extension-DFVOvciD.js +62 -0
  65. package/dist/npm/chunks/{extension-BST6LH1q.js → extension-SmoH5AA4.js} +20 -12
  66. package/dist/npm/chunks/files-4lV9YQIX.js +114 -0
  67. package/dist/npm/chunks/{fr-rsVe-Lqk.js → fr-TkuQaIAa.js} +120 -76
  68. package/dist/npm/chunks/{hi-cvwbSaWP.js → hi-DXSH2U8d.js} +63 -19
  69. package/dist/npm/chunks/{i18n-C4v0M-6z.js → i18n-aVSu9TcJ.js} +136 -92
  70. package/dist/npm/chunks/identify-BGYh2dVo.js +106 -0
  71. package/dist/npm/chunks/{it-C8tnV0BF.js → it-CiWA_bch.js} +81 -37
  72. package/dist/npm/chunks/{ja-BWxDfC2f.js → ja-C-QmR3yz.js} +60 -16
  73. package/dist/npm/chunks/late-words-80_VWt8S.js +14 -0
  74. package/dist/npm/chunks/live-BExWHzQ7.js +85 -0
  75. package/dist/npm/chunks/locale-D8Q4Q2Nt.js +26 -0
  76. package/dist/npm/chunks/{nl-DNQ6eCht.js → nl-CEmZRqjX.js} +63 -19
  77. package/dist/npm/chunks/page-key-HSY3Lze5.js +62 -0
  78. package/dist/npm/chunks/{pick-CLyOdjnD.js → pick-B3sR7jtS.js} +45 -44
  79. package/dist/npm/chunks/pkce-CfZhiNBi.js +8 -0
  80. package/dist/npm/chunks/placement-BF_HOUDD.js +74 -0
  81. package/dist/npm/chunks/privacy-BWUGlHw5.js +57 -0
  82. package/dist/npm/chunks/{pt-BR-CkG7vpU2.js → pt-BR-b-a8sxO8.js} +62 -18
  83. package/dist/npm/chunks/{realtime-DIo-Wth4.js → realtime-C79zF50C.js} +14 -12
  84. package/dist/npm/chunks/report-DaVuoRYS.js +44 -0
  85. package/dist/npm/chunks/show-BoN8AC-F.js +97 -0
  86. package/dist/npm/chunks/signin-BOWr_WCo.js +75 -0
  87. package/dist/npm/chunks/{source-CS7C6wJA.js → source-mk3rGBBQ.js} +1 -1
  88. package/dist/npm/chunks/src-C8rZFyL_.js +215 -0
  89. package/dist/npm/chunks/start-CV4j78_q.js +1894 -0
  90. package/dist/npm/chunks/states-b9Bv3Ci7.js +3 -0
  91. package/dist/npm/chunks/upload-B2mkgMeJ.js +42 -0
  92. package/dist/npm/chunks/uploads-8AxyRq7g.js +1147 -0
  93. package/dist/npm/chunks/wrap-DW6EFbVQ.js +69 -0
  94. package/dist/npm/chunks/{zh-CN-BKuZOLBE.js → zh-CN-JTscW8u8.js} +61 -17
  95. package/dist/npm/element.js +58 -21
  96. package/dist/npm/headless.js +7 -3
  97. package/dist/npm/index.js +3 -3
  98. package/dist/npm/react.js +18 -11
  99. package/dist/npm/svelte.js +28 -12
  100. package/dist/npm/types/adapters/react.d.ts +4 -1
  101. package/dist/npm/types/adapters/svelte.d.ts +4 -1
  102. package/dist/npm/types/adapters/vue.d.ts +35 -2
  103. package/dist/npm/types/anchor/index.d.ts +19 -0
  104. package/dist/npm/types/capture/privacy.d.ts +14 -0
  105. package/dist/npm/types/core/api.d.ts +20 -1
  106. package/dist/npm/types/core/auth.d.ts +40 -21
  107. package/dist/npm/types/core/client.d.ts +60 -4
  108. package/dist/npm/types/core/page-key.d.ts +42 -0
  109. package/dist/npm/types/core/types.d.ts +87 -4
  110. package/dist/npm/types/element.d.ts +17 -7
  111. package/dist/npm/types/headless.d.ts +2 -1
  112. package/dist/npm/types/index.d.ts +16 -6
  113. package/dist/npm/vue.js +44 -9
  114. package/package.json +90 -14
  115. package/dist/npm/chunks/AgentSend-2JPDseOo.js +0 -63
  116. package/dist/npm/chunks/Checklist-BpDXQebo.js +0 -257
  117. package/dist/npm/chunks/Composer-CAyj-c8e.js +0 -677
  118. package/dist/npm/chunks/Guest-ZdFmTcXI.js +0 -187
  119. package/dist/npm/chunks/MarkupEditor-BFplZwFy.js +0 -332
  120. package/dist/npm/chunks/Panel-BhZ4XRDR.js +0 -861
  121. package/dist/npm/chunks/Settings-SPG9EHUZ.js +0 -204
  122. package/dist/npm/chunks/Shortcuts-C28HVDw6.js +0 -58
  123. package/dist/npm/chunks/StyleEditor-ByZMtq10.js +0 -43
  124. package/dist/npm/chunks/StylePanel-Iwhce2tE.js +0 -197
  125. package/dist/npm/chunks/TaskFields-BsP_fVJg.js +0 -273
  126. package/dist/npm/chunks/ThreadCard-BzVZdDCb.js +0 -1030
  127. package/dist/npm/chunks/Viewer-CqtGrdD8.js +0 -108
  128. package/dist/npm/chunks/card-bits-Bna-g3Py.js +0 -124
  129. package/dist/npm/chunks/confetti-DTKpwF3O.js +0 -40
  130. package/dist/npm/chunks/drafts-akdBsOd0.js +0 -50
  131. package/dist/npm/chunks/extension-D-V3utTm.js +0 -53
  132. package/dist/npm/chunks/live-BCpJVBeN.js +0 -33
  133. package/dist/npm/chunks/report-BBrT3r89.js +0 -27
  134. package/dist/npm/chunks/src-C4FsVoUp.js +0 -148
  135. package/dist/npm/chunks/start-i9M-r3aH.js +0 -1800
  136. package/dist/npm/chunks/upload-DSv7EyBD.js +0 -41
  137. package/dist/npm/chunks/uploads-I01kdqQF.js +0 -1103
@@ -0,0 +1,789 @@
1
+ // `npx @commentkit/comment-kit doctor [url]`: find out, in plain words, why the widget is not showing.
2
+ // Node built-ins only. Every network call goes through an injectable fetch, so the tests run offline.
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { DASHBOARD } from "../shared/dashboard-places.js";
6
+ import { CliError, endpointFrom, Project } from "./api.js";
7
+ import { safeUrl } from "./format.js";
8
+ import { describePlace, PLUGIN_IMPORT, plan, templatesWithTag } from "./init.js";
9
+ import { PUBLISHABLE_KEY } from "./main.js";
10
+ const TIMEOUT_MS = 10_000;
11
+ const MAX_PAGE_BYTES = 2 * 1024 * 1024;
12
+ const MAX_API_BYTES = 256 * 1024;
13
+ const MAX_REDIRECTS = 3;
14
+ const SDK = "@commentkit/comment-kit";
15
+ /**
16
+ * How to run this CLI: always the full package name. A bare `npx commentkit` runs this package only where it is
17
+ * installed; anywhere else npx would fetch an unrelated npm package named "commentkit".
18
+ */
19
+ export const CLI = `npx ${SDK}`;
20
+ const KEY_VARS = ["NEXT_PUBLIC_COMMENTKIT_KEY", "VITE_COMMENTKIT_KEY", "PUBLIC_COMMENTKIT_KEY", "NUXT_PUBLIC_COMMENTKIT_KEY", "COMMENTKIT_KEY"];
21
+ /** A placeholder key for init's plan(): doctor only reads what it detects, it never writes. */
22
+ const PLAN_KEY = "pk_test_doctordoctordoctordoc";
23
+ const MARK = { pass: "✓", fail: "✗", warn: "!", info: "•" };
24
+ // ---------------------------------------------------------------------------------------------
25
+ // Small helpers
26
+ /** Text from a server or a page, safe for one terminal line: no control characters, bounded. */
27
+ export function clean(text, max = 120) {
28
+ const t = String(text ?? "").replace(/[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁠-⁩]/g, " ").replace(/\s+/g, " ").trim();
29
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t;
30
+ }
31
+ /** A publishable key, shortened: it identifies a project and grants nothing, but there is no need to print it whole. */
32
+ export function maskKey(key) {
33
+ return key.length > 12 ? `${key.slice(0, 12)}…` : key;
34
+ }
35
+ function isLocalHost(host) {
36
+ const name = host.toLowerCase().replace(/^\[|\]$/g, "");
37
+ return ["localhost", "127.0.0.1", "::1"].includes(name) || name.endsWith(".localhost");
38
+ }
39
+ /** Hosts the widget treats as local development (src/activation.ts isLocalOrigin): shown without a share link. */
40
+ function isDevHost(host) {
41
+ return isLocalHost(host) || host.toLowerCase().endsWith(".test");
42
+ }
43
+ /**
44
+ * The website to check: http or https only, no user name or password in it. Anything else
45
+ * (file:, javascript:, data:, chrome:, custom app schemes) is refused before any request is made.
46
+ */
47
+ export function siteUrl(raw) {
48
+ let url;
49
+ try {
50
+ url = new URL(/^[a-z][a-z0-9+.-]*:/i.test(raw.trim()) ? raw.trim() : `https://${raw.trim()}`);
51
+ }
52
+ catch {
53
+ throw new CliError(`“${clean(raw, 80)}” is not a website address. Give one like https://example.com.`, "invalid_url");
54
+ }
55
+ if (url.protocol !== "http:" && url.protocol !== "https:")
56
+ throw new CliError(`doctor checks websites only (http:// or https://), not ${clean(url.protocol, 20)} addresses.`, "invalid_url");
57
+ if (url.username || url.password)
58
+ throw new CliError("Leave the user name and password out of the address: doctor never sends credentials.", "invalid_url");
59
+ if (!url.hostname)
60
+ throw new CliError("That address has no host name.", "invalid_url");
61
+ return url;
62
+ }
63
+ async function readCapped(response, maxBytes) {
64
+ if (!response.body)
65
+ return { text: "", truncated: false };
66
+ const reader = response.body.getReader();
67
+ const chunks = [];
68
+ let size = 0;
69
+ let truncated = false;
70
+ for (;;) {
71
+ const { done, value } = await reader.read();
72
+ if (done)
73
+ break;
74
+ if (size + value.byteLength > maxBytes) {
75
+ chunks.push(value.subarray(0, maxBytes - size));
76
+ size = maxBytes;
77
+ truncated = true;
78
+ await reader.cancel().catch(() => undefined);
79
+ break;
80
+ }
81
+ chunks.push(value);
82
+ size += value.byteLength;
83
+ }
84
+ const all = new Uint8Array(size);
85
+ let at = 0;
86
+ for (const chunk of chunks) {
87
+ all.set(chunk, at);
88
+ at += chunk.byteLength;
89
+ }
90
+ return { text: new TextDecoder("utf-8", { fatal: false }).decode(all), truncated };
91
+ }
92
+ function reason(error) {
93
+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError"))
94
+ return "no answer in time";
95
+ const cause = error instanceof Error ? error.cause : undefined;
96
+ const code = cause && typeof cause === "object" && "code" in cause ? String(cause.code) : "";
97
+ return clean(code || (error instanceof Error ? error.message : String(error)), 80);
98
+ }
99
+ /**
100
+ * GET a page the way a first-time visitor would: no cookies or credentials, at most 3 redirects (each
101
+ * one checked like the address itself), one timeout for the whole thing, and at most `maxBytes` read.
102
+ */
103
+ export async function fetchPage(start, fetchFn, { timeoutMs = TIMEOUT_MS, maxBytes = MAX_PAGE_BYTES } = {}) {
104
+ const signal = AbortSignal.timeout(timeoutMs);
105
+ let url = start;
106
+ for (let redirects = 0;; redirects++) {
107
+ const response = await fetchFn(url.href, {
108
+ redirect: "manual",
109
+ credentials: "omit",
110
+ signal,
111
+ headers: { accept: "text/html,application/xhtml+xml;q=0.9,*/*;q=0.1", "user-agent": "commentkit-doctor" },
112
+ });
113
+ const location = response.headers.get("location");
114
+ if (response.status >= 300 && response.status < 400 && location) {
115
+ await response.body?.cancel().catch(() => undefined);
116
+ if (redirects >= MAX_REDIRECTS)
117
+ throw new CliError(`it redirects more than ${MAX_REDIRECTS} times`, "too_many_redirects");
118
+ url = siteUrl(new URL(location, url).href);
119
+ continue;
120
+ }
121
+ const { text, truncated } = await readCapped(response, maxBytes);
122
+ return { url, status: response.status, headers: response.headers, html: text, truncated, redirects };
123
+ }
124
+ }
125
+ /** Policies from header values and meta tags. A header value may hold several policies separated by commas. */
126
+ export function parseCsp(values) {
127
+ const policies = [];
128
+ for (const value of values) {
129
+ for (const text of value.split(",")) {
130
+ const policy = new Map();
131
+ for (const part of text.split(";")) {
132
+ const [name, ...sources] = part.trim().split(/\s+/).filter(Boolean);
133
+ if (!name || !/^[a-z-]+$/i.test(name))
134
+ continue;
135
+ const key = name.toLowerCase();
136
+ if (!policy.has(key))
137
+ policy.set(key, sources);
138
+ }
139
+ if (policy.size)
140
+ policies.push(policy);
141
+ }
142
+ }
143
+ return policies;
144
+ }
145
+ /** Content of every <meta http-equiv="Content-Security-Policy"> in the page. */
146
+ export function metaCsp(html) {
147
+ const found = [];
148
+ for (const [tag] of html.matchAll(/<meta\b[^>]*>/gi)) {
149
+ if (!/http-equiv\s*=\s*["']?content-security-policy["'\s>/]/i.test(tag))
150
+ continue;
151
+ const content = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(tag);
152
+ if (content)
153
+ found.push(decodeEntities(content[1] ?? content[2] ?? ""));
154
+ }
155
+ return found;
156
+ }
157
+ function decodeEntities(text) {
158
+ return text.replace(/&(#\d+|#x[0-9a-f]+|quot|apos|amp|lt|gt);/gi, (_, e) => {
159
+ const lower = e.toLowerCase();
160
+ if (lower.startsWith("#x"))
161
+ return String.fromCodePoint(parseInt(lower.slice(2), 16));
162
+ if (lower.startsWith("#"))
163
+ return String.fromCodePoint(Number(lower.slice(1)));
164
+ return { quot: '"', apos: "'", amp: "&", lt: "<", gt: ">" }[lower];
165
+ });
166
+ }
167
+ /** Which directive governs a request when the specific one is absent (CSP Level 3 fallback lists). */
168
+ const FALLBACK = {
169
+ script: ["script-src-elem", "script-src", "default-src"],
170
+ connect: ["connect-src", "default-src"],
171
+ img: ["img-src", "default-src"],
172
+ };
173
+ const DEFAULT_PORT = { "http:": "80", "https:": "443", "ws:": "80", "wss:": "443" };
174
+ const portOf = (url) => url.port || DEFAULT_PORT[url.protocol] || "";
175
+ /**
176
+ * Scheme matching from CSP3 ("scheme-part match"): http: also allows https:, ws: allows wss:, and
177
+ * secure web sockets are allowed by the matching http(s) scheme (browsers treat https: as allowing wss:).
178
+ */
179
+ function schemeMatches(source, target) {
180
+ if (source === target)
181
+ return true;
182
+ if (source === "http:")
183
+ return target === "https:" || target === "ws:" || target === "wss:";
184
+ if (source === "https:")
185
+ return target === "wss:";
186
+ if (source === "ws:")
187
+ return target === "wss:";
188
+ return false;
189
+ }
190
+ /** Does one source expression allow `url` on a page at `page`? Keywords other than 'self' and * never match a URL. */
191
+ export function sourceMatches(source, url, page) {
192
+ const s = source.toLowerCase();
193
+ if (s === "*")
194
+ return ["http:", "https:", "ws:", "wss:"].includes(url.protocol);
195
+ if (s === "'self'")
196
+ return url.hostname === page.hostname && schemeMatches(page.protocol, url.protocol) && (portOf(url) === portOf(page) || (!url.port && !page.port));
197
+ if (s.startsWith("'"))
198
+ return false;
199
+ if (/^[a-z][a-z0-9+.-]*:$/.test(s))
200
+ return schemeMatches(s, url.protocol);
201
+ const m = /^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9_-]+(?:\.[a-z0-9_-]+)*)(?::(\*|\d+))?(\/[^?#]*)?$/.exec(s);
202
+ if (!m)
203
+ return false;
204
+ const [, scheme, host, port, path] = m;
205
+ if (!schemeMatches(scheme ? `${scheme}:` : page.protocol, url.protocol))
206
+ return false;
207
+ const target = url.hostname.toLowerCase();
208
+ if (host === "*") {
209
+ // A lone "*" with a scheme (https://*) matches any host.
210
+ }
211
+ else if (host.startsWith("*.")) {
212
+ if (!target.endsWith(host.slice(1)))
213
+ return false;
214
+ }
215
+ else if (host !== target)
216
+ return false;
217
+ if (port === "*") {
218
+ // any port
219
+ }
220
+ else if (port) {
221
+ if (port !== portOf(url))
222
+ return false;
223
+ }
224
+ else if (url.port && url.port !== DEFAULT_PORT[url.protocol])
225
+ return false;
226
+ if (path && path !== "/")
227
+ return path.endsWith("/") ? url.pathname.startsWith(path) : url.pathname === path;
228
+ return true;
229
+ }
230
+ /**
231
+ * Is `target` allowed by every policy (all of a page's policies are enforced together)? For the
232
+ * loader script, `nonce` is the nonce attribute on its tag. Without 'strict-dynamic' the loader's
233
+ * origin must be allowed by host anyway: the loader then imports the widget from the same place.
234
+ */
235
+ export function cspAllows(policies, kind, target, pageUrl, nonce) {
236
+ const url = new URL(target);
237
+ const page = new URL(pageUrl);
238
+ for (const policy of policies) {
239
+ const directive = FALLBACK[kind].find((d) => policy.has(d));
240
+ if (!directive)
241
+ continue;
242
+ const sources = policy.get(directive);
243
+ if (kind === "script" && sources.some((s) => s.toLowerCase() === "'strict-dynamic'")) {
244
+ const nonces = sources.filter((s) => /^'nonce-[^']+'$/i.test(s)).map((s) => s.slice(7, -1));
245
+ if (!nonce || !nonces.includes(nonce))
246
+ return { allowed: false, directive, needsNonce: true };
247
+ continue;
248
+ }
249
+ if (!sources.some((s) => sourceMatches(s, url, page)))
250
+ return { allowed: false, directive, sources };
251
+ }
252
+ return { allowed: true, directive: null };
253
+ }
254
+ /** The directive for each kind that, once set, takes over from default-src for it alone. */
255
+ const SPECIFIC = { script: "script-src", connect: "connect-src", img: "img-src" };
256
+ /**
257
+ * What to change when `v` blocks `origin`. When only default-src decides, adding the host there would open it
258
+ * to every kind of request; the specific directive is the narrow fix, and it must repeat what default-src
259
+ * allows today, as a set directive replaces default-src for that kind.
260
+ */
261
+ export function cspFix(v, kind, origin, where) {
262
+ if (v.directive !== "default-src")
263
+ return `Add ${origin} to ${v.directive} in ${where}.`;
264
+ const specific = SPECIFIC[kind];
265
+ const keep = (v.sources ?? []).filter((s) => s.toLowerCase() !== "'none'");
266
+ return `Add ${kind === "img" ? "an" : "a"} ${specific} directive to ${where}: ${[specific, ...keep, origin].join(" ")} (only default-src restricts this now; leave default-src as it is).`;
267
+ }
268
+ /** The name of the SDK's one Trusted Types policy (vite.config.ts, screenshot capture). */
269
+ export const TRUSTED_TYPES_POLICY = "commentkit-capture";
270
+ /**
271
+ * Whether the page's `trusted-types` directives let the SDK create its policy: each one that is set must name
272
+ * it or allow any name (`*`). `'allow-duplicates'` only lets a listed name be created twice; it allows no
273
+ * other name. Without a `trusted-types` directive any name may be created.
274
+ */
275
+ export function trustedTypesAllowed(policies) {
276
+ for (const policy of policies) {
277
+ const sources = policy.get("trusted-types");
278
+ if (!sources)
279
+ continue;
280
+ if (!sources.some((s) => s === "*" || s === TRUSTED_TYPES_POLICY))
281
+ return { allowed: false, sources };
282
+ }
283
+ return { allowed: true, sources: null };
284
+ }
285
+ // ---------------------------------------------------------------------------------------------
286
+ // What the page's HTML says
287
+ /** The CDN loader tag: /cdn/v1/loader.js or a pinned /cdn/<version>/loader.js. */
288
+ const LOADER_TAG = /<script\b[^>]*\bsrc\s*=\s*["']?[^"'\s>]*\/cdn\/[^"'\s>/]+\/loader\.js[^>]*>/gi;
289
+ function attr(tag, name) {
290
+ const m = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`, "i").exec(tag);
291
+ return m ? decodeEntities(m[1] ?? m[2] ?? m[3] ?? "") : null;
292
+ }
293
+ export function findSdk(html, pageUrl) {
294
+ let loader = null;
295
+ for (const [tag] of html.matchAll(LOADER_TAG)) {
296
+ const raw = attr(tag, "src");
297
+ if (!raw)
298
+ continue;
299
+ let src;
300
+ try {
301
+ src = new URL(raw, pageUrl);
302
+ }
303
+ catch {
304
+ continue;
305
+ }
306
+ // Tag managers rebuild the tag with its address only, so loader.js?project=pk_… counts too (src/loader.ts).
307
+ const key = attr(tag, "data-project") ?? src.searchParams.get("project");
308
+ loader = { src: src.href, key: key || null, nonce: attr(tag, "nonce") };
309
+ break;
310
+ }
311
+ const markers = [];
312
+ if (/data-commentkit-host/.test(html))
313
+ markers.push("the widget's container");
314
+ if (html.includes(SDK))
315
+ markers.push(`the ${SDK} package name`);
316
+ const key = /\bpk_(?:live|test)_[a-z0-9]{20,40}\b/.exec(html)?.[0] ?? null;
317
+ if (!loader && key)
318
+ markers.push("your project key");
319
+ if (/\bdata-ck-src\s*=/.test(html))
320
+ markers.push("source locations from the build plugin");
321
+ return { loader, markers, key: loader ? null : key };
322
+ }
323
+ function readJson(file) {
324
+ try {
325
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
326
+ return parsed && typeof parsed === "object" ? parsed : null;
327
+ }
328
+ catch {
329
+ return null;
330
+ }
331
+ }
332
+ /** KEY=value lines of an env file (quotes and `export` allowed). */
333
+ export function envValue(text, name) {
334
+ const m = new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=\\s*(.*)$`, "m").exec(text);
335
+ if (!m)
336
+ return null;
337
+ return m[1].trim().replace(/\s+#.*$/, "").replace(/^(["'])(.*)\1$/, "$2");
338
+ }
339
+ function projectSetup(cwd, flagKey, env) {
340
+ const checks = [];
341
+ const pkg = readJson(join(cwd, "package.json"));
342
+ const htmlFiles = ["index.html", "public/index.html"].filter((f) => existsSync(join(cwd, f)));
343
+ // The same framework and entry-file detection init uses; plan() only reads files.
344
+ const p = plan(cwd, PLAN_KEY);
345
+ // A Laravel app with plain Blade pages may have no package.json.
346
+ const appFound = Boolean(pkg) || htmlFiles.length > 0 || p.framework === "laravel";
347
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
348
+ const installed = readJson(join(cwd, "node_modules", SDK, "package.json"));
349
+ const installedVersion = typeof installed?.version === "string" ? clean(installed.version, 40) : null;
350
+ const html = htmlFiles.map((f) => ({ file: f, text: readFileSync(join(cwd, f), "utf8") }));
351
+ const htmlLoader = html.map((h) => ({ file: h.file, sdk: findSdk(h.text, "http://localhost/") })).find((h) => h.sdk.loader);
352
+ // Laravel: the script tag can be in a Blade layout or a public/*.html page.
353
+ const templateTags = p.framework === "laravel" ? templatesWithTag(cwd) : [];
354
+ const bundled = Boolean(deps[SDK]);
355
+ // Where the widget is: the entry or a file it imports (Vite, Laravel), else what init's plan found.
356
+ const widget = p.widget;
357
+ const add = p.install[0]?.join(" ") ?? `npm install ${SDK}`;
358
+ if (!appFound) {
359
+ checks.push({ id: "setup.app", status: "info", message: "No package.json or index.html in this folder, so the project checks were skipped.", fix: `Run ${CLI} doctor in your app's folder to include them.` });
360
+ }
361
+ else if (bundled) {
362
+ checks.push(installedVersion
363
+ ? { id: "setup.package", status: "pass", message: `${SDK} ${installedVersion} is installed (${p.label}).` }
364
+ : { id: "setup.package", status: "fail", message: `${SDK} is in package.json but not installed.`, fix: `Run your package manager's install (for example ${p.packageManager} install).` });
365
+ }
366
+ else if (htmlLoader) {
367
+ checks.push({ id: "setup.package", status: "pass", message: `The CommentKit script tag is in ${htmlLoader.file}.` });
368
+ }
369
+ else if (templateTags.length) {
370
+ checks.push({ id: "setup.package", status: "pass", message: `The CommentKit script tag is in ${templateTags.map((t) => t.file).slice(0, 3).join(", ")}${templateTags.length > 3 ? ` and ${templateTags.length - 3} more` : ""}.` });
371
+ }
372
+ else if (p.entry === "done") {
373
+ checks.push({ id: "setup.package", status: "pass", message: `The CommentKit script tag is in your ${p.label} app.` });
374
+ }
375
+ else {
376
+ checks.push({ id: "setup.package", status: "fail", message: `CommentKit is not installed in this ${p.label} app: no ${SDK} in package.json and no script tag.`, fix: p.framework === "html" || !p.install.length ? `Run ${CLI} init, or add the script tag before </body> (https://commentkit.dev/docs).` : `Run ${CLI} init (or ${add}).` });
377
+ }
378
+ if (appFound && bundled) {
379
+ if (widget)
380
+ checks.push({ id: "setup.widget", status: "pass", message: `The widget is added in ${describePlace(widget)}.` });
381
+ else if (p.entry === "done")
382
+ checks.push({ id: "setup.widget", status: "pass", message: "The widget is added in your layout or entry file." });
383
+ else {
384
+ const where = p.entry ? p.entry.file : "your layout or entry file";
385
+ checks.push({ id: "setup.widget", status: "warn", message: `Could not find the widget in ${where}${p.entry && p.framework === "laravel" ? " or a file it imports" : ""}.`, fix: `If you call init() or render <CommentKit> somewhere else, ignore this; otherwise run ${CLI} init.` });
386
+ }
387
+ }
388
+ // The key: --key, then the env files init writes, then the environment, then the script tag.
389
+ let key = null;
390
+ let keySource = null;
391
+ let keyVar = null;
392
+ if (flagKey) {
393
+ key = flagKey;
394
+ keySource = "--key";
395
+ }
396
+ else {
397
+ const files = [...new Set([p.envFile, ".env.local", ".env", ".env.production", ".env.production.local", ".env.development"].filter(Boolean))];
398
+ const vars = [...new Set([p.envVar, ...KEY_VARS].filter(Boolean))];
399
+ outer: for (const file of files) {
400
+ if (!existsSync(join(cwd, file)))
401
+ continue;
402
+ const text = readFileSync(join(cwd, file), "utf8");
403
+ for (const name of vars) {
404
+ const value = envValue(text, name);
405
+ if (value) {
406
+ key = value;
407
+ keySource = `${file} (${name})`;
408
+ keyVar = name;
409
+ break outer;
410
+ }
411
+ }
412
+ }
413
+ if (!key) {
414
+ const name = [p.envVar, ...KEY_VARS].find((n) => n && env[n]);
415
+ if (name) {
416
+ key = env[name];
417
+ keySource = `the environment variable ${name}`;
418
+ keyVar = name;
419
+ }
420
+ }
421
+ if (!key && htmlLoader?.sdk.loader?.key) {
422
+ key = htmlLoader.sdk.loader.key;
423
+ keySource = htmlLoader.file;
424
+ }
425
+ // Written into the code as the default (init({ project: import.meta.env.VITE_COMMENTKIT_KEY || "pk_…" })), or on a template's tag.
426
+ const written = [widget, ...templateTags].find((place) => place?.key);
427
+ if (!key && written) {
428
+ key = written.key;
429
+ keySource = written.file;
430
+ }
431
+ }
432
+ if (key && !PUBLISHABLE_KEY.test(key)) {
433
+ checks.push({ id: "setup.key", status: "fail", message: `The project key in ${keySource} is not a publishable key (it should look like pk_live_… or pk_test_…).`, fix: `Copy the key again from ${DASHBOARD.install} in CommentKit.` });
434
+ }
435
+ else if (key) {
436
+ checks.push({ id: "setup.key", status: "pass", message: `Project key ${maskKey(key)} found in ${keySource}.` });
437
+ if (keyVar && p.envVar && keyVar !== p.envVar && keyVar !== "COMMENTKIT_KEY") {
438
+ checks.push({ id: "setup.key-name", status: "warn", message: `${p.label} apps do not read ${keyVar}, so the widget gets no key.`, fix: `Rename it to ${p.envVar} in ${keySource.split(" ")[0]}.` });
439
+ }
440
+ }
441
+ else if (appFound && p.framework === "laravel") {
442
+ checks.push({ id: "setup.key", status: "fail", message: "No project key found in .env, your JavaScript entry or a Blade script tag.", fix: `Run ${CLI} init, or write the key into your entry: init({ project: import.meta.env.VITE_COMMENTKIT_KEY || "pk_…" }) (the key is in ${DASHBOARD.install} in CommentKit). If the key comes from somewhere else, run ${CLI} doctor --key pk_… instead.` });
443
+ }
444
+ else if (appFound) {
445
+ checks.push({ id: "setup.key", status: "fail", message: `No project key found${p.envFile ? ` in ${p.envFile}` : ""}${htmlFiles.length ? ` or ${htmlFiles[0]}` : ""}.`, fix: p.envVar ? `Run ${CLI} init, or add ${p.envVar}=pk_… to ${p.envFile} (the key is in ${DASHBOARD.install} in CommentKit). If the key is written straight into your code, run ${CLI} doctor --key pk_… instead.` : `Run ${CLI} init, or put data-project="pk_…" on the script tag (the key is in ${DASHBOARD.install} in CommentKit).` });
446
+ }
447
+ // A Laravel app without a JavaScript entry uses the script tag: there is no build to add the plugin to.
448
+ if (appFound && p.framework !== "html" && !(p.framework === "laravel" && !p.configFile)) {
449
+ const config = p.configFile ? readFileSync(join(cwd, p.configFile), "utf8") : "";
450
+ if (PLUGIN_IMPORT.test(config))
451
+ checks.push({ id: "setup.plugin", status: "pass", message: `The build plugin is set up in ${p.configFile}.` });
452
+ else
453
+ checks.push({ id: "setup.plugin", status: "info", message: "The build plugin is not set up. It is optional: it adds source file and line to feedback, so you and your coding agent land on the right code.", fix: p.configFile && !p.configEdit ? `Run ${CLI} init: it prints the lines to add to ${p.configFile}, which it cannot edit safely.` : `Run ${CLI} init to add it.` });
454
+ }
455
+ return { checks, key, keySource, installedVersion, bundled, appFound };
456
+ }
457
+ /** Code hosts and registries: a package.json homepage there is not the website. */
458
+ const NOT_A_SITE = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org|npmjs\.com|npmjs\.org)$/i;
459
+ /**
460
+ * The website's address as the project records it: APP_URL in .env.example (Laravel), then "homepage" in
461
+ * package.json. Only a real http(s) address counts: localhost, *.test and code-host links are left out.
462
+ */
463
+ export function siteAddress(cwd) {
464
+ const candidates = [];
465
+ if (existsSync(join(cwd, ".env.example")))
466
+ candidates.push({ raw: envValue(readFileSync(join(cwd, ".env.example"), "utf8"), "APP_URL"), source: ".env.example (APP_URL)" });
467
+ const homepage = readJson(join(cwd, "package.json"))?.homepage;
468
+ candidates.push({ raw: typeof homepage === "string" ? homepage : null, source: "package.json (homepage)" });
469
+ for (const { raw, source } of candidates) {
470
+ if (!raw || /[\s"'`$<>]/.test(raw))
471
+ continue;
472
+ let url;
473
+ try {
474
+ url = new URL(raw);
475
+ }
476
+ catch {
477
+ continue;
478
+ }
479
+ if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password || isDevHost(url.hostname) || NOT_A_SITE.test(url.hostname))
480
+ continue;
481
+ return { url: url.origin, source };
482
+ }
483
+ return null;
484
+ }
485
+ async function getJson(fetchFn, url, headers, timeoutMs) {
486
+ try {
487
+ const response = await fetchFn(url, { redirect: "error", credentials: "omit", signal: AbortSignal.timeout(timeoutMs), headers: { accept: "application/json", ...headers } });
488
+ const { text } = await readCapped(response, MAX_API_BYTES);
489
+ let json = {};
490
+ try {
491
+ const parsed = text ? JSON.parse(text) : {};
492
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
493
+ json = parsed;
494
+ }
495
+ catch {
496
+ // Not JSON (a proxy's error page): the status says enough.
497
+ }
498
+ return { status: response.status, json };
499
+ }
500
+ catch (error) {
501
+ return { error: reason(error) };
502
+ }
503
+ }
504
+ /**
505
+ * GET /widget/config. The API needs an Origin to find the website (no Origin answers 404, as for an
506
+ * unknown key), and localhost is always accepted, so the plain key check sends http://localhost.
507
+ * `sdk`: the installed SDK version, sent as the widget sends it (X-CommentKit-SDK), so a version CommentKit
508
+ * switched off answers `disabled_reason: version_blocked`. That answer comes before the key and website are
509
+ * checked, so the website check sends no version.
510
+ */
511
+ async function widgetConfig(fetchFn, endpoint, key, origin, timeoutMs, sdk) {
512
+ return getJson(fetchFn, `${endpoint}/api/v1/widget/config?key=${encodeURIComponent(key)}`, { origin, ...(sdk ? { "x-commentkit-sdk": sdk } : {}) }, timeoutMs);
513
+ }
514
+ function unreachable(id, host, error) {
515
+ return { id, status: "fail", message: `Could not reach CommentKit at ${host} (${error}).`, fix: `Check your internet connection (or COMMENTKIT_ENDPOINT), then run ${CLI} doctor again.` };
516
+ }
517
+ function keyCheck(answer, key, host, sdk) {
518
+ if ("error" in answer)
519
+ return { check: unreachable("api.key", host, answer.error), config: null };
520
+ const { status, json } = answer;
521
+ if (status === 200) {
522
+ const config = json;
523
+ const name = clean(config.project?.name, 80) || "your project";
524
+ if (config.enabled === false && config.disabled_reason === "version_blocked")
525
+ return { config, check: { id: "api.key", status: "fail", message: `This SDK version${sdk ? ` (${clean(sdk, 40)})` : ""} has been switched off by CommentKit; update the package. Until then the widget stays hidden everywhere.`, fix: `npm install ${SDK}@latest, then deploy (sites with the /cdn/v1/ script tag get the fix by themselves).` } };
526
+ if (config.enabled === false)
527
+ return { config, check: { id: "api.key", status: "fail", message: `Feedback is paused for “${name}” (the kill switch is on), so the widget stays hidden everywhere.`, fix: `Turn feedback back on in CommentKit, in ${DASHBOARD.feedbackState}; it applies within a minute.` } };
528
+ if (config.read_only === true)
529
+ return { config, check: { id: "api.key", status: "warn", message: `“${name}” is read-only: the widget shows existing feedback, but nobody can add new feedback (comments are turned off or the plan ended).`, fix: `Check the workspace's plan in CommentKit, and ${DASHBOARD.feedbackState}.` } };
530
+ return { config, check: { id: "api.key", status: "pass", message: `CommentKit knows the key ${maskKey(key)} (project “${name}”) and feedback is on.` } };
531
+ }
532
+ if (status === 404)
533
+ return { config: null, check: { id: "api.key", status: "fail", message: `CommentKit does not know the key ${maskKey(key)}.`, fix: `Copy the key again from ${DASHBOARD.install} in CommentKit (pk_live_… for your live site, pk_test_… for staging).` } };
534
+ if (status === 429)
535
+ return { config: null, check: { id: "api.key", status: "warn", message: "CommentKit is getting too many requests from this network right now, so the key was not checked.", fix: `Run ${CLI} doctor again in a minute.` } };
536
+ return { config: null, check: { id: "api.key", status: "fail", message: `CommentKit answered HTTP ${status} when checking the key${json.detail ? `: ${clean(json.detail)}` : ""}.`, fix: `Run ${CLI} doctor again in a few minutes; if it keeps failing, contact CommentKit support.` } };
537
+ }
538
+ async function signedIn() {
539
+ try {
540
+ const project = await Project.connect();
541
+ const info = await project.request("");
542
+ return { name: info.data.name, keys: [info.data.publishable_keys?.live, info.data.publishable_keys?.test].filter((k) => typeof k === "string") };
543
+ }
544
+ catch (error) {
545
+ if (error instanceof CliError && error.code === "signed_out")
546
+ return null;
547
+ throw error;
548
+ }
549
+ }
550
+ /** -1, 0 or 1 for two x.y.z versions (a prerelease sorts before its release). */
551
+ export function compareVersions(a, b) {
552
+ const parse = (v) => {
553
+ const [core, pre] = v.replace(/^v/, "").split("-", 2);
554
+ return { nums: core.split(".").map((n) => Number(n) || 0), pre: pre ?? null };
555
+ };
556
+ const x = parse(a);
557
+ const y = parse(b);
558
+ for (let i = 0; i < 3; i++) {
559
+ const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0);
560
+ if (d)
561
+ return Math.sign(d);
562
+ }
563
+ if (x.pre === y.pre)
564
+ return 0;
565
+ if (x.pre === null)
566
+ return 1;
567
+ if (y.pre === null)
568
+ return -1;
569
+ return x.pre < y.pre ? -1 : 1;
570
+ }
571
+ // ---------------------------------------------------------------------------------------------
572
+ // The run
573
+ export async function doctor(options, deps = {}) {
574
+ const env = deps.env ?? process.env;
575
+ const fetchFn = deps.fetch ?? ((url, init) => fetch(url, init));
576
+ const timeoutMs = deps.timeoutMs ?? TIMEOUT_MS;
577
+ const endpoint = endpointFrom(env.COMMENTKIT_ENDPOINT || undefined);
578
+ const ck = new URL(endpoint);
579
+ const host = ck.host;
580
+ // Refused before anything else happens: a bad address never reaches the network.
581
+ const site = options.url ? siteUrl(options.url) : null;
582
+ if (options.key !== undefined && !PUBLISHABLE_KEY.test(options.key))
583
+ throw new CliError("--key is not a publishable key (pk_live_… or pk_test_…).");
584
+ const checks = [];
585
+ const setup = projectSetup(options.cwd, options.key, env);
586
+ checks.push(...setup.checks);
587
+ // The page first: its script tag may carry the key when this folder has none.
588
+ let page = null;
589
+ let pageError = null;
590
+ if (site) {
591
+ try {
592
+ page = await fetchPage(site, fetchFn, { timeoutMs, maxBytes: deps.maxBytes ?? MAX_PAGE_BYTES });
593
+ }
594
+ catch (error) {
595
+ pageError = error instanceof CliError ? error.message : reason(error);
596
+ }
597
+ }
598
+ const sdk = page ? findSdk(page.html, page.url.href) : null;
599
+ const pageKey = sdk?.loader?.key ?? sdk?.key ?? null;
600
+ const key = setup.key && PUBLISHABLE_KEY.test(setup.key) ? setup.key : pageKey && PUBLISHABLE_KEY.test(pageKey) ? pageKey : null;
601
+ if (!setup.appFound && !key)
602
+ checks.push({ id: "setup.key", status: "fail", message: "No project key to check: none in this folder" + (site ? " or on the page." : "."), fix: `Run doctor in your app's folder, or pass --key pk_… (the key is in ${DASHBOARD.install} in CommentKit).` });
603
+ // 2. Sign-in (optional for doctor).
604
+ let otherWebsite = null;
605
+ try {
606
+ const project = await (deps.project ?? signedIn)();
607
+ if (!project) {
608
+ checks.push({ id: "signin", status: "info", message: "The CLI is not signed in, so the check that the key belongs to your project was skipped.", fix: `Run ${CLI} login to include it.` });
609
+ }
610
+ else {
611
+ checks.push({ id: "signin", status: "pass", message: `The CLI is signed in to “${clean(project.name, 80)}”.` });
612
+ if (key && project.keys.length && !project.keys.includes(key))
613
+ otherWebsite = clean(project.name, 80);
614
+ }
615
+ }
616
+ catch (error) {
617
+ checks.push({ id: "signin", status: "warn", message: `Could not check the CLI's sign-in (${clean(error instanceof Error ? error.message : String(error), 160)}).`, fix: `Run ${CLI} status for details.` });
618
+ }
619
+ // 3. The key against the API.
620
+ let config = null;
621
+ let reachable = true;
622
+ if (key) {
623
+ const answer = await widgetConfig(fetchFn, endpoint, key, "http://localhost", timeoutMs, setup.installedVersion);
624
+ reachable = !("error" in answer);
625
+ const result = keyCheck(answer, key, host, setup.installedVersion);
626
+ config = result.config;
627
+ checks.push(result.check);
628
+ }
629
+ else if (setup.appFound) {
630
+ checks.push({ id: "api.key", status: "info", message: "Skipped the check with CommentKit: there is no valid project key." });
631
+ }
632
+ // The folder's key belongs to another website than the one the CLI is signed in to. When CommentKit
633
+ // confirmed the key, that is a normal setup (one terminal, several websites): one neutral line.
634
+ if (otherWebsite && key) {
635
+ const known = config ? clean(config.project?.name, 80) : "";
636
+ checks.push(config
637
+ ? { id: "signin.key", status: "info", message: `The terminal is signed in to “${otherWebsite}”, a different website from this folder's key${known ? ` (“${known}”)` : ""}. To switch, run ${CLI} login and choose ${known ? `“${known}”` : "this website"}.` }
638
+ : { id: "signin.key", status: "warn", message: `The key ${maskKey(key)} is not one of “${otherWebsite}”'s keys.`, fix: `If this app belongs to another website, ignore this; otherwise copy the key from ${DASHBOARD.install} in CommentKit.` });
639
+ }
640
+ // 4. The website.
641
+ if (site) {
642
+ const shown = clean(safeUrl(site.href), 200);
643
+ // (a) Is the website on the project's allowed list? Same request, with the site's Origin.
644
+ const originKey = pageKey && PUBLISHABLE_KEY.test(pageKey) ? pageKey : key;
645
+ if (originKey && reachable) {
646
+ const origin = site.origin;
647
+ if (isLocalHost(site.hostname)) {
648
+ checks.push({ id: "site.origin", status: "pass", message: `${origin} is local: CommentKit always allows it for your team.` });
649
+ }
650
+ else {
651
+ const answer = await widgetConfig(fetchFn, endpoint, originKey, origin, timeoutMs);
652
+ if ("error" in answer)
653
+ checks.push(unreachable("site.origin", host, answer.error));
654
+ else if (answer.status === 403 && answer.json.code === "origin_not_allowed")
655
+ checks.push({ id: "site.origin", status: "fail", message: `${origin} is not on the project's list of allowed websites, so the widget will not load there.`, fix: `A workspace owner or admin adds it in CommentKit, in ${DASHBOARD.addresses}.` });
656
+ else if (answer.status === 200) {
657
+ const environment = clean(answer.json.environment, 30);
658
+ checks.push({ id: "site.origin", status: "pass", message: `${origin} is on the project's allowed websites${environment ? ` (${environment})` : ""}.` });
659
+ config ??= answer.json;
660
+ }
661
+ else if (answer.status === 404)
662
+ checks.push({ id: "site.origin", status: "fail", message: `CommentKit does not know the key ${maskKey(originKey)} used on the page.`, fix: `Copy the key again from ${DASHBOARD.install} in CommentKit.` });
663
+ else
664
+ checks.push({ id: "site.origin", status: "warn", message: `Could not check whether ${origin} is allowed (HTTP ${answer.status}).`, fix: `Run ${CLI} doctor again in a minute.` });
665
+ }
666
+ }
667
+ // (d) Plain http on a real host: the page loads, but signing in to comment needs https.
668
+ if (site.protocol === "http:" && !isLocalHost(site.hostname)) {
669
+ checks.push({ id: "site.https", status: "warn", message: `${site.origin} uses plain http: reviewers cannot sign in to comment there.`, fix: "Serve the site over https." });
670
+ }
671
+ if (!page) {
672
+ checks.push({ id: "site.page", status: "fail", message: `Could not open ${shown} (${clean(pageError, 120)}).`, fix: `Check the address and that the site is up, then run ${CLI} doctor again.` });
673
+ }
674
+ else {
675
+ if (page.status >= 400)
676
+ checks.push({ id: "site.page", status: "warn", message: `${shown} answered HTTP ${page.status}; the checks below use that response.`, fix: "Check the address, or give the page where the widget should appear." });
677
+ if (page.truncated)
678
+ checks.push({ id: "site.size", status: "info", message: `The page is larger than ${Math.round((deps.maxBytes ?? MAX_PAGE_BYTES) / 1024 / 1024) || 1} MB; only the start was checked.` });
679
+ // (b) The loader tag, or signs of the bundled SDK.
680
+ if (sdk.loader) {
681
+ const loaderKey = sdk.loader.key;
682
+ if (!loaderKey)
683
+ checks.push({ id: "site.sdk", status: "fail", message: "The page has the CommentKit script tag, but without a project key.", fix: `Add data-project="pk_…" to the script tag (the key is in ${DASHBOARD.install} in CommentKit).` });
684
+ else if (!PUBLISHABLE_KEY.test(loaderKey))
685
+ checks.push({ id: "site.sdk", status: "fail", message: "The CommentKit script tag on the page has a key that is not a publishable key.", fix: `Copy the key again from ${DASHBOARD.install} in CommentKit into data-project.` });
686
+ else {
687
+ checks.push({ id: "site.sdk", status: "pass", message: `The page has the CommentKit script tag (key ${maskKey(loaderKey)}).` });
688
+ if (setup.key && PUBLISHABLE_KEY.test(setup.key) && setup.key !== loaderKey)
689
+ checks.push({ id: "site.key-match", status: "warn", message: `The page uses the key ${maskKey(loaderKey)}, this folder ${maskKey(setup.key)}.`, fix: "If the site is deployed from this folder, deploy again or use the same key." });
690
+ }
691
+ }
692
+ else if (sdk.markers.length) {
693
+ checks.push({ id: "site.sdk", status: "pass", message: `The page shows signs of the bundled SDK (${sdk.markers.join(", ")}).` });
694
+ }
695
+ else {
696
+ checks.push({ id: "site.sdk", status: "warn", message: "CommentKit is not in the page's HTML. An app that renders in the browser may add it later, so this is not certain.", fix: `Open the page and look for the Comment button; if it is missing, check that the widget is added to the page's layout (${CLI} init).` });
697
+ }
698
+ // (c) Content Security Policy: response header(s) and <meta http-equiv>.
699
+ const headerCsp = page.headers.get("content-security-policy");
700
+ const meta = metaCsp(page.html);
701
+ const policies = parseCsp([...(headerCsp ? [headerCsp] : []), ...meta]);
702
+ if (!policies.length) {
703
+ checks.push({ id: "site.csp", status: "pass", message: "The page has no Content Security Policy, so nothing blocks CommentKit." });
704
+ }
705
+ else {
706
+ const where = headerCsp && meta.length ? "the Content-Security-Policy header and <meta> tag" : headerCsp ? "the Content-Security-Policy header" : "the <meta http-equiv=\"Content-Security-Policy\"> tag";
707
+ const pageUrl = page.url.href;
708
+ // The loader comes from the CDN and imports the widget from the same folder (src/loader.ts).
709
+ // A bundled SDK is the site's own code, so script-src only matters for the script tag.
710
+ if (sdk.loader || !setup.bundled) {
711
+ const loaderSrc = sdk.loader?.src ?? `${endpoint}/cdn/v1/loader.js`;
712
+ const origin = new URL(loaderSrc).origin;
713
+ const v = cspAllows(policies, "script", loaderSrc, pageUrl, sdk.loader?.nonce ?? undefined);
714
+ if (v.allowed)
715
+ checks.push({ id: "site.csp.script", status: "pass", message: `The page's CSP lets the CommentKit script load from ${origin}.` });
716
+ else if (v.needsNonce)
717
+ checks.push({ id: "site.csp.script", status: "fail", message: `The page's CSP (${v.directive} with 'strict-dynamic') only runs scripts that carry its nonce, and the CommentKit script tag does not.`, fix: 'Add your page\'s nonce to the tag: <script nonce="…" src="…/loader.js" …>.' });
718
+ else
719
+ checks.push({ id: "site.csp.script", status: "fail", message: `The page's CSP blocks the CommentKit script: ${v.directive} does not allow ${origin}.`, fix: cspFix(v, "script", origin, where) });
720
+ }
721
+ // The widget calls the API on the CommentKit server (src/core/client.ts, endpoint).
722
+ const api = cspAllows(policies, "connect", `${endpoint}/api/v1/widget/config`, pageUrl);
723
+ if (api.allowed)
724
+ checks.push({ id: "site.csp.connect", status: "pass", message: `The page's CSP lets the widget talk to ${ck.origin}.` });
725
+ else
726
+ checks.push({ id: "site.csp.connect", status: "fail", message: `The page's CSP blocks the widget's requests: ${api.directive} does not allow ${ck.origin}.`, fix: cspFix(api, "connect", ck.origin, where) });
727
+ // Images: emoji are <img src="<endpoint>/cdn/emoji/<code>.svg"> (src/ui/format.tsx Emoji, base set in
728
+ // src/ui/mount.tsx from client.assets in src/core/client.ts); screenshot thumbnails are <img> from
729
+ // thumbnail_url (src/ui/ThreadCard.tsx). A blocked emoji falls back to the device's own, so a warning.
730
+ const img = cspAllows(policies, "img", `${endpoint}/cdn/emoji/1f44d.svg`, pageUrl);
731
+ if (img.allowed)
732
+ checks.push({ id: "site.csp.img", status: "pass", message: `The page's CSP lets screenshots and emoji load from ${ck.origin}.` });
733
+ else
734
+ checks.push({ id: "site.csp.img", status: "warn", message: `The page's CSP blocks images from ${ck.origin} (${img.directive}): screenshots and emoji will not show in the widget.`, fix: cspFix(img, "img", ck.origin, where) });
735
+ // Live updates: a web socket to the realtime host from /widget/config (src/core/realtime.ts).
736
+ const rt = config?.realtime;
737
+ if (rt && typeof rt.host === "string" && /^[a-z0-9.-]+$/i.test(rt.host)) {
738
+ const scheme = rt.scheme === "http" ? "ws" : "wss";
739
+ const port = typeof rt.port === "number" && rt.port !== (scheme === "wss" ? 443 : 80) ? `:${rt.port}` : "";
740
+ const socket = `${scheme}://${rt.host}${port}`;
741
+ const v = cspAllows(policies, "connect", `${socket}/app/x`, pageUrl);
742
+ if (v.allowed)
743
+ checks.push({ id: "site.csp.realtime", status: "pass", message: `The page's CSP allows live updates (${socket}).` });
744
+ else
745
+ checks.push({ id: "site.csp.realtime", status: "warn", message: `The page's CSP blocks live updates (${socket}); the widget still works, new feedback shows after a reload.`, fix: cspFix(v, "connect", socket, where) });
746
+ }
747
+ // Trusted Types: screenshots write one fixed string through the SDK's own policy (vite.config.ts), which
748
+ // the page's trusted-types directive must let it create. Without require-trusted-types-for nothing needs it.
749
+ if (policies.some((p) => p.has("require-trusted-types-for"))) {
750
+ const tt = trustedTypesAllowed(policies);
751
+ if (tt.allowed)
752
+ checks.push({ id: "site.csp.trusted-types", status: "pass", message: `The page requires Trusted Types; CommentKit supports that (it never writes HTML into the page, and its screenshots use one policy, ${TRUSTED_TYPES_POLICY}, that the page allows).` });
753
+ else
754
+ checks.push({ id: "site.csp.trusted-types", status: "warn", message: `The page requires Trusted Types and its trusted-types directive does not allow CommentKit's policy (${TRUSTED_TYPES_POLICY}): comments can be written, but screenshots will not be taken.`, fix: `Add ${TRUSTED_TYPES_POLICY} to trusted-types in ${where}: trusted-types ${[...tt.sources.filter((s) => s.toLowerCase() !== "'none'"), TRUSTED_TYPES_POLICY].join(" ")}` });
755
+ }
756
+ }
757
+ }
758
+ // Who sees the button on a real website: the widget stays hidden for visitors (src/activation.ts).
759
+ if (!isDevHost(site.hostname)) {
760
+ checks.push({ id: "site.visibility", status: "info", message: `On ${site.host} the Comment button is hidden from ordinary visitors. It appears after opening a share link, for signed-in reviewers, or after pressing Cmd+Shift+K (Ctrl+Shift+K on Windows).` });
761
+ }
762
+ }
763
+ // Without an address only this folder and the key were checked. Say how to check the site too.
764
+ if (!site && (setup.appFound || key)) {
765
+ const found = siteAddress(options.cwd);
766
+ checks.push(found
767
+ ? { id: "site.suggest", status: "info", message: `To also check that ${found.url} is on the project's allowed websites and that its Content Security Policy lets CommentKit load, run ${CLI} doctor ${found.url} (address from ${found.source}).` }
768
+ : { id: "site.suggest", status: "info", message: `To also check that your site is on the project's allowed websites and that its Content Security Policy lets CommentKit load, run ${CLI} doctor with its address, for example ${CLI} doctor https://staging.example.com.` });
769
+ }
770
+ // 5. Version: GET /sdk/latest is the newest stable SDK (public, no key needed). A canary rolling out is not
771
+ // offered: only what every site gets once it is stable.
772
+ if (reachable && setup.installedVersion) {
773
+ const answer = await getJson(fetchFn, `${endpoint}/api/v1/sdk/latest`, {}, timeoutMs);
774
+ const version = "error" in answer || answer.status !== 200 ? null : answer.json.version;
775
+ if (typeof version === "string" && /^\d+\.\d+\.\d+$/.test(version) && compareVersions(setup.installedVersion, version) < 0) {
776
+ checks.push({ id: "version", status: "info", message: `CommentKit ${version} is available; this app has ${setup.installedVersion}.`, fix: `Update when convenient: npm install ${SDK}@${version} (or your package manager's equivalent), then deploy.` });
777
+ }
778
+ }
779
+ return { ok: !checks.some((c) => c.status === "fail"), endpoint, url: site ? safeUrl(site.href) : null, checks };
780
+ }
781
+ /** The terminal report: one line per check, then a summary. */
782
+ export function render(result) {
783
+ const lines = [`CommentKit doctor (${result.endpoint})`, ""];
784
+ for (const c of result.checks)
785
+ lines.push(`${MARK[c.status]} ${c.message}${c.fix && c.status !== "pass" ? ` ${c.fix}` : ""}`);
786
+ const failed = result.checks.filter((c) => c.status === "fail").length;
787
+ lines.push("", failed ? `${failed} problem${failed === 1 ? "" : "s"} found. Fix the ✗ lines, then run ${CLI} doctor again.` : "Everything CommentKit needs is in place.");
788
+ return lines;
789
+ }