@githumbi/grabby 0.1.2 → 0.2.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.
package/dist/cli/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli/index.ts
4
- import { spawn } from "child_process";
5
4
  import { parseArgs } from "util";
6
5
 
7
6
  // src/cli/commands/init.ts
@@ -130,10 +129,62 @@ function patchAngularAppConfig(code) {
130
129
  const withProvider = `${code.slice(0, at)}provideGrabby(), ${code.slice(at)}`;
131
130
  return { status: "patched", code: insertImport(withProvider, "import { provideGrabby } from '@githumbi/grabby/angular';") };
132
131
  }
132
+ function tagAttrs(tag, style) {
133
+ const jsx = style === "jsx" || style === "next-script";
134
+ const q = (v) => JSON.stringify(v);
135
+ return [
136
+ `src=${q(tag.src)}`,
137
+ ...tag.integrity ? [`integrity=${q(tag.integrity)}`, jsx ? 'crossOrigin="anonymous"' : 'crossorigin="anonymous"'] : [],
138
+ ...tag.dataIntegrity ? [`data-integrity=${q(tag.dataIntegrity)}`] : [],
139
+ 'data-mode="live"',
140
+ `data-server=${q(tag.server)}`,
141
+ `data-project-key=${q(tag.projectKey)}`,
142
+ style === "next-script" ? 'strategy="afterInteractive"' : "defer",
143
+ // Astro leaves an is:inline script exactly as written instead of bundling it.
144
+ ...style === "astro" ? ["is:inline"] : []
145
+ ];
146
+ }
147
+ function renderTag(tag, style, indent = "", name = style === "next-script" ? "Script" : "script") {
148
+ const attrs = tagAttrs(tag, style).map((a) => `${indent} ${a}`).join("\n");
149
+ return style === "next-script" ? `<${name}
150
+ ${attrs}
151
+ ${indent}/>` : `<${name}
152
+ ${attrs}
153
+ ${indent}></${name}>`;
154
+ }
155
+ var EXISTING_TAG = /<(script|Script)\b(?=[^>]*@githumbi\/grabby@[^"'\s>]*\/dist\/loader\.global\.js)[^>]*?(?:\/>|>\s*<\/\1>)/;
156
+ function indentAt(code, index) {
157
+ const lineStart = code.lastIndexOf("\n", index - 1) + 1;
158
+ return /^[ \t]*/.exec(code.slice(lineStart, index))?.[0] ?? "";
159
+ }
160
+ function patchLoaderTag(code, tag, kind) {
161
+ const existing = EXISTING_TAG.exec(code);
162
+ if (existing) {
163
+ const name2 = existing[1];
164
+ const style = name2 === "Script" ? "next-script" : kind === "html" || kind === "astro" ? kind : "jsx";
165
+ const next = renderTag(tag, style, indentAt(code, existing.index), name2);
166
+ if (next === existing[0]) return { status: "already" };
167
+ return { status: "patched", code: code.slice(0, existing.index) + next + code.slice(existing.index + existing[0].length) };
168
+ }
169
+ const bodies = code.split("</body>").length - 1;
170
+ if (bodies !== 1) return { status: "unrecognised", reason: bodies ? "more than one </body>" : "no </body> found" };
171
+ const at = code.indexOf("</body>");
172
+ const indent = `${indentAt(code, at)} `;
173
+ if (kind !== "next-app") {
174
+ const withTag2 = `${code.slice(0, at)} ${renderTag(tag, kind, indent)}
175
+ ${indentAt(code, at)}${code.slice(at)}`;
176
+ return { status: "patched", code: withTag2 };
177
+ }
178
+ const imported = /import\s+(\w+)\s+from\s+['"]next\/script['"]/.exec(code);
179
+ const name = imported?.[1] ?? "Script";
180
+ const withTag = `${code.slice(0, at)} ${renderTag(tag, "next-script", indent, name)}
181
+ ${indentAt(code, at)}${code.slice(at)}`;
182
+ return { status: "patched", code: imported ? withTag : insertImport(withTag, 'import Script from "next/script";') };
183
+ }
133
184
 
134
185
  // src/cli/versions.ts
135
- var GRABBY_VERSION = "0.1.2";
136
- var SERVER_PACKAGE = `@githumbi/grabby-server@${"0.1.0"}`;
186
+ var GRABBY_VERSION = "0.2.1";
187
+ var SERVER_PACKAGE = `@githumbi/grabby-server@${"0.2.0"}`;
137
188
 
138
189
  // src/cli/commands/init.ts
139
190
  var PKG = "@githumbi/grabby";
@@ -152,6 +203,16 @@ function sri(file) {
152
203
  return null;
153
204
  }
154
205
  }
206
+ function liveTag(server, projectKey) {
207
+ return {
208
+ src: `https://cdn.jsdelivr.net/npm/${PKG}@${GRABBY_VERSION}/dist/loader.global.js`,
209
+ integrity: sri("loader.global.js"),
210
+ // The loader fetches the full build itself; data-integrity covers that file.
211
+ dataIntegrity: sri("grabby.global.js"),
212
+ server,
213
+ projectKey
214
+ };
215
+ }
155
216
  function cdnScriptTag(live) {
156
217
  const file = live ? "loader.global.js" : "grabby.global.js";
157
218
  const own = sri(file);
@@ -340,9 +401,9 @@ function getMcpServerEntry() {
340
401
  args: ["-y", SERVER_PACKAGE, "mcp"]
341
402
  };
342
403
  }
343
- async function addMcp() {
344
- log2("Adding grabby MCP server...\n");
345
- const mcpJsonPath = join3(process.cwd(), ".mcp.json");
404
+ async function addMcp(options = {}) {
405
+ if (!options.quiet) log2("Adding grabby MCP server...\n");
406
+ const mcpJsonPath = join3(options.cwd ?? process.cwd(), ".mcp.json");
346
407
  let config = {};
347
408
  if (existsSync3(mcpJsonPath)) {
348
409
  try {
@@ -357,28 +418,452 @@ async function addMcp() {
357
418
  servers[MCP_SERVER_NAME] = getMcpServerEntry();
358
419
  config.mcpServers = servers;
359
420
  writeFileSync2(mcpJsonPath, JSON.stringify(config, null, 2) + "\n");
360
- success("Added grabby MCP server to .mcp.json");
421
+ success(options.quiet ? "\x1B[32m\u2713\x1B[0m .mcp.json (grabby MCP server)" : "Added grabby MCP server to .mcp.json");
422
+ if (options.quiet) return;
361
423
  console.log("");
362
- console.log(" It also collects comments from your app on http://localhost:3456.");
363
- console.log(" Point Grabby at it: initGrabby({ server: 'http://localhost:3456' })");
424
+ console.log(" After `npx @githumbi/grabby share`, it reads your live site's feedback.");
425
+ console.log(" Otherwise it collects comments from your app on http://localhost:3456;");
426
+ console.log(" point Grabby at it: initGrabby({ server: 'http://localhost:3456' })");
364
427
  console.log("");
365
428
  console.log(" \x1B[1mRestart your editor\x1B[0m to activate the MCP connection.");
366
429
  console.log(" When prompted, \x1B[1mapprove the MCP server\x1B[0m in your editor.");
367
430
  console.log("");
368
431
  }
369
432
 
433
+ // src/cli/commands/share.ts
434
+ import { existsSync as existsSync5, readdirSync, readFileSync as readFileSync6, rmSync, writeFileSync as writeFileSync4 } from "fs";
435
+ import { join as join6, relative as relative2 } from "path";
436
+ import { createInterface as createInterface2 } from "readline";
437
+
438
+ // src/cli/utils/detect-site.ts
439
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
440
+ import { join as join4 } from "path";
441
+ var DEV_PORTS = {
442
+ next: 3e3,
443
+ nuxt: 3e3,
444
+ angular: 4200,
445
+ astro: 4321,
446
+ react: 5173,
447
+ vue: 5173,
448
+ svelte: 5173,
449
+ sveltekit: 5173,
450
+ solid: 5173,
451
+ preact: 5173
452
+ };
453
+ function devOrigin(framework) {
454
+ const port = DEV_PORTS[framework];
455
+ return port ? `http://localhost:${port}` : null;
456
+ }
457
+ function toOrigin(input) {
458
+ const raw = input.trim();
459
+ if (!raw) return null;
460
+ try {
461
+ const url = new URL(/^[a-z]+:\/\//i.test(raw) ? raw : `https://${raw}`);
462
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
463
+ if (!url.hostname.includes(".") && url.hostname !== "localhost") return null;
464
+ return url.origin;
465
+ } catch {
466
+ return null;
467
+ }
468
+ }
469
+ function guessSiteOrigins(root) {
470
+ const found = [];
471
+ try {
472
+ const pkg = JSON.parse(readFileSync4(join4(root, "package.json"), "utf8"));
473
+ const o = typeof pkg.homepage === "string" ? toOrigin(pkg.homepage) : null;
474
+ if (o && new URL(o).hostname !== "github.com") found.push(o);
475
+ } catch {
476
+ }
477
+ for (const cname of ["CNAME", "public/CNAME", "static/CNAME"]) {
478
+ const file = join4(root, cname);
479
+ if (existsSync4(file)) {
480
+ const o = toOrigin(readFileSync4(file, "utf8").split("\n")[0]);
481
+ if (o) found.push(o);
482
+ }
483
+ }
484
+ return [...new Set(found)];
485
+ }
486
+
487
+ // src/cli/utils/project-config.ts
488
+ import { appendFileSync, chmodSync, mkdirSync, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
489
+ import { dirname as dirname2, join as join5 } from "path";
490
+ var projectConfigPath = (root) => join5(root, ".grabby", "config.json");
491
+ function readProjectConfig(root) {
492
+ try {
493
+ const parsed = JSON.parse(readFileSync5(projectConfigPath(root), "utf8"));
494
+ return parsed && typeof parsed.server === "string" ? parsed : null;
495
+ } catch {
496
+ return null;
497
+ }
498
+ }
499
+ function writeProjectConfig(root, config) {
500
+ const file = projectConfigPath(root);
501
+ mkdirSync(dirname2(file), { recursive: true });
502
+ writeFileSync3(file, `${JSON.stringify(config, null, 2)}
503
+ `, { mode: 384 });
504
+ try {
505
+ chmodSync(file, 384);
506
+ } catch {
507
+ }
508
+ return file;
509
+ }
510
+ function ensureGitignore(root) {
511
+ const file = join5(root, ".gitignore");
512
+ let current = "";
513
+ try {
514
+ current = readFileSync5(file, "utf8");
515
+ } catch (err) {
516
+ if (err.code !== "ENOENT") throw err;
517
+ }
518
+ if (/^\/?\.grabby\/?\s*$/m.test(current)) return false;
519
+ const sep = current && !current.endsWith("\n") ? "\n" : "";
520
+ appendFileSync(file, `${sep}# Grabby: collector settings and admin token
521
+ .grabby/
522
+ `);
523
+ return true;
524
+ }
525
+
526
+ // src/cli/utils/server-cli.ts
527
+ import { spawn } from "child_process";
528
+ function runServer(args, options = {}) {
529
+ const local = process.env.GRABBY_SERVER_BIN;
530
+ const windows = process.platform === "win32";
531
+ const argv2 = local ? [local, ...args] : ["-y", SERVER_PACKAGE, ...args];
532
+ if (!local && windows && !argv2.every((a) => /^[\w@./:=,+-]+$/.test(a))) {
533
+ return Promise.reject(new Error(`unsupported characters in arguments; run it directly: npx ${argv2.join(" ")}`));
534
+ }
535
+ return new Promise((resolve, reject) => {
536
+ const child = spawn(local ? process.execPath : windows ? "npx.cmd" : "npx", argv2, {
537
+ stdio: ["inherit", options.captureStdout ? "pipe" : "inherit", "inherit"],
538
+ shell: !local && windows,
539
+ cwd: options.cwd,
540
+ env: { ...process.env, ...options.env }
541
+ });
542
+ let stdout = "";
543
+ child.stdout?.on("data", (chunk) => {
544
+ stdout += chunk.toString("utf8");
545
+ });
546
+ child.on("error", reject);
547
+ child.on("close", (code) => resolve({ code: code ?? 1, stdout }));
548
+ });
549
+ }
550
+
551
+ // src/cli/commands/share.ts
552
+ var c2 = {
553
+ cyan: (s) => `\x1B[36m${s}\x1B[0m`,
554
+ yellow: (s) => `\x1B[33m${s}\x1B[0m`,
555
+ green: (s) => `\x1B[32m${s}\x1B[0m`,
556
+ bold: (s) => `\x1B[1m${s}\x1B[0m`,
557
+ dim: (s) => `\x1B[2m${s}\x1B[0m`
558
+ };
559
+ var log3 = (msg = "") => console.log(msg && `${c2.cyan("[grabby]")} ${msg}`);
560
+ var warn3 = (msg) => console.log(`${c2.yellow("[grabby]")} ${msg}`);
561
+ function trimSlashes(url) {
562
+ let end = url.length;
563
+ while (end > 0 && url[end - 1] === "/") end--;
564
+ return url.slice(0, end);
565
+ }
566
+ async function ask(question) {
567
+ if (!process.stdin.isTTY) return "";
568
+ const rl = createInterface2({ input: process.stdin, output: process.stdout });
569
+ const answer = await new Promise((resolve) => rl.question(question, resolve));
570
+ rl.close();
571
+ return answer.trim();
572
+ }
573
+ function siteTarget(stack) {
574
+ const first = (files) => files.map((f) => join6(stack.root, f)).find((f) => existsSync5(f));
575
+ if (stack.framework === "next") {
576
+ const layout = first(["app/layout.tsx", "app/layout.jsx", "app/layout.js", "src/app/layout.tsx", "src/app/layout.jsx", "src/app/layout.js"]);
577
+ if (layout) return { file: layout, kind: "next-app" };
578
+ const doc = first(["pages/_document.tsx", "pages/_document.jsx", "pages/_document.js", "src/pages/_document.tsx", "src/pages/_document.jsx", "src/pages/_document.js"]);
579
+ return doc ? { file: doc, kind: "jsx" } : null;
580
+ }
581
+ if (stack.framework === "astro") {
582
+ const withBody = astroFiles(join6(stack.root, "src", "layouts")).filter((f) => readFileSync6(f, "utf8").includes("</body>"));
583
+ return withBody.length === 1 ? { file: withBody[0], kind: "astro" } : null;
584
+ }
585
+ const html = first(["index.html", "src/index.html", "public/index.html", "src/app.html"]);
586
+ return html ? { file: html, kind: "html" } : null;
587
+ }
588
+ var settleMs = 9e4;
589
+ function astroFiles(dir, depth = 0) {
590
+ if (depth > 3 || !existsSync5(dir)) return [];
591
+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
592
+ const full = join6(dir, e.name);
593
+ if (e.isDirectory()) return astroFiles(full, depth + 1);
594
+ return e.name.endsWith(".astro") ? [full] : [];
595
+ });
596
+ }
597
+ async function collector(server, path, token, init2 = {}) {
598
+ const deadline = Date.now() + settleMs;
599
+ for (; ; ) {
600
+ let res = null;
601
+ try {
602
+ res = await fetch(`${server}${path}`, {
603
+ ...init2,
604
+ headers: { Authorization: `Bearer ${token}`, ...init2.body ? { "Content-Type": "application/json" } : {} },
605
+ signal: AbortSignal.timeout(15e3)
606
+ });
607
+ } catch (err) {
608
+ if (Date.now() >= deadline) throw err;
609
+ }
610
+ if (res) {
611
+ const fromCollector = (res.headers.get("content-type") ?? "").includes("application/json");
612
+ const notReadyYet = res.status >= 500 || res.status === 404 && !fromCollector;
613
+ if (!notReadyYet || Date.now() >= deadline) return res;
614
+ }
615
+ await new Promise((r) => setTimeout(r, Math.min(3e3, Math.max(50, settleMs / 30))));
616
+ }
617
+ }
618
+ async function resolveOrigins(stack, saved, options) {
619
+ const given = (options.origins ?? []).map((o) => {
620
+ const origin = toOrigin(o);
621
+ if (!origin) throw new Error(`"${o}" is not a web address (e.g. https://your-site.com)`);
622
+ return origin;
623
+ });
624
+ let sites = given.length ? given : saved?.origins.filter((o) => !o.startsWith("http://localhost")) ?? [];
625
+ if (!sites.length) sites = guessSiteOrigins(stack.root);
626
+ if (!sites.length) {
627
+ const answer = await ask(` Where is your site live? ${c2.dim("(e.g. https://my-app.netlify.app)")} `);
628
+ const origin = toOrigin(answer);
629
+ if (!origin) {
630
+ throw new Error(process.stdin.isTTY ? "a site address is needed, e.g. https://my-app.netlify.app" : "pass the site address: npx @githumbi/grabby share --origin https://your-site.com");
631
+ }
632
+ sites = [origin];
633
+ }
634
+ const merged = /* @__PURE__ */ new Set([...given.length ? [] : saved?.origins ?? [], ...sites]);
635
+ const dev = devOrigin(stack.framework);
636
+ if (dev && !options.noLocalhost) merged.add(dev);
637
+ return [...merged];
638
+ }
639
+ function projectKeyInSite(stack) {
640
+ const target = siteTarget(stack);
641
+ if (!target) return void 0;
642
+ const code = readFileSync6(target.file, "utf8");
643
+ if (!code.includes("/dist/loader.global.js")) return void 0;
644
+ return /data-project-key=["'](pk_[A-Za-z0-9_-]{8,64})["']/.exec(code)?.[1];
645
+ }
646
+ function patchSite(stack, tag, dryRun) {
647
+ const target = siteTarget(stack);
648
+ if (!target) return { file: null, result: null };
649
+ const result = patchLoaderTag(readFileSync6(target.file, "utf8"), tag, target.kind);
650
+ if (result.status === "patched" && !dryRun) writeFileSync4(target.file, result.code, "utf8");
651
+ return { file: target.file, result };
652
+ }
653
+ async function share(options = {}) {
654
+ const stack = detectStack(options.cwd);
655
+ const rel = (f) => relative2(stack.root, f) || f;
656
+ const saved = readProjectConfig(stack.root);
657
+ const keyInSite = saved ? void 0 : projectKeyInSite(stack);
658
+ const selfHosted = options.server ?? (saved?.deploy.kind === "server" ? saved.server : void 0);
659
+ const origins = await resolveOrigins(stack, saved, options);
660
+ const target = siteTarget(stack);
661
+ log3(`Project: ${stack.root}`);
662
+ log3(`Detected: ${stack.framework}${saved ? " \xB7 already shared, updating" : ""}`);
663
+ console.log("");
664
+ console.log(c2.bold(" Grabby will:"));
665
+ console.log(selfHosted ? ` \u2022 use your collector at ${c2.bold(selfHosted)}` : ` \u2022 ${saved ? "update" : "set up"} a feedback collector in ${c2.bold("your Cloudflare account")} ${c2.dim("(free, no card; a browser window opens to sign in the first time)")}`);
666
+ console.log(` \u2022 accept comments from ${origins.map((o) => c2.bold(o)).join(", ")}`);
667
+ console.log(target ? ` \u2022 add the Grabby script to ${c2.bold(rel(target.file))}` : ` \u2022 show you the script tag to add ${c2.dim("(no layout or index.html found to edit)")}`);
668
+ console.log(` \u2022 save settings in ${c2.bold(".grabby/config.json")} ${c2.dim("(private; added to .gitignore)")}`);
669
+ if (!options.noMcp) console.log(` \u2022 let your AI agent read feedback ${c2.dim("(.mcp.json)")}`);
670
+ if (options.slack) console.log(" \u2022 post new feedback to Slack");
671
+ console.log("");
672
+ if (options.dryRun) return;
673
+ if (!options.yes) {
674
+ const go = /^y(es)?$/i.test(await ask(" Go ahead? [y/N] "));
675
+ if (!go) {
676
+ warn3(process.stdin.isTTY ? "Nothing changed." : "Nothing changed (not a terminal; re-run with --yes to apply).");
677
+ return;
678
+ }
679
+ }
680
+ let server;
681
+ let projectKey;
682
+ let adminToken;
683
+ let deploy;
684
+ if (selfHosted) {
685
+ server = trimSlashes(selfHosted);
686
+ adminToken = options.token ?? process.env.GRABBY_ADMIN_TOKEN ?? saved?.adminToken;
687
+ if (!adminToken) throw new Error("--server needs the collector's admin token: --token sk_\u2026 (or GRABBY_ADMIN_TOKEN)");
688
+ const res = await collector(server, "/v1/meta", adminToken).catch((err) => {
689
+ throw new Error(`could not reach ${server}: ${err.message}`);
690
+ });
691
+ if (res.status === 401) throw new Error(`${server} rejected the admin token`);
692
+ if (!res.ok) throw new Error(`${server}/v1/meta answered ${res.status}. Is it a Grabby collector, version 0.2 or newer?`);
693
+ const meta = await res.json();
694
+ const project = meta.projects[0];
695
+ if (!project?.publicKey) throw new Error(`${server} has no project key configured`);
696
+ projectKey = project.publicKey;
697
+ const missing = origins.filter((o) => !o.startsWith("http://localhost") && !project.allowedOrigins.includes(o));
698
+ if (missing.length) warn3(`Your collector doesn't accept ${missing.join(", ")} yet. Add it to GRABBY_ALLOWED_ORIGINS on the server.`);
699
+ deploy = { kind: "server" };
700
+ } else {
701
+ const resultFile = join6(stack.root, ".grabby", "cloudflare", "result.json");
702
+ const args = ["deploy", "cloudflare", "--out", resultFile, "--dir", join6(stack.root, ".grabby", "cloudflare"), ...origins.flatMap((o) => ["--origin", o])];
703
+ const key = saved?.projectKey ?? keyInSite;
704
+ if (key) args.push("--key", key);
705
+ if (options.rotateAdmin) args.push("--rotate-admin");
706
+ rmSync(resultFile, { force: true });
707
+ const run = await runServer(args, { env: { GRABBY_ADMIN_TOKEN: saved?.adminToken } });
708
+ let result2;
709
+ try {
710
+ result2 = JSON.parse(readFileSync6(resultFile, "utf8"));
711
+ } catch {
712
+ throw new Error("setting up the collector failed (see the messages above)");
713
+ } finally {
714
+ rmSync(resultFile, { force: true });
715
+ }
716
+ if (run.code !== 0) throw new Error("setting up the collector failed (see the messages above)");
717
+ server = result2.url;
718
+ projectKey = result2.projectKey;
719
+ adminToken = result2.adminToken ?? saved?.adminToken;
720
+ deploy = { kind: "cloudflare", worker: result2.worker, database: result2.database };
721
+ if (!adminToken) {
722
+ throw new Error("this collector already has an admin token that is not saved on this computer. Run again with --rotate-admin to replace it.");
723
+ }
724
+ }
725
+ writeProjectConfig(stack.root, {
726
+ version: 1,
727
+ server,
728
+ projectKey,
729
+ adminToken,
730
+ origins,
731
+ deploy,
732
+ ...saved?.inbox && saved.server === server ? { inbox: saved.inbox } : {}
733
+ });
734
+ const gitignoreChanged = ensureGitignore(stack.root);
735
+ let inbox = saved?.inbox && saved.server === server && !options.rotate ? saved.inbox : void 0;
736
+ if (inbox) {
737
+ const token = new URL(inbox).hash.replace(/^#k=/, "");
738
+ const check = await collector(server, "/v1/meta", token).catch(() => null);
739
+ if (check?.status === 401) inbox = void 0;
740
+ }
741
+ if (!inbox) {
742
+ const res = await collector(server, "/v1/admin/inbox-token", adminToken, { method: "POST" });
743
+ if (!res.ok) {
744
+ throw new Error(`could not create the inbox link (${res.status}). Your collector and settings are saved; run \`npx @githumbi/grabby share\` again in a minute`);
745
+ }
746
+ inbox = (await res.json()).url;
747
+ let sameCollector = false;
748
+ try {
749
+ sameCollector = typeof inbox === "string" && new URL(inbox).origin === new URL(server).origin;
750
+ } catch {
751
+ }
752
+ if (!sameCollector) throw new Error(`${server} returned an unexpected inbox link`);
753
+ }
754
+ if (options.slack) {
755
+ const res = await collector(server, "/v1/admin/alerts", adminToken, { method: "PUT", body: JSON.stringify({ slack: options.slack }) });
756
+ if (!res.ok) warn3(`Slack alerts not set: ${(await res.json().catch(() => ({}))).error ?? res.status}`);
757
+ }
758
+ const tag = liveTag(server, projectKey);
759
+ const { file, result } = patchSite(stack, tag, false);
760
+ let siteChanged = null;
761
+ if (file && result?.status === "patched") {
762
+ siteChanged = rel(file);
763
+ log3(`${c2.green("\u2713")} ${siteChanged}`);
764
+ } else if (file && result?.status === "already") {
765
+ log3(`${rel(file)}: already up to date`);
766
+ } else {
767
+ warn3(`Add this before </body> in your site's layout${file && result?.status === "unrecognised" ? ` (${rel(file)}: ${result.reason})` : ""}:`);
768
+ console.log(`
769
+ ${renderTag(tag, "html")}
770
+ `);
771
+ }
772
+ writeProjectConfig(stack.root, { version: 1, server, projectKey, adminToken, inbox, origins, deploy });
773
+ if (gitignoreChanged) log3(`${c2.green("\u2713")} .gitignore (added .grabby/)`);
774
+ log3(`${c2.green("\u2713")} .grabby/config.json`);
775
+ if (!options.noMcp) await addMcp({ cwd: stack.root, quiet: true });
776
+ const site = origins.find((o) => !o.startsWith("http://localhost")) ?? origins[0];
777
+ console.log("");
778
+ log3(c2.green("Grabby is ready."));
779
+ console.log("");
780
+ console.log(` ${c2.bold("1.")} ${siteChanged ? `Commit and deploy your site as usual (${siteChanged} changed).` : "Deploy your site as usual."}`);
781
+ console.log(` ${c2.bold("2.")} Send reviewers this link. They click Comment, pick anything, and type:`);
782
+ console.log(` ${c2.bold(`${site}/?grabby=${projectKey}`)}`);
783
+ console.log(` ${c2.bold("3.")} Read feedback in your private inbox ${c2.dim("(bookmark it; don't share it)")}:`);
784
+ console.log(` ${c2.bold(inbox)}`);
785
+ console.log(` or hand it to your AI agent: ${c2.bold("npx @githumbi/grabby pull")}`);
786
+ console.log("");
787
+ console.log(c2.dim(` Comments arrive even while your computer is off. Later: ${c2.bold("npx @githumbi/grabby inbox")} opens the inbox,`));
788
+ console.log(c2.dim(` ${c2.bold("npx @githumbi/grabby alerts --slack <webhook>")} posts new feedback to Slack.`));
789
+ console.log("");
790
+ }
791
+
792
+ // src/cli/commands/inbox.ts
793
+ import { spawn as spawn2 } from "child_process";
794
+ function sharedConfig(cwd) {
795
+ const config = readProjectConfig(findProjectRoot(cwd));
796
+ if (!config) throw new Error("this project isn't shared yet. Run: npx @githumbi/grabby share");
797
+ return config;
798
+ }
799
+ async function openInbox(options = {}) {
800
+ const { inbox } = sharedConfig(options.cwd);
801
+ if (!inbox) throw new Error("no inbox link saved. Run: npx @githumbi/grabby share --rotate");
802
+ console.log(`\x1B[36m[grabby]\x1B[0m Your inbox (private, don't share it): ${inbox}`);
803
+ if (options.print || !process.stdout.isTTY) return;
804
+ const [cmd, args] = process.platform === "darwin" ? ["open", [inbox]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", inbox]] : ["xdg-open", [inbox]];
805
+ spawn2(cmd, args, { stdio: "ignore", detached: true }).on("error", () => {
806
+ }).unref();
807
+ }
808
+
809
+ // src/cli/commands/alerts.ts
810
+ async function alerts(options) {
811
+ const { server, adminToken } = sharedConfig(options.cwd);
812
+ if (!adminToken) throw new Error("no admin token saved for this project. Run: npx @githumbi/grabby share --rotate-admin");
813
+ const call = (path, init2 = {}) => fetch(`${server}${path}`, {
814
+ ...init2,
815
+ headers: { Authorization: `Bearer ${adminToken}`, ...init2.body ? { "Content-Type": "application/json" } : {} },
816
+ signal: AbortSignal.timeout(15e3)
817
+ });
818
+ const say = (m) => console.log(`\x1B[36m[grabby]\x1B[0m ${m}`);
819
+ const body = {};
820
+ if (options.off) Object.assign(body, { slack: null, webhook: null });
821
+ if (options.slack) body.slack = options.slack;
822
+ if (options.webhook) body.webhook = options.webhook;
823
+ if (Object.keys(body).length) {
824
+ const res = await call("/v1/admin/alerts", { method: "PUT", body: JSON.stringify(body) });
825
+ if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error ?? `the collector answered ${res.status}`);
826
+ say(options.off ? "Alerts are off." : "Alerts are on. New feedback is posted within about 20 seconds, one message per burst.");
827
+ }
828
+ if (options.test) {
829
+ const res = await call("/v1/admin/alerts/test", { method: "POST" });
830
+ say(res.ok ? "Sent a test alert." : "The test alert did not go through: is an alert set?");
831
+ }
832
+ if (!Object.keys(body).length && !options.test) {
833
+ const res = await call("/v1/admin/alerts");
834
+ const current = await res.json();
835
+ say(`Slack: ${current.slack ? "on" : "off"} \xB7 webhook: ${current.webhook ? "on" : "off"}`);
836
+ say("Set one with: npx @githumbi/grabby alerts --slack https://hooks.slack.com/services/\u2026");
837
+ }
838
+ }
839
+
370
840
  // src/cli/index.ts
371
841
  var HELP = `Grabby: point at any UI element, leave a comment, hand it to your AI agent.
372
842
 
373
843
  Usage
374
- npx @githumbi/grabby init Set up Grabby in this project (asks before changing files)
844
+ npx @githumbi/grabby init Set up Grabby for local development (asks before changing files)
375
845
  --yes Apply without asking
376
846
  --dry-run Only show what would change
377
847
  --no-install Don't install the package
378
- --live --server <url> --key <pk_\u2026>
379
- Set up live-site feedback instead of local dev mode
848
+
849
+ npx @githumbi/grabby share Get feedback from others on your live site. Sets up a
850
+ collector in your own free Cloudflare account, adds the
851
+ script to your site, and gives you a feedback link and
852
+ a private inbox. Safe to re-run.
853
+ --origin <url> Your site's address (repeatable; asked if missing)
854
+ --server <url> --token <sk_\u2026>
855
+ Use a collector you run yourself instead
856
+ --slack <webhook> Post new feedback to Slack
857
+ --rotate Replace the private inbox link
858
+ --rotate-admin Replace the admin token
859
+ --no-localhost Don't accept comments from your local dev server
860
+ --no-mcp Don't add the MCP server to .mcp.json
861
+ --yes, --dry-run
862
+
863
+ npx @githumbi/grabby inbox Open your private feedback inbox (--print to only show the link)
864
+ npx @githumbi/grabby pull Print open comments for your AI agent, then mark them resolved
865
+ npx @githumbi/grabby alerts --slack <webhook> | --webhook <url> | --off | --test
380
866
  npx @githumbi/grabby add mcp Let your AI agent read comments over MCP (.mcp.json)
381
- npx @githumbi/grabby pull Print collected comments for your agent (runs grabby-server pull)
382
867
  `;
383
868
  function fail(err) {
384
869
  console.error("\x1B[31mError:\x1B[0m", err instanceof Error ? err.message : String(err));
@@ -387,13 +872,43 @@ function fail(err) {
387
872
  var argv = process.argv.slice(2);
388
873
  var [command, subcommand] = argv;
389
874
  if (command === "pull") {
390
- const args = ["-y", SERVER_PACKAGE, "pull", ...argv.slice(1)];
391
- const windows = process.platform === "win32";
392
- if (windows && !args.every((a) => /^[\w@./:=,+-]+$/.test(a))) {
393
- fail(`unsupported characters in arguments; run it directly: npx ${args.join(" ")}`);
394
- }
395
- const child = spawn(windows ? "npx.cmd" : "npx", args, { stdio: "inherit", shell: windows });
396
- child.on("exit", (code) => process.exit(code ?? 1));
875
+ runServer(["pull", ...argv.slice(1)]).then(({ code }) => process.exit(code)).catch(fail);
876
+ } else if (command === "share") {
877
+ const { values } = parseArgs({
878
+ args: argv.slice(1),
879
+ options: {
880
+ origin: { type: "string", multiple: true },
881
+ server: { type: "string" },
882
+ token: { type: "string" },
883
+ slack: { type: "string" },
884
+ rotate: { type: "boolean" },
885
+ "rotate-admin": { type: "boolean" },
886
+ "no-localhost": { type: "boolean" },
887
+ "no-mcp": { type: "boolean" },
888
+ yes: { type: "boolean", short: "y" },
889
+ "dry-run": { type: "boolean" }
890
+ }
891
+ });
892
+ share({
893
+ origins: values.origin,
894
+ server: values.server,
895
+ token: values.token,
896
+ slack: values.slack,
897
+ rotate: values.rotate,
898
+ rotateAdmin: values["rotate-admin"],
899
+ noLocalhost: values["no-localhost"],
900
+ noMcp: values["no-mcp"],
901
+ yes: values.yes,
902
+ dryRun: values["dry-run"]
903
+ }).catch(fail);
904
+ } else if (command === "inbox") {
905
+ openInbox({ print: argv.includes("--print") }).catch(fail);
906
+ } else if (command === "alerts") {
907
+ const { values } = parseArgs({
908
+ args: argv.slice(1),
909
+ options: { slack: { type: "string" }, webhook: { type: "string" }, off: { type: "boolean" }, test: { type: "boolean" } }
910
+ });
911
+ alerts(values).catch(fail);
397
912
  } else if (command === "add" && subcommand === "mcp") {
398
913
  addMcp().catch(fail);
399
914
  } else if (!command || command === "init") {