@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,537 @@
1
+ // The `commentkit` command.
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { dirname, join, relative, resolve } from "node:path";
5
+ import { createInterface } from "node:readline/promises";
6
+ import { parseArgs } from "node:util";
7
+ import { CliError, endpointFrom, pollDevice, Project, registerClient, SIGN_IN_AGAIN, startDevice } from "./api.js";
8
+ import { DASHBOARD } from "../shared/dashboard-places.js";
9
+ import { forget, load, save } from "./credentials.js";
10
+ import { doctor, render } from "./doctor.js";
11
+ import { feedbackMarkdown } from "./format.js";
12
+ import { describePlace, ignoreFolder, plan, PLUGIN_NODE_NOTE, setEnv } from "./init.js";
13
+ import { AGENTS, backup, configPath, DEFAULT_SCOPE, entry, gitPlace, mergeJson, mergeToml, NEXT_STEP, readIfExists, writeAtomic } from "./mcp.js";
14
+ import { openUrl } from "./open.js";
15
+ /** The publishable key format; a test keeps it equal to the pattern in contract/openapi-v1.yaml. */
16
+ export const PUBLISHABLE_KEY = /^pk_(live|test)_[a-z0-9]{20,40}$/;
17
+ const HELP = `CommentKit in your terminal.
18
+
19
+ Usage: npx @commentkit/comment-kit <command> [options]
20
+
21
+ login Sign in with your browser and choose a project
22
+ logout Forget the sign-in on this computer
23
+ status Show who and which project you are signed in to
24
+ init Add the key, the build plugin and the widget to your app
25
+ doctor [url] Find out why the widget is not showing (this folder and your site)
26
+ pull Save open feedback and tasks to .commentkit/feedback.md
27
+ open [CK-12] Open a task (or the task board) in the browser
28
+ token list|create|revoke Manage tokens for CI
29
+ mcp install <agent> Add CommentKit to Cursor, VS Code, Claude Code or Codex
30
+
31
+ Options:
32
+ --help Show help for a command (npx @commentkit/comment-kit init --help)
33
+ --yes (init, mcp install) Apply every change without asking
34
+ --dry-run (init, mcp install) Show what would change, change nothing
35
+ --install (init) Also install the package
36
+ --key <pk_…> (init, doctor) Use this project key without signing in
37
+ --all (pull) Include resolved feedback
38
+ --out <file> (pull) Where to write (default .commentkit/feedback.md)
39
+ --json (pull, token list, status, doctor) Print JSON
40
+ --reply, --status (token create) Let the token reply / mark ready for review
41
+ --days <n> (token create) Days until it expires (default 30, up to 90)
42
+
43
+ CI: set COMMENTKIT_TOKEN and COMMENTKIT_PROJECT_ID instead of logging in.
44
+ Another server: set COMMENTKIT_ENDPOINT (default https://commentkit.dev).
45
+ `;
46
+ const COMMAND_HELP = {
47
+ login: `Usage: npx @commentkit/comment-kit login [--no-browser] [--scopes read,reply,status]
48
+
49
+ Shows a short code and opens CommentKit in your browser. Confirm the code, then choose
50
+ the project and what the CLI may do.
51
+
52
+ --no-browser Print the link instead of opening it
53
+ --scopes <list> What to ask for (default read,reply,status)`,
54
+ logout: `Usage: npx @commentkit/comment-kit logout
55
+
56
+ Forgets the sign-in on this computer. To end it on the server too, disconnect it in
57
+ CommentKit, in Settings → Security, under Connected coding agents.`,
58
+ status: `Usage: npx @commentkit/comment-kit status [--json]
59
+
60
+ Which project you are signed in to, what the CLI may do, and whether agent changes wait
61
+ for a person's approval.
62
+
63
+ --json Print JSON`,
64
+ init: `Usage: npx @commentkit/comment-kit init [--yes] [--dry-run] [--install] [--key pk_…]
65
+
66
+ Finds your framework (Next.js, Vite, SvelteKit, Astro, Nuxt, Laravel or a plain website) and
67
+ sets CommentKit up: the key in your env file (Laravel: in the entry, as the default), the build
68
+ plugin in your config, .commentkit/ in .gitignore, and the widget in your layout or entry file.
69
+ Asks before each change.
70
+
71
+ --yes, -y Make every change without asking
72
+ --dry-run Show what would change, change nothing
73
+ --install Also install the package
74
+ --key <pk_…> Use this project key without signing in`,
75
+ doctor: `Usage: npx @commentkit/comment-kit doctor [url] [--key pk_…] [--json]
76
+
77
+ Finds out why the widget is not showing. Checks the package or script tag and the key in this
78
+ folder, and the key with CommentKit (unknown, paused or read-only). With your site's address it
79
+ also checks that the site is on the project's allowed websites, that the page has CommentKit,
80
+ and that its Content Security Policy lets CommentKit load. Sends no cookies or passwords.
81
+ Exits 0 when nothing is wrong, 1 when something is.
82
+
83
+ url Your website, http:// or https:// (for example https://staging.acme.com)
84
+ --key <pk_…> Check this project key instead of the one found in this folder
85
+ --json Print the result as JSON`,
86
+ pull: `Usage: npx @commentkit/comment-kit pull [--all] [--out <file>] [--json]
87
+
88
+ Saves open feedback and tasks to .commentkit/feedback.md for your coding agent. Reviewer
89
+ text is fenced as untrusted content.
90
+
91
+ --all Include resolved feedback
92
+ --out <file> Where to write (default .commentkit/feedback.md)
93
+ --json Print JSON instead`,
94
+ open: `Usage: npx @commentkit/comment-kit open [CK-12]
95
+
96
+ Opens the task in your browser, or the task board without a reference.`,
97
+ token: `Usage: npx @commentkit/comment-kit token list [--json]
98
+ npx @commentkit/comment-kit token create "<name>" [--reply] [--status] [--days <n>]
99
+ npx @commentkit/comment-kit token revoke <id>
100
+
101
+ Tokens for CI (COMMENTKIT_TOKEN), never with more permissions than your sign-in.
102
+
103
+ --reply Let the token reply to feedback
104
+ --status Let the token mark feedback ready for review and link commits
105
+ --days <n> Days until it expires (default 30, 1 to 90)
106
+ --json (list) Print JSON`,
107
+ mcp: `Usage: npx @commentkit/comment-kit mcp install <cursor|vscode|claude|codex> [--scope user|project] [--dry-run] [--yes]
108
+
109
+ Adds the hosted CommentKit MCP server (https://commentkit.dev/mcp) to your coding agent's
110
+ config file. Nothing else in the file changes (its indentation and last newline stay), and it
111
+ is backed up first. Your agent asks you to sign in the first time.
112
+
113
+ cursor ~/.cursor/mcp.json (--scope project: .cursor/mcp.json)
114
+ vscode .vscode/mcp.json (--scope user: your VS Code profile's mcp.json)
115
+ claude ~/.claude.json (--scope project: .mcp.json)
116
+ codex ~/.codex/config.toml
117
+
118
+ --scope <s> user or project (defaults above)
119
+ --dry-run Show the change, write nothing
120
+ --yes, -y Replace an existing commentkit entry without asking`,
121
+ };
122
+ COMMAND_HELP.whoami = COMMAND_HELP.status;
123
+ COMMAND_HELP.tokens = COMMAND_HELP.token;
124
+ const console_ = { log: (t) => process.stdout.write(`${t}\n`), error: (t) => process.stderr.write(`${t}\n`) };
125
+ export async function main(argv, out = console_, cwd = process.cwd()) {
126
+ const [command, ...rest] = argv;
127
+ if (!command || command === "--help" || command === "-h" || command === "help") {
128
+ out.log(HELP);
129
+ return 0;
130
+ }
131
+ // Per-command help never needs a sign-in or the network.
132
+ if (rest.includes("--help") || rest.includes("-h")) {
133
+ out.log(COMMAND_HELP[command] ?? HELP);
134
+ return 0;
135
+ }
136
+ try {
137
+ switch (command) {
138
+ case "login":
139
+ return await login(rest, out);
140
+ case "logout":
141
+ return await logout(out);
142
+ case "status":
143
+ case "whoami":
144
+ return await status(rest, out);
145
+ case "init":
146
+ return await init(rest, out, cwd);
147
+ case "pull":
148
+ return await pull(rest, out, cwd);
149
+ case "doctor":
150
+ return await runDoctor(rest, out, cwd);
151
+ case "open":
152
+ return await open(rest, out);
153
+ case "token":
154
+ case "tokens":
155
+ return await token(rest, out);
156
+ case "mcp":
157
+ return await mcp(rest, out, cwd);
158
+ case "--version":
159
+ case "-v":
160
+ out.log(version());
161
+ return 0;
162
+ default:
163
+ out.error(`Unknown command “${command}”. Run npx @commentkit/comment-kit --help.`);
164
+ return 2;
165
+ }
166
+ }
167
+ catch (error) {
168
+ // node:util parseArgs: an unknown option or a missing value is a usage mistake, not a crash.
169
+ if (error instanceof Error && String(error.code).startsWith("ERR_PARSE_ARGS")) {
170
+ out.error(`${error.message} Run npx @commentkit/comment-kit ${command} --help.`);
171
+ return 2;
172
+ }
173
+ out.error(error instanceof CliError || error instanceof Error ? `Error: ${error.message}` : String(error));
174
+ return 1;
175
+ }
176
+ }
177
+ function version() {
178
+ try {
179
+ // dist/node/cli/main.js → the package root.
180
+ return JSON.parse(readFileSync(new URL("../../../package.json", import.meta.url), "utf8")).version;
181
+ }
182
+ catch {
183
+ return "unknown";
184
+ }
185
+ }
186
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
187
+ async function login(args, out) {
188
+ const { values } = parseArgs({ args, options: { "no-browser": { type: "boolean" }, scopes: { type: "string" } }, allowPositionals: false });
189
+ const endpoint = endpointFrom();
190
+ let clientId = load(endpoint).client_id;
191
+ if (!clientId) {
192
+ clientId = await registerClient(endpoint);
193
+ await save(endpoint, { client_id: clientId });
194
+ }
195
+ const wanted = (values.scopes ?? "read,reply,status").split(",").map((s) => s.trim()).filter(Boolean);
196
+ const scope = ["feedback:read", ...wanted.filter((s) => s !== "read").map((s) => `feedback:${s}`)].join(" ");
197
+ let device;
198
+ try {
199
+ device = await startDevice(endpoint, clientId, scope);
200
+ }
201
+ catch (error) {
202
+ if (error instanceof CliError && error.code === "invalid_client") {
203
+ clientId = await registerClient(endpoint);
204
+ await save(endpoint, { client_id: clientId });
205
+ device = await startDevice(endpoint, clientId, scope);
206
+ }
207
+ else
208
+ throw error;
209
+ }
210
+ // Only the plain page is opened: a link with the code already in it is a phishing path (someone could send
211
+ // their own link), so the person types the code they see here. Never a URL built with the code.
212
+ out.log(`\nYour code: ${device.user_code}\n`);
213
+ out.log(`Type this code on ${device.verification_uri}, then choose the project.`);
214
+ if (!values["no-browser"] && (await openUrl(device.verification_uri)))
215
+ out.log("(Opened that page in your browser.)");
216
+ out.log("Waiting for you to confirm…");
217
+ let interval = Math.max(1, device.interval) * 1000;
218
+ const deadline = Date.now() + device.expires_in * 1000;
219
+ while (Date.now() < deadline) {
220
+ await sleep(interval);
221
+ const answer = await pollDevice(endpoint, clientId, device.device_code);
222
+ if (typeof answer !== "string")
223
+ return finishLogin(endpoint, clientId, answer, out);
224
+ if (answer === "authorization_pending")
225
+ continue;
226
+ if (answer === "slow_down") {
227
+ interval += 5000;
228
+ continue;
229
+ }
230
+ if (answer === "access_denied")
231
+ throw new CliError("Sign-in was cancelled in the browser.");
232
+ if (answer === "expired_token")
233
+ break;
234
+ if (answer === "invalid_client")
235
+ throw new CliError(SIGN_IN_AGAIN, "signed_out");
236
+ throw new CliError(`Sign-in failed (${answer}). Run npx @commentkit/comment-kit login again.`);
237
+ }
238
+ throw new CliError("The code expired before it was confirmed. Run npx @commentkit/comment-kit login again.");
239
+ }
240
+ async function finishLogin(endpoint, clientId, answer, out) {
241
+ if (!answer.project?.id)
242
+ throw new CliError("Signed in, but CommentKit did not say which project was chosen. Update the CLI and try again.");
243
+ await save(endpoint, {
244
+ client_id: clientId,
245
+ access_token: answer.access_token,
246
+ refresh_token: answer.refresh_token,
247
+ expires_at: Date.now() + answer.expires_in * 1000,
248
+ scope: answer.scope,
249
+ project_id: answer.project.id,
250
+ project_name: answer.project.name,
251
+ });
252
+ out.log(`\nSigned in. Project: ${answer.project.name}. Allowed: ${permissions(answer.scope)}.`);
253
+ return 0;
254
+ }
255
+ function permissions(scope) {
256
+ const parts = scope.split(" ");
257
+ return ["read", parts.includes("feedback:reply") ? "reply" : null, parts.includes("feedback:status") ? "status and commit links" : null, parts.includes("cli") ? "CI tokens" : null].filter(Boolean).join(", ");
258
+ }
259
+ async function logout(out) {
260
+ // CommentKit has no endpoint yet for a terminal sign-in to end itself, so this is local only.
261
+ const had = await forget(endpointFrom());
262
+ out.log(had
263
+ ? `Signed out on this computer. The sign-in still works on the server until it expires (30 days unused); to end it now, disconnect it in CommentKit, in ${DASHBOARD.connectedAgents}.`
264
+ : "You were not signed in.");
265
+ return 0;
266
+ }
267
+ async function status(args, out) {
268
+ const { values } = parseArgs({ args, options: { json: { type: "boolean" } } });
269
+ const endpoint = endpointFrom();
270
+ const project = await Project.connect(endpoint);
271
+ const info = await project.request("");
272
+ const credential = load(endpoint);
273
+ if (values.json) {
274
+ out.log(JSON.stringify({ endpoint, project: info.data, scope: credential.scope ?? null }, null, 2));
275
+ return 0;
276
+ }
277
+ out.log(`Endpoint: ${endpoint}`);
278
+ out.log(`Project: ${String(info.data.name)} (id ${project.projectId})`);
279
+ if (credential.scope)
280
+ out.log(`Allowed: ${permissions(credential.scope)}`);
281
+ out.log(`Agent changes ${info.data.agent_approval ? "wait for a person's approval" : "apply right away"}.`);
282
+ return 0;
283
+ }
284
+ async function ask(question, yes) {
285
+ if (yes)
286
+ return true;
287
+ if (!process.stdin.isTTY)
288
+ return false;
289
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
290
+ try {
291
+ return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
292
+ }
293
+ finally {
294
+ rl.close();
295
+ }
296
+ }
297
+ function run(command, cwd) {
298
+ return new Promise((resolve) => {
299
+ const child = spawn(command[0], command.slice(1), { cwd, stdio: "inherit", shell: process.platform === "win32" });
300
+ child.on("error", () => resolve(1));
301
+ child.on("exit", (code) => resolve(code ?? 1));
302
+ });
303
+ }
304
+ async function init(args, out, cwd) {
305
+ const { values } = parseArgs({ args, options: { yes: { type: "boolean", short: "y" }, install: { type: "boolean" }, key: { type: "string" }, "dry-run": { type: "boolean" } } });
306
+ const yes = Boolean(values.yes);
307
+ const dryRun = Boolean(values["dry-run"]);
308
+ let key = values.key;
309
+ if (!key) {
310
+ const info = await (await Project.connect()).request("");
311
+ key = info.data.publishable_keys.live ?? info.data.publishable_keys.test ?? undefined;
312
+ if (!key)
313
+ throw new CliError(`This website has no publishable key yet. In CommentKit, open ${DASHBOARD.install} and press Create the key, then try again.`);
314
+ out.log(`Project: ${info.data.name}`);
315
+ }
316
+ if (!PUBLISHABLE_KEY.test(key))
317
+ throw new CliError("That is not a publishable key (pk_live_… or pk_test_…).");
318
+ const p = plan(cwd, key);
319
+ out.log(`Found ${p.label}.${dryRun ? " Dry run: nothing is changed." : ""}\n`);
320
+ let skipped = 0;
321
+ // Each change is shown and confirmed (or --yes) before it is written; --dry-run only shows it.
322
+ const change = async (file, before, after, question) => {
323
+ if (after === before)
324
+ return;
325
+ if (dryRun) {
326
+ out.log(`Would ${existsSync(join(cwd, file)) ? "change" : "create"} ${file}:\n${addedLines(before, after)}\n`);
327
+ return;
328
+ }
329
+ if (await ask(question, yes)) {
330
+ mkdirSync(dirname(join(cwd, file)), { recursive: true });
331
+ writeFileSync(join(cwd, file), after);
332
+ }
333
+ else
334
+ skipped++;
335
+ };
336
+ const readOr = (file) => (existsSync(join(cwd, file)) ? readFileSync(join(cwd, file), "utf8") : "");
337
+ if (p.envVar && p.envFile) {
338
+ const before = readOr(p.envFile);
339
+ await change(p.envFile, before, setEnv(before, p.envVar, key), `Add ${p.envVar} to ${p.envFile}?`);
340
+ }
341
+ const ignoreBefore = readOr(".gitignore");
342
+ await change(".gitignore", ignoreBefore, ignoreFolder(ignoreBefore), "Add .commentkit/ to .gitignore (pulled feedback stays on your computer)?");
343
+ const configBefore = p.configFile ? readOr(p.configFile) : "";
344
+ if (p.configFile && p.configEdit) {
345
+ await change(p.configFile, configBefore, p.configEdit, `Add the CommentKit build plugin to ${p.configFile}?`);
346
+ }
347
+ else if (p.configFile && !p.configEdit) {
348
+ out.log(`Could not edit ${p.configFile} safely, so it was left as it is. Add the build plugin by hand:\n ${p.configSnippet}\n${PLUGIN_NODE_NOTE}\n(more: https://commentkit.dev/docs/frameworks)\n`);
349
+ }
350
+ if (p.entry && p.entry !== "done") {
351
+ const { file, content, created } = p.entry;
352
+ await change(file, created ? "" : readOr(file), content, created ? `Create ${file} to show the widget?` : `Show the widget: add it to ${file}?`);
353
+ }
354
+ for (const line of p.manual)
355
+ out.log(`By hand: ${line}`);
356
+ for (const line of p.notes)
357
+ out.log(line);
358
+ // Laravel servers often build on deploy, with whatever Node they have.
359
+ if (p.framework === "laravel" && p.configFile && p.configEdit && p.configEdit !== configBefore)
360
+ out.log(PLUGIN_NODE_NOTE);
361
+ if (p.install.length) {
362
+ if (values.install && !dryRun) {
363
+ for (const command of p.install) {
364
+ out.log(`$ ${command.join(" ")}`);
365
+ if ((await run(command, cwd)) !== 0)
366
+ throw new CliError(`${command.join(" ")} failed.`);
367
+ }
368
+ }
369
+ else {
370
+ out.log("\nInstall the package:");
371
+ for (const command of p.install)
372
+ out.log(` ${command.join(" ")}`);
373
+ }
374
+ }
375
+ if (p.entry === "done")
376
+ out.log(`\nThe widget is already in your app${p.widget ? ` (${describePlace(p.widget)})` : ""}.`);
377
+ else if (!p.entry)
378
+ out.log(`\nLast step, show the widget. ${p.snippet}\n`);
379
+ if (dryRun) {
380
+ out.log("\nRun it again without --dry-run to make these changes.");
381
+ return 0;
382
+ }
383
+ if (skipped && !process.stdin.isTTY && !yes)
384
+ out.log(`${skipped} change(s) were not made. Run npx @commentkit/comment-kit init --yes to apply them.`);
385
+ out.log("Then start your dev server: the Comment button appears on localhost for your team.");
386
+ return 0;
387
+ }
388
+ /** The lines `after` adds to `before`, marked with +, for a dry run. */
389
+ export function addedLines(before, after) {
390
+ const old = new Set(before.split("\n"));
391
+ return after.split("\n").filter((line) => !old.has(line)).map((line) => ` + ${line}`).join("\n");
392
+ }
393
+ async function mcp(args, out, cwd) {
394
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { scope: { type: "string" }, "dry-run": { type: "boolean" }, yes: { type: "boolean", short: "y" } } });
395
+ const [sub, agent] = positionals;
396
+ if (sub !== "install")
397
+ throw new CliError("Use: npx @commentkit/comment-kit mcp install <cursor|vscode|claude|codex>");
398
+ if (!AGENTS.includes(agent))
399
+ throw new CliError(`Which agent? Use one of: ${AGENTS.join(", ")}.`);
400
+ const target = agent;
401
+ if (values.scope !== undefined && values.scope !== "user" && values.scope !== "project")
402
+ throw new CliError("--scope is user or project.");
403
+ const scope = values.scope ?? DEFAULT_SCOPE[target];
404
+ const url = `${endpointFrom()}/mcp`;
405
+ const file = configPath(target, scope, cwd);
406
+ const before = readIfExists(file);
407
+ let merged;
408
+ try {
409
+ merged = target === "codex" ? mergeToml(before, url) : mergeJson(before, target, url);
410
+ }
411
+ catch (error) {
412
+ const manual = target === "codex" ? `[mcp_servers.commentkit]\nurl = "${url}"` : JSON.stringify({ [target === "vscode" ? "servers" : "mcpServers"]: { commentkit: entry(target, url) } }, null, 2);
413
+ out.error(`Did not change ${file}: ${error instanceof Error ? error.message : String(error)}. Add this by hand:\n\n${manual}\n`);
414
+ return 1;
415
+ }
416
+ if (merged.status === "same") {
417
+ out.log(`CommentKit is already set up in ${file}.`);
418
+ out.log(NEXT_STEP[target]);
419
+ return 0;
420
+ }
421
+ // A project file that git ignores stays on this computer: each developer adds it for themselves.
422
+ const ignored = scope === "project" ? gitPlace(file) : null;
423
+ const ignoredNote = ignored?.ignored
424
+ ? `Git ignores ${relative(cwd, file) || file}${ignored.rule ? ` (${ignored.rule})` : ""}, so this stays on this computer and is not shared through the repository: each developer who wants CommentKit in their agent runs npx @commentkit/comment-kit mcp install ${target} --scope project themselves.`
425
+ : null;
426
+ if (values["dry-run"]) {
427
+ out.log(`Would ${before === null ? "create" : merged.status === "replaced" ? "replace the commentkit entry in" : "add CommentKit to"} ${file}:\n${addedLines(before ?? "", merged.content)}`);
428
+ if (ignoredNote)
429
+ out.log(ignoredNote);
430
+ out.log("\nRun it again without --dry-run to write it.");
431
+ return 0;
432
+ }
433
+ if (merged.status === "replaced" && !(await ask(`${file} already has a different commentkit entry. Replace it?`, Boolean(values.yes)))) {
434
+ out.log("Left it as it is. Use --yes to replace it.");
435
+ return 1;
436
+ }
437
+ const copy = before !== null ? backup(file) : null;
438
+ writeAtomic(file, merged.content);
439
+ const away = copy && dirname(copy) !== dirname(file) ? " (kept outside the repository, so git does not pick it up)" : "";
440
+ out.log(`${merged.status === "replaced" ? "Replaced" : "Added"} CommentKit (${url}) in ${file}.${copy ? ` Backup: ${copy}${away}` : ""}`);
441
+ if (ignoredNote)
442
+ out.log(ignoredNote);
443
+ out.log(NEXT_STEP[target]);
444
+ return 0;
445
+ }
446
+ async function runDoctor(args, out, cwd) {
447
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { json: { type: "boolean" }, key: { type: "string" } } });
448
+ if (positionals.length > 1)
449
+ throw new CliError("Give one website address, for example: npx @commentkit/comment-kit doctor https://staging.acme.com");
450
+ const result = await doctor({ cwd, url: positionals[0], key: values.key });
451
+ if (values.json)
452
+ out.log(JSON.stringify(result, null, 2));
453
+ else
454
+ for (const line of render(result))
455
+ out.log(line);
456
+ return result.ok ? 0 : 1;
457
+ }
458
+ /** pull saves at most this many items (the most recently active first). */
459
+ const PULL_MAX = 500;
460
+ async function pull(args, out, cwd) {
461
+ const { values } = parseArgs({ args, options: { out: { type: "string" }, json: { type: "boolean" }, all: { type: "boolean" } } });
462
+ const project = await Project.connect();
463
+ const info = await project.request("");
464
+ const threads = [];
465
+ let cursor;
466
+ do {
467
+ const page = await project.request("/threads", { query: { kind: "all", status: values.all ? "all" : "active", limit: 100, cursor } });
468
+ threads.push(...page.data);
469
+ cursor = page.next_cursor ?? undefined;
470
+ } while (cursor && threads.length < PULL_MAX);
471
+ const more = Boolean(cursor);
472
+ if (values.json) {
473
+ out.log(JSON.stringify(threads, null, 2));
474
+ return 0;
475
+ }
476
+ const file = resolve(cwd, values.out ?? ".commentkit/feedback.md");
477
+ mkdirSync(dirname(file), { recursive: true });
478
+ writeFileSync(file, feedbackMarkdown(info.data.name, threads, new Date(), more));
479
+ out.log(`Saved ${threads.length} item(s) to ${file}.${more ? ` There are more: only the ${PULL_MAX} with the latest activity were saved.` : ""}`);
480
+ return 0;
481
+ }
482
+ async function open(args, out) {
483
+ const ref = args[0];
484
+ if (ref && !/^(CK-)?\d{1,9}$/i.test(ref))
485
+ throw new CliError("Give a task reference like CK-12.");
486
+ const project = await Project.connect();
487
+ const info = await project.request("");
488
+ let url = info.data.tasks_url;
489
+ if (ref) {
490
+ const thread = await project.request(`/threads/${encodeURIComponent(ref.toUpperCase())}`);
491
+ url = `${info.data.tasks_url}?task=${encodeURIComponent(thread.data.id)}`;
492
+ }
493
+ out.log(url);
494
+ if (!(await openUrl(url)))
495
+ out.log("(Open the link above in your browser.)");
496
+ return 0;
497
+ }
498
+ async function token(args, out) {
499
+ const [sub, ...rest] = args;
500
+ const project = await Project.connect();
501
+ if (!sub || sub === "list") {
502
+ const { values } = parseArgs({ args: rest, options: { json: { type: "boolean" } } });
503
+ const list = await project.request("/tokens");
504
+ if (values.json)
505
+ out.log(JSON.stringify(list.data, null, 2));
506
+ else if (!list.data.length)
507
+ out.log("No agent tokens for this project.");
508
+ else
509
+ for (const t of list.data)
510
+ out.log(`${String(t.id).padEnd(6)} ${t.name.padEnd(28)} ${["read", ...t.scopes].join(",").padEnd(18)} ${t.expires_at ? `expires ${t.expires_at.slice(0, 10)}` : ""}`);
511
+ return 0;
512
+ }
513
+ if (sub === "create") {
514
+ const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { reply: { type: "boolean" }, status: { type: "boolean" }, days: { type: "string" } } });
515
+ const name = positionals.join(" ").trim();
516
+ if (!name)
517
+ throw new CliError('Give the token a name, for example: npx @commentkit/comment-kit token create "GitHub Actions" --status');
518
+ if (values.days !== undefined && !/^(?:[1-9]|[1-8]\d|90)$/.test(values.days.trim()))
519
+ throw new CliError("--days is a whole number from 1 to 90.");
520
+ const created = await project.request("/tokens", {
521
+ method: "POST",
522
+ body: { name, scopes: [values.reply ? "reply" : null, values.status ? "status" : null].filter(Boolean), ...(values.days ? { days: Number(values.days) } : {}) },
523
+ });
524
+ out.log(`Created “${created.data.name}” (id ${created.data.id}). It is shown only once:\n\n${created.data.token}\n`);
525
+ out.log(`In CI set COMMENTKIT_TOKEN to it and COMMENTKIT_PROJECT_ID=${project.projectId}.`);
526
+ return 0;
527
+ }
528
+ if (sub === "revoke") {
529
+ const id = Number(rest[0]);
530
+ if (!Number.isInteger(id) || id < 1)
531
+ throw new CliError("Give the token id from npx @commentkit/comment-kit token list.");
532
+ await project.request(`/tokens/${id}`, { method: "DELETE" });
533
+ out.log(`Revoked token ${id}.`);
534
+ return 0;
535
+ }
536
+ throw new CliError(`Unknown token command “${sub}”. Use list, create or revoke.`);
537
+ }